1*0b57cec5SDimitry Andric //===- LEB128.cpp - LEB128 utility functions implementation -----*- C++ -*-===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file implements some utility functions for encoding SLEB128 and
10*0b57cec5SDimitry Andric // ULEB128 values.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13*0b57cec5SDimitry Andric 
14*0b57cec5SDimitry Andric #include "llvm/Support/LEB128.h"
15*0b57cec5SDimitry Andric 
16*0b57cec5SDimitry Andric namespace llvm {
17*0b57cec5SDimitry Andric 
18*0b57cec5SDimitry Andric /// Utility function to get the size of the ULEB128-encoded value.
getULEB128Size(uint64_t Value)19*0b57cec5SDimitry Andric unsigned getULEB128Size(uint64_t Value) {
20*0b57cec5SDimitry Andric   unsigned Size = 0;
21*0b57cec5SDimitry Andric   do {
22*0b57cec5SDimitry Andric     Value >>= 7;
23*0b57cec5SDimitry Andric     Size += sizeof(int8_t);
24*0b57cec5SDimitry Andric   } while (Value);
25*0b57cec5SDimitry Andric   return Size;
26*0b57cec5SDimitry Andric }
27*0b57cec5SDimitry Andric 
28*0b57cec5SDimitry Andric /// Utility function to get the size of the SLEB128-encoded value.
getSLEB128Size(int64_t Value)29*0b57cec5SDimitry Andric unsigned getSLEB128Size(int64_t Value) {
30*0b57cec5SDimitry Andric   unsigned Size = 0;
31*0b57cec5SDimitry Andric   int Sign = Value >> (8 * sizeof(Value) - 1);
32*0b57cec5SDimitry Andric   bool IsMore;
33*0b57cec5SDimitry Andric 
34*0b57cec5SDimitry Andric   do {
35*0b57cec5SDimitry Andric     unsigned Byte = Value & 0x7f;
36*0b57cec5SDimitry Andric     Value >>= 7;
37*0b57cec5SDimitry Andric     IsMore = Value != Sign || ((Byte ^ Sign) & 0x40) != 0;
38*0b57cec5SDimitry Andric     Size += sizeof(int8_t);
39*0b57cec5SDimitry Andric   } while (IsMore);
40*0b57cec5SDimitry Andric   return Size;
41*0b57cec5SDimitry Andric }
42*0b57cec5SDimitry Andric 
43*0b57cec5SDimitry Andric }  // namespace llvm
44