Fix some implicit truncation and sign coersion in the networking APIs
[folly.git] / folly / detail / RangeSse42.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "RangeSse42.h"
18
19 #include <glog/logging.h>
20 #include <folly/Portability.h>
21
22 //  Essentially, two versions of this file: one with an SSE42 implementation
23 //  and one with a fallback implementation. We determine which version to use by
24 //  testing for the presence of the required headers.
25 //
26 //  TODO: Maybe this should be done by the build system....
27 #if !FOLLY_SSE_PREREQ(4, 2)
28 namespace folly {
29 namespace detail {
30 size_t qfind_first_byte_of_sse42(const StringPieceLite haystack,
31                                  const StringPieceLite needles) {
32   return qfind_first_byte_of_nosse(haystack, needles);
33 }
34 }
35 }
36 # else
37 #include <cstdint>
38 #include <limits>
39 #include <string>
40
41 #include <emmintrin.h>
42 #include <nmmintrin.h>
43 #include <smmintrin.h>
44
45 #include <folly/Likely.h>
46
47 //  GCC 4.9 with ASAN has a problem: a function with no_sanitize_address calling
48 //  a function with always_inline fails to build. The _mm_* functions are marked
49 //  always_inline.
50 //  https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67368
51 #if defined FOLLY_SANITIZE_ADDRESS && \
52     FOLLY_SANITIZE_ADDRESS == 1 && \
53     __GNUC_PREREQ(4, 9)
54 # define _mm_load_si128(p) (*(p))
55 # define _mm_loadu_si128(p) ((__m128i)__builtin_ia32_loaddqu((const char*)(p)))
56 # ifdef _mm_cmpestri
57 #  undef _mm_cmpestri
58 # endif
59 # define _mm_cmpestri(a, b, c, d, e) \
60   __builtin_ia32_pcmpestri128((__v16qi)(a), b, (__v16qi)(c), d, e)
61 #endif
62
63 namespace folly {
64 namespace detail {
65
66 // It's okay if pages are bigger than this (as powers of two), but they should
67 // not be smaller.
68 static constexpr size_t kMinPageSize = 4096;
69 static_assert(kMinPageSize >= 16,
70               "kMinPageSize must be at least SSE register size");
71
72 template <typename T>
73 static inline uintptr_t page_for(T* addr) {
74   return reinterpret_cast<uintptr_t>(addr) / kMinPageSize;
75 }
76
77 static inline size_t nextAlignedIndex(const char* arr) {
78    auto firstPossible = reinterpret_cast<uintptr_t>(arr) + 1;
79    return 1 +                       // add 1 because the index starts at 'arr'
80      ((firstPossible + 15) & ~0xF)  // round up to next multiple of 16
81      - firstPossible;
82 }
83
84 static size_t qfind_first_byte_of_needles16(const StringPieceLite haystack,
85                                             const StringPieceLite needles)
86   FOLLY_DISABLE_ADDRESS_SANITIZER;
87
88 // helper method for case where needles.size() <= 16
89 size_t qfind_first_byte_of_needles16(const StringPieceLite haystack,
90                                      const StringPieceLite needles) {
91   DCHECK_GT(haystack.size(), 0u);
92   DCHECK_GT(needles.size(), 0u);
93   DCHECK_LE(needles.size(), 16u);
94   if ((needles.size() <= 2 && haystack.size() >= 256) ||
95       // must bail if we can't even SSE-load a single segment of haystack
96       (haystack.size() < 16 &&
97        page_for(haystack.end() - 1) != page_for(haystack.data() + 15)) ||
98       // can't load needles into SSE register if it could cross page boundary
99       page_for(needles.end() - 1) != page_for(needles.data() + 15)) {
100     return detail::qfind_first_byte_of_nosse(haystack, needles);
101   }
102
103   auto arr2 = _mm_loadu_si128(
104       reinterpret_cast<const __m128i*>(needles.data()));
105   // do an unaligned load for first block of haystack
106   auto arr1 = _mm_loadu_si128(
107       reinterpret_cast<const __m128i*>(haystack.data()));
108   auto index = _mm_cmpestri(arr2, needles.size(),
109                             arr1, haystack.size(), 0);
110   if (index < 16) {
111     return index;
112   }
113
114   // Now, we can do aligned loads hereafter...
115   size_t i = nextAlignedIndex(haystack.data());
116   for (; i < haystack.size(); i+= 16) {
117     arr1 =
118         _mm_load_si128(reinterpret_cast<const __m128i*>(haystack.data() + i));
119     index = _mm_cmpestri(arr2, needles.size(), arr1, haystack.size() - i, 0);
120     if (index < 16) {
121       return i + index;
122     }
123   }
124   return std::string::npos;
125 }
126
127 template <bool HAYSTACK_ALIGNED>
128 size_t scanHaystackBlock(const StringPieceLite haystack,
129                          const StringPieceLite needles,
130                          uint64_t idx)
131 // Turn off ASAN because the "arr2 = ..." assignment in the loop below reads
132 // up to 15 bytes beyond end of the buffer in #needles#.  That is ok because
133 // ptr2 is always 16-byte aligned, so the read can never span a page boundary.
134 // Also, the extra data that may be read is never actually used.
135   FOLLY_DISABLE_ADDRESS_SANITIZER;
136
137 // Scans a 16-byte block of haystack (starting at blockStartIdx) to find first
138 // needle. If HAYSTACK_ALIGNED, then haystack must be 16byte aligned.
139 // If !HAYSTACK_ALIGNED, then caller must ensure that it is safe to load the
140 // block.
141 template <bool HAYSTACK_ALIGNED>
142 size_t scanHaystackBlock(const StringPieceLite haystack,
143                          const StringPieceLite needles,
144                          uint64_t blockStartIdx) {
145   DCHECK_GT(needles.size(), 16u); // should handled by *needles16() method
146   DCHECK(blockStartIdx + 16 <= haystack.size() ||
147          (page_for(haystack.data() + blockStartIdx) ==
148           page_for(haystack.data() + blockStartIdx + 15)));
149
150   __m128i arr1;
151   if (HAYSTACK_ALIGNED) {
152     arr1 = _mm_load_si128(
153         reinterpret_cast<const __m128i*>(haystack.data() + blockStartIdx));
154   } else {
155     arr1 = _mm_loadu_si128(
156         reinterpret_cast<const __m128i*>(haystack.data() + blockStartIdx));
157   }
158
159   // This load is safe because needles.size() >= 16
160   auto arr2 = _mm_loadu_si128(
161       reinterpret_cast<const __m128i*>(needles.data()));
162   size_t b = _mm_cmpestri(
163       arr2, 16, arr1, haystack.size() - blockStartIdx, 0);
164
165   size_t j = nextAlignedIndex(needles.data());
166   for (; j < needles.size(); j += 16) {
167     arr2 = _mm_load_si128(
168         reinterpret_cast<const __m128i*>(needles.data() + j));
169
170     auto index = _mm_cmpestri(
171       arr2, needles.size() - j,
172       arr1, haystack.size() - blockStartIdx, 0);
173     b = std::min<size_t>(index, b);
174   }
175
176   if (b < 16) {
177     return blockStartIdx + b;
178   }
179   return std::string::npos;
180 }
181
182 size_t qfind_first_byte_of_sse42(const StringPieceLite haystack,
183                                  const StringPieceLite needles);
184
185 size_t qfind_first_byte_of_sse42(const StringPieceLite haystack,
186                                  const StringPieceLite needles) {
187   if (UNLIKELY(needles.empty() || haystack.empty())) {
188     return std::string::npos;
189   } else if (needles.size() <= 16) {
190     // we can save some unnecessary load instructions by optimizing for
191     // the common case of needles.size() <= 16
192     return qfind_first_byte_of_needles16(haystack, needles);
193   }
194
195   if (haystack.size() < 16 &&
196       page_for(haystack.end() - 1) != page_for(haystack.data() + 16)) {
197     // We can't safely SSE-load haystack. Use a different approach.
198     if (haystack.size() <= 2) {
199       return qfind_first_byte_of_std(haystack, needles);
200     }
201     return qfind_first_byte_of_byteset(haystack, needles);
202   }
203
204   auto ret = scanHaystackBlock<false>(haystack, needles, 0);
205   if (ret != std::string::npos) {
206     return ret;
207   }
208
209   size_t i = nextAlignedIndex(haystack.data());
210   for (; i < haystack.size(); i += 16) {
211     ret = scanHaystackBlock<true>(haystack, needles, i);
212     if (ret != std::string::npos) {
213       return ret;
214     }
215   }
216
217   return std::string::npos;
218 }
219 }
220 }
221 #endif