/
toir.cpp
3482 lines (2933 loc) · 113 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 "attrib.h"
#include "enum.h"
#include "hdrgen.h"
#include "id.h"
#include "init.h"
#include "mtype.h"
#include "module.h"
#include "port.h"
#include "rmem.h"
#include "template.h"
#include "gen/aa.h"
#include "gen/abi.h"
#include "gen/arrays.h"
#include "gen/classes.h"
#include "gen/complex.h"
#include "gen/dvalue.h"
#include "gen/functions.h"
#include "gen/irstate.h"
#include "gen/llvm.h"
#include "gen/llvmhelpers.h"
#include "gen/logger.h"
#include "gen/nested.h"
#include "gen/optimizer.h"
#include "gen/pragma.h"
#include "gen/runtime.h"
#include "gen/structs.h"
#include "gen/tollvm.h"
#include "gen/typeinf.h"
#include "gen/utils.h"
#include "gen/warnings.h"
#include "ir/irtypeclass.h"
#include "ir/irtypestruct.h"
#include "ir/irlandingpad.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include <fstream>
#include <math.h>
#include <stack>
#include <stdio.h>
// Needs other includes.
#include "ctfe.h"
llvm::cl::opt<bool> checkPrintf("check-printf-calls",
llvm::cl::desc("Validate printf call format strings against arguments"),
llvm::cl::ZeroOrMore);
//////////////////////////////////////////////////////////////////////////////////////////
void Expression::cacheLvalue(IRState* irs)
{
error("expression %s does not mask any l-value", toChars());
fatal();
}
/*******************************************
* Evaluate Expression, then call destructors on any temporaries in it.
*/
DValue *Expression::toElemDtor(IRState *p)
{
Logger::println("Expression::toElemDtor(): %s", toChars());
LOG_SCOPE
class CallDestructors : public IRLandingPadCatchFinallyInfo {
public:
CallDestructors(const std::vector<Expression*> &edtors_)
: edtors(edtors_)
{}
const std::vector<Expression*> &edtors;
void toIR(LLValue */*eh_ptr*/ = 0)
{
std::vector<Expression*>::const_reverse_iterator itr, end = edtors.rend();
for (itr = edtors.rbegin(); itr != end; ++itr)
(*itr)->toElem(gIR);
}
static int searchVarsWithDesctructors(Expression *exp, void *edtors)
{
if (exp->op == TOKdeclaration) {
DeclarationExp *de = (DeclarationExp*)exp;
if (VarDeclaration *vd = de->declaration->isVarDeclaration()) {
while (vd->aliassym) {
vd = vd->aliassym->isVarDeclaration();
if (!vd)
return 0;
}
if (vd->init) {
if (ExpInitializer *ex = vd->init->isExpInitializer())
ex->exp->apply(&searchVarsWithDesctructors, edtors);
}
if (!vd->isDataseg() && vd->edtor && !vd->noscope)
static_cast<std::vector<Expression*>*>(edtors)->push_back(vd->edtor);
}
}
return 0;
}
};
// find destructors that must be called
std::vector<Expression*> edtors;
apply(&CallDestructors::searchVarsWithDesctructors, &edtors);
if (!edtors.empty()) {
if (op == TOKcall) {
// create finally block that calls destructors on temporaries
CallDestructors *callDestructors = new CallDestructors(edtors);
// create landing pad
llvm::BasicBlock *oldend = p->scopeend();
llvm::BasicBlock *landingpadbb = llvm::BasicBlock::Create(gIR->context(), "landingpad", p->topfunc(), oldend);
// set up the landing pad
IRLandingPad &pad = gIR->func()->gen->landingPadInfo;
pad.addFinally(callDestructors);
pad.push(landingpadbb);
// evaluate the expression
DValue *val = toElem(p);
// build the landing pad
llvm::BasicBlock *oldbb = p->scopebb();
pad.pop();
// call the destructors
gIR->scope() = IRScope(oldbb, oldend);
callDestructors->toIR();
delete callDestructors;
return val;
} else {
DValue *val = toElem(p);
CallDestructors(edtors).toIR();
return val;
}
}
return toElem(p);
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* DeclarationExp::toElem(IRState* p)
{
Logger::print("DeclarationExp::toElem: %s | T=%s\n", toChars(), type->toChars());
LOG_SCOPE;
return DtoDeclarationExp(declaration);
}
//////////////////////////////////////////////////////////////////////////////////////////
void VarExp::cacheLvalue(IRState* p)
{
Logger::println("Caching l-value of %s", toChars());
LOG_SCOPE;
cachedLvalue = toElem(p)->getLVal();
}
DValue* VarExp::toElem(IRState* p)
{
Logger::print("VarExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
assert(var);
if (cachedLvalue)
{
LLValue* V = cachedLvalue;
return new DVarValue(type, V);
}
return DtoSymbolAddress(loc, type, var);
}
//////////////////////////////////////////////////////////////////////////////////////////
LLConstant* VarExp::toConstElem(IRState* p)
{
Logger::print("VarExp::toConstElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
if (SymbolDeclaration* sdecl = var->isSymbolDeclaration())
{
// this seems to be the static initialiser for structs
Type* sdecltype = sdecl->type->toBasetype();
Logger::print("Sym: type=%s\n", sdecltype->toChars());
assert(sdecltype->ty == Tstruct);
TypeStruct* ts = static_cast<TypeStruct*>(sdecltype);
DtoResolveStruct(ts->sym);
return ts->sym->ir.irAggr->getDefaultInit();
}
if (TypeInfoDeclaration* ti = var->isTypeInfoDeclaration())
{
LLType* vartype = DtoType(type);
LLConstant* m = DtoTypeInfoOf(ti->tinfo, false);
if (m->getType() != getPtrToType(vartype))
m = llvm::ConstantExpr::getBitCast(m, vartype);
return m;
}
VarDeclaration* vd = var->isVarDeclaration();
if (vd && vd->isConst() && vd->init)
{
if (vd->inuse)
{
error("recursive reference %s", toChars());
return llvm::UndefValue::get(DtoType(type));
}
vd->inuse++;
LLConstant* ret = DtoConstInitializer(loc, type, vd->init);
vd->inuse--;
// return the initializer
return ret;
}
// fail
error("non-constant expression %s", toChars());
return llvm::UndefValue::get(DtoType(type));
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* IntegerExp::toElem(IRState* p)
{
Logger::print("IntegerExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
LLConstant* c = toConstElem(p);
return new DConstValue(type, c);
}
//////////////////////////////////////////////////////////////////////////////////////////
LLConstant* IntegerExp::toConstElem(IRState* p)
{
Logger::print("IntegerExp::toConstElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
LLType* t = DtoType(type);
if (isaPointer(t)) {
Logger::println("pointer");
LLConstant* i = LLConstantInt::get(DtoSize_t(),(uint64_t)value,false);
return llvm::ConstantExpr::getIntToPtr(i, t);
}
assert(llvm::isa<LLIntegerType>(t));
LLConstant* c = LLConstantInt::get(t,(uint64_t)value,!type->isunsigned());
assert(c);
if (Logger::enabled())
Logger::cout() << "value = " << *c << '\n';
return c;
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* RealExp::toElem(IRState* p)
{
Logger::print("RealExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
LLConstant* c = toConstElem(p);
return new DConstValue(type, c);
}
//////////////////////////////////////////////////////////////////////////////////////////
LLConstant* RealExp::toConstElem(IRState* p)
{
Logger::print("RealExp::toConstElem: %s @ %s | %La\n", toChars(), type->toChars(), value);
LOG_SCOPE;
Type* t = type->toBasetype();
return DtoConstFP(t, value);
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* NullExp::toElem(IRState* p)
{
Logger::print("NullExp::toElem(type=%s): %s\n", type->toChars(),toChars());
LOG_SCOPE;
LLConstant* c = toConstElem(p);
return new DNullValue(type, c);
}
//////////////////////////////////////////////////////////////////////////////////////////
LLConstant* NullExp::toConstElem(IRState* p)
{
Logger::print("NullExp::toConstElem(type=%s): %s\n", type->toChars(),toChars());
LOG_SCOPE;
LLType* t = DtoType(type);
if (type->ty == Tarray) {
assert(isaStruct(t));
return llvm::ConstantAggregateZero::get(t);
}
else {
return LLConstant::getNullValue(t);
}
llvm_unreachable("Unknown type for null constant.");
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* ComplexExp::toElem(IRState* p)
{
Logger::print("ComplexExp::toElem(): %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
LLConstant* c = toConstElem(p);
LLValue* res;
if (c->isNullValue()) {
switch (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(type), c, c);
}
else {
res = DtoAggrPair(DtoType(type), c->getOperand(0), c->getOperand(1));
}
return new DImValue(type, res);
}
//////////////////////////////////////////////////////////////////////////////////////////
LLConstant* ComplexExp::toConstElem(IRState* p)
{
Logger::print("ComplexExp::toConstElem(): %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
return DtoConstComplex(type, value.re, value.im);
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* StringExp::toElem(IRState* p)
{
Logger::print("StringExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
Type* dtype = type->toBasetype();
Type* cty = dtype->nextOf()->toBasetype();
LLType* ct = voidToI8(DtoType(cty));
//printf("ct = %s\n", type->nextOf()->toChars());
LLArrayType* at = LLArrayType::get(ct,len+1);
LLConstant* _init;
switch (cty->size())
{
default:
llvm_unreachable("Unknown char type");
case 1:
_init = toConstantArray(ct, at, static_cast<uint8_t *>(string), len);
break;
case 2:
_init = toConstantArray(ct, at, static_cast<uint16_t *>(string), len);
break;
case 4:
_init = toConstantArray(ct, at, static_cast<uint32_t *>(string), len);
break;
}
llvm::GlobalValue::LinkageTypes _linkage = llvm::GlobalValue::InternalLinkage;
if (Logger::enabled())
{
Logger::cout() << "type: " << *at << '\n';
Logger::cout() << "init: " << *_init << '\n';
}
llvm::GlobalVariable* gvar = new llvm::GlobalVariable(*gIR->module, at, true, _linkage, _init, ".str");
gvar->setUnnamedAddr(true);
llvm::ConstantInt* zero = LLConstantInt::get(LLType::getInt32Ty(gIR->context()), 0, false);
LLConstant* idxs[2] = { zero, zero };
LLConstant* arrptr = llvm::ConstantExpr::getGetElementPtr(gvar, idxs, true);
if (dtype->ty == Tarray) {
LLConstant* clen = LLConstantInt::get(DtoSize_t(),len,false);
return new DImValue(type, DtoConstSlice(clen, arrptr, dtype));
}
else if (dtype->ty == Tsarray) {
LLType* dstType = getPtrToType(LLArrayType::get(ct, len));
LLValue* emem = (gvar->getType() == dstType) ? gvar : DtoBitCast(gvar, dstType);
return new DVarValue(type, emem);
}
else if (dtype->ty == Tpointer) {
return new DImValue(type, arrptr);
}
llvm_unreachable("Unknown type for StringExp.");
}
//////////////////////////////////////////////////////////////////////////////////////////
LLConstant* StringExp::toConstElem(IRState* p)
{
Logger::print("StringExp::toConstElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
Type* t = type->toBasetype();
Type* cty = t->nextOf()->toBasetype();
bool nullterm = (t->ty != Tsarray);
size_t endlen = nullterm ? len+1 : len;
LLType* ct = voidToI8(DtoType(cty));
LLArrayType* at = LLArrayType::get(ct,endlen);
LLConstant* _init;
switch (cty->size())
{
default:
llvm_unreachable("Unknown char type");
case 1:
_init = toConstantArray(ct, at, static_cast<uint8_t *>(string), len, nullterm);
break;
case 2:
_init = toConstantArray(ct, at, static_cast<uint16_t *>(string), len, nullterm);
break;
case 4:
_init = toConstantArray(ct, at, static_cast<uint32_t *>(string), len, nullterm);
break;
}
if (t->ty == Tsarray)
{
return _init;
}
llvm::GlobalValue::LinkageTypes _linkage = llvm::GlobalValue::InternalLinkage;
llvm::GlobalVariable* gvar = new llvm::GlobalVariable(*gIR->module, _init->getType(), true, _linkage, _init, ".str");
gvar->setUnnamedAddr(true);
llvm::ConstantInt* zero = LLConstantInt::get(LLType::getInt32Ty(gIR->context()), 0, false);
LLConstant* idxs[2] = { zero, zero };
LLConstant* arrptr = llvm::ConstantExpr::getGetElementPtr(gvar, idxs, true);
if (t->ty == Tpointer) {
return arrptr;
}
else if (t->ty == Tarray) {
LLConstant* clen = LLConstantInt::get(DtoSize_t(),len,false);
return DtoConstSlice(clen, arrptr, type);
}
llvm_unreachable("Unknown type for StringExp.");
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* AssignExp::toElem(IRState* p)
{
Logger::print("AssignExp::toElem: %s | (%s)(%s = %s)\n", toChars(), type->toChars(), e1->type->toChars(), e2->type ? e2->type->toChars() : 0);
LOG_SCOPE;
if (e1->op == TOKarraylength)
{
Logger::println("performing array.length assignment");
ArrayLengthExp *ale = static_cast<ArrayLengthExp *>(e1);
DValue* arr = ale->e1->toElem(p);
DVarValue arrval(ale->e1->type, arr->getLVal());
DValue* newlen = e2->toElem(p);
DSliceValue* slice = DtoResizeDynArray(arrval.getType(), &arrval, newlen->getRVal());
DtoAssign(loc, &arrval, slice);
return newlen;
}
// Can't just override ConstructExp::toElem because not all TOKconstruct
// operations are actually instances of ConstructExp... Long live the DMD
// coding style!
if (op == TOKconstruct)
{
if (e1->op == TOKvar)
{
VarExp* ve = (VarExp*)e1;
if (ve->var->storage_class & STCref)
{
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!
DVarValue* lhs = e1->toElem(p)->isVar();
assert(lhs);
DValue* rhs = e2->toElem(p);
// We shouldn't really need makeLValue() here, but the 2.063
// frontend generates ref variables initialized from function
// calls.
DtoStore(makeLValue(loc, rhs), lhs->getRefStorage());
return rhs;
}
}
}
if (e1->op == TOKslice)
{
// Check if this is an initialization of a static array with an array
// literal that the frontend has foolishly rewritten into an
// assignment of a dynamic array literal to a slice.
Logger::println("performing static array literal assignment");
SliceExp * const se = static_cast<SliceExp *>(e1);
Type * const t2 = e2->type->toBasetype();
Type * const ta = se->e1->type->toBasetype();
if (se->lwr == NULL && ta->ty == Tsarray &&
e2->op == TOKarrayliteral &&
t2->nextOf()->mutableOf()->implicitConvTo(ta->nextOf()))
{
ArrayLiteralExp * const ale = static_cast<ArrayLiteralExp *>(e2);
initializeArrayLiteral(p, ale, se->e1->toElem(p)->getLVal());
return e1->toElem(p);
}
}
DValue* l = e1->toElem(p);
DValue* r = e2->toElem(p);
if (e1->type->toBasetype()->ty == Tstruct && e2->op == TOKint64)
{
Logger::println("performing aggregate zero initialization");
assert(e2->toInteger() == 0);
DtoAggrZeroInit(l->getLVal());
TypeStruct *ts = static_cast<TypeStruct*>(e1->type);
if (ts->sym->isNested() && ts->sym->vthis)
DtoResolveNestedContext(loc, ts->sym, l->getLVal());
// Return value should be irrelevant.
return r;
}
bool canSkipPostblit = false;
if (!(e2->op == TOKslice && ((UnaExp *)e2)->e1->isLvalue()) &&
!(e2->op == TOKcast && ((UnaExp *)e2)->e1->isLvalue()) &&
(e2->op == TOKslice || !e2->isLvalue()))
{
canSkipPostblit = true;
}
Logger::println("performing normal assignment (canSkipPostblit = %d)", canSkipPostblit);
DtoAssign(loc, l, r, op, canSkipPostblit);
if (l->isSlice())
return l;
return r;
}
//////////////////////////////////////////////////////////////////////////////////////////
/// Finds the proper lvalue for a binassign expressions.
/// Makes sure the given LHS expression is only evaluated once.
static Expression* findLvalue(IRState* irs, Expression* exp)
{
Expression* e = exp;
// skip past any casts
while(e->op == TOKcast)
e = static_cast<CastExp*>(e)->e1;
// cache lvalue and return
e->cacheLvalue(irs);
return e;
}
#define BIN_ASSIGN(X) \
DValue* X##AssignExp::toElem(IRState* p) \
{ \
Logger::print(#X"AssignExp::toElem: %s @ %s\n", toChars(), type->toChars()); \
LOG_SCOPE; \
X##Exp e3(loc, e1, e2); \
e3.type = e1->type; \
DValue* dst = findLvalue(p, e1)->toElem(p); \
DValue* res = e3.toElem(p); \
/* Now that we are done with the expression, clear the cached lvalue. */ \
Expression* e = e1; \
while(e->op == TOKcast) \
e = static_cast<CastExp*>(e)->e1; \
e->cachedLvalue = NULL; \
/* Assign the (casted) value and return it. */ \
DValue* stval = DtoCast(loc, res, dst->getType()); \
DtoAssign(loc, dst, stval); \
return DtoCast(loc, res, type); \
}
BIN_ASSIGN(Add)
BIN_ASSIGN(Min)
BIN_ASSIGN(Mul)
BIN_ASSIGN(Div)
BIN_ASSIGN(Mod)
BIN_ASSIGN(And)
BIN_ASSIGN(Or)
BIN_ASSIGN(Xor)
BIN_ASSIGN(Shl)
BIN_ASSIGN(Shr)
BIN_ASSIGN(Ushr)
#undef BIN_ASSIGN
//////////////////////////////////////////////////////////////////////////////////////////
static 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();
}
}
//////////////////////////////////////////////////////////////////////////////////////////
static dinteger_t undoStrideMul(const Loc& loc, Type* t, dinteger_t offset)
{
assert(t->ty == Tpointer);
d_uns64 elemSize = t->nextOf()->size(loc);
assert((offset % elemSize) == 0 &&
"Expected offset by an integer amount of elements");
return offset / elemSize;
}
LLConstant* AddExp::toConstElem(IRState* p)
{
// add to pointer
Type* t1b = e1->type->toBasetype();
if (t1b->ty == Tpointer && e2->type->isintegral()) {
llvm::Constant* ptr = e1->toConstElem(p);
dinteger_t idx = undoStrideMul(loc, t1b, e2->toInteger());
return llvm::ConstantExpr::getGetElementPtr(ptr, DtoConstSize_t(idx));
}
error("expression '%s' is not a constant", toChars());
fatal();
return NULL;
}
/// Tries to remove a MulExp by a constant value of baseSize from e. Returns
/// NULL if not possible.
static Expression* extractNoStrideInc(Expression* e, d_uns64 baseSize, bool& negate)
{
MulExp* mul;
while (true)
{
if (e->op == TOKneg)
{
negate = !negate;
e = static_cast<NegExp*>(e)->e1;
continue;
}
if (e->op == TOKmul)
{
mul = static_cast<MulExp*>(e);
break;
}
return NULL;
}
if (!mul->e2->isConst()) return NULL;
dinteger_t stride = mul->e2->toInteger();
if (stride != baseSize) return NULL;
return mul->e1;
}
static DValue* emitPointerOffset(IRState* p, Loc loc, DValue* base,
Expression* offset, bool negateOffset, Type* resultType)
{
// The operand emitted by the frontend is in units of bytes, and not
// pointer elements. We try to undo this before resorting to
// temporarily bitcasting the pointer to i8.
llvm::Value* noStrideInc = NULL;
if (offset->isConst())
{
dinteger_t byteOffset = offset->toInteger();
if (byteOffset == 0)
{
Logger::println("offset is zero");
return base;
}
noStrideInc = DtoConstSize_t(undoStrideMul(loc, base->type, byteOffset));
}
else if (Expression* inc = extractNoStrideInc(offset,
base->type->nextOf()->size(loc), negateOffset))
{
noStrideInc = inc->toElem(p)->getRVal();
}
if (noStrideInc)
{
if (negateOffset) noStrideInc = p->ir->CreateNeg(noStrideInc);
return new DImValue(base->type,
DtoGEP1(base->getRVal(), noStrideInc, 0, p->scopebb()));
}
// This might not actually be generated by the frontend, just to be
// safe.
llvm::Value* inc = offset->toElem(p)->getRVal();
if (negateOffset) inc = p->ir->CreateNeg(inc);
llvm::Value* bytePtr = DtoBitCast(base->getRVal(), getVoidPtrType());
DValue* result = new DImValue(Type::tvoidptr, DtoGEP1(bytePtr, inc));
return DtoCast(loc, result, resultType);
}
DValue* AddExp::toElem(IRState* p)
{
Logger::print("AddExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
DValue* l = e1->toElem(p);
Type* t = type->toBasetype();
Type* e1type = e1->type->toBasetype();
Type* e2type = e2->type->toBasetype();
errorOnIllegalArrayOp(this, e1, e2);
if (e1type != e2type && e1type->ty == Tpointer && e2type->isintegral())
{
Logger::println("Adding integer to pointer");
return emitPointerOffset(p, loc, l, e2, false, type);
}
else if (t->iscomplex()) {
return DtoComplexAdd(loc, type, l, e2->toElem(p));
}
else {
return DtoBinAdd(l, e2->toElem(p));
}
}
LLConstant* MinExp::toConstElem(IRState* p)
{
Type* t1b = e1->type->toBasetype();
if (t1b->ty == Tpointer && e2->type->isintegral()) {
llvm::Constant* ptr = e1->toConstElem(p);
dinteger_t idx = undoStrideMul(loc, t1b, e2->toInteger());
llvm::Constant* negIdx = llvm::ConstantExpr::getNeg(DtoConstSize_t(idx));
return llvm::ConstantExpr::getGetElementPtr(ptr, negIdx);
}
error("expression '%s' is not a constant", toChars());
fatal();
return NULL;
}
DValue* MinExp::toElem(IRState* p)
{
Logger::print("MinExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
DValue* l = e1->toElem(p);
Type* t = type->toBasetype();
Type* t1 = e1->type->toBasetype();
Type* t2 = e2->type->toBasetype();
errorOnIllegalArrayOp(this, e1, e2);
if (t1->ty == Tpointer && t2->ty == Tpointer) {
LLValue* lv = l->getRVal();
LLValue* rv = e2->toElem(p)->getRVal();
if (Logger::enabled())
Logger::cout() << "lv: " << *lv << " rv: " << *rv << '\n';
lv = p->ir->CreatePtrToInt(lv, DtoSize_t(), "tmp");
rv = p->ir->CreatePtrToInt(rv, DtoSize_t(), "tmp");
LLValue* diff = p->ir->CreateSub(lv,rv,"tmp");
if (diff->getType() != DtoType(type))
diff = p->ir->CreateIntToPtr(diff, DtoType(type), "tmp");
return new DImValue(type, diff);
}
else if (t1->ty == Tpointer && t2->isintegral())
{
Logger::println("Subtracting integer from pointer");
return emitPointerOffset(p, loc, l, e2, true, type);
}
else if (t->iscomplex()) {
return DtoComplexSub(loc, type, l, e2->toElem(p));
}
else {
return DtoBinSub(l, e2->toElem(p));
}
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* MulExp::toElem(IRState* p)
{
Logger::print("MulExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
DValue* l = e1->toElem(p);
DValue* r = e2->toElem(p);
errorOnIllegalArrayOp(this, e1, e2);
if (type->iscomplex()) {
return DtoComplexMul(loc, type, l, r);
}
return DtoBinMul(type, l, r);
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* DivExp::toElem(IRState* p)
{
Logger::print("DivExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
DValue* l = e1->toElem(p);
DValue* r = e2->toElem(p);
errorOnIllegalArrayOp(this, e1, e2);
if (type->iscomplex()) {
return DtoComplexDiv(loc, type, l, r);
}
return DtoBinDiv(type, l, r);
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* ModExp::toElem(IRState* p)
{
Logger::print("ModExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
DValue* l = e1->toElem(p);
DValue* r = e2->toElem(p);
errorOnIllegalArrayOp(this, e1, e2);
if (type->iscomplex()) {
return DtoComplexRem(loc, type, l, r);
}
return DtoBinRem(type, l, r);
}
//////////////////////////////////////////////////////////////////////////////////////////
void CallExp::cacheLvalue(IRState* p)
{
Logger::println("Caching l-value of %s", toChars());
LOG_SCOPE;
cachedLvalue = toElem(p)->getLVal();
}
//////////////////////////////////////////////////////////////////////////////////////////
DValue* CallExp::toElem(IRState* p)
{
Logger::print("CallExp::toElem: %s @ %s\n", toChars(), type->toChars());
LOG_SCOPE;
if (cachedLvalue)
{
LLValue* V = cachedLvalue;
return new DVarValue(type, V);
}
// handle magic inline asm
if (e1->op == TOKvar)
{
VarExp* ve = static_cast<VarExp*>(e1);
if (FuncDeclaration* fd = ve->var->isFuncDeclaration())
{
if (fd->llvmInternal == LLVMinline_asm)
{
return DtoInlineAsmExpr(loc, fd, arguments);
}
}
}
// get the callee value
DValue* fnval = e1->toElem(p);
// 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 && checkPrintf)
{
if (fndecl->linkage == LINKc && strcmp(fndecl->ident->string, "printf") == 0)
{
warnInvalidPrintfCall(loc, static_cast<Expression*>(arguments->data[0]), arguments->dim);
}
}
// va_start instruction
if (fndecl->llvmInternal == LLVMva_start) {
if (arguments->dim != 2) {
error("va_start instruction expects 2 arguments");
return NULL;
}
// llvm doesn't need the second param hence the override
Expression* exp = static_cast<Expression*>(arguments->data[0]);
LLValue* arg = exp->toElem(p)->getLVal();
if (LLValue *argptr = gIR->func()->_argptr) {
DtoStore(DtoLoad(argptr), DtoBitCast(arg, getPtrToType(getVoidPtrType())));
return new DImValue(type, arg);
} else if (global.params.targetTriple.getArch() == llvm::Triple::x86_64) {
LLValue *va_list = DtoAlloca(exp->type->nextOf());
DtoStore(va_list, arg);
va_list = DtoBitCast(va_list, getVoidPtrType());
return new DImValue(type, gIR->ir->CreateCall(GET_INTRINSIC_DECL(vastart), va_list, ""));
} else
{
arg = DtoBitCast(arg, getVoidPtrType());
return new DImValue(type, gIR->ir->CreateCall(GET_INTRINSIC_DECL(vastart), arg, ""));
}
}
else if (fndecl->llvmInternal == LLVMva_copy &&
global.params.targetTriple.getArch() == llvm::Triple::x86_64) {
if (arguments->dim != 2) {
error("va_copy instruction expects 2 arguments");
return NULL;
}
Expression* exp1 = static_cast<Expression*>(arguments->data[0]);
Expression* exp2 = static_cast<Expression*>(arguments->data[1]);
LLValue* arg1 = exp1->toElem(p)->getLVal();
LLValue* arg2 = exp2->toElem(p)->getLVal();
LLValue *va_list = DtoAlloca(exp1->type->nextOf());
DtoStore(va_list, arg1);
DtoStore(DtoLoad(DtoLoad(arg2)), DtoLoad(arg1));
return new DVarValue(type, arg1);
}
// va_arg instruction
else if (fndecl->llvmInternal == LLVMva_arg) {
if (arguments->dim != 1) {
error("va_arg instruction expects 1 arguments");
return NULL;
}
return DtoVaArg(loc, type, static_cast<Expression*>(arguments->data[0]));
}
// C alloca
else if (fndecl->llvmInternal == LLVMalloca) {
if (arguments->dim != 1) {
error("alloca expects 1 arguments");
return NULL;
}
Expression* exp = static_cast<Expression*>(arguments->data[0]);
DValue* expv = exp->toElem(p);
if (expv->getType()->toBasetype()->ty != Tint32)
expv = DtoCast(loc, expv, Type::tint32);
return new DImValue(type, p->ir->CreateAlloca(LLType::getInt8Ty(gIR->context()), expv->getRVal(), ".alloca"));
}
// fence instruction
else if (fndecl->llvmInternal == LLVMfence) {
if (arguments->dim != 1) {
error("fence instruction expects 1 arguments");
return NULL;
}
gIR->ir->CreateFence(llvm::AtomicOrdering(static_cast<Expression*>(arguments->data[0])->toInteger()));
return NULL;
// atomic store instruction
} else if (fndecl->llvmInternal == LLVMatomic_store) {
if (arguments->dim != 3) {
error("atomic store instruction expects 3 arguments");
return NULL;
}
Expression* exp1 = static_cast<Expression*>(arguments->data[0]);
Expression* exp2 = static_cast<Expression*>(arguments->data[1]);
int atomicOrdering = static_cast<Expression*>(arguments->data[2])->toInteger();
LLValue* val = exp1->toElem(p)->getRVal();
LLValue* ptr = exp2->toElem(p)->getRVal();