forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 337
/
Copy pathtools.cpp
2174 lines (2032 loc) · 81.6 KB
/
tools.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
//===-- lib/Evaluate/tools.cpp --------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "flang/Evaluate/tools.h"
#include "flang/Common/idioms.h"
#include "flang/Common/type-kinds.h"
#include "flang/Evaluate/characteristics.h"
#include "flang/Evaluate/traverse.h"
#include "flang/Parser/message.h"
#include "flang/Semantics/tools.h"
#include <algorithm>
#include <variant>
using namespace Fortran::parser::literals;
namespace Fortran::evaluate {
// Can x*(a,b) be represented as (x*a,x*b)? This code duplication
// of the subexpression "x" cannot (yet?) be reliably undone by
// common subexpression elimination in lowering, so it's disabled
// here for now to avoid the risk of potential duplication of
// expensive subexpressions (e.g., large array expressions, references
// to expensive functions) in generate code.
static constexpr bool allowOperandDuplication{false};
std::optional<Expr<SomeType>> AsGenericExpr(DataRef &&ref) {
if (auto dyType{DynamicType::From(ref.GetLastSymbol())}) {
return TypedWrapper<Designator, DataRef>(*dyType, std::move(ref));
} else {
return std::nullopt;
}
}
std::optional<Expr<SomeType>> AsGenericExpr(const Symbol &symbol) {
return AsGenericExpr(DataRef{symbol});
}
Expr<SomeType> Parenthesize(Expr<SomeType> &&expr) {
return common::visit(
[&](auto &&x) {
using T = std::decay_t<decltype(x)>;
if constexpr (common::HasMember<T, TypelessExpression>) {
return expr; // no parentheses around typeless
} else if constexpr (std::is_same_v<T, Expr<SomeDerived>>) {
return AsGenericExpr(Parentheses<SomeDerived>{std::move(x)});
} else {
return common::visit(
[](auto &&y) {
using T = ResultType<decltype(y)>;
return AsGenericExpr(Parentheses<T>{std::move(y)});
},
std::move(x.u));
}
},
std::move(expr.u));
}
std::optional<DataRef> ExtractDataRef(
const ActualArgument &arg, bool intoSubstring, bool intoComplexPart) {
return ExtractDataRef(arg.UnwrapExpr(), intoSubstring, intoComplexPart);
}
std::optional<DataRef> ExtractSubstringBase(const Substring &substring) {
return common::visit(
common::visitors{
[&](const DataRef &x) -> std::optional<DataRef> { return x; },
[&](const StaticDataObject::Pointer &) -> std::optional<DataRef> {
return std::nullopt;
},
},
substring.parent());
}
// IsVariable()
auto IsVariableHelper::operator()(const Symbol &symbol) const -> Result {
// ASSOCIATE(x => expr) -- x counts as a variable, but undefinable
const Symbol &ultimate{symbol.GetUltimate()};
return !IsNamedConstant(ultimate) &&
(ultimate.has<semantics::ObjectEntityDetails>() ||
(ultimate.has<semantics::EntityDetails>() &&
ultimate.attrs().test(semantics::Attr::TARGET)) ||
ultimate.has<semantics::AssocEntityDetails>());
}
auto IsVariableHelper::operator()(const Component &x) const -> Result {
const Symbol &comp{x.GetLastSymbol()};
return (*this)(comp) && (IsPointer(comp) || (*this)(x.base()));
}
auto IsVariableHelper::operator()(const ArrayRef &x) const -> Result {
return (*this)(x.base());
}
auto IsVariableHelper::operator()(const Substring &x) const -> Result {
return (*this)(x.GetBaseObject());
}
auto IsVariableHelper::operator()(const ProcedureDesignator &x) const
-> Result {
if (const Symbol * symbol{x.GetSymbol()}) {
const Symbol *result{FindFunctionResult(*symbol)};
return result && IsPointer(*result) && !IsProcedurePointer(*result);
}
return false;
}
// Conversions of COMPLEX component expressions to REAL.
ConvertRealOperandsResult ConvertRealOperands(
parser::ContextualMessages &messages, Expr<SomeType> &&x,
Expr<SomeType> &&y, int defaultRealKind) {
return common::visit(
common::visitors{
[&](Expr<SomeInteger> &&ix,
Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
// Can happen in a CMPLX() constructor. Per F'2018,
// both integer operands are converted to default REAL.
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeInteger> &&ix,
Expr<SomeUnsigned> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeUnsigned> &&ix,
Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeUnsigned> &&ix,
Expr<SomeUnsigned> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeInteger> &&ix,
Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertTo(ry, std::move(ix)), std::move(ry))};
},
[&](Expr<SomeUnsigned> &&ix,
Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertTo(ry, std::move(ix)), std::move(ry))};
},
[&](Expr<SomeReal> &&rx,
Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
std::move(rx), ConvertTo(rx, std::move(iy)))};
},
[&](Expr<SomeReal> &&rx,
Expr<SomeUnsigned> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
std::move(rx), ConvertTo(rx, std::move(iy)))};
},
[&](Expr<SomeReal> &&rx,
Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
std::move(rx), std::move(ry))};
},
[&](Expr<SomeInteger> &&ix,
BOZLiteralConstant &&by) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(by)))};
},
[&](Expr<SomeUnsigned> &&ix,
BOZLiteralConstant &&by) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(ix)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(by)))};
},
[&](BOZLiteralConstant &&bx,
Expr<SomeInteger> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(bx)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](BOZLiteralConstant &&bx,
Expr<SomeUnsigned> &&iy) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(bx)),
ConvertToKind<TypeCategory::Real>(
defaultRealKind, std::move(iy)))};
},
[&](Expr<SomeReal> &&rx,
BOZLiteralConstant &&by) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
std::move(rx), ConvertTo(rx, std::move(by)))};
},
[&](BOZLiteralConstant &&bx,
Expr<SomeReal> &&ry) -> ConvertRealOperandsResult {
return {AsSameKindExprs<TypeCategory::Real>(
ConvertTo(ry, std::move(bx)), std::move(ry))};
},
[&](BOZLiteralConstant &&,
BOZLiteralConstant &&) -> ConvertRealOperandsResult {
messages.Say("operands cannot both be BOZ"_err_en_US);
return std::nullopt;
},
[&](auto &&, auto &&) -> ConvertRealOperandsResult { // C718
messages.Say(
"operands must be INTEGER, UNSIGNED, REAL, or BOZ"_err_en_US);
return std::nullopt;
},
},
std::move(x.u), std::move(y.u));
}
// Helpers for NumericOperation and its subroutines below.
static std::optional<Expr<SomeType>> NoExpr() { return std::nullopt; }
template <TypeCategory CAT>
std::optional<Expr<SomeType>> Package(Expr<SomeKind<CAT>> &&catExpr) {
return {AsGenericExpr(std::move(catExpr))};
}
template <TypeCategory CAT>
std::optional<Expr<SomeType>> Package(
std::optional<Expr<SomeKind<CAT>>> &&catExpr) {
if (catExpr) {
return {AsGenericExpr(std::move(*catExpr))};
} else {
return std::nullopt;
}
}
// Mixed REAL+INTEGER operations. REAL**INTEGER is a special case that
// does not require conversion of the exponent expression.
template <template <typename> class OPR>
std::optional<Expr<SomeType>> MixedRealLeft(
Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
return Package(common::visit(
[&](auto &&rxk) -> Expr<SomeReal> {
using resultType = ResultType<decltype(rxk)>;
if constexpr (std::is_same_v<OPR<resultType>, Power<resultType>>) {
return AsCategoryExpr(
RealToIntPower<resultType>{std::move(rxk), std::move(iy)});
}
// G++ 8.1.0 emits bogus warnings about missing return statements if
// this statement is wrapped in an "else", as it should be.
return AsCategoryExpr(OPR<resultType>{
std::move(rxk), ConvertToType<resultType>(std::move(iy))});
},
std::move(rx.u)));
}
template <int KIND>
Expr<SomeComplex> MakeComplex(Expr<Type<TypeCategory::Real, KIND>> &&re,
Expr<Type<TypeCategory::Real, KIND>> &&im) {
return AsCategoryExpr(ComplexConstructor<KIND>{std::move(re), std::move(im)});
}
std::optional<Expr<SomeComplex>> ConstructComplex(
parser::ContextualMessages &messages, Expr<SomeType> &&real,
Expr<SomeType> &&imaginary, int defaultRealKind) {
if (auto converted{ConvertRealOperands(
messages, std::move(real), std::move(imaginary), defaultRealKind)}) {
return {common::visit(
[](auto &&pair) {
return MakeComplex(std::move(pair[0]), std::move(pair[1]));
},
std::move(*converted))};
}
return std::nullopt;
}
std::optional<Expr<SomeComplex>> ConstructComplex(
parser::ContextualMessages &messages, std::optional<Expr<SomeType>> &&real,
std::optional<Expr<SomeType>> &&imaginary, int defaultRealKind) {
if (auto parts{common::AllPresent(std::move(real), std::move(imaginary))}) {
return ConstructComplex(messages, std::get<0>(std::move(*parts)),
std::get<1>(std::move(*parts)), defaultRealKind);
}
return std::nullopt;
}
// Extracts the real or imaginary part of the result of a COMPLEX
// expression, when that expression is simple enough to be duplicated.
template <bool GET_IMAGINARY> struct ComplexPartExtractor {
template <typename A> static std::optional<Expr<SomeReal>> Get(const A &) {
return std::nullopt;
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Parentheses<Type<TypeCategory::Complex, KIND>> &kz) {
if (auto x{Get(kz.left())}) {
return AsGenericExpr(AsSpecificExpr(
Parentheses<Type<TypeCategory::Real, KIND>>{std::move(*x)}));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Negate<Type<TypeCategory::Complex, KIND>> &kz) {
if (auto x{Get(kz.left())}) {
return AsGenericExpr(AsSpecificExpr(
Negate<Type<TypeCategory::Real, KIND>>{std::move(*x)}));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Convert<Type<TypeCategory::Complex, KIND>, TypeCategory::Complex>
&kz) {
if (auto x{Get(kz.left())}) {
return AsGenericExpr(AsSpecificExpr(
Convert<Type<TypeCategory::Real, KIND>, TypeCategory::Real>{
AsGenericExpr(std::move(*x))}));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(const ComplexConstructor<KIND> &kz) {
return GET_IMAGINARY ? Get(kz.right()) : Get(kz.left());
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Constant<Type<TypeCategory::Complex, KIND>> &kz) {
if (auto cz{kz.GetScalarValue()}) {
return AsGenericExpr(
AsSpecificExpr(GET_IMAGINARY ? cz->AIMAG() : cz->REAL()));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Designator<Type<TypeCategory::Complex, KIND>> &kz) {
if (const auto *symbolRef{std::get_if<SymbolRef>(&kz.u)}) {
return AsGenericExpr(AsSpecificExpr(
Designator<Type<TypeCategory::Complex, KIND>>{ComplexPart{
DataRef{*symbolRef},
GET_IMAGINARY ? ComplexPart::Part::IM : ComplexPart::Part::RE}}));
} else {
return std::nullopt;
}
}
template <int KIND>
static std::optional<Expr<SomeReal>> Get(
const Expr<Type<TypeCategory::Complex, KIND>> &kz) {
return Get(kz.u);
}
static std::optional<Expr<SomeReal>> Get(const Expr<SomeComplex> &z) {
return Get(z.u);
}
};
// Convert REAL to COMPLEX of the same kind. Preserving the real operand kind
// and then applying complex operand promotion rules allows the result to have
// the highest precision of REAL and COMPLEX operands as required by Fortran
// 2018 10.9.1.3.
Expr<SomeComplex> PromoteRealToComplex(Expr<SomeReal> &&someX) {
return common::visit(
[](auto &&x) {
using RT = ResultType<decltype(x)>;
return AsCategoryExpr(ComplexConstructor<RT::kind>{
std::move(x), AsExpr(Constant<RT>{Scalar<RT>{}})});
},
std::move(someX.u));
}
// Handle mixed COMPLEX+REAL (or INTEGER) operations in a better way
// than just converting the second operand to COMPLEX and performing the
// corresponding COMPLEX+COMPLEX operation.
template <template <typename> class OPR, TypeCategory RCAT>
std::optional<Expr<SomeType>> MixedComplexLeft(
parser::ContextualMessages &messages, const Expr<SomeComplex> &zx,
const Expr<SomeKind<RCAT>> &iry, [[maybe_unused]] int defaultRealKind) {
if constexpr (RCAT == TypeCategory::Integer &&
std::is_same_v<OPR<LargestReal>, Power<LargestReal>>) {
// COMPLEX**INTEGER is a special case that doesn't convert the exponent.
return Package(common::visit(
[&](const auto &zxk) {
using Ty = ResultType<decltype(zxk)>;
return AsCategoryExpr(AsExpr(
RealToIntPower<Ty>{common::Clone(zxk), common::Clone(iry)}));
},
zx.u));
}
std::optional<Expr<SomeReal>> zr{ComplexPartExtractor<false>{}.Get(zx)};
std::optional<Expr<SomeReal>> zi{ComplexPartExtractor<true>{}.Get(zx)};
if (!zr || !zi) {
} else if constexpr (std::is_same_v<OPR<LargestReal>, Add<LargestReal>> ||
std::is_same_v<OPR<LargestReal>, Subtract<LargestReal>>) {
// (a,b) + x -> (a+x, b)
// (a,b) - x -> (a-x, b)
if (std::optional<Expr<SomeType>> rr{
NumericOperation<OPR>(messages, AsGenericExpr(std::move(*zr)),
AsGenericExpr(common::Clone(iry)), defaultRealKind)}) {
return Package(ConstructComplex(messages, std::move(*rr),
AsGenericExpr(std::move(*zi)), defaultRealKind));
}
} else if constexpr (allowOperandDuplication &&
(std::is_same_v<OPR<LargestReal>, Multiply<LargestReal>> ||
std::is_same_v<OPR<LargestReal>, Divide<LargestReal>>)) {
// (a,b) * x -> (a*x, b*x)
// (a,b) / x -> (a/x, b/x)
auto copy{iry};
auto rr{NumericOperation<OPR>(messages, AsGenericExpr(std::move(*zr)),
AsGenericExpr(common::Clone(iry)), defaultRealKind)};
auto ri{NumericOperation<OPR>(messages, AsGenericExpr(std::move(*zi)),
AsGenericExpr(std::move(copy)), defaultRealKind)};
if (auto parts{common::AllPresent(std::move(rr), std::move(ri))}) {
return Package(ConstructComplex(messages, std::get<0>(std::move(*parts)),
std::get<1>(std::move(*parts)), defaultRealKind));
}
}
return std::nullopt;
}
// Mixed COMPLEX operations with the COMPLEX operand on the right.
// x + (a,b) -> (x+a, b)
// x - (a,b) -> (x-a, -b)
// x * (a,b) -> (x*a, x*b)
// x / (a,b) -> (x,0) / (a,b) (and **)
template <template <typename> class OPR, TypeCategory LCAT>
std::optional<Expr<SomeType>> MixedComplexRight(
parser::ContextualMessages &messages, const Expr<SomeKind<LCAT>> &irx,
const Expr<SomeComplex> &zy, [[maybe_unused]] int defaultRealKind) {
if constexpr (std::is_same_v<OPR<LargestReal>, Add<LargestReal>>) {
// x + (a,b) -> (a,b) + x -> (a+x, b)
return MixedComplexLeft<OPR, LCAT>(messages, zy, irx, defaultRealKind);
} else if constexpr (allowOperandDuplication &&
std::is_same_v<OPR<LargestReal>, Multiply<LargestReal>>) {
// x * (a,b) -> (a,b) * x -> (a*x, b*x)
return MixedComplexLeft<OPR, LCAT>(messages, zy, irx, defaultRealKind);
} else if constexpr (std::is_same_v<OPR<LargestReal>,
Subtract<LargestReal>>) {
// x - (a,b) -> (x-a, -b)
std::optional<Expr<SomeReal>> zr{ComplexPartExtractor<false>{}.Get(zy)};
std::optional<Expr<SomeReal>> zi{ComplexPartExtractor<true>{}.Get(zy)};
if (zr && zi) {
if (std::optional<Expr<SomeType>> rr{NumericOperation<Subtract>(messages,
AsGenericExpr(common::Clone(irx)), AsGenericExpr(std::move(*zr)),
defaultRealKind)}) {
return Package(ConstructComplex(messages, std::move(*rr),
AsGenericExpr(-std::move(*zi)), defaultRealKind));
}
}
}
return std::nullopt;
}
// Promotes REAL(rk) and COMPLEX(zk) operands COMPLEX(max(rk,zk))
// then combine them with an operator.
template <template <typename> class OPR, TypeCategory XCAT, TypeCategory YCAT>
Expr<SomeComplex> PromoteMixedComplexReal(
Expr<SomeKind<XCAT>> &&x, Expr<SomeKind<YCAT>> &&y) {
static_assert(XCAT == TypeCategory::Complex || YCAT == TypeCategory::Complex);
static_assert(XCAT == TypeCategory::Real || YCAT == TypeCategory::Real);
return common::visit(
[&](const auto &kx, const auto &ky) {
constexpr int maxKind{std::max(
ResultType<decltype(kx)>::kind, ResultType<decltype(ky)>::kind)};
using ZTy = Type<TypeCategory::Complex, maxKind>;
return Expr<SomeComplex>{
Expr<ZTy>{OPR<ZTy>{ConvertToType<ZTy>(std::move(x)),
ConvertToType<ZTy>(std::move(y))}}};
},
x.u, y.u);
}
// N.B. When a "typeless" BOZ literal constant appears as one (not both!) of
// the operands to a dyadic operation where one is permitted, it assumes the
// type and kind of the other operand.
template <template <typename> class OPR, bool CAN_BE_UNSIGNED>
std::optional<Expr<SomeType>> NumericOperation(
parser::ContextualMessages &messages, Expr<SomeType> &&x,
Expr<SomeType> &&y, int defaultRealKind) {
return common::visit(
common::visitors{
[](Expr<SomeInteger> &&ix, Expr<SomeInteger> &&iy) {
return Package(PromoteAndCombine<OPR, TypeCategory::Integer>(
std::move(ix), std::move(iy)));
},
[](Expr<SomeReal> &&rx, Expr<SomeReal> &&ry) {
return Package(PromoteAndCombine<OPR, TypeCategory::Real>(
std::move(rx), std::move(ry)));
},
[&](Expr<SomeUnsigned> &&ix, Expr<SomeUnsigned> &&iy) {
if constexpr (CAN_BE_UNSIGNED) {
return Package(PromoteAndCombine<OPR, TypeCategory::Unsigned>(
std::move(ix), std::move(iy)));
} else {
messages.Say("Operands must not be UNSIGNED"_err_en_US);
return NoExpr();
}
},
// Mixed REAL/INTEGER operations
[](Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
return MixedRealLeft<OPR>(std::move(rx), std::move(iy));
},
[](Expr<SomeInteger> &&ix, Expr<SomeReal> &&ry) {
return Package(common::visit(
[&](auto &&ryk) -> Expr<SomeReal> {
using resultType = ResultType<decltype(ryk)>;
return AsCategoryExpr(
OPR<resultType>{ConvertToType<resultType>(std::move(ix)),
std::move(ryk)});
},
std::move(ry.u)));
},
// Homogeneous and mixed COMPLEX operations
[](Expr<SomeComplex> &&zx, Expr<SomeComplex> &&zy) {
return Package(PromoteAndCombine<OPR, TypeCategory::Complex>(
std::move(zx), std::move(zy)));
},
[&](Expr<SomeComplex> &&zx, Expr<SomeInteger> &&iy) {
if (auto result{
MixedComplexLeft<OPR>(messages, zx, iy, defaultRealKind)}) {
return result;
} else {
return Package(PromoteAndCombine<OPR, TypeCategory::Complex>(
std::move(zx), ConvertTo(zx, std::move(iy))));
}
},
[&](Expr<SomeComplex> &&zx, Expr<SomeReal> &&ry) {
if (auto result{
MixedComplexLeft<OPR>(messages, zx, ry, defaultRealKind)}) {
return result;
} else {
return Package(
PromoteMixedComplexReal<OPR>(std::move(zx), std::move(ry)));
}
},
[&](Expr<SomeInteger> &&ix, Expr<SomeComplex> &&zy) {
if (auto result{MixedComplexRight<OPR>(
messages, ix, zy, defaultRealKind)}) {
return result;
} else {
return Package(PromoteAndCombine<OPR, TypeCategory::Complex>(
ConvertTo(zy, std::move(ix)), std::move(zy)));
}
},
[&](Expr<SomeReal> &&rx, Expr<SomeComplex> &&zy) {
if (auto result{MixedComplexRight<OPR>(
messages, rx, zy, defaultRealKind)}) {
return result;
} else {
return Package(
PromoteMixedComplexReal<OPR>(std::move(rx), std::move(zy)));
}
},
// Operations with one typeless operand
[&](BOZLiteralConstant &&bx, Expr<SomeInteger> &&iy) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
AsGenericExpr(ConvertTo(iy, std::move(bx))), std::move(y),
defaultRealKind);
},
[&](BOZLiteralConstant &&bx, Expr<SomeUnsigned> &&iy) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
AsGenericExpr(ConvertTo(iy, std::move(bx))), std::move(y),
defaultRealKind);
},
[&](BOZLiteralConstant &&bx, Expr<SomeReal> &&ry) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
AsGenericExpr(ConvertTo(ry, std::move(bx))), std::move(y),
defaultRealKind);
},
[&](Expr<SomeInteger> &&ix, BOZLiteralConstant &&by) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
std::move(x), AsGenericExpr(ConvertTo(ix, std::move(by))),
defaultRealKind);
},
[&](Expr<SomeUnsigned> &&ix, BOZLiteralConstant &&by) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
std::move(x), AsGenericExpr(ConvertTo(ix, std::move(by))),
defaultRealKind);
},
[&](Expr<SomeReal> &&rx, BOZLiteralConstant &&by) {
return NumericOperation<OPR, CAN_BE_UNSIGNED>(messages,
std::move(x), AsGenericExpr(ConvertTo(rx, std::move(by))),
defaultRealKind);
},
// Error cases
[&](Expr<SomeUnsigned> &&, auto &&) {
messages.Say("Both operands must be UNSIGNED"_err_en_US);
return NoExpr();
},
[&](auto &&, Expr<SomeUnsigned> &&) {
messages.Say("Both operands must be UNSIGNED"_err_en_US);
return NoExpr();
},
[&](auto &&, auto &&) {
messages.Say("non-numeric operands to numeric operation"_err_en_US);
return NoExpr();
},
},
std::move(x.u), std::move(y.u));
}
template std::optional<Expr<SomeType>> NumericOperation<Power, false>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
template std::optional<Expr<SomeType>> NumericOperation<Multiply>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
template std::optional<Expr<SomeType>> NumericOperation<Divide>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
template std::optional<Expr<SomeType>> NumericOperation<Add>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
template std::optional<Expr<SomeType>> NumericOperation<Subtract>(
parser::ContextualMessages &, Expr<SomeType> &&, Expr<SomeType> &&,
int defaultRealKind);
std::optional<Expr<SomeType>> Negation(
parser::ContextualMessages &messages, Expr<SomeType> &&x) {
return common::visit(
common::visitors{
[&](BOZLiteralConstant &&) {
messages.Say("BOZ literal cannot be negated"_err_en_US);
return NoExpr();
},
[&](NullPointer &&) {
messages.Say("NULL() cannot be negated"_err_en_US);
return NoExpr();
},
[&](ProcedureDesignator &&) {
messages.Say("Subroutine cannot be negated"_err_en_US);
return NoExpr();
},
[&](ProcedureRef &&) {
messages.Say("Pointer to subroutine cannot be negated"_err_en_US);
return NoExpr();
},
[&](Expr<SomeInteger> &&x) { return Package(-std::move(x)); },
[&](Expr<SomeReal> &&x) { return Package(-std::move(x)); },
[&](Expr<SomeComplex> &&x) { return Package(-std::move(x)); },
[&](Expr<SomeCharacter> &&) {
messages.Say("CHARACTER cannot be negated"_err_en_US);
return NoExpr();
},
[&](Expr<SomeLogical> &&) {
messages.Say("LOGICAL cannot be negated"_err_en_US);
return NoExpr();
},
[&](Expr<SomeUnsigned> &&x) { return Package(-std::move(x)); },
[&](Expr<SomeDerived> &&) {
messages.Say("Operand cannot be negated"_err_en_US);
return NoExpr();
},
},
std::move(x.u));
}
Expr<SomeLogical> LogicalNegation(Expr<SomeLogical> &&x) {
return common::visit(
[](auto &&xk) { return AsCategoryExpr(LogicalNegation(std::move(xk))); },
std::move(x.u));
}
template <TypeCategory CAT>
Expr<LogicalResult> PromoteAndRelate(
RelationalOperator opr, Expr<SomeKind<CAT>> &&x, Expr<SomeKind<CAT>> &&y) {
return common::visit(
[=](auto &&xy) {
return PackageRelation(opr, std::move(xy[0]), std::move(xy[1]));
},
AsSameKindExprs(std::move(x), std::move(y)));
}
std::optional<Expr<LogicalResult>> Relate(parser::ContextualMessages &messages,
RelationalOperator opr, Expr<SomeType> &&x, Expr<SomeType> &&y) {
return common::visit(
common::visitors{
[=](Expr<SomeInteger> &&ix,
Expr<SomeInteger> &&iy) -> std::optional<Expr<LogicalResult>> {
return PromoteAndRelate(opr, std::move(ix), std::move(iy));
},
[=](Expr<SomeUnsigned> &&ix,
Expr<SomeUnsigned> &&iy) -> std::optional<Expr<LogicalResult>> {
return PromoteAndRelate(opr, std::move(ix), std::move(iy));
},
[=](Expr<SomeReal> &&rx,
Expr<SomeReal> &&ry) -> std::optional<Expr<LogicalResult>> {
return PromoteAndRelate(opr, std::move(rx), std::move(ry));
},
[&](Expr<SomeReal> &&rx, Expr<SomeInteger> &&iy) {
return Relate(messages, opr, std::move(x),
AsGenericExpr(ConvertTo(rx, std::move(iy))));
},
[&](Expr<SomeInteger> &&ix, Expr<SomeReal> &&ry) {
return Relate(messages, opr,
AsGenericExpr(ConvertTo(ry, std::move(ix))), std::move(y));
},
[&](Expr<SomeComplex> &&zx,
Expr<SomeComplex> &&zy) -> std::optional<Expr<LogicalResult>> {
if (opr == RelationalOperator::EQ ||
opr == RelationalOperator::NE) {
return PromoteAndRelate(opr, std::move(zx), std::move(zy));
} else {
messages.Say(
"COMPLEX data may be compared only for equality"_err_en_US);
return std::nullopt;
}
},
[&](Expr<SomeComplex> &&zx, Expr<SomeInteger> &&iy) {
return Relate(messages, opr, std::move(x),
AsGenericExpr(ConvertTo(zx, std::move(iy))));
},
[&](Expr<SomeComplex> &&zx, Expr<SomeReal> &&ry) {
return Relate(messages, opr, std::move(x),
AsGenericExpr(ConvertTo(zx, std::move(ry))));
},
[&](Expr<SomeInteger> &&ix, Expr<SomeComplex> &&zy) {
return Relate(messages, opr,
AsGenericExpr(ConvertTo(zy, std::move(ix))), std::move(y));
},
[&](Expr<SomeReal> &&rx, Expr<SomeComplex> &&zy) {
return Relate(messages, opr,
AsGenericExpr(ConvertTo(zy, std::move(rx))), std::move(y));
},
[&](Expr<SomeCharacter> &&cx, Expr<SomeCharacter> &&cy) {
return common::visit(
[&](auto &&cxk,
auto &&cyk) -> std::optional<Expr<LogicalResult>> {
using Ty = ResultType<decltype(cxk)>;
if constexpr (std::is_same_v<Ty, ResultType<decltype(cyk)>>) {
return PackageRelation(opr, std::move(cxk), std::move(cyk));
} else {
messages.Say(
"CHARACTER operands do not have same KIND"_err_en_US);
return std::nullopt;
}
},
std::move(cx.u), std::move(cy.u));
},
// Default case
[&](auto &&, auto &&) {
DIE("invalid types for relational operator");
return std::optional<Expr<LogicalResult>>{};
},
},
std::move(x.u), std::move(y.u));
}
Expr<SomeLogical> BinaryLogicalOperation(
LogicalOperator opr, Expr<SomeLogical> &&x, Expr<SomeLogical> &&y) {
CHECK(opr != LogicalOperator::Not);
return common::visit(
[=](auto &&xy) {
using Ty = ResultType<decltype(xy[0])>;
return Expr<SomeLogical>{BinaryLogicalOperation<Ty::kind>(
opr, std::move(xy[0]), std::move(xy[1]))};
},
AsSameKindExprs(std::move(x), std::move(y)));
}
template <TypeCategory TO>
std::optional<Expr<SomeType>> ConvertToNumeric(int kind, Expr<SomeType> &&x) {
static_assert(common::IsNumericTypeCategory(TO));
return common::visit(
[=](auto &&cx) -> std::optional<Expr<SomeType>> {
using cxType = std::decay_t<decltype(cx)>;
if constexpr (!common::HasMember<cxType, TypelessExpression>) {
if constexpr (IsNumericTypeCategory(ResultType<cxType>::category)) {
return Expr<SomeType>{ConvertToKind<TO>(kind, std::move(cx))};
}
}
return std::nullopt;
},
std::move(x.u));
}
std::optional<Expr<SomeType>> ConvertToType(
const DynamicType &type, Expr<SomeType> &&x) {
if (type.IsTypelessIntrinsicArgument()) {
return std::nullopt;
}
switch (type.category()) {
case TypeCategory::Integer:
if (auto *boz{std::get_if<BOZLiteralConstant>(&x.u)}) {
// Extension to C7109: allow BOZ literals to appear in integer contexts
// when the type is unambiguous.
return Expr<SomeType>{
ConvertToKind<TypeCategory::Integer>(type.kind(), std::move(*boz))};
}
return ConvertToNumeric<TypeCategory::Integer>(type.kind(), std::move(x));
case TypeCategory::Unsigned:
if (auto *boz{std::get_if<BOZLiteralConstant>(&x.u)}) {
return Expr<SomeType>{
ConvertToKind<TypeCategory::Unsigned>(type.kind(), std::move(*boz))};
}
if (auto *cx{UnwrapExpr<Expr<SomeUnsigned>>(x)}) {
return Expr<SomeType>{
ConvertToKind<TypeCategory::Unsigned>(type.kind(), std::move(*cx))};
}
break;
case TypeCategory::Real:
if (auto *boz{std::get_if<BOZLiteralConstant>(&x.u)}) {
return Expr<SomeType>{
ConvertToKind<TypeCategory::Real>(type.kind(), std::move(*boz))};
}
return ConvertToNumeric<TypeCategory::Real>(type.kind(), std::move(x));
case TypeCategory::Complex:
return ConvertToNumeric<TypeCategory::Complex>(type.kind(), std::move(x));
case TypeCategory::Character:
if (auto *cx{UnwrapExpr<Expr<SomeCharacter>>(x)}) {
auto converted{
ConvertToKind<TypeCategory::Character>(type.kind(), std::move(*cx))};
if (auto length{type.GetCharLength()}) {
converted = common::visit(
[&](auto &&x) {
using CharacterType = ResultType<decltype(x)>;
return Expr<SomeCharacter>{
Expr<CharacterType>{SetLength<CharacterType::kind>{
std::move(x), std::move(*length)}}};
},
std::move(converted.u));
}
return Expr<SomeType>{std::move(converted)};
}
break;
case TypeCategory::Logical:
if (auto *cx{UnwrapExpr<Expr<SomeLogical>>(x)}) {
return Expr<SomeType>{
ConvertToKind<TypeCategory::Logical>(type.kind(), std::move(*cx))};
}
break;
case TypeCategory::Derived:
if (auto fromType{x.GetType()}) {
if (type.IsTkCompatibleWith(*fromType)) {
// "x" could be assigned or passed to "type", or appear in a
// structure constructor as a value for a component with "type"
return std::move(x);
}
}
break;
}
return std::nullopt;
}
std::optional<Expr<SomeType>> ConvertToType(
const DynamicType &to, std::optional<Expr<SomeType>> &&x) {
if (x) {
return ConvertToType(to, std::move(*x));
} else {
return std::nullopt;
}
}
std::optional<Expr<SomeType>> ConvertToType(
const Symbol &symbol, Expr<SomeType> &&x) {
if (auto symType{DynamicType::From(symbol)}) {
return ConvertToType(*symType, std::move(x));
}
return std::nullopt;
}
std::optional<Expr<SomeType>> ConvertToType(
const Symbol &to, std::optional<Expr<SomeType>> &&x) {
if (x) {
return ConvertToType(to, std::move(*x));
} else {
return std::nullopt;
}
}
bool IsAssumedRank(const Symbol &original) {
if (const auto *assoc{original.detailsIf<semantics::AssocEntityDetails>()}) {
if (assoc->rank()) {
return false; // in RANK(n) or RANK(*)
} else if (assoc->IsAssumedRank()) {
return true; // RANK DEFAULT
}
}
const Symbol &symbol{semantics::ResolveAssociations(original)};
const auto *object{symbol.detailsIf<semantics::ObjectEntityDetails>()};
return object && object->IsAssumedRank();
}
bool IsAssumedRank(const ActualArgument &arg) {
if (const auto *expr{arg.UnwrapExpr()}) {
return IsAssumedRank(*expr);
} else {
const Symbol *assumedTypeDummy{arg.GetAssumedTypeDummy()};
CHECK(assumedTypeDummy);
return IsAssumedRank(*assumedTypeDummy);
}
}
int GetCorank(const ActualArgument &arg) {
const auto *expr{arg.UnwrapExpr()};
return GetCorank(*expr);
}
bool IsProcedureDesignator(const Expr<SomeType> &expr) {
return std::holds_alternative<ProcedureDesignator>(expr.u);
}
bool IsFunctionDesignator(const Expr<SomeType> &expr) {
const auto *designator{std::get_if<ProcedureDesignator>(&expr.u)};
return designator && designator->GetType().has_value();
}
bool IsPointer(const Expr<SomeType> &expr) {
return IsObjectPointer(expr) || IsProcedurePointer(expr);
}
bool IsProcedurePointer(const Expr<SomeType> &expr) {
if (IsNullProcedurePointer(&expr)) {
return true;
} else if (const auto *funcRef{UnwrapProcedureRef(expr)}) {
if (const Symbol * proc{funcRef->proc().GetSymbol()}) {
const Symbol *result{FindFunctionResult(*proc)};
return result && IsProcedurePointer(*result);
} else {
return false;
}
} else if (const auto *proc{std::get_if<ProcedureDesignator>(&expr.u)}) {
return IsProcedurePointer(proc->GetSymbol());
} else {
return false;
}
}
bool IsProcedure(const Expr<SomeType> &expr) {
return IsProcedureDesignator(expr) || IsProcedurePointer(expr);
}
bool IsProcedurePointerTarget(const Expr<SomeType> &expr) {
return common::visit(common::visitors{
[](const NullPointer &) { return true; },
[](const ProcedureDesignator &) { return true; },
[](const ProcedureRef &) { return true; },
[&](const auto &) {
const Symbol *last{GetLastSymbol(expr)};
return last && IsProcedurePointer(*last);
},
},
expr.u);
}
bool IsObjectPointer(const Expr<SomeType> &expr) {
if (IsNullObjectPointer(&expr)) {
return true;
} else if (IsProcedurePointerTarget(expr)) {
return false;
} else if (const auto *funcRef{UnwrapProcedureRef(expr)}) {
return IsVariable(*funcRef);
} else if (const Symbol * symbol{UnwrapWholeSymbolOrComponentDataRef(expr)}) {
return IsPointer(symbol->GetUltimate());
} else {
return false;
}
}
// IsNullPointer() & variations
template <bool IS_PROC_PTR> struct IsNullPointerHelper {
template <typename A> bool operator()(const A &) const { return false; }
bool operator()(const ProcedureRef &call) const {
if constexpr (IS_PROC_PTR) {
const auto *intrinsic{call.proc().GetSpecificIntrinsic()};
return intrinsic &&
intrinsic->characteristics.value().attrs.test(
characteristics::Procedure::Attr::NullPointer);
} else {
return false;
}
}
template <typename T> bool operator()(const FunctionRef<T> &call) const {
if constexpr (IS_PROC_PTR) {
return false;
} else {
const auto *intrinsic{call.proc().GetSpecificIntrinsic()};
return intrinsic &&
intrinsic->characteristics.value().attrs.test(