-
-
Notifications
You must be signed in to change notification settings - Fork 267
/
Copy pathtoir.cpp
2937 lines (2461 loc) · 98.5 KB
/
toir.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
//===-- toir.cpp ----------------------------------------------------------===//
//
// LDC – the LLVM D compiler
//
// This file is distributed under the BSD-style LDC license. See the LICENSE
// file for details.
//
//===----------------------------------------------------------------------===//
#include "dmd/attrib.h"
#include "dmd/ctfe.h"
#include "dmd/enum.h"
#include "dmd/errors.h"
#include "dmd/hdrgen.h"
#include "dmd/id.h"
#include "dmd/identifier.h"
#include "dmd/init.h"
#include "dmd/ldcbindings.h"
#include "dmd/module.h"
#include "dmd/mtype.h"
#include "dmd/root/port.h"
#include "dmd/root/rmem.h"
#include "dmd/template.h"
#include "gen/aa.h"
#include "gen/abi.h"
#include "gen/arrays.h"
#include "gen/binops.h"
#include "gen/classes.h"
#include "gen/complex.h"
#include "gen/coverage.h"
#include "gen/dvalue.h"
#include "gen/functions.h"
#include "gen/funcgenstate.h"
#include "gen/inlineir.h"
#include "gen/irstate.h"
#include "gen/llvm.h"
#include "gen/llvmhelpers.h"
#include "gen/logger.h"
#include "gen/mangling.h"
#include "gen/nested.h"
#include "gen/optimizer.h"
#include "gen/pragma.h"
#include "gen/runtime.h"
#include "gen/scope_exit.h"
#include "gen/structs.h"
#include "gen/tollvm.h"
#include "gen/typinf.h"
#include "gen/warnings.h"
#include "ir/irfunction.h"
#include "ir/irtypeclass.h"
#include "ir/irtypestruct.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include <fstream>
#include <math.h>
#include <stack>
#include <stdio.h>
llvm::cl::opt<bool> checkPrintf(
"check-printf-calls", llvm::cl::ZeroOrMore,
llvm::cl::desc("Validate printf call format strings against arguments"));
bool walkPostorder(Expression *e, StoppableVisitor *v);
////////////////////////////////////////////////////////////////////////////////
static LLValue *write_zeroes(LLValue *mem, unsigned start, unsigned end) {
mem = DtoBitCast(mem, getVoidPtrType());
LLValue *gep = DtoGEP1(mem, start, ".padding");
DtoMemSetZero(gep, DtoConstSize_t(end - start));
return mem;
}
////////////////////////////////////////////////////////////////////////////////
static void write_struct_literal(Loc loc, LLValue *mem, StructDeclaration *sd,
Expressions *elements) {
assert(elements && "struct literal has null elements");
const auto numMissingElements = sd->fields.length - elements->length;
(void)numMissingElements;
assert(numMissingElements == 0 || (sd->vthis && numMissingElements == 1));
// might be reset to an actual i8* value so only a single bitcast is emitted
LLValue *voidptr = mem;
struct Data {
VarDeclaration *field;
Expression *expr;
};
LLSmallVector<Data, 16> data;
// collect init expressions in fields declaration order
for (size_t index = 0; index < sd->fields.length; ++index) {
VarDeclaration *field = sd->fields[index];
// Skip zero-sized fields such as zero-length static arrays: `ubyte[0]
// data`.
if (field->type->size() == 0)
continue;
// the initializer expression may be null for overridden overlapping fields
Expression *expr =
(index < elements->length ? (*elements)[index] : nullptr);
if (expr || field == sd->vthis) {
// DMD issue #16471:
// There may be overlapping initializer expressions in some cases.
// Prefer the last expression in lexical (declaration) order to mimic DMD.
if (field->overlapped) {
const unsigned f_begin = field->offset;
const unsigned f_end = f_begin + field->type->size();
const auto newEndIt =
std::remove_if(data.begin(), data.end(), [=](const Data &d) {
unsigned v_begin = d.field->offset;
unsigned v_end = v_begin + d.field->type->size();
return v_begin < f_end && v_end > f_begin;
});
data.erase(newEndIt, data.end());
}
data.push_back({field, expr});
}
}
// sort by offset
std::sort(data.begin(), data.end(), [](const Data &l, const Data &r) {
return l.field->offset < r.field->offset;
});
unsigned offset = 0;
for (const auto &d : data) {
const auto vd = d.field;
const auto expr = d.expr;
// initialize any padding so struct comparisons work
if (vd->offset != offset) {
assert(vd->offset > offset);
voidptr = write_zeroes(voidptr, offset, vd->offset);
offset = vd->offset;
}
IF_LOG Logger::println("initializing field: %s %s (+%u)",
vd->type->toChars(), vd->toChars(), vd->offset);
LOG_SCOPE
// get a pointer to this field
assert(!isSpecialRefVar(vd) && "Code not expected to handle special ref "
"vars, although it can easily be made to.");
DLValue field(vd->type, DtoIndexAggregate(mem, sd, vd));
// initialize the field
if (expr) {
IF_LOG Logger::println("expr = %s", expr->toChars());
// try to construct it in-place
if (!toInPlaceConstruction(&field, expr)) {
DtoAssign(loc, &field, toElem(expr), TOKblit);
if (expr->isLvalue())
callPostblit(loc, expr, DtoLVal(&field));
}
} else {
assert(vd == sd->vthis);
IF_LOG Logger::println("initializing vthis");
LOG_SCOPE
DImValue val(vd->type,
DtoBitCast(DtoNestedContext(loc, sd), DtoType(vd->type)));
DtoAssign(loc, &field, &val, TOKblit);
}
offset += vd->type->size();
// Also zero out padding bytes counted as being part of the type in DMD
// but not in LLVM; e.g. real/x86_fp80.
int implicitPadding =
vd->type->size() - gDataLayout->getTypeStoreSize(DtoType(vd->type));
assert(implicitPadding >= 0);
if (implicitPadding > 0) {
IF_LOG Logger::println("zeroing %d padding bytes", implicitPadding);
voidptr = write_zeroes(voidptr, offset - implicitPadding, offset);
}
}
// initialize trailing padding
if (sd->structsize != offset)
voidptr = write_zeroes(voidptr, offset, sd->structsize);
}
namespace {
void pushVarDtorCleanup(IRState *p, VarDeclaration *vd) {
llvm::BasicBlock *beginBB = p->insertBB(llvm::Twine("dtor.") + vd->toChars());
// TODO: Clean this up with push/pop insertion point methods.
IRScope oldScope = p->scope();
p->scope() = IRScope(beginBB);
toElemDtor(vd->edtor);
p->funcGen().scopes.pushCleanup(beginBB, p->scopebb());
p->scope() = oldScope;
}
}
////////////////////////////////////////////////////////////////////////////////
static Expression *skipOverCasts(Expression *e) {
while (auto ce = e->isCastExp())
e = ce->e1;
return e;
}
DValue *toElem(Expression *e, bool doSkipOverCasts) {
Expression *inner = skipOverCasts(e);
if (!doSkipOverCasts || inner == e)
return toElem(e);
return DtoCast(e->loc, toElem(inner), e->type);
}
////////////////////////////////////////////////////////////////////////////////
class ToElemVisitor : public Visitor {
IRState *p;
bool destructTemporaries;
CleanupCursor initialCleanupScope;
DValue *result;
public:
ToElemVisitor(IRState *p_, bool destructTemporaries_)
: p(p_), destructTemporaries(destructTemporaries_), result(nullptr) {
initialCleanupScope = p->funcGen().scopes.currentCleanupScope();
}
DValue *getResult() {
if (destructTemporaries &&
p->funcGen().scopes.currentCleanupScope() != initialCleanupScope) {
// We might share the CFG edges through the below cleanup blocks with
// other paths (e.g. exception unwinding) where the result value has not
// been constructed. At runtime, the branches will be chosen such that the
// end bb (which will likely go on to access the value) is never executed
// in those other cases, but we need to make sure that the SSA is also
// well-formed statically (i.e. all instructions dominate their uses).
// Thus, dump the result to a temporary stack slot (created in the entry
// bb) if it is not guaranteed to dominate the end bb after possibly
// adding more control flow.
if (result && result->type->ty != Tvoid &&
!result->definedInFuncEntryBB()) {
if (result->isRVal()) {
LLValue *lval = DtoAllocaDump(result, ".toElemRValResult");
result = new DLValue(result->type, lval);
} else {
LLValue *lval = DtoLVal(result);
LLValue *lvalPtr = DtoAllocaDump(lval, 0, ".toElemLValResult");
result = new DSpecialRefValue(result->type, lvalPtr);
}
}
llvm::BasicBlock *endbb = p->insertBB("toElem.success");
p->funcGen().scopes.runCleanups(initialCleanupScope, endbb);
p->funcGen().scopes.popCleanups(initialCleanupScope);
p->scope() = IRScope(endbb);
destructTemporaries = false;
}
return result;
}
//////////////////////////////////////////////////////////////////////////////
// Import all functions from class Visitor
using Visitor::visit;
//////////////////////////////////////////////////////////////////////////////
void visit(DeclarationExp *e) override {
IF_LOG Logger::print("DeclarationExp::toElem: %s | T=%s\n", e->toChars(),
e->type ? e->type->toChars() : "(null)");
LOG_SCOPE;
auto &PGO = gIR->funcGen().pgo;
PGO.setCurrentStmt(e);
result = DtoDeclarationExp(e->declaration);
if (auto vd = e->declaration->isVarDeclaration()) {
if (!vd->isDataseg() && vd->needsScopeDtor()) {
pushVarDtorCleanup(p, vd);
}
}
}
//////////////////////////////////////////////////////////////////////////////
void visit(VarExp *e) override {
IF_LOG Logger::print("VarExp::toElem: %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
assert(e->var);
if (auto fd = e->var->isFuncLiteralDeclaration()) {
genFuncLiteral(fd, nullptr);
}
if (auto em = e->var->isEnumMember()) {
IF_LOG Logger::println("Create temporary for enum member");
// Return the value of the enum member instead of trying to take its
// address (impossible because we don't emit them as variables)
// In most cases, the front-end constfolds a VarExp of an EnumMember,
// leaving the AST free of EnumMembers. However in rare cases,
// EnumMembers remain and thus we have to deal with them here.
// See DMD issues 16022 and 16100.
result = toElem(em->value(), p);
return;
}
result = DtoSymbolAddress(e->loc, e->type, e->var);
}
//////////////////////////////////////////////////////////////////////////////
void visit(IntegerExp *e) override {
IF_LOG Logger::print("IntegerExp::toElem: %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
LLConstant *c = toConstElem(e, p);
result = new DConstValue(e->type, c);
}
//////////////////////////////////////////////////////////////////////////////
void visit(RealExp *e) override {
IF_LOG Logger::print("RealExp::toElem: %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
LLConstant *c = toConstElem(e, p);
result = new DConstValue(e->type, c);
}
//////////////////////////////////////////////////////////////////////////////
void visit(NullExp *e) override {
IF_LOG Logger::print("NullExp::toElem(type=%s): %s\n", e->type->toChars(),
e->toChars());
LOG_SCOPE;
LLConstant *c = toConstElem(e, p);
result = new DNullValue(e->type, c);
}
//////////////////////////////////////////////////////////////////////////////
void visit(ComplexExp *e) override {
IF_LOG Logger::print("ComplexExp::toElem(): %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
LLConstant *c = toConstElem(e, p);
LLValue *res;
if (c->isNullValue()) {
switch (e->type->toBasetype()->ty) {
default:
llvm_unreachable("Unexpected complex floating point type");
case Tcomplex32:
c = DtoConstFP(Type::tfloat32, ldouble(0));
break;
case Tcomplex64:
c = DtoConstFP(Type::tfloat64, ldouble(0));
break;
case Tcomplex80:
c = DtoConstFP(Type::tfloat80, ldouble(0));
break;
}
res = DtoAggrPair(DtoType(e->type), c, c);
} else {
res = DtoAggrPair(DtoType(e->type), c->getOperand(0), c->getOperand(1));
}
result = new DImValue(e->type, res);
}
//////////////////////////////////////////////////////////////////////////////
void visit(StringExp *e) override {
IF_LOG Logger::print("StringExp::toElem: %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
Type *dtype = e->type->toBasetype();
Type *cty = dtype->nextOf()->toBasetype();
LLType *ct = DtoMemType(cty);
llvm::StringMap<llvm::GlobalVariable *> *stringLiteralCache =
stringLiteralCacheForType(cty);
LLConstant *_init = buildStringLiteralConstant(e, true);
const auto at = _init->getType();
llvm::StringRef key(e->toChars());
llvm::GlobalVariable *gvar =
(stringLiteralCache->find(key) == stringLiteralCache->end())
? nullptr
: (*stringLiteralCache)[key];
if (gvar == nullptr) {
llvm::GlobalValue::LinkageTypes _linkage =
llvm::GlobalValue::PrivateLinkage;
IF_LOG {
Logger::cout() << "type: " << *at << '\n';
Logger::cout() << "init: " << *_init << '\n';
}
gvar = new llvm::GlobalVariable(gIR->module, at, true, _linkage, _init,
".str");
gvar->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
(*stringLiteralCache)[key] = gvar;
}
llvm::ConstantInt *zero =
LLConstantInt::get(LLType::getInt32Ty(gIR->context()), 0, false);
LLConstant *idxs[2] = {zero, zero};
LLConstant *arrptr = llvm::ConstantExpr::getGetElementPtr(
isaPointer(gvar)->getElementType(), gvar, idxs, true);
if (dtype->ty == Tarray) {
LLConstant *clen =
LLConstantInt::get(DtoSize_t(), e->numberOfCodeUnits(), false);
result = new DSliceValue(e->type, DtoConstSlice(clen, arrptr, dtype));
} else if (dtype->ty == Tsarray) {
LLType *dstType =
getPtrToType(LLArrayType::get(ct, e->numberOfCodeUnits()));
LLValue *emem =
(gvar->getType() == dstType) ? gvar : DtoBitCast(gvar, dstType);
result = new DLValue(e->type, emem);
} else if (dtype->ty == Tpointer) {
result = new DImValue(e->type, arrptr);
} else {
llvm_unreachable("Unknown type for StringExp.");
}
}
//////////////////////////////////////////////////////////////////////////////
void visit(AssignExp *e) override {
IF_LOG Logger::print("AssignExp::toElem: %s | (%s)(%s = %s)\n",
e->toChars(), e->type->toChars(),
e->e1->type->toChars(),
e->e2->type ? e->e2->type->toChars() : nullptr);
LOG_SCOPE;
if (auto ale = e->e1->isArrayLengthExp()) {
Logger::println("performing array.length assignment");
DLValue arrval(ale->e1->type, DtoLVal(ale->e1));
DValue *newlen = toElem(e->e2);
DSliceValue *slice =
DtoResizeDynArray(e->loc, arrval.type, &arrval, DtoRVal(newlen));
DtoStore(DtoRVal(slice), DtoLVal(&arrval));
result = newlen;
return;
}
// Initialization of ref variable?
// Can't just override ConstructExp::toElem because not all TOKconstruct
// operations are actually instances of ConstructExp... Long live the DMD
// coding style!
if (e->memset & referenceInit) {
assert(e->op == TOKconstruct || e->op == TOKblit);
auto ve = e->e1->isVarExp();
assert(ve);
if (ve->var->storage_class & (STCref | STCout)) {
Logger::println("performing ref variable initialization");
// Note that the variable value is accessed directly (instead
// of via getLVal(), which would perform a load from the
// uninitialized location), and that rhs is stored as an l-value!
DSpecialRefValue *lhs = toElem(e->e1)->isSpecialRef();
assert(lhs);
DValue *rhs = toElem(e->e2);
// We shouldn't really need makeLValue() here, but the 2.063
// frontend generates ref variables initialized from function
// calls.
DtoStore(makeLValue(e->loc, rhs), lhs->getRefStorage());
result = lhs;
return;
}
}
// The front-end sometimes rewrites a static-array-lhs to a slice, e.g.,
// when initializing a static array with an array literal.
// Use the static array as lhs in that case.
DValue *rewrittenLhsStaticArray = nullptr;
if (auto se = e->e1->isSliceExp()) {
Type *sliceeBaseType = se->e1->type->toBasetype();
if (se->lwr == nullptr && sliceeBaseType->ty == Tsarray &&
se->type->toBasetype()->nextOf() == sliceeBaseType->nextOf())
rewrittenLhsStaticArray = toElem(se->e1, true);
}
DValue *const lhs = (rewrittenLhsStaticArray ? rewrittenLhsStaticArray
: toElem(e->e1, true));
// Set the result of the AssignExp to the lhs.
// Defer this to the end of this function, so that static arrays are
// rewritten (converted to a slice) after the assignment, primarily for a
// more intuitive IR order.
SCOPE_EXIT {
if (rewrittenLhsStaticArray) {
result =
new DSliceValue(e->e1->type, DtoArrayLen(rewrittenLhsStaticArray),
DtoArrayPtr(rewrittenLhsStaticArray));
} else {
result = lhs;
}
};
// Try to construct the lhs in-place.
if (lhs->isLVal() && (e->op == TOKconstruct || e->op == TOKblit)) {
if (toInPlaceConstruction(lhs->isLVal(), e->e2))
return;
}
// Try to assign to the lhs in-place.
// This extra complication at -O0 is to prevent excessive stack space usage
// when assigning to large structs.
// Note: If the assignment is non-trivial, a CallExp to opAssign is
// generated by the frontend instead of this AssignExp. The in-place
// construction is not valid if the rhs is not a literal (consider for
// example `a = foo(a)`), but also not if the rhs contains non-constant
// elements (consider for example `a = [0, a[0], 2]` or `a = [0, i, 2]`
// where `i` is a ref variable aliasing with a).
// Be conservative with this optimization for now: only do the optimization
// for struct `.init` assignment.
if (lhs->isLVal() && e->op == TOKassign) {
if (auto sle = e->e2->isStructLiteralExp()) {
if (sle->useStaticInit) {
if (toInPlaceConstruction(lhs->isLVal(), sle))
return;
}
}
}
DValue *r = toElem(e->e2);
if (e->e1->type->toBasetype()->ty == Tstruct && e->e2->op == TOKint64) {
Logger::println("performing aggregate zero initialization");
assert(e->e2->toInteger() == 0);
LLValue *lval = DtoLVal(lhs);
DtoMemSetZero(lval);
TypeStruct *ts = static_cast<TypeStruct *>(e->e1->type);
if (ts->sym->isNested() && ts->sym->vthis)
DtoResolveNestedContext(e->loc, ts->sym, lval);
return;
}
// This matches the logic in AssignExp::semantic.
// TODO: Should be cached in the frontend to avoid issues with the code
// getting out of sync?
bool lvalueElem = false;
if ((e->e2->op == TOKslice &&
static_cast<UnaExp *>(e->e2)->e1->isLvalue()) ||
(e->e2->op == TOKcast &&
static_cast<UnaExp *>(e->e2)->e1->isLvalue()) ||
(e->e2->op != TOKslice && e->e2->isLvalue())) {
lvalueElem = true;
}
Logger::println("performing normal assignment (rhs has lvalue elems = %d)",
lvalueElem);
DtoAssign(e->loc, lhs, r, e->op, !lvalueElem);
}
//////////////////////////////////////////////////////////////////////////////
void errorOnIllegalArrayOp(Expression *base, Expression *e1, Expression *e2) {
Type *t1 = e1->type->toBasetype();
Type *t2 = e2->type->toBasetype();
// valid array ops would have been transformed by optimize
if ((t1->ty == Tarray || t1->ty == Tsarray) &&
(t2->ty == Tarray || t2->ty == Tsarray)) {
base->error("Array operation `%s` not recognized", base->toChars());
fatal();
}
}
//////////////////////////////////////////////////////////////////////////////
#define BIN_OP(Op, Func) \
void visit(Op##Exp *e) override { \
IF_LOG Logger::print(#Op "Exp::toElem: %s @ %s\n", e->toChars(), \
e->type->toChars()); \
LOG_SCOPE; \
\
errorOnIllegalArrayOp(e, e->e1, e->e2); \
\
auto &PGO = gIR->funcGen().pgo; \
PGO.setCurrentStmt(e); \
\
result = Func(e->loc, e->type, toElem(e->e1), e->e2); \
}
BIN_OP(Add, binAdd)
BIN_OP(Min, binMin)
BIN_OP(Mul, binMul)
BIN_OP(Div, binDiv)
BIN_OP(Mod, binMod)
BIN_OP(And, binAnd)
BIN_OP(Or, binOr)
BIN_OP(Xor, binXor)
BIN_OP(Shl, binShl)
BIN_OP(Shr, binShr)
BIN_OP(Ushr, binUshr)
#undef BIN_OP
//////////////////////////////////////////////////////////////////////////////
using BinOpFunc = DValue *(Loc &, Type *, DValue *, Expression *, bool);
static Expression *getLValExp(Expression *e) {
e = skipOverCasts(e);
if (auto ce = e->isCommaExp()) {
Expression *newCommaRhs = getLValExp(ce->e2);
if (newCommaRhs != ce->e2) {
CommaExp *newComma = static_cast<CommaExp *>(ce->copy());
newComma->e2 = newCommaRhs;
newComma->type = newCommaRhs->type;
e = newComma;
}
}
return e;
}
template <BinOpFunc binOpFunc, bool useLValTypeForBinOp>
static DValue *binAssign(BinAssignExp *e) {
Expression *lvalExp = getLValExp(e->e1);
DValue *lhsLVal = toElem(lvalExp);
// Use the lhs lvalue for the binop lhs and optionally cast it to the full
// lhs type (!useLValTypeForBinOp).
// The front-end apparently likes to specify the binop type via lhs casts,
// e.g., `byte x; cast(int)x += 5;`.
// Load the binop lhs AFTER evaluating the rhs.
Type *opType = (useLValTypeForBinOp ? lhsLVal->type : e->e1->type);
DValue *opResult = binOpFunc(e->loc, opType, lhsLVal, e->e2, true);
DValue *assignedResult = DtoCast(e->loc, opResult, lhsLVal->type);
DtoAssign(e->loc, lhsLVal, assignedResult, TOKassign);
if (e->type->equals(lhsLVal->type))
return lhsLVal;
return new DLValue(e->type, DtoLVal(lhsLVal));
}
#define BIN_ASSIGN(Op, Func, useLValTypeForBinOp) \
void visit(Op##AssignExp *e) override { \
IF_LOG Logger::print(#Op "AssignExp::toElem: %s @ %s\n", e->toChars(), \
e->type->toChars()); \
LOG_SCOPE; \
\
errorOnIllegalArrayOp(e, e->e1, e->e2); \
\
auto &PGO = gIR->funcGen().pgo; \
PGO.setCurrentStmt(e); \
\
result = binAssign<Func, useLValTypeForBinOp>(e); \
}
BIN_ASSIGN(Add, binAdd, false)
BIN_ASSIGN(Min, binMin, false)
BIN_ASSIGN(Mul, binMul, false)
BIN_ASSIGN(Div, binDiv, false)
BIN_ASSIGN(Mod, binMod, false)
BIN_ASSIGN(And, binAnd, false)
BIN_ASSIGN(Or, binOr, false)
BIN_ASSIGN(Xor, binXor, false)
BIN_ASSIGN(Shl, binShl, true)
BIN_ASSIGN(Shr, binShr, true)
BIN_ASSIGN(Ushr, binUshr, true)
#undef BIN_ASSIGN
//////////////////////////////////////////////////////////////////////////////
static DValue *call(IRState *p, CallExp *e, LLValue *sretPointer = nullptr) {
IF_LOG Logger::print("CallExp::toElem: %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
auto &PGO = gIR->funcGen().pgo;
PGO.setCurrentStmt(e);
// handle magic inline asm
if (auto ve = e->e1->isVarExp()) {
if (auto fd = ve->var->isFuncDeclaration()) {
if (fd->llvmInternal == LLVMinline_asm) {
return DtoInlineAsmExpr(e->loc, fd, e->arguments, sretPointer);
}
if (fd->llvmInternal == LLVMinline_ir) {
return DtoInlineIRExpr(e->loc, fd, e->arguments, sretPointer);
}
}
}
// Check if we are about to construct a just declared temporary. DMD
// unfortunately rewrites this as
// MyStruct(myArgs) => (MyStruct tmp; tmp).this(myArgs),
// which would lead us to invoke the dtor even if the ctor throws. To
// work around this, we hold on to the cleanup and push it only after
// making the function call.
//
// The correct fix for this (DMD issue 13095) would have been to adapt
// the AST, but we are stuck with this as DMD also patched over it with
// a similar hack.
VarDeclaration *delayedDtorVar = nullptr;
Expression *delayedDtorExp = nullptr;
if (e->f && e->f->isCtorDeclaration()) {
if (auto dve = e->e1->isDotVarExp())
if (auto ce = dve->e1->isCommaExp())
if (ce->e1->op == TOKdeclaration)
if (auto ve = ce->e2->isVarExp())
if (auto vd = ve->var->isVarDeclaration())
if (vd->needsScopeDtor()) {
Logger::println("Delaying edtor");
delayedDtorVar = vd;
delayedDtorExp = vd->edtor;
vd->edtor = nullptr;
}
}
// get the callee value
DValue *fnval;
if (e->directcall) {
// TODO: Do this as an extra parameter to DotVarExp implementation.
auto dve = e->e1->isDotVarExp();
assert(dve);
FuncDeclaration *fdecl = dve->var->isFuncDeclaration();
assert(fdecl);
DtoDeclareFunction(fdecl);
Expression *thisExp = dve->e1;
LLValue *thisArg = thisExp->type->toBasetype()->ty == Tclass
? DtoRVal(thisExp)
: DtoLVal(thisExp); // when calling a struct method
fnval = new DFuncValue(fdecl, DtoCallee(fdecl), thisArg);
} else {
fnval = toElem(e->e1);
}
// get func value if any
DFuncValue *dfnval = fnval->isFunc();
// handle magic intrinsics (mapping to instructions)
if (dfnval && dfnval->func) {
FuncDeclaration *fndecl = dfnval->func;
// as requested by bearophile, see if it's a C printf call and that it's
// valid.
if (global.params.warnings != DIAGNOSTICoff && checkPrintf) {
if (fndecl->linkage == LINKc &&
strcmp(fndecl->ident->toChars(), "printf") == 0) {
warnInvalidPrintfCall(e->loc, (*e->arguments)[0],
e->arguments->length);
}
}
DValue *result = nullptr;
if (DtoLowerMagicIntrinsic(p, fndecl, e, result))
return result;
}
DValue *result =
DtoCallFunction(e->loc, e->type, fnval, e->arguments, sretPointer);
if (delayedDtorVar) {
delayedDtorVar->edtor = delayedDtorExp;
pushVarDtorCleanup(p, delayedDtorVar);
}
return result;
}
void visit(CallExp *e) override { result = call(p, e); }
//////////////////////////////////////////////////////////////////////////////
void visit(CastExp *e) override {
IF_LOG Logger::print("CastExp::toElem: %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
auto &PGO = gIR->funcGen().pgo;
PGO.setCurrentStmt(e);
// get the value to cast
DValue *u = toElem(e->e1);
// handle cast to void (usually created by frontend to avoid "has no effect"
// error)
if (e->to == Type::tvoid) {
result = nullptr;
return;
}
// cast it to the 'to' type, if necessary
result = u;
if (!e->to->equals(e->e1->type)) {
result = DtoCast(e->loc, u, e->to);
}
// paint the type, if necessary
if (!e->type->equals(e->to)) {
result = DtoPaintType(e->loc, result, e->type);
}
}
//////////////////////////////////////////////////////////////////////////////
void visit(SymOffExp *e) override {
IF_LOG Logger::print("SymOffExp::toElem: %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
auto &PGO = gIR->funcGen().pgo;
PGO.setCurrentStmt(e);
DValue *base = DtoSymbolAddress(e->loc, e->var->type, e->var);
// This weird setup is required to be able to handle both variables as
// well as functions and TypeInfo references (which are not a DLValue
// as well due to the level-of-indirection hack in Type::getTypeInfo that
// is unfortunately required by the frontend).
llvm::Value *baseValue;
if (base->isLVal()) {
baseValue = DtoLVal(base);
} else {
baseValue = DtoRVal(base);
}
assert(isaPointer(baseValue));
llvm::Value *offsetValue = nullptr;
if (e->offset == 0) {
offsetValue = baseValue;
} else {
LLType *elemType = baseValue->getType()->getContainedType(0);
if (elemType->isSized()) {
uint64_t elemSize = gDataLayout->getTypeAllocSize(elemType);
if (e->offset % elemSize == 0) {
// We can turn this into a "nice" GEP.
offsetValue = DtoGEP1(baseValue, e->offset / elemSize);
}
}
if (!offsetValue) {
// Offset isn't a multiple of base type size, just cast to i8* and
// apply the byte offset.
offsetValue =
DtoGEP1(DtoBitCast(baseValue, getVoidPtrType()), e->offset);
}
}
// Casts are also "optimized into" SymOffExp by the frontend.
LLValue *llVal = (e->type->toBasetype()->isintegral()
? p->ir->CreatePtrToInt(offsetValue, DtoType(e->type))
: DtoBitCast(offsetValue, DtoType(e->type)));
result = new DImValue(e->type, llVal);
}
//////////////////////////////////////////////////////////////////////////////
void visit(AddrExp *e) override {
IF_LOG Logger::println("AddrExp::toElem: %s @ %s", e->toChars(),
e->type->toChars());
LOG_SCOPE;
auto &PGO = gIR->funcGen().pgo;
PGO.setCurrentStmt(e);
// The address of a StructLiteralExp can in fact be a global variable, check
// for that instead of re-codegening the literal.
if (e->e1->op == TOKstructliteral) {
// lvalue literal must be a global, hence we can just use
// toConstElem on the AddrExp to get the address.
LLConstant *addr = toConstElem(e, p);
IF_LOG Logger::cout()
<< "returning address of struct literal global: " << addr << '\n';
result = new DImValue(e->type, DtoBitCast(addr, DtoType(e->type)));
return;
}
DValue *v = toElem(e->e1, true);
if (DFuncValue *fv = v->isFunc()) {
Logger::println("is func");
// Logger::println("FuncDeclaration");
FuncDeclaration *fd = fv->func;
assert(fd);
DtoResolveFunction(fd);
result = new DFuncValue(fd, DtoCallee(fd));
return;
}
if (v->isIm()) {
Logger::println("is immediate");
result = v;
return;
}
Logger::println("is nothing special");
// we special case here, since apparently taking the address of a slice is
// ok
LLValue *lval;
if (v->isLVal()) {
lval = DtoLVal(v);
} else {
assert(v->isSlice());
lval = DtoAllocaDump(v, ".tmp_slice_storage");
}
IF_LOG Logger::cout() << "lval: " << *lval << '\n';
result = new DImValue(e->type, DtoBitCast(lval, DtoType(e->type)));
}
//////////////////////////////////////////////////////////////////////////////
void visit(PtrExp *e) override {
IF_LOG Logger::println("PtrExp::toElem: %s @ %s", e->toChars(),
e->type->toChars());
LOG_SCOPE;
auto &PGO = gIR->funcGen().pgo;
PGO.setCurrentStmt(e);
// function pointers are special
if (e->type->toBasetype()->ty == Tfunction) {
DValue *dv = toElem(e->e1);
LLValue *llVal = DtoRVal(dv);
if (DFuncValue *dfv = dv->isFunc()) {
result = new DFuncValue(e->type, dfv->func, llVal);
} else {
result = new DImValue(e->type, llVal);
}
return;
}
// get the rvalue and return it as an lvalue
LLValue *V = DtoRVal(e->e1);
result = new DLValue(e->type, DtoBitCast(V, DtoPtrToType(e->type)));
}
//////////////////////////////////////////////////////////////////////////////
void visit(DotVarExp *e) override {
IF_LOG Logger::print("DotVarExp::toElem: %s @ %s\n", e->toChars(),
e->type->toChars());
LOG_SCOPE;
auto &PGO = gIR->funcGen().pgo;
PGO.setCurrentStmt(e);
DValue *l = toElem(e->e1);
Type *e1type = e->e1->type->toBasetype();
// Logger::println("e1type=%s", e1type->toChars());
// Logger::cout() << *DtoType(e1type) << '\n';
if (VarDeclaration *vd = e->var->isVarDeclaration()) {
LLValue *arrptr;
// indexing struct pointer
if (e1type->ty == Tpointer) {
assert(e1type->nextOf()->ty == Tstruct);
TypeStruct *ts = static_cast<TypeStruct *>(e1type->nextOf());
arrptr = DtoIndexAggregate(DtoRVal(l), ts->sym, vd);
}
// indexing normal struct
else if (e1type->ty == Tstruct) {
TypeStruct *ts = static_cast<TypeStruct *>(e1type);
arrptr = DtoIndexAggregate(DtoLVal(l), ts->sym, vd);
}
// indexing class
else if (e1type->ty == Tclass) {
TypeClass *tc = static_cast<TypeClass *>(e1type);
arrptr = DtoIndexAggregate(DtoRVal(l), tc->sym, vd);
} else {
llvm_unreachable("Unknown DotVarExp type for VarDeclaration.");
}
// Logger::cout() << "mem: " << *arrptr << '\n';
result = new DLValue(e->type, DtoBitCast(arrptr, DtoPtrToType(e->type)));
} else if (FuncDeclaration *fdecl = e->var->isFuncDeclaration()) {
DtoResolveFunction(fdecl);
// This is a bit more convoluted than it would need to be, because it
// has to take templated interface methods into account, for which
// isFinalFunc is not necessarily true.
// Also, private/package methods are always non-virtual.
const bool nonFinal = !fdecl->isFinalFunc() &&
(fdecl->isAbstract() || fdecl->isVirtual()) &&
fdecl->prot().kind != Prot::private_ &&
fdecl->prot().kind != Prot::package_;
// Get the actual function value to call.
LLValue *funcval = nullptr;
if (nonFinal) {