forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCIRGenExprScalar.cpp
1609 lines (1388 loc) · 61.6 KB
/
CIRGenExprScalar.cpp
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
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Emit Expr nodes with scalar CIR types as CIR code.
//
//===----------------------------------------------------------------------===//
#include "CIRGenFunction.h"
#include "CIRGenValue.h"
#include "clang/AST/Expr.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/CIR/MissingFeatures.h"
#include "mlir/IR/Location.h"
#include "mlir/IR/Value.h"
#include <cassert>
#include <utility>
using namespace clang;
using namespace clang::CIRGen;
namespace {
struct BinOpInfo {
mlir::Value lhs;
mlir::Value rhs;
SourceRange loc;
QualType fullType; // Type of operands and result
QualType compType; // Type used for computations. Element type
// for vectors, otherwise same as FullType.
BinaryOperator::Opcode opcode; // Opcode of BinOp to perform
FPOptions fpfeatures;
const Expr *e; // Entire expr, for error unsupported. May not be binop.
/// Check if the binop computes a division or a remainder.
bool isDivRemOp() const {
return opcode == BO_Div || opcode == BO_Rem || opcode == BO_DivAssign ||
opcode == BO_RemAssign;
}
/// Check if the binop can result in integer overflow.
bool mayHaveIntegerOverflow() const {
// Without constant input, we can't rule out overflow.
auto lhsci = dyn_cast<cir::ConstantOp>(lhs.getDefiningOp());
auto rhsci = dyn_cast<cir::ConstantOp>(rhs.getDefiningOp());
if (!lhsci || !rhsci)
return true;
assert(!cir::MissingFeatures::mayHaveIntegerOverflow());
// TODO(cir): For now we just assume that we might overflow
return true;
}
/// Check if at least one operand is a fixed point type. In such cases,
/// this operation did not follow usual arithmetic conversion and both
/// operands might not be of the same type.
bool isFixedPointOp() const {
// We cannot simply check the result type since comparison operations
// return an int.
if (const auto *binOp = llvm::dyn_cast<BinaryOperator>(e)) {
QualType lhstype = binOp->getLHS()->getType();
QualType rhstype = binOp->getRHS()->getType();
return lhstype->isFixedPointType() || rhstype->isFixedPointType();
}
if (const auto *unop = llvm::dyn_cast<UnaryOperator>(e))
return unop->getSubExpr()->getType()->isFixedPointType();
return false;
}
};
class ScalarExprEmitter : public StmtVisitor<ScalarExprEmitter, mlir::Value> {
CIRGenFunction &cgf;
CIRGenBuilderTy &builder;
bool ignoreResultAssign;
public:
ScalarExprEmitter(CIRGenFunction &cgf, CIRGenBuilderTy &builder)
: cgf(cgf), builder(builder) {}
//===--------------------------------------------------------------------===//
// Utilities
//===--------------------------------------------------------------------===//
mlir::Value emitPromotedValue(mlir::Value result, QualType promotionType) {
return builder.createFloatingCast(result, cgf.convertType(promotionType));
}
mlir::Value emitUnPromotedValue(mlir::Value result, QualType exprType) {
return builder.createFloatingCast(result, cgf.convertType(exprType));
}
mlir::Value emitPromoted(const Expr *e, QualType promotionType);
//===--------------------------------------------------------------------===//
// Visitor Methods
//===--------------------------------------------------------------------===//
mlir::Value Visit(Expr *e) {
return StmtVisitor<ScalarExprEmitter, mlir::Value>::Visit(e);
}
mlir::Value VisitStmt(Stmt *s) {
llvm_unreachable("Statement passed to ScalarExprEmitter");
}
mlir::Value VisitExpr(Expr *e) {
cgf.getCIRGenModule().errorNYI(
e->getSourceRange(), "scalar expression kind: ", e->getStmtClassName());
return {};
}
/// Emits the address of the l-value, then loads and returns the result.
mlir::Value emitLoadOfLValue(const Expr *e) {
LValue lv = cgf.emitLValue(e);
// FIXME: add some akin to EmitLValueAlignmentAssumption(E, V);
return cgf.emitLoadOfLValue(lv, e->getExprLoc()).getScalarVal();
}
mlir::Value emitLoadOfLValue(LValue lv, SourceLocation loc) {
return cgf.emitLoadOfLValue(lv, loc).getScalarVal();
}
// l-values
mlir::Value VisitDeclRefExpr(DeclRefExpr *e) {
assert(!cir::MissingFeatures::tryEmitAsConstant());
return emitLoadOfLValue(e);
}
mlir::Value VisitIntegerLiteral(const IntegerLiteral *e) {
mlir::Type type = cgf.convertType(e->getType());
return builder.create<cir::ConstantOp>(
cgf.getLoc(e->getExprLoc()), type,
builder.getAttr<cir::IntAttr>(type, e->getValue()));
}
mlir::Value VisitFloatingLiteral(const FloatingLiteral *e) {
mlir::Type type = cgf.convertType(e->getType());
assert(mlir::isa<cir::CIRFPTypeInterface>(type) &&
"expect floating-point type");
return builder.create<cir::ConstantOp>(
cgf.getLoc(e->getExprLoc()), type,
builder.getAttr<cir::FPAttr>(type, e->getValue()));
}
mlir::Value VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *e) {
mlir::Type type = cgf.convertType(e->getType());
return builder.create<cir::ConstantOp>(
cgf.getLoc(e->getExprLoc()), type,
builder.getCIRBoolAttr(e->getValue()));
}
mlir::Value VisitCastExpr(CastExpr *e);
mlir::Value VisitCallExpr(const CallExpr *e);
mlir::Value VisitArraySubscriptExpr(ArraySubscriptExpr *e) {
if (e->getBase()->getType()->isVectorType()) {
assert(!cir::MissingFeatures::scalableVectors());
cgf.getCIRGenModule().errorNYI("VisitArraySubscriptExpr: VectorType");
return {};
}
// Just load the lvalue formed by the subscript expression.
return emitLoadOfLValue(e);
}
mlir::Value VisitExplicitCastExpr(ExplicitCastExpr *e) {
return VisitCastExpr(e);
}
mlir::Value VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *e) {
return cgf.cgm.emitNullConstant(e->getType(),
cgf.getLoc(e->getSourceRange()));
}
/// Perform a pointer to boolean conversion.
mlir::Value emitPointerToBoolConversion(mlir::Value v, QualType qt) {
// TODO(cir): comparing the ptr to null is done when lowering CIR to LLVM.
// We might want to have a separate pass for these types of conversions.
return cgf.getBuilder().createPtrToBoolCast(v);
}
mlir::Value emitFloatToBoolConversion(mlir::Value src, mlir::Location loc) {
cir::BoolType boolTy = builder.getBoolTy();
return builder.create<cir::CastOp>(loc, boolTy,
cir::CastKind::float_to_bool, src);
}
mlir::Value emitIntToBoolConversion(mlir::Value srcVal, mlir::Location loc) {
// Because of the type rules of C, we often end up computing a
// logical value, then zero extending it to int, then wanting it
// as a logical value again.
// TODO: optimize this common case here or leave it for later
// CIR passes?
cir::BoolType boolTy = builder.getBoolTy();
return builder.create<cir::CastOp>(loc, boolTy, cir::CastKind::int_to_bool,
srcVal);
}
/// Convert the specified expression value to a boolean (!cir.bool) truth
/// value. This is equivalent to "Val != 0".
mlir::Value emitConversionToBool(mlir::Value src, QualType srcType,
mlir::Location loc) {
assert(srcType.isCanonical() && "EmitScalarConversion strips typedefs");
if (srcType->isRealFloatingType())
return emitFloatToBoolConversion(src, loc);
if (llvm::isa<MemberPointerType>(srcType)) {
cgf.getCIRGenModule().errorNYI(loc, "member pointer to bool conversion");
mlir::Type boolType = builder.getBoolTy();
return builder.create<cir::ConstantOp>(loc, boolType,
builder.getCIRBoolAttr(false));
}
if (srcType->isIntegerType())
return emitIntToBoolConversion(src, loc);
assert(::mlir::isa<cir::PointerType>(src.getType()));
return emitPointerToBoolConversion(src, srcType);
}
// Emit a conversion from the specified type to the specified destination
// type, both of which are CIR scalar types.
struct ScalarConversionOpts {
bool treatBooleanAsSigned;
bool emitImplicitIntegerTruncationChecks;
bool emitImplicitIntegerSignChangeChecks;
ScalarConversionOpts()
: treatBooleanAsSigned(false),
emitImplicitIntegerTruncationChecks(false),
emitImplicitIntegerSignChangeChecks(false) {}
ScalarConversionOpts(clang::SanitizerSet sanOpts)
: treatBooleanAsSigned(false),
emitImplicitIntegerTruncationChecks(
sanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
emitImplicitIntegerSignChangeChecks(
sanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
};
// Conversion from bool, integral, or floating-point to integral or
// floating-point. Conversions involving other types are handled elsewhere.
// Conversion to bool is handled elsewhere because that's a comparison against
// zero, not a simple cast. This handles both individual scalars and vectors.
mlir::Value emitScalarCast(mlir::Value src, QualType srcType,
QualType dstType, mlir::Type srcTy,
mlir::Type dstTy, ScalarConversionOpts opts) {
assert(!srcType->isMatrixType() && !dstType->isMatrixType() &&
"Internal error: matrix types not handled by this function.");
assert(!(mlir::isa<mlir::IntegerType>(srcTy) ||
mlir::isa<mlir::IntegerType>(dstTy)) &&
"Obsolete code. Don't use mlir::IntegerType with CIR.");
mlir::Type fullDstTy = dstTy;
assert(!cir::MissingFeatures::vectorType());
std::optional<cir::CastKind> castKind;
if (mlir::isa<cir::BoolType>(srcTy)) {
if (opts.treatBooleanAsSigned)
cgf.getCIRGenModule().errorNYI("signed bool");
if (cgf.getBuilder().isInt(dstTy))
castKind = cir::CastKind::bool_to_int;
else if (mlir::isa<cir::CIRFPTypeInterface>(dstTy))
castKind = cir::CastKind::bool_to_float;
else
llvm_unreachable("Internal error: Cast to unexpected type");
} else if (cgf.getBuilder().isInt(srcTy)) {
if (cgf.getBuilder().isInt(dstTy))
castKind = cir::CastKind::integral;
else if (mlir::isa<cir::CIRFPTypeInterface>(dstTy))
castKind = cir::CastKind::int_to_float;
else
llvm_unreachable("Internal error: Cast to unexpected type");
} else if (mlir::isa<cir::CIRFPTypeInterface>(srcTy)) {
if (cgf.getBuilder().isInt(dstTy)) {
// If we can't recognize overflow as undefined behavior, assume that
// overflow saturates. This protects against normal optimizations if we
// are compiling with non-standard FP semantics.
if (!cgf.cgm.getCodeGenOpts().StrictFloatCastOverflow)
cgf.getCIRGenModule().errorNYI("strict float cast overflow");
assert(!cir::MissingFeatures::fpConstraints());
castKind = cir::CastKind::float_to_int;
} else if (mlir::isa<cir::CIRFPTypeInterface>(dstTy)) {
cgf.getCIRGenModule().errorNYI("floating point casts");
return cgf.createDummyValue(src.getLoc(), dstType);
} else {
llvm_unreachable("Internal error: Cast to unexpected type");
}
} else {
llvm_unreachable("Internal error: Cast from unexpected type");
}
assert(castKind.has_value() && "Internal error: CastKind not set.");
return builder.create<cir::CastOp>(src.getLoc(), fullDstTy, *castKind, src);
}
mlir::Value VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *e);
// Unary Operators.
mlir::Value VisitUnaryPostDec(const UnaryOperator *e) {
LValue lv = cgf.emitLValue(e->getSubExpr());
return emitScalarPrePostIncDec(e, lv, false, false);
}
mlir::Value VisitUnaryPostInc(const UnaryOperator *e) {
LValue lv = cgf.emitLValue(e->getSubExpr());
return emitScalarPrePostIncDec(e, lv, true, false);
}
mlir::Value VisitUnaryPreDec(const UnaryOperator *e) {
LValue lv = cgf.emitLValue(e->getSubExpr());
return emitScalarPrePostIncDec(e, lv, false, true);
}
mlir::Value VisitUnaryPreInc(const UnaryOperator *e) {
LValue lv = cgf.emitLValue(e->getSubExpr());
return emitScalarPrePostIncDec(e, lv, true, true);
}
mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv,
bool isInc, bool isPre) {
if (cgf.getLangOpts().OpenMP)
cgf.cgm.errorNYI(e->getSourceRange(), "inc/dec OpenMP");
QualType type = e->getSubExpr()->getType();
mlir::Value value;
mlir::Value input;
if (type->getAs<AtomicType>()) {
cgf.cgm.errorNYI(e->getSourceRange(), "Atomic inc/dec");
// TODO(cir): This is not correct, but it will produce reasonable code
// until atomic operations are implemented.
value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getScalarVal();
input = value;
} else {
value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getScalarVal();
input = value;
}
// NOTE: When possible, more frequent cases are handled first.
// Special case of integer increment that we have to check first: bool++.
// Due to promotion rules, we get:
// bool++ -> bool = bool + 1
// -> bool = (int)bool + 1
// -> bool = ((int)bool + 1 != 0)
// An interesting aspect of this is that increment is always true.
// Decrement does not have this property.
if (isInc && type->isBooleanType()) {
value = builder.create<cir::ConstantOp>(cgf.getLoc(e->getExprLoc()),
cgf.convertType(type),
builder.getCIRBoolAttr(true));
} else if (type->isIntegerType()) {
QualType promotedType;
bool canPerformLossyDemotionCheck = false;
if (cgf.getContext().isPromotableIntegerType(type)) {
promotedType = cgf.getContext().getPromotedIntegerType(type);
assert(promotedType != type && "Shouldn't promote to the same type.");
canPerformLossyDemotionCheck = true;
canPerformLossyDemotionCheck &=
cgf.getContext().getCanonicalType(type) !=
cgf.getContext().getCanonicalType(promotedType);
canPerformLossyDemotionCheck &=
type->isIntegerType() && promotedType->isIntegerType();
// TODO(cir): Currently, we store bitwidths in CIR types only for
// integers. This might also be required for other types.
assert(
(!canPerformLossyDemotionCheck ||
type->isSignedIntegerOrEnumerationType() ||
promotedType->isSignedIntegerOrEnumerationType() ||
mlir::cast<cir::IntType>(cgf.convertType(type)).getWidth() ==
mlir::cast<cir::IntType>(cgf.convertType(type)).getWidth()) &&
"The following check expects that if we do promotion to different "
"underlying canonical type, at least one of the types (either "
"base or promoted) will be signed, or the bitwidths will match.");
}
assert(!cir::MissingFeatures::sanitizers());
if (e->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
value = emitIncDecConsiderOverflowBehavior(e, value, isInc);
} else {
cir::UnaryOpKind kind =
e->isIncrementOp() ? cir::UnaryOpKind::Inc : cir::UnaryOpKind::Dec;
// NOTE(CIR): clang calls CreateAdd but folds this to a unary op
value = emitUnaryOp(e, kind, input, /*nsw=*/false);
}
} else if (isa<PointerType>(type)) {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec pointer");
return {};
} else if (type->isVectorType()) {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec vector");
return {};
} else if (type->isRealFloatingType()) {
assert(!cir::MissingFeatures::cgFPOptionsRAII());
if (type->isHalfType() &&
!cgf.getContext().getLangOpts().NativeHalfType) {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec half");
return {};
}
if (mlir::isa<cir::SingleType, cir::DoubleType>(value.getType())) {
// Create the inc/dec operation.
// NOTE(CIR): clang calls CreateAdd but folds this to a unary op
cir::UnaryOpKind kind =
(isInc ? cir::UnaryOpKind::Inc : cir::UnaryOpKind::Dec);
value = emitUnaryOp(e, kind, value);
} else {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec other fp type");
return {};
}
} else if (type->isFixedPointType()) {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec other fixed point");
return {};
} else {
assert(type->castAs<ObjCObjectPointerType>());
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec ObjectiveC pointer");
return {};
}
CIRGenFunction::SourceLocRAIIObject sourceloc{
cgf, cgf.getLoc(e->getSourceRange())};
// Store the updated result through the lvalue
if (lv.isBitField()) {
cgf.cgm.errorNYI(e->getSourceRange(), "Unary inc/dec bitfield");
return {};
} else {
cgf.emitStoreThroughLValue(RValue::get(value), lv);
}
// If this is a postinc, return the value read from memory, otherwise use
// the updated value.
return isPre ? value : input;
}
mlir::Value emitIncDecConsiderOverflowBehavior(const UnaryOperator *e,
mlir::Value inVal,
bool isInc) {
cir::UnaryOpKind kind =
e->isIncrementOp() ? cir::UnaryOpKind::Inc : cir::UnaryOpKind::Dec;
switch (cgf.getLangOpts().getSignedOverflowBehavior()) {
case LangOptions::SOB_Defined:
return emitUnaryOp(e, kind, inVal, /*nsw=*/false);
case LangOptions::SOB_Undefined:
assert(!cir::MissingFeatures::sanitizers());
return emitUnaryOp(e, kind, inVal, /*nsw=*/true);
case LangOptions::SOB_Trapping:
if (!e->canOverflow())
return emitUnaryOp(e, kind, inVal, /*nsw=*/true);
cgf.cgm.errorNYI(e->getSourceRange(), "inc/def overflow SOB_Trapping");
return {};
}
llvm_unreachable("Unexpected signed overflow behavior kind");
}
mlir::Value VisitUnaryAddrOf(const UnaryOperator *e) {
if (llvm::isa<MemberPointerType>(e->getType())) {
cgf.cgm.errorNYI(e->getSourceRange(), "Address of member pointer");
return builder.getNullPtr(cgf.convertType(e->getType()),
cgf.getLoc(e->getExprLoc()));
}
return cgf.emitLValue(e->getSubExpr()).getPointer();
}
mlir::Value VisitUnaryDeref(const UnaryOperator *e) {
if (e->getType()->isVoidType())
return Visit(e->getSubExpr()); // the actual value should be unused
return emitLoadOfLValue(e);
}
mlir::Value VisitUnaryPlus(const UnaryOperator *e) {
return emitUnaryPlusOrMinus(e, cir::UnaryOpKind::Plus);
}
mlir::Value VisitUnaryMinus(const UnaryOperator *e) {
return emitUnaryPlusOrMinus(e, cir::UnaryOpKind::Minus);
}
mlir::Value emitUnaryPlusOrMinus(const UnaryOperator *e,
cir::UnaryOpKind kind) {
ignoreResultAssign = false;
QualType promotionType = getPromotionType(e->getSubExpr()->getType());
mlir::Value operand;
if (!promotionType.isNull())
operand = cgf.emitPromotedScalarExpr(e->getSubExpr(), promotionType);
else
operand = Visit(e->getSubExpr());
bool nsw =
kind == cir::UnaryOpKind::Minus && e->getType()->isSignedIntegerType();
// NOTE: LLVM codegen will lower this directly to either a FNeg
// or a Sub instruction. In CIR this will be handled later in LowerToLLVM.
mlir::Value result = emitUnaryOp(e, kind, operand, nsw);
if (result && !promotionType.isNull())
return emitUnPromotedValue(result, e->getType());
return result;
}
mlir::Value emitUnaryOp(const UnaryOperator *e, cir::UnaryOpKind kind,
mlir::Value input, bool nsw = false) {
return builder.create<cir::UnaryOp>(
cgf.getLoc(e->getSourceRange().getBegin()), input.getType(), kind,
input, nsw);
}
mlir::Value VisitUnaryNot(const UnaryOperator *e) {
ignoreResultAssign = false;
mlir::Value op = Visit(e->getSubExpr());
return emitUnaryOp(e, cir::UnaryOpKind::Not, op);
}
mlir::Value VisitUnaryLNot(const UnaryOperator *e);
/// Emit a conversion from the specified type to the specified destination
/// type, both of which are CIR scalar types.
/// TODO: do we need ScalarConversionOpts here? Should be done in another
/// pass.
mlir::Value
emitScalarConversion(mlir::Value src, QualType srcType, QualType dstType,
SourceLocation loc,
ScalarConversionOpts opts = ScalarConversionOpts()) {
// All conversions involving fixed point types should be handled by the
// emitFixedPoint family functions. This is done to prevent bloating up
// this function more, and although fixed point numbers are represented by
// integers, we do not want to follow any logic that assumes they should be
// treated as integers.
// TODO(leonardchan): When necessary, add another if statement checking for
// conversions to fixed point types from other types.
// conversions to fixed point types from other types.
if (srcType->isFixedPointType() || dstType->isFixedPointType()) {
cgf.getCIRGenModule().errorNYI(loc, "fixed point conversions");
return {};
}
srcType = srcType.getCanonicalType();
dstType = dstType.getCanonicalType();
if (srcType == dstType) {
if (opts.emitImplicitIntegerSignChangeChecks)
cgf.getCIRGenModule().errorNYI(loc,
"implicit integer sign change checks");
return src;
}
if (dstType->isVoidType())
return {};
mlir::Type mlirSrcType = src.getType();
// Handle conversions to bool first, they are special: comparisons against
// 0.
if (dstType->isBooleanType())
return emitConversionToBool(src, srcType, cgf.getLoc(loc));
mlir::Type mlirDstType = cgf.convertType(dstType);
if (srcType->isHalfType() &&
!cgf.getContext().getLangOpts().NativeHalfType) {
// Cast to FP using the intrinsic if the half type itself isn't supported.
if (mlir::isa<cir::CIRFPTypeInterface>(mlirDstType)) {
if (cgf.getContext().getTargetInfo().useFP16ConversionIntrinsics())
cgf.getCIRGenModule().errorNYI(loc,
"cast via llvm.convert.from.fp16");
} else {
// Cast to other types through float, using either the intrinsic or
// FPExt, depending on whether the half type itself is supported (as
// opposed to operations on half, available with NativeHalfType).
if (cgf.getContext().getTargetInfo().useFP16ConversionIntrinsics())
cgf.getCIRGenModule().errorNYI(loc,
"cast via llvm.convert.from.fp16");
// FIXME(cir): For now lets pretend we shouldn't use the conversion
// intrinsics and insert a cast here unconditionally.
src = builder.createCast(cgf.getLoc(loc), cir::CastKind::floating, src,
cgf.FloatTy);
srcType = cgf.getContext().FloatTy;
mlirSrcType = cgf.FloatTy;
}
}
// TODO(cir): LLVM codegen ignore conversions like int -> uint,
// is there anything to be done for CIR here?
if (mlirSrcType == mlirDstType) {
if (opts.emitImplicitIntegerSignChangeChecks)
cgf.getCIRGenModule().errorNYI(loc,
"implicit integer sign change checks");
return src;
}
// Handle pointer conversions next: pointers can only be converted to/from
// other pointers and integers. Check for pointer types in terms of LLVM, as
// some native types (like Obj-C id) may map to a pointer type.
if (auto dstPT = dyn_cast<cir::PointerType>(mlirDstType)) {
cgf.getCIRGenModule().errorNYI(loc, "pointer casts");
return builder.getNullPtr(dstPT, src.getLoc());
}
if (isa<cir::PointerType>(mlirSrcType)) {
// Must be an ptr to int cast.
assert(isa<cir::IntType>(mlirDstType) && "not ptr->int?");
return builder.createPtrToInt(src, mlirDstType);
}
// A scalar can be splatted to an extended vector of the same element type
if (dstType->isExtVectorType() && !srcType->isVectorType()) {
// Sema should add casts to make sure that the source expression's type
// is the same as the vector's element type (sans qualifiers)
assert(dstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
srcType.getTypePtr() &&
"Splatted expr doesn't match with vector element type?");
cgf.getCIRGenModule().errorNYI(loc, "vector splatting");
return {};
}
if (srcType->isMatrixType() && dstType->isMatrixType()) {
cgf.getCIRGenModule().errorNYI(loc,
"matrix type to matrix type conversion");
return {};
}
assert(!srcType->isMatrixType() && !dstType->isMatrixType() &&
"Internal error: conversion between matrix type and scalar type");
// Finally, we have the arithmetic types or vectors of arithmetic types.
mlir::Value res = nullptr;
mlir::Type resTy = mlirDstType;
res = emitScalarCast(src, srcType, dstType, mlirSrcType, mlirDstType, opts);
if (mlirDstType != resTy) {
if (cgf.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
cgf.getCIRGenModule().errorNYI(loc, "cast via llvm.convert.to.fp16");
}
// FIXME(cir): For now we never use FP16 conversion intrinsics even if
// required by the target. Change that once this is implemented
res = builder.createCast(cgf.getLoc(loc), cir::CastKind::floating, res,
resTy);
}
if (opts.emitImplicitIntegerTruncationChecks)
cgf.getCIRGenModule().errorNYI(loc, "implicit integer truncation checks");
if (opts.emitImplicitIntegerSignChangeChecks)
cgf.getCIRGenModule().errorNYI(loc,
"implicit integer sign change checks");
return res;
}
BinOpInfo emitBinOps(const BinaryOperator *e,
QualType promotionType = QualType()) {
BinOpInfo result;
result.lhs = cgf.emitPromotedScalarExpr(e->getLHS(), promotionType);
result.rhs = cgf.emitPromotedScalarExpr(e->getRHS(), promotionType);
if (!promotionType.isNull())
result.fullType = promotionType;
else
result.fullType = e->getType();
result.compType = result.fullType;
if (const auto *vecType = dyn_cast_or_null<VectorType>(result.fullType)) {
result.compType = vecType->getElementType();
}
result.opcode = e->getOpcode();
result.loc = e->getSourceRange();
// TODO(cir): Result.FPFeatures
assert(!cir::MissingFeatures::cgFPOptionsRAII());
result.e = e;
return result;
}
mlir::Value emitMul(const BinOpInfo &ops);
mlir::Value emitDiv(const BinOpInfo &ops);
mlir::Value emitRem(const BinOpInfo &ops);
mlir::Value emitAdd(const BinOpInfo &ops);
mlir::Value emitSub(const BinOpInfo &ops);
mlir::Value emitShl(const BinOpInfo &ops);
mlir::Value emitShr(const BinOpInfo &ops);
mlir::Value emitAnd(const BinOpInfo &ops);
mlir::Value emitXor(const BinOpInfo &ops);
mlir::Value emitOr(const BinOpInfo &ops);
LValue emitCompoundAssignLValue(
const CompoundAssignOperator *e,
mlir::Value (ScalarExprEmitter::*f)(const BinOpInfo &),
mlir::Value &result);
mlir::Value
emitCompoundAssign(const CompoundAssignOperator *e,
mlir::Value (ScalarExprEmitter::*f)(const BinOpInfo &));
// TODO(cir): Candidate to be in a common AST helper between CIR and LLVM
// codegen.
QualType getPromotionType(QualType ty) {
if (ty->getAs<ComplexType>()) {
assert(!cir::MissingFeatures::complexType());
cgf.cgm.errorNYI("promotion to complex type");
return QualType();
}
if (ty.UseExcessPrecision(cgf.getContext())) {
if (ty->getAs<VectorType>()) {
assert(!cir::MissingFeatures::vectorType());
cgf.cgm.errorNYI("promotion to vector type");
return QualType();
}
return cgf.getContext().FloatTy;
}
return QualType();
}
// Binary operators and binary compound assignment operators.
#define HANDLEBINOP(OP) \
mlir::Value VisitBin##OP(const BinaryOperator *e) { \
QualType promotionTy = getPromotionType(e->getType()); \
auto result = emit##OP(emitBinOps(e, promotionTy)); \
if (result && !promotionTy.isNull()) \
result = emitUnPromotedValue(result, e->getType()); \
return result; \
} \
mlir::Value VisitBin##OP##Assign(const CompoundAssignOperator *e) { \
return emitCompoundAssign(e, &ScalarExprEmitter::emit##OP); \
}
HANDLEBINOP(Mul)
HANDLEBINOP(Div)
HANDLEBINOP(Rem)
HANDLEBINOP(Add)
HANDLEBINOP(Sub)
HANDLEBINOP(Shl)
HANDLEBINOP(Shr)
HANDLEBINOP(And)
HANDLEBINOP(Xor)
HANDLEBINOP(Or)
#undef HANDLEBINOP
mlir::Value emitCmp(const BinaryOperator *e) {
const mlir::Location loc = cgf.getLoc(e->getExprLoc());
mlir::Value result;
QualType lhsTy = e->getLHS()->getType();
QualType rhsTy = e->getRHS()->getType();
auto clangCmpToCIRCmp =
[](clang::BinaryOperatorKind clangCmp) -> cir::CmpOpKind {
switch (clangCmp) {
case BO_LT:
return cir::CmpOpKind::lt;
case BO_GT:
return cir::CmpOpKind::gt;
case BO_LE:
return cir::CmpOpKind::le;
case BO_GE:
return cir::CmpOpKind::ge;
case BO_EQ:
return cir::CmpOpKind::eq;
case BO_NE:
return cir::CmpOpKind::ne;
default:
llvm_unreachable("unsupported comparison kind for cir.cmp");
}
};
if (lhsTy->getAs<MemberPointerType>()) {
assert(!cir::MissingFeatures::dataMemberType());
assert(e->getOpcode() == BO_EQ || e->getOpcode() == BO_NE);
mlir::Value lhs = cgf.emitScalarExpr(e->getLHS());
mlir::Value rhs = cgf.emitScalarExpr(e->getRHS());
cir::CmpOpKind kind = clangCmpToCIRCmp(e->getOpcode());
result = builder.createCompare(loc, kind, lhs, rhs);
} else if (!lhsTy->isAnyComplexType() && !rhsTy->isAnyComplexType()) {
BinOpInfo boInfo = emitBinOps(e);
mlir::Value lhs = boInfo.lhs;
mlir::Value rhs = boInfo.rhs;
if (lhsTy->isVectorType()) {
assert(!cir::MissingFeatures::vectorType());
cgf.cgm.errorNYI(loc, "vector comparisons");
result = builder.getBool(false, loc);
} else if (boInfo.isFixedPointOp()) {
assert(!cir::MissingFeatures::fixedPointType());
cgf.cgm.errorNYI(loc, "fixed point comparisons");
result = builder.getBool(false, loc);
} else {
// integers and pointers
if (cgf.cgm.getCodeGenOpts().StrictVTablePointers &&
mlir::isa<cir::PointerType>(lhs.getType()) &&
mlir::isa<cir::PointerType>(rhs.getType())) {
cgf.cgm.errorNYI(loc, "strict vtable pointer comparisons");
}
cir::CmpOpKind kind = clangCmpToCIRCmp(e->getOpcode());
result = builder.createCompare(loc, kind, lhs, rhs);
}
} else {
// Complex Comparison: can only be an equality comparison.
assert(!cir::MissingFeatures::complexType());
cgf.cgm.errorNYI(loc, "complex comparison");
result = builder.getBool(false, loc);
}
return emitScalarConversion(result, cgf.getContext().BoolTy, e->getType(),
e->getExprLoc());
}
// Comparisons.
#define VISITCOMP(CODE) \
mlir::Value VisitBin##CODE(const BinaryOperator *E) { return emitCmp(E); }
VISITCOMP(LT)
VISITCOMP(GT)
VISITCOMP(LE)
VISITCOMP(GE)
VISITCOMP(EQ)
VISITCOMP(NE)
#undef VISITCOMP
mlir::Value VisitBinAssign(const BinaryOperator *e) {
const bool ignore = std::exchange(ignoreResultAssign, false);
mlir::Value rhs;
LValue lhs;
switch (e->getLHS()->getType().getObjCLifetime()) {
case Qualifiers::OCL_Strong:
case Qualifiers::OCL_Autoreleasing:
case Qualifiers::OCL_ExplicitNone:
case Qualifiers::OCL_Weak:
assert(!cir::MissingFeatures::objCLifetime());
break;
case Qualifiers::OCL_None:
// __block variables need to have the rhs evaluated first, plus this
// should improve codegen just a little.
rhs = Visit(e->getRHS());
assert(!cir::MissingFeatures::sanitizers());
// TODO(cir): This needs to be emitCheckedLValue() once we support
// sanitizers
lhs = cgf.emitLValue(e->getLHS());
// Store the value into the LHS. Bit-fields are handled specially because
// the result is altered by the store, i.e., [C99 6.5.16p1]
// 'An assignment expression has the value of the left operand after the
// assignment...'.
if (lhs.isBitField()) {
rhs = cgf.emitStoreThroughBitfieldLValue(RValue::get(rhs), lhs);
} else {
cgf.emitNullabilityCheck(lhs, rhs, e->getExprLoc());
CIRGenFunction::SourceLocRAIIObject loc{
cgf, cgf.getLoc(e->getSourceRange())};
cgf.emitStoreThroughLValue(RValue::get(rhs), lhs);
}
}
// If the result is clearly ignored, return now.
if (ignore)
return nullptr;
// The result of an assignment in C is the assigned r-value.
if (!cgf.getLangOpts().CPlusPlus)
return rhs;
// If the lvalue is non-volatile, return the computed value of the
// assignment.
if (!lhs.isVolatile())
return rhs;
// Otherwise, reload the value.
return emitLoadOfLValue(lhs, e->getExprLoc());
}
mlir::Value VisitBinComma(const BinaryOperator *e) {
cgf.emitIgnoredExpr(e->getLHS());
// NOTE: We don't need to EnsureInsertPoint() like LLVM codegen.
return Visit(e->getRHS());
}
};
LValue ScalarExprEmitter::emitCompoundAssignLValue(
const CompoundAssignOperator *e,
mlir::Value (ScalarExprEmitter::*func)(const BinOpInfo &),
mlir::Value &result) {
QualType lhsTy = e->getLHS()->getType();
BinOpInfo opInfo;
if (e->getComputationResultType()->isAnyComplexType()) {
cgf.cgm.errorNYI(result.getLoc(), "complex lvalue assign");
return LValue();
}
// Emit the RHS first. __block variables need to have the rhs evaluated
// first, plus this should improve codegen a little.
QualType promotionTypeCR = getPromotionType(e->getComputationResultType());
if (promotionTypeCR.isNull())
promotionTypeCR = e->getComputationResultType();
QualType promotionTypeLHS = getPromotionType(e->getComputationLHSType());
QualType promotionTypeRHS = getPromotionType(e->getRHS()->getType());
if (!promotionTypeRHS.isNull())
opInfo.rhs = cgf.emitPromotedScalarExpr(e->getRHS(), promotionTypeRHS);
else
opInfo.rhs = Visit(e->getRHS());
opInfo.fullType = promotionTypeCR;
opInfo.compType = opInfo.fullType;
if (const auto *vecType = dyn_cast_or_null<VectorType>(opInfo.fullType))
opInfo.compType = vecType->getElementType();
opInfo.opcode = e->getOpcode();
opInfo.fpfeatures = e->getFPFeaturesInEffect(cgf.getLangOpts());
opInfo.e = e;
opInfo.loc = e->getSourceRange();
// Load/convert the LHS
LValue lhsLV = cgf.emitLValue(e->getLHS());
if (lhsTy->getAs<AtomicType>()) {
cgf.cgm.errorNYI(result.getLoc(), "atomic lvalue assign");
return LValue();
}
opInfo.lhs = emitLoadOfLValue(lhsLV, e->getExprLoc());
CIRGenFunction::SourceLocRAIIObject sourceloc{
cgf, cgf.getLoc(e->getSourceRange())};
SourceLocation loc = e->getExprLoc();
if (!promotionTypeLHS.isNull())
opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy, promotionTypeLHS, loc);
else
opInfo.lhs = emitScalarConversion(opInfo.lhs, lhsTy,
e->getComputationLHSType(), loc);
// Expand the binary operator.
result = (this->*func)(opInfo);
// Convert the result back to the LHS type,
// potentially with Implicit Conversion sanitizer check.
result = emitScalarConversion(result, promotionTypeCR, lhsTy, loc,
ScalarConversionOpts(cgf.sanOpts));
// Store the result value into the LHS lvalue. Bit-fields are handled
// specially because the result is altered by the store, i.e., [C99 6.5.16p1]
// 'An assignment expression has the value of the left operand after the
// assignment...'.
if (lhsLV.isBitField())
cgf.cgm.errorNYI(e->getSourceRange(), "store through bitfield lvalue");
else
cgf.emitStoreThroughLValue(RValue::get(result), lhsLV);
if (cgf.getLangOpts().OpenMP)
cgf.cgm.errorNYI(e->getSourceRange(), "openmp");
return lhsLV;
}
mlir::Value ScalarExprEmitter::emitPromoted(const Expr *e,
QualType promotionType) {
e = e->IgnoreParens();
if (const auto *bo = dyn_cast<BinaryOperator>(e)) {
switch (bo->getOpcode()) {
#define HANDLE_BINOP(OP) \
case BO_##OP: \
return emit##OP(emitBinOps(bo, promotionType));
HANDLE_BINOP(Add)
HANDLE_BINOP(Sub)
HANDLE_BINOP(Mul)
HANDLE_BINOP(Div)
#undef HANDLE_BINOP
default:
break;
}
} else if (isa<UnaryOperator>(e)) {
cgf.cgm.errorNYI(e->getSourceRange(), "unary operators");
return {};
}
mlir::Value result = Visit(const_cast<Expr *>(e));
if (result) {
if (!promotionType.isNull())
return emitPromotedValue(result, promotionType);
return emitUnPromotedValue(result, e->getType());
}
return result;
}
mlir::Value ScalarExprEmitter::emitCompoundAssign(
const CompoundAssignOperator *e,
mlir::Value (ScalarExprEmitter::*func)(const BinOpInfo &)) {
bool ignore = std::exchange(ignoreResultAssign, false);
mlir::Value rhs;
LValue lhs = emitCompoundAssignLValue(e, func, rhs);
// If the result is clearly ignored, return now.
if (ignore)
return {};