Debian Codegraph @

plink2_cmdline.cc

raw
1 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
2 // Christopher Chang.
3 //
4 // This library is free software: you can redistribute it and/or modify it
5 // under the terms of the GNU Lesser General Public License as published by the
6 // Free Software Foundation; either version 3 of the License, or (at your
7 // option) any later version.
8 //
9 // This library is distributed in the hope that it will be useful, but WITHOUT
10 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 // for more details.
13 //
14 // You should have received a copy of the GNU Lesser General Public License
15 // along with this library. If not, see <http://www.gnu.org/licenses/>.
16
17
18 #include "plink2_cmdline.h"
19
20 #include <sys/types.h> // open()
21 #include <sys/stat.h> // open()
22 #include <fcntl.h> // open()
23 #include <time.h> // time(), ctime()
24 #include <unistd.h> // getcwd(), gethostname(), sysconf(), fstat()
25
26 #ifdef __cplusplus
27 namespace plink2 {
28 #endif
29
30 char g_textbuf[kTextbufSize];
31
32 // now initialized by init_bigstack
33 // can't use std::array<char, 512>& since it's initially null
34 const char* g_one_char_strs = nullptr;
35 // If one-base indels become sufficiently common, might want to predefine
36 // g_two_char_strs[], and update allele string construction/destruction
37 // accordingly.
38
39 FILE* g_logfile = nullptr;
40
41 char g_logbuf[kLogbufSize];
42
43 uint32_t g_debug_on = 0;
44 uint32_t g_log_failed = 0;
45 uint32_t g_stderr_written_to = 0;
46
47 void logputs_silent(const char* str) {
48 if (!g_debug_on) {
49 fputs(str, g_logfile);
50 if (unlikely(ferror_unlocked(g_logfile))) {
51 putchar('\n');
52 fflush(stdout);
53 fprintf(stderr, "Warning: Logging failure on:\n%s\nFurther logging will not be attempted in this run.\n", str);
54 g_log_failed = 1;
55 }
56 } else {
57 if (g_log_failed) {
58 fflush(stdout);
59 fputs(str, stderr);
60 } else {
61 fputs(str, g_logfile);
62 if (unlikely(ferror_unlocked(g_logfile))) {
63 putchar('\n');
64 fflush(stdout);
65 fprintf(stderr, "Error: Debug logging failure. Dumping to stderr:\n%s", str);
66 g_log_failed = 1;
67 g_stderr_written_to = 1;
68 } else {
69 fflush(g_logfile);
70 }
71 }
72 }
73 }
74
75 void logputs(const char* str) {
76 logputs_silent(str);
77 fputs(str, stdout);
78 }
79
80 void logerrputs(const char* str) {
81 logputs_silent(str);
82 fflush(stdout);
83 fputs(str, stderr);
84 g_stderr_written_to = 1;
85 }
86
87 void logputsb() {
88 logputs_silent(g_logbuf);
89 fputs(g_logbuf, stdout);
90 }
91
92 void logerrputsb() {
93 logputs_silent(g_logbuf);
94 fflush(stdout);
95 fputs(g_logbuf, stderr);
96 g_stderr_written_to = 1;
97 }
98
99 PglErr ForceNonFifo(const char* fname) {
100 int32_t file_handle = open(fname, O_RDONLY);
101 if (unlikely(file_handle < 0)) {
102 return kPglRetOpenFail;
103 }
104 struct stat statbuf;
105 if (unlikely(fstat(file_handle, &statbuf) < 0)) {
106 close(file_handle);
107 return kPglRetOpenFail;
108 }
109 if (unlikely(S_ISFIFO(statbuf.st_mode))) {
110 close(file_handle);
111 return kPglRetRewindFail;
112 }
113 close(file_handle);
114 return kPglRetSuccess;
115 }
116
117 BoolErr fopen_checked(const char* fname, const char* mode, FILE** target_ptr) {
118 /*
119 if (!strcmp(mode, FOPEN_WB)) {
120 // The fopen call may take a long time to return when overwriting in mode
121 // "w" in some scenarios on some OSes (I've seen 15+ sec). On the other
122 // hand, sometimes it returns immediately and then writing takes less time.
123 // Since it goes both ways, I won't second-guess the OSes for now;
124 // presumably they're trying to minimize average amortized time. But it
125 // might be worth retesting in the future; perhaps some common plink
126 // workflows violate normally-reasonable OS assumptions.
127 if (access(fname, W_OK) != -1) {
128 if (unlikely(unlink(fname))) {
129 logputs("\n");
130 logerrprintfww(kErrprintfFopen, fname, strerror(errno));
131 return 1;
132 }
133 }
134 }
135 */
136 *target_ptr = fopen(fname, mode);
137 if (unlikely(!(*target_ptr))) {
138 logputs("\n");
139 logerrprintfww(kErrprintfFopen, fname, strerror(errno));
140 return 1;
141 }
142 return 0;
143 }
144
145 BoolErr fwrite_flush2(char* buf_flush, FILE* outfile, char** write_iter_ptr) {
146 char* buf = &(buf_flush[-S_CAST(int32_t, kMaxMediumLine)]);
147 char* buf_end = *write_iter_ptr;
148 *write_iter_ptr = buf;
149 return fwrite_checked(buf, buf_end - buf, outfile);
150 }
151
152 BoolErr fclose_flush_null(char* buf_flush, char* write_iter, FILE** outfile_ptr) {
153 char* buf = &(buf_flush[-S_CAST(int32_t, kMaxMediumLine)]);
154 if (write_iter != buf) {
155 if (unlikely(fwrite_checked(buf, write_iter - buf, *outfile_ptr))) {
156 return 1;
157 }
158 }
159 return fclose_null(outfile_ptr);
160 }
161
162
163 int32_t u32cmp(const void* aa, const void* bb) {
164 const uint32_t uaa = *S_CAST(const uint32_t*, aa);
165 const uint32_t ubb = *S_CAST(const uint32_t*, bb);
166 if (uaa < ubb) {
167 return -1;
168 }
169 return (uaa > ubb);
170 }
171
172 int32_t float_cmp(const void* aa, const void* bb) {
173 const float fxx = *S_CAST(const float*, aa);
174 const float fyy = *S_CAST(const float*, bb);
175 if (fxx < fyy) {
176 return -1;
177 }
178 return (fxx > fyy);
179 }
180
181 int32_t double_cmp(const void* aa, const void* bb) {
182 const double dxx = *S_CAST(const double*, aa);
183 const double dyy = *S_CAST(const double*, bb);
184 if (dxx < dyy) {
185 return -1;
186 }
187 return (dxx > dyy);
188 }
189
190 int32_t double_cmp_decr(const void* aa, const void* bb) {
191 const double dxx = *S_CAST(const double*, aa);
192 const double dyy = *S_CAST(const double*, bb);
193 if (dxx > dyy) {
194 return -1;
195 }
196 return (dxx < dyy);
197 }
198
199 int32_t u64cmp(const void* aa, const void* bb) {
200 const uint64_t ullaa = *S_CAST(const uint64_t*, aa);
201 const uint64_t ullbb = *S_CAST(const uint64_t*, bb);
202 if (ullaa < ullbb) {
203 return -1;
204 }
205 return (ullaa > ullbb);
206 }
207
208 #ifndef __cplusplus
209 int32_t u64cmp_decr(const void* aa, const void* bb) {
210 const uint64_t ullaa = *S_CAST(const uint64_t*, aa);
211 const uint64_t ullbb = *S_CAST(const uint64_t*, bb);
212 if (ullaa > ullbb) {
213 return -1;
214 }
215 return (ullaa < ullbb);
216 }
217 #endif
218
219 #ifdef __cplusplus
220 float DestructiveMedianF(uintptr_t len, float* unsorted_arr) {
221 if (!len) {
222 return 0.0;
223 }
224 const uintptr_t len_d2 = len / 2;
225 std::nth_element(unsorted_arr, &(unsorted_arr[len_d2]), &(unsorted_arr[len]));
226 const float median_upper = unsorted_arr[len_d2];
227 if (len % 2) {
228 return median_upper;
229 }
230 return (FArrMax(unsorted_arr, len_d2) + median_upper) * 0.5f;
231 }
232
233 double DestructiveMedianD(uintptr_t len, double* unsorted_arr) {
234 if (!len) {
235 return 0.0;
236 }
237 const uintptr_t len_d2 = len / 2;
238 std::nth_element(unsorted_arr, &(unsorted_arr[len_d2]), &(unsorted_arr[len]));
239 const double median_upper = unsorted_arr[len_d2];
240 if (len % 2) {
241 return median_upper;
242 }
243 return (DArrMax(unsorted_arr, len_d2) + median_upper) * 0.5;
244 }
245 #else
246 // these will probably be used in __cplusplus case too
247 float MedianF(const float* sorted_arr, uintptr_t len) {
248 if (!len) {
249 return 0.0;
250 }
251 if (len % 2) {
252 return sorted_arr[len / 2];
253 }
254 return (sorted_arr[len / 2] + sorted_arr[(len / 2) - 1]) * 0.5f;
255 }
256
257 double MedianD(const double* sorted_arr, uintptr_t len) {
258 if (!len) {
259 return 0.0;
260 }
261 if (len % 2) {
262 return sorted_arr[len / 2];
263 }
264 return (sorted_arr[len / 2] + sorted_arr[(len / 2) - 1]) * 0.5;
265 }
266
267 float DestructiveMedianF(uintptr_t len, float* unsorted_arr) {
268 // no, I'm not gonna bother reimplementing introselect just for folks who
269 // insist on compiling this as pure C instead of C++
270 qsort(unsorted_arr, len, sizeof(float), float_cmp);
271 return MedianF(unsorted_arr, len);
272 }
273
274 double DestructiveMedianD(uintptr_t len, double* unsorted_arr) {
275 qsort(unsorted_arr, len, sizeof(double), double_cmp);
276 return MedianD(unsorted_arr, len);
277 }
278 #endif
279
280
281 // Overread must be ok.
282 BoolErr SortStrboxIndexed(uintptr_t str_ct, uintptr_t max_str_blen, uint32_t use_nsort, char* strbox, uint32_t* id_map) {
283 if (str_ct < 2) {
284 return 0;
285 }
286 unsigned char* bigstack_mark = g_bigstack_base;
287 const uintptr_t wkspace_entry_blen = GetStrboxsortWentryBlen(max_str_blen);
288 unsigned char* sort_wkspace;
289 if (unlikely(bigstack_alloc_uc(str_ct * wkspace_entry_blen, &sort_wkspace))) {
290 return 1;
291 }
292 SortStrboxIndexed2(str_ct, max_str_blen, use_nsort, strbox, id_map, sort_wkspace);
293 BigstackReset(bigstack_mark);
294 return 0;
295 }
296
297 uintptr_t LowerBoundNonemptyU32(const uint32_t* sorted_u32_arr, uintptr_t arr_length, uint32_t needle) {
298 // This is still benchmarking better than std::lower_bound on macOS as of 16
299 // Sep 2023. Also beats start/end indexing, by a smaller margin. I'm
300 // guessing the edge comes from the last-iteration branch that is avoided
301 // (and that's where the "nonempty" restriction comes from).
302 uintptr_t min_idx = 0;
303 // max_idx is either the last index that might compare less than needle, or
304 // -1 if there can't be any. It can drop to min_idx - 1.
305 uintptr_t max_idx = arr_length - 1;
306 while (S_CAST(intptr_t, min_idx) < S_CAST(intptr_t, max_idx)) {
307 const uintptr_t mid_idx = (min_idx + max_idx) / 2;
308 if (needle > sorted_u32_arr[mid_idx]) {
309 min_idx = mid_idx + 1;
310 } else {
311 max_idx = mid_idx - 1;
312 }
313 }
314 return min_idx + (needle > sorted_u32_arr[min_idx]);
315 }
316
317 uintptr_t Expsearch0U32(const uint32_t* sorted_u32_arr, uintptr_t end_idx, uint32_t needle) {
318 uintptr_t next_incr = 1;
319 uintptr_t start_idx = 0;
320 uintptr_t cur_idx = 0;
321 while (cur_idx < end_idx) {
322 if (sorted_u32_arr[cur_idx] >= needle) {
323 end_idx = cur_idx;
324 break;
325 }
326 start_idx = cur_idx + 1;
327 cur_idx += next_incr;
328 next_incr *= 2;
329 }
330 while (start_idx < end_idx) {
331 const uintptr_t mid_idx = (start_idx + end_idx) / 2;
332 if (sorted_u32_arr[mid_idx] < needle) {
333 start_idx = mid_idx + 1;
334 } else {
335 end_idx = mid_idx;
336 }
337 }
338 return start_idx;
339 }
340
341 #ifdef __LP64__
342 uintptr_t Expsearch0U64(const uint64_t* sorted_u64_arr, uintptr_t end_idx, uint64_t needle) {
343 uintptr_t next_incr = 1;
344 uintptr_t start_idx = 0;
345 uintptr_t cur_idx = 0;
346 while (cur_idx < end_idx) {
347 if (sorted_u64_arr[cur_idx] >= needle) {
348 end_idx = cur_idx;
349 break;
350 }
351 start_idx = cur_idx + 1;
352 cur_idx += next_incr;
353 next_incr *= 2;
354 }
355 while (start_idx < end_idx) {
356 const uintptr_t mid_idx = (start_idx + end_idx) / 2;
357 if (sorted_u64_arr[mid_idx] < needle) {
358 start_idx = mid_idx + 1;
359 } else {
360 end_idx = mid_idx;
361 }
362 }
363 return start_idx;
364 }
365 #endif
366
367 uintptr_t LowerBoundNonemptyU64(const uint64_t* sorted_u64_arr, uintptr_t arr_length, uint64_t needle) {
368 uintptr_t min_idx = 0;
369 uintptr_t max_idx = arr_length - 1;
370 while (S_CAST(intptr_t, min_idx) < S_CAST(intptr_t, max_idx)) {
371 const uintptr_t mid_idx = (min_idx + max_idx) / 2;
372 if (needle > sorted_u64_arr[mid_idx]) {
373 min_idx = mid_idx + 1;
374 } else {
375 max_idx = mid_idx - 1;
376 }
377 }
378 return min_idx + (needle > sorted_u64_arr[min_idx]);
379 }
380
381 uintptr_t LowerBoundNonemptyD(const double* sorted_dbl_arr, uintptr_t arr_length, double needle) {
382 uintptr_t min_idx = 0;
383 uintptr_t max_idx = arr_length - 1;
384 while (S_CAST(intptr_t, min_idx) < S_CAST(intptr_t, max_idx)) {
385 const uintptr_t mid_idx = (min_idx + max_idx) / 2;
386 if (needle > sorted_dbl_arr[mid_idx]) {
387 min_idx = mid_idx + 1;
388 } else {
389 max_idx = mid_idx - 1;
390 }
391 }
392 return min_idx + (needle > sorted_dbl_arr[min_idx]);
393 }
394
395 uintptr_t Expsearch0D(const double* sorted_dbl_arr, uintptr_t end_idx, double needle) {
396 uintptr_t next_incr = 1;
397 uintptr_t start_idx = 0;
398 uintptr_t cur_idx = 0;
399 while (cur_idx < end_idx) {
400 if (sorted_dbl_arr[cur_idx] >= needle) {
401 end_idx = cur_idx;
402 break;
403 }
404 start_idx = cur_idx + 1;
405 cur_idx += next_incr;
406 next_incr *= 2;
407 }
408 while (start_idx < end_idx) {
409 const uintptr_t mid_idx = (start_idx + end_idx) / 2;
410 if (sorted_dbl_arr[mid_idx] < needle) {
411 start_idx = mid_idx + 1;
412 } else {
413 end_idx = mid_idx;
414 }
415 }
416 return start_idx;
417 }
418
419 uintptr_t UpperBoundNonemptyU32(const uint32_t* sorted_u32_arr, uintptr_t arr_length, uint32_t needle) {
420 uintptr_t min_idx = 0;
421 uintptr_t max_idx = arr_length - 1;
422 while (S_CAST(intptr_t, min_idx) < S_CAST(intptr_t, max_idx)) {
423 const uintptr_t mid_idx = (min_idx + max_idx) / 2;
424 if (needle >= sorted_u32_arr[mid_idx]) {
425 min_idx = mid_idx + 1;
426 } else {
427 max_idx = mid_idx - 1;
428 }
429 }
430 return min_idx + (needle >= sorted_u32_arr[min_idx]);
431 }
432
433 uintptr_t UpperBoundNonemptyU64(const uint64_t* sorted_u64_arr, uintptr_t arr_length, uint64_t needle) {
434 uintptr_t min_idx = 0;
435 uintptr_t max_idx = arr_length - 1;
436 while (S_CAST(intptr_t, min_idx) < S_CAST(intptr_t, max_idx)) {
437 const uintptr_t mid_idx = (min_idx + max_idx) / 2;
438 if (needle >= sorted_u64_arr[mid_idx]) {
439 min_idx = mid_idx + 1;
440 } else {
441 max_idx = mid_idx - 1;
442 }
443 }
444 return min_idx + (needle >= sorted_u64_arr[min_idx]);
445 }
446
447 uint32_t IdxToUidx(const uintptr_t* bitvec, const uint32_t* cumulative_popcounts, uint32_t widx_start, uint32_t widx_end, uint32_t idx) {
448 if (widx_end > widx_start) {
449 widx_start = LastLeqU32(cumulative_popcounts, widx_start, widx_end, idx);
450 }
451 const uint32_t idx_at_widx_start = cumulative_popcounts[widx_start];
452 return widx_start * kBitsPerWord + WordBitIdxToUidx(bitvec[widx_start], idx - idx_at_widx_start);
453 }
454
455 uintptr_t IdxToUidxW(const uintptr_t* bitvec, const uintptr_t* cumulative_popcounts, uintptr_t widx_start, uintptr_t widx_end, uintptr_t idx) {
456 if (widx_end > widx_start) {
457 widx_start = LastLeqW(cumulative_popcounts, widx_start, widx_end, idx);
458 }
459 const uintptr_t idx_at_widx_start = cumulative_popcounts[widx_start];
460 return widx_start * kBitsPerWord + WordBitIdxToUidx(bitvec[widx_start], idx - idx_at_widx_start);
461 }
462
463 uint32_t ExpsearchIdxToUidx(const uintptr_t* bitvec, const uint32_t* cumulative_popcounts, uint32_t widx_end, uint32_t idx, uint32_t* widx_startp) {
464 uint32_t widx_start = *widx_startp;
465 if (widx_end > widx_start) {
466 widx_start = ExpsearchLastLeqU32(cumulative_popcounts, widx_start, widx_end, idx);
467 *widx_startp = widx_start;
468 }
469 const uint32_t idx_at_widx_start = cumulative_popcounts[widx_start];
470 return widx_start * kBitsPerWord + WordBitIdxToUidx(bitvec[widx_start], idx - idx_at_widx_start);
471 }
472
473 uintptr_t ExpsearchIdxToUidxW(const uintptr_t* bitvec, const uintptr_t* cumulative_popcounts, uintptr_t widx_end, uintptr_t idx, uintptr_t* widx_startp) {
474 uintptr_t widx_start = *widx_startp;
475 if (widx_end > widx_start) {
476 widx_start = ExpsearchLastLeqW(cumulative_popcounts, widx_start, widx_end, idx);
477 *widx_startp = widx_start;
478 }
479 const uintptr_t idx_at_widx_start = cumulative_popcounts[widx_start];
480 return widx_start * kBitsPerWord + WordBitIdxToUidx(bitvec[widx_start], idx - idx_at_widx_start);
481 }
482
483 uint32_t GetParamCt(const char* const* argvk, uint32_t argc, uint32_t flag_idx) {
484 // Counts the number of optional arguments given to the flag at position
485 // flag_idx, treating any nonnumeric argument beginning with "-" as optional.
486 ++flag_idx;
487 uint32_t cur_idx = flag_idx;
488 while ((cur_idx < argc) && (!IsCmdlineFlag(argvk[cur_idx]))) {
489 ++cur_idx;
490 }
491 return cur_idx - flag_idx;
492 }
493
494 BoolErr EnforceParamCtRange(const char* flag_name, uint32_t param_ct, uint32_t min_ct, uint32_t max_ct) {
495 if (unlikely(param_ct > max_ct)) {
496 if (max_ct > min_ct) {
497 snprintf(g_logbuf, kLogbufSize, "Error: %s accepts at most %u argument%s.\n", flag_name, max_ct, (max_ct == 1)? "" : "s");
498 } else {
499 snprintf(g_logbuf, kLogbufSize, "Error: %s only accepts %u argument%s.\n", flag_name, max_ct, (max_ct == 1)? "" : "s");
500 }
501 return 1;
502 }
503 if (likely(param_ct >= min_ct)) {
504 return 0;
505 }
506 if (min_ct == 1) {
507 snprintf(g_logbuf, kLogbufSize, "Error: Missing %s argument.\n", flag_name);
508 } else {
509 snprintf(g_logbuf, kLogbufSize, "Error: %s requires %s%u arguments.\n", flag_name, (min_ct < max_ct)? "at least " : "", min_ct);
510 }
511 return 1;
512 }
513
514 PglErr SortCmdlineFlags(uint32_t max_flag_blen, uint32_t flag_ct, char* flag_buf, uint32_t* flag_map) {
515 // Assumes flag_ct is the number of flag (as opposed to value) arguments,
516 // flag_buf[] points to a rectangular char* array (width max_flag_blen) of
517 // flag names with leading dash(es) stripped, and flag_map[] maps flag_buf[]
518 // entries to argv[] entries.
519 // Lexicographically sorts flag_buf (updating flag_map in the process), and
520 // then checks for duplicates.
521 // Okay for flag_buf to contain entries with spaces (plink 1.9's alias
522 // resolution takes advantage of this).
523 assert(flag_ct); // this must be skipped if there are no flags at all
524 if (unlikely(SortStrboxIndexedMalloc(flag_ct, max_flag_blen, flag_buf, flag_map))) {
525 return kPglRetNomem;
526 }
527 uint32_t prev_flag_len = strlen_se(flag_buf);
528 char* prev_flag_ptr = flag_buf;
529 for (uint32_t cur_flag_idx = 1; cur_flag_idx != flag_ct; ++cur_flag_idx) {
530 char* cur_flag_ptr = &(prev_flag_ptr[max_flag_blen]);
531 const uint32_t cur_flag_len = strlen_se(cur_flag_ptr);
532 if (unlikely((prev_flag_len == cur_flag_len) && memequal(prev_flag_ptr, cur_flag_ptr, cur_flag_len))) {
533 cur_flag_ptr[cur_flag_len] = '\0'; // just in case of aliases
534 fflush(stdout);
535 fprintf(stderr, "Error: Duplicate --%s flag.\n", cur_flag_ptr);
536 // g_stderr_written_to = 1;
537 return kPglRetInvalidCmdline;
538 }
539 prev_flag_ptr = cur_flag_ptr;
540 prev_flag_len = cur_flag_len;
541 }
542 return kPglRetSuccess;
543 }
544
545 PglErr InitLogfile(uint32_t always_stderr, char* outname, char* outname_end) {
546 snprintf(outname_end, kMaxOutfnameExtBlen, ".log");
547 g_logfile = fopen(outname, "w");
548 if (unlikely(!g_logfile)) {
549 fflush(stdout);
550 fprintf(stderr, "Error: Failed to open %s for logging: %s.\n", outname, strerror(errno));
551 // g_stderr_written_to = 1;
552 return kPglRetOpenFail;
553 }
554 fprintf(always_stderr? stderr : stdout, "Logging to %s.\n", outname);
555 return kPglRetSuccess;
556 }
557
558 BoolErr CleanupLogfile(uint32_t print_end_time) {
559 char* write_iter = strcpya_k(g_logbuf, "End time: ");
560 time_t rawtime;
561 time(&rawtime);
562 write_iter = Stpcpy(write_iter, ctime(&rawtime)); // has trailing \n
563 if (print_end_time) {
564 fputs(g_logbuf, stdout);
565 }
566 BoolErr ret_boolerr = 0;
567 if (g_logfile) {
568 if (!g_log_failed) {
569 logputs_silent("\n");
570 logputs_silent(g_logbuf);
571 if (unlikely(fclose(g_logfile))) {
572 fflush(stdout);
573 fprintf(stderr, "Error: Failed to finish writing to log: %s.\n", strerror(errno));
574 ret_boolerr = 1;
575 }
576 } else {
577 fclose(g_logfile);
578 }
579 g_logfile = nullptr;
580 }
581 return ret_boolerr;
582 }
583
584 // manually managed, very large stack
585 unsigned char* g_bigstack_base = nullptr;
586 unsigned char* g_bigstack_end = nullptr;
587
588 uintptr_t GetDefaultAllocMib() {
589 const uint64_t total_mib = DetectMib();
590 if (!total_mib) {
591 return kBigstackDefaultMib;
592 }
593 if (total_mib < (kBigstackMinMib * 2)) {
594 return kBigstackMinMib;
595 }
596 #ifdef __LP64__
597 return (total_mib / 2);
598 #else
599 // theoretically possible for a 32-bit app to run on a system with a ton of
600 // memory?
601 return MINV(2047, total_mib / 2);
602 #endif
603 }
604
605 PglErr InitBigstack(uintptr_t malloc_size_mib, uintptr_t* malloc_mib_final_ptr, unsigned char** bigstack_ua_ptr) {
606 // guarantee contiguous malloc space outside of main workspace
607 unsigned char* bubble;
608
609 // this is pointless with overcommit on, may want to conditionally compile
610 // this out, and/or conditionally skip this
611 if (unlikely(pgl_malloc(kNonBigstackMin, &bubble))) {
612 return kPglRetNomem;
613 }
614
615 assert(malloc_size_mib >= kBigstackMinMib);
616 #ifndef __LP64__
617 assert(malloc_size_mib <= 2047);
618 #endif
619 // don't use pgl_malloc here since we don't automatically want to set
620 // g_failed_alloc_attempt_size on failure
621 unsigned char* bigstack_ua = S_CAST(unsigned char*, malloc(malloc_size_mib * 1048576 * sizeof(char)));
622 // this is thwarted by overcommit, but still better than nothing...
623 while (!bigstack_ua) {
624 malloc_size_mib = (malloc_size_mib * 3) / 4;
625 if (malloc_size_mib < kBigstackMinMib) {
626 malloc_size_mib = kBigstackMinMib;
627 }
628 bigstack_ua = S_CAST(unsigned char*, malloc(malloc_size_mib * 1048576 * sizeof(char)));
629 if (unlikely((!bigstack_ua) && (malloc_size_mib == kBigstackMinMib))) {
630 // switch to "goto cleanup" pattern if any more exit points are needed
631 g_failed_alloc_attempt_size = kBigstackMinMib * 1048576;
632 free(bubble);
633 return kPglRetNomem;
634 }
635 }
636 // force 64-byte align to make cache line sensitivity work
637 unsigned char* bigstack_initial_base = R_CAST(unsigned char*, RoundUpPow2(R_CAST(uintptr_t, bigstack_ua), kCacheline));
638 g_bigstack_base = bigstack_initial_base;
639 // last 576 bytes now reserved for g_one_char_strs + overread buffer
640 g_bigstack_end = &(bigstack_initial_base[RoundDownPow2(malloc_size_mib * 1048576 - 576 - S_CAST(uintptr_t, bigstack_initial_base - bigstack_ua), kCacheline)]);
641 free(bubble);
642 uintptr_t* one_char_iter = R_CAST(uintptr_t*, g_bigstack_end);
643 #ifdef __LP64__
644 // assumes little-endian
645 uintptr_t cur_word = 0x3000200010000LLU;
646 for (uint32_t uii = 0; uii != 64; ++uii) {
647 *one_char_iter++ = cur_word;
648 cur_word += 0x4000400040004LLU;
649 }
650 #else
651 uintptr_t cur_word = 0x10000;
652 for (uint32_t uii = 0; uii != 128; ++uii) {
653 *one_char_iter++ = cur_word;
654 cur_word += 0x20002;
655 }
656 #endif
657 g_one_char_strs = R_CAST(const char*, g_bigstack_end);
658
659 *malloc_mib_final_ptr = malloc_size_mib;
660 *bigstack_ua_ptr = bigstack_ua;
661 return kPglRetSuccess;
662 }
663
664
665 BoolErr bigstack_calloc_uc(uintptr_t ct, unsigned char** uc_arr_ptr) {
666 *uc_arr_ptr = S_CAST(unsigned char*, bigstack_alloc(ct));
667 if (unlikely(!(*uc_arr_ptr))) {
668 return 1;
669 }
670 memset(*uc_arr_ptr, 0, ct);
671 return 0;
672 }
673
674 BoolErr bigstack_calloc_d(uintptr_t ct, double** d_arr_ptr) {
675 *d_arr_ptr = S_CAST(double*, bigstack_alloc(ct * sizeof(double)));
676 if (unlikely(!(*d_arr_ptr))) {
677 return 1;
678 }
679 ZeroDArr(ct, *d_arr_ptr);
680 return 0;
681 }
682
683 BoolErr bigstack_calloc_f(uintptr_t ct, float** f_arr_ptr) {
684 *f_arr_ptr = S_CAST(float*, bigstack_alloc(ct * sizeof(float)));
685 if (unlikely(!(*f_arr_ptr))) {
686 return 1;
687 }
688 ZeroFArr(ct, *f_arr_ptr);
689 return 0;
690 }
691
692 BoolErr bigstack_calloc_u16(uintptr_t ct, uint16_t** u16_arr_ptr) {
693 *u16_arr_ptr = S_CAST(uint16_t*, bigstack_alloc(ct * sizeof(int16_t)));
694 if (unlikely(!(*u16_arr_ptr))) {
695 return 1;
696 }
697 memset(*u16_arr_ptr, 0, ct * sizeof(int16_t));
698 return 0;
699 }
700
701 BoolErr bigstack_calloc_u32(uintptr_t ct, uint32_t** u32_arr_ptr) {
702 *u32_arr_ptr = S_CAST(uint32_t*, bigstack_alloc(ct * sizeof(int32_t)));
703 if (unlikely(!(*u32_arr_ptr))) {
704 return 1;
705 }
706 ZeroU32Arr(ct, *u32_arr_ptr);
707 return 0;
708 }
709
710 BoolErr bigstack_calloc_w(uintptr_t ct, uintptr_t** w_arr_ptr) {
711 *w_arr_ptr = S_CAST(uintptr_t*, bigstack_alloc(ct * sizeof(intptr_t)));
712 if (unlikely(!(*w_arr_ptr))) {
713 return 1;
714 }
715 ZeroWArr(ct, *w_arr_ptr);
716 return 0;
717 }
718
719 BoolErr bigstack_calloc_u64(uintptr_t ct, uint64_t** u64_arr_ptr) {
720 *u64_arr_ptr = S_CAST(uint64_t*, bigstack_alloc(ct * sizeof(int64_t)));
721 if (unlikely(!(*u64_arr_ptr))) {
722 return 1;
723 }
724 ZeroU64Arr(ct, *u64_arr_ptr);
725 return 0;
726 }
727
728 BoolErr bigstack_calloc_v(uintptr_t ct, VecW** v_arr_ptr) {
729 *v_arr_ptr = S_CAST(VecW*, bigstack_alloc(ct * kBytesPerVec));
730 if (unlikely(!(*v_arr_ptr))) {
731 return 1;
732 }
733 ZeroVecArr(ct, *v_arr_ptr);
734 return 0;
735 }
736
737 BoolErr bigstack_calloc_wp(uintptr_t ct, uintptr_t*** wp_arr_ptr) {
738 *wp_arr_ptr = S_CAST(uintptr_t**, bigstack_alloc(ct * sizeof(intptr_t)));
739 if (unlikely(!(*wp_arr_ptr))) {
740 return 1;
741 }
742 ZeroPtrArr(ct, *wp_arr_ptr);
743 return 0;
744 }
745
746 BoolErr bigstack_calloc_cp(uintptr_t ct, char*** cp_arr_ptr) {
747 *cp_arr_ptr = S_CAST(char**, bigstack_alloc(ct * sizeof(intptr_t)));
748 if (unlikely(!(*cp_arr_ptr))) {
749 return 1;
750 }
751 ZeroPtrArr(ct, *cp_arr_ptr);
752 return 0;
753 }
754
755 BoolErr bigstack_calloc_kcp(uintptr_t ct, const char*** kcp_arr_ptr) {
756 *kcp_arr_ptr = S_CAST(const char**, bigstack_alloc(ct * sizeof(intptr_t)));
757 if (unlikely(!(*kcp_arr_ptr))) {
758 return 1;
759 }
760 ZeroPtrArr(ct, *kcp_arr_ptr);
761 return 0;
762 }
763
764 BoolErr bigstack_calloc_cpp(uintptr_t ct, char**** cpp_arr_ptr) {
765 *cpp_arr_ptr = S_CAST(char***, bigstack_alloc(ct * sizeof(intptr_t)));
766 if (unlikely(!(*cpp_arr_ptr))) {
767 return 1;
768 }
769 ZeroPtrArr(ct, *cpp_arr_ptr);
770 return 0;
771 }
772
773 #ifndef __LP64__
774 BoolErr bigstack_calloc64_d(uint64_t ct, double** d_arr_ptr) {
775 *d_arr_ptr = S_CAST(double*, bigstack_alloc64(ct * sizeof(double)));
776 if (unlikely(!(*d_arr_ptr))) {
777 return 1;
778 }
779 ZeroDArr(ct, *d_arr_ptr);
780 return 0;
781 }
782 #endif
783
784 BoolErr bigstack_end_calloc_uc(uintptr_t ct, unsigned char** uc_arr_ptr) {
785 *uc_arr_ptr = S_CAST(unsigned char*, bigstack_end_alloc(ct));
786 if (unlikely(!(*uc_arr_ptr))) {
787 return 1;
788 }
789 memset(*uc_arr_ptr, 0, ct);
790 return 0;
791 }
792
793 BoolErr bigstack_end_calloc_d(uintptr_t ct, double** d_arr_ptr) {
794 *d_arr_ptr = S_CAST(double*, bigstack_end_alloc(ct * sizeof(double)));
795 if (unlikely(!(*d_arr_ptr))) {
796 return 1;
797 }
798 ZeroDArr(ct, *d_arr_ptr);
799 return 0;
800 }
801
802 BoolErr bigstack_end_calloc_f(uintptr_t ct, float** f_arr_ptr) {
803 *f_arr_ptr = S_CAST(float*, bigstack_end_alloc(ct * sizeof(float)));
804 if (unlikely(!(*f_arr_ptr))) {
805 return 1;
806 }
807 ZeroFArr(ct, *f_arr_ptr);
808 return 0;
809 }
810
811 BoolErr bigstack_end_calloc_u32(uintptr_t ct, uint32_t** u32_arr_ptr) {
812 *u32_arr_ptr = S_CAST(uint32_t*, bigstack_end_alloc(ct * sizeof(int32_t)));
813 if (unlikely(!(*u32_arr_ptr))) {
814 return 1;
815 }
816 ZeroU32Arr(ct, *u32_arr_ptr);
817 return 0;
818 }
819
820 BoolErr bigstack_end_calloc_w(uintptr_t ct, uintptr_t** w_arr_ptr) {
821 *w_arr_ptr = S_CAST(uintptr_t*, bigstack_end_alloc(ct * sizeof(intptr_t)));
822 if (unlikely(!(*w_arr_ptr))) {
823 return 1;
824 }
825 ZeroWArr(ct, *w_arr_ptr);
826 return 0;
827 }
828
829 BoolErr bigstack_end_calloc_u64(uintptr_t ct, uint64_t** u64_arr_ptr) {
830 *u64_arr_ptr = S_CAST(uint64_t*, bigstack_end_alloc(ct * sizeof(int64_t)));
831 if (unlikely(!(*u64_arr_ptr))) {
832 return 1;
833 }
834 ZeroU64Arr(ct, *u64_arr_ptr);
835 return 0;
836 }
837
838 BoolErr bigstack_end_calloc_wp(uintptr_t ct, uintptr_t*** wp_arr_ptr) {
839 *wp_arr_ptr = S_CAST(uintptr_t**, bigstack_end_alloc(ct * sizeof(intptr_t)));
840 if (unlikely(!(*wp_arr_ptr))) {
841 return 1;
842 }
843 ZeroPtrArr(ct, *wp_arr_ptr);
844 return 0;
845 }
846
847 BoolErr bigstack_end_calloc_cp(uintptr_t ct, char*** cp_arr_ptr) {
848 *cp_arr_ptr = S_CAST(char**, bigstack_end_alloc(ct * sizeof(intptr_t)));
849 if (unlikely(!(*cp_arr_ptr))) {
850 return 1;
851 }
852 ZeroPtrArr(ct, *cp_arr_ptr);
853 return 0;
854 }
855
856 #ifndef __LP64__
857 BoolErr bigstack_end_calloc64_w(uint64_t ct, uintptr_t** w_arr_ptr) {
858 *w_arr_ptr = S_CAST(uintptr_t*, bigstack_end_alloc64(ct * sizeof(intptr_t)));
859 if (unlikely(!(*w_arr_ptr))) {
860 return 1;
861 }
862 ZeroWArr(ct, *w_arr_ptr);
863 return 0;
864 }
865 #endif
866
867
868 BoolErr PushLlStr(const char* str, LlStr** ll_stack_ptr) {
869 uintptr_t blen = strlen(str) + 1;
870 LlStr* new_llstr;
871 if (unlikely(pgl_malloc(sizeof(LlStr) + blen, &new_llstr))) {
872 return 1;
873 }
874 new_llstr->next = *ll_stack_ptr;
875 memcpy(new_llstr->str, str, blen);
876 *ll_stack_ptr = new_llstr;
877 return 0;
878 }
879
880 /*
881 BoolErr push_llstr_counted(const char* str, uint32_t slen, LlStr** ll_stack_ptr) {
882 LlStr* new_llstr;
883 if (pgl_malloc(sizeof(LlStr) + slen + 1, &new_llstr)) {
884 return 1;
885 }
886 new_llstr->next = *ll_stack_ptr;
887 memcpy(new_llstr->str, str, slen);
888 new_llstr->str[slen] = '\0';
889 *ll_stack_ptr = new_llstr;
890 return 0;
891 }
892 */
893
894 void llstr_free_cond(LlStr* llstr_head) {
895 while (llstr_head) {
896 LlStr* next = llstr_head->next;
897 free(llstr_head);
898 llstr_head = next;
899 }
900 }
901
902 /*
903 BoolErr CountAndMeasureMultistrAlloc(const char* multistr, uintptr_t max_str_ct, const char** strptr_arr, uint32_t* str_ct_ptr, uintptr_t* max_blen_ptr) {
904 // assumes multistr is nonempty
905 assert(multistr[0]);
906 uintptr_t ct = 0;
907 uintptr_t max_blen = *max_blen_ptr;
908 do {
909 if (unlikely(ct == max_str_ct)) {
910 return 1;
911 }
912 const uintptr_t blen = strlen(multistr) + 1;
913 if (blen > max_blen) {
914 max_blen = blen;
915 }
916 strptr_arr[ct++] = multistr;
917 multistr = &(multistr[blen]);
918 } while (*multistr);
919 *str_ct_ptr = ct;
920 *max_blen_ptr = max_blen;
921 return 0;
922 }
923 */
924
925 BoolErr CountAndMeasureMultistrReverseAlloc(const char* multistr, uintptr_t max_str_ct, uint32_t* str_ct_ptr, uintptr_t* max_blen_ptr, const char*** strptr_arrp) {
926 // assumes multistr is nonempty
927 assert(multistr[0]);
928 uintptr_t ct = 0;
929 uintptr_t max_blen = *max_blen_ptr;
930 const char** strptr_arr_iter = *strptr_arrp;
931 do {
932 if (unlikely(++ct > max_str_ct)) {
933 return 1;
934 }
935 const uintptr_t blen = strlen(multistr) + 1;
936 if (blen > max_blen) {
937 max_blen = blen;
938 }
939 *(--strptr_arr_iter) = multistr;
940 multistr = &(multistr[blen]);
941 } while (*multistr);
942 *str_ct_ptr = ct;
943 *max_blen_ptr = max_blen;
944 *strptr_arrp = strptr_arr_iter;
945 return 0;
946 }
947
948 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) {
949 const char** strptr_arr = R_CAST(const char**, arena_top);
950 uintptr_t max_str_blen = 0;
951 uint32_t str_ct;
952 if (unlikely(CountAndMeasureMultistrReverseAlloc(multistr, (arena_top - (*arena_bottom_ptr)) / sizeof(intptr_t), &str_ct, &max_str_blen, &strptr_arr))) {
953 return 1;
954 }
955 const uintptr_t strbox_byte_ct = RoundUpPow2(str_ct * max_str_blen, kCacheline);
956 if (unlikely((R_CAST(uintptr_t, strptr_arr) - R_CAST(uintptr_t, *arena_bottom_ptr)) < strbox_byte_ct)) {
957 return 1;
958 }
959 // multistr can currently come from command line parser, which does not
960 // guarantee safe overread
961 StrptrArrSort(str_ct, strptr_arr);
962 *sorted_strbox_ptr = R_CAST(char*, *arena_bottom_ptr);
963 str_ct = CopyAndDedupSortedStrptrsToStrbox(strptr_arr, str_ct, max_str_blen, *sorted_strbox_ptr);
964 *arena_bottom_ptr += RoundUpPow2(str_ct * max_str_blen, kCacheline);
965 *str_ct_ptr = str_ct;
966 *max_blen_ptr = max_str_blen;
967 return 0;
968 }
969
970
971 void DivisionMagicNums(uint32_t divisor, uint64_t* multp, uint32_t* __restrict pre_shiftp, uint32_t* __restrict post_shiftp, uint32_t* __restrict incrp) {
972 // Enables fast integer division by a constant not known until runtime. See
973 // http://ridiculousfish.com/blog/posts/labor-of-division-episode-iii.html .
974 // Assumes divisor is not zero, of course.
975 // May want to populate a struct instead.
976 assert(divisor);
977 if (!(divisor & (divisor - 1))) {
978 // power of 2
979 *multp = 1;
980 *pre_shiftp = 0;
981 *post_shiftp = ctzu32(divisor);
982 *incrp = 0;
983 return;
984 }
985 uint32_t quotient = 0x80000000U / divisor;
986 uint32_t remainder = 0x80000000U - (quotient * divisor);
987 const uint32_t ceil_log_2_d = 1 + bsru32(divisor);
988 uint32_t down_multiplier = 0;
989 uint32_t down_exponent = 0;
990 uint32_t has_magic_down = 0;
991 for (uint32_t exponent = 0; ; ++exponent) {
992 if (remainder >= divisor - remainder) {
993 quotient = quotient * 2 + 1;
994 remainder = remainder * 2 - divisor;
995 } else {
996 quotient = quotient * 2;
997 remainder = remainder * 2;
998 }
999 if ((exponent >= ceil_log_2_d) || (divisor - remainder) <= (1U << exponent)) {
1000 if (exponent < ceil_log_2_d) {
1001 *multp = quotient + 1;
1002 *pre_shiftp = 0;
1003 *post_shiftp = 32 + exponent;
1004 *incrp = 0;
1005 return;
1006 }
1007 break;
1008 }
1009 if ((!has_magic_down) && (remainder <= (1U << exponent))) {
1010 has_magic_down = 1;
1011 down_multiplier = quotient;
1012 down_exponent = exponent;
1013 }
1014 }
1015 if (divisor & 1) {
1016 *multp = down_multiplier;
1017 *pre_shiftp = 0;
1018 *post_shiftp = 32 + down_exponent;
1019 *incrp = 1;
1020 return;
1021 }
1022 *pre_shiftp = ctzu32(divisor);
1023 uint32_t dummy;
1024 DivisionMagicNums(divisor >> (*pre_shiftp), multp, &dummy, post_shiftp, incrp);
1025 }
1026
1027
1028 // floor permitted to be -1, though not smaller than that.
1029 int32_t FindLast1BitBeforeBounded(const uintptr_t* bitarr, uint32_t loc, int32_t floor) {
1030 const uintptr_t* bitarr_ptr = &(bitarr[loc / kBitsPerWord]);
1031 uint32_t remainder = loc % kBitsPerWord;
1032 uintptr_t ulii;
1033 if (remainder) {
1034 ulii = bzhi(*bitarr_ptr, remainder);
1035 if (ulii) {
1036 const uint32_t set_bit_loc = loc - remainder + bsrw(ulii);
1037 return MAXV(S_CAST(int32_t, set_bit_loc), floor);
1038 }
1039 }
1040 const uintptr_t* bitarr_last = &(bitarr[S_CAST(uint32_t, floor + 1) / kBitsPerWord]);
1041 do {
1042 if (bitarr_ptr <= bitarr_last) {
1043 return floor;
1044 }
1045 ulii = *(--bitarr_ptr);
1046 } while (!ulii);
1047 const uint32_t set_bit_loc = S_CAST(uintptr_t, bitarr_ptr - bitarr) * kBitsPerWord + bsrw(ulii);
1048 return MAXV(S_CAST(int32_t, set_bit_loc), floor);
1049 }
1050
1051 void BitvecAndCopy(const uintptr_t* __restrict source1_bitvec, const uintptr_t* __restrict source2_bitvec, uintptr_t word_ct, uintptr_t* target_bitvec) {
1052 #ifdef __LP64__
1053 VecW* target_bitvvec = R_CAST(VecW*, target_bitvec);
1054 const VecW* source1_bitvvec = R_CAST(const VecW*, source1_bitvec);
1055 const VecW* source2_bitvvec = R_CAST(const VecW*, source2_bitvec);
1056 const uintptr_t full_vec_ct = word_ct / kWordsPerVec;
1057 for (uintptr_t ulii = 0; ulii != full_vec_ct; ++ulii) {
1058 target_bitvvec[ulii] = source1_bitvvec[ulii] & source2_bitvvec[ulii];
1059 }
1060 # ifdef USE_AVX2
1061 if (word_ct & 2) {
1062 const uintptr_t base_idx = full_vec_ct * kWordsPerVec;
1063 target_bitvec[base_idx] = source1_bitvec[base_idx] & source2_bitvec[base_idx];
1064 target_bitvec[base_idx + 1] = source1_bitvec[base_idx + 1] & source2_bitvec[base_idx + 1];
1065 }
1066 # endif
1067 if (word_ct & 1) {
1068 target_bitvec[word_ct - 1] = source1_bitvec[word_ct - 1] & source2_bitvec[word_ct - 1];
1069 }
1070 #else
1071 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
1072 target_bitvec[widx] = source1_bitvec[widx] & source2_bitvec[widx];
1073 }
1074 #endif
1075 }
1076
1077 void BitvecInvmaskCopy(const uintptr_t* __restrict source_bitvec, const uintptr_t* __restrict exclude_bitvec, uintptr_t word_ct, uintptr_t* target_bitvec) {
1078 // target_bitvec := source_bitvec AND (~exclude_bitvec)
1079 #ifdef __LP64__
1080 VecW* target_bitvvec = R_CAST(VecW*, target_bitvec);
1081 const VecW* source_bitvvec = R_CAST(const VecW*, source_bitvec);
1082 const VecW* exclude_bitvvec = R_CAST(const VecW*, exclude_bitvec);
1083 const uintptr_t full_vec_ct = word_ct / kWordsPerVec;
1084 for (uintptr_t ulii = 0; ulii != full_vec_ct; ++ulii) {
1085 target_bitvvec[ulii] = vecw_and_notfirst(exclude_bitvvec[ulii], source_bitvvec[ulii]);
1086 }
1087 # ifdef USE_AVX2
1088 if (word_ct & 2) {
1089 const uintptr_t base_idx = full_vec_ct * kWordsPerVec;
1090 target_bitvec[base_idx] = (~exclude_bitvec[base_idx]) & source_bitvec[base_idx];
1091 target_bitvec[base_idx + 1] = (~exclude_bitvec[base_idx + 1]) & source_bitvec[base_idx + 1];
1092 }
1093 # endif
1094 if (word_ct & 1) {
1095 target_bitvec[word_ct - 1] = source_bitvec[word_ct - 1] & (~exclude_bitvec[word_ct - 1]);
1096 }
1097 #else
1098 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
1099 target_bitvec[widx] = source_bitvec[widx] & (~exclude_bitvec[widx]);
1100 }
1101 #endif
1102 }
1103
1104 void BitvecXor(const uintptr_t* __restrict arg_bitvec, uintptr_t word_ct, uintptr_t* main_bitvec) {
1105 // main_bitvec := main_bitvec XOR arg_bitvec
1106 #ifdef __LP64__
1107 VecW* main_bitvvec_iter = R_CAST(VecW*, main_bitvec);
1108 const VecW* arg_bitvvec_iter = R_CAST(const VecW*, arg_bitvec);
1109 const uintptr_t full_vec_ct = word_ct / kWordsPerVec;
1110 if (full_vec_ct & 1) {
1111 *main_bitvvec_iter++ ^= (*arg_bitvvec_iter++);
1112 }
1113 if (full_vec_ct & 2) {
1114 *main_bitvvec_iter++ ^= (*arg_bitvvec_iter++);
1115 *main_bitvvec_iter++ ^= (*arg_bitvvec_iter++);
1116 }
1117 for (uintptr_t ulii = 3; ulii < full_vec_ct; ulii += 4) {
1118 *main_bitvvec_iter++ ^= (*arg_bitvvec_iter++);
1119 *main_bitvvec_iter++ ^= (*arg_bitvvec_iter++);
1120 *main_bitvvec_iter++ ^= (*arg_bitvvec_iter++);
1121 *main_bitvvec_iter++ ^= (*arg_bitvvec_iter++);
1122 }
1123 # ifdef USE_AVX2
1124 if (word_ct & 2) {
1125 const uintptr_t base_idx = full_vec_ct * kWordsPerVec;
1126 main_bitvec[base_idx] ^= arg_bitvec[base_idx];
1127 main_bitvec[base_idx + 1] ^= arg_bitvec[base_idx + 1];
1128 }
1129 # endif
1130 if (word_ct & 1) {
1131 main_bitvec[word_ct - 1] ^= arg_bitvec[word_ct - 1];
1132 }
1133 #else
1134 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
1135 main_bitvec[widx] ^= arg_bitvec[widx];
1136 }
1137 #endif
1138 }
1139
1140 void BitvecInvertAndMask(const uintptr_t* __restrict include_bitvec, uintptr_t word_ct, uintptr_t* __restrict main_bitvec) {
1141 // main_bitvec := (~main_bitvec) AND include_bitvec
1142 // this corresponds _mm_andnot() operand order
1143 #ifdef __LP64__
1144 VecW* main_bitvvec_iter = R_CAST(VecW*, main_bitvec);
1145 const VecW* include_bitvvec_iter = R_CAST(const VecW*, include_bitvec);
1146 const uintptr_t full_vec_ct = word_ct / kWordsPerVec;
1147 if (full_vec_ct & 1) {
1148 *main_bitvvec_iter = vecw_and_notfirst(*main_bitvvec_iter, *include_bitvvec_iter++);
1149 ++main_bitvvec_iter;
1150 }
1151 if (full_vec_ct & 2) {
1152 *main_bitvvec_iter = vecw_and_notfirst(*main_bitvvec_iter, *include_bitvvec_iter++);
1153 ++main_bitvvec_iter;
1154 *main_bitvvec_iter = vecw_and_notfirst(*main_bitvvec_iter, *include_bitvvec_iter++);
1155 ++main_bitvvec_iter;
1156 }
1157 for (uintptr_t ulii = 3; ulii < full_vec_ct; ulii += 4) {
1158 *main_bitvvec_iter = vecw_and_notfirst(*main_bitvvec_iter, *include_bitvvec_iter++);
1159 ++main_bitvvec_iter;
1160 *main_bitvvec_iter = vecw_and_notfirst(*main_bitvvec_iter, *include_bitvvec_iter++);
1161 ++main_bitvvec_iter;
1162 *main_bitvvec_iter = vecw_and_notfirst(*main_bitvvec_iter, *include_bitvvec_iter++);
1163 ++main_bitvvec_iter;
1164 *main_bitvvec_iter = vecw_and_notfirst(*main_bitvvec_iter, *include_bitvvec_iter++);
1165 ++main_bitvvec_iter;
1166 }
1167 # ifdef USE_AVX2
1168 if (word_ct & 2) {
1169 const uintptr_t base_idx = full_vec_ct * kWordsPerVec;
1170 main_bitvec[base_idx] = (~main_bitvec[base_idx]) & include_bitvec[base_idx];
1171 main_bitvec[base_idx + 1] = (~main_bitvec[base_idx + 1]) & include_bitvec[base_idx + 1];
1172 }
1173 # endif
1174 if (word_ct & 1) {
1175 main_bitvec[word_ct - 1] = (~main_bitvec[word_ct - 1]) & include_bitvec[word_ct - 1];
1176 }
1177 #else
1178 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
1179 main_bitvec[widx] = (~main_bitvec[widx]) & include_bitvec[widx];
1180 }
1181 #endif
1182 }
1183
1184 /*
1185 void BitvecOrNot(const uintptr_t* __restrict arg_bitvec, uintptr_t word_ct, uintptr_t* main_bitvec) {
1186 // main_bitvec := main_bitvec OR (~arg_bitvec)
1187 #ifdef __LP64__
1188 VecW* main_bitvvec_iter = (VecW*)main_bitvec;
1189 const VecW* arg_bitvvec_iter = (const VecW*)arg_bitvec;
1190 const uintptr_t full_vec_ct = word_ct / kWordsPerVec;
1191 if (full_vec_ct & 1) {
1192 // todo: verify the compiler isn't dumb here
1193 *main_bitvvec_iter++ |= ~(*arg_bitvvec_iter++);
1194 }
1195 if (full_vec_ct & 2) {
1196 *main_bitvvec_iter++ |= ~(*arg_bitvvec_iter++);
1197 *main_bitvvec_iter++ |= ~(*arg_bitvvec_iter++);
1198 }
1199 for (uintptr_t ulii = 3; ulii < full_vec_ct; ulii += 4) {
1200 *main_bitvvec_iter++ |= ~(*arg_bitvvec_iter++);
1201 *main_bitvvec_iter++ |= ~(*arg_bitvvec_iter++);
1202 *main_bitvvec_iter++ |= ~(*arg_bitvvec_iter++);
1203 *main_bitvvec_iter++ |= ~(*arg_bitvvec_iter++);
1204 }
1205 # ifdef USE_AVX2
1206 if (word_ct & 2) {
1207 const uintptr_t base_idx = full_vec_ct * kWordsPerVec;
1208 main_bitvec[base_idx] |= ~arg_bitvec[base_idx];
1209 main_bitvec[base_idx + 1] |= ~arg_bitvec[base_idx + 1]
1210 }
1211 # endif
1212 if (word_ct & 1) {
1213 main_bitvec[word_ct - 1] |= ~arg_bitvec[word_ct - 1];
1214 }
1215 #else
1216 for (uintptr_t widx = 0; widx != word_ct; ++widx) {
1217 main_bitvec[widx] |= ~arg_bitvec[widx];
1218 }
1219 #endif
1220 }
1221 */
1222
1223 void AlignedBitarrOrnotCopy(const uintptr_t* __restrict argyes_bitvec, const uintptr_t* __restrict argno_bitvec, uintptr_t bit_ct, uintptr_t* __restrict target_bitvec) {
1224 const uintptr_t fullword_ct = bit_ct / kBitsPerWord;
1225 #ifdef __LP64__
1226 VecW* target_bitvvec = R_CAST(VecW*, target_bitvec);
1227 const VecW* argyes_bitvvec = R_CAST(const VecW*, argyes_bitvec);
1228 const VecW* argno_bitvvec = R_CAST(const VecW*, argno_bitvec);
1229 const uintptr_t full_vec_ct = fullword_ct / kWordsPerVec;
1230 for (uintptr_t ulii = 0; ulii != full_vec_ct; ++ulii) {
1231 target_bitvvec[ulii] = argyes_bitvvec[ulii] | (~argno_bitvvec[ulii]);
1232 }
1233 # ifdef USE_AVX2
1234 if (fullword_ct & 2) {
1235 const uintptr_t base_idx = full_vec_ct * kWordsPerVec;
1236 target_bitvec[base_idx] = argyes_bitvec[base_idx] | (~argno_bitvec[base_idx]);
1237 target_bitvec[base_idx + 1] = argyes_bitvec[base_idx + 1] | (~argno_bitvec[base_idx + 1]);
1238 }
1239 # endif
1240 if (fullword_ct & 1) {
1241 target_bitvec[fullword_ct - 1] = argyes_bitvec[fullword_ct - 1] | (~argno_bitvec[fullword_ct - 1]);
1242 }
1243 #else
1244 for (uintptr_t widx = 0; widx != fullword_ct; ++widx) {
1245 target_bitvec[widx] = argyes_bitvec[widx] | (~argno_bitvec[widx]);
1246 }
1247 #endif
1248 const uint32_t remainder = bit_ct % kBitsPerWord;
1249 if (remainder) {
1250 target_bitvec[fullword_ct] = bzhi(argyes_bitvec[fullword_ct] | (~argno_bitvec[fullword_ct]), remainder);
1251 }
1252 }
1253
1254 int32_t GetVariantUidxWithoutHtable(const char* idstr, const char* const* variant_ids, const uintptr_t* variant_include, uint32_t variant_ct) {
1255 const uint32_t id_blen = strlen(idstr) + 1;
1256 uintptr_t widx = ~k0LU;
1257 int32_t retval = -1;
1258 for (uint32_t variant_idx = 0; variant_idx != variant_ct; ) {
1259 uintptr_t variant_include_bits;
1260 do {
1261 variant_include_bits = variant_include[++widx];
1262 } while (!variant_include_bits);
1263 const uintptr_t variant_uidx_base = widx * kBitsPerWord;
1264 const char* const* cur_variant_ids = &(variant_ids[variant_uidx_base]);
1265 variant_idx += PopcountWord(variant_include_bits);
1266 do {
1267 const uint32_t uidx_lowbits = ctzw(variant_include_bits);
1268 if (memequal(idstr, cur_variant_ids[uidx_lowbits], id_blen)) {
1269 if (retval != -1) {
1270 // duplicate
1271 return -2;
1272 }
1273 retval = S_CAST(int32_t, uidx_lowbits + variant_uidx_base);
1274 }
1275 variant_include_bits &= variant_include_bits - 1;
1276 } while (variant_include_bits);
1277 }
1278 return retval;
1279 }
1280
1281
1282
1283 /*
1284 uint32_t is_composite6(uintptr_t num) {
1285 // assumes num is congruent to 1 or 5 mod 6.
1286 // can speed this up by ~50% by hardcoding avoidance of multiples of 5/7,
1287 // but this isn't currently a bottleneck so I'll keep this simple
1288 assert((num % 6 == 1) || (num % 6 == 5));
1289 uintptr_t divisor = 5;
1290 while (divisor * divisor <= num) {
1291 if (!(num % divisor)) {
1292 return 1;
1293 }
1294 divisor += 2;
1295 if (!(num % divisor)) {
1296 return 1;
1297 }
1298 divisor += 4;
1299 }
1300 return 0;
1301 }
1302
1303 uintptr_t geqprime(uintptr_t floor) {
1304 // assumes floor is odd and greater than 1. Returns 5 if floor = 3,
1305 // otherwise returns the first prime >= floor.
1306 assert((floor % 2) && (floor > 1));
1307 uintptr_t ulii = floor % 3;
1308 if (!ulii) {
1309 floor += 2;
1310 } else if (ulii == 1) {
1311 goto geqprime_1mod6;
1312 }
1313 while (is_composite6(floor)) {
1314 floor += 2;
1315 geqprime_1mod6:
1316 if (!is_composite6(floor)) {
1317 return floor;
1318 }
1319 floor += 4;
1320 }
1321 return floor;
1322 }
1323
1324 uintptr_t leqprime(uintptr_t ceil) {
1325 // assumes ceil is odd and greater than 4. Returns the first prime <= ceil.
1326 assert((ceil % 2) && (ceil > 4));
1327 uintptr_t ulii = ceil % 3;
1328 if (!ulii) {
1329 ceil -= 2;
1330 } else if (ulii == 2) {
1331 goto leqprime_5mod6;
1332 }
1333 while (is_composite6(ceil)) {
1334 ceil -= 2;
1335 leqprime_5mod6:
1336 if (!is_composite6(ceil)) {
1337 return ceil;
1338 }
1339 ceil -= 4;
1340 }
1341 return ceil;
1342 }
1343 */
1344
1345 BoolErr HtableGoodSizeAlloc(uint32_t item_ct, uintptr_t bytes_avail, uint32_t** htable_ptr, uint32_t* htable_size_ptr) {
1346 bytes_avail &= (~(kCacheline - k1LU));
1347 uint32_t htable_size = GetHtableFastSize(item_ct);
1348 if (htable_size > bytes_avail / sizeof(int32_t)) {
1349 if (unlikely(!bytes_avail)) {
1350 return 1;
1351 }
1352 htable_size = bytes_avail / sizeof(int32_t);
1353 // htable_size = leqprime((bytes_avail / sizeof(int32_t)) - 1);
1354 if (unlikely(htable_size < item_ct * 2)) {
1355 return 1;
1356 }
1357 }
1358 *htable_ptr = S_CAST(uint32_t*, bigstack_alloc_raw_rd(htable_size * sizeof(int32_t)));
1359 *htable_size_ptr = htable_size;
1360 return 0;
1361 }
1362
1363 // could merge this with non-subset case, but this isn't much code
1364 /*
1365 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) {
1366 // may want subset_mask parameter later
1367 SetAllU32Arr(str_htable_size, str_htable);
1368 uintptr_t str_uidx = 0;
1369 for (uintptr_t str_idx = 0; str_idx != str_ct; ++str_idx, ++str_uidx) {
1370 MovWTo1Bit(subset_mask, &str_uidx);
1371 const char* cur_str = &(strbox[str_uidx * max_str_blen]);
1372 const uint32_t slen = strlen(cur_str);
1373 uint32_t hashval = Hashceil(cur_str, slen, str_htable_size);
1374 while (1) {
1375 const uint32_t cur_htable_entry = str_htable[hashval];
1376 if (cur_htable_entry == UINT32_MAX) {
1377 str_htable[hashval] = str_uidx;
1378 break;
1379 }
1380 if (memequal(cur_str, &(strbox[cur_htable_entry * max_str_blen]), slen + 1)) {
1381 // guaranteed to be positive
1382 return str_uidx;
1383 }
1384 if (++hashval == str_htable_size) {
1385 hashval = 0;
1386 }
1387 }
1388 }
1389 return 0;
1390 }
1391 */
1392
1393 // assumes cur_id_slen < max_str_blen.
1394 // requires cur_id to be null-terminated.
1395 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) {
1396 const uint32_t cur_id_blen = cur_id_slen + 1;
1397 for (uint32_t hashval = Hashceil(cur_id, cur_id_slen, id_htable_size); ; ) {
1398 const uint32_t cur_htable_idval = id_htable[hashval];
1399 if ((cur_htable_idval == UINT32_MAX) || memequal(cur_id, &(strbox[cur_htable_idval * max_str_blen]), cur_id_blen)) {
1400 return cur_htable_idval;
1401 }
1402 if (++hashval == id_htable_size) {
1403 hashval = 0;
1404 }
1405 }
1406 }
1407
1408 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) {
1409 for (uint32_t hashval = Hashceil(cur_id, cur_id_slen, id_htable_size); ; ) {
1410 const uint32_t cur_htable_idval = id_htable[hashval];
1411 if ((cur_htable_idval == UINT32_MAX) || strequal_unsafe(&(strbox[cur_htable_idval * max_str_blen]), cur_id, cur_id_slen)) {
1412 return cur_htable_idval;
1413 }
1414 if (++hashval == id_htable_size) {
1415 hashval = 0;
1416 }
1417 }
1418 }
1419
1420 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) {
1421 for (uint32_t hashval = Hashceil(cur_id, cur_id_slen, id_htable_size); ; ) {
1422 const uint32_t cur_htable_entry = id_htable[hashval];
1423 if (cur_htable_entry == UINT32_MAX) {
1424 id_htable[hashval] = value;
1425 return UINT32_MAX;
1426 }
1427 if (memequal(cur_id, &(strbox[cur_htable_entry * max_str_blen]), cur_id_slen + 1)) {
1428 return cur_htable_entry;
1429 }
1430 if (++hashval == id_htable_size) {
1431 hashval = 0;
1432 }
1433 }
1434 }
1435
1436 uint32_t PopulateStrboxHtable(const char* strbox, uint32_t str_ct, uintptr_t max_str_blen, uint32_t str_htable_size, uint32_t* str_htable) {
1437 // may want subset_mask parameter later
1438 SetAllU32Arr(str_htable_size, str_htable);
1439 const char* strbox_iter = strbox;
1440 for (uintptr_t str_idx = 0; str_idx != str_ct; ++str_idx) {
1441 const uint32_t slen = strlen(strbox_iter);
1442 if (StrboxHtableAdd(strbox_iter, strbox, max_str_blen, slen, str_htable_size, str_idx, str_htable) != UINT32_MAX) {
1443 // guaranteed to be positive
1444 return str_idx;
1445 }
1446 strbox_iter = &(strbox_iter[max_str_blen]);
1447 }
1448 return 0;
1449 }
1450
1451 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) {
1452 SetAllU32Arr(str_htable_size, str_htable);
1453 uintptr_t str_uidx_base = 0;
1454 uintptr_t subset_mask_bits = subset_mask[0];
1455 for (uintptr_t str_idx = 0; str_idx != str_ct; ++str_idx) {
1456 const uint32_t str_uidx = BitIter1(subset_mask, &str_uidx_base, &subset_mask_bits);
1457 const char* strptr = &(strbox[str_uidx * max_str_blen]);
1458 const uint32_t slen = strlen(strptr);
1459 StrboxHtableAdd(strptr, strbox, max_str_blen, slen, str_htable_size, str_uidx, str_htable);
1460 }
1461 return 0;
1462 }
1463
1464 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) {
1465 // assumes duplicate variant IDs are flagged, but full variant_uidx linked
1466 // lists are not stored
1467 // idbuf does not need to be null-terminated (note that this is currently
1468 // achieved in a way that forces variant_ids[] entries to not be too close
1469 // to the end of bigstack, otherwise memequal behavior is potentially
1470 // undefined)
1471 // returns UINT32_MAX on failure, value with bit 31 set on duplicate
1472 if (cur_id_slen > max_id_slen) {
1473 return UINT32_MAX;
1474 }
1475 for (uint32_t hashval = Hashceil(idbuf, cur_id_slen, id_htable_size); ; ) {
1476 const uint32_t cur_htable_idval = id_htable[hashval];
1477 if ((cur_htable_idval == UINT32_MAX) || strequal_unsafe(variant_ids[cur_htable_idval & 0x7fffffff], idbuf, cur_id_slen)) {
1478 return cur_htable_idval;
1479 }
1480 if (++hashval == id_htable_size) {
1481 hashval = 0;
1482 }
1483 }
1484 }
1485
1486 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) {
1487 // Permits duplicate entries. Similar to plink 1.9
1488 // extract_exclude_process_token().
1489 // - Returns UINT32_MAX on failure (llidx currently unset in that case),
1490 // otherwise returns the index of the first match (which will have the
1491 // highest index, due to how the linked list is constructed)
1492 // - Sets llidx to UINT32_MAX if not a duplicate, otherwise it's the
1493 // position in htable_dup_base[] of the next {variant_uidx, next_llidx}
1494 // linked list entry.
1495 // - idbuf does not need to be null-terminated.
1496 if (cur_id_slen > max_id_slen) {
1497 return UINT32_MAX;
1498 }
1499 for (uint32_t hashval = Hashceil(idbuf, cur_id_slen, id_htable_size); ; ) {
1500 const uint32_t cur_htable_idval = id_htable[hashval];
1501 const uint32_t cur_dup = cur_htable_idval >> 31;
1502 uint32_t cur_llidx;
1503 uint32_t variant_uidx;
1504 if (cur_dup) {
1505 // UINT32_MAX empty-entry code has high bit set, so only need to check
1506 // here
1507 if (cur_htable_idval == UINT32_MAX) {
1508 return UINT32_MAX;
1509 }
1510 cur_llidx = cur_htable_idval << 1;
1511 variant_uidx = htable_dup_base[cur_llidx];
1512 } else {
1513 cur_llidx = UINT32_MAX;
1514 variant_uidx = cur_htable_idval;
1515 }
1516 const char* sptr = variant_ids[variant_uidx];
1517 if (strequal_unsafe(sptr, idbuf, cur_id_slen)) {
1518 *llidx_ptr = cur_llidx;
1519 return variant_uidx;
1520 }
1521 if (++hashval == id_htable_size) {
1522 hashval = 0;
1523 }
1524 }
1525 }
1526
1527
1528 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) {
1529 // Stores a lexicographically sorted list of IDs in sorted_strbox and the raw
1530 // positions of the corresponding markers/samples in *id_map_ptr. Does not
1531 // include excluded markers/samples in the list.
1532 // Assumes sorted_strbox and id_map have been allocated; use the
1533 // CopySortStrboxSubset() wrapper if they haven't been.
1534 // Note that this DOES still perform a "stack" allocation; 'Noalloc' just
1535 // means that sorted_strbox/id_map must already be allocated.
1536 if (!str_ct) {
1537 return kPglRetSuccess;
1538 }
1539 unsigned char* bigstack_mark = g_bigstack_base;
1540 PglErr reterr = kPglRetSuccess;
1541 {
1542 #ifdef __cplusplus
1543 if (max_str_blen <= 60) {
1544 uintptr_t wkspace_entry_blen = (max_str_blen > 28)? sizeof(Strbuf60Ui) : sizeof(Strbuf28Ui);
1545 char* sort_wkspace;
1546 if (unlikely(bigstack_alloc_c(str_ct * wkspace_entry_blen, &sort_wkspace))) {
1547 goto CopySortStrboxSubsetNoalloc_ret_NOMEM;
1548 }
1549 const uint32_t wkspace_entry_blen_m4 = wkspace_entry_blen - 4;
1550 char* sort_wkspace_iter = sort_wkspace;
1551 uintptr_t str_uidx_base = 0;
1552 uintptr_t subset_mask_bits = subset_mask[0];
1553 for (uint32_t str_idx = 0; str_idx != str_ct; ++str_idx) {
1554 const uint32_t str_uidx = BitIter1(subset_mask, &str_uidx_base, &subset_mask_bits);
1555 strcpy(sort_wkspace_iter, &(orig_strbox[str_uidx * max_str_blen]));
1556 sort_wkspace_iter = &(sort_wkspace_iter[wkspace_entry_blen_m4]);
1557 if (collapse_idxs) {
1558 memcpy(sort_wkspace_iter, &str_idx, sizeof(int32_t));
1559 } else {
1560 memcpy(sort_wkspace_iter, &str_uidx, sizeof(int32_t));
1561 }
1562 sort_wkspace_iter = &(sort_wkspace_iter[sizeof(int32_t)]);
1563 }
1564 if (wkspace_entry_blen == 32) {
1565 SortStrbox32bFinish(str_ct, max_str_blen, use_nsort, R_CAST(Strbuf28Ui*, sort_wkspace), sorted_strbox, id_map);
1566 } else {
1567 SortStrbox64bFinish(str_ct, max_str_blen, use_nsort, R_CAST(Strbuf60Ui*, sort_wkspace), sorted_strbox, id_map);
1568 }
1569 } else {
1570 #endif
1571 StrSortIndexedDerefOverread* sort_wkspace;
1572 if (unlikely(BIGSTACK_ALLOC_X(StrSortIndexedDerefOverread, str_ct, &sort_wkspace))) {
1573 goto CopySortStrboxSubsetNoalloc_ret_NOMEM;
1574 }
1575 uintptr_t str_uidx_base = 0;
1576 uintptr_t cur_bits = subset_mask[0];
1577 for (uint32_t str_idx = 0; str_idx != str_ct; ++str_idx) {
1578 uintptr_t str_uidx = BitIter1(subset_mask, &str_uidx_base, &cur_bits);
1579 sort_wkspace[str_idx].strptr = &(orig_strbox[str_uidx * max_str_blen]);
1580 if (collapse_idxs) {
1581 sort_wkspace[str_idx].orig_idx = str_idx;
1582 } else {
1583 sort_wkspace[str_idx].orig_idx = str_uidx;
1584 }
1585 }
1586 if (!use_nsort) {
1587 STD_SORT_PAR_UNSEQ(str_ct, strcmp_overread_deref, sort_wkspace);
1588 } else {
1589 #ifdef __cplusplus
1590 StrNsortIndexedDeref* wkspace_alias = R_CAST(StrNsortIndexedDeref*, sort_wkspace);
1591 STD_SORT_PAR_UNSEQ(str_ct, nullptr, wkspace_alias);
1592 #else
1593 STD_SORT_PAR_UNSEQ(str_ct, strcmp_natural_deref, sort_wkspace);
1594 #endif
1595 }
1596 for (uintptr_t str_idx = 0; str_idx != str_ct; ++str_idx) {
1597 strcpy(&(sorted_strbox[str_idx * max_str_blen]), sort_wkspace[str_idx].strptr);
1598 id_map[str_idx] = sort_wkspace[str_idx].orig_idx;
1599 }
1600 #ifdef __cplusplus
1601 }
1602 #endif
1603 }
1604 while (0) {
1605 CopySortStrboxSubsetNoalloc_ret_NOMEM:
1606 reterr = kPglRetNomem;
1607 break;
1608 }
1609 BigstackReset(bigstack_mark);
1610 return reterr;
1611 }
1612
1613 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) {
1614 // id_map on bottom because --indiv-sort frees *sorted_strbox_ptr
1615 if (unlikely(bigstack_alloc_u32(str_ct, id_map_ptr) ||
1616 bigstack_alloc_c(str_ct * max_str_blen, sorted_strbox_ptr))) {
1617 return kPglRetNomem;
1618 }
1619 return CopySortStrboxSubsetNoalloc(subset_mask, orig_strbox, str_ct, max_str_blen, collapse_idxs, use_nsort, *sorted_strbox_ptr, *id_map_ptr);
1620 }
1621
1622
1623 void InitRangeList(RangeList* range_list_ptr) {
1624 range_list_ptr->names = nullptr;
1625 range_list_ptr->starts_range = nullptr;
1626 range_list_ptr->name_ct = 0;
1627 range_list_ptr->name_max_blen = 0;
1628 }
1629
1630 void CleanupRangeList(RangeList* range_list_ptr) {
1631 free_cond(range_list_ptr->names);
1632 // starts_range now uses same allocation
1633 }
1634
1635 BoolErr NumericRangeListToBitarr(const RangeList* range_list_ptr, uint32_t bitarr_size, uint32_t offset, uint32_t ignore_overflow, uintptr_t* bitarr) {
1636 // bitarr assumed to be initialized (but not necessarily zero-initialized)
1637 const char* names = range_list_ptr->names;
1638 const unsigned char* starts_range = range_list_ptr->starts_range;
1639 const uint32_t name_ct = range_list_ptr->name_ct;
1640 const uint32_t name_max_blen = range_list_ptr->name_max_blen;
1641 const uint32_t idx_max = bitarr_size + offset;
1642 for (uint32_t name_idx = 0; name_idx != name_ct; ++name_idx) {
1643 uint32_t idx1;
1644 if (ScanUintCapped(&(names[name_idx * name_max_blen]), idx_max, &idx1)) {
1645 if (likely(ignore_overflow)) {
1646 continue;
1647 }
1648 return 1;
1649 }
1650 if (unlikely(idx1 < offset)) {
1651 return 1;
1652 }
1653 if (starts_range[name_idx]) {
1654 ++name_idx;
1655 uint32_t idx2;
1656 if (ScanUintCapped(&(names[name_idx * name_max_blen]), idx_max, &idx2)) {
1657 if (unlikely(!ignore_overflow)) {
1658 return 1;
1659 }
1660 idx2 = idx_max - 1;
1661 }
1662 FillBitsNz(idx1 - offset, (idx2 - offset) + 1, bitarr);
1663 } else {
1664 SetBit(idx1 - offset, bitarr);
1665 }
1666 }
1667 return 0;
1668 }
1669
1670 uint32_t NumericRangeListMax(const RangeList* range_list_ptr) {
1671 const char* names = range_list_ptr->names;
1672 const unsigned char* starts_range = range_list_ptr->starts_range;
1673 const uint32_t name_ct = range_list_ptr->name_ct;
1674 const uint32_t name_max_blen = range_list_ptr->name_max_blen;
1675 uint32_t max_idx = 0;
1676 for (uint32_t name_idx = 0; name_idx != name_ct; ++name_idx) {
1677 if (starts_range[name_idx]) {
1678 ++name_idx;
1679 }
1680 uint32_t idx;
1681 if (ScanUintDefcap(&(names[name_idx * name_max_blen]), &idx)) {
1682 return UINT32_MAX;
1683 }
1684 if (idx > max_idx) {
1685 max_idx = idx;
1686 }
1687 }
1688 return max_idx;
1689 }
1690
1691 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) {
1692 // bitarr assumed to be zero-initialized
1693 // if fixed_len is zero, header_line is assumed to be a list of
1694 // space-delimited unequal-length names
1695 assert(token_ct);
1696 assert(!PopcountWords(bitarr, BitCtToWordCt(token_ct)));
1697 PglErr reterr = kPglRetSuccess;
1698 {
1699 const char* header_line_iter = header_line;
1700 const uintptr_t name_ct = range_list_ptr->name_ct;
1701 const uintptr_t max_id_blen = range_list_ptr->name_max_blen;
1702 for (uint32_t item_idx = 0; ; ) {
1703 const char* token_end = CommaOrTspaceTokenEnd(header_line_iter, comma_delim);
1704 const int32_t sorted_pos = bsearch_strbox(header_line_iter, sorted_ids, token_end - header_line_iter, max_id_blen, name_ct);
1705 if (sorted_pos != -1) {
1706 uint32_t cmdline_pos = sorted_pos;
1707 if (id_map) {
1708 cmdline_pos = id_map[S_CAST(uint32_t, sorted_pos)];
1709 }
1710 if (unlikely(seen_idxs[cmdline_pos] != -1)) {
1711 logerrprintfww("Error: --%s: '%s' appears multiple times in header line of %s.\n", range_list_flag, &(sorted_ids[S_CAST(uint32_t, sorted_pos) * max_id_blen]), file_descrip);
1712 goto StringRangeListToBitarr_ret_MALFORMED_INPUT;
1713 }
1714 seen_idxs[cmdline_pos] = item_idx;
1715 if (cmdline_pos && range_list_ptr->starts_range[cmdline_pos - 1]) {
1716 if (unlikely(seen_idxs[cmdline_pos - 1] == -1)) {
1717 uint32_t first_sorted_pos = cmdline_pos - 1;
1718 if (id_map) {
1719 for (first_sorted_pos = 0; ; ++first_sorted_pos) {
1720 if (id_map[first_sorted_pos] == cmdline_pos - 1) {
1721 break;
1722 }
1723 }
1724 }
1725 snprintf(g_logbuf, kLogbufSize, "Error: --%s: '%s' appears before '%s' in header line of %s.\n", range_list_flag, &(sorted_ids[S_CAST(uint32_t, sorted_pos) * max_id_blen]), &(sorted_ids[first_sorted_pos * max_id_blen]), file_descrip);
1726 goto StringRangeListToBitarr_ret_INVALID_CMDLINE_WW;
1727 }
1728 FillBitsNz(seen_idxs[cmdline_pos - 1], item_idx + 1, bitarr);
1729 } else if (!(range_list_ptr->starts_range[cmdline_pos])) {
1730 SetBit(item_idx, bitarr);
1731 }
1732 }
1733 if (++item_idx == token_ct) {
1734 break;
1735 }
1736 if (fixed_len) {
1737 header_line_iter = &(header_line_iter[fixed_len]);
1738 } else {
1739 header_line_iter = FirstNonTspace(&(token_end[1]));
1740 }
1741 }
1742 for (uint32_t cmdline_pos = 0; cmdline_pos != name_ct; ++cmdline_pos) {
1743 if (unlikely(seen_idxs[cmdline_pos] == -1)) {
1744 uint32_t sorted_pos = cmdline_pos;
1745 if (id_map) {
1746 for (sorted_pos = 0; ; ++sorted_pos) {
1747 if (id_map[sorted_pos] == cmdline_pos) {
1748 break;
1749 }
1750 }
1751 }
1752 snprintf(g_logbuf, kLogbufSize, "Error: --%s: '%s' does not appear in header line of %s.\n", range_list_flag, &(sorted_ids[sorted_pos * max_id_blen]), file_descrip);
1753 goto StringRangeListToBitarr_ret_INVALID_CMDLINE_WW;
1754 }
1755 }
1756 }
1757 while (0) {
1758 StringRangeListToBitarr_ret_INVALID_CMDLINE_WW:
1759 WordWrapB(0);
1760 logerrputsb();
1761 reterr = kPglRetInvalidCmdline;
1762 break;
1763 StringRangeListToBitarr_ret_MALFORMED_INPUT:
1764 reterr = kPglRetMalformedInput;
1765 break;
1766 }
1767 return reterr;
1768 }
1769
1770 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) {
1771 // wrapper for StringRangeListToBitarr which allocates the bitfield and
1772 // temporary buffers on the heap
1773 uintptr_t token_ctl = BitCtToWordCt(token_ct);
1774 uintptr_t name_ct = range_list_ptr->name_ct;
1775 int32_t* seen_idxs;
1776 char* sorted_ids;
1777 uint32_t* id_map;
1778 if (unlikely(bigstack_calloc_w(token_ctl, bitarr_ptr) ||
1779 bigstack_alloc_i32(name_ct, &seen_idxs))) {
1780 return kPglRetNomem;
1781 }
1782 // kludge to use CopySortStrboxSubset()
1783 SetAllBits(name_ct, R_CAST(uintptr_t*, seen_idxs));
1784 if (unlikely(CopySortStrboxSubset(R_CAST(uintptr_t*, seen_idxs), range_list_ptr->names, name_ct, range_list_ptr->name_max_blen, 0, 0, &sorted_ids, &id_map))) {
1785 return kPglRetNomem;
1786 }
1787 SetAllI32Arr(name_ct, seen_idxs);
1788 PglErr reterr = StringRangeListToBitarr(header_line, range_list_ptr, sorted_ids, id_map, range_list_flag, file_descrip, token_ct, fixed_len, comma_delim, *bitarr_ptr, seen_idxs);
1789 BigstackReset(seen_idxs);
1790 return reterr;
1791 }
1792
1793 uint32_t IntersectionRangeIsEmpty(const uintptr_t* bitarr1, const uintptr_t* bitarr2, uintptr_t start_idx, uintptr_t end_idx) {
1794 uintptr_t start_idxl = start_idx / kBitsPerWord;
1795 const uintptr_t start_idxlr = start_idx & (kBitsPerWord - 1);
1796 const uintptr_t end_idxl = end_idx / kBitsPerWord;
1797 const uintptr_t end_idxlr = end_idx & (kBitsPerWord - 1);
1798 if (start_idxl == end_idxl) {
1799 return ((bitarr1[start_idxl] & bitarr2[start_idxl] & ((k1LU << end_idxlr) - (k1LU << start_idxlr))) == 0);
1800 }
1801 if (start_idxlr) {
1802 if ((bitarr1[start_idxl] & bitarr2[start_idxl]) >> start_idxlr) {
1803 return 0;
1804 }
1805 ++start_idxl;
1806 }
1807 // can speed this up with vectorization, and/or bitwise-oring multiple
1808 // comparison results before each comparison to zero
1809 for (; start_idxl != end_idxl; ++start_idxl) {
1810 if (bitarr1[start_idxl] & bitarr2[start_idxl]) {
1811 return 0;
1812 }
1813 }
1814 if (end_idxlr) {
1815 if (bzhi(bitarr1[end_idxl] & bitarr2[end_idxl], end_idxlr)) {
1816 return 0;
1817 }
1818 }
1819 return 1;
1820 }
1821
1822 #ifdef USE_SSE42
1823 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) {
1824 uint32_t ct1 = 0;
1825 uint32_t ct2 = 0;
1826 uint32_t ct3 = 0;
1827 for (uint32_t widx = 0; widx != word_ct; ++widx) {
1828 const uintptr_t word1 = bitvec1[widx];
1829 const uintptr_t word2 = bitvec2[widx];
1830 ct1 += PopcountWord(word1);
1831 ct2 += PopcountWord(word2);
1832 ct3 += PopcountWord(word1 & word2);
1833 }
1834 *popcount1_ptr = ct1;
1835 *popcount2_ptr = ct2;
1836 *popcount_intersect_ptr = ct3;
1837 }
1838 #else
1839 static inline void PopcountVecsNoSse42Intersect3val(const VecW* __restrict vvec1_iter, const VecW* __restrict vvec2_iter, uint32_t vec_ct, uint32_t* __restrict popcount1_ptr, uint32_t* popcount2_ptr, uint32_t* __restrict popcount_intersect_ptr) {
1840 // ct must be a multiple of 3.
1841 assert(!(vec_ct % 3));
1842 const VecW m1 = VCONST_W(kMask5555);
1843 const VecW m2 = VCONST_W(kMask3333);
1844 const VecW m4 = VCONST_W(kMask0F0F);
1845 VecW acc1 = vecw_setzero();
1846 VecW acc2 = vecw_setzero();
1847 VecW acc3 = vecw_setzero();
1848 uintptr_t cur_incr = 30;
1849 for (; ; vec_ct -= cur_incr) {
1850 if (vec_ct < 30) {
1851 if (!vec_ct) {
1852 *popcount1_ptr = HsumW(acc1);
1853 *popcount2_ptr = HsumW(acc2);
1854 *popcount_intersect_ptr = HsumW(acc3);
1855 return;
1856 }
1857 cur_incr = vec_ct;
1858 }
1859 VecW inner_acc1 = vecw_setzero();
1860 VecW inner_acc2 = vecw_setzero();
1861 VecW inner_acc3 = vecw_setzero();
1862 const VecW* vvec1_stop = &(vvec1_iter[cur_incr]);
1863 do {
1864 VecW count1a = *vvec1_iter++;
1865 VecW count2a = *vvec2_iter++;
1866 VecW count3a = count1a & count2a;
1867 VecW count1b = *vvec1_iter++;
1868 VecW count2b = *vvec2_iter++;
1869 VecW count3b = count1b & count2b;
1870 VecW half1a = *vvec1_iter++;
1871 VecW half2a = *vvec2_iter++;
1872 const VecW half1b = vecw_srli(half1a, 1) & m1;
1873 const VecW half2b = vecw_srli(half2a, 1) & m1;
1874 half1a = half1a & m1;
1875 half2a = half2a & m1;
1876
1877 count1a = count1a - (vecw_srli(count1a, 1) & m1);
1878 count2a = count2a - (vecw_srli(count2a, 1) & m1);
1879 count3a = count3a - (vecw_srli(count3a, 1) & m1);
1880 count1b = count1b - (vecw_srli(count1b, 1) & m1);
1881 count2b = count2b - (vecw_srli(count2b, 1) & m1);
1882 count3b = count3b - (vecw_srli(count3b, 1) & m1);
1883 count1a = count1a + half1a;
1884 count2a = count2a + half2a;
1885 count3a = count3a + (half1a & half2a);
1886 count1b = count1b + half1b;
1887 count2b = count2b + half2b;
1888 count3b = count3b + (half1b & half2b);
1889
1890 count1a = (count1a & m2) + (vecw_srli(count1a, 2) & m2);
1891 count2a = (count2a & m2) + (vecw_srli(count2a, 2) & m2);
1892 count3a = (count3a & m2) + (vecw_srli(count3a, 2) & m2);
1893 count1a = count1a + (count1b & m2) + (vecw_srli(count1b, 2) & m2);
1894 count2a = count2a + (count2b & m2) + (vecw_srli(count2b, 2) & m2);
1895 count3a = count3a + (count3b & m2) + (vecw_srli(count3b, 2) & m2);
1896 inner_acc1 = inner_acc1 + (count1a & m4) + (vecw_srli(count1a, 4) & m4);
1897 inner_acc2 = inner_acc2 + (count2a & m4) + (vecw_srli(count2a, 4) & m4);
1898 inner_acc3 = inner_acc3 + (count3a & m4) + (vecw_srli(count3a, 4) & m4);
1899 } while (vvec1_iter < vvec1_stop);
1900 // too much register pressure to use prev_sad_result pattern?
1901 const VecW m0 = vecw_setzero();
1902 acc1 = acc1 + vecw_bytesum(inner_acc1, m0);
1903 acc2 = acc2 + vecw_bytesum(inner_acc2, m0);
1904 acc3 = acc3 + vecw_bytesum(inner_acc3, m0);
1905 }
1906 }
1907
1908 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) {
1909 const uint32_t trivec_ct = word_ct / (3 * kWordsPerVec);
1910 uint32_t ct1;
1911 uint32_t ct2;
1912 uint32_t ct3;
1913 PopcountVecsNoSse42Intersect3val(R_CAST(const VecW*, bitvec1), R_CAST(const VecW*, bitvec2), trivec_ct * 3, &ct1, &ct2, &ct3);
1914 const uint32_t words_consumed = trivec_ct * (3 * kWordsPerVec);
1915 bitvec1 = &(bitvec1[words_consumed]);
1916 bitvec2 = &(bitvec2[words_consumed]);
1917 const uint32_t remainder = word_ct - words_consumed;
1918 for (uint32_t widx = 0; widx != remainder; ++widx) {
1919 const uintptr_t word1 = bitvec1[widx];
1920 const uintptr_t word2 = bitvec2[widx];
1921 ct1 += PopcountWord(word1);
1922 ct2 += PopcountWord(word2);
1923 ct3 += PopcountWord(word1 & word2);
1924 }
1925 *popcount1_ptr = ct1;
1926 *popcount2_ptr = ct2;
1927 *popcount_intersect_ptr = ct3;
1928 }
1929 #endif
1930
1931 uint32_t AllBitsAreZero(const uintptr_t* bitarr, uintptr_t start_idx, uintptr_t end_idx) {
1932 uintptr_t start_idxl = start_idx / kBitsPerWord;
1933 const uintptr_t start_idxlr = start_idx & (kBitsPerWord - 1);
1934 const uintptr_t end_idxl = end_idx / kBitsPerWord;
1935 const uintptr_t end_idxlr = end_idx & (kBitsPerWord - 1);
1936 if (start_idxl == end_idxl) {
1937 return !(bitarr[start_idxl] & ((k1LU << end_idxlr) - (k1LU << start_idxlr)));
1938 }
1939 if (start_idxlr) {
1940 if (bitarr[start_idxl++] >> start_idxlr) {
1941 return 0;
1942 }
1943 }
1944 for (; start_idxl != end_idxl; ++start_idxl) {
1945 if (bitarr[start_idxl]) {
1946 return 0;
1947 }
1948 }
1949 if (!end_idxlr) {
1950 return 1;
1951 }
1952 return !bzhi(bitarr[end_idxl], end_idxlr);
1953 }
1954
1955 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) {
1956 // assumes len is positive, and relevant bits of target_bitarr are zero
1957 const uintptr_t* src_bitarr_iter = &(src_bitarr[src_start_bitidx / kBitsPerWord]);
1958 uint32_t src_rshift = src_start_bitidx % kBitsPerWord;
1959 uintptr_t* target_bitarr_iter = &(target_bitarr[target_start_bitidx / kBitsPerWord]);
1960 uint32_t target_initial_lshift = target_start_bitidx % kBitsPerWord;
1961 uintptr_t cur_src_word;
1962 if (target_initial_lshift) {
1963 const uint32_t initial_copy_bitct = kBitsPerWord - target_initial_lshift;
1964 if (len <= initial_copy_bitct) {
1965 goto CopyBitarrRange_last_partial_word;
1966 }
1967 cur_src_word = (*src_bitarr_iter) >> src_rshift;
1968 if (src_rshift >= target_initial_lshift) {
1969 ++src_bitarr_iter;
1970 cur_src_word |= (*src_bitarr_iter) << (kBitsPerWord - src_rshift);
1971 }
1972 *target_bitarr_iter++ |= cur_src_word << target_initial_lshift;
1973 src_rshift = (src_rshift + initial_copy_bitct) % kBitsPerWord;
1974 len -= initial_copy_bitct;
1975 }
1976 {
1977 const uintptr_t fullword_ct = len / kBitsPerWord;
1978 if (!src_rshift) {
1979 memcpy(target_bitarr_iter, src_bitarr_iter, fullword_ct * sizeof(intptr_t));
1980 target_bitarr_iter = &(target_bitarr_iter[fullword_ct]);
1981 src_bitarr_iter = &(src_bitarr_iter[fullword_ct]);
1982 } else {
1983 const uint32_t src_lshift = kBitsPerWord - src_rshift;
1984 cur_src_word = *src_bitarr_iter;
1985 for (uintptr_t widx = 0; widx != fullword_ct; ++widx) {
1986 const uintptr_t next_src_word = *(++src_bitarr_iter);
1987 *target_bitarr_iter++ = (cur_src_word >> src_rshift) | (next_src_word << src_lshift);
1988 cur_src_word = next_src_word;
1989 }
1990 }
1991 }
1992 len %= kBitsPerWord;
1993 if (len) {
1994 target_initial_lshift = 0;
1995 CopyBitarrRange_last_partial_word:
1996 cur_src_word = (*src_bitarr_iter) >> src_rshift;
1997 if (len + src_rshift > kBitsPerWord) {
1998 cur_src_word |= src_bitarr_iter[1] << (kBitsPerWord - src_rshift);
1999 }
2000 *target_bitarr_iter |= (cur_src_word & ((~k0LU) >> (kBitsPerWord - S_CAST(uint32_t, len)))) << target_initial_lshift;
2001 }
2002 }
2003
2004 void VerticalCounterUpdate(const uintptr_t* acc1, uint32_t acc1_vec_ct, uint32_t* rem15_and_255d15, VecW* acc4_8_32) {
2005 VcountIncr1To4(acc1, acc1_vec_ct, acc4_8_32);
2006 rem15_and_255d15[0] -= 1;
2007 if (!rem15_and_255d15[0]) {
2008 const uint32_t acc4_vec_ct = acc1_vec_ct * 4;
2009 VecW* acc8 = &(acc4_8_32[acc4_vec_ct]);
2010 Vcount0Incr4To8(acc4_vec_ct, acc4_8_32, acc8);
2011 rem15_and_255d15[0] = 15;
2012 rem15_and_255d15[1] -= 1;
2013 if (!rem15_and_255d15[1]) {
2014 const uint32_t acc8_vec_ct = acc4_vec_ct * 2;
2015 VecW* acc32 = &(acc8[acc8_vec_ct]);
2016 Vcount0Incr8To32(acc8_vec_ct, acc8, acc32);
2017 rem15_and_255d15[1] = 17;
2018 }
2019 }
2020 }
2021
2022 void FillWStarts(uint32_t thread_ct, uintptr_t start, uint64_t bit_ct, uintptr_t* starts) {
2023 starts[0] = start;
2024 for (uint32_t tidx = 1; tidx != thread_ct; ++tidx) {
2025 starts[tidx] = start + (bit_ct * tidx) / thread_ct;
2026 }
2027 }
2028
2029 #ifdef __LP64__
2030 void FillWSubsetStarts(const uintptr_t* subset, uint32_t thread_ct, uintptr_t start, uint64_t bit_ct, uintptr_t* starts) {
2031 assert(bit_ct);
2032 uintptr_t uidx = AdvTo1Bit(subset, start);
2033 uintptr_t prev_bit_idx = 0;
2034 starts[0] = uidx;
2035 for (uint32_t tidx = 1; tidx != thread_ct; ++tidx) {
2036 const uintptr_t bit_idx = (tidx * bit_ct) / thread_ct;
2037 if (bit_idx != prev_bit_idx) {
2038 uidx = FindNth1BitFrom(subset, uidx + 1, bit_idx - prev_bit_idx);
2039 prev_bit_idx = bit_idx;
2040 }
2041 starts[tidx] = uidx;
2042 }
2043 }
2044 #endif
2045
2046 // May want to have an multiallelic_set bitarray to accelerate this type of
2047 // operation? Probably only want to conditionally initialize it, and only
2048 // after variant filtering is complete, though.
2049 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) {
2050 if (!allele_idx_offsets) {
2051 return 0;
2052 }
2053 const uint32_t variant_ct = PopcountBitRange(variant_include, variant_uidx_start, variant_uidx_end);
2054 const uint32_t const_subtract = 2 - multiallelic_variant_ct_multiplier;
2055 uintptr_t result = 0;
2056 uintptr_t variant_uidx_base;
2057 uintptr_t cur_bits;
2058 BitIter1Start(variant_include, variant_uidx_start, &variant_uidx_base, &cur_bits);
2059 for (uint32_t uii = 0; uii != variant_ct; ++uii) {
2060 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
2061 const uintptr_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
2062 if (allele_ct != 2) {
2063 result += allele_ct - const_subtract;
2064 }
2065 }
2066 return result;
2067 }
2068
2069 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) {
2070 if (!allele_idx_offsets) {
2071 return 2;
2072 }
2073 if (raw_variant_ct == variant_ct) {
2074 return max_allele_ct;
2075 }
2076 uintptr_t variant_uidx_base = 0;
2077 uintptr_t cur_bits = variant_include[0];
2078 uintptr_t subset_max_allele_ct = 2;
2079 for (uint32_t uii = 0; uii != variant_ct; ++uii) {
2080 const uintptr_t variant_uidx = BitIter1(variant_include, &variant_uidx_base, &cur_bits);
2081 const uint32_t allele_ct = allele_idx_offsets[variant_uidx + 1] - allele_idx_offsets[variant_uidx];
2082 if (allele_ct > subset_max_allele_ct) {
2083 if (allele_ct == max_allele_ct) {
2084 return max_allele_ct;
2085 }
2086 subset_max_allele_ct = allele_ct;
2087 }
2088 }
2089 return subset_max_allele_ct;
2090 }
2091
2092 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) {
2093 // Minimize size of the largest chunk, under the condition that all
2094 // intermediate variant_idx values are divisible by alignment.
2095 //
2096 // There are three possibilities:
2097 // 1. The straightforward solution one gets from rounding cur_variant_idx
2098 // down, and (cur_variant_idx + variant_ct) up, is optimal. Call this
2099 // chunk size C.
2100 // 2. C - leading_idx_ct is ideal.
2101 // 3. C - trailing_idx_ct is ideal.
2102
2103 assert(cur_variant_ct);
2104 const uint32_t variant_idx_end = cur_variant_idx + cur_variant_ct;
2105 const uint32_t log2_align = ctzu32(alignment);
2106 const uint32_t leading_idx_ct = cur_variant_idx % alignment;
2107 const uint32_t trailing_idx_ct = (-variant_idx_end) % alignment;
2108 const uint32_t block_ct = (cur_variant_ct + leading_idx_ct + trailing_idx_ct) >> log2_align;
2109 uint32_t cur_variant_uidx_start = AdvTo1Bit(variant_include, first_variant_uidx);
2110 variant_uidx_starts[0] = cur_variant_uidx_start;
2111 vidx_starts[0] = cur_variant_idx;
2112 const uint32_t thread_ct = MINV(orig_thread_ct, block_ct);
2113 if (thread_ct > 1) {
2114 const uint32_t std_blocks_per_thread = 1 + (block_ct - 1) / thread_ct;
2115 // Possibilities 2 and 3 are only live if
2116 // block_ct == (std_blocks_per_thread - 1) * thread_ct + 1, or
2117 // block_ct == (std_blocks_per_thread - 1) * thread_ct + 2,
2118 // In the first situation, the best solution is
2119 // min(possibility 2, possibility 3).
2120 // In the second situation, the best solution is
2121 // max(possibility 2, possibility 3).
2122 uint32_t central_variant_ct = std_blocks_per_thread * alignment;
2123 uint32_t first_block_variant_ct = central_variant_ct - leading_idx_ct;
2124 const uint32_t remainder_m1 = block_ct - (std_blocks_per_thread - 1) * thread_ct - 1;
2125 if (remainder_m1 <= 1) {
2126 central_variant_ct -= alignment;
2127 if ((!remainder_m1) && (leading_idx_ct < trailing_idx_ct)) {
2128 first_block_variant_ct -= alignment;
2129 }
2130 }
2131 cur_variant_uidx_start = FindNth1BitFrom(variant_include, cur_variant_uidx_start + 1, first_block_variant_ct);
2132 cur_variant_idx += first_block_variant_ct;
2133 variant_uidx_starts[1] = cur_variant_uidx_start;
2134 vidx_starts[1] = cur_variant_idx;
2135 for (uint32_t tidx = 2; tidx != thread_ct; ++tidx) {
2136 cur_variant_uidx_start = FindNth1BitFrom(variant_include, cur_variant_uidx_start + 1, central_variant_ct);
2137 cur_variant_idx += central_variant_ct;
2138 // bugfix (14 Nov 2017): this decrement was in the wrong place
2139 if (tidx == remainder_m1) {
2140 central_variant_ct -= alignment;
2141 }
2142 variant_uidx_starts[tidx] = cur_variant_uidx_start;
2143 vidx_starts[tidx] = cur_variant_idx;
2144 }
2145 }
2146 if (thread_ct < orig_thread_ct) {
2147 uint32_t last_vidx_ct = variant_idx_end - vidx_starts[thread_ct - 1];
2148 cur_variant_uidx_start = FindNth1BitFrom(variant_include, cur_variant_uidx_start + 1, last_vidx_ct);
2149 for (uint32_t tidx = thread_ct; tidx != orig_thread_ct; ++tidx) {
2150 variant_uidx_starts[tidx] = cur_variant_uidx_start;
2151 }
2152 for (uint32_t tidx = thread_ct; tidx != orig_thread_ct; ++tidx) {
2153 vidx_starts[tidx] = variant_idx_end;
2154 }
2155 }
2156 vidx_starts[orig_thread_ct] = variant_idx_end;
2157 }
2158
2159 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) {
2160 // Starts reading from argv[cur_param_idx][cur_pos]. If a valid range is
2161 // next, range_start + rs_len + range_end + re_len are updated. If only a
2162 // single item is next, range_end is set to nullptr and range_start + rs_len
2163 // are updated. If there are no items left, range_start is set to nullptr.
2164 // If the input is not well-formed, 1 is returned instead of 0.
2165 uint32_t cur_param_idx = *cur_param_idx_ptr;
2166 if (cur_param_idx > param_ct) {
2167 *cur_arg_pptr = nullptr;
2168 return 0;
2169 }
2170 const char* cur_arg_ptr = *cur_arg_pptr;
2171 while (1) {
2172 char cc = *cur_arg_ptr;
2173 if (!cc) {
2174 *cur_param_idx_ptr = ++cur_param_idx;
2175 if (cur_param_idx > param_ct) {
2176 *range_start_ptr = nullptr;
2177 return 0;
2178 }
2179 cur_arg_ptr = argvk[cur_param_idx];
2180 cc = *cur_arg_ptr;
2181 }
2182 if (unlikely(cc == range_delim)) {
2183 return 1;
2184 }
2185 if (cc != ',') {
2186 break;
2187 }
2188 ++cur_arg_ptr;
2189 }
2190 *range_start_ptr = cur_arg_ptr;
2191 char cc;
2192 do {
2193 cc = *(++cur_arg_ptr);
2194 if ((!cc) || (cc == ',')) {
2195 *rs_len_ptr = cur_arg_ptr - (*range_start_ptr);
2196 *cur_arg_pptr = cur_arg_ptr;
2197 *range_end_ptr = nullptr;
2198 return 0;
2199 }
2200 } while (cc != range_delim);
2201 *rs_len_ptr = cur_arg_ptr - (*range_start_ptr);
2202 cc = *(++cur_arg_ptr);
2203 if (unlikely(((*rs_len_ptr) > kMaxIdSlen) || (!cc) || (cc == ',') || (cc == range_delim))) {
2204 return 1;
2205 }
2206 *range_end_ptr = cur_arg_ptr;
2207 do {
2208 cc = *(++cur_arg_ptr);
2209 if (unlikely(cc == range_delim)) {
2210 return 1;
2211 }
2212 } while (cc && (cc != ','));
2213 *re_len_ptr = cur_arg_ptr - (*range_end_ptr);
2214 if (unlikely((*re_len_ptr) > kMaxIdSlen)) {
2215 return 1;
2216 }
2217 *cur_arg_pptr = cur_arg_ptr;
2218 return 0;
2219 }
2220
2221 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) {
2222 uint32_t name_ct = 0;
2223 uint32_t cur_param_idx = 1;
2224 uint32_t name_max_blen = 0;
2225 const char* cur_arg_ptr;
2226 const char* range_start;
2227 uint32_t rs_len;
2228 const char* range_end;
2229 uint32_t re_len;
2230 unsigned char* cur_name_starts_range;
2231 uint32_t last_val;
2232 uint32_t cur_val;
2233 // two passes. first pass: count arguments, determine name_max_blen;
2234 // then allocate memory; then fill it.
2235 if (param_ct) {
2236 cur_arg_ptr = argvk[1];
2237 while (1) {
2238 if (unlikely(ParseNextRange(argvk, param_ct, range_delim, &cur_param_idx, &cur_arg_ptr, &range_start, &rs_len, &range_end, &re_len))) {
2239 logerrprintfww("Error: Invalid %s argument '%s'.\n", argvk[0], argvk[cur_param_idx]);
2240 logerrputs(errstr_append);
2241 return kPglRetInvalidCmdline;
2242 }
2243 if (!range_start) {
2244 break;
2245 }
2246 ++name_ct;
2247 if (rs_len > name_max_blen) {
2248 name_max_blen = rs_len; // does NOT include trailing null yet
2249 }
2250 if (range_end) {
2251 ++name_ct;
2252 if (re_len > name_max_blen) {
2253 name_max_blen = re_len;
2254 }
2255 }
2256 }
2257 }
2258 if (unlikely(!name_ct)) {
2259 logerrprintf("Error: %s requires at least one value.\n%s", argvk[0], errstr_append);
2260 return kPglRetInvalidCmdline;
2261 }
2262 range_list_ptr->name_max_blen = ++name_max_blen;
2263 range_list_ptr->name_ct = name_ct;
2264 if (unlikely(pgl_malloc(name_ct * (S_CAST(uintptr_t, name_max_blen) + 1), &range_list_ptr->names))) {
2265 return kPglRetNomem;
2266 }
2267 range_list_ptr->starts_range = R_CAST(unsigned char*, &(range_list_ptr->names[name_ct * S_CAST(uintptr_t, name_max_blen)]));
2268 char* cur_name_str = range_list_ptr->names;
2269 cur_name_starts_range = range_list_ptr->starts_range;
2270 cur_param_idx = 1;
2271 cur_arg_ptr = argvk[1];
2272 while (1) {
2273 // second pass; this can't fail since we already validated
2274 ParseNextRange(argvk, param_ct, range_delim, &cur_param_idx, &cur_arg_ptr, &range_start, &rs_len, &range_end, &re_len);
2275 if (!range_start) {
2276 if (require_posint) {
2277 last_val = 0;
2278 for (cur_param_idx = 0; cur_param_idx != name_ct; ++cur_param_idx) {
2279 cur_name_str = &(range_list_ptr->names[cur_param_idx * S_CAST(uintptr_t, name_max_blen)]);
2280 const char* dup_check = cur_name_str; // actually a numeric check
2281 do {
2282 if (unlikely(IsNotDigit(*dup_check))) {
2283 logerrprintfww("Error: Invalid %s argument '%s'.\n", argvk[0], cur_name_str);
2284 return kPglRetInvalidCmdline;
2285 }
2286 } while (*(++dup_check));
2287 if (unlikely(ScanPosintDefcapx(cur_name_str, &cur_val))) {
2288 logerrprintfww("Error: Invalid %s argument '%s'.\n", argvk[0], cur_name_str);
2289 return kPglRetInvalidCmdline;
2290 }
2291 if (range_list_ptr->starts_range[cur_param_idx]) {
2292 last_val = cur_val;
2293 } else {
2294 if (unlikely(cur_val <= last_val)) {
2295 logerrprintfww("Error: Invalid %s range '%s-%s'.\n", argvk[0], &(range_list_ptr->names[(cur_param_idx - 1) * name_max_blen]), cur_name_str);
2296 return kPglRetInvalidCmdline;
2297 }
2298 last_val = 0;
2299 }
2300 }
2301 }
2302 return kPglRetSuccess;
2303 }
2304 memcpyx(cur_name_str, range_start, rs_len, '\0');
2305 const char* dup_check = range_list_ptr->names;
2306 while (dup_check < cur_name_str) {
2307 if (unlikely(memequal(dup_check, cur_name_str, rs_len + 1))) {
2308 logerrprintfww("Error: Duplicate %s argument '%s'.\n", argvk[0], cur_name_str);
2309 return kPglRetInvalidCmdline;
2310 }
2311 dup_check = &(dup_check[name_max_blen]);
2312 }
2313 cur_name_str = &(cur_name_str[name_max_blen]);
2314 if (range_end) {
2315 *cur_name_starts_range++ = 1;
2316 memcpyx(cur_name_str, range_end, re_len, '\0');
2317 dup_check = range_list_ptr->names;
2318 while (dup_check < cur_name_str) {
2319 if (unlikely(memequal(dup_check, cur_name_str, rs_len + 1))) {
2320 logerrprintfww("Error: Duplicate %s argument '%s'.\n", argvk[0], cur_name_str);
2321 return kPglRetInvalidCmdline;
2322 }
2323 dup_check = &(dup_check[name_max_blen]);
2324 }
2325 cur_name_str = &(cur_name_str[name_max_blen]);
2326 *cur_name_starts_range++ = 0;
2327 } else {
2328 *cur_name_starts_range++ = 0;
2329 }
2330 }
2331 }
2332
2333 /* Analytically finds all real roots of x^3 + ax^2 + bx + c, saving them in
2334 * solutions[] (sorted from smallest to largest), and returning the count.
2335 * Multiple roots are only returned/counted once.
2336 * (TODO: Move this to something like plink2_math. Note that
2337 * include/plink2_math is not an option because of the GPL vs. LGPL
2338 * difference.)
2339 * gsl_poly_solve_cubic() in the GNU Scientific Library was used as a template
2340 * when writing this function. Its license text follows:
2341 *
2342 * Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007, 2009 Brian Gough
2343 *
2344 * This program is free software; you can redistribute it and/or modify it
2345 * under the terms of the GNU General Public License as published by the Free
2346 * Software Foundation; either version 3 of the License, or (at your option)
2347 * any later version.
2348 *
2349 * This program is distributed in the hope that it will be useful, but WITHOUT
2350 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
2351 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
2352 * more details.
2353 *
2354 * You should have received a copy of the GNU General Public License along with
2355 * this program; if not, write to the Free Software Foundation, Inc., 51
2356 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
2357 */
2358 uint32_t CubicRealRoots(double coef_a, double coef_b, double coef_c, STD_ARRAY_REF(double, 3) solutions) {
2359 const double a2 = coef_a * coef_a;
2360 const double small_q = a2 - 3 * coef_b;
2361 const double small_r = 2 * a2 * coef_a - 9 * coef_a * coef_b + 27 * coef_c;
2362 const double small_r2 = small_r * small_r;
2363 const double small_q3_x4 = 4 * small_q * small_q * small_q;
2364 const double coef_a_div3 = coef_a * (1.0 / 3.0);
2365 if (small_r2 == small_q3_x4) {
2366 // Not a big deal if we miss this branch due to floating-point error, as
2367 // long as it doesn't cause us to divide by zero later.
2368 const double sqrt_q = (1.0 / 3.0) * sqrt(small_q);
2369 if (small_r > 0.0) {
2370 solutions[0] = -2 * sqrt_q - coef_a_div3;
2371 solutions[1] = sqrt_q - coef_a_div3;
2372 } else {
2373 solutions[0] = -sqrt_q - coef_a_div3;
2374 solutions[1] = 2 * sqrt_q - coef_a_div3;
2375 }
2376 // kEpsilon configured to 2^{-30} as of this writing.
2377 return 2 - (solutions[1] - solutions[0] < kEpsilon);
2378 }
2379 const double qq = small_q * (1.0 / 9.0);
2380 const double rr = small_r * (1.0 / 54.0);
2381 // r2 = small_r2 / 54^2
2382 // q3 = small_q3_x4 / 54^2
2383 // We check small_r2 > small_q3_x4 instead of r2 > q3 because (i) it lets us
2384 // skip a few unnecessary operations and (ii) it also plugs a divide-by-zero
2385 // hole in the GSL implementation (R == 0, Q slightly below cbrt(min positive
2386 // double)).
2387 if (small_r2 > small_q3_x4) {
2388 const double neg_sgn_r = (small_r >= 0)? -1 : 1;
2389 const double aa = neg_sgn_r * cbrt(fabs(rr) + sqrt(small_r2 - small_q3_x4) * (1.0 / 54.0));
2390 // As long as fabs(rr) is at least the ~2.23e-308 subnormal threshold, aa
2391 // can't be zero.
2392 // If fabs(rr) is smaller, small_r2 must be 0, small_r2 > small_q3_x4
2393 // indicates that small_q3_x4 must be negative, and there's no
2394 // underflow-to-zero risk in evaluating small_r2 - small_q3_x4.
2395 const double bb = qq / aa;
2396 solutions[0] = aa + bb - coef_a_div3;
2397 return 1;
2398 }
2399 // 0 <= small_r2 < small_q3_x4; no risk of qq < 0 or sqrt_q * qq == 0.
2400 const double sqrt_q = sqrt(qq);
2401 const double ratio = rr / (sqrt_q * qq);
2402 const double theta_div3 = acos(ratio) * (1.0 / 3.0);
2403 const double norm = -2 * sqrt_q;
2404 double sol0 = norm * cos(theta_div3) - coef_a_div3;
2405 double sol1 = norm * cos(theta_div3 + (2.0 * kPi / 3.0)) - coef_a_div3;
2406 double sol2 = norm * cos(theta_div3 - (2.0 * kPi / 3.0)) - coef_a_div3;
2407 // sort and check for within-epsilon equality
2408 if (sol0 > sol1) {
2409 const double dxx = sol0;
2410 sol0 = sol1;
2411 sol1 = dxx;
2412 }
2413 if (sol1 > sol2) {
2414 double dxx = sol1;
2415 sol1 = sol2;
2416 sol2 = dxx;
2417 if (sol0 > sol1) {
2418 dxx = sol0;
2419 sol0 = sol1;
2420 sol1 = dxx;
2421 }
2422 }
2423 // Now sol0 <= sol1 <= sol2.
2424 solutions[0] = sol0;
2425 if (sol1 - sol0 < kEpsilon) {
2426 solutions[1] = sol2;
2427 return 2 - (sol2 - sol0 < kEpsilon);
2428 }
2429 solutions[1] = sol1;
2430 solutions[2] = sol2;
2431 return 3 - (sol2 - sol1 < kEpsilon);
2432 }
2433
2434 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) {
2435 uint32_t id_htable_size = GetHtableFastSize(item_ct);
2436 // if store_all_dups, up to 8 bytes per variant in extra_alloc for duplicate
2437 // tracking, as well as a small amount of per-thread temporary workspace
2438 const uint32_t store_all_dups = (htable_dup_base_ptr != nullptr);
2439 uintptr_t nonhtable_alloc = 0;
2440 if (store_all_dups) {
2441 const uint32_t actual_thread_ct = PopulateIdHtableMtDupstoreThreadCt(max_thread_ct, item_ct);
2442 // "2 *" in front of second term is temporary
2443 nonhtable_alloc = actual_thread_ct * kDupstoreThreadWkspace + 2 * RoundUpPow2(item_ct * 2 * sizeof(int32_t), kCacheline);
2444 }
2445 uintptr_t max_bytes = RoundDownPow2(bigstack_left(), kCacheline);
2446 // force max_bytes >= 5 so leqprime() doesn't fail
2447 // (not actually relevant any more, but whatever)
2448 if (nonhtable_alloc + (item_ct + 6) * sizeof(int32_t) > max_bytes) {
2449 return kPglRetNomem;
2450 }
2451 max_bytes -= nonhtable_alloc;
2452 if (id_htable_size * sizeof(int32_t) + fast_size_min_extra_bytes > max_bytes) {
2453 id_htable_size = max_bytes / sizeof(int32_t);
2454 // id_htable_size = leqprime((max_bytes / sizeof(int32_t)) - 1);
2455 const uint32_t min_htable_size = GetHtableMinSize(item_ct);
2456 if (id_htable_size < min_htable_size) {
2457 id_htable_size = min_htable_size;
2458 }
2459 }
2460 *id_htable_ptr = S_CAST(uint32_t*, bigstack_alloc_raw_rd(id_htable_size * sizeof(int32_t)));
2461 if (store_all_dups) {
2462 *htable_dup_base_ptr = &((*id_htable_ptr)[RoundUpPow2(id_htable_size, kInt32PerCacheline)]);
2463 }
2464 *id_htable_size_ptr = id_htable_size;
2465 return PopulateIdHtableMt(g_bigstack_end, subset_mask, item_ids, item_ct, store_all_dups, id_htable_size, max_thread_ct, &g_bigstack_base, *id_htable_ptr, dup_ct_ptr);
2466 }
2467
2468 uint32_t Edit1Match(const char* s1, const char* s2, uint32_t len1, uint32_t len2) {
2469 // Permit one difference of the following forms (Damerau-Levenshtein distance
2470 // 1):
2471 // - inserted/deleted character
2472 // - replaced character
2473 // - adjacent pair of swapped characters
2474 // Returns 1 on approximate match, 0 on nonmatch.
2475 // With only one difference allowed, it is unnecessary to use a
2476 // fully-powered quadratic-time DP algorithm; instead, given the lengths of
2477 // the two strings, we select the appropriate linear-time loop.
2478 if (abs_i32(len1 - len2) > 1) {
2479 return 0;
2480 }
2481 uintptr_t mismatch_pos = FirstUnequal(s1, s2, len1);
2482 if (mismatch_pos == len1) {
2483 // bugfix (5 Nov 2019): this was backwards...
2484 return 1;
2485 }
2486 if (len1 != len2) {
2487 // At least one mismatch guaranteed.
2488 if (len1 < len2) {
2489 return memequal(&(s1[mismatch_pos]), &(s2[mismatch_pos + 1]), len1 - mismatch_pos);
2490 }
2491 return memequal(&(s1[mismatch_pos + 1]), &(s2[mismatch_pos]), len2 - mismatch_pos);
2492 }
2493 // Strings are equal length, and we have at least one mismatch.
2494 // Two ways to still have an approximate match:
2495 // 1. Remainder of strings are equal.
2496 // 2. Next character also differs, but due to transposition. Remainder of
2497 // strings are equal.
2498 if (s1[mismatch_pos + 1] != s2[mismatch_pos + 1]) {
2499 if ((s1[mismatch_pos] != s2[mismatch_pos + 1]) || (s1[mismatch_pos + 1] != s2[mismatch_pos])) {
2500 return 0;
2501 }
2502 ++mismatch_pos;
2503 }
2504 const uintptr_t post_mismatch_pos = mismatch_pos + 1;
2505 return memequal(&(s1[post_mismatch_pos]), &(s2[post_mismatch_pos]), len1 - post_mismatch_pos);
2506 }
2507
2508 CONSTI32(kMaxEqualHelpParams, 64);
2509
2510 void HelpPrint(const char* cur_params, HelpCtrl* help_ctrl_ptr, uint32_t postprint_newline, const char* payload) {
2511 if (help_ctrl_ptr->param_ct) {
2512 const char* params_iter = cur_params;
2513 uint32_t cur_param_ct = 0;
2514 const char* cur_param_starts[kMaxEqualHelpParams];
2515 uint32_t cur_param_slens[kMaxEqualHelpParams];
2516 while (*params_iter) {
2517 cur_param_starts[cur_param_ct] = params_iter;
2518 const uint32_t cur_slen = strlen(params_iter);
2519 cur_param_slens[cur_param_ct++] = cur_slen;
2520 params_iter = &(params_iter[cur_slen + 1]);
2521 }
2522 if (help_ctrl_ptr->iters_left) {
2523 const uint32_t orig_unmatched_ct = help_ctrl_ptr->unmatched_ct;
2524 if (orig_unmatched_ct) {
2525 uint32_t arg_uidx = 0;
2526 if (help_ctrl_ptr->iters_left == 2) {
2527 // First pass: only exact matches.
2528 for (uint32_t arg_idx = 0; arg_idx != orig_unmatched_ct; ++arg_idx, ++arg_uidx) {
2529 arg_uidx = AdvTo0Bit(help_ctrl_ptr->all_match_arr, arg_uidx);
2530 const char* cur_arg = help_ctrl_ptr->argv[arg_uidx];
2531 const uint32_t cur_arg_slen = help_ctrl_ptr->param_slens[arg_uidx];
2532 for (uint32_t cur_param_idx = 0; cur_param_idx != cur_param_ct; ++cur_param_idx) {
2533 if ((cur_arg_slen == cur_param_slens[cur_param_idx]) && memequal(cur_arg, cur_param_starts[cur_param_idx], cur_arg_slen)) {
2534 SetBit(arg_uidx, help_ctrl_ptr->perfect_match_arr);
2535 SetBit(arg_uidx, help_ctrl_ptr->prefix_match_arr);
2536 SetBit(arg_uidx, help_ctrl_ptr->all_match_arr);
2537 help_ctrl_ptr->unmatched_ct -= 1;
2538 break;
2539 }
2540 }
2541 }
2542 } else {
2543 // Second pass: Prefix matches.
2544 for (uint32_t arg_idx = 0; arg_idx != orig_unmatched_ct; ++arg_idx, ++arg_uidx) {
2545 arg_uidx = AdvTo0Bit(help_ctrl_ptr->all_match_arr, arg_uidx);
2546 const char* cur_arg = help_ctrl_ptr->argv[arg_uidx];
2547 const uint32_t cur_arg_slen = help_ctrl_ptr->param_slens[arg_uidx];
2548 for (uint32_t cur_param_idx = 0; cur_param_idx != cur_param_ct; ++cur_param_idx) {
2549 if (cur_param_slens[cur_param_idx] > cur_arg_slen) {
2550 if (memequal(cur_arg, cur_param_starts[cur_param_idx], cur_arg_slen)) {
2551 SetBit(arg_uidx, help_ctrl_ptr->prefix_match_arr);
2552 SetBit(arg_uidx, help_ctrl_ptr->all_match_arr);
2553 help_ctrl_ptr->unmatched_ct -= 1;
2554 break;
2555 }
2556 }
2557 }
2558 }
2559 }
2560 }
2561 } else {
2562 uint32_t print_this = 0;
2563 for (uint32_t arg_uidx = 0; arg_uidx != help_ctrl_ptr->param_ct; ++arg_uidx) {
2564 if (IsSet(help_ctrl_ptr->prefix_match_arr, arg_uidx)) {
2565 // Current user-provided help argument has at least one prefix
2566 // match...
2567 if (!print_this) {
2568 const char* cur_arg = help_ctrl_ptr->argv[arg_uidx];
2569 const uint32_t cur_arg_slen = help_ctrl_ptr->param_slens[arg_uidx];
2570 if (IsSet(help_ctrl_ptr->perfect_match_arr, arg_uidx)) {
2571 // ...and at least one exact match. So we only care about an
2572 // exact match.
2573 for (uint32_t cur_param_idx = 0; cur_param_idx != cur_param_ct; ++cur_param_idx) {
2574 if ((cur_arg_slen == cur_param_slens[cur_param_idx]) && memequal(cur_arg, cur_param_starts[cur_param_idx], cur_arg_slen)) {
2575 print_this = 1;
2576 break;
2577 }
2578 }
2579 } else {
2580 for (uint32_t cur_param_idx = 0; cur_param_idx != cur_param_ct; ++cur_param_idx) {
2581 if (cur_param_slens[cur_param_idx] > cur_arg_slen) {
2582 if (memequal(cur_arg, cur_param_starts[cur_param_idx], cur_arg_slen)) {
2583 print_this = 1;
2584 break;
2585 }
2586 }
2587 }
2588 }
2589 }
2590 } else {
2591 // Current user-provided help argument does not have an exact or
2592 // prefix match. Print current help text if it's within
2593 // Damerau-Levenshtein distance 1 of any index term.
2594 for (uint32_t cur_param_idx = 0; cur_param_idx != cur_param_ct; ++cur_param_idx) {
2595 if (Edit1Match(cur_param_starts[cur_param_idx], help_ctrl_ptr->argv[arg_uidx], cur_param_slens[cur_param_idx], help_ctrl_ptr->param_slens[arg_uidx])) {
2596 print_this = 1;
2597 if (!IsSet(help_ctrl_ptr->all_match_arr, arg_uidx)) {
2598 SetBit(arg_uidx, help_ctrl_ptr->all_match_arr);
2599 help_ctrl_ptr->unmatched_ct -= 1;
2600 }
2601 break;
2602 }
2603 }
2604 }
2605 }
2606 if (print_this) {
2607 const uint32_t payload_slen = strlen(payload);
2608 const char* payload_end;
2609 if (payload[payload_slen - 2] == '\n') {
2610 payload_end = &(payload[payload_slen - 1]);
2611 } else {
2612 payload_end = &(payload[payload_slen]);
2613 }
2614 if (help_ctrl_ptr->preprint_newline) {
2615 putc_unlocked('\n', stdout);
2616 }
2617 help_ctrl_ptr->preprint_newline = postprint_newline;
2618 const char* payload_iter = payload;
2619 do {
2620 const char* line_end = AdvPastDelim(payload_iter, '\n');
2621 uint32_t line_slen = S_CAST(uint32_t, line_end - payload_iter);
2622 if (line_slen > 2) {
2623 payload_iter = &(payload_iter[2]);
2624 line_slen -= 2;
2625 }
2626 memcpyx(g_textbuf, payload_iter, line_slen, '\0');
2627 fputs(g_textbuf, stdout);
2628 payload_iter = line_end;
2629 } while (payload_iter < payload_end);
2630 }
2631 }
2632 } else {
2633 fputs(payload, stdout);
2634 }
2635 }
2636
2637
2638 void PreinitPlink2CmdlineMeta(Plink2CmdlineMeta* pcmp) {
2639 pcmp->subst_argv = nullptr;
2640 pcmp->script_buf = nullptr;
2641 pcmp->rerun_buf = nullptr;
2642 pcmp->flag_buf = nullptr;
2643 pcmp->flag_map = nullptr;
2644 }
2645
2646 const char kErrstrVarRecordTooLarge[] = "Error: Variant record size exceeds ~4 GiB limit.\n";
2647 const char kErrstrReadCorrupted[] = "File appears to be corrupted";
2648
2649 // assumes logfile is open
2650 void DispExitMsg(PglErr reterr) {
2651 if (reterr) {
2652 if (reterr == kPglRetNomem) {
2653 logputs("\n");
2654 logerrputs(kErrstrNomem);
2655 if (g_failed_alloc_attempt_size) {
2656 logerrprintf("Failed allocation size: %" PRIu64 "\n", g_failed_alloc_attempt_size);
2657 }
2658 // kPglRetReadFail no longer gets a message here, for the same reason
2659 // kPglRetOpenFail doesn't: it's important to know which file we failed
2660 // to read.
2661 } else if (reterr == kPglRetWriteFail) {
2662 logputs("\n");
2663 if (errno) {
2664 logerrprintfww(kErrstrWrite, strerror(errno));
2665 } else {
2666 // Defensive.
2667 logerrputs("Error: File write failure: Untracked cause.\n");
2668 }
2669 } else if (reterr == kPglRetThreadCreateFail) {
2670 logputs("\n");
2671 logerrputs(kErrstrThreadCreate);
2672 } else if (reterr == kPglRetVarRecordTooLarge) {
2673 logputs("\n");
2674 logerrputs(kErrstrVarRecordTooLarge);
2675 } else if (reterr == kPglRetLongLine) {
2676 logputs("\n");
2677 logerrprintf("Error: Unhandled internal line-too-long message.\n");
2678 } else if (reterr == kPglRetEof) {
2679 logputs("\n");
2680 logerrprintf("Error: Unhandled internal EOF message.\n");
2681 }
2682 }
2683 }
2684
2685 // useful when there's e.g. a filename and an optional modifier, and we want to
2686 // permit either parmeter ordering
2687 BoolErr CheckExtraParam(const char* const* argvk, const char* permitted_modif, uint32_t* other_idx_ptr) {
2688 const uint32_t idx_base = *other_idx_ptr;
2689 if (!strcmp(argvk[idx_base], permitted_modif)) {
2690 *other_idx_ptr = idx_base + 1;
2691 } else if (strcmp(argvk[idx_base + 1], permitted_modif)) {
2692 logerrprintf("Error: Invalid %s argument sequence.\n", argvk[0]);
2693 return 1;
2694 }
2695 return 0;
2696 }
2697
2698 char ExtractCharParam(const char* ss) {
2699 // maps c, 'c', and "c" to c, and anything else to the null char. This is
2700 // intended to support e.g. always using '#' to designate a # argument
2701 // without worrying about differences between shells.
2702 const char cc = ss[0];
2703 if (((cc == '\'') || (cc == '"')) && (ss[1]) && (ss[2] == cc) && (!ss[3])) {
2704 return ss[1];
2705 }
2706 if (cc && (!ss[1])) {
2707 return cc;
2708 }
2709 return '\0';
2710 }
2711
2712 PglErr CmdlineAllocString(const char* source, const char* flag_name, uint32_t max_slen, char** sbuf_ptr) {
2713 const uint32_t slen = strlen(source);
2714 if (unlikely(slen > max_slen)) {
2715 logerrprintf("Error: %s argument too long.\n", flag_name);
2716 return kPglRetInvalidCmdline;
2717 }
2718 const uint32_t blen = slen + 1;
2719 if (unlikely(pgl_malloc(blen, sbuf_ptr))) {
2720 return kPglRetNomem;
2721 }
2722 memcpy(*sbuf_ptr, source, blen);
2723 return kPglRetSuccess;
2724 }
2725
2726 PglErr AllocFname(const char* source, const char* flagname_p, uint32_t extra_size, char** fnbuf_ptr) {
2727 const uint32_t blen = strlen(source) + 1;
2728 if (unlikely(blen > (kPglFnamesize - extra_size))) {
2729 logerrprintf("Error: --%s filename too long.\n", flagname_p);
2730 return kPglRetOpenFail;
2731 }
2732 if (unlikely(pgl_malloc(blen + extra_size, fnbuf_ptr))) {
2733 return kPglRetNomem;
2734 }
2735 memcpy(*fnbuf_ptr, source, blen);
2736 return kPglRetSuccess;
2737 }
2738
2739 PglErr AllocAndFlatten(const char* const* sources, uint32_t param_ct, uint32_t max_blen, char** flattened_buf_ptr) {
2740 uintptr_t tot_blen = 1;
2741 for (uint32_t param_idx = 0; param_idx != param_ct; ++param_idx) {
2742 const uint32_t cur_blen = 1 + strlen(sources[param_idx]);
2743 if (cur_blen > max_blen) {
2744 return kPglRetInvalidCmdline;
2745 }
2746 tot_blen += cur_blen;
2747 }
2748 char* buf_iter;
2749 if (pgl_malloc(tot_blen, &buf_iter)) {
2750 return kPglRetNomem;
2751 }
2752 *flattened_buf_ptr = buf_iter;
2753 for (uint32_t param_idx = 0; param_idx != param_ct; ++param_idx) {
2754 buf_iter = strcpyax(buf_iter, sources[param_idx], '\0');
2755 }
2756 *buf_iter = '\0';
2757 return kPglRetSuccess;
2758 }
2759
2760 PglErr Rerun(const char* ver_str, const char* ver_str2, const char* prog_name_str, uint32_t rerun_argv_pos, uint32_t rerun_parameter_present, int32_t* argc_ptr, uint32_t* first_arg_idx_ptr, char*** argv_ptr, char*** subst_argv_ptr, char** rerun_buf_ptr) {
2761 // caller is responsible for freeing rerun_buf
2762
2763 // ok, requiring zlib/zstd here is totally not worth it
2764 FILE* rerunfile = nullptr;
2765
2766 char** subst_argv2 = nullptr;
2767 char** argv = *argv_ptr;
2768 char* rerun_fname = rerun_parameter_present? argv[rerun_argv_pos + 1] : g_textbuf;
2769 uintptr_t line_idx = 1;
2770 PglErr reterr = kPglRetSuccess;
2771 {
2772 if (!rerun_parameter_present) {
2773 char* write_iter = strcpya(rerun_fname, prog_name_str);
2774 snprintf(write_iter, kMaxOutfnameExtBlen, ".log");
2775 }
2776 rerunfile = fopen(rerun_fname, FOPEN_RB);
2777 if (unlikely(!rerunfile)) {
2778 goto Rerun_ret_OPEN_FAIL;
2779 }
2780 char* textbuf = g_textbuf;
2781 textbuf[kMaxMediumLine - 1] = ' ';
2782 if (unlikely(!fgets(textbuf, kMaxMediumLine, rerunfile))) {
2783 fputs(ver_str, stdout);
2784 fputs(ver_str2, stdout);
2785 fputs("Error: Empty log file for --rerun.\n", stderr);
2786 goto Rerun_ret_MALFORMED_INPUT;
2787 }
2788 if (unlikely(!textbuf[kMaxMediumLine - 1])) {
2789 goto Rerun_ret_LONG_LINE;
2790 }
2791 if (unlikely(!fgets(textbuf, kMaxMediumLine, rerunfile))) {
2792 fputs(ver_str, stdout);
2793 fputs(ver_str2, stdout);
2794 fputs("Error: Only one line in --rerun log file.\n", stderr);
2795 goto Rerun_ret_MALFORMED_INPUT;
2796 }
2797 ++line_idx;
2798 if (unlikely(!textbuf[kMaxMediumLine - 1])) {
2799 goto Rerun_ret_LONG_LINE;
2800 }
2801 // don't bother supporting "xx arguments: --aa bb --cc --dd" format
2802 while ((!StrStartsWithUnsafe(textbuf, "Options in effect:")) || (textbuf[strlen("Options in effect:")] >= ' ')) {
2803 ++line_idx;
2804 if (unlikely(!fgets(textbuf, kMaxMediumLine, rerunfile))) {
2805 fputs(ver_str, stdout);
2806 fputs(ver_str2, stdout);
2807 fputs("Error: Invalid log file for --rerun.\n", stderr);
2808 goto Rerun_ret_MALFORMED_INPUT;
2809 }
2810 }
2811 char* all_args_write_iter = textbuf;
2812 char* textbuf_limit = &(textbuf[kMaxMediumLine]);
2813 uint32_t loaded_arg_ct = 0;
2814 // We load each of the option lines in sequence into textbuf, always
2815 // overwriting the previous line's newline. (Note that textbuf[] has
2816 // size > 2 * kMaxMediumLine; this lets us avoid additional
2817 // dynamic memory allocation as long as we impose the constraint that all
2818 // lines combined add up to less than kMaxMediumLine.)
2819 while (1) {
2820 all_args_write_iter[kMaxMediumLine - 1] = ' ';
2821 if (!fgets(all_args_write_iter, kMaxMediumLine, rerunfile)) {
2822 break;
2823 }
2824 ++line_idx;
2825 if (unlikely(!all_args_write_iter[kMaxMediumLine - 1])) {
2826 goto Rerun_ret_LONG_LINE;
2827 }
2828 char* arg_iter = FirstNonTspace(all_args_write_iter);
2829 if (IsEolnKns(*arg_iter)) {
2830 *all_args_write_iter = '\0';
2831 break;
2832 }
2833 char* token_end;
2834 do {
2835 token_end = CurTokenEnd(arg_iter);
2836 ++loaded_arg_ct;
2837 arg_iter = FirstNonTspace(token_end);
2838 } while (!IsEolnKns(*arg_iter));
2839 all_args_write_iter = token_end;
2840 if (unlikely(all_args_write_iter >= textbuf_limit)) {
2841 fputs(ver_str, stdout);
2842 fputs(ver_str2, stdout);
2843 fputs("Error: --rerun argument sequence too long.\n", stderr);
2844 goto Rerun_ret_MALFORMED_INPUT;
2845 }
2846 }
2847 fclose_null(&rerunfile);
2848 const uint32_t line_byte_ct = 1 + S_CAST(uintptr_t, all_args_write_iter - textbuf);
2849 char* rerun_buf;
2850 if (unlikely(pgl_malloc(line_byte_ct, &rerun_buf))) {
2851 goto Rerun_ret_NOMEM;
2852 }
2853 *rerun_buf_ptr = rerun_buf;
2854 memcpy(rerun_buf, textbuf, line_byte_ct);
2855 const uint32_t argc = *argc_ptr;
2856 const uint32_t first_arg_idx = *first_arg_idx_ptr;
2857 char* rerun_first_token = FirstNonTspace(rerun_buf);
2858 const char* arg_iter = rerun_first_token;
2859 // now use textbuf as a lame bitfield
2860 memset(textbuf, 1, loaded_arg_ct);
2861 uint32_t loaded_arg_idx = 0;
2862 uint32_t duplicate_arg_ct = 0;
2863 do {
2864 if (unlikely(NoMoreTokensKns(arg_iter))) {
2865 fputs(ver_str, stdout);
2866 fputs(ver_str2, stdout);
2867 fputs("Error: Line 2 of --rerun log file has fewer tokens than expected.\n", stderr);
2868 goto Rerun_ret_MALFORMED_INPUT;
2869 }
2870 const char* flagname_p = IsCmdlineFlagStart(arg_iter);
2871 if (flagname_p) {
2872 const uint32_t slen = strlen_se(flagname_p);
2873 uint32_t cmdline_arg_idx = first_arg_idx;
2874 for (; cmdline_arg_idx != argc; ++cmdline_arg_idx) {
2875 const char* later_flagname_p = IsCmdlineFlagStart(argv[cmdline_arg_idx]);
2876 if (later_flagname_p) {
2877 const uint32_t slen2 = strlen(later_flagname_p);
2878 if ((slen == slen2) && memequal(flagname_p, later_flagname_p, slen)) {
2879 cmdline_arg_idx = UINT32_MAX;
2880 break;
2881 }
2882 }
2883 }
2884 if (cmdline_arg_idx == UINT32_MAX) {
2885 // matching flag, override --rerun
2886 do {
2887 ++duplicate_arg_ct;
2888 textbuf[loaded_arg_idx++] = 0;
2889 if (loaded_arg_idx == loaded_arg_ct) {
2890 break;
2891 }
2892 arg_iter = NextToken(arg_iter);
2893 } while (!IsCmdlineFlag(arg_iter));
2894 } else {
2895 ++loaded_arg_idx;
2896 arg_iter = NextToken(arg_iter);
2897 }
2898 } else {
2899 ++loaded_arg_idx;
2900 arg_iter = NextToken(arg_iter);
2901 }
2902 } while (loaded_arg_idx < loaded_arg_ct);
2903 if (unlikely(pgl_malloc((argc + loaded_arg_ct - duplicate_arg_ct - rerun_parameter_present - 1 - first_arg_idx) * sizeof(intptr_t), &subst_argv2))) {
2904 goto Rerun_ret_NOMEM;
2905 }
2906 uint32_t new_arg_idx = rerun_argv_pos - first_arg_idx;
2907 memcpy(subst_argv2, &(argv[first_arg_idx]), new_arg_idx * sizeof(intptr_t));
2908 char* arg_nullterminate_iter = rerun_first_token;
2909 for (loaded_arg_idx = 0; loaded_arg_idx != loaded_arg_ct; ++loaded_arg_idx) {
2910 arg_nullterminate_iter = FirstNonTspace(arg_nullterminate_iter);
2911 char* token_end = CurTokenEnd(arg_nullterminate_iter);
2912 if (textbuf[loaded_arg_idx]) {
2913 subst_argv2[new_arg_idx++] = arg_nullterminate_iter;
2914 *token_end = '\0';
2915 }
2916 arg_nullterminate_iter = &(token_end[1]);
2917 }
2918 const uint32_t final_copy_start_idx = rerun_argv_pos + rerun_parameter_present + 1;
2919 memcpy(&(subst_argv2[new_arg_idx]), &(argv[final_copy_start_idx]), (argc - final_copy_start_idx) * sizeof(intptr_t));
2920 *first_arg_idx_ptr = 0;
2921 *argc_ptr = new_arg_idx + argc - final_copy_start_idx;
2922 if (*subst_argv_ptr) {
2923 free(*subst_argv_ptr);
2924 }
2925 *subst_argv_ptr = subst_argv2;
2926 *argv_ptr = subst_argv2;
2927 subst_argv2 = nullptr;
2928 }
2929 while (0) {
2930 Rerun_ret_NOMEM:
2931 fputs(ver_str, stdout);
2932 fputs(ver_str2, stdout);
2933 reterr = kPglRetNomem;
2934 break;
2935 Rerun_ret_OPEN_FAIL:
2936 fputs(ver_str, stdout);
2937 fputs(ver_str2, stdout);
2938 fprintf(stderr, kErrprintfFopen, rerun_fname, strerror(errno));
2939 reterr = kPglRetOpenFail;
2940 break;
2941 Rerun_ret_LONG_LINE:
2942 fputs(ver_str, stdout);
2943 fputs(ver_str2, stdout);
2944 fprintf(stderr, "Error: Line %" PRIuPTR " of --rerun log file is pathologically long.\n", line_idx);
2945 Rerun_ret_MALFORMED_INPUT:
2946 reterr = kPglRetMalformedInput;
2947 break;
2948 }
2949 free_cond(subst_argv2);
2950 fclose_cond(rerunfile);
2951 return reterr;
2952 }
2953
2954
2955 // Handles --script, --rerun, --help, --version, and --silent.
2956 // subst_argv, script_buf, and rerun_buf must be initialized to nullptr.
2957 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) {
2958 FILE* scriptfile = nullptr;
2959 PglErr reterr = kPglRetSuccess;
2960 {
2961 int argc = *argc_ptr;
2962 if (argc < 1) {
2963 fputs(ver_str, stdout);
2964 fputs(ver_str2, stdout);
2965 fputs("Error: This application must be invoked with positive argc.\n", stderr);
2966 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
2967 }
2968 const char* const* argvk = TO_CONSTCPCONSTP(*argv_ptr);
2969 char** subst_argv = nullptr;
2970 uint32_t first_arg_idx = 1;
2971 for (uint32_t arg_idx = 1; arg_idx != S_CAST(uint32_t, argc); ++arg_idx) {
2972 if ((!strcmp("-script", argvk[arg_idx])) || (!strcmp("--script", argvk[arg_idx]))) {
2973 const uint32_t param_ct = GetParamCt(argvk, argc, arg_idx);
2974 if (unlikely(EnforceParamCtRange(argvk[arg_idx], param_ct, 1, 1))) {
2975 fputs(ver_str, stdout);
2976 fputs(ver_str2, stdout);
2977 fputs(g_logbuf, stderr);
2978 fputs(errstr_append, stderr);
2979 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
2980 }
2981 for (uint32_t arg_idx2 = arg_idx + 2; arg_idx2 != S_CAST(uint32_t, argc); ++arg_idx2) {
2982 if (unlikely((!strcmp("-script", argvk[arg_idx2])) || (!strcmp("--script", argvk[arg_idx2])))) {
2983 fputs(ver_str, stdout);
2984 fputs(ver_str2, stdout);
2985 fputs("Error: Multiple --script flags. Merge the files into one.\n", stderr);
2986 fputs(errstr_append, stderr);
2987 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
2988 }
2989 }
2990 // logging not yet active, so don't use fopen_checked()
2991 scriptfile = fopen(argvk[arg_idx + 1], FOPEN_RB);
2992 if (unlikely(!scriptfile)) {
2993 fputs(ver_str, stdout);
2994 fputs(ver_str2, stdout);
2995 fprintf(stderr, kErrprintfFopen, argvk[arg_idx + 1], strerror(errno));
2996 goto CmdlineParsePhase1_ret_OPEN_FAIL;
2997 }
2998 if (unlikely(fseeko(scriptfile, 0, SEEK_END))) {
2999 fputs(ver_str, stdout);
3000 fputs(ver_str2, stdout);
3001 fprintf(stderr, kErrprintfFread, argvk[arg_idx + 1], strerror(errno));
3002 goto CmdlineParsePhase1_ret_READ_FAIL;
3003 }
3004 int64_t fsize = ftello(scriptfile);
3005 if (unlikely(fsize < 0)) {
3006 fputs(ver_str, stdout);
3007 fputs(ver_str2, stdout);
3008 fprintf(stderr, kErrprintfFread, argvk[arg_idx + 1], rstrerror(errno));
3009 goto CmdlineParsePhase1_ret_READ_FAIL;
3010 }
3011 if (unlikely(fsize > 0x7ffffffe)) {
3012 // could actually happen if user enters parameters in the wrong
3013 // order, so may as well catch it and print a somewhat informative
3014 // error message
3015 fputs(ver_str, stdout);
3016 fputs(ver_str2, stdout);
3017 fputs("Error: --script file too large.", stderr);
3018 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
3019 }
3020 rewind(scriptfile);
3021 const uint32_t fsize_ui = fsize;
3022 if (unlikely(pgl_malloc(fsize_ui + 1, &pcmp->script_buf))) {
3023 goto CmdlineParsePhase1_ret_NOMEM;
3024 }
3025 char* script_buf = pcmp->script_buf;
3026 if (unlikely(!fread_unlocked(script_buf, fsize_ui, 1, scriptfile))) {
3027 fputs(ver_str, stdout);
3028 fputs(ver_str2, stdout);
3029 if (feof_unlocked(scriptfile)) {
3030 // shouldn't actually be possible, but let's handle this in as
3031 // uniform a manner as we can
3032 errno = 0;
3033 }
3034 fprintf(stderr, kErrprintfFread, argvk[arg_idx + 1], rstrerror(errno));
3035 goto CmdlineParsePhase1_ret_READ_FAIL;
3036 }
3037 script_buf[fsize_ui] = '\0';
3038 fclose_null(&scriptfile);
3039 uint32_t num_script_params = 0;
3040 char* script_buf_iter = script_buf;
3041 uint32_t char_code;
3042 do {
3043 uint32_t char_code_m1;
3044 do {
3045 char_code_m1 = ctou32(*script_buf_iter++) - 1;
3046 } while (char_code_m1 < 32);
3047 if (char_code_m1 == UINT32_MAX) {
3048 break;
3049 }
3050 ++num_script_params;
3051 do {
3052 char_code = ctou32(*script_buf_iter++);
3053 } while (char_code > 32);
3054 } while (char_code);
3055 if (unlikely(script_buf_iter != (&(script_buf[fsize_ui + 1])))) {
3056 fputs(ver_str, stdout);
3057 fputs(ver_str2, stdout);
3058 fputs("Error: Null byte in --script file.\n", stderr);
3059 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
3060 }
3061 // probable todo: detect duplicate flags in the same manner as --rerun
3062 const uint32_t new_param_ct = num_script_params + argc - 3;
3063 if (unlikely(pgl_malloc(new_param_ct * sizeof(intptr_t), &subst_argv))) {
3064 goto CmdlineParsePhase1_ret_NOMEM;
3065 }
3066 pcmp->subst_argv = subst_argv;
3067 memcpy(subst_argv, &(argvk[1]), arg_idx * sizeof(intptr_t));
3068 const uint32_t load_param_idx_end = arg_idx + num_script_params;
3069 script_buf_iter = &(script_buf[-1]);
3070 for (uint32_t param_idx = arg_idx; param_idx != load_param_idx_end; ++param_idx) {
3071 while (ctou32(*(++script_buf_iter)) <= 32);
3072 subst_argv[param_idx] = script_buf_iter;
3073 while (ctou32(*(++script_buf_iter)) > 32);
3074 // could enforce some sort of length limit here
3075 *script_buf_iter = '\0';
3076 }
3077 memcpy(&(subst_argv[load_param_idx_end]), &(argvk[arg_idx + 2]), (argc - arg_idx - 2) * sizeof(intptr_t));
3078 argc = new_param_ct;
3079 *argc_ptr = argc;
3080 first_arg_idx = 0;
3081 argvk = TO_CONSTCPCONSTP(subst_argv);
3082 *argv_ptr = subst_argv;
3083 break;
3084 }
3085 }
3086 for (uint32_t arg_idx = first_arg_idx; arg_idx != S_CAST(uint32_t, argc); ++arg_idx) {
3087 if ((!strcmp("-rerun", argvk[arg_idx])) || (!strcmp("--rerun", argvk[arg_idx]))) {
3088 const uint32_t param_ct = GetParamCt(argvk, argc, arg_idx);
3089 if (unlikely(EnforceParamCtRange(argvk[arg_idx], param_ct, 0, 1))) {
3090 fputs(ver_str, stdout);
3091 fputs(ver_str2, stdout);
3092 fputs(g_logbuf, stderr);
3093 fputs(errstr_append, stderr);
3094 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
3095 }
3096 for (uint32_t arg_idx2 = arg_idx + param_ct + 1; arg_idx2 != S_CAST(uint32_t, argc); ++arg_idx2) {
3097 if (unlikely((!strcmp("-rerun", argvk[arg_idx2])) || (!strcmp("--rerun", argvk[arg_idx2])))) {
3098 fputs(ver_str, stdout);
3099 fputs(ver_str2, stdout);
3100 fputs("Error: Duplicate --rerun flag.\n", stderr);
3101 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
3102 }
3103 }
3104 reterr = Rerun(ver_str, ver_str2, prog_name_str, arg_idx, param_ct, &argc, &first_arg_idx, argv_ptr, &pcmp->subst_argv, &pcmp->rerun_buf);
3105 if (unlikely(reterr)) {
3106 goto CmdlineParsePhase1_ret_1;
3107 }
3108 *argc_ptr = argc;
3109 subst_argv = pcmp->subst_argv;
3110 argvk = TO_CONSTCPCONSTP(*argv_ptr);
3111 break;
3112 }
3113 }
3114 if (unlikely((first_arg_idx < S_CAST(uint32_t, argc)) && (!IsCmdlineFlag(argvk[first_arg_idx])))) {
3115 fputs("Error: First argument must be a flag.\n", stderr);
3116 fputs(errstr_append, stderr);
3117 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
3118 }
3119 uint32_t flag_ct = 0;
3120 uint32_t version_present = 0;
3121 uint32_t silent_present = 0;
3122 for (uint32_t arg_idx = first_arg_idx; arg_idx != S_CAST(uint32_t, argc); ++arg_idx) {
3123 const char* flagname_p = IsCmdlineFlagStart(argvk[arg_idx]);
3124 if (flagname_p) {
3125 const uint32_t flagname_p_slen = strlen(flagname_p);
3126 if (strequal_k(flagname_p, "help", flagname_p_slen)) {
3127 fputs(ver_str, stdout);
3128 fputs(ver_str2, stdout);
3129 if ((!first_arg_idx) || (arg_idx != 1) || subst_argv) {
3130 fputs("--help present, ignoring other flags.\n", stdout);
3131 }
3132 if ((arg_idx == S_CAST(uint32_t, argc) - 1) && flag_ct) {
3133 // make "plink [valid flags/arguments] --help" work, and skip the
3134 // arguments
3135 const char** help_argv;
3136 if (unlikely(pgl_malloc(flag_ct * sizeof(intptr_t), &help_argv))) {
3137 goto CmdlineParsePhase1_ret_NOMEM2;
3138 }
3139 uint32_t arg_idx2 = 0;
3140 for (uint32_t flag_idx = 0; flag_idx != flag_ct; ++flag_idx) {
3141 while (!IsCmdlineFlagStart(argvk[++arg_idx2]));
3142 help_argv[flag_idx] = argvk[arg_idx2];
3143 }
3144 reterr = disp_help_fn(help_argv, flag_ct);
3145 free(help_argv);
3146 } else {
3147 reterr = disp_help_fn(&(argvk[arg_idx + 1]), argc - arg_idx - 1);
3148 }
3149 if (!reterr) {
3150 reterr = kPglRetHelp;
3151 }
3152 goto CmdlineParsePhase1_ret_1;
3153 }
3154 if (strequal_k(flagname_p, "h", flagname_p_slen) ||
3155 strequal_k(flagname_p, "?", flagname_p_slen)) {
3156 // these just act like the no-argument case
3157 fputs(ver_str, stdout);
3158 fputs(ver_str2, stdout);
3159 if ((!first_arg_idx) || (arg_idx != 1) || subst_argv) {
3160 printf("-%c present, ignoring other flags.\n", *flagname_p);
3161 }
3162 fputs(cmdline_format_str, stdout);
3163 fputs(notestr_null_calc2, stdout);
3164 reterr = kPglRetHelp;
3165 goto CmdlineParsePhase1_ret_1;
3166 }
3167 if (strequal_k(flagname_p, "version", flagname_p_slen)) {
3168 version_present = 1;
3169 } else if (strequal_k(flagname_p, "silent", flagname_p_slen)) {
3170 silent_present = 1;
3171 } else if (unlikely(flagname_p_slen >= max_flag_blen)) {
3172 fputs(ver_str, stdout);
3173 fputs(ver_str2, stdout);
3174 // shouldn't be possible for this to overflow the buffer...
3175 snprintf(g_logbuf, kLogbufSize, "Error: Unrecognized flag ('%s').\n", argvk[arg_idx]);
3176 WordWrapB(0);
3177 fputs(g_logbuf, stderr);
3178 fputs(errstr_append, stderr);
3179 goto CmdlineParsePhase1_ret_INVALID_CMDLINE;
3180 }
3181 ++flag_ct;
3182 }
3183 }
3184 if (version_present) {
3185 fputs(ver_str, stdout);
3186 putc_unlocked('\n', stdout);
3187 reterr = kPglRetHelp;
3188 goto CmdlineParsePhase1_ret_1;
3189 }
3190 if (silent_present) {
3191 if (unlikely(!freopen(NULL_STREAM_NAME, "w", stdout))) {
3192 fputs("Warning: --silent failed.", stderr);
3193 g_stderr_written_to = 1;
3194 }
3195 }
3196 fputs(ver_str, stdout);
3197 fputs(ver_str2, stdout);
3198 *first_arg_idx_ptr = first_arg_idx;
3199 *flag_ct_ptr = flag_ct;
3200 }
3201 while (0) {
3202 CmdlineParsePhase1_ret_NOMEM:
3203 fputs(ver_str, stdout);
3204 fputs(ver_str2, stdout);
3205 CmdlineParsePhase1_ret_NOMEM2:
3206 fputs(kErrstrNomem, stderr);
3207 if (g_failed_alloc_attempt_size) {
3208 fprintf(stderr, "Failed allocation size: %" PRIu64 "\n", g_failed_alloc_attempt_size);
3209 }
3210 reterr = kPglRetNomem;
3211 break;
3212 CmdlineParsePhase1_ret_OPEN_FAIL:
3213 reterr = kPglRetOpenFail;
3214 break;
3215 CmdlineParsePhase1_ret_READ_FAIL:
3216 reterr = kPglRetReadFail;
3217 break;
3218 CmdlineParsePhase1_ret_INVALID_CMDLINE:
3219 reterr = kPglRetInvalidCmdline;
3220 break;
3221 }
3222 CmdlineParsePhase1_ret_1:
3223 fclose_cond(scriptfile);
3224 return reterr;
3225 }
3226
3227 // Assumes CmdlineParsePhase1() has completed, flag names have been copied to
3228 // flag_buf/flag_map, aliases handled, and PROG_NAME_STR has been copied to
3229 // outname (no null-terminator needed). outname_end must be initialized to
3230 // nullptr.
3231 // This sorts the flag names so they're processed in a predictable order,
3232 // handles --d/--out/--strict-extra-chr if present, initializes the log, and
3233 // determines the number of processors the OS wants us to think the machine
3234 // has.
3235 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) {
3236 PglErr reterr = kPglRetSuccess;
3237 {
3238 char* flag_buf = pcmp->flag_buf;
3239 uint32_t* flag_map = pcmp->flag_map;
3240 reterr = SortCmdlineFlags(max_flag_blen, flag_ct, flag_buf, flag_map);
3241 if (unlikely(reterr)) {
3242 if (reterr == kPglRetNomem) {
3243 goto CmdlineParsePhase2_ret_NOMEM_NOLOG;
3244 }
3245 goto CmdlineParsePhase2_ret_1;
3246 }
3247
3248 *range_delim_ptr = '-';
3249 *strict_extra_chr_ptr = 0;
3250 for (uint32_t cur_flag_idx = 0; cur_flag_idx != flag_ct; ++cur_flag_idx) {
3251 char* cur_flag = &(flag_buf[cur_flag_idx * max_flag_blen]);
3252 if (strequal_k_unsafe(cur_flag, "d")) {
3253 // Must be here, instead of in the main parse loop, for --covar-name +
3254 // --d to work.
3255 const uint32_t arg_idx = flag_map[cur_flag_idx];
3256 const uint32_t param_ct = GetParamCt(argvk, argc, arg_idx);
3257 if (unlikely(EnforceParamCtRange(argvk[arg_idx], param_ct, 1, 1))) {
3258 fputs(g_logbuf, stderr);
3259 fputs(errstr_append, stderr);
3260 goto CmdlineParsePhase2_ret_INVALID_CMDLINE;
3261 }
3262 const char cc = ExtractCharParam(argvk[arg_idx + 1]);
3263 if (unlikely(!cc)) {
3264 fputs("Error: --d argument too long (must be a single character).\n", stderr);
3265 goto CmdlineParsePhase2_ret_INVALID_CMDLINE;
3266 }
3267 if ((cc == '-') || (cc == ',')) {
3268 fputs("Error: --d argument cannot be '-' or ','.\n", stderr);
3269 goto CmdlineParsePhase2_ret_INVALID_CMDLINE;
3270 }
3271 *range_delim_ptr = cc;
3272 // bugfix (31 Jul 2019): can't set *cur_flag = '\0' to mark the flag as
3273 // already-processed, since we haven't written the start of the .log
3274 // file yet.
3275 continue;
3276 }
3277 const int32_t memcmp_out_result = Memcmp("out", cur_flag, 4);
3278 if (memcmp_out_result >= 0) {
3279 if (!memcmp_out_result) {
3280 const uint32_t arg_idx = flag_map[cur_flag_idx];
3281 const uint32_t param_ct = GetParamCt(argvk, argc, arg_idx);
3282 if (unlikely(EnforceParamCtRange(argvk[arg_idx], param_ct, 1, 1))) {
3283 fputs(g_logbuf, stderr);
3284 fputs(errstr_append, stderr);
3285 goto CmdlineParsePhase2_ret_INVALID_CMDLINE;
3286 }
3287 if (unlikely(strlen(argvk[arg_idx + 1]) > (kPglFnamesize - kMaxOutfnameExtBlen))) {
3288 fflush(stdout);
3289 fputs("Error: --out argument too long.\n", stderr);
3290 goto CmdlineParsePhase2_ret_OPEN_FAIL;
3291 }
3292 const uint32_t slen = strlen(argvk[arg_idx + 1]);
3293 memcpy(outname, argvk[arg_idx + 1], slen + 1);
3294 *outname_end_ptr = &(outname[slen]);
3295 }
3296 continue;
3297 }
3298 const int32_t strict_extra_chr_result = Memcmp("strict-extra-chr", cur_flag, 17);
3299 if (!strict_extra_chr_result) {
3300 *strict_extra_chr_ptr = 1;
3301 }
3302 if (strict_extra_chr_result <= 0) {
3303 break;
3304 }
3305 }
3306 if (unlikely(InitLogfile(0, outname, (*outname_end_ptr)? (*outname_end_ptr) : &(outname[prog_name_str_slen])))) {
3307 goto CmdlineParsePhase2_ret_OPEN_FAIL;
3308 }
3309 logputs_silent(ver_str);
3310 logputs_silent("\n");
3311 logputs("Options in effect:\n");
3312 for (uint32_t cur_flag_idx = 0; cur_flag_idx != flag_ct; ++cur_flag_idx) {
3313 logputs(" --");
3314 logputs(&(flag_buf[cur_flag_idx * max_flag_blen]));
3315 uint32_t arg_idx = flag_map[cur_flag_idx] + 1;
3316 while ((arg_idx < S_CAST(uint32_t, argc)) && (!IsCmdlineFlag(argvk[arg_idx]))) {
3317 logputs(" ");
3318 // Thought about special-casing argvk[arg_idx] == " ", so that
3319 // "--id-delim ' '" actually works with --rerun, but that adds too much
3320 // complexity to the rereader to be worth it. Instead we just document
3321 // the incompatibility.
3322 logputs(argvk[arg_idx++]);
3323 }
3324 logputs("\n");
3325 }
3326 logputs("\n");
3327
3328 #ifdef _WIN32
3329 DWORD windows_dw = kTextbufSize;
3330 if (GetComputerName(g_textbuf, &windows_dw))
3331 #else
3332 if (gethostname(g_textbuf, kTextbufSize) != -1)
3333 #endif
3334 {
3335 logputs_silent("Hostname: ");
3336 logputs_silent(g_textbuf);
3337 }
3338 logputs_silent("\nWorking directory: ");
3339 if (unlikely(!getcwd(g_textbuf, kPglFnamesize))) {
3340 logputs_silent("\n");
3341 logerrprintfww("Error: Failed to get current working directory: %s.\n", strerror(errno));
3342 // debatable what error code applies here
3343 goto CmdlineParsePhase2_ret_OPEN_FAIL;
3344 }
3345 logputs_silent(g_textbuf);
3346 logputs_silent("\n");
3347 logputs("Start time: ");
3348 time_t rawtime;
3349 time(&rawtime);
3350 logputs(ctime(&rawtime));
3351 // ctime string always has a newline at the end
3352 logputs_silent("\n");
3353
3354 *max_thread_ct_ptr = NumCpu(known_procs_ptr);
3355 // don't subtract 1 any more since, when max_thread_ct > 2, one of the
3356 // (virtual) cores will be dedicated to I/O and have lots of downtime.
3357 //
3358 // may make kMaxThreads a parameter later.
3359 if (*max_thread_ct_ptr > kMaxThreads) {
3360 *max_thread_ct_ptr = kMaxThreads;
3361 }
3362 }
3363 while (0) {
3364 CmdlineParsePhase2_ret_NOMEM_NOLOG:
3365 fputs(kErrstrNomem, stderr);
3366 if (g_failed_alloc_attempt_size) {
3367 fprintf(stderr, "Failed allocation size: %" PRIu64 "\n", g_failed_alloc_attempt_size);
3368 }
3369 reterr = kPglRetNomem;
3370 break;
3371 CmdlineParsePhase2_ret_OPEN_FAIL:
3372 reterr = kPglRetOpenFail;
3373 break;
3374 CmdlineParsePhase2_ret_INVALID_CMDLINE:
3375 reterr = kPglRetInvalidCmdline;
3376 break;
3377 }
3378 CmdlineParsePhase2_ret_1:
3379 return reterr;
3380 }
3381
3382 PglErr CmdlineParsePhase3(uintptr_t max_default_mib, uintptr_t malloc_size_mib, uint32_t memory_require, Plink2CmdlineMeta* pcmp, unsigned char** bigstack_ua_ptr) {
3383 PglErr reterr = kPglRetSuccess;
3384 {
3385 if (pcmp->subst_argv) {
3386 free(pcmp->subst_argv);
3387 pcmp->subst_argv = nullptr;
3388 }
3389 if (pcmp->script_buf) {
3390 free(pcmp->script_buf);
3391 pcmp->script_buf = nullptr;
3392 }
3393 if (pcmp->rerun_buf) {
3394 free(pcmp->rerun_buf);
3395 pcmp->rerun_buf = nullptr;
3396 }
3397 if (pcmp->flag_buf) {
3398 free(pcmp->flag_buf);
3399 pcmp->flag_buf = nullptr;
3400 }
3401 if (pcmp->flag_map) {
3402 free(pcmp->flag_map);
3403 pcmp->flag_map = nullptr;
3404 }
3405
3406 const uint64_t total_mib = DetectMib();
3407 if (!malloc_size_mib) {
3408 if (!total_mib) {
3409 malloc_size_mib = max_default_mib? max_default_mib : kBigstackDefaultMib;
3410 } else if (total_mib < (kBigstackMinMib * 2)) {
3411 malloc_size_mib = kBigstackMinMib;
3412 } else {
3413 #ifdef __LP64__
3414 malloc_size_mib = total_mib / 2;
3415 #else
3416 malloc_size_mib = MINV(2047, total_mib / 2);
3417 #endif
3418 if (max_default_mib && (malloc_size_mib > max_default_mib)) {
3419 malloc_size_mib = max_default_mib;
3420 }
3421 }
3422 }
3423 assert(malloc_size_mib >= kBigstackMinMib);
3424 #ifndef __LP64__
3425 if (malloc_size_mib > kMalloc32bitMibMax) {
3426 malloc_size_mib = kMalloc32bitMibMax;
3427 }
3428 #endif
3429 if (total_mib) {
3430 const uint64_t mem_available_kib = GetMemAvailableKib(kMaxMediumLine, g_textbuf);
3431 if (mem_available_kib == (~0LLU)) {
3432 logprintf("%" PRIu64 " MiB RAM detected; reserving %" PRIuPTR " MiB for main workspace.\n", total_mib, malloc_size_mib);
3433 } else {
3434 const uint64_t mem_available_mib = mem_available_kib / 1024;
3435 if ((mem_available_mib < malloc_size_mib + (kNonBigstackMin >> 20)) && (!memory_require)) {
3436 if (mem_available_mib < kBigstackMinMib + (kNonBigstackMin >> 20)) {
3437 malloc_size_mib = kBigstackMinMib;
3438 } else {
3439 malloc_size_mib = mem_available_mib - (kNonBigstackMin >> 20);
3440 }
3441 }
3442 logprintfww("%" PRIu64 " MiB RAM detected, ~%" PRIu64 " available; reserving %" PRIuPTR " MiB for main workspace.\n", total_mib, mem_available_mib, malloc_size_mib);
3443 }
3444 } else {
3445 logprintf("Failed to determine total system memory. Attempting to reserve %" PRIuPTR " MiB.\n", malloc_size_mib);
3446 }
3447 uintptr_t malloc_mib_final;
3448 if (unlikely(InitBigstack(malloc_size_mib, &malloc_mib_final, bigstack_ua_ptr))) {
3449 goto CmdlineParsePhase3_ret_NOMEM;
3450 }
3451 if (malloc_size_mib != malloc_mib_final) {
3452 if (unlikely(memory_require)) {
3453 goto CmdlineParsePhase3_ret_NOMEM;
3454 }
3455 logprintf("Allocated %" PRIuPTR " MiB successfully, after larger attempt(s) failed.\n", malloc_mib_final);
3456 }
3457 }
3458 while (0) {
3459 CmdlineParsePhase3_ret_NOMEM:
3460 reterr = kPglRetNomem;
3461 break;
3462 }
3463 return reterr;
3464 }
3465
3466 void CleanupPlink2CmdlineMeta(Plink2CmdlineMeta* pcmp) {
3467 free_cond(pcmp->subst_argv);
3468 free_cond(pcmp->script_buf);
3469 free_cond(pcmp->rerun_buf);
3470 free_cond(pcmp->flag_buf);
3471 free_cond(pcmp->flag_map);
3472 }
3473
3474
3475 void InitCmpExpr(CmpExpr* cmp_expr_ptr) {
3476 cmp_expr_ptr->pheno_name = nullptr;
3477 }
3478
3479 void CleanupCmpExpr(CmpExpr* cmp_expr_ptr) {
3480 free_cond(cmp_expr_ptr->pheno_name);
3481 }
3482
3483 // may want CXXCONST_CP treatment later
3484 const char* ParseNextBinaryOp(const char* expr_str, uint32_t expr_slen, const char** op_start_ptr, CmpBinaryOp* binary_op_ptr) {
3485 // !=, <>: kCmpOperatorNoteq
3486 // <: kCmpOperatorLe
3487 // <=: kCmpOperatorLeq
3488 // =, ==: kCmpOperatorEq
3489 // >=: kCmpOperatorGeq
3490 // >: kCmpOperatorGe
3491 const char* next_eq = S_CAST(const char*, memchr(expr_str, '=', expr_slen));
3492 const char* next_lt = S_CAST(const char*, memchr(expr_str, '<', expr_slen));
3493 const char* next_gt = S_CAST(const char*, memchr(expr_str, '>', expr_slen));
3494 if (!next_eq) {
3495 if (!next_lt) {
3496 // may want to remove unlikely() later
3497 if (unlikely(!next_gt)) {
3498 return nullptr;
3499 }
3500 *op_start_ptr = next_gt;
3501 *binary_op_ptr = kCmpOperatorGe;
3502 return &(next_gt[1]);
3503 }
3504 if (next_gt == (&(next_lt[1]))) {
3505 *op_start_ptr = next_lt;
3506 *binary_op_ptr = kCmpOperatorNoteq;
3507 return &(next_lt[2]);
3508 }
3509 if ((!next_gt) || (next_gt > next_lt)) {
3510 *op_start_ptr = next_lt;
3511 *binary_op_ptr = kCmpOperatorLe;
3512 return &(next_lt[1]);
3513 }
3514 *op_start_ptr = next_gt;
3515 *binary_op_ptr = kCmpOperatorGe;
3516 return &(next_gt[1]);
3517 }
3518 if ((!next_lt) || (next_lt > next_eq)) {
3519 if ((!next_gt) || (next_gt > next_eq)) {
3520 if ((next_eq != expr_str) && (next_eq[-1] == '!')) {
3521 *op_start_ptr = &(next_eq[-1]);
3522 *binary_op_ptr = kCmpOperatorNoteq;
3523 return &(next_eq[1]);
3524 }
3525 *op_start_ptr = next_eq;
3526 *binary_op_ptr = kCmpOperatorEq;
3527 return (next_eq[1] == '=')? (&(next_eq[2])) : (&(next_eq[1]));
3528 }
3529 *op_start_ptr = next_gt;
3530 if (next_eq == (&(next_gt[1]))) {
3531 *binary_op_ptr = kCmpOperatorGeq;
3532 return &(next_gt[2]);
3533 }
3534 *binary_op_ptr = kCmpOperatorGe;
3535 return &(next_gt[1]);
3536 }
3537 if (next_gt == (&(next_lt[1]))) {
3538 *op_start_ptr = next_lt;
3539 *binary_op_ptr = kCmpOperatorNoteq;
3540 return &(next_lt[2]);
3541 }
3542 if ((!next_gt) || (next_gt > next_lt)) {
3543 *op_start_ptr = next_lt;
3544 if (next_eq == (&(next_lt[1]))) {
3545 *binary_op_ptr = kCmpOperatorLeq;
3546 return &(next_lt[2]);
3547 }
3548 *binary_op_ptr = kCmpOperatorLe;
3549 return &(next_lt[1]);
3550 }
3551 *op_start_ptr = next_gt;
3552 if (next_eq == (&(next_gt[1]))) {
3553 *binary_op_ptr = kCmpOperatorGeq;
3554 return &(next_gt[2]);
3555 }
3556 *binary_op_ptr = kCmpOperatorGe;
3557 return &(next_gt[1]);
3558 }
3559
3560 PglErr ValidateAndAllocCmpExpr(const char* const* sources, const char* flag_name, uint32_t param_ct, CmpExpr* cmp_expr_ptr) {
3561 // Currently four use cases:
3562 // [pheno/covar name] [operator] [pheno val]: regular comparison
3563 // [pheno/covar name]: existence check
3564 // [INFO key] [operator] [val]: regular comparison
3565 // [INFO key]: existence check
3566 // Some key/value validation is deferred to LoadPvar()/KeepRemoveIf(),
3567 // since the requirements are different (e.g. no semicolons in anything
3568 // INFO-related, categorical phenotypes can be assumed to not start with a
3569 // valid number).
3570 // May support or/and, parentheses later, but need to be careful to not slow
3571 // down LoadPvar() too much in the no-INFO-filter case.
3572 PglErr reterr = kPglRetSuccess;
3573 {
3574 if (unlikely((param_ct != 1) && (param_ct != 3))) {
3575 goto ValidateAndAllocCmpExpr_ret_INVALID_EXPR_GENERIC;
3576 }
3577 const char* pheno_name_start = sources[0];
3578 const char* pheno_val_start;
3579 uint32_t pheno_name_slen;
3580 uint32_t pheno_val_slen;
3581 if (param_ct == 3) {
3582 pheno_name_slen = strlen(pheno_name_start);
3583 const char* op_str = sources[1];
3584 uint32_t op_slen = strlen(op_str);
3585 // ok to have single/double quotes around operator
3586 if (op_slen > 2) {
3587 const char cc = op_str[0];
3588 if (((cc == '\'') || (cc == '"')) && (op_str[op_slen - 1] == cc)) {
3589 ++op_str;
3590 op_slen -= 2;
3591 }
3592 }
3593 const char* op_start;
3594 const char* op_end = ParseNextBinaryOp(op_str, op_slen, &op_start, &cmp_expr_ptr->binary_op);
3595 if (unlikely((!op_end) || (*op_end) || (op_start != op_str))) {
3596 goto ValidateAndAllocCmpExpr_ret_INVALID_EXPR_GENERIC;
3597 }
3598 pheno_val_start = sources[2];
3599 pheno_val_slen = strlen(pheno_val_start);
3600 } else {
3601 // permit param_ct == 1 as long as tokens are unambiguous
3602 uint32_t expr_slen = strlen(pheno_name_start);
3603 const char* op_start;
3604 pheno_val_start = ParseNextBinaryOp(pheno_name_start, expr_slen, &op_start, &cmp_expr_ptr->binary_op);
3605 if (unlikely((!pheno_val_start) || (!(*pheno_val_start)) || (op_start == pheno_name_start))) {
3606 goto ValidateAndAllocCmpExpr_ret_INVALID_EXPR_GENERIC;
3607 }
3608 pheno_name_slen = op_start - pheno_name_start;
3609 // quasi-bugfix (13 Dec 2017): allow single argument to contain internal
3610 // spaces;
3611 // --keep-if "PHENO1 > 1"
3612 // is more intuitive and consistent with usage of other command-line
3613 // tools than
3614 // --keep-if PHENO1 '>' 1
3615 //
3616 // To prevent --rerun from breaking, if there's a space after the
3617 // operator, there must be a space before the operator as well, etc.
3618 if (*pheno_val_start == ' ') {
3619 if (unlikely(pheno_name_start[pheno_name_slen - 1] != ' ')) {
3620 goto ValidateAndAllocCmpExpr_ret_INVALID_EXPR_GENERIC;
3621 }
3622 do {
3623 ++pheno_val_start;
3624 } while (*pheno_val_start == ' ');
3625 do {
3626 --pheno_name_slen;
3627 if (unlikely(!pheno_name_slen)) {
3628 goto ValidateAndAllocCmpExpr_ret_INVALID_EXPR_GENERIC;
3629 }
3630 } while (pheno_name_start[pheno_name_slen - 1] == ' ');
3631 }
3632 pheno_val_slen = expr_slen - S_CAST(uintptr_t, pheno_val_start - pheno_name_start);
3633 }
3634 if (unlikely(memchr(pheno_name_start, ' ', pheno_name_slen) || memchr(pheno_val_start, ' ', pheno_val_slen))) {
3635 goto ValidateAndAllocCmpExpr_ret_INVALID_EXPR_GENERIC;
3636 }
3637 if (unlikely((pheno_name_slen > kMaxIdSlen) || (pheno_val_slen > kMaxIdSlen))) {
3638 logerrprintf("Error: ID too long in %s expression.\n", flag_name);
3639 goto ValidateAndAllocCmpExpr_ret_INVALID_CMDLINE;
3640 }
3641 if ((cmp_expr_ptr->binary_op != kCmpOperatorNoteq) && (cmp_expr_ptr->binary_op != kCmpOperatorEq)) {
3642 double dxx;
3643 if (unlikely(!ScantokDouble(pheno_val_start, &dxx))) {
3644 logerrprintfww("Error: Invalid %s value '%s' (finite number expected).\n", flag_name, pheno_val_start);
3645 goto ValidateAndAllocCmpExpr_ret_INVALID_CMDLINE;
3646 }
3647 }
3648 char* new_pheno_name_buf;
3649 if (unlikely(pgl_malloc(2 + pheno_name_slen + pheno_val_slen, &new_pheno_name_buf))) {
3650 goto ValidateAndAllocCmpExpr_ret_NOMEM;
3651 }
3652 memcpyx(new_pheno_name_buf, pheno_name_start, pheno_name_slen, '\0');
3653 // pheno_val_start guaranteed to be null-terminated for now
3654 memcpy(&(new_pheno_name_buf[pheno_name_slen + 1]), pheno_val_start, pheno_val_slen + 1);
3655 cmp_expr_ptr->pheno_name = new_pheno_name_buf;
3656 }
3657 while (0) {
3658 ValidateAndAllocCmpExpr_ret_NOMEM:
3659 reterr = kPglRetNomem;
3660 break;
3661 ValidateAndAllocCmpExpr_ret_INVALID_EXPR_GENERIC:
3662 logerrprintf("Error: Invalid %s expression.\n", flag_name);
3663 ValidateAndAllocCmpExpr_ret_INVALID_CMDLINE:
3664 reterr = kPglRetInvalidCmdline;
3665 break;
3666 }
3667 return reterr;
3668 }
3669
3670 // See e.g. meta_analysis_open_and_read_header() in plink 1.9.
3671 // Assumes at least one search term.
3672 PglErr SearchHeaderLine(const char* header_line_iter, const char* const* search_multistrs, const char* flagname_p, 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) {
3673 assert(search_col_ct <= 32);
3674 unsigned char* bigstack_mark = g_bigstack_base;
3675 PglErr reterr = kPglRetSuccess;
3676 {
3677 uint32_t search_term_ct = 0;
3678 uintptr_t max_blen = 0;
3679 for (uint32_t search_col_idx = 0; search_col_idx != search_col_ct; ++search_col_idx) {
3680 const uint32_t cur_search_term_ct = CountAndMeasureMultistr(search_multistrs[search_col_idx], &max_blen);
3681 assert(cur_search_term_ct <= (1 << 26));
3682 search_term_ct += cur_search_term_ct;
3683 }
3684 char* merged_strbox;
3685 uint32_t* id_map;
3686 uint32_t* priority_vals;
3687 uint64_t* cols_and_types;
3688 if (unlikely(bigstack_alloc_c(search_term_ct * max_blen, &merged_strbox) ||
3689 bigstack_alloc_u32(search_term_ct, &id_map) ||
3690 bigstack_alloc_u32(search_col_ct, &priority_vals) ||
3691 bigstack_alloc_u64(search_col_ct, &cols_and_types))) {
3692 goto SearchHeaderLine_ret_NOMEM;
3693 }
3694 uint32_t search_term_idx = 0;
3695 for (uint32_t search_col_idx = 0; search_col_idx != search_col_ct; ++search_col_idx) {
3696 const char* multistr_iter = search_multistrs[search_col_idx];
3697 uint32_t priority_idx = 0; // 0 = highest priority
3698 while (*multistr_iter) {
3699 const uint32_t cur_blen = strlen(multistr_iter) + 1;
3700 memcpy(&(merged_strbox[search_term_idx * max_blen]), multistr_iter, cur_blen);
3701 id_map[search_term_idx] = search_col_idx + (priority_idx * 32);
3702 ++search_term_idx;
3703 ++priority_idx;
3704 multistr_iter = &(multistr_iter[cur_blen]);
3705 }
3706 }
3707 SortStrboxIndexed(search_term_ct, max_blen, 0, merged_strbox, id_map);
3708 assert(search_term_ct);
3709 const char* duplicate_search_term = FindSortedStrboxDuplicate(merged_strbox, search_term_ct, max_blen);
3710 if (unlikely(duplicate_search_term)) {
3711 logerrprintfww("Error: Duplicate term '%s' in --%s column search order.\n", duplicate_search_term, flagname_p);
3712 goto SearchHeaderLine_ret_INVALID_CMDLINE;
3713 }
3714
3715 SetAllU32Arr(search_col_ct, priority_vals);
3716 SetAllU64Arr(search_col_ct, cols_and_types);
3717 for (uintptr_t col_idx = 0; ; ++col_idx) {
3718 const char* token_end = CurTokenEnd(header_line_iter);
3719 const uint32_t token_slen = token_end - header_line_iter;
3720 int32_t ii = bsearch_strbox(header_line_iter, merged_strbox, token_slen, max_blen, search_term_ct);
3721 if (ii != -1) {
3722 const uint32_t cur_map_idx = id_map[S_CAST(uint32_t, ii)];
3723 const uint32_t search_col_idx = cur_map_idx & 31;
3724 const uint32_t priority_idx = cur_map_idx >> 5;
3725 if (priority_vals[search_col_idx] >= priority_idx) {
3726 if (unlikely(priority_vals[search_col_idx] == priority_idx)) {
3727 logerrprintfww("Error: Duplicate column header '%s' in --%s file.\n", &(merged_strbox[max_blen * cur_map_idx]), flagname_p);
3728 goto SearchHeaderLine_ret_MALFORMED_INPUT;
3729 }
3730 priority_vals[search_col_idx] = priority_idx;
3731 cols_and_types[search_col_idx] = (S_CAST(uint64_t, col_idx) << 32) | search_col_idx;
3732 }
3733 }
3734 header_line_iter = FirstNonTspace(token_end);
3735 if (IsEolnKns(*header_line_iter)) {
3736 break;
3737 }
3738 }
3739 uint32_t found_type_bitset = 0;
3740 for (uint32_t search_col_idx = 0; search_col_idx != search_col_ct; ++search_col_idx) {
3741 if (priority_vals[search_col_idx] != UINT32_MAX) {
3742 found_type_bitset |= 1U << search_col_idx;
3743 }
3744 }
3745 const uint32_t found_col_ct = PopcountWord(found_type_bitset);
3746 *found_col_ct_ptr = found_col_ct;
3747 *found_type_bitset_ptr = found_type_bitset;
3748 if (found_col_ct) {
3749 STD_SORT(search_col_ct, u64cmp, cols_and_types);
3750 uint32_t prev_col_idx = cols_and_types[0] >> 32;
3751 col_skips[0] = prev_col_idx;
3752 col_types[0] = S_CAST(uint32_t, cols_and_types[0]);
3753 for (uint32_t found_col_idx = 1; found_col_idx != found_col_ct; ++found_col_idx) {
3754 const uint64_t cur_col_and_type = cols_and_types[found_col_idx];
3755 const uint32_t cur_col_idx = cur_col_and_type >> 32;
3756 col_skips[found_col_idx] = cur_col_idx - prev_col_idx;
3757 col_types[found_col_idx] = S_CAST(uint32_t, cur_col_and_type);
3758 prev_col_idx = cur_col_idx;
3759 }
3760 }
3761 }
3762 while (0) {
3763 SearchHeaderLine_ret_NOMEM:
3764 reterr = kPglRetNomem;
3765 break;
3766 SearchHeaderLine_ret_INVALID_CMDLINE:
3767 reterr = kPglRetInvalidCmdline;
3768 break;
3769 SearchHeaderLine_ret_MALFORMED_INPUT:
3770 reterr = kPglRetMalformedInput;
3771 break;
3772 }
3773 BigstackReset(bigstack_mark);
3774 return reterr;
3775 }
3776
3777 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) {
3778 // col_descriptor is usually a pointer to argv[...][5] (first five characters
3779 // are "cols="). supported_ids is a multistr.
3780 // may need to switch first_col_shifted/default_cols_mask/result to uint64_t
3781 PglErr reterr = kPglRetSuccess;
3782 uint32_t* id_map = nullptr;
3783 {
3784 uint32_t max_id_blen = 0;
3785 uint32_t id_ct = 0;
3786
3787 // work around strchr not returning a const char*?
3788 const char* supported_ids_iter = supported_ids;
3789
3790 // can precompute this sorted index and avoid the dynamic
3791 // allocations/deallocations, but this is cheap enough that I'd rather make
3792 // it easier to extend functionality.
3793 do {
3794 const uint32_t blen = 1 + strlen(supported_ids_iter);
3795 if (blen > max_id_blen) {
3796 max_id_blen = blen;
3797 }
3798 ++id_ct;
3799 supported_ids_iter = &(supported_ids_iter[blen]);
3800 } while (*supported_ids_iter);
3801 // max_id_blen + 4 extra bytes at the end, to support a "maybe" search
3802 // (yes, this can also be precomputed)
3803 if (unlikely(pgl_malloc((max_id_blen + 4) * (id_ct + 1) + 1, &id_map))) {
3804 goto ParseColDescriptor_ret_NOMEM;
3805 }
3806 char* sorted_ids = R_CAST(char*, &(id_map[id_ct]));
3807 supported_ids_iter = supported_ids;
3808 for (uint32_t id_idx = 0; id_idx != id_ct; ++id_idx) {
3809 const uint32_t blen = strlen(supported_ids_iter) + 1;
3810 memcpy(&(sorted_ids[id_idx * max_id_blen]), supported_ids_iter, blen);
3811 id_map[id_idx] = id_idx;
3812 supported_ids_iter = &(supported_ids_iter[blen]);
3813 }
3814 if (unlikely(SortStrboxIndexedMalloc(id_ct, max_id_blen, sorted_ids, id_map))) {
3815 goto ParseColDescriptor_ret_NOMEM;
3816 }
3817 uint32_t result = *S_CAST(uint32_t*, result_ptr);
3818 // might not want to bother splitting this into two loops
3819 if ((col_descriptor_iter[0] == '+') || (col_descriptor_iter[0] == '-')) {
3820 result |= default_cols_mask;
3821 char* maybebuf = &(sorted_ids[max_id_blen * id_ct]);
3822 memcpy_k(maybebuf, "maybe", 5);
3823 while (1) {
3824 const char* id_start = &(col_descriptor_iter[1]);
3825 const char* tok_end = strchrnul(id_start, ',');
3826 const uint32_t slen = tok_end - id_start;
3827 int32_t alpha_idx = bsearch_strbox(id_start, sorted_ids, slen, max_id_blen, id_ct);
3828 if (unlikely(alpha_idx == -1)) {
3829 char* write_iter = strcpya_k(g_logbuf, "Error: Unrecognized ID '");
3830 write_iter = memcpya(write_iter, id_start, slen);
3831 write_iter = strcpya_k(write_iter, "' in --");
3832 write_iter = strcpya(write_iter, cur_flag_name);
3833 snprintf(write_iter, kLogbufSize - kMaxIdSlen - 128, " column set descriptor.\n");
3834 goto ParseColDescriptor_ret_INVALID_CMDLINE_WW;
3835 }
3836 uint32_t shift = id_map[S_CAST(uint32_t, alpha_idx)];
3837 if (col_descriptor_iter[0] == '+') {
3838 result |= first_col_shifted << shift;
3839 } else {
3840 if (result & (first_col_shifted << shift)) {
3841 result -= first_col_shifted << shift;
3842 } else if (slen + 5 < max_id_blen) {
3843 // special case: if default column set includes e.g. "maybesid",
3844 // and user types "-sid", that should work
3845 memcpy(&(maybebuf[5]), id_start, slen);
3846 alpha_idx = bsearch_strbox(maybebuf, sorted_ids, slen + 5, max_id_blen, id_ct);
3847 if (alpha_idx != -1) {
3848 shift = id_map[S_CAST(uint32_t, alpha_idx)];
3849 result &= ~(first_col_shifted << shift);
3850 }
3851 }
3852 }
3853 // bugfix (16 Oct 2017): forgot to switch from !tok_end to !(*tok_end)
3854 // after use of strchrnul().
3855 if (!(*tok_end)) {
3856 break;
3857 }
3858 col_descriptor_iter = &(tok_end[1]);
3859 if (unlikely((col_descriptor_iter[0] != '+') && (col_descriptor_iter[0] != '-'))) {
3860 goto ParseColDescriptor_ret_MIXED_SIGN;
3861 }
3862 }
3863 } else if (*col_descriptor_iter) {
3864 while (1) {
3865 const char* tok_end = strchrnul(col_descriptor_iter, ',');
3866 const uint32_t slen = tok_end - col_descriptor_iter;
3867 const int32_t alpha_idx = bsearch_strbox(col_descriptor_iter, sorted_ids, slen, max_id_blen, id_ct);
3868 if (unlikely(alpha_idx == -1)) {
3869 char* write_iter = strcpya_k(g_logbuf, "Error: Unrecognized ID '");
3870 write_iter = memcpya(write_iter, col_descriptor_iter, slen);
3871 write_iter = strcpya_k(write_iter, "' in --");
3872 write_iter = strcpya(write_iter, cur_flag_name);
3873 snprintf(write_iter, kLogbufSize - kMaxIdSlen - 128, " column set descriptor.\n");
3874 goto ParseColDescriptor_ret_INVALID_CMDLINE_WW;
3875 }
3876 uint32_t shift = id_map[S_CAST(uint32_t, alpha_idx)];
3877 result |= first_col_shifted << shift;
3878 if (!(*tok_end)) {
3879 break;
3880 }
3881 col_descriptor_iter = &(tok_end[1]);
3882 if (unlikely((col_descriptor_iter[0] == '+') || (col_descriptor_iter[0] == '-'))) {
3883 goto ParseColDescriptor_ret_MIXED_SIGN;
3884 }
3885 }
3886 }
3887 if (unlikely(prohibit_empty && (!(result & (first_col_shifted * (UINT32_MAX >> (32 - id_ct))))))) {
3888 char* write_iter = strcpya_k(g_logbuf, "Error: All columns excluded by --");
3889 write_iter = strcpya(write_iter, cur_flag_name);
3890 snprintf(write_iter, kLogbufSize - 128, " column set descriptor.\n");
3891 goto ParseColDescriptor_ret_INVALID_CMDLINE_WW;
3892 }
3893 *S_CAST(uint32_t*, result_ptr) = result;
3894 }
3895 while (0) {
3896 ParseColDescriptor_ret_NOMEM:
3897 reterr = kPglRetNomem;
3898 break;
3899 ParseColDescriptor_ret_MIXED_SIGN:
3900 snprintf(g_logbuf, kLogbufSize, "Error: Invalid --%s column set descriptor (either all column set IDs must be preceded by +/-, or none of them can be).\n", cur_flag_name);
3901 ParseColDescriptor_ret_INVALID_CMDLINE_WW:
3902 WordWrapB(0);
3903 logerrputsb();
3904 reterr = kPglRetInvalidCmdline;
3905 break;
3906 }
3907 free_cond(id_map);
3908 return reterr;
3909 }
3910
3911 #ifdef __cplusplus
3912 } // namespace plink2
3913 #endif