Fix reading Time zone rules using Julian days (#17672)
[platform/upstream/coreclr.git] / src / jit / block.cpp
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4
5 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7 XX                                                                           XX
8 XX                          BasicBlock                                       XX
9 XX                                                                           XX
10 XX                                                                           XX
11 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
12 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
13 */
14 #include "jitpch.h"
15 #ifdef _MSC_VER
16 #pragma hdrstop
17 #endif
18
19 #if MEASURE_BLOCK_SIZE
20 /* static  */
21 size_t BasicBlock::s_Size;
22 /* static */
23 size_t BasicBlock::s_Count;
24 #endif // MEASURE_BLOCK_SIZE
25
26 #ifdef DEBUG
27 // The max # of tree nodes in any BB
28 /* static */
29 unsigned BasicBlock::s_nMaxTrees;
30 #endif // DEBUG
31
32 #ifdef DEBUG
33 flowList* ShuffleHelper(unsigned hash, flowList* res)
34 {
35     flowList* head = res;
36     for (flowList *prev = nullptr; res != nullptr; prev = res, res = res->flNext)
37     {
38         unsigned blkHash = (hash ^ (res->flBlock->bbNum << 16) ^ res->flBlock->bbNum);
39         if (((blkHash % 1879) & 1) && prev != nullptr)
40         {
41             // Swap res with head.
42             prev->flNext = head;
43             jitstd::swap(head->flNext, res->flNext);
44             jitstd::swap(head, res);
45         }
46     }
47     return head;
48 }
49
50 unsigned SsaStressHashHelper()
51 {
52     // hash = 0: turned off, hash = 1: use method hash, hash = *: use custom hash.
53     unsigned hash = JitConfig.JitSsaStress();
54
55     if (hash == 0)
56     {
57         return hash;
58     }
59     if (hash == 1)
60     {
61         return JitTls::GetCompiler()->info.compMethodHash();
62     }
63     return ((hash >> 16) == 0) ? ((hash << 16) | hash) : hash;
64 }
65 #endif
66
67 EHSuccessorIter::EHSuccessorIter(Compiler* comp, BasicBlock* block)
68     : m_comp(comp)
69     , m_block(block)
70     , m_curRegSucc(nullptr)
71     , m_curTry(comp->ehGetBlockExnFlowDsc(block))
72     , m_remainingRegSuccs(block->NumSucc(comp))
73 {
74     // If "block" is a "leave helper" block (the empty BBJ_ALWAYS block that pairs with a
75     // preceding BBJ_CALLFINALLY block to implement a "leave" IL instruction), then no exceptions
76     // can occur within it, so clear m_curTry if it's non-null.
77     if (m_curTry != nullptr)
78     {
79         BasicBlock* beforeBlock = block->bbPrev;
80         if (beforeBlock != nullptr && beforeBlock->isBBCallAlwaysPair())
81         {
82             m_curTry = nullptr;
83         }
84     }
85
86     if (m_curTry == nullptr && m_remainingRegSuccs > 0)
87     {
88         // Examine the successors to see if any are the start of try blocks.
89         FindNextRegSuccTry();
90     }
91 }
92
93 void EHSuccessorIter::FindNextRegSuccTry()
94 {
95     assert(m_curTry == nullptr);
96
97     // Must now consider the next regular successor, if any.
98     while (m_remainingRegSuccs > 0)
99     {
100         m_remainingRegSuccs--;
101         m_curRegSucc = m_block->GetSucc(m_remainingRegSuccs, m_comp);
102         if (m_comp->bbIsTryBeg(m_curRegSucc))
103         {
104             assert(m_curRegSucc->hasTryIndex()); // Since it is a try begin.
105             unsigned newTryIndex = m_curRegSucc->getTryIndex();
106
107             // If the try region started by "m_curRegSucc" (represented by newTryIndex) contains m_block,
108             // we've already yielded its handler, as one of the EH handler successors of m_block itself.
109             if (m_comp->bbInExnFlowRegions(newTryIndex, m_block))
110             {
111                 continue;
112             }
113
114             // Otherwise, consider this try.
115             m_curTry = m_comp->ehGetDsc(newTryIndex);
116             break;
117         }
118     }
119 }
120
121 void EHSuccessorIter::operator++(void)
122 {
123     assert(m_curTry != nullptr);
124     if (m_curTry->ebdEnclosingTryIndex != EHblkDsc::NO_ENCLOSING_INDEX)
125     {
126         m_curTry = m_comp->ehGetDsc(m_curTry->ebdEnclosingTryIndex);
127
128         // If we've gone over into considering try's containing successors,
129         // then the enclosing try must have the successor as its first block.
130         if (m_curRegSucc == nullptr || m_curTry->ebdTryBeg == m_curRegSucc)
131         {
132             return;
133         }
134
135         // Otherwise, give up, try the next regular successor.
136         m_curTry = nullptr;
137     }
138     else
139     {
140         m_curTry = nullptr;
141     }
142
143     // We've exhausted all try blocks.
144     // See if there are any remaining regular successors that start try blocks.
145     FindNextRegSuccTry();
146 }
147
148 BasicBlock* EHSuccessorIter::operator*()
149 {
150     assert(m_curTry != nullptr);
151     return m_curTry->ExFlowBlock();
152 }
153
154 flowList* Compiler::BlockPredsWithEH(BasicBlock* blk)
155 {
156     BlockToFlowListMap* ehPreds = GetBlockToEHPreds();
157     flowList*           res;
158     if (ehPreds->Lookup(blk, &res))
159     {
160         return res;
161     }
162
163     res = blk->bbPreds;
164     unsigned tryIndex;
165     if (bbIsExFlowBlock(blk, &tryIndex))
166     {
167         // Find the first block of the try.
168         EHblkDsc*   ehblk    = ehGetDsc(tryIndex);
169         BasicBlock* tryStart = ehblk->ebdTryBeg;
170         for (flowList* tryStartPreds = tryStart->bbPreds; tryStartPreds != nullptr;
171              tryStartPreds           = tryStartPreds->flNext)
172         {
173             res = new (this, CMK_FlowList) flowList(tryStartPreds->flBlock, res);
174
175 #if MEASURE_BLOCK_SIZE
176             genFlowNodeCnt += 1;
177             genFlowNodeSize += sizeof(flowList);
178 #endif // MEASURE_BLOCK_SIZE
179         }
180
181         // Now add all blocks handled by this handler (except for second blocks of BBJ_CALLFINALLY/BBJ_ALWAYS pairs;
182         // these cannot cause transfer to the handler...)
183         BasicBlock* prevBB = nullptr;
184
185         // TODO-Throughput: It would be nice if we could iterate just over the blocks in the try, via
186         // something like:
187         //   for (BasicBlock* bb = ehblk->ebdTryBeg; bb != ehblk->ebdTryLast->bbNext; bb = bb->bbNext)
188         //     (plus adding in any filter blocks outside the try whose exceptions are handled here).
189         // That doesn't work, however: funclets have caused us to sometimes split the body of a try into
190         // more than one sequence of contiguous blocks.  We need to find a better way to do this.
191         for (BasicBlock *bb = fgFirstBB; bb != nullptr; prevBB = bb, bb = bb->bbNext)
192         {
193             if (bbInExnFlowRegions(tryIndex, bb) && (prevBB == nullptr || !prevBB->isBBCallAlwaysPair()))
194             {
195                 res = new (this, CMK_FlowList) flowList(bb, res);
196
197 #if MEASURE_BLOCK_SIZE
198                 genFlowNodeCnt += 1;
199                 genFlowNodeSize += sizeof(flowList);
200 #endif // MEASURE_BLOCK_SIZE
201             }
202         }
203
204 #ifdef DEBUG
205         unsigned hash = SsaStressHashHelper();
206         if (hash != 0)
207         {
208             res = ShuffleHelper(hash, res);
209         }
210 #endif // DEBUG
211
212         ehPreds->Set(blk, res);
213     }
214     return res;
215 }
216
217 #ifdef DEBUG
218
219 //------------------------------------------------------------------------
220 // dspBlockILRange(): Display the block's IL range as [XXX...YYY), where XXX and YYY might be "???" for BAD_IL_OFFSET.
221 //
222 void BasicBlock::dspBlockILRange()
223 {
224     if (bbCodeOffs != BAD_IL_OFFSET)
225     {
226         printf("[%03X..", bbCodeOffs);
227     }
228     else
229     {
230         printf("[???"
231                "..");
232     }
233
234     if (bbCodeOffsEnd != BAD_IL_OFFSET)
235     {
236         // brace-matching editor workaround for following line: (
237         printf("%03X)", bbCodeOffsEnd);
238     }
239     else
240     {
241         // brace-matching editor workaround for following line: (
242         printf("???"
243                ")");
244     }
245 }
246
247 //------------------------------------------------------------------------
248 // dspFlags: Print out the block's flags
249 //
250 void BasicBlock::dspFlags()
251 {
252     if (bbFlags & BBF_VISITED)
253     {
254         printf("v ");
255     }
256     if (bbFlags & BBF_MARKED)
257     {
258         printf("m ");
259     }
260     if (bbFlags & BBF_CHANGED)
261     {
262         printf("! ");
263     }
264     if (bbFlags & BBF_REMOVED)
265     {
266         printf("del ");
267     }
268     if (bbFlags & BBF_DONT_REMOVE)
269     {
270         printf("keep ");
271     }
272     if (bbFlags & BBF_IMPORTED)
273     {
274         printf("i ");
275     }
276     if (bbFlags & BBF_INTERNAL)
277     {
278         printf("internal ");
279     }
280     if (bbFlags & BBF_FAILED_VERIFICATION)
281     {
282         printf("failV ");
283     }
284     if (bbFlags & BBF_TRY_BEG)
285     {
286         printf("try ");
287     }
288     if (bbFlags & BBF_NEEDS_GCPOLL)
289     {
290         printf("poll ");
291     }
292     if (bbFlags & BBF_RUN_RARELY)
293     {
294         printf("rare ");
295     }
296     if (bbFlags & BBF_LOOP_HEAD)
297     {
298         printf("Loop ");
299     }
300     if (bbFlags & BBF_LOOP_CALL0)
301     {
302         printf("Loop0 ");
303     }
304     if (bbFlags & BBF_LOOP_CALL1)
305     {
306         printf("Loop1 ");
307     }
308     if (bbFlags & BBF_HAS_LABEL)
309     {
310         printf("label ");
311     }
312     if (bbFlags & BBF_JMP_TARGET)
313     {
314         printf("target ");
315     }
316     if (bbFlags & BBF_HAS_JMP)
317     {
318         printf("jmp ");
319     }
320     if (bbFlags & BBF_GC_SAFE_POINT)
321     {
322         printf("gcsafe ");
323     }
324     if (bbFlags & BBF_FUNCLET_BEG)
325     {
326         printf("flet ");
327     }
328     if (bbFlags & BBF_HAS_IDX_LEN)
329     {
330         printf("idxlen ");
331     }
332     if (bbFlags & BBF_HAS_NEWARRAY)
333     {
334         printf("new[] ");
335     }
336     if (bbFlags & BBF_HAS_NEWOBJ)
337     {
338         printf("newobj ");
339     }
340 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
341     if (bbFlags & BBF_FINALLY_TARGET)
342     {
343         printf("ftarget ");
344     }
345 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
346     if (bbFlags & BBF_BACKWARD_JUMP)
347     {
348         printf("bwd ");
349     }
350     if (bbFlags & BBF_RETLESS_CALL)
351     {
352         printf("retless ");
353     }
354     if (bbFlags & BBF_LOOP_PREHEADER)
355     {
356         printf("LoopPH ");
357     }
358     if (bbFlags & BBF_COLD)
359     {
360         printf("cold ");
361     }
362     if (bbFlags & BBF_PROF_WEIGHT)
363     {
364         printf("IBC ");
365     }
366 #ifdef LEGACY_BACKEND
367     if (bbFlags & BBF_FORWARD_SWITCH)
368     {
369         printf("fswitch ");
370     }
371 #else  // !LEGACY_BACKEND
372     if (bbFlags & BBF_IS_LIR)
373     {
374         printf("LIR ");
375     }
376 #endif // LEGACY_BACKEND
377     if (bbFlags & BBF_KEEP_BBJ_ALWAYS)
378     {
379         printf("KEEP ");
380     }
381     if (bbFlags & BBF_CLONED_FINALLY_BEGIN)
382     {
383         printf("cfb ");
384     }
385     if (bbFlags & BBF_CLONED_FINALLY_END)
386     {
387         printf("cfe ");
388     }
389 }
390
391 /*****************************************************************************
392  *
393  *  Display the bbPreds basic block list (the block predecessors).
394  *  Returns the number of characters printed.
395  */
396
397 unsigned BasicBlock::dspPreds()
398 {
399     unsigned count = 0;
400     for (flowList* pred = bbPreds; pred != nullptr; pred = pred->flNext)
401     {
402         if (count != 0)
403         {
404             printf(",");
405             count += 1;
406         }
407         printf("BB%02u", pred->flBlock->bbNum);
408         count += 4;
409
410         // Account for %02u only handling 2 digits, but we can display more than that.
411         unsigned digits = CountDigits(pred->flBlock->bbNum);
412         if (digits > 2)
413         {
414             count += digits - 2;
415         }
416
417         // Does this predecessor have an interesting dup count? If so, display it.
418         if (pred->flDupCount > 1)
419         {
420             printf("(%u)", pred->flDupCount);
421             count += 2 + CountDigits(pred->flDupCount);
422         }
423     }
424     return count;
425 }
426
427 /*****************************************************************************
428  *
429  *  Display the bbCheapPreds basic block list (the block predecessors).
430  *  Returns the number of characters printed.
431  */
432
433 unsigned BasicBlock::dspCheapPreds()
434 {
435     unsigned count = 0;
436     for (BasicBlockList* pred = bbCheapPreds; pred != nullptr; pred = pred->next)
437     {
438         if (count != 0)
439         {
440             printf(",");
441             count += 1;
442         }
443         printf("BB%02u", pred->block->bbNum);
444         count += 4;
445
446         // Account for %02u only handling 2 digits, but we can display more than that.
447         unsigned digits = CountDigits(pred->block->bbNum);
448         if (digits > 2)
449         {
450             count += digits - 2;
451         }
452     }
453     return count;
454 }
455
456 /*****************************************************************************
457  *
458  *  Display the basic block successors.
459  *  Returns the count of successors.
460  */
461
462 unsigned BasicBlock::dspSuccs(Compiler* compiler)
463 {
464     unsigned numSuccs = NumSucc(compiler);
465     unsigned count    = 0;
466     for (unsigned i = 0; i < numSuccs; i++)
467     {
468         printf("%s", (count == 0) ? "" : ",");
469         printf("BB%02u", GetSucc(i, compiler)->bbNum);
470         count++;
471     }
472     return count;
473 }
474
475 // Display a compact representation of the bbJumpKind, that is, where this block branches.
476 // This is similar to code in Compiler::fgTableDispBasicBlock(), but doesn't have that code's requirements to align
477 // things strictly.
478 void BasicBlock::dspJumpKind()
479 {
480     switch (bbJumpKind)
481     {
482         case BBJ_EHFINALLYRET:
483             printf(" (finret)");
484             break;
485
486         case BBJ_EHFILTERRET:
487             printf(" (fltret)");
488             break;
489
490         case BBJ_EHCATCHRET:
491             printf(" -> BB%02u (cret)", bbJumpDest->bbNum);
492             break;
493
494         case BBJ_THROW:
495             printf(" (throw)");
496             break;
497
498         case BBJ_RETURN:
499             printf(" (return)");
500             break;
501
502         case BBJ_NONE:
503             // For fall-through blocks, print nothing.
504             break;
505
506         case BBJ_ALWAYS:
507             if (bbFlags & BBF_KEEP_BBJ_ALWAYS)
508             {
509                 printf(" -> BB%02u (ALWAYS)", bbJumpDest->bbNum);
510             }
511             else
512             {
513                 printf(" -> BB%02u (always)", bbJumpDest->bbNum);
514             }
515             break;
516
517         case BBJ_LEAVE:
518             printf(" -> BB%02u (leave)", bbJumpDest->bbNum);
519             break;
520
521         case BBJ_CALLFINALLY:
522             printf(" -> BB%02u (callf)", bbJumpDest->bbNum);
523             break;
524
525         case BBJ_COND:
526             printf(" -> BB%02u (cond)", bbJumpDest->bbNum);
527             break;
528
529         case BBJ_SWITCH:
530             printf(" ->");
531
532             unsigned jumpCnt;
533             jumpCnt = bbJumpSwt->bbsCount;
534             BasicBlock** jumpTab;
535             jumpTab = bbJumpSwt->bbsDstTab;
536             do
537             {
538                 printf("%cBB%02u", (jumpTab == bbJumpSwt->bbsDstTab) ? ' ' : ',', (*jumpTab)->bbNum);
539             } while (++jumpTab, --jumpCnt);
540
541             printf(" (switch)");
542             break;
543
544         default:
545             unreached();
546             break;
547     }
548 }
549
550 void BasicBlock::dspBlockHeader(Compiler* compiler,
551                                 bool      showKind /*= true*/,
552                                 bool      showFlags /*= false*/,
553                                 bool      showPreds /*= true*/)
554 {
555     printf("BB%02u ", bbNum);
556     dspBlockILRange();
557     if (showKind)
558     {
559         dspJumpKind();
560     }
561     if (showPreds)
562     {
563         printf(", preds={");
564         if (compiler->fgCheapPredsValid)
565         {
566             dspCheapPreds();
567         }
568         else
569         {
570             dspPreds();
571         }
572         printf("} succs={");
573         dspSuccs(compiler);
574         printf("}");
575     }
576     if (showFlags)
577     {
578         const unsigned lowFlags  = (unsigned)bbFlags;
579         const unsigned highFlags = (unsigned)(bbFlags >> 32);
580         printf(" flags=0x%08x.%08x: ", highFlags, lowFlags);
581         dspFlags();
582     }
583     printf("\n");
584 }
585
586 const char* BasicBlock::dspToString(int blockNumPadding /* = 2*/)
587 {
588     static char buffers[3][64]; // static array of 3 to allow 3 concurrent calls in one printf()
589     static int  nextBufferIndex = 0;
590
591     auto& buffer    = buffers[nextBufferIndex];
592     nextBufferIndex = (nextBufferIndex + 1) % _countof(buffers);
593     _snprintf_s(buffer, _countof(buffer), _countof(buffer), "BB%02u%*s [%04u]", bbNum, blockNumPadding, "", bbID);
594     return buffer;
595 }
596
597 #endif // DEBUG
598
599 // Allocation function for MemoryPhiArg.
600 void* BasicBlock::MemoryPhiArg::operator new(size_t sz, Compiler* comp)
601 {
602     return comp->compGetMem(sz, CMK_MemoryPhiArg);
603 }
604
605 //------------------------------------------------------------------------
606 // CloneBlockState: Try to populate `to` block with a copy of `from` block's statements, replacing
607 //                  uses of local `varNum` with IntCns `varVal`.
608 //
609 // Arguments:
610 //    compiler - Jit compiler instance
611 //    to - New/empty block to copy statements into
612 //    from - Block to copy statements from
613 //    varNum - lclVar uses with lclNum `varNum` will be replaced; can be ~0 to indicate no replacement.
614 //    varVal - If replacing uses of `varNum`, replace them with int constants with value `varVal`.
615 //
616 // Return Value:
617 //    Cloning may fail because this routine uses `gtCloneExpr` for cloning and it can't handle all
618 //    IR nodes.  If cloning of any statement fails, `false` will be returned and block `to` may be
619 //    partially populated.  If cloning of all statements succeeds, `true` will be returned and
620 //    block `to` will be fully populated.
621
622 bool BasicBlock::CloneBlockState(
623     Compiler* compiler, BasicBlock* to, const BasicBlock* from, unsigned varNum, int varVal)
624 {
625     assert(to->bbTreeList == nullptr);
626
627     to->bbFlags  = from->bbFlags;
628     to->bbWeight = from->bbWeight;
629     BlockSetOps::AssignAllowUninitRhs(compiler, to->bbReach, from->bbReach);
630     to->copyEHRegion(from);
631     to->bbCatchTyp    = from->bbCatchTyp;
632     to->bbRefs        = from->bbRefs;
633     to->bbStkTempsIn  = from->bbStkTempsIn;
634     to->bbStkTempsOut = from->bbStkTempsOut;
635     to->bbStkDepth    = from->bbStkDepth;
636     to->bbCodeOffs    = from->bbCodeOffs;
637     to->bbCodeOffsEnd = from->bbCodeOffsEnd;
638     VarSetOps::AssignAllowUninitRhs(compiler, to->bbScope, from->bbScope);
639 #if FEATURE_STACK_FP_X87
640     to->bbFPStateX87 = from->bbFPStateX87;
641 #endif // FEATURE_STACK_FP_X87
642     to->bbNatLoopNum = from->bbNatLoopNum;
643 #ifdef DEBUG
644     to->bbLoopNum     = from->bbLoopNum;
645     to->bbTgtStkDepth = from->bbTgtStkDepth;
646 #endif // DEBUG
647
648     for (GenTree* fromStmt = from->bbTreeList; fromStmt != nullptr; fromStmt = fromStmt->gtNext)
649     {
650         auto newExpr = compiler->gtCloneExpr(fromStmt->gtStmt.gtStmtExpr, 0, varNum, varVal);
651         if (!newExpr)
652         {
653             // gtCloneExpr doesn't handle all opcodes, so may fail to clone a statement.
654             // When that happens, it returns nullptr; abandon the rest of this block and
655             // return `false` to the caller to indicate that cloning was unsuccessful.
656             return false;
657         }
658         compiler->fgInsertStmtAtEnd(to, compiler->fgNewStmtFromTree(newExpr));
659     }
660     return true;
661 }
662
663 // LIR helpers
664 void BasicBlock::MakeLIR(GenTree* firstNode, GenTree* lastNode)
665 {
666 #ifdef LEGACY_BACKEND
667     unreached();
668 #else  // !LEGACY_BACKEND
669     assert(!IsLIR());
670     assert((firstNode == nullptr) == (lastNode == nullptr));
671     assert((firstNode == lastNode) || firstNode->Precedes(lastNode));
672
673     m_firstNode = firstNode;
674     m_lastNode  = lastNode;
675     bbFlags |= BBF_IS_LIR;
676 #endif // LEGACY_BACKEND
677 }
678
679 bool BasicBlock::IsLIR()
680 {
681 #ifdef LEGACY_BACKEND
682     return false;
683 #else  // !LEGACY_BACKEND
684     const bool isLIR = (bbFlags & BBF_IS_LIR) != 0;
685     assert((bbTreeList == nullptr) || ((isLIR) == !bbTreeList->IsStatement()));
686     return isLIR;
687 #endif // LEGACY_BACKEND
688 }
689
690 //------------------------------------------------------------------------
691 // firstStmt: Returns the first statement in the block
692 //
693 // Arguments:
694 //    None.
695 //
696 // Return Value:
697 //    The first statement in the block's bbTreeList.
698 //
699 GenTreeStmt* BasicBlock::firstStmt() const
700 {
701     if (bbTreeList == nullptr)
702     {
703         return nullptr;
704     }
705
706     return bbTreeList->AsStmt();
707 }
708
709 //------------------------------------------------------------------------
710 // lastStmt: Returns the last statement in the block
711 //
712 // Arguments:
713 //    None.
714 //
715 // Return Value:
716 //    The last statement in the block's bbTreeList.
717 //
718 GenTreeStmt* BasicBlock::lastStmt() const
719 {
720     if (bbTreeList == nullptr)
721     {
722         return nullptr;
723     }
724
725     GenTree* result = bbTreeList->gtPrev;
726     assert(result && result->gtNext == nullptr);
727     return result->AsStmt();
728 }
729
730 //------------------------------------------------------------------------
731 // BasicBlock::firstNode: Returns the first node in the block.
732 //
733 GenTree* BasicBlock::firstNode()
734 {
735     return IsLIR() ? bbTreeList : Compiler::fgGetFirstNode(firstStmt()->gtStmtExpr);
736 }
737
738 //------------------------------------------------------------------------
739 // BasicBlock::lastNode: Returns the last node in the block.
740 //
741 GenTree* BasicBlock::lastNode()
742 {
743     return IsLIR() ? m_lastNode : lastStmt()->gtStmtExpr;
744 }
745
746 //------------------------------------------------------------------------
747 // GetUniquePred: Returns the unique predecessor of a block, if one exists.
748 // The predecessor lists must be accurate.
749 //
750 // Arguments:
751 //    None.
752 //
753 // Return Value:
754 //    The unique predecessor of a block, or nullptr if there is no unique predecessor.
755 //
756 // Notes:
757 //    If the first block has a predecessor (which it may have, if it is the target of
758 //    a backedge), we never want to consider it "unique" because the prolog is an
759 //    implicit predecessor.
760
761 BasicBlock* BasicBlock::GetUniquePred(Compiler* compiler)
762 {
763     if ((bbPreds == nullptr) || (bbPreds->flNext != nullptr) || (this == compiler->fgFirstBB))
764     {
765         return nullptr;
766     }
767     else
768     {
769         return bbPreds->flBlock;
770     }
771 }
772
773 //------------------------------------------------------------------------
774 // GetUniqueSucc: Returns the unique successor of a block, if one exists.
775 // Only considers BBJ_ALWAYS and BBJ_NONE block types.
776 //
777 // Arguments:
778 //    None.
779 //
780 // Return Value:
781 //    The unique successor of a block, or nullptr if there is no unique successor.
782
783 BasicBlock* BasicBlock::GetUniqueSucc()
784 {
785     if (bbJumpKind == BBJ_ALWAYS)
786     {
787         return bbJumpDest;
788     }
789     else if (bbJumpKind == BBJ_NONE)
790     {
791         return bbNext;
792     }
793     else
794     {
795         return nullptr;
796     }
797 }
798
799 // Static vars.
800 BasicBlock::MemoryPhiArg* BasicBlock::EmptyMemoryPhiDef = (BasicBlock::MemoryPhiArg*)0x1;
801
802 unsigned JitPtrKeyFuncs<BasicBlock>::GetHashCode(const BasicBlock* ptr)
803 {
804 #ifdef DEBUG
805     unsigned hash = SsaStressHashHelper();
806     if (hash != 0)
807     {
808         return (hash ^ (ptr->bbNum << 16) ^ ptr->bbNum);
809     }
810 #endif
811     return ptr->bbNum;
812 }
813
814 bool BasicBlock::isEmpty()
815 {
816     if (!IsLIR())
817     {
818         return (this->FirstNonPhiDef() == nullptr);
819     }
820
821     for (GenTree* node : LIR::AsRange(this).NonPhiNodes())
822     {
823         if (node->OperGet() != GT_IL_OFFSET)
824         {
825             return false;
826         }
827     }
828
829     return true;
830 }
831
832 GenTreeStmt* BasicBlock::FirstNonPhiDef()
833 {
834     GenTree* stmt = bbTreeList;
835     if (stmt == nullptr)
836     {
837         return nullptr;
838     }
839     GenTree* tree = stmt->gtStmt.gtStmtExpr;
840     while ((tree->OperGet() == GT_ASG && tree->gtOp.gtOp2->OperGet() == GT_PHI) ||
841            (tree->OperGet() == GT_STORE_LCL_VAR && tree->gtOp.gtOp1->OperGet() == GT_PHI))
842     {
843         stmt = stmt->gtNext;
844         if (stmt == nullptr)
845         {
846             return nullptr;
847         }
848         tree = stmt->gtStmt.gtStmtExpr;
849     }
850     return stmt->AsStmt();
851 }
852
853 GenTree* BasicBlock::FirstNonPhiDefOrCatchArgAsg()
854 {
855     GenTree* stmt = FirstNonPhiDef();
856     if (stmt == nullptr)
857     {
858         return nullptr;
859     }
860     GenTree* tree = stmt->gtStmt.gtStmtExpr;
861     if ((tree->OperGet() == GT_ASG && tree->gtOp.gtOp2->OperGet() == GT_CATCH_ARG) ||
862         (tree->OperGet() == GT_STORE_LCL_VAR && tree->gtOp.gtOp1->OperGet() == GT_CATCH_ARG))
863     {
864         stmt = stmt->gtNext;
865     }
866     return stmt;
867 }
868
869 /*****************************************************************************
870  *
871  *  Mark a block as rarely run, we also don't want to have a loop in a
872  *   rarely run block, and we set it's weight to zero.
873  */
874
875 void BasicBlock::bbSetRunRarely()
876 {
877     setBBWeight(BB_ZERO_WEIGHT);
878     if (bbWeight == BB_ZERO_WEIGHT)
879     {
880         bbFlags |= BBF_RUN_RARELY; // This block is never/rarely run
881     }
882 }
883
884 /*****************************************************************************
885  *
886  *  Can a BasicBlock be inserted after this without altering the flowgraph
887  */
888
889 bool BasicBlock::bbFallsThrough()
890 {
891     switch (bbJumpKind)
892     {
893
894         case BBJ_THROW:
895         case BBJ_EHFINALLYRET:
896         case BBJ_EHFILTERRET:
897         case BBJ_EHCATCHRET:
898         case BBJ_RETURN:
899         case BBJ_ALWAYS:
900         case BBJ_LEAVE:
901         case BBJ_SWITCH:
902             return false;
903
904         case BBJ_NONE:
905         case BBJ_COND:
906             return true;
907
908         case BBJ_CALLFINALLY:
909             return ((bbFlags & BBF_RETLESS_CALL) == 0);
910
911         default:
912             assert(!"Unknown bbJumpKind in bbFallsThrough()");
913             return true;
914     }
915 }
916
917 //------------------------------------------------------------------------
918 // NumSucc: Returns the count of block successors. See the declaration comment for details.
919 //
920 // Arguments:
921 //    None.
922 //
923 // Return Value:
924 //    Count of block successors.
925 //
926 unsigned BasicBlock::NumSucc()
927 {
928     switch (bbJumpKind)
929     {
930         case BBJ_THROW:
931         case BBJ_RETURN:
932         case BBJ_EHFINALLYRET:
933         case BBJ_EHFILTERRET:
934             return 0;
935
936         case BBJ_CALLFINALLY:
937         case BBJ_ALWAYS:
938         case BBJ_EHCATCHRET:
939         case BBJ_LEAVE:
940         case BBJ_NONE:
941             return 1;
942
943         case BBJ_COND:
944             if (bbJumpDest == bbNext)
945             {
946                 return 1;
947             }
948             else
949             {
950                 return 2;
951             }
952
953         case BBJ_SWITCH:
954             return bbJumpSwt->bbsCount;
955
956         default:
957             unreached();
958     }
959 }
960
961 //------------------------------------------------------------------------
962 // GetSucc: Returns the requested block successor. See the declaration comment for details.
963 //
964 // Arguments:
965 //    i - index of successor to return. 0 <= i <= NumSucc().
966 //
967 // Return Value:
968 //    Requested successor block
969 //
970 BasicBlock* BasicBlock::GetSucc(unsigned i)
971 {
972     assert(i < NumSucc()); // Index bounds check.
973     switch (bbJumpKind)
974     {
975         case BBJ_CALLFINALLY:
976         case BBJ_ALWAYS:
977         case BBJ_EHCATCHRET:
978         case BBJ_LEAVE:
979             return bbJumpDest;
980
981         case BBJ_NONE:
982             return bbNext;
983
984         case BBJ_COND:
985             if (i == 0)
986             {
987                 return bbNext;
988             }
989             else
990             {
991                 assert(i == 1);
992                 return bbJumpDest;
993             }
994
995         case BBJ_SWITCH:
996             return bbJumpSwt->bbsDstTab[i];
997
998         default:
999             unreached();
1000     }
1001 }
1002
1003 //------------------------------------------------------------------------
1004 // NumSucc: Returns the count of block successors. See the declaration comment for details.
1005 //
1006 // Arguments:
1007 //    comp - Compiler instance
1008 //
1009 // Return Value:
1010 //    Count of block successors.
1011 //
1012 unsigned BasicBlock::NumSucc(Compiler* comp)
1013 {
1014     assert(comp != nullptr);
1015
1016     switch (bbJumpKind)
1017     {
1018         case BBJ_THROW:
1019         case BBJ_RETURN:
1020             return 0;
1021
1022         case BBJ_EHFINALLYRET:
1023         {
1024             // The first block of the handler is labelled with the catch type.
1025             BasicBlock* hndBeg = comp->fgFirstBlockOfHandler(this);
1026             if (hndBeg->bbCatchTyp == BBCT_FINALLY)
1027             {
1028                 return comp->fgNSuccsOfFinallyRet(this);
1029             }
1030             else
1031             {
1032                 assert(hndBeg->bbCatchTyp == BBCT_FAULT); // We can only BBJ_EHFINALLYRET from FINALLY and FAULT.
1033                 // A FAULT block has no successors.
1034                 return 0;
1035             }
1036         }
1037
1038         case BBJ_CALLFINALLY:
1039         case BBJ_ALWAYS:
1040         case BBJ_EHCATCHRET:
1041         case BBJ_EHFILTERRET:
1042         case BBJ_LEAVE:
1043         case BBJ_NONE:
1044             return 1;
1045
1046         case BBJ_COND:
1047             if (bbJumpDest == bbNext)
1048             {
1049                 return 1;
1050             }
1051             else
1052             {
1053                 return 2;
1054             }
1055
1056         case BBJ_SWITCH:
1057         {
1058             Compiler::SwitchUniqueSuccSet sd = comp->GetDescriptorForSwitch(this);
1059             return sd.numDistinctSuccs;
1060         }
1061
1062         default:
1063             unreached();
1064     }
1065 }
1066
1067 //------------------------------------------------------------------------
1068 // GetSucc: Returns the requested block successor. See the declaration comment for details.
1069 //
1070 // Arguments:
1071 //    i - index of successor to return. 0 <= i <= NumSucc(comp).
1072 //    comp - Compiler instance
1073 //
1074 // Return Value:
1075 //    Requested successor block
1076 //
1077 BasicBlock* BasicBlock::GetSucc(unsigned i, Compiler* comp)
1078 {
1079     assert(comp != nullptr);
1080
1081     assert(i < NumSucc(comp)); // Index bounds check.
1082     switch (bbJumpKind)
1083     {
1084         case BBJ_EHFILTERRET:
1085         {
1086             // Handler is the (sole) normal successor of the filter.
1087             assert(comp->fgFirstBlockOfHandler(this) == bbJumpDest);
1088             return bbJumpDest;
1089         }
1090
1091         case BBJ_EHFINALLYRET:
1092             // Note: the following call is expensive.
1093             return comp->fgSuccOfFinallyRet(this, i);
1094
1095         case BBJ_CALLFINALLY:
1096         case BBJ_ALWAYS:
1097         case BBJ_EHCATCHRET:
1098         case BBJ_LEAVE:
1099             return bbJumpDest;
1100
1101         case BBJ_NONE:
1102             return bbNext;
1103
1104         case BBJ_COND:
1105             if (i == 0)
1106             {
1107                 return bbNext;
1108             }
1109             else
1110             {
1111                 assert(i == 1);
1112                 return bbJumpDest;
1113             }
1114
1115         case BBJ_SWITCH:
1116         {
1117             Compiler::SwitchUniqueSuccSet sd = comp->GetDescriptorForSwitch(this);
1118             assert(i < sd.numDistinctSuccs); // Range check.
1119             return sd.nonDuplicates[i];
1120         }
1121
1122         default:
1123             unreached();
1124     }
1125 }
1126
1127 void BasicBlock::InitVarSets(Compiler* comp)
1128 {
1129     VarSetOps::AssignNoCopy(comp, bbVarUse, VarSetOps::MakeEmpty(comp));
1130     VarSetOps::AssignNoCopy(comp, bbVarDef, VarSetOps::MakeEmpty(comp));
1131     VarSetOps::AssignNoCopy(comp, bbLiveIn, VarSetOps::MakeEmpty(comp));
1132     VarSetOps::AssignNoCopy(comp, bbLiveOut, VarSetOps::MakeEmpty(comp));
1133     VarSetOps::AssignNoCopy(comp, bbScope, VarSetOps::MakeEmpty(comp));
1134
1135     bbMemoryUse     = emptyMemoryKindSet;
1136     bbMemoryDef     = emptyMemoryKindSet;
1137     bbMemoryLiveIn  = emptyMemoryKindSet;
1138     bbMemoryLiveOut = emptyMemoryKindSet;
1139 }
1140
1141 // Returns true if the basic block ends with GT_JMP
1142 bool BasicBlock::endsWithJmpMethod(Compiler* comp)
1143 {
1144     if (comp->compJmpOpUsed && (bbJumpKind == BBJ_RETURN) && (bbFlags & BBF_HAS_JMP))
1145     {
1146         GenTree* lastNode = this->lastNode();
1147         assert(lastNode != nullptr);
1148         return lastNode->OperGet() == GT_JMP;
1149     }
1150
1151     return false;
1152 }
1153
1154 // Returns true if the basic block ends with either
1155 //  i) GT_JMP or
1156 // ii) tail call (implicit or explicit)
1157 //
1158 // Params:
1159 //    comp              - Compiler instance
1160 //    fastTailCallsOnly - Only consider fast tail calls excluding tail calls via helper.
1161 //
1162 bool BasicBlock::endsWithTailCallOrJmp(Compiler* comp, bool fastTailCallsOnly /*=false*/)
1163 {
1164     GenTree* tailCall                       = nullptr;
1165     bool     tailCallsConvertibleToLoopOnly = false;
1166     return endsWithJmpMethod(comp) ||
1167            endsWithTailCall(comp, fastTailCallsOnly, tailCallsConvertibleToLoopOnly, &tailCall);
1168 }
1169
1170 //------------------------------------------------------------------------------
1171 // endsWithTailCall : Check if the block ends with a tail call.
1172 //
1173 // Arguments:
1174 //    comp                            - compiler instance
1175 //    fastTailCallsOnly               - check for fast tail calls only
1176 //    tailCallsConvertibleToLoopOnly  - check for tail calls convertible to loop only
1177 //    tailCall                        - a pointer to a tree that will be set to the call tree if the block
1178 //                                      ends with a tail call and will be set to nullptr otherwise.
1179 //
1180 // Return Value:
1181 //    true if the block ends with a tail call; false otherwise.
1182 //
1183 // Notes:
1184 //    At most one of fastTailCallsOnly and tailCallsConvertibleToLoopOnly flags can be true.
1185 //
1186 bool BasicBlock::endsWithTailCall(Compiler* comp,
1187                                   bool      fastTailCallsOnly,
1188                                   bool      tailCallsConvertibleToLoopOnly,
1189                                   GenTree** tailCall)
1190 {
1191     assert(!fastTailCallsOnly || !tailCallsConvertibleToLoopOnly);
1192     *tailCall   = nullptr;
1193     bool result = false;
1194
1195     // Is this a tail call?
1196     // The reason for keeping this under RyuJIT is so as not to impact existing Jit32 x86 and arm
1197     // targets.
1198     if (comp->compTailCallUsed)
1199     {
1200         if (fastTailCallsOnly || tailCallsConvertibleToLoopOnly)
1201         {
1202             // Only fast tail calls or only tail calls convertible to loops
1203             result = (bbFlags & BBF_HAS_JMP) && (bbJumpKind == BBJ_RETURN);
1204         }
1205         else
1206         {
1207             // Fast tail calls, tail calls convertible to loops, and tails calls dispatched via helper
1208             result = (bbJumpKind == BBJ_THROW) || ((bbFlags & BBF_HAS_JMP) && (bbJumpKind == BBJ_RETURN));
1209         }
1210
1211         if (result)
1212         {
1213             GenTree* lastNode = this->lastNode();
1214             if (lastNode->OperGet() == GT_CALL)
1215             {
1216                 GenTreeCall* call = lastNode->AsCall();
1217                 if (tailCallsConvertibleToLoopOnly)
1218                 {
1219                     result = call->IsTailCallConvertibleToLoop();
1220                 }
1221                 else if (fastTailCallsOnly)
1222                 {
1223                     result = call->IsFastTailCall();
1224                 }
1225                 else
1226                 {
1227                     result = call->IsTailCall();
1228                 }
1229
1230                 if (result)
1231                 {
1232                     *tailCall = call;
1233                 }
1234             }
1235             else
1236             {
1237                 result = false;
1238             }
1239         }
1240     }
1241
1242     return result;
1243 }
1244
1245 //------------------------------------------------------------------------------
1246 // endsWithTailCallConvertibleToLoop : Check if the block ends with a tail call convertible to loop.
1247 //
1248 // Arguments:
1249 //    comp  -  compiler instance
1250 //    tailCall  -  a pointer to a tree that will be set to the call tree if the block
1251 //                 ends with a tail call convertible to loop and will be set to nullptr otherwise.
1252 //
1253 // Return Value:
1254 //    true if the block ends with a tail call convertible to loop.
1255 //
1256 bool BasicBlock::endsWithTailCallConvertibleToLoop(Compiler* comp, GenTree** tailCall)
1257 {
1258     bool fastTailCallsOnly              = false;
1259     bool tailCallsConvertibleToLoopOnly = true;
1260     return endsWithTailCall(comp, fastTailCallsOnly, tailCallsConvertibleToLoopOnly, tailCall);
1261 }
1262
1263 /*****************************************************************************
1264  *
1265  *  Allocate a basic block but don't append it to the current BB list.
1266  */
1267
1268 BasicBlock* Compiler::bbNewBasicBlock(BBjumpKinds jumpKind)
1269 {
1270     BasicBlock* block;
1271
1272     /* Allocate the block descriptor and zero it out */
1273     assert(fgSafeBasicBlockCreation);
1274
1275     block = new (this, CMK_BasicBlock) BasicBlock;
1276
1277 #if MEASURE_BLOCK_SIZE
1278     BasicBlock::s_Count += 1;
1279     BasicBlock::s_Size += sizeof(*block);
1280 #endif
1281
1282 #ifdef DEBUG
1283     // fgLookupBB() is invalid until fgInitBBLookup() is called again.
1284     fgBBs = (BasicBlock**)0xCDCD;
1285 #endif
1286
1287     // TODO-Throughput: The following memset is pretty expensive - do something else?
1288     // Note that some fields have to be initialized to 0 (like bbFPStateX87)
1289     memset(block, 0, sizeof(*block));
1290
1291     // scopeInfo needs to be able to differentiate between blocks which
1292     // correspond to some instrs (and so may have some LocalVarInfo
1293     // boundaries), or have been inserted by the JIT
1294     block->bbCodeOffs    = BAD_IL_OFFSET;
1295     block->bbCodeOffsEnd = BAD_IL_OFFSET;
1296
1297 #ifdef DEBUG
1298     block->bbID = compBasicBlockID++;
1299 #endif
1300
1301     /* Give the block a number, set the ancestor count and weight */
1302
1303     ++fgBBcount;
1304
1305     if (compIsForInlining())
1306     {
1307         block->bbNum = ++impInlineInfo->InlinerCompiler->fgBBNumMax;
1308     }
1309     else
1310     {
1311         block->bbNum = ++fgBBNumMax;
1312     }
1313
1314 #ifndef LEGACY_BACKEND
1315     if (compRationalIRForm)
1316     {
1317         block->bbFlags |= BBF_IS_LIR;
1318     }
1319 #endif // !LEGACY_BACKEND
1320
1321     block->bbRefs   = 1;
1322     block->bbWeight = BB_UNITY_WEIGHT;
1323
1324     block->bbStkTempsIn  = NO_BASE_TMP;
1325     block->bbStkTempsOut = NO_BASE_TMP;
1326
1327     block->bbEntryState = nullptr;
1328
1329     /* Record the jump kind in the block */
1330
1331     block->bbJumpKind = jumpKind;
1332
1333     if (jumpKind == BBJ_THROW)
1334     {
1335         block->bbSetRunRarely();
1336     }
1337
1338 #ifdef DEBUG
1339     if (verbose)
1340     {
1341         printf("New Basic Block %s created.\n", block->dspToString());
1342     }
1343 #endif
1344
1345     // We will give all the blocks var sets after the number of tracked variables
1346     // is determined and frozen.  After that, if we dynamically create a basic block,
1347     // we will initialize its var sets.
1348     if (fgBBVarSetsInited)
1349     {
1350         VarSetOps::AssignNoCopy(this, block->bbVarUse, VarSetOps::MakeEmpty(this));
1351         VarSetOps::AssignNoCopy(this, block->bbVarDef, VarSetOps::MakeEmpty(this));
1352         VarSetOps::AssignNoCopy(this, block->bbLiveIn, VarSetOps::MakeEmpty(this));
1353         VarSetOps::AssignNoCopy(this, block->bbLiveOut, VarSetOps::MakeEmpty(this));
1354         VarSetOps::AssignNoCopy(this, block->bbScope, VarSetOps::MakeEmpty(this));
1355     }
1356     else
1357     {
1358         VarSetOps::AssignNoCopy(this, block->bbVarUse, VarSetOps::UninitVal());
1359         VarSetOps::AssignNoCopy(this, block->bbVarDef, VarSetOps::UninitVal());
1360         VarSetOps::AssignNoCopy(this, block->bbLiveIn, VarSetOps::UninitVal());
1361         VarSetOps::AssignNoCopy(this, block->bbLiveOut, VarSetOps::UninitVal());
1362         VarSetOps::AssignNoCopy(this, block->bbScope, VarSetOps::UninitVal());
1363     }
1364
1365     block->bbMemoryUse     = emptyMemoryKindSet;
1366     block->bbMemoryDef     = emptyMemoryKindSet;
1367     block->bbMemoryLiveIn  = emptyMemoryKindSet;
1368     block->bbMemoryLiveOut = emptyMemoryKindSet;
1369
1370     for (MemoryKind memoryKind : allMemoryKinds())
1371     {
1372         block->bbMemorySsaPhiFunc[memoryKind] = nullptr;
1373         block->bbMemorySsaNumIn[memoryKind]   = 0;
1374         block->bbMemorySsaNumOut[memoryKind]  = 0;
1375     }
1376
1377     // Make sure we reserve a NOT_IN_LOOP value that isn't a legal table index.
1378     static_assert_no_msg(MAX_LOOP_NUM < BasicBlock::NOT_IN_LOOP);
1379
1380     block->bbNatLoopNum = BasicBlock::NOT_IN_LOOP;
1381
1382     return block;
1383 }