Initial checking of some rough documentation for commandline library
[oota-llvm.git] / docs / CommandLine.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html><head><title>CommandLine Library Manual</title></head>
3 <body bgcolor=white>
4
5 <table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
6 <tr><td>&nbsp; <font size=+5 color="#EEEEFF" face="Georgia,Palatino,Times,Roman"><b>CommandLine Library Manual</b></font></td>
7 </tr></table>
8
9 <ol>
10   <li><a href="#introduction">Introduction</a>
11   <li><a href="#quickstart">Quick Start Guide</a>
12     <ol>
13       <li><a href="#flags">Flag Arguments</a>
14       <li><a href="#aliases">Argument Aliases</a>
15       <li><a href="#onealternative">Selecting one alternative from a set</a>
16       <li><a href="#namedalternatives">Named alternatives</a>
17       <li><a href="#enumlist">Parsing a list of options</a>
18     </ol>
19   <li><a href="#referenceguide">Reference Guide</a>
20   <li><a href="#extensionguide">Extension Guide</a>
21 </ol><p>
22
23
24 <!-- *********************************************************************** -->
25 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
26 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
27 <a name="introduction">Introduction
28 </b></font></td></tr></table><ul>
29 <!-- *********************************************************************** -->
30
31 This document describes the CommandLine argument processing library.  It will show you how to use it, and what it can do.<p>
32
33 Although there are a <b>lot</b> of command line argument parsing libraries out there in many different languages, none of them fit well with what I needed.  By looking at the features and problems of other libraries, I designed the CommandLine library to have the following features:<p>
34
35 <ol>
36 <li>Speed: The CommandLine library is very quick and uses little resources.  The parsing time of the library is directly proportional to the number of arguments parsed, not the the number of options recognized.  Additionally, command line argument values are captured transparently into user defined variables, which can be accessed like any other variable (and with the same performance).<p>
37
38 <li>Type Safe: As a user of CommandLine, you don't have to worry about remembering the type of arguments that you want (is it an int?  a string? a bool? an enum?) and keep casting it around.  Not only does this help prevent error prone constructs, it also leads to dramatically cleaner source code.<p>
39
40 <li>No subclasses required: To use CommandLine, you instantiate variables that correspond to the arguments that you would like to capture, you don't subclass a parser.  This leads to much less boilerplate code.<p>
41
42 <li>Globally accessible: Libraries can specify command line arguments that are automatically enabled in any tool that links to the library.  This is possible because the application doesn't have to keep a "list" of arguments to pass to the parser.<p>
43
44 <li>More Clean: CommandLine supports enum types directly, meaning that there is less error and more security built into the library.  You don't have to worry about whether your integral command line argument accidentally got assigned a value that is not valid for your enum type.<p>
45
46 <li>Powerful: The CommandLine library supports many different types of arguments, from simple boolean flags to scalars arguments (strings, integers, enums, doubles), to lists of arguments.  This is possible because CommandLine is...<p>
47
48 <li>Extensible: It is very simple to add a new argument type to CommandLine.  Simply subclass the <tt>cl::Option</tt> and customize its behaviour however you would like.<p>
49
50 <li>Labor Saving: The CommandLine library cuts down on the amount of grunt work that you, the user, have to do.  For example, it automatically provides a --help option that shows the available command line options for your tool.<p>
51 </ol>
52
53 This document will hopefully let you jump in and start using CommandLine in your utility quickly and painlessly.  Additionally it should be a simple reference manual to figure out how stuff works.  If it is failing in some area, nag the author, <a href="mailto:sabre@nondot.org">Chris Lattner</a>.<p>
54
55
56 <!-- *********************************************************************** -->
57 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
58 <a name="quickstart">Quick Start Guide
59 </b></font></td></tr></table><ul>
60 <!-- *********************************************************************** -->
61
62 This section of the manual runs through a simple CommandLine'ification of a utility, a program optimizer.  This is intended to show you how to jump into using the CommandLine library in your own program, and show you some of the cool things it can do.<p>
63
64 To start out, you need to include the CommandLine header file into your program:<p>
65
66 <pre>
67   #include "llvm/Support/CommandLine.h"
68 </pre><p>
69
70 Additionally, you need to add this as the first line of your main program:<p>
71
72 <pre>
73 int main(int argc, char **argv) {
74   cl::ParseCommandLineOptions(argc, argv);
75   ...
76 }
77 </pre><p>
78
79 ... which actually parses the arguments and fills in the variable declarations.<p>
80
81 Now that you are ready to support command line arguments, we need to tell the system which ones we want, and what type of argument they are.  The CommandLine library uses the model of variable declarations to capture command line arguments.  This means that for every command line option that you would like to support, there should be a variable declaration to capture the result.  For example, in our optimizer, we would like to support the unix standard '<tt>-o &lt;filename&gt;</tt>' option to specify where to put the output.  With the CommandLine library, this is represented like this:<p>
82
83 <pre>
84 cl::String OutputFilename("<i>o</i>", "<i>Specify output filename</i>");
85 </pre><p>
86
87 or more verbosely, like this:<p>
88
89 <pre>
90 cl::String OutputFilename("<i>o</i>", "<i>Specify output filename</i>", cl::NoFlags, "");
91 </pre><p>
92
93 This declares a variable "<tt>OutputFilename</tt>" that is used to capture the result of the "<tt>o</tt>" argument (first parameter).  The help text that is associated with the option is specified as the second argument to the constructor.  The type of the variable is "<tt>cl::String</tt>", which stands for CommandLine string argument.  This variable may be used in any context that a normal C++ string object may be used.  For example:<p>
94
95 <pre>
96   ...
97   ofstream Output(OutputFilename.c_str());
98   if (Out.good()) ...
99   ...
100 </pre><p>
101
102 The two optional arguments (shown in the verbose example) show that you can pass "flags" to control the behavior of the argument (discussed later), and a default value for the argument (which is normally just an empty string, but you can override it if you would like).<p>
103
104 In addition, we would like to specify an input filename as well, but without an associated flag (i.e. we would like for the optimizer to be run like this: "<tt>opt [flags] sourcefilename.c</tt>").  To support this style of argument, the CommandLine library allows one "unnamed" argument to be specified for the program.  In our case it would look like this:<p>
105
106 <pre>
107 cl::String InputFilename("", "<i>Source file to optimize</i>", cl::NoFlags, "<i>-</i>");
108 </pre>
109
110 This declaration indicates that an unbound option should be treated as the input filename... and if one is not specified, a default value of "-" is desired (which is commonly used to refer to standard input).  If you would like to require that the user of your tool specify an input filename, you can mark the argument as such with the "<tt>cl::Required</tt>" flag:<p>
111
112 <pre>
113 cl::String InputFilename("", "<i>Source file to optimize</i>", <b>cl::Required</b>, "<i>-</i>");
114 </pre>
115
116 The CommandLine library will then issue an error if the argument is not specified (this flag can, of course, be applied to any argument type).  This is one example of how using flags can alter the default behaviour of the library, on a per-option basis.<p>
117
118 <!-- ======================================================================= -->
119 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
120 <a name="flags">Flag Arguments
121 </b></font></td></tr></table><ul>
122
123 In addition to input and output filenames, we would like the optimizer to support three boolean flags: "<tt>-f</tt>" to force overwriting of the output file, "<tt>--quiet</tt>" to enable quiet mode, and "<tt>-q</tt>" for backwards compatibility with some of our users.  We can support these with the "<tt>cl::Flag</tt>" declaration like this:<p>
124
125 <pre>
126 cl::Flag Force ("<i>f</i>", "<i>Overwrite output files</i>", cl::NoFlags, false);
127 cl::Flag Quiet ("<i>q</i>", "<i>Don't print informational messages</i>", cl::Hidden);
128 cl::Flag Quiet2("<i>quiet</i>", "<i>Don't print informational messages</i>", cl::NoFlags);
129 </pre><p>
130
131 This does what you would expect: it declares three boolean variables ("<tt>Force</tt>", "<tt>Quiet</tt>", and "<tt>Quiet2</tt>") to recognize these options.  Note that the "<tt>-q</tt>" option is specified with the "<tt>cl::Hidden</tt>" flag.  This prevents it from being shown by the standard "<tt>--help</tt>" command line argument provided.  With these declarations, "<tt>opt --help</tt>" emits this:<p>
132
133 <pre>
134 USAGE: opt [options]
135
136 OPTIONS:
137   -f     - Overwrite output files
138   -o     - Override output filename
139   -quiet - Don't print informational messages
140   -help  - display available options (--help-hidden for more)
141 </pre><p>
142
143 and "<tt>opt --help-hidden</tt>" emits this:<p>
144
145 <pre>
146 USAGE: opt [options]
147
148 OPTIONS:
149   -f     - Overwrite output files
150   -o     - Override output filename
151   -q     - Don't print informational messages
152   -quiet - Don't print informational messages
153   -help  - display available options (--help-hidden for more)
154 </pre><p>
155
156 This brief example has shown you how to use simple scalar command line arguments, by using the "<tt>cl::String</tt>" and "<tt>cl::Flag</tt>" classes.  In addition to these classes, there are also "<tt>cl::Int</tt>" and "<tt>cl::Double</tt>" classes that work analagously.<p>
157
158
159 <!-- ======================================================================= -->
160 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
161 <a name="aliases">Argument Aliases
162 </b></font></td></tr></table><ul>
163
164 This works well, except for the fact that we need to check the quiet condition like this now:<p>
165
166 <pre>
167 ...
168   if (!Quiet &amp;&amp; !Quiet2) printInformationalMessage(...);
169 ...
170 </pre><p>
171
172 ... which is a real pain!  Instead of defining two values for the same condition, we can use the "<tt>cl::Alias</tt>" to make the "<tt>-q</tt>" option an <b>alias</b> for "<tt>-quiet</tt>" instead of a value itself:<p>
173
174 <pre>
175 cl::Flag  Force ("<i>f</i>", "<i>Overwrite output files</i>", cl::NoFlags, false);
176 cl::Flag  Quiet ("<i>quiet</i>", "<i>Don't print informational messages</i>", cl::NoFlags, false);
177 cl::Alias QuietA("<i>q</i>", "<i>Alias for -quiet</i>", cl::NoFlags, Quiet);
178 </pre><p>
179
180 Which does exactly what we want... and the alias is automatically hidden from the "<tt>--help</tt>" output.  Note how the alias specifies the variable that it wants to alias to, the alias argument name, and the help description (shown by "<tt>--help-hidden</tt>") of the alias.  Now your user code can simply use:<p>
181
182 <pre>
183 ...
184   if (!Quiet) printInformationalMessage(...);
185 ...
186 </pre><p>
187
188 ... which is much nicer!  The "<tt>cl::Alias</tt>" can be used to specify an alternative name for any variable type, and has many uses.<p>
189
190
191 <!-- ======================================================================= -->
192 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
193 <a name="onealternative">Selecting one alternative from a set
194 </b></font></td></tr></table><ul>
195
196 Often we would like to be able to enable one option from a set of options.  The CommandLine library has a couple of different ways to do this... the first is with the "<tt>cl::EnumFlags</tt> class.<p>
197
198 Lets say that we would like to add four optimizations levels to our optimizer, using the standard flags "<tt>-g</tt>", "<tt>-O0</tt>", "<tt>-O1</tt>", and "<tt>-O2</tt>".  We could easily implement this with the "<tt>cl::Flag</tt>" class above, but there are several problems with this strategy:<p>
199
200 <ol>
201 <li>A user could specify more than one of the options at a time, for example, "<tt>opt -O3 -O2</tt>".  The CommandLine library would not catch this erroneous input for us.
202 <li>We would have to test 4 different variables to see which ones are set.
203 <li>This doesn't map to the numeric levels that we want... so we cannot easily see if some level &gt;= "<tt>-O1</tt>" is enabled.
204 </ol><p>
205
206 To cope with these problems, the CommandLine library provides the "<tt>cl::EnumFlags</tt> class, which is used like this:<p>
207
208 <pre>
209 enum OptLevel {
210   g, O1, O2, O3
211 };
212
213 cl::EnumFlags&lt;enum OptLevel&gt; OptimizationLevel(cl::NoFlags,
214   clEnumVal(g , "<i>No optimizations, enable debugging</i>"),
215   clEnumVal(O1, "<i>Enable trivial optimizations</i>"),
216   clEnumVal(O2, "<i>Enable default optimizations</i>"),
217   clEnumVal(O3, "<i>Enable expensive optimizations</i>"),
218  0);
219
220 ...
221   if (OptimizationLevel &gt;= O2) doGCSE(...);
222 ...
223 </pre><p>
224
225 This declaration defines a variable "<tt>OptimizationLevel</tt>" of the "<tt>OptLevel</tt>" enum type.  This variable can be assigned any of the values that are listed in the declaration (Note that the declaration list must be terminated with the "<tt>0</tt>" argument!).  The CommandLine library enforces that the user can only specify one of the options, and it ensure that only valid enum values can be specified.  The default value of the flag is the first value listed.
226
227
228 In addition to all of this, the CommandLine library automatically names the flag values the same as the enum values.<p>
229
230 In this case, it is sort of awkward that flag names correspond directly to enum names, because we probably don't want a enum definition named "<tt>g</tt>" in our program.  We could alternatively write this example like this:<p>
231
232 <pre>
233 enum OptLevel {
234   Debug, O1, O2, O3
235 };
236
237 cl::EnumFlags&lt;enum OptLevel&gt; OptimizationLevel(cl::NoFlags,
238  clEnumValN(Debug, "g", "<i>No optimizations, enable debugging</i>"),
239   clEnumVal(O1        , "<i>Enable trivial optimizations</i>"),
240   clEnumVal(O2        , "<i>Enable default optimizations</i>"),
241   clEnumVal(O3        , "<i>Enable expensive optimizations</i>"),
242  0);
243
244 ...
245   if (OptimizationLevel == Debug) outputDebugInfo(...);
246 ...
247 </pre><p>
248
249 By using the "<tt>clEnumValN</tt>" token instead of "<tt>clEnumVal</tt>", we can directly specify the name that the flag should get.<p>
250
251 <!-- ======================================================================= -->
252 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
253 <a name="namedalternatives">Named Alternatives
254 </b></font></td></tr></table><ul>
255
256 Another useful argument form is a named alternative style.  We shall use this style in our optimizer to specify different debug levels that can be used.  Instead of each debug level being its own switch, we want to support the following options, of which only one can be specified at a time: "<tt>--debug-level=none</tt>", "<tt>--debug-level=quick</tt>", "<tt>--debug-level=detailed</tt>".  To do this, we use the CommandLine "<tt>cl::Enum</tt>" class:<p>
257
258 <pre>
259 enum DebugLev {
260   nodebuginfo, quick, detailed
261 };
262
263 // Enable Debug Options to be specified on the command line
264 cl::Enum&lt;enum DebugLev&gt; DebugLevel("<i>debug_level</i>", cl::NoFlags,
265    "select debugging level",
266   clEnumValN(nodebuginfo, "none", "<i>disable debug information</i>"),
267    clEnumVal(quick,               "<i>enable quick debug information</i>"),
268    clEnumVal(detailed,            "<i>enable detailed debug information</i>"),
269  0);
270 </pre>
271
272 This definition defines an enumerated command line variable of type "<tt>enum DebugLev</tt>", with the same semantics as the "<tt>EnumFlags</tt>" definition does.  The difference here is just the interface exposed to the user of your program and the help output by the "<tt>--help</tt>" option:<p>
273
274 <pre>
275 ...
276 OPTIONS:
277   -debug_level - select debugging level
278     =none      - disable debug information
279     =quick     - enable quick debug information
280     =detailed  - enable detailed debug information
281   -g           - No optimizations, enable debugging
282   -O1          - Enable trivial optimizations
283   -O2          - Enable default optimizations
284   -O3          - Enable expensive optimizations
285   ...
286 </pre><p>
287
288 By providing both of these forms of command line argument, the CommandLine library lets the application developer choose the appropriate interface for the job.<p>
289
290
291 <!-- ======================================================================= -->
292 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td>&nbsp;</td><td width="100%">&nbsp; <font color="#EEEEFF" face="Georgia,Palatino"><b>
293 <a name="enumlist">Parsing a list of options
294 </b></font></td></tr></table><ul>
295
296 Now that we have the standard run of the mill argument types out of the way, lets get a little wild and crazy.  Lets say that we want our optimizer to accept a <b>list</b> of optimizations to perform, allowing duplicates.  For example, we might want to run: "<tt>opt -dce -constprop -inline -dce -strip</tt>".  For this case, the order of the arguments and the number of appearances is very important.  This is what the "<tt>cl::EnumList</tt>" definition is for.  First, start by defining an enum of the optimizations that you would like to perform:<p>
297
298 <pre>
299 enum Opts {
300   // 'inline' is a C++ reserved word, so name it 'inlining'
301   dce, constprop, inlining, strip
302 }
303 </pre><p>
304
305 Then define your "<tt>cl::EnumList</tt>" variable:<p>
306
307 <pre>
308 cl::EnumList<enum Opts> OptimizationList(cl::NoFlags,
309   clEnumVal(dce               , "<i>Dead Code Elimination</i>"),
310   clEnumVal(constprop         , "<i>Constant Propogation</i>"),
311  clEnumValN(inlining, "<i>inline</i>", "<i>Procedure Integration</i>"),
312   clEnumVal(strip             , "<i>Strip Symbols</i>"),
313 0);
314 </pre><p>
315
316 This defines a variable that is conceptually of the type "<tt>vector&lt;enum Opts&gt;</tt>".  Thus, you can do operations like this:<p>
317
318 <pre>
319   for (unsigned i = 0; i &lt; OptimizationList.size(); ++i)
320     switch (OptimizationList[i])
321        ...
322 </pre>
323
324 ... to iterate through the list of options specified.
325
326
327 <!-- *********************************************************************** -->
328 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
329 <a name="referenceguide">Reference Guide
330 </b></font></td></tr></table><ul>
331 <!-- *********************************************************************** -->
332
333 Reference Guide: TODO
334
335
336 <!-- *********************************************************************** -->
337 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
338 <a name="extensionguide">Extension Guide
339 </b></font></td></tr></table><ul>
340 <!-- *********************************************************************** -->
341
342 Extension Guide: TODO
343
344
345
346
347 <!-- *********************************************************************** -->
348 </ul>
349 <!-- *********************************************************************** -->
350
351 <hr>
352 <font size=-1>
353 <address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
354 <!-- Created: Tue Jan 23 15:19:28 CST 2001 -->
355 <!-- hhmts start -->
356 Last modified: Mon Jul 23 17:33:57 CDT 2001
357 <!-- hhmts end -->
358 </font>
359 </body></html>