Repository navigation
Expand file tree
/
Copy pathPass_IntegerConversion.cpp
More file actions
1397 lines (1194 loc) · 47.5 KB
/
Copy pathPass_IntegerConversion.cpp
File metadata and controls
1397 lines (1194 loc) · 47.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "Pass_IntegerConversion.h"
#include "Pass_TransformLogicalExpressions.h"
#include "Utils.h"
#include <clang/AST/ASTConsumer.h>
#include <clang/AST/ASTContext.h>
#include <clang/AST/Decl.h>
#include <clang/AST/Expr.h>
#include <clang/AST/OperationKinds.h>
#include <clang/AST/RecordLayout.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/TypeBase.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/ASTMatchers/ASTMatchers.h>
#include <clang/Basic/LLVM.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Basic/TokenKinds.h>
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Lex/Lexer.h>
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/Tooling/Core/Replacement.h>
#include <clang/Tooling/Refactoring/AtomicChange.h>
#include <clang/Tooling/Transformer/MatchConsumer.h>
#include <clang/Tooling/Transformer/RangeSelector.h>
#include <clang/Tooling/Transformer/RewriteRule.h>
#include <clang/Tooling/Transformer/Stencil.h>
#include <clang/Tooling/Transformer/Transformer.h>
#include <clang/lib/CodeGen/CodeGenFunction.h>
#include <clang/lib/CodeGen/CodeGenModule.h>
#include <clang/lib/CodeGen/CodeGenTypes.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/ADT/StringExtras.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/Error.h>
#include <llvm/Support/ErrorHandling.h>
#include <llvm/Support/FormatVariadic.h>
#include <llvm/Support/raw_ostream.h>
#include <cstddef>
#include <memory>
#include <optional>
#include <ranges>
#include <string>
#include <utility>
using namespace clang;
using namespace clang::tooling;
using namespace clang::transformer;
using namespace clang::ast_matchers;
namespace pancake::pass_implicit_to_explicit_casts {
namespace {
class TypeNameComputation : public MatchComputation<std::string> {
public:
explicit TypeNameComputation(std::string id) : id(std::move(id)) {}
auto eval(const MatchFinder::MatchResult &result, std::string *out) const -> llvm::Error override {
const auto *expr = result.Nodes.getNodeAs<Expr>(id);
if (expr == nullptr) {
return llvm::make_error<llvm::StringError>(llvm::formatv("TypeName: id '{0}' is not bound to an Expr", id),
llvm::inconvertibleErrorCode());
}
llvm::raw_string_ostream os(*out);
expr->getType().print(os, result.Context->getPrintingPolicy());
os.flush();
return llvm::Error::success();
}
auto toString() const -> std::string override { return llvm::formatv("TypeName({0})", id); }
private:
std::string id;
};
auto TypeName(std::string Id) -> TextGenerator { return std::make_shared<TypeNameComputation>(std::move(Id)); }
auto MakeRule() -> RewriteRule {
return makeRule(implicitCastExpr(isExpansionInMainFile(), unless(hasCastKind(CK_LValueToRValue)),
unless(hasCastKind(CK_NoOp)), unless(hasCastKind(CK_ArrayToPointerDecay)),
unless(hasCastKind(CK_FunctionToPointerDecay)),
unless(hasCastKind(CK_BuiltinFnToFnPtr)))
.bind("cast"),
changeTo(node("cast"), cat("(", TypeName("cast"), ")(", node("cast"), ")")));
}
} // namespace
auto Consumer::HandleTranslationUnit(ASTContext &Ctx) -> void {
llvm::SmallVector<AtomicChange, 64> changes;
llvm::Error error = llvm::Error::success();
auto t = Transformer(MakeRule(), [&](llvm::Expected<llvm::MutableArrayRef<AtomicChange>> c) -> void {
if (c) {
changes.insert(changes.end(), c->begin(), c->end());
} else if (error) {
error = llvm::joinErrors(std::move(error), c.takeError());
} else {
error = c.takeError();
}
});
MatchFinder finder;
t.registerMatchers(&finder);
finder.matchAST(Ctx);
if (error) {
ps_ctx.error = llvm::joinErrors(CreateRuntimeError("Error during transformation"), std::move(error));
ps_ctx.SetControl(StageControl::NextFile);
return;
}
int errors = 0;
for (const auto &change : changes) {
for (const auto &r : change.getReplacements()) {
if (auto error = ps_ctx.replacements.add(r)) {
llvm::consumeError(std::move(error));
errors++;
}
}
}
if (errors == 0 && changes.empty()) {
ps_ctx.SetControl(StageControl::Continue);
return;
}
if (errors > 0) {
PrintLogBegin(llvm::outs(), ps_ctx);
llvm::outs() << llvm::formatv("Couldn't add {0} replacement{1}\n", errors, errors != 1 ? "s" : "");
}
ps_ctx.SetControl(StageControl::Repeat);
}
} // namespace pancake::pass_implicit_to_explicit_casts
/*
Every value of every integer type u8, i8, u16, i16, ..., i64 is represented as a single uint64_t, but what that
uint64_t looks like depends on signedness:
- Unsigned N-bit value: stored as its plain zero-extended bit pattern in the low N bits, upper bits 0.
- Signed N-bit value: stored sign-extended to the full 64 bit, i.e. the canonical form is "as if it were already cast to
int64_t".
So the "type" of a uint64_t value in this system isn't encoded in the bits themselves, and the operations (conversions,
comparisons, shifts) are the things responsible for maintaining the correct bit-pattern invariant for whichever type
it's supposed to represent at that point.
This is because pancake only supports word sized variables on the stack.
*/
namespace pancake::pass_integer_conversion {
namespace {
const char *signed_i64_helpers = R"(#include <stdint.h>
/* c2pancake generated code start: helpers for i64 signed ops */
static inline uint64_t __c2pnk_u8_to_u64(uint8_t x) {
// noop
return (uint64_t)x;
}
static inline uint64_t __c2pnk_u16_to_u64(uint16_t x) {
// noop
return (uint64_t)x;
}
static inline uint64_t __c2pnk_u32_to_u64(uint32_t x) {
// noop
return (uint64_t)x;
}
static inline uint64_t __c2pnk_u64_to_u64(uint64_t x) {
// noop
return x;
}
static inline uint64_t __c2pnk_i8_to_u64(int8_t x) {
uint64_t y = (uint64_t)(uint8_t)x;
return (y ^ 0x80UL) - 0x80UL;
}
static inline uint64_t __c2pnk_i16_to_u64(int16_t x) {
uint64_t y = (uint64_t)(uint16_t)x;
return (y ^ 0x8000UL) - 0x8000UL;
}
static inline uint64_t __c2pnk_i32_to_u64(int32_t x) {
uint64_t y = (uint64_t)(uint32_t)x;
return (y ^ 0x80000000UL) - 0x80000000UL;
}
static inline uint64_t __c2pnk_i64_to_u64(int64_t x) {
// noop
return (uint64_t)x;
}
static inline uint64_t __c2pnk_i64_lt(uint64_t a, uint64_t b) {
uint64_t sa = a >> 63UL;
uint64_t sb = b >> 63UL;
if (sa != sb) {
return sa > sb;
} else {
return a < b;
}
}
static inline uint64_t __c2pnk_i64_lte(uint64_t a, uint64_t b) {
uint64_t sa = a >> 63UL;
uint64_t sb = b >> 63UL;
if (sa != sb) {
return sa > sb;
} else {
return a <= b;
}
}
static inline uint64_t __c2pnk_i64_gt(uint64_t a, uint64_t b) {
uint64_t sa = a >> 63UL;
uint64_t sb = b >> 63UL;
if (sa != sb) {
return sa < sb;
} else {
return a > b;
}
}
static inline uint64_t __c2pnk_i64_gte(uint64_t a, uint64_t b) {
uint64_t sa = a >> 63UL;
uint64_t sb = b >> 63UL;
if (sa != sb) {
return sa < sb;
} else {
return a >= b;
}
}
/* arithmetic right shift */
static inline uint64_t __c2pnk_i64_sar(uint64_t a, uint64_t n) {
uint64_t sign = a >> 63UL;
uint64_t mask = 0UL - sign;
uint64_t fill = mask << (64UL - n);
return (a >> n) | fill;
}
static uint64_t __c2pnk_u64_div(uint64_t dividend, uint64_t divisor) {
if (divisor == 0UL) {
return 0UL; // uh oh
}
uint64_t quotient = 0UL;
uint64_t remainder = 0UL;
uint64_t i = 63UL;
while (i != UINT64_MAX) {
remainder = (remainder << 1UL) | ((dividend >> i) & 1UL);
if (remainder >= divisor) {
remainder = remainder - divisor;
quotient = quotient | (1UL << i);
}
i = i - 1UL;
}
return quotient;
}
static uint64_t __c2pnk_u64_rem(uint64_t dividend, uint64_t divisor) {
if (divisor == 0UL) {
return 0UL; // uh oh
}
uint64_t remainder = 0UL;
uint64_t i = 63UL;
while (i != UINT64_MAX) {
remainder = (remainder << 1UL) | ((dividend >> i) & 1UL);
if (remainder >= divisor) {
remainder = remainder - divisor;
}
i = i - 1UL;
}
return remainder;
}
static uint64_t __c2pnk_i64_div(uint64_t dividend, uint64_t divisor, uint64_t width) {
if (divisor == 0UL) {
return 0UL; // uh oh
}
uint64_t int_min_n = 0UL - (1UL << (width - 1UL));
uint64_t neg_one = ~0UL;
if (dividend == int_min_n) {
if (divisor == neg_one) {
return int_min_n; // N-bit overflow: wraps back to INT_MIN(N)
}
}
uint64_t dividend_sign = dividend >> 63UL;
uint64_t divisor_sign = divisor >> 63UL;
uint64_t quotient_sign = dividend_sign ^ divisor_sign;
uint64_t abs_dividend;
if (dividend_sign) {
abs_dividend = 0UL - dividend;
} else {
abs_dividend = dividend;
}
uint64_t abs_divisor;
if (divisor_sign) {
abs_divisor = 0UL - divisor;
} else {
abs_divisor = divisor;
}
uint64_t uq = __c2pnk_u64_div(abs_dividend, abs_divisor);
uint64_t quotient;
if (quotient_sign) {
quotient = 0UL - uq;
} else {
quotient = uq;
}
return quotient;
}
static uint64_t __c2pnk_i64_rem(uint64_t dividend, uint64_t divisor, uint64_t width) {
if (divisor == 0UL) {
return 0UL; // uh oh
}
uint64_t int_min_n = 0UL - (1UL << (width - 1));
uint64_t neg_one = ~0UL;
if (dividend == int_min_n) {
if (divisor == neg_one) {
return 0UL; // N-bit overflow: remainder is 0 (exact division)
}
}
uint64_t dividend_sign = dividend >> 63UL;
uint64_t divisor_sign = divisor >> 63UL;
uint64_t abs_dividend;
if (dividend_sign) {
abs_dividend = 0UL - dividend;
} else {
abs_dividend = dividend;
}
uint64_t abs_divisor;
if (divisor_sign) {
abs_divisor = 0UL - divisor;
} else {
abs_divisor = divisor;
}
uint64_t ur = __c2pnk_u64_rem(abs_dividend, abs_divisor);
uint64_t remainder;
if (dividend_sign) {
remainder = 0UL - ur;
} else {
remainder = ur;
}
return remainder;
}
static inline uint64_t __c2pnk_trunc_u64_to_u64(uint64_t x) {
// noop
return x;
}
static inline uint64_t __c2pnk_trunc_u64_to_u32(uint64_t x) {
return x & 0xffffffffUL;
}
static inline uint64_t __c2pnk_trunc_u64_to_u16(uint64_t x) {
return x & 0xffffUL;
}
static inline uint64_t __c2pnk_trunc_u64_to_u8(uint64_t x) {
return x & 0xffUL;
}
static inline uint64_t __c2pnk_trunc_u64_to_i64(uint64_t x) {
// noop
return x;
}
static inline uint64_t __c2pnk_trunc_u64_to_i32(uint64_t x) {
uint64_t y = x & 0xffffffffUL;
return (y ^ 0x80000000UL) - 0x80000000UL;
}
static inline uint64_t __c2pnk_trunc_u64_to_i16(uint64_t x) {
uint64_t y = x & 0xffffUL;
return (y ^ 0x8000UL) - 0x8000UL;
}
static inline uint64_t __c2pnk_trunc_u64_to_i8(uint64_t x) {
uint64_t y = x & 0xffUL;
return (y ^ 0x80UL) - 0x80UL;
}
/* c2pancake generated code end: helpers for i64 signed ops */
)";
const char *signed_i32_helpers = R"(#include <stdint.h>
/* c2pancake generated code start: helpers for i32 signed ops */
static inline uint32_t __c2pnk_i8_to_u32(int8_t x) {
uint32_t y = (uint32_t)(uint8_t)x;
return (y ^ 0x80UL) - 0x80UL;
}
static inline uint32_t __c2pnk_i16_to_u32(int16_t x) {
uint32_t y = (uint32_t)(uint16_t)x;
return (y ^ 0x8000UL) - 0x8000UL;
}
static inline uint32_t __c2pnk_i32_to_u32(int32_t x) {
// noop
return (uint32_t)x;
}
static inline uint32_t __c2pnk_u8_to_u32(uint8_t x) {
// noop
return (uint32_t)x;
}
static inline uint32_t __c2pnk_u16_to_u32(uint16_t x) {
// noop
return (uint32_t)x;
}
static inline uint32_t __c2pnk_u32_to_u32(uint32_t x) {
// noop
return x;
}
static inline uint32_t __c2pnk_i32_lt(uint32_t a, uint32_t b) {
uint32_t sa = a >> 31UL;
uint32_t sb = b >> 31UL;
if (sa != sb) {
return sa > sb;
} else {
return a < b;
}
}
static inline uint32_t __c2pnk_i32_lte(uint32_t a, uint32_t b) {
uint32_t sa = a >> 31UL;
uint32_t sb = b >> 31UL;
if (sa != sb) {
return sa > sb;
} else {
return a <= b;
}
}
static inline uint32_t __c2pnk_i32_gt(uint32_t a, uint32_t b) {
uint32_t sa = a >> 31UL;
uint32_t sb = b >> 31UL;
if (sa != sb) {
return sa < sb;
} else {
return a > b;
}
}
static inline uint32_t __c2pnk_i32_gte(uint32_t a, uint32_t b) {
uint32_t sa = a >> 31UL;
uint32_t sb = b >> 31UL;
if (sa != sb) {
return sa < sb;
} else {
return a >= b;
}
}
static inline uint32_t __c2pnk_i32_sar(uint32_t a, uint32_t n) {
uint32_t sign = a >> 31UL;
uint32_t mask = 0UL - sign;
uint32_t fill = mask << (32UL - n);
return (a >> n) | fill;
}
static uint32_t __c2pnk_u32_div(uint32_t dividend, uint32_t divisor) {
if (divisor == 0UL) {
return 0UL; // uh oh
}
uint32_t quotient = 0UL;
uint32_t remainder = 0UL;
uint32_t i = 31UL;
while (i != UINT32_MAX) {
remainder = (remainder << 1UL) | ((dividend >> i) & 1UL);
if (remainder >= divisor) {
remainder = remainder - divisor;
quotient = quotient | (1UL << i);
}
i = i - 1UL;
}
return quotient;
}
static uint32_t __c2pnk_u32_rem(uint32_t dividend, uint32_t divisor) {
if (divisor == 0UL) {
return 0UL; // uh oh
}
uint32_t remainder = 0UL;
uint32_t i = 31UL;
while (i != UINT32_MAX) {
remainder = (remainder << 1UL) | ((dividend >> i) & 1UL);
if (remainder >= divisor) {
remainder = remainder - divisor;
}
i = i - 1UL;
}
return remainder;
}
static uint32_t __c2pnk_i32_div(uint32_t dividend, uint32_t divisor, uint32_t width) {
if (divisor == 0UL) {
return 0UL; // uh oh
}
uint32_t int_min_n = 0UL - (1UL << (width - 1UL));
uint32_t neg_one = ~0UL;
if (dividend == int_min_n) {
if (divisor == neg_one) {
return int_min_n; // N-bit overflow: wraps back to INT_MIN(N)
}
}
uint32_t dividend_sign = dividend >> 31UL;
uint32_t divisor_sign = divisor >> 31UL;
uint32_t quotient_sign = dividend_sign ^ divisor_sign;
uint32_t abs_dividend;
if (dividend_sign) {
abs_dividend = 0UL - dividend;
} else {
abs_dividend = dividend;
}
uint32_t abs_divisor;
if (divisor_sign) {
abs_divisor = 0UL - divisor;
} else {
abs_divisor = divisor;
}
uint32_t uq = __c2pnk_u32_div(abs_dividend, abs_divisor);
uint32_t quotient;
if (quotient_sign) {
quotient = 0UL - uq;
} else {
quotient = uq;
}
return quotient;
}
static uint32_t __c2pnk_i32_rem(uint32_t dividend, uint32_t divisor, uint32_t width) {
if (divisor == 0UL) {
return 0UL; // uh oh
}
uint32_t int_min_n = 0UL - (1UL << (width - 1UL));
uint32_t neg_one = ~0UL;
if (dividend == int_min_n) {
if (divisor == neg_one) {
return 0UL; // N-bit overflow: remainder is 0 (exact division)
}
}
uint32_t dividend_sign = dividend >> 31UL;
uint32_t divisor_sign = divisor >> 31UL;
uint32_t abs_dividend;
if (dividend_sign) {
abs_dividend = 0UL - dividend;
} else {
abs_dividend = dividend;
}
uint32_t abs_divisor;
if (divisor_sign) {
abs_divisor = 0UL - divisor;
} else {
abs_divisor = divisor;
}
uint32_t ur = __c2pnk_u32_rem(abs_dividend, abs_divisor);
uint32_t remainder;
if (dividend_sign) {
remainder = 0UL - ur;
} else {
remainder = ur;
}
return remainder;
}
static inline uint32_t __c2pnk_trunc_u32_to_u32(uint32_t x) {
// noop
return x;
}
static inline uint32_t __c2pnk_trunc_u32_to_u16(uint32_t x) {
return x & 0xffffUL;
}
static inline uint32_t __c2pnk_trunc_u32_to_u8(uint32_t x) {
return x & 0xffUL;
}
static inline uint32_t __c2pnk_trunc_u32_to_i32(uint32_t x) {
// noop
return (int32_t)x;
}
static inline uint32_t __c2pnk_trunc_u32_to_i16(uint32_t x) {
uint32_t y = x & 0xffffUL;
return (y ^ 0x8000UL) - 0x8000UL;
}
static inline uint32_t __c2pnk_trunc_u32_to_i8(uint32_t x) {
uint32_t y = x & 0xffUL;
return (y ^ 0x80UL) - 0x80UL;
}
/* c2pancake generated code end: helpers for i32 signed ops */
)";
struct WorkerData {
ASTContext &Ctx;
StageContext &ps_ctx;
llvm::SmallVector<Replacement, 64> &replacements;
size_t tmp_var_counter = 0;
llvm::Error error = llvm::Error::success();
bool need_int_helpers = false;
FunctionDecl *current_function_decl = nullptr;
};
class Worker : public RecursiveASTVisitor<Worker> {
struct WorkerData &data;
public:
explicit Worker(struct WorkerData &data) : data(data) {}
static auto shouldTraversePostOrder() -> bool { return false; }
auto GetTempVarName(std::string hint) -> auto {
return llvm::formatv("__c2pnk_{0}_{1}_{2}_{3}", hint, data.ps_ctx.stage_index, data.ps_ctx.attempt_index,
data.tmp_var_counter++);
}
auto PrintType(const QualType ty, const llvm::StringRef var_name) const -> std::string {
std::string s;
llvm::raw_string_ostream os(s);
ty.print(os, data.Ctx.getPrintingPolicy(), var_name);
return os.str();
}
auto VerifyTypeWidth(const QualType type) const -> llvm::Error {
auto width = data.Ctx.getTypeSize(type);
if (GetPointerWidth(data.Ctx) == 32) {
if (width == 32 || width == 16 || width == 8) {
return llvm::Error::success();
}
return CreateRuntimeError(std::move(llvm::formatv("Unsupported type width for 32-bit target: {0}", width)));
}
if (GetPointerWidth(data.Ctx) == 64) {
if (width == 64 || width == 32 || width == 16 || width == 8) {
return llvm::Error::success();
}
return CreateRuntimeError(std::move(llvm::formatv("Unsupported type width for 64-bit target: {0}", width)));
}
return CreateRuntimeError(std::move(llvm::formatv("Unsupported pointer width: {0}", GetPointerWidth(data.Ctx))));
}
static auto BinOpTypeToStr(const BinaryOperatorKind op) -> Expected<StringRef> {
switch (op) {
case BO_LT:
return "lt";
case BO_GT:
return "gt";
case BO_LE:
return "lte";
case BO_GE:
return "gte";
case BO_Div:
return "div";
case BO_Rem:
return "rem";
default:
return CreateRuntimeError(std::move(llvm::formatv("Unsupported binary operator: {0}", op)));
}
}
using BuiltExpr = pancake::pass_lower_nested_expressions::BuiltExpr;
using BuildExprCtx = pancake::pass_lower_nested_expressions::BuildExprCtx;
using Usage = pancake::pass_lower_nested_expressions::Usage;
template <typename... Args>
auto GetUsage(Args &&...args)
-> decltype(pancake::pass_lower_nested_expressions::GetUsage(std::forward<Args>(args)...)) {
return pancake::pass_lower_nested_expressions::GetUsage(std::forward<Args>(args)...);
}
auto BuildExpr(const BuildExprCtx &ctx) -> Expected<BuiltExpr> {
auto *expr = ctx.expr->IgnoreParenImpCasts();
llvm::SmallVector<std::string, 8> pre_stmts;
std::string final_expr;
llvm::raw_string_ostream os(final_expr);
const QualType final_expr_type = expr->getType();
if (auto *decl_ref_expr = dyn_cast<DeclRefExpr>(expr)) {
auto type = decl_ref_expr->getType();
if (type->isIntegerType() && ctx.usage_kind == Usage::Value) {
auto is_signed = type->isSignedIntegerType();
auto bit_width = data.Ctx.getTypeSize(type);
if (auto error = VerifyTypeWidth(type)) {
return error;
}
if (bit_width == GetPointerWidth(data.Ctx) && !is_signed) {
goto decl_ref_expr_general_case;
}
if (!is_signed) {
goto decl_ref_expr_general_case;
}
auto decl_ref_expr_source_text = GetSourceText(decl_ref_expr, data.Ctx);
if (auto error = decl_ref_expr_source_text.takeError()) {
return llvm::joinErrors(CreateRuntimeError(std::move(llvm::formatv(
"\n at {0}\nFailed to get source text for DeclRefExpr",
decl_ref_expr->getExprLoc().printToString(data.Ctx.getSourceManager())))),
std::move(error));
}
auto signed_to_unsigned = llvm::formatv("__c2pnk_{0}{1}_to_u{2}({3})", is_signed ? 'i' : 'u', bit_width,
GetPointerWidth(data.Ctx), *decl_ref_expr_source_text);
auto final_conv = llvm::formatv("__c2pnk_trunc_u{0}_to_{1}{2}({3})", GetPointerWidth(data.Ctx),
is_signed ? 'i' : 'u', bit_width, signed_to_unsigned);
os << final_conv;
} else {
decl_ref_expr_general_case:
if (auto error = PrintSourceText(os, decl_ref_expr, data.Ctx)) {
return llvm::joinErrors(CreateRuntimeError(std::move(llvm::formatv(
"\n at {0}\nFailed to print source text for DeclRefExpr",
decl_ref_expr->getExprLoc().printToString(data.Ctx.getSourceManager())))),
std::move(error));
}
}
} else if (auto *integer_literal = dyn_cast<IntegerLiteral>(expr)) {
data.need_int_helpers = true;
auto type = integer_literal->getType();
auto is_signed = type->isSignedIntegerType();
auto bit_width = data.Ctx.getTypeSize(type);
if (auto error = VerifyTypeWidth(type)) {
return error;
}
if (bit_width == GetPointerWidth(data.Ctx) && !is_signed) {
if (auto error = PrintSourceText(os, integer_literal, data.Ctx)) {
return llvm::joinErrors(CreateRuntimeError(std::move(llvm::formatv(
"\n at {0}\nFailed to print source text for IntegerLiteral",
integer_literal->getExprLoc().printToString(data.Ctx.getSourceManager())))),
std::move(error));
}
} else if (!is_signed) {
if (auto error = PrintSourceText(os, integer_literal, data.Ctx)) {
return llvm::joinErrors(CreateRuntimeError(std::move(llvm::formatv(
"\n at {0}\nFailed to print source text for IntegerLiteral",
integer_literal->getExprLoc().printToString(data.Ctx.getSourceManager())))),
std::move(error));
}
} else {
auto integer_literal_source_text = GetSourceText(integer_literal, data.Ctx);
if (auto error = integer_literal_source_text.takeError()) {
return llvm::joinErrors(CreateRuntimeError(std::move(llvm::formatv(
"\n at {0}\nFailed to get source text for IntegerLiteral",
integer_literal->getExprLoc().printToString(data.Ctx.getSourceManager())))),
std::move(error));
}
auto signed_to_unsigned = llvm::formatv("__c2pnk_{0}{1}_to_u{2}({3})", is_signed ? 'i' : 'u', bit_width,
GetPointerWidth(data.Ctx), *integer_literal_source_text);
auto final_conv = llvm::formatv("__c2pnk_trunc_u{0}_to_{1}{2}({3})", GetPointerWidth(data.Ctx),
is_signed ? 'i' : 'u', bit_width, signed_to_unsigned);
os << final_conv;
}
} else if (auto *_ = dyn_cast<FloatingLiteral>(expr)) {
return CreateRuntimeError(
std::move(llvm::formatv("\n at {0}\nFloating point literals are not allowed",
expr->getExprLoc().printToString(data.Ctx.getSourceManager()))));
} else if (auto *character_literal = dyn_cast<CharacterLiteral>(expr)) {
data.need_int_helpers = true;
auto type = character_literal->getType();
auto is_signed = type->isSignedIntegerType();
auto bit_width = data.Ctx.getTypeSize(type);
if (auto error = VerifyTypeWidth(type)) {
return error;
}
if (!is_signed) {
if (auto error = PrintSourceText(os, character_literal, data.Ctx)) {
return llvm::joinErrors(CreateRuntimeError(std::move(llvm::formatv(
"\n at {0}\nFailed to print source text for CharacterLiteral",
character_literal->getExprLoc().printToString(data.Ctx.getSourceManager())))),
std::move(error));
}
} else {
auto character_literal_source_text = GetSourceText(character_literal, data.Ctx);
if (auto error = character_literal_source_text.takeError()) {
return llvm::joinErrors(CreateRuntimeError(std::move(llvm::formatv(
"\n at {0}\nFailed to get source text for CharacterLiteral",
character_literal->getExprLoc().printToString(data.Ctx.getSourceManager())))),
std::move(error));
}
auto signed_to_unsigned = llvm::formatv("__c2pnk_{0}{1}_to_u{2}({3})", is_signed ? 'i' : 'u', bit_width,
GetPointerWidth(data.Ctx), *character_literal_source_text);
auto final_conv = llvm::formatv("__c2pnk_trunc_u{0}_to_{1}{2}({3})", GetPointerWidth(data.Ctx),
is_signed ? 'i' : 'u', bit_width, signed_to_unsigned);
os << final_conv;
}
} else if (auto *string_literal = dyn_cast<StringLiteral>(expr)) {
if (auto error = PrintSourceText(os, string_literal, data.Ctx)) {
return llvm::joinErrors(CreateRuntimeError(std::move(llvm::formatv(
"\n at {0}\nFailed to print source text for StringLiteral",
string_literal->getExprLoc().printToString(data.Ctx.getSourceManager())))),
std::move(error));
}
} else if (auto *c_style_cast_expr = dyn_cast<CStyleCastExpr>(expr)) {
auto *sub_expr = c_style_cast_expr->getSubExpr();
auto res = BuildExpr(BuildExprCtx(sub_expr, Usage::Value, ctx.deref_force_extract, ctx.assigned_to,
ctx.string_literal_usage_kind));
if (auto error = res.takeError()) {
return error;
}
if (c_style_cast_expr->getCastKind() == CK_IntegralCast) {
data.need_int_helpers = true;
// although src_type might be different in the original code, it should just be a uint64_t at this point
auto src_type = sub_expr->getType();
if (auto error = VerifyTypeWidth(src_type)) {
return error;
}
auto dest_type = c_style_cast_expr->getType();
auto dest_is_signed = dest_type->isSignedIntegerType();
auto dest_bit_width = data.Ctx.getTypeSize(dest_type);
if (auto error = VerifyTypeWidth(dest_type)) {
return error;
}
if (dest_bit_width == GetPointerWidth(data.Ctx)) {
goto c_style_cast_general_case;
} else {
os << llvm::formatv("__c2pnk_trunc_u{0}_to_{1}{2}({3})", GetPointerWidth(data.Ctx),
dest_is_signed ? 'i' : 'u', dest_bit_width, res->final_expr);
}
} else {
c_style_cast_general_case:
os << "(";
c_style_cast_expr->getTypeAsWritten().print(os, data.Ctx.getPrintingPolicy());
os << ")(";
os << res->final_expr;
os << ")";
}
pre_stmts.insert(pre_stmts.end(), res->pre_stmts.begin(), res->pre_stmts.end());
} else if (auto *binary_operator = dyn_cast<BinaryOperator>(expr)) {
if (ctx.usage_kind == Usage::Place) {
return CreateRuntimeError(
std::move(llvm::formatv("Binary operator cannot be used as a place expression, {1}",
binary_operator->getExprLoc().printToString(data.Ctx.getSourceManager()))));
}
auto *lhs = binary_operator->getLHS()->IgnoreParenImpCasts();
auto *rhs = binary_operator->getRHS()->IgnoreParenImpCasts();
auto rhs_res = BuildExpr(
BuildExprCtx(rhs, Usage::Value, ctx.deref_force_extract, ctx.assigned_to, ctx.string_literal_usage_kind));
if (auto error = rhs_res.takeError()) {
return error;
}
auto lhs_res = BuildExpr(
BuildExprCtx(lhs, Usage::Value, ctx.deref_force_extract, ctx.assigned_to, ctx.string_literal_usage_kind));
if (auto error = lhs_res.takeError()) {
return error;
}
switch (binary_operator->getOpcode()) {
case BO_Div:
[[fallthrough]];
case BO_Rem: {
if (!lhs->getType()->isIntegerType() || !rhs->getType()->isIntegerType()) {
return CreateRuntimeError(
std::move(llvm::formatv("Binary operator (DIV, REM) operands must be integer types, {1}",
binary_operator->getExprLoc().printToString(data.Ctx.getSourceManager()))));
}
data.need_int_helpers = true;
auto lhs_type = lhs->getType();
auto lhs_is_signed = lhs_type->isSignedIntegerType();
auto lhs_bit_width = data.Ctx.getTypeSize(lhs_type);
if (auto error = VerifyTypeWidth(lhs_type)) {
return error;
}
auto bin_op_str = BinOpTypeToStr(binary_operator->getOpcode());
if (auto error = bin_op_str.takeError()) {
return error;
}
if (lhs_is_signed) {
os << llvm::formatv("__c2pnk_i{0}_{1}({2}, {3}, {4})", GetPointerWidth(data.Ctx), *bin_op_str,
lhs_res->final_expr, rhs_res->final_expr, lhs_bit_width);
} else {
os << llvm::formatv("__c2pnk_u{0}_{1}({2}, {3})", GetPointerWidth(data.Ctx), *bin_op_str, lhs_res->final_expr,
rhs_res->final_expr);
}
break;
}
case BO_Assign: {
// clang should have inserted an implicit cast to turn the RHS into the same type as the LHS
// this should then have been converted into an explicit cast
// which would have been handled at this point already
// so there's nothing to do...
// we want to build with the LHS as a place expression, and the RHS as a value expression
lhs_res = BuildExpr(
BuildExprCtx(lhs, Usage::Place, ctx.deref_force_extract, ctx.assigned_to, ctx.string_literal_usage_kind));
if (auto error = lhs_res.takeError()) {
return error;
}
pre_stmts.push_back(llvm::formatv("{0} = {1};", lhs_res->final_expr, rhs_res->final_expr).str());
if (ctx.usage_kind == Usage::Value) {
os << lhs_res->final_expr;
}
break;
}
case BO_Shr: {
if (!lhs->getType()->isIntegerType() || !rhs->getType()->isIntegerType()) {
return CreateRuntimeError(
std::move(llvm::formatv("Binary operator (SHR) operands must be integer types, {1}",
binary_operator->getExprLoc().printToString(data.Ctx.getSourceManager()))));
}
data.need_int_helpers = true;
auto lhs_type = lhs->getType();
auto lhs_is_signed = lhs_type->isSignedIntegerType();
// auto lhs_bit_width = data.Ctx.getTypeSize(lhs_type);
if (auto error = VerifyTypeWidth(lhs_type)) {
return error;
}
auto rhs_type = rhs->getType();
if (auto error = VerifyTypeWidth(rhs_type)) {
return error;
}
if (lhs_is_signed) {
os << llvm::formatv("__c2pnk_i{0}_sar({1}, {2})", GetPointerWidth(data.Ctx), lhs_res->final_expr,
rhs_res->final_expr);
} else {
os << llvm::formatv("({0} >> {1})", lhs_res->final_expr, rhs_res->final_expr);
}
break;
}
case BO_LT:
[[fallthrough]];
case BO_GT:
[[fallthrough]];
case BO_LE: