llvm_profparser 0.1.1-alpha1

Parsing and interpretation of llvm coverage profiles and generated data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use llvm_profparser::instrumentation_profile::stats::*;
use llvm_profparser::instrumentation_profile::summary::*;
use llvm_profparser::instrumentation_profile::types::*;
use llvm_profparser::*;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::path::PathBuf;
use structopt::StructOpt;

#[derive(Clone, Debug, Eq, PartialEq, StructOpt)]
pub enum Command {
    Show {
        #[structopt(flatten)]
        show: ShowCommand,
    },
    Merge {
        #[structopt(flatten)]
        merge: MergeCommand,
    },
    Overlap {
        #[structopt(flatten)]
        overlap: OverlapCommand,
    },
}

#[derive(Clone, Debug, Eq, PartialEq, StructOpt)]
pub struct ShowCommand {
    /// Input profraw file to show some information about
    #[structopt(name = "<filename...>", long = "input", short = "i")]
    input: PathBuf,
    /// Show counter values for shown functions
    #[structopt(long = "counts")]
    show_counts: bool,
    /// Details for every function
    #[structopt(long = "all-functions")]
    all_functions: bool,
    /// Show instr profile data in text dump format
    #[structopt(long = "text")]
    text: bool,
    /// Show indirect call site target values for shown functions
    #[structopt(long = "ic-targets")]
    ic_targets: bool,
    /// Show the profiled sizes of the memory intrinsic call for shown functions"
    #[structopt(long = "memop-sizes")]
    memop_sizes: bool,
    /// Show detailed profile summary
    #[structopt(long = "show_detailed_summary")]
    show_detailed_summary: bool,
    /// Cutoff percentages (times 10000) for generating detailed summary
    #[structopt(long = "detailed_summary_cutoffs")]
    detailed_summary_cutoffs: Vec<usize>,
    /// Show profile summary of a list of hot functions
    #[structopt(long = "show_hot_fn_list")]
    show_hot_fn_list: bool,
    /// Show context sensitive counts
    #[structopt(long = "showcs")]
    showcs: bool,
    /// Details for matching functions
    #[structopt(long = "function")]
    function: Option<String>,
    /// Output file
    #[structopt(long = "output", short = "o")]
    output: Option<String>,
    /// Show the list of functions with the largest internal counts
    #[structopt(long = "topn")]
    topn: Option<usize>,
    /// Set the count value cutoff. Functions with the maximum count less than
    /// this value will not be printed out. (Default is 0)
    #[structopt(long = "value_cutoff", default_value = "0")]
    value_cutoff: u64,
    /// Set the count value cutoff. Functions with the maximum count below the
    /// cutoff value
    #[structopt(long = "only_list_below")]
    only_list_below: bool,
    /// Show profile symbol list if it exists in the profile.
    #[structopt(long = "show_profile_sym_list")]
    show_profile_sym_list: bool,
    /// Show the information of each section in the sample profile. The flag is
    /// only usable when the sample profile is in extbinary format
    #[structopt(long = "show_section_info_only")]
    show_section_info_only: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, StructOpt)]
pub struct MergeCommand {
    /// Input files to merge
    #[structopt(name = "<filename...>", long = "input", short = "i")]
    input: Vec<PathBuf>,
    /// Output file
    #[structopt(long = "output", short = "o")]
    output: PathBuf,
    /// List of weights and filenames in `<weight>,<filename>` format
    #[structopt(long = "weighted-input", parse(try_from_str=try_parse_weighted))]
    weighted_input: Vec<(u64, String)>,
    /// Number of merge threads to use (will autodetect by default)
    #[structopt(long = "num-threads", short = "j")]
    jobs: Option<usize>,
}

#[derive(Clone, Debug, Eq, PartialEq, StructOpt)]
pub struct OverlapCommand {
    #[structopt(name = "<base profile file>")]
    base_file: PathBuf,
    #[structopt(name = "<test profile file>")]
    test_file: PathBuf,
    #[structopt(long = "output", short = "o")]
    output: Option<PathBuf>,
    /// For context sensitive counts
    #[structopt(long = "cs")]
    context_sensitive_counts: bool,
    /// Function level overlap information for every function in test profile with max count value
    /// greater than the parameter value
    #[structopt(long = "value-cutoff")]
    value_cutoff: Option<usize>,
    /// Function level overlap information for matching functions
    #[structopt(long = "function")]
    function: Option<String>,
    /// Generate a sparse profile
    #[structopt(long = "sparse")]
    sparse: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, StructOpt)]
