forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelperexpansion.cpp
2898 lines (2506 loc) · 115 KB
/
helperexpansion.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
// 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"
#include <minipal/utf8.h>
#ifdef _MSC_VER
#pragma hdrstop
#endif
// Save expression to a local and append it as the last statement in exprBlock
static GenTree* SpillExpression(Compiler* comp, GenTree* expr, BasicBlock* exprBlock, DebugInfo& debugInfo)
{
unsigned const tmpNum = comp->lvaGrabTemp(true DEBUGARG("spilling expr"));
Statement* stmt = comp->fgNewStmtAtEnd(exprBlock, comp->gtNewTempStore(tmpNum, expr), debugInfo);
comp->gtSetStmtInfo(stmt);
comp->fgSetStmtSeq(stmt);
return comp->gtNewLclVarNode(tmpNum);
};
//------------------------------------------------------------------------------
// SplitAtTreeAndReplaceItWithLocal : Split block at the given tree and replace it with a local
// See comments in gtSplitTree and fgSplitBlockBeforeTree
// TODO: use this function in more places in this file.
//
// Arguments:
// comp - Compiler instance
// block - Block to split
// stmt - Statement containing the tree to split at
// tree - Tree to split at
// topBlock - [out] Top block after the split
// bottomBlock - [out] Bottom block after the split
//
// Return Value:
// Number of the local that replaces the tree
//
static unsigned SplitAtTreeAndReplaceItWithLocal(
Compiler* comp, BasicBlock* block, Statement* stmt, GenTree* tree, BasicBlock** topBlock, BasicBlock** bottomBlock)
{
BasicBlock* prevBb = block;
GenTree** callUse = nullptr;
Statement* newFirstStmt = nullptr;
block = comp->fgSplitBlockBeforeTree(block, stmt, tree, &newFirstStmt, &callUse);
assert(prevBb != nullptr && block != nullptr);
// Block ops inserted by the split need to be morphed here since we are after morph.
// We cannot morph stmt yet as we may modify it further below, and the morphing
// could invalidate callUse
while ((newFirstStmt != nullptr) && (newFirstStmt != stmt))
{
comp->fgMorphStmtBlockOps(block, newFirstStmt);
newFirstStmt = newFirstStmt->GetNextStmt();
}
// Grab a temp to store the result.
const unsigned tmpNum = comp->lvaGrabTemp(true DEBUGARG("replacement local"));
comp->lvaTable[tmpNum].lvType = tree->TypeGet();
// Replace the original call with that temp
*callUse = comp->gtNewLclvNode(tmpNum, tree->TypeGet());
comp->fgMorphStmtBlockOps(block, stmt);
comp->gtUpdateStmtSideEffects(stmt);
*topBlock = prevBb;
*bottomBlock = block;
return tmpNum;
}
//------------------------------------------------------------------------------
// gtNewRuntimeLookupHelperCallNode : Helper to create a runtime lookup call helper node.
//
// Arguments:
// helper - Call helper
// type - Type of the node
// args - Call args
//
// Return Value:
// New CT_HELPER node
//
GenTreeCall* Compiler::gtNewRuntimeLookupHelperCallNode(CORINFO_RUNTIME_LOOKUP* pRuntimeLookup,
GenTree* ctxTree,
void* compileTimeHandle)
{
// Call the helper
// - Setup argNode with the pointer to the signature returned by the lookup
GenTree* argNode = gtNewIconEmbHndNode(pRuntimeLookup->signature, nullptr, GTF_ICON_GLOBAL_PTR, compileTimeHandle);
GenTreeCall* helperCall = gtNewHelperCallNode(pRuntimeLookup->helper, TYP_I_IMPL, ctxTree, argNode);
// No need to perform CSE/hoisting for signature node - it is expected to end up in a rarely-taken block after
// "Expand runtime lookups" phase.
argNode->gtFlags |= GTF_DONT_CSE;
// Leave a note that this method has runtime lookups we might want to expand (nullchecks, size checks) later.
// We can also consider marking current block as a runtime lookup holder to improve TP for Tier0
impInlineRoot()->setMethodHasExpRuntimeLookup();
if (!impInlineRoot()->GetSignatureToLookupInfoMap()->Lookup(pRuntimeLookup->signature))
{
JITDUMP("Registering %p in SignatureToLookupInfoMap\n", pRuntimeLookup->signature)
impInlineRoot()->GetSignatureToLookupInfoMap()->Set(pRuntimeLookup->signature, *pRuntimeLookup);
}
return helperCall;
}
//------------------------------------------------------------------------------
// fgExpandRuntimeLookups : partially expand runtime lookups helper calls
// to add a nullcheck [+ size check] and a fast path
// Returns:
// PhaseStatus indicating what, if anything, was changed.
//
// Notes:
// The runtime lookup itself is needed to access a handle in code shared between
// generic instantiations. The lookup depends on the typeContext which is only available at
// runtime, and not at compile - time. See ASCII block diagrams in comments below for
// better understanding how this phase expands runtime lookups.
//
PhaseStatus Compiler::fgExpandRuntimeLookups()
{
PhaseStatus result = PhaseStatus::MODIFIED_NOTHING;
if (!doesMethodHaveExpRuntimeLookup())
{
// The method being compiled doesn't have expandable runtime lookups. If it does
// and doesMethodHaveExpRuntimeLookup() still returns false we'll assert in LowerCall
return result;
}
return fgExpandHelper<&Compiler::fgExpandRuntimeLookupsForCall>(false);
}
//------------------------------------------------------------------------------
// fgExpandRuntimeLookupsForCall : partially expand runtime lookups helper calls
// to add a nullcheck [+ size check] and a fast path
//
// Arguments:
// pBlock - Block containing the helper call to expand. If expansion is performed,
// this is updated to the new block that was an outcome of block splitting.
// stmt - Statement containing the helper call
// call - The helper call
//
// Returns:
// true if a runtime lookup was found and expanded.
//
// Notes:
// The runtime lookup itself is needed to access a handle in code shared between
// generic instantiations. The lookup depends on the typeContext which is only available at
// runtime, and not at compile - time. See ASCII block diagrams in comments below for
// better understanding how this phase expands runtime lookups.
//
bool Compiler::fgExpandRuntimeLookupsForCall(BasicBlock** pBlock, Statement* stmt, GenTreeCall* call)
{
BasicBlock* block = *pBlock;
if (!call->IsRuntimeLookupHelperCall(this))
{
return false;
}
INDEBUG(call->gtCallDebugFlags |= GTF_CALL_MD_RUNTIME_LOOKUP_EXPANDED);
if (call->IsTailCall())
{
// It is very unlikely to happen and is impossible to represent in C#
return false;
}
assert(call->gtArgs.CountArgs() == 2);
// The call has the following signature:
//
// type = call(genericCtx, signatureCns);
//
const GenTree* signatureNode = call->gtArgs.GetArgByIndex(1)->GetNode();
if (!signatureNode->IsCnsIntOrI())
{
// We expect the signature to be a constant node here (it's marked as DONT_CSE)
// It's still correct if JIT decides to violate this assumption, but we really
// don't want it to happen, hence, the assert.
assert(!"can't restore signature argument value");
return false;
}
void* signature = reinterpret_cast<void*>(signatureNode->AsIntCon()->IconValue());
JITDUMP("Expanding runtime lookup for [%06d] in " FMT_BB ":\n", dspTreeID(call), block->bbNum)
DISPTREE(call)
JITDUMP("\n")
// Restore runtimeLookup using signature argument via a global dictionary
CORINFO_RUNTIME_LOOKUP runtimeLookup = {};
const bool lookupFound = GetSignatureToLookupInfoMap()->Lookup(signature, &runtimeLookup);
assert(lookupFound);
const bool needsSizeCheck = runtimeLookup.sizeOffset != CORINFO_NO_SIZE_CHECK;
if (needsSizeCheck)
{
JITDUMP("dynamic expansion, needs size check.\n")
}
DebugInfo debugInfo = stmt->GetDebugInfo();
assert(runtimeLookup.indirections != 0);
assert(runtimeLookup.testForNull);
// Split block right before the call tree
BasicBlock* prevBb = block;
GenTree** callUse = nullptr;
Statement* newFirstStmt = nullptr;
block = fgSplitBlockBeforeTree(block, stmt, call, &newFirstStmt, &callUse);
*pBlock = block;
assert(prevBb != nullptr && block != nullptr);
// Block ops inserted by the split need to be morphed here since we are after morph.
// We cannot morph stmt yet as we may modify it further below, and the morphing
// could invalidate callUse.
while ((newFirstStmt != nullptr) && (newFirstStmt != stmt))
{
fgMorphStmtBlockOps(block, newFirstStmt);
newFirstStmt = newFirstStmt->GetNextStmt();
}
GenTreeLclVar* rtLookupLcl = nullptr;
// Mostly for Tier0: if the current statement is STORE_LCL_VAR(RuntimeLookup)
// we can drop it and use that LCL as the destination
if (stmt->GetRootNode()->OperIs(GT_STORE_LCL_VAR) && (stmt->GetRootNode()->AsLclVar()->Data() == *callUse))
{
rtLookupLcl = gtNewLclVarNode(stmt->GetRootNode()->AsLclVar()->GetLclNum());
fgRemoveStmt(block, stmt);
}
// Grab a temp to store result (it's assigned from either fastPathBb or fallbackBb)
if (rtLookupLcl == nullptr)
{
// Define a local for the result
unsigned rtLookupLclNum = lvaGrabTemp(true DEBUGARG("runtime lookup"));
lvaTable[rtLookupLclNum].lvType = TYP_I_IMPL;
rtLookupLcl = gtNewLclvNode(rtLookupLclNum, call->TypeGet());
*callUse = gtClone(rtLookupLcl);
fgMorphStmtBlockOps(block, stmt);
gtUpdateStmtSideEffects(stmt);
}
GenTree* ctxTree = call->gtArgs.GetArgByIndex(0)->GetNode();
GenTree* sigNode = call->gtArgs.GetArgByIndex(1)->GetNode();
// Prepare slotPtr tree (TODO: consider sharing this part with impRuntimeLookup)
GenTree* slotPtrTree = gtCloneExpr(ctxTree);
GenTree* indOffTree = nullptr;
GenTree* lastIndOfTree = nullptr;
for (WORD i = 0; i < runtimeLookup.indirections; i++)
{
if ((i == 1 && runtimeLookup.indirectFirstOffset) || (i == 2 && runtimeLookup.indirectSecondOffset))
{
indOffTree = SpillExpression(this, slotPtrTree, prevBb, debugInfo);
slotPtrTree = gtCloneExpr(indOffTree);
}
// The last indirection could be subject to a size check (dynamic dictionary expansion)
const bool isLastIndirectionWithSizeCheck = (i == runtimeLookup.indirections - 1) && needsSizeCheck;
if (i != 0)
{
GenTreeFlags indirFlags = GTF_IND_NONFAULTING;
if (!isLastIndirectionWithSizeCheck)
{
indirFlags |= GTF_IND_INVARIANT;
}
slotPtrTree = gtNewIndir(TYP_I_IMPL, slotPtrTree, indirFlags);
}
if ((i == 1 && runtimeLookup.indirectFirstOffset) || (i == 2 && runtimeLookup.indirectSecondOffset))
{
slotPtrTree = gtNewOperNode(GT_ADD, TYP_I_IMPL, indOffTree, slotPtrTree);
}
if (runtimeLookup.offsets[i] != 0)
{
if (isLastIndirectionWithSizeCheck)
{
lastIndOfTree = SpillExpression(this, slotPtrTree, prevBb, debugInfo);
slotPtrTree = gtCloneExpr(lastIndOfTree);
}
slotPtrTree =
gtNewOperNode(GT_ADD, TYP_I_IMPL, slotPtrTree, gtNewIconNode(runtimeLookup.offsets[i], TYP_I_IMPL));
}
}
// Non-dynamic expansion case (no size check):
//
// prevBb(BBJ_ALWAYS): [weight: 1.0]
// ...
//
// nullcheckBb(BBJ_COND): [weight: 1.0]
// if (*fastPathValue == null)
// goto fallbackBb;
//
// fastPathBb(BBJ_ALWAYS): [weight: 0.8]
// rtLookupLcl = *fastPathValue;
// goto block;
//
// fallbackBb(BBJ_ALWAYS): [weight: 0.2]
// rtLookupLcl = HelperCall();
//
// block(...): [weight: 1.0]
// use(rtLookupLcl);
//
// null-check basic block
GenTree* fastPathValue = gtNewIndir(TYP_I_IMPL, gtCloneExpr(slotPtrTree), GTF_IND_NONFAULTING);
// Save dictionary slot to a local (to be used by fast path)
GenTree* fastPathValueClone = fgMakeMultiUse(&fastPathValue);
GenTree* nullcheckOp = gtNewOperNode(GT_EQ, TYP_INT, fastPathValue, gtNewIconNode(0, TYP_I_IMPL));
nullcheckOp->gtFlags |= GTF_RELOP_JMP_USED;
// nullcheckBb conditionally jumps to fallbackBb, but we need to initialize fallbackBb last
// so we can place it after nullcheckBb. So set the jump target later.
BasicBlock* nullcheckBb =
fgNewBBFromTreeAfter(BBJ_COND, prevBb, gtNewOperNode(GT_JTRUE, TYP_VOID, nullcheckOp), debugInfo);
// Fallback basic block
GenTree* fallbackValueDef = gtNewStoreLclVarNode(rtLookupLcl->GetLclNum(), call);
BasicBlock* fallbackBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, nullcheckBb, fallbackValueDef, debugInfo, true);
// Fast-path basic block
GenTree* fastpathValueDef = gtNewStoreLclVarNode(rtLookupLcl->GetLclNum(), fastPathValueClone);
BasicBlock* fastPathBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, nullcheckBb, fastpathValueDef, debugInfo);
BasicBlock* sizeCheckBb = nullptr;
if (needsSizeCheck)
{
// Dynamic expansion case (sizeCheckBb is added and some preds are changed):
//
// prevBb(BBJ_ALWAYS): [weight: 1.0]
//
// sizeCheckBb(BBJ_COND): [weight: 1.0]
// if (sizeValue <= offsetValue)
// goto fallbackBb;
// ...
//
// nullcheckBb(BBJ_COND): [weight: 0.8]
// if (*fastPathValue == null)
// goto fallbackBb;
//
// fastPathBb(BBJ_ALWAYS): [weight: 0.64]
// rtLookupLcl = *fastPathValue;
// goto block;
//
// fallbackBb(BBJ_ALWAYS): [weight: 0.36]
// rtLookupLcl = HelperCall();
//
// block(...): [weight: 1.0]
// use(rtLookupLcl);
//
// sizeValue = dictionary[pRuntimeLookup->sizeOffset]
GenTreeIntCon* sizeOffset = gtNewIconNode(runtimeLookup.sizeOffset, TYP_I_IMPL);
assert(lastIndOfTree != nullptr);
GenTree* sizeValueOffset = gtNewOperNode(GT_ADD, TYP_I_IMPL, lastIndOfTree, sizeOffset);
GenTree* sizeValue = gtNewIndir(TYP_I_IMPL, sizeValueOffset, GTF_IND_NONFAULTING);
// sizeCheck fails if sizeValue <= pRuntimeLookup->offsets[i]
GenTree* offsetValue = gtNewIconNode(runtimeLookup.offsets[runtimeLookup.indirections - 1], TYP_I_IMPL);
GenTree* sizeCheck = gtNewOperNode(GT_LE, TYP_INT, sizeValue, offsetValue);
sizeCheck->gtFlags |= GTF_RELOP_JMP_USED;
GenTree* jtrue = gtNewOperNode(GT_JTRUE, TYP_VOID, sizeCheck);
// sizeCheckBb fails - jump to fallbackBb
sizeCheckBb = fgNewBBFromTreeAfter(BBJ_COND, prevBb, jtrue, debugInfo);
}
//
// Update preds in all new blocks
//
assert(prevBb->KindIs(BBJ_ALWAYS));
{
FlowEdge* const newEdge = fgAddRefPred(block, fastPathBb);
fastPathBb->SetTargetEdge(newEdge);
}
{
FlowEdge* const newEdge = fgAddRefPred(block, fallbackBb);
fallbackBb->SetTargetEdge(newEdge);
assert(fallbackBb->JumpsToNext());
}
if (needsSizeCheck)
{
// sizeCheckBb is the first block after prevBb
fgRedirectTargetEdge(prevBb, sizeCheckBb);
// sizeCheckBb flows into nullcheckBb in case if the size check passes
{
FlowEdge* const trueEdge = fgAddRefPred(fallbackBb, sizeCheckBb);
FlowEdge* const falseEdge = fgAddRefPred(nullcheckBb, sizeCheckBb);
sizeCheckBb->SetTrueEdge(trueEdge);
sizeCheckBb->SetFalseEdge(falseEdge);
trueEdge->setLikelihood(0.2);
falseEdge->setLikelihood(0.8);
}
// fallbackBb is reachable from both nullcheckBb and sizeCheckBb
// fastPathBb is only reachable from successful nullcheckBb
}
else
{
// nullcheckBb is the first block after prevBb
fgRedirectTargetEdge(prevBb, nullcheckBb);
// No size check, nullcheckBb jumps to fast path
// fallbackBb is only reachable from nullcheckBb (jump destination)
}
FlowEdge* const trueEdge = fgAddRefPred(fallbackBb, nullcheckBb);
FlowEdge* const falseEdge = fgAddRefPred(fastPathBb, nullcheckBb);
nullcheckBb->SetTrueEdge(trueEdge);
nullcheckBb->SetFalseEdge(falseEdge);
trueEdge->setLikelihood(0.2);
falseEdge->setLikelihood(0.8);
//
// Re-distribute weights (see '[weight: X]' on the diagrams above)
// TODO: consider marking fallbackBb as rarely-taken
// TODO: derive block weights from edge likelihoods.
//
block->inheritWeight(prevBb);
if (needsSizeCheck)
{
sizeCheckBb->inheritWeight(prevBb);
// 80% chance we pass nullcheck
nullcheckBb->inheritWeightPercentage(sizeCheckBb, 80);
// 64% (0.8 * 0.8) chance we pass both nullcheck and sizecheck
fastPathBb->inheritWeightPercentage(nullcheckBb, 80);
// 100-64=36% chance we fail either nullcheck or sizecheck
fallbackBb->inheritWeightPercentage(sizeCheckBb, 36);
}
else
{
nullcheckBb->inheritWeight(prevBb);
// 80% chance we pass nullcheck
fastPathBb->inheritWeightPercentage(nullcheckBb, 80);
// 20% chance we fail nullcheck (TODO: Consider making it cold (0%))
fallbackBb->inheritWeightPercentage(nullcheckBb, 20);
}
// All blocks are expected to be in the same EH region
assert(BasicBlock::sameEHRegion(prevBb, block));
assert(BasicBlock::sameEHRegion(prevBb, nullcheckBb));
assert(BasicBlock::sameEHRegion(prevBb, fastPathBb));
if (needsSizeCheck)
{
assert(BasicBlock::sameEHRegion(prevBb, sizeCheckBb));
}
return true;
}
//------------------------------------------------------------------------------
// fgExpandThreadLocalAccess: Inline the CORINFO_HELP_GETDYNAMIC_NONGCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED,
// CORINFO_HELP_GETDYNAMIC_GCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED, or
// CORINFO_HELP_GETDYNAMIC_GCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED2 helper. See
// fgExpandThreadLocalAccessForCall for details.
//
// Returns:
// PhaseStatus indicating what, if anything, was changed.
//
PhaseStatus Compiler::fgExpandThreadLocalAccess()
{
PhaseStatus result = PhaseStatus::MODIFIED_NOTHING;
if (!methodHasTlsFieldAccess())
{
// TP: nothing to expand in the current method
JITDUMP("Nothing to expand.\n")
return result;
}
// Always expand for NativeAOT because the slow TLS access helper will not be generated by NativeAOT
const bool isNativeAOT = IsTargetAbi(CORINFO_NATIVEAOT_ABI);
if (isNativeAOT)
{
return fgExpandHelper<&Compiler::fgExpandThreadLocalAccessForCallNativeAOT>(
false /* expand rarely run blocks for NativeAOT */);
}
if (opts.OptimizationDisabled())
{
JITDUMP("Optimizations aren't allowed - bail out.\n")
return result;
}
// TODO: Replace with opts.compCodeOpt once it's fixed
const bool preferSize = opts.jitFlags->IsSet(JitFlags::JIT_FLAG_SIZE_OPT);
if (preferSize)
{
// The optimization comes with a codegen size increase
JITDUMP("Optimized for size - bail out.\n")
return result;
}
return fgExpandHelper<&Compiler::fgExpandThreadLocalAccessForCall>(true);
}
//------------------------------------------------------------------------------
// fgExpandThreadLocalAccessForCallNativeAOT : Expand the access of tlsRoot needed
// to access fields marked with [ThreadLocal].
//
// Arguments:
// pBlock - Block containing the helper call to expand. If expansion is performed,
// this is updated to the new block that was an outcome of block splitting.
// stmt - Statement containing the helper call
// call - The helper call
//
//
// Returns:
// true if we expanded any field access, false otherwise.
//
bool Compiler::fgExpandThreadLocalAccessForCallNativeAOT(BasicBlock** pBlock, Statement* stmt, GenTreeCall* call)
{
assert(IsTargetAbi(CORINFO_NATIVEAOT_ABI));
BasicBlock* block = *pBlock;
CorInfoHelpFunc helper = call->GetHelperNum();
const bool isExpTLSFieldAccess = (helper == CORINFO_HELP_READYTORUN_THREADSTATIC_BASE_NOCTOR);
if (!call->IsHelperCall() || !isExpTLSFieldAccess)
{
return false;
}
JITDUMP("Expanding thread static local access for [%06d] in " FMT_BB ":\n", dspTreeID(call), block->bbNum);
DISPTREE(call);
JITDUMP("\n");
CORINFO_THREAD_STATIC_INFO_NATIVEAOT threadStaticInfo;
memset(&threadStaticInfo, 0, sizeof(CORINFO_THREAD_STATIC_INFO_NATIVEAOT));
info.compCompHnd->getThreadLocalStaticInfo_NativeAOT(&threadStaticInfo);
JITDUMP("tlsRootObject= %p\n", dspPtr(threadStaticInfo.tlsRootObject.addr));
JITDUMP("tlsIndexObject= %p\n", dspPtr(threadStaticInfo.tlsIndexObject.addr));
JITDUMP("offsetOfThreadLocalStoragePointer= %u\n", dspOffset(threadStaticInfo.offsetOfThreadLocalStoragePointer));
JITDUMP("threadStaticBaseSlow= %p\n", dspPtr(threadStaticInfo.threadStaticBaseSlow.addr));
// Split block right before the call tree
BasicBlock* prevBb = block;
GenTree** callUse = nullptr;
Statement* newFirstStmt = nullptr;
DebugInfo debugInfo = stmt->GetDebugInfo();
block = fgSplitBlockBeforeTree(block, stmt, call, &newFirstStmt, &callUse);
*pBlock = block;
var_types callType = call->TypeGet();
assert(prevBb != nullptr && block != nullptr);
unsigned finalLclNum = lvaGrabTemp(true DEBUGARG("Final offset"));
// Note, `tlsRoot` refers to the TLS blob object, which is an unpinned managed object,
// thus the type of the local is TYP_REF
lvaTable[finalLclNum].lvType = TYP_REF;
GenTree* finalLcl = gtNewLclVarNode(finalLclNum);
// Block ops inserted by the split need to be morphed here since we are after morph.
// We cannot morph stmt yet as we may modify it further below, and the morphing
// could invalidate callUse.
while ((newFirstStmt != nullptr) && (newFirstStmt != stmt))
{
fgMorphStmtBlockOps(block, newFirstStmt);
newFirstStmt = newFirstStmt->GetNextStmt();
}
#ifdef TARGET_64BIT
// prevBb (BBJ_NONE): [weight: 1.0]
// ...
//
// tlsRootNullCondBB (BBJ_COND): [weight: 1.0]
// fastPathValue = [tlsRootAddress]
// if (fastPathValue != nullptr)
// goto fastPathBb;
//
// fallbackBb (BBJ_ALWAYS): [weight: 0]
// tlsRoot = HelperCall();
// goto block;
//
// fastPathBb(BBJ_ALWAYS): [weight: 1.0]
// tlsRoot = fastPathValue;
//
// block (...): [weight: 1.0]
// use(tlsRoot);
// ...
GenTree* tlsRootAddr = nullptr;
CORINFO_GENERIC_HANDLE tlsRootObject = threadStaticInfo.tlsRootObject.handle;
if (TargetOS::IsWindows)
{
// Mark this ICON as a TLS_HDL, codegen will use FS:[cns] or GS:[cns]
GenTree* tlsValue = gtNewIconHandleNode(threadStaticInfo.offsetOfThreadLocalStoragePointer, GTF_ICON_TLS_HDL);
tlsValue = gtNewIndir(TYP_I_IMPL, tlsValue, GTF_IND_NONFAULTING | GTF_IND_INVARIANT);
CORINFO_CONST_LOOKUP tlsIndexObject = threadStaticInfo.tlsIndexObject;
GenTree* dllRef = gtNewIconHandleNode((size_t)tlsIndexObject.handle, GTF_ICON_CONST_PTR);
dllRef = gtNewIndir(TYP_INT, dllRef, GTF_IND_NONFAULTING | GTF_IND_INVARIANT);
dllRef = gtNewCastNode(TYP_I_IMPL, dllRef, true, TYP_I_IMPL);
dllRef = gtNewOperNode(GT_LSH, TYP_I_IMPL, dllRef, gtNewIconNode(3, TYP_I_IMPL));
// Add the dllRef to produce thread local storage reference for coreclr
tlsValue = gtNewOperNode(GT_ADD, TYP_I_IMPL, tlsValue, dllRef);
// Base of coreclr's thread local storage
tlsValue = gtNewIndir(TYP_I_IMPL, tlsValue, GTF_IND_NONFAULTING | GTF_IND_INVARIANT);
// This resolves to an offset which is TYP_INT
GenTree* tlsRootOffset = gtNewIconNode((size_t)tlsRootObject, TYP_INT);
tlsRootOffset->gtFlags |= GTF_ICON_SECREL_OFFSET;
// Add the tlsValue and tlsRootOffset to produce tlsRootAddr.
tlsRootAddr = gtNewOperNode(GT_ADD, TYP_I_IMPL, tlsValue, tlsRootOffset);
}
else if (TargetOS::IsUnix)
{
if (TargetArchitecture::IsX64)
{
// Code sequence to access thread local variable on linux/x64:
// data16
// lea rdi, 0x7FE5C418CD28 ; tlsRootObject
// data16 data16
// call _tls_get_addr
//
// This sequence along with `data16` prefix is expected by the linker so it
// will patch these with TLS access.
GenTree* tls_get_addr_val =
gtNewIconHandleNode((size_t)threadStaticInfo.tlsGetAddrFtnPtr.handle, GTF_ICON_FTN_ADDR);
tls_get_addr_val->SetContained();
GenTreeCall* tlsRefCall = gtNewIndCallNode(tls_get_addr_val, TYP_I_IMPL);
tlsRefCall->gtFlags |= GTF_TLS_GET_ADDR;
// This is an indirect call which takes an argument.
// Populate and set the ABI appropriately.
assert(tlsRootObject != 0);
GenTree* tlsArg = gtNewIconNode((size_t)tlsRootObject, TYP_I_IMPL);
tlsArg->gtFlags |= GTF_ICON_TLSGD_OFFSET;
tlsRefCall->gtArgs.PushBack(this, NewCallArg::Primitive(tlsArg));
fgMorphArgs(tlsRefCall);
tlsRefCall->gtFlags |= GTF_EXCEPT | (tls_get_addr_val->gtFlags & GTF_GLOB_EFFECT);
tlsRootAddr = tlsRefCall;
}
else if (TargetArchitecture::IsArm64)
{
/*
x0 = adrp :tlsdesc:tlsRoot ; 1st parameter
x0 += tlsdesc_lo12:tlsRoot ; update 1st parameter
x1 = tpidr_el0 ; 2nd parameter
x2 = [x0] ; call
blr x2
*/
GenTree* tlsRootOffset = gtNewIconHandleNode((size_t)tlsRootObject, GTF_ICON_TLS_HDL);
tlsRootOffset->gtFlags |= GTF_ICON_TLSGD_OFFSET;
GenTree* tlsCallIndir = gtCloneExpr(tlsRootOffset);
GenTreeCall* tlsRefCall = gtNewIndCallNode(tlsCallIndir, TYP_I_IMPL);
tlsRefCall->gtFlags |= GTF_TLS_GET_ADDR;
fgMorphArgs(tlsRefCall);
tlsRefCall->gtFlags |= GTF_EXCEPT | (tlsCallIndir->gtFlags & GTF_GLOB_EFFECT);
tlsRootAddr = tlsRefCall;
}
else
{
unreached();
}
}
else
{
unreached();
}
// Cache the TlsRootAddr value
unsigned tlsRootAddrLclNum = lvaGrabTemp(true DEBUGARG("TlsRootAddr access"));
lvaTable[tlsRootAddrLclNum].lvType = TYP_I_IMPL;
GenTree* tlsRootAddrDef = gtNewStoreLclVarNode(tlsRootAddrLclNum, tlsRootAddr);
GenTree* tlsRootAddrUse = gtNewLclVarNode(tlsRootAddrLclNum);
// See comments near finalLclNum above regarding TYP_REF
GenTree* tlsRootVal = gtNewIndir(TYP_REF, tlsRootAddrUse, GTF_IND_NONFAULTING | GTF_IND_INVARIANT);
GenTree* tlsRootDef = gtNewStoreLclVarNode(finalLclNum, tlsRootVal);
GenTree* tlsRootNullCond = gtNewOperNode(GT_NE, TYP_INT, gtCloneExpr(finalLcl), gtNewIconNode(0, TYP_I_IMPL));
tlsRootNullCond = gtNewOperNode(GT_JTRUE, TYP_VOID, tlsRootNullCond);
// tlsRootNullCondBB
BasicBlock* tlsRootNullCondBB = fgNewBBFromTreeAfter(BBJ_COND, prevBb, tlsRootAddrDef, debugInfo);
fgInsertStmtAfter(tlsRootNullCondBB, tlsRootNullCondBB->firstStmt(), fgNewStmtFromTree(tlsRootNullCond));
fgInsertStmtAfter(tlsRootNullCondBB, tlsRootNullCondBB->firstStmt(), fgNewStmtFromTree(tlsRootDef));
CORINFO_CONST_LOOKUP threadStaticSlowHelper = threadStaticInfo.threadStaticBaseSlow;
// See comments near finalLclNum above regarding TYP_REF
GenTreeCall* slowHelper =
gtNewIndCallNode(gtNewIconHandleNode((size_t)threadStaticSlowHelper.addr, GTF_ICON_TLS_HDL), TYP_REF);
GenTree* helperArg = gtClone(tlsRootAddrUse);
slowHelper->gtArgs.PushBack(this, NewCallArg::Primitive(helperArg));
fgMorphArgs(slowHelper);
// fallbackBb
GenTree* fallbackValueDef = gtNewStoreLclVarNode(finalLclNum, slowHelper);
BasicBlock* fallbackBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, tlsRootNullCondBB, fallbackValueDef, debugInfo, true);
GenTree* fastPathValueDef = gtNewStoreLclVarNode(finalLclNum, gtCloneExpr(finalLcl));
BasicBlock* fastPathBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, fallbackBb, fastPathValueDef, debugInfo, true);
*callUse = finalLcl;
fgMorphStmtBlockOps(block, stmt);
gtUpdateStmtSideEffects(stmt);
//
// Update preds in all new blocks
//
FlowEdge* const trueEdge = fgAddRefPred(fastPathBb, tlsRootNullCondBB);
FlowEdge* const falseEdge = fgAddRefPred(fallbackBb, tlsRootNullCondBB);
tlsRootNullCondBB->SetTrueEdge(trueEdge);
tlsRootNullCondBB->SetFalseEdge(falseEdge);
trueEdge->setLikelihood(1.0);
falseEdge->setLikelihood(0.0);
{
FlowEdge* const newEdge = fgAddRefPred(block, fallbackBb);
fallbackBb->SetTargetEdge(newEdge);
}
{
FlowEdge* const newEdge = fgAddRefPred(block, fastPathBb);
fastPathBb->SetTargetEdge(newEdge);
}
// Inherit the weights
block->inheritWeight(prevBb);
tlsRootNullCondBB->inheritWeight(prevBb);
fastPathBb->inheritWeight(prevBb);
// fallback will just execute first time
fallbackBb->inheritWeightPercentage(tlsRootNullCondBB, 0);
fgRedirectTargetEdge(prevBb, tlsRootNullCondBB);
// All blocks are expected to be in the same EH region
assert(BasicBlock::sameEHRegion(prevBb, block));
assert(BasicBlock::sameEHRegion(prevBb, tlsRootNullCondBB));
assert(BasicBlock::sameEHRegion(prevBb, fastPathBb));
JITDUMP("tlsRootNullCondBB: " FMT_BB "\n", tlsRootNullCondBB->bbNum);
JITDUMP("fallbackBb: " FMT_BB "\n", fallbackBb->bbNum);
JITDUMP("fastPathBb: " FMT_BB "\n", fastPathBb->bbNum);
#else
unreached();
#endif // TARGET_64BIT
return true;
}
//------------------------------------------------------------------------------
// fgExpandThreadLocalAccessForCall : Expand the CORINFO_HELP_GETDYNAMIC_NONGCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED
// or CORINFO_HELP_GETDYNAMIC_GCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED, that access fields marked with [ThreadLocal].
//
// Arguments:
// pBlock - Block containing the helper call to expand. If expansion is performed,
// this is updated to the new block that was an outcome of block splitting.
// stmt - Statement containing the helper call
// call - The helper call
//
//
// Returns:
// true if we expanded any field access, false otherwise.
//
// Notes:
// A cache is stored in thread local storage (TLS) of coreclr. It maps the typeIndex (embedded in
// the code at the JIT time) to the base of static blocks. This method generates code to
// extract the TLS, get the entry at which the cache is stored. Then it checks if the typeIndex of
// enclosing type of current field is present in the cache and if yes, extract out that can be directly
// accessed at the uses.
// If the entry is not present, the helper is called, which would make an entry of current static block
// in the cache.
//
bool Compiler::fgExpandThreadLocalAccessForCall(BasicBlock** pBlock, Statement* stmt, GenTreeCall* call)
{
assert(!opts.IsReadyToRun());
BasicBlock* block = *pBlock;
CorInfoHelpFunc helper = call->GetHelperNum();
if ((helper != CORINFO_HELP_GETDYNAMIC_NONGCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED) &&
(helper != CORINFO_HELP_GETDYNAMIC_GCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED) &&
(helper != CORINFO_HELP_GETDYNAMIC_NONGCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED2))
{
return false;
}
assert(!opts.IsReadyToRun());
if (TargetOS::IsUnix)
{
#if defined(TARGET_ARM) || !defined(TARGET_64BIT)
// On Arm, Thread execution blocks are accessed using co-processor registers and instructions such
// as MRC and MCR are used to access them. We do not support them and so should never optimize the
// field access using TLS.
noway_assert(!"Unsupported scenario of optimizing TLS access on Linux Arm32/x86");
#endif
}
else
{
#ifdef TARGET_ARM
// On Arm, Thread execution blocks are accessed using co-processor registers and instructions such
// as MRC and MCR are used to access them. We do not support them and so should never optimize the
// field access using TLS.
noway_assert(!"Unsupported scenario of optimizing TLS access on Windows Arm32");
#endif
}
JITDUMP("Expanding thread static local access for [%06d] in " FMT_BB ":\n", dspTreeID(call), block->bbNum);
DISPTREE(call);
JITDUMP("\n");
CORINFO_THREAD_STATIC_BLOCKS_INFO threadStaticBlocksInfo;
memset(&threadStaticBlocksInfo, 0, sizeof(CORINFO_THREAD_STATIC_BLOCKS_INFO));
info.compCompHnd->getThreadLocalStaticBlocksInfo(&threadStaticBlocksInfo);
JITDUMP("getThreadLocalStaticBlocksInfo\n:");
JITDUMP("tlsIndex= %p\n", dspPtr(threadStaticBlocksInfo.tlsIndex.addr));
JITDUMP("tlsGetAddrFtnPtr= %p\n", dspPtr(threadStaticBlocksInfo.tlsGetAddrFtnPtr));
JITDUMP("tlsIndexObject= %p\n", dspPtr(threadStaticBlocksInfo.tlsIndexObject));
JITDUMP("threadVarsSection= %p\n", dspPtr(threadStaticBlocksInfo.threadVarsSection));
JITDUMP("offsetOfThreadLocalStoragePointer= %u\n",
dspOffset(threadStaticBlocksInfo.offsetOfThreadLocalStoragePointer));
JITDUMP("offsetOfMaxThreadStaticBlocks= %u\n", dspOffset(threadStaticBlocksInfo.offsetOfMaxThreadStaticBlocks));
JITDUMP("offsetOfThreadStaticBlocks= %u\n", dspOffset(threadStaticBlocksInfo.offsetOfThreadStaticBlocks));
JITDUMP("offsetOfBaseOfThreadLocalData= %u\n", dspOffset(threadStaticBlocksInfo.offsetOfBaseOfThreadLocalData));
assert(call->gtArgs.CountArgs() == 1);
// Split block right before the call tree
BasicBlock* prevBb = block;
GenTree** callUse = nullptr;
Statement* newFirstStmt = nullptr;
DebugInfo debugInfo = stmt->GetDebugInfo();
block = fgSplitBlockBeforeTree(block, stmt, call, &newFirstStmt, &callUse);
*pBlock = block;
var_types callType = call->TypeGet();
assert(prevBb != nullptr && block != nullptr);
// Block ops inserted by the split need to be morphed here since we are after morph.
// We cannot morph stmt yet as we may modify it further below, and the morphing
// could invalidate callUse.
while ((newFirstStmt != nullptr) && (newFirstStmt != stmt))
{
fgMorphStmtBlockOps(block, newFirstStmt);
newFirstStmt = newFirstStmt->GetNextStmt();
}
GenTreeLclVar* threadStaticBlockLcl = nullptr;
// Grab a temp to store result (it's assigned from either fastPathBb or fallbackBb)
unsigned threadStaticBlockLclNum = lvaGrabTemp(true DEBUGARG("TLS field access"));
lvaTable[threadStaticBlockLclNum].lvType = callType;
threadStaticBlockLcl = gtNewLclvNode(threadStaticBlockLclNum, callType);
*callUse = gtClone(threadStaticBlockLcl);
fgMorphStmtBlockOps(block, stmt);
gtUpdateStmtSideEffects(stmt);
GenTree* tlsValue = nullptr;
unsigned tlsLclNum = lvaGrabTemp(true DEBUGARG("TLS access"));
lvaTable[tlsLclNum].lvType = TYP_I_IMPL;
GenTree* maxThreadStaticBlocksValue = nullptr;
GenTree* threadStaticBlocksValue = nullptr;
GenTree* tlsValueDef = nullptr;
if (TargetOS::IsWindows)
{
size_t tlsIndexValue = (size_t)threadStaticBlocksInfo.tlsIndex.addr;
GenTree* dllRef = nullptr;
if (tlsIndexValue != 0)
{
dllRef = gtNewIconHandleNode(tlsIndexValue * TARGET_POINTER_SIZE, GTF_ICON_TLS_HDL);
}
// Mark this ICON as a TLS_HDL, codegen will use FS:[cns] or GS:[cns]
tlsValue = gtNewIconHandleNode(threadStaticBlocksInfo.offsetOfThreadLocalStoragePointer, GTF_ICON_TLS_HDL);
tlsValue = gtNewIndir(TYP_I_IMPL, tlsValue, GTF_IND_NONFAULTING | GTF_IND_INVARIANT);
if (dllRef != nullptr)
{
// Add the dllRef to produce thread local storage reference for coreclr
tlsValue = gtNewOperNode(GT_ADD, TYP_I_IMPL, tlsValue, dllRef);
}
// Base of coreclr's thread local storage
tlsValue = gtNewIndir(TYP_I_IMPL, tlsValue, GTF_IND_NONFAULTING | GTF_IND_INVARIANT);
}
else if (TargetOS::IsApplePlatform)
{
// For Apple x64/arm64, we need to get the address of relevant __thread_vars section of
// the thread local variable `t_ThreadStatics`. Address of `tlv_get_address` is stored
// in this entry, which we dereference and invoke it, passing the __thread_vars address
// present in `threadVarsSection`.
//
// Code sequence to access thread local variable on Apple/x64:
//
// mov rdi, threadVarsSection
// call [rdi]
//
// Code sequence to access thread local variable on Apple/arm64:
//
// mov x0, threadVarsSection
// mov x1, [x0]
// blr x1
//
size_t threadVarsSectionVal = (size_t)threadStaticBlocksInfo.threadVarsSection;
GenTree* tls_get_addr_val = gtNewIconHandleNode(threadVarsSectionVal, GTF_ICON_FTN_ADDR);
tls_get_addr_val = gtNewIndir(TYP_I_IMPL, tls_get_addr_val, GTF_IND_NONFAULTING | GTF_IND_INVARIANT);
tlsValue = gtNewIndCallNode(tls_get_addr_val, TYP_I_IMPL);
GenTreeCall* tlsRefCall = tlsValue->AsCall();
// This is a call which takes an argument.
// Populate and set the ABI appropriately.
assert(opts.altJit || threadVarsSectionVal != 0);
GenTree* tlsArg = gtNewIconNode(threadVarsSectionVal, TYP_I_IMPL);
tlsRefCall->gtArgs.PushBack(this, NewCallArg::Primitive(tlsArg));
fgMorphArgs(tlsRefCall);
tlsRefCall->gtFlags |= GTF_EXCEPT | (tls_get_addr_val->gtFlags & GTF_GLOB_EFFECT);
}
else if (TargetOS::IsUnix)
{
#if defined(TARGET_AMD64)
// Code sequence to access thread local variable on linux/x64:
//
// mov rdi, 0x7FE5C418CD28 ; tlsIndexObject
// mov rax, 0x7FE5C47AFDB0 ; _tls_get_addr
// call rax
//
GenTree* tls_get_addr_val =
gtNewIconHandleNode((size_t)threadStaticBlocksInfo.tlsGetAddrFtnPtr, GTF_ICON_FTN_ADDR);
tlsValue = gtNewIndCallNode(tls_get_addr_val, TYP_I_IMPL);
GenTreeCall* tlsRefCall = tlsValue->AsCall();
// This is an indirect call which takes an argument.
// Populate and set the ABI appropriately.
assert(opts.altJit || threadStaticBlocksInfo.tlsIndexObject != 0);
GenTree* tlsArg = gtNewIconNode((size_t)threadStaticBlocksInfo.tlsIndexObject, TYP_I_IMPL);
tlsRefCall->gtArgs.PushBack(this, NewCallArg::Primitive(tlsArg));
fgMorphArgs(tlsRefCall);
tlsRefCall->gtFlags |= GTF_EXCEPT | (tls_get_addr_val->gtFlags & GTF_GLOB_EFFECT);
#ifdef UNIX_X86_ABI
tlsRefCall->gtFlags &= ~GTF_CALL_POP_ARGS;
#endif // UNIX_X86_ABI
#elif defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
// Code sequence to access thread local variable on linux/arm64:
//
// mrs xt, tpidr_elf0
// mov xd, [xt+cns]
//
// Code sequence to access thread local variable on linux/loongarch64:
//
// ori, targetReg, $tp, 0
// load rd, targetReg, cns
//
// Code sequence to access thread local variable on linux/riscv64:
//
// mov targetReg, $tp
// ld rd, targetReg(cns)
tlsValue = gtNewIconHandleNode(0, GTF_ICON_TLS_HDL);
#else
assert(!"Unsupported scenario of optimizing TLS access on Linux Arm32/x86");
#endif
}
// Cache the tls value
tlsValueDef = gtNewStoreLclVarNode(tlsLclNum, tlsValue);
GenTree* tlsLclValueUse = gtNewLclVarNode(tlsLclNum);
GenTree* typeThreadStaticBlockIndexValue = call->gtArgs.GetArgByIndex(0)->GetNode();
assert(genActualType(typeThreadStaticBlockIndexValue) == TYP_INT);
if (helper == CORINFO_HELP_GETDYNAMIC_NONGCTHREADSTATIC_BASE_NOCTOR_OPTIMIZED2)
{
// In this case we can entirely remove the block which uses the helper call, and just get the TLS pointer
// directly