]> git.cworth.org Git - apitrace/blob - cli/cli_trim.cpp
trim: Drop unused textures while trimming.
[apitrace] / cli / cli_trim.cpp
1 /**************************************************************************
2  *
3  * Copyright 2010 VMware, Inc.
4  * Copyright 2011 Intel corporation
5  * All Rights Reserved.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  *
25  **************************************************************************/
26
27 #include <sstream>
28 #include <string.h>
29 #include <limits.h> // for CHAR_MAX
30 #include <getopt.h>
31
32 #include <GL/gl.h>
33 #include <GL/glext.h>
34
35 #include <set>
36
37 #include "cli.hpp"
38
39 #include "os_string.hpp"
40
41 #include "trace_callset.hpp"
42 #include "trace_parser.hpp"
43 #include "trace_writer.hpp"
44
45 #define STRNCMP_LITERAL(var, literal) strncmp((var), (literal), sizeof (literal) -1)
46
47 static const char *synopsis = "Create a new trace by trimming an existing trace.";
48
49 static void
50 usage(void)
51 {
52     std::cout
53         << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n"
54         << synopsis << "\n"
55         "\n"
56         "    -h, --help               Show detailed help for trim options and exit\n"
57         "        --calls=CALLSET      Include specified calls in the trimmed output.\n"
58         "        --deps               Include additional calls to satisfy dependencies\n"
59         "        --no-deps            Do not include calls from dependency analysis\n"
60         "        --prune              Omit uninteresting calls from the trace output\n"
61         "        --no-prune           Do not prune uninteresting calls from the trace.\n"
62         "    -x, --exact              Include exactly the calls specified in --calls\n"
63         "                             Equivalent to both --no-deps and --no-prune\n"
64         "        --thread=THREAD_ID   Only retain calls from specified thread\n"
65         "    -o, --output=TRACE_FILE  Output trace file\n"
66     ;
67 }
68
69 static void
70 help()
71 {
72     std::cout
73         << "usage: apitrace trim [OPTIONS] TRACE_FILE...\n"
74         << synopsis << "\n"
75         "\n"
76         "    -h, --help               Show this help message and exit\n"
77         "\n"
78         "        --calls=CALLSET      Include specified calls in the trimmed output.\n"
79         "                             Note that due to dependency analysis and pruning\n"
80         "                             of uninteresting calls the resulting trace may\n"
81         "                             include more and less calls than specified.\n"
82         "                             See --no-deps, --no-prune, and --exact to change\n"
83         "                             this behavior.\n"
84         "\n"
85         "        --deps               Perform dependency analysis and include dependent\n"
86         "                             calls as needed, (even if those calls were not\n"
87         "                             explicitly requested with --calls). This is the\n"
88         "                             default behavior. See --no-deps and --exact.\n"
89         "\n"
90         "        --no-deps            Do not perform dependency analysis. In this mode\n"
91         "                             the trimmed trace will never include calls from\n"
92         "                             outside the range specified in --calls.\n"
93         "\n"
94         "        --prune              Omit calls that have no side effects, even if the\n"
95         "                             call is within the range specified by --calls.\n"
96         "                             This is the default behavior. See --no-prune\n"
97         "\n"
98         "        --no-prune           Do not prune uninteresting calls from the trace.\n"
99         "                             In this mode the trimmed trace will never omit\n"
100         "                             any calls within the range specified in --calls.\n"
101         "\n"
102         "    -x, --exact              Trim the trace to exactly the calls specified in\n"
103         "                             --calls. This option is equivalent to passing\n"
104         "                             both --no-deps and --no-prune.\n"
105         "\n"
106         "        --thread=THREAD_ID   Only retain calls from specified thread\n"
107         "\n"
108         "    -o, --output=TRACE_FILE  Output trace file\n"
109         "\n"
110     ;
111 }
112
113 enum {
114     CALLS_OPT = CHAR_MAX + 1,
115     DEPS_OPT,
116     NO_DEPS_OPT,
117     PRUNE_OPT,
118     NO_PRUNE_OPT,
119     THREAD_OPT,
120 };
121
122 const static char *
123 shortOptions = "ho:x";
124
125 const static struct option
126 longOptions[] = {
127     {"help", no_argument, 0, 'h'},
128     {"calls", required_argument, 0, CALLS_OPT},
129     {"deps", no_argument, 0, DEPS_OPT},
130     {"no-deps", no_argument, 0, NO_DEPS_OPT},
131     {"prune", no_argument, 0, PRUNE_OPT},
132     {"no-prune", no_argument, 0, NO_PRUNE_OPT},
133     {"exact", no_argument, 0, 'x'},
134     {"thread", required_argument, 0, THREAD_OPT},
135     {"output", required_argument, 0, 'o'},
136     {0, 0, 0, 0}
137 };
138
139 struct stringCompare {
140     bool operator() (const char *a, const char *b) const {
141         return strcmp(a, b) < 0;
142     }
143 };
144
145 class TraceAnalyzer {
146     /* Maps for tracking resource dependencies between calls. */
147     std::map<std::string, std::set<unsigned> > resources;
148     std::map<std::string, std::set<std::string> > dependencies;
149
150     /* Maps for tracking OpenGL state. */
151     std::map<GLenum, unsigned> texture_map;
152
153     /* The final set of calls required. This consists of calls added
154      * explicitly with the require() method as well as all calls
155      * implicitly required by those through resource dependencies. */
156     std::set<unsigned> required;
157
158     bool transformFeedbackActive;
159     bool framebufferObjectActive;
160     bool insideBeginEnd;
161
162     /* Rendering often has no side effects, but it can in some cases,
163      * (such as when transform feedback is active, or when rendering
164      * targets a framebuffer object). */
165     bool renderingHasSideEffect() {
166         return transformFeedbackActive || framebufferObjectActive;
167     }
168
169     /* Provide: Record that the given call affects the given resource
170      * as a side effect. */
171     void provide(std::string resource, trace::CallNo call_no) {
172         resources[resource].insert(call_no);
173     }
174
175     /* Link: Establish a dependency between resource 'resource' and
176      * resource 'dependency'. This dependency is captured by name so
177      * that if the list of calls that provide 'dependency' grows
178      * before 'resource' is consumed, those calls will still be
179      * captured. */
180     void link(std::string resource, std::string dependency) {
181         dependencies[resource].insert(dependency);
182     }
183
184     /* Unlink: Remove dependency from 'resource' on 'dependency'. */
185     void unlink(std::string resource, std::string dependency) {
186         dependencies[resource].erase(dependency);
187         if (dependencies[resource].size() == 0) {
188             dependencies.erase(resource);
189         }
190     }
191
192     /* Unlink all: Remove dependencies from 'resource' to all other
193      * resources. */
194     void unlinkAll(std::string resource) {
195         dependencies.erase(resource);
196     }
197
198     /* Resolve: Recursively compute all calls providing 'resource',
199      * (including linked dependencies of 'resource' on other
200      * resources). */
201     std::set<unsigned> resolve(std::string resource) {
202         std::set<std::string> *deps;
203         std::set<std::string>::iterator dep;
204
205         std::set<unsigned> *calls;
206         std::set<unsigned>::iterator call;
207
208         std::set<unsigned> result, deps_set;
209
210         /* Recursively chase dependencies. */
211         if (dependencies.count(resource)) {
212             deps = &dependencies[resource];
213             for (dep = deps->begin(); dep != deps->end(); dep++) {
214                 deps_set = resolve(*dep);
215                 for (call = deps_set.begin(); call != deps_set.end(); call++) {
216                     result.insert(*call);
217                 }
218             }
219         }
220
221         /* Also look for calls that directly provide 'resource' */
222         if (resources.count(resource)) {
223             calls = &resources[resource];
224             for (call = calls->begin(); call != calls->end(); call++) {
225                 result.insert(*call);
226             }
227         }
228
229         return result;
230     }
231
232     /* Consume: Resolve all calls that provide the given resource, and
233      * add them to the required list. Then clear the call list for
234      * 'resource' along with any dependencies. */
235     void consume(std::string resource) {
236
237         std::set<unsigned> calls;
238         std::set<unsigned>::iterator call;
239
240         calls = resolve(resource);
241
242         dependencies.erase(resource);
243         resources.erase(resource);
244
245         for (call = calls.begin(); call != calls.end(); call++) {
246             required.insert(*call);
247         }
248     }
249
250     void stateTrackPreCall(trace::Call *call) {
251
252         const char *name = call->name();
253
254         if (strcmp(name, "glBegin") == 0) {
255             insideBeginEnd = true;
256             return;
257         }
258
259         if (strcmp(name, "glBeginTransformFeedback") == 0) {
260             transformFeedbackActive = true;
261             return;
262         }
263
264         if (strcmp(name, "glBindTexture") == 0) {
265             GLenum target;
266             GLuint texture;
267
268             target = static_cast<GLenum>(call->arg(0).toSInt());
269             texture = call->arg(1).toUInt();
270
271             if (texture == 0) {
272                 texture_map.erase(target);
273             } else {
274                 texture_map[target] = texture;
275             }
276
277             return;
278         }
279
280         if (strcmp(name, "glBindFramebuffer") == 0) {
281             GLenum target;
282             GLuint framebuffer;
283
284             target = static_cast<GLenum>(call->arg(0).toSInt());
285             framebuffer = call->arg(1).toUInt();
286
287             if (target == GL_FRAMEBUFFER || target == GL_DRAW_FRAMEBUFFER) {
288                 if (framebuffer == 0) {
289                     framebufferObjectActive = false;
290                 } else {
291                     framebufferObjectActive = true;
292                 }
293             }
294             return;
295         }
296     }
297
298     void stateTrackPostCall(trace::Call *call) {
299
300         const char *name = call->name();
301
302         if (strcmp(name, "glEnd") == 0) {
303             insideBeginEnd = false;
304             return;
305         }
306
307         if (strcmp(name, "glEndTransformFeedback") == 0) {
308             transformFeedbackActive = false;
309             return;
310         }
311
312         /* If this swapbuffers was included in the trace then it will
313          * have already consumed all framebuffer dependencies. If not,
314          * then clear them now so that they don't carry over into the
315          * next frame. */
316         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
317             call->flags & trace::CALL_FLAG_END_FRAME) {
318             dependencies.erase("framebuffer");
319             resources.erase("framebuffer");
320             return;
321         }
322     }
323
324     void recordSideEffects(trace::Call *call) {
325
326         const char *name = call->name();
327
328         /* If call is flagged as no side effects, then we are done here. */
329         if (call->flags & trace::CALL_FLAG_NO_SIDE_EFFECTS) {
330             return;
331         }
332
333         /* Similarly, swap-buffers calls don't have interesting side effects. */
334         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
335             call->flags & trace::CALL_FLAG_END_FRAME) {
336             return;
337         }
338
339         if (strcmp(name, "glGenTextures") == 0) {
340             const trace::Array *textures = dynamic_cast<const trace::Array *>(&call->arg(1));
341             size_t i;
342             GLuint texture;
343
344             if (textures) {
345                 for (i = 0; i < textures->size(); i++) {
346                     std::stringstream ss;
347
348                     texture = textures->values[i]->toUInt();
349                     ss << "texture-" << texture;
350
351                     provide(ss.str(), call->no);
352                 }
353             }
354             return;
355         }
356
357         if (strcmp(name, "glBindTexture") == 0) {
358             GLenum target;
359             GLuint texture;
360
361             std::stringstream ss_target, ss_texture;
362
363             target = static_cast<GLenum>(call->arg(0).toSInt());
364             texture = call->arg(1).toUInt();
365
366             ss_target << "texture-target-" << target;
367             ss_texture << "texture-" << texture;
368
369             resources.erase(ss_target.str());
370             provide(ss_target.str(), call->no);
371
372             unlinkAll(ss_target.str());
373             link(ss_target.str(), ss_texture.str());
374
375             return;
376         }
377
378         /* FIXME: Need to handle glMultTexImage and friends. */
379         if (STRNCMP_LITERAL(name, "glTexImage") == 0 ||
380             STRNCMP_LITERAL(name, "glTexSubImage") == 0 ||
381             STRNCMP_LITERAL(name, "glCopyTexImage") == 0 ||
382             STRNCMP_LITERAL(name, "glCopyTexSubImage") == 0 ||
383             STRNCMP_LITERAL(name, "glCompressedTexImage") == 0 ||
384             STRNCMP_LITERAL(name, "glCompressedTexSubImage") == 0 ||
385             strcmp(name, "glInvalidateTexImage") == 0 ||
386             strcmp(name, "glInvalidateTexSubImage") == 0) {
387
388             std::set<unsigned> *calls;
389             std::set<unsigned>::iterator c;
390             std::stringstream ss_target, ss_texture;
391
392             GLenum target = static_cast<GLenum>(call->arg(0).toSInt());
393
394             ss_target << "texture-target-" << target;
395             ss_texture << "texture-" << texture_map[target];
396
397             /* The texture resource depends on this call and any calls
398              * providing the given texture target. */
399             provide(ss_texture.str(), call->no);
400
401             if (resources.count(ss_target.str())) {
402                 calls = &resources[ss_target.str()];
403                 for (c = calls->begin(); c != calls->end(); c++) {
404                     provide(ss_texture.str(), *c);
405                 }
406             }
407
408             return;
409         }
410
411         if (strcmp(name, "glEnable") == 0) {
412             GLenum cap;
413
414             cap = static_cast<GLenum>(call->arg(0).toSInt());
415
416             if (cap == GL_TEXTURE_1D ||
417                 cap == GL_TEXTURE_2D ||
418                 cap == GL_TEXTURE_3D ||
419                 cap == GL_TEXTURE_CUBE_MAP)
420             {
421                 std::stringstream ss;
422
423                 ss << "texture-target-" << cap;
424
425                 link("render-state", ss.str());
426             }
427
428             provide("state", call->no);
429
430             return;
431         }
432
433         if (strcmp(name, "glDisable") == 0) {
434             GLenum cap;
435
436             cap = static_cast<GLenum>(call->arg(0).toSInt());
437
438             if (cap == GL_TEXTURE_1D ||
439                 cap == GL_TEXTURE_2D ||
440                 cap == GL_TEXTURE_3D ||
441                 cap == GL_TEXTURE_CUBE_MAP)
442             {
443                 std::stringstream ss;
444
445                 ss << "texture-target-" << cap;
446
447                 unlink("render-state", ss.str());
448             }
449
450             provide("state", call->no);
451
452             return;
453         }
454
455         /* Handle all rendering operations, (even though only glEnd is
456          * flagged as a rendering operation we treat everything from
457          * glBegin through glEnd as a rendering operation). */
458         if (call->flags & trace::CALL_FLAG_RENDER ||
459             insideBeginEnd) {
460
461             std::set<unsigned> calls;
462             std::set<unsigned>::iterator c;
463
464             provide("framebuffer", call->no);
465
466             calls = resolve("render-state");
467
468             for (c = calls.begin(); c != calls.end(); c++) {
469                 provide("framebuffer", *c);
470             }
471
472             /* In some cases, rendering has side effects beyond the
473              * framebuffer update. */
474             if (renderingHasSideEffect()) {
475                 provide("state", call->no);
476                 for (c = calls.begin(); c != calls.end(); c++) {
477                     provide("state", *c);
478                 }
479             }
480
481             return;
482         }
483
484         /* By default, assume this call affects the state somehow. */
485         resources["state"].insert(call->no);
486     }
487
488     void requireDependencies(trace::Call *call) {
489
490         /* Swap-buffers calls depend on framebuffer state. */
491         if (call->flags & trace::CALL_FLAG_SWAP_RENDERTARGET &&
492             call->flags & trace::CALL_FLAG_END_FRAME) {
493             consume("framebuffer");
494         }
495
496         /* By default, just assume this call depends on generic state. */
497         consume("state");
498     }
499
500
501 public:
502     TraceAnalyzer(): transformFeedbackActive(false),
503                      framebufferObjectActive(false),
504                      insideBeginEnd(false)
505     {}
506
507     ~TraceAnalyzer() {}
508
509     /* Analyze this call by tracking state and recording all the
510      * resources provided by this call as side effects.. */
511     void analyze(trace::Call *call) {
512
513         stateTrackPreCall(call);
514
515         recordSideEffects(call);
516
517         stateTrackPostCall(call);
518     }
519
520     /* Require this call and all of its dependencies to be included in
521      * the final trace. */
522     void require(trace::Call *call) {
523
524         /* First, find and insert all calls that this call depends on. */
525         requireDependencies(call);
526
527         /* Then insert this call itself. */
528         required.insert(call->no);
529     }
530
531     /* Return a set of all the required calls, (both those calls added
532      * explicitly with require() and those implicitly depended
533      * upon. */
534     std::set<unsigned> *get_required(void) {
535         return &required;
536     }
537 };
538
539 struct trim_options {
540     /* Calls to be included in trace. */
541     trace::CallSet calls;
542
543     /* Whether dependency analysis should be performed. */
544     bool dependency_analysis;
545
546     /* Whether uninteresting calls should be pruned.. */
547     bool prune_uninteresting;
548
549     /* Output filename */
550     std::string output;
551
552     /* Emit only calls from this thread (-1 == all threads) */
553     int thread;
554 };
555
556 static int
557 trim_trace(const char *filename, struct trim_options *options)
558 {
559     trace::ParseBookmark beginning;
560     trace::Parser p;
561     TraceAnalyzer analyzer;
562     std::set<unsigned> *required;
563
564     if (!p.open(filename)) {
565         std::cerr << "error: failed to open " << filename << "\n";
566         return 1;
567     }
568
569     /* Mark the beginning so we can return here for pass 2. */
570     p.getBookmark(beginning);
571
572     /* In pass 1, analyze which calls are needed. */
573     trace::Call *call;
574     while ((call = p.parse_call())) {
575
576         /* There's no use doing any work past the last call requested
577          * by the user. */
578         if (call->no > options->calls.getLast()) {
579             delete call;
580             break;
581         }
582
583         /* If requested, ignore all calls not belonging to the specified thread. */
584         if (options->thread != -1 && call->thread_id != options->thread) {
585             delete call;
586             continue;
587         }
588
589         /* Also, prune if uninteresting (unless the user asked for no pruning. */
590         if (options->prune_uninteresting && call->flags & trace::CALL_FLAG_UNINTERESTING) {
591             delete call;
592             continue;
593         }
594
595         /* If this call is included in the user-specified call set,
596          * then require it (and all dependencies) in the trimmed
597          * output. */
598         if (options->calls.contains(*call)) {
599             analyzer.require(call);
600         }
601
602         /* Regardless of whether we include this call or not, we do
603          * some dependency tracking (unless disabled by the user). We
604          * do this even for calls we have included in the output so
605          * that any state updates get performed. */
606         if (options->dependency_analysis) {
607             analyzer.analyze(call);
608         }
609
610         delete call;
611     }
612
613     /* Prepare output file and writer for output. */
614     if (options->output.empty()) {
615         os::String base(filename);
616         base.trimExtension();
617
618         options->output = std::string(base.str()) + std::string("-trim.trace");
619     }
620
621     trace::Writer writer;
622     if (!writer.open(options->output.c_str())) {
623         std::cerr << "error: failed to create " << filename << "\n";
624         return 1;
625     }
626
627     /* Reset bookmark for pass 2. */
628     p.setBookmark(beginning);
629
630     /* In pass 2, emit the calls that are required. */
631     required = analyzer.get_required();
632
633     while ((call = p.parse_call())) {
634
635         /* There's no use doing any work past the last call requested
636          * by the user. */
637         if (call->no > options->calls.getLast())
638             break;
639
640         if (required->find(call->no) != required->end()) {
641             writer.writeCall(call);
642         }
643         delete call;
644     }
645
646     std::cout << "Trimmed trace is available as " << options->output << "\n";
647
648     return 0;
649 }
650
651 static int
652 command(int argc, char *argv[])
653 {
654     struct trim_options options;
655
656     options.calls = trace::CallSet(trace::FREQUENCY_ALL);
657     options.dependency_analysis = true;
658     options.prune_uninteresting = true;
659     options.output = "";
660     options.thread = -1;
661
662     int opt;
663     while ((opt = getopt_long(argc, argv, shortOptions, longOptions, NULL)) != -1) {
664         switch (opt) {
665         case 'h':
666             help();
667             return 0;
668         case CALLS_OPT:
669             options.calls = trace::CallSet(optarg);
670             break;
671         case DEPS_OPT:
672             options.dependency_analysis = true;
673             break;
674         case NO_DEPS_OPT:
675             options.dependency_analysis = false;
676             break;
677         case PRUNE_OPT:
678             options.prune_uninteresting = true;
679             break;
680         case NO_PRUNE_OPT:
681             options.prune_uninteresting = false;
682             break;
683         case 'x':
684             options.dependency_analysis = false;
685             options.prune_uninteresting = false;
686             break;
687         case THREAD_OPT:
688             options.thread = atoi(optarg);
689             break;
690         case 'o':
691             options.output = optarg;
692             break;
693         default:
694             std::cerr << "error: unexpected option `" << opt << "`\n";
695             usage();
696             return 1;
697         }
698     }
699
700     if (optind >= argc) {
701         std::cerr << "error: apitrace trim requires a trace file as an argument.\n";
702         usage();
703         return 1;
704     }
705
706     if (argc > optind + 1) {
707         std::cerr << "error: extraneous arguments:";
708         for (int i = optind + 1; i < argc; i++) {
709             std::cerr << " " << argv[i];
710         }
711         std::cerr << "\n";
712         usage();
713         return 1;
714     }
715
716     return trim_trace(argv[optind], &options);
717 }
718
719 const Command trim_command = {
720     "trim",
721     synopsis,
722     help,
723     command
724 };