pub struct Opts {
    #[structopt(subcommand)]
    cmd: Command,
}

fn try_parse_weighted(input: &str) -> Result<(u64, String), String> {
    if !input.contains(',') {
        Ok((1, input.to_string()))
    } else {
        let parts = input.split(',').collect::<Vec<_>>();
        if parts.len() != 2 {
            Err(format!(
                "Unexpected weighting format, expected $weight,$name or just $name"
            ))
        } else {
            let weight = parts[0]
                .parse()
                .map_err(|e| format!("Invalid weight: {}", e))?;
            if weight < 1 {
                Err(format!("Weight must be positive integer"))
            } else {
                Ok((weight, parts[1].to_string()))
            }
        }
    }
}

fn check_function(name: Option<&String>, pattern: Option<&String>) -> bool {
    match pattern {
        Some(pat) => name.map(|x| x.contains(pat)).unwrap_or(false),
        None => false,
    }
}

#[derive(Clone, Debug, Eq)]
struct HotFn {
    name: String,
    count: u64,
}

impl PartialOrd for HotFn {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for HotFn {
    fn cmp(&self, other: &Self) -> Ordering {
        // Do the reverse here
        other.count.cmp(&self.count)
    }
}

impl PartialEq for HotFn {
    fn eq(&self, other: &Self) -> bool {
        self.count == other.count
    }
}

impl ShowCommand {
    pub fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        let profile = parse(&self.input)?;
        let mut summary = ProfileSummary::new();
        let mut stats = vec![ValueSiteStats::default(); ValueKind::len()];

