PVS-Studio noticed that EmitVBR64 would perform undefined behaviour if the
[oota-llvm.git] / include / llvm / Bitcode / BitstreamWriter.h
index 56b20c8474a47824c50e48291d3f8116f715896e..65933a28e43d3bb5b2c640e9fbfb8674b0472fec 100644 (file)
 #define BITSTREAM_WRITER_H
 
 #include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/SmallVector.h"
 #include "llvm/Bitcode/BitCodes.h"
 #include <vector>
 
 namespace llvm {
 
 class BitstreamWriter {
-  std::vector<unsigned char> &Out;
+  SmallVectorImpl<char> &Out;
 
   /// CurBit - Always between 0 and 31 inclusive, specifies the next bit to use.
   unsigned CurBit;
@@ -73,10 +74,12 @@ class BitstreamWriter {
   }
 
   void WriteWord(unsigned Value) {
-    Out.push_back((unsigned char)(Value >>  0));
-    Out.push_back((unsigned char)(Value >>  8));
-    Out.push_back((unsigned char)(Value >> 16));
-    Out.push_back((unsigned char)(Value >> 24));
+    unsigned char Bytes[4] = {
+      (unsigned char)(Value >>  0),
+      (unsigned char)(Value >>  8),
+      (unsigned char)(Value >> 16),
+      (unsigned char)(Value >> 24) };
+    Out.append(&Bytes[0], &Bytes[4]);
   }
 
   unsigned GetBufferOffset() const {
@@ -90,7 +93,7 @@ class BitstreamWriter {
   }
 
 public:
-  explicit BitstreamWriter(std::vector<unsigned char> &O)
+  explicit BitstreamWriter(SmallVectorImpl<char> &O)
     : Out(O), CurBit(0), CurValue(0), CurCodeSize(2) {}
 
   ~BitstreamWriter() {
@@ -152,6 +155,7 @@ public:
   }
 
   void EmitVBR(uint32_t Val, unsigned NumBits) {
+    assert(NumBits <= 32 && "Too many bits to emit!");
     uint32_t Threshold = 1U << (NumBits-1);
 
     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
@@ -164,10 +168,11 @@ public:
   }
 
   void EmitVBR64(uint64_t Val, unsigned NumBits) {
+    assert(NumBits <= 32 && "Too many bits to emit!");
     if ((uint32_t)Val == Val)
       return EmitVBR((uint32_t)Val, NumBits);
 
-    uint64_t Threshold = 1U << (NumBits-1);
+    uint64_t Threshold = uint64_t(1U << (NumBits-1));
 
     // Emit the bits with VBR encoding, NumBits-1 bits at a time.
     while (Val >= Threshold) {
@@ -498,7 +503,7 @@ public:
   /// EnterBlockInfoBlock - Start emitting the BLOCKINFO_BLOCK.
   void EnterBlockInfoBlock(unsigned CodeWidth) {
     EnterSubblock(bitc::BLOCKINFO_BLOCK_ID, CodeWidth);
-    BlockInfoCurBID = -1U;
+    BlockInfoCurBID = ~0U;
   }
 private:
   /// SwitchToBlockID - If we aren't already talking about the specified block