constexpr static size_t genericOffsetForField()

in cpp/perfevents/Records.cpp [134:225]


constexpr static size_t genericOffsetForField(
    uint64_t sample_type,
    uint64_t read_format,
    uint64_t field) {
  size_t offset = 0;

  if ((sample_type & PERF_SAMPLE_IDENTIFIER) != 0) {
    if (field == PERF_SAMPLE_IDENTIFIER) {
      return offset;
    }
    offset += sizeof(uint64_t);
  }

  if ((sample_type & PERF_SAMPLE_IP) != 0) {
    if (field == PERF_SAMPLE_IP) {
      return offset;
    }
    offset += sizeof(uint64_t);
  }

  if ((sample_type & PERF_SAMPLE_TID) != 0) {
    if (field == PERF_SAMPLE_TID) {
      return offset;
    }
    offset += 2 * sizeof(uint32_t); // uint32_t tid, pid
  }

  if ((sample_type & PERF_SAMPLE_TIME) != 0) {
    if (field == PERF_SAMPLE_TIME) {
      return offset;
    }
    offset += sizeof(uint64_t);
  }

  if ((sample_type & PERF_SAMPLE_ADDR) != 0) {
    if (field == PERF_SAMPLE_ADDR) {
      return offset;
    }
    offset += sizeof(uint64_t);
  }

  if ((sample_type & PERF_SAMPLE_ID) != 0) {
    if (field == PERF_SAMPLE_ID) {
      return offset;
    }
    offset += sizeof(uint64_t);
  }

  if ((sample_type & PERF_SAMPLE_STREAM_ID) != 0) {
    if (field == PERF_SAMPLE_STREAM_ID) {
      return offset;
    }
    offset += sizeof(uint64_t);
  }

  if ((sample_type & PERF_SAMPLE_CPU) != 0) {
    if (field == PERF_SAMPLE_CPU) {
      return offset;
    }
    offset += 2 * sizeof(uint32_t); // uint32_t cpu, __res;
  }

  if ((sample_type & PERF_SAMPLE_PERIOD) != 0) {
    if (field == PERF_SAMPLE_PERIOD) {
      return offset;
    }
    offset += sizeof(uint64_t);
  }

  bool field_in_read_format = field == PERF_FORMAT_ID ||
      field == PERF_FORMAT_TOTAL_TIME_RUNNING ||
      field == PERF_FORMAT_TOTAL_TIME_ENABLED;

  if ((sample_type & PERF_SAMPLE_READ) != 0) {
    if (field_in_read_format) {
      return offset + genericOffsetForReadFormat(read_format, field);
    }

    // Skip the entire read_format struct.
    // Every field in read_format is a u64, +1 because `value` is always
    // present.
    size_t bytes_in_read_format =
        (__builtin_popcountll(read_format) + 1) * sizeof(uint64_t);
    offset += bytes_in_read_format;
  } else if (field_in_read_format) {
    // If we hit this branch, we will de-constexpr-ify the function anyway.
    throw std::logic_error(
        "Attempting to access field in read_format without PERF_SAMPLE_READ in sample_type");
  }

  return offset;
}