CommandLine.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719
  1. //===-- CommandLine.cpp - Command line parser implementation --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This class implements a command line argument processor that is useful when
  10. // creating a tool. It provides a simple, minimalistic interface that is easily
  11. // extensible and supports nonlocal (library) command line options.
  12. //
  13. // Note that rather than trying to figure out what this code does, you could try
  14. // reading the library documentation located in docs/CommandLine.html
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/Support/CommandLine.h"
  18. #include "DebugOptions.h"
  19. #include "llvm-c/Support.h"
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/Optional.h"
  22. #include "llvm/ADT/STLFunctionalExtras.h"
  23. #include "llvm/ADT/SmallPtrSet.h"
  24. #include "llvm/ADT/SmallString.h"
  25. #include "llvm/ADT/StringExtras.h"
  26. #include "llvm/ADT/StringMap.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/ADT/Triple.h"
  29. #include "llvm/ADT/Twine.h"
  30. #include "llvm/Config/config.h"
  31. #include "llvm/Support/ConvertUTF.h"
  32. #include "llvm/Support/Debug.h"
  33. #include "llvm/Support/Error.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "llvm/Support/Host.h"
  37. #include "llvm/Support/ManagedStatic.h"
  38. #include "llvm/Support/MemoryBuffer.h"
  39. #include "llvm/Support/Path.h"
  40. #include "llvm/Support/Process.h"
  41. #include "llvm/Support/StringSaver.h"
  42. #include "llvm/Support/VirtualFileSystem.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include <cstdlib>
  45. #include <string>
  46. using namespace llvm;
  47. using namespace cl;
  48. #define DEBUG_TYPE "commandline"
  49. //===----------------------------------------------------------------------===//
  50. // Template instantiations and anchors.
  51. //
  52. namespace llvm {
  53. namespace cl {
  54. template class basic_parser<bool>;
  55. template class basic_parser<boolOrDefault>;
  56. template class basic_parser<int>;
  57. template class basic_parser<long>;
  58. template class basic_parser<long long>;
  59. template class basic_parser<unsigned>;
  60. template class basic_parser<unsigned long>;
  61. template class basic_parser<unsigned long long>;
  62. template class basic_parser<double>;
  63. template class basic_parser<float>;
  64. template class basic_parser<std::string>;
  65. template class basic_parser<char>;
  66. template class opt<unsigned>;
  67. template class opt<int>;
  68. template class opt<std::string>;
  69. template class opt<char>;
  70. template class opt<bool>;
  71. } // namespace cl
  72. } // namespace llvm
  73. // Pin the vtables to this file.
  74. void GenericOptionValue::anchor() {}
  75. void OptionValue<boolOrDefault>::anchor() {}
  76. void OptionValue<std::string>::anchor() {}
  77. void Option::anchor() {}
  78. void basic_parser_impl::anchor() {}
  79. void parser<bool>::anchor() {}
  80. void parser<boolOrDefault>::anchor() {}
  81. void parser<int>::anchor() {}
  82. void parser<long>::anchor() {}
  83. void parser<long long>::anchor() {}
  84. void parser<unsigned>::anchor() {}
  85. void parser<unsigned long>::anchor() {}
  86. void parser<unsigned long long>::anchor() {}
  87. void parser<double>::anchor() {}
  88. void parser<float>::anchor() {}
  89. void parser<std::string>::anchor() {}
  90. void parser<char>::anchor() {}
  91. //===----------------------------------------------------------------------===//
  92. const static size_t DefaultPad = 2;
  93. static StringRef ArgPrefix = "-";
  94. static StringRef ArgPrefixLong = "--";
  95. static StringRef ArgHelpPrefix = " - ";
  96. static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
  97. size_t Len = ArgName.size();
  98. if (Len == 1)
  99. return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
  100. return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
  101. }
  102. static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
  103. SmallString<8> Prefix;
  104. for (size_t I = 0; I < Pad; ++I) {
  105. Prefix.push_back(' ');
  106. }
  107. Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
  108. return Prefix;
  109. }
  110. // Option predicates...
  111. static inline bool isGrouping(const Option *O) {
  112. return O->getMiscFlags() & cl::Grouping;
  113. }
  114. static inline bool isPrefixedOrGrouping(const Option *O) {
  115. return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
  116. O->getFormattingFlag() == cl::AlwaysPrefix;
  117. }
  118. namespace {
  119. class PrintArg {
  120. StringRef ArgName;
  121. size_t Pad;
  122. public:
  123. PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
  124. friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
  125. };
  126. raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
  127. OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
  128. return OS;
  129. }
  130. class CommandLineParser {
  131. public:
  132. // Globals for name and overview of program. Program name is not a string to
  133. // avoid static ctor/dtor issues.
  134. std::string ProgramName;
  135. StringRef ProgramOverview;
  136. // This collects additional help to be printed.
  137. std::vector<StringRef> MoreHelp;
  138. // This collects Options added with the cl::DefaultOption flag. Since they can
  139. // be overridden, they are not added to the appropriate SubCommands until
  140. // ParseCommandLineOptions actually runs.
  141. SmallVector<Option*, 4> DefaultOptions;
  142. // This collects the different option categories that have been registered.
  143. SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
  144. // This collects the different subcommands that have been registered.
  145. SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
  146. CommandLineParser() : ActiveSubCommand(nullptr) {
  147. registerSubCommand(&*TopLevelSubCommand);
  148. registerSubCommand(&*AllSubCommands);
  149. }
  150. void ResetAllOptionOccurrences();
  151. bool ParseCommandLineOptions(int argc, const char *const *argv,
  152. StringRef Overview, raw_ostream *Errs = nullptr,
  153. bool LongOptionsUseDoubleDash = false);
  154. void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
  155. if (Opt.hasArgStr())
  156. return;
  157. if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
  158. errs() << ProgramName << ": CommandLine Error: Option '" << Name
  159. << "' registered more than once!\n";
  160. report_fatal_error("inconsistency in registered CommandLine options");
  161. }
  162. // If we're adding this to all sub-commands, add it to the ones that have
  163. // already been registered.
  164. if (SC == &*AllSubCommands) {
  165. for (auto *Sub : RegisteredSubCommands) {
  166. if (SC == Sub)
  167. continue;
  168. addLiteralOption(Opt, Sub, Name);
  169. }
  170. }
  171. }
  172. void addLiteralOption(Option &Opt, StringRef Name) {
  173. if (Opt.Subs.empty())
  174. addLiteralOption(Opt, &*TopLevelSubCommand, Name);
  175. else {
  176. for (auto *SC : Opt.Subs)
  177. addLiteralOption(Opt, SC, Name);
  178. }
  179. }
  180. void addOption(Option *O, SubCommand *SC) {
  181. bool HadErrors = false;
  182. if (O->hasArgStr()) {
  183. // If it's a DefaultOption, check to make sure it isn't already there.
  184. if (O->isDefaultOption() &&
  185. SC->OptionsMap.find(O->ArgStr) != SC->OptionsMap.end())
  186. return;
  187. // Add argument to the argument map!
  188. if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
  189. errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
  190. << "' registered more than once!\n";
  191. HadErrors = true;
  192. }
  193. }
  194. // Remember information about positional options.
  195. if (O->getFormattingFlag() == cl::Positional)
  196. SC->PositionalOpts.push_back(O);
  197. else if (O->getMiscFlags() & cl::Sink) // Remember sink options
  198. SC->SinkOpts.push_back(O);
  199. else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
  200. if (SC->ConsumeAfterOpt) {
  201. O->error("Cannot specify more than one option with cl::ConsumeAfter!");
  202. HadErrors = true;
  203. }
  204. SC->ConsumeAfterOpt = O;
  205. }
  206. // Fail hard if there were errors. These are strictly unrecoverable and
  207. // indicate serious issues such as conflicting option names or an
  208. // incorrectly
  209. // linked LLVM distribution.
  210. if (HadErrors)
  211. report_fatal_error("inconsistency in registered CommandLine options");
  212. // If we're adding this to all sub-commands, add it to the ones that have
  213. // already been registered.
  214. if (SC == &*AllSubCommands) {
  215. for (auto *Sub : RegisteredSubCommands) {
  216. if (SC == Sub)
  217. continue;
  218. addOption(O, Sub);
  219. }
  220. }
  221. }
  222. void addOption(Option *O, bool ProcessDefaultOption = false) {
  223. if (!ProcessDefaultOption && O->isDefaultOption()) {
  224. DefaultOptions.push_back(O);
  225. return;
  226. }
  227. if (O->Subs.empty()) {
  228. addOption(O, &*TopLevelSubCommand);
  229. } else {
  230. for (auto *SC : O->Subs)
  231. addOption(O, SC);
  232. }
  233. }
  234. void removeOption(Option *O, SubCommand *SC) {
  235. SmallVector<StringRef, 16> OptionNames;
  236. O->getExtraOptionNames(OptionNames);
  237. if (O->hasArgStr())
  238. OptionNames.push_back(O->ArgStr);
  239. SubCommand &Sub = *SC;
  240. auto End = Sub.OptionsMap.end();
  241. for (auto Name : OptionNames) {
  242. auto I = Sub.OptionsMap.find(Name);
  243. if (I != End && I->getValue() == O)
  244. Sub.OptionsMap.erase(I);
  245. }
  246. if (O->getFormattingFlag() == cl::Positional)
  247. for (auto *Opt = Sub.PositionalOpts.begin();
  248. Opt != Sub.PositionalOpts.end(); ++Opt) {
  249. if (*Opt == O) {
  250. Sub.PositionalOpts.erase(Opt);
  251. break;
  252. }
  253. }
  254. else if (O->getMiscFlags() & cl::Sink)
  255. for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
  256. if (*Opt == O) {
  257. Sub.SinkOpts.erase(Opt);
  258. break;
  259. }
  260. }
  261. else if (O == Sub.ConsumeAfterOpt)
  262. Sub.ConsumeAfterOpt = nullptr;
  263. }
  264. void removeOption(Option *O) {
  265. if (O->Subs.empty())
  266. removeOption(O, &*TopLevelSubCommand);
  267. else {
  268. if (O->isInAllSubCommands()) {
  269. for (auto *SC : RegisteredSubCommands)
  270. removeOption(O, SC);
  271. } else {
  272. for (auto *SC : O->Subs)
  273. removeOption(O, SC);
  274. }
  275. }
  276. }
  277. bool hasOptions(const SubCommand &Sub) const {
  278. return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
  279. nullptr != Sub.ConsumeAfterOpt);
  280. }
  281. bool hasOptions() const {
  282. for (const auto *S : RegisteredSubCommands) {
  283. if (hasOptions(*S))
  284. return true;
  285. }
  286. return false;
  287. }
  288. SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
  289. void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
  290. SubCommand &Sub = *SC;
  291. if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
  292. errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
  293. << "' registered more than once!\n";
  294. report_fatal_error("inconsistency in registered CommandLine options");
  295. }
  296. Sub.OptionsMap.erase(O->ArgStr);
  297. }
  298. void updateArgStr(Option *O, StringRef NewName) {
  299. if (O->Subs.empty())
  300. updateArgStr(O, NewName, &*TopLevelSubCommand);
  301. else {
  302. if (O->isInAllSubCommands()) {
  303. for (auto *SC : RegisteredSubCommands)
  304. updateArgStr(O, NewName, SC);
  305. } else {
  306. for (auto *SC : O->Subs)
  307. updateArgStr(O, NewName, SC);
  308. }
  309. }
  310. }
  311. void printOptionValues();
  312. void registerCategory(OptionCategory *cat) {
  313. assert(count_if(RegisteredOptionCategories,
  314. [cat](const OptionCategory *Category) {
  315. return cat->getName() == Category->getName();
  316. }) == 0 &&
  317. "Duplicate option categories");
  318. RegisteredOptionCategories.insert(cat);
  319. }
  320. void registerSubCommand(SubCommand *sub) {
  321. assert(count_if(RegisteredSubCommands,
  322. [sub](const SubCommand *Sub) {
  323. return (!sub->getName().empty()) &&
  324. (Sub->getName() == sub->getName());
  325. }) == 0 &&
  326. "Duplicate subcommands");
  327. RegisteredSubCommands.insert(sub);
  328. // For all options that have been registered for all subcommands, add the
  329. // option to this subcommand now.
  330. if (sub != &*AllSubCommands) {
  331. for (auto &E : AllSubCommands->OptionsMap) {
  332. Option *O = E.second;
  333. if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
  334. O->hasArgStr())
  335. addOption(O, sub);
  336. else
  337. addLiteralOption(*O, sub, E.first());
  338. }
  339. }
  340. }
  341. void unregisterSubCommand(SubCommand *sub) {
  342. RegisteredSubCommands.erase(sub);
  343. }
  344. iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
  345. getRegisteredSubcommands() {
  346. return make_range(RegisteredSubCommands.begin(),
  347. RegisteredSubCommands.end());
  348. }
  349. void reset() {
  350. ActiveSubCommand = nullptr;
  351. ProgramName.clear();
  352. ProgramOverview = StringRef();
  353. MoreHelp.clear();
  354. RegisteredOptionCategories.clear();
  355. ResetAllOptionOccurrences();
  356. RegisteredSubCommands.clear();
  357. TopLevelSubCommand->reset();
  358. AllSubCommands->reset();
  359. registerSubCommand(&*TopLevelSubCommand);
  360. registerSubCommand(&*AllSubCommands);
  361. DefaultOptions.clear();
  362. }
  363. private:
  364. SubCommand *ActiveSubCommand;
  365. Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
  366. Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
  367. bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
  368. Option *Opt = LookupOption(Sub, Arg, Value);
  369. if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
  370. return nullptr;
  371. return Opt;
  372. }
  373. SubCommand *LookupSubCommand(StringRef Name);
  374. };
  375. } // namespace
  376. static ManagedStatic<CommandLineParser> GlobalParser;
  377. void cl::AddLiteralOption(Option &O, StringRef Name) {
  378. GlobalParser->addLiteralOption(O, Name);
  379. }
  380. extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
  381. GlobalParser->MoreHelp.push_back(Help);
  382. }
  383. void Option::addArgument() {
  384. GlobalParser->addOption(this);
  385. FullyInitialized = true;
  386. }
  387. void Option::removeArgument() { GlobalParser->removeOption(this); }
  388. void Option::setArgStr(StringRef S) {
  389. if (FullyInitialized)
  390. GlobalParser->updateArgStr(this, S);
  391. assert((S.empty() || S[0] != '-') && "Option can't start with '-");
  392. ArgStr = S;
  393. if (ArgStr.size() == 1)
  394. setMiscFlag(Grouping);
  395. }
  396. void Option::addCategory(OptionCategory &C) {
  397. assert(!Categories.empty() && "Categories cannot be empty.");
  398. // Maintain backward compatibility by replacing the default GeneralCategory
  399. // if it's still set. Otherwise, just add the new one. The GeneralCategory
  400. // must be explicitly added if you want multiple categories that include it.
  401. if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
  402. Categories[0] = &C;
  403. else if (!is_contained(Categories, &C))
  404. Categories.push_back(&C);
  405. }
  406. void Option::reset() {
  407. NumOccurrences = 0;
  408. setDefault();
  409. if (isDefaultOption())
  410. removeArgument();
  411. }
  412. void OptionCategory::registerCategory() {
  413. GlobalParser->registerCategory(this);
  414. }
  415. // A special subcommand representing no subcommand. It is particularly important
  416. // that this ManagedStatic uses constant initailization and not dynamic
  417. // initialization because it is referenced from cl::opt constructors, which run
  418. // dynamically in an arbitrary order.
  419. LLVM_REQUIRE_CONSTANT_INITIALIZATION
  420. ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
  421. // A special subcommand that can be used to put an option into all subcommands.
  422. ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
  423. void SubCommand::registerSubCommand() {
  424. GlobalParser->registerSubCommand(this);
  425. }
  426. void SubCommand::unregisterSubCommand() {
  427. GlobalParser->unregisterSubCommand(this);
  428. }
  429. void SubCommand::reset() {
  430. PositionalOpts.clear();
  431. SinkOpts.clear();
  432. OptionsMap.clear();
  433. ConsumeAfterOpt = nullptr;
  434. }
  435. SubCommand::operator bool() const {
  436. return (GlobalParser->getActiveSubCommand() == this);
  437. }
  438. //===----------------------------------------------------------------------===//
  439. // Basic, shared command line option processing machinery.
  440. //
  441. /// LookupOption - Lookup the option specified by the specified option on the
  442. /// command line. If there is a value specified (after an equal sign) return
  443. /// that as well. This assumes that leading dashes have already been stripped.
  444. Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
  445. StringRef &Value) {
  446. // Reject all dashes.
  447. if (Arg.empty())
  448. return nullptr;
  449. assert(&Sub != &*AllSubCommands);
  450. size_t EqualPos = Arg.find('=');
  451. // If we have an equals sign, remember the value.
  452. if (EqualPos == StringRef::npos) {
  453. // Look up the option.
  454. return Sub.OptionsMap.lookup(Arg);
  455. }
  456. // If the argument before the = is a valid option name and the option allows
  457. // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
  458. // failure by returning nullptr.
  459. auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
  460. if (I == Sub.OptionsMap.end())
  461. return nullptr;
  462. auto *O = I->second;
  463. if (O->getFormattingFlag() == cl::AlwaysPrefix)
  464. return nullptr;
  465. Value = Arg.substr(EqualPos + 1);
  466. Arg = Arg.substr(0, EqualPos);
  467. return I->second;
  468. }
  469. SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
  470. if (Name.empty())
  471. return &*TopLevelSubCommand;
  472. for (auto *S : RegisteredSubCommands) {
  473. if (S == &*AllSubCommands)
  474. continue;
  475. if (S->getName().empty())
  476. continue;
  477. if (StringRef(S->getName()) == StringRef(Name))
  478. return S;
  479. }
  480. return &*TopLevelSubCommand;
  481. }
  482. /// LookupNearestOption - Lookup the closest match to the option specified by
  483. /// the specified option on the command line. If there is a value specified
  484. /// (after an equal sign) return that as well. This assumes that leading dashes
  485. /// have already been stripped.
  486. static Option *LookupNearestOption(StringRef Arg,
  487. const StringMap<Option *> &OptionsMap,
  488. std::string &NearestString) {
  489. // Reject all dashes.
  490. if (Arg.empty())
  491. return nullptr;
  492. // Split on any equal sign.
  493. std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
  494. StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
  495. StringRef &RHS = SplitArg.second;
  496. // Find the closest match.
  497. Option *Best = nullptr;
  498. unsigned BestDistance = 0;
  499. for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
  500. ie = OptionsMap.end();
  501. it != ie; ++it) {
  502. Option *O = it->second;
  503. // Do not suggest really hidden options (not shown in any help).
  504. if (O->getOptionHiddenFlag() == ReallyHidden)
  505. continue;
  506. SmallVector<StringRef, 16> OptionNames;
  507. O->getExtraOptionNames(OptionNames);
  508. if (O->hasArgStr())
  509. OptionNames.push_back(O->ArgStr);
  510. bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
  511. StringRef Flag = PermitValue ? LHS : Arg;
  512. for (const auto &Name : OptionNames) {
  513. unsigned Distance = StringRef(Name).edit_distance(
  514. Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
  515. if (!Best || Distance < BestDistance) {
  516. Best = O;
  517. BestDistance = Distance;
  518. if (RHS.empty() || !PermitValue)
  519. NearestString = std::string(Name);
  520. else
  521. NearestString = (Twine(Name) + "=" + RHS).str();
  522. }
  523. }
  524. }
  525. return Best;
  526. }
  527. /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
  528. /// that does special handling of cl::CommaSeparated options.
  529. static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
  530. StringRef ArgName, StringRef Value,
  531. bool MultiArg = false) {
  532. // Check to see if this option accepts a comma separated list of values. If
  533. // it does, we have to split up the value into multiple values.
  534. if (Handler->getMiscFlags() & CommaSeparated) {
  535. StringRef Val(Value);
  536. StringRef::size_type Pos = Val.find(',');
  537. while (Pos != StringRef::npos) {
  538. // Process the portion before the comma.
  539. if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
  540. return true;
  541. // Erase the portion before the comma, AND the comma.
  542. Val = Val.substr(Pos + 1);
  543. // Check for another comma.
  544. Pos = Val.find(',');
  545. }
  546. Value = Val;
  547. }
  548. return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
  549. }
  550. /// ProvideOption - For Value, this differentiates between an empty value ("")
  551. /// and a null value (StringRef()). The later is accepted for arguments that
  552. /// don't allow a value (-foo) the former is rejected (-foo=).
  553. static inline bool ProvideOption(Option *Handler, StringRef ArgName,
  554. StringRef Value, int argc,
  555. const char *const *argv, int &i) {
  556. // Is this a multi-argument option?
  557. unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
  558. // Enforce value requirements
  559. switch (Handler->getValueExpectedFlag()) {
  560. case ValueRequired:
  561. if (!Value.data()) { // No value specified?
  562. // If no other argument or the option only supports prefix form, we
  563. // cannot look at the next argument.
  564. if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
  565. return Handler->error("requires a value!");
  566. // Steal the next argument, like for '-o filename'
  567. assert(argv && "null check");
  568. Value = StringRef(argv[++i]);
  569. }
  570. break;
  571. case ValueDisallowed:
  572. if (NumAdditionalVals > 0)
  573. return Handler->error("multi-valued option specified"
  574. " with ValueDisallowed modifier!");
  575. if (Value.data())
  576. return Handler->error("does not allow a value! '" + Twine(Value) +
  577. "' specified.");
  578. break;
  579. case ValueOptional:
  580. break;
  581. }
  582. // If this isn't a multi-arg option, just run the handler.
  583. if (NumAdditionalVals == 0)
  584. return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
  585. // If it is, run the handle several times.
  586. bool MultiArg = false;
  587. if (Value.data()) {
  588. if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
  589. return true;
  590. --NumAdditionalVals;
  591. MultiArg = true;
  592. }
  593. while (NumAdditionalVals > 0) {
  594. if (i + 1 >= argc)
  595. return Handler->error("not enough values!");
  596. assert(argv && "null check");
  597. Value = StringRef(argv[++i]);
  598. if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
  599. return true;
  600. MultiArg = true;
  601. --NumAdditionalVals;
  602. }
  603. return false;
  604. }
  605. bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
  606. int Dummy = i;
  607. return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
  608. }
  609. // getOptionPred - Check to see if there are any options that satisfy the
  610. // specified predicate with names that are the prefixes in Name. This is
  611. // checked by progressively stripping characters off of the name, checking to
  612. // see if there options that satisfy the predicate. If we find one, return it,
  613. // otherwise return null.
  614. //
  615. static Option *getOptionPred(StringRef Name, size_t &Length,
  616. bool (*Pred)(const Option *),
  617. const StringMap<Option *> &OptionsMap) {
  618. StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
  619. if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
  620. OMI = OptionsMap.end();
  621. // Loop while we haven't found an option and Name still has at least two
  622. // characters in it (so that the next iteration will not be the empty
  623. // string.
  624. while (OMI == OptionsMap.end() && Name.size() > 1) {
  625. Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
  626. OMI = OptionsMap.find(Name);
  627. if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
  628. OMI = OptionsMap.end();
  629. }
  630. if (OMI != OptionsMap.end() && Pred(OMI->second)) {
  631. Length = Name.size();
  632. return OMI->second; // Found one!
  633. }
  634. return nullptr; // No option found!
  635. }
  636. /// HandlePrefixedOrGroupedOption - The specified argument string (which started
  637. /// with at least one '-') does not fully match an available option. Check to
  638. /// see if this is a prefix or grouped option. If so, split arg into output an
  639. /// Arg/Value pair and return the Option to parse it with.
  640. static Option *
  641. HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
  642. bool &ErrorParsing,
  643. const StringMap<Option *> &OptionsMap) {
  644. if (Arg.size() == 1)
  645. return nullptr;
  646. // Do the lookup!
  647. size_t Length = 0;
  648. Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
  649. if (!PGOpt)
  650. return nullptr;
  651. do {
  652. StringRef MaybeValue =
  653. (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
  654. Arg = Arg.substr(0, Length);
  655. assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
  656. // cl::Prefix options do not preserve '=' when used separately.
  657. // The behavior for them with grouped options should be the same.
  658. if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
  659. (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
  660. Value = MaybeValue;
  661. return PGOpt;
  662. }
  663. if (MaybeValue[0] == '=') {
  664. Value = MaybeValue.substr(1);
  665. return PGOpt;
  666. }
  667. // This must be a grouped option.
  668. assert(isGrouping(PGOpt) && "Broken getOptionPred!");
  669. // Grouping options inside a group can't have values.
  670. if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
  671. ErrorParsing |= PGOpt->error("may not occur within a group!");
  672. return nullptr;
  673. }
  674. // Because the value for the option is not required, we don't need to pass
  675. // argc/argv in.
  676. int Dummy = 0;
  677. ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
  678. // Get the next grouping option.
  679. Arg = MaybeValue;
  680. PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
  681. } while (PGOpt);
  682. // We could not find a grouping option in the remainder of Arg.
  683. return nullptr;
  684. }
  685. static bool RequiresValue(const Option *O) {
  686. return O->getNumOccurrencesFlag() == cl::Required ||
  687. O->getNumOccurrencesFlag() == cl::OneOrMore;
  688. }
  689. static bool EatsUnboundedNumberOfValues(const Option *O) {
  690. return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
  691. O->getNumOccurrencesFlag() == cl::OneOrMore;
  692. }
  693. static bool isWhitespace(char C) {
  694. return C == ' ' || C == '\t' || C == '\r' || C == '\n';
  695. }
  696. static bool isWhitespaceOrNull(char C) {
  697. return isWhitespace(C) || C == '\0';
  698. }
  699. static bool isQuote(char C) { return C == '\"' || C == '\''; }
  700. void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
  701. SmallVectorImpl<const char *> &NewArgv,
  702. bool MarkEOLs) {
  703. SmallString<128> Token;
  704. for (size_t I = 0, E = Src.size(); I != E; ++I) {
  705. // Consume runs of whitespace.
  706. if (Token.empty()) {
  707. while (I != E && isWhitespace(Src[I])) {
  708. // Mark the end of lines in response files.
  709. if (MarkEOLs && Src[I] == '\n')
  710. NewArgv.push_back(nullptr);
  711. ++I;
  712. }
  713. if (I == E)
  714. break;
  715. }
  716. char C = Src[I];
  717. // Backslash escapes the next character.
  718. if (I + 1 < E && C == '\\') {
  719. ++I; // Skip the escape.
  720. Token.push_back(Src[I]);
  721. continue;
  722. }
  723. // Consume a quoted string.
  724. if (isQuote(C)) {
  725. ++I;
  726. while (I != E && Src[I] != C) {
  727. // Backslash escapes the next character.
  728. if (Src[I] == '\\' && I + 1 != E)
  729. ++I;
  730. Token.push_back(Src[I]);
  731. ++I;
  732. }
  733. if (I == E)
  734. break;
  735. continue;
  736. }
  737. // End the token if this is whitespace.
  738. if (isWhitespace(C)) {
  739. if (!Token.empty())
  740. NewArgv.push_back(Saver.save(Token.str()).data());
  741. // Mark the end of lines in response files.
  742. if (MarkEOLs && C == '\n')
  743. NewArgv.push_back(nullptr);
  744. Token.clear();
  745. continue;
  746. }
  747. // This is a normal character. Append it.
  748. Token.push_back(C);
  749. }
  750. // Append the last token after hitting EOF with no whitespace.
  751. if (!Token.empty())
  752. NewArgv.push_back(Saver.save(Token.str()).data());
  753. }
  754. /// Backslashes are interpreted in a rather complicated way in the Windows-style
  755. /// command line, because backslashes are used both to separate path and to
  756. /// escape double quote. This method consumes runs of backslashes as well as the
  757. /// following double quote if it's escaped.
  758. ///
  759. /// * If an even number of backslashes is followed by a double quote, one
  760. /// backslash is output for every pair of backslashes, and the last double
  761. /// quote remains unconsumed. The double quote will later be interpreted as
  762. /// the start or end of a quoted string in the main loop outside of this
  763. /// function.
  764. ///
  765. /// * If an odd number of backslashes is followed by a double quote, one
  766. /// backslash is output for every pair of backslashes, and a double quote is
  767. /// output for the last pair of backslash-double quote. The double quote is
  768. /// consumed in this case.
  769. ///
  770. /// * Otherwise, backslashes are interpreted literally.
  771. static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
  772. size_t E = Src.size();
  773. int BackslashCount = 0;
  774. // Skip the backslashes.
  775. do {
  776. ++I;
  777. ++BackslashCount;
  778. } while (I != E && Src[I] == '\\');
  779. bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
  780. if (FollowedByDoubleQuote) {
  781. Token.append(BackslashCount / 2, '\\');
  782. if (BackslashCount % 2 == 0)
  783. return I - 1;
  784. Token.push_back('"');
  785. return I;
  786. }
  787. Token.append(BackslashCount, '\\');
  788. return I - 1;
  789. }
  790. // Windows treats whitespace, double quotes, and backslashes specially.
  791. static bool isWindowsSpecialChar(char C) {
  792. return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
  793. }
  794. // Windows tokenization implementation. The implementation is designed to be
  795. // inlined and specialized for the two user entry points.
  796. static inline void
  797. tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver,
  798. function_ref<void(StringRef)> AddToken,
  799. bool AlwaysCopy, function_ref<void()> MarkEOL) {
  800. SmallString<128> Token;
  801. // Try to do as much work inside the state machine as possible.
  802. enum { INIT, UNQUOTED, QUOTED } State = INIT;
  803. for (size_t I = 0, E = Src.size(); I < E; ++I) {
  804. switch (State) {
  805. case INIT: {
  806. assert(Token.empty() && "token should be empty in initial state");
  807. // Eat whitespace before a token.
  808. while (I < E && isWhitespaceOrNull(Src[I])) {
  809. if (Src[I] == '\n')
  810. MarkEOL();
  811. ++I;
  812. }
  813. // Stop if this was trailing whitespace.
  814. if (I >= E)
  815. break;
  816. size_t Start = I;
  817. while (I < E && !isWindowsSpecialChar(Src[I]))
  818. ++I;
  819. StringRef NormalChars = Src.slice(Start, I);
  820. if (I >= E || isWhitespaceOrNull(Src[I])) {
  821. // No special characters: slice out the substring and start the next
  822. // token. Copy the string if the caller asks us to.
  823. AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
  824. if (I < E && Src[I] == '\n')
  825. MarkEOL();
  826. } else if (Src[I] == '\"') {
  827. Token += NormalChars;
  828. State = QUOTED;
  829. } else if (Src[I] == '\\') {
  830. Token += NormalChars;
  831. I = parseBackslash(Src, I, Token);
  832. State = UNQUOTED;
  833. } else {
  834. llvm_unreachable("unexpected special character");
  835. }
  836. break;
  837. }
  838. case UNQUOTED:
  839. if (isWhitespaceOrNull(Src[I])) {
  840. // Whitespace means the end of the token. If we are in this state, the
  841. // token must have contained a special character, so we must copy the
  842. // token.
  843. AddToken(Saver.save(Token.str()));
  844. Token.clear();
  845. if (Src[I] == '\n')
  846. MarkEOL();
  847. State = INIT;
  848. } else if (Src[I] == '\"') {
  849. State = QUOTED;
  850. } else if (Src[I] == '\\') {
  851. I = parseBackslash(Src, I, Token);
  852. } else {
  853. Token.push_back(Src[I]);
  854. }
  855. break;
  856. case QUOTED:
  857. if (Src[I] == '\"') {
  858. if (I < (E - 1) && Src[I + 1] == '"') {
  859. // Consecutive double-quotes inside a quoted string implies one
  860. // double-quote.
  861. Token.push_back('"');
  862. ++I;
  863. } else {
  864. // Otherwise, end the quoted portion and return to the unquoted state.
  865. State = UNQUOTED;
  866. }
  867. } else if (Src[I] == '\\') {
  868. I = parseBackslash(Src, I, Token);
  869. } else {
  870. Token.push_back(Src[I]);
  871. }
  872. break;
  873. }
  874. }
  875. if (State == UNQUOTED)
  876. AddToken(Saver.save(Token.str()));
  877. }
  878. void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
  879. SmallVectorImpl<const char *> &NewArgv,
  880. bool MarkEOLs) {
  881. auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
  882. auto OnEOL = [&]() {
  883. if (MarkEOLs)
  884. NewArgv.push_back(nullptr);
  885. };
  886. tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
  887. /*AlwaysCopy=*/true, OnEOL);
  888. }
  889. void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver,
  890. SmallVectorImpl<StringRef> &NewArgv) {
  891. auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
  892. auto OnEOL = []() {};
  893. tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
  894. OnEOL);
  895. }
  896. void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
  897. SmallVectorImpl<const char *> &NewArgv,
  898. bool MarkEOLs) {
  899. for (const char *Cur = Source.begin(); Cur != Source.end();) {
  900. SmallString<128> Line;
  901. // Check for comment line.
  902. if (isWhitespace(*Cur)) {
  903. while (Cur != Source.end() && isWhitespace(*Cur))
  904. ++Cur;
  905. continue;
  906. }
  907. if (*Cur == '#') {
  908. while (Cur != Source.end() && *Cur != '\n')
  909. ++Cur;
  910. continue;
  911. }
  912. // Find end of the current line.
  913. const char *Start = Cur;
  914. for (const char *End = Source.end(); Cur != End; ++Cur) {
  915. if (*Cur == '\\') {
  916. if (Cur + 1 != End) {
  917. ++Cur;
  918. if (*Cur == '\n' ||
  919. (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
  920. Line.append(Start, Cur - 1);
  921. if (*Cur == '\r')
  922. ++Cur;
  923. Start = Cur + 1;
  924. }
  925. }
  926. } else if (*Cur == '\n')
  927. break;
  928. }
  929. // Tokenize line.
  930. Line.append(Start, Cur);
  931. cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
  932. }
  933. }
  934. // It is called byte order marker but the UTF-8 BOM is actually not affected
  935. // by the host system's endianness.
  936. static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
  937. return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
  938. }
  939. // Substitute <CFGDIR> with the file's base path.
  940. static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
  941. const char *&Arg) {
  942. assert(sys::path::is_absolute(BasePath));
  943. constexpr StringLiteral Token("<CFGDIR>");
  944. const StringRef ArgString(Arg);
  945. SmallString<128> ResponseFile;
  946. StringRef::size_type StartPos = 0;
  947. for (StringRef::size_type TokenPos = ArgString.find(Token);
  948. TokenPos != StringRef::npos;
  949. TokenPos = ArgString.find(Token, StartPos)) {
  950. // Token may appear more than once per arg (e.g. comma-separated linker
  951. // args). Support by using path-append on any subsequent appearances.
  952. const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
  953. if (ResponseFile.empty())
  954. ResponseFile = LHS;
  955. else
  956. llvm::sys::path::append(ResponseFile, LHS);
  957. ResponseFile.append(BasePath);
  958. StartPos = TokenPos + Token.size();
  959. }
  960. if (!ResponseFile.empty()) {
  961. // Path-append the remaining arg substring if at least one token appeared.
  962. const StringRef Remaining = ArgString.substr(StartPos);
  963. if (!Remaining.empty())
  964. llvm::sys::path::append(ResponseFile, Remaining);
  965. Arg = Saver.save(ResponseFile.str()).data();
  966. }
  967. }
  968. // FName must be an absolute path.
  969. static llvm::Error ExpandResponseFile(StringRef FName, StringSaver &Saver,
  970. TokenizerCallback Tokenizer,
  971. SmallVectorImpl<const char *> &NewArgv,
  972. bool MarkEOLs, bool RelativeNames,
  973. bool ExpandBasePath,
  974. llvm::vfs::FileSystem &FS) {
  975. assert(sys::path::is_absolute(FName));
  976. llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
  977. FS.getBufferForFile(FName);
  978. if (!MemBufOrErr)
  979. return llvm::errorCodeToError(MemBufOrErr.getError());
  980. MemoryBuffer &MemBuf = *MemBufOrErr.get();
  981. StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
  982. // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
  983. ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
  984. std::string UTF8Buf;
  985. if (hasUTF16ByteOrderMark(BufRef)) {
  986. if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
  987. return llvm::createStringError(std::errc::illegal_byte_sequence,
  988. "Could not convert UTF16 to UTF8");
  989. Str = StringRef(UTF8Buf);
  990. }
  991. // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
  992. // these bytes before parsing.
  993. // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
  994. else if (hasUTF8ByteOrderMark(BufRef))
  995. Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
  996. // Tokenize the contents into NewArgv.
  997. Tokenizer(Str, Saver, NewArgv, MarkEOLs);
  998. if (!RelativeNames)
  999. return Error::success();
  1000. llvm::StringRef BasePath = llvm::sys::path::parent_path(FName);
  1001. // If names of nested response files should be resolved relative to including
  1002. // file, replace the included response file names with their full paths
  1003. // obtained by required resolution.
  1004. for (auto &Arg : NewArgv) {
  1005. if (!Arg)
  1006. continue;
  1007. // Substitute <CFGDIR> with the file's base path.
  1008. if (ExpandBasePath)
  1009. ExpandBasePaths(BasePath, Saver, Arg);
  1010. // Skip non-rsp file arguments.
  1011. if (Arg[0] != '@')
  1012. continue;
  1013. StringRef FileName(Arg + 1);
  1014. // Skip if non-relative.
  1015. if (!llvm::sys::path::is_relative(FileName))
  1016. continue;
  1017. SmallString<128> ResponseFile;
  1018. ResponseFile.push_back('@');
  1019. ResponseFile.append(BasePath);
  1020. llvm::sys::path::append(ResponseFile, FileName);
  1021. Arg = Saver.save(ResponseFile.str()).data();
  1022. }
  1023. return Error::success();
  1024. }
  1025. /// Expand response files on a command line recursively using the given
  1026. /// StringSaver and tokenization strategy.
  1027. bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
  1028. SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
  1029. bool RelativeNames, bool ExpandBasePath,
  1030. llvm::Optional<llvm::StringRef> CurrentDir,
  1031. llvm::vfs::FileSystem &FS) {
  1032. bool AllExpanded = true;
  1033. struct ResponseFileRecord {
  1034. std::string File;
  1035. size_t End;
  1036. };
  1037. // To detect recursive response files, we maintain a stack of files and the
  1038. // position of the last argument in the file. This position is updated
  1039. // dynamically as we recursively expand files.
  1040. SmallVector<ResponseFileRecord, 3> FileStack;
  1041. // Push a dummy entry that represents the initial command line, removing
  1042. // the need to check for an empty list.
  1043. FileStack.push_back({"", Argv.size()});
  1044. // Don't cache Argv.size() because it can change.
  1045. for (unsigned I = 0; I != Argv.size();) {
  1046. while (I == FileStack.back().End) {
  1047. // Passing the end of a file's argument list, so we can remove it from the
  1048. // stack.
  1049. FileStack.pop_back();
  1050. }
  1051. const char *Arg = Argv[I];
  1052. // Check if it is an EOL marker
  1053. if (Arg == nullptr) {
  1054. ++I;
  1055. continue;
  1056. }
  1057. if (Arg[0] != '@') {
  1058. ++I;
  1059. continue;
  1060. }
  1061. const char *FName = Arg + 1;
  1062. // Note that CurrentDir is only used for top-level rsp files, the rest will
  1063. // always have an absolute path deduced from the containing file.
  1064. SmallString<128> CurrDir;
  1065. if (llvm::sys::path::is_relative(FName)) {
  1066. if (!CurrentDir)
  1067. llvm::sys::fs::current_path(CurrDir);
  1068. else
  1069. CurrDir = *CurrentDir;
  1070. llvm::sys::path::append(CurrDir, FName);
  1071. FName = CurrDir.c_str();
  1072. }
  1073. auto IsEquivalent = [FName, &FS](const ResponseFileRecord &RFile) {
  1074. llvm::ErrorOr<llvm::vfs::Status> LHS = FS.status(FName);
  1075. if (!LHS) {
  1076. // TODO: The error should be propagated up the stack.
  1077. llvm::consumeError(llvm::errorCodeToError(LHS.getError()));
  1078. return false;
  1079. }
  1080. llvm::ErrorOr<llvm::vfs::Status> RHS = FS.status(RFile.File);
  1081. if (!RHS) {
  1082. // TODO: The error should be propagated up the stack.
  1083. llvm::consumeError(llvm::errorCodeToError(RHS.getError()));
  1084. return false;
  1085. }
  1086. return LHS->equivalent(*RHS);
  1087. };
  1088. // Check for recursive response files.
  1089. if (any_of(drop_begin(FileStack), IsEquivalent)) {
  1090. // This file is recursive, so we leave it in the argument stream and
  1091. // move on.
  1092. AllExpanded = false;
  1093. ++I;
  1094. continue;
  1095. }
  1096. // Replace this response file argument with the tokenization of its
  1097. // contents. Nested response files are expanded in subsequent iterations.
  1098. SmallVector<const char *, 0> ExpandedArgv;
  1099. if (llvm::Error Err =
  1100. ExpandResponseFile(FName, Saver, Tokenizer, ExpandedArgv, MarkEOLs,
  1101. RelativeNames, ExpandBasePath, FS)) {
  1102. // We couldn't read this file, so we leave it in the argument stream and
  1103. // move on.
  1104. // TODO: The error should be propagated up the stack.
  1105. llvm::consumeError(std::move(Err));
  1106. AllExpanded = false;
  1107. ++I;
  1108. continue;
  1109. }
  1110. for (ResponseFileRecord &Record : FileStack) {
  1111. // Increase the end of all active records by the number of newly expanded
  1112. // arguments, minus the response file itself.
  1113. Record.End += ExpandedArgv.size() - 1;
  1114. }
  1115. FileStack.push_back({FName, I + ExpandedArgv.size()});
  1116. Argv.erase(Argv.begin() + I);
  1117. Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
  1118. }
  1119. // If successful, the top of the file stack will mark the end of the Argv
  1120. // stream. A failure here indicates a bug in the stack popping logic above.
  1121. // Note that FileStack may have more than one element at this point because we
  1122. // don't have a chance to pop the stack when encountering recursive files at
  1123. // the end of the stream, so seeing that doesn't indicate a bug.
  1124. assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
  1125. return AllExpanded;
  1126. }
  1127. bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
  1128. SmallVectorImpl<const char *> &Argv, bool MarkEOLs,
  1129. bool RelativeNames, bool ExpandBasePath,
  1130. llvm::Optional<StringRef> CurrentDir) {
  1131. return ExpandResponseFiles(Saver, std::move(Tokenizer), Argv, MarkEOLs,
  1132. RelativeNames, ExpandBasePath,
  1133. std::move(CurrentDir), *vfs::getRealFileSystem());
  1134. }
  1135. bool cl::expandResponseFiles(int Argc, const char *const *Argv,
  1136. const char *EnvVar, StringSaver &Saver,
  1137. SmallVectorImpl<const char *> &NewArgv) {
  1138. auto Tokenize = Triple(sys::getProcessTriple()).isOSWindows()
  1139. ? cl::TokenizeWindowsCommandLine
  1140. : cl::TokenizeGNUCommandLine;
  1141. // The environment variable specifies initial options.
  1142. if (EnvVar)
  1143. if (llvm::Optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
  1144. Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
  1145. // Command line options can override the environment variable.
  1146. NewArgv.append(Argv + 1, Argv + Argc);
  1147. return ExpandResponseFiles(Saver, Tokenize, NewArgv);
  1148. }
  1149. bool cl::readConfigFile(StringRef CfgFile, StringSaver &Saver,
  1150. SmallVectorImpl<const char *> &Argv) {
  1151. SmallString<128> AbsPath;
  1152. if (sys::path::is_relative(CfgFile)) {
  1153. llvm::sys::fs::current_path(AbsPath);
  1154. llvm::sys::path::append(AbsPath, CfgFile);
  1155. CfgFile = AbsPath.str();
  1156. }
  1157. if (llvm::Error Err = ExpandResponseFile(
  1158. CfgFile, Saver, cl::tokenizeConfigFile, Argv,
  1159. /*MarkEOLs=*/false, /*RelativeNames=*/true, /*ExpandBasePath=*/true,
  1160. *llvm::vfs::getRealFileSystem())) {
  1161. // TODO: The error should be propagated up the stack.
  1162. llvm::consumeError(std::move(Err));
  1163. return false;
  1164. }
  1165. return ExpandResponseFiles(Saver, cl::tokenizeConfigFile, Argv,
  1166. /*MarkEOLs=*/false, /*RelativeNames=*/true,
  1167. /*ExpandBasePath=*/true, llvm::None);
  1168. }
  1169. static void initCommonOptions();
  1170. bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
  1171. StringRef Overview, raw_ostream *Errs,
  1172. const char *EnvVar,
  1173. bool LongOptionsUseDoubleDash) {
  1174. initCommonOptions();
  1175. SmallVector<const char *, 20> NewArgv;
  1176. BumpPtrAllocator A;
  1177. StringSaver Saver(A);
  1178. NewArgv.push_back(argv[0]);
  1179. // Parse options from environment variable.
  1180. if (EnvVar) {
  1181. if (llvm::Optional<std::string> EnvValue =
  1182. sys::Process::GetEnv(StringRef(EnvVar)))
  1183. TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
  1184. }
  1185. // Append options from command line.
  1186. for (int I = 1; I < argc; ++I)
  1187. NewArgv.push_back(argv[I]);
  1188. int NewArgc = static_cast<int>(NewArgv.size());
  1189. // Parse all options.
  1190. return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
  1191. Errs, LongOptionsUseDoubleDash);
  1192. }
  1193. /// Reset all options at least once, so that we can parse different options.
  1194. void CommandLineParser::ResetAllOptionOccurrences() {
  1195. // Reset all option values to look like they have never been seen before.
  1196. // Options might be reset twice (they can be reference in both OptionsMap
  1197. // and one of the other members), but that does not harm.
  1198. for (auto *SC : RegisteredSubCommands) {
  1199. for (auto &O : SC->OptionsMap)
  1200. O.second->reset();
  1201. for (Option *O : SC->PositionalOpts)
  1202. O->reset();
  1203. for (Option *O : SC->SinkOpts)
  1204. O->reset();
  1205. if (SC->ConsumeAfterOpt)
  1206. SC->ConsumeAfterOpt->reset();
  1207. }
  1208. }
  1209. bool CommandLineParser::ParseCommandLineOptions(int argc,
  1210. const char *const *argv,
  1211. StringRef Overview,
  1212. raw_ostream *Errs,
  1213. bool LongOptionsUseDoubleDash) {
  1214. assert(hasOptions() && "No options specified!");
  1215. // Expand response files.
  1216. SmallVector<const char *, 20> newArgv(argv, argv + argc);
  1217. BumpPtrAllocator A;
  1218. StringSaver Saver(A);
  1219. ExpandResponseFiles(Saver,
  1220. Triple(sys::getProcessTriple()).isOSWindows() ?
  1221. cl::TokenizeWindowsCommandLine : cl::TokenizeGNUCommandLine,
  1222. newArgv);
  1223. argv = &newArgv[0];
  1224. argc = static_cast<int>(newArgv.size());
  1225. // Copy the program name into ProgName, making sure not to overflow it.
  1226. ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
  1227. ProgramOverview = Overview;
  1228. bool IgnoreErrors = Errs;
  1229. if (!Errs)
  1230. Errs = &errs();
  1231. bool ErrorParsing = false;
  1232. // Check out the positional arguments to collect information about them.
  1233. unsigned NumPositionalRequired = 0;
  1234. // Determine whether or not there are an unlimited number of positionals
  1235. bool HasUnlimitedPositionals = false;
  1236. int FirstArg = 1;
  1237. SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
  1238. if (argc >= 2 && argv[FirstArg][0] != '-') {
  1239. // If the first argument specifies a valid subcommand, start processing
  1240. // options from the second argument.
  1241. ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
  1242. if (ChosenSubCommand != &*TopLevelSubCommand)
  1243. FirstArg = 2;
  1244. }
  1245. GlobalParser->ActiveSubCommand = ChosenSubCommand;
  1246. assert(ChosenSubCommand);
  1247. auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
  1248. auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
  1249. auto &SinkOpts = ChosenSubCommand->SinkOpts;
  1250. auto &OptionsMap = ChosenSubCommand->OptionsMap;
  1251. for (auto *O: DefaultOptions) {
  1252. addOption(O, true);
  1253. }
  1254. if (ConsumeAfterOpt) {
  1255. assert(PositionalOpts.size() > 0 &&
  1256. "Cannot specify cl::ConsumeAfter without a positional argument!");
  1257. }
  1258. if (!PositionalOpts.empty()) {
  1259. // Calculate how many positional values are _required_.
  1260. bool UnboundedFound = false;
  1261. for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
  1262. Option *Opt = PositionalOpts[i];
  1263. if (RequiresValue(Opt))
  1264. ++NumPositionalRequired;
  1265. else if (ConsumeAfterOpt) {
  1266. // ConsumeAfter cannot be combined with "optional" positional options
  1267. // unless there is only one positional argument...
  1268. if (PositionalOpts.size() > 1) {
  1269. if (!IgnoreErrors)
  1270. Opt->error("error - this positional option will never be matched, "
  1271. "because it does not Require a value, and a "
  1272. "cl::ConsumeAfter option is active!");
  1273. ErrorParsing = true;
  1274. }
  1275. } else if (UnboundedFound && !Opt->hasArgStr()) {
  1276. // This option does not "require" a value... Make sure this option is
  1277. // not specified after an option that eats all extra arguments, or this
  1278. // one will never get any!
  1279. //
  1280. if (!IgnoreErrors)
  1281. Opt->error("error - option can never match, because "
  1282. "another positional argument will match an "
  1283. "unbounded number of values, and this option"
  1284. " does not require a value!");
  1285. *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
  1286. << "' is all messed up!\n";
  1287. *Errs << PositionalOpts.size();
  1288. ErrorParsing = true;
  1289. }
  1290. UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
  1291. }
  1292. HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
  1293. }
  1294. // PositionalVals - A vector of "positional" arguments we accumulate into
  1295. // the process at the end.
  1296. //
  1297. SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
  1298. // If the program has named positional arguments, and the name has been run
  1299. // across, keep track of which positional argument was named. Otherwise put
  1300. // the positional args into the PositionalVals list...
  1301. Option *ActivePositionalArg = nullptr;
  1302. // Loop over all of the arguments... processing them.
  1303. bool DashDashFound = false; // Have we read '--'?
  1304. for (int i = FirstArg; i < argc; ++i) {
  1305. Option *Handler = nullptr;
  1306. Option *NearestHandler = nullptr;
  1307. std::string NearestHandlerString;
  1308. StringRef Value;
  1309. StringRef ArgName = "";
  1310. bool HaveDoubleDash = false;
  1311. // Check to see if this is a positional argument. This argument is
  1312. // considered to be positional if it doesn't start with '-', if it is "-"
  1313. // itself, or if we have seen "--" already.
  1314. //
  1315. if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
  1316. // Positional argument!
  1317. if (ActivePositionalArg) {
  1318. ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
  1319. continue; // We are done!
  1320. }
  1321. if (!PositionalOpts.empty()) {
  1322. PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
  1323. // All of the positional arguments have been fulfulled, give the rest to
  1324. // the consume after option... if it's specified...
  1325. //
  1326. if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
  1327. for (++i; i < argc; ++i)
  1328. PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
  1329. break; // Handle outside of the argument processing loop...
  1330. }
  1331. // Delay processing positional arguments until the end...
  1332. continue;
  1333. }
  1334. } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
  1335. !DashDashFound) {
  1336. DashDashFound = true; // This is the mythical "--"?
  1337. continue; // Don't try to process it as an argument itself.
  1338. } else if (ActivePositionalArg &&
  1339. (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
  1340. // If there is a positional argument eating options, check to see if this
  1341. // option is another positional argument. If so, treat it as an argument,
  1342. // otherwise feed it to the eating positional.
  1343. ArgName = StringRef(argv[i] + 1);
  1344. // Eat second dash.
  1345. if (!ArgName.empty() && ArgName[0] == '-') {
  1346. HaveDoubleDash = true;
  1347. ArgName = ArgName.substr(1);
  1348. }
  1349. Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
  1350. LongOptionsUseDoubleDash, HaveDoubleDash);
  1351. if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
  1352. ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
  1353. continue; // We are done!
  1354. }
  1355. } else { // We start with a '-', must be an argument.
  1356. ArgName = StringRef(argv[i] + 1);
  1357. // Eat second dash.
  1358. if (!ArgName.empty() && ArgName[0] == '-') {
  1359. HaveDoubleDash = true;
  1360. ArgName = ArgName.substr(1);
  1361. }
  1362. Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
  1363. LongOptionsUseDoubleDash, HaveDoubleDash);
  1364. // Check to see if this "option" is really a prefixed or grouped argument.
  1365. if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
  1366. Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
  1367. OptionsMap);
  1368. // Otherwise, look for the closest available option to report to the user
  1369. // in the upcoming error.
  1370. if (!Handler && SinkOpts.empty())
  1371. NearestHandler =
  1372. LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
  1373. }
  1374. if (!Handler) {
  1375. if (SinkOpts.empty()) {
  1376. *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
  1377. << "'. Try: '" << argv[0] << " --help'\n";
  1378. if (NearestHandler) {
  1379. // If we know a near match, report it as well.
  1380. *Errs << ProgramName << ": Did you mean '"
  1381. << PrintArg(NearestHandlerString, 0) << "'?\n";
  1382. }
  1383. ErrorParsing = true;
  1384. } else {
  1385. for (Option *SinkOpt : SinkOpts)
  1386. SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
  1387. }
  1388. continue;
  1389. }
  1390. // If this is a named positional argument, just remember that it is the
  1391. // active one...
  1392. if (Handler->getFormattingFlag() == cl::Positional) {
  1393. if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
  1394. Handler->error("This argument does not take a value.\n"
  1395. "\tInstead, it consumes any positional arguments until "
  1396. "the next recognized option.", *Errs);
  1397. ErrorParsing = true;
  1398. }
  1399. ActivePositionalArg = Handler;
  1400. }
  1401. else
  1402. ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
  1403. }
  1404. // Check and handle positional arguments now...
  1405. if (NumPositionalRequired > PositionalVals.size()) {
  1406. *Errs << ProgramName
  1407. << ": Not enough positional command line arguments specified!\n"
  1408. << "Must specify at least " << NumPositionalRequired
  1409. << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
  1410. << ": See: " << argv[0] << " --help\n";
  1411. ErrorParsing = true;
  1412. } else if (!HasUnlimitedPositionals &&
  1413. PositionalVals.size() > PositionalOpts.size()) {
  1414. *Errs << ProgramName << ": Too many positional arguments specified!\n"
  1415. << "Can specify at most " << PositionalOpts.size()
  1416. << " positional arguments: See: " << argv[0] << " --help\n";
  1417. ErrorParsing = true;
  1418. } else if (!ConsumeAfterOpt) {
  1419. // Positional args have already been handled if ConsumeAfter is specified.
  1420. unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
  1421. for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
  1422. if (RequiresValue(PositionalOpts[i])) {
  1423. ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
  1424. PositionalVals[ValNo].second);
  1425. ValNo++;
  1426. --NumPositionalRequired; // We fulfilled our duty...
  1427. }
  1428. // If we _can_ give this option more arguments, do so now, as long as we
  1429. // do not give it values that others need. 'Done' controls whether the
  1430. // option even _WANTS_ any more.
  1431. //
  1432. bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
  1433. while (NumVals - ValNo > NumPositionalRequired && !Done) {
  1434. switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
  1435. case cl::Optional:
  1436. Done = true; // Optional arguments want _at most_ one value
  1437. LLVM_FALLTHROUGH;
  1438. case cl::ZeroOrMore: // Zero or more will take all they can get...
  1439. case cl::OneOrMore: // One or more will take all they can get...
  1440. ProvidePositionalOption(PositionalOpts[i],
  1441. PositionalVals[ValNo].first,
  1442. PositionalVals[ValNo].second);
  1443. ValNo++;
  1444. break;
  1445. default:
  1446. llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
  1447. "positional argument processing!");
  1448. }
  1449. }
  1450. }
  1451. } else {
  1452. assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
  1453. unsigned ValNo = 0;
  1454. for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
  1455. if (RequiresValue(PositionalOpts[J])) {
  1456. ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
  1457. PositionalVals[ValNo].first,
  1458. PositionalVals[ValNo].second);
  1459. ValNo++;
  1460. }
  1461. // Handle the case where there is just one positional option, and it's
  1462. // optional. In this case, we want to give JUST THE FIRST option to the
  1463. // positional option and keep the rest for the consume after. The above
  1464. // loop would have assigned no values to positional options in this case.
  1465. //
  1466. if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
  1467. ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
  1468. PositionalVals[ValNo].first,
  1469. PositionalVals[ValNo].second);
  1470. ValNo++;
  1471. }
  1472. // Handle over all of the rest of the arguments to the
  1473. // cl::ConsumeAfter command line option...
  1474. for (; ValNo != PositionalVals.size(); ++ValNo)
  1475. ErrorParsing |=
  1476. ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
  1477. PositionalVals[ValNo].second);
  1478. }
  1479. // Loop over args and make sure all required args are specified!
  1480. for (const auto &Opt : OptionsMap) {
  1481. switch (Opt.second->getNumOccurrencesFlag()) {
  1482. case Required:
  1483. case OneOrMore:
  1484. if (Opt.second->getNumOccurrences() == 0) {
  1485. Opt.second->error("must be specified at least once!");
  1486. ErrorParsing = true;
  1487. }
  1488. LLVM_FALLTHROUGH;
  1489. default:
  1490. break;
  1491. }
  1492. }
  1493. // Now that we know if -debug is specified, we can use it.
  1494. // Note that if ReadResponseFiles == true, this must be done before the
  1495. // memory allocated for the expanded command line is free()d below.
  1496. LLVM_DEBUG(dbgs() << "Args: ";
  1497. for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
  1498. dbgs() << '\n';);
  1499. // Free all of the memory allocated to the map. Command line options may only
  1500. // be processed once!
  1501. MoreHelp.clear();
  1502. // If we had an error processing our arguments, don't let the program execute
  1503. if (ErrorParsing) {
  1504. if (!IgnoreErrors)
  1505. exit(1);
  1506. return false;
  1507. }
  1508. return true;
  1509. }
  1510. //===----------------------------------------------------------------------===//
  1511. // Option Base class implementation
  1512. //
  1513. bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
  1514. if (!ArgName.data())
  1515. ArgName = ArgStr;
  1516. if (ArgName.empty())
  1517. Errs << HelpStr; // Be nice for positional arguments
  1518. else
  1519. Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
  1520. Errs << " option: " << Message << "\n";
  1521. return true;
  1522. }
  1523. bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
  1524. bool MultiArg) {
  1525. if (!MultiArg)
  1526. NumOccurrences++; // Increment the number of times we have been seen
  1527. switch (getNumOccurrencesFlag()) {
  1528. case Optional:
  1529. if (NumOccurrences > 1)
  1530. return error("may only occur zero or one times!", ArgName);
  1531. break;
  1532. case Required:
  1533. if (NumOccurrences > 1)
  1534. return error("must occur exactly one time!", ArgName);
  1535. LLVM_FALLTHROUGH;
  1536. case OneOrMore:
  1537. case ZeroOrMore:
  1538. case ConsumeAfter:
  1539. break;
  1540. }
  1541. return handleOccurrence(pos, ArgName, Value);
  1542. }
  1543. // getValueStr - Get the value description string, using "DefaultMsg" if nothing
  1544. // has been specified yet.
  1545. //
  1546. static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
  1547. if (O.ValueStr.empty())
  1548. return DefaultMsg;
  1549. return O.ValueStr;
  1550. }
  1551. //===----------------------------------------------------------------------===//
  1552. // cl::alias class implementation
  1553. //
  1554. // Return the width of the option tag for printing...
  1555. size_t alias::getOptionWidth() const {
  1556. return argPlusPrefixesSize(ArgStr);
  1557. }
  1558. void Option::printHelpStr(StringRef HelpStr, size_t Indent,
  1559. size_t FirstLineIndentedBy) {
  1560. assert(Indent >= FirstLineIndentedBy);
  1561. std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
  1562. outs().indent(Indent - FirstLineIndentedBy)
  1563. << ArgHelpPrefix << Split.first << "\n";
  1564. while (!Split.second.empty()) {
  1565. Split = Split.second.split('\n');
  1566. outs().indent(Indent) << Split.first << "\n";
  1567. }
  1568. }
  1569. void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
  1570. size_t FirstLineIndentedBy) {
  1571. const StringRef ValHelpPrefix = " ";
  1572. assert(BaseIndent >= FirstLineIndentedBy);
  1573. std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
  1574. outs().indent(BaseIndent - FirstLineIndentedBy)
  1575. << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
  1576. while (!Split.second.empty()) {
  1577. Split = Split.second.split('\n');
  1578. outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
  1579. }
  1580. }
  1581. // Print out the option for the alias.
  1582. void alias::printOptionInfo(size_t GlobalWidth) const {
  1583. outs() << PrintArg(ArgStr);
  1584. printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
  1585. }
  1586. //===----------------------------------------------------------------------===//
  1587. // Parser Implementation code...
  1588. //
  1589. // basic_parser implementation
  1590. //
  1591. // Return the width of the option tag for printing...
  1592. size_t basic_parser_impl::getOptionWidth(const Option &O) const {
  1593. size_t Len = argPlusPrefixesSize(O.ArgStr);
  1594. auto ValName = getValueName();
  1595. if (!ValName.empty()) {
  1596. size_t FormattingLen = 3;
  1597. if (O.getMiscFlags() & PositionalEatsArgs)
  1598. FormattingLen = 6;
  1599. Len += getValueStr(O, ValName).size() + FormattingLen;
  1600. }
  1601. return Len;
  1602. }
  1603. // printOptionInfo - Print out information about this option. The
  1604. // to-be-maintained width is specified.
  1605. //
  1606. void basic_parser_impl::printOptionInfo(const Option &O,
  1607. size_t GlobalWidth) const {
  1608. outs() << PrintArg(O.ArgStr);
  1609. auto ValName = getValueName();
  1610. if (!ValName.empty()) {
  1611. if (O.getMiscFlags() & PositionalEatsArgs) {
  1612. outs() << " <" << getValueStr(O, ValName) << ">...";
  1613. } else if (O.getValueExpectedFlag() == ValueOptional)
  1614. outs() << "[=<" << getValueStr(O, ValName) << ">]";
  1615. else
  1616. outs() << "=<" << getValueStr(O, ValName) << '>';
  1617. }
  1618. Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
  1619. }
  1620. void basic_parser_impl::printOptionName(const Option &O,
  1621. size_t GlobalWidth) const {
  1622. outs() << PrintArg(O.ArgStr);
  1623. outs().indent(GlobalWidth - O.ArgStr.size());
  1624. }
  1625. // parser<bool> implementation
  1626. //
  1627. bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1628. bool &Value) {
  1629. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  1630. Arg == "1") {
  1631. Value = true;
  1632. return false;
  1633. }
  1634. if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  1635. Value = false;
  1636. return false;
  1637. }
  1638. return O.error("'" + Arg +
  1639. "' is invalid value for boolean argument! Try 0 or 1");
  1640. }
  1641. // parser<boolOrDefault> implementation
  1642. //
  1643. bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1644. boolOrDefault &Value) {
  1645. if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
  1646. Arg == "1") {
  1647. Value = BOU_TRUE;
  1648. return false;
  1649. }
  1650. if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
  1651. Value = BOU_FALSE;
  1652. return false;
  1653. }
  1654. return O.error("'" + Arg +
  1655. "' is invalid value for boolean argument! Try 0 or 1");
  1656. }
  1657. // parser<int> implementation
  1658. //
  1659. bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1660. int &Value) {
  1661. if (Arg.getAsInteger(0, Value))
  1662. return O.error("'" + Arg + "' value invalid for integer argument!");
  1663. return false;
  1664. }
  1665. // parser<long> implementation
  1666. //
  1667. bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1668. long &Value) {
  1669. if (Arg.getAsInteger(0, Value))
  1670. return O.error("'" + Arg + "' value invalid for long argument!");
  1671. return false;
  1672. }
  1673. // parser<long long> implementation
  1674. //
  1675. bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1676. long long &Value) {
  1677. if (Arg.getAsInteger(0, Value))
  1678. return O.error("'" + Arg + "' value invalid for llong argument!");
  1679. return false;
  1680. }
  1681. // parser<unsigned> implementation
  1682. //
  1683. bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1684. unsigned &Value) {
  1685. if (Arg.getAsInteger(0, Value))
  1686. return O.error("'" + Arg + "' value invalid for uint argument!");
  1687. return false;
  1688. }
  1689. // parser<unsigned long> implementation
  1690. //
  1691. bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1692. unsigned long &Value) {
  1693. if (Arg.getAsInteger(0, Value))
  1694. return O.error("'" + Arg + "' value invalid for ulong argument!");
  1695. return false;
  1696. }
  1697. // parser<unsigned long long> implementation
  1698. //
  1699. bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
  1700. StringRef Arg,
  1701. unsigned long long &Value) {
  1702. if (Arg.getAsInteger(0, Value))
  1703. return O.error("'" + Arg + "' value invalid for ullong argument!");
  1704. return false;
  1705. }
  1706. // parser<double>/parser<float> implementation
  1707. //
  1708. static bool parseDouble(Option &O, StringRef Arg, double &Value) {
  1709. if (to_float(Arg, Value))
  1710. return false;
  1711. return O.error("'" + Arg + "' value invalid for floating point argument!");
  1712. }
  1713. bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1714. double &Val) {
  1715. return parseDouble(O, Arg, Val);
  1716. }
  1717. bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
  1718. float &Val) {
  1719. double dVal;
  1720. if (parseDouble(O, Arg, dVal))
  1721. return true;
  1722. Val = (float)dVal;
  1723. return false;
  1724. }
  1725. // generic_parser_base implementation
  1726. //
  1727. // findOption - Return the option number corresponding to the specified
  1728. // argument string. If the option is not found, getNumOptions() is returned.
  1729. //
  1730. unsigned generic_parser_base::findOption(StringRef Name) {
  1731. unsigned e = getNumOptions();
  1732. for (unsigned i = 0; i != e; ++i) {
  1733. if (getOption(i) == Name)
  1734. return i;
  1735. }
  1736. return e;
  1737. }
  1738. static StringRef EqValue = "=<value>";
  1739. static StringRef EmptyOption = "<empty>";
  1740. static StringRef OptionPrefix = " =";
  1741. static size_t getOptionPrefixesSize() {
  1742. return OptionPrefix.size() + ArgHelpPrefix.size();
  1743. }
  1744. static bool shouldPrintOption(StringRef Name, StringRef Description,
  1745. const Option &O) {
  1746. return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
  1747. !Description.empty();
  1748. }
  1749. // Return the width of the option tag for printing...
  1750. size_t generic_parser_base::getOptionWidth(const Option &O) const {
  1751. if (O.hasArgStr()) {
  1752. size_t Size =
  1753. argPlusPrefixesSize(O.ArgStr) + EqValue.size();
  1754. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1755. StringRef Name = getOption(i);
  1756. if (!shouldPrintOption(Name, getDescription(i), O))
  1757. continue;
  1758. size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
  1759. Size = std::max(Size, NameSize + getOptionPrefixesSize());
  1760. }
  1761. return Size;
  1762. } else {
  1763. size_t BaseSize = 0;
  1764. for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
  1765. BaseSize = std::max(BaseSize, getOption(i).size() + 8);
  1766. return BaseSize;
  1767. }
  1768. }
  1769. // printOptionInfo - Print out information about this option. The
  1770. // to-be-maintained width is specified.
  1771. //
  1772. void generic_parser_base::printOptionInfo(const Option &O,
  1773. size_t GlobalWidth) const {
  1774. if (O.hasArgStr()) {
  1775. // When the value is optional, first print a line just describing the
  1776. // option without values.
  1777. if (O.getValueExpectedFlag() == ValueOptional) {
  1778. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1779. if (getOption(i).empty()) {
  1780. outs() << PrintArg(O.ArgStr);
  1781. Option::printHelpStr(O.HelpStr, GlobalWidth,
  1782. argPlusPrefixesSize(O.ArgStr));
  1783. break;
  1784. }
  1785. }
  1786. }
  1787. outs() << PrintArg(O.ArgStr) << EqValue;
  1788. Option::printHelpStr(O.HelpStr, GlobalWidth,
  1789. EqValue.size() +
  1790. argPlusPrefixesSize(O.ArgStr));
  1791. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1792. StringRef OptionName = getOption(i);
  1793. StringRef Description = getDescription(i);
  1794. if (!shouldPrintOption(OptionName, Description, O))
  1795. continue;
  1796. size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
  1797. outs() << OptionPrefix << OptionName;
  1798. if (OptionName.empty()) {
  1799. outs() << EmptyOption;
  1800. assert(FirstLineIndent >= EmptyOption.size());
  1801. FirstLineIndent += EmptyOption.size();
  1802. }
  1803. if (!Description.empty())
  1804. Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
  1805. else
  1806. outs() << '\n';
  1807. }
  1808. } else {
  1809. if (!O.HelpStr.empty())
  1810. outs() << " " << O.HelpStr << '\n';
  1811. for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
  1812. StringRef Option = getOption(i);
  1813. outs() << " " << PrintArg(Option);
  1814. Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
  1815. }
  1816. }
  1817. }
  1818. static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
  1819. // printGenericOptionDiff - Print the value of this option and it's default.
  1820. //
  1821. // "Generic" options have each value mapped to a name.
  1822. void generic_parser_base::printGenericOptionDiff(
  1823. const Option &O, const GenericOptionValue &Value,
  1824. const GenericOptionValue &Default, size_t GlobalWidth) const {
  1825. outs() << " " << PrintArg(O.ArgStr);
  1826. outs().indent(GlobalWidth - O.ArgStr.size());
  1827. unsigned NumOpts = getNumOptions();
  1828. for (unsigned i = 0; i != NumOpts; ++i) {
  1829. if (Value.compare(getOptionValue(i)))
  1830. continue;
  1831. outs() << "= " << getOption(i);
  1832. size_t L = getOption(i).size();
  1833. size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
  1834. outs().indent(NumSpaces) << " (default: ";
  1835. for (unsigned j = 0; j != NumOpts; ++j) {
  1836. if (Default.compare(getOptionValue(j)))
  1837. continue;
  1838. outs() << getOption(j);
  1839. break;
  1840. }
  1841. outs() << ")\n";
  1842. return;
  1843. }
  1844. outs() << "= *unknown option value*\n";
  1845. }
  1846. // printOptionDiff - Specializations for printing basic value types.
  1847. //
  1848. #define PRINT_OPT_DIFF(T) \
  1849. void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
  1850. size_t GlobalWidth) const { \
  1851. printOptionName(O, GlobalWidth); \
  1852. std::string Str; \
  1853. { \
  1854. raw_string_ostream SS(Str); \
  1855. SS << V; \
  1856. } \
  1857. outs() << "= " << Str; \
  1858. size_t NumSpaces = \
  1859. MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
  1860. outs().indent(NumSpaces) << " (default: "; \
  1861. if (D.hasValue()) \
  1862. outs() << D.getValue(); \
  1863. else \
  1864. outs() << "*no default*"; \
  1865. outs() << ")\n"; \
  1866. }
  1867. PRINT_OPT_DIFF(bool)
  1868. PRINT_OPT_DIFF(boolOrDefault)
  1869. PRINT_OPT_DIFF(int)
  1870. PRINT_OPT_DIFF(long)
  1871. PRINT_OPT_DIFF(long long)
  1872. PRINT_OPT_DIFF(unsigned)
  1873. PRINT_OPT_DIFF(unsigned long)
  1874. PRINT_OPT_DIFF(unsigned long long)
  1875. PRINT_OPT_DIFF(double)
  1876. PRINT_OPT_DIFF(float)
  1877. PRINT_OPT_DIFF(char)
  1878. void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
  1879. const OptionValue<std::string> &D,
  1880. size_t GlobalWidth) const {
  1881. printOptionName(O, GlobalWidth);
  1882. outs() << "= " << V;
  1883. size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
  1884. outs().indent(NumSpaces) << " (default: ";
  1885. if (D.hasValue())
  1886. outs() << D.getValue();
  1887. else
  1888. outs() << "*no default*";
  1889. outs() << ")\n";
  1890. }
  1891. // Print a placeholder for options that don't yet support printOptionDiff().
  1892. void basic_parser_impl::printOptionNoValue(const Option &O,
  1893. size_t GlobalWidth) const {
  1894. printOptionName(O, GlobalWidth);
  1895. outs() << "= *cannot print option value*\n";
  1896. }
  1897. //===----------------------------------------------------------------------===//
  1898. // -help and -help-hidden option implementation
  1899. //
  1900. static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
  1901. const std::pair<const char *, Option *> *RHS) {
  1902. return strcmp(LHS->first, RHS->first);
  1903. }
  1904. static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
  1905. const std::pair<const char *, SubCommand *> *RHS) {
  1906. return strcmp(LHS->first, RHS->first);
  1907. }
  1908. // Copy Options into a vector so we can sort them as we like.
  1909. static void sortOpts(StringMap<Option *> &OptMap,
  1910. SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
  1911. bool ShowHidden) {
  1912. SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
  1913. for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
  1914. I != E; ++I) {
  1915. // Ignore really-hidden options.
  1916. if (I->second->getOptionHiddenFlag() == ReallyHidden)
  1917. continue;
  1918. // Unless showhidden is set, ignore hidden flags.
  1919. if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
  1920. continue;
  1921. // If we've already seen this option, don't add it to the list again.
  1922. if (!OptionSet.insert(I->second).second)
  1923. continue;
  1924. Opts.push_back(
  1925. std::pair<const char *, Option *>(I->getKey().data(), I->second));
  1926. }
  1927. // Sort the options list alphabetically.
  1928. array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
  1929. }
  1930. static void
  1931. sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
  1932. SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
  1933. for (auto *S : SubMap) {
  1934. if (S->getName().empty())
  1935. continue;
  1936. Subs.push_back(std::make_pair(S->getName().data(), S));
  1937. }
  1938. array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
  1939. }
  1940. namespace {
  1941. class HelpPrinter {
  1942. protected:
  1943. const bool ShowHidden;
  1944. typedef SmallVector<std::pair<const char *, Option *>, 128>
  1945. StrOptionPairVector;
  1946. typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
  1947. StrSubCommandPairVector;
  1948. // Print the options. Opts is assumed to be alphabetically sorted.
  1949. virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
  1950. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  1951. Opts[i].second->printOptionInfo(MaxArgLen);
  1952. }
  1953. void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
  1954. for (const auto &S : Subs) {
  1955. outs() << " " << S.first;
  1956. if (!S.second->getDescription().empty()) {
  1957. outs().indent(MaxSubLen - strlen(S.first));
  1958. outs() << " - " << S.second->getDescription();
  1959. }
  1960. outs() << "\n";
  1961. }
  1962. }
  1963. public:
  1964. explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
  1965. virtual ~HelpPrinter() {}
  1966. // Invoke the printer.
  1967. void operator=(bool Value) {
  1968. if (!Value)
  1969. return;
  1970. printHelp();
  1971. // Halt the program since help information was printed
  1972. exit(0);
  1973. }
  1974. void printHelp() {
  1975. SubCommand *Sub = GlobalParser->getActiveSubCommand();
  1976. auto &OptionsMap = Sub->OptionsMap;
  1977. auto &PositionalOpts = Sub->PositionalOpts;
  1978. auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
  1979. StrOptionPairVector Opts;
  1980. sortOpts(OptionsMap, Opts, ShowHidden);
  1981. StrSubCommandPairVector Subs;
  1982. sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
  1983. if (!GlobalParser->ProgramOverview.empty())
  1984. outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
  1985. if (Sub == &*TopLevelSubCommand) {
  1986. outs() << "USAGE: " << GlobalParser->ProgramName;
  1987. if (Subs.size() > 2)
  1988. outs() << " [subcommand]";
  1989. outs() << " [options]";
  1990. } else {
  1991. if (!Sub->getDescription().empty()) {
  1992. outs() << "SUBCOMMAND '" << Sub->getName()
  1993. << "': " << Sub->getDescription() << "\n\n";
  1994. }
  1995. outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
  1996. << " [options]";
  1997. }
  1998. for (auto *Opt : PositionalOpts) {
  1999. if (Opt->hasArgStr())
  2000. outs() << " --" << Opt->ArgStr;
  2001. outs() << " " << Opt->HelpStr;
  2002. }
  2003. // Print the consume after option info if it exists...
  2004. if (ConsumeAfterOpt)
  2005. outs() << " " << ConsumeAfterOpt->HelpStr;
  2006. if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
  2007. // Compute the maximum subcommand length...
  2008. size_t MaxSubLen = 0;
  2009. for (size_t i = 0, e = Subs.size(); i != e; ++i)
  2010. MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
  2011. outs() << "\n\n";
  2012. outs() << "SUBCOMMANDS:\n\n";
  2013. printSubCommands(Subs, MaxSubLen);
  2014. outs() << "\n";
  2015. outs() << " Type \"" << GlobalParser->ProgramName
  2016. << " <subcommand> --help\" to get more help on a specific "
  2017. "subcommand";
  2018. }
  2019. outs() << "\n\n";
  2020. // Compute the maximum argument length...
  2021. size_t MaxArgLen = 0;
  2022. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  2023. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  2024. outs() << "OPTIONS:\n";
  2025. printOptions(Opts, MaxArgLen);
  2026. // Print any extra help the user has declared.
  2027. for (const auto &I : GlobalParser->MoreHelp)
  2028. outs() << I;
  2029. GlobalParser->MoreHelp.clear();
  2030. }
  2031. };
  2032. class CategorizedHelpPrinter : public HelpPrinter {
  2033. public:
  2034. explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
  2035. // Helper function for printOptions().
  2036. // It shall return a negative value if A's name should be lexicographically
  2037. // ordered before B's name. It returns a value greater than zero if B's name
  2038. // should be ordered before A's name, and it returns 0 otherwise.
  2039. static int OptionCategoryCompare(OptionCategory *const *A,
  2040. OptionCategory *const *B) {
  2041. return (*A)->getName().compare((*B)->getName());
  2042. }
  2043. // Make sure we inherit our base class's operator=()
  2044. using HelpPrinter::operator=;
  2045. protected:
  2046. void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
  2047. std::vector<OptionCategory *> SortedCategories;
  2048. DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
  2049. // Collect registered option categories into vector in preparation for
  2050. // sorting.
  2051. for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
  2052. SortedCategories.push_back(Category);
  2053. // Sort the different option categories alphabetically.
  2054. assert(SortedCategories.size() > 0 && "No option categories registered!");
  2055. array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
  2056. OptionCategoryCompare);
  2057. // Walk through pre-sorted options and assign into categories.
  2058. // Because the options are already alphabetically sorted the
  2059. // options within categories will also be alphabetically sorted.
  2060. for (size_t I = 0, E = Opts.size(); I != E; ++I) {
  2061. Option *Opt = Opts[I].second;
  2062. for (auto &Cat : Opt->Categories) {
  2063. assert(find(SortedCategories, Cat) != SortedCategories.end() &&
  2064. "Option has an unregistered category");
  2065. CategorizedOptions[Cat].push_back(Opt);
  2066. }
  2067. }
  2068. // Now do printing.
  2069. for (OptionCategory *Category : SortedCategories) {
  2070. // Hide empty categories for --help, but show for --help-hidden.
  2071. const auto &CategoryOptions = CategorizedOptions[Category];
  2072. bool IsEmptyCategory = CategoryOptions.empty();
  2073. if (!ShowHidden && IsEmptyCategory)
  2074. continue;
  2075. // Print category information.
  2076. outs() << "\n";
  2077. outs() << Category->getName() << ":\n";
  2078. // Check if description is set.
  2079. if (!Category->getDescription().empty())
  2080. outs() << Category->getDescription() << "\n\n";
  2081. else
  2082. outs() << "\n";
  2083. // When using --help-hidden explicitly state if the category has no
  2084. // options associated with it.
  2085. if (IsEmptyCategory) {
  2086. outs() << " This option category has no options.\n";
  2087. continue;
  2088. }
  2089. // Loop over the options in the category and print.
  2090. for (const Option *Opt : CategoryOptions)
  2091. Opt->printOptionInfo(MaxArgLen);
  2092. }
  2093. }
  2094. };
  2095. // This wraps the Uncategorizing and Categorizing printers and decides
  2096. // at run time which should be invoked.
  2097. class HelpPrinterWrapper {
  2098. private:
  2099. HelpPrinter &UncategorizedPrinter;
  2100. CategorizedHelpPrinter &CategorizedPrinter;
  2101. public:
  2102. explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
  2103. CategorizedHelpPrinter &CategorizedPrinter)
  2104. : UncategorizedPrinter(UncategorizedPrinter),
  2105. CategorizedPrinter(CategorizedPrinter) {}
  2106. // Invoke the printer.
  2107. void operator=(bool Value);
  2108. };
  2109. } // End anonymous namespace
  2110. #if defined(__GNUC__)
  2111. // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
  2112. // enabled.
  2113. # if defined(__OPTIMIZE__)
  2114. # define LLVM_IS_DEBUG_BUILD 0
  2115. # else
  2116. # define LLVM_IS_DEBUG_BUILD 1
  2117. # endif
  2118. #elif defined(_MSC_VER)
  2119. // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
  2120. // Use _DEBUG instead. This macro actually corresponds to the choice between
  2121. // debug and release CRTs, but it is a reasonable proxy.
  2122. # if defined(_DEBUG)
  2123. # define LLVM_IS_DEBUG_BUILD 1
  2124. # else
  2125. # define LLVM_IS_DEBUG_BUILD 0
  2126. # endif
  2127. #else
  2128. // Otherwise, for an unknown compiler, assume this is an optimized build.
  2129. # define LLVM_IS_DEBUG_BUILD 0
  2130. #endif
  2131. namespace {
  2132. class VersionPrinter {
  2133. public:
  2134. void print() {
  2135. raw_ostream &OS = outs();
  2136. #ifdef PACKAGE_VENDOR
  2137. OS << PACKAGE_VENDOR << " ";
  2138. #else
  2139. OS << "LLVM (http://llvm.org/):\n ";
  2140. #endif
  2141. OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
  2142. #ifdef LLVM_VERSION_INFO
  2143. OS << " " << LLVM_VERSION_INFO;
  2144. #endif
  2145. OS << "\n ";
  2146. #if LLVM_IS_DEBUG_BUILD
  2147. OS << "DEBUG build";
  2148. #else
  2149. OS << "Optimized build";
  2150. #endif
  2151. #ifndef NDEBUG
  2152. OS << " with assertions";
  2153. #endif
  2154. #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
  2155. std::string CPU = std::string(sys::getHostCPUName());
  2156. if (CPU == "generic")
  2157. CPU = "(unknown)";
  2158. OS << ".\n"
  2159. << " Default target: " << sys::getDefaultTargetTriple() << '\n'
  2160. << " Host CPU: " << CPU;
  2161. #endif
  2162. OS << '\n';
  2163. }
  2164. void operator=(bool OptionWasSpecified);
  2165. };
  2166. struct CommandLineCommonOptions {
  2167. // Declare the four HelpPrinter instances that are used to print out help, or
  2168. // help-hidden as an uncategorized list or in categories.
  2169. HelpPrinter UncategorizedNormalPrinter{false};
  2170. HelpPrinter UncategorizedHiddenPrinter{true};
  2171. CategorizedHelpPrinter CategorizedNormalPrinter{false};
  2172. CategorizedHelpPrinter CategorizedHiddenPrinter{true};
  2173. // Declare HelpPrinter wrappers that will decide whether or not to invoke
  2174. // a categorizing help printer
  2175. HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
  2176. CategorizedNormalPrinter};
  2177. HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
  2178. CategorizedHiddenPrinter};
  2179. // Define a category for generic options that all tools should have.
  2180. cl::OptionCategory GenericCategory{"Generic Options"};
  2181. // Define uncategorized help printers.
  2182. // --help-list is hidden by default because if Option categories are being
  2183. // used then --help behaves the same as --help-list.
  2184. cl::opt<HelpPrinter, true, parser<bool>> HLOp{
  2185. "help-list",
  2186. cl::desc(
  2187. "Display list of available options (--help-list-hidden for more)"),
  2188. cl::location(UncategorizedNormalPrinter),
  2189. cl::Hidden,
  2190. cl::ValueDisallowed,
  2191. cl::cat(GenericCategory),
  2192. cl::sub(*AllSubCommands)};
  2193. cl::opt<HelpPrinter, true, parser<bool>> HLHOp{
  2194. "help-list-hidden",
  2195. cl::desc("Display list of all available options"),
  2196. cl::location(UncategorizedHiddenPrinter),
  2197. cl::Hidden,
  2198. cl::ValueDisallowed,
  2199. cl::cat(GenericCategory),
  2200. cl::sub(*AllSubCommands)};
  2201. // Define uncategorized/categorized help printers. These printers change their
  2202. // behaviour at runtime depending on whether one or more Option categories
  2203. // have been declared.
  2204. cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{
  2205. "help",
  2206. cl::desc("Display available options (--help-hidden for more)"),
  2207. cl::location(WrappedNormalPrinter),
  2208. cl::ValueDisallowed,
  2209. cl::cat(GenericCategory),
  2210. cl::sub(*AllSubCommands)};
  2211. cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
  2212. cl::DefaultOption};
  2213. cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{
  2214. "help-hidden",
  2215. cl::desc("Display all available options"),
  2216. cl::location(WrappedHiddenPrinter),
  2217. cl::Hidden,
  2218. cl::ValueDisallowed,
  2219. cl::cat(GenericCategory),
  2220. cl::sub(*AllSubCommands)};
  2221. cl::opt<bool> PrintOptions{
  2222. "print-options",
  2223. cl::desc("Print non-default options after command line parsing"),
  2224. cl::Hidden,
  2225. cl::init(false),
  2226. cl::cat(GenericCategory),
  2227. cl::sub(*AllSubCommands)};
  2228. cl::opt<bool> PrintAllOptions{
  2229. "print-all-options",
  2230. cl::desc("Print all option values after command line parsing"),
  2231. cl::Hidden,
  2232. cl::init(false),
  2233. cl::cat(GenericCategory),
  2234. cl::sub(*AllSubCommands)};
  2235. VersionPrinterTy OverrideVersionPrinter = nullptr;
  2236. std::vector<VersionPrinterTy> ExtraVersionPrinters;
  2237. // Define the --version option that prints out the LLVM version for the tool
  2238. VersionPrinter VersionPrinterInstance;
  2239. cl::opt<VersionPrinter, true, parser<bool>> VersOp{
  2240. "version", cl::desc("Display the version of this program"),
  2241. cl::location(VersionPrinterInstance), cl::ValueDisallowed,
  2242. cl::cat(GenericCategory)};
  2243. };
  2244. } // End anonymous namespace
  2245. // Lazy-initialized global instance of options controlling the command-line
  2246. // parser and general handling.
  2247. static ManagedStatic<CommandLineCommonOptions> CommonOptions;
  2248. static void initCommonOptions() {
  2249. *CommonOptions;
  2250. initDebugCounterOptions();
  2251. initGraphWriterOptions();
  2252. initSignalsOptions();
  2253. initStatisticOptions();
  2254. initTimerOptions();
  2255. initTypeSizeOptions();
  2256. initWithColorOptions();
  2257. initDebugOptions();
  2258. initRandomSeedOptions();
  2259. }
  2260. OptionCategory &cl::getGeneralCategory() {
  2261. // Initialise the general option category.
  2262. static OptionCategory GeneralCategory{"General options"};
  2263. return GeneralCategory;
  2264. }
  2265. void VersionPrinter::operator=(bool OptionWasSpecified) {
  2266. if (!OptionWasSpecified)
  2267. return;
  2268. if (CommonOptions->OverrideVersionPrinter != nullptr) {
  2269. CommonOptions->OverrideVersionPrinter(outs());
  2270. exit(0);
  2271. }
  2272. print();
  2273. // Iterate over any registered extra printers and call them to add further
  2274. // information.
  2275. if (!CommonOptions->ExtraVersionPrinters.empty()) {
  2276. outs() << '\n';
  2277. for (const auto &I : CommonOptions->ExtraVersionPrinters)
  2278. I(outs());
  2279. }
  2280. exit(0);
  2281. }
  2282. void HelpPrinterWrapper::operator=(bool Value) {
  2283. if (!Value)
  2284. return;
  2285. // Decide which printer to invoke. If more than one option category is
  2286. // registered then it is useful to show the categorized help instead of
  2287. // uncategorized help.
  2288. if (GlobalParser->RegisteredOptionCategories.size() > 1) {
  2289. // unhide --help-list option so user can have uncategorized output if they
  2290. // want it.
  2291. CommonOptions->HLOp.setHiddenFlag(NotHidden);
  2292. CategorizedPrinter = true; // Invoke categorized printer
  2293. } else
  2294. UncategorizedPrinter = true; // Invoke uncategorized printer
  2295. }
  2296. // Print the value of each option.
  2297. void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
  2298. void CommandLineParser::printOptionValues() {
  2299. if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
  2300. return;
  2301. SmallVector<std::pair<const char *, Option *>, 128> Opts;
  2302. sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
  2303. // Compute the maximum argument length...
  2304. size_t MaxArgLen = 0;
  2305. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  2306. MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
  2307. for (size_t i = 0, e = Opts.size(); i != e; ++i)
  2308. Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
  2309. }
  2310. // Utility function for printing the help message.
  2311. void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
  2312. if (!Hidden && !Categorized)
  2313. CommonOptions->UncategorizedNormalPrinter.printHelp();
  2314. else if (!Hidden && Categorized)
  2315. CommonOptions->CategorizedNormalPrinter.printHelp();
  2316. else if (Hidden && !Categorized)
  2317. CommonOptions->UncategorizedHiddenPrinter.printHelp();
  2318. else
  2319. CommonOptions->CategorizedHiddenPrinter.printHelp();
  2320. }
  2321. /// Utility function for printing version number.
  2322. void cl::PrintVersionMessage() {
  2323. CommonOptions->VersionPrinterInstance.print();
  2324. }
  2325. void cl::SetVersionPrinter(VersionPrinterTy func) {
  2326. CommonOptions->OverrideVersionPrinter = func;
  2327. }
  2328. void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
  2329. CommonOptions->ExtraVersionPrinters.push_back(func);
  2330. }
  2331. StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
  2332. initCommonOptions();
  2333. auto &Subs = GlobalParser->RegisteredSubCommands;
  2334. (void)Subs;
  2335. assert(is_contained(Subs, &Sub));
  2336. return Sub.OptionsMap;
  2337. }
  2338. iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
  2339. cl::getRegisteredSubcommands() {
  2340. return GlobalParser->getRegisteredSubcommands();
  2341. }
  2342. void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
  2343. initCommonOptions();
  2344. for (auto &I : Sub.OptionsMap) {
  2345. bool Unrelated = true;
  2346. for (auto &Cat : I.second->Categories) {
  2347. if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
  2348. Unrelated = false;
  2349. }
  2350. if (Unrelated)
  2351. I.second->setHiddenFlag(cl::ReallyHidden);
  2352. }
  2353. }
  2354. void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
  2355. SubCommand &Sub) {
  2356. initCommonOptions();
  2357. for (auto &I : Sub.OptionsMap) {
  2358. bool Unrelated = true;
  2359. for (auto &Cat : I.second->Categories) {
  2360. if (is_contained(Categories, Cat) ||
  2361. Cat == &CommonOptions->GenericCategory)
  2362. Unrelated = false;
  2363. }
  2364. if (Unrelated)
  2365. I.second->setHiddenFlag(cl::ReallyHidden);
  2366. }
  2367. }
  2368. void cl::ResetCommandLineParser() { GlobalParser->reset(); }
  2369. void cl::ResetAllOptionOccurrences() {
  2370. GlobalParser->ResetAllOptionOccurrences();
  2371. }
  2372. void LLVMParseCommandLineOptions(int argc, const char *const *argv,
  2373. const char *Overview) {
  2374. llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
  2375. &llvm::nulls());
  2376. }