Debian Codegraph @

plink2_cmdline.h

raw
1 #ifndef __PLINK2_CMDLINE_H__
2 #define __PLINK2_CMDLINE_H__
3
4 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
5 // Christopher Chang.
6 //
7 // This program is free software: you can redistribute it and/or modify it
8 // under the terms of the GNU Lesser General Public License as published by the
9 // Free Software Foundation, either version 3 of the License, or (at your
10 // option) any later version.
11 //
12 // This library is distributed in the hope that it will be useful, but WITHOUT
13 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15 // for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
21 // Cross-platform logging, command-line parsing, workspace
22 // initialization/allocation, basic multithreading code, and a few numeric
23 // constants.
24
25 #include "include/plink2_bits.h"
26 #include "include/plink2_htable.h"
27 #include "include/plink2_memory.h"
28 #include "include/plink2_string.h"
29 #include "include/plink2_thread.h"
30
31 #include <errno.h>
32 #include <stdarg.h>
33
34 #ifndef _WIN32
35 # include <sys/stat.h>
36 #endif
37
38 #ifdef _WIN32
39 # define NULL_STREAM_NAME "nul"
40 #else
41 # define NULL_STREAM_NAME "/dev/null"
42 #endif
43
44 #ifdef __cplusplus
45 namespace plink2 {
46 #endif
47
48 CONSTI32(kLogbufSize, 2 * kMaxMediumLine);
49
50 // must be at least 2 * kMaxMediumLine + 2 to support generic token loader.
51 CONSTI32(kTextbufSize, 2 * kMaxMediumLine + 256);
52
53 // when g_textbuf is used as a generic I/O buffer, this is a convenient
54 // power-of-2 size (must be <= kTextbufSize).
55 CONSTI32(kTextbufMainSize, 2 * kMaxMediumLine);
56
57 // "slen" is now used to indicate string lengths excluding terminating nulls,
58 // while "blen" includes the terminator.
59
60 // Maximum length of chromosome, variant, FID, IID, cluster, and set IDs (not
61 // including terminating null). This value supports up to 8 IDs per line
62 // (maximum so far is 5, for e.g. --hom).
63 // Assumed by plink2_pvar to be a multiple of 16.
64 CONSTI32(kMaxIdSlen, 16000);
65 CONSTI32(kMaxIdBlen, kMaxIdSlen + 1);
66 // Don't see a better option than #define for this.
67 #define MAX_ID_SLEN_STR "16000"
68
69 // allow extensions like .model.trend.fisher.set.score.adjusted
70 CONSTI32(kMaxOutfnameExtBlen, 39);
71
72 // All global variables not initialized at compile time start with g_ (even if
73 // they're initialized very early and never changed afterwards, like
74 // g_one_char_strs).
75 extern char g_textbuf[];
76
77 extern const char* g_one_char_strs;
78
79 extern FILE* g_logfile;
80
81 // Mostly-safe log buffer (length kLogbufSize, currently 256k). Good practice
82 // to use snprintf when writing an entire line to it in a single statement.
83 // Warning: Do NOT put allele codes or arbitrary-length lists in here.
84 extern char g_logbuf[];
85
86 extern uint32_t g_debug_on;
87 extern uint32_t g_log_failed;
88
89 // for --warning-errcode
90 extern uint32_t g_stderr_written_to;
91
92
93 // Warning: Do NOT include allele codes (unless they're guaranteed to be SNPs)
94 // in log strings; they can overflow the buffer.
95 void logputs_silent(const char* str);
96
97 void logputs(const char* str);
98
99 void logerrputs(const char* str);
100
101 void logputsb();
102
103 void logerrputsb();
104
105 HEADER_INLINE void logprintf(const char* fmt, ...) {
106 va_list args;
107 va_start(args, fmt);
108 vsnprintf(g_logbuf, kLogbufSize, fmt, args);
109 logputsb();
110 }
111
112 HEADER_INLINE void logerrprintf(const char* fmt, ...) {
113 va_list args;
114 va_start(args, fmt);
115 vsnprintf(g_logbuf, kLogbufSize, fmt, args);
116 logerrputsb();
117 }
118
119 // input for WordWrapB/logprintfww should have no intermediate '\n's. If
120 // suffix_len is 0, there should be a terminating \n.
121 HEADER_INLINE void WordWrapB(uint32_t suffix_len) {
122 WordWrap(suffix_len, g_logbuf);
123 }
124
125 HEADER_INLINE void logpreprintfww(const char* fmt, ...) {
126 va_list args;
127 va_start(args, fmt);
128 vsnprintf(g_logbuf, kLogbufSize, fmt, args);
129 WordWrapB(0);
130 }
131
132 HEADER_INLINE void logprintfww(const char* fmt, ...) {
133 va_list args;
134 va_start(args, fmt);
135 vsnprintf(g_logbuf, kLogbufSize, fmt, args);
136 WordWrapB(0);
137 logputsb();
138 }
139
140 HEADER_INLINE void logerrprintfww(const char* fmt, ...) {
141 va_list args;
142 va_start(args, fmt);
143 vsnprintf(g_logbuf, kLogbufSize, fmt, args);
144 WordWrapB(0);
145 logerrputsb();
146 }
147
148 // 5 = length of "done." suffix, which is commonly used
149 HEADER_INLINE void logprintfww5(const char* fmt, ...) {
150 va_list args;
151 va_start(args, fmt);
152 vsnprintf(g_logbuf, kLogbufSize, fmt, args);
153 WordWrapB(5);
154 logputsb();
155 }
156
157 HEADER_INLINE void DebugPrintf(const char* fmt, ...) {
158 if (g_debug_on) {
159 va_list args;
160 va_start(args, fmt);
161 vsnprintf(g_logbuf, kLogbufSize, fmt, args);
162 logputsb();
163 }
164 }
165
166 HEADER_INLINE void DPrintf(const char* fmt, ...) {
167 if (g_debug_on) {
168 va_list args;
169 va_start(args, fmt);
170 vsnprintf(g_logbuf, kLogbufSize, fmt, args);
171 logputsb();
172 }
173 }
174
175 // Returns kPglRetOpenFail if file doesn't exist, or kPglRetRewindFail if file
176 // is process-substitution/named-pipe. Does not print an error message.
177 PglErr ForceNonFifo(const char* fname);
178
179 BoolErr fopen_checked(const char* fname, const char* mode, FILE** target_ptr);
180
181 HEADER_INLINE IntErr fputs_checked(const char* str, FILE* outfile) {
182 fputs(str, outfile);
183 return ferror_unlocked(outfile);
184 }
185
186 BoolErr fwrite_flush2(char* buf_flush, FILE* outfile, char** write_iter_ptr);
187
188 HEADER_INLINE BoolErr fwrite_uflush2(unsigned char* buf_flush, FILE* outfile, unsigned char** write_iter_ptr) {
189 return fwrite_flush2(R_CAST(char*, buf_flush), outfile, R_CAST(char**, write_iter_ptr));
190 }
191
192 HEADER_INLINE BoolErr fwrite_ck(char* buf_flush, FILE* outfile, char** write_iter_ptr) {
193 if ((*write_iter_ptr) < buf_flush) {
194 return 0;
195 }
196 return fwrite_flush2(buf_flush, outfile, write_iter_ptr);
197 }
198
199 // fclose_null defined in plink2_base.h
200
201 BoolErr fclose_flush_null(char* buf_flush, char* write_iter, FILE** outfile_ptr);
202
203 HEADER_INLINE BoolErr fclose_uflush_null(unsigned char* buf_flush, unsigned char* write_iter, FILE** outfile_ptr) {
204 return fclose_flush_null(R_CAST(char*, buf_flush), R_CAST(char*, write_iter), outfile_ptr);
205 }
206
207 // This should only be used when the file can only be open on error-early-exit;
208 // otherwise we care about fclose's error code.
209 HEADER_INLINE void fclose_cond(FILE* fptr) {
210 if (fptr) {
211 fclose(fptr);
212 }
213 }
214
215 HEADER_INLINE uint32_t ClipU32(uint32_t val, uint32_t lbound, uint32_t ubound) {
216 if (val >= ubound) {
217 return ubound;
218 }
219 return MAXV(val, lbound);
220 }
221
222 int32_t u32cmp(const void* aa, const void* bb);
223
224 int32_t double_cmp(const void* aa, const void* bb);
225
226 int32_t double_cmp_decr(const void* aa, const void* bb);
227
228 int32_t u64cmp(const void* aa, const void* bb);
229
230 #ifndef __cplusplus
231 int32_t u64cmp_decr(const void* aa, const void* bb);
232 #endif
233
234 HEADER_INLINE uint32_t U32ArrMax(const uint32_t* unsorted_arr, uintptr_t len) {
235 const uint32_t* unsorted_arr_end = &(unsorted_arr[len]);
236 #ifndef __cplusplus
237 const uint32_t* unsorted_arr_iter = unsorted_arr;
238 uint32_t uimax = *unsorted_arr_iter++;
239 while (unsorted_arr_iter < unsorted_arr_end) {
240 const uint32_t cur_val = *unsorted_arr_iter++;
241 if (cur_val > uimax) {
242 uimax = cur_val;
243 }
244 }
245 return uimax;
246 #else
247 return *std::max_element(unsorted_arr, unsorted_arr_end);
248 #endif
249 }
250
251 HEADER_INLINE float FArrMax(const float* unsorted_arr, uintptr_t len) {
252 const float* unsorted_arr_end = &(unsorted_arr[len]);
253 #if defined(__APPLE__) || !defined(__cplusplus)
254 // std::max_element doesn't seem to be performant for floats/doubles on OS X
255 const float* unsorted_arr_iter = unsorted_arr;
256 float fmax = *unsorted_arr_iter++;
257 while (unsorted_arr_iter < unsorted_arr_end) {
258 const float cur_val = *unsorted_arr_iter++;
259 if (cur_val > fmax) {
260 fmax = cur_val;
261 }
262 }
263 return fmax;
264 #else
265 return *std::max_element(unsorted_arr, unsorted_arr_end);
266 #endif
267 }
268
269 HEADER_INLINE double DArrMax(const double* unsorted_arr, uintptr_t len) {
270 const double* unsorted_arr_end = &(unsorted_arr[len]);
271 #if defined(__APPLE__) || !defined(__cplusplus)
272 const double* unsorted_arr_iter = unsorted_arr;
273 double dmax = *unsorted_arr_iter++;
274 while (unsorted_arr_iter < unsorted_arr_end) {
275 const double cur_val = *unsorted_arr_iter++;
276 if (cur_val > dmax) {
277 dmax = cur_val;
278 }
279 }
280 return dmax;
281 #else
282 return *std::max_element(unsorted_arr, unsorted_arr_end);
283 #endif
284 }
285
286 float DestructiveMedianF(uintptr_t len, float* unsorted_arr);
287
288 double DestructiveMedianD(uintptr_t len, double* unsorted_arr);
289
290
291 // This makes a temporary g_bigstack allocation.
292 // Must be safe to read up to (kBytesPerWord - 1) bytes past end of strbox.
293 // Results may technically vary between runs when duplicate elements are
294 // present; it's assumed that this doesn't matter because all duplicates will
295 // be handled in the same manner.
296 // id_map is new_to_old_idx.
297 BoolErr SortStrboxIndexed(uintptr_t str_ct, uintptr_t max_str_blen, uint32_t use_nsort, char* strbox, uint32_t* id_map);
298
299 // Offset of std::lower_bound, i.e. # of elements < needle.
300 // Requires arr_length > 0.
301 uintptr_t LowerBoundNonemptyU32(const uint32_t* sorted_u32_arr, uintptr_t arr_length, uint32_t needle);
302
303 HEADER_INLINE uintptr_t LowerBoundU32(const uint32_t* sorted_u32_arr, uintptr_t arr_length, uint32_t needle) {
304 if (!arr_length) {
305 return 0;
306 }
307 return LowerBoundNonemptyU32(sorted_u32_arr, arr_length, needle);
308 }
309
310 HEADER_INLINE uintptr_t LowerBoundConstrainedNonemptyU32(const uint32_t* sorted_u32_arr, uintptr_t start_idx, uintptr_t end_idx, uint32_t needle) {
311 return start_idx + LowerBoundNonemptyU32(&(sorted_u32_arr[start_idx]), end_idx - start_idx, needle);
312 }
313
314 // Same as above, but optimized for case where result is probably close to the
315 // front, and tolerates end_idx (== arr_length) == 0.
316 uintptr_t Expsearch0U32(const uint32_t* sorted_u32_arr, uintptr_t end_idx, uint32_t needle);
317
318 HEADER_INLINE uintptr_t ExpsearchU32(const uint32_t* sorted_u32_arr, uintptr_t start_idx, uintptr_t end_idx, uint32_t needle) {
319 return start_idx + Expsearch0U32(&(sorted_u32_arr[start_idx]), end_idx - start_idx, needle);
320 }
321
322 #ifdef __LP64__
323 uintptr_t Expsearch0U64(const uint64_t* sorted_u64_arr, uintptr_t end_idx, uint64_t needle);
324
325 HEADER_INLINE uintptr_t ExpsearchU64(const uint64_t* sorted_u64_arr, uintptr_t start_idx, uintptr_t end_idx, uint64_t needle) {
326 return start_idx + Expsearch0U64(&(sorted_u64_arr[start_idx]), end_idx - start_idx, needle);
327 }
328
329 HEADER_INLINE uintptr_t ExpsearchW(const uintptr_t* sorted_w_arr, uintptr_t start_idx, uintptr_t end_idx, uintptr_t needle) {
330 return ExpsearchU64(R_CAST(const uint64_t*, sorted_w_arr), start_idx, end_idx, needle);
331 }
332 #else
333 HEADER_INLINE uintptr_t ExpsearchW(const uintptr_t* sorted_w_arr, uintptr_t start_idx, uintptr_t end_idx, uintptr_t needle) {
334 return ExpsearchU32(R_CAST(const uint32_t*, sorted_w_arr), start_idx, end_idx, needle);
335 }
336 #endif
337
338 uintptr_t LowerBoundNonemptyU64(const uint64_t* sorted_u64_arr, uintptr_t arr_length, uint64_t needle);
339
340 HEADER_INLINE uintptr_t LowerBoundNonemptyW(const uintptr_t* sorted_w_arr, uintptr_t arr_length, uintptr_t needle) {
341 #ifdef __LP64__
342 return LowerBoundNonemptyU64(R_CAST(const uint64_t*, sorted_w_arr), arr_length, needle);
343 #else
344 return LowerBoundNonemptyU32(R_CAST(const uint32_t*, sorted_w_arr), arr_length, needle);
345 #endif
346 }
347
348 HEADER_INLINE uintptr_t LowerBoundConstrainedNonemptyW(const uintptr_t* sorted_w_arr, uintptr_t start_idx, uintptr_t end_idx, uintptr_t needle) {
349 return start_idx + LowerBoundNonemptyW(&(sorted_w_arr[start_idx]), end_idx - start_idx, needle);
350 }
351
352 uintptr_t LowerBoundNonemptyD(const double* sorted_dbl_arr, uintptr_t arr_length, double needle);
353
354 uintptr_t Expsearch0D(const double* sorted_dbl_arr, uintptr_t end_idx, double needle);
355
356 HEADER_INLINE uintptr_t ExpsearchD(const double* sorted_dbl_arr, uintptr_t start_idx, uintptr_t end_idx, double needle) {
357 return start_idx + Expsearch0D(&(sorted_dbl_arr[start_idx]), end_idx - start_idx, needle);
358 }
359
360 uintptr_t UpperBoundNonemptyU32(const uint32_t* sorted_u32_arr, uintptr_t arr_length, uint32_t needle);
361
362 HEADER_INLINE uintptr_t UpperBoundConstrainedNonemptyU32(const uint32_t* sorted_u32_arr, uintptr_t start_idx, uintptr_t end_idx, uint32_t needle) {
363 return start_idx + UpperBoundNonemptyU32(&(sorted_u32_arr[start_idx]), end_idx - start_idx, needle);
364 }
365
366 uintptr_t UpperBoundNonemptyU64(const uint64_t* sorted_u64_arr, uintptr_t arr_length, uint64_t needle);
367
368 HEADER_INLINE uintptr_t UpperBoundConstrainedNonemptyU64(const uint64_t* sorted_u64_arr, uintptr_t start_idx, uintptr_t end_idx, uint64_t needle) {
369 return start_idx + UpperBoundNonemptyU64(&(sorted_u64_arr[start_idx]), end_idx - start_idx, needle);
370 }
371
372 HEADER_INLINE uintptr_t UpperBoundNonemptyW(const uintptr_t* sorted_w_arr, uintptr_t arr_length, uintptr_t needle) {
373 #ifdef __LP64__
374 return UpperBoundNonemptyU64(R_CAST(const uint64_t*, sorted_w_arr), arr_length, needle);
375 #else
376 return UpperBoundNonemptyU32(R_CAST(const uint32_t*, sorted_w_arr), arr_length, needle);
377 #endif
378 }
379
380 HEADER_INLINE uintptr_t UpperBoundConstrainedNonemptyW(const uintptr_t* sorted_w_arr, uintptr_t start_idx, uintptr_t end_idx, uintptr_t needle) {
381 return start_idx + UpperBoundNonemptyW(&(sorted_w_arr[start_idx]), end_idx - start_idx, needle);
382 }
383
384 // Requires sorted_w_arr[start_idx] <= needle.
385 HEADER_INLINE uintptr_t LastLeqU32(const uint32_t* sorted_u32_arr, uintptr_t start_idx, uintptr_t end_idx, uint32_t needle) {
386 return UpperBoundConstrainedNonemptyU32(sorted_u32_arr, start_idx, end_idx, needle) - 1;
387 }
388
389 HEADER_INLINE uintptr_t LastLeqU64(const uint64_t* sorted_u64_arr, uintptr_t start_idx, uintptr_t end_idx, uint64_t needle) {
390 return UpperBoundConstrainedNonemptyU64(sorted_u64_arr, start_idx, end_idx, needle) - 1;
391 }
392
393 HEADER_INLINE uintptr_t LastLeqW(const uintptr_t* sorted_w_arr, uintptr_t start_idx, uintptr_t end_idx, uintptr_t needle) {
394 return UpperBoundConstrainedNonemptyW(sorted_w_arr, start_idx, end_idx, needle) - 1;
395 }
396
397 // Requires sorted_w_arr[start_idx] <= needle, and needle < maxint.
398 HEADER_INLINE uintptr_t ExpsearchLastLeqU32(const uint32_t* sorted_u32_arr, uintptr_t start_idx, uintptr_t end_idx, uint32_t needle) {
399 return ExpsearchU32(sorted_u32_arr, start_idx, end_idx, needle + 1) - 1;
400 }
401
402 HEADER_INLINE uintptr_t ExpsearchLastLeqW(const uintptr_t* sorted_w_arr, uintptr_t start_idx, uintptr_t end_idx, uintptr_t needle) {
403 return ExpsearchW(sorted_w_arr, start_idx, end_idx, needle + 1) - 1;
404 }
405
406 uint32_t IdxToUidx(const uintptr_t* bitvec, const uint32_t* cumulative_popcounts, uint32_t widx_start, uint32_t widx_end, uint32_t idx);
407
408 uintptr_t IdxToUidxW(const uintptr_t* bitvec, const uintptr_t* cumulative_popcounts, uintptr_t widx_start, uintptr_t widx_end, uintptr_t idx);
409
410 uint32_t ExpsearchIdxToUidx(const uintptr_t* bitvec, const uint32_t* cumulative_popcounts, uint32_t widx_end, uint32_t idx, uint32_t* widx_startp);
411
412 uintptr_t ExpsearchIdxToUidxW(const uintptr_t* bitvec, const uintptr_t* cumulative_popcounts, uintptr_t widx_end, uintptr_t idx, uintptr_t* widx_startp);
413
414
415 HEADER_INLINE uint32_t IsCmdlineFlag(const char* param) {
416 unsigned char ucc = param[1];
417 return ((*param == '-') && ((ucc > '9') || ((ucc < '0') && (ucc != '.') && (ucc != '\0'))));
418 }
419
420 HEADER_INLINE CXXCONST_CP IsCmdlineFlagStart(const char* param) {
421 unsigned char ucc = param[1];
422 if ((*param == '-') && ((ucc > '9') || ((ucc < '0') && (ucc != '.') && (ucc != '\0')))) {
423 return S_CAST(CXXCONST_CP, &(param[1 + (ucc == '-')]));
424 }
425 return nullptr;
426 }
427
428 #ifdef __cplusplus
429 HEADER_INLINE char* IsCmdlineFlagStart(char* param) {
430 return const_cast<char*>(IsCmdlineFlagStart(const_cast<const char*>(param)));
431 }
432 #endif
433
434 uint32_t GetParamCt(const char* const* argvk, uint32_t argc, uint32_t flag_idx);
435
436 BoolErr EnforceParamCtRange(const char* flag_name, uint32_t param_ct, uint32_t min_ct, uint32_t max_ct);
437
438 // PglErr SortCmdlineFlags(uint32_t max_flag_blen, uint32_t flag_ct, char* flag_buf, uint32_t* flag_map);
439
440 BoolErr CleanupLogfile(uint32_t print_end_time);
441
442 CONSTI32(kNonBigstackMin, 67108864);
443
444 CONSTI32(kBigstackMinMib, 640);
445 CONSTI32(kBigstackDefaultMib, 2048);
446
447 static const double kSmallishEpsilon = 0.00000000002910383045673370361328125;
448 static const double kRecip2m32 = 0.00000000023283064365386962890625;
449 static const double k2m64 = 18446744073709551616.0;
450
451 static const double kLnPvalError = 9.0;
452
453 static const double kDblNormalMin = 2.2250738585072013e-308;
454
455 // probably time to flip arena_alloc and bigstack_alloc definitions...
456
457 PglErr InitLogfile(uint32_t always_stderr, char* outname, char* outname_end);
458
459 BoolErr CleanupLogfile(uint32_t print_end_time);
460
461 // manually managed, very large double-ended stack
462 extern unsigned char* g_bigstack_base;
463 extern unsigned char* g_bigstack_end;
464
465 uintptr_t GetDefaultAllocMib();
466
467 // caller is responsible for freeing bigstack_ua
468 PglErr InitBigstack(uintptr_t malloc_size_mib, uintptr_t* malloc_mib_final_ptr, unsigned char** bigstack_ua_ptr);
469
470
471 HEADER_INLINE uintptr_t bigstack_left() {
472 return g_bigstack_end - g_bigstack_base;
473 }
474
475 HEADER_INLINE void* bigstack_alloc_raw(uintptr_t size) {
476 // Assumes caller has already forced size to a multiple of
477 // kCacheline, and verified that enough space is available.
478 assert(!(size % kCacheline));
479 unsigned char* alloc_ptr = g_bigstack_base;
480 g_bigstack_base += size;
481 return alloc_ptr;
482 }
483
484 HEADER_INLINE void* bigstack_alloc_raw_rd(uintptr_t size) {
485 // Same as bigstack_alloc_raw(), except for rounding up size.
486 unsigned char* alloc_ptr = g_bigstack_base;
487 g_bigstack_base += RoundUpPow2(size, kCacheline);
488 return alloc_ptr;
489 }
490
491 // Basic 64-byte-aligned allocation at bottom of stack.
492 // Note that --make-pgen switches gracefully to a less memory-hungry algorithm
493 // when it encounters an allocation failure with its default algorithm. Since
494 // it can only happen once, unlikely() is still justified, but keep an eye on
495 // this.
496 HEADER_INLINE void* bigstack_alloc(uintptr_t size) {
497 size = RoundUpPow2(size, kCacheline);
498 if (unlikely(bigstack_left() < size)) {
499 g_failed_alloc_attempt_size = size;
500 return nullptr;
501 }
502 return bigstack_alloc_raw(size);
503 }
504
505 // When we only want vector-alignment.
506 HEADER_INLINE void* bigstack_allocv(uintptr_t size) {
507 size = RoundUpPow2(size, kCacheline);
508 if (unlikely(bigstack_left() < size)) {
509 g_failed_alloc_attempt_size = size;
510 return nullptr;
511 }
512 return bigstack_alloc_raw(size);
513 }
514
515 // Don't want uint64_t -> uintptr_t truncation to hide insufficient-memory
516 // scenarios in 32-bit builds.
517 HEADER_INLINE void* bigstack_alloc64(uint64_t size) {
518 size = RoundUpPow2U64(size, kCacheline);
519 if (unlikely(bigstack_left() < size)) {
520 g_failed_alloc_attempt_size = size;
521 return nullptr;
522 }
523 return bigstack_alloc_raw(size);
524 }
525
526
527 // Typesafe, return-0-iff-success interfaces. (See also bigstack_calloc_...
528 // further below.)
529 // This interface deliberately not provided for bigstack_alloc_raw() and
530 // bigstack_alloc_raw_rd() (and I wouldn't blame a future maintainer for
531 // entirely eliminating those functions).
532 HEADER_INLINE BoolErr bigstack_alloc_c(uintptr_t ct, char** c_arr_ptr) {
533 *c_arr_ptr = S_CAST(char*, bigstack_alloc(ct));
534 return !(*c_arr_ptr);
535 }
536
537 HEADER_INLINE BoolErr bigstack_alloc_d(uintptr_t ct, double** d_arr_ptr) {
538 *d_arr_ptr = S_CAST(double*, bigstack_alloc(ct * sizeof(double)));
539 return !(*d_arr_ptr);
540 }
541
542 HEADER_INLINE BoolErr bigstack_alloc_f(uintptr_t ct, float** f_arr_ptr) {
543 *f_arr_ptr = S_CAST(float*, bigstack_alloc(ct * sizeof(float)));
544 return !(*f_arr_ptr);
545 }
546
547 HEADER_INLINE BoolErr bigstack_alloc_i8(uintptr_t ct, int8_t** i8_arr_ptr) {
548 *i8_arr_ptr = S_CAST(int8_t*, bigstack_alloc(ct * sizeof(int8_t)));
549 return !(*i8_arr_ptr);
550 }
551
552 HEADER_INLINE BoolErr bigstack_alloc_i16(uintptr_t ct, int16_t** i16_arr_ptr) {
553 *i16_arr_ptr = S_CAST(int16_t*, bigstack_alloc(ct * sizeof(int16_t)));
554 return !(*i16_arr_ptr);
555 }
556
557 HEADER_INLINE BoolErr bigstack_alloc_i32(uintptr_t ct, int32_t** i32_arr_ptr) {
558 *i32_arr_ptr = S_CAST(int32_t*, bigstack_alloc(ct * sizeof(int32_t)));
559 return !(*i32_arr_ptr);
560 }
561
562 HEADER_INLINE BoolErr bigstack_alloc_uc(uintptr_t ct, unsigned char** uc_arr_ptr) {
563 *uc_arr_ptr = S_CAST(unsigned char*, bigstack_alloc(ct));
564 return !(*uc_arr_ptr);
565 }
566
567 HEADER_INLINE BoolErr bigstack_alloc_u16(uintptr_t ct, uint16_t** u16_arr_ptr) {
568 *u16_arr_ptr = S_CAST(uint16_t*, bigstack_alloc(ct * sizeof(int16_t)));
569 return !(*u16_arr_ptr);
570 }
571
572 HEADER_INLINE BoolErr bigstack_alloc_u32(uintptr_t ct, uint32_t** u32_arr_ptr) {
573 *u32_arr_ptr = S_CAST(uint32_t*, bigstack_alloc(ct * sizeof(int32_t)));
574 return !(*u32_arr_ptr);
575 }
576
577 HEADER_INLINE BoolErr bigstack_alloc_w(uintptr_t ct, uintptr_t** w_arr_ptr) {
578 *w_arr_ptr = S_CAST(uintptr_t*, bigstack_alloc(ct * sizeof(intptr_t)));
579 return !(*w_arr_ptr);
580 }
581
582 HEADER_INLINE BoolErr bigstack_alloc_hw(uintptr_t ct, Halfword** hw_arr_ptr) {
583 *hw_arr_ptr = S_CAST(Halfword*, bigstack_alloc(ct * sizeof(Halfword)));
584 return !(*hw_arr_ptr);
585 }
586
587 HEADER_INLINE BoolErr bigstack_alloc_i64(uintptr_t ct, int64_t** i64_arr_ptr) {
588 *i64_arr_ptr = S_CAST(int64_t*, bigstack_alloc(ct * sizeof(int64_t)));
589 return !(*i64_arr_ptr);
590 }
591
592 HEADER_INLINE BoolErr bigstack_alloc_u64(uintptr_t ct, uint64_t** u64_arr_ptr) {
593 *u64_arr_ptr = S_CAST(uint64_t*, bigstack_alloc(ct * sizeof(int64_t)));
594 return !(*u64_arr_ptr);
595 }
596
597 HEADER_INLINE BoolErr bigstack_alloc_v(uintptr_t ct, VecW** v_arr_ptr) {
598 *v_arr_ptr = S_CAST(VecW*, bigstack_alloc(ct * sizeof(VecW)));
599 return !(*v_arr_ptr);
600 }
601
602 // some versions of gcc give aliasing warnings if we use bigstack_alloc_w()
603 // for everything
604 // if sizeof(intptr_t) != sizeof(uintptr_t*), we're doomed anyway, so I won't
605 // bother with that static assert...
606 HEADER_INLINE BoolErr bigstack_alloc_wp(uintptr_t ct, uintptr_t*** ulp_arr_ptr) {
607 *ulp_arr_ptr = S_CAST(uintptr_t**, bigstack_alloc(ct * sizeof(intptr_t)));
608 return !(*ulp_arr_ptr);
609 }
610
611 HEADER_INLINE BoolErr bigstack_alloc_cp(uintptr_t ct, char*** cp_arr_ptr) {
612 *cp_arr_ptr = S_CAST(char**, bigstack_alloc(ct * sizeof(intptr_t)));
613 return !(*cp_arr_ptr);
614 }
615
616 HEADER_INLINE BoolErr bigstack_alloc_kcp(uintptr_t ct, const char*** kcp_arr_ptr) {
617 *kcp_arr_ptr = S_CAST(const char**, bigstack_alloc(ct * sizeof(intptr_t)));
618 return !(*kcp_arr_ptr);
619 }
620
621 HEADER_INLINE BoolErr bigstack_alloc_kcpp(uintptr_t ct, const char**** kcpp_arr_ptr) {
622 *kcpp_arr_ptr = S_CAST(const char***, bigstack_alloc(ct * sizeof(intptr_t)));
623 return !(*kcpp_arr_ptr);
624 }
625
626 HEADER_INLINE BoolErr bigstack_alloc_i16p(uintptr_t ct, int16_t*** i16p_arr_ptr) {
627 *i16p_arr_ptr = S_CAST(int16_t**, bigstack_alloc(ct * sizeof(intptr_t)));
628 return !(*i16p_arr_ptr);
629 }
630
631 HEADER_INLINE BoolErr bigstack_alloc_i32p(uintptr_t ct, int32_t*** i32p_arr_ptr) {
632 *i32p_arr_ptr = S_CAST(int32_t**, bigstack_alloc(ct * sizeof(intptr_t)));
633 return !(*i32p_arr_ptr);
634 }
635
636 HEADER_INLINE BoolErr bigstack_alloc_ucp(uintptr_t ct, unsigned char*** ucp_arr_ptr) {
637 *ucp_arr_ptr = S_CAST(unsigned char**, bigstack_alloc(ct * sizeof(intptr_t)));
638 return !(*ucp_arr_ptr);
639 }
640
641 HEADER_INLINE BoolErr bigstack_alloc_u16p(uintptr_t ct, uint16_t*** u16p_arr_ptr) {
642 *u16p_arr_ptr = S_CAST(uint16_t**, bigstack_alloc(ct * sizeof(intptr_t)));
643 return !(*u16p_arr_ptr);
644 }
645
646 HEADER_INLINE BoolErr bigstack_alloc_u32p(uintptr_t ct, uint32_t*** u32p_arr_ptr) {
647 *u32p_arr_ptr = S_CAST(uint32_t**, bigstack_alloc(ct * sizeof(intptr_t)));
648 return !(*u32p_arr_ptr);
649 }
650
651 HEADER_INLINE BoolErr bigstack_alloc_u64p(uintptr_t ct, uint64_t*** u64p_arr_ptr) {
652 *u64p_arr_ptr = S_CAST(uint64_t**, bigstack_alloc(ct * sizeof(intptr_t)));
653 return !(*u64p_arr_ptr);
654 }
655
656 HEADER_INLINE BoolErr bigstack_alloc_fp(uintptr_t ct, float*** fp_arr_ptr) {
657 *fp_arr_ptr = S_CAST(float**, bigstack_alloc(ct * sizeof(intptr_t)));
658 return !(*fp_arr_ptr);
659 }
660
661 HEADER_INLINE BoolErr bigstack_alloc_dp(uintptr_t ct, double*** dp_arr_ptr) {
662 *dp_arr_ptr = S_CAST(double**, bigstack_alloc(ct * sizeof(intptr_t)));
663 return !(*dp_arr_ptr);
664 }
665
666 HEADER_INLINE BoolErr bigstack_alloc_vp(uintptr_t ct, VecW*** vp_arr_ptr) {
667 *vp_arr_ptr = S_CAST(VecW**, bigstack_alloc(ct * sizeof(intptr_t)));
668 return !(*vp_arr_ptr);
669 }
670
671 HEADER_INLINE BoolErr bigstack_alloc_wpp(uintptr_t ct, uintptr_t**** wpp_arr_ptr) {
672 *wpp_arr_ptr = S_CAST(uintptr_t***, bigstack_alloc(ct * sizeof(intptr_t)));
673 return !(*wpp_arr_ptr);
674 }
675
676 HEADER_INLINE BoolErr bigstack_alloc_cpp(uintptr_t ct, char**** cpp_arr_ptr) {
677 *cpp_arr_ptr = S_CAST(char***, bigstack_alloc(ct * sizeof(intptr_t)));
678 return !(*cpp_arr_ptr);
679 }
680
681 HEADER_INLINE BoolErr bigstack_alloc_u32pp(uintptr_t ct, uint32_t**** u32pp_arr_ptr) {
682 *u32pp_arr_ptr = S_CAST(uint32_t***, bigstack_alloc(ct * sizeof(intptr_t)));
683 return !(*u32pp_arr_ptr);
684 }
685
686 HEADER_INLINE BoolErr bigstack_alloc_vpp(uintptr_t ct, VecW**** vpp_arr_ptr) {
687 *vpp_arr_ptr = S_CAST(VecW***, bigstack_alloc(ct * sizeof(VecW)));
688 return !(*vpp_arr_ptr);
689 }
690
691 HEADER_INLINE BoolErr bigstack_allocv_w(uintptr_t ct, uintptr_t** w_arr_ptr) {
692 *w_arr_ptr = S_CAST(uintptr_t*, bigstack_allocv(ct * sizeof(intptr_t)));
693 return !(*w_arr_ptr);
694 }
695
696 HEADER_INLINE BoolErr bigstack_alloc64_c(uint64_t ct, char** c_arr_ptr) {
697 *c_arr_ptr = S_CAST(char*, bigstack_alloc64(ct));
698 return !(*c_arr_ptr);
699 }
700
701 HEADER_INLINE BoolErr bigstack_alloc64_d(uint64_t ct, double** d_arr_ptr) {
702 *d_arr_ptr = S_CAST(double*, bigstack_alloc64(ct * sizeof(double)));
703 return !(*d_arr_ptr);
704 }
705
706 HEADER_INLINE BoolErr bigstack_alloc64_f(uint64_t ct, float** f_arr_ptr) {
707 *f_arr_ptr = S_CAST(float*, bigstack_alloc64(ct * sizeof(float)));
708 return !(*f_arr_ptr);
709 }
710
711 HEADER_INLINE BoolErr bigstack_alloc64_uc(uint64_t ct, unsigned char** uc_arr_ptr) {
712 *uc_arr_ptr = S_CAST(unsigned char*, bigstack_alloc64(ct));
713 return !(*uc_arr_ptr);
714 }
715
716 HEADER_INLINE BoolErr bigstack_alloc64_u32(uint64_t ct, uint32_t** u32_arr_ptr) {
717 *u32_arr_ptr = S_CAST(uint32_t*, bigstack_alloc64(ct * sizeof(int32_t)));
718 return !(*u32_arr_ptr);
719 }
720
721 typedef struct LlStrStruct {
722 NONCOPYABLE(LlStrStruct);
723 struct LlStrStruct* next;
724 char str[];
725 } LlStr;
726
727 // bigstack_end_alloc_llstr is usually better for small allocations like this.
728 HEADER_INLINE BoolErr bigstack_alloc_llstr(uintptr_t str_blen, LlStr** llstr_arr_ptr) {
729 *llstr_arr_ptr = S_CAST(LlStr*, bigstack_alloc(str_blen + sizeof(LlStr)));
730 return !(*llstr_arr_ptr);
731 }
732
733 BoolErr bigstack_calloc_uc(uintptr_t ct, unsigned char** uc_arr_ptr);
734
735 BoolErr bigstack_calloc_d(uintptr_t ct, double** d_arr_ptr);
736
737 BoolErr bigstack_calloc_f(uintptr_t ct, float** f_arr_ptr);
738
739 BoolErr bigstack_calloc_u16(uintptr_t ct, uint16_t** u16_arr_ptr);
740
741 BoolErr bigstack_calloc_u32(uintptr_t ct, uint32_t** u32_arr_ptr);
742
743 BoolErr bigstack_calloc_w(uintptr_t ct, uintptr_t** w_arr_ptr);
744
745 BoolErr bigstack_calloc_u64(uintptr_t ct, uint64_t** u64_arr_ptr);
746
747 BoolErr bigstack_calloc_v(uintptr_t ct, VecW** v_arr_ptr);
748
749 BoolErr bigstack_calloc_wp(uintptr_t ct, uintptr_t*** wp_arr_ptr);
750
751 BoolErr bigstack_calloc_cp(uintptr_t ct, char*** cp_arr_ptr);
752
753 BoolErr bigstack_calloc_kcp(uintptr_t ct, const char*** kcp_arr_ptr);
754
755 BoolErr bigstack_calloc_cpp(uintptr_t ct, char**** cpp_arr_ptr);
756
757 HEADER_INLINE BoolErr bigstack_calloc_c(uintptr_t ct, char** c_arr_ptr) {
758 return bigstack_calloc_uc(ct, R_CAST(unsigned char**, c_arr_ptr));
759 }
760
761 HEADER_INLINE BoolErr bigstack_calloc_i16(uintptr_t ct, int16_t** i16_arr_ptr) {
762 return bigstack_calloc_u16(ct, R_CAST(uint16_t**, i16_arr_ptr));
763 }
764
765 HEADER_INLINE BoolErr bigstack_calloc_i32(uintptr_t ct, int32_t** i32_arr_ptr) {
766 return bigstack_calloc_u32(ct, R_CAST(uint32_t**, i32_arr_ptr));
767 }
768
769 HEADER_INLINE BoolErr bigstack_calloc_i64(uintptr_t ct, int64_t** i64_arr_ptr) {
770 return bigstack_calloc_u64(ct, R_CAST(uint64_t**, i64_arr_ptr));
771 }
772
773 HEADER_INLINE BoolErr bigstack_calloc_u32p(uintptr_t ct, uint32_t*** u32p_arr_ptr) {
774 return bigstack_calloc_w(ct, R_CAST(uintptr_t**, u32p_arr_ptr));
775 }
776
777 #ifdef __LP64__
778 HEADER_INLINE BoolErr bigstack_calloc64_d(uint64_t ct, double** d_arr_ptr) {
779 return bigstack_calloc_d(ct, d_arr_ptr);
780 }
781 #else
782 BoolErr bigstack_calloc64_d(uint64_t ct, double** d_arr_ptr);
783 #endif
784
785 #if __cplusplus >= 201103L
786
787 template <class T> BoolErr BigstackAllocX(uintptr_t ct, T** x_arr_ptr) {
788 *x_arr_ptr = S_CAST(T*, bigstack_alloc(ct * sizeof(T)));
789 return !(*x_arr_ptr);
790 }
791
792 // todo: define all BigstackAlloc functions in terms of ArenaAlloc; then these
793 // can be namespaced, and we only need ARENA_ALLOC_X and ARENA_ALLOC_STD_ARRAY
794 // macros
795 # define BIGSTACK_ALLOC_X(tt, ct, pp) plink2::BigstackAllocX<tt>((ct), (pp))
796
797 # define BIGSTACK_ALLOC_STD_ARRAY(tt, arr_size, len, pp) plink2::BigstackAllocX<std::array<tt, arr_size>>((len), (pp))
798
799 #else
800
801 # define BIGSTACK_ALLOC_X(tt, ct, pp) (!((*(pp)) = S_CAST(tt*, bigstack_alloc((ct) * sizeof(tt)))))
802
803 # define BIGSTACK_ALLOC_STD_ARRAY(tt, arr_size, len, pp) (!((*(pp)) = S_CAST(STD_ARRAY_PTR_TYPE(tt, arr_size), bigstack_alloc((len) * (arr_size * sizeof(tt))))))
804
805 #endif
806
807 HEADER_INLINE void BigstackReset(void* new_base) {
808 g_bigstack_base = S_CAST(unsigned char*, new_base);
809 }
810
811 HEADER_INLINE void BigstackEndReset(void* new_end) {
812 g_bigstack_end = S_CAST(unsigned char*, new_end);
813 }
814
815 HEADER_INLINE void BigstackDoubleReset(void* new_base, void* new_end) {
816 BigstackReset(new_base);
817 BigstackEndReset(new_end);
818 }
819
820 // assumes we've already been writing to wptr and have previously performed
821 // bounds-checking.
822 HEADER_INLINE void BigstackFinalizeW(__maybe_unused const uintptr_t* wptr, uintptr_t ct) {
823 assert(wptr == R_CAST(const uintptr_t*, g_bigstack_base));
824 g_bigstack_base += RoundUpPow2(ct * sizeof(intptr_t), kCacheline);
825 assert(g_bigstack_base <= g_bigstack_end);
826 }
827
828 HEADER_INLINE void BigstackFinalizeU32(__maybe_unused const uint32_t* u32ptr, uintptr_t ct) {
829 assert(u32ptr == R_CAST(const uint32_t*, g_bigstack_base));
830 g_bigstack_base += RoundUpPow2(ct * sizeof(int32_t), kCacheline);
831 assert(g_bigstack_base <= g_bigstack_end);
832 }
833
834 HEADER_INLINE void BigstackFinalizeU64(__maybe_unused const uint64_t* u64ptr, uintptr_t ct) {
835 assert(u64ptr == R_CAST(const uint64_t*, g_bigstack_base));
836 g_bigstack_base += RoundUpPow2(ct * sizeof(int64_t), kCacheline);
837 assert(g_bigstack_base <= g_bigstack_end);
838 }
839
840 HEADER_INLINE void BigstackFinalizeC(__maybe_unused const char* cptr, uintptr_t ct) {
841 assert(cptr == R_CAST(const char*, g_bigstack_base));
842 g_bigstack_base += RoundUpPow2(ct, kCacheline);
843 assert(g_bigstack_base <= g_bigstack_end);
844 }
845
846 HEADER_INLINE void BigstackFinalizeCp(__maybe_unused const char* const* cpptr, uintptr_t ct) {
847 assert(cpptr == R_CAST(const char* const*, g_bigstack_base));
848 g_bigstack_base += RoundUpPow2(ct * sizeof(intptr_t), kCacheline);
849 assert(g_bigstack_base <= g_bigstack_end);
850 }
851
852
853 HEADER_INLINE void BigstackBaseSet(const void* unaligned_base) {
854 g_bigstack_base = R_CAST(unsigned char*, RoundUpPow2(R_CAST(uintptr_t, unaligned_base), kCacheline));
855 }
856
857 // When using BigstackBaseSet() after a loop where tmp_alloc_end is fixed, the
858 // latter should be initialized with BigstackEndRoundedDown().
859 // If tmp_alloc_end is not fixed, BigstackBaseSetChecked() should be called
860 // instead.
861 HEADER_INLINE BoolErr BigstackBaseSetChecked(const void* unaligned_base) {
862 g_bigstack_base = R_CAST(unsigned char*, RoundUpPow2(R_CAST(uintptr_t, unaligned_base), kCacheline));
863 return (g_bigstack_base > g_bigstack_end);
864 }
865
866 HEADER_INLINE unsigned char* BigstackEndRoundedDown() {
867 return R_CAST(unsigned char*, RoundDownPow2(R_CAST(uintptr_t, g_bigstack_end), kCacheline));
868 }
869
870 HEADER_INLINE void BigstackShrinkTop(const void* rebase, uintptr_t new_size) {
871 // could assert that this doesn't go in the wrong direction?
872 g_bigstack_base = R_CAST(unsigned char*, RoundUpPow2(R_CAST(uintptr_t, rebase) + new_size, kCacheline));
873 }
874
875 HEADER_INLINE void BigstackEndSet(const void* unaligned_end) {
876 g_bigstack_end = R_CAST(unsigned char*, RoundDownPow2(R_CAST(uintptr_t, unaligned_end), kEndAllocAlign));
877 }
878
879 // assumes size is divisible by kEndAllocAlign
880 // assumes enough space is available
881 HEADER_INLINE void* bigstack_end_alloc_raw(uintptr_t size) {
882 assert(!(size % kEndAllocAlign));
883 g_bigstack_end -= size;
884 return g_bigstack_end;
885 }
886
887 HEADER_INLINE void* bigstack_end_alloc_raw_rd(uintptr_t size) {
888 g_bigstack_end -= RoundUpPow2(size, kEndAllocAlign);
889 return g_bigstack_end;
890 }
891
892 HEADER_INLINE void* bigstack_end_alloc_presized(uintptr_t size) {
893 const uintptr_t cur_bigstack_left = bigstack_left();
894 if (size > cur_bigstack_left) {
895 g_failed_alloc_attempt_size = size;
896 return nullptr;
897 }
898 return bigstack_end_alloc_raw(size);
899 }
900
901 HEADER_INLINE void* bigstack_end_alloc(uintptr_t size) {
902 size = RoundUpPow2(size, kEndAllocAlign);
903 return bigstack_end_alloc_presized(size);
904 }
905
906 HEADER_INLINE void* bigstack_end_alloc64_presized(uint64_t size) {
907 const uintptr_t cur_bigstack_left = bigstack_left();
908 if (size > cur_bigstack_left) {
909 g_failed_alloc_attempt_size = size;
910 return nullptr;
911 }
912 return bigstack_end_alloc_raw(size);
913 }
914
915 HEADER_INLINE void* bigstack_end_alloc64(uint64_t size) {
916 size = RoundUpPow2U64(size, kEndAllocAlign);
917 return bigstack_end_alloc64_presized(size);
918 }
919
920 HEADER_INLINE BoolErr bigstack_end_alloc_c(uintptr_t ct, char** c_arr_ptr) {
921 *c_arr_ptr = S_CAST(char*, bigstack_end_alloc(ct));
922 return !(*c_arr_ptr);
923 }
924
925 HEADER_INLINE BoolErr bigstack_end_alloc_d(uintptr_t ct, double** d_arr_ptr) {
926 *d_arr_ptr = S_CAST(double*, bigstack_end_alloc(ct * sizeof(double)));
927 return !(*d_arr_ptr);
928 }
929
930 HEADER_INLINE BoolErr bigstack_end_alloc_f(uintptr_t ct, float** f_arr_ptr) {
931 *f_arr_ptr = S_CAST(float*, bigstack_end_alloc(ct * sizeof(float)));
932 return !(*f_arr_ptr);
933 }
934
935 HEADER_INLINE BoolErr bigstack_end_alloc_i32(uintptr_t ct, int32_t** i32_arr_ptr) {
936 *i32_arr_ptr = S_CAST(int32_t*, bigstack_end_alloc(ct * sizeof(int32_t)));
937 return !(*i32_arr_ptr);
938 }
939
940 HEADER_INLINE BoolErr bigstack_end_alloc_uc(uintptr_t ct, unsigned char** uc_arr_ptr) {
941 *uc_arr_ptr = S_CAST(unsigned char*, bigstack_end_alloc(ct));
942 return !(*uc_arr_ptr);
943 }
944
945 HEADER_INLINE BoolErr bigstack_end_alloc_u32(uintptr_t ct, uint32_t** u32_arr_ptr) {
946 *u32_arr_ptr = S_CAST(uint32_t*, bigstack_end_alloc(ct * sizeof(int32_t)));
947 return !(*u32_arr_ptr);
948 }
949
950 HEADER_INLINE BoolErr bigstack_end_alloc_w(uintptr_t ct, uintptr_t** w_arr_ptr) {
951 *w_arr_ptr = S_CAST(uintptr_t*, bigstack_end_alloc(ct * sizeof(intptr_t)));
952 return !(*w_arr_ptr);
953 }
954
955 HEADER_INLINE BoolErr bigstack_end_alloc_i64(uintptr_t ct, int64_t** i64_arr_ptr) {
956 *i64_arr_ptr = S_CAST(int64_t*, bigstack_end_alloc(ct * sizeof(int64_t)));
957 return !(*i64_arr_ptr);
958 }
959
960 HEADER_INLINE BoolErr bigstack_end_alloc_u64(uintptr_t ct, uint64_t** u64_arr_ptr) {
961 *u64_arr_ptr = S_CAST(uint64_t*, bigstack_end_alloc(ct * sizeof(int64_t)));
962 return !(*u64_arr_ptr);
963 }
964
965 HEADER_INLINE BoolErr bigstack_end_alloc_llstr(uintptr_t str_blen, LlStr** llstr_arr_ptr) {
966 *llstr_arr_ptr = S_CAST(LlStr*, bigstack_end_alloc(str_blen + sizeof(LlStr)));
967 return !(*llstr_arr_ptr);
968 }
969
970 HEADER_INLINE BoolErr bigstack_end_alloc_cp(uintptr_t ct, char*** cp_arr_ptr) {
971 *cp_arr_ptr = S_CAST(char**, bigstack_end_alloc(ct * sizeof(intptr_t)));
972 return !(*cp_arr_ptr);
973 }
974
975 HEADER_INLINE BoolErr bigstack_end_alloc_kcp(uintptr_t ct, const char*** kcp_arr_ptr) {
976 *kcp_arr_ptr = S_CAST(const char**, bigstack_end_alloc(ct * sizeof(intptr_t)));
977 return !(*kcp_arr_ptr);
978 }
979
980 HEADER_INLINE BoolErr bigstack_end_alloc_ucp(uintptr_t ct, unsigned char*** ucp_arr_ptr) {
981 *ucp_arr_ptr = S_CAST(unsigned char**, bigstack_end_alloc(ct * sizeof(intptr_t)));
982 return !(*ucp_arr_ptr);
983 }
984
985 BoolErr bigstack_end_calloc_uc(uintptr_t ct, unsigned char** uc_arr_ptr);
986
987 BoolErr bigstack_end_calloc_d(uintptr_t ct, double** d_arr_ptr);
988
989 BoolErr bigstack_end_calloc_f(uintptr_t ct, float** f_arr_ptr);
990
991 BoolErr bigstack_end_calloc_u32(uintptr_t ct, uint32_t** u32_arr_ptr);
992
993 BoolErr bigstack_end_calloc_w(uintptr_t ct, uintptr_t** w_arr_ptr);
994
995 BoolErr bigstack_end_calloc_u64(uintptr_t ct, uint64_t** u64_arr_ptr);
996
997 BoolErr bigstack_end_calloc_wp(uintptr_t ct, uintptr_t*** wp_arr_ptr);
998
999 BoolErr bigstack_end_calloc_cp(uintptr_t ct, char*** cp_arr_ptr);
1000
1001 HEADER_INLINE BoolErr bigstack_end_calloc_c(uintptr_t ct, char** c_arr_ptr) {
1002 return bigstack_end_calloc_uc(ct, R_CAST(unsigned char**, c_arr_ptr));
1003 }
1004
1005 HEADER_INLINE BoolErr bigstack_end_calloc_i32(uintptr_t ct, int32_t** i32_arr_ptr) {
1006 return bigstack_end_calloc_u32(ct, R_CAST(uint32_t**, i32_arr_ptr));
1007 }
1008
1009 HEADER_INLINE BoolErr bigstack_end_calloc_i64(uintptr_t ct, int64_t** i64_arr_ptr) {
1010 return bigstack_end_calloc_u64(ct, R_CAST(uint64_t**, i64_arr_ptr));
1011 }
1012
1013 HEADER_INLINE BoolErr bigstack_end_calloc_kcp(uintptr_t ct, const char*** kcp_arr_ptr) {
1014 return bigstack_end_calloc_cp(ct, K_CAST(char***, kcp_arr_ptr));
1015 }
1016
1017 #ifdef __LP64__
1018 HEADER_INLINE BoolErr bigstack_end_calloc64_w(uint64_t ct, uintptr_t** w_arr_ptr) {
1019 return bigstack_end_calloc_w(ct, w_arr_ptr);
1020 }
1021 #else
1022 BoolErr bigstack_end_calloc64_w(uint64_t ct, uintptr_t** w_arr_ptr);
1023 #endif
1024
1025 HEADER_INLINE void bigstack_end_clalign() {
1026 g_bigstack_end = BigstackEndRoundedDown();
1027 }
1028
1029 HEADER_INLINE void* bigstack_end_clalloc(uintptr_t size) {
1030 // assumes g_bigstack_end is cacheline-aligned by e.g. a
1031 // bigstack_end_clalign() call.
1032 size = RoundUpPow2(size, kCacheline);
1033 return bigstack_end_alloc_presized(size);
1034 }
1035
1036 HEADER_INLINE BoolErr bigstack_end_clalloc_c(uintptr_t ct, char** c_arr_ptr) {
1037 *c_arr_ptr = S_CAST(char*, bigstack_end_clalloc(ct));
1038 return !(*c_arr_ptr);
1039 }
1040
1041 HEADER_INLINE BoolErr bigstack_end_clalloc_d(uintptr_t ct, double** d_arr_ptr) {
1042 *d_arr_ptr = S_CAST(double*, bigstack_end_clalloc(ct * sizeof(double)));
1043 return !(*d_arr_ptr);
1044 }
1045
1046 HEADER_INLINE BoolErr bigstack_end_clalloc_v(uintptr_t ct, VecW** v_arr_ptr) {
1047 *v_arr_ptr = S_CAST(VecW*, bigstack_end_clalloc(ct * sizeof(VecW)));
1048 return !(*v_arr_ptr);
1049 }
1050
1051 HEADER_INLINE BoolErr bigstack_end_clalloc_cp(uintptr_t ct, char*** cp_arr_ptr) {
1052 *cp_arr_ptr = S_CAST(char**, bigstack_end_clalloc(ct * sizeof(intptr_t)));
1053 return !(*cp_arr_ptr);
1054 }
1055
1056 // most of the non-global arena interface (necessary for some multithreaded
1057 // code) now in include/plink2_memory; arena_alloc_raw() and
1058 // arena_alloc_raw_rd() in include/plink2_base
1059
1060
1061 BoolErr PushLlStr(const char* str, LlStr** ll_stack_ptr);
1062
1063 // Does not require null-termination.
1064 // BoolErr push_llstr_counted(const char* str, uint32_t slen, LlStr** ll_stack_ptr);
1065
1066 void llstr_free_cond(LlStr* llstr_head);
1067
1068 typedef struct L32StrStruct {
1069 NONCOPYABLE(L32StrStruct);
1070 uint32_t len;
1071 char str[];
1072 } L32Str;
1073
1074 // assumes multistr is nonempty
1075 // BoolErr CountAndMeasureMultistrAlloc(const char* multistr, uintptr_t max_str_ct, const char** strptr_arr, uint32_t* str_ct_ptr, uintptr_t* max_blen_ptr);
1076
1077 // assumes multistr is nonempty
1078 BoolErr CountAndMeasureMultistrReverseAlloc(const char* multistr, uintptr_t max_str_ct, uint32_t* str_ct_ptr, uintptr_t* max_blen_ptr, const char*** strptr_arrp);
1079
1080 // er, should benchmark this against hash table and InMultistr()
1081 BoolErr MultistrToStrboxDedupArenaAlloc(unsigned char* arena_top, const char* multistr, unsigned char** arena_bottom_ptr, char** sorted_strbox_ptr, uint32_t* str_ct_ptr, uintptr_t* max_blen_ptr);
1082
1083 HEADER_INLINE BoolErr MultistrToStrboxDedupAlloc(const char* multistr, char** sorted_strbox_ptr, uint32_t* str_ct_ptr, uintptr_t* max_blen_ptr) {
1084 return MultistrToStrboxDedupArenaAlloc(g_bigstack_end, multistr, &g_bigstack_base, sorted_strbox_ptr, str_ct_ptr, max_blen_ptr);
1085 }
1086
1087
1088 void DivisionMagicNums(uint32_t divisor, uint64_t* multp, uint32_t* __restrict pre_shiftp, uint32_t* __restrict post_shiftp, uint32_t* __restrict incrp);
1089
1090 // ZeroU32Arr, ZeroWArr, ZeroU64Arr, SetAllWArr, SetAllU32Arr currently defined
1091 // in plink2_base.h
1092
1093 HEADER_INLINE void ZeroVecArr(uintptr_t entry_ct, VecW* vvec) {
1094 memset(vvec, 0, entry_ct * kBytesPerVec);
1095 }
1096
1097 HEADER_INLINE void SetAllU64Arr(uintptr_t entry_ct, uint64_t* u64arr) {
1098 // bugfix (1 Feb 2018): forgot to multiply by 2 in 32-bit case
1099 SetAllWArr(entry_ct * (sizeof(int64_t) / kBytesPerWord), R_CAST(uintptr_t*, u64arr));
1100 }
1101
1102 HEADER_INLINE void ZeroI32Arr(uintptr_t entry_ct, int32_t* i32arr) {
1103 memset(i32arr, 0, entry_ct * sizeof(int32_t));
1104 }
1105
1106 HEADER_INLINE void SetAllI32Arr(uintptr_t entry_ct, int32_t* i32arr) {
1107 for (uintptr_t ulii = 0; ulii != entry_ct; ulii++) {
1108 *i32arr++ = -1;
1109 }
1110 }
1111
1112 HEADER_INLINE void ZeromovFArr(uintptr_t entry_ct, float** farr_ptr) {
1113 float* farr = *farr_ptr;
1114 for (uintptr_t ulii = 0; ulii != entry_ct; ulii++) {
1115 *farr++ = 0.0;
1116 }
1117 *farr_ptr = farr;
1118 }
1119
1120 HEADER_INLINE void ZeromovDArr(uintptr_t entry_ct, double** darr_ptr) {
1121 double* darr = *darr_ptr;
1122 for (uintptr_t ulii = 0; ulii != entry_ct; ulii++) {
1123 *darr++ = 0.0;
1124 }
1125 *darr_ptr = darr;
1126 }
1127
1128
1129 // SetAllBits, IsSet, SetBit, ClearBit, AdvTo1Bit, AdvTo0Bit, AdvBoundedTo1Bit,
1130 // FindLast1BitBefore, AllWordsAreZero, FillBitsNz, ClearBitsNz defined in
1131 // plink2_bits.h
1132
1133 // Useful when we don't want to think about the signedness of a 32-bit int.
1134 HEADER_INLINE void SetBitI(int32_t loc, uintptr_t* bitarr) {
1135 SetBit(S_CAST(uint32_t, loc), bitarr);
1136 }
1137
1138 HEADER_INLINE void FlipBit(uintptr_t loc, uintptr_t* bitarr) {
1139 bitarr[loc / kBitsPerWord] ^= k1LU << (loc % kBitsPerWord);
1140 }
1141
1142 // floor permitted to be -1, though not smaller than that.
1143 int32_t FindLast1BitBeforeBounded(const uintptr_t* bitarr, uint32_t loc, int32_t floor);
1144
1145 // This can be made a tiny bit faster than memequal() in isolation, but the
1146 // difference is almost certainly too small to justify additional i-cache
1147 // pressure.
1148 HEADER_INLINE uint32_t wordsequal(const uintptr_t* word_arr1, const uintptr_t* word_arr2, uintptr_t word_ct) {
1149 return memequal(word_arr1, word_arr2, word_ct * kBytesPerWord);
1150 }
1151
1152
1153 // BitvecAnd(), BitvecInvmask(), BitvecOr(), BitvecInvert(), BitvecXorCopy(),
1154 // BitvecInvertCopy(), AlignedBitarrInvert(), and AlignedBitarrInvertCopy() in
1155 // plink2_bits.h
1156
1157 void BitvecAndCopy(const uintptr_t* __restrict source1_bitvec, const uintptr_t* __restrict source2_bitvec, uintptr_t word_ct, uintptr_t* target_bitvec);
1158
1159 void BitvecInvmaskCopy(const uintptr_t* __restrict source_bitvec, const uintptr_t* __restrict exclude_bitvec, uintptr_t word_ct, uintptr_t* target_bitvec);
1160
1161 void BitvecXor(const uintptr_t* __restrict arg_bitvec, uintptr_t word_ct, uintptr_t* main_bitvec);
1162
1163 void BitvecInvertAndMask(const uintptr_t* __restrict include_bitvec, uintptr_t word_ct, uintptr_t* __restrict main_bitvec);
1164
1165 // void BitvecOrNot(const uintptr_t* __restrict arg_bitvec, uintptr_t word_ct, uintptr_t* main_bitvec);
1166
1167 // yes || (!no)
1168 // 'AlignedBitarr' instead of Bitvec since this takes bit_ct instead of word_ct
1169 // as the size argument, and zeroes trailing bits.
1170 void AlignedBitarrOrnotCopy(const uintptr_t* __restrict argyes_bitvec, const uintptr_t* __restrict argno_bitvec, uintptr_t bit_ct, uintptr_t* __restrict target_bitvec);
1171
1172 // Address C-only incompatible-pointer-types-discards-qualifiers warning.
1173 #ifdef __cplusplus
1174 # define TO_CONSTU32PCONSTP(u32_pp) (u32_pp)
1175 #else
1176 # define TO_CONSTU32PCONSTP(u32_pp) ((const uint32_t* const*)(u32_pp))
1177 #endif
1178
1179 HEADER_INLINE void U32VecAdd(const VecU32* arg_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1180 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1181 main_u32vec[vidx] += arg_u32vec[vidx];
1182 }
1183 }
1184
1185 HEADER_INLINE void U32CastVecAdd(const uint32_t* arg_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1186 U32VecAdd(R_CAST(const VecU32*, arg_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1187 }
1188
1189 HEADER_INLINE void I32CastVecAdd(const int32_t* arg_i32arr, uintptr_t vec_ct, int32_t* main_i32arr) {
1190 U32VecAdd(R_CAST(const VecU32*, arg_i32arr), vec_ct, R_CAST(VecU32*, main_i32arr));
1191 }
1192
1193 HEADER_INLINE void U32VecSub(const VecU32* arg_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1194 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1195 main_u32vec[vidx] -= arg_u32vec[vidx];
1196 }
1197 }
1198
1199 HEADER_INLINE void U32CastVecSub(const uint32_t* arg_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1200 U32VecSub(R_CAST(const VecU32*, arg_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1201 }
1202
1203 HEADER_INLINE void U32VecMaskedAdd(const VecU32* mask_u32vec, const VecU32* arg_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1204 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1205 main_u32vec[vidx] += mask_u32vec[vidx] & arg_u32vec[vidx];
1206 }
1207 }
1208
1209 HEADER_INLINE void U32CastVecMaskedAdd(const uint32_t* mask_u32arr, const uint32_t* arg_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1210 U32VecMaskedAdd(R_CAST(const VecU32*, mask_u32arr), R_CAST(const VecU32*, arg_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1211 }
1212
1213 HEADER_INLINE void U32VecInvmaskedAdd(const VecU32* invmask_u32vec, const VecU32* arg_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1214 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1215 main_u32vec[vidx] += vecu32_and_notfirst(invmask_u32vec[vidx], arg_u32vec[vidx]);
1216 }
1217 }
1218
1219 HEADER_INLINE void U32CastVecInvmaskedAdd(const uint32_t* invmask_u32arr, const uint32_t* arg_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1220 U32VecInvmaskedAdd(R_CAST(const VecU32*, invmask_u32arr), R_CAST(const VecU32*, arg_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1221 }
1222
1223
1224 HEADER_INLINE void U32VecAdd2(const VecU32* arg1_u32vec, const VecU32* arg2_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1225 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1226 main_u32vec[vidx] += arg1_u32vec[vidx] + arg2_u32vec[vidx];
1227 }
1228 }
1229
1230 HEADER_INLINE void U32CastVecAdd2(const uint32_t* arg1_u32arr, const uint32_t* arg2_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1231 U32VecAdd2(R_CAST(const VecU32*, arg1_u32arr), R_CAST(const VecU32*, arg2_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1232 }
1233
1234 HEADER_INLINE void U32VecAssignAdd2(const VecU32* arg1_u32vec, const VecU32* arg2_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1235 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1236 main_u32vec[vidx] = arg1_u32vec[vidx] + arg2_u32vec[vidx];
1237 }
1238 }
1239
1240 HEADER_INLINE void U32CastVecAssignAdd2(const uint32_t* arg1_u32arr, const uint32_t* arg2_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1241 U32VecAssignAdd2(R_CAST(const VecU32*, arg1_u32arr), R_CAST(const VecU32*, arg2_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1242 }
1243
1244 HEADER_INLINE void U32VecMaskedAdd2(const VecU32* mask_u32vec, const VecU32* arg1_u32vec, const VecU32* arg2_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1245 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1246 main_u32vec[vidx] += mask_u32vec[vidx] & (arg1_u32vec[vidx] + arg2_u32vec[vidx]);
1247 }
1248 }
1249
1250 HEADER_INLINE void U32CastVecMaskedAdd2(const uint32_t* mask_u32arr, const uint32_t* arg1_u32arr, const uint32_t* arg2_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1251 U32VecMaskedAdd2(R_CAST(const VecU32*, mask_u32arr), R_CAST(const VecU32*, arg1_u32arr), R_CAST(const VecU32*, arg2_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1252 }
1253
1254 HEADER_INLINE void U32VecAddSub(const VecU32* add_u32vec, const VecU32* sub_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1255 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1256 main_u32vec[vidx] += add_u32vec[vidx] - sub_u32vec[vidx];
1257 }
1258 }
1259
1260 HEADER_INLINE void U32CastVecAddSub(const uint32_t* add_u32arr, const uint32_t* sub_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1261 U32VecAddSub(R_CAST(const VecU32*, add_u32arr), R_CAST(const VecU32*, sub_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1262 }
1263
1264
1265 HEADER_INLINE void U32VecAdd3(const VecU32* arg1_u32vec, const VecU32* arg2_u32vec, const VecU32* arg3_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1266 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1267 main_u32vec[vidx] += arg1_u32vec[vidx] + arg2_u32vec[vidx] + arg3_u32vec[vidx];
1268 }
1269 }
1270
1271 HEADER_INLINE void U32CastVecAdd3(const uint32_t* arg1_u32arr, const uint32_t* arg2_u32arr, const uint32_t* arg3_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1272 U32VecAdd3(R_CAST(const VecU32*, arg1_u32arr), R_CAST(const VecU32*, arg2_u32arr), R_CAST(const VecU32*, arg3_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1273 }
1274
1275 HEADER_INLINE void U32VecAssignAdd3(const VecU32* arg1_u32vec, const VecU32* arg2_u32vec, const VecU32* arg3_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1276 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1277 main_u32vec[vidx] = arg1_u32vec[vidx] + arg2_u32vec[vidx] + arg3_u32vec[vidx];
1278 }
1279 }
1280
1281 HEADER_INLINE void U32CastVecAssignAdd3(const uint32_t* arg1_u32arr, const uint32_t* arg2_u32arr, const uint32_t* arg3_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1282 U32VecAssignAdd3(R_CAST(const VecU32*, arg1_u32arr), R_CAST(const VecU32*, arg2_u32arr), R_CAST(const VecU32*, arg3_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1283 }
1284
1285 HEADER_INLINE void U32VecSub3(const VecU32* arg1_u32vec, const VecU32* arg2_u32vec, const VecU32* arg3_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1286 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1287 main_u32vec[vidx] -= arg1_u32vec[vidx] + arg2_u32vec[vidx] + arg3_u32vec[vidx];
1288 }
1289 }
1290
1291 HEADER_INLINE void U32CastVecSub3(const uint32_t* arg1_u32arr, const uint32_t* arg2_u32arr, const uint32_t* arg3_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1292 U32VecSub3(R_CAST(const VecU32*, arg1_u32arr), R_CAST(const VecU32*, arg2_u32arr), R_CAST(const VecU32*, arg3_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1293 }
1294
1295 HEADER_INLINE void U32VecAssignAdd5(const VecU32* arg1_u32vec, const VecU32* arg2_u32vec, const VecU32* arg3_u32vec, const VecU32* arg4_u32vec, const VecU32* arg5_u32vec, uintptr_t vec_ct, VecU32* main_u32vec) {
1296 for (uintptr_t vidx = 0; vidx != vec_ct; ++vidx) {
1297 main_u32vec[vidx] = arg1_u32vec[vidx] + arg2_u32vec[vidx] + arg3_u32vec[vidx] + arg4_u32vec[vidx] + arg5_u32vec[vidx];
1298 }
1299 }
1300
1301 HEADER_INLINE void U32CastVecAssignAdd5(const uint32_t* arg1_u32arr, const uint32_t* arg2_u32arr, const uint32_t* arg3_u32arr, const uint32_t* arg4_u32arr, const uint32_t* arg5_u32arr, uintptr_t vec_ct, uint32_t* main_u32arr) {
1302 U32VecAssignAdd5(R_CAST(const VecU32*, arg1_u32arr), R_CAST(const VecU32*, arg2_u32arr), R_CAST(const VecU32*, arg3_u32arr), R_CAST(const VecU32*, arg4_u32arr), R_CAST(const VecU32*, arg5_u32arr), vec_ct, R_CAST(VecU32*, main_u32arr));
1303 }
1304
1305 // This usually makes a temporary g_bigstack allocation.
1306 HEADER_INLINE BoolErr SortStrptrArrIndexed(uint32_t str_ct, uint32_t leave_first_alone, uint32_t overread_ok, uint32_t use_nsort, const char** strptrs, uint32_t* new_to_old_idx, uint32_t* old_to_new_idx) {
1307 const uint32_t str_sort_ct = str_ct - leave_first_alone;
1308 if ((str_sort_ct > 1) && (bigstack_left() < str_sort_ct * sizeof(StrSortIndexedDeref))) {
1309 return 1;
1310 }
1311 SortStrptrArrIndexed2(str_ct, leave_first_alone, overread_ok, use_nsort, strptrs, new_to_old_idx, old_to_new_idx, g_bigstack_base);
1312 return 0;
1313 }
1314
1315 // basic linear scan
1316 // returns -1 on failure to find, -2 if duplicate
1317 int32_t GetVariantUidxWithoutHtable(const char* idstr, const char* const* variant_ids, const uintptr_t* variant_include, uint32_t variant_ct);
1318
1319 BoolErr HtableGoodSizeAlloc(uint32_t item_ct, uintptr_t bytes_avail, uint32_t** htable_ptr, uint32_t* htable_size_ptr);
1320
1321 // returned index in duplicate-pair case is unfiltered
1322 // uint32_t populate_strbox_subset_htable(const uintptr_t* __restrict subset_mask, const char* strbox, uintptr_t raw_str_ct, uintptr_t str_ct, uintptr_t max_str_blen, uint32_t str_htable_size, uint32_t* str_htable);
1323
1324 // assumes cur_id_slen < max_str_blen.
1325 // requires cur_id to be null-terminated.
1326 uint32_t StrboxHtableFind(const char* cur_id, const char* strbox, const uint32_t* id_htable, uintptr_t max_str_blen, uint32_t cur_id_slen, uint32_t id_htable_size);
1327
1328 uint32_t StrboxHtableFindNnt(const char* cur_id, const char* strbox, const uint32_t* id_htable, uintptr_t max_str_blen, uint32_t cur_id_slen, uint32_t id_htable_size);
1329
1330 // Assumes cur_id is null-terminated.
1331 // Returns string-index if cur_id is already in the table, UINT32_MAX if it was
1332 // added.
1333 uint32_t StrboxHtableAdd(const char* cur_id, const char* strbox, uintptr_t max_str_blen, uint32_t cur_id_slen, uint32_t id_htable_size, uint32_t value, uint32_t* id_htable);
1334
1335 // useful for duplicate detection: returns 0 on no duplicates, a positive index
1336 // of a duplicate pair if they're present
1337 uint32_t PopulateStrboxHtable(const char* strbox, uint32_t str_ct, uintptr_t max_str_blen, uint32_t str_htable_size, uint32_t* str_htable);
1338
1339 uint32_t PopulateStrboxSubsetHtableDup(const char* strbox, const uintptr_t* subset_mask, uint32_t str_ct, uintptr_t max_str_blen, uint32_t str_htable_size, uint32_t* str_htable);
1340
1341 // last variant_ids entry must be at least kMaxIdBlen bytes before end of
1342 // bigstack
1343 uint32_t VariantIdDupflagHtableFind(const char* idbuf, const char* const* variant_ids, const uint32_t* id_htable, uint32_t cur_id_slen, uint32_t id_htable_size, uint32_t max_id_slen);
1344
1345 uint32_t VariantIdDupHtableFind(const char* idbuf, const char* const* variant_ids, const uint32_t* id_htable, const uint32_t* htable_dup_base, uint32_t cur_id_slen, uint32_t id_htable_size, uint32_t max_id_slen, uint32_t* llidx_ptr);
1346
1347
1348 // This still perform a temporary bigstack allocation; 'noalloc' here just
1349 // means that sorted_strbox and id_map must be allocated in advance. (Overread
1350 // must be safe.)
1351 PglErr CopySortStrboxSubsetNoalloc(const uintptr_t* __restrict subset_mask, const char* __restrict orig_strbox, uintptr_t str_ct, uintptr_t max_str_blen, uint32_t collapse_idxs, uint32_t use_nsort, char* __restrict sorted_strbox, uint32_t* __restrict id_map);
1352
1353 PglErr CopySortStrboxSubset(const uintptr_t* __restrict subset_mask, const char* __restrict orig_strbox, uintptr_t str_ct, uintptr_t max_str_blen, uint32_t collapse_idxs, uint32_t use_nsort, char** sorted_strbox_ptr, uint32_t** id_map_ptr);
1354
1355
1356 typedef struct RangeListStruct {
1357 NONCOPYABLE(RangeListStruct);
1358 char* names;
1359 unsigned char* starts_range;
1360 uint32_t name_ct;
1361 uint32_t name_max_blen;
1362 } RangeList;
1363
1364 void InitRangeList(RangeList* range_list_ptr);
1365
1366 void CleanupRangeList(RangeList* range_list_ptr);
1367
1368 // bitarr assumed to be initialized (but not necessarily zero-initialized)
1369 BoolErr NumericRangeListToBitarr(const RangeList* range_list_ptr, uint32_t bitarr_size, uint32_t offset, uint32_t ignore_overflow, uintptr_t* bitarr);
1370
1371 // returns UINT32_MAX on parsing error
1372 uint32_t NumericRangeListMax(const RangeList* range_list_ptr);
1373
1374 PglErr StringRangeListToBitarr(const char* header_line, const RangeList* range_list_ptr, const char* __restrict sorted_ids, const uint32_t* __restrict id_map, const char* __restrict range_list_flag, const char* __restrict file_descrip, uint32_t token_ct, uint32_t fixed_len, uint32_t comma_delim, uintptr_t* bitarr, int32_t* __restrict seen_idxs);
1375
1376 PglErr StringRangeListToBitarrAlloc(const char* header_line, const RangeList* range_list_ptr, const char* __restrict range_list_flag, const char* __restrict file_descrip, uint32_t token_ct, uint32_t fixed_len, uint32_t comma_delim, uintptr_t** bitarr_ptr);
1377
1378
1379 HEADER_INLINE uint32_t IntersectionIsEmpty(const uintptr_t* bitvec1, const uintptr_t* bitvec2, uintptr_t word_ct) {
1380 #ifdef USE_SSE42
1381 const uintptr_t fullvec_ct = word_ct / kWordsPerVec;
1382 # ifdef USE_AVX2
1383 const __m256i* bitvvec1 = R_CAST(const __m256i*, bitvec1);
1384 const __m256i* bitvvec2 = R_CAST(const __m256i*, bitvec2);
1385 for (uintptr_t vidx = 0; vidx != fullvec_ct; ++vidx) {
1386 if (!_mm256_testz_si256(bitvvec1[vidx], bitvvec2[vidx])) {
1387 return 0;
1388 }
1389 }
1390 # else
1391 const __m128i* bitvvec1 = R_CAST(const __m128i*, bitvec1);
1392 const __m128i* bitvvec2 = R_CAST(const __m128i*, bitvec2);
1393 for (uintptr_t vidx = 0; vidx != fullvec_ct; ++vidx) {
1394 if (!_mm_testz_si128(bitvvec1[vidx], bitvvec2[vidx])) {
1395 return 0;
1396 }
1397 }
1398 # endif
1399 word_ct = word_ct & (kWordsPerVec - 1);
1400 bitvec1 = R_CAST(const uintptr_t*, &(bitvvec1[fullvec_ct]));
1401 bitvec2 = R_CAST(const uintptr_t*, &(bitvvec2[fullvec_ct]));
1402 #endif
1403 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
1404 if (bitvec1[widx] & bitvec2[widx]) {
1405 return 0;
1406 }
1407 }
1408 return 1;
1409 }
1410
1411 uint32_t IntersectionRangeIsEmpty(const uintptr_t* bitarr1, const uintptr_t* bitarr2, uintptr_t start_idx, uintptr_t end_idx);
1412
1413 // could use testz here, but it's more awkward
1414 HEADER_INLINE uint32_t UnionIsFull(const uintptr_t* bitarr1, const uintptr_t* bitarr2, uintptr_t bit_ct) {
1415 const uintptr_t fullword_ct = bit_ct / kBitsPerWord;
1416 for (uintptr_t widx = 0; widx != fullword_ct; ++widx) {
1417 if ((bitarr1[widx] | bitarr2[widx]) != ~k0LU) {
1418 return 0;
1419 }
1420 }
1421 const uint32_t trailing_bit_ct = bit_ct % kBitsPerWord;
1422 if (trailing_bit_ct) {
1423 if ((bitarr1[fullword_ct] | bitarr2[fullword_ct]) != ((k1LU << trailing_bit_ct) - k1LU)) {
1424 return 0;
1425 }
1426 }
1427 return 1;
1428 }
1429
1430 // PopcountWordsIntersect moved to plink2_bits
1431
1432 void PopcountWordsIntersect3val(const uintptr_t* __restrict bitvec1, const uintptr_t* __restrict bitvec2, uint32_t word_ct, uint32_t* __restrict popcount1_ptr, uint32_t* __restrict popcount2_ptr, uint32_t* __restrict popcount_intersect_ptr);
1433
1434 // uintptr_t count_11_longs(const uintptr_t* genovec, uintptr_t word_ct);
1435 // (see CountNyp in pgenlib_misc for that functionality)
1436
1437 // Must be safe to read from bitarr[start_idx / kBitsPerWord].
1438 uint32_t AllBitsAreZero(const uintptr_t* bitarr, uintptr_t start_idx, uintptr_t end_idx);
1439
1440 // does not assume relevant bits of target_bitarr are zero
1441 HEADER_INLINE void CopyBits(uintptr_t src_word, uint64_t target_start_bitidx, uint32_t len, void* target_bitarr) {
1442 unsigned char* target_bitarr_uc = S_CAST(unsigned char*, target_bitarr);
1443 unsigned char* update_ptr = &(target_bitarr_uc[(target_start_bitidx / kBitsPerWord) * kBytesPerWord]);
1444 uintptr_t target_word;
1445 CopyFromUnalignedW(&target_word, update_ptr);
1446 const uint32_t bit_idx_start = target_start_bitidx % kBitsPerWord;
1447 const uintptr_t shifted_new_bits = src_word << bit_idx_start;
1448 const uint32_t bit_idx_end = bit_idx_start + len;
1449 if (bit_idx_end <= kBitsPerWord) {
1450 const uintptr_t invmask = bzhi_max((~k0LU) << bit_idx_start, bit_idx_end);
1451 target_word = (target_word & (~invmask)) | shifted_new_bits;
1452 CopyToUnalignedW(update_ptr, &target_word);
1453 return;
1454 }
1455 AppendW(bzhi(target_word, bit_idx_start) | shifted_new_bits, &update_ptr);
1456
1457 CopyFromUnalignedW(&target_word, update_ptr);
1458 const uint32_t remainder = bit_idx_end - kBitsPerWord;
1459 target_word = (target_word & ((~k0LU) << remainder)) | (src_word >> (len - remainder));
1460 CopyToUnalignedW(update_ptr, &target_word);
1461 }
1462
1463 // assumes len is positive, and relevant bits of target_bitarr are zero
1464 void CopyBitarrRange(const uintptr_t* __restrict src_bitarr, uintptr_t src_start_bitidx, uintptr_t target_start_bitidx, uintptr_t len, uintptr_t* __restrict target_bitarr);
1465
1466
1467 // vertical popcount support
1468 // VcountScramble1() and friends are here since they apply to generic
1469 // arrays; scramble_2_4_8_32() is more plink-specific
1470
1471 #ifdef __LP64__
1472 # ifdef USE_AVX2
1473 HEADER_INLINE uint32_t VcountScramble1(uint32_t orig_idx) {
1474 // 1->4: 0 4 8 12 16 20 24 28 32 ... 252 1 5 9 ...
1475 // 4->8: 0 8 16 24 32 ... 248 4 12 20 ... 1 9 17 ...
1476 // 8->32: 0 32 ... 224 8 40 ... 232 ... 248 4 36 ... 252 1 33 ...
1477 return (orig_idx & (~255)) + ((orig_idx & 3) * 64) + ((orig_idx & 4) * 8) + (orig_idx & 24) + ((orig_idx & 224) / 32);
1478 }
1479 # else
1480 HEADER_INLINE uint32_t VcountScramble1(uint32_t orig_idx) {
1481 // 1->4: 0 4 8 12 16 20 24 28 32 ... 124 1 5 9 ...
1482 // 4->8: 0 8 16 24 32 ... 120 4 12 20 ... 1 9 17 ...
1483 // 8->32: 0 32 64 96 8 40 72 104 16 48 80 112 24 56 88 120 4 36 68 ... 1 33 ...
1484 return (orig_idx & (~127)) + ((orig_idx & 3) * 32) + ((orig_idx & 4) * 4) + ((orig_idx & 24) / 2) + ((orig_idx & 96) / 32);
1485 }
1486 # endif
1487 #else
1488 // 1->4: 0 4 8 12 16 20 24 28 1 5 9 13 17 21 25 29 2 6 10 ...
1489 // 4->8: 0 8 16 24 4 12 20 28 1 9 17 25 5 13 21 29 2 10 18 ...
1490 // 8->32: 0 8 16 24 4 12 20 28 1 9 17 25 5 13 21 29 2 10 18 ...
1491 HEADER_INLINE uint32_t VcountScramble1(uint32_t orig_idx) {
1492 return (orig_idx & (~31)) + ((orig_idx & 3) * 8) + (orig_idx & 4) + ((orig_idx & 24) / 8);
1493 }
1494 #endif
1495
1496 // change acc1 type to const void* if a VecW* use case arises
1497 HEADER_INLINE void VcountIncr1To4(const uintptr_t* acc1, uint32_t acc1_vec_ct, VecW* acc4_iter) {
1498 const VecW m1x4 = VCONST_W(kMask1111);
1499 const VecW* acc1_iter = R_CAST(const VecW*, acc1);
1500 for (uint32_t vidx = 0; vidx != acc1_vec_ct; ++vidx) {
1501 VecW loader = *acc1_iter++;
1502 *acc4_iter = (*acc4_iter) + (loader & m1x4);
1503 ++acc4_iter;
1504 loader = vecw_srli(loader, 1);
1505 *acc4_iter = (*acc4_iter) + (loader & m1x4);
1506 ++acc4_iter;
1507 loader = vecw_srli(loader, 1);
1508 *acc4_iter = (*acc4_iter) + (loader & m1x4);
1509 ++acc4_iter;
1510 loader = vecw_srli(loader, 1);
1511 *acc4_iter = (*acc4_iter) + (loader & m1x4);
1512 ++acc4_iter;
1513 }
1514 }
1515
1516 HEADER_INLINE void Vcount0Incr1To4(uint32_t acc1_vec_ct, uintptr_t* acc1, VecW* acc4_iter) {
1517 const VecW m1x4 = VCONST_W(kMask1111);
1518 VecW* acc1_iter = R_CAST(VecW*, acc1);
1519 for (uint32_t vidx = 0; vidx != acc1_vec_ct; ++vidx) {
1520 VecW loader = *acc1_iter;
1521 *acc1_iter++ = vecw_setzero();
1522 *acc4_iter = (*acc4_iter) + (loader & m1x4);
1523 ++acc4_iter;
1524 loader = vecw_srli(loader, 1);
1525 *acc4_iter = (*acc4_iter) + (loader & m1x4);
1526 ++acc4_iter;
1527 loader = vecw_srli(loader, 1);
1528 *acc4_iter = (*acc4_iter) + (loader & m1x4);
1529 ++acc4_iter;
1530 loader = vecw_srli(loader, 1);
1531 *acc4_iter = (*acc4_iter) + (loader & m1x4);
1532 ++acc4_iter;
1533 }
1534 }
1535
1536 // er, should this just be the same function as unroll_incr_2_4 with extra
1537 // parameters?...
1538 HEADER_INLINE void VcountIncr4To8(const VecW* acc4_iter, uint32_t acc4_vec_ct, VecW* acc8_iter) {
1539 const VecW m4 = VCONST_W(kMask0F0F);
1540 for (uint32_t vidx = 0; vidx != acc4_vec_ct; ++vidx) {
1541 VecW loader = *acc4_iter++;
1542 *acc8_iter = (*acc8_iter) + (loader & m4);
1543 ++acc8_iter;
1544 loader = vecw_srli(loader, 4);
1545 *acc8_iter = (*acc8_iter) + (loader & m4);
1546 ++acc8_iter;
1547 }
1548 }
1549
1550 HEADER_INLINE void Vcount0Incr4To8(uint32_t acc4_vec_ct, VecW* acc4_iter, VecW* acc8_iter) {
1551 const VecW m4 = VCONST_W(kMask0F0F);
1552 for (uint32_t vidx = 0; vidx != acc4_vec_ct; ++vidx) {
1553 VecW loader = *acc4_iter;
1554 *acc4_iter++ = vecw_setzero();
1555 *acc8_iter = (*acc8_iter) + (loader & m4);
1556 ++acc8_iter;
1557 loader = vecw_srli(loader, 4);
1558 *acc8_iter = (*acc8_iter) + (loader & m4);
1559 ++acc8_iter;
1560 }
1561 }
1562
1563 HEADER_INLINE void VcountIncr8To32(const VecW* acc8_iter, uint32_t acc8_vec_ct, VecW* acc32_iter) {
1564 const VecW m8x32 = VCONST_W(kMask000000FF);
1565 for (uint32_t vidx = 0; vidx != acc8_vec_ct; ++vidx) {
1566 VecW loader = *acc8_iter++;
1567 *acc32_iter = (*acc32_iter) + (loader & m8x32);
1568 ++acc32_iter;
1569 loader = vecw_srli(loader, 8);
1570 *acc32_iter = (*acc32_iter) + (loader & m8x32);
1571 ++acc32_iter;
1572 loader = vecw_srli(loader, 8);
1573 *acc32_iter = (*acc32_iter) + (loader & m8x32);
1574 ++acc32_iter;
1575 loader = vecw_srli(loader, 8);
1576 *acc32_iter = (*acc32_iter) + (loader & m8x32);
1577 ++acc32_iter;
1578 }
1579 }
1580
1581 HEADER_INLINE void Vcount0Incr8To32(uint32_t acc8_vec_ct, VecW* acc8_iter, VecW* acc32_iter) {
1582 const VecW m8x32 = VCONST_W(kMask000000FF);
1583 for (uint32_t vidx = 0; vidx != acc8_vec_ct; ++vidx) {
1584 VecW loader = *acc8_iter;
1585 *acc8_iter++ = vecw_setzero();
1586 *acc32_iter = (*acc32_iter) + (loader & m8x32);
1587 ++acc32_iter;
1588 loader = vecw_srli(loader, 8);
1589 *acc32_iter = (*acc32_iter) + (loader & m8x32);
1590 ++acc32_iter;
1591 loader = vecw_srli(loader, 8);
1592 *acc32_iter = (*acc32_iter) + (loader & m8x32);
1593 ++acc32_iter;
1594 loader = vecw_srli(loader, 8);
1595 *acc32_iter = (*acc32_iter) + (loader & m8x32);
1596 ++acc32_iter;
1597 }
1598 }
1599
1600 void VerticalCounterUpdate(const uintptr_t* acc1, uint32_t acc1_vec_ct, uint32_t* rem15_and_255d15, VecW* acc4_8_32);
1601
1602
1603 HEADER_INLINE uint32_t IdxToUidxBasic(const uintptr_t* bitvec, uint32_t idx) {
1604 return FindNth1BitFrom(bitvec, 0, idx + 1);
1605 }
1606
1607 HEADER_INLINE void ComputeUidxStartPartition(const uintptr_t* variant_include, uint64_t variant_ct, uint32_t thread_ct, uint32_t first_uidx, uint32_t* variant_uidx_starts) {
1608 FillU32SubsetStarts(variant_include, thread_ct, first_uidx, variant_ct, variant_uidx_starts);
1609 }
1610
1611 // These functions assume (bit_ct * (thread_ct - 1)) < 2^64.
1612 // bit_ct must be positive, but can be smaller than thread_ct
1613 // FillU32SubsetStarts moved to plink2_bits
1614
1615 void FillWStarts(uint32_t thread_ct, uintptr_t start, uint64_t bit_ct, uintptr_t* starts);
1616
1617 #ifdef __LP64__
1618 void FillWSubsetStarts(const uintptr_t* subset, uint32_t thread_ct, uintptr_t start, uint64_t bit_ct, uintptr_t* starts);
1619 #else
1620 HEADER_INLINE void FillWSubsetStarts(const uintptr_t* subset, uint32_t thread_ct, uintptr_t start, uint64_t bit_ct, uintptr_t* starts) {
1621 return FillU32SubsetStarts(subset, thread_ct, start, bit_ct, R_CAST(uint32_t*, starts));
1622 }
1623 #endif
1624
1625
1626
1627 // Set multiplier to 0 to only count extra alleles, 1 to also count alt1 for
1628 // those variants (useful for HWE), 2 to count both ref and alt1 for
1629 // multiallelic variants.
1630 // allele_idx_offsets == nullptr ok.
1631 uintptr_t CountExtraAlleles(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, uint32_t variant_uidx_start, uint32_t variant_uidx_end, uint32_t multiallelic_variant_ct_multiplier);
1632
1633 uint32_t MaxAlleleCtSubset(const uintptr_t* variant_include, const uintptr_t* allele_idx_offsets, uint32_t raw_variant_ct, uint32_t variant_ct, uint32_t max_allele_ct);
1634
1635 void ComputePartitionAligned(const uintptr_t* variant_include, uint32_t orig_thread_ct, uint32_t first_variant_uidx, uint32_t cur_variant_idx, uint32_t cur_variant_ct, uint32_t alignment, uint32_t* variant_uidx_starts, uint32_t* vidx_starts);
1636
1637 BoolErr ParseNextRange(const char* const* argvk, uint32_t param_ct, char range_delim, uint32_t* cur_param_idx_ptr, const char** cur_arg_pptr, const char** range_start_ptr, uint32_t* rs_len_ptr, const char** range_end_ptr, uint32_t* re_len_ptr);
1638
1639 PglErr ParseNameRanges(const char* const* argvk, const char* errstr_append, uint32_t param_ct, uint32_t require_posint, char range_delim, RangeList* range_list_ptr);
1640
1641
1642 // Analytically finds all real roots of x^3 + ax^2 + bx + c, saving them in
1643 // solutions[] (sorted from smallest to largest), and returning the count.
1644 // Multiple roots are only returned/counted once.
1645 uint32_t CubicRealRoots(double coef_a, double coef_b, double coef_c, STD_ARRAY_REF(double, 3) solutions);
1646
1647 HEADER_INLINE double PrevFloat64(double dxx) {
1648 uint64_t ullii;
1649 memcpy(&ullii, &dxx, 8);
1650 --ullii;
1651 memcpy(&dxx, &ullii, 8);
1652 return dxx;
1653 }
1654
1655 HEADER_INLINE double NextFloat64(double dxx) {
1656 uint64_t ullii;
1657 memcpy(&ullii, &dxx, 8);
1658 ++ullii;
1659 memcpy(&dxx, &ullii, 8);
1660 return dxx;
1661 }
1662
1663
1664 // Pass in htable_dup_base_ptr == nullptr if just flagging duplicate IDs rather
1665 // than tracking all their positions in item_ids.
1666 // Otherwise, htable_dup_base entries are guaranteed to be filled in increasing
1667 // order (briefly made that nondeterministic on 11 Oct 2019 and broke --rm-dup,
1668 // not doing that again).
1669 PglErr AllocAndPopulateIdHtableMt(const uintptr_t* subset_mask, const char* const* item_ids, uintptr_t item_ct, uintptr_t fast_size_min_extra_bytes, uint32_t max_thread_ct, uint32_t** id_htable_ptr, uint32_t** htable_dup_base_ptr, uint32_t* id_htable_size_ptr, uint32_t* dup_ct_ptr);
1670
1671 typedef struct HelpCtrlStruct {
1672 NONCOPYABLE(HelpCtrlStruct);
1673 uint32_t iters_left;
1674 uint32_t param_ct;
1675 const char* const* argv;
1676 uintptr_t unmatched_ct;
1677 uintptr_t* all_match_arr;
1678 uintptr_t* prefix_match_arr;
1679 uintptr_t* perfect_match_arr;
1680 uint32_t* param_slens;
1681 uint32_t preprint_newline;
1682 } HelpCtrl;
1683
1684 void HelpPrint(const char* cur_params, HelpCtrl* help_ctrl_ptr, uint32_t postprint_newline, const char* payload);
1685
1686
1687 extern const char kErrstrReadCorrupted[];
1688
1689 // 'r' in front for (file) read. We default to a generic "File appears to be
1690 // corrupted" message when the C-library I/O function calls succeed (so errno
1691 // is 0) but we determine that the logical contents of the file don't make
1692 // sense.
1693 HEADER_INLINE const char* rstrerror(int errnum) {
1694 if (errnum) {
1695 return strerror(errnum);
1696 }
1697 return kErrstrReadCorrupted;
1698 }
1699
1700 // assumes logfile is open
1701 void DispExitMsg(PglErr reterr);
1702
1703 BoolErr CheckExtraParam(const char* const* argvk, const char* permitted_modif, uint32_t* other_idx_ptr);
1704
1705 char ExtractCharParam(const char* ss);
1706
1707 PglErr CmdlineAllocString(const char* source, const char* flag_name, uint32_t max_slen, char** sbuf_ptr);
1708
1709 PglErr AllocFname(const char* source, const char* flagname_p, uint32_t extra_size, char** fnbuf_ptr);
1710
1711 PglErr AllocAndFlatten(const char* const* sources, uint32_t param_ct, uint32_t max_blen, char** flattened_buf_ptr);
1712
1713
1714 typedef struct Plink2CmdlineMetaStruct {
1715 NONCOPYABLE(Plink2CmdlineMetaStruct);
1716 // need to be able to assign this to argv, so don't make it const char**
1717 char** subst_argv;
1718
1719 char* script_buf;
1720 char* rerun_buf;
1721 char* flag_buf;
1722 uint32_t* flag_map;
1723 } Plink2CmdlineMeta;
1724
1725 void PreinitPlink2CmdlineMeta(Plink2CmdlineMeta* pcmp);
1726
1727 // Handles --script, --rerun, --help, --version, and --silent.
1728 // subst_argv, script_buf, and rerun_buf must be initialized to nullptr.
1729 PglErr CmdlineParsePhase1(const char* ver_str, const char* ver_str2, const char* prog_name_str, const char* notestr_null_calc2, const char* cmdline_format_str, const char* errstr_append, uint32_t max_flag_blen, PglErr(* disp_help_fn)(const char* const*, uint32_t), int* argc_ptr, char*** argv_ptr, Plink2CmdlineMeta* pcmp, uint32_t* first_arg_idx_ptr, uint32_t* flag_ct_ptr);
1730
1731 // Assumes CmdlineParsePhase1() has completed, flag names have been copied to
1732 // flag_buf/flag_map, aliases handled, and PROG_NAME_STR has been copied to
1733 // outname (no null-terminator needed). outname_end must be initialized to
1734 // nullptr.
1735 // This sorts the flag names so they're processed in a predictable order,
1736 // handles --d/--out/--strict-extra-chr if present, initializes the log, and
1737 // determines the number of processors the OS wants us to think the machine
1738 // has.
1739 PglErr CmdlineParsePhase2(const char* ver_str, const char* errstr_append, const char* const* argvk, uint32_t prog_name_str_slen, uint32_t max_flag_blen, int32_t argc, uint32_t flag_ct, Plink2CmdlineMeta* pcmp, char* outname, char** outname_end_ptr, char* range_delim_ptr, uint32_t* strict_extra_chr_ptr, int32_t* known_procs_ptr, uint32_t* max_thread_ct_ptr);
1740
1741 HEADER_INLINE void InvalidArg(const char* cur_arg) {
1742 logpreprintfww("Error: Unrecognized flag ('%s').\n", cur_arg);
1743 }
1744
1745 PglErr CmdlineParsePhase3(uintptr_t max_default_mib, uintptr_t malloc_size_mib, uint32_t memory_require, Plink2CmdlineMeta* pcmp, unsigned char** bigstack_ua_ptr);
1746
1747 void CleanupPlink2CmdlineMeta(Plink2CmdlineMeta* pcmp);
1748
1749 // order is such that (kCmpOperatorEq - x) is the inverse of x
1750 ENUM_U31_DEF_START()
1751 kCmpOperatorNoteq,
1752 kCmpOperatorLe,
1753 kCmpOperatorLeq,
1754
1755 kCmpOperatorGe,
1756 kCmpOperatorGeq,
1757 kCmpOperatorEq
1758 ENUM_U31_DEF_END(CmpBinaryOp);
1759
1760 typedef struct CmpExprStruct {
1761 // arguably too small for noncopyable to be a great idea, but the next
1762 // iteration of this struct probably won't have that issue.
1763 NONCOPYABLE(CmpExprStruct);
1764 // Restrict to <key> <operator> <value> for now; key=INFO/pheno/covar.
1765 //
1766 // Almost certainly want to support conjunctions/disjunctions later; but
1767 // there are complications regarding the command-line interface:
1768 // * Phenotype/covariate names and VCFv4.2 INFO keys can contain parenthesis
1769 // and mathematical-operator characters. And we actually need to permit at
1770 // least the latter, since autogenerated categorical-covariate names
1771 // contain '=' for a good reason. Some sort of escaping is probably in
1772 // in order, but...
1773 // * Escaping is not a big deal in a shell script, but most
1774 // conjunctions/disjunctions can already be emulated easily enough in a
1775 // shell script by calling plink2 multiple times. While there's some
1776 // execution-time improvement, the main value-add from directly supporting
1777 // logical operations in --keep-if/--extract-if-info is reduced
1778 // interactive-use cognitive load.
1779 // * We can't treat multiple command-line arguments differently from the
1780 // corresponding space-containing single command-line argument; otherwise
1781 // --rerun breaks. So "multiple-argument-form supports keys with special
1782 // characters but not conjunctions/disjunctions; single-argument-form is
1783 // the other way around" is not an option.
1784 // The least-bad solution I've thought of is to add --keep-if-file/etc. flags
1785 // which read the expression from a short text file. In that case, we'd at
1786 // least be able to define normal quoting and escaping rules without worrying
1787 // about confusing interactions with bash. Deferring implementation for now
1788 // in hopes of coming up with a better idea, but this should go in before
1789 // beta testing begins.
1790
1791 // Currently stores null-terminated key, followed by null-terminated value
1792 // string. Storage format needs to be synced with ValidateAndAllocCmpExpr().
1793 char* pheno_name;
1794 CmpBinaryOp binary_op;
1795 } CmpExpr;
1796
1797 void InitCmpExpr(CmpExpr* cmp_expr_ptr);
1798
1799 void CleanupCmpExpr(CmpExpr* cmp_expr_ptr);
1800
1801 PglErr ValidateAndAllocCmpExpr(const char* const* sources, const char* flag_name, uint32_t param_ct, CmpExpr* cmp_expr_ptr);
1802
1803 PglErr SearchHeaderLine(const char* header_line_iter, const char* const* search_multistrs, const char* flag_nodash, uint32_t search_col_ct, uint32_t* found_col_ct_ptr, uint32_t* found_type_bitset_ptr, uint32_t* col_skips, uint32_t* col_types);
1804
1805 // col_descriptor is usually a pointer to argv[...][5] (first five characters
1806 // are "cols="). supported_ids is a multistr.
1807 PglErr ParseColDescriptor(const char* col_descriptor_iter, const char* supported_ids, const char* cur_flag_name, uint32_t first_col_shifted, uint32_t default_cols_mask, uint32_t prohibit_empty, void* result_ptr);
1808
1809
1810 // this is technically application-dependent, but let's keep this simple for
1811 // now
1812 // todo: recalibrate these numbers before each beta release
1813 #ifndef __LP64__
1814 // 2047 seems to consistently fail on both OS X and Windows
1815 # ifdef _WIN32
1816 CONSTI32(kMalloc32bitMibMax, 1728);
1817 # else
1818 # ifdef __APPLE__
1819 CONSTI32(kMalloc32bitMibMax, 1888);
1820 # else
1821 CONSTI32(kMalloc32bitMibMax, 2047);
1822 # endif
1823 # endif
1824 #endif
1825
1826
1827
1828 #ifdef __cplusplus
1829 } // namespace plink2
1830 #endif
1831
1832 #endif // __PLINK2_CMDLINE_H__