-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
rationalize.cpp
483 lines (414 loc) · 15.2 KB
/
rationalize.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
// 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
// RewriteNodeAsCall : Replace the given tree node by a GT_CALL.
//
// Arguments:
// ppTree - A pointer-to-a-pointer for the tree node
// fgWalkData - A pointer to tree walk data providing the context
// callHnd - The method handle of the call to be generated
// entryPoint - The method entrypoint of the call to be generated
// args - The argument list of the call to be generated
//
// Return Value:
// None.
//
void Rationalizer::RewriteNodeAsCall(GenTree** use,
ArrayStack<GenTree*>& parents,
CORINFO_METHOD_HANDLE callHnd,
#ifdef FEATURE_READYTORUN
CORINFO_CONST_LOOKUP entryPoint,
#endif
GenTree* arg1,
GenTree* arg2)
{
GenTree* const tree = *use;
GenTree* const treeFirstNode = comp->fgGetFirstNode(tree);
GenTree* const insertionPoint = treeFirstNode->gtPrev;
BlockRange().Remove(treeFirstNode, tree);
// Create the call node
GenTreeCall* call = comp->gtNewCallNode(CT_USER_FUNC, callHnd, tree->gtType);
if (arg2 != nullptr)
{
call->gtArgs.PushFront(comp, NewCallArg::Primitive(arg2));
call->gtFlags |= arg2->gtFlags & GTF_ALL_EFFECT;
}
if (arg1 != nullptr)
{
call->gtArgs.PushFront(comp, NewCallArg::Primitive(arg1));
call->gtFlags |= arg1->gtFlags & GTF_ALL_EFFECT;
}
#if DEBUG
CORINFO_SIG_INFO sig;
comp->eeGetMethodSig(callHnd, &sig);
assert(JITtype2varType(sig.retType) == tree->gtType);
#endif // DEBUG
#ifdef FEATURE_READYTORUN
call->AsCall()->setEntryPoint(entryPoint);
#endif
call = comp->fgMorphArgs(call);
// Replace "tree" with "call"
if (parents.Height() > 1)
{
parents.Top(1)->ReplaceOperand(use, call);
}
else
{
// If there's no parent, the tree being replaced is the root of the
// statement (and no special handling is necessary).
*use = call;
}
comp->gtSetEvalOrder(call);
BlockRange().InsertAfter(insertionPoint, LIR::Range(comp->fgSetTreeSeq(call), call));
// Propagate flags of "call" to its parents.
// 0 is current node, so start at 1
for (int i = 1; i < parents.Height(); i++)
{
parents.Top(i)->gtFlags |= (call->gtFlags & GTF_ALL_EFFECT) | GTF_CALL;
}
// Since "tree" is replaced with "call", pop "tree" node (i.e the current node)
// and replace it with "call" on parent stack.
assert(parents.Top() == tree);
(void)parents.Pop();
parents.Push(call);
}
// RewriteIntrinsicAsUserCall : Rewrite an intrinsic operator as a GT_CALL to the original method.
//
// Arguments:
// ppTree - A pointer-to-a-pointer for the intrinsic node
// fgWalkData - A pointer to tree walk data providing the context
//
// Return Value:
// None.
//
// Some intrinsics, such as operation Sqrt, are rewritten back to calls, and some are not.
// The ones that are not being rewritten here must be handled in Codegen.
// Conceptually, the lower is the right place to do the rewrite. Keeping it in rationalization is
// mainly for throughput issue.
void Rationalizer::RewriteIntrinsicAsUserCall(GenTree** use, ArrayStack<GenTree*>& parents)
{
GenTreeIntrinsic* intrinsic = (*use)->AsIntrinsic();
GenTree* arg1 = intrinsic->gtGetOp1();
GenTree* arg2 = intrinsic->gtGetOp2();
RewriteNodeAsCall(use, parents, intrinsic->gtMethodHandle,
#ifdef FEATURE_READYTORUN
intrinsic->gtEntryPoint,
#endif
arg1, arg2);
}
#ifdef TARGET_ARM64
// RewriteSubLshDiv: Possibly rewrite a SubLshDiv node into a Mod.
//
// Arguments:
// use - A use of a node.
//
// Transform: a - (a / cns) << shift => a % cns
// where cns is a signed integer constant that is a power of 2.
// We do this transformation because Lowering has a specific optimization
// for 'a % cns' that is not easily reduced by other means.
//
void Rationalizer::RewriteSubLshDiv(GenTree** use)
{
if (!comp->opts.OptimizationEnabled())
return;
GenTree* const node = *use;
if (!node->OperIs(GT_SUB))
return;
GenTree* op1 = node->gtGetOp1();
GenTree* op2 = node->gtGetOp2();
if (!(node->TypeIs(TYP_INT, TYP_LONG) && op1->OperIs(GT_LCL_VAR)))
return;
if (!op2->OperIs(GT_LSH))
return;
GenTree* lsh = op2;
GenTree* div = lsh->gtGetOp1();
GenTree* shift = lsh->gtGetOp2();
if (div->OperIs(GT_DIV) && shift->IsIntegralConst())
{
GenTree* a = div->gtGetOp1();
GenTree* cns = div->gtGetOp2();
if (a->OperIs(GT_LCL_VAR) && cns->IsIntegralConstPow2() &&
op1->AsLclVar()->GetLclNum() == a->AsLclVar()->GetLclNum())
{
size_t shiftValue = shift->AsIntConCommon()->IntegralValue();
size_t cnsValue = cns->AsIntConCommon()->IntegralValue();
if ((cnsValue >> shiftValue) == 1)
{
node->ChangeOper(GT_MOD);
node->AsOp()->gtOp2 = cns;
BlockRange().Remove(lsh);
BlockRange().Remove(div);
BlockRange().Remove(a);
BlockRange().Remove(shift);
}
}
}
}
#endif
#ifdef DEBUG
void Rationalizer::ValidateStatement(Statement* stmt, BasicBlock* block)
{
DBEXEC(TRUE, JitTls::GetCompiler()->fgDebugCheckNodeLinks(block, stmt));
}
// sanity checks that apply to all kinds of IR
void Rationalizer::SanityCheck()
{
// TODO: assert(!IsLIR());
for (BasicBlock* const block : comp->Blocks())
{
for (Statement* const stmt : block->Statements())
{
ValidateStatement(stmt, block);
}
}
}
void Rationalizer::SanityCheckRational()
{
// TODO-Cleanup : check that the tree is rational here
// then do normal checks
SanityCheck();
}
#endif // DEBUG
Compiler::fgWalkResult Rationalizer::RewriteNode(GenTree** useEdge, Compiler::GenTreeStack& parentStack)
{
assert(useEdge != nullptr);
GenTree* node = *useEdge;
assert(node != nullptr);
// Clear the REVERSE_OPS flag on the current node.
node->gtFlags &= ~GTF_REVERSE_OPS;
LIR::Use use;
if (parentStack.Height() < 2)
{
LIR::Use::MakeDummyUse(BlockRange(), *useEdge, &use);
}
else
{
use = LIR::Use(BlockRange(), useEdge, parentStack.Top(1));
}
assert(node == use.Def());
switch (node->OperGet())
{
case GT_CALL:
// In linear order we no longer need to retain the stores in early
// args as these have now been sequenced.
for (CallArg& arg : node->AsCall()->gtArgs.EarlyArgs())
{
if (arg.GetLateNode() != nullptr)
{
if (arg.GetEarlyNode()->IsValue())
{
arg.GetEarlyNode()->SetUnusedValue();
}
arg.SetEarlyNode(nullptr);
}
}
#ifdef DEBUG
// The above means that all argument nodes are now true arguments.
for (CallArg& arg : node->AsCall()->gtArgs.Args())
{
assert((arg.GetEarlyNode() == nullptr) != (arg.GetLateNode() == nullptr));
}
#endif
break;
case GT_BOX:
case GT_ARR_ADDR:
// BOX/ARR_ADDR are "passthrough" nodes,
// and at this point we no longer need them.
if (node->gtGetOp1() != nullptr)
{
use.ReplaceWith(node->gtGetOp1());
BlockRange().Remove(node);
node = node->gtGetOp1();
}
break;
case GT_COMMA:
{
GenTree* op1 = node->gtGetOp1();
bool isClosed = false;
unsigned sideEffects = 0;
LIR::ReadOnlyRange lhsRange = BlockRange().GetTreeRange(op1, &isClosed, &sideEffects);
if ((sideEffects & GTF_ALL_EFFECT) == 0)
{
// The LHS has no side effects. Remove it.
// All transformations on pure trees keep their operands in LIR
// and should not violate tree order.
assert(isClosed);
BlockRange().Delete(comp, m_block, std::move(lhsRange));
}
else if (op1->IsValue())
{
op1->SetUnusedValue();
}
BlockRange().Remove(node);
GenTree* replacement = node->gtGetOp2();
if (!use.IsDummyUse())
{
use.ReplaceWith(replacement);
node = replacement;
}
else
{
// This is a top-level comma. If the RHS has no side effects we can remove
// it as well.
bool isClosed = false;
unsigned sideEffects = 0;
LIR::ReadOnlyRange rhsRange = BlockRange().GetTreeRange(replacement, &isClosed, &sideEffects);
if ((sideEffects & GTF_ALL_EFFECT) == 0)
{
// All transformations on pure trees keep their operands in
// LIR and should not violate tree order.
assert(isClosed);
BlockRange().Delete(comp, m_block, std::move(rhsRange));
}
else
{
node = replacement;
}
}
}
break;
case GT_INTRINSIC:
// Non-target intrinsics should have already been rewritten back into user calls.
assert(comp->IsTargetIntrinsic(node->AsIntrinsic()->gtIntrinsicName));
break;
case GT_CAST:
if (node->AsCast()->CastOp()->OperIsSimple())
{
comp->fgSimpleLowerCastOfSmpOp(BlockRange(), node->AsCast());
}
break;
default:
// Check that we don't have nodes not allowed in HIR here.
assert((node->DebugOperKind() & DBK_NOTHIR) == 0);
break;
}
// Do some extra processing on top-level nodes to remove unused local reads.
if (node->OperIsLocalRead())
{
if (use.IsDummyUse())
{
BlockRange().Remove(node);
}
else
{
// Local reads are side-effect-free; clear any flags leftover from frontend transformations.
node->gtFlags &= ~GTF_ALL_EFFECT;
}
}
else
{
if (node->IsValue() && use.IsDummyUse())
{
node->SetUnusedValue();
}
if (node->TypeIs(TYP_LONG))
{
comp->compLongUsed = true;
}
}
return Compiler::WALK_CONTINUE;
}
//------------------------------------------------------------------------
// DoPhase: Run the rationalize over the method IR.
//
// Returns:
// PhaseStatus indicating, what, if anything, was modified
//
PhaseStatus Rationalizer::DoPhase()
{
class RationalizeVisitor final : public GenTreeVisitor<RationalizeVisitor>
{
Rationalizer& m_rationalizer;
public:
enum
{
ComputeStack = true,
DoPreOrder = true,
DoPostOrder = true,
UseExecutionOrder = true,
};
RationalizeVisitor(Rationalizer& rationalizer)
: GenTreeVisitor<RationalizeVisitor>(rationalizer.comp)
, m_rationalizer(rationalizer)
{
}
// Rewrite intrinsics that are not supported by the target back into user calls.
// This needs to be done before the transition to LIR because it relies on the use
// of fgMorphArgs, which is designed to operate on HIR. Once this is done for a
// particular statement, link that statement's nodes into the current basic block.
fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
{
GenTree* const node = *use;
if (node->OperGet() == GT_INTRINSIC &&
m_rationalizer.comp->IsIntrinsicImplementedByUserCall(node->AsIntrinsic()->gtIntrinsicName))
{
m_rationalizer.RewriteIntrinsicAsUserCall(use, this->m_ancestors);
}
#ifdef TARGET_ARM64
if (node->OperIs(GT_SUB))
{
m_rationalizer.RewriteSubLshDiv(use);
}
#endif
return Compiler::WALK_CONTINUE;
}
// Rewrite HIR nodes into LIR nodes.
fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
{
return m_rationalizer.RewriteNode(use, this->m_ancestors);
}
};
DBEXEC(TRUE, SanityCheck());
comp->compCurBB = nullptr;
comp->fgOrder = Compiler::FGOrderLinear;
RationalizeVisitor visitor(*this);
for (BasicBlock* const block : comp->Blocks())
{
comp->compCurBB = block;
m_block = block;
block->MakeLIR(nullptr, nullptr);
// Establish the first and last nodes for the block. This is necessary in order for the LIR
// utilities that hang off the BasicBlock type to work correctly.
Statement* firstStatement = block->firstStmt();
if (firstStatement == nullptr)
{
// No statements in this block; skip it.
continue;
}
for (Statement* const statement : block->Statements())
{
assert(statement->GetTreeList() != nullptr);
assert(statement->GetTreeList()->gtPrev == nullptr);
assert(statement->GetRootNode() != nullptr);
assert(statement->GetRootNode()->gtNext == nullptr);
if (!statement->IsPhiDefnStmt()) // Note that we get rid of PHI nodes here.
{
BlockRange().InsertAtEnd(LIR::Range(statement->GetTreeList(), statement->GetRootNode()));
// If this statement has correct debug information, change it
// into a debug info node and insert it into the LIR. Note that
// we are currently reporting root info only back to the EE, so
// if the leaf debug info is invalid we still attach it.
// Note that we would like to have the invariant di.IsValid()
// => parent.IsValid() but it is currently not the case for
// NEWOBJ IL instructions where the debug info ends up attached
// to the allocation instead of the constructor call.
DebugInfo di = statement->GetDebugInfo();
if (di.IsValid() || di.GetRoot().IsValid())
{
GenTreeILOffset* ilOffset =
new (comp, GT_IL_OFFSET) GenTreeILOffset(di DEBUGARG(statement->GetLastILOffset()));
BlockRange().InsertBefore(statement->GetTreeList(), ilOffset);
}
m_block = block;
visitor.WalkTree(statement->GetRootNodePointer(), nullptr);
}
}
block->bbStmtList = nullptr;
assert(BlockRange().CheckLIR(comp, true));
}
comp->compRationalIRForm = true;
return PhaseStatus::MODIFIED_EVERYTHING;
}