forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegenwasm.cpp
More file actions
3466 lines (3029 loc) · 115 KB
/
codegenwasm.cpp
File metadata and controls
3466 lines (3029 loc) · 115 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "codegen.h"
#include "regallocwasm.h"
#include "fgwasm.h"
#include "gcinfo.h"
#include "gcinfoencoder.h"
static const int LINEAR_MEMORY_INDEX = 0;
#ifdef TARGET_64BIT
static const instruction INS_I_load = INS_i64_load;
static const instruction INS_I_store = INS_i64_store;
static const instruction INS_I_const = INS_i64_const;
static const instruction INS_I_add = INS_i64_add;
static const instruction INS_I_and = INS_i64_and;
static const instruction INS_I_eqz = INS_i64_eqz;
static const instruction INS_I_mul = INS_i64_mul;
static const instruction INS_I_sub = INS_i64_sub;
static const instruction INS_I_le_u = INS_i64_le_u;
static const instruction INS_I_ge_u = INS_i64_ge_u;
static const instruction INS_I_gt_u = INS_i64_gt_u;
#else // !TARGET_64BIT
static const instruction INS_I_load = INS_i32_load;
static const instruction INS_I_store = INS_i32_store;
static const instruction INS_I_const = INS_i32_const;
static const instruction INS_I_add = INS_i32_add;
static const instruction INS_I_and = INS_i32_and;
static const instruction INS_I_eqz = INS_i32_eqz;
static const instruction INS_I_mul = INS_i32_mul;
static const instruction INS_I_sub = INS_i32_sub;
static const instruction INS_I_le_u = INS_i32_le_u;
static const instruction INS_I_ge_u = INS_i32_ge_u;
static const instruction INS_I_gt_u = INS_i32_gt_u;
#endif // !TARGET_64BIT
//------------------------------------------------------------------------
// ensureCurrentFuncIsUnwindable: ensure we set up an unwindable frame
// for the current function or funclet.
//
void CodeGen::ensureCurrentFuncIsUnwindable()
{
FuncInfoDsc* const func = m_compiler->funCurrentFunc();
func->ensureUnwindableFrame(m_compiler);
}
//------------------------------------------------------------------------
// GetStackPointerRegIndex: get the Wasm local index for the stack pointer
//
unsigned CodeGen::GetStackPointerRegIndex() const
{
regNumber spReg = GetStackPointerReg(m_compiler->funCurrentFuncIdx());
assert(spReg != REG_NA);
return WasmRegToIndex(spReg);
}
//------------------------------------------------------------------------
// GetFramePointerRegIndex: get the Wasm local index for the frame pointer
//
unsigned CodeGen::GetFramePointerRegIndex() const
{
regNumber fpReg = GetFramePointerReg(m_compiler->funCurrentFuncIdx());
assert(fpReg != REG_NA);
return WasmRegToIndex(fpReg);
}
//------------------------------------------------------------------------
// genMarkLabelsForCodegen: mark labels for codegen
//
void CodeGen::genMarkLabelsForCodegen()
{
assert(!m_compiler->fgSafeBasicBlockCreation);
JITDUMP("Mark labels for codegen\n");
#ifdef DEBUG
// No label flags should be set before this.
for (BasicBlock* const block : m_compiler->Blocks())
{
assert(!block->HasFlag(BBF_HAS_LABEL));
}
#endif // DEBUG
// Mark all the funclet boundaries.
//
for (FuncInfoDsc* const func : m_compiler->Funcs())
{
BasicBlock* const firstBlock = func->GetStartBlock(m_compiler);
firstBlock->SetFlags(BBF_HAS_LABEL);
JITDUMP(" " FMT_BB " : %s begin\n", firstBlock->bbNum, (func->funKind == FUNC_ROOT) ? "method" : "funclet");
}
}
//------------------------------------------------------------------------
// genBeginFnProlog: generate wasm local declarations
//
void CodeGen::genBeginFnProlog()
{
FuncInfoDsc* const func = m_compiler->funGetFunc(ROOT_FUNC_IDX);
assert(func->funWasmLocalDecls != nullptr);
unsigned localsCount = 0;
assert(m_compiler->funCurrentFuncIdx() == 0);
GetEmitter()->emitIns_I(INS_local_cnt, EA_8BYTE, func->funWasmLocalDecls->size());
for (FuncInfoDsc::WasmLocalsDecl& decl : *func->funWasmLocalDecls)
{
GetEmitter()->emitIns_I_Ty(INS_local_decl, decl.Count, decl.Type, localsCount);
localsCount += decl.Count;
}
}
//------------------------------------------------------------------------
// genPushCalleeSavedRegisters: no-op since we don't need to save anything.
//
void CodeGen::genPushCalleeSavedRegisters(regNumber initReg, bool* pInitRegZeroed)
{
}
//------------------------------------------------------------------------
// genAllocLclFrame: initialize the SP and FP locals.
//
// Arguments:
// frameSize - Size of the frame to establish
// initReg - Unused
// pInitRegZeroed - Unused
// maskArgRegsLiveIn - Unused
//
void CodeGen::genAllocLclFrame(unsigned frameSize, regNumber initReg, bool* pInitRegZeroed, regMaskTP maskArgRegsLiveIn)
{
assert(m_compiler->compGeneratingProlog);
regNumber spReg = GetStackPointerReg(m_compiler->funCurrentFuncIdx());
if (spReg == REG_NA)
{
assert(!isFramePointerUsed());
return;
}
m_compiler->unwindAllocStack(frameSize);
// TODO-WASM: reverse pinvoke frame allocation
//
if (!m_compiler->lvaGetDesc(m_compiler->lvaWasmSpArg)->lvIsParam)
{
NYI_WASM("alloc local frame for reverse pinvoke");
}
unsigned initialSPLclIndex =
WasmRegToIndex(m_compiler->lvaGetParameterABIInfo(m_compiler->lvaWasmSpArg).Segment(0).GetRegister());
unsigned spLclIndex = WasmRegToIndex(spReg);
assert(initialSPLclIndex == spLclIndex);
if (frameSize != 0)
{
GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, initialSPLclIndex);
GetEmitter()->emitIns_I(INS_I_const, EA_PTRSIZE, frameSize);
GetEmitter()->emitIns(INS_I_sub);
GetEmitter()->emitIns_I(INS_local_set, EA_PTRSIZE, spLclIndex);
}
regNumber fpReg = GetFramePointerReg(m_compiler->funCurrentFuncIdx());
if ((fpReg != REG_NA) && (fpReg != spReg))
{
GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, spLclIndex);
GetEmitter()->emitIns_I(INS_local_set, EA_PTRSIZE, WasmRegToIndex(fpReg));
}
FuncInfoDsc* const func = m_compiler->funGetFunc(ROOT_FUNC_IDX);
if (func->needsUnwindableFrame)
{
assert(m_compiler->lvaWasmVirtualIP != BAD_VAR_NUM);
assert(m_compiler->lvaWasmFunctionIndex != BAD_VAR_NUM);
// fp[0] == functionIndex
//
// TODO-WASM: Save the actual function index. For now we save a fixed constant
//
GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, GetFramePointerRegIndex());
GetEmitter()->emitIns_I(INS_I_const, EA_PTRSIZE, 0xBBBB);
GetEmitter()->emitIns_S(ins_Store(TYP_I_IMPL), EA_PTRSIZE, m_compiler->lvaWasmFunctionIndex, 0);
}
}
//------------------------------------------------------------------------
// genEnregisterOSRArgsAndLocals: enregister OSR args and locals.
//
void CodeGen::genEnregisterOSRArgsAndLocals(regNumber initReg, bool* pInitRegZeroed)
{
unreached(); // OSR not supported on WASM.
}
//------------------------------------------------------------------------
// genOSRHandleTier0CalleeSavedRegistersAndFrame:
// Not called for WASM without OSR support.
//
void CodeGen::genOSRHandleTier0CalleeSavedRegistersAndFrame()
{
unreached();
}
//------------------------------------------------------------------------
// genHomeRegisterParams: place register arguments into their RA-assigned locations.
//
// We can't actually do this task here because the prolog will overflow. Instead, we
// do this later on and inject all the relevant code into the first basic block.
// See genHomeRegisterParamsOutsideProlog, below.
//
// Arguments:
// initReg - Unused
// initRegStillZeroed - Unused
//
void CodeGen::genHomeRegisterParams(regNumber initReg, bool* initRegStillZeroed)
{
// Intentionally empty
}
//------------------------------------------------------------------------
// genHomeRegisterParamsOutsideProlog: place register arguments into their RA-assigned locations.
//
// For the WASM RA, we have a much simplified (compared to LSRA) contract of:
// - If an argument is live on entry in a set of registers, then the RA will
// assign those registers to that argument on entry.
// This means we never need to do any copying or cycle resolution here.
//
// The main motivation for this (along with the obvious CQ implications) is
// obviating the need to adapt the general "RegGraph"-based algorithm to
// !HAS_FIXED_REGISTER_SET constraints (no reg masks).
void CodeGen::genHomeRegisterParamsOutsideProlog()
{
JITDUMP("*************** In genHomeRegisterParamsOutsideProlog()\n");
auto spillParam = [this](unsigned lclNum, unsigned offset, unsigned paramLclNum, const ABIPassingSegment& segment) {
assert(segment.IsPassedInRegister());
LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum);
if (varDsc->lvTracked && !VarSetOps::IsMember(m_compiler, m_compiler->fgFirstBB->bbLiveIn, varDsc->lvVarIndex))
{
return;
}
if (varDsc->lvOnFrame && (!varDsc->lvIsInReg() || varDsc->lvLiveInOutOfHndlr))
{
LclVarDsc* paramVarDsc = m_compiler->lvaGetDesc(paramLclNum);
var_types storeType = genParamStackType(paramVarDsc, segment);
if (!varDsc->TypeIs(TYP_STRUCT) && (genTypeSize(genActualType(varDsc)) < genTypeSize(storeType)))
{
// Can happen for struct fields due to padding.
storeType = genActualType(varDsc);
}
GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, GetFramePointerRegIndex());
GetEmitter()->emitIns_I(INS_local_get, emitActualTypeSize(storeType),
WasmRegToIndex(segment.GetRegister()));
GetEmitter()->emitIns_S(ins_Store(storeType), emitActualTypeSize(storeType), lclNum, offset);
}
if (varDsc->lvIsInReg())
{
assert(varDsc->GetRegNum() == segment.GetRegister());
}
};
for (unsigned lclNum = 0; lclNum < m_compiler->info.compArgsCount; lclNum++)
{
LclVarDsc* lclDsc = m_compiler->lvaGetDesc(lclNum);
const ABIPassingInformation& abiInfo = m_compiler->lvaGetParameterABIInfo(lclNum);
for (const ABIPassingSegment& segment : abiInfo.Segments())
{
if (!segment.IsPassedInRegister())
{
continue;
}
const ParameterRegisterLocalMapping* mapping =
m_compiler->FindParameterRegisterLocalMappingByRegister(segment.GetRegister());
bool spillToBaseLocal = true;
if (mapping != nullptr)
{
spillParam(mapping->LclNum, mapping->Offset, lclNum, segment);
// If home is shared with base local, then skip spilling to the base local.
if (lclDsc->lvPromoted)
{
spillToBaseLocal = false;
}
}
if (spillToBaseLocal)
{
spillParam(lclNum, segment.Offset, lclNum, segment);
}
}
}
}
void CodeGen::genFnEpilog(BasicBlock* block)
{
#ifdef DEBUG
if (verbose)
{
printf("*************** In genFnEpilog()\n");
}
#endif // DEBUG
ScopedSetVariable<bool> _setGeneratingEpilog(&m_compiler->compGeneratingEpilog, true);
#ifdef DEBUG
if (m_compiler->opts.dspCode)
printf("\n__epilog:\n");
#endif // DEBUG
bool jmpEpilog = block->HasFlag(BBF_HAS_JMP);
if (jmpEpilog)
{
NYI_WASM("genFnEpilog: jmpEpilog");
}
// TODO-WASM: shadow stack maintenance
// TODO-WASM: we need to handle the end-of-function case if we reach the end of a codegen for a function
// and do NOT have an epilog. In those cases we currently will not emit an end instruction.
if (block->IsLast() || m_compiler->bbIsFuncletBeg(block->Next()))
{
instGen(INS_end);
}
else
{
instGen(INS_return);
}
}
void CodeGen::genCaptureFuncletPrologEpilogInfo()
{
}
//------------------------------------------------------------------------
// genFuncletProlog: codegen for funclet prologs.
//
// Arguments:
// block - the funclet entry block
//
void CodeGen::genFuncletProlog(BasicBlock* block)
{
assert(m_compiler->bbIsFuncletBeg(block));
JITDUMP("*************** In genFuncletProlog()\n");
// Local sig for the funclet
//
unsigned localsCount = 0;
unsigned funcletIndex = m_compiler->funCurrentFuncIdx();
FuncInfoDsc* const func = m_compiler->funGetFunc(funcletIndex);
assert(funcletIndex > 0);
assert(func->funWasmLocalDecls != nullptr);
GetEmitter()->emitIns_I(INS_local_cnt, EA_8BYTE, func->funWasmLocalDecls->size());
for (FuncInfoDsc::WasmLocalsDecl& decl : *func->funWasmLocalDecls)
{
GetEmitter()->emitIns_I_Ty(INS_local_decl, decl.Count, decl.Type, localsCount);
localsCount += decl.Count;
}
// All the funclet params are used from their home registers, so nothing
// needs homing here.
//
// If the funclet needs to be unwindable (contains any calls), set up
// what we need.
//
if (func->needsUnwindableFrame)
{
// We need two stack slots for the function index and for the funclet virtual IP.
// We also need to keep SP aligned.
//
size_t slotSize = 2 * TARGET_POINTER_SIZE;
size_t frameSize = AlignUp(slotSize, STACK_ALIGN);
m_compiler->unwindAllocStack((unsigned)frameSize);
// Move SP
//
GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, GetStackPointerRegIndex());
GetEmitter()->emitIns_I(INS_I_const, EA_PTRSIZE, frameSize);
GetEmitter()->emitIns(INS_I_sub);
GetEmitter()->emitIns_I(INS_local_set, EA_PTRSIZE, GetStackPointerRegIndex());
// TODO-WASM: Save the funclet index. For now we save a fixed constant
//
GetEmitter()->emitIns_I(INS_local_get, EA_PTRSIZE, GetStackPointerRegIndex());
GetEmitter()->emitIns_I(INS_I_const, EA_PTRSIZE, 0xAAAA);
GetEmitter()->emitIns_I(ins_Store(TYP_I_IMPL), EA_PTRSIZE, 0);
}
}
//------------------------------------------------------------------------
// genFuncletEpilog: codegen for funclet epilogs.
//
// Arguments:
// block - funclet epilog block
//
void CodeGen::genFuncletEpilog(BasicBlock* block)
{
ScopedSetVariable<bool> _setGeneratingEpilog(&m_compiler->compGeneratingEpilog, true);
if (block->IsLast() || m_compiler->bbIsFuncletBeg(block->Next()))
{
instGen(INS_end);
}
else
{
instGen(INS_return);
}
}
//------------------------------------------------------------------------
// getBlockIndex: return the index of this block in the linear block
// order
//
// Arguments:
// block - block in question
//
// Returns:
// index of block
//
static unsigned getBlockIndex(BasicBlock* block)
{
return block->bbPreorderNum;
}
//------------------------------------------------------------------------
// findTargetDepth: find the depth of a target block in the wasm control flow stack
//
// Arguments:
// targetBlock - block to branch to
// (implicit) compCurBB -- block to branch from
//
// Returns:
// depth of target block in control stack
//
unsigned CodeGen::findTargetDepth(BasicBlock* targetBlock)
{
BasicBlock* const sourceBlock = m_compiler->compCurBB;
int const h = wasmControlFlowStack->Height();
const unsigned targetIndex = getBlockIndex(targetBlock);
const unsigned sourceIndex = getBlockIndex(sourceBlock);
const bool isBackedge = targetIndex <= sourceIndex;
for (int i = 0; i < h; i++)
{
WasmInterval* const ii = wasmControlFlowStack->Top(i);
unsigned match = 0;
if (isBackedge)
{
// loops bind to start
match = ii->Start();
}
else
{
// blocks and trys bind to end
match = ii->End();
}
if ((match == targetIndex) && (isBackedge == ii->IsLoop()))
{
return i;
}
}
#ifdef DEBUG
JITDUMP("Could not find " FMT_BB "[%u]%s in active control stack\n", targetBlock->bbNum, targetIndex,
isBackedge ? " (backedge)" : "");
JITDUMP("Current stack is\n");
for (int i = 0; i < h; i++)
{
WasmInterval* const ii = wasmControlFlowStack->Top(i);
JITDUMPEXEC(ii->Dump());
}
#endif
assert(!"Can't find target in control stack");
return ~0;
}
//------------------------------------------------------------------------
// genEmitStartBlock: prepare for codegen in a block
//
// Arguments:
// block - block to prepare for
//
// Notes:
// Updates the wasm control flow stack
//
void CodeGen::genEmitStartBlock(BasicBlock* block)
{
const unsigned cursor = getBlockIndex(block);
// Pop control flow intervals that end here (at most two, block and/or loop)
// and emit wasm END instructions for them.
//
while (!wasmControlFlowStack->Empty() && (wasmControlFlowStack->Top()->End() == cursor))
{
instGen(INS_end);
WasmInterval* interval = wasmControlFlowStack->Pop();
}
// Push control flow for intervals that start here or earlier, and emit
// Wasm BLOCK or LOOP instruction
//
if (wasmCursor < m_compiler->fgWasmIntervals->size())
{
WasmInterval* interval = m_compiler->fgWasmIntervals->at(wasmCursor);
WasmInterval* chain = interval->Chain();
while (chain->Start() <= cursor)
{
if (interval->IsLoop())
{
GetEmitter()->emitIns_BlockTy(INS_loop);
}
else if (interval->IsTry())
{
// Handle try_table emission here, since there may be blocks nested inside.
// (that is, we can't wait until we do codegen the block IR)
//
LIR::Range& blockRange = LIR::AsRange(block);
GenTree* const jTrue = blockRange.LastNode();
assert(jTrue->OperIs(GT_WASM_JEXCEPT));
// Empty stack sig, one catch clause
//
GetEmitter()->emitIns_Ty_I(INS_try_table, WasmValueType::Invalid, 1);
// Post-catch continuation dispatch block is the true target.
// False target should be the next block.
//
assert(block->GetFalseTarget() == block->Next());
BasicBlock* const target = block->GetTrueTarget();
unsigned depth = findTargetDepth(target);
GetEmitter()->emitIns_J(INS_catch_ref, EA_4BYTE, depth, target);
}
else
{
assert(interval->IsBlock());
bool isTryWrapper = false;
#if FALSE
// TODO-WASM: block sig when we emit catch_ref
// If this interval exactly wraps a try, it represents the branch to the
// catch handlers. We need to emit an exnref block sig
//
// (TODO, perhaps ... detect this earlier and make it an interval property)
if ((wasmCursor + 1) < m_compiler->fgWasmIntervals->size())
{
WasmInterval* nextInterval = m_compiler->fgWasmIntervals->at(wasmCursor + 1);
if (nextInterval->IsTry())
{
// we should always see a wrapping block because of the
// control flow added by fgWasmEhFlow
//
if ((nextInterval->Start() == interval->Start()) && (nextInterval->End() == interval->End()))
{
isTryWrapper = true;
}
else
{
assert(!"Expected block to wrap the try");
}
}
}
#endif
if (isTryWrapper)
{
GetEmitter()->emitIns_BlockTy(INS_block, WasmValueType::ExnRef);
}
else
{
GetEmitter()->emitIns_BlockTy(INS_block);
}
}
wasmCursor++;
wasmControlFlowStack->Push(interval);
if (interval->IsLoop())
{
if (!block->HasFlag(BBF_HAS_LABEL))
{
block->SetFlags(BBF_HAS_LABEL);
genDefineTempLabel(block);
}
}
else
{
BasicBlock* const endBlock = m_compiler->fgIndexToBlockMap[interval->End()];
if (!endBlock->HasFlag(BBF_HAS_LABEL))
{
endBlock->SetFlags(BBF_HAS_LABEL);
genDefineTempLabel(endBlock);
}
}
if (wasmCursor >= m_compiler->fgWasmIntervals->size())
{
break;
}
interval = m_compiler->fgWasmIntervals->at(wasmCursor);
chain = interval->Chain();
}
}
}
//------------------------------------------------------------------------
// WasmProduceReg: Produce a register and update liveness for an emitted node.
//
// Wrapper over "genProduceReg". Does two additional things:
// 1. Emits "local.tee"s for nodes that produce temporary registers so that
// they can be used multiple times.
// 2. Emits "drop" for unused values.
//
// Arguments:
// node - The emitted node
//
void CodeGen::WasmProduceReg(GenTree* node)
{
assert(!genIsRegCandidateLocal(node)); // Candidate liveness is handled in "genConsumeReg".
if (genIsValidReg(node->GetRegNum()))
{
GetEmitter()->emitIns_I(INS_local_tee, emitActualTypeSize(node), WasmRegToIndex(node->GetRegNum()));
}
genProduceReg(node);
if (node->IsUnusedValue())
{
GetEmitter()->emitIns(INS_drop);
}
}
//------------------------------------------------------------------------
// GetMultiUseOperandReg: Get the register of a multi-use operand.
//
// If the operand is a candidate, we use that candidate's current register.
// Otherwise it must have been allocated into a temporary register initialized
// in 'WasmProduceReg'. To do this, call SetMultiplyUsed(treeNode) during
// lowering and ensure that regalloc is updated to call 'ConsumeTemporaryRegForOperand'
// on the node(s) that need to be used multiple times.
//
// Arguments:
// operand - The operand node
//
// Return Value:
// The register to use for 'operand'.
//
regNumber CodeGen::GetMultiUseOperandReg(GenTree* operand)
{
if (genIsRegCandidateLocal(operand))
{
LclVarDsc* varDsc = m_compiler->lvaGetDesc(operand->AsLclVar());
assert(varDsc->lvIsInReg());
return varDsc->GetRegNum();
}
regNumber reg = operand->GetRegNum();
assert(genIsValidReg(reg));
return reg;
}
//------------------------------------------------------------------------
// genCodeForTreeNode: codegen for a particular tree node
//
// Arguments:
// treeNode - node to generate code for
//
void CodeGen::genCodeForTreeNode(GenTree* treeNode)
{
#ifdef DEBUG
lastConsumedNode = nullptr;
if (m_compiler->verbose)
{
m_compiler->gtDispLIRNode(treeNode, "Generating: ");
}
#endif // DEBUG
assert(!treeNode->IsReuseRegVal()); // TODO-WASM-CQ: enable.
// Contained nodes are part of the parent for codegen purposes.
if (treeNode->isContained())
{
return;
}
switch (treeNode->OperGet())
{
case GT_ADD:
case GT_SUB:
case GT_MUL:
case GT_OR:
case GT_XOR:
case GT_AND:
genCodeForBinary(treeNode->AsOp());
break;
case GT_DIV:
case GT_MOD:
case GT_UDIV:
case GT_UMOD:
genCodeForDivMod(treeNode->AsOp());
break;
case GT_LSH:
case GT_RSH:
case GT_RSZ:
case GT_ROL:
case GT_ROR:
genCodeForShift(treeNode);
break;
case GT_EQ:
case GT_NE:
case GT_LT:
case GT_LE:
case GT_GE:
case GT_GT:
genCodeForCompare(treeNode->AsOp());
break;
case GT_LCL_ADDR:
genCodeForLclAddr(treeNode->AsLclFld());
break;
case GT_LCL_FLD:
genCodeForLclFld(treeNode->AsLclFld());
break;
case GT_LCL_VAR:
genCodeForLclVar(treeNode->AsLclVar());
break;
case GT_STORE_LCL_VAR:
genCodeForStoreLclVar(treeNode->AsLclVar());
break;
case GT_PHYSREG:
genCodeForPhysReg(treeNode->AsPhysReg());
break;
case GT_JTRUE:
genCodeForJTrue(treeNode->AsOp());
break;
case GT_SWITCH:
genTableBasedSwitch(treeNode);
break;
case GT_RETURN:
case GT_RETFILT:
genReturn(treeNode);
break;
case GT_IL_OFFSET:
// Do nothing; this node is a marker for debug info.
break;
case GT_NOP:
break;
case GT_NO_OP:
instGen(INS_nop);
break;
case GT_CNS_INT:
case GT_CNS_LNG:
case GT_CNS_DBL:
genCodeForConstant(treeNode);
break;
case GT_CAST:
genCodeForCast(treeNode->AsOp());
break;
case GT_BITCAST:
genCodeForBitCast(treeNode->AsOp());
break;
case GT_NEG:
case GT_NOT:
genCodeForNegNot(treeNode->AsOp());
break;
case GT_IND:
genCodeForIndir(treeNode->AsIndir());
break;
case GT_STOREIND:
genCodeForStoreInd(treeNode->AsStoreInd());
break;
case GT_CALL:
genCall(treeNode->AsCall());
break;
case GT_NULLCHECK:
genCodeForNullCheck(treeNode->AsIndir());
break;
case GT_BOUNDS_CHECK:
genRangeCheck(treeNode);
break;
case GT_KEEPALIVE:
// TODO-WASM-RA: remove KEEPALIVE after we've produced the GC info.
genConsumeRegs(treeNode->AsOp()->gtOp1);
GetEmitter()->emitIns(INS_drop);
break;
case GT_LCLHEAP:
genLclHeap(treeNode);
break;
case GT_INDEX_ADDR:
genCodeForIndexAddr(treeNode->AsIndexAddr());
break;
case GT_LEA:
genLeaInstruction(treeNode->AsAddrMode());
break;
case GT_STORE_BLK:
genCodeForStoreBlk(treeNode->AsBlk());
break;
case GT_MEMORYBARRIER:
// No-op for single-threaded wasm.
assert(!WASM_THREAD_SUPPORT);
JITDUMP("Ignoring GT_MEMORYBARRIER; single-threaded codegen\n");
break;
case GT_INTRINSIC:
genIntrinsic(treeNode->AsIntrinsic());
break;
case GT_WASM_JEXCEPT:
// no codegen needed here.
break;
case GT_WASM_THROW_REF:
// TODO-WASM: enable when we emit catch_ref instead of catch_all
// GetEmitter()->emitIns(INS_throw_ref);
GetEmitter()->emitIns(INS_unreachable);
break;
case GT_CATCH_ARG:
genCatchArg(treeNode);
break;
default:
#ifdef DEBUG
if (JitConfig.JitWasmNyiToR2RUnsupported())
{
NYI_WASM("Opcode not implemented");
}
NYIRAW(GenTree::OpName(treeNode->OperGet()));
#else
NYI_WASM("Opcode not implemented");
#endif
break;
}
}
//------------------------------------------------------------------------
// genCodeForJTrue: emit Wasm br_if
//
// Arguments:
// treeNode - predicate value
//
void CodeGen::genCodeForJTrue(GenTreeOp* jtrue)
{
BasicBlock* const block = m_compiler->compCurBB;
assert(block->KindIs(BBJ_COND));
genConsumeOperands(jtrue);
BasicBlock* const trueTarget = block->GetTrueTarget();
BasicBlock* const falseTarget = block->GetFalseTarget();
// We don't expect degenerate BBJ_COND
//
assert(trueTarget != falseTarget);
// We don't expect the true target to be the next block.
//
assert(trueTarget != block->Next());
// br_if for true target
//
inst_JMP(EJ_jmpif, trueTarget);
// br for false target, if not fallthrough
//
if (falseTarget != block->Next())
{
inst_JMP(EJ_jmp, falseTarget);
}
}
//------------------------------------------------------------------------
// genTableBasedSwitch: emit Wasm br_table
//
// Arguments:
// treeNode - value to switch on
//
void CodeGen::genTableBasedSwitch(GenTree* treeNode)
{
BasicBlock* const block = m_compiler->compCurBB;
assert(block->KindIs(BBJ_SWITCH));
genConsumeOperands(treeNode->AsOp());
BBswtDesc* const desc = block->GetSwitchTargets();
unsigned const caseCount = desc->GetCaseCount();
// We don't expect degenerate or default-less switches
//
assert(caseCount > 0);
assert(desc->HasDefaultCase());
// br_table list (labelidx*) labelidx
// list is prefixed with length, which is caseCount - 1
//
GetEmitter()->emitIns_I(INS_br_table, EA_4BYTE, caseCount - 1);
// Emit the list case targets, then default case target
// (which is always the last case in the desc).
//
for (unsigned caseNum = 0; caseNum < caseCount; caseNum++)
{
BasicBlock* const caseTarget = desc->GetCase(caseNum)->getDestinationBlock();
unsigned depth = findTargetDepth(caseTarget);
GetEmitter()->emitIns_J(INS_label, EA_4BYTE, depth, caseTarget);
}
}
//------------------------------------------------------------------------
// genCatchArg: emit code for GT_CATCH_ARG
//
// Arguments:
// treeNode - catch arg node
//
void CodeGen::genCatchArg(GenTree* treeNode)
{
assert(treeNode->OperIs(GT_CATCH_ARG));
// The catch arg is passed as the 3rd parameter, so has Wasm local index 2.
GetEmitter()->emitIns_I(INS_local_get, EA_GCREF, 2);
WasmProduceReg(treeNode);
}
//------------------------------------------------------------------------
// PackOperAndType: Pack a genTreeOps and var_types into a uint32_t
//
// Arguments:
// oper - a genTreeOps to pack
// type - a var_types to pack
//
// Return Value:
// oper and type packed into an integer that can be used as a switch value/case
//
static constexpr uint32_t PackOperAndType(genTreeOps oper, var_types type)
{
if ((type == TYP_BYREF) || (type == TYP_REF))
{
type = TYP_I_IMPL;
}
const int shift1 = ConstLog2<TYP_COUNT>::value + 1;
return ((uint32_t)oper << shift1) | ((uint32_t)type);
}
// ------------------------------------------------------------------------
// PackTypes: Pack two var_types together into a uint32_t
// Arguments:
// toType - a var_types to pack
// fromType - a var_types to pack
//
// Return Value:
// The two types packed together into an integer that can be used as a switch/value,
// the primary use case being the handling of operations with two-type variants such
// as casts.
//