        let is_ir_instr = profile.is_ir_level_profile();
        let mut hotties =
            BinaryHeap::<HotFn>::with_capacity(self.topn.unwrap_or_default() as usize);
        let mut shown_funcs = 0;
        let mut below_cutoff_funcs = 0;
        let topn = self.topn.unwrap_or_default();
        for func in &profile.records {
            if func.name.is_none() || func.hash.is_none() {
                continue;
            }
            if is_ir_instr && func.has_cs_flag() != self.showcs {
                continue;
            }
            let show =
                self.all_functions || check_function(func.name.as_ref(), self.function.as_ref());

            if show && self.text {
                // TODO text format dump
                continue;
            }
            summary.add_record(&func.record);

            let (func_max, func_sum) = func.counts().iter().fold((0, 0u64), |acc, x| {
                (*x.max(&acc.0), acc.1.saturating_add(*x))
            });
            if func_max < self.value_cutoff {
                below_cutoff_funcs += 1;
                if self.only_list_below {
                    println!(
                        "  {}: (Max = {} Sum = {})",
                        func.name.as_ref().unwrap(),
                        func_max,
                        func_sum
                    );
                    continue;
                }
            } else if self.only_list_below {
                continue;
            }
            if topn > 0 {
                if hotties.len() == topn {
                    let top = hotties.peek().unwrap();
                    if top.count < func_max {
                        hotties.pop();
                        hotties.push(HotFn {
                            name: func.name.as_ref().unwrap().to_string(),
                            count: func_max,
                        });
                    }
                } else {
                    hotties.push(HotFn {
                        name: func.name.as_ref().unwrap().to_string(),
                        count: func_max,
                    });
                }
            }
            if show {
                if shown_funcs == 0 {
                    println!("Counters:");
                }
                shown_funcs += 1;
                println!("  {}:", func.name.as_ref().unwrap());
                println!("    Hash: {:#018x}", func.hash.unwrap());
                println!("    Counters: {}", func.counts().len());
                if !is_ir_instr {
                    let counts = if func.counts().is_empty() {
                        0
                    } else {
                        func.counts()[0]
                    };
                    println!("    Function count: {}", counts);
                }
                if self.ic_targets {
                    println!(
                        "    Indirect Call Site Count: {}",
                        func.num_value_sites(ValueKind::IndirectCallTarget)
                    );
                    stats[ValueKind::IndirectCallTarget as usize].traverse_sites(
                        &func.record,
                        ValueKind::IndirectCallTarget,
                        Some(&profile.symtab),
                    );
                }
                let num_memop_calls = func.num_value_sites(ValueKind::MemOpSize);
                if self.memop_sizes && num_memop_calls > 0 {
                    println!("    Number of Memory Intrinsics Calls: {}", num_memop_calls);
                    stats[ValueKind::MemOpSize as usize].traverse_sites(
                        &func.record,
                        ValueKind::MemOpSize,
                        None,
                    );
                }
                if self.show_counts {
                    let start = if is_ir_instr { 0 } else { 1 };
                    let counts = func
                        .counts()
                        .iter()
                        .skip(start)
                        .map(|x| x.to_string())
                        .collect::<Vec<String>>()
                        .join(", ");
                    println!("    Block counts: [{}]", counts);
                }
                if self.ic_targets {
                    println!("    Indirect Target Results:");
                }
                if self.memop_sizes && num_memop_calls > 0 {
                    println!("    Memory Intrinsic Size Results:");
                }
            }
        }
        if profile.get_level() == InstrumentationLevel::Ir {
            // This is just to enable same printout in older versions with llvm 11
            #[cfg(not(llvm_11))]
            println!(
                "Instrumentation level: {}  entry_first = {}",
                profile.get_level(),
                profile.is_entry_first() as usize
            );
            #[cfg(llvm_11)]
            println!("Instrumentation level: {}", profile.get_level());
        } else {
            println!("Instrumentation level: {}", profile.get_level());
        }
        if self.all_functions || self.function.is_some() {
            println!("Functions shown: {}", shown_funcs);
        }
        println!("Total functions: {}", summary.num_functions());
        if self.value_cutoff > 0 {
            println!(
                "Number of functions with maximum count (< {} ): {}",
                self.value_cutoff, below_cutoff_funcs
            );
            println!(
                "Number of functions with maximum count (>= {}): {}",
                self.value_cutoff,
                summary.num_functions() - below_cutoff_funcs
            );
        }
        println!("Maximum function count: {}", summary.max_function_count());
        println!(
            "Maximum internal block count: {}",
            summary.max_internal_block_count()
        );
        if let Some(topn) = self.topn {
            println!(
                "Top {} functions with the largest internal block counts: ",
                topn
            );
            let hotties = hotties.into_sorted_vec();
            for f in hotties.iter() {
                println!("  {}, max count = {}", f.name, f.count);
            }
        }

        if self.ic_targets && shown_funcs > 0 {
            println!("Statistics for indirect call sites profile:");
            println!("{}", stats[ValueKind::IndirectCallTarget as usize]);
        }

        if self.memop_sizes && shown_funcs > 0 {
            println!("Statistics for memory instrinsic calls sizes profile:");
            println!("{}", stats[ValueKind::MemOpSize as usize]);
        }

        if self.show_detailed_summary {
            println!("Total number of blocks: ?");
            println!("Total count: ?");
        }
        Ok(())
    }
}

impl MergeCommand {
    fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        assert!(
            !self.input.is_empty(),
            "No input files selected. See merge --help"
        );
        let profile = merge_profiles(&self.input)?;
        // Now to write it out?
        Ok(())
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let opts = Opts::from_args();
    match opts.cmd {
        Command::Show { show } => show.run(),
        Command::Merge { merge } => merge.run(),
        _ => {
            panic!("Unsupported command");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn weight_arg_parsing() {
        // Examples taken from LLVM docs
        let foo_10 = "10,foo.profdata";
        let bar_1 = "1,bar.profdata";

        assert_eq!(
            Ok((10, "foo.profdata".to_string())),
            try_parse_weighted(foo_10)
        );
        assert_eq!(
            Ok((1, "bar.profdata".to_string())),
            try_parse_weighted(bar_1)
        );
        assert_eq!(
            Ok((1, "foo.profdata".to_string())),
            try_parse_weighted("foo.profdata")
        );
        assert!(try_parse_weighted("foo.profdata,1").is_err());
        assert!(try_parse_weighted("1,1,foo.profdata").is_err());
    }
}