Make GT_LIST processing non-recursive to avoid StackOverflow.
[platform/upstream/coreclr.git] / src / jit / compiler.h
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                           Compiler                                        XX
9 XX                                                                           XX
10 XX  Represents the method data we are currently JIT-compiling.               XX
11 XX  An instance of this class is created for every method we JIT.            XX
12 XX  This contains all the info needed for the method. So allocating a        XX
13 XX  a new instance per method makes it thread-safe.                          XX
14 XX  It should be used to do all the memory management for the compiler run.  XX
15 XX                                                                           XX
16 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
17 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
18 */
19
20 /*****************************************************************************/
21 #ifndef _COMPILER_H_
22 #define _COMPILER_H_
23 /*****************************************************************************/
24
25 #include "jit.h"
26 #include "opcode.h"
27 #include "varset.h"
28 #include "gentree.h"
29 #include "lir.h"
30 #include "block.h"
31 #include "inline.h"
32 #include "jiteh.h"
33 #include "instr.h"
34 #include "regalloc.h"
35 #include "sm.h"
36 #include "simplerhash.h"
37 #include "cycletimer.h"
38 #include "blockset.h"
39 #include "jitstd.h"
40 #include "arraystack.h"
41 #include "hashbv.h"
42 #include "fp.h"
43 #include "expandarray.h"
44 #include "tinyarray.h"
45 #include "valuenum.h"
46 #include "reglist.h"
47 #include "jittelemetry.h"
48 #ifdef LATE_DISASM
49 #include "disasm.h"
50 #endif
51
52 #include "codegeninterface.h"
53 #include "regset.h"
54 #include "jitgcinfo.h"
55
56 #if DUMP_GC_TABLES && defined(JIT32_GCENCODER)
57 #include "gcdump.h"
58 #endif
59
60 #include "emit.h"
61
62 #include "simd.h"
63
64 // This is only used locally in the JIT to indicate that
65 // a verification block should be inserted
66 #define SEH_VERIFICATION_EXCEPTION 0xe0564552 // VER
67
68 /*****************************************************************************
69  *                  Forward declarations
70  */
71
72 struct InfoHdr;            // defined in GCInfo.h
73 struct escapeMapping_t;    // defined in flowgraph.cpp
74 class emitter;             // defined in emit.h
75 struct ShadowParamVarInfo; // defined in GSChecks.cpp
76 struct InitVarDscInfo;     // defined in register_arg_convention.h
77 class FgStack;             // defined in flowgraph.cpp
78 #if FEATURE_STACK_FP_X87
79 struct FlatFPStateX87; // defined in fp.h
80 #endif
81 #if FEATURE_ANYCSE
82 class CSE_DataFlow; // defined in OptCSE.cpp
83 #endif
84 #ifdef DEBUG
85 struct IndentStack;
86 #endif
87
88 // The following are defined in this file, Compiler.h
89
90 class Compiler;
91
92 /*****************************************************************************
93  *                  Unwind info
94  */
95
96 #include "unwind.h"
97
98 /*****************************************************************************/
99
100 //
101 // Declare global operator new overloads that use the Compiler::compGetMem() function for allocation.
102 //
103
104 // Or the more-general IAllocator interface.
105 void* __cdecl operator new(size_t n, IAllocator* alloc);
106 void* __cdecl operator new[](size_t n, IAllocator* alloc);
107
108 // I wanted to make the second argument optional, with default = CMK_Unknown, but that
109 // caused these to be ambiguous with the global placement new operators.
110 void* __cdecl operator new(size_t n, Compiler* context, CompMemKind cmk);
111 void* __cdecl operator new[](size_t n, Compiler* context, CompMemKind cmk);
112 void* __cdecl operator new(size_t n, void* p, const jitstd::placement_t& syntax_difference);
113
114 // Requires the definitions of "operator new" so including "LoopCloning.h" after the definitions.
115 #include "loopcloning.h"
116
117 /*****************************************************************************/
118
119 /* This is included here and not earlier as it needs the definition of "CSE"
120  * which is defined in the section above */
121
122 /*****************************************************************************/
123
124 unsigned genLog2(unsigned value);
125 unsigned genLog2(unsigned __int64 value);
126
127 var_types genActualType(var_types type);
128 var_types genUnsignedType(var_types type);
129 var_types genSignedType(var_types type);
130
131 unsigned ReinterpretHexAsDecimal(unsigned);
132
133 /*****************************************************************************/
134
135 #ifdef FEATURE_SIMD
136 #ifdef FEATURE_AVX_SUPPORT
137 const unsigned TEMP_MAX_SIZE = YMM_REGSIZE_BYTES;
138 #else  // !FEATURE_AVX_SUPPORT
139 const unsigned TEMP_MAX_SIZE = XMM_REGSIZE_BYTES;
140 #endif // !FEATURE_AVX_SUPPORT
141 #else  // !FEATURE_SIMD
142 const unsigned TEMP_MAX_SIZE = sizeof(double);
143 #endif // !FEATURE_SIMD
144 const unsigned TEMP_SLOT_COUNT = (TEMP_MAX_SIZE / sizeof(int));
145
146 const unsigned FLG_CCTOR = (CORINFO_FLG_CONSTRUCTOR | CORINFO_FLG_STATIC);
147
148 #ifdef DEBUG
149 const int BAD_STK_OFFS = 0xBAADF00D; // for LclVarDsc::lvStkOffs
150 #endif
151
152 // The following holds the Local var info (scope information)
153 typedef const char* VarName; // Actual ASCII string
154 struct VarScopeDsc
155 {
156     IL_OFFSET vsdLifeBeg; // instr offset of beg of life
157     IL_OFFSET vsdLifeEnd; // instr offset of end of life
158     unsigned  vsdVarNum;  // (remapped) LclVarDsc number
159
160 #ifdef DEBUG
161     VarName vsdName; // name of the var
162 #endif
163
164     unsigned vsdLVnum; // 'which' in eeGetLVinfo().
165                        // Also, it is the index of this entry in the info.compVarScopes array,
166                        // which is useful since the array is also accessed via the
167                        // compEnterScopeList and compExitScopeList sorted arrays.
168 };
169
170 /*****************************************************************************
171  *
172  *  The following holds the local variable counts and the descriptor table.
173  */
174
175 // This is the location of a definition.
176 struct DefLoc
177 {
178     BasicBlock* m_blk;
179     GenTreePtr  m_tree;
180
181     DefLoc() : m_blk(nullptr), m_tree(nullptr)
182     {
183     }
184 };
185
186 // This class encapsulates all info about a local variable that may vary for different SSA names
187 // in the family.
188 class LclSsaVarDsc
189 {
190 public:
191     ValueNumPair m_vnPair;
192     DefLoc       m_defLoc;
193
194     LclSsaVarDsc()
195     {
196     }
197 };
198
199 typedef ExpandArray<LclSsaVarDsc> PerSsaArray;
200
201 class LclVarDsc
202 {
203 public:
204     // The constructor. Most things can just be zero'ed.
205     LclVarDsc(Compiler* comp);
206
207     // note this only packs because var_types is a typedef of unsigned char
208     var_types lvType : 5; // TYP_INT/LONG/FLOAT/DOUBLE/REF
209
210     unsigned char lvIsParam : 1;           // is this a parameter?
211     unsigned char lvIsRegArg : 1;          // is this a register argument?
212     unsigned char lvFramePointerBased : 1; // 0 = off of REG_SPBASE (e.g., ESP), 1 = off of REG_FPBASE (e.g., EBP)
213
214     unsigned char lvStructGcCount : 3; // if struct, how many GC pointer (stop counting at 7). The only use of values >1
215                                        // is to help determine whether to use block init in the prolog.
216     unsigned char lvOnFrame : 1;       // (part of) the variable lives on the frame
217     unsigned char lvDependReg : 1;     // did the predictor depend upon this being enregistered
218     unsigned char lvRegister : 1;      // assigned to live in a register? For RyuJIT backend, this is only set if the
219                                        // variable is in the same register for the entire function.
220     unsigned char lvTracked : 1;       // is this a tracked variable?
221     bool          lvTrackedNonStruct()
222     {
223         return lvTracked && lvType != TYP_STRUCT;
224     }
225     unsigned char lvPinned : 1; // is this a pinned variable?
226
227     unsigned char lvMustInit : 1;    // must be initialized
228     unsigned char lvAddrExposed : 1; // The address of this variable is "exposed" -- passed as an argument, stored in a
229                                      // global location, etc.
230                                      // We cannot reason reliably about the value of the variable.
231     unsigned char lvDoNotEnregister : 1; // Do not enregister this variable.
232     unsigned char lvFieldAccessed : 1;   // The var is a struct local, and a field of the variable is accessed.  Affects
233                                          // struct promotion.
234
235 #ifdef DEBUG
236     // These further document the reasons for setting "lvDoNotEnregister".  (Note that "lvAddrExposed" is one of the
237     // reasons;
238     // also, lvType == TYP_STRUCT prevents enregistration.  At least one of the reasons should be true.
239     unsigned char lvVMNeedsStackAddr : 1; // The VM may have access to a stack-relative address of the variable, and
240                                           // read/write its value.
241     unsigned char lvLiveInOutOfHndlr : 1; // The variable was live in or out of an exception handler, and this required
242                                           // the variable to be
243                                           // in the stack (at least at those boundaries.)
244     unsigned char lvLclFieldExpr : 1;     // The variable is not a struct, but was accessed like one (e.g., reading a
245                                           // particular byte from an int).
246     unsigned char lvLclBlockOpAddr : 1;   // The variable was written to via a block operation that took its address.
247     unsigned char lvLiveAcrossUCall : 1;  // The variable is live across an unmanaged call.
248 #endif
249     unsigned char lvIsCSE : 1;       // Indicates if this LclVar is a CSE variable.
250     unsigned char lvRefAssign : 1;   // involved in pointer assignment
251     unsigned char lvHasLdAddrOp : 1; // has ldloca or ldarga opcode on this local.
252     unsigned char lvStackByref : 1;  // This is a compiler temporary of TYP_BYREF that is known to point into our local
253                                      // stack frame.
254
255     unsigned char lvArgWrite : 1; // variable is a parameter and STARG was used on it
256     unsigned char lvIsTemp : 1;   // Short-lifetime compiler temp
257 #if OPT_BOOL_OPS
258     unsigned char lvIsBoolean : 1; // set if variable is boolean
259 #endif
260     unsigned char lvRngOptDone : 1; // considered for range check opt?
261     unsigned char lvLoopInc : 1;    // incremented in the loop?
262     unsigned char lvLoopAsg : 1;    // reassigned  in the loop (other than a monotonic inc/dec for the index var)?
263     unsigned char lvArrIndx : 1;    // used as an array index?
264     unsigned char lvArrIndxOff : 1; // used as an array index with an offset?
265     unsigned char lvArrIndxDom : 1; // index dominates loop exit
266 #if ASSERTION_PROP
267     unsigned char lvSingleDef : 1;    // variable has a single def
268     unsigned char lvDisqualify : 1;   // variable is no longer OK for add copy optimization
269     unsigned char lvVolatileHint : 1; // hint for AssertionProp
270 #endif
271 #if FANCY_ARRAY_OPT
272     unsigned char lvAssignOne : 1; // assigned at least  once?
273     unsigned char lvAssignTwo : 1; // assigned at least twice?
274 #endif
275
276     unsigned char lvSpilled : 1; // enregistered variable was spilled
277 #ifndef _TARGET_64BIT_
278     unsigned char lvStructDoubleAlign : 1; // Must we double align this struct?
279 #endif                                     // !_TARGET_64BIT_
280 #ifdef _TARGET_64BIT_
281     unsigned char lvQuirkToLong : 1; // Quirk to allocate this LclVar as a 64-bit long
282 #endif
283 #ifdef DEBUG
284     unsigned char lvKeepType : 1;       // Don't change the type of this variable
285     unsigned char lvNoLclFldStress : 1; // Can't apply local field stress on this one
286 #endif
287     unsigned char lvIsPtr : 1; // Might this be used in an address computation? (used by buffer overflow security
288                                // checks)
289     unsigned char lvIsUnsafeBuffer : 1; // Does this contain an unsafe buffer requiring buffer overflow security checks?
290     unsigned char lvPromoted : 1; // True when this local is a promoted struct, a normed struct, or a "split" long on a
291                                   // 32-bit target.
292     unsigned char lvIsStructField : 1;          // Is this local var a field of a promoted struct local?
293     unsigned char lvContainsFloatingFields : 1; // Does this struct contains floating point fields?
294     unsigned char lvOverlappingFields : 1;      // True when we have a struct with possibly overlapping fields
295     unsigned char lvContainsHoles : 1;          // True when we have a promoted struct that contains holes
296     unsigned char lvCustomLayout : 1;           // True when this struct has "CustomLayout"
297
298     unsigned char lvIsMultiRegArg : 1; // true if this is a multireg LclVar struct used in an argument context
299     unsigned char lvIsMultiRegRet : 1; // true if this is a multireg LclVar struct assigned from a multireg call
300
301 #ifdef FEATURE_HFA
302     unsigned char _lvIsHfa : 1;          // Is this a struct variable who's class handle is an HFA type
303     unsigned char _lvIsHfaRegArg : 1;    // Is this a HFA argument variable?    // TODO-CLEANUP: Remove this and replace
304                                          // with (lvIsRegArg && lvIsHfa())
305     unsigned char _lvHfaTypeIsFloat : 1; // Is the HFA type float or double?
306 #endif                                   // FEATURE_HFA
307
308 #ifdef DEBUG
309     // TODO-Cleanup: See the note on lvSize() - this flag is only in use by asserts that are checking for struct
310     // types, and is needed because of cases where TYP_STRUCT is bashed to an integral type.
311     // Consider cleaning this up so this workaround is not required.
312     unsigned char lvUnusedStruct : 1; // All references to this promoted struct are through its field locals.
313                                       // I.e. there is no longer any reference to the struct directly.
314                                       // In this case we can simply remove this struct local.
315 #endif
316 #ifndef LEGACY_BACKEND
317     unsigned char lvLRACandidate : 1; // Tracked for linear scan register allocation purposes
318 #endif                                // !LEGACY_BACKEND
319
320 #ifdef FEATURE_SIMD
321     // Note that both SIMD vector args and locals are marked as lvSIMDType = true, but the
322     // type of an arg node is TYP_BYREF and a local node is TYP_SIMD*.
323     unsigned char lvSIMDType : 1;            // This is a SIMD struct
324     unsigned char lvUsedInSIMDIntrinsic : 1; // This tells lclvar is used for simd intrinsic
325 #endif                                       // FEATURE_SIMD
326     unsigned char lvRegStruct : 1;           // This is a reg-sized non-field-addressed struct.
327
328     union {
329         unsigned lvFieldLclStart; // The index of the local var representing the first field in the promoted struct
330                                   // local.
331         unsigned lvParentLcl; // The index of the local var representing the parent (i.e. the promoted struct local).
332                               // Valid on promoted struct local fields.
333 #ifdef FEATURE_SIMD
334         var_types lvBaseType; // The base type of a SIMD local var.  Valid on TYP_SIMD locals.
335 #endif                        // FEATURE_SIMD
336     };
337
338     unsigned char lvFieldCnt; //  Number of fields in the promoted VarDsc.
339     unsigned char lvFldOffset;
340     unsigned char lvFldOrdinal;
341
342 #if FEATURE_MULTIREG_ARGS
343     regNumber lvRegNumForSlot(unsigned slotNum)
344     {
345         if (slotNum == 0)
346         {
347             return lvArgReg;
348         }
349         else if (slotNum == 1)
350         {
351             return lvOtherArgReg;
352         }
353         else
354         {
355             assert(false && "Invalid slotNum!");
356         }
357
358         unreached();
359     }
360 #endif // FEATURE_MULTIREG_ARGS
361
362     bool lvIsHfa() const
363     {
364 #ifdef FEATURE_HFA
365         return _lvIsHfa;
366 #else
367         return false;
368 #endif
369     }
370
371     void lvSetIsHfa()
372     {
373 #ifdef FEATURE_HFA
374         _lvIsHfa = true;
375 #endif
376     }
377
378     bool lvIsHfaRegArg() const
379     {
380 #ifdef FEATURE_HFA
381         return _lvIsHfaRegArg;
382 #else
383         return false;
384 #endif
385     }
386
387     void lvSetIsHfaRegArg()
388     {
389 #ifdef FEATURE_HFA
390         _lvIsHfaRegArg = true;
391 #endif
392     }
393
394     bool lvHfaTypeIsFloat() const
395     {
396 #ifdef FEATURE_HFA
397         return _lvHfaTypeIsFloat;
398 #else
399         return false;
400 #endif
401     }
402
403     void lvSetHfaTypeIsFloat(bool value)
404     {
405 #ifdef FEATURE_HFA
406         _lvHfaTypeIsFloat = value;
407 #endif
408     }
409
410     // on Arm64 - Returns 1-4 indicating the number of register slots used by the HFA
411     // on Arm32 - Returns the total number of single FP register slots used by the HFA, max is 8
412     //
413     unsigned lvHfaSlots() const
414     {
415         assert(lvIsHfa());
416         assert(lvType == TYP_STRUCT);
417 #ifdef _TARGET_ARM_
418         return lvExactSize / sizeof(float);
419 #else  //  _TARGET_ARM64_
420         if (lvHfaTypeIsFloat())
421         {
422             return lvExactSize / sizeof(float);
423         }
424         else
425         {
426             return lvExactSize / sizeof(double);
427         }
428 #endif //  _TARGET_ARM64_
429     }
430
431     // lvIsMultiRegArgOrRet()
432     //     returns true if this is a multireg LclVar struct used in an argument context
433     //               or if this is a multireg LclVar struct assigned from a multireg call
434     bool lvIsMultiRegArgOrRet()
435     {
436         return lvIsMultiRegArg || lvIsMultiRegRet;
437     }
438
439 private:
440     regNumberSmall _lvRegNum; // Used to store the register this variable is in (or, the low register of a
441                               // register pair). For LEGACY_BACKEND, this is only set if lvRegister is
442                               // non-zero. For non-LEGACY_BACKEND, it is set during codegen any time the
443                               // variable is enregistered (in non-LEGACY_BACKEND, lvRegister is only set
444                               // to non-zero if the variable gets the same register assignment for its entire
445                               // lifetime).
446 #if !defined(_TARGET_64BIT_)
447     regNumberSmall _lvOtherReg; // Used for "upper half" of long var.
448 #endif                          // !defined(_TARGET_64BIT_)
449
450     regNumberSmall _lvArgReg; // The register in which this argument is passed.
451
452 #if FEATURE_MULTIREG_ARGS
453     regNumberSmall _lvOtherArgReg; // Used for the second part of the struct passed in a register.
454                                    // Note this is defined but not used by ARM32
455 #endif                             // FEATURE_MULTIREG_ARGS
456
457 #ifndef LEGACY_BACKEND
458     union {
459         regNumberSmall _lvArgInitReg;     // the register      into which the argument is moved at entry
460         regPairNoSmall _lvArgInitRegPair; // the register pair into which the argument is moved at entry
461     };
462 #endif // !LEGACY_BACKEND
463
464 public:
465     // The register number is stored in a small format (8 bits), but the getters return and the setters take
466     // a full-size (unsigned) format, to localize the casts here.
467
468     /////////////////////
469
470     __declspec(property(get = GetRegNum, put = SetRegNum)) regNumber lvRegNum;
471
472     regNumber GetRegNum() const
473     {
474         return (regNumber)_lvRegNum;
475     }
476
477     void SetRegNum(regNumber reg)
478     {
479         _lvRegNum = (regNumberSmall)reg;
480         assert(_lvRegNum == reg);
481     }
482
483 /////////////////////
484
485 #if defined(_TARGET_64BIT_)
486     __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
487
488     regNumber GetOtherReg() const
489     {
490         assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
491                                        // "unreachable code" warnings
492         return REG_NA;
493     }
494
495     void SetOtherReg(regNumber reg)
496     {
497         assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
498                                        // "unreachable code" warnings
499     }
500 #else  // !_TARGET_64BIT_
501     __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
502
503     regNumber GetOtherReg() const
504     {
505         return (regNumber)_lvOtherReg;
506     }
507
508     void SetOtherReg(regNumber reg)
509     {
510         _lvOtherReg = (regNumberSmall)reg;
511         assert(_lvOtherReg == reg);
512     }
513 #endif // !_TARGET_64BIT_
514
515     /////////////////////
516
517     __declspec(property(get = GetArgReg, put = SetArgReg)) regNumber lvArgReg;
518
519     regNumber GetArgReg() const
520     {
521         return (regNumber)_lvArgReg;
522     }
523
524     void SetArgReg(regNumber reg)
525     {
526         _lvArgReg = (regNumberSmall)reg;
527         assert(_lvArgReg == reg);
528     }
529
530 #if FEATURE_MULTIREG_ARGS
531     __declspec(property(get = GetOtherArgReg, put = SetOtherArgReg)) regNumber lvOtherArgReg;
532
533     regNumber GetOtherArgReg() const
534     {
535         return (regNumber)_lvOtherArgReg;
536     }
537
538     void SetOtherArgReg(regNumber reg)
539     {
540         _lvOtherArgReg = (regNumberSmall)reg;
541         assert(_lvOtherArgReg == reg);
542     }
543 #endif // FEATURE_MULTIREG_ARGS
544
545 #ifdef FEATURE_SIMD
546     // Is this is a SIMD struct?
547     bool lvIsSIMDType() const
548     {
549         return lvSIMDType;
550     }
551
552     // Is this is a SIMD struct which is used for SIMD intrinsic?
553     bool lvIsUsedInSIMDIntrinsic() const
554     {
555         return lvUsedInSIMDIntrinsic;
556     }
557 #else
558     // If feature_simd not enabled, return false
559     bool lvIsSIMDType() const
560     {
561         return false;
562     }
563     bool lvIsUsedInSIMDIntrinsic() const
564     {
565         return false;
566     }
567 #endif
568
569 /////////////////////
570
571 #ifndef LEGACY_BACKEND
572     __declspec(property(get = GetArgInitReg, put = SetArgInitReg)) regNumber lvArgInitReg;
573
574     regNumber GetArgInitReg() const
575     {
576         return (regNumber)_lvArgInitReg;
577     }
578
579     void SetArgInitReg(regNumber reg)
580     {
581         _lvArgInitReg = (regNumberSmall)reg;
582         assert(_lvArgInitReg == reg);
583     }
584
585     /////////////////////
586
587     __declspec(property(get = GetArgInitRegPair, put = SetArgInitRegPair)) regPairNo lvArgInitRegPair;
588
589     regPairNo GetArgInitRegPair() const
590     {
591         regPairNo regPair = (regPairNo)_lvArgInitRegPair;
592         assert(regPair >= REG_PAIR_FIRST && regPair <= REG_PAIR_LAST);
593         return regPair;
594     }
595
596     void SetArgInitRegPair(regPairNo regPair)
597     {
598         assert(regPair >= REG_PAIR_FIRST && regPair <= REG_PAIR_LAST);
599         _lvArgInitRegPair = (regPairNoSmall)regPair;
600         assert(_lvArgInitRegPair == regPair);
601     }
602
603     /////////////////////
604
605     bool lvIsRegCandidate() const
606     {
607         return lvLRACandidate != 0;
608     }
609
610     bool lvIsInReg() const
611     {
612         return lvIsRegCandidate() && (lvRegNum != REG_STK);
613     }
614
615 #else // LEGACY_BACKEND
616
617     bool lvIsRegCandidate() const
618     {
619         return lvTracked != 0;
620     }
621
622     bool lvIsInReg() const
623     {
624         return lvRegister != 0;
625     }
626
627 #endif // LEGACY_BACKEND
628
629     regMaskTP lvRegMask() const
630     {
631         regMaskTP regMask = RBM_NONE;
632         if (varTypeIsFloating(TypeGet()))
633         {
634             if (lvRegNum != REG_STK)
635             {
636                 regMask = genRegMaskFloat(lvRegNum, TypeGet());
637             }
638         }
639         else
640         {
641             if (lvRegNum != REG_STK)
642             {
643                 regMask = genRegMask(lvRegNum);
644             }
645
646             // For longs we may have two regs
647             if (isRegPairType(lvType) && lvOtherReg != REG_STK)
648             {
649                 regMask |= genRegMask(lvOtherReg);
650             }
651         }
652         return regMask;
653     }
654
655     regMaskSmall lvPrefReg; // set of regs it prefers to live in
656
657     unsigned short lvVarIndex;  // variable tracking index
658     unsigned short lvRefCnt;    // unweighted (real) reference count
659     unsigned       lvRefCntWtd; // weighted reference count
660     int            lvStkOffs;   // stack offset of home
661     unsigned       lvExactSize; // (exact) size of the type in bytes
662
663     // Is this a promoted struct?
664     // This method returns true only for structs (including SIMD structs), not for
665     // locals that are split on a 32-bit target.
666     // It is only necessary to use this:
667     //   1) if only structs are wanted, and
668     //   2) if Lowering has already been done.
669     // Otherwise lvPromoted is valid.
670     bool lvPromotedStruct()
671     {
672 #if !defined(_TARGET_64BIT_)
673         return (lvPromoted && !varTypeIsLong(lvType));
674 #else  // defined(_TARGET_64BIT_)
675         return lvPromoted;
676 #endif // defined(_TARGET_64BIT_)
677     }
678
679     unsigned lvSize() // Size needed for storage representation. Only used for structs or TYP_BLK.
680     {
681         // TODO-Review: Sometimes we get called on ARM with HFA struct variables that have been promoted,
682         // where the struct itself is no longer used because all access is via its member fields.
683         // When that happens, the struct is marked as unused and its type has been changed to
684         // TYP_INT (to keep the GC tracking code from looking at it).
685         // See Compiler::raAssignVars() for details. For example:
686         //      N002 (  4,  3) [00EA067C] -------------               return    struct $346
687         //      N001 (  3,  2) [00EA0628] -------------                  lclVar    struct(U) V03 loc2
688         //                                                                        float  V03.f1 (offs=0x00) -> V12 tmp7
689         //                                                                        f8 (last use) (last use) $345
690         // Here, the "struct(U)" shows that the "V03 loc2" variable is unused. Not shown is that V03
691         // is now TYP_INT in the local variable table. It's not really unused, because it's in the tree.
692
693         assert(varTypeIsStruct(lvType) || (lvType == TYP_BLK) || (lvPromoted && lvUnusedStruct));
694         return (unsigned)(roundUp(lvExactSize, TARGET_POINTER_SIZE));
695     }
696
697 #if defined(DEBUGGING_SUPPORT) || defined(DEBUG)
698     unsigned lvSlotNum; // original slot # (if remapped)
699 #endif
700
701     typeInfo lvVerTypeInfo; // type info needed for verification
702
703     BYTE* lvGcLayout; // GC layout info for structs
704
705 #if FANCY_ARRAY_OPT
706     GenTreePtr lvKnownDim; // array size if known
707 #endif
708
709 #if ASSERTION_PROP
710     BlockSet   lvRefBlks;          // Set of blocks that contain refs
711     GenTreePtr lvDefStmt;          // Pointer to the statement with the single definition
712     void       lvaDisqualifyVar(); // Call to disqualify a local variable from use in optAddCopies
713 #endif
714     var_types TypeGet() const
715     {
716         return (var_types)lvType;
717     }
718     bool lvStackAligned() const
719     {
720         assert(lvIsStructField);
721         return ((lvFldOffset % sizeof(void*)) == 0);
722     }
723     bool lvNormalizeOnLoad() const
724     {
725         return varTypeIsSmall(TypeGet()) &&
726                // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
727                (lvIsParam || lvAddrExposed || lvIsStructField);
728     }
729
730     bool lvNormalizeOnStore()
731     {
732         return varTypeIsSmall(TypeGet()) &&
733                // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
734                !(lvIsParam || lvAddrExposed || lvIsStructField);
735     }
736
737     void lvaResetSortAgainFlag(Compiler* pComp);
738     void decRefCnts(BasicBlock::weight_t weight, Compiler* pComp, bool propagate = true);
739     void incRefCnts(BasicBlock::weight_t weight, Compiler* pComp, bool propagate = true);
740     void setPrefReg(regNumber regNum, Compiler* pComp);
741     void addPrefReg(regMaskTP regMask, Compiler* pComp);
742     bool IsFloatRegType() const
743     {
744         return isFloatRegType(lvType) || lvIsHfaRegArg();
745     }
746     var_types GetHfaType() const
747     {
748         return lvIsHfa() ? (lvHfaTypeIsFloat() ? TYP_FLOAT : TYP_DOUBLE) : TYP_UNDEF;
749     }
750     void SetHfaType(var_types type)
751     {
752         assert(varTypeIsFloating(type));
753         lvSetHfaTypeIsFloat(type == TYP_FLOAT);
754     }
755
756 #ifndef LEGACY_BACKEND
757     var_types lvaArgType();
758 #endif
759
760     PerSsaArray lvPerSsaData;
761
762 #ifdef DEBUG
763     // Keep track of the # of SsaNames, for a bounds check.
764     unsigned lvNumSsaNames;
765 #endif
766
767     // Returns the address of the per-Ssa data for the given ssaNum (which is required
768     // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
769     // not an SSA variable).
770     LclSsaVarDsc* GetPerSsaData(unsigned ssaNum)
771     {
772         assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
773         assert(SsaConfig::RESERVED_SSA_NUM == 0);
774         unsigned zeroBased = ssaNum - SsaConfig::UNINIT_SSA_NUM;
775         assert(zeroBased < lvNumSsaNames);
776         return &lvPerSsaData.GetRef(zeroBased);
777     }
778
779 #ifdef DEBUG
780 public:
781     void PrintVarReg() const
782     {
783         if (isRegPairType(TypeGet()))
784         {
785             printf("%s:%s", getRegName(lvOtherReg), // hi32
786                    getRegName(lvRegNum));           // lo32
787         }
788         else
789         {
790             printf("%s", getRegName(lvRegNum));
791         }
792     }
793 #endif // DEBUG
794
795 }; // class LclVarDsc
796
797 /*
798 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
799 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
800 XX                                                                           XX
801 XX                           TempsInfo                                       XX
802 XX                                                                           XX
803 XX  The temporary lclVars allocated by the compiler for code generation      XX
804 XX                                                                           XX
805 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
806 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
807 */
808
809 /*****************************************************************************
810  *
811  *  The following keeps track of temporaries allocated in the stack frame
812  *  during code-generation (after register allocation). These spill-temps are
813  *  only used if we run out of registers while evaluating a tree.
814  *
815  *  These are different from the more common temps allocated by lvaGrabTemp().
816  */
817
818 class TempDsc
819 {
820 public:
821     TempDsc* tdNext;
822
823 private:
824     int tdOffs;
825 #ifdef DEBUG
826     static const int BAD_TEMP_OFFSET = 0xDDDDDDDD; // used as a sentinel "bad value" for tdOffs in DEBUG
827 #endif                                             // DEBUG
828
829     int       tdNum;
830     BYTE      tdSize;
831     var_types tdType;
832
833 public:
834     TempDsc(int _tdNum, unsigned _tdSize, var_types _tdType) : tdNum(_tdNum), tdSize((BYTE)_tdSize), tdType(_tdType)
835     {
836 #ifdef DEBUG
837         assert(tdNum <
838                0); // temps must have a negative number (so they have a different number from all local variables)
839         tdOffs = BAD_TEMP_OFFSET;
840 #endif // DEBUG
841         if (tdNum != _tdNum)
842         {
843             IMPL_LIMITATION("too many spill temps");
844         }
845     }
846
847 #ifdef DEBUG
848     bool tdLegalOffset() const
849     {
850         return tdOffs != BAD_TEMP_OFFSET;
851     }
852 #endif // DEBUG
853
854     int tdTempOffs() const
855     {
856         assert(tdLegalOffset());
857         return tdOffs;
858     }
859     void tdSetTempOffs(int offs)
860     {
861         tdOffs = offs;
862         assert(tdLegalOffset());
863     }
864     void tdAdjustTempOffs(int offs)
865     {
866         tdOffs += offs;
867         assert(tdLegalOffset());
868     }
869
870     int tdTempNum() const
871     {
872         assert(tdNum < 0);
873         return tdNum;
874     }
875     unsigned tdTempSize() const
876     {
877         return tdSize;
878     }
879     var_types tdTempType() const
880     {
881         return tdType;
882     }
883 };
884
885 // interface to hide linearscan implementation from rest of compiler
886 class LinearScanInterface
887 {
888 public:
889     virtual void doLinearScan()                                = 0;
890     virtual void recordVarLocationsAtStartOfBB(BasicBlock* bb) = 0;
891 };
892
893 LinearScanInterface* getLinearScanAllocator(Compiler* comp);
894
895 // Information about arrays: their element type and size, and the offset of the first element.
896 // We label GT_IND's that are array indices with GTF_IND_ARR_INDEX, and, for such nodes,
897 // associate an array info via the map retrieved by GetArrayInfoMap().  This information is used,
898 // for example, in value numbering of array index expressions.
899 struct ArrayInfo
900 {
901     var_types            m_elemType;
902     CORINFO_CLASS_HANDLE m_elemStructType;
903     unsigned             m_elemSize;
904     unsigned             m_elemOffset;
905
906     ArrayInfo() : m_elemType(TYP_UNDEF), m_elemStructType(nullptr), m_elemSize(0), m_elemOffset(0)
907     {
908     }
909
910     ArrayInfo(var_types elemType, unsigned elemSize, unsigned elemOffset, CORINFO_CLASS_HANDLE elemStructType)
911         : m_elemType(elemType), m_elemStructType(elemStructType), m_elemSize(elemSize), m_elemOffset(elemOffset)
912     {
913     }
914 };
915
916 // This enumeration names the phases into which we divide compilation.  The phases should completely
917 // partition a compilation.
918 enum Phases
919 {
920 #define CompPhaseNameMacro(enum_nm, string_nm, short_nm, hasChildren, parent) enum_nm,
921 #include "compphases.h"
922     PHASE_NUMBER_OF
923 };
924
925 extern const char*   PhaseNames[];
926 extern const char*   PhaseEnums[];
927 extern const LPCWSTR PhaseShortNames[];
928
929 //---------------------------------------------------------------
930 // Compilation time.
931 //
932
933 // A "CompTimeInfo" is a structure for tracking the compilation time of one or more methods.
934 // We divide a compilation into a sequence of contiguous phases, and track the total (per-thread) cycles
935 // of the compilation, as well as the cycles for each phase.  We also track the number of bytecodes.
936 // If there is a failure in reading a timer at any point, the "CompTimeInfo" becomes invalid, as indicated
937 // by "m_timerFailure" being true.
938 // If FEATURE_JIT_METHOD_PERF is not set, we define a minimal form of this, enough to let other code compile.
939 struct CompTimeInfo
940 {
941 #ifdef FEATURE_JIT_METHOD_PERF
942     // The string names of the phases.
943     static const char* PhaseNames[];
944
945     static bool PhaseHasChildren[];
946     static int  PhaseParent[];
947
948     unsigned         m_byteCodeBytes;
949     unsigned __int64 m_totalCycles;
950     unsigned __int64 m_invokesByPhase[PHASE_NUMBER_OF];
951     unsigned __int64 m_cyclesByPhase[PHASE_NUMBER_OF];
952     // For better documentation, we call EndPhase on
953     // non-leaf phases.  We should also call EndPhase on the
954     // last leaf subphase; obviously, the elapsed cycles between the EndPhase
955     // for the last leaf subphase and the EndPhase for an ancestor should be very small.
956     // We add all such "redundant end phase" intervals to this variable below; we print
957     // it out in a report, so we can verify that it is, indeed, very small.  If it ever
958     // isn't, this means that we're doing something significant between the end of the last
959     // declared subphase and the end of its parent.
960     unsigned __int64 m_parentPhaseEndSlop;
961     bool             m_timerFailure;
962
963     CompTimeInfo(unsigned byteCodeBytes);
964 #endif
965 };
966
967 #ifdef FEATURE_JIT_METHOD_PERF
968
969 // This class summarizes the JIT time information over the course of a run: the number of methods compiled,
970 // and the total and maximum timings.  (These are instances of the "CompTimeInfo" type described above).
971 // The operation of adding a single method's timing to the summary may be performed concurrently by several
972 // threads, so it is protected by a lock.
973 // This class is intended to be used as a singleton type, with only a single instance.
974 class CompTimeSummaryInfo
975 {
976     // This lock protects the fields of all CompTimeSummaryInfo(s) (of which we expect there to be one).
977     static CritSecObject s_compTimeSummaryLock;
978
979     int          m_numMethods;
980     CompTimeInfo m_total;
981     CompTimeInfo m_maximum;
982
983     int          m_numFilteredMethods;
984     CompTimeInfo m_filtered;
985
986     // This method computes the number of cycles/sec for the current machine.  The cycles are those counted
987     // by GetThreadCycleTime; we assume that these are of equal duration, though that is not necessarily true.
988     // If any OS interaction fails, returns 0.0.
989     double CyclesPerSecond();
990
991     // This can use what ever data you want to determine if the value to be added
992     // belongs in the filtered section (it's always included in the unfiltered section)
993     bool IncludedInFilteredData(CompTimeInfo& info);
994
995 public:
996     // This is the unique CompTimeSummaryInfo object for this instance of the runtime.
997     static CompTimeSummaryInfo s_compTimeSummary;
998
999     CompTimeSummaryInfo() : m_total(0), m_maximum(0), m_numMethods(0), m_filtered(0), m_numFilteredMethods(0)
1000     {
1001     }
1002
1003     // Assumes that "info" is a completed CompTimeInfo for a compilation; adds it to the summary.
1004     // This is thread safe.
1005     void AddInfo(CompTimeInfo& info);
1006
1007     // Print the summary information to "f".
1008     // This is not thread-safe; assumed to be called by only one thread.
1009     void Print(FILE* f);
1010 };
1011
1012 // A JitTimer encapsulates a CompTimeInfo for a single compilation. It also tracks the start of compilation,
1013 // and when the current phase started.  This is intended to be part of a Compilation object.  This is
1014 // disabled (FEATURE_JIT_METHOD_PERF not defined) when FEATURE_CORECLR is set, or on non-windows platforms.
1015 //
1016 class JitTimer
1017 {
1018     unsigned __int64 m_start;         // Start of the compilation.
1019     unsigned __int64 m_curPhaseStart; // Start of the current phase.
1020 #ifdef DEBUG
1021     Phases m_lastPhase; // The last phase that was completed (or (Phases)-1 to start).
1022 #endif
1023     CompTimeInfo m_info; // The CompTimeInfo for this compilation.
1024
1025     static CritSecObject s_csvLock; // Lock to protect the time log file.
1026     void PrintCsvMethodStats(Compiler* comp);
1027
1028 private:
1029     void* operator new(size_t);
1030     void* operator new[](size_t);
1031     void operator delete(void*);
1032     void operator delete[](void*);
1033
1034 public:
1035     // Initialized the timer instance
1036     JitTimer(unsigned byteCodeSize);
1037
1038     static JitTimer* Create(Compiler* comp, unsigned byteCodeSize)
1039     {
1040         return ::new (comp, CMK_Unknown) JitTimer(byteCodeSize);
1041     }
1042
1043     static void PrintCsvHeader();
1044
1045     // Ends the current phase (argument is for a redundant check).
1046     void EndPhase(Phases phase);
1047
1048     // Completes the timing of the current method, which is assumed to have "byteCodeBytes" bytes of bytecode,
1049     // and adds it to "sum".
1050     void Terminate(Compiler* comp, CompTimeSummaryInfo& sum);
1051
1052     // Attempts to query the cycle counter of the current thread.  If successful, returns "true" and sets
1053     // *cycles to the cycle counter value.  Otherwise, returns false and sets the "m_timerFailure" flag of
1054     // "m_info" to true.
1055     bool GetThreadCycles(unsigned __int64* cycles)
1056     {
1057         bool res = CycleTimer::GetThreadCyclesS(cycles);
1058         if (!res)
1059         {
1060             m_info.m_timerFailure = true;
1061         }
1062         return res;
1063     }
1064 };
1065 #endif // FEATURE_JIT_METHOD_PERF
1066
1067 //------------------- Function/Funclet info -------------------------------
1068 DECLARE_TYPED_ENUM(FuncKind, BYTE)
1069 {
1070     FUNC_ROOT,        // The main/root function (always id==0)
1071         FUNC_HANDLER, // a funclet associated with an EH handler (finally, fault, catch, filter handler)
1072         FUNC_FILTER,  // a funclet associated with an EH filter
1073         FUNC_COUNT
1074 }
1075 END_DECLARE_TYPED_ENUM(FuncKind, BYTE)
1076
1077 class emitLocation;
1078
1079 struct FuncInfoDsc
1080 {
1081     FuncKind       funKind;
1082     BYTE           funFlags;   // Currently unused, just here for padding
1083     unsigned short funEHIndex; // index, into the ebd table, of innermost EH clause corresponding to this
1084                                // funclet. It is only valid if funKind field indicates this is a
1085                                // EH-related funclet: FUNC_HANDLER or FUNC_FILTER
1086
1087 #if defined(_TARGET_AMD64_)
1088
1089     // TODO-AMD64-Throughput: make the AMD64 info more like the ARM info to avoid having this large static array.
1090     emitLocation* startLoc;
1091     emitLocation* endLoc;
1092     emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1093     emitLocation* coldEndLoc;
1094     UNWIND_INFO   unwindHeader;
1095     // Maximum of 255 UNWIND_CODE 'nodes' and then the unwind header. If there are an odd
1096     // number of codes, the VM or Zapper will 4-byte align the whole thing.
1097     BYTE     unwindCodes[offsetof(UNWIND_INFO, UnwindCode) + (0xFF * sizeof(UNWIND_CODE))];
1098     unsigned unwindCodeSlot;
1099
1100 #ifdef UNIX_AMD64_ABI
1101     jitstd::vector<CFI_CODE>* cfiCodes;
1102 #endif // UNIX_AMD64_ABI
1103
1104 #elif defined(_TARGET_ARMARCH_)
1105
1106     UnwindInfo  uwi;     // Unwind information for this function/funclet's hot  section
1107     UnwindInfo* uwiCold; // Unwind information for this function/funclet's cold section
1108                          //   Note: we only have a pointer here instead of the actual object,
1109                          //   to save memory in the JIT case (compared to the NGEN case),
1110                          //   where we don't have any cold section.
1111                          //   Note 2: we currently don't support hot/cold splitting in functions
1112                          //   with EH, so uwiCold will be NULL for all funclets.
1113
1114 #endif // _TARGET_ARMARCH_
1115
1116     // Eventually we may want to move rsModifiedRegsMask, lvaOutgoingArgSize, and anything else
1117     // that isn't shared between the main function body and funclets.
1118 };
1119
1120 struct fgArgTabEntry
1121 {
1122
1123 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1124     fgArgTabEntry()
1125     {
1126         otherRegNum = REG_NA;
1127         isStruct    = false; // is this a struct arg
1128     }
1129 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1130
1131     GenTreePtr node; // Initially points at the Op1 field of 'parent', but if the argument is replaced with an GT_ASG or
1132                      // placeholder
1133                      //  it will point at the actual argument in the gtCallLateArgs list.
1134     GenTreePtr parent; // Points at the GT_LIST node in the gtCallArgs for this argument
1135
1136     unsigned argNum; // The original argument number, also specifies the required argument evaluation order from the IL
1137
1138     regNumber regNum; // The (first) register to use when passing this argument, set to REG_STK for arguments passed on
1139                       // the stack
1140     unsigned numRegs; // Count of number of registers that this argument uses
1141
1142     // A slot is a pointer sized region in the OutArg area.
1143     unsigned slotNum;  // When an argument is passed in the OutArg area this is the slot number in the OutArg area
1144     unsigned numSlots; // Count of number of slots that this argument uses
1145
1146     unsigned alignment;  // 1 or 2 (slots/registers)
1147     unsigned lateArgInx; // index into gtCallLateArgs list
1148     unsigned tmpNum;     // the LclVar number if we had to force evaluation of this arg
1149
1150     bool isSplit : 1;       // True when this argument is split between the registers and OutArg area
1151     bool needTmp : 1;       // True when we force this argument's evaluation into a temp LclVar
1152     bool needPlace : 1;     // True when we must replace this argument with a placeholder node
1153     bool isTmp : 1;         // True when we setup a temp LclVar for this argument due to size issues with the struct
1154     bool processed : 1;     // True when we have decided the evaluation order for this argument in the gtCallLateArgs
1155     bool isHfaRegArg : 1;   // True when the argument is passed as a HFA in FP registers.
1156     bool isBackFilled : 1;  // True when the argument fills a register slot skipped due to alignment requirements of
1157                             // previous arguments.
1158     bool isNonStandard : 1; // True if it is an arg that is passed in a reg other than a standard arg reg, or is forced
1159                             // to be on the stack despite its arg list position.
1160
1161 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1162     bool isStruct : 1; // True if this is a struct arg
1163
1164     regNumber otherRegNum; // The (second) register to use when passing this argument.
1165
1166     SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR structDesc;
1167 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1168
1169 #ifdef _TARGET_ARM_
1170     void SetIsHfaRegArg(bool hfaRegArg)
1171     {
1172         isHfaRegArg = hfaRegArg;
1173     }
1174
1175     void SetIsBackFilled(bool backFilled)
1176     {
1177         isBackFilled = backFilled;
1178     }
1179
1180     bool IsBackFilled() const
1181     {
1182         return isBackFilled;
1183     }
1184 #else  // !_TARGET_ARM_
1185     // To make the callers easier, we allow these calls (and the isHfaRegArg and isBackFilled data members) for all
1186     // platforms.
1187     void SetIsHfaRegArg(bool hfaRegArg)
1188     {
1189     }
1190
1191     void SetIsBackFilled(bool backFilled)
1192     {
1193     }
1194
1195     bool IsBackFilled() const
1196     {
1197         return false;
1198     }
1199 #endif // !_TARGET_ARM_
1200
1201 #ifdef DEBUG
1202     void Dump();
1203 #endif
1204 };
1205 typedef struct fgArgTabEntry* fgArgTabEntryPtr;
1206
1207 //-------------------------------------------------------------------------
1208 //
1209 //  The class fgArgInfo is used to handle the arguments
1210 //  when morphing a GT_CALL node.
1211 //
1212
1213 class fgArgInfo
1214 {
1215     Compiler*  compiler;    // Back pointer to the compiler instance so that we can allocate memory
1216     GenTreePtr callTree;    // Back pointer to the GT_CALL node for this fgArgInfo
1217     unsigned   argCount;    // Updatable arg count value
1218     unsigned   nextSlotNum; // Updatable slot count value
1219     unsigned   stkLevel;    // Stack depth when we make this call (for x86)
1220
1221     unsigned          argTableSize; // size of argTable array (equal to the argCount when done with fgMorphArgs)
1222     bool              hasRegArgs;   // true if we have one or more register arguments
1223     bool              hasStackArgs; // true if we have one or more stack arguments
1224     bool              argsComplete; // marker for state
1225     bool              argsSorted;   // marker for state
1226     fgArgTabEntryPtr* argTable;     // variable sized array of per argument descrption: (i.e. argTable[argTableSize])
1227
1228 private:
1229     void AddArg(fgArgTabEntryPtr curArgTabEntry);
1230
1231 public:
1232     fgArgInfo(Compiler* comp, GenTreePtr call, unsigned argCount);
1233     fgArgInfo(GenTreePtr newCall, GenTreePtr oldCall);
1234
1235     fgArgTabEntryPtr AddRegArg(
1236         unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment);
1237
1238 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
1239     fgArgTabEntryPtr AddRegArg(
1240         unsigned                                                         argNum,
1241         GenTreePtr                                                       node,
1242         GenTreePtr                                                       parent,
1243         regNumber                                                        regNum,
1244         unsigned                                                         numRegs,
1245         unsigned                                                         alignment,
1246         const bool                                                       isStruct,
1247         const regNumber                                                  otherRegNum   = REG_NA,
1248         const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* const structDescPtr = nullptr);
1249 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
1250
1251     fgArgTabEntryPtr AddStkArg(unsigned   argNum,
1252                                GenTreePtr node,
1253                                GenTreePtr parent,
1254                                unsigned   numSlots,
1255                                unsigned alignment FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool isStruct));
1256
1257     void             RemorphReset();
1258     fgArgTabEntryPtr RemorphRegArg(
1259         unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment);
1260
1261     void RemorphStkArg(unsigned argNum, GenTreePtr node, GenTreePtr parent, unsigned numSlots, unsigned alignment);
1262
1263     void SplitArg(unsigned argNum, unsigned numRegs, unsigned numSlots);
1264
1265     void EvalToTmp(unsigned argNum, unsigned tmpNum, GenTreePtr newNode);
1266
1267     void ArgsComplete();
1268
1269     void SortArgs();
1270
1271     void EvalArgsToTemps();
1272
1273     void RecordStkLevel(unsigned stkLvl);
1274     unsigned RetrieveStkLevel();
1275
1276     unsigned ArgCount()
1277     {
1278         return argCount;
1279     }
1280     fgArgTabEntryPtr* ArgTable()
1281     {
1282         return argTable;
1283     }
1284     unsigned GetNextSlotNum()
1285     {
1286         return nextSlotNum;
1287     }
1288     bool HasRegArgs()
1289     {
1290         return hasRegArgs;
1291     }
1292     bool HasStackArgs()
1293     {
1294         return hasStackArgs;
1295     }
1296 };
1297
1298 #ifdef DEBUG
1299 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1300 // We have the ability to mark source expressions with "Test Labels."
1301 // These drive assertions within the JIT, or internal JIT testing.  For example, we could label expressions
1302 // that should be CSE defs, and other expressions that should uses of those defs, with a shared label.
1303
1304 enum TestLabel // This must be kept identical to System.Runtime.CompilerServices.JitTestLabel.TestLabel.
1305 {
1306     TL_SsaName,
1307     TL_VN,        // Defines a "VN equivalence class".  (For full VN, including exceptions thrown).
1308     TL_VNNorm,    // Like above, but uses the non-exceptional value of the expression.
1309     TL_CSE_Def,   //  This must be identified in the JIT as a CSE def
1310     TL_CSE_Use,   //  This must be identified in the JIT as a CSE use
1311     TL_LoopHoist, // Expression must (or must not) be hoisted out of the loop.
1312 };
1313
1314 struct TestLabelAndNum
1315 {
1316     TestLabel m_tl;
1317     ssize_t   m_num;
1318
1319     TestLabelAndNum() : m_tl(TestLabel(0)), m_num(0)
1320     {
1321     }
1322 };
1323
1324 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, TestLabelAndNum, JitSimplerHashBehavior> NodeToTestDataMap;
1325
1326 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1327 #endif // DEBUG
1328
1329 // This class implements the "IAllocator" interface, so that we can use
1330 // utilcode collection classes in the JIT, and have them use the JIT's allocator.
1331
1332 class CompAllocator : public IAllocator
1333 {
1334     Compiler* m_comp;
1335 #if MEASURE_MEM_ALLOC
1336     CompMemKind m_cmk;
1337 #endif
1338 public:
1339     CompAllocator(Compiler* comp, CompMemKind cmk)
1340         : m_comp(comp)
1341 #if MEASURE_MEM_ALLOC
1342         , m_cmk(cmk)
1343 #endif
1344     {
1345     }
1346
1347     inline void* Alloc(size_t sz);
1348
1349     inline void* ArrayAlloc(size_t elems, size_t elemSize);
1350
1351     // For the compiler's no-release allocator, free operations are no-ops.
1352     void Free(void* p)
1353     {
1354     }
1355 };
1356
1357 /*
1358 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1359 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1360 XX                                                                           XX
1361 XX   The big guy. The sections are currently organized as :                  XX
1362 XX                                                                           XX
1363 XX    o  GenTree and BasicBlock                                              XX
1364 XX    o  LclVarsInfo                                                         XX
1365 XX    o  Importer                                                            XX
1366 XX    o  FlowGraph                                                           XX
1367 XX    o  Optimizer                                                           XX
1368 XX    o  RegAlloc                                                            XX
1369 XX    o  EEInterface                                                         XX
1370 XX    o  TempsInfo                                                           XX
1371 XX    o  RegSet                                                              XX
1372 XX    o  GCInfo                                                              XX
1373 XX    o  Instruction                                                         XX
1374 XX    o  ScopeInfo                                                           XX
1375 XX    o  PrologScopeInfo                                                     XX
1376 XX    o  CodeGenerator                                                       XX
1377 XX    o  UnwindInfo                                                          XX
1378 XX    o  Compiler                                                            XX
1379 XX    o  typeInfo                                                            XX
1380 XX                                                                           XX
1381 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1382 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1383 */
1384
1385 class Compiler
1386 {
1387     friend class emitter;
1388     friend class UnwindInfo;
1389     friend class UnwindFragmentInfo;
1390     friend class UnwindEpilogInfo;
1391     friend class JitTimer;
1392     friend class LinearScan;
1393     friend class fgArgInfo;
1394     friend class Rationalizer;
1395     friend class Phase;
1396     friend class Lowering;
1397     friend class CSE_DataFlow;
1398     friend class CSE_Heuristic;
1399     friend class CodeGenInterface;
1400     friend class CodeGen;
1401     friend class LclVarDsc;
1402     friend class TempDsc;
1403     friend class LIR;
1404     friend class ObjectAllocator;
1405
1406 #ifndef _TARGET_64BIT_
1407     friend class DecomposeLongs;
1408 #endif // !_TARGET_64BIT_
1409
1410     /*
1411     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1412     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1413     XX                                                                           XX
1414     XX  Misc structs definitions                                                 XX
1415     XX                                                                           XX
1416     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1417     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1418     */
1419
1420 public:
1421     hashBvGlobalData hbvGlobalData; // Used by the hashBv bitvector package.
1422
1423 #ifdef DEBUG
1424     bool    verbose;
1425     bool    dumpIR;
1426     bool    dumpIRNodes;
1427     bool    dumpIRTypes;
1428     bool    dumpIRKinds;
1429     bool    dumpIRLocals;
1430     bool    dumpIRRegs;
1431     bool    dumpIRSsa;
1432     bool    dumpIRValnums;
1433     bool    dumpIRCosts;
1434     bool    dumpIRFlags;
1435     bool    dumpIRNoLists;
1436     bool    dumpIRNoLeafs;
1437     bool    dumpIRNoStmts;
1438     bool    dumpIRTrees;
1439     bool    dumpIRLinear;
1440     bool    dumpIRDataflow;
1441     bool    dumpIRBlockHeaders;
1442     bool    dumpIRExit;
1443     LPCWSTR dumpIRPhase;
1444     LPCWSTR dumpIRFormat;
1445     bool    verboseTrees;
1446     bool    shouldUseVerboseTrees();
1447     bool    asciiTrees; // If true, dump trees using only ASCII characters
1448     bool    shouldDumpASCIITrees();
1449     bool    verboseSsa; // If true, produce especially verbose dump output in SSA construction.
1450     bool    shouldUseVerboseSsa();
1451     bool    treesBeforeAfterMorph; // If true, print trees before/after morphing (paired by an intra-compilation id:
1452     int     morphNum; // This counts the the trees that have been morphed, allowing us to label each uniquely.
1453
1454     const char* VarNameToStr(VarName name)
1455     {
1456         return name;
1457     }
1458
1459     DWORD expensiveDebugCheckLevel;
1460 #endif
1461
1462 #if FEATURE_MULTIREG_RET
1463     GenTreePtr impAssignMultiRegTypeToVar(GenTreePtr op, CORINFO_CLASS_HANDLE hClass);
1464 #endif // FEATURE_MULTIREG_RET
1465
1466 #ifdef ARM_SOFTFP
1467     bool isSingleFloat32Struct(CORINFO_CLASS_HANDLE hClass);
1468 #endif // ARM_SOFTFP
1469
1470     //-------------------------------------------------------------------------
1471     // Functions to handle homogeneous floating-point aggregates (HFAs) in ARM.
1472     // HFAs are one to four element structs where each element is the same
1473     // type, either all float or all double. They are treated specially
1474     // in the ARM Procedure Call Standard, specifically, they are passed in
1475     // floating-point registers instead of the general purpose registers.
1476     //
1477
1478     bool IsHfa(CORINFO_CLASS_HANDLE hClass);
1479     bool IsHfa(GenTreePtr tree);
1480
1481     var_types GetHfaType(GenTreePtr tree);
1482     unsigned GetHfaCount(GenTreePtr tree);
1483
1484     var_types GetHfaType(CORINFO_CLASS_HANDLE hClass);
1485     unsigned GetHfaCount(CORINFO_CLASS_HANDLE hClass);
1486
1487     bool IsMultiRegPassedType(CORINFO_CLASS_HANDLE hClass);
1488     bool IsMultiRegReturnedType(CORINFO_CLASS_HANDLE hClass);
1489
1490     //-------------------------------------------------------------------------
1491     // The following is used for validating format of EH table
1492     //
1493
1494     struct EHNodeDsc;
1495     typedef struct EHNodeDsc* pEHNodeDsc;
1496
1497     EHNodeDsc* ehnTree; // root of the tree comprising the EHnodes.
1498     EHNodeDsc* ehnNext; // root of the tree comprising the EHnodes.
1499
1500     struct EHNodeDsc
1501     {
1502         enum EHBlockType
1503         {
1504             TryNode,
1505             FilterNode,
1506             HandlerNode,
1507             FinallyNode,
1508             FaultNode
1509         };
1510
1511         EHBlockType ehnBlockType;   // kind of EH block
1512         IL_OFFSET   ehnStartOffset; // IL offset of start of the EH block
1513         IL_OFFSET ehnEndOffset; // IL offset past end of the EH block. (TODO: looks like verInsertEhNode() sets this to
1514                                 // the last IL offset, not "one past the last one", i.e., the range Start to End is
1515                                 // inclusive).
1516         pEHNodeDsc ehnNext;     // next (non-nested) block in sequential order
1517         pEHNodeDsc ehnChild;    // leftmost nested block
1518         union {
1519             pEHNodeDsc ehnTryNode;     // for filters and handlers, the corresponding try node
1520             pEHNodeDsc ehnHandlerNode; // for a try node, the corresponding handler node
1521         };
1522         pEHNodeDsc ehnFilterNode; // if this is a try node and has a filter, otherwise 0
1523         pEHNodeDsc ehnEquivalent; // if blockType=tryNode, start offset and end offset is same,
1524
1525         inline void ehnSetTryNodeType()
1526         {
1527             ehnBlockType = TryNode;
1528         }
1529         inline void ehnSetFilterNodeType()
1530         {
1531             ehnBlockType = FilterNode;
1532         }
1533         inline void ehnSetHandlerNodeType()
1534         {
1535             ehnBlockType = HandlerNode;
1536         }
1537         inline void ehnSetFinallyNodeType()
1538         {
1539             ehnBlockType = FinallyNode;
1540         }
1541         inline void ehnSetFaultNodeType()
1542         {
1543             ehnBlockType = FaultNode;
1544         }
1545
1546         inline BOOL ehnIsTryBlock()
1547         {
1548             return ehnBlockType == TryNode;
1549         }
1550         inline BOOL ehnIsFilterBlock()
1551         {
1552             return ehnBlockType == FilterNode;
1553         }
1554         inline BOOL ehnIsHandlerBlock()
1555         {
1556             return ehnBlockType == HandlerNode;
1557         }
1558         inline BOOL ehnIsFinallyBlock()
1559         {
1560             return ehnBlockType == FinallyNode;
1561         }
1562         inline BOOL ehnIsFaultBlock()
1563         {
1564             return ehnBlockType == FaultNode;
1565         }
1566
1567         // returns true if there is any overlap between the two nodes
1568         static inline BOOL ehnIsOverlap(pEHNodeDsc node1, pEHNodeDsc node2)
1569         {
1570             if (node1->ehnStartOffset < node2->ehnStartOffset)
1571             {
1572                 return (node1->ehnEndOffset >= node2->ehnStartOffset);
1573             }
1574             else
1575             {
1576                 return (node1->ehnStartOffset <= node2->ehnEndOffset);
1577             }
1578         }
1579
1580         // fails with BADCODE if inner is not completely nested inside outer
1581         static inline BOOL ehnIsNested(pEHNodeDsc inner, pEHNodeDsc outer)
1582         {
1583             return ((inner->ehnStartOffset >= outer->ehnStartOffset) && (inner->ehnEndOffset <= outer->ehnEndOffset));
1584         }
1585     };
1586
1587 //-------------------------------------------------------------------------
1588 // Exception handling functions
1589 //
1590
1591 #if !FEATURE_EH_FUNCLETS
1592
1593     bool ehNeedsShadowSPslots()
1594     {
1595         return (info.compXcptnsCount || opts.compDbgEnC);
1596     }
1597
1598     // 0 for methods with no EH
1599     // 1 for methods with non-nested EH, or where only the try blocks are nested
1600     // 2 for a method with a catch within a catch
1601     // etc.
1602     unsigned ehMaxHndNestingCount;
1603
1604 #endif // !FEATURE_EH_FUNCLETS
1605
1606     static bool jitIsBetween(unsigned value, unsigned start, unsigned end);
1607     static bool jitIsBetweenInclusive(unsigned value, unsigned start, unsigned end);
1608
1609     bool bbInCatchHandlerILRange(BasicBlock* blk);
1610     bool bbInFilterILRange(BasicBlock* blk);
1611     bool bbInTryRegions(unsigned regionIndex, BasicBlock* blk);
1612     bool bbInExnFlowRegions(unsigned regionIndex, BasicBlock* blk);
1613     bool bbInHandlerRegions(unsigned regionIndex, BasicBlock* blk);
1614     bool bbInCatchHandlerRegions(BasicBlock* tryBlk, BasicBlock* hndBlk);
1615     unsigned short bbFindInnermostCommonTryRegion(BasicBlock* bbOne, BasicBlock* bbTwo);
1616
1617     unsigned short bbFindInnermostTryRegionContainingHandlerRegion(unsigned handlerIndex);
1618     unsigned short bbFindInnermostHandlerRegionContainingTryRegion(unsigned tryIndex);
1619
1620     // Returns true if "block" is the start of a try region.
1621     bool bbIsTryBeg(BasicBlock* block);
1622
1623     // Returns true if "block" is the start of a handler or filter region.
1624     bool bbIsHandlerBeg(BasicBlock* block);
1625
1626     // Returns true iff "block" is where control flows if an exception is raised in the
1627     // try region, and sets "*regionIndex" to the index of the try for the handler.
1628     // Differs from "IsHandlerBeg" in the case of filters, where this is true for the first
1629     // block of the filter, but not for the filter's handler.
1630     bool bbIsExFlowBlock(BasicBlock* block, unsigned* regionIndex);
1631
1632     bool ehHasCallableHandlers();
1633
1634     // Return the EH descriptor for the given region index.
1635     EHblkDsc* ehGetDsc(unsigned regionIndex);
1636
1637     // Return the EH index given a region descriptor.
1638     unsigned ehGetIndex(EHblkDsc* ehDsc);
1639
1640     // Return the EH descriptor index of the enclosing try, for the given region index.
1641     unsigned ehGetEnclosingTryIndex(unsigned regionIndex);
1642
1643     // Return the EH descriptor index of the enclosing handler, for the given region index.
1644     unsigned ehGetEnclosingHndIndex(unsigned regionIndex);
1645
1646     // Return the EH descriptor for the most nested 'try' region this BasicBlock is a member of (or nullptr if this
1647     // block is not in a 'try' region).
1648     EHblkDsc* ehGetBlockTryDsc(BasicBlock* block);
1649
1650     // Return the EH descriptor for the most nested filter or handler region this BasicBlock is a member of (or nullptr
1651     // if this block is not in a filter or handler region).
1652     EHblkDsc* ehGetBlockHndDsc(BasicBlock* block);
1653
1654     // Return the EH descriptor for the most nested region that may handle exceptions raised in this BasicBlock (or
1655     // nullptr if this block's exceptions propagate to caller).
1656     EHblkDsc* ehGetBlockExnFlowDsc(BasicBlock* block);
1657
1658     EHblkDsc* ehIsBlockTryLast(BasicBlock* block);
1659     EHblkDsc* ehIsBlockHndLast(BasicBlock* block);
1660     bool ehIsBlockEHLast(BasicBlock* block);
1661
1662     bool ehBlockHasExnFlowDsc(BasicBlock* block);
1663
1664     // Return the region index of the most nested EH region this block is in.
1665     unsigned ehGetMostNestedRegionIndex(BasicBlock* block, bool* inTryRegion);
1666
1667     // Find the true enclosing try index, ignoring 'mutual protect' try. Uses IL ranges to check.
1668     unsigned ehTrueEnclosingTryIndexIL(unsigned regionIndex);
1669
1670     // Return the index of the most nested enclosing region for a particular EH region. Returns NO_ENCLOSING_INDEX
1671     // if there is no enclosing region. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion'
1672     // is set to 'true' if the enclosing region is a 'try', or 'false' if the enclosing region is a handler.
1673     // (It can never be a filter.)
1674     unsigned ehGetEnclosingRegionIndex(unsigned regionIndex, bool* inTryRegion);
1675
1676     // A block has been deleted. Update the EH table appropriately.
1677     void ehUpdateForDeletedBlock(BasicBlock* block);
1678
1679     // Determine whether a block can be deleted while preserving the EH normalization rules.
1680     bool ehCanDeleteEmptyBlock(BasicBlock* block);
1681
1682     // Update the 'last' pointers in the EH table to reflect new or deleted blocks in an EH region.
1683     void ehUpdateLastBlocks(BasicBlock* oldLast, BasicBlock* newLast);
1684
1685     // For a finally handler, find the region index that the BBJ_CALLFINALLY lives in that calls the handler,
1686     // or NO_ENCLOSING_INDEX if the BBJ_CALLFINALLY lives in the main function body. Normally, the index
1687     // is the same index as the handler (and the BBJ_CALLFINALLY lives in the 'try' region), but for AMD64 the
1688     // BBJ_CALLFINALLY lives in the enclosing try or handler region, whichever is more nested, or the main function
1689     // body. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion' is set to 'true' if the
1690     // BBJ_CALLFINALLY lives in the returned index's 'try' region, or 'false' if lives in the handler region. (It never
1691     // lives in a filter.)
1692     unsigned ehGetCallFinallyRegionIndex(unsigned finallyIndex, bool* inTryRegion);
1693
1694     // Find the range of basic blocks in which all BBJ_CALLFINALLY will be found that target the 'finallyIndex' region's
1695     // handler. Set begBlk to the first block, and endBlk to the block after the last block of the range
1696     // (nullptr if the last block is the last block in the program).
1697     // Precondition: 'finallyIndex' is the EH region of a try/finally clause.
1698     void ehGetCallFinallyBlockRange(unsigned finallyIndex, BasicBlock** begBlk, BasicBlock** endBlk);
1699
1700 #ifdef DEBUG
1701     // Given a BBJ_CALLFINALLY block and the EH region index of the finally it is calling, return
1702     // 'true' if the BBJ_CALLFINALLY is in the correct EH region.
1703     bool ehCallFinallyInCorrectRegion(BasicBlock* blockCallFinally, unsigned finallyIndex);
1704 #endif // DEBUG
1705
1706 #if FEATURE_EH_FUNCLETS
1707     // Do we need a PSPSym in the main function? For codegen purposes, we only need one
1708     // if there is a filter that protects a region with a nested EH clause (such as a
1709     // try/catch nested in the 'try' body of a try/filter/filter-handler). See
1710     // genFuncletProlog() for more details. However, the VM seems to use it for more
1711     // purposes, maybe including debugging. Until we are sure otherwise, always create
1712     // a PSPSym for functions with any EH.
1713     bool ehNeedsPSPSym() const
1714     {
1715         return compHndBBtabCount > 0;
1716     }
1717
1718     bool     ehAnyFunclets();  // Are there any funclets in this function?
1719     unsigned ehFuncletCount(); // Return the count of funclets in the function
1720
1721     unsigned bbThrowIndex(BasicBlock* blk); // Get the index to use as the cache key for sharing throw blocks
1722 #else                                       // !FEATURE_EH_FUNCLETS
1723     bool ehAnyFunclets()
1724     {
1725         return false;
1726     }
1727     unsigned ehFuncletCount()
1728     {
1729         return 0;
1730     }
1731
1732     unsigned bbThrowIndex(BasicBlock* blk)
1733     {
1734         return blk->bbTryIndex;
1735     } // Get the index to use as the cache key for sharing throw blocks
1736 #endif                                      // !FEATURE_EH_FUNCLETS
1737
1738     // Returns a flowList representing the "EH predecessors" of "blk".  These are the normal predecessors of
1739     // "blk", plus one special case: if "blk" is the first block of a handler, considers the predecessor(s) of the first
1740     // first block of the corresponding try region to be "EH predecessors".  (If there is a single such predecessor,
1741     // for example, we want to consider that the immediate dominator of the catch clause start block, so it's
1742     // convenient to also consider it a predecessor.)
1743     flowList* BlockPredsWithEH(BasicBlock* blk);
1744
1745     // This table is useful for memoization of the method above.
1746     typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, flowList*, JitSimplerHashBehavior>
1747                         BlockToFlowListMap;
1748     BlockToFlowListMap* m_blockToEHPreds;
1749     BlockToFlowListMap* GetBlockToEHPreds()
1750     {
1751         if (m_blockToEHPreds == nullptr)
1752         {
1753             m_blockToEHPreds = new (getAllocator()) BlockToFlowListMap(getAllocator());
1754         }
1755         return m_blockToEHPreds;
1756     }
1757
1758     void* ehEmitCookie(BasicBlock* block);
1759     UNATIVE_OFFSET ehCodeOffset(BasicBlock* block);
1760
1761     EHblkDsc* ehInitHndRange(BasicBlock* src, IL_OFFSET* hndBeg, IL_OFFSET* hndEnd, bool* inFilter);
1762
1763     EHblkDsc* ehInitTryRange(BasicBlock* src, IL_OFFSET* tryBeg, IL_OFFSET* tryEnd);
1764
1765     EHblkDsc* ehInitHndBlockRange(BasicBlock* blk, BasicBlock** hndBeg, BasicBlock** hndLast, bool* inFilter);
1766
1767     EHblkDsc* ehInitTryBlockRange(BasicBlock* blk, BasicBlock** tryBeg, BasicBlock** tryLast);
1768
1769     void fgSetTryEnd(EHblkDsc* handlerTab, BasicBlock* newTryLast);
1770
1771     void fgSetHndEnd(EHblkDsc* handlerTab, BasicBlock* newHndLast);
1772
1773     void fgSkipRmvdBlocks(EHblkDsc* handlerTab);
1774
1775     void fgAllocEHTable();
1776
1777     void fgRemoveEHTableEntry(unsigned XTnum);
1778
1779 #if FEATURE_EH_FUNCLETS
1780
1781     EHblkDsc* fgAddEHTableEntry(unsigned XTnum);
1782
1783 #endif // FEATURE_EH_FUNCLETS
1784
1785 #if !FEATURE_EH
1786     void fgRemoveEH();
1787 #endif // !FEATURE_EH
1788
1789     void fgSortEHTable();
1790
1791     // Causes the EH table to obey some well-formedness conditions, by inserting
1792     // empty BB's when necessary:
1793     //   * No block is both the first block of a handler and the first block of a try.
1794     //   * No block is the first block of multiple 'try' regions.
1795     //   * No block is the last block of multiple EH regions.
1796     void fgNormalizeEH();
1797     bool fgNormalizeEHCase1();
1798     bool fgNormalizeEHCase2();
1799     bool fgNormalizeEHCase3();
1800
1801 #ifdef DEBUG
1802     void dispIncomingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
1803     void dispOutgoingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
1804     void fgVerifyHandlerTab();
1805     void fgDispHandlerTab();
1806 #endif // DEBUG
1807
1808     bool fgNeedToSortEHTable;
1809
1810     void verInitEHTree(unsigned numEHClauses);
1811     void verInsertEhNode(CORINFO_EH_CLAUSE* clause, EHblkDsc* handlerTab);
1812     void verInsertEhNodeInTree(EHNodeDsc** ppRoot, EHNodeDsc* node);
1813     void verInsertEhNodeParent(EHNodeDsc** ppRoot, EHNodeDsc* node);
1814     void verCheckNestingLevel(EHNodeDsc* initRoot);
1815
1816     /*
1817     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1818     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1819     XX                                                                           XX
1820     XX                        GenTree and BasicBlock                             XX
1821     XX                                                                           XX
1822     XX  Functions to allocate and display the GenTrees and BasicBlocks           XX
1823     XX                                                                           XX
1824     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1825     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1826     */
1827
1828     // Functions to create nodes
1829     GenTreeStmt* gtNewStmt(GenTreePtr expr = nullptr, IL_OFFSETX offset = BAD_IL_OFFSET);
1830
1831     // For unary opers.
1832     GenTreePtr gtNewOperNode(genTreeOps oper, var_types type, GenTreePtr op1, bool doSimplifications = TRUE);
1833
1834     // For binary opers.
1835     GenTreePtr gtNewOperNode(genTreeOps oper, var_types type, GenTreePtr op1, GenTreePtr op2);
1836
1837     GenTreePtr gtNewQmarkNode(var_types type, GenTreePtr cond, GenTreePtr colon);
1838
1839     GenTreePtr gtNewLargeOperNode(genTreeOps oper,
1840                                   var_types  type = TYP_I_IMPL,
1841                                   GenTreePtr op1  = nullptr,
1842                                   GenTreePtr op2  = nullptr);
1843
1844     GenTreeIntCon* gtNewIconNode(ssize_t value, var_types type = TYP_INT);
1845
1846     GenTree* gtNewPhysRegNode(regNumber reg, var_types type);
1847
1848     GenTree* gtNewPhysRegNode(regNumber reg, GenTree* src);
1849
1850     GenTreePtr gtNewJmpTableNode();
1851     GenTreePtr gtNewIconHandleNode(
1852         size_t value, unsigned flags, FieldSeqNode* fields = nullptr, unsigned handle1 = 0, void* handle2 = nullptr);
1853
1854     unsigned gtTokenToIconFlags(unsigned token);
1855
1856     GenTreePtr gtNewIconEmbHndNode(void*    value,
1857                                    void*    pValue,
1858                                    unsigned flags,
1859                                    unsigned handle1           = 0,
1860                                    void*    handle2           = nullptr,
1861                                    void*    compileTimeHandle = nullptr);
1862
1863     GenTreePtr gtNewIconEmbScpHndNode(CORINFO_MODULE_HANDLE scpHnd, unsigned hnd1 = 0, void* hnd2 = nullptr);
1864     GenTreePtr gtNewIconEmbClsHndNode(CORINFO_CLASS_HANDLE clsHnd, unsigned hnd1 = 0, void* hnd2 = nullptr);
1865     GenTreePtr gtNewIconEmbMethHndNode(CORINFO_METHOD_HANDLE methHnd, unsigned hnd1 = 0, void* hnd2 = nullptr);
1866     GenTreePtr gtNewIconEmbFldHndNode(CORINFO_FIELD_HANDLE fldHnd, unsigned hnd1 = 0, void* hnd2 = nullptr);
1867
1868     GenTreePtr gtNewStringLiteralNode(InfoAccessType iat, void* pValue);
1869
1870     GenTreePtr gtNewLconNode(__int64 value);
1871
1872     GenTreePtr gtNewDconNode(double value);
1873
1874     GenTreePtr gtNewSconNode(int CPX, CORINFO_MODULE_HANDLE scpHandle);
1875
1876     GenTreePtr gtNewZeroConNode(var_types type);
1877
1878     GenTreePtr gtNewOneConNode(var_types type);
1879
1880     GenTreeBlkOp* gtNewBlkOpNode(
1881         genTreeOps oper, GenTreePtr dst, GenTreePtr srcOrFillVal, GenTreePtr sizeOrClsTok, bool volatil);
1882
1883 protected:
1884     void gtBlockOpInit(GenTreePtr node, genTreeOps oper, GenTreePtr dst, GenTreePtr src, GenTreePtr size, bool volatil);
1885
1886 public:
1887     GenTreeObj* gtNewObjNode(CORINFO_CLASS_HANDLE structHnd, GenTreePtr addr);
1888
1889     GenTreeBlkOp* gtNewCpObjNode(GenTreePtr dst, GenTreePtr src, CORINFO_CLASS_HANDLE structHnd, bool volatil);
1890
1891     GenTreeBlkOp* gtCloneCpObjNode(GenTreeCpObj* source);
1892
1893     GenTreeArgList* gtNewListNode(GenTreePtr op1, GenTreeArgList* op2);
1894
1895     GenTreeCall* gtNewCallNode(gtCallTypes           callType,
1896                                CORINFO_METHOD_HANDLE handle,
1897                                var_types             type,
1898                                GenTreeArgList*       args,
1899                                IL_OFFSETX            ilOffset = BAD_IL_OFFSET);
1900
1901     GenTreeCall* gtNewIndCallNode(GenTreePtr      addr,
1902                                   var_types       type,
1903                                   GenTreeArgList* args,
1904                                   IL_OFFSETX      ilOffset = BAD_IL_OFFSET);
1905
1906     GenTreeCall* gtNewHelperCallNode(unsigned        helper,
1907                                      var_types       type,
1908                                      unsigned        flags = 0,
1909                                      GenTreeArgList* args  = nullptr);
1910
1911     GenTreePtr gtNewLclvNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
1912
1913 #ifdef FEATURE_SIMD
1914     GenTreeSIMD* gtNewSIMDNode(
1915         var_types type, GenTreePtr op1, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
1916     GenTreeSIMD* gtNewSIMDNode(var_types       type,
1917                                GenTreePtr      op1,
1918                                GenTreePtr      op2,
1919                                SIMDIntrinsicID simdIntrinsicID,
1920                                var_types       baseType,
1921                                unsigned        size);
1922 #endif
1923
1924     GenTreePtr gtNewLclLNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
1925     GenTreeLclFld* gtNewLclFldNode(unsigned lnum, var_types type, unsigned offset);
1926     GenTreePtr gtNewInlineCandidateReturnExpr(GenTreePtr inlineCandidate, var_types type);
1927
1928     GenTreePtr gtNewCodeRef(BasicBlock* block);
1929
1930     GenTreePtr gtNewFieldRef(
1931         var_types typ, CORINFO_FIELD_HANDLE fldHnd, GenTreePtr obj = nullptr, DWORD offset = 0, bool nullcheck = false);
1932
1933     GenTreePtr gtNewIndexRef(var_types typ, GenTreePtr arrayOp, GenTreePtr indexOp);
1934
1935     GenTreeArgList* gtNewArgList(GenTreePtr op);
1936     GenTreeArgList* gtNewArgList(GenTreePtr op1, GenTreePtr op2);
1937     GenTreeArgList* gtNewArgList(GenTreePtr op1, GenTreePtr op2, GenTreePtr op3);
1938
1939     GenTreeArgList* gtNewAggregate(GenTree* element);
1940
1941     static fgArgTabEntryPtr gtArgEntryByArgNum(GenTreePtr call, unsigned argNum);
1942     static fgArgTabEntryPtr gtArgEntryByNode(GenTreePtr call, GenTreePtr node);
1943     fgArgTabEntryPtr gtArgEntryByLateArgIndex(GenTreePtr call, unsigned lateArgInx);
1944     bool gtArgIsThisPtr(fgArgTabEntryPtr argEntry);
1945
1946     GenTreePtr gtNewAssignNode(GenTreePtr dst, GenTreePtr src);
1947
1948     GenTreePtr gtNewTempAssign(unsigned tmp, GenTreePtr val);
1949
1950     GenTreePtr gtNewRefCOMfield(GenTreePtr              objPtr,
1951                                 CORINFO_RESOLVED_TOKEN* pResolvedToken,
1952                                 CORINFO_ACCESS_FLAGS    access,
1953                                 CORINFO_FIELD_INFO*     pFieldInfo,
1954                                 var_types               lclTyp,
1955                                 CORINFO_CLASS_HANDLE    structType,
1956                                 GenTreePtr              assg);
1957
1958     GenTreePtr gtNewNothingNode();
1959
1960     GenTreePtr gtNewArgPlaceHolderNode(var_types type, CORINFO_CLASS_HANDLE clsHnd);
1961
1962     GenTreePtr gtUnusedValNode(GenTreePtr expr);
1963
1964     GenTreePtr gtNewCastNode(var_types typ, GenTreePtr op1, var_types castType);
1965
1966     GenTreePtr gtNewCastNodeL(var_types typ, GenTreePtr op1, var_types castType);
1967
1968     GenTreePtr gtNewAllocObjNode(unsigned int helper, CORINFO_CLASS_HANDLE clsHnd, var_types type, GenTreePtr op1);
1969
1970     //------------------------------------------------------------------------
1971     // Other GenTree functions
1972
1973     GenTreePtr gtClone(GenTree* tree, bool complexOK = false);
1974
1975     GenTreePtr gtCloneExpr(GenTree* tree, unsigned addFlags = 0, unsigned varNum = (unsigned)-1, int varVal = 0);
1976
1977     GenTreePtr gtReplaceTree(GenTreePtr stmt, GenTreePtr tree, GenTreePtr replacementTree);
1978
1979     void gtUpdateSideEffects(GenTreePtr tree, unsigned oldGtFlags, unsigned newGtFlags);
1980
1981     // Returns "true" iff the complexity (not formally defined, but first interpretation
1982     // is #of nodes in subtree) of "tree" is greater than "limit".
1983     // (This is somewhat redundant with the "gtCostEx/gtCostSz" fields, but can be used
1984     // before they have been set.)
1985     bool gtComplexityExceeds(GenTreePtr* tree, unsigned limit);
1986
1987     bool gtCompareTree(GenTree* op1, GenTree* op2);
1988
1989     GenTreePtr gtReverseCond(GenTree* tree);
1990
1991     bool gtHasRef(GenTree* tree, ssize_t lclNum, bool defOnly);
1992
1993     bool gtHasLocalsWithAddrOp(GenTreePtr tree);
1994
1995     unsigned gtHashValue(GenTree* tree);
1996
1997     unsigned gtSetListOrder(GenTree* list, bool regs, bool isListCallArgs);
1998
1999     void gtWalkOp(GenTree** op1, GenTree** op2, GenTree* adr, bool constOnly);
2000
2001 #ifdef DEBUG
2002     GenTreePtr gtWalkOpEffectiveVal(GenTreePtr op);
2003 #endif
2004
2005     void gtPrepareCost(GenTree* tree);
2006     bool gtIsLikelyRegVar(GenTree* tree);
2007
2008     unsigned gtSetEvalOrderAndRestoreFPstkLevel(GenTree* tree);
2009
2010     // Returns true iff the secondNode can be swapped with firstNode.
2011     bool gtCanSwapOrder(GenTree* firstNode, GenTree* secondNode);
2012
2013     unsigned gtSetEvalOrder(GenTree* tree);
2014
2015 #if FEATURE_STACK_FP_X87
2016     bool gtFPstLvlRedo;
2017     void gtComputeFPlvls(GenTreePtr tree);
2018 #endif // FEATURE_STACK_FP_X87
2019
2020     void gtSetStmtInfo(GenTree* stmt);
2021
2022     // Returns "true" iff "node" has any of the side effects in "flags".
2023     bool gtNodeHasSideEffects(GenTreePtr node, unsigned flags);
2024
2025     // Returns "true" iff "tree" or its (transitive) children have any of the side effects in "flags".
2026     bool gtTreeHasSideEffects(GenTreePtr tree, unsigned flags);
2027
2028     // Appends 'expr' in front of 'list'
2029     //    'list' will typically start off as 'nullptr'
2030     //    when 'list' is non-null a GT_COMMA node is used to insert 'expr'
2031     GenTreePtr gtBuildCommaList(GenTreePtr list, GenTreePtr expr);
2032
2033     void gtExtractSideEffList(GenTreePtr  expr,
2034                               GenTreePtr* pList,
2035                               unsigned    flags      = GTF_SIDE_EFFECT,
2036                               bool        ignoreRoot = false);
2037
2038     GenTreePtr gtGetThisArg(GenTreePtr call);
2039
2040     // Static fields of struct types (and sometimes the types that those are reduced to) are represented by having the
2041     // static field contain an object pointer to the boxed struct.  This simplifies the GC implementation...but
2042     // complicates the JIT somewhat.  This predicate returns "true" iff a node with type "fieldNodeType", representing
2043     // the given "fldHnd", is such an object pointer.
2044     bool gtIsStaticFieldPtrToBoxedStruct(var_types fieldNodeType, CORINFO_FIELD_HANDLE fldHnd);
2045
2046     // Return true if call is a recursive call; return false otherwise.
2047     bool gtIsRecursiveCall(GenTreeCall* call)
2048     {
2049         return (call->gtCallMethHnd == info.compMethodHnd);
2050     }
2051
2052     //-------------------------------------------------------------------------
2053
2054     GenTreePtr gtFoldExpr(GenTreePtr tree);
2055     GenTreePtr
2056 #ifdef __clang__
2057         // TODO-Amd64-Unix: Remove this when the clang optimizer is fixed and/or the method implementation is
2058         // refactored in a simpler code. This is a workaround for a bug in the clang-3.5 optimizer. The issue is that in
2059         // release build the optimizer is mistyping (or just wrongly decides to use 32 bit operation for a corner case
2060         // of MIN_LONG) the args of the (ltemp / lval2) to int (it does a 32 bit div operation instead of 64 bit) - see
2061         // the implementation of the method in gentree.cpp. For the case of lval1 and lval2 equal to MIN_LONG
2062         // (0x8000000000000000) this results in raising a SIGFPE. The method implementation is rather complex. Disable
2063         // optimizations for now.
2064         __attribute__((optnone))
2065 #endif // __clang__
2066         gtFoldExprConst(GenTreePtr tree);
2067     GenTreePtr gtFoldExprSpecial(GenTreePtr tree);
2068     GenTreePtr gtFoldExprCompare(GenTreePtr tree);
2069
2070     //-------------------------------------------------------------------------
2071     // Get the handle, if any.
2072     CORINFO_CLASS_HANDLE gtGetStructHandleIfPresent(GenTreePtr tree);
2073     // Get the handle, and assert if not found.
2074     CORINFO_CLASS_HANDLE gtGetStructHandle(GenTreePtr tree);
2075
2076 //-------------------------------------------------------------------------
2077 // Functions to display the trees
2078
2079 #ifdef DEBUG
2080     void gtDispNode(GenTreePtr tree, IndentStack* indentStack, __in_z const char* msg, bool isLIR);
2081
2082     void gtDispVN(GenTreePtr tree);
2083     void gtDispConst(GenTreePtr tree);
2084     void gtDispLeaf(GenTreePtr tree, IndentStack* indentStack);
2085     void gtDispNodeName(GenTreePtr tree);
2086     void gtDispRegVal(GenTreePtr tree);
2087
2088     enum IndentInfo
2089     {
2090         IINone,
2091         IIArc,
2092         IIArcTop,
2093         IIArcBottom,
2094         IIEmbedded,
2095         IIError,
2096         IndentInfoCount
2097     };
2098     void gtDispChild(GenTreePtr           child,
2099                      IndentStack*         indentStack,
2100                      IndentInfo           arcType,
2101                      __in_opt const char* msg     = nullptr,
2102                      bool                 topOnly = false);
2103     void gtDispTree(GenTreePtr           tree,
2104                     IndentStack*         indentStack = nullptr,
2105                     __in_opt const char* msg         = nullptr,
2106                     bool                 topOnly     = false,
2107                     bool                 isLIR       = false);
2108     void gtGetLclVarNameInfo(unsigned lclNum, const char** ilKindOut, const char** ilNameOut, unsigned* ilNumOut);
2109     int gtGetLclVarName(unsigned lclNum, char* buf, unsigned buf_remaining);
2110     char* gtGetLclVarName(unsigned lclNum);
2111     void gtDispLclVar(unsigned varNum, bool padForBiggestDisp = true);
2112     void gtDispTreeList(GenTreePtr tree, IndentStack* indentStack = nullptr);
2113     void gtGetArgMsg(GenTreePtr call, GenTreePtr arg, unsigned argNum, int listCount, char* bufp, unsigned bufLength);
2114     void gtGetLateArgMsg(GenTreePtr call, GenTreePtr arg, int argNum, int listCount, char* bufp, unsigned bufLength);
2115     void gtDispArgList(GenTreePtr tree, IndentStack* indentStack);
2116     void gtDispFieldSeq(FieldSeqNode* pfsn);
2117
2118     void gtDispRange(LIR::ReadOnlyRange const& range);
2119
2120     void gtDispTreeRange(LIR::Range& containingRange, GenTree* tree);
2121
2122     void gtDispLIRNode(GenTree* node);
2123 #endif
2124
2125     // For tree walks
2126
2127     enum fgWalkResult
2128     {
2129         WALK_CONTINUE,
2130         WALK_SKIP_SUBTREES,
2131         WALK_ABORT
2132     };
2133     struct fgWalkData;
2134     typedef fgWalkResult(fgWalkPreFn)(GenTreePtr* pTree, fgWalkData* data);
2135     typedef fgWalkResult(fgWalkPostFn)(GenTreePtr* pTree, fgWalkData* data);
2136
2137 #ifdef DEBUG
2138     static fgWalkPreFn gtAssertColonCond;
2139 #endif
2140     static fgWalkPreFn gtMarkColonCond;
2141     static fgWalkPreFn gtClearColonCond;
2142
2143     GenTreePtr* gtFindLink(GenTreePtr stmt, GenTreePtr node);
2144     bool gtHasCatchArg(GenTreePtr tree);
2145     bool gtHasUnmanagedCall(GenTreePtr tree);
2146
2147     typedef ArrayStack<GenTree*> GenTreeStack;
2148
2149     static bool gtHasCallOnStack(GenTreeStack* parentStack);
2150     void gtCheckQuirkAddrExposedLclVar(GenTreePtr argTree, GenTreeStack* parentStack);
2151
2152 //=========================================================================
2153 // BasicBlock functions
2154 #ifdef DEBUG
2155     // This is a debug flag we will use to assert when creating block during codegen
2156     // as this interferes with procedure splitting. If you know what you're doing, set
2157     // it to true before creating the block. (DEBUG only)
2158     bool fgSafeBasicBlockCreation;
2159 #endif
2160
2161     BasicBlock* bbNewBasicBlock(BBjumpKinds jumpKind);
2162
2163     /*
2164     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2165     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2166     XX                                                                           XX
2167     XX                           LclVarsInfo                                     XX
2168     XX                                                                           XX
2169     XX   The variables to be used by the code generator.                         XX
2170     XX                                                                           XX
2171     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2172     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2173     */
2174
2175     //
2176     // For both PROMOTION_TYPE_NONE and PROMOTION_TYPE_DEPENDENT the struct will
2177     // be placed in the stack frame and it's fields must be laid out sequentially.
2178     //
2179     // For PROMOTION_TYPE_INDEPENDENT each of the struct's fields is replaced by
2180     //  a local variable that can be enregistered or placed in the stack frame.
2181     //  The fields do not need to be laid out sequentially
2182     //
2183     enum lvaPromotionType
2184     {
2185         PROMOTION_TYPE_NONE,        // The struct local is not promoted
2186         PROMOTION_TYPE_INDEPENDENT, // The struct local is promoted,
2187                                     //   and its field locals are independent of its parent struct local.
2188         PROMOTION_TYPE_DEPENDENT    // The struct local is promoted,
2189                                     //   but its field locals depend on its parent struct local.
2190     };
2191
2192     static int __cdecl RefCntCmp(const void* op1, const void* op2);
2193     static int __cdecl WtdRefCntCmp(const void* op1, const void* op2);
2194
2195     /*****************************************************************************/
2196
2197     enum FrameLayoutState
2198     {
2199         NO_FRAME_LAYOUT,
2200         INITIAL_FRAME_LAYOUT,
2201         PRE_REGALLOC_FRAME_LAYOUT,
2202         REGALLOC_FRAME_LAYOUT,
2203         TENTATIVE_FRAME_LAYOUT,
2204         FINAL_FRAME_LAYOUT
2205     };
2206
2207 public:
2208     bool     lvaRefCountingStarted; // Set to true when we have started counting the local vars
2209     bool     lvaLocalVarRefCounted; // Set to true after we have called lvaMarkLocalVars()
2210     bool     lvaSortAgain;          // true: We need to sort the lvaTable
2211     bool     lvaTrackedFixed;       // true: We cannot add new 'tracked' variable
2212     unsigned lvaCount;              // total number of locals
2213
2214     unsigned   lvaRefCount; // total number of references to locals
2215     LclVarDsc* lvaTable;    // variable descriptor table
2216     unsigned   lvaTableCnt; // lvaTable size (>= lvaCount)
2217
2218     LclVarDsc** lvaRefSorted; // table sorted by refcount
2219
2220     unsigned short lvaTrackedCount;       // actual # of locals being tracked
2221     unsigned lvaTrackedCountInSizeTUnits; // min # of size_t's sufficient to hold a bit for all the locals being tracked
2222
2223 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
2224     // Only for AMD64 System V cache the first caller stack homed argument.
2225     unsigned lvaFirstStackIncomingArgNum; // First argument with stack slot in the caller.
2226 #endif                                    // !FEATURE_UNIX_AMD64_STRUCT_PASSING
2227
2228 #ifdef DEBUG
2229     VARSET_TP lvaTrackedVars; // set of tracked variables
2230 #endif
2231 #ifndef _TARGET_64BIT_
2232     VARSET_TP lvaLongVars; // set of long (64-bit) variables
2233 #endif
2234     VARSET_TP lvaFloatVars; // set of floating-point (32-bit and 64-bit) variables
2235
2236     unsigned lvaCurEpoch; // VarSets are relative to a specific set of tracked var indices.
2237                           // It that changes, this changes.  VarSets from different epochs
2238                           // cannot be meaningfully combined.
2239
2240     unsigned GetCurLVEpoch()
2241     {
2242         return lvaCurEpoch;
2243     }
2244
2245     // reverse map of tracked number to var number
2246     unsigned lvaTrackedToVarNum[lclMAX_TRACKED];
2247
2248 #ifdef LEGACY_BACKEND
2249     // variable interference graph
2250     VARSET_TP lvaVarIntf[lclMAX_TRACKED];
2251 #endif
2252
2253     // variable preference graph
2254     VARSET_TP lvaVarPref[lclMAX_TRACKED];
2255
2256 #if DOUBLE_ALIGN
2257 #ifdef DEBUG
2258     // # of procs compiled a with double-aligned stack
2259     static unsigned s_lvaDoubleAlignedProcsCount;
2260 #endif
2261 #endif
2262
2263     // Getters and setters for address-exposed and do-not-enregister local var properties.
2264     bool lvaVarAddrExposed(unsigned varNum);
2265     void lvaSetVarAddrExposed(unsigned varNum);
2266     bool lvaVarDoNotEnregister(unsigned varNum);
2267 #ifdef DEBUG
2268     // Reasons why we can't enregister.  Some of these correspond to debug properties of local vars.
2269     enum DoNotEnregisterReason
2270     {
2271         DNER_AddrExposed,
2272         DNER_IsStruct,
2273         DNER_LocalField,
2274         DNER_VMNeedsStackAddr,
2275         DNER_LiveInOutOfHandler,
2276         DNER_LiveAcrossUnmanagedCall,
2277         DNER_BlockOp, // Is read or written via a block operation that explicitly takes the address.
2278 #ifdef JIT32_GCENCODER
2279         DNER_PinningRef,
2280 #endif
2281     };
2282 #endif
2283     void lvaSetVarDoNotEnregister(unsigned varNum DEBUGARG(DoNotEnregisterReason reason));
2284
2285     unsigned lvaVarargsHandleArg;
2286 #ifdef _TARGET_X86_
2287     unsigned lvaVarargsBaseOfStkArgs; // Pointer (computed based on incoming varargs handle) to the start of the stack
2288                                       // arguments
2289 #endif                                // _TARGET_X86_
2290
2291     unsigned lvaInlinedPInvokeFrameVar; // variable representing the InlinedCallFrame
2292     unsigned lvaReversePInvokeFrameVar; // variable representing the reverse PInvoke frame
2293 #if FEATURE_FIXED_OUT_ARGS
2294     unsigned lvaPInvokeFrameRegSaveVar; // variable representing the RegSave for PInvoke inlining.
2295 #endif
2296     unsigned lvaMonAcquired; // boolean variable introduced into in synchronized methods
2297                              // that tracks whether the lock has been taken
2298
2299     unsigned lvaArg0Var; // The lclNum of arg0. Normally this will be info.compThisArg.
2300                          // However, if there is a "ldarga 0" or "starg 0" in the IL,
2301                          // we will redirect all "ldarg(a) 0" and "starg 0" to this temp.
2302
2303     unsigned lvaInlineeReturnSpillTemp; // The temp to spill the non-VOID return expression
2304                                         // in case there are multiple BBJ_RETURN blocks in the inlinee.
2305
2306 #if FEATURE_FIXED_OUT_ARGS
2307     unsigned lvaOutgoingArgSpaceVar;  // dummy TYP_LCLBLK var for fixed outgoing argument space
2308     unsigned lvaOutgoingArgSpaceSize; // size of fixed outgoing argument space
2309 #endif                                // FEATURE_FIXED_OUT_ARGS
2310
2311 #ifdef _TARGET_ARM_
2312     // On architectures whose ABIs allow structs to be passed in registers, struct promotion will sometimes
2313     // require us to "rematerialize" a struct from it's separate constituent field variables.  Packing several sub-word
2314     // field variables into an argument register is a hard problem.  It's easier to reserve a word of memory into which
2315     // such field can be copied, after which the assembled memory word can be read into the register.  We will allocate
2316     // this variable to be this scratch word whenever struct promotion occurs.
2317     unsigned lvaPromotedStructAssemblyScratchVar;
2318 #endif // _TARGET_ARM_
2319
2320 #ifdef DEBUG
2321     unsigned lvaReturnEspCheck; // confirms ESP not corrupted on return
2322     unsigned lvaCallEspCheck;   // confirms ESP not corrupted after a call
2323 #endif
2324
2325     bool lvaGenericsContextUsed;
2326
2327     bool lvaKeepAliveAndReportThis(); // Synchronized instance method of a reference type, or
2328                                       // CORINFO_GENERICS_CTXT_FROM_THIS?
2329     bool lvaReportParamTypeArg();     // Exceptions and CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG?
2330
2331 //-------------------------------------------------------------------------
2332 // All these frame offsets are inter-related and must be kept in sync
2333
2334 #if !FEATURE_EH_FUNCLETS
2335     // This is used for the callable handlers
2336     unsigned lvaShadowSPslotsVar; // TYP_BLK variable for all the shadow SP slots
2337 #endif                            // FEATURE_EH_FUNCLETS
2338
2339     unsigned lvaCachedGenericContextArgOffs;
2340     unsigned lvaCachedGenericContextArgOffset(); // For CORINFO_CALLCONV_PARAMTYPE and if generic context is passed as
2341                                                  // THIS pointer
2342
2343     unsigned lvaLocAllocSPvar; // variable which has the result of the last alloca/localloc
2344
2345     unsigned lvaNewObjArrayArgs; // variable with arguments for new MD array helper
2346
2347     // TODO-Review: Prior to reg predict we reserve 24 bytes for Spill temps.
2348     //              after the reg predict we will use a computed maxTmpSize
2349     //              which is based upon the number of spill temps predicted by reg predict
2350     //              All this is necessary because if we under-estimate the size of the spill
2351     //              temps we could fail when encoding instructions that reference stack offsets for ARM.
2352     //
2353     // Pre codegen max spill temp size.
2354     static const unsigned MAX_SPILL_TEMP_SIZE = 24;
2355
2356     //-------------------------------------------------------------------------
2357
2358     unsigned lvaGetMaxSpillTempSize();
2359 #ifdef _TARGET_ARM_
2360     bool lvaIsPreSpilled(unsigned lclNum, regMaskTP preSpillMask);
2361 #endif // _TARGET_ARM_
2362     void lvaAssignFrameOffsets(FrameLayoutState curState);
2363     void lvaFixVirtualFrameOffsets();
2364
2365 #ifndef LEGACY_BACKEND
2366     void lvaUpdateArgsWithInitialReg();
2367 #endif // !LEGACY_BACKEND
2368
2369     void lvaAssignVirtualFrameOffsetsToArgs();
2370 #ifdef UNIX_AMD64_ABI
2371     int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs, int* callerArgOffset);
2372 #else  // !UNIX_AMD64_ABI
2373     int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs);
2374 #endif // !UNIX_AMD64_ABI
2375     void lvaAssignVirtualFrameOffsetsToLocals();
2376     int lvaAllocLocalAndSetVirtualOffset(unsigned lclNum, unsigned size, int stkOffs);
2377 #ifdef _TARGET_AMD64_
2378     // Returns true if compCalleeRegsPushed (including RBP if used as frame pointer) is even.
2379     bool lvaIsCalleeSavedIntRegCountEven();
2380 #endif
2381     void lvaAlignFrame();
2382     void lvaAssignFrameOffsetsToPromotedStructs();
2383     int lvaAllocateTemps(int stkOffs, bool mustDoubleAlign);
2384
2385 #ifdef DEBUG
2386     void lvaDumpRegLocation(unsigned lclNum);
2387     void lvaDumpFrameLocation(unsigned lclNum);
2388     void lvaDumpEntry(unsigned lclNum, FrameLayoutState curState, size_t refCntWtdWidth = 6);
2389     void lvaTableDump(FrameLayoutState curState = NO_FRAME_LAYOUT); // NO_FRAME_LAYOUT means use the current frame
2390                                                                     // layout state defined by lvaDoneFrameLayout
2391 #endif
2392
2393 // Limit frames size to 1GB. The maximum is 2GB in theory - make it intentionally smaller
2394 // to avoid bugs from borderline cases.
2395 #define MAX_FrameSize 0x3FFFFFFF
2396     void lvaIncrementFrameSize(unsigned size);
2397
2398     unsigned lvaFrameSize(FrameLayoutState curState);
2399
2400     // Returns the caller-SP-relative offset for the SP/FP relative offset determined by FP based.
2401     int lvaToCallerSPRelativeOffset(int offs, bool isFpBased);
2402
2403     // Returns the caller-SP-relative offset for the local variable "varNum."
2404     int lvaGetCallerSPRelativeOffset(unsigned varNum);
2405
2406     // Returns the SP-relative offset for the local variable "varNum". Illegal to ask this for functions with localloc.
2407     int lvaGetSPRelativeOffset(unsigned varNum);
2408
2409     int lvaToInitialSPRelativeOffset(unsigned offset, bool isFpBased);
2410     int lvaGetInitialSPRelativeOffset(unsigned varNum);
2411
2412     //------------------------ For splitting types ----------------------------
2413
2414     void lvaInitTypeRef();
2415
2416     void lvaInitArgs(InitVarDscInfo* varDscInfo);
2417     void lvaInitThisPtr(InitVarDscInfo* varDscInfo);
2418     void lvaInitRetBuffArg(InitVarDscInfo* varDscInfo);
2419     void lvaInitUserArgs(InitVarDscInfo* varDscInfo);
2420     void lvaInitGenericsCtxt(InitVarDscInfo* varDscInfo);
2421     void lvaInitVarArgsHandle(InitVarDscInfo* varDscInfo);
2422
2423     void lvaInitVarDsc(LclVarDsc*              varDsc,
2424                        unsigned                varNum,
2425                        CorInfoType             corInfoType,
2426                        CORINFO_CLASS_HANDLE    typeHnd,
2427                        CORINFO_ARG_LIST_HANDLE varList,
2428                        CORINFO_SIG_INFO*       varSig);
2429
2430     static unsigned lvaTypeRefMask(var_types type);
2431
2432     var_types lvaGetActualType(unsigned lclNum);
2433     var_types lvaGetRealType(unsigned lclNum);
2434
2435     //-------------------------------------------------------------------------
2436
2437     void lvaInit();
2438
2439     unsigned lvaArgSize(const void* argTok);
2440     unsigned lvaLclSize(unsigned varNum);
2441     unsigned lvaLclExactSize(unsigned varNum);
2442
2443     bool lvaLclVarRefs(GenTreePtr tree, GenTreePtr* findPtr, varRefKinds* refsPtr, void* result);
2444
2445     // Call lvaLclVarRefs on "true"; accumulate "*result" into whichever of
2446     // "allVars" and "trkdVars" is indiated by the nullness of "findPtr"; return
2447     // the return result.
2448     bool lvaLclVarRefsAccum(
2449         GenTreePtr tree, GenTreePtr* findPtr, varRefKinds* refsPtr, ALLVARSET_TP* allVars, VARSET_TP* trkdVars);
2450
2451     // If "findPtr" is non-NULL, assumes "result" is an "ALLVARSET_TP*", and
2452     // (destructively) unions "allVars" into "*result".  Otherwise, assumes "result" is a "VARSET_TP*",
2453     // and (destructively) unions "trkedVars" into "*result".
2454     void lvaLclVarRefsAccumIntoRes(GenTreePtr*         findPtr,
2455                                    void*               result,
2456                                    ALLVARSET_VALARG_TP allVars,
2457                                    VARSET_VALARG_TP    trkdVars);
2458
2459     bool lvaHaveManyLocals() const;
2460
2461     unsigned lvaGrabTemp(bool shortLifetime DEBUGARG(const char* reason));
2462     unsigned lvaGrabTemps(unsigned cnt DEBUGARG(const char* reason));
2463     unsigned lvaGrabTempWithImplicitUse(bool shortLifetime DEBUGARG(const char* reason));
2464
2465     void lvaSortOnly();
2466     void lvaSortByRefCount();
2467     void lvaDumpRefCounts();
2468
2469     void lvaMarkLocalVars(BasicBlock* block);
2470
2471     void lvaMarkLocalVars(); // Local variable ref-counting
2472
2473     void lvaAllocOutgoingArgSpace(); // 'Commit' lvaOutgoingArgSpaceSize and lvaOutgoingArgSpaceVar
2474
2475     VARSET_VALRET_TP lvaStmtLclMask(GenTreePtr stmt);
2476
2477     static fgWalkPreFn lvaIncRefCntsCB;
2478     void lvaIncRefCnts(GenTreePtr tree);
2479
2480     static fgWalkPreFn lvaDecRefCntsCB;
2481     void lvaDecRefCnts(GenTreePtr tree);
2482     void lvaDecRefCnts(BasicBlock* basicBlock, GenTreePtr tree);
2483     void lvaRecursiveDecRefCounts(GenTreePtr tree);
2484     void lvaRecursiveIncRefCounts(GenTreePtr tree);
2485
2486 #ifdef DEBUG
2487     struct lvaStressLclFldArgs
2488     {
2489         Compiler* m_pCompiler;
2490         bool      m_bFirstPass;
2491     };
2492
2493     static fgWalkPreFn lvaStressLclFldCB;
2494     void               lvaStressLclFld();
2495
2496     void lvaDispVarSet(VARSET_VALARG_TP set, VARSET_VALARG_TP allVars);
2497     void lvaDispVarSet(VARSET_VALARG_TP set);
2498
2499 #endif
2500
2501 #ifdef _TARGET_ARM_
2502     int lvaFrameAddress(int varNum, bool mustBeFPBased, regNumber* pBaseReg, int addrModeOffset);
2503 #else
2504     int lvaFrameAddress(int varNum, bool* pFPbased);
2505 #endif
2506
2507     bool lvaIsParameter(unsigned varNum);
2508     bool lvaIsRegArgument(unsigned varNum);
2509     BOOL lvaIsOriginalThisArg(unsigned varNum); // Is this varNum the original this argument?
2510     BOOL lvaIsOriginalThisReadOnly();           // return TRUE if there is no place in the code
2511                                                 // that writes to arg0
2512
2513     // Struct parameters that are passed by reference are marked as both lvIsParam and lvIsTemp
2514     // (this is an overload of lvIsTemp because there are no temp parameters).
2515     // For x64 this is 3, 5, 6, 7, >8 byte structs that are passed by reference.
2516     // For ARM64, this is structs larger than 16 bytes that are passed by reference.
2517     bool lvaIsImplicitByRefLocal(unsigned varNum)
2518     {
2519 #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
2520         LclVarDsc* varDsc = &(lvaTable[varNum]);
2521         if (varDsc->lvIsParam && varDsc->lvIsTemp)
2522         {
2523             assert((varDsc->lvType == TYP_STRUCT) || (varDsc->lvType == TYP_BYREF));
2524             return true;
2525         }
2526 #endif // defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
2527         return false;
2528     }
2529
2530     // Returns true if this local var is a multireg struct
2531     bool lvaIsMultiregStruct(LclVarDsc* varDsc);
2532
2533     // If the class is a TYP_STRUCT, get/set a class handle describing it
2534
2535     CORINFO_CLASS_HANDLE lvaGetStruct(unsigned varNum);
2536     void lvaSetStruct(unsigned varNum, CORINFO_CLASS_HANDLE typeHnd, bool unsafeValueClsCheck, bool setTypeInfo = true);
2537
2538 #define MAX_NumOfFieldsInPromotableStruct 4 // Maximum number of fields in promotable struct
2539
2540     // Info about struct fields
2541     struct lvaStructFieldInfo
2542     {
2543         CORINFO_FIELD_HANDLE fldHnd;
2544         unsigned char        fldOffset;
2545         unsigned char        fldOrdinal;
2546         var_types            fldType;
2547         unsigned             fldSize;
2548         CORINFO_CLASS_HANDLE fldTypeHnd;
2549     };
2550
2551     // Info about struct to be promoted.
2552     struct lvaStructPromotionInfo
2553     {
2554         CORINFO_CLASS_HANDLE typeHnd;
2555         bool                 canPromote;
2556         bool                 requiresScratchVar;
2557         bool                 containsHoles;
2558         bool                 customLayout;
2559         unsigned char        fieldCnt;
2560         lvaStructFieldInfo   fields[MAX_NumOfFieldsInPromotableStruct];
2561
2562         lvaStructPromotionInfo()
2563             : typeHnd(nullptr), canPromote(false), requiresScratchVar(false), containsHoles(false), customLayout(false)
2564         {
2565         }
2566     };
2567
2568     static int __cdecl lvaFieldOffsetCmp(const void* field1, const void* field2);
2569     void lvaCanPromoteStructType(CORINFO_CLASS_HANDLE    typeHnd,
2570                                  lvaStructPromotionInfo* StructPromotionInfo,
2571                                  bool                    sortFields);
2572     void lvaCanPromoteStructVar(unsigned lclNum, lvaStructPromotionInfo* StructPromotionInfo);
2573     void lvaPromoteStructVar(unsigned lclNum, lvaStructPromotionInfo* StructPromotionInfo);
2574 #if !defined(_TARGET_64BIT_)
2575     void lvaPromoteLongVars();
2576 #endif // !defined(_TARGET_64BIT_)
2577     unsigned lvaGetFieldLocal(LclVarDsc* varDsc, unsigned int fldOffset);
2578     lvaPromotionType lvaGetPromotionType(const LclVarDsc* varDsc);
2579     lvaPromotionType lvaGetPromotionType(unsigned varNum);
2580     lvaPromotionType lvaGetParentPromotionType(const LclVarDsc* varDsc);
2581     lvaPromotionType lvaGetParentPromotionType(unsigned varNum);
2582     bool lvaIsFieldOfDependentlyPromotedStruct(const LclVarDsc* varDsc);
2583     bool lvaIsGCTracked(const LclVarDsc* varDsc);
2584
2585     BYTE* lvaGetGcLayout(unsigned varNum);
2586     bool lvaTypeIsGC(unsigned varNum);
2587     unsigned lvaGSSecurityCookie; // LclVar number
2588     bool     lvaTempsHaveLargerOffsetThanVars();
2589
2590     unsigned lvaSecurityObject;  // variable representing the security object on the stack
2591     unsigned lvaStubArgumentVar; // variable representing the secret stub argument coming in EAX
2592
2593 #if FEATURE_EH_FUNCLETS
2594     unsigned lvaPSPSym; // variable representing the PSPSym
2595 #endif
2596
2597     InlineInfo*     impInlineInfo;
2598     InlineStrategy* m_inlineStrategy;
2599
2600     // The Compiler* that is the root of the inlining tree of which "this" is a member.
2601     Compiler* impInlineRoot();
2602
2603 #if defined(DEBUG) || defined(INLINE_DATA)
2604     unsigned __int64 getInlineCycleCount()
2605     {
2606         return m_compCycles;
2607     }
2608 #endif // defined(DEBUG) || defined(INLINE_DATA)
2609
2610     bool fgNoStructPromotion;      // Set to TRUE to turn off struct promotion for this method.
2611     bool fgNoStructParamPromotion; // Set to TRUE to turn off struct promotion for parameters this method.
2612
2613     //=========================================================================
2614     //                          PROTECTED
2615     //=========================================================================
2616
2617 protected:
2618 //---------------- Local variable ref-counting ----------------------------
2619
2620 #if ASSERTION_PROP
2621     BasicBlock* lvaMarkRefsCurBlock;
2622     GenTreePtr  lvaMarkRefsCurStmt;
2623 #endif
2624     BasicBlock::weight_t lvaMarkRefsWeight;
2625
2626     static fgWalkPreFn lvaMarkLclRefsCallback;
2627     void lvaMarkLclRefs(GenTreePtr tree);
2628
2629     // Keeps the mapping from SSA #'s to VN's for the implicit "Heap" variable.
2630     PerSsaArray lvHeapPerSsaData;
2631     unsigned    lvHeapNumSsaNames;
2632
2633 public:
2634     // Returns the address of the per-Ssa data for "Heap" at the given ssaNum (which is required
2635     // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
2636     // not an SSA variable).
2637     LclSsaVarDsc* GetHeapPerSsaData(unsigned ssaNum)
2638     {
2639         assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
2640         assert(SsaConfig::RESERVED_SSA_NUM == 0);
2641         ssaNum--;
2642         assert(ssaNum < lvHeapNumSsaNames);
2643         return &lvHeapPerSsaData.GetRef(ssaNum);
2644     }
2645
2646     /*
2647     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2648     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2649     XX                                                                           XX
2650     XX                           Importer                                        XX
2651     XX                                                                           XX
2652     XX   Imports the given method and converts it to semantic trees              XX
2653     XX                                                                           XX
2654     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2655     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2656     */
2657
2658 public:
2659     void impInit();
2660
2661     void impImport(BasicBlock* method);
2662
2663     CORINFO_CLASS_HANDLE impGetRefAnyClass();
2664     CORINFO_CLASS_HANDLE impGetRuntimeArgumentHandle();
2665     CORINFO_CLASS_HANDLE impGetTypeHandleClass();
2666     CORINFO_CLASS_HANDLE impGetStringClass();
2667     CORINFO_CLASS_HANDLE impGetObjectClass();
2668
2669     //=========================================================================
2670     //                          PROTECTED
2671     //=========================================================================
2672
2673 protected:
2674     //-------------------- Stack manipulation ---------------------------------
2675
2676     unsigned impStkSize; // Size of the full stack
2677
2678 #define SMALL_STACK_SIZE 16 // number of elements in impSmallStack
2679
2680     StackEntry impSmallStack[SMALL_STACK_SIZE]; // Use this array if possible
2681
2682     struct SavedStack // used to save/restore stack contents.
2683     {
2684         unsigned    ssDepth; // number of values on stack
2685         StackEntry* ssTrees; // saved tree values
2686     };
2687
2688     bool impIsPrimitive(CorInfoType type);
2689     bool impILConsumesAddr(const BYTE* codeAddr, CORINFO_METHOD_HANDLE fncHandle, CORINFO_MODULE_HANDLE scpHandle);
2690
2691     void impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind);
2692     void impPushOnStackNoType(GenTreePtr tree);
2693
2694     void impPushOnStack(GenTreePtr tree, typeInfo ti);
2695     void       impPushNullObjRefOnStack();
2696     StackEntry impPopStack();
2697     StackEntry impPopStack(CORINFO_CLASS_HANDLE& structTypeRet);
2698     GenTreePtr impPopStack(typeInfo& ti);
2699     StackEntry& impStackTop(unsigned n = 0);
2700
2701     void impSaveStackState(SavedStack* savePtr, bool copy);
2702     void impRestoreStackState(SavedStack* savePtr);
2703
2704     GenTreePtr impImportLdvirtftn(GenTreePtr              thisPtr,
2705                                   CORINFO_RESOLVED_TOKEN* pResolvedToken,
2706                                   CORINFO_CALL_INFO*      pCallInfo);
2707
2708     void impImportAndPushBox(CORINFO_RESOLVED_TOKEN* pResolvedToken);
2709
2710     void impImportNewObjArray(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
2711
2712     bool impCanPInvokeInline(var_types callRetTyp);
2713     bool impCanPInvokeInlineCallSite(var_types callRetTyp);
2714     void impCheckForPInvokeCall(GenTreePtr call, CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* sig, unsigned mflags);
2715     GenTreePtr impImportIndirectCall(CORINFO_SIG_INFO* sig, IL_OFFSETX ilOffset = BAD_IL_OFFSET);
2716     void impPopArgsForUnmanagedCall(GenTreePtr call, CORINFO_SIG_INFO* sig);
2717
2718     void impInsertHelperCall(CORINFO_HELPER_DESC* helperCall);
2719     void impHandleAccessAllowed(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
2720     void impHandleAccessAllowedInternal(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
2721
2722     void impInsertCalloutForDelegate(CORINFO_METHOD_HANDLE callerMethodHnd,
2723                                      CORINFO_METHOD_HANDLE calleeMethodHnd,
2724                                      CORINFO_CLASS_HANDLE  delegateTypeHnd);
2725
2726     var_types impImportCall(OPCODE                  opcode,
2727                             CORINFO_RESOLVED_TOKEN* pResolvedToken,
2728                             CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call on a
2729                                                                                // type parameter?
2730                             GenTreePtr         newobjThis,
2731                             int                prefixFlags,
2732                             CORINFO_CALL_INFO* callInfo,
2733                             IL_OFFSET          rawILOffset);
2734
2735     bool impMethodInfo_hasRetBuffArg(CORINFO_METHOD_INFO* methInfo);
2736
2737     GenTreePtr impFixupCallStructReturn(GenTreePtr call, CORINFO_CLASS_HANDLE retClsHnd);
2738
2739     GenTreePtr impInitCallLongReturn(GenTreePtr call);
2740
2741     GenTreePtr impFixupStructReturnType(GenTreePtr op, CORINFO_CLASS_HANDLE retClsHnd);
2742
2743 #ifdef DEBUG
2744     var_types impImportJitTestLabelMark(int numArgs);
2745 #endif // DEBUG
2746
2747     GenTreePtr impInitClass(CORINFO_RESOLVED_TOKEN* pResolvedToken);
2748
2749     GenTreePtr impImportStaticReadOnlyField(void* fldAddr, var_types lclTyp);
2750
2751     GenTreePtr impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2752                                           CORINFO_ACCESS_FLAGS    access,
2753                                           CORINFO_FIELD_INFO*     pFieldInfo,
2754                                           var_types               lclTyp);
2755
2756     static void impBashVarAddrsToI(GenTreePtr tree1, GenTreePtr tree2 = nullptr);
2757
2758     GenTreePtr impImplicitIorI4Cast(GenTreePtr tree, var_types dstTyp);
2759
2760     GenTreePtr impImplicitR4orR8Cast(GenTreePtr tree, var_types dstTyp);
2761
2762     void impImportLeave(BasicBlock* block);
2763     void impResetLeaveBlock(BasicBlock* block, unsigned jmpAddr);
2764     BOOL       impLocAllocOnStack();
2765     GenTreePtr impIntrinsic(CORINFO_CLASS_HANDLE  clsHnd,
2766                             CORINFO_METHOD_HANDLE method,
2767                             CORINFO_SIG_INFO*     sig,
2768                             int                   memberRef,
2769                             bool                  readonlyCall,
2770                             bool                  tailCall,
2771                             CorInfoIntrinsics*    pIntrinsicID);
2772     GenTreePtr impArrayAccessIntrinsic(CORINFO_CLASS_HANDLE clsHnd,
2773                                        CORINFO_SIG_INFO*    sig,
2774                                        int                  memberRef,
2775                                        bool                 readonlyCall,
2776                                        CorInfoIntrinsics    intrinsicID);
2777     GenTreePtr impInitializeArrayIntrinsic(CORINFO_SIG_INFO* sig);
2778
2779     GenTreePtr impMethodPointer(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
2780
2781     GenTreePtr impTransformThis(GenTreePtr              thisPtr,
2782                                 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
2783                                 CORINFO_THIS_TRANSFORM  transform);
2784
2785     //----------------- Manipulating the trees and stmts ----------------------
2786
2787     GenTreePtr impTreeList; // Trees for the BB being imported
2788     GenTreePtr impTreeLast; // The last tree for the current BB
2789
2790     enum
2791     {
2792         CHECK_SPILL_ALL  = -1,
2793         CHECK_SPILL_NONE = -2
2794     };
2795
2796 public:
2797     void impBeginTreeList();
2798     void impEndTreeList(BasicBlock* block, GenTreePtr firstStmt, GenTreePtr lastStmt);
2799     void impEndTreeList(BasicBlock* block);
2800     void impAppendStmtCheck(GenTreePtr stmt, unsigned chkLevel);
2801     void impAppendStmt(GenTreePtr stmt, unsigned chkLevel);
2802     void impInsertStmtBefore(GenTreePtr stmt, GenTreePtr stmtBefore);
2803     GenTreePtr impAppendTree(GenTreePtr tree, unsigned chkLevel, IL_OFFSETX offset);
2804     void impInsertTreeBefore(GenTreePtr tree, IL_OFFSETX offset, GenTreePtr stmtBefore);
2805     void impAssignTempGen(unsigned    tmp,
2806                           GenTreePtr  val,
2807                           unsigned    curLevel,
2808                           GenTreePtr* pAfterStmt = nullptr,
2809                           IL_OFFSETX  ilOffset   = BAD_IL_OFFSET,
2810                           BasicBlock* block      = nullptr);
2811     void impAssignTempGen(unsigned             tmpNum,
2812                           GenTreePtr           val,
2813                           CORINFO_CLASS_HANDLE structHnd,
2814                           unsigned             curLevel,
2815                           GenTreePtr*          pAfterStmt = nullptr,
2816                           IL_OFFSETX           ilOffset   = BAD_IL_OFFSET,
2817                           BasicBlock*          block      = nullptr);
2818     GenTreePtr impCloneExpr(GenTreePtr           tree,
2819                             GenTreePtr*          clone,
2820                             CORINFO_CLASS_HANDLE structHnd,
2821                             unsigned             curLevel,
2822                             GenTreePtr* pAfterStmt DEBUGARG(const char* reason));
2823     GenTreePtr impAssignStruct(GenTreePtr           dest,
2824                                GenTreePtr           src,
2825                                CORINFO_CLASS_HANDLE structHnd,
2826                                unsigned             curLevel,
2827                                GenTreePtr*          pAfterStmt = nullptr,
2828                                BasicBlock*          block      = nullptr);
2829     GenTreePtr impAssignStructPtr(GenTreePtr           dest,
2830                                   GenTreePtr           src,
2831                                   CORINFO_CLASS_HANDLE structHnd,
2832                                   unsigned             curLevel,
2833                                   GenTreePtr*          pAfterStmt = nullptr,
2834                                   BasicBlock*          block      = nullptr);
2835
2836     GenTreePtr impGetStructAddr(GenTreePtr           structVal,
2837                                 CORINFO_CLASS_HANDLE structHnd,
2838                                 unsigned             curLevel,
2839                                 bool                 willDeref);
2840
2841     var_types impNormStructType(CORINFO_CLASS_HANDLE structHnd,
2842                                 BYTE*                gcLayout     = nullptr,
2843                                 unsigned*            numGCVars    = nullptr,
2844                                 var_types*           simdBaseType = nullptr);
2845
2846     GenTreePtr impNormStructVal(GenTreePtr           structVal,
2847                                 CORINFO_CLASS_HANDLE structHnd,
2848                                 unsigned             curLevel,
2849                                 bool                 forceNormalization = false);
2850
2851     GenTreePtr impTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2852                                 BOOL*                   pRuntimeLookup    = nullptr,
2853                                 BOOL                    mustRestoreHandle = FALSE,
2854                                 BOOL                    importParent      = FALSE);
2855
2856     GenTreePtr impParentClassTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2857                                            BOOL*                   pRuntimeLookup    = nullptr,
2858                                            BOOL                    mustRestoreHandle = FALSE)
2859     {
2860         return impTokenToHandle(pResolvedToken, pRuntimeLookup, mustRestoreHandle, TRUE);
2861     }
2862
2863     GenTreePtr impLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2864                                CORINFO_LOOKUP*         pLookup,
2865                                unsigned                flags,
2866                                void*                   compileTimeHandle);
2867
2868     GenTreePtr impRuntimeLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2869                                       CORINFO_LOOKUP*         pLookup,
2870                                       void*                   compileTimeHandle);
2871
2872     GenTreePtr impReadyToRunLookupToTree(CORINFO_CONST_LOOKUP* pLookup, unsigned flags, void* compileTimeHandle);
2873
2874     GenTreePtr impReadyToRunHelperToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2875                                          CorInfoHelpFunc         helper,
2876                                          var_types               type,
2877                                          GenTreeArgList*         arg                = nullptr,
2878                                          CORINFO_LOOKUP_KIND*    pGenericLookupKind = nullptr);
2879
2880     GenTreePtr impCastClassOrIsInstToTree(GenTreePtr              op1,
2881                                           GenTreePtr              op2,
2882                                           CORINFO_RESOLVED_TOKEN* pResolvedToken,
2883                                           bool                    isCastClass);
2884
2885     bool VarTypeIsMultiByteAndCanEnreg(var_types            type,
2886                                        CORINFO_CLASS_HANDLE typeClass,
2887                                        unsigned*            typeSize,
2888                                        bool                 forReturn);
2889
2890     static bool IsIntrinsicImplementedByUserCall(CorInfoIntrinsics intrinsicId);
2891     static bool IsTargetIntrinsic(CorInfoIntrinsics intrinsicId);
2892     static bool IsMathIntrinsic(CorInfoIntrinsics intrinsicId);
2893     static bool IsMathIntrinsic(GenTreePtr tree);
2894
2895 private:
2896     //----------------- Importing the method ----------------------------------
2897
2898     CORINFO_CONTEXT_HANDLE impTokenLookupContextHandle; // The context used for looking up tokens.
2899
2900 #ifdef DEBUG
2901     unsigned    impCurOpcOffs;
2902     const char* impCurOpcName;
2903     bool        impNestedStackSpill;
2904
2905     // For displaying instrs with generated native code (-n:B)
2906     GenTreePtr impLastILoffsStmt; // oldest stmt added for which we did not gtStmtLastILoffs
2907     void       impNoteLastILoffs();
2908 #endif
2909
2910     /* IL offset of the stmt currently being imported. It gets set to
2911        BAD_IL_OFFSET after it has been set in the appended trees. Then it gets
2912        updated at IL offsets for which we have to report mapping info.
2913        It also includes flag bits, so use jitGetILoffs()
2914        to get the actual IL offset value.
2915     */
2916
2917     IL_OFFSETX impCurStmtOffs;
2918     void impCurStmtOffsSet(IL_OFFSET offs);
2919
2920     void impNoteBranchOffs();
2921
2922     unsigned impInitBlockLineInfo();
2923
2924     GenTreePtr impCheckForNullPointer(GenTreePtr obj);
2925     bool impIsThis(GenTreePtr obj);
2926     bool impIsLDFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
2927     bool impIsDUP_LDVIRTFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
2928     bool impIsAnySTLOC(OPCODE opcode)
2929     {
2930         return ((opcode == CEE_STLOC) || (opcode == CEE_STLOC_S) ||
2931                 ((opcode >= CEE_STLOC_0) && (opcode <= CEE_STLOC_3)));
2932     }
2933
2934     GenTreeArgList* impPopList(unsigned          count,
2935                                unsigned*         flagsPtr,
2936                                CORINFO_SIG_INFO* sig,
2937                                GenTreeArgList*   prefixTree = nullptr);
2938
2939     GenTreeArgList* impPopRevList(unsigned          count,
2940                                   unsigned*         flagsPtr,
2941                                   CORINFO_SIG_INFO* sig,
2942                                   unsigned          skipReverseCount = 0);
2943
2944     /*
2945      * Get current IL offset with stack-empty info incoporated
2946      */
2947     IL_OFFSETX impCurILOffset(IL_OFFSET offs, bool callInstruction = false);
2948
2949     //---------------- Spilling the importer stack ----------------------------
2950
2951     struct PendingDsc
2952     {
2953         PendingDsc*   pdNext;
2954         BasicBlock*   pdBB;
2955         SavedStack    pdSavedStack;
2956         ThisInitState pdThisPtrInit;
2957     };
2958
2959     PendingDsc* impPendingList; // list of BBs currently waiting to be imported.
2960     PendingDsc* impPendingFree; // Freed up dscs that can be reused
2961
2962     // We keep a byte-per-block map (dynamically extended) in the top-level Compiler object of a compilation.
2963     ExpandArray<BYTE> impPendingBlockMembers;
2964
2965     // Return the byte for "b" (allocating/extending impPendingBlockMembers if necessary.)
2966     // Operates on the map in the top-level ancestor.
2967     BYTE impGetPendingBlockMember(BasicBlock* blk)
2968     {
2969         return impInlineRoot()->impPendingBlockMembers.Get(blk->bbInd());
2970     }
2971
2972     // Set the byte for "b" to "val" (allocating/extending impPendingBlockMembers if necessary.)
2973     // Operates on the map in the top-level ancestor.
2974     void impSetPendingBlockMember(BasicBlock* blk, BYTE val)
2975     {
2976         impInlineRoot()->impPendingBlockMembers.Set(blk->bbInd(), val);
2977     }
2978
2979     bool impCanReimport;
2980
2981     bool impSpillStackEntry(unsigned level,
2982                             unsigned varNum
2983 #ifdef DEBUG
2984                             ,
2985                             bool        bAssertOnRecursion,
2986                             const char* reason
2987 #endif
2988                             );
2989
2990     void impSpillStackEnsure(bool spillLeaves = false);
2991     void impEvalSideEffects();
2992     void impSpillSpecialSideEff();
2993     void impSpillSideEffects(bool spillGlobEffects, unsigned chkLevel DEBUGARG(const char* reason));
2994     void               impSpillValueClasses();
2995     void               impSpillEvalStack();
2996     static fgWalkPreFn impFindValueClasses;
2997     void impSpillLclRefs(ssize_t lclNum);
2998
2999     BasicBlock* impPushCatchArgOnStack(BasicBlock* hndBlk, CORINFO_CLASS_HANDLE clsHnd);
3000
3001     void impImportBlockCode(BasicBlock* block);
3002
3003     void impReimportMarkBlock(BasicBlock* block);
3004     void impReimportMarkSuccessors(BasicBlock* block);
3005
3006     void impVerifyEHBlock(BasicBlock* block, bool isTryStart);
3007
3008     void impImportBlockPending(BasicBlock* block);
3009
3010     // Similar to impImportBlockPending, but assumes that block has already been imported once and is being
3011     // reimported for some reason.  It specifically does *not* look at verCurrentState to set the EntryState
3012     // for the block, but instead, just re-uses the block's existing EntryState.
3013     void impReimportBlockPending(BasicBlock* block);
3014
3015     var_types impGetByRefResultType(genTreeOps oper, bool fUnsigned, GenTreePtr* pOp1, GenTreePtr* pOp2);
3016
3017     void impImportBlock(BasicBlock* block);
3018
3019     // Assumes that "block" is a basic block that completes with a non-empty stack. We will assign the values
3020     // on the stack to local variables (the "spill temp" variables). The successor blocks will assume that
3021     // its incoming stack contents are in those locals. This requires "block" and its successors to agree on
3022     // the variables that will be used -- and for all the predecessors of those successors, and the
3023     // successors of those predecessors, etc. Call such a set of blocks closed under alternating
3024     // successor/predecessor edges a "spill clique." A block is a "predecessor" or "successor" member of the
3025     // clique (or, conceivably, both). Each block has a specified sequence of incoming and outgoing spill
3026     // temps. If "block" already has its outgoing spill temps assigned (they are always a contiguous series
3027     // of local variable numbers, so we represent them with the base local variable number), returns that.
3028     // Otherwise, picks a set of spill temps, and propagates this choice to all blocks in the spill clique of
3029     // which "block" is a member (asserting, in debug mode, that no block in this clique had its spill temps
3030     // chosen already. More precisely, that the incoming or outgoing spill temps are not chosen, depending
3031     // on which kind of member of the clique the block is).
3032     unsigned impGetSpillTmpBase(BasicBlock* block);
3033
3034     // Assumes that "block" is a basic block that completes with a non-empty stack. We have previously
3035     // assigned the values on the stack to local variables (the "spill temp" variables). The successor blocks
3036     // will assume that its incoming stack contents are in those locals. This requires "block" and its
3037     // successors to agree on the variables and their types that will be used.  The CLI spec allows implicit
3038     // conversions between 'int' and 'native int' or 'float' and 'double' stack types. So one predecessor can
3039     // push an int and another can push a native int.  For 64-bit we have chosen to implement this by typing
3040     // the "spill temp" as native int, and then importing (or re-importing as needed) so that all the
3041     // predecessors in the "spill clique" push a native int (sign-extending if needed), and all the
3042     // successors receive a native int. Similarly float and double are unified to double.
3043     // This routine is called after a type-mismatch is detected, and it will walk the spill clique to mark
3044     // blocks for re-importation as appropriate (both successors, so they get the right incoming type, and
3045     // predecessors, so they insert an upcast if needed).
3046     void impReimportSpillClique(BasicBlock* block);
3047
3048     // When we compute a "spill clique" (see above) these byte-maps are allocated to have a byte per basic
3049     // block, and represent the predecessor and successor members of the clique currently being computed.
3050     // *** Access to these will need to be locked in a parallel compiler.
3051     ExpandArray<BYTE> impSpillCliquePredMembers;
3052     ExpandArray<BYTE> impSpillCliqueSuccMembers;
3053
3054     enum SpillCliqueDir
3055     {
3056         SpillCliquePred,
3057         SpillCliqueSucc
3058     };
3059
3060     // Abstract class for receiving a callback while walking a spill clique
3061     class SpillCliqueWalker
3062     {
3063     public:
3064         virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk) = 0;
3065     };
3066
3067     // This class is used for setting the bbStkTempsIn and bbStkTempsOut on the blocks within a spill clique
3068     class SetSpillTempsBase : public SpillCliqueWalker
3069     {
3070         unsigned m_baseTmp;
3071
3072     public:
3073         SetSpillTempsBase(unsigned baseTmp) : m_baseTmp(baseTmp)
3074         {
3075         }
3076         virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3077     };
3078
3079     // This class is used for implementing impReimportSpillClique part on each block within the spill clique
3080     class ReimportSpillClique : public SpillCliqueWalker
3081     {
3082         Compiler* m_pComp;
3083
3084     public:
3085         ReimportSpillClique(Compiler* pComp) : m_pComp(pComp)
3086         {
3087         }
3088         virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3089     };
3090
3091     // This is the heart of the algorithm for walking spill cliques. It invokes callback->Visit for each
3092     // predecessor or successor within the spill clique
3093     void impWalkSpillCliqueFromPred(BasicBlock* pred, SpillCliqueWalker* callback);
3094
3095     // For a BasicBlock that has already been imported, the EntryState has an array of GenTrees for the
3096     // incoming locals. This walks that list an resets the types of the GenTrees to match the types of
3097     // the VarDscs. They get out of sync when we have int/native int issues (see impReimportSpillClique).
3098     void impRetypeEntryStateTemps(BasicBlock* blk);
3099
3100     BYTE impSpillCliqueGetMember(SpillCliqueDir predOrSucc, BasicBlock* blk);
3101     void impSpillCliqueSetMember(SpillCliqueDir predOrSucc, BasicBlock* blk, BYTE val);
3102
3103     void impPushVar(GenTree* op, typeInfo tiRetVal);
3104     void impLoadVar(unsigned lclNum, IL_OFFSET offset, typeInfo tiRetVal);
3105     void impLoadVar(unsigned lclNum, IL_OFFSET offset)
3106     {
3107         impLoadVar(lclNum, offset, lvaTable[lclNum].lvVerTypeInfo);
3108     }
3109     void impLoadArg(unsigned ilArgNum, IL_OFFSET offset);
3110     void impLoadLoc(unsigned ilLclNum, IL_OFFSET offset);
3111     bool impReturnInstruction(BasicBlock* block, int prefixFlags, OPCODE& opcode);
3112
3113 #ifdef _TARGET_ARM_
3114     void impMarkLclDstNotPromotable(unsigned tmpNum, GenTreePtr op, CORINFO_CLASS_HANDLE hClass);
3115 #endif
3116
3117     // A free list of linked list nodes used to represent to-do stacks of basic blocks.
3118     struct BlockListNode
3119     {
3120         BasicBlock*    m_blk;
3121         BlockListNode* m_next;
3122         BlockListNode(BasicBlock* blk, BlockListNode* next = nullptr) : m_blk(blk), m_next(next)
3123         {
3124         }
3125         void* operator new(size_t sz, Compiler* comp);
3126     };
3127     BlockListNode* impBlockListNodeFreeList;
3128
3129     BlockListNode* AllocBlockListNode();
3130     void FreeBlockListNode(BlockListNode* node);
3131
3132     bool impIsValueType(typeInfo* pTypeInfo);
3133     var_types mangleVarArgsType(var_types type);
3134
3135 #if FEATURE_VARARG
3136     regNumber getCallArgIntRegister(regNumber floatReg);
3137     regNumber getCallArgFloatRegister(regNumber intReg);
3138 #endif // FEATURE_VARARG
3139
3140 #if defined(DEBUG)
3141     static unsigned jitTotalMethodCompiled;
3142 #endif
3143
3144 #ifdef DEBUG
3145     static LONG jitNestingLevel;
3146 #endif // DEBUG
3147
3148     bool seenConditionalJump;
3149
3150     static BOOL impIsAddressInLocal(GenTreePtr tree, GenTreePtr* lclVarTreeOut);
3151
3152     void impMakeDiscretionaryInlineObservations(InlineInfo* pInlineInfo, InlineResult* inlineResult);
3153
3154     // STATIC inlining decision based on the IL code.
3155     void impCanInlineIL(CORINFO_METHOD_HANDLE fncHandle,
3156                         CORINFO_METHOD_INFO*  methInfo,
3157                         bool                  forceInline,
3158                         InlineResult*         inlineResult);
3159
3160     void impCheckCanInline(GenTreePtr             call,
3161                            CORINFO_METHOD_HANDLE  fncHandle,
3162                            unsigned               methAttr,
3163                            CORINFO_CONTEXT_HANDLE exactContextHnd,
3164                            InlineCandidateInfo**  ppInlineCandidateInfo,
3165                            InlineResult*          inlineResult);
3166
3167     void impInlineRecordArgInfo(InlineInfo*   pInlineInfo,
3168                                 GenTreePtr    curArgVal,
3169                                 unsigned      argNum,
3170                                 InlineResult* inlineResult);
3171
3172     void impInlineInitVars(InlineInfo* pInlineInfo);
3173
3174     unsigned impInlineFetchLocal(unsigned lclNum DEBUGARG(const char* reason));
3175
3176     GenTreePtr impInlineFetchArg(unsigned lclNum, InlArgInfo* inlArgInfo, InlLclVarInfo* lclTypeInfo);
3177
3178     BOOL impInlineIsThis(GenTreePtr tree, InlArgInfo* inlArgInfo);
3179
3180     BOOL impInlineIsGuaranteedThisDerefBeforeAnySideEffects(GenTreePtr  additionalTreesToBeEvaluatedBefore,
3181                                                             GenTreePtr  variableBeingDereferenced,
3182                                                             InlArgInfo* inlArgInfo);
3183
3184     void impMarkInlineCandidate(GenTreePtr call, CORINFO_CONTEXT_HANDLE exactContextHnd, CORINFO_CALL_INFO* callInfo);
3185
3186     bool impTailCallRetTypeCompatible(var_types            callerRetType,
3187                                       CORINFO_CLASS_HANDLE callerRetTypeClass,
3188                                       var_types            calleeRetType,
3189                                       CORINFO_CLASS_HANDLE calleeRetTypeClass);
3190
3191     bool impIsTailCallILPattern(bool        tailPrefixed,
3192                                 OPCODE      curOpcode,
3193                                 const BYTE* codeAddrOfNextOpcode,
3194                                 const BYTE* codeEnd,
3195                                 bool        isRecursive,
3196                                 bool*       IsCallPopRet = nullptr);
3197
3198     bool impIsImplicitTailCallCandidate(
3199         OPCODE curOpcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, int prefixFlags, bool isRecursive);
3200
3201     /*
3202     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3203     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3204     XX                                                                           XX
3205     XX                           FlowGraph                                       XX
3206     XX                                                                           XX
3207     XX   Info about the basic-blocks, their contents and the flow analysis       XX
3208     XX                                                                           XX
3209     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3210     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3211     */
3212
3213 public:
3214     BasicBlock* fgFirstBB;        // Beginning of the basic block list
3215     BasicBlock* fgLastBB;         // End of the basic block list
3216     BasicBlock* fgFirstColdBlock; // First block to be placed in the cold section
3217 #if FEATURE_EH_FUNCLETS
3218     BasicBlock* fgFirstFuncletBB; // First block of outlined funclets (to allow block insertion before the funclets)
3219 #endif
3220     BasicBlock* fgFirstBBScratch;   // Block inserted for initialization stuff. Is nullptr if no such block has been
3221                                     // created.
3222     BasicBlockList* fgReturnBlocks; // list of BBJ_RETURN blocks
3223     unsigned        fgEdgeCount;    // # of control flow edges between the BBs
3224     unsigned        fgBBcount;      // # of BBs in the method
3225 #ifdef DEBUG
3226     unsigned fgBBcountAtCodegen; // # of BBs in the method at the start of codegen
3227 #endif
3228     unsigned     fgBBNumMax;       // The max bbNum that has been assigned to basic blocks
3229     unsigned     fgDomBBcount;     // # of BBs for which we have dominator and reachability information
3230     BasicBlock** fgBBInvPostOrder; // The flow graph stored in an array sorted in topological order, needed to compute
3231                                    // dominance. Indexed by block number. Size: fgBBNumMax + 1.
3232
3233     // After the dominance tree is computed, we cache a DFS preorder number and DFS postorder number to compute
3234     // dominance queries in O(1). fgDomTreePreOrder and fgDomTreePostOrder are arrays giving the block's preorder and
3235     // postorder number, respectively. The arrays are indexed by basic block number. (Note that blocks are numbered
3236     // starting from one. Thus, we always waste element zero. This makes debugging easier and makes the code less likely
3237     // to suffer from bugs stemming from forgetting to add or subtract one from the block number to form an array
3238     // index). The arrays are of size fgBBNumMax + 1.
3239     unsigned* fgDomTreePreOrder;
3240     unsigned* fgDomTreePostOrder;
3241
3242     bool fgBBVarSetsInited;
3243
3244     // Allocate array like T* a = new T[fgBBNumMax + 1];
3245     // Using helper so we don't keep forgetting +1.
3246     template <typename T>
3247     T* fgAllocateTypeForEachBlk(CompMemKind cmk = CMK_Unknown)
3248     {
3249         return (T*)compGetMem((fgBBNumMax + 1) * sizeof(T), cmk);
3250     }
3251
3252     // BlockSets are relative to a specific set of BasicBlock numbers. If that changes
3253     // (if the blocks are renumbered), this changes. BlockSets from different epochs
3254     // cannot be meaningfully combined. Note that new blocks can be created with higher
3255     // block numbers without changing the basic block epoch. These blocks *cannot*
3256     // participate in a block set until the blocks are all renumbered, causing the epoch
3257     // to change. This is useful if continuing to use previous block sets is valuable.
3258     // If the epoch is zero, then it is uninitialized, and block sets can't be used.
3259     unsigned fgCurBBEpoch;
3260
3261     unsigned GetCurBasicBlockEpoch()
3262     {
3263         return fgCurBBEpoch;
3264     }
3265
3266     // The number of basic blocks in the current epoch. When the blocks are renumbered,
3267     // this is fgBBcount. As blocks are added, fgBBcount increases, fgCurBBEpochSize remains
3268     // the same, until a new BasicBlock epoch is created, such as when the blocks are all renumbered.
3269     unsigned fgCurBBEpochSize;
3270
3271     // The number of "size_t" elements required to hold a bitset large enough for fgCurBBEpochSize
3272     // bits. This is precomputed to avoid doing math every time BasicBlockBitSetTraits::GetArrSize() is called.
3273     unsigned fgBBSetCountInSizeTUnits;
3274
3275     void NewBasicBlockEpoch()
3276     {
3277         INDEBUG(unsigned oldEpochArrSize = fgBBSetCountInSizeTUnits);
3278
3279         // We have a new epoch. Compute and cache the size needed for new BlockSets.
3280         fgCurBBEpoch++;
3281         fgCurBBEpochSize = fgBBNumMax + 1;
3282         fgBBSetCountInSizeTUnits =
3283             unsigned(roundUp(fgCurBBEpochSize, sizeof(size_t) * 8)) / unsigned(sizeof(size_t) * 8);
3284
3285 #ifdef DEBUG
3286         // All BlockSet objects are now invalid!
3287         fgReachabilitySetsValid = false; // the bbReach sets are now invalid!
3288         fgEnterBlksSetValid     = false; // the fgEnterBlks set is now invalid!
3289
3290         if (verbose)
3291         {
3292             unsigned epochArrSize = BasicBlockBitSetTraits::GetArrSize(this, sizeof(size_t));
3293             printf("\nNew BlockSet epoch %d, # of blocks (including unused BB00): %u, bitset array size: %u (%s)",
3294                    fgCurBBEpoch, fgCurBBEpochSize, epochArrSize, (epochArrSize <= 1) ? "short" : "long");
3295             if ((fgCurBBEpoch != 1) && ((oldEpochArrSize <= 1) != (epochArrSize <= 1)))
3296             {
3297                 // If we're not just establishing the first epoch, and the epoch array size has changed such that we're
3298                 // going to change our bitset representation from short (just a size_t bitset) to long (a pointer to an
3299                 // array of size_t bitsets), then print that out.
3300                 printf("; NOTE: BlockSet size was previously %s!", (oldEpochArrSize <= 1) ? "short" : "long");
3301             }
3302             printf("\n");
3303         }
3304 #endif // DEBUG
3305     }
3306
3307     void EnsureBasicBlockEpoch()
3308     {
3309         if (fgCurBBEpochSize != fgBBNumMax + 1)
3310         {
3311             NewBasicBlockEpoch();
3312         }
3313     }
3314
3315     BasicBlock* fgNewBasicBlock(BBjumpKinds jumpKind);
3316     void fgEnsureFirstBBisScratch();
3317     bool fgFirstBBisScratch();
3318     bool fgBBisScratch(BasicBlock* block);
3319
3320     void fgExtendEHRegionBefore(BasicBlock* block);
3321     void fgExtendEHRegionAfter(BasicBlock* block);
3322
3323     BasicBlock* fgNewBBbefore(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
3324
3325     BasicBlock* fgNewBBafter(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
3326
3327     BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
3328                                 unsigned    tryIndex,
3329                                 unsigned    hndIndex,
3330                                 BasicBlock* nearBlk,
3331                                 bool        putInFilter = false,
3332                                 bool        runRarely   = false,
3333                                 bool        insertAtEnd = false);
3334
3335     BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
3336                                 BasicBlock* srcBlk,
3337                                 bool        runRarely   = false,
3338                                 bool        insertAtEnd = false);
3339
3340     BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind);
3341
3342     BasicBlock* fgNewBBinRegionWorker(BBjumpKinds jumpKind,
3343                                       BasicBlock* afterBlk,
3344                                       unsigned    xcptnIndex,
3345                                       bool        putInTryRegion);
3346
3347     void fgInsertBBbefore(BasicBlock* insertBeforeBlk, BasicBlock* newBlk);
3348     void fgInsertBBafter(BasicBlock* insertAfterBlk, BasicBlock* newBlk);
3349     void fgUnlinkBlock(BasicBlock* block);
3350
3351 #if OPT_BOOL_OPS // Used to detect multiple logical "not" assignments.
3352     bool fgMultipleNots;
3353 #endif
3354
3355     bool fgModified;         // True if the flow graph has been modified recently
3356     bool fgComputePredsDone; // Have we computed the bbPreds list
3357     bool fgCheapPredsValid;  // Is the bbCheapPreds list valid?
3358     bool fgDomsComputed;     // Have we computed the dominator sets?
3359
3360     bool     fgHasSwitch;  // any BBJ_SWITCH jumps?
3361     bool     fgHasPostfix; // any postfix ++/-- found?
3362     unsigned fgIncrCount;  // number of increment nodes found
3363
3364     BlockSet fgEnterBlks; // Set of blocks which have a special transfer of control; the "entry" blocks plus EH handler
3365                           // begin blocks.
3366
3367 #ifdef DEBUG
3368     bool fgReachabilitySetsValid; // Are the bbReach sets valid?
3369     bool fgEnterBlksSetValid;     // Is the fgEnterBlks set valid?
3370 #endif                            // DEBUG
3371
3372     bool fgRemoveRestOfBlock; // true if we know that we will throw
3373     bool fgStmtRemoved;       // true if we remove statements -> need new DFA
3374
3375     // There are two modes for ordering of the trees.
3376     //  - In FGOrderTree, the dominant ordering is the tree order, and the nodes contained in
3377     //    each tree and sub-tree are contiguous, and can be traversed (in gtNext/gtPrev order)
3378     //    by traversing the tree according to the order of the operands.
3379     //  - In FGOrderLinear, the dominant ordering is the linear order.
3380
3381     enum FlowGraphOrder
3382     {
3383         FGOrderTree,
3384         FGOrderLinear
3385     };
3386     FlowGraphOrder fgOrder;
3387
3388     // The following are boolean flags that keep track of the state of internal data structures
3389
3390     bool                 fgStmtListThreaded;
3391     bool                 fgCanRelocateEHRegions;   // true if we are allowed to relocate the EH regions
3392     bool                 fgEdgeWeightsComputed;    // true after we have called fgComputeEdgeWeights
3393     bool                 fgHaveValidEdgeWeights;   // true if we were successful in computing all of the edge weights
3394     bool                 fgSlopUsedInEdgeWeights;  // true if their was some slop used when computing the edge weights
3395     bool                 fgRangeUsedInEdgeWeights; // true if some of the edgeWeight are expressed in Min..Max form
3396     bool                 fgNeedsUpdateFlowGraph;   // true if we need to run fgUpdateFlowGraph
3397     BasicBlock::weight_t fgCalledWeight;           // count of the number of times this method was called
3398                                                    // This is derived from the profile data
3399                                                    // or is BB_UNITY_WEIGHT when we don't have profile data
3400
3401 #if FEATURE_EH_FUNCLETS
3402     bool fgFuncletsCreated; // true if the funclet creation phase has been run
3403 #endif                      // FEATURE_EH_FUNCLETS
3404
3405     bool fgGlobalMorph;  // indicates if we are during the global morphing phase
3406                          // since fgMorphTree can be called from several places
3407     bool fgExpandInline; // indicates that we are creating tree for the inliner
3408
3409     bool     impBoxTempInUse; // the temp below is valid and available
3410     unsigned impBoxTemp;      // a temporary that is used for boxing
3411
3412 #ifdef DEBUG
3413     bool jitFallbackCompile; // Are we doing a fallback compile? That is, have we executed a NO_WAY assert,
3414                              //   and we are trying to compile again in a "safer", minopts mode?
3415 #endif
3416
3417 #if defined(DEBUG)
3418     unsigned impInlinedCodeSize;
3419 #endif
3420
3421     //-------------------------------------------------------------------------
3422
3423     void fgInit();
3424
3425     void fgImport();
3426
3427     void fgInline();
3428
3429     GenTreePtr fgGetCritSectOfStaticMethod();
3430
3431 #if !defined(_TARGET_X86_)
3432
3433     void fgAddSyncMethodEnterExit();
3434
3435     GenTree* fgCreateMonitorTree(unsigned lvaMonitorBool, unsigned lvaThisVar, BasicBlock* block, bool enter);
3436
3437     void fgConvertSyncReturnToLeave(BasicBlock* block);
3438
3439 #endif // !_TARGET_X86_
3440
3441     void fgAddReversePInvokeEnterExit();
3442
3443     bool fgMoreThanOneReturnBlock();
3444
3445     // The number of separate return points in the method.
3446     unsigned fgReturnCount;
3447
3448     void fgAddInternal();
3449
3450     bool fgFoldConditional(BasicBlock* block);
3451
3452     void fgMorphStmts(BasicBlock* block, bool* mult, bool* lnot, bool* loadw);
3453     void fgMorphBlocks();
3454
3455     bool fgMorphBlockStmt(BasicBlock* block, GenTreePtr stmt DEBUGARG(const char* msg));
3456
3457     void fgSetOptions();
3458
3459 #ifdef DEBUG
3460     static fgWalkPreFn fgAssertNoQmark;
3461     void fgPreExpandQmarkChecks(GenTreePtr expr);
3462     void        fgPostExpandQmarkChecks();
3463     static void fgCheckQmarkAllowedForm(GenTreePtr tree);
3464 #endif
3465
3466     IL_OFFSET fgFindBlockILOffset(BasicBlock* block);
3467
3468     BasicBlock* fgSplitBlockAtBeginning(BasicBlock* curr);
3469     BasicBlock* fgSplitBlockAtEnd(BasicBlock* curr);
3470     BasicBlock* fgSplitBlockAfterStatement(BasicBlock* curr, GenTree* stmt);
3471     BasicBlock* fgSplitBlockAfterNode(BasicBlock* curr, GenTree* node); // for LIR
3472     BasicBlock* fgSplitEdge(BasicBlock* curr, BasicBlock* succ);
3473
3474     GenTreeStmt* fgNewStmtFromTree(GenTreePtr tree, BasicBlock* block, IL_OFFSETX offs);
3475     GenTreeStmt* fgNewStmtFromTree(GenTreePtr tree);
3476     GenTreeStmt* fgNewStmtFromTree(GenTreePtr tree, BasicBlock* block);
3477     GenTreeStmt* fgNewStmtFromTree(GenTreePtr tree, IL_OFFSETX offs);
3478
3479     GenTreePtr fgGetTopLevelQmark(GenTreePtr expr, GenTreePtr* ppDst = nullptr);
3480     void fgExpandQmarkForCastInstOf(BasicBlock* block, GenTreePtr stmt);
3481     void fgExpandQmarkStmt(BasicBlock* block, GenTreePtr expr);
3482     void fgExpandQmarkNodes();
3483
3484     void fgMorph();
3485
3486     // Do "simple lowering."  This functionality is (conceptually) part of "general"
3487     // lowering that is distributed between fgMorph and the lowering phase of LSRA.
3488     void fgSimpleLowering();
3489
3490     bool fgShouldCreateAssignOp(GenTreePtr tree, bool* bReverse);
3491
3492     GenTreePtr fgInitThisClass();
3493
3494     GenTreePtr fgGetStaticsCCtorHelper(CORINFO_CLASS_HANDLE cls, CorInfoHelpFunc helper);
3495
3496     GenTreePtr fgGetSharedCCtor(CORINFO_CLASS_HANDLE cls);
3497
3498     void fgLocalVarLiveness();
3499
3500     void fgLocalVarLivenessInit();
3501
3502 #ifdef LEGACY_BACKEND
3503     GenTreePtr fgLegacyPerStatementLocalVarLiveness(GenTreePtr startNode, GenTreePtr relopNode, GenTreePtr asgdLclVar);
3504 #else
3505     void fgPerNodeLocalVarLiveness(GenTree* node, GenTree* asgdLclVar);
3506     void fgPerStatementLocalVarLiveness(GenTree* node, GenTree* asgdLclVar);
3507 #endif
3508     void fgPerBlockLocalVarLiveness();
3509
3510     VARSET_VALRET_TP fgGetHandlerLiveVars(BasicBlock* block);
3511
3512     void fgLiveVarAnalysis(bool updateInternalOnly = false);
3513
3514     // This is used in the liveness computation, as a temporary.  When we use the
3515     // arbitrary-length VarSet representation, it is better not to allocate a new one
3516     // at each call.
3517     VARSET_TP fgMarkIntfUnionVS;
3518
3519     bool fgMarkIntf(VARSET_VALARG_TP varSet);
3520
3521     bool fgMarkIntf(VARSET_VALARG_TP varSet1, VARSET_VALARG_TP varSet2);
3522
3523     void fgUpdateRefCntForClone(BasicBlock* addedToBlock, GenTreePtr clonedTree);
3524
3525     void fgUpdateRefCntForExtract(GenTreePtr wholeTree, GenTreePtr keptTree);
3526
3527     void fgComputeLifeCall(VARSET_TP& life, GenTreeCall* call);
3528
3529     bool fgComputeLifeLocal(VARSET_TP& life, VARSET_TP& keepAliveVars, GenTree* lclVarNode, GenTree* node);
3530
3531     VARSET_VALRET_TP fgComputeLife(VARSET_VALARG_TP life,
3532                                    GenTreePtr       startNode,
3533                                    GenTreePtr       endNode,
3534                                    VARSET_VALARG_TP volatileVars,
3535                                    bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
3536
3537     VARSET_VALRET_TP fgComputeLifeLIR(VARSET_VALARG_TP life, BasicBlock* block, VARSET_VALARG_TP volatileVars);
3538
3539     bool fgRemoveDeadStore(GenTree**  pTree,
3540                            LclVarDsc* varDsc,
3541                            VARSET_TP  life,
3542                            bool*      doAgain,
3543                            bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
3544
3545     bool fgTryRemoveDeadLIRStore(LIR::Range& blockRange, GenTree* node, GenTree** next);
3546
3547     // For updating liveset during traversal AFTER fgComputeLife has completed
3548     VARSET_VALRET_TP fgGetVarBits(GenTreePtr tree);
3549     VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTreePtr tree);
3550
3551     // Returns the set of live variables after endTree,
3552     // assuming that liveSet is the set of live variables BEFORE tree.
3553     // Requires that fgComputeLife has completed, and that tree is in the same
3554     // statement as endTree, and that it comes before endTree in execution order
3555
3556     VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTreePtr tree, GenTreePtr endTree)
3557     {
3558         VARSET_TP VARSET_INIT(this, newLiveSet, liveSet);
3559         while (tree != nullptr && tree != endTree->gtNext)
3560         {
3561             VarSetOps::AssignNoCopy(this, newLiveSet, fgUpdateLiveSet(newLiveSet, tree));
3562             tree = tree->gtNext;
3563         }
3564         assert(tree == endTree->gtNext);
3565         return newLiveSet;
3566     }
3567
3568     void fgInterBlockLocalVarLiveness();
3569
3570     // The presence of "x op= y" operations presents some difficulties for SSA: this is both a use of some SSA name of
3571     // "x", and a def of a new SSA name for "x".  The tree only has one local variable for "x", so it has to choose
3572     // whether to treat that as the use or def.  It chooses the "use", and thus the old SSA name.  This map allows us
3573     // to record/recover the "def" SSA number, given the lcl var node for "x" in such a tree.
3574     typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, unsigned, JitSimplerHashBehavior> NodeToUnsignedMap;
3575     NodeToUnsignedMap* m_opAsgnVarDefSsaNums;
3576     NodeToUnsignedMap* GetOpAsgnVarDefSsaNums()
3577     {
3578         if (m_opAsgnVarDefSsaNums == nullptr)
3579         {
3580             m_opAsgnVarDefSsaNums = new (getAllocator()) NodeToUnsignedMap(getAllocator());
3581         }
3582         return m_opAsgnVarDefSsaNums;
3583     }
3584
3585     // Requires value numbering phase to have completed. Returns the value number ("gtVN") of the
3586     // "tree," EXCEPT in the case of GTF_VAR_USEASG, because the tree node's gtVN member is the
3587     // "use" VN. Performs a lookup into the map of (use asg tree -> def VN.) to return the "def's"
3588     // VN.
3589     inline ValueNum GetUseAsgDefVNOrTreeVN(GenTreePtr tree);
3590
3591     // Requires that "lcl" has the GTF_VAR_DEF flag set.  Returns the SSA number of "lcl".
3592     // Except: assumes that lcl is a def, and if it is
3593     // a def appearing in "lcl op= rhs" (GTF_VAR_USEASG), looks up and returns the SSA number for the "def",
3594     // rather than the "use" SSA number recorded in the tree "lcl".
3595     inline unsigned GetSsaNumForLocalVarDef(GenTreePtr lcl);
3596
3597     // Some assignments assign to a local "indirectly": they are part of a comma expression that takes the address
3598     // of the local (or a field thereof), assigns this address to a temp, and uses an indirection of this temp as
3599     // the LHS of the assignment.  This actually arises in exactly one situation.  At the source level we assign one
3600     // struct local to another: "s1 = s2".  This becomes a copyblk.  If "s2" is promoted into  field variables "s2f0",
3601     // ..."s2fn", then the copyblk will morph to a comma expression that takes the address of "s1" and does field-wise
3602     // assignments:
3603     //   (byref addrS1 = &s1,
3604     //    *(addrS1 * offsetof(f0)) = s2f0,
3605     //    ...
3606     //    *(addrS1 * offsetof(fn)) = s2fn)
3607     //
3608     // It would be a shame, given the simple form at the source level, to be unable to track the values in the
3609     // fields of "s1" after this.  But "s1" does not appear in the assignments that modify it.  How, then, to
3610     // give it SSA names and value numbers?
3611     //
3612     // The solution is to use the side table described below to annotate each of the field-wise assignments at the
3613     // end with an instance of the structure below, whose fields are described in the declaration.
3614     struct IndirectAssignmentAnnotation
3615     {
3616         unsigned      m_lclNum;   // The local num that is being indirectly assigned.
3617         FieldSeqNode* m_fieldSeq; // If the LHS of the struct assignment is itself a struct field dereference,
3618                                   // as in "s0.g = s2", then "m_lclNum" would be "s0", and "m_fieldSeq" would
3619                                   // be the singleton field sequence "g".  The individual assignments would
3620                                   // further append the fields of "s.g" to that.
3621         bool m_isEntire;          // True iff this assignment writes all of m_lclNum.  (This can occur if the
3622                                   // structure has a single field).
3623         unsigned m_defSsaNum;     // The new SSA number of "m_lclNum" after the assignment.
3624         unsigned m_useSsaNum;     // Only valid if "m_isEntire" is false; if so, the SSA number of "m_lclNum" before the
3625                                   // assignment.
3626
3627         IndirectAssignmentAnnotation(unsigned      lclNum,
3628                                      FieldSeqNode* fldSeq,
3629                                      bool          isEntire,
3630                                      unsigned      defSsaNum = SsaConfig::RESERVED_SSA_NUM,
3631                                      unsigned      useSsaNum = SsaConfig::RESERVED_SSA_NUM)
3632             : m_lclNum(lclNum), m_fieldSeq(fldSeq), m_isEntire(isEntire), m_defSsaNum(defSsaNum), m_useSsaNum(useSsaNum)
3633         {
3634         }
3635     };
3636     typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, IndirectAssignmentAnnotation*, JitSimplerHashBehavior>
3637                           NodeToIndirAssignMap;
3638     NodeToIndirAssignMap* m_indirAssignMap;
3639     NodeToIndirAssignMap* GetIndirAssignMap()
3640     {
3641         if (m_indirAssignMap == nullptr)
3642         {
3643             // Create a CompAllocator that labels sub-structure with CMK_IndirAssignMap, and use that for allocation.
3644             IAllocator* ialloc = new (this, CMK_IndirAssignMap) CompAllocator(this, CMK_IndirAssignMap);
3645             m_indirAssignMap   = new (ialloc) NodeToIndirAssignMap(ialloc);
3646         }
3647         return m_indirAssignMap;
3648     }
3649
3650     // Performs SSA conversion.
3651     void fgSsaBuild();
3652
3653     // Reset any data structures to the state expected by "fgSsaBuild", so it can be run again.
3654     void fgResetForSsa();
3655
3656     unsigned fgSsaPassesCompleted; // Number of times fgSsaBuild has been run.
3657
3658     // Returns "true" iff lcl "lclNum" should be excluded from SSA.
3659     inline bool fgExcludeFromSsa(unsigned lclNum);
3660
3661     // The value numbers for this compilation.
3662     ValueNumStore* vnStore;
3663
3664 public:
3665     ValueNumStore* GetValueNumStore()
3666     {
3667         return vnStore;
3668     }
3669
3670     // Do value numbering (assign a value number to each
3671     // tree node).
3672     void fgValueNumber();
3673
3674     // Updates "fgCurHeap" via the assignment H[elemTypeEq][arrVN][inx][fldSeq] = rhsVN.
3675     // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
3676     // The 'indType' is the indirection type of the lhs of the assignment and will typically
3677     // match the element type of the array or fldSeq.  When this type doesn't match
3678     // or if the fldSeq is 'NotAField' we invalidate the array contents H[elemTypeEq][arrVN]
3679     //
3680     void fgValueNumberArrIndexAssign(CORINFO_CLASS_HANDLE elemTypeEq,
3681                                      ValueNum             arrVN,
3682                                      ValueNum             inxVN,
3683                                      FieldSeqNode*        fldSeq,
3684                                      ValueNum             rhsVN,
3685                                      var_types            indType);
3686
3687     // Requires that "tree" is a GT_IND marked as an array index, and that its address argument
3688     // has been parsed to yield the other input arguments.  If evaluation of the address
3689     // can raise exceptions, those should be captured in the exception set "excVN."
3690     // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
3691     // Marks "tree" with the VN for H[elemTypeEq][arrVN][inx][fldSeq] (for the liberal VN; a new unique
3692     // VN for the conservative VN.)  Also marks the tree's argument as the address of an array element.
3693     // The type tree->TypeGet() will typically match the element type of the array or fldSeq.
3694     // When this type doesn't match or if the fldSeq is 'NotAField' we return a new unique VN
3695     //
3696     ValueNum fgValueNumberArrIndexVal(GenTreePtr           tree,
3697                                       CORINFO_CLASS_HANDLE elemTypeEq,
3698                                       ValueNum             arrVN,
3699                                       ValueNum             inxVN,
3700                                       ValueNum             excVN,
3701                                       FieldSeqNode*        fldSeq);
3702
3703     // Requires "funcApp" to be a VNF_PtrToArrElem, and "addrXvn" to represent the exception set thrown
3704     // by evaluating the array index expression "tree".  Returns the value number resulting from
3705     // dereferencing the array in the current heap state.  If "tree" is non-null, it must be the
3706     // "GT_IND" that does the dereference, and it is given the returned value number.
3707     ValueNum fgValueNumberArrIndexVal(GenTreePtr tree, struct VNFuncApp* funcApp, ValueNum addrXvn);
3708
3709     unsigned fgVNPassesCompleted; // Number of times fgValueNumber has been run.
3710
3711     // Utility functions for fgValueNumber.
3712
3713     // Perform value-numbering for the trees in "blk".  When giving VN's to the SSA
3714     // names defined by phi definitions at the start of "blk", "newVNsForPhis" indicates
3715     // that these should be given new VN's, irrespective of the values of the LHS.
3716     // If "false", then we may assume that all inputs to phi RHS's of such definitions
3717     // have already been assigned value numbers; if they are all assigned the *same* value
3718     // number, then the LHS SSA name gets the same VN.
3719     void fgValueNumberBlock(BasicBlock* blk, bool newVNsForPhis);
3720
3721     // Requires that "entryBlock" is the entry block of loop "loopNum", and that "loopNum" is the
3722     // innermost loop of which "entryBlock" is the entry.  Returns the value number that should be
3723     // assumed for the heap at the start "entryBlk".
3724     ValueNum fgHeapVNForLoopSideEffects(BasicBlock* entryBlock, unsigned loopNum);
3725
3726     // Called when an operation (performed by "tree", described by "msg") may cause the global Heap to be mutated.
3727     void fgMutateHeap(GenTreePtr tree DEBUGARG(const char* msg));
3728
3729     // Tree caused an update in the current heap VN.  If "tree" has an associated heap SSA #, record that
3730     // value in that SSA #.
3731     void fgValueNumberRecordHeapSsa(GenTreePtr tree);
3732
3733     // The input 'tree' is a leaf node that is a constant
3734     // Assign the proper value number to the tree
3735     void fgValueNumberTreeConst(GenTreePtr tree);
3736
3737     // Assumes that all inputs to "tree" have had value numbers assigned; assigns a VN to tree.
3738     // (With some exceptions: the VN of the lhs of an assignment is assigned as part of the
3739     // assignment.)
3740     // If "evalAsgLhsInd" is true, evaluate a GT_IND node, even if it's labeled as the LHS of
3741     // an assignment.
3742     void fgValueNumberTree(GenTreePtr tree, bool evalAsgLhsInd = false);
3743
3744     // Does value-numbering for a block assignment.
3745     void fgValueNumberBlockAssignment(GenTreePtr tree, bool evalAsgLhsInd);
3746
3747     // Does value-numbering for a cast tree.
3748     void fgValueNumberCastTree(GenTreePtr tree);
3749
3750     // Does value-numbering for an intrinsic tree.
3751     void fgValueNumberIntrinsic(GenTreePtr tree);
3752
3753     // Does value-numbering for a call.  We interpret some helper calls.
3754     void fgValueNumberCall(GenTreeCall* call);
3755
3756     // The VN of some nodes in "args" may have changed -- reassign VNs to the arg list nodes.
3757     void fgUpdateArgListVNs(GenTreeArgList* args);
3758
3759     // Does value-numbering for a helper "call" that has a VN function symbol "vnf".
3760     void fgValueNumberHelperCallFunc(GenTreeCall* call, VNFunc vnf, ValueNumPair vnpExc);
3761
3762     // Requires "helpCall" to be a helper call.  Assigns it a value number;
3763     // we understand the semantics of some of the calls.  Returns "true" if
3764     // the call may modify the heap (we assume arbitrary memory side effects if so).
3765     bool fgValueNumberHelperCall(GenTreeCall* helpCall);
3766
3767     // Requires "helpFunc" to be pure.  Returns the corresponding VNFunc.
3768     VNFunc fgValueNumberHelperMethVNFunc(CorInfoHelpFunc helpFunc);
3769
3770     // This is the current value number for the "Heap" implicit variable while
3771     // doing value numbering.  This is the value number under the "liberal" interpretation
3772     // of heap values; the "conservative" interpretation needs no VN, since every access of
3773     // the heap yields an unknown value.
3774     ValueNum fgCurHeapVN;
3775
3776     // Return a "pseudo"-class handle for an array element type.  If "elemType" is TYP_STRUCT,
3777     // requires "elemStructType" to be non-null (and to have a low-order zero).  Otherwise, low order bit
3778     // is 1, and the rest is an encoding of "elemTyp".
3779     static CORINFO_CLASS_HANDLE EncodeElemType(var_types elemTyp, CORINFO_CLASS_HANDLE elemStructType)
3780     {
3781         if (elemStructType != nullptr)
3782         {
3783             assert(varTypeIsStruct(elemTyp) || elemTyp == TYP_REF || elemTyp == TYP_BYREF ||
3784                    varTypeIsIntegral(elemTyp));
3785             assert((size_t(elemStructType) & 0x1) == 0x0); // Make sure the encoding below is valid.
3786             return elemStructType;
3787         }
3788         else
3789         {
3790             elemTyp = varTypeUnsignedToSigned(elemTyp);
3791             return CORINFO_CLASS_HANDLE(size_t(elemTyp) << 1 | 0x1);
3792         }
3793     }
3794     // If "clsHnd" is the result of an "EncodePrim" call, returns true and sets "*pPrimType" to the
3795     // var_types it represents.  Otherwise, returns TYP_STRUCT (on the assumption that "clsHnd" is
3796     // the struct type of the element).
3797     static var_types DecodeElemType(CORINFO_CLASS_HANDLE clsHnd)
3798     {
3799         size_t clsHndVal = size_t(clsHnd);
3800         if (clsHndVal & 0x1)
3801         {
3802             return var_types(clsHndVal >> 1);
3803         }
3804         else
3805         {
3806             return TYP_STRUCT;
3807         }
3808     }
3809
3810     // Convert a BYTE which represents the VM's CorInfoGCtype to the JIT's var_types
3811     var_types getJitGCType(BYTE gcType);
3812
3813     enum structPassingKind
3814     {
3815         SPK_Unknown,       // Invalid value, never returned
3816         SPK_PrimitiveType, // The struct is passed/returned using a primitive type.
3817         SPK_ByValue,       // The struct is passed/returned by value (using the ABI rules)
3818                            //  for ARM64 and UNIX_X64 in multiple registers. (when all of the
3819                            //   parameters registers are used, then the stack will be used)
3820                            //  for X86 passed on the stack, for ARM32 passed in registers
3821                            //   or the stack or split between registers and the stack.
3822         SPK_ByValueAsHfa,  // The struct is passed/returned as an HFA in multiple registers.
3823         SPK_ByReference
3824     }; // The struct is passed/returned by reference to a copy/buffer.
3825
3826     // Get the "primitive" type that is is used when we are given a struct of size 'structSize'.
3827     // For pointer sized structs the 'clsHnd' is used to determine if the struct contains GC ref.
3828     // A "primitive" type is one of the scalar types: byte, short, int, long, ref, float, double
3829     // If we can't or shouldn't use a "primitive" type then TYP_UNKNOWN is returned.
3830     //
3831     var_types getPrimitiveTypeForStruct(unsigned structSize, CORINFO_CLASS_HANDLE clsHnd);
3832
3833     // Get the type that is used to pass values of the given struct type.
3834     // If you have already retrieved the struct size then pass it as the optional third argument
3835     //
3836     var_types getArgTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
3837                                   structPassingKind*   wbPassStruct,
3838                                   unsigned             structSize = 0);
3839
3840     // Get the type that is used to return values of the given struct type.
3841     // If you have already retrieved the struct size then pass it as the optional third argument
3842     //
3843     var_types getReturnTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
3844                                      structPassingKind*   wbPassStruct = nullptr,
3845                                      unsigned             structSize = 0);
3846
3847 #ifdef DEBUG
3848     // Print a representation of "vnp" or "vn" on standard output.
3849     // If "level" is non-zero, we also print out a partial expansion of the value.
3850     void vnpPrint(ValueNumPair vnp, unsigned level);
3851     void vnPrint(ValueNum vn, unsigned level);
3852 #endif
3853
3854     // Dominator computation member functions
3855     // Not exposed outside Compiler
3856 protected:
3857     bool fgDominate(BasicBlock* b1, BasicBlock* b2); // Return true if b1 dominates b2
3858
3859     bool fgReachable(BasicBlock* b1, BasicBlock* b2); // Returns true if block b1 can reach block b2
3860
3861     void fgComputeDoms(); // Computes the immediate dominators for each basic block in the
3862                           // flow graph.  We first assume the fields bbIDom on each
3863                           // basic block are invalid. This computation is needed later
3864                           // by fgBuildDomTree to build the dominance tree structure.
3865                           // Based on: A Simple, Fast Dominance Algorithm
3866                           // by Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy
3867
3868     BlockSet_ValRet_T fgGetDominatorSet(BasicBlock* block); // Returns a set of blocks that dominate the given block.
3869     // Note: this is relatively slow compared to calling fgDominate(),
3870     // especially if dealing with a single block versus block check.
3871
3872     void fgComputeReachabilitySets(); // Compute bbReach sets. (Also sets BBF_GC_SAFE_POINT flag on blocks.)
3873
3874     void fgComputeEnterBlocksSet(); // Compute the set of entry blocks, 'fgEnterBlks'.
3875
3876     bool fgRemoveUnreachableBlocks(); // Remove blocks determined to be unreachable by the bbReach sets.
3877
3878     void fgComputeReachability(); // Perform flow graph node reachability analysis.
3879
3880     BasicBlock* fgIntersectDom(BasicBlock* a, BasicBlock* b); // Intersect two immediate dominator sets.
3881
3882     void fgDfsInvPostOrder(); // In order to compute dominance using fgIntersectDom, the flow graph nodes must be
3883                               // processed in topological sort, this function takes care of that.
3884
3885     void fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count);
3886
3887     BlockSet_ValRet_T fgDomFindStartNodes(); // Computes which basic blocks don't have incoming edges in the flow graph.
3888                                              // Returns this as a set.
3889
3890     BlockSet_ValRet_T fgDomTreeEntryNodes(BasicBlockList** domTree); // Computes which nodes in the dominance forest are
3891                                                                      // root nodes. Returns this as a set.
3892
3893 #ifdef DEBUG
3894     void fgDispDomTree(BasicBlockList** domTree); // Helper that prints out the Dominator Tree in debug builds.
3895 #endif                                            // DEBUG
3896
3897     void fgBuildDomTree(); // Once we compute all the immediate dominator sets for each node in the flow graph
3898                            // (performed by fgComputeDoms), this procedure builds the dominance tree represented
3899                            // adjacency lists.
3900
3901     // In order to speed up the queries of the form 'Does A dominates B', we can perform a DFS preorder and postorder
3902     // traversal of the dominance tree and the dominance query will become A dominates B iif preOrder(A) <= preOrder(B)
3903     // && postOrder(A) >= postOrder(B) making the computation O(1).
3904     void fgTraverseDomTree(unsigned bbNum, BasicBlockList** domTree, unsigned* preNum, unsigned* postNum);
3905
3906     // When the flow graph changes, we need to update the block numbers, predecessor lists, reachability sets, and
3907     // dominators.
3908     void fgUpdateChangedFlowGraph();
3909
3910 public:
3911     // Compute the predecessors of the blocks in the control flow graph.
3912     void fgComputePreds();
3913
3914     // Remove all predecessor information.
3915     void fgRemovePreds();
3916
3917     // Compute the cheap flow graph predecessors lists. This is used in some early phases
3918     // before the full predecessors lists are computed.
3919     void fgComputeCheapPreds();
3920
3921 private:
3922     void fgAddCheapPred(BasicBlock* block, BasicBlock* blockPred);
3923
3924     void fgRemoveCheapPred(BasicBlock* block, BasicBlock* blockPred);
3925
3926 public:
3927     enum GCPollType
3928     {
3929         GCPOLL_NONE,
3930         GCPOLL_CALL,
3931         GCPOLL_INLINE
3932     };
3933
3934     // Initialize the per-block variable sets (used for liveness analysis).
3935     void fgInitBlockVarSets();
3936
3937     // true if we've gone through and created GC Poll calls.
3938     bool fgGCPollsCreated;
3939     void fgMarkGCPollBlocks();
3940     void fgCreateGCPolls();
3941     bool fgCreateGCPoll(GCPollType pollType, BasicBlock* block);
3942
3943     // Requires that "block" is a block that returns from
3944     // a finally.  Returns the number of successors (jump targets of
3945     // of blocks in the covered "try" that did a "LEAVE".)
3946     unsigned fgNSuccsOfFinallyRet(BasicBlock* block);
3947
3948     // Requires that "block" is a block that returns (in the sense of BBJ_EHFINALLYRET) from
3949     // a finally.  Returns its "i"th successor (jump targets of
3950     // of blocks in the covered "try" that did a "LEAVE".)
3951     // Requires that "i" < fgNSuccsOfFinallyRet(block).
3952     BasicBlock* fgSuccOfFinallyRet(BasicBlock* block, unsigned i);
3953
3954 private:
3955     // Factor out common portions of the impls of the methods above.
3956     void fgSuccOfFinallyRetWork(BasicBlock* block, unsigned i, BasicBlock** bres, unsigned* nres);
3957
3958 public:
3959     // For many purposes, it is desirable to be able to enumerate the *distinct* targets of a switch statement,
3960     // skipping duplicate targets.  (E.g., in flow analyses that are only interested in the set of possible targets.)
3961     // SwitchUniqueSuccSet contains the non-duplicated switch targets.
3962     // (Code that modifies the jump table of a switch has an obligation to call Compiler::UpdateSwitchTableTarget,
3963     // which in turn will call the "UpdateTarget" method of this type if a SwitchUniqueSuccSet has already
3964     // been computed for the switch block.  If a switch block is deleted or is transformed into a non-switch,
3965     // we leave the entry associated with the block, but it will no longer be accessed.)
3966     struct SwitchUniqueSuccSet
3967     {
3968         unsigned     numDistinctSuccs; // Number of distinct targets of the switch.
3969         BasicBlock** nonDuplicates;    // Array of "numDistinctSuccs", containing all the distinct switch target
3970                                        // successors.
3971
3972         // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
3973         // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
3974         // remove it from "this", and ensure that "to" is a member.  Use "alloc" to do any required allocation.
3975         void UpdateTarget(IAllocator* alloc, BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
3976     };
3977
3978     typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, SwitchUniqueSuccSet, JitSimplerHashBehavior>
3979         BlockToSwitchDescMap;
3980
3981 private:
3982     // Maps BasicBlock*'s that end in switch statements to SwitchUniqueSuccSets that allow
3983     // iteration over only the distinct successors.
3984     BlockToSwitchDescMap* m_switchDescMap;
3985
3986 public:
3987     BlockToSwitchDescMap* GetSwitchDescMap()
3988     {
3989         if (m_switchDescMap == nullptr)
3990         {
3991             m_switchDescMap = new (getAllocator()) BlockToSwitchDescMap(getAllocator());
3992         }
3993         return m_switchDescMap;
3994     }
3995
3996     // Invalidate the map of unique switch block successors. For example, since the hash key of the map
3997     // depends on block numbers, we must invalidate the map when the blocks are renumbered, to ensure that
3998     // we don't accidentally look up and return the wrong switch data.
3999     void InvalidateUniqueSwitchSuccMap()
4000     {
4001         m_switchDescMap = nullptr;
4002     }
4003
4004     // Requires "switchBlock" to be a block that ends in a switch.  Returns
4005     // the corresponding SwitchUniqueSuccSet.
4006     SwitchUniqueSuccSet GetDescriptorForSwitch(BasicBlock* switchBlk);
4007
4008     // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
4009     // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
4010     // remove it from "this", and ensure that "to" is a member.
4011     void UpdateSwitchTableTarget(BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
4012
4013     // Remove the "SwitchUniqueSuccSet" of "switchBlk" in the BlockToSwitchDescMap.
4014     void fgInvalidateSwitchDescMapEntry(BasicBlock* switchBlk);
4015
4016     BasicBlock* fgFirstBlockOfHandler(BasicBlock* block);
4017
4018     flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred);
4019
4020     flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred, flowList*** ptrToPred);
4021
4022     flowList* fgSpliceOutPred(BasicBlock* block, BasicBlock* blockPred);
4023
4024     flowList* fgRemoveRefPred(BasicBlock* block, BasicBlock* blockPred);
4025
4026     flowList* fgRemoveAllRefPreds(BasicBlock* block, BasicBlock* blockPred);
4027
4028     flowList* fgRemoveAllRefPreds(BasicBlock* block, flowList** ptrToPred);
4029
4030     void fgRemoveBlockAsPred(BasicBlock* block);
4031
4032     void fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock);
4033
4034     void fgReplaceSwitchJumpTarget(BasicBlock* blockSwitch, BasicBlock* newTarget, BasicBlock* oldTarget);
4035
4036     void fgReplaceJumpTarget(BasicBlock* block, BasicBlock* newTarget, BasicBlock* oldTarget);
4037
4038     void fgReplacePred(BasicBlock* block, BasicBlock* oldPred, BasicBlock* newPred);
4039
4040     flowList* fgAddRefPred(BasicBlock* block,
4041                            BasicBlock* blockPred,
4042                            flowList*   oldEdge           = nullptr,
4043                            bool        initializingPreds = false); // Only set to 'true' when we are computing preds in
4044                                                                    // fgComputePreds()
4045
4046     void fgFindBasicBlocks();
4047
4048     bool fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt);
4049
4050     bool fgCheckEHCanInsertAfterBlock(BasicBlock* blk, unsigned regionIndex, bool putInTryRegion);
4051
4052     BasicBlock* fgFindInsertPoint(unsigned    regionIndex,
4053                                   bool        putInTryRegion,
4054                                   BasicBlock* startBlk,
4055                                   BasicBlock* endBlk,
4056                                   BasicBlock* nearBlk,
4057                                   BasicBlock* jumpBlk,
4058                                   bool        runRarely);
4059
4060     unsigned fgGetNestingLevel(BasicBlock* block, unsigned* pFinallyNesting = nullptr);
4061
4062     void fgRemoveEmptyBlocks();
4063
4064     void fgRemoveStmt(BasicBlock* block, GenTreePtr stmt, bool updateRefCnt = true);
4065
4066     bool fgCheckRemoveStmt(BasicBlock* block, GenTreePtr stmt);
4067
4068     void fgCreateLoopPreHeader(unsigned lnum);
4069
4070     void fgUnreachableBlock(BasicBlock* block);
4071
4072     void fgRemoveJTrue(BasicBlock* block);
4073
4074     BasicBlock* fgLastBBInMainFunction();
4075
4076     BasicBlock* fgEndBBAfterMainFunction();
4077
4078     void fgUnlinkRange(BasicBlock* bBeg, BasicBlock* bEnd);
4079
4080     void fgRemoveBlock(BasicBlock* block, bool unreachable);
4081
4082     bool fgCanCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4083
4084     void fgCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4085
4086     void fgUpdateLoopsAfterCompacting(BasicBlock* block, BasicBlock* bNext);
4087
4088     BasicBlock* fgConnectFallThrough(BasicBlock* bSrc, BasicBlock* bDst);
4089
4090     bool fgRenumberBlocks();
4091
4092     bool fgExpandRarelyRunBlocks();
4093
4094     bool fgEhAllowsMoveBlock(BasicBlock* bBefore, BasicBlock* bAfter);
4095
4096     void fgMoveBlocksAfter(BasicBlock* bStart, BasicBlock* bEnd, BasicBlock* insertAfterBlk);
4097
4098     enum FG_RELOCATE_TYPE
4099     {
4100         FG_RELOCATE_TRY,    // relocate the 'try' region
4101         FG_RELOCATE_HANDLER // relocate the handler region (including the filter if necessary)
4102     };
4103     BasicBlock* fgRelocateEHRange(unsigned regionIndex, FG_RELOCATE_TYPE relocateType);
4104
4105 #if FEATURE_EH_FUNCLETS
4106 #if defined(_TARGET_ARM_)
4107     void fgClearFinallyTargetBit(BasicBlock* block);
4108 #endif // defined(_TARGET_ARM_)
4109     bool fgIsIntraHandlerPred(BasicBlock* predBlock, BasicBlock* block);
4110     bool fgAnyIntraHandlerPreds(BasicBlock* block);
4111     void fgInsertFuncletPrologBlock(BasicBlock* block);
4112     void fgCreateFuncletPrologBlocks();
4113     void fgCreateFunclets();
4114 #else  // !FEATURE_EH_FUNCLETS
4115     bool fgRelocateEHRegions();
4116 #endif // !FEATURE_EH_FUNCLETS
4117
4118     bool fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* target);
4119
4120     bool fgBlockEndFavorsTailDuplication(BasicBlock* block);
4121
4122     bool fgBlockIsGoodTailDuplicationCandidate(BasicBlock* block);
4123
4124     bool fgOptimizeFallthroughTailDup(BasicBlock* block, BasicBlock* target);
4125
4126     bool fgOptimizeEmptyBlock(BasicBlock* block);
4127
4128     bool fgOptimizeBranchToEmptyUnconditional(BasicBlock* block, BasicBlock* bDest);
4129
4130     bool fgOptimizeBranch(BasicBlock* bJump);
4131
4132     bool fgOptimizeSwitchBranches(BasicBlock* block);
4133
4134     bool fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev);
4135
4136     bool fgOptimizeSwitchJumps();
4137 #ifdef DEBUG
4138     void fgPrintEdgeWeights();
4139 #endif
4140     void fgComputeEdgeWeights();
4141
4142     void fgReorderBlocks();
4143
4144     void fgDetermineFirstColdBlock();
4145
4146     bool fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc = nullptr);
4147
4148     bool fgUpdateFlowGraph(bool doTailDup = false);
4149
4150     void fgFindOperOrder();
4151
4152     // method that returns if you should split here
4153     typedef bool(fgSplitPredicate)(GenTree* tree, GenTree* parent, fgWalkData* data);
4154
4155     void fgSetBlockOrder();
4156
4157     void fgRemoveReturnBlock(BasicBlock* block);
4158
4159     /* Helper code that has been factored out */
4160     inline void fgConvertBBToThrowBB(BasicBlock* block);
4161
4162     bool fgCastNeeded(GenTreePtr tree, var_types toType);
4163     GenTreePtr fgDoNormalizeOnStore(GenTreePtr tree);
4164     GenTreePtr fgMakeTmpArgNode(
4165         unsigned tmpVarNum FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool passedInRegisters));
4166
4167     // The following check for loops that don't execute calls
4168     bool fgLoopCallMarked;
4169
4170     void fgLoopCallTest(BasicBlock* srcBB, BasicBlock* dstBB);
4171     void fgLoopCallMark();
4172
4173     void fgMarkLoopHead(BasicBlock* block);
4174
4175     unsigned fgGetCodeEstimate(BasicBlock* block);
4176
4177 #if DUMP_FLOWGRAPHS
4178     const char* fgProcessEscapes(const char* nameIn, escapeMapping_t* map);
4179     FILE* fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type);
4180     bool fgDumpFlowGraph(Phases phase);
4181
4182 #endif // DUMP_FLOWGRAPHS
4183
4184 #ifdef DEBUG
4185     void fgDispDoms();
4186     void fgDispReach();
4187     void fgDispBBLiveness(BasicBlock* block);
4188     void fgDispBBLiveness();
4189     void fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth = 0);
4190     void fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees);
4191     void fgDispBasicBlocks(bool dumpTrees = false);
4192     void fgDumpStmtTree(GenTreePtr stmt, unsigned blkNum);
4193     void fgDumpBlock(BasicBlock* block);
4194     void fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock);
4195
4196     static fgWalkPreFn fgStress64RsltMulCB;
4197     void               fgStress64RsltMul();
4198     void               fgDebugCheckUpdate();
4199     void fgDebugCheckBBlist(bool checkBBNum = false, bool checkBBRefs = true);
4200     void fgDebugCheckBlockLinks();
4201     void fgDebugCheckLinks(bool morphTrees = false);
4202     void fgDebugCheckNodeLinks(BasicBlock* block, GenTreePtr stmt);
4203     void fgDebugCheckFlags(GenTreePtr tree);
4204     void fgDebugCheckFlagsHelper(GenTreePtr tree, unsigned treeFlags, unsigned chkFlags);
4205 #endif
4206
4207 #ifdef LEGACY_BACKEND
4208     static void fgOrderBlockOps(GenTreePtr  tree,
4209                                 regMaskTP   reg0,
4210                                 regMaskTP   reg1,
4211                                 regMaskTP   reg2,
4212                                 GenTreePtr* opsPtr,   // OUT
4213                                 regMaskTP*  regsPtr); // OUT
4214 #endif                                                // LEGACY_BACKEND
4215
4216     static GenTreePtr fgGetFirstNode(GenTreePtr tree);
4217     static bool fgTreeIsInStmt(GenTree* tree, GenTreeStmt* stmt);
4218
4219     inline bool fgIsInlining()
4220     {
4221         return fgExpandInline;
4222     }
4223
4224     void fgTraverseRPO();
4225
4226     //--------------------- Walking the trees in the IR -----------------------
4227
4228     struct fgWalkData
4229     {
4230         Compiler*     compiler;
4231         fgWalkPreFn*  wtprVisitorFn;
4232         fgWalkPostFn* wtpoVisitorFn;
4233         void*         pCallbackData; // user-provided data
4234         bool          wtprLclsOnly;  // whether to only visit lclvar nodes
4235         GenTreePtr    parent;        // parent of current node, provided to callback
4236         GenTreeStack* parentStack;   // stack of parent nodes, if asked for
4237 #ifdef DEBUG
4238         bool printModified; // callback can use this
4239 #endif
4240     };
4241
4242     template <bool      computeStack>
4243     static fgWalkResult fgWalkTreePreRec(GenTreePtr* pTree, fgWalkData* fgWalkPre);
4244
4245     // general purpose tree-walker that is capable of doing pre- and post- order
4246     // callbacks at the same time
4247     template <bool doPreOrder, bool doPostOrder>
4248     static fgWalkResult fgWalkTreeRec(GenTreePtr* pTree, fgWalkData* fgWalkPre);
4249
4250     fgWalkResult fgWalkTreePre(GenTreePtr*  pTree,
4251                                fgWalkPreFn* visitor,
4252                                void*        pCallBackData = nullptr,
4253                                bool         lclVarsOnly   = false,
4254                                bool         computeStack  = false);
4255
4256     fgWalkResult fgWalkTree(GenTreePtr*   pTree,
4257                             fgWalkPreFn*  preVisitor,
4258                             fgWalkPostFn* postVisitor,
4259                             void*         pCallBackData = nullptr);
4260
4261     void fgWalkAllTreesPre(fgWalkPreFn* visitor, void* pCallBackData);
4262
4263     //----- Postorder
4264
4265     template <bool      computeStack>
4266     static fgWalkResult fgWalkTreePostRec(GenTreePtr* pTree, fgWalkData* fgWalkPre);
4267
4268     fgWalkResult fgWalkTreePost(GenTreePtr*   pTree,
4269                                 fgWalkPostFn* visitor,
4270                                 void*         pCallBackData = nullptr,
4271                                 bool          computeStack  = false);
4272
4273     // An fgWalkPreFn that looks for expressions that have inline throws in
4274     // minopts mode. Basically it looks for tress with gtOverflowEx() or
4275     // GTF_IND_RNGCHK.  It returns WALK_ABORT if one is found.  It
4276     // returns WALK_SKIP_SUBTREES if GTF_EXCEPT is not set (assumes flags
4277     // properly propagated to parent trees).  It returns WALK_CONTINUE
4278     // otherwise.
4279     static fgWalkResult fgChkThrowCB(GenTreePtr* pTree, Compiler::fgWalkData* data);
4280     static fgWalkResult fgChkLocAllocCB(GenTreePtr* pTree, Compiler::fgWalkData* data);
4281     static fgWalkResult fgChkQmarkCB(GenTreePtr* pTree, Compiler::fgWalkData* data);
4282
4283     /**************************************************************************
4284      *                          PROTECTED
4285      *************************************************************************/
4286
4287 protected:
4288     friend class SsaBuilder;
4289     friend struct ValueNumberState;
4290
4291     //--------------------- Detect the basic blocks ---------------------------
4292
4293     BasicBlock** fgBBs; // Table of pointers to the BBs
4294
4295     void        fgInitBBLookup();
4296     BasicBlock* fgLookupBB(unsigned addr);
4297
4298     void fgMarkJumpTarget(BYTE* jumpTarget, IL_OFFSET offs);
4299
4300     void fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, BYTE* jumpTarget);
4301
4302     void fgMarkBackwardJump(BasicBlock* startBlock, BasicBlock* endBlock);
4303
4304     void fgLinkBasicBlocks();
4305
4306     void fgMakeBasicBlocks(const BYTE* codeAddr, IL_OFFSET codeSize, BYTE* jumpTarget);
4307
4308     void fgCheckBasicBlockControlFlow();
4309
4310     void fgControlFlowPermitted(BasicBlock* blkSrc,
4311                                 BasicBlock* blkDest,
4312                                 BOOL        IsLeave = false /* is the src a leave block */);
4313
4314     bool fgFlowToFirstBlockOfInnerTry(BasicBlock* blkSrc, BasicBlock* blkDest, bool sibling);
4315
4316     void fgObserveInlineConstants(OPCODE opcode, const FgStack& stack, bool isInlining);
4317
4318     void fgAdjustForAddressExposedOrWrittenThis();
4319
4320     bool                        fgProfileData_ILSizeMismatch;
4321     ICorJitInfo::ProfileBuffer* fgProfileBuffer;
4322     ULONG                       fgProfileBufferCount;
4323     ULONG                       fgNumProfileRuns;
4324
4325     unsigned fgStressBBProf()
4326     {
4327 #ifdef DEBUG
4328         unsigned result = JitConfig.JitStressBBProf();
4329         if (result == 0)
4330         {
4331             if (compStressCompile(STRESS_BB_PROFILE, 15))
4332             {
4333                 result = 1;
4334             }
4335         }
4336         return result;
4337 #else
4338         return 0;
4339 #endif
4340     }
4341
4342     bool fgHaveProfileData();
4343     bool fgGetProfileWeightForBasicBlock(IL_OFFSET offset, unsigned* weight);
4344
4345     bool fgIsUsingProfileWeights()
4346     {
4347         return (fgHaveProfileData() || fgStressBBProf());
4348     }
4349     void fgInstrumentMethod();
4350
4351 //-------- Insert a statement at the start or end of a basic block --------
4352
4353 #ifdef DEBUG
4354 public:
4355     static bool fgBlockContainsStatementBounded(BasicBlock* block, GenTree* stmt, bool answerOnBoundExceeded = true);
4356 #endif
4357
4358 public:
4359     GenTreeStmt* fgInsertStmtAtEnd(BasicBlock* block, GenTreePtr node);
4360
4361 public: // Used by linear scan register allocation
4362     GenTreeStmt* fgInsertStmtNearEnd(BasicBlock* block, GenTreePtr node);
4363
4364 private:
4365     GenTreePtr fgInsertStmtAtBeg(BasicBlock* block, GenTreePtr stmt);
4366     GenTreePtr fgInsertStmtAfter(BasicBlock* block, GenTreePtr insertionPoint, GenTreePtr stmt);
4367
4368 public: // Used by linear scan register allocation
4369     GenTreePtr fgInsertStmtBefore(BasicBlock* block, GenTreePtr insertionPoint, GenTreePtr stmt);
4370
4371 private:
4372     GenTreePtr fgInsertStmtListAfter(BasicBlock* block, GenTreePtr stmtAfter, GenTreePtr stmtList);
4373
4374     GenTreePtr fgMorphSplitTree(GenTree** splitPoint, GenTree* stmt, BasicBlock* blk);
4375
4376     //                  Create a new temporary variable to hold the result of *ppTree,
4377     //                  and transform the graph accordingly.
4378     GenTree* fgInsertCommaFormTemp(GenTree** ppTree, CORINFO_CLASS_HANDLE structType = nullptr);
4379     GenTree* fgMakeMultiUse(GenTree** ppTree);
4380
4381     //                  After replacing oldChild with newChild, fixup the fgArgTabEntryPtr
4382     //                  if it happens to be an argument to a call.
4383     void fgFixupIfCallArg(ArrayStack<GenTree*>* parentStack, GenTree* oldChild, GenTree* newChild);
4384
4385 public:
4386     void fgFixupArgTabEntryPtr(GenTreePtr parentCall, GenTreePtr oldArg, GenTreePtr newArg);
4387
4388 private:
4389     //                  Recognize a bitwise rotation pattern and convert into a GT_ROL or a GT_ROR node.
4390     GenTreePtr fgRecognizeAndMorphBitwiseRotation(GenTreePtr tree);
4391     bool fgOperIsBitwiseRotationRoot(genTreeOps oper);
4392
4393     //-------- Determine the order in which the trees will be evaluated -------
4394
4395     unsigned fgTreeSeqNum;
4396     GenTree* fgTreeSeqLst;
4397     GenTree* fgTreeSeqBeg;
4398
4399     GenTree* fgSetTreeSeq(GenTree* tree, GenTree* prev = nullptr, bool isLIR = false);
4400     void fgSetTreeSeqHelper(GenTree* tree, bool isLIR);
4401     void fgSetTreeSeqFinish(GenTreePtr tree, bool isLIR);
4402     void fgSetStmtSeq(GenTree* tree);
4403     void fgSetBlockOrder(BasicBlock* block);
4404
4405     //------------------------- Morphing --------------------------------------
4406
4407     unsigned fgPtrArgCntCur;
4408     unsigned fgPtrArgCntMax;
4409     hashBv*  fgOutgoingArgTemps;
4410     hashBv*  fgCurrentlyInUseArgTemps;
4411
4412     bool compCanEncodePtrArgCntMax();
4413
4414     void fgSetRngChkTarget(GenTreePtr tree, bool delay = true);
4415
4416 #if REARRANGE_ADDS
4417     void fgMoveOpsLeft(GenTreePtr tree);
4418 #endif
4419
4420     bool fgIsCommaThrow(GenTreePtr tree, bool forFolding = false);
4421
4422     bool fgIsThrow(GenTreePtr tree);
4423
4424     bool fgInDifferentRegions(BasicBlock* blk1, BasicBlock* blk2);
4425     bool fgIsBlockCold(BasicBlock* block);
4426
4427     GenTreePtr fgMorphCastIntoHelper(GenTreePtr tree, int helper, GenTreePtr oper);
4428
4429     GenTreePtr fgMorphIntoHelperCall(GenTreePtr tree, int helper, GenTreeArgList* args);
4430
4431     GenTreePtr fgMorphStackArgForVarArgs(unsigned lclNum, var_types varType, unsigned lclOffs);
4432
4433     bool fgMorphRelopToQmark(GenTreePtr tree);
4434
4435     // A "MorphAddrContext" carries information from the surrounding context.  If we are evaluating a byref address,
4436     // it is useful to know whether the address will be immediately dereferenced, or whether the address value will
4437     // be used, perhaps by passing it as an argument to a called method.  This affects how null checking is done:
4438     // for sufficiently small offsets, we can rely on OS page protection to implicitly null-check addresses that we
4439     // know will be dereferenced.  To know that reliance on implicit null checking is sound, we must further know that
4440     // all offsets between the top-level indirection and the bottom are constant, and that their sum is sufficiently
4441     // small; hence the other fields of MorphAddrContext.  Finally, the odd structure of GT_COPYBLK, in which the second
4442     // argument is a GT_LIST, requires us to "tell" that List node that its parent is a GT_COPYBLK, so it "knows" that
4443     // each of its arguments should be evaluated in MACK_Ind contexts.  (This would not be true for GT_LIST nodes
4444     // representing method call argument lists.)
4445     enum MorphAddrContextKind
4446     {
4447         MACK_Ind,
4448         MACK_Addr,
4449         MACK_CopyBlock, // This is necessary so we know we have to start a new "Ind" context for each of the
4450                         // addresses in the arg list.
4451     };
4452     struct MorphAddrContext
4453     {
4454         MorphAddrContextKind m_kind;
4455         bool                 m_allConstantOffsets; // Valid only for "m_kind == MACK_Ind".  True iff all offsets between
4456                                                    // top-level indirection and here have been constants.
4457         size_t m_totalOffset; // Valid only for "m_kind == MACK_Ind", and if "m_allConstantOffsets" is true.
4458                               // In that case, is the sum of those constant offsets.
4459
4460         MorphAddrContext(MorphAddrContextKind kind) : m_kind(kind), m_allConstantOffsets(true), m_totalOffset(0)
4461         {
4462         }
4463     };
4464
4465     // A MACK_CopyBlock context is immutable, so we can just make one of these and share it.
4466     static MorphAddrContext s_CopyBlockMAC;
4467
4468 #ifdef FEATURE_SIMD
4469     GenTreePtr fgCopySIMDNode(GenTreeSIMD* simdNode);
4470     GenTreePtr getSIMDStructFromField(GenTreePtr tree,
4471                                       var_types* baseTypeOut,
4472                                       unsigned*  indexOut,
4473                                       unsigned*  simdSizeOut,
4474                                       bool       ignoreUsedInSIMDIntrinsic = false);
4475     GenTreePtr fgMorphFieldAssignToSIMDIntrinsicSet(GenTreePtr tree);
4476     GenTreePtr fgMorphFieldToSIMDIntrinsicGet(GenTreePtr tree);
4477     bool fgMorphCombineSIMDFieldAssignments(BasicBlock* block, GenTreePtr stmt);
4478     void impMarkContiguousSIMDFieldAssignments(GenTreePtr stmt);
4479
4480     // fgPreviousCandidateSIMDFieldAsgStmt is only used for tracking previous simd field assignment
4481     // in function: Complier::impMarkContiguousSIMDFieldAssignments.
4482     GenTreePtr fgPreviousCandidateSIMDFieldAsgStmt;
4483
4484 #endif // FEATURE_SIMD
4485     GenTreePtr fgMorphArrayIndex(GenTreePtr tree);
4486     GenTreePtr fgMorphCast(GenTreePtr tree);
4487     GenTreePtr fgUnwrapProxy(GenTreePtr objRef);
4488     GenTreeCall* fgMorphArgs(GenTreeCall* call);
4489
4490     void fgMakeOutgoingStructArgCopy(GenTreeCall*         call,
4491                                      GenTree*             args,
4492                                      unsigned             argIndex,
4493                                      CORINFO_CLASS_HANDLE copyBlkClass FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(
4494                                          const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structDescPtr));
4495
4496     void fgFixupStructReturn(GenTreePtr call);
4497     GenTreePtr fgMorphLocalVar(GenTreePtr tree);
4498     bool fgAddrCouldBeNull(GenTreePtr addr);
4499     GenTreePtr fgMorphField(GenTreePtr tree, MorphAddrContext* mac);
4500     bool fgCanFastTailCall(GenTreeCall* call);
4501     void fgMorphTailCall(GenTreeCall* call);
4502     void fgMorphRecursiveFastTailCallIntoLoop(BasicBlock* block, GenTreeCall* recursiveTailCall);
4503     GenTreePtr fgAssignRecursiveCallArgToCallerParam(GenTreePtr       arg,
4504                                                      fgArgTabEntryPtr argTabEntry,
4505                                                      BasicBlock*      block,
4506                                                      IL_OFFSETX       callILOffset,
4507                                                      GenTreePtr       tmpAssignmentInsertionPoint,
4508                                                      GenTreePtr       paramAssignmentInsertionPoint);
4509     static int fgEstimateCallStackSize(GenTreeCall* call);
4510     GenTreePtr fgMorphCall(GenTreeCall* call);
4511     void fgMorphCallInline(GenTreeCall* call, InlineResult* result);
4512     void fgMorphCallInlineHelper(GenTreeCall* call, InlineResult* result);
4513 #if DEBUG
4514     void fgNoteNonInlineCandidate(GenTreePtr tree, GenTreeCall* call);
4515     static fgWalkPreFn fgFindNonInlineCandidate;
4516 #endif
4517     GenTreePtr fgOptimizeDelegateConstructor(GenTreePtr call, CORINFO_CONTEXT_HANDLE* ExactContextHnd);
4518     GenTreePtr fgMorphLeaf(GenTreePtr tree);
4519     void fgAssignSetVarDef(GenTreePtr tree);
4520     GenTreePtr fgMorphOneAsgBlockOp(GenTreePtr tree);
4521     GenTreePtr fgMorphInitBlock(GenTreePtr tree);
4522     GenTreePtr fgMorphCopyBlock(GenTreePtr tree);
4523     GenTreePtr fgMorphForRegisterFP(GenTreePtr tree);
4524     GenTreePtr fgMorphSmpOp(GenTreePtr tree, MorphAddrContext* mac = nullptr);
4525     GenTreePtr fgMorphSmpOpPre(GenTreePtr tree);
4526     GenTreePtr fgMorphDivByConst(GenTreeOp* tree);
4527     GenTreePtr fgMorphModByConst(GenTreeOp* tree);
4528     GenTreePtr fgMorphModToSubMulDiv(GenTreeOp* tree);
4529     GenTreePtr fgMorphSmpOpOptional(GenTreeOp* tree);
4530     GenTreePtr fgMorphRecognizeBoxNullable(GenTree* compare);
4531     bool fgShouldUseMagicNumberDivide(GenTreeOp* tree);
4532
4533     GenTreePtr fgMorphToEmulatedFP(GenTreePtr tree);
4534     GenTreePtr fgMorphConst(GenTreePtr tree);
4535
4536 public:
4537     GenTreePtr fgMorphTree(GenTreePtr tree, MorphAddrContext* mac = nullptr);
4538
4539 private:
4540 #if LOCAL_ASSERTION_PROP
4541     void fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTreePtr tree));
4542 #endif
4543     void fgMorphTreeDone(GenTreePtr tree, GenTreePtr oldTree = nullptr DEBUGARG(int morphNum = 0));
4544
4545     GenTreePtr fgMorphStmt;
4546
4547     unsigned fgGetBigOffsetMorphingTemp(var_types type); // We cache one temp per type to be
4548                                                          // used when morphing big offset.
4549
4550     //----------------------- Liveness analysis -------------------------------
4551
4552     VARSET_TP fgCurUseSet; // vars used     by block (before an assignment)
4553     VARSET_TP fgCurDefSet; // vars assigned by block (before a use)
4554
4555     bool fgCurHeapUse;   // True iff the current basic block uses the heap before defining it.
4556     bool fgCurHeapDef;   // True iff the current basic block defines the heap.
4557     bool fgCurHeapHavoc; // True if  the current basic block is known to set the heap to a "havoc" value.
4558
4559     void fgMarkUseDef(GenTreeLclVarCommon* tree, GenTree* asgdLclVar = nullptr);
4560
4561 #ifdef DEBUGGING_SUPPORT
4562     void fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
4563     void fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
4564
4565     void fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope);
4566     void fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope);
4567
4568     void fgExtendDbgScopes();
4569     void fgExtendDbgLifetimes();
4570
4571 #ifdef DEBUG
4572     void fgDispDebugScopes();
4573 #endif // DEBUG
4574
4575 #endif // DEBUGGING_SUPPORT
4576
4577     //-------------------------------------------------------------------------
4578     //
4579     //  The following keeps track of any code we've added for things like array
4580     //  range checking or explicit calls to enable GC, and so on.
4581     //
4582 public:
4583     struct AddCodeDsc
4584     {
4585         AddCodeDsc*     acdNext;
4586         BasicBlock*     acdDstBlk; // block  to  which we jump
4587         unsigned        acdData;
4588         SpecialCodeKind acdKind; // what kind of a special block is this?
4589         unsigned short  acdStkLvl;
4590     };
4591
4592 private:
4593     static unsigned acdHelper(SpecialCodeKind codeKind);
4594
4595     AddCodeDsc* fgAddCodeList;
4596     bool        fgAddCodeModf;
4597     bool        fgRngChkThrowAdded;
4598     AddCodeDsc* fgExcptnTargetCache[SCK_COUNT];
4599
4600     BasicBlock* fgRngChkTarget(BasicBlock* block, unsigned stkDepth, SpecialCodeKind kind);
4601
4602     BasicBlock* fgAddCodeRef(BasicBlock* srcBlk, unsigned refData, SpecialCodeKind kind, unsigned stkDepth = 0);
4603
4604 public:
4605     AddCodeDsc* fgFindExcptnTarget(SpecialCodeKind kind, unsigned refData);
4606
4607 private:
4608     bool fgIsCodeAdded();
4609
4610     bool fgIsThrowHlpBlk(BasicBlock* block);
4611     unsigned fgThrowHlpBlkStkLevel(BasicBlock* block);
4612
4613     unsigned fgBigOffsetMorphingTemps[TYP_COUNT];
4614
4615     unsigned fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo);
4616     void fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* result);
4617     void fgInsertInlineeBlocks(InlineInfo* pInlineInfo);
4618     GenTreePtr fgInlinePrependStatements(InlineInfo* inlineInfo);
4619
4620 #if FEATURE_MULTIREG_RET
4621     GenTreePtr fgGetStructAsStructPtr(GenTreePtr tree);
4622     GenTreePtr fgAssignStructInlineeToVar(GenTreePtr child, CORINFO_CLASS_HANDLE retClsHnd);
4623     void fgAttachStructInlineeToAsg(GenTreePtr tree, GenTreePtr child, CORINFO_CLASS_HANDLE retClsHnd);
4624 #endif // FEATURE_MULTIREG_RET
4625
4626     static fgWalkPreFn fgUpdateInlineReturnExpressionPlaceHolder;
4627
4628 #ifdef DEBUG
4629     static fgWalkPreFn fgDebugCheckInlineCandidates;
4630 #endif
4631
4632     void         fgPromoteStructs();
4633     fgWalkResult fgMorphStructField(GenTreePtr tree, fgWalkData* fgWalkPre);
4634     fgWalkResult fgMorphLocalField(GenTreePtr tree, fgWalkData* fgWalkPre);
4635     void fgMarkImplicitByRefArgs();
4636     bool fgMorphImplicitByRefArgs(GenTree** pTree, fgWalkData* fgWalkPre);
4637     static fgWalkPreFn  fgMarkAddrTakenLocalsPreCB;
4638     static fgWalkPostFn fgMarkAddrTakenLocalsPostCB;
4639     void                fgMarkAddressExposedLocals();
4640     bool fgNodesMayInterfere(GenTree* store, GenTree* load);
4641
4642     // Returns true if the type of tree is of size at least "width", or if "tree" is not a
4643     // local variable.
4644     bool fgFitsInOrNotLoc(GenTreePtr tree, unsigned width);
4645
4646     // The given local variable, required to be a struct variable, is being assigned via
4647     // a "lclField", to make it masquerade as an integral type in the ABI.  Make sure that
4648     // the variable is not enregistered, and is therefore not promoted independently.
4649     void fgLclFldAssign(unsigned lclNum);
4650
4651     static fgWalkPreFn gtHasLocalsWithAddrOpCB;
4652     bool gtCanOptimizeTypeEquality(GenTreePtr tree);
4653     bool gtIsTypeHandleToRuntimeTypeHelper(GenTreePtr tree);
4654     bool gtIsActiveCSE_Candidate(GenTreePtr tree);
4655
4656 #ifdef DEBUG
4657     bool fgPrintInlinedMethods;
4658 #endif
4659
4660     bool fgIsBigOffset(size_t offset);
4661
4662     // The following are used when morphing special cases of integer div/mod operations and also by codegen
4663     bool fgIsSignedDivOptimizable(GenTreePtr divisor);
4664     bool fgIsUnsignedDivOptimizable(GenTreePtr divisor);
4665     bool fgIsSignedModOptimizable(GenTreePtr divisor);
4666     bool fgIsUnsignedModOptimizable(GenTreePtr divisor);
4667
4668     /*
4669     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4670     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4671     XX                                                                           XX
4672     XX                           Optimizer                                       XX
4673     XX                                                                           XX
4674     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4675     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4676     */
4677
4678 public:
4679     void optInit();
4680
4681 protected:
4682     LclVarDsc* optIsTrackedLocal(GenTreePtr tree);
4683
4684 public:
4685     void optRemoveRangeCheck(
4686         GenTreePtr tree, GenTreePtr stmt, bool updateCSEcounts, unsigned sideEffFlags = 0, bool forceRemove = false);
4687     bool optIsRangeCheckRemovable(GenTreePtr tree);
4688
4689 protected:
4690     static fgWalkPreFn optValidRangeCheckIndex;
4691     static fgWalkPreFn optRemoveTreeVisitor; // Helper passed to Compiler::fgWalkAllTreesPre() to decrement the LclVar
4692                                              // usage counts
4693
4694     void optRemoveTree(GenTreePtr deadTree, GenTreePtr keepList);
4695
4696     /**************************************************************************
4697      *
4698      *************************************************************************/
4699
4700 protected:
4701     // Do hoisting for all loops.
4702     void optHoistLoopCode();
4703
4704     // To represent sets of VN's that have already been hoisted in outer loops.
4705     typedef SimplerHashTable<ValueNum, SmallPrimitiveKeyFuncs<ValueNum>, bool, JitSimplerHashBehavior> VNToBoolMap;
4706     typedef VNToBoolMap VNSet;
4707
4708     struct LoopHoistContext
4709     {
4710     private:
4711         // The set of variables hoisted in the current loop (or nullptr if there are none).
4712         VNSet* m_pHoistedInCurLoop;
4713
4714     public:
4715         // Value numbers of expressions that have been hoisted in parent loops in the loop nest.
4716         VNSet m_hoistedInParentLoops;
4717         // Value numbers of expressions that have been hoisted in the current (or most recent) loop in the nest.
4718         // Previous decisions on loop-invariance of value numbers in the current loop.
4719         VNToBoolMap m_curLoopVnInvariantCache;
4720
4721         VNSet* GetHoistedInCurLoop(Compiler* comp)
4722         {
4723             if (m_pHoistedInCurLoop == nullptr)
4724             {
4725                 m_pHoistedInCurLoop = new (comp->getAllocatorLoopHoist()) VNSet(comp->getAllocatorLoopHoist());
4726             }
4727             return m_pHoistedInCurLoop;
4728         }
4729
4730         VNSet* ExtractHoistedInCurLoop()
4731         {
4732             VNSet* res          = m_pHoistedInCurLoop;
4733             m_pHoistedInCurLoop = nullptr;
4734             return res;
4735         }
4736
4737         LoopHoistContext(Compiler* comp)
4738             : m_pHoistedInCurLoop(nullptr)
4739             , m_hoistedInParentLoops(comp->getAllocatorLoopHoist())
4740             , m_curLoopVnInvariantCache(comp->getAllocatorLoopHoist())
4741         {
4742         }
4743     };
4744
4745     // Do hoisting for loop "lnum" (an index into the optLoopTable), and all loops nested within it.
4746     // Tracks the expressions that have been hoisted by containing loops by temporary recording their
4747     // value numbers in "m_hoistedInParentLoops".  This set is not modified by the call.
4748     void optHoistLoopNest(unsigned lnum, LoopHoistContext* hoistCtxt);
4749
4750     // Do hoisting for a particular loop ("lnum" is an index into the optLoopTable.)
4751     // Assumes that expressions have been hoisted in containing loops if their value numbers are in
4752     // "m_hoistedInParentLoops".
4753     //
4754     void optHoistThisLoop(unsigned lnum, LoopHoistContext* hoistCtxt);
4755
4756     // Hoist all expressions in "blk" that are invariant in loop "lnum" (an index into the optLoopTable)
4757     // outside of that loop.  Exempt expressions whose value number is in "m_hoistedInParentLoops"; add VN's of hoisted
4758     // expressions to "hoistInLoop".
4759     void optHoistLoopExprsForBlock(BasicBlock* blk, unsigned lnum, LoopHoistContext* hoistCtxt);
4760
4761     // Return true if the tree looks profitable to hoist out of loop 'lnum'.
4762     bool optIsProfitableToHoistableTree(GenTreePtr tree, unsigned lnum);
4763
4764     // Hoist all proper sub-expressions of "tree" (which occurs in "stmt", which occurs in "blk")
4765     // that are invariant in loop "lnum" (an index into the optLoopTable)
4766     // outside of that loop.  Exempt expressions whose value number is in "hoistedInParents"; add VN's of hoisted
4767     // expressions to "hoistInLoop".
4768     // Returns "true" iff "tree" is loop-invariant (wrt "lnum").
4769     // Assumes that the value of "*firstBlockAndBeforeSideEffect" indicates that we're in the first block, and before
4770     // any possible globally visible side effects.  Assume is called in evaluation order, and updates this.
4771     bool optHoistLoopExprsForTree(GenTreePtr        tree,
4772                                   unsigned          lnum,
4773                                   LoopHoistContext* hoistCtxt,
4774                                   bool*             firstBlockAndBeforeSideEffect,
4775                                   bool*             pHoistable);
4776
4777     // Performs the hoisting 'tree' into the PreHeader for loop 'lnum'
4778     void optHoistCandidate(GenTreePtr tree, unsigned lnum, LoopHoistContext* hoistCtxt);
4779
4780     // Returns true iff the ValueNum "vn" represents a value that is loop-invariant in "lnum".
4781     //   Constants and init values are always loop invariant.
4782     //   VNPhi's connect VN's to the SSA definition, so we can know if the SSA def occurs in the loop.
4783     bool optVNIsLoopInvariant(ValueNum vn, unsigned lnum, VNToBoolMap* recordedVNs);
4784
4785     // Returns "true" iff "tree" is valid at the head of loop "lnum", in the context of the hoist substitution
4786     // "subst".  If "tree" is a local SSA var, it is valid if its SSA definition occurs outside of the loop, or
4787     // if it is in the domain of "subst" (meaning that it's definition has been previously hoisted, with a "standin"
4788     // local.)  If tree is a constant, it is valid.  Otherwise, if it is an operator, it is valid iff its children are.
4789     bool optTreeIsValidAtLoopHead(GenTreePtr tree, unsigned lnum);
4790
4791     // If "blk" is the entry block of a natural loop, returns true and sets "*pLnum" to the index of the loop
4792     // in the loop table.
4793     bool optBlockIsLoopEntry(BasicBlock* blk, unsigned* pLnum);
4794
4795     // Records the set of "side effects" of all loops: fields (object instance and static)
4796     // written to, and SZ-array element type equivalence classes updated.
4797     void optComputeLoopSideEffects();
4798
4799 private:
4800     // Requires "lnum" to be the index of an outermost loop in the loop table.  Traverses the body of that loop,
4801     // including all nested loops, and records the set of "side effects" of the loop: fields (object instance and
4802     // static) written to, and SZ-array element type equivalence classes updated.
4803     void optComputeLoopNestSideEffects(unsigned lnum);
4804
4805     // Add the side effects of "blk" (which is required to be within a loop) to all loops of which it is a part.
4806     void optComputeLoopSideEffectsOfBlock(BasicBlock* blk);
4807
4808     // Hoist the expression "expr" out of loop "lnum".
4809     void optPerformHoistExpr(GenTreePtr expr, unsigned lnum);
4810
4811 public:
4812     void optOptimizeBools();
4813
4814 private:
4815     GenTree* optIsBoolCond(GenTree* condBranch, GenTree** compPtr, bool* boolPtr);
4816 #ifdef DEBUG
4817     void optOptimizeBoolsGcStress(BasicBlock* condBlock);
4818 #endif
4819 public:
4820     void optOptimizeLayout(); // Optimize the BasicBlock layout of the method
4821
4822     void optOptimizeLoops(); // for "while-do" loops duplicates simple loop conditions and transforms
4823                              // the loop into a "do-while" loop
4824                              // Also finds all natural loops and records them in the loop table
4825
4826     // Optionally clone loops in the loop table.
4827     void optCloneLoops();
4828
4829     // Clone loop "loopInd" in the loop table.
4830     void optCloneLoop(unsigned loopInd, LoopCloneContext* context);
4831
4832     // Ensure that loop "loopInd" has a unique head block.  (If the existing entry has
4833     // non-loop predecessors other than the head entry, create a new, empty block that goes (only) to the entry,
4834     // and redirects the preds of the entry to this new block.)  Sets the weight of the newly created block to
4835     // "ambientWeight".
4836     void optEnsureUniqueHead(unsigned loopInd, unsigned ambientWeight);
4837
4838     void optUnrollLoops(); // Unrolls loops (needs to have cost info)
4839
4840 protected:
4841     // This enumeration describes what is killed by a call.
4842
4843     enum callInterf
4844     {
4845         CALLINT_NONE,       // no interference                               (most helpers)
4846         CALLINT_REF_INDIRS, // kills GC ref indirections                     (SETFIELD OBJ)
4847         CALLINT_SCL_INDIRS, // kills non GC ref indirections                 (SETFIELD non-OBJ)
4848         CALLINT_ALL_INDIRS, // kills both GC ref and non GC ref indirections (SETFIELD STRUCT)
4849         CALLINT_ALL,        // kills everything                              (normal method call)
4850     };
4851
4852 public:
4853     // A "LoopDsc" describes a ("natural") loop.  We (currently) require the body of a loop to be a contiguous (in
4854     // bbNext order) sequence of basic blocks.  (At times, we may require the blocks in a loop to be "properly numbered"
4855     // in bbNext order; we use comparisons on the bbNum to decide order.)
4856     // The blocks that define the body are
4857     //   first <= top <= entry <= bottom   .
4858     // The "head" of the loop is a block outside the loop that has "entry" as a successor. We only support loops with a
4859     // single 'head' block. The meanings of these blocks are given in the definitions below. Also see the picture at
4860     // Compiler::optFindNaturalLoops().
4861     struct LoopDsc
4862     {
4863         BasicBlock* lpHead;  // HEAD of the loop (not part of the looping of the loop) -- has ENTRY as a successor.
4864         BasicBlock* lpFirst; // FIRST block (in bbNext order) reachable within this loop.  (May be part of a nested
4865                              // loop, but not the outer loop.)
4866         BasicBlock* lpTop;   // loop TOP (the back edge from lpBottom reaches here) (in most cases FIRST and TOP are the
4867                              // same)
4868         BasicBlock* lpEntry; // the ENTRY in the loop (in most cases TOP or BOTTOM)
4869         BasicBlock* lpBottom; // loop BOTTOM (from here we have a back edge to the TOP)
4870         BasicBlock* lpExit;   // if a single exit loop this is the EXIT (in most cases BOTTOM)
4871
4872         callInterf   lpAsgCall;     // "callInterf" for calls in the loop
4873         ALLVARSET_TP lpAsgVars;     // set of vars assigned within the loop (all vars, not just tracked)
4874         varRefKinds  lpAsgInds : 8; // set of inds modified within the loop
4875
4876         unsigned short lpFlags; // Mask of the LPFLG_* constants
4877
4878         unsigned char lpExitCnt; // number of exits from the loop
4879
4880         unsigned char lpParent;  // The index of the most-nested loop that completely contains this one,
4881                                  // or else BasicBlock::NOT_IN_LOOP if no such loop exists.
4882         unsigned char lpChild;   // The index of a nested loop, or else BasicBlock::NOT_IN_LOOP if no child exists.
4883                                  // (Actually, an "immediately" nested loop --
4884                                  // no other child of this loop is a parent of lpChild.)
4885         unsigned char lpSibling; // The index of another loop that is an immediate child of lpParent,
4886                                  // or else BasicBlock::NOT_IN_LOOP.  One can enumerate all the children of a loop
4887                                  // by following "lpChild" then "lpSibling" links.
4888
4889 #define LPFLG_DO_WHILE 0x0001 // it's a do-while loop (i.e ENTRY is at the TOP)
4890 #define LPFLG_ONE_EXIT 0x0002 // the loop has only one exit
4891
4892 #define LPFLG_ITER 0x0004      // for (i = icon or lclVar; test_condition(); i++)
4893 #define LPFLG_HOISTABLE 0x0008 // the loop is in a form that is suitable for hoisting expressions
4894 #define LPFLG_CONST 0x0010     // for (i=icon;i<icon;i++){ ... } - constant loop
4895
4896 #define LPFLG_VAR_INIT 0x0020   // iterator is initialized with a local var (var # found in lpVarInit)
4897 #define LPFLG_CONST_INIT 0x0040 // iterator is initialized with a constant (found in lpConstInit)
4898
4899 #define LPFLG_VAR_LIMIT 0x0100    // iterator is compared with a local var (var # found in lpVarLimit)
4900 #define LPFLG_CONST_LIMIT 0x0200  // iterator is compared with a constant (found in lpConstLimit)
4901 #define LPFLG_ARRLEN_LIMIT 0x0400 // iterator is compared with a.len or a[i].len (found in lpArrLenLimit)
4902
4903 #define LPFLG_HAS_PREHEAD 0x0800 // lpHead is known to be a preHead for this loop
4904 #define LPFLG_REMOVED 0x1000     // has been removed from the loop table (unrolled or optimized away)
4905 #define LPFLG_DONT_UNROLL 0x2000 // do not unroll this loop
4906
4907 #define LPFLG_ASGVARS_YES 0x4000 // "lpAsgVars" has been  computed
4908 #define LPFLG_ASGVARS_INC 0x8000 // "lpAsgVars" is incomplete -- vars beyond those representable in an AllVarSet
4909                                  // type are assigned to.
4910
4911         bool lpLoopHasHeapHavoc; // The loop contains an operation that we assume has arbitrary heap side effects.
4912                                  // If this is set, the fields below may not be accurate (since they become irrelevant.)
4913         bool lpContainsCall;     // True if executing the loop body *may* execute a call
4914
4915         VARSET_TP lpVarInOut;  // The set of variables that are IN or OUT during the execution of this loop
4916         VARSET_TP lpVarUseDef; // The set of variables that are USE or DEF during the execution of this loop
4917
4918         int lpHoistedExprCount; // The register count for the non-FP expressions from inside this loop that have been
4919                                 // hoisted
4920         int lpLoopVarCount;     // The register count for the non-FP LclVars that are read/written inside this loop
4921         int lpVarInOutCount;    // The register count for the non-FP LclVars that are alive inside or accross this loop
4922
4923         int lpHoistedFPExprCount; // The register count for the FP expressions from inside this loop that have been
4924                                   // hoisted
4925         int lpLoopVarFPCount;     // The register count for the FP LclVars that are read/written inside this loop
4926         int lpVarInOutFPCount;    // The register count for the FP LclVars that are alive inside or accross this loop
4927
4928         typedef SimplerHashTable<CORINFO_FIELD_HANDLE,
4929                                  PtrKeyFuncs<struct CORINFO_FIELD_STRUCT_>,
4930                                  bool,
4931                                  JitSimplerHashBehavior>
4932                         FieldHandleSet;
4933         FieldHandleSet* lpFieldsModified; // This has entries (mappings to "true") for all static field and object
4934                                           // instance fields modified
4935                                           // in the loop.
4936
4937         typedef SimplerHashTable<CORINFO_CLASS_HANDLE,
4938                                  PtrKeyFuncs<struct CORINFO_CLASS_STRUCT_>,
4939                                  bool,
4940                                  JitSimplerHashBehavior>
4941                         ClassHandleSet;
4942         ClassHandleSet* lpArrayElemTypesModified; // Bits set indicate the set of sz array element types such that
4943                                                   // arrays of that type are modified
4944                                                   // in the loop.
4945
4946         // Adds the variable liveness information for 'blk' to 'this' LoopDsc
4947         void AddVariableLiveness(Compiler* comp, BasicBlock* blk);
4948
4949         inline void AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd);
4950         // This doesn't *always* take a class handle -- it can also take primitive types, encoded as class handles
4951         // (shifted left, with a low-order bit set to distinguish.)
4952         // Use the {Encode/Decode}ElemType methods to construct/destruct these.
4953         inline void AddModifiedElemType(Compiler* comp, CORINFO_CLASS_HANDLE structHnd);
4954
4955         /* The following values are set only for iterator loops, i.e. has the flag LPFLG_ITER set */
4956
4957         GenTreePtr lpIterTree;    // The "i <op>= const" tree
4958         unsigned   lpIterVar();   // iterator variable #
4959         int        lpIterConst(); // the constant with which the iterator is incremented
4960         genTreeOps lpIterOper();  // the type of the operation on the iterator (ASG_ADD, ASG_SUB, etc.)
4961         void       VERIFY_lpIterTree();
4962
4963         var_types lpIterOperType(); // For overflow instructions
4964
4965         union {
4966             int lpConstInit; // initial constant value of iterator                           : Valid if LPFLG_CONST_INIT
4967             unsigned lpVarInit; // initial local var number to which we initialize the iterator : Valid if
4968                                 // LPFLG_VAR_INIT
4969         };
4970
4971         /* The following is for LPFLG_ITER loops only (i.e. the loop condition is "i RELOP const or var" */
4972
4973         GenTreePtr lpTestTree;   // pointer to the node containing the loop test
4974         genTreeOps lpTestOper(); // the type of the comparison between the iterator and the limit (GT_LE, GT_GE, etc.)
4975         void       VERIFY_lpTestTree();
4976
4977         bool       lpIsReversed(); // true if the iterator node is the second operand in the loop condition
4978         GenTreePtr lpIterator();   // the iterator node in the loop test
4979         GenTreePtr lpLimit();      // the limit node in the loop test
4980
4981         int lpConstLimit();    // limit   constant value of iterator - loop condition is "i RELOP const" : Valid if
4982                                // LPFLG_CONST_LIMIT
4983         unsigned lpVarLimit(); // the lclVar # in the loop condition ( "i RELOP lclVar" )                : Valid if
4984                                // LPFLG_VAR_LIMIT
4985         bool lpArrLenLimit(Compiler* comp, ArrIndex* index); // The array length in the loop condition ( "i RELOP
4986                                                              // arr.len" or "i RELOP arr[i][j].len" )  : Valid if
4987                                                              // LPFLG_ARRLEN_LIMIT
4988
4989         // Returns "true" iff "*this" contains the blk.
4990         bool lpContains(BasicBlock* blk)
4991         {
4992             return lpFirst->bbNum <= blk->bbNum && blk->bbNum <= lpBottom->bbNum;
4993         }
4994         // Returns "true" iff "*this" (properly) contains the range [first, bottom] (allowing firsts
4995         // to be equal, but requiring bottoms to be different.)
4996         bool lpContains(BasicBlock* first, BasicBlock* bottom)
4997         {
4998             return lpFirst->bbNum <= first->bbNum && bottom->bbNum < lpBottom->bbNum;
4999         }
5000
5001         // Returns "true" iff "*this" (properly) contains "lp2" (allowing firsts to be equal, but requiring
5002         // bottoms to be different.)
5003         bool lpContains(const LoopDsc& lp2)
5004         {
5005             return lpContains(lp2.lpFirst, lp2.lpBottom);
5006         }
5007
5008         // Returns "true" iff "*this" is (properly) contained by the range [first, bottom]
5009         // (allowing firsts to be equal, but requiring bottoms to be different.)
5010         bool lpContainedBy(BasicBlock* first, BasicBlock* bottom)
5011         {
5012             return first->bbNum <= lpFirst->bbNum && lpBottom->bbNum < bottom->bbNum;
5013         }
5014
5015         // Returns "true" iff "*this" is (properly) contained by "lp2"
5016         // (allowing firsts to be equal, but requiring bottoms to be different.)
5017         bool lpContainedBy(const LoopDsc& lp2)
5018         {
5019             return lpContains(lp2.lpFirst, lp2.lpBottom);
5020         }
5021
5022         // Returns "true" iff "*this" is disjoint from the range [top, bottom].
5023         bool lpDisjoint(BasicBlock* first, BasicBlock* bottom)
5024         {
5025             return bottom->bbNum < lpFirst->bbNum || lpBottom->bbNum < first->bbNum;
5026         }
5027         // Returns "true" iff "*this" is disjoint from "lp2".
5028         bool lpDisjoint(const LoopDsc& lp2)
5029         {
5030             return lpDisjoint(lp2.lpFirst, lp2.lpBottom);
5031         }
5032         // Returns "true" iff the loop is well-formed (see code for defn).
5033         bool lpWellFormed()
5034         {
5035             return lpFirst->bbNum <= lpTop->bbNum && lpTop->bbNum <= lpEntry->bbNum &&
5036                    lpEntry->bbNum <= lpBottom->bbNum &&
5037                    (lpHead->bbNum < lpTop->bbNum || lpHead->bbNum > lpBottom->bbNum);
5038         }
5039     };
5040
5041 protected:
5042     bool fgMightHaveLoop(); // returns true if there are any backedges
5043     bool fgHasLoops;        // True if this method has any loops, set in fgComputeReachability
5044
5045 public:
5046     LoopDsc       optLoopTable[MAX_LOOP_NUM]; // loop descriptor table
5047     unsigned char optLoopCount;               // number of tracked loops
5048
5049 protected:
5050     unsigned optCallCount;         // number of calls made in the method
5051     unsigned optIndirectCallCount; // number of virtual, interface and indirect calls made in the method
5052     unsigned optNativeCallCount;   // number of Pinvoke/Native calls made in the method
5053     unsigned optLoopsCloned;       // number of loops cloned in the current method.
5054
5055 #ifdef DEBUG
5056     unsigned optFindLoopNumberFromBeginBlock(BasicBlock* begBlk);
5057     void optPrintLoopInfo(unsigned      loopNum,
5058                           BasicBlock*   lpHead,
5059                           BasicBlock*   lpFirst,
5060                           BasicBlock*   lpTop,
5061                           BasicBlock*   lpEntry,
5062                           BasicBlock*   lpBottom,
5063                           unsigned char lpExitCnt,
5064                           BasicBlock*   lpExit,
5065                           unsigned      parentLoop = BasicBlock::NOT_IN_LOOP);
5066     void optPrintLoopInfo(unsigned lnum);
5067     void optPrintLoopRecording(unsigned lnum);
5068
5069     void optCheckPreds();
5070 #endif
5071
5072     void optSetBlockWeights();
5073
5074     void optMarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk, bool excludeEndBlk);
5075
5076     void optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk);
5077
5078     void optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmarkLoop = false);
5079
5080     bool optIsLoopTestEvalIntoTemp(GenTreePtr test, GenTreePtr* newTest);
5081     unsigned optIsLoopIncrTree(GenTreePtr incr);
5082     bool optCheckIterInLoopTest(unsigned loopInd, GenTreePtr test, BasicBlock* from, BasicBlock* to, unsigned iterVar);
5083     bool optComputeIterInfo(GenTreePtr incr, BasicBlock* from, BasicBlock* to, unsigned* pIterVar);
5084     bool optPopulateInitInfo(unsigned loopInd, GenTreePtr init, unsigned iterVar);
5085     bool optExtractInitTestIncr(BasicBlock* head,
5086                                 BasicBlock* bottom,
5087                                 BasicBlock* exit,
5088                                 GenTreePtr* ppInit,
5089                                 GenTreePtr* ppTest,
5090                                 GenTreePtr* ppIncr);
5091
5092     void optRecordLoop(BasicBlock*   head,
5093                        BasicBlock*   first,
5094                        BasicBlock*   top,
5095                        BasicBlock*   entry,
5096                        BasicBlock*   bottom,
5097                        BasicBlock*   exit,
5098                        unsigned char exitCnt);
5099
5100     void optFindNaturalLoops();
5101
5102     // Ensures that all the loops in the loop nest rooted at "loopInd" (an index into the loop table) are 'canonical' --
5103     // each loop has a unique "top."  Returns "true" iff the flowgraph has been modified.
5104     bool optCanonicalizeLoopNest(unsigned char loopInd);
5105
5106     // Ensures that the loop "loopInd" (an index into the loop table) is 'canonical' -- it has a unique "top,"
5107     // unshared with any other loop.  Returns "true" iff the flowgraph has been modified
5108     bool optCanonicalizeLoop(unsigned char loopInd);
5109
5110     // Requires "l1" to be a valid loop table index, and not "BasicBlock::NOT_IN_LOOP".  Requires "l2" to be
5111     // a valid loop table index, or else "BasicBlock::NOT_IN_LOOP".  Returns true
5112     // iff "l2" is not NOT_IN_LOOP, and "l1" contains "l2".
5113     bool optLoopContains(unsigned l1, unsigned l2);
5114
5115     // Requires "loopInd" to be a valid index into the loop table.
5116     // Updates the loop table by changing loop "loopInd", whose head is required
5117     // to be "from", to be "to".  Also performs this transformation for any
5118     // loop nested in "loopInd" that shares the same head as "loopInd".
5119     void optUpdateLoopHead(unsigned loopInd, BasicBlock* from, BasicBlock* to);
5120
5121     // Updates the successors of "blk": if "blk2" is a successor of "blk", and there is a mapping for "blk2->blk3" in
5122     // "redirectMap", change "blk" so that "blk3" is this successor. Note that the predecessor lists are not updated.
5123     void optRedirectBlock(BasicBlock* blk, BlockToBlockMap* redirectMap);
5124
5125     // Marks the containsCall information to "lnum" and any parent loops.
5126     void AddContainsCallAllContainingLoops(unsigned lnum);
5127     // Adds the variable liveness information from 'blk' to "lnum" and any parent loops.
5128     void AddVariableLivenessAllContainingLoops(unsigned lnum, BasicBlock* blk);
5129     // Adds "fldHnd" to the set of modified fields of "lnum" and any parent loops.
5130     void AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd);
5131     // Adds "elemType" to the set of modified array element types of "lnum" and any parent loops.
5132     void AddModifiedElemTypeAllContainingLoops(unsigned lnum, CORINFO_CLASS_HANDLE elemType);
5133
5134     // Requires that "from" and "to" have the same "bbJumpKind" (perhaps because "to" is a clone
5135     // of "from".)  Copies the jump destination from "from" to "to".
5136     void optCopyBlkDest(BasicBlock* from, BasicBlock* to);
5137
5138     // The depth of the loop described by "lnum" (an index into the loop table.) (0 == top level)
5139     unsigned optLoopDepth(unsigned lnum)
5140     {
5141         unsigned par = optLoopTable[lnum].lpParent;
5142         if (par == BasicBlock::NOT_IN_LOOP)
5143         {
5144             return 0;
5145         }
5146         else
5147         {
5148             return 1 + optLoopDepth(par);
5149         }
5150     }
5151
5152     void fgOptWhileLoop(BasicBlock* block);
5153
5154     bool optComputeLoopRep(int        constInit,
5155                            int        constLimit,
5156                            int        iterInc,
5157                            genTreeOps iterOper,
5158                            var_types  iterType,
5159                            genTreeOps testOper,
5160                            bool       unsignedTest,
5161                            bool       dupCond,
5162                            unsigned*  iterCount);
5163 #if FEATURE_STACK_FP_X87
5164
5165 public:
5166     VARSET_TP optAllFloatVars; // mask of all tracked      FP variables
5167     VARSET_TP optAllFPregVars; // mask of all enregistered FP variables
5168     VARSET_TP optAllNonFPvars; // mask of all tracked  non-FP variables
5169 #endif                         // FEATURE_STACK_FP_X87
5170
5171 private:
5172     static fgWalkPreFn optIsVarAssgCB;
5173
5174 protected:
5175     bool optIsVarAssigned(BasicBlock* beg, BasicBlock* end, GenTreePtr skip, unsigned var);
5176
5177     bool optIsVarAssgLoop(unsigned lnum, unsigned var);
5178
5179     int optIsSetAssgLoop(unsigned lnum, ALLVARSET_VALARG_TP vars, varRefKinds inds = VR_NONE);
5180
5181     bool optNarrowTree(GenTreePtr tree, var_types srct, var_types dstt, ValueNumPair vnpNarrow, bool doit);
5182
5183     /**************************************************************************
5184      *                       Optimization conditions
5185      *************************************************************************/
5186
5187     bool optFastCodeOrBlendedLoop(BasicBlock::weight_t bbWeight);
5188     bool optPentium4(void);
5189     bool optAvoidIncDec(BasicBlock::weight_t bbWeight);
5190     bool optAvoidIntMult(void);
5191
5192 #if FEATURE_ANYCSE
5193
5194 protected:
5195     //  The following is the upper limit on how many expressions we'll keep track
5196     //  of for the CSE analysis.
5197     //
5198     static const unsigned MAX_CSE_CNT = EXPSET_SZ;
5199
5200     static const int MIN_CSE_COST = 2;
5201
5202     /* Generic list of nodes - used by the CSE logic */
5203
5204     struct treeLst
5205     {
5206         treeLst*   tlNext;
5207         GenTreePtr tlTree;
5208     };
5209
5210     typedef struct treeLst* treeLstPtr;
5211
5212     struct treeStmtLst
5213     {
5214         treeStmtLst* tslNext;
5215         GenTreePtr   tslTree;  // tree node
5216         GenTreePtr   tslStmt;  // statement containing the tree
5217         BasicBlock*  tslBlock; // block containing the statement
5218     };
5219
5220     typedef struct treeStmtLst* treeStmtLstPtr;
5221
5222     // The following logic keeps track of expressions via a simple hash table.
5223
5224     struct CSEdsc
5225     {
5226         CSEdsc* csdNextInBucket; // used by the hash table
5227
5228         unsigned csdHashValue; // the orginal hashkey
5229
5230         unsigned csdIndex;          // 1..optCSECandidateCount
5231         char     csdLiveAcrossCall; // 0 or 1
5232
5233         unsigned short csdDefCount; // definition   count
5234         unsigned short csdUseCount; // use          count  (excluding the implicit uses at defs)
5235
5236         unsigned csdDefWtCnt; // weighted def count
5237         unsigned csdUseWtCnt; // weighted use count  (excluding the implicit uses at defs)
5238
5239         GenTreePtr  csdTree;  // treenode containing the 1st occurance
5240         GenTreePtr  csdStmt;  // stmt containing the 1st occurance
5241         BasicBlock* csdBlock; // block containing the 1st occurance
5242
5243         treeStmtLstPtr csdTreeList; // list of matching tree nodes: head
5244         treeStmtLstPtr csdTreeLast; // list of matching tree nodes: tail
5245     };
5246
5247     static const size_t s_optCSEhashSize;
5248     CSEdsc**            optCSEhash;
5249     CSEdsc**            optCSEtab;
5250
5251     void optCSEstop();
5252
5253     CSEdsc* optCSEfindDsc(unsigned index);
5254     void optUnmarkCSE(GenTreePtr tree);
5255
5256     // user defined callback data for the tree walk function optCSE_MaskHelper()
5257     struct optCSE_MaskData
5258     {
5259         EXPSET_TP CSE_defMask;
5260         EXPSET_TP CSE_useMask;
5261     };
5262
5263     // Treewalk helper for optCSE_DefMask and optCSE_UseMask
5264     static fgWalkPreFn optCSE_MaskHelper;
5265
5266     // This function walks all the node for an given tree
5267     // and return the mask of CSE definitions and uses for the tree
5268     //
5269     void optCSE_GetMaskData(GenTreePtr tree, optCSE_MaskData* pMaskData);
5270
5271     // Given a binary tree node return true if it is safe to swap the order of evaluation for op1 and op2.
5272     bool optCSE_canSwap(GenTree* firstNode, GenTree* secondNode);
5273     bool optCSE_canSwap(GenTree* tree);
5274
5275     static fgWalkPostFn optPropagateNonCSE;
5276     static fgWalkPreFn  optHasNonCSEChild;
5277
5278     static fgWalkPreFn optUnmarkCSEs;
5279
5280     static int __cdecl optCSEcostCmpEx(const void* op1, const void* op2);
5281     static int __cdecl optCSEcostCmpSz(const void* op1, const void* op2);
5282
5283     void optCleanupCSEs();
5284
5285 #ifdef DEBUG
5286     void optEnsureClearCSEInfo();
5287 #endif // DEBUG
5288
5289 #endif // FEATURE_ANYCSE
5290
5291 #if FEATURE_VALNUM_CSE
5292     /**************************************************************************
5293      *                   Value Number based CSEs
5294      *************************************************************************/
5295
5296 public:
5297     void optOptimizeValnumCSEs();
5298
5299 protected:
5300     void     optValnumCSE_Init();
5301     unsigned optValnumCSE_Index(GenTreePtr tree, GenTreePtr stmt);
5302     unsigned optValnumCSE_Locate();
5303     void     optValnumCSE_InitDataFlow();
5304     void     optValnumCSE_DataFlow();
5305     void     optValnumCSE_Availablity();
5306     void     optValnumCSE_Heuristic();
5307     void optValnumCSE_UnmarkCSEs(GenTreePtr deadTree, GenTreePtr keepList);
5308
5309 #endif // FEATURE_VALNUM_CSE
5310
5311 #if FEATURE_ANYCSE
5312     bool     optDoCSE;             // True when we have found a duplicate CSE tree
5313     bool     optValnumCSE_phase;   // True when we are executing the optValnumCSE_phase
5314     unsigned optCSECandidateTotal; // Grand total of CSE candidates for both Lexical and ValNum
5315     unsigned optCSECandidateCount; // Count of CSE's candidates, reset for Lexical and ValNum CSE's
5316     unsigned optCSEstart;          // The first local variable number that is a CSE
5317     unsigned optCSEcount;          // The total count of CSE's introduced.
5318     unsigned optCSEweight;         // The weight of the current block when we are
5319                                    // scanning for CSE expressions
5320
5321     bool optIsCSEcandidate(GenTreePtr tree);
5322
5323     // lclNumIsTrueCSE returns true if the LclVar was introduced by the CSE phase of the compiler
5324     //
5325     bool lclNumIsTrueCSE(unsigned lclNum) const
5326     {
5327         return ((optCSEcount > 0) && (lclNum >= optCSEstart) && (lclNum < optCSEstart + optCSEcount));
5328     }
5329
5330     //  lclNumIsCSE returns true if the LclVar should be treated like a CSE with regards to constant prop.
5331     //
5332     bool lclNumIsCSE(unsigned lclNum) const
5333     {
5334         return lvaTable[lclNum].lvIsCSE;
5335     }
5336
5337 #ifdef DEBUG
5338     bool optConfigDisableCSE();
5339     bool optConfigDisableCSE2();
5340 #endif
5341     void optOptimizeCSEs();
5342
5343 #endif // FEATURE_ANYCSE
5344
5345     struct isVarAssgDsc
5346     {
5347         GenTreePtr ivaSkip;
5348 #ifdef DEBUG
5349         void* ivaSelf;
5350 #endif
5351         unsigned     ivaVar;            // Variable we are interested in, or -1
5352         ALLVARSET_TP ivaMaskVal;        // Set of variables assigned to.  This is a set of all vars, not tracked vars.
5353         bool         ivaMaskIncomplete; // Variables not representable in ivaMaskVal were assigned to.
5354         varRefKinds  ivaMaskInd;        // What kind of indirect assignments are there?
5355         callInterf   ivaMaskCall;       // What kind of calls are there?
5356     };
5357
5358     static callInterf optCallInterf(GenTreePtr call);
5359
5360 public:
5361     // VN based copy propagation.
5362     typedef ArrayStack<GenTreePtr> GenTreePtrStack;
5363     typedef SimplerHashTable<unsigned, SmallPrimitiveKeyFuncs<unsigned>, GenTreePtrStack*, JitSimplerHashBehavior>
5364         LclNumToGenTreePtrStack;
5365
5366     // Kill set to track variables with intervening definitions.
5367     VARSET_TP optCopyPropKillSet;
5368
5369     // Copy propagation functions.
5370     void optCopyProp(BasicBlock* block, GenTreePtr stmt, GenTreePtr tree, LclNumToGenTreePtrStack* curSsaName);
5371     void optBlockCopyPropPopStacks(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
5372     void optBlockCopyProp(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
5373     bool optIsSsaLocal(GenTreePtr tree);
5374     int optCopyProp_LclVarScore(LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc, bool preferOp2);
5375     void optVnCopyProp();
5376
5377     /**************************************************************************
5378     *               Early value propagation
5379     *************************************************************************/
5380     struct SSAName
5381     {
5382         unsigned m_lvNum;
5383         unsigned m_ssaNum;
5384
5385         SSAName(unsigned lvNum, unsigned ssaNum) : m_lvNum(lvNum), m_ssaNum(ssaNum)
5386         {
5387         }
5388
5389         static unsigned GetHashCode(SSAName ssaNm)
5390         {
5391             return (ssaNm.m_lvNum << 16) | (ssaNm.m_ssaNum);
5392         }
5393
5394         static bool Equals(SSAName ssaNm1, SSAName ssaNm2)
5395         {
5396             return (ssaNm1.m_lvNum == ssaNm2.m_lvNum) && (ssaNm1.m_ssaNum == ssaNm2.m_ssaNum);
5397         }
5398     };
5399
5400 #define OMF_HAS_NEWARRAY 0x00000001  // Method contains 'new' of an array
5401 #define OMF_HAS_NEWOBJ 0x00000002    // Method contains 'new' of an object type.
5402 #define OMF_HAS_ARRAYREF 0x00000004  // Method contains array element loads or stores.
5403 #define OMF_HAS_VTABLEREF 0x00000008 // Method contains method table reference.
5404 #define OMF_HAS_NULLCHECK 0x00000010 // Method contains null check.
5405
5406     unsigned optMethodFlags;
5407
5408     // Recursion bound controls how far we can go backwards tracking for a SSA value.
5409     // No throughput diff was found with backward walk bound between 3-8.
5410     static const int optEarlyPropRecurBound = 5;
5411
5412     enum class optPropKind
5413     {
5414         OPK_INVALID,
5415         OPK_ARRAYLEN,
5416         OPK_OBJ_GETTYPE,
5417         OPK_NULLCHECK
5418     };
5419
5420     bool gtIsVtableRef(GenTreePtr tree);
5421     GenTreePtr getArrayLengthFromAllocation(GenTreePtr tree);
5422     GenTreePtr getObjectHandleNodeFromAllocation(GenTreePtr tree);
5423     GenTreePtr optPropGetValueRec(unsigned lclNum, unsigned ssaNum, optPropKind valueKind, int walkDepth);
5424     GenTreePtr optPropGetValue(unsigned lclNum, unsigned ssaNum, optPropKind valueKind);
5425     bool optEarlyPropRewriteTree(GenTreePtr tree);
5426     bool optDoEarlyPropForBlock(BasicBlock* block);
5427     bool optDoEarlyPropForFunc();
5428     void optEarlyProp();
5429     void optFoldNullCheck(GenTreePtr tree);
5430     bool optCanMoveNullCheckPastTree(GenTreePtr tree, bool isInsideTry);
5431
5432 #if ASSERTION_PROP
5433     /**************************************************************************
5434      *               Value/Assertion propagation
5435      *************************************************************************/
5436 public:
5437     // Data structures for assertion prop
5438     BitVecTraits* apTraits;
5439     ASSERT_TP     apFull;
5440     ASSERT_TP     apEmpty;
5441
5442     enum optAssertionKind
5443     {
5444         OAK_INVALID,
5445         OAK_EQUAL,
5446         OAK_NOT_EQUAL,
5447         OAK_SUBRANGE,
5448         OAK_NO_THROW,
5449         OAK_COUNT
5450     };
5451
5452     enum optOp1Kind
5453     {
5454         O1K_INVALID,
5455         O1K_LCLVAR,
5456         O1K_ARR_BND,
5457         O1K_ARRLEN_OPER_BND,
5458         O1K_ARRLEN_LOOP_BND,
5459         O1K_CONSTANT_LOOP_BND,
5460         O1K_EXACT_TYPE,
5461         O1K_SUBTYPE,
5462         O1K_VALUE_NUMBER,
5463         O1K_COUNT
5464     };
5465
5466     enum optOp2Kind
5467     {
5468         O2K_INVALID,
5469         O2K_LCLVAR_COPY,
5470         O2K_IND_CNS_INT,
5471         O2K_CONST_INT,
5472         O2K_CONST_LONG,
5473         O2K_CONST_DOUBLE,
5474         O2K_ARR_LEN,
5475         O2K_SUBRANGE,
5476         O2K_COUNT
5477     };
5478     struct AssertionDsc
5479     {
5480         optAssertionKind assertionKind;
5481         struct SsaVar
5482         {
5483             unsigned lclNum; // assigned to or property of this local var number
5484             unsigned ssaNum;
5485         };
5486         struct ArrBnd
5487         {
5488             ValueNum vnIdx;
5489             ValueNum vnLen;
5490         };
5491         struct AssertionDscOp1
5492         {
5493             optOp1Kind kind; // a normal LclVar, or Exact-type or Subtype
5494             ValueNum   vn;
5495             union {
5496                 SsaVar lcl;
5497                 ArrBnd bnd;
5498             };
5499         } op1;
5500         struct AssertionDscOp2
5501         {
5502             optOp2Kind kind; // a const or copy assignment
5503             ValueNum   vn;
5504             struct IntVal
5505             {
5506                 ssize_t  iconVal;   // integer
5507                 unsigned iconFlags; // gtFlags
5508             };
5509             struct Range // integer subrange
5510             {
5511                 ssize_t loBound;
5512                 ssize_t hiBound;
5513             };
5514             union {
5515                 SsaVar  lcl;
5516                 IntVal  u1;
5517                 __int64 lconVal;
5518                 double  dconVal;
5519                 Range   u2;
5520             };
5521         } op2;
5522
5523         bool IsArrLenArithBound()
5524         {
5525             return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_ARRLEN_OPER_BND);
5526         }
5527         bool IsArrLenBound()
5528         {
5529             return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_ARRLEN_LOOP_BND);
5530         }
5531         bool IsConstantBound()
5532         {
5533             return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) &&
5534                     op1.kind == O1K_CONSTANT_LOOP_BND);
5535         }
5536         bool IsBoundsCheckNoThrow()
5537         {
5538             return ((assertionKind == OAK_NO_THROW) && (op1.kind == O1K_ARR_BND));
5539         }
5540
5541         bool IsCopyAssertion()
5542         {
5543             return ((assertionKind == OAK_EQUAL) && (op1.kind == O1K_LCLVAR) && (op2.kind == O2K_LCLVAR_COPY));
5544         }
5545
5546         static bool SameKind(AssertionDsc* a1, AssertionDsc* a2)
5547         {
5548             return a1->assertionKind == a2->assertionKind && a1->op1.kind == a2->op1.kind &&
5549                    a1->op2.kind == a2->op2.kind;
5550         }
5551
5552         static bool ComplementaryKind(optAssertionKind kind, optAssertionKind kind2)
5553         {
5554             if (kind == OAK_EQUAL)
5555             {
5556                 return kind2 == OAK_NOT_EQUAL;
5557             }
5558             else if (kind == OAK_NOT_EQUAL)
5559             {
5560                 return kind2 == OAK_EQUAL;
5561             }
5562             return false;
5563         }
5564
5565         static ssize_t GetLowerBoundForIntegralType(var_types type)
5566         {
5567             switch (type)
5568             {
5569                 case TYP_BYTE:
5570                     return SCHAR_MIN;
5571                 case TYP_SHORT:
5572                     return SHRT_MIN;
5573                 case TYP_INT:
5574                     return INT_MIN;
5575                 case TYP_BOOL:
5576                 case TYP_UBYTE:
5577                 case TYP_CHAR:
5578                 case TYP_USHORT:
5579                 case TYP_UINT:
5580                     return 0;
5581                 default:
5582                     unreached();
5583             }
5584         }
5585         static ssize_t GetUpperBoundForIntegralType(var_types type)
5586         {
5587             switch (type)
5588             {
5589                 case TYP_BOOL:
5590                     return 1;
5591                 case TYP_BYTE:
5592                     return SCHAR_MAX;
5593                 case TYP_SHORT:
5594                     return SHRT_MAX;
5595                 case TYP_INT:
5596                     return INT_MAX;
5597                 case TYP_UBYTE:
5598                     return UCHAR_MAX;
5599                 case TYP_CHAR:
5600                 case TYP_USHORT:
5601                     return USHRT_MAX;
5602                 case TYP_UINT:
5603                     return UINT_MAX;
5604                 default:
5605                     unreached();
5606             }
5607         }
5608
5609         bool HasSameOp1(AssertionDsc* that, bool vnBased)
5610         {
5611             return (op1.kind == that->op1.kind) &&
5612                    ((vnBased && (op1.vn == that->op1.vn)) || (!vnBased && (op1.lcl.lclNum == that->op1.lcl.lclNum)));
5613         }
5614
5615         bool HasSameOp2(AssertionDsc* that, bool vnBased)
5616         {
5617             if (op2.kind != that->op2.kind)
5618             {
5619                 return false;
5620             }
5621             switch (op2.kind)
5622             {
5623                 case O2K_IND_CNS_INT:
5624                 case O2K_CONST_INT:
5625                     return ((op2.u1.iconVal == that->op2.u1.iconVal) && (op2.u1.iconFlags == that->op2.u1.iconFlags));
5626
5627                 case O2K_CONST_LONG:
5628                     return (op2.lconVal == that->op2.lconVal);
5629
5630                 case O2K_CONST_DOUBLE:
5631                     // exact match because of positive and negative zero.
5632                     return (memcmp(&op2.dconVal, &that->op2.dconVal, sizeof(double)) == 0);
5633
5634                 case O2K_LCLVAR_COPY:
5635                 case O2K_ARR_LEN:
5636                     return (op2.lcl.lclNum == that->op2.lcl.lclNum) &&
5637                            (!vnBased || op2.lcl.ssaNum == that->op2.lcl.ssaNum);
5638
5639                 case O2K_SUBRANGE:
5640                     return ((op2.u2.loBound == that->op2.u2.loBound) && (op2.u2.hiBound == that->op2.u2.hiBound));
5641
5642                 case O2K_INVALID:
5643                     // we will return false
5644                     break;
5645
5646                 default:
5647                     assert(!"Unexpected value for op2.kind in AssertionDsc.");
5648                     break;
5649             }
5650             return false;
5651         }
5652
5653         bool Complementary(AssertionDsc* that, bool vnBased)
5654         {
5655             return ComplementaryKind(assertionKind, that->assertionKind) && HasSameOp1(that, vnBased) &&
5656                    HasSameOp2(that, vnBased);
5657         }
5658
5659         bool Equals(AssertionDsc* that, bool vnBased)
5660         {
5661             return (assertionKind == that->assertionKind) && HasSameOp1(that, vnBased) && HasSameOp2(that, vnBased);
5662         }
5663     };
5664
5665     typedef unsigned short AssertionIndex;
5666
5667 protected:
5668     static fgWalkPreFn optAddCopiesCallback;
5669     static fgWalkPreFn optVNAssertionPropCurStmtVisitor;
5670     unsigned           optAddCopyLclNum;
5671     GenTreePtr         optAddCopyAsgnNode;
5672
5673     bool optLocalAssertionProp;  // indicates that we are performing local assertion prop
5674     bool optAssertionPropagated; // set to true if we modified the trees
5675     bool optAssertionPropagatedCurrentStmt;
5676 #ifdef DEBUG
5677     GenTreePtr optAssertionPropCurrentTree;
5678 #endif
5679     AssertionIndex*         optComplementaryAssertionMap;
5680     ExpandArray<ASSERT_TP>* optAssertionDep; // table that holds dependent assertions (assertions
5681                                              // using the value of a local var) for each local var
5682     AssertionDsc*  optAssertionTabPrivate;   // table that holds info about value assignments
5683     AssertionIndex optAssertionCount;        // total number of assertions in the assertion table
5684     AssertionIndex optMaxAssertionCount;
5685
5686 public:
5687     void optVnNonNullPropCurStmt(BasicBlock* block, GenTreePtr stmt, GenTreePtr tree);
5688     fgWalkResult optVNConstantPropCurStmt(BasicBlock* block, GenTreePtr stmt, GenTreePtr tree);
5689     GenTreePtr optVNConstantPropOnRelOp(GenTreePtr tree);
5690     GenTreePtr optVNConstantPropOnJTrue(BasicBlock* block, GenTreePtr stmt, GenTreePtr test);
5691     GenTreePtr optVNConstantPropOnTree(BasicBlock* block, GenTreePtr stmt, GenTreePtr tree);
5692     GenTreePtr optPrepareTreeForReplacement(GenTreePtr extractTree, GenTreePtr replaceTree);
5693
5694     AssertionIndex GetAssertionCount()
5695     {
5696         return optAssertionCount;
5697     }
5698     ASSERT_TP* bbJtrueAssertionOut;
5699     typedef SimplerHashTable<ValueNum, SmallPrimitiveKeyFuncs<ValueNum>, ASSERT_TP, JitSimplerHashBehavior>
5700                           ValueNumToAssertsMap;
5701     ValueNumToAssertsMap* optValueNumToAsserts;
5702
5703     static const AssertionIndex NO_ASSERTION_INDEX = 0;
5704
5705     // Assertion prop helpers.
5706     ASSERT_TP& GetAssertionDep(unsigned lclNum);
5707     AssertionDsc* optGetAssertion(AssertionIndex assertIndex);
5708     void optAssertionInit(bool isLocalProp);
5709     void optAssertionTraitsInit(AssertionIndex assertionCount);
5710 #if LOCAL_ASSERTION_PROP
5711     void optAssertionReset(AssertionIndex limit);
5712     void optAssertionRemove(AssertionIndex index);
5713 #endif
5714
5715     // Assertion prop data flow functions.
5716     void       optAssertionPropMain();
5717     GenTreePtr optVNAssertionPropCurStmt(BasicBlock* block, GenTreePtr stmt);
5718     bool optIsTreeKnownIntValue(bool vnBased, GenTreePtr tree, ssize_t* pConstant, unsigned* pIconFlags);
5719     ASSERT_TP* optInitAssertionDataflowFlags();
5720     ASSERT_TP* optComputeAssertionGen();
5721
5722     // Assertion Gen functions.
5723     void optAssertionGen(GenTreePtr tree);
5724     AssertionIndex optAssertionGenPhiDefn(GenTreePtr tree);
5725     AssertionIndex optCreateJTrueBoundsAssertion(GenTreePtr tree);
5726     AssertionIndex optAssertionGenJtrue(GenTreePtr tree);
5727     AssertionIndex optCreateJtrueAssertions(GenTreePtr op1, GenTreePtr op2, Compiler::optAssertionKind assertionKind);
5728     AssertionIndex optFindComplementary(AssertionIndex assertionIndex);
5729     void optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index);
5730
5731     // Assertion creation functions.
5732     AssertionIndex optCreateAssertion(GenTreePtr op1, GenTreePtr op2, optAssertionKind assertionKind);
5733     AssertionIndex optCreateAssertion(GenTreePtr       op1,
5734                                       GenTreePtr       op2,
5735                                       optAssertionKind assertionKind,
5736                                       AssertionDsc*    assertion);
5737     void optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTreePtr op1, GenTreePtr op2);
5738
5739     bool optAssertionVnInvolvesNan(AssertionDsc* assertion);
5740     AssertionIndex optAddAssertion(AssertionDsc* assertion);
5741     void optAddVnAssertionMapping(ValueNum vn, AssertionIndex index);
5742 #ifdef DEBUG
5743     void optPrintVnAssertionMapping();
5744 #endif
5745     ASSERT_TP optGetVnMappedAssertions(ValueNum vn);
5746
5747     // Used for respective assertion propagations.
5748     AssertionIndex optAssertionIsSubrange(GenTreePtr tree, var_types toType, ASSERT_VALARG_TP assertions);
5749     AssertionIndex optAssertionIsSubtype(GenTreePtr tree, GenTreePtr methodTableArg, ASSERT_VALARG_TP assertions);
5750     AssertionIndex optAssertionIsNonNullInternal(GenTreePtr op, ASSERT_VALARG_TP assertions);
5751     bool optAssertionIsNonNull(GenTreePtr       op,
5752                                ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex));
5753
5754     // Used for Relop propagation.
5755     AssertionIndex optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTreePtr op1, GenTreePtr op2);
5756     AssertionIndex optLocalAssertionIsEqualOrNotEqual(
5757         optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions);
5758
5759     // Assertion prop for lcl var functions.
5760     bool optAssertionProp_LclVarTypeCheck(GenTreePtr tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc);
5761     GenTreePtr optCopyAssertionProp(AssertionDsc* curAssertion,
5762                                     GenTreePtr    tree,
5763                                     GenTreePtr stmt DEBUGARG(AssertionIndex index));
5764     GenTreePtr optConstantAssertionProp(AssertionDsc*    curAssertion,
5765                                         const GenTreePtr tree,
5766                                         const GenTreePtr stmt DEBUGARG(AssertionIndex index));
5767     GenTreePtr optVnConstantAssertionProp(const GenTreePtr tree, const GenTreePtr stmt);
5768
5769     // Assertion propagation functions.
5770     GenTreePtr optAssertionProp(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5771     GenTreePtr optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5772     GenTreePtr optAssertionProp_Ind(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5773     GenTreePtr optAssertionProp_Cast(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5774     GenTreePtr optAssertionProp_Call(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5775     GenTreePtr optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5776     GenTreePtr optAssertionProp_Comma(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5777     GenTreePtr optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5778     GenTreePtr optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5779     GenTreePtr optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5780     GenTreePtr optAssertionProp_Update(const GenTreePtr newTree, const GenTreePtr tree, const GenTreePtr stmt);
5781     GenTreePtr optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5782
5783     // Implied assertion functions.
5784     void optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions);
5785     void optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions);
5786     void optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result);
5787     void optImpliedByConstAssertion(AssertionDsc* curAssertion, ASSERT_TP& result);
5788
5789     ASSERT_VALRET_TP optNewFullAssertSet();
5790     ASSERT_VALRET_TP optNewEmptyAssertSet();
5791
5792 #ifdef DEBUG
5793     void optPrintAssertion(AssertionDsc* newAssertion, AssertionIndex assertionIndex = 0);
5794     void optDebugCheckAssertion(AssertionDsc* assertion);
5795     void optDebugCheckAssertions(AssertionIndex AssertionIndex);
5796 #endif
5797     void optAddCopies();
5798 #endif // ASSERTION_PROP
5799
5800     /**************************************************************************
5801      *                          Range checks
5802      *************************************************************************/
5803
5804 public:
5805     struct LoopCloneVisitorInfo
5806     {
5807         LoopCloneContext* context;
5808         unsigned          loopNum;
5809         GenTreePtr        stmt;
5810         LoopCloneVisitorInfo(LoopCloneContext* context, unsigned loopNum, GenTreePtr stmt)
5811             : context(context), loopNum(loopNum), stmt(nullptr)
5812         {
5813         }
5814     };
5815
5816     bool optIsStackLocalInvariant(unsigned loopNum, unsigned lclNum);
5817     bool optExtractArrIndex(GenTreePtr tree, ArrIndex* result, unsigned lhsNum);
5818     bool optReconstructArrIndex(GenTreePtr tree, ArrIndex* result, unsigned lhsNum);
5819     bool optIdentifyLoopOptInfo(unsigned loopNum, LoopCloneContext* context);
5820     static fgWalkPreFn optCanOptimizeByLoopCloningVisitor;
5821     fgWalkResult optCanOptimizeByLoopCloning(GenTreePtr tree, LoopCloneVisitorInfo* info);
5822     void optObtainLoopCloningOpts(LoopCloneContext* context);
5823     bool optIsLoopClonable(unsigned loopInd);
5824
5825     bool optCanCloneLoops();
5826
5827 #ifdef DEBUG
5828     void optDebugLogLoopCloning(BasicBlock* block, GenTreePtr insertBefore);
5829 #endif
5830     void optPerformStaticOptimizations(unsigned loopNum, LoopCloneContext* context DEBUGARG(bool fastPath));
5831     bool optComputeDerefConditions(unsigned loopNum, LoopCloneContext* context);
5832     bool optDeriveLoopCloningConditions(unsigned loopNum, LoopCloneContext* context);
5833     BasicBlock* optInsertLoopChoiceConditions(LoopCloneContext* context,
5834                                               unsigned          loopNum,
5835                                               BasicBlock*       head,
5836                                               BasicBlock*       slow);
5837     void optInsertLoopCloningStress(BasicBlock* head);
5838
5839 #if COUNT_RANGECHECKS
5840     static unsigned optRangeChkRmv;
5841     static unsigned optRangeChkAll;
5842 #endif
5843
5844 protected:
5845     struct arraySizes
5846     {
5847         unsigned arrayVar;
5848         int      arrayDim;
5849
5850 #define MAX_ARRAYS 4 // a magic max number of arrays tracked for bounds check elimination
5851     };
5852
5853     struct RngChkDsc
5854     {
5855         RngChkDsc* rcdNextInBucket; // used by the hash table
5856
5857         unsigned short rcdHashValue; // to make matching faster
5858         unsigned short rcdIndex;     // 0..optRngChkCount-1
5859
5860         GenTreePtr rcdTree; // the array index tree
5861     };
5862
5863     unsigned            optRngChkCount;
5864     static const size_t optRngChkHashSize;
5865
5866     ssize_t optGetArrayRefScaleAndIndex(GenTreePtr mul, GenTreePtr* pIndex DEBUGARG(bool bRngChk));
5867     GenTreePtr optFindLocalInit(BasicBlock* block, GenTreePtr local, VARSET_TP* pKilledInOut, bool* isKilledAfterInit);
5868
5869 #if FANCY_ARRAY_OPT
5870     bool optIsNoMore(GenTreePtr op1, GenTreePtr op2, int add1 = 0, int add2 = 0);
5871 #endif
5872
5873     bool optReachWithoutCall(BasicBlock* srcBB, BasicBlock* dstBB);
5874
5875 protected:
5876     bool optLoopsMarked;
5877
5878     /*
5879     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5880     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5881     XX                                                                           XX
5882     XX                           RegAlloc                                        XX
5883     XX                                                                           XX
5884     XX  Does the register allocation and puts the remaining lclVars on the stack XX
5885     XX                                                                           XX
5886     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5887     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5888     */
5889
5890 public:
5891 #ifndef LEGACY_BACKEND
5892     bool doLSRA() const
5893     {
5894         return true;
5895     }
5896 #else  // LEGACY_BACKEND
5897     bool doLSRA() const
5898     {
5899         return false;
5900     }
5901 #endif // LEGACY_BACKEND
5902
5903 #ifdef LEGACY_BACKEND
5904     void raInit();
5905     void raAssignVars(); // register allocation
5906 #endif                   // LEGACY_BACKEND
5907
5908     VARSET_TP raRegVarsMask; // Set of all enregistered variables (not including FEATURE_STACK_FP_X87 enregistered
5909                              // variables)
5910     regNumber raUpdateRegStateForArg(RegState* regState, LclVarDsc* argDsc);
5911
5912     void raMarkStkVars();
5913
5914 protected:
5915     // Some things are used by both LSRA and regpredict allocators.
5916
5917     FrameType rpFrameType;
5918     bool      rpMustCreateEBPCalled; // Set to true after we have called rpMustCreateEBPFrame once
5919
5920 #ifdef LEGACY_BACKEND
5921     regMaskTP rpMaskPInvokeEpilogIntf; // pinvoke epilog trashes esi/edi holding stack args needed to setup tail call's
5922                                        // args
5923 #endif                                 // LEGACY_BACKEND
5924
5925     bool rpMustCreateEBPFrame(INDEBUG(const char** wbReason));
5926
5927 #if FEATURE_FP_REGALLOC
5928     enum enumConfigRegisterFP
5929     {
5930         CONFIG_REGISTER_FP_NONE         = 0x0,
5931         CONFIG_REGISTER_FP_CALLEE_TRASH = 0x1,
5932         CONFIG_REGISTER_FP_CALLEE_SAVED = 0x2,
5933         CONFIG_REGISTER_FP_FULL         = 0x3,
5934     };
5935     enumConfigRegisterFP raConfigRegisterFP();
5936 #endif // FEATURE_FP_REGALLOC
5937
5938 public:
5939     regMaskTP raConfigRestrictMaskFP();
5940
5941 private:
5942 #ifndef LEGACY_BACKEND
5943     LinearScanInterface* m_pLinearScan; // Linear Scan allocator
5944 #else                                   // LEGACY_BACKEND
5945     unsigned  raAvoidArgRegMask;       // Mask of incoming argument registers that we may need to avoid
5946     VARSET_TP raLclRegIntf[REG_COUNT]; // variable to register interference graph
5947     bool      raNewBlocks;             // True is we added killing blocks for FPU registers
5948     unsigned  rpPasses;                // Number of passes made by the register predicter
5949     unsigned  rpPassesMax;             // Maximum number of passes made by the register predicter
5950     unsigned  rpPassesPessimize;       // Number of passes non-pessimizing made by the register predicter
5951     unsigned rpStkPredict; // Weighted count of variables were predicted STK (lower means register allocation is better)
5952     unsigned rpPredictSpillCnt;     // Predicted number of integer spill tmps for the current tree
5953     regMaskTP rpPredictAssignMask;  // Mask of registers to consider in rpPredictAssignRegVars()
5954     VARSET_TP rpLastUseVars;        // Set of last use variables in rpPredictTreeRegUse
5955     VARSET_TP rpUseInPlace;         // Set of variables that we used in place
5956     int       rpAsgVarNum;          // VarNum for the target of GT_ASG node
5957     bool      rpPredictAssignAgain; // Must rerun the rpPredictAssignRegVars()
5958     bool      rpAddedVarIntf;       // Set to true if we need to add a new var intf
5959     bool      rpLostEnreg;          // Set to true if we lost an enregister var that had lvDependReg set
5960     bool      rpReverseEBPenreg;    // Decided to reverse the enregistration of EBP
5961 public:
5962     bool rpRegAllocDone; // Set to true after we have completed register allocation
5963 private:
5964     regMaskTP rpPredictMap[PREDICT_COUNT]; // Holds the regMaskTP for each of the enum values
5965
5966     void raSetupArgMasks(RegState* r);
5967
5968     const regNumber* raGetRegVarOrder(var_types regType, unsigned* wbVarOrderSize);
5969 #ifdef DEBUG
5970     void raDumpVarIntf(); // Dump the variable to variable interference graph
5971     void raDumpRegIntf(); // Dump the variable to register interference graph
5972 #endif
5973     void raAdjustVarIntf();
5974
5975     regMaskTP rpPredictRegMask(rpPredictReg predictReg, var_types type);
5976
5977     bool rpRecordRegIntf(regMaskTP regMask, VARSET_VALARG_TP life DEBUGARG(const char* msg));
5978
5979     bool rpRecordVarIntf(unsigned varNum, VARSET_VALARG_TP intfVar DEBUGARG(const char* msg));
5980     regMaskTP rpPredictRegPick(var_types type, rpPredictReg predictReg, regMaskTP lockedRegs);
5981
5982     regMaskTP rpPredictGrabReg(var_types type, rpPredictReg predictReg, regMaskTP lockedRegs);
5983
5984     static fgWalkPreFn rpMarkRegIntf;
5985
5986     regMaskTP rpPredictAddressMode(
5987         GenTreePtr tree, var_types type, regMaskTP lockedRegs, regMaskTP rsvdRegs, GenTreePtr lenCSE);
5988
5989     void rpPredictRefAssign(unsigned lclNum);
5990
5991     regMaskTP rpPredictBlkAsgRegUse(GenTreePtr tree, rpPredictReg predictReg, regMaskTP lockedRegs, regMaskTP rsvdRegs);
5992
5993     regMaskTP rpPredictTreeRegUse(GenTreePtr tree, rpPredictReg predictReg, regMaskTP lockedRegs, regMaskTP rsvdRegs);
5994
5995     regMaskTP rpPredictAssignRegVars(regMaskTP regAvail);
5996
5997     void rpPredictRegUse(); // Entry point
5998
5999     unsigned raPredictTreeRegUse(GenTreePtr tree);
6000     unsigned raPredictListRegUse(GenTreePtr list);
6001
6002     void raSetRegVarOrder(var_types  regType,
6003                           regNumber* customVarOrder,
6004                           unsigned*  customVarOrderSize,
6005                           regMaskTP  prefReg,
6006                           regMaskTP  avoidReg);
6007
6008     // We use (unsigned)-1 as an uninitialized sentinel for rpStkPredict and
6009     // also as the maximum value of lvRefCntWtd. Don't allow overflow, and
6010     // saturate at UINT_MAX - 1, to avoid using the sentinel.
6011     void raAddToStkPredict(unsigned val)
6012     {
6013         unsigned newStkPredict = rpStkPredict + val;
6014         if ((newStkPredict < rpStkPredict) || (newStkPredict == UINT_MAX))
6015             rpStkPredict = UINT_MAX - 1;
6016         else
6017             rpStkPredict = newStkPredict;
6018     }
6019
6020 #ifdef DEBUG
6021 #if !FEATURE_FP_REGALLOC
6022     void raDispFPlifeInfo();
6023 #endif
6024 #endif
6025
6026     regMaskTP genReturnRegForTree(GenTreePtr tree);
6027 #endif // LEGACY_BACKEND
6028
6029     /* raIsVarargsStackArg is called by raMaskStkVars and by
6030        lvaSortByRefCount.  It identifies the special case
6031        where a varargs function has a parameter passed on the
6032        stack, other than the special varargs handle.  Such parameters
6033        require special treatment, because they cannot be tracked
6034        by the GC (their offsets in the stack are not known
6035        at compile time).
6036     */
6037
6038     bool raIsVarargsStackArg(unsigned lclNum)
6039     {
6040 #ifdef _TARGET_X86_
6041
6042         LclVarDsc* varDsc = &lvaTable[lclNum];
6043
6044         assert(varDsc->lvIsParam);
6045
6046         return (info.compIsVarArgs && !varDsc->lvIsRegArg && (lclNum != lvaVarargsHandleArg));
6047
6048 #else // _TARGET_X86_
6049
6050         return false;
6051
6052 #endif // _TARGET_X86_
6053     }
6054
6055 #ifdef LEGACY_BACKEND
6056     // Records the current prediction, if it's better than any previous recorded prediction.
6057     void rpRecordPrediction();
6058     // Applies the best recorded prediction, if one exists and is better than the current prediction.
6059     void rpUseRecordedPredictionIfBetter();
6060
6061     // Data members used in the methods above.
6062     unsigned rpBestRecordedStkPredict;
6063     struct VarRegPrediction
6064     {
6065         bool           m_isEnregistered;
6066         regNumberSmall m_regNum;
6067         regNumberSmall m_otherReg;
6068     };
6069     VarRegPrediction* rpBestRecordedPrediction;
6070 #endif // LEGACY_BACKEND
6071
6072     /*
6073     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6074     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6075     XX                                                                           XX
6076     XX                           EEInterface                                     XX
6077     XX                                                                           XX
6078     XX   Get to the class and method info from the Execution Engine given        XX
6079     XX   tokens for the class and method                                         XX
6080     XX                                                                           XX
6081     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6082     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6083     */
6084
6085 public:
6086     /* These are the different addressing modes used to access a local var.
6087      * The JIT has to report the location of the locals back to the EE
6088      * for debugging purposes.
6089      */
6090
6091     enum siVarLocType
6092     {
6093         VLT_REG,
6094         VLT_REG_BYREF, // this type is currently only used for value types on X64
6095         VLT_REG_FP,
6096         VLT_STK,
6097         VLT_STK_BYREF, // this type is currently only used for value types on X64
6098         VLT_REG_REG,
6099         VLT_REG_STK,
6100         VLT_STK_REG,
6101         VLT_STK2,
6102         VLT_FPSTK,
6103         VLT_FIXED_VA,
6104
6105         VLT_COUNT,
6106         VLT_INVALID
6107     };
6108
6109     struct siVarLoc
6110     {
6111         siVarLocType vlType;
6112
6113         union {
6114             // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc)
6115             // eg. EAX
6116             // VLT_REG_BYREF -- the specified register contains the address of the variable
6117             // eg. [EAX]
6118
6119             struct
6120             {
6121                 regNumber vlrReg;
6122             } vlReg;
6123
6124             // VLT_STK       -- Any 32 bit value which is on the stack
6125             // eg. [ESP+0x20], or [EBP-0x28]
6126             // VLT_STK_BYREF -- the specified stack location contains the address of the variable
6127             // eg. mov EAX, [ESP+0x20]; [EAX]
6128
6129             struct
6130             {
6131                 regNumber     vlsBaseReg;
6132                 NATIVE_OFFSET vlsOffset;
6133             } vlStk;
6134
6135             // VLT_REG_REG -- TYP_LONG/TYP_DOUBLE with both DWords enregistered
6136             // eg. RBM_EAXEDX
6137
6138             struct
6139             {
6140                 regNumber vlrrReg1;
6141                 regNumber vlrrReg2;
6142             } vlRegReg;
6143
6144             // VLT_REG_STK -- Partly enregistered TYP_LONG/TYP_DOUBLE
6145             // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] }
6146
6147             struct
6148             {
6149                 regNumber vlrsReg;
6150
6151                 struct
6152                 {
6153                     regNumber     vlrssBaseReg;
6154                     NATIVE_OFFSET vlrssOffset;
6155                 } vlrsStk;
6156             } vlRegStk;
6157
6158             // VLT_STK_REG -- Partly enregistered TYP_LONG/TYP_DOUBLE
6159             // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX }
6160
6161             struct
6162             {
6163                 struct
6164                 {
6165                     regNumber     vlsrsBaseReg;
6166                     NATIVE_OFFSET vlsrsOffset;
6167                 } vlsrStk;
6168
6169                 regNumber vlsrReg;
6170             } vlStkReg;
6171
6172             // VLT_STK2 -- Any 64 bit value which is on the stack, in 2 successsive DWords
6173             // eg 2 DWords at [ESP+0x10]
6174
6175             struct
6176             {
6177                 regNumber     vls2BaseReg;
6178                 NATIVE_OFFSET vls2Offset;
6179             } vlStk2;
6180
6181             // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack)
6182             // eg. ST(3). Actually it is ST("FPstkHeight - vpFpStk")
6183
6184             struct
6185             {
6186                 unsigned vlfReg;
6187             } vlFPstk;
6188
6189             // VLT_FIXED_VA -- fixed argument of a varargs function.
6190             // The argument location depends on the size of the variable
6191             // arguments (...). Inspecting the VARARGS_HANDLE indicates the
6192             // location of the first arg. This argument can then be accessed
6193             // relative to the position of the first arg
6194
6195             struct
6196             {
6197                 unsigned vlfvOffset;
6198             } vlFixedVarArg;
6199
6200             // VLT_MEMORY
6201
6202             struct
6203             {
6204                 void* rpValue; // pointer to the in-process
6205                                // location of the value.
6206             } vlMemory;
6207         };
6208
6209         // Helper functions
6210
6211         bool vlIsInReg(regNumber reg);
6212         bool vlIsOnStk(regNumber reg, signed offset);
6213     };
6214
6215     /*************************************************************************/
6216
6217 public:
6218     // Get handles
6219
6220     void eeGetCallInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6221                        CORINFO_RESOLVED_TOKEN* pConstrainedToken,
6222                        CORINFO_CALLINFO_FLAGS  flags,
6223                        CORINFO_CALL_INFO*      pResult);
6224     inline CORINFO_CALLINFO_FLAGS addVerifyFlag(CORINFO_CALLINFO_FLAGS flags);
6225
6226     void eeGetFieldInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6227                         CORINFO_ACCESS_FLAGS    flags,
6228                         CORINFO_FIELD_INFO*     pResult);
6229
6230     // Get the flags
6231
6232     BOOL eeIsValueClass(CORINFO_CLASS_HANDLE clsHnd);
6233
6234 #if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD)
6235
6236     bool IsSuperPMIException(unsigned code)
6237     {
6238         // Copied from NDP\clr\src\ToolBox\SuperPMI\SuperPMI-Shared\ErrorHandling.h
6239
6240         const unsigned EXCEPTIONCODE_DebugBreakorAV = 0xe0421000;
6241         const unsigned EXCEPTIONCODE_MC             = 0xe0422000;
6242         const unsigned EXCEPTIONCODE_LWM            = 0xe0423000;
6243         const unsigned EXCEPTIONCODE_SASM           = 0xe0424000;
6244         const unsigned EXCEPTIONCODE_SSYM           = 0xe0425000;
6245         const unsigned EXCEPTIONCODE_CALLUTILS      = 0xe0426000;
6246         const unsigned EXCEPTIONCODE_TYPEUTILS      = 0xe0427000;
6247         const unsigned EXCEPTIONCODE_ASSERT         = 0xe0440000;
6248
6249         switch (code)
6250         {
6251             case EXCEPTIONCODE_DebugBreakorAV:
6252             case EXCEPTIONCODE_MC:
6253             case EXCEPTIONCODE_LWM:
6254             case EXCEPTIONCODE_SASM:
6255             case EXCEPTIONCODE_SSYM:
6256             case EXCEPTIONCODE_CALLUTILS:
6257             case EXCEPTIONCODE_TYPEUTILS:
6258             case EXCEPTIONCODE_ASSERT:
6259                 return true;
6260             default:
6261                 return false;
6262         }
6263     }
6264
6265     const char* eeGetMethodName(CORINFO_METHOD_HANDLE hnd, const char** className);
6266     const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd);
6267
6268     bool eeIsNativeMethod(CORINFO_METHOD_HANDLE method);
6269     CORINFO_METHOD_HANDLE eeGetMethodHandleForNative(CORINFO_METHOD_HANDLE method);
6270 #endif
6271
6272     var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6273     var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig, bool* isPinned);
6274     unsigned eeGetArgSize(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6275
6276     // VOM info, method sigs
6277
6278     void eeGetSig(unsigned               sigTok,
6279                   CORINFO_MODULE_HANDLE  scope,
6280                   CORINFO_CONTEXT_HANDLE context,
6281                   CORINFO_SIG_INFO*      retSig);
6282
6283     void eeGetCallSiteSig(unsigned               sigTok,
6284                           CORINFO_MODULE_HANDLE  scope,
6285                           CORINFO_CONTEXT_HANDLE context,
6286                           CORINFO_SIG_INFO*      retSig);
6287
6288     void eeGetMethodSig(CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* retSig, CORINFO_CLASS_HANDLE owner = nullptr);
6289
6290     // Method entry-points, instrs
6291
6292     void* eeGetFieldAddress(CORINFO_FIELD_HANDLE handle, void*** ppIndir);
6293
6294     CORINFO_METHOD_HANDLE eeMarkNativeTarget(CORINFO_METHOD_HANDLE method);
6295
6296     CORINFO_EE_INFO eeInfo;
6297     bool            eeInfoInitialized;
6298
6299     CORINFO_EE_INFO* eeGetEEInfo();
6300
6301     // Gets the offset of a SDArray's first element
6302     unsigned eeGetArrayDataOffset(var_types type);
6303     // Gets the offset of a MDArray's first element
6304     unsigned eeGetMDArrayDataOffset(var_types type, unsigned rank);
6305
6306     GenTreePtr eeGetPInvokeCookie(CORINFO_SIG_INFO* szMetaSig);
6307
6308     // Returns the page size for the target machine as reported by the EE.
6309     inline size_t eeGetPageSize()
6310     {
6311 #if COR_JIT_EE_VERSION > 460
6312         return eeGetEEInfo()->osPageSize;
6313 #else  // COR_JIT_EE_VERSION <= 460
6314         return CORINFO_PAGE_SIZE;
6315 #endif // COR_JIT_EE_VERSION > 460
6316     }
6317
6318     // Returns the frame size at which we will generate a loop to probe the stack.
6319     inline size_t getVeryLargeFrameSize()
6320     {
6321 #ifdef _TARGET_ARM_
6322         // The looping probe code is 40 bytes, whereas the straight-line probing for
6323         // the (0x2000..0x3000) case is 44, so use looping for anything 0x2000 bytes
6324         // or greater, to generate smaller code.
6325         return 2 * eeGetPageSize();
6326 #else
6327         return 3 * eeGetPageSize();
6328 #endif
6329     }
6330
6331     inline bool generateCFIUnwindCodes()
6332     {
6333 #if COR_JIT_EE_VERSION > 460 && defined(UNIX_AMD64_ABI)
6334         return eeGetEEInfo()->targetAbi == CORINFO_CORERT_ABI;
6335 #else
6336         return false;
6337 #endif
6338     }
6339
6340     // Exceptions
6341
6342     unsigned eeGetEHcount(CORINFO_METHOD_HANDLE handle);
6343
6344     // Debugging support - Line number info
6345
6346     void eeGetStmtOffsets();
6347
6348     unsigned eeBoundariesCount;
6349
6350     struct boundariesDsc
6351     {
6352         UNATIVE_OFFSET nativeIP;
6353         IL_OFFSET      ilOffset;
6354         unsigned       sourceReason;
6355     } * eeBoundaries; // Boundaries to report to EE
6356     void eeSetLIcount(unsigned count);
6357     void eeSetLIinfo(unsigned which, UNATIVE_OFFSET offs, unsigned srcIP, bool stkEmpty, bool callInstruction);
6358     void eeSetLIdone();
6359
6360 #ifdef DEBUG
6361     static void eeDispILOffs(IL_OFFSET offs);
6362     static void eeDispLineInfo(const boundariesDsc* line);
6363     void eeDispLineInfos();
6364 #endif // DEBUG
6365
6366     // Debugging support - Local var info
6367
6368     void eeGetVars();
6369
6370     unsigned eeVarsCount;
6371
6372     struct VarResultInfo
6373     {
6374         UNATIVE_OFFSET startOffset;
6375         UNATIVE_OFFSET endOffset;
6376         DWORD          varNumber;
6377         siVarLoc       loc;
6378     } * eeVars;
6379     void eeSetLVcount(unsigned count);
6380     void eeSetLVinfo(unsigned        which,
6381                      UNATIVE_OFFSET  startOffs,
6382                      UNATIVE_OFFSET  length,
6383                      unsigned        varNum,
6384                      unsigned        LVnum,
6385                      VarName         namex,
6386                      bool            avail,
6387                      const siVarLoc& loc);
6388     void eeSetLVdone();
6389
6390 #ifdef DEBUG
6391     void eeDispVar(ICorDebugInfo::NativeVarInfo* var);
6392     void eeDispVars(CORINFO_METHOD_HANDLE ftn, ULONG32 cVars, ICorDebugInfo::NativeVarInfo* vars);
6393 #endif // DEBUG
6394
6395     // ICorJitInfo wrappers
6396
6397     void eeReserveUnwindInfo(BOOL isFunclet, BOOL isColdCode, ULONG unwindSize);
6398
6399     void eeAllocUnwindInfo(BYTE*          pHotCode,
6400                            BYTE*          pColdCode,
6401                            ULONG          startOffset,
6402                            ULONG          endOffset,
6403                            ULONG          unwindSize,
6404                            BYTE*          pUnwindBlock,
6405                            CorJitFuncKind funcKind);
6406
6407     void eeSetEHcount(unsigned cEH);
6408
6409     void eeSetEHinfo(unsigned EHnumber, const CORINFO_EH_CLAUSE* clause);
6410
6411     WORD eeGetRelocTypeHint(void* target);
6412
6413     // ICorStaticInfo wrapper functions
6414
6415     bool eeTryResolveToken(CORINFO_RESOLVED_TOKEN* resolvedToken);
6416
6417 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
6418 #ifdef DEBUG
6419     static void dumpSystemVClassificationType(SystemVClassificationType ct);
6420 #endif // DEBUG
6421
6422     void eeGetSystemVAmd64PassStructInRegisterDescriptor(
6423         /*IN*/ CORINFO_CLASS_HANDLE                                  structHnd,
6424         /*OUT*/ SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr);
6425 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
6426
6427     template <typename ParamType>
6428     bool eeRunWithErrorTrap(void (*function)(ParamType*), ParamType* param)
6429     {
6430         return eeRunWithErrorTrapImp(reinterpret_cast<void (*)(void*)>(function), reinterpret_cast<void*>(param));
6431     }
6432
6433     bool eeRunWithErrorTrapImp(void (*function)(void*), void* param);
6434
6435     // Utility functions
6436
6437     const char* eeGetFieldName(CORINFO_FIELD_HANDLE fieldHnd, const char** classNamePtr = nullptr);
6438
6439 #if defined(DEBUG)
6440     const wchar_t* eeGetCPString(size_t stringHandle);
6441 #endif
6442
6443     const char* eeGetClassName(CORINFO_CLASS_HANDLE clsHnd);
6444
6445     static CORINFO_METHOD_HANDLE eeFindHelper(unsigned helper);
6446     static CorInfoHelpFunc eeGetHelperNum(CORINFO_METHOD_HANDLE method);
6447
6448     static fgWalkPreFn CountSharedStaticHelper;
6449     static bool IsSharedStaticHelper(GenTreePtr tree);
6450     static bool IsTreeAlwaysHoistable(GenTreePtr tree);
6451
6452     static CORINFO_FIELD_HANDLE eeFindJitDataOffs(unsigned jitDataOffs);
6453     // returns true/false if 'field' is a Jit Data offset
6454     static bool eeIsJitDataOffs(CORINFO_FIELD_HANDLE field);
6455     // returns a number < 0 if 'field' is not a Jit Data offset, otherwise the data offset (limited to 2GB)
6456     static int eeGetJitDataOffs(CORINFO_FIELD_HANDLE field);
6457
6458     /*****************************************************************************/
6459
6460 public:
6461     void tmpInit();
6462
6463     enum TEMP_USAGE_TYPE
6464     {
6465         TEMP_USAGE_FREE,
6466         TEMP_USAGE_USED
6467     };
6468
6469     static var_types tmpNormalizeType(var_types type);
6470     TempDsc* tmpGetTemp(var_types type); // get temp for the given type
6471     void tmpRlsTemp(TempDsc* temp);
6472     TempDsc* tmpFindNum(int temp, TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
6473
6474     void     tmpEnd();
6475     TempDsc* tmpListBeg(TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
6476     TempDsc* tmpListNxt(TempDsc* curTemp, TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
6477     void tmpDone();
6478
6479 #ifdef DEBUG
6480     bool tmpAllFree() const;
6481 #endif // DEBUG
6482
6483 #ifndef LEGACY_BACKEND
6484     void tmpPreAllocateTemps(var_types type, unsigned count);
6485 #endif // !LEGACY_BACKEND
6486
6487 protected:
6488 #ifdef LEGACY_BACKEND
6489     unsigned tmpIntSpillMax;    // number of int-sized spill temps
6490     unsigned tmpDoubleSpillMax; // number of double-sized spill temps
6491 #endif                          // LEGACY_BACKEND
6492
6493     unsigned tmpCount; // Number of temps
6494     unsigned tmpSize;  // Size of all the temps
6495 #ifdef DEBUG
6496 public:
6497     // Used by RegSet::rsSpillChk()
6498     unsigned tmpGetCount; // Temps which haven't been released yet
6499 #endif
6500 private:
6501     static unsigned tmpSlot(unsigned size); // which slot in tmpFree[] or tmpUsed[] to use
6502
6503     TempDsc* tmpFree[TEMP_MAX_SIZE / sizeof(int)];
6504     TempDsc* tmpUsed[TEMP_MAX_SIZE / sizeof(int)];
6505
6506     /*
6507     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6508     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6509     XX                                                                           XX
6510     XX                           CodeGenerator                                   XX
6511     XX                                                                           XX
6512     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6513     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6514     */
6515
6516 public:
6517     CodeGenInterface* codeGen;
6518
6519 #ifdef DEBUGGING_SUPPORT
6520
6521     //  The following holds information about instr offsets in terms of generated code.
6522
6523     struct IPmappingDsc
6524     {
6525         IPmappingDsc* ipmdNext;      // next line# record
6526         IL_OFFSETX    ipmdILoffsx;   // the instr offset
6527         emitLocation  ipmdNativeLoc; // the emitter location of the native code corresponding to the IL offset
6528         bool          ipmdIsLabel;   // Can this code be a branch label?
6529     };
6530
6531     // Record the instr offset mapping to the generated code
6532
6533     IPmappingDsc* genIPmappingList;
6534     IPmappingDsc* genIPmappingLast;
6535
6536     // Managed RetVal - A side hash table meant to record the mapping from a
6537     // GT_CALL node to its IL offset.  This info is used to emit sequence points
6538     // that can be used by debugger to determine the native offset at which the
6539     // managed RetVal will be available.
6540     //
6541     // In fact we can store IL offset in a GT_CALL node.  This was ruled out in
6542     // favor of a side table for two reasons: 1) We need IL offset for only those
6543     // GT_CALL nodes (created during importation) that correspond to an IL call and
6544     // whose return type is other than TYP_VOID. 2) GT_CALL node is a frequently used
6545     // structure and IL offset is needed only when generating debuggable code. Therefore
6546     // it is desirable to avoid memory size penalty in retail scenarios.
6547     typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, IL_OFFSETX, JitSimplerHashBehavior>
6548                            CallSiteILOffsetTable;
6549     CallSiteILOffsetTable* genCallSite2ILOffsetMap;
6550 #endif // DEBUGGING_SUPPORT
6551
6552     unsigned    genReturnLocal; // Local number for the return value when applicable.
6553     BasicBlock* genReturnBB;    // jumped to when not optimizing for speed.
6554
6555     // The following properties are part of CodeGenContext.  Getters are provided here for
6556     // convenience and backward compatibility, but the properties can only be set by invoking
6557     // the setter on CodeGenContext directly.
6558
6559     __declspec(property(get = getEmitter)) emitter* genEmitter;
6560     emitter* getEmitter()
6561     {
6562         return codeGen->getEmitter();
6563     }
6564
6565     const bool isFramePointerUsed()
6566     {
6567         return codeGen->isFramePointerUsed();
6568     }
6569
6570     __declspec(property(get = getInterruptible, put = setInterruptible)) bool genInterruptible;
6571     bool getInterruptible()
6572     {
6573         return codeGen->genInterruptible;
6574     }
6575     void setInterruptible(bool value)
6576     {
6577         codeGen->setInterruptible(value);
6578     }
6579
6580 #if DOUBLE_ALIGN
6581     const bool genDoubleAlign()
6582     {
6583         return codeGen->doDoubleAlign();
6584     }
6585     DWORD getCanDoubleAlign(); // Defined & used only by RegAlloc
6586 #endif                         // DOUBLE_ALIGN
6587     __declspec(property(get = getFullPtrRegMap, put = setFullPtrRegMap)) bool genFullPtrRegMap;
6588     bool getFullPtrRegMap()
6589     {
6590         return codeGen->genFullPtrRegMap;
6591     }
6592     void setFullPtrRegMap(bool value)
6593     {
6594         codeGen->setFullPtrRegMap(value);
6595     }
6596
6597 // Things that MAY belong either in CodeGen or CodeGenContext
6598
6599 #if FEATURE_EH_FUNCLETS
6600     FuncInfoDsc*   compFuncInfos;
6601     unsigned short compCurrFuncIdx;
6602     unsigned short compFuncInfoCount;
6603
6604     unsigned short compFuncCount()
6605     {
6606         assert(fgFuncletsCreated);
6607         return compFuncInfoCount;
6608     }
6609
6610 #else // !FEATURE_EH_FUNCLETS
6611
6612     // This is a no-op when there are no funclets!
6613     void genUpdateCurrentFunclet(BasicBlock* block)
6614     {
6615         return;
6616     }
6617
6618     FuncInfoDsc compFuncInfoRoot;
6619
6620     static const unsigned compCurrFuncIdx = 0;
6621
6622     unsigned short compFuncCount()
6623     {
6624         return 1;
6625     }
6626
6627 #endif // !FEATURE_EH_FUNCLETS
6628
6629     FuncInfoDsc* funCurrentFunc();
6630     void funSetCurrentFunc(unsigned funcIdx);
6631     FuncInfoDsc* funGetFunc(unsigned funcIdx);
6632     unsigned int funGetFuncIdx(BasicBlock* block);
6633
6634     // LIVENESS
6635
6636     VARSET_TP  compCurLife;     // current live variables
6637     GenTreePtr compCurLifeTree; // node after which compCurLife has been computed
6638
6639     template <bool ForCodeGen>
6640     void compChangeLife(VARSET_VALARG_TP newLife DEBUGARG(GenTreePtr tree));
6641
6642     void genChangeLife(VARSET_VALARG_TP newLife DEBUGARG(GenTreePtr tree))
6643     {
6644         compChangeLife</*ForCodeGen*/ true>(newLife DEBUGARG(tree));
6645     }
6646
6647     template <bool ForCodeGen>
6648     void compUpdateLife(GenTreePtr tree);
6649
6650     // Updates "compCurLife" to its state after evaluate of "true".  If "pLastUseVars" is
6651     // non-null, sets "*pLastUseVars" to the set of tracked variables for which "tree" was a last
6652     // use.  (Can be more than one var in the case of dependently promoted struct vars.)
6653     template <bool ForCodeGen>
6654     void compUpdateLifeVar(GenTreePtr tree, VARSET_TP* pLastUseVars = nullptr);
6655
6656     template <bool ForCodeGen>
6657     inline void compUpdateLife(VARSET_VALARG_TP newLife);
6658
6659     // Gets a register mask that represent the kill set for a helper call since
6660     // not all JIT Helper calls follow the standard ABI on the target architecture.
6661     regMaskTP compHelperCallKillSet(CorInfoHelpFunc helper);
6662
6663     // Gets a register mask that represent the kill set for a NoGC helper call.
6664     regMaskTP compNoGCHelperCallKillSet(CorInfoHelpFunc helper);
6665
6666 #ifdef _TARGET_ARM_
6667     // Requires that "varDsc" be a promoted struct local variable being passed as an argument, beginning at
6668     // "firstArgRegNum", which is assumed to have already been aligned to the register alignment restriction of the
6669     // struct type. Adds bits to "*pArgSkippedRegMask" for any argument registers *not* used in passing "varDsc" --
6670     // i.e., internal "holes" caused by internal alignment constraints.  For example, if the struct contained an int and
6671     // a double, and we at R0 (on ARM), then R1 would be skipped, and the bit for R1 would be added to the mask.
6672     void fgAddSkippedRegsInPromotedStructArg(LclVarDsc* varDsc, unsigned firstArgRegNum, regMaskTP* pArgSkippedRegMask);
6673 #endif // _TARGET_ARM_
6674
6675     // If "tree" is a indirection (GT_IND, or GT_OBJ) whose arg is an ADDR, whose arg is a LCL_VAR, return that LCL_VAR
6676     // node, else NULL.
6677     static GenTreePtr fgIsIndirOfAddrOfLocal(GenTreePtr tree);
6678
6679     // This is indexed by GT_OBJ nodes that are address of promoted struct variables, which
6680     // have been annotated with the GTF_VAR_DEATH flag.  If such a node is *not* mapped in this
6681     // table, one may assume that all the (tracked) field vars die at this point.  Otherwise,
6682     // the node maps to a pointer to a VARSET_TP, containing set bits for each of the tracked field
6683     // vars of the promoted struct local that go dead at the given node (the set bits are the bits
6684     // for the tracked var indices of the field vars, as in a live var set).
6685     NodeToVarsetPtrMap* m_promotedStructDeathVars;
6686
6687     NodeToVarsetPtrMap* GetPromotedStructDeathVars()
6688     {
6689         if (m_promotedStructDeathVars == nullptr)
6690         {
6691             m_promotedStructDeathVars = new (getAllocator()) NodeToVarsetPtrMap(getAllocator());
6692         }
6693         return m_promotedStructDeathVars;
6694     }
6695
6696 /*
6697 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6698 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6699 XX                                                                           XX
6700 XX                           UnwindInfo                                      XX
6701 XX                                                                           XX
6702 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6703 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6704 */
6705
6706 #if !defined(__GNUC__)
6707 #pragma region Unwind information
6708 #endif
6709
6710 public:
6711     //
6712     // Infrastructure functions: start/stop/reserve/emit.
6713     //
6714
6715     void unwindBegProlog();
6716     void unwindEndProlog();
6717     void unwindBegEpilog();
6718     void unwindEndEpilog();
6719     void unwindReserve();
6720     void unwindEmit(void* pHotCode, void* pColdCode);
6721
6722     //
6723     // Specific unwind information functions: called by code generation to indicate a particular
6724     // prolog or epilog unwindable instruction has been generated.
6725     //
6726
6727     void unwindPush(regNumber reg);
6728     void unwindAllocStack(unsigned size);
6729     void unwindSetFrameReg(regNumber reg, unsigned offset);
6730     void unwindSaveReg(regNumber reg, unsigned offset);
6731
6732 #if defined(_TARGET_ARM_)
6733     void unwindPushMaskInt(regMaskTP mask);
6734     void unwindPushMaskFloat(regMaskTP mask);
6735     void unwindPopMaskInt(regMaskTP mask);
6736     void unwindPopMaskFloat(regMaskTP mask);
6737     void unwindBranch16();                    // The epilog terminates with a 16-bit branch (e.g., "bx lr")
6738     void unwindNop(unsigned codeSizeInBytes); // Generate unwind NOP code. 'codeSizeInBytes' is 2 or 4 bytes. Only
6739                                               // called via unwindPadding().
6740     void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
6741                           // instruction and the current location.
6742 #endif                    // _TARGET_ARM_
6743
6744 #if defined(_TARGET_ARM64_)
6745     void unwindNop();
6746     void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
6747                           // instruction and the current location.
6748     void unwindSaveReg(regNumber reg, int offset);                                // str reg, [sp, #offset]
6749     void unwindSaveRegPreindexed(regNumber reg, int offset);                      // str reg, [sp, #offset]!
6750     void unwindSaveRegPair(regNumber reg1, regNumber reg2, int offset);           // stp reg1, reg2, [sp, #offset]
6751     void unwindSaveRegPairPreindexed(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]!
6752     void unwindSaveNext();                                                        // unwind code: save_next
6753     void unwindReturn(regNumber reg);                                             // ret lr
6754 #endif                                                                            // defined(_TARGET_ARM64_)
6755
6756     //
6757     // Private "helper" functions for the unwind implementation.
6758     //
6759
6760 private:
6761 #if FEATURE_EH_FUNCLETS
6762     void unwindGetFuncLocations(FuncInfoDsc*             func,
6763                                 bool                     getHotSectionData,
6764                                 /* OUT */ emitLocation** ppStartLoc,
6765                                 /* OUT */ emitLocation** ppEndLoc);
6766 #endif // FEATURE_EH_FUNCLETS
6767
6768     void unwindReserveFunc(FuncInfoDsc* func);
6769     void unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
6770
6771 #if defined(_TARGET_AMD64_)
6772
6773     void unwindReserveFuncHelper(FuncInfoDsc* func, bool isHotCode);
6774     void unwindEmitFuncHelper(FuncInfoDsc* func, void* pHotCode, void* pColdCode, bool isHotCode);
6775     UNATIVE_OFFSET unwindGetCurrentOffset(FuncInfoDsc* func);
6776
6777     void unwindBegPrologWindows();
6778     void unwindPushWindows(regNumber reg);
6779     void unwindAllocStackWindows(unsigned size);
6780     void unwindSetFrameRegWindows(regNumber reg, unsigned offset);
6781     void unwindSaveRegWindows(regNumber reg, unsigned offset);
6782
6783 #ifdef UNIX_AMD64_ABI
6784     void unwindBegPrologCFI();
6785     void unwindPushCFI(regNumber reg);
6786     void unwindAllocStackCFI(unsigned size);
6787     void unwindSetFrameRegCFI(regNumber reg, unsigned offset);
6788     void unwindSaveRegCFI(regNumber reg, unsigned offset);
6789     int mapRegNumToDwarfReg(regNumber reg);
6790     void createCfiCode(FuncInfoDsc* func, UCHAR codeOffset, UCHAR opcode, USHORT dwarfReg, INT offset = 0);
6791 #endif // UNIX_AMD64_ABI
6792 #elif defined(_TARGET_ARM_)
6793
6794     void unwindPushPopMaskInt(regMaskTP mask, bool useOpsize16);
6795     void unwindPushPopMaskFloat(regMaskTP mask);
6796     void unwindSplit(FuncInfoDsc* func);
6797
6798 #endif // _TARGET_ARM_
6799
6800 #if !defined(__GNUC__)
6801 #pragma endregion // Note: region is NOT under !defined(__GNUC__)
6802 #endif
6803
6804     /*
6805     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6806     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6807     XX                                                                           XX
6808     XX                               SIMD                                        XX
6809     XX                                                                           XX
6810     XX   Info about SIMD types, methods and the SIMD assembly (i.e. the assembly XX
6811     XX   that contains the distinguished, well-known SIMD type definitions).     XX
6812     XX                                                                           XX
6813     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6814     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6815     */
6816
6817     // Get highest available instruction set for floating point codegen
6818     InstructionSet getFloatingPointInstructionSet()
6819     {
6820 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
6821         if (canUseAVX())
6822         {
6823             return InstructionSet_AVX;
6824         }
6825
6826         // min bar is SSE2
6827         assert(canUseSSE2());
6828         return InstructionSet_SSE2;
6829 #else
6830         assert(!"getFPInstructionSet() is not implemented for target arch");
6831         unreached();
6832         return InstructionSet_NONE;
6833 #endif
6834     }
6835
6836     // Get highest available instruction set for SIMD codegen
6837     InstructionSet getSIMDInstructionSet()
6838     {
6839 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
6840         return getFloatingPointInstructionSet();
6841 #else
6842         assert(!"Available instruction set(s) for SIMD codegen is not defined for target arch");
6843         unreached();
6844         return InstructionSet_NONE;
6845 #endif
6846     }
6847
6848 #ifdef FEATURE_SIMD
6849
6850     // Should we support SIMD intrinsics?
6851     bool featureSIMD;
6852
6853     // This is a temp lclVar allocated on the stack as TYP_SIMD.  It is used to implement intrinsics
6854     // that require indexed access to the individual fields of the vector, which is not well supported
6855     // by the hardware.  It is allocated when/if such situations are encountered during Lowering.
6856     unsigned lvaSIMDInitTempVarNum;
6857
6858     // SIMD Types
6859     CORINFO_CLASS_HANDLE SIMDFloatHandle;
6860     CORINFO_CLASS_HANDLE SIMDDoubleHandle;
6861     CORINFO_CLASS_HANDLE SIMDIntHandle;
6862     CORINFO_CLASS_HANDLE SIMDUShortHandle;
6863     CORINFO_CLASS_HANDLE SIMDUByteHandle;
6864     CORINFO_CLASS_HANDLE SIMDShortHandle;
6865     CORINFO_CLASS_HANDLE SIMDByteHandle;
6866     CORINFO_CLASS_HANDLE SIMDLongHandle;
6867     CORINFO_CLASS_HANDLE SIMDUIntHandle;
6868     CORINFO_CLASS_HANDLE SIMDULongHandle;
6869     CORINFO_CLASS_HANDLE SIMDVector2Handle;
6870     CORINFO_CLASS_HANDLE SIMDVector3Handle;
6871     CORINFO_CLASS_HANDLE SIMDVector4Handle;
6872     CORINFO_CLASS_HANDLE SIMDVectorHandle;
6873
6874     // Get the handle for a SIMD type.
6875     CORINFO_CLASS_HANDLE gtGetStructHandleForSIMD(var_types simdType, var_types simdBaseType)
6876     {
6877         if (simdBaseType == TYP_FLOAT)
6878         {
6879             switch (simdType)
6880             {
6881                 case TYP_SIMD8:
6882                     return SIMDVector2Handle;
6883                 case TYP_SIMD12:
6884                     return SIMDVector3Handle;
6885                 case TYP_SIMD16:
6886                     if ((getSIMDVectorType() == TYP_SIMD32) || (SIMDVector4Handle != NO_CLASS_HANDLE))
6887                     {
6888                         return SIMDVector4Handle;
6889                     }
6890                     break;
6891                 case TYP_SIMD32:
6892                     break;
6893                 default:
6894                     unreached();
6895             }
6896         }
6897         assert(simdType == getSIMDVectorType());
6898         switch (simdBaseType)
6899         {
6900             case TYP_FLOAT:
6901                 return SIMDFloatHandle;
6902             case TYP_DOUBLE:
6903                 return SIMDDoubleHandle;
6904             case TYP_INT:
6905                 return SIMDIntHandle;
6906             case TYP_CHAR:
6907                 return SIMDUShortHandle;
6908             case TYP_USHORT:
6909                 return SIMDUShortHandle;
6910             case TYP_UBYTE:
6911                 return SIMDUByteHandle;
6912             case TYP_SHORT:
6913                 return SIMDShortHandle;
6914             case TYP_BYTE:
6915                 return SIMDByteHandle;
6916             case TYP_LONG:
6917                 return SIMDLongHandle;
6918             case TYP_UINT:
6919                 return SIMDUIntHandle;
6920             case TYP_ULONG:
6921                 return SIMDULongHandle;
6922             default:
6923                 assert(!"Didn't find a class handle for simdType");
6924         }
6925         return NO_CLASS_HANDLE;
6926     }
6927
6928     // SIMD Methods
6929     CORINFO_METHOD_HANDLE SIMDVectorFloat_set_Item;
6930     CORINFO_METHOD_HANDLE SIMDVectorFloat_get_Length;
6931     CORINFO_METHOD_HANDLE SIMDVectorFloat_op_Addition;
6932
6933     // Returns true if the tree corresponds to a TYP_SIMD lcl var.
6934     // Note that both SIMD vector args and locals are mared as lvSIMDType = true, but
6935     // type of an arg node is TYP_BYREF and a local node is TYP_SIMD or TYP_STRUCT.
6936     bool isSIMDTypeLocal(GenTree* tree)
6937     {
6938         return tree->OperIsLocal() && lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
6939     }
6940
6941     // Returns true if the type of the tree is a byref of TYP_SIMD
6942     bool isAddrOfSIMDType(GenTree* tree)
6943     {
6944         if (tree->TypeGet() == TYP_BYREF || tree->TypeGet() == TYP_I_IMPL)
6945         {
6946             switch (tree->OperGet())
6947             {
6948                 case GT_ADDR:
6949                     return varTypeIsSIMD(tree->gtGetOp1());
6950
6951                 case GT_LCL_VAR_ADDR:
6952                     return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
6953
6954                 default:
6955                     return isSIMDTypeLocal(tree);
6956             }
6957         }
6958
6959         return false;
6960     }
6961
6962     static bool isRelOpSIMDIntrinsic(SIMDIntrinsicID intrinsicId)
6963     {
6964         return (intrinsicId == SIMDIntrinsicEqual || intrinsicId == SIMDIntrinsicLessThan ||
6965                 intrinsicId == SIMDIntrinsicLessThanOrEqual || intrinsicId == SIMDIntrinsicGreaterThan ||
6966                 intrinsicId == SIMDIntrinsicGreaterThanOrEqual);
6967     }
6968
6969     // Returns base type of a TYP_SIMD local.
6970     // Returns TYP_UNKNOWN if the local is not TYP_SIMD.
6971     var_types getBaseTypeOfSIMDLocal(GenTree* tree)
6972     {
6973         if (isSIMDTypeLocal(tree))
6974         {
6975             return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvBaseType;
6976         }
6977
6978         return TYP_UNKNOWN;
6979     }
6980
6981     bool isSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
6982     {
6983         return info.compCompHnd->isInSIMDModule(clsHnd);
6984     }
6985
6986     bool isSIMDClass(typeInfo* pTypeInfo)
6987     {
6988         return pTypeInfo->IsStruct() && isSIMDClass(pTypeInfo->GetClassHandleForValueClass());
6989     }
6990
6991     // Get the base (element) type and size in bytes for a SIMD type. Returns TYP_UNKNOWN
6992     // if it is not a SIMD type or is an unsupported base type.
6993     var_types getBaseTypeAndSizeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd, unsigned* sizeBytes = nullptr);
6994
6995     var_types getBaseTypeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd)
6996     {
6997         return getBaseTypeAndSizeOfSIMDType(typeHnd, nullptr);
6998     }
6999
7000     // Get SIMD Intrinsic info given the method handle.
7001     // Also sets typeHnd, argCount, baseType and sizeBytes out params.
7002     const SIMDIntrinsicInfo* getSIMDIntrinsicInfo(CORINFO_CLASS_HANDLE* typeHnd,
7003                                                   CORINFO_METHOD_HANDLE methodHnd,
7004                                                   CORINFO_SIG_INFO*     sig,
7005                                                   bool                  isNewObj,
7006                                                   unsigned*             argCount,
7007                                                   var_types*            baseType,
7008                                                   unsigned*             sizeBytes);
7009
7010     // Pops and returns GenTree node from importers type stack.
7011     // Normalizes TYP_STRUCT value in case of GT_CALL, GT_RET_EXPR and arg nodes.
7012     GenTreePtr impSIMDPopStack(var_types type, bool expectAddr = false);
7013
7014     // Create a GT_SIMD tree for a Get property of SIMD vector with a fixed index.
7015     GenTreeSIMD* impSIMDGetFixed(var_types simdType, var_types baseType, unsigned simdSize, int index);
7016
7017     // Creates a GT_SIMD tree for Select operation
7018     GenTreePtr impSIMDSelect(CORINFO_CLASS_HANDLE typeHnd,
7019                              var_types            baseType,
7020                              unsigned             simdVectorSize,
7021                              GenTree*             op1,
7022                              GenTree*             op2,
7023                              GenTree*             op3);
7024
7025     // Creates a GT_SIMD tree for Min/Max operation
7026     GenTreePtr impSIMDMinMax(SIMDIntrinsicID      intrinsicId,
7027                              CORINFO_CLASS_HANDLE typeHnd,
7028                              var_types            baseType,
7029                              unsigned             simdVectorSize,
7030                              GenTree*             op1,
7031                              GenTree*             op2);
7032
7033     // Transforms operands and returns the SIMD intrinsic to be applied on
7034     // transformed operands to obtain given relop result.
7035     SIMDIntrinsicID impSIMDRelOp(SIMDIntrinsicID      relOpIntrinsicId,
7036                                  CORINFO_CLASS_HANDLE typeHnd,
7037                                  unsigned             simdVectorSize,
7038                                  var_types*           baseType,
7039                                  GenTree**            op1,
7040                                  GenTree**            op2);
7041
7042 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7043     // Transforms operands and returns the SIMD intrinsic to be applied on
7044     // transformed operands to obtain == comparison result.
7045     SIMDIntrinsicID impSIMDLongRelOpEqual(CORINFO_CLASS_HANDLE typeHnd,
7046                                           unsigned             simdVectorSize,
7047                                           GenTree**            op1,
7048                                           GenTree**            op2);
7049
7050     // Transforms operands and returns the SIMD intrinsic to be applied on
7051     // transformed operands to obtain > comparison result.
7052     SIMDIntrinsicID impSIMDLongRelOpGreaterThan(CORINFO_CLASS_HANDLE typeHnd,
7053                                                 unsigned             simdVectorSize,
7054                                                 GenTree**            op1,
7055                                                 GenTree**            op2);
7056
7057     // Transforms operands and returns the SIMD intrinsic to be applied on
7058     // transformed operands to obtain >= comparison result.
7059     SIMDIntrinsicID impSIMDLongRelOpGreaterThanOrEqual(CORINFO_CLASS_HANDLE typeHnd,
7060                                                        unsigned             simdVectorSize,
7061                                                        GenTree**            op1,
7062                                                        GenTree**            op2);
7063
7064     // Transforms operands and returns the SIMD intrinsic to be applied on
7065     // transformed operands to obtain >= comparison result in case of int32
7066     // and small int base type vectors.
7067     SIMDIntrinsicID impSIMDIntegralRelOpGreaterThanOrEqual(
7068         CORINFO_CLASS_HANDLE typeHnd, unsigned simdVectorSize, var_types baseType, GenTree** op1, GenTree** op2);
7069 #endif // defined(_TARGET_AMD64_) && !defined(LEGACY_BACKEND)
7070
7071     void setLclRelatedToSIMDIntrinsic(GenTreePtr tree);
7072     bool areFieldsContiguous(GenTreePtr op1, GenTreePtr op2);
7073     bool areArrayElementsContiguous(GenTreePtr op1, GenTreePtr op2);
7074     bool areArgumentsContiguous(GenTreePtr op1, GenTreePtr op2);
7075     GenTreePtr createAddressNodeForSIMDInit(GenTreePtr tree, unsigned simdSize);
7076
7077     // check methodHnd to see if it is a SIMD method that is expanded as an intrinsic in the JIT.
7078     GenTreePtr impSIMDIntrinsic(OPCODE                opcode,
7079                                 GenTreePtr            newobjThis,
7080                                 CORINFO_CLASS_HANDLE  clsHnd,
7081                                 CORINFO_METHOD_HANDLE method,
7082                                 CORINFO_SIG_INFO*     sig,
7083                                 int                   memberRef);
7084
7085     GenTreePtr getOp1ForConstructor(OPCODE opcode, GenTreePtr newobjThis, CORINFO_CLASS_HANDLE clsHnd);
7086
7087     // Whether SIMD vector occupies part of SIMD register.
7088     // SSE2: vector2f/3f are considered sub register SIMD types.
7089     // AVX: vector2f, 3f and 4f are all considered sub register SIMD types.
7090     bool isSubRegisterSIMDType(CORINFO_CLASS_HANDLE typeHnd)
7091     {
7092         unsigned  sizeBytes = 0;
7093         var_types baseType  = getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7094         return (baseType == TYP_FLOAT) && (sizeBytes < getSIMDVectorRegisterByteLength());
7095     }
7096
7097     bool isSubRegisterSIMDType(GenTreeSIMD* simdNode)
7098     {
7099         return (simdNode->gtSIMDSize < getSIMDVectorRegisterByteLength());
7100     }
7101
7102     // Get the type for the hardware SIMD vector.
7103     // This is the maximum SIMD type supported for this target.
7104     var_types getSIMDVectorType()
7105     {
7106 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7107         if (canUseAVX())
7108         {
7109             return TYP_SIMD32;
7110         }
7111         else
7112         {
7113             assert(canUseSSE2());
7114             return TYP_SIMD16;
7115         }
7116 #else
7117         assert(!"getSIMDVectorType() unimplemented on target arch");
7118         unreached();
7119 #endif
7120     }
7121
7122     // Get the size of the SIMD type in bytes
7123     int getSIMDTypeSizeInBytes(CORINFO_CLASS_HANDLE typeHnd)
7124     {
7125         unsigned sizeBytes = 0;
7126         (void)getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7127         return sizeBytes;
7128     }
7129
7130     // Get the the number of elements of basetype of SIMD vector given by its size and baseType
7131     static int getSIMDVectorLength(unsigned simdSize, var_types baseType);
7132
7133     // Get the the number of elements of basetype of SIMD vector given by its type handle
7134     int getSIMDVectorLength(CORINFO_CLASS_HANDLE typeHnd);
7135
7136     // Get preferred alignment of SIMD type.
7137     int getSIMDTypeAlignment(var_types simdType);
7138
7139     // Get the number of bytes in a SIMD Vector for the current compilation.
7140     unsigned getSIMDVectorRegisterByteLength()
7141     {
7142 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7143         if (canUseAVX())
7144         {
7145             return YMM_REGSIZE_BYTES;
7146         }
7147         else
7148         {
7149             assert(canUseSSE2());
7150             return XMM_REGSIZE_BYTES;
7151         }
7152 #else
7153         assert(!"getSIMDVectorRegisterByteLength() unimplemented on target arch");
7154         unreached();
7155 #endif
7156     }
7157
7158     // The minimum and maximum possible number of bytes in a SIMD vector.
7159     unsigned int maxSIMDStructBytes()
7160     {
7161         return getSIMDVectorRegisterByteLength();
7162     }
7163     unsigned int minSIMDStructBytes()
7164     {
7165         return emitTypeSize(TYP_SIMD8);
7166     }
7167
7168 #ifdef FEATURE_AVX_SUPPORT
7169     // (maxPossibleSIMDStructBytes is for use in a context that requires a compile-time constant.)
7170     static const unsigned maxPossibleSIMDStructBytes = 32;
7171 #else  // !FEATURE_AVX_SUPPORT
7172     static const unsigned maxPossibleSIMDStructBytes = 16;
7173 #endif // !FEATURE_AVX_SUPPORT
7174
7175     // Returns the codegen type for a given SIMD size.
7176     var_types getSIMDTypeForSize(unsigned size)
7177     {
7178         var_types simdType = TYP_UNDEF;
7179         if (size == 8)
7180         {
7181             simdType = TYP_SIMD8;
7182         }
7183         else if (size == 12)
7184         {
7185             simdType = TYP_SIMD12;
7186         }
7187         else if (size == 16)
7188         {
7189             simdType = TYP_SIMD16;
7190         }
7191 #ifdef FEATURE_AVX_SUPPORT
7192         else if (size == 32)
7193         {
7194             simdType = TYP_SIMD32;
7195         }
7196 #endif // FEATURE_AVX_SUPPORT
7197         else
7198         {
7199             noway_assert(!"Unexpected size for SIMD type");
7200         }
7201         return simdType;
7202     }
7203
7204     unsigned getSIMDInitTempVarNum()
7205     {
7206         if (lvaSIMDInitTempVarNum == BAD_VAR_NUM)
7207         {
7208             lvaSIMDInitTempVarNum                  = lvaGrabTempWithImplicitUse(false DEBUGARG("SIMDInitTempVar"));
7209             lvaTable[lvaSIMDInitTempVarNum].lvType = getSIMDVectorType();
7210         }
7211         return lvaSIMDInitTempVarNum;
7212     }
7213
7214 #endif // FEATURE_SIMD
7215
7216 public:
7217     //------------------------------------------------------------------------
7218     // largestEnregisterableStruct: The size in bytes of the largest struct that can be enregistered.
7219     //
7220     // Notes: It is not guaranteed that the struct of this size or smaller WILL be a
7221     //        candidate for enregistration.
7222
7223     unsigned largestEnregisterableStructSize()
7224     {
7225 #ifdef FEATURE_SIMD
7226         unsigned vectorRegSize = getSIMDVectorRegisterByteLength();
7227         if (vectorRegSize > TARGET_POINTER_SIZE)
7228         {
7229             return vectorRegSize;
7230         }
7231         else
7232 #endif // FEATURE_SIMD
7233         {
7234             return TARGET_POINTER_SIZE;
7235         }
7236     }
7237
7238 private:
7239     // These routines need not be enclosed under FEATURE_SIMD since lvIsSIMDType()
7240     // is defined for both FEATURE_SIMD and !FEATURE_SIMD apropriately. The use
7241     // of this routines also avoids the need of #ifdef FEATURE_SIMD specific code.
7242
7243     // Is this var is of type simd struct?
7244     bool lclVarIsSIMDType(unsigned varNum)
7245     {
7246         LclVarDsc* varDsc = lvaTable + varNum;
7247         return varDsc->lvIsSIMDType();
7248     }
7249
7250     // Is this Local node a SIMD local?
7251     bool lclVarIsSIMDType(GenTreeLclVarCommon* lclVarTree)
7252     {
7253         return lclVarIsSIMDType(lclVarTree->gtLclNum);
7254     }
7255
7256     // Returns true if the TYP_SIMD locals on stack are aligned at their
7257     // preferred byte boundary specified by getSIMDTypeAlignment().
7258     bool isSIMDTypeLocalAligned(unsigned varNum)
7259     {
7260 #if defined(FEATURE_SIMD) && ALIGN_SIMD_TYPES
7261         if (lclVarIsSIMDType(varNum) && lvaTable[varNum].lvType != TYP_BYREF)
7262         {
7263             bool ebpBased;
7264             int  off = lvaFrameAddress(varNum, &ebpBased);
7265             // TODO-Cleanup: Can't this use the lvExactSize on the varDsc?
7266             int  alignment = getSIMDTypeAlignment(lvaTable[varNum].lvType);
7267             bool isAligned = ((off % alignment) == 0);
7268             noway_assert(isAligned || lvaTable[varNum].lvIsParam);
7269             return isAligned;
7270         }
7271 #endif // FEATURE_SIMD
7272
7273         return false;
7274     }
7275
7276     // Whether SSE2 is available
7277     bool canUseSSE2() const
7278     {
7279 #ifdef _TARGET_XARCH_
7280         return opts.compCanUseSSE2;
7281 #else
7282         return false;
7283 #endif
7284     }
7285
7286     bool canUseAVX() const
7287     {
7288 #ifdef FEATURE_AVX_SUPPORT
7289         return opts.compCanUseAVX;
7290 #else
7291         return false;
7292 #endif
7293     }
7294
7295     /*
7296     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7297     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7298     XX                                                                           XX
7299     XX                           Compiler                                        XX
7300     XX                                                                           XX
7301     XX   Generic info about the compilation and the method being compiled.       XX
7302     XX   It is responsible for driving the other phases.                         XX
7303     XX   It is also responsible for all the memory management.                   XX
7304     XX                                                                           XX
7305     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7306     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7307     */
7308
7309 public:
7310     Compiler* InlineeCompiler; // The Compiler instance for the inlinee
7311
7312     InlineResult* compInlineResult; // The result of importing the inlinee method.
7313
7314     bool compDoAggressiveInlining; // If true, mark every method as CORINFO_FLG_FORCEINLINE
7315     bool compJmpOpUsed;            // Does the method do a JMP
7316     bool compLongUsed;             // Does the method use TYP_LONG
7317     bool compFloatingPointUsed;    // Does the method use TYP_FLOAT or TYP_DOUBLE
7318     bool compTailCallUsed;         // Does the method do a tailcall
7319     bool compLocallocUsed;         // Does the method use localloc.
7320     bool compQmarkUsed;            // Does the method use GT_QMARK/GT_COLON
7321     bool compQmarkRationalized;    // Is it allowed to use a GT_QMARK/GT_COLON node.
7322     bool compUnsafeCastUsed;       // Does the method use LDIND/STIND to cast between scalar/refernce types
7323
7324     // NOTE: These values are only reliable after
7325     //       the importing is completely finished.
7326
7327     ExpandArrayStack<GenTreePtr>* compQMarks; // The set of QMark nodes created in the current compilation, so
7328                                               // we can iterate over these efficiently.
7329
7330 #if CPU_USES_BLOCK_MOVE
7331     bool compBlkOpUsed; // Does the method do a COPYBLK or INITBLK
7332 #endif
7333
7334 #ifdef DEBUG
7335     // State information - which phases have completed?
7336     // These are kept together for easy discoverability
7337
7338     bool    bRangeAllowStress;
7339     bool    compCodeGenDone;
7340     int64_t compNumStatementLinksTraversed; // # of links traversed while doing debug checks
7341     bool    fgNormalizeEHDone;              // Has the flowgraph EH normalization phase been done?
7342     size_t  compSizeEstimate;               // The estimated size of the method as per `gtSetEvalOrder`.
7343     size_t  compCycleEstimate;              // The estimated cycle count of the method as per `gtSetEvalOrder`
7344 #endif                                      // DEBUG
7345
7346     bool fgLocalVarLivenessDone; // Note that this one is used outside of debug.
7347     bool fgLocalVarLivenessChanged;
7348 #if STACK_PROBES
7349     bool compStackProbePrologDone;
7350 #endif
7351 #ifndef LEGACY_BACKEND
7352     bool compLSRADone;
7353 #endif // !LEGACY_BACKEND
7354     bool compRationalIRForm;
7355
7356     bool compUsesThrowHelper; // There is a call to a THOROW_HELPER for the compiled method.
7357
7358     bool compGeneratingProlog;
7359     bool compGeneratingEpilog;
7360     bool compNeedsGSSecurityCookie; // There is an unsafe buffer (or localloc) on the stack.
7361                                     // Insert cookie on frame and code to check the cookie, like VC++ -GS.
7362     bool compGSReorderStackLayout;  // There is an unsafe buffer on the stack, reorder locals and make local
7363     // copies of susceptible parameters to avoid buffer overrun attacks through locals/params
7364     bool getNeedsGSSecurityCookie() const
7365     {
7366         return compNeedsGSSecurityCookie;
7367     }
7368     void setNeedsGSSecurityCookie()
7369     {
7370         compNeedsGSSecurityCookie = true;
7371     }
7372
7373     FrameLayoutState lvaDoneFrameLayout; // The highest frame layout state that we've completed. During
7374                                          // frame layout calculations, this is the level we are currently
7375                                          // computing.
7376
7377     //---------------------------- JITing options -----------------------------
7378
7379     enum codeOptimize
7380     {
7381         BLENDED_CODE,
7382         SMALL_CODE,
7383         FAST_CODE,
7384
7385         COUNT_OPT_CODE
7386     };
7387
7388     struct Options
7389     {
7390         CORJIT_FLAGS* jitFlags;  // all flags passed from the EE
7391         unsigned      eeFlags;   // CorJitFlag flags passed from the EE
7392         unsigned      compFlags; // method attributes
7393
7394         codeOptimize compCodeOpt; // what type of code optimizations
7395
7396         bool compUseFCOMI;
7397         bool compUseCMOV;
7398 #ifdef _TARGET_XARCH_
7399         bool compCanUseSSE2; // Allow CodeGen to use "movq XMM" instructions
7400
7401 #ifdef FEATURE_AVX_SUPPORT
7402         bool compCanUseAVX; // Allow CodeGen to use AVX 256-bit vectors for SIMD operations
7403 #endif
7404 #endif
7405
7406 // optimize maximally and/or favor speed over size?
7407
7408 #define DEFAULT_MIN_OPTS_CODE_SIZE 60000
7409 #define DEFAULT_MIN_OPTS_INSTR_COUNT 20000
7410 #define DEFAULT_MIN_OPTS_BB_COUNT 2000
7411 #define DEFAULT_MIN_OPTS_LV_NUM_COUNT 2000
7412 #define DEFAULT_MIN_OPTS_LV_REF_COUNT 8000
7413
7414 // Maximun number of locals before turning off the inlining
7415 #define MAX_LV_NUM_COUNT_FOR_INLINING 512
7416
7417         bool     compMinOpts;
7418         unsigned instrCount;
7419         unsigned lvRefCount;
7420         bool     compMinOptsIsSet;
7421 #ifdef DEBUG
7422         bool compMinOptsIsUsed;
7423
7424         inline bool MinOpts()
7425         {
7426             assert(compMinOptsIsSet);
7427             compMinOptsIsUsed = true;
7428             return compMinOpts;
7429         }
7430         inline bool IsMinOptsSet()
7431         {
7432             return compMinOptsIsSet;
7433         }
7434 #else  // !DEBUG
7435         inline bool MinOpts()
7436         {
7437             return compMinOpts;
7438         }
7439         inline bool IsMinOptsSet()
7440         {
7441             return compMinOptsIsSet;
7442         }
7443 #endif // !DEBUG
7444         inline void SetMinOpts(bool val)
7445         {
7446             assert(!compMinOptsIsUsed);
7447             assert(!compMinOptsIsSet || (compMinOpts == val));
7448             compMinOpts      = val;
7449             compMinOptsIsSet = true;
7450         }
7451
7452         // true if the CLFLG_* for an optimization is set.
7453         inline bool OptEnabled(unsigned optFlag)
7454         {
7455             return !!(compFlags & optFlag);
7456         }
7457
7458 #ifdef FEATURE_READYTORUN_COMPILER
7459         inline bool IsReadyToRun()
7460         {
7461             return (eeFlags & CORJIT_FLG_READYTORUN) != 0;
7462         }
7463 #else
7464         inline bool IsReadyToRun()
7465         {
7466             return false;
7467         }
7468 #endif
7469
7470         // true if we should use the PINVOKE_{BEGIN,END} helpers instead of generating
7471         // PInvoke transitions inline (e.g. when targeting CoreRT).
7472         inline bool ShouldUsePInvokeHelpers()
7473         {
7474 #if COR_JIT_EE_VERSION > 460
7475             return (jitFlags->corJitFlags2 & CORJIT_FLG2_USE_PINVOKE_HELPERS) != 0;
7476 #else
7477             return false;
7478 #endif
7479         }
7480
7481         // true if we should use insert the REVERSE_PINVOKE_{ENTER,EXIT} helpers in the method
7482         // prolog/epilog
7483         inline bool IsReversePInvoke()
7484         {
7485 #if COR_JIT_EE_VERSION > 460
7486             return (jitFlags->corJitFlags2 & CORJIT_FLG2_REVERSE_PINVOKE) != 0;
7487 #else
7488             return false;
7489 #endif
7490         }
7491
7492         // true if we must generate code compatible with JIT32 quirks
7493         inline bool IsJit32Compat()
7494         {
7495 #if defined(_TARGET_X86_) && COR_JIT_EE_VERSION > 460
7496             return (jitFlags->corJitFlags2 & CORJIT_FLG2_DESKTOP_QUIRKS) != 0;
7497 #else
7498             return false;
7499 #endif
7500         }
7501
7502         // true if we must generate code compatible with Jit64 quirks
7503         inline bool IsJit64Compat()
7504         {
7505 #if defined(_TARGET_AMD64_) && COR_JIT_EE_VERSION > 460
7506             return (jitFlags->corJitFlags2 & CORJIT_FLG2_DESKTOP_QUIRKS) != 0;
7507 #elif defined(_TARGET_AMD64_) && !defined(FEATURE_CORECLR)
7508             return true;
7509 #else
7510             return false;
7511 #endif
7512         }
7513
7514 #ifdef DEBUGGING_SUPPORT
7515         bool compScopeInfo; // Generate the LocalVar info ?
7516         bool compDbgCode;   // Generate debugger-friendly code?
7517         bool compDbgInfo;   // Gather debugging info?
7518         bool compDbgEnC;
7519 #else
7520         static const bool compDbgCode;
7521 #endif
7522
7523 #ifdef PROFILING_SUPPORTED
7524         bool compNoPInvokeInlineCB;
7525 #else
7526         static const bool compNoPInvokeInlineCB;
7527 #endif
7528
7529         bool compMustInlinePInvokeCalli; // Unmanaged CALLI in IL stubs must be inlined
7530
7531 #ifdef DEBUG
7532         bool compGcChecks;         // Check arguments and return values to ensure they are sane
7533         bool compStackCheckOnRet;  // Check ESP on return to ensure it is correct
7534         bool compStackCheckOnCall; // Check ESP after every call to ensure it is correct
7535
7536 #endif
7537
7538         bool compNeedSecurityCheck; // This flag really means where or not a security object needs
7539                                     // to be allocated on the stack.
7540                                     // It will be set to true in the following cases:
7541                                     //   1. When the method being compiled has a declarative security
7542                                     //        (i.e. when CORINFO_FLG_NOSECURITYWRAP is reset for the current method).
7543                                     //        This is also the case when we inject a prolog and epilog in the method.
7544                                     //   (or)
7545                                     //   2. When the method being compiled has imperative security (i.e. the method
7546                                     //        calls into another method that has CORINFO_FLG_SECURITYCHECK flag set).
7547                                     //   (or)
7548                                     //   3. When opts.compDbgEnC is true. (See also Compiler::compCompile).
7549                                     //
7550 // When this flag is set, jit will allocate a gc-reference local variable (lvaSecurityObject),
7551 // which gets reported as a GC root to stackwalker.
7552 // (See also ICodeManager::GetAddrOfSecurityObject.)
7553
7554 #if RELOC_SUPPORT
7555         bool compReloc;
7556 #endif
7557
7558 #ifdef DEBUG
7559 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7560         bool compEnablePCRelAddr; // Whether absolute addr be encoded as PC-rel offset by RyuJIT where possible
7561 #endif
7562 #endif // DEBUG
7563
7564 #ifdef UNIX_AMD64_ABI
7565         // This flag  is indicating if there is a need to align the frame.
7566         // On AMD64-Windows, if there are calls, 4 slots for the outgoing ars are allocated, except for
7567         // FastTailCall. This slots makes the frame size non-zero, so alignment logic will be called.
7568         // On AMD64-Unix, there are no such slots. There is a possibility to have calls in the method with frame size of
7569         // 0. The frame alignment logic won't kick in. This flags takes care of the AMD64-Unix case by remembering that
7570         // there are calls and making sure the frame alignment logic is executed.
7571         bool compNeedToAlignFrame;
7572 #endif // UNIX_AMD64_ABI
7573
7574         bool compProcedureSplitting; // Separate cold code from hot code
7575
7576         bool genFPorder; // Preserve FP order (operations are non-commutative)
7577         bool genFPopt;   // Can we do frame-pointer-omission optimization?
7578         bool altJit;     // True if we are an altjit and are compiling this method
7579
7580 #ifdef DEBUG
7581         bool compProcedureSplittingEH; // Separate cold code from hot code for functions with EH
7582         bool dspCode;                  // Display native code generated
7583         bool dspEHTable;               // Display the EH table reported to the VM
7584         bool dspInstrs;                // Display the IL instructions intermixed with the native code output
7585         bool dspEmit;                  // Display emitter output
7586         bool dspLines;                 // Display source-code lines intermixed with native code output
7587         bool dmpHex;                   // Display raw bytes in hex of native code output
7588         bool varNames;                 // Display variables names in native code output
7589         bool disAsm;                   // Display native code as it is generated
7590         bool disAsmSpilled;            // Display native code when any register spilling occurs
7591         bool disDiffable;              // Makes the Disassembly code 'diff-able'
7592         bool disAsm2;                  // Display native code after it is generated using external disassembler
7593         bool dspOrder;                 // Display names of each of the methods that we ngen/jit
7594         bool dspUnwind;                // Display the unwind info output
7595         bool dspDiffable;     // Makes the Jit Dump 'diff-able' (currently uses same COMPlus_* flag as disDiffable)
7596         bool compLongAddress; // Force using large pseudo instructions for long address
7597                               // (IF_LARGEJMP/IF_LARGEADR/IF_LARGLDC)
7598         bool dspGCtbls;       // Display the GC tables
7599 #endif
7600
7601 #ifdef LATE_DISASM
7602         bool doLateDisasm; // Run the late disassembler
7603 #endif                     // LATE_DISASM
7604
7605 #if DUMP_GC_TABLES && !defined(DEBUG) && defined(JIT32_GCENCODER)
7606 // Only the JIT32_GCENCODER implements GC dumping in non-DEBUG code.
7607 #pragma message("NOTE: this non-debug build has GC ptr table dumping always enabled!")
7608         static const bool dspGCtbls = true;
7609 #endif
7610
7611         // We need stack probes to guarantee that we won't trigger a stack overflow
7612         // when calling unmanaged code until they get a chance to set up a frame, because
7613         // the EE will have no idea where it is.
7614         //
7615         // We will only be doing this currently for hosted environments. Unfortunately
7616         // we need to take care of stubs, so potentially, we will have to do the probes
7617         // for any call. We have a plan for not needing for stubs though
7618         bool compNeedStackProbes;
7619
7620         // Whether to emit Enter/Leave/TailCall hooks using a dummy stub (DummyProfilerELTStub())
7621         // This options helps one to make JIT behave as if it is under profiler.
7622         bool compJitELTHookEnabled;
7623
7624 #if FEATURE_TAILCALL_OPT
7625         // Whether opportunistic or implicit tail call optimization is enabled.
7626         bool compTailCallOpt;
7627         // Whether optimization of transforming a recursive tail call into a loop is enabled.
7628         bool compTailCallLoopOpt;
7629 #endif
7630
7631 #ifdef ARM_SOFTFP
7632         static const bool compUseSoftFP = true;
7633 #else // !ARM_SOFTFP
7634         static const bool compUseSoftFP = false;
7635 #endif
7636
7637         GCPollType compGCPollType;
7638     } opts;
7639
7640 #ifdef ALT_JIT
7641     static bool                s_pAltJitExcludeAssembliesListInitialized;
7642     static AssemblyNamesList2* s_pAltJitExcludeAssembliesList;
7643 #endif // ALT_JIT
7644
7645 #ifdef DEBUG
7646
7647     static bool s_dspMemStats; // Display per-phase memory statistics for every function
7648
7649     template <typename T>
7650     T dspPtr(T p)
7651     {
7652         return (p == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : p);
7653     }
7654
7655     template <typename T>
7656     T dspOffset(T o)
7657     {
7658         return (o == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : o);
7659     }
7660
7661     static int dspTreeID(GenTree* tree)
7662     {
7663         return tree->gtTreeID;
7664     }
7665     static void printTreeID(GenTree* tree)
7666     {
7667         if (tree == nullptr)
7668         {
7669             printf("[------]");
7670         }
7671         else
7672         {
7673             printf("[%06d]", dspTreeID(tree));
7674         }
7675     }
7676
7677 #endif // DEBUG
7678
7679 // clang-format off
7680 #define STRESS_MODES                                                                            \
7681                                                                                                 \
7682         STRESS_MODE(NONE)                                                                       \
7683                                                                                                 \
7684         /* "Variations" stress areas which we try to mix up with each other. */                 \
7685         /* These should not be exhaustively used as they might */                               \
7686         /* hide/trivialize other areas */                                                       \
7687                                                                                                 \
7688         STRESS_MODE(REGS) STRESS_MODE(DBL_ALN) STRESS_MODE(LCL_FLDS) STRESS_MODE(UNROLL_LOOPS)  \
7689         STRESS_MODE(MAKE_CSE) STRESS_MODE(LEGACY_INLINE) STRESS_MODE(CLONE_EXPR)                \
7690         STRESS_MODE(USE_FCOMI) STRESS_MODE(USE_CMOV) STRESS_MODE(FOLD)                          \
7691         STRESS_MODE(BB_PROFILE) STRESS_MODE(OPT_BOOLS_GC) STRESS_MODE(REMORPH_TREES)            \
7692         STRESS_MODE(64RSLT_MUL) STRESS_MODE(DO_WHILE_LOOPS) STRESS_MODE(MIN_OPTS)               \
7693         STRESS_MODE(REVERSE_FLAG)     /* Will set GTF_REVERSE_OPS whenever we can */            \
7694         STRESS_MODE(REVERSE_COMMA)    /* Will reverse commas created  with gtNewCommaNode */    \
7695         STRESS_MODE(TAILCALL)         /* Will make the call as a tailcall whenever legal */     \
7696         STRESS_MODE(CATCH_ARG)        /* Will spill catch arg */                                \
7697         STRESS_MODE(UNSAFE_BUFFER_CHECKS)                                                       \
7698         STRESS_MODE(NULL_OBJECT_CHECK)                                                          \
7699         STRESS_MODE(PINVOKE_RESTORE_ESP)                                                        \
7700         STRESS_MODE(RANDOM_INLINE)                                                              \
7701                                                                                                 \
7702         STRESS_MODE(GENERIC_VARN) STRESS_MODE(COUNT_VARN)                                       \
7703                                                                                                 \
7704         /* "Check" stress areas that can be exhaustively used if we */                          \
7705         /*  dont care about performance at all */                                               \
7706                                                                                                 \
7707         STRESS_MODE(FORCE_INLINE) /* Treat every method as AggressiveInlining */                \
7708         STRESS_MODE(CHK_FLOW_UPDATE)                                                            \
7709         STRESS_MODE(EMITTER) STRESS_MODE(CHK_REIMPORT) STRESS_MODE(FLATFP)                      \
7710                                                                                                 \
7711         STRESS_MODE(GENERIC_CHECK) STRESS_MODE(COUNT)                                           \
7712
7713     enum                compStressArea
7714     {
7715 #define STRESS_MODE(mode) STRESS_##mode,
7716         STRESS_MODES
7717 #undef STRESS_MODE
7718     };
7719 // clang-format on
7720
7721 #ifdef DEBUG
7722     static const LPCWSTR s_compStressModeNames[STRESS_COUNT + 1];
7723     BYTE                 compActiveStressModes[STRESS_COUNT];
7724 #endif // DEBUG
7725
7726 #define MAX_STRESS_WEIGHT 100
7727
7728     bool compStressCompile(compStressArea stressArea, unsigned weightPercentage);
7729
7730 #ifdef DEBUG
7731
7732     bool compInlineStress()
7733     {
7734         return compStressCompile(STRESS_LEGACY_INLINE, 50);
7735     }
7736
7737     bool compRandomInlineStress()
7738     {
7739         return compStressCompile(STRESS_RANDOM_INLINE, 50);
7740     }
7741
7742 #endif // DEBUG
7743
7744     bool compTailCallStress()
7745     {
7746 #ifdef DEBUG
7747         return (JitConfig.TailcallStress() != 0 || compStressCompile(STRESS_TAILCALL, 5));
7748 #else
7749         return false;
7750 #endif
7751     }
7752
7753     codeOptimize compCodeOpt()
7754     {
7755 #if 0
7756         // Switching between size & speed has measurable throughput impact 
7757         // (3.5% on NGen mscorlib when measured). It used to be enabled for 
7758         // DEBUG, but should generate identical code between CHK & RET builds,
7759         // so that's not acceptable.
7760         // TODO-Throughput: Figure out what to do about size vs. speed & throughput.
7761         //                  Investigate the cause of the throughput regression.
7762
7763         return opts.compCodeOpt;
7764 #else
7765         return BLENDED_CODE;
7766 #endif
7767     }
7768
7769 #ifdef DEBUG
7770     CLRRandom* inlRNG;
7771 #endif
7772
7773     //--------------------- Info about the procedure --------------------------
7774
7775     struct Info
7776     {
7777         COMP_HANDLE           compCompHnd;
7778         CORINFO_MODULE_HANDLE compScopeHnd;
7779         CORINFO_CLASS_HANDLE  compClassHnd;
7780         CORINFO_METHOD_HANDLE compMethodHnd;
7781         CORINFO_METHOD_INFO*  compMethodInfo;
7782
7783         BOOL hasCircularClassConstraints;
7784         BOOL hasCircularMethodConstraints;
7785
7786 #if defined(DEBUG) || defined(LATE_DISASM)
7787         const char* compMethodName;
7788         const char* compClassName;
7789         const char* compFullName;
7790 #endif // defined(DEBUG) || defined(LATE_DISASM)
7791
7792 #if defined(DEBUG) || defined(INLINE_DATA)
7793         // Method hash is logcally const, but computed
7794         // on first demand.
7795         mutable unsigned compMethodHashPrivate;
7796         unsigned         compMethodHash() const;
7797 #endif // defined(DEBUG) || defined(INLINE_DATA)
7798
7799 #ifdef PSEUDORANDOM_NOP_INSERTION
7800         // things for pseudorandom nop insertion
7801         unsigned  compChecksum;
7802         CLRRandom compRNG;
7803 #endif
7804
7805         // The following holds the FLG_xxxx flags for the method we're compiling.
7806         unsigned compFlags;
7807
7808         // The following holds the class attributes for the method we're compiling.
7809         unsigned compClassAttr;
7810
7811         const BYTE*    compCode;
7812         IL_OFFSET      compILCodeSize;     // The IL code size
7813         UNATIVE_OFFSET compNativeCodeSize; // The native code size, after instructions are issued. This
7814                                            // is less than (compTotalHotCodeSize + compTotalColdCodeSize) only if:
7815         // (1) the code is not hot/cold split, and we issued less code than we expected, or
7816         // (2) the code is hot/cold split, and we issued less code than we expected
7817         // in the cold section (the hot section will always be padded out to compTotalHotCodeSize).
7818
7819         bool compIsStatic : 1;         // Is the method static (no 'this' pointer)?
7820         bool compIsVarArgs : 1;        // Does the method have varargs parameters?
7821         bool compIsContextful : 1;     // contextful method
7822         bool compInitMem : 1;          // Is the CORINFO_OPT_INIT_LOCALS bit set in the method info options?
7823         bool compUnwrapContextful : 1; // JIT should unwrap proxies when possible
7824         bool compProfilerCallback : 1; // JIT inserted a profiler Enter callback
7825         bool compPublishStubParam : 1; // EAX captured in prolog will be available through an instrinsic
7826         bool compRetBuffDefStack : 1;  // The ret buff argument definitely points into the stack.
7827
7828         var_types compRetType;       // Return type of the method as declared in IL
7829         var_types compRetNativeType; // Normalized return type as per target arch ABI
7830         unsigned  compILargsCount;   // Number of arguments (incl. implicit but not hidden)
7831         unsigned  compArgsCount;     // Number of arguments (incl. implicit and     hidden)
7832         unsigned  compRetBuffArg;    // position of hidden return param var (0, 1) (BAD_VAR_NUM means not present);
7833         int compTypeCtxtArg; // position of hidden param for type context for generic code (CORINFO_CALLCONV_PARAMTYPE)
7834         unsigned       compThisArg; // position of implicit this pointer param (not to be confused with lvaArg0Var)
7835         unsigned       compILlocalsCount; // Number of vars : args + locals (incl. implicit but not hidden)
7836         unsigned       compLocalsCount;   // Number of vars : args + locals (incl. implicit and     hidden)
7837         unsigned       compMaxStack;
7838         UNATIVE_OFFSET compTotalHotCodeSize;  // Total number of bytes of Hot Code in the method
7839         UNATIVE_OFFSET compTotalColdCodeSize; // Total number of bytes of Cold Code in the method
7840
7841         unsigned compCallUnmanaged;   // count of unmanaged calls
7842         unsigned compLvFrameListRoot; // lclNum for the Frame root
7843         unsigned compXcptnsCount;     // Number of exception-handling clauses read in the method's IL.
7844                                       // You should generally use compHndBBtabCount instead: it is the
7845                                       // current number of EH clauses (after additions like synchronized
7846                                       // methods and funclets, and removals like unreachable code deletion).
7847
7848         bool compMatchedVM; // true if the VM is "matched": either the JIT is a cross-compiler
7849                             // and the VM expects that, or the JIT is a "self-host" compiler
7850                             // (e.g., x86 hosted targeting x86) and the VM expects that.
7851
7852 #if defined(DEBUGGING_SUPPORT) || defined(DEBUG)
7853
7854         /*  The following holds IL scope information about local variables.
7855          */
7856
7857         unsigned     compVarScopesCount;
7858         VarScopeDsc* compVarScopes;
7859
7860         /* The following holds information about instr offsets for
7861          * which we need to report IP-mappings
7862          */
7863
7864         IL_OFFSET*                   compStmtOffsets; // sorted
7865         unsigned                     compStmtOffsetsCount;
7866         ICorDebugInfo::BoundaryTypes compStmtOffsetsImplicit;
7867
7868 #endif // DEBUGGING_SUPPORT || DEBUG
7869
7870 #define CPU_X86 0x0100 // The generic X86 CPU
7871 #define CPU_X86_PENTIUM_4 0x0110
7872
7873 #define CPU_X64 0x0200       // The generic x64 CPU
7874 #define CPU_AMD_X64 0x0210   // AMD x64 CPU
7875 #define CPU_INTEL_X64 0x0240 // Intel x64 CPU
7876
7877 #define CPU_ARM 0x0300 // The generic ARM CPU
7878
7879         unsigned genCPU; // What CPU are we running on
7880     } info;
7881
7882     // Returns true if the method being compiled returns a non-void and non-struct value.
7883     // Note that lvaInitTypeRef() normalizes compRetNativeType for struct returns in a
7884     // single register as per target arch ABI (e.g on Amd64 Windows structs of size 1, 2,
7885     // 4 or 8 gets normalized to TYP_BYTE/TYP_SHORT/TYP_INT/TYP_LONG; On Arm HFA structs).
7886     // Methods returning such structs are considered to return non-struct return value and
7887     // this method returns true in that case.
7888     bool compMethodReturnsNativeScalarType()
7889     {
7890         return (info.compRetType != TYP_VOID) && !varTypeIsStruct(info.compRetNativeType);
7891     }
7892
7893     // Returns true if the method being compiled returns RetBuf addr as its return value
7894     bool compMethodReturnsRetBufAddr()
7895     {
7896         // There are cases where implicit RetBuf argument should be explicitly returned in a register.
7897         // In such cases the return type is changed to TYP_BYREF and appropriate IR is generated.
7898         // These cases are:
7899         // 1. Profiler Leave calllback expects the address of retbuf as return value for
7900         //    methods with hidden RetBuf argument.  impReturnInstruction() when profiler
7901         //    callbacks are needed creates GT_RETURN(TYP_BYREF, op1 = Addr of RetBuf) for
7902         //    methods with hidden RetBufArg.
7903         //
7904         // 2. As per the System V ABI, the address of RetBuf needs to be returned by
7905         //    methods with hidden RetBufArg in RAX. In such case GT_RETURN is of TYP_BYREF,
7906         //    returning the address of RetBuf.
7907         //
7908         // 3. Windows 64-bit native calling convention also requires the address of RetBuff
7909         //    to be returned in RAX.
7910         CLANG_FORMAT_COMMENT_ANCHOR;
7911
7912 #ifdef _TARGET_AMD64_
7913         return (info.compRetBuffArg != BAD_VAR_NUM);
7914 #else  // !_TARGET_AMD64_
7915         return (compIsProfilerHookNeeded()) && (info.compRetBuffArg != BAD_VAR_NUM);
7916 #endif // !_TARGET_AMD64_
7917     }
7918
7919     // Returns true if the method returns a value in more than one return register
7920     // TODO-ARM-Bug: Deal with multi-register genReturnLocaled structs?
7921     // TODO-ARM64: Does this apply for ARM64 too?
7922     bool compMethodReturnsMultiRegRetType()
7923     {
7924 #if FEATURE_MULTIREG_RET
7925 #if defined(_TARGET_X86_)
7926         // On x86 only 64-bit longs are returned in multiple registers
7927         return varTypeIsLong(info.compRetNativeType);
7928 #else  // targets: X64-UNIX, ARM64 or ARM32
7929         // On all other targets that support multireg return values:
7930         // Methods returning a struct in multiple registers have a return value of TYP_STRUCT.
7931         // Such method's compRetNativeType is TYP_STRUCT without a hidden RetBufArg
7932         return varTypeIsStruct(info.compRetNativeType) && (info.compRetBuffArg == BAD_VAR_NUM);
7933 #endif // TARGET_XXX
7934 #else // not FEATURE_MULTIREG_RET
7935         // For this architecture there are no multireg returns
7936         return false;
7937 #endif // FEATURE_MULTIREG_RET
7938     }
7939
7940 #if FEATURE_MULTIREG_ARGS
7941     // Given a GenTree node of TYP_STRUCT that represents a pass by value argument
7942     // return the gcPtr layout for the pointers sized fields
7943     void getStructGcPtrsFromOp(GenTreePtr op, BYTE* gcPtrsOut);
7944 #endif // FEATURE_MULTIREG_ARGS
7945
7946     // Returns true if the method being compiled returns a value
7947     bool compMethodHasRetVal()
7948     {
7949         return compMethodReturnsNativeScalarType() || compMethodReturnsRetBufAddr() ||
7950                compMethodReturnsMultiRegRetType();
7951     }
7952
7953 #if defined(DEBUG)
7954
7955     void compDispLocalVars();
7956
7957 #endif // DEBUGGING_SUPPORT || DEBUG
7958
7959 //-------------------------- Global Compiler Data ------------------------------------
7960
7961 #ifdef DEBUG
7962     static unsigned s_compMethodsCount; // to produce unique label names
7963     unsigned        compGenTreeID;
7964 #endif
7965
7966     BasicBlock* compCurBB;   // the current basic block in process
7967     GenTreePtr  compCurStmt; // the current statement in process
7968 #ifdef DEBUG
7969     unsigned compCurStmtNum; // to give all statements an increasing StmtNum when printing dumps
7970 #endif
7971
7972     //  The following is used to create the 'method JIT info' block.
7973     size_t compInfoBlkSize;
7974     BYTE*  compInfoBlkAddr;
7975
7976     EHblkDsc* compHndBBtab;           // array of EH data
7977     unsigned  compHndBBtabCount;      // element count of used elements in EH data array
7978     unsigned  compHndBBtabAllocCount; // element count of allocated elements in EH data array
7979
7980 #if defined(_TARGET_X86_)
7981
7982     //-------------------------------------------------------------------------
7983     //  Tracking of region covered by the monitor in synchronized methods
7984     void* syncStartEmitCookie; // the emitter cookie for first instruction after the call to MON_ENTER
7985     void* syncEndEmitCookie;   // the emitter cookie for first instruction after the call to MON_EXIT
7986
7987 #endif // !_TARGET_X86_
7988
7989     Phases previousCompletedPhase; // the most recently completed phase
7990
7991     //-------------------------------------------------------------------------
7992     //  The following keeps track of how many bytes of local frame space we've
7993     //  grabbed so far in the current function, and how many argument bytes we
7994     //  need to pop when we return.
7995     //
7996
7997     unsigned compLclFrameSize; // secObject+lclBlk+locals+temps
7998
7999     // Count of callee-saved regs we pushed in the prolog.
8000     // Does not include EBP for isFramePointerUsed() and double-aligned frames.
8001     // In case of Amd64 this doesn't include float regs saved on stack.
8002     unsigned compCalleeRegsPushed;
8003
8004 #if defined(_TARGET_XARCH_) && !FEATURE_STACK_FP_X87
8005     // Mask of callee saved float regs on stack.
8006     regMaskTP compCalleeFPRegsSavedMask;
8007 #endif
8008 #ifdef _TARGET_AMD64_
8009 // Quirk for VS debug-launch scenario to work:
8010 // Bytes of padding between save-reg area and locals.
8011 #define VSQUIRK_STACK_PAD (2 * REGSIZE_BYTES)
8012     unsigned compVSQuirkStackPaddingNeeded;
8013     bool     compQuirkForPPPflag;
8014 #endif
8015
8016     unsigned compArgSize; // total size of arguments in bytes (including register args (lvIsRegArg))
8017
8018     unsigned compMapILargNum(unsigned ILargNum); // map accounting for hidden args
8019     unsigned compMapILvarNum(unsigned ILvarNum); // map accounting for hidden args
8020     unsigned compMap2ILvarNum(unsigned varNum);  // map accounting for hidden args
8021
8022     //-------------------------------------------------------------------------
8023
8024     static void compStartup();  // One-time initialization
8025     static void compShutdown(); // One-time finalization
8026
8027     void compInit(ArenaAllocator* pAlloc, InlineInfo* inlineInfo);
8028     void compDone();
8029
8030     static void compDisplayStaticSizes(FILE* fout);
8031
8032     //------------ Some utility functions --------------
8033
8034     void* compGetHelperFtn(CorInfoHelpFunc ftnNum,         /* IN  */
8035                            void**          ppIndirection); /* OUT */
8036
8037     // Several JIT/EE interface functions return a CorInfoType, and also return a
8038     // class handle as an out parameter if the type is a value class.  Returns the
8039     // size of the type these describe.
8040     unsigned compGetTypeSize(CorInfoType cit, CORINFO_CLASS_HANDLE clsHnd);
8041
8042 #ifdef DEBUG
8043     // Components used by the compiler may write unit test suites, and
8044     // have them run within this method.  They will be run only once per process, and only
8045     // in debug.  (Perhaps should be under the control of a COMPlus_ flag.)
8046     // These should fail by asserting.
8047     void compDoComponentUnitTestsOnce();
8048 #endif // DEBUG
8049
8050     int compCompile(CORINFO_METHOD_HANDLE methodHnd,
8051                     CORINFO_MODULE_HANDLE classPtr,
8052                     COMP_HANDLE           compHnd,
8053                     CORINFO_METHOD_INFO*  methodInfo,
8054                     void**                methodCodePtr,
8055                     ULONG*                methodCodeSize,
8056                     CORJIT_FLAGS*         compileFlags);
8057     void compCompileFinish();
8058     int compCompileHelper(CORINFO_MODULE_HANDLE            classPtr,
8059                           COMP_HANDLE                      compHnd,
8060                           CORINFO_METHOD_INFO*             methodInfo,
8061                           void**                           methodCodePtr,
8062                           ULONG*                           methodCodeSize,
8063                           CORJIT_FLAGS*                    compileFlags,
8064                           CorInfoInstantiationVerification instVerInfo);
8065
8066     ArenaAllocator* compGetAllocator();
8067
8068 #if MEASURE_MEM_ALLOC
8069     struct MemStats
8070     {
8071         unsigned allocCnt;                 // # of allocs
8072         UINT64   allocSz;                  // total size of those alloc.
8073         UINT64   allocSzMax;               // Maximum single allocation.
8074         UINT64   allocSzByKind[CMK_Count]; // Classified by "kind".
8075         UINT64   nraTotalSizeAlloc;
8076         UINT64   nraTotalSizeUsed;
8077
8078         static const char* s_CompMemKindNames[]; // Names of the kinds.
8079
8080         MemStats() : allocCnt(0), allocSz(0), allocSzMax(0), nraTotalSizeAlloc(0), nraTotalSizeUsed(0)
8081         {
8082             for (int i = 0; i < CMK_Count; i++)
8083             {
8084                 allocSzByKind[i] = 0;
8085             }
8086         }
8087         MemStats(const MemStats& ms)
8088             : allocCnt(ms.allocCnt)
8089             , allocSz(ms.allocSz)
8090             , allocSzMax(ms.allocSzMax)
8091             , nraTotalSizeAlloc(ms.nraTotalSizeAlloc)
8092             , nraTotalSizeUsed(ms.nraTotalSizeUsed)
8093         {
8094             for (int i = 0; i < CMK_Count; i++)
8095             {
8096                 allocSzByKind[i] = ms.allocSzByKind[i];
8097             }
8098         }
8099
8100         // Until we have ubiquitous constructors.
8101         void Init()
8102         {
8103             this->MemStats::MemStats();
8104         }
8105
8106         void AddAlloc(size_t sz, CompMemKind cmk)
8107         {
8108             allocCnt += 1;
8109             allocSz += sz;
8110             if (sz > allocSzMax)
8111             {
8112                 allocSzMax = sz;
8113             }
8114             allocSzByKind[cmk] += sz;
8115         }
8116
8117         void Print(FILE* f);       // Print these stats to f.
8118         void PrintByKind(FILE* f); // Do just the by-kind histogram part.
8119     };
8120     MemStats genMemStats;
8121
8122     struct AggregateMemStats : public MemStats
8123     {
8124         unsigned nMethods;
8125
8126         AggregateMemStats() : MemStats(), nMethods(0)
8127         {
8128         }
8129
8130         void Add(const MemStats& ms)
8131         {
8132             nMethods++;
8133             allocCnt += ms.allocCnt;
8134             allocSz += ms.allocSz;
8135             allocSzMax = max(allocSzMax, ms.allocSzMax);
8136             for (int i = 0; i < CMK_Count; i++)
8137             {
8138                 allocSzByKind[i] += ms.allocSzByKind[i];
8139             }
8140             nraTotalSizeAlloc += ms.nraTotalSizeAlloc;
8141             nraTotalSizeUsed += ms.nraTotalSizeUsed;
8142         }
8143
8144         void Print(FILE* f); // Print these stats to jitstdout.
8145     };
8146
8147     static CritSecObject     s_memStatsLock;    // This lock protects the data structures below.
8148     static MemStats          s_maxCompMemStats; // Stats for the compilation with the largest amount allocated.
8149     static AggregateMemStats s_aggMemStats;     // Aggregates statistics for all compilations.
8150
8151 #endif // MEASURE_MEM_ALLOC
8152
8153 #if LOOP_HOIST_STATS
8154     unsigned m_loopsConsidered;
8155     bool     m_curLoopHasHoistedExpression;
8156     unsigned m_loopsWithHoistedExpressions;
8157     unsigned m_totalHoistedExpressions;
8158
8159     void AddLoopHoistStats();
8160     void PrintPerMethodLoopHoistStats();
8161
8162     static CritSecObject s_loopHoistStatsLock; // This lock protects the data structures below.
8163     static unsigned      s_loopsConsidered;
8164     static unsigned      s_loopsWithHoistedExpressions;
8165     static unsigned      s_totalHoistedExpressions;
8166
8167     static void PrintAggregateLoopHoistStats(FILE* f);
8168 #endif // LOOP_HOIST_STATS
8169
8170     void* compGetMemArray(size_t numElem, size_t elemSize, CompMemKind cmk = CMK_Unknown);
8171     void* compGetMemArrayA(size_t numElem, size_t elemSize, CompMemKind cmk = CMK_Unknown);
8172     void* compGetMem(size_t sz, CompMemKind cmk = CMK_Unknown);
8173     void* compGetMemA(size_t sz, CompMemKind cmk = CMK_Unknown);
8174     static void* compGetMemCallback(void*, size_t, CompMemKind cmk = CMK_Unknown);
8175     void compFreeMem(void*);
8176
8177     bool compIsForImportOnly();
8178     bool compIsForInlining();
8179     bool compDonotInline();
8180
8181 #ifdef DEBUG
8182     const char* compLocalVarName(unsigned varNum, unsigned offs);
8183     VarName compVarName(regNumber reg, bool isFloatReg = false);
8184     const char* compRegVarName(regNumber reg, bool displayVar = false, bool isFloatReg = false);
8185     const char* compRegPairName(regPairNo regPair);
8186     const char* compRegNameForSize(regNumber reg, size_t size);
8187     const char* compFPregVarName(unsigned fpReg, bool displayVar = false);
8188     void compDspSrcLinesByNativeIP(UNATIVE_OFFSET curIP);
8189     void compDspSrcLinesByLineNum(unsigned line, bool seek = false);
8190 #endif // DEBUG
8191
8192 //-------------------------------------------------------------------------
8193
8194 #ifdef DEBUGGING_SUPPORT
8195     typedef ListNode<VarScopeDsc*> VarScopeListNode;
8196
8197     struct VarScopeMapInfo
8198     {
8199         VarScopeListNode*       head;
8200         VarScopeListNode*       tail;
8201         static VarScopeMapInfo* Create(VarScopeListNode* node, IAllocator* alloc)
8202         {
8203             VarScopeMapInfo* info = new (alloc) VarScopeMapInfo;
8204             info->head            = node;
8205             info->tail            = node;
8206             return info;
8207         }
8208     };
8209
8210     // Max value of scope count for which we would use linear search; for larger values we would use hashtable lookup.
8211     static const unsigned MAX_LINEAR_FIND_LCL_SCOPELIST = 32;
8212
8213     typedef SimplerHashTable<unsigned, SmallPrimitiveKeyFuncs<unsigned>, VarScopeMapInfo*, JitSimplerHashBehavior>
8214         VarNumToScopeDscMap;
8215
8216     // Map to keep variables' scope indexed by varNum containing it's scope dscs at the index.
8217     VarNumToScopeDscMap* compVarScopeMap;
8218
8219     VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned lifeBeg, unsigned lifeEnd);
8220
8221     VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned offs);
8222
8223     VarScopeDsc* compFindLocalVarLinear(unsigned varNum, unsigned offs);
8224
8225     void compInitVarScopeMap();
8226
8227     VarScopeDsc** compEnterScopeList; // List has the offsets where variables
8228                                       // enter scope, sorted by instr offset
8229     unsigned compNextEnterScope;
8230
8231     VarScopeDsc** compExitScopeList; // List has the offsets where variables
8232                                      // go out of scope, sorted by instr offset
8233     unsigned compNextExitScope;
8234
8235     void compInitScopeLists();
8236
8237     void compResetScopeLists();
8238
8239     VarScopeDsc* compGetNextEnterScope(unsigned offs, bool scan = false);
8240
8241     VarScopeDsc* compGetNextExitScope(unsigned offs, bool scan = false);
8242
8243     void compProcessScopesUntil(unsigned   offset,
8244                                 VARSET_TP* inScope,
8245                                 void (Compiler::*enterScopeFn)(VARSET_TP* inScope, VarScopeDsc*),
8246                                 void (Compiler::*exitScopeFn)(VARSET_TP* inScope, VarScopeDsc*));
8247
8248 #ifdef DEBUG
8249     void compDispScopeLists();
8250 #endif // DEBUG
8251
8252 #endif // DEBUGGING_SUPPORT
8253
8254     bool compIsProfilerHookNeeded();
8255
8256     //-------------------------------------------------------------------------
8257     /*               Statistical Data Gathering                               */
8258
8259     void compJitStats(); // call this function and enable
8260                          // various ifdef's below for statistical data
8261
8262 #if CALL_ARG_STATS
8263     void        compCallArgStats();
8264     static void compDispCallArgStats(FILE* fout);
8265 #endif
8266
8267     //-------------------------------------------------------------------------
8268
8269 protected:
8270 #ifdef DEBUG
8271     bool skipMethod();
8272 #endif
8273
8274     ArenaAllocator* compAllocator;
8275
8276 public:
8277     // This one presents an implementation of the "IAllocator" abstract class that uses "compAllocator",
8278     // suitable for use by utilcode collection types.
8279     IAllocator* compAsIAllocator;
8280
8281 #if MEASURE_MEM_ALLOC
8282     IAllocator* compAsIAllocatorBitset;    // An allocator that uses the CMK_bitset tracker.
8283     IAllocator* compAsIAllocatorGC;        // An allocator that uses the CMK_GC tracker.
8284     IAllocator* compAsIAllocatorLoopHoist; // An allocator that uses the CMK_LoopHoist tracker.
8285 #ifdef DEBUG
8286     IAllocator* compAsIAllocatorDebugOnly; // An allocator that uses the CMK_DebugOnly tracker.
8287 #endif                                     // DEBUG
8288 #endif                                     // MEASURE_MEM_ALLOC
8289
8290     void compFunctionTraceStart();
8291     void compFunctionTraceEnd(void* methodCodePtr, ULONG methodCodeSize, bool isNYI);
8292
8293 protected:
8294     size_t compMaxUncheckedOffsetForNullObject;
8295
8296     void compInitOptions(CORJIT_FLAGS* compileFlags);
8297
8298     void compSetProcessor();
8299     void compInitDebuggingInfo();
8300     void compSetOptimizationLevel();
8301 #ifdef _TARGET_ARMARCH_
8302     bool compRsvdRegCheck(FrameLayoutState curState);
8303 #endif
8304     void compCompile(void** methodCodePtr, ULONG* methodCodeSize, CORJIT_FLAGS* compileFlags);
8305
8306     // Data required for generating profiler Enter/Leave/TailCall hooks
8307     CLANG_FORMAT_COMMENT_ANCHOR;
8308
8309 #ifdef PROFILING_SUPPORTED
8310     bool  compProfilerHookNeeded; // Whether profiler Enter/Leave/TailCall hook needs to be generated for the method
8311     void* compProfilerMethHnd;    // Profiler handle of the method being compiled. Passed as param to ELT callbacks
8312     bool  compProfilerMethHndIndirected; // Whether compProfilerHandle is pointer to the handle or is an actual handle
8313 #endif
8314 #ifdef _TARGET_AMD64_
8315     bool compQuirkForPPP(); // Check if this method should be Quirked for the PPP issue
8316 #endif
8317 public:
8318     // Assumes called as part of process shutdown; does any compiler-specific work associated with that.
8319     static void ProcessShutdownWork(ICorStaticInfo* statInfo);
8320
8321     IAllocator* getAllocator()
8322     {
8323         return compAsIAllocator;
8324     }
8325
8326 #if MEASURE_MEM_ALLOC
8327     IAllocator* getAllocatorBitset()
8328     {
8329         return compAsIAllocatorBitset;
8330     }
8331     IAllocator* getAllocatorGC()
8332     {
8333         return compAsIAllocatorGC;
8334     }
8335     IAllocator* getAllocatorLoopHoist()
8336     {
8337         return compAsIAllocatorLoopHoist;
8338     }
8339 #else  // !MEASURE_MEM_ALLOC
8340     IAllocator* getAllocatorBitset()
8341     {
8342         return compAsIAllocator;
8343     }
8344     IAllocator* getAllocatorGC()
8345     {
8346         return compAsIAllocator;
8347     }
8348     IAllocator* getAllocatorLoopHoist()
8349     {
8350         return compAsIAllocator;
8351     }
8352 #endif // !MEASURE_MEM_ALLOC
8353
8354 #ifdef DEBUG
8355     IAllocator* getAllocatorDebugOnly()
8356     {
8357 #if MEASURE_MEM_ALLOC
8358         return compAsIAllocatorDebugOnly;
8359 #else  // !MEASURE_MEM_ALLOC
8360         return compAsIAllocator;
8361 #endif // !MEASURE_MEM_ALLOC
8362     }
8363 #endif // DEBUG
8364
8365     /*
8366     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8367     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8368     XX                                                                           XX
8369     XX                           typeInfo                                        XX
8370     XX                                                                           XX
8371     XX   Checks for type compatibility and merges types                          XX
8372     XX                                                                           XX
8373     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8374     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8375     */
8376
8377 public:
8378     // Set to TRUE if verification cannot be skipped for this method
8379     // If we detect unverifiable code, we will lazily check
8380     // canSkipMethodVerification() to see if verification is REALLY needed.
8381     BOOL tiVerificationNeeded;
8382
8383     // It it initially TRUE, and it gets set to FALSE if we run into unverifiable code
8384     // Note that this is valid only if tiVerificationNeeded was ever TRUE.
8385     BOOL tiIsVerifiableCode;
8386
8387     // Set to TRUE if runtime callout is needed for this method
8388     BOOL tiRuntimeCalloutNeeded;
8389
8390     // Set to TRUE if security prolog/epilog callout is needed for this method
8391     // Note: This flag is different than compNeedSecurityCheck.
8392     //     compNeedSecurityCheck means whether or not a security object needs
8393     //         to be allocated on the stack, which is currently true for EnC as well.
8394     //     tiSecurityCalloutNeeded means whether or not security callouts need
8395     //         to be inserted in the jitted code.
8396     BOOL tiSecurityCalloutNeeded;
8397
8398     // Returns TRUE if child is equal to or a subtype of parent for merge purposes
8399     // This support is necessary to suport attributes that are not described in
8400     // for example, signatures. For example, the permanent home byref (byref that
8401     // points to the gc heap), isn't a property of method signatures, therefore,
8402     // it is safe to have mismatches here (that tiCompatibleWith will not flag),
8403     // but when deciding if we need to reimport a block, we need to take these
8404     // in account
8405     BOOL tiMergeCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
8406
8407     // Returns TRUE if child is equal to or a subtype of parent.
8408     // normalisedForStack indicates that both types are normalised for the stack
8409     BOOL tiCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
8410
8411     // Merges pDest and pSrc. Returns FALSE if merge is undefined.
8412     // *pDest is modified to represent the merged type.  Sets "*changed" to true
8413     // if this changes "*pDest".
8414     BOOL tiMergeToCommonParent(typeInfo* pDest, const typeInfo* pSrc, bool* changed) const;
8415
8416     // Set pDest from the primitive value type.
8417     // Eg. System.Int32 -> ELEMENT_TYPE_I4
8418
8419     BOOL tiFromPrimitiveValueClass(typeInfo* pDest, const typeInfo* pVC) const;
8420
8421 #ifdef DEBUG
8422     // <BUGNUM> VSW 471305
8423     // IJW allows assigning REF to BYREF. The following allows us to temporarily
8424     // bypass the assert check in gcMarkRegSetGCref and gcMarkRegSetByref
8425     // We use a "short" as we need to push/pop this scope.
8426     // </BUGNUM>
8427     short compRegSetCheckLevel;
8428 #endif
8429
8430     /*
8431     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8432     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8433     XX                                                                           XX
8434     XX                           IL verification stuff                           XX
8435     XX                                                                           XX
8436     XX                                                                           XX
8437     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8438     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8439     */
8440
8441 public:
8442     // The following is used to track liveness of local variables, initialization
8443     // of valueclass constructors, and type safe use of IL instructions.
8444
8445     // dynamic state info needed for verification
8446     EntryState verCurrentState;
8447
8448     // this ptr of object type .ctors are considered intited only after
8449     // the base class ctor is called, or an alternate ctor is called.
8450     // An uninited this ptr can be used to access fields, but cannot
8451     // be used to call a member function.
8452     BOOL verTrackObjCtorInitState;
8453
8454     void verInitBBEntryState(BasicBlock* block, EntryState* currentState);
8455
8456     // Requires that "tis" is not TIS_Bottom -- it's a definite init/uninit state.
8457     void verSetThisInit(BasicBlock* block, ThisInitState tis);
8458     void verInitCurrentState();
8459     void verResetCurrentState(BasicBlock* block, EntryState* currentState);
8460
8461     // Merges the current verification state into the entry state of "block", return FALSE if that merge fails,
8462     // TRUE if it succeeds.  Further sets "*changed" to true if this changes the entry state of "block".
8463     BOOL verMergeEntryStates(BasicBlock* block, bool* changed);
8464
8465     void verConvertBBToThrowVerificationException(BasicBlock* block DEBUGARG(bool logMsg));
8466     void verHandleVerificationFailure(BasicBlock* block DEBUGARG(bool logMsg));
8467     typeInfo verMakeTypeInfo(CORINFO_CLASS_HANDLE clsHnd,
8468                              bool bashStructToRef = false); // converts from jit type representation to typeInfo
8469     typeInfo verMakeTypeInfo(CorInfoType          ciType,
8470                              CORINFO_CLASS_HANDLE clsHnd); // converts from jit type representation to typeInfo
8471     BOOL verIsSDArray(typeInfo ti);
8472     typeInfo verGetArrayElemType(typeInfo ti);
8473
8474     typeInfo verParseArgSigToTypeInfo(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_HANDLE args);
8475     BOOL verNeedsVerification();
8476     BOOL verIsByRefLike(const typeInfo& ti);
8477     BOOL verIsSafeToReturnByRef(const typeInfo& ti);
8478
8479     // generic type variables range over types that satisfy IsBoxable
8480     BOOL verIsBoxable(const typeInfo& ti);
8481
8482     void DECLSPEC_NORETURN verRaiseVerifyException(INDEBUG(const char* reason) DEBUGARG(const char* file)
8483                                                        DEBUGARG(unsigned line));
8484     void verRaiseVerifyExceptionIfNeeded(INDEBUG(const char* reason) DEBUGARG(const char* file)
8485                                              DEBUGARG(unsigned line));
8486     bool verCheckTailCallConstraint(OPCODE                  opcode,
8487                                     CORINFO_RESOLVED_TOKEN* pResolvedToken,
8488                                     CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call
8489                                                                                        // on a type parameter?
8490                                     bool speculative // If true, won't throw if verificatoin fails. Instead it will
8491                                                      // return false to the caller.
8492                                                      // If false, it will throw.
8493                                     );
8494     bool verIsBoxedValueType(typeInfo ti);
8495
8496     void verVerifyCall(OPCODE                  opcode,
8497                        CORINFO_RESOLVED_TOKEN* pResolvedToken,
8498                        CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
8499                        bool                    tailCall,
8500                        bool                    readonlyCall, // is this a "readonly." call?
8501                        const BYTE*             delegateCreateStart,
8502                        const BYTE*             codeAddr,
8503                        CORINFO_CALL_INFO* callInfo DEBUGARG(const char* methodName));
8504
8505     BOOL verCheckDelegateCreation(const BYTE* delegateCreateStart, const BYTE* codeAddr, mdMemberRef& targetMemberRef);
8506
8507     typeInfo verVerifySTIND(const typeInfo& ptr, const typeInfo& value, const typeInfo& instrType);
8508     typeInfo verVerifyLDIND(const typeInfo& ptr, const typeInfo& instrType);
8509     void verVerifyField(CORINFO_RESOLVED_TOKEN*   pResolvedToken,
8510                         const CORINFO_FIELD_INFO& fieldInfo,
8511                         const typeInfo*           tiThis,
8512                         BOOL                      mutator,
8513                         BOOL                      allowPlainStructAsThis = FALSE);
8514     void verVerifyCond(const typeInfo& tiOp1, const typeInfo& tiOp2, unsigned opcode);
8515     void verVerifyThisPtrInitialised();
8516     BOOL verIsCallToInitThisPtr(CORINFO_CLASS_HANDLE context, CORINFO_CLASS_HANDLE target);
8517
8518     // Register allocator
8519     void raInitStackFP();
8520     void raEnregisterVarsPrePassStackFP();
8521     void raSetRegLclBirthDeath(GenTreePtr tree, VARSET_VALARG_TP lastlife, bool fromLDOBJ);
8522     void raEnregisterVarsPostPassStackFP();
8523     void raGenerateFPRefCounts();
8524     void raEnregisterVarsStackFP();
8525     void raUpdateHeightsForVarsStackFP(VARSET_VALARG_TP mask);
8526
8527     regNumber raRegForVarStackFP(unsigned varTrackedIndex);
8528     void raAddPayloadStackFP(VARSET_VALARG_TP mask, unsigned weight);
8529
8530     // returns true if enregistering v1 would save more mem accesses than v2
8531     bool raVarIsGreaterValueStackFP(LclVarDsc* lv1, LclVarDsc* lv2);
8532
8533 #ifdef DEBUG
8534     void raDumpHeightsStackFP();
8535     void raDumpVariableRegIntfFloat();
8536 #endif
8537
8538 #if FEATURE_STACK_FP_X87
8539
8540     // Currently, we use FP transition blocks in only 2 situations:
8541     //
8542     //      -conditional jump on longs where FP stack differs with target: it's not strictly
8543     //       necessary, but its low frequency and the code would get complicated if we try to
8544     //       inline the FP stack adjustment, as we have a lot of special casing going on to try
8545     //       minimize the way we generate the jump code.
8546     //      -case statements of switch where the FP stack differs with the one of evaluating the switch () statement
8547     //       We do this as we want to codegen switch as a jumptable. Again, this is low frequency.
8548     //
8549     //      However, transition blocks have 2 problems
8550     //
8551     //          - Procedure splitting: current implementation of procedure splitting requires all basic blocks to
8552     //            be known at codegen time, as it generates all hot blocks first and cold blocks later. This ties
8553     //            us up in codegen and is a solvable problem (we could make procedure splitting generate blocks
8554     //            in the right place without preordering them), this causes us to have to generate the transition
8555     //            blocks in the cold area if we want procedure splitting.
8556     //
8557     //
8558     //          - Thread abort exceptions and transition blocks. Transition blocks were designed under the assumption
8559     //            that no exceptions can happen inside them. Unfortunately Thread.Abort can happen in any instruction,
8560     //            and if we have handlers we will have to try to call them. Fixing this the right way would imply
8561     //            having multiple try native code regions for a single try il region. This is doable and shouldnt be
8562     //            a big change in the exception.
8563     //
8564     //      Given the low frequency of the cases where we have transition blocks, I've decided to dumb down
8565     //      optimizations. For these 2 cases:
8566     //
8567     //          - When there is a chance that we will have FP transition blocks, we won't do procedure splitting.
8568     //          - When a method has a handler, it won't enregister any FP variables that go thru a conditional long or
8569     //          a switch statement.
8570     //
8571     //      If at any point we find we need to optimize this, we should throw work at unblocking the restrictions our
8572     //      current procedure splitting and exception code have.
8573     bool compMayHaveTransitionBlocks;
8574
8575     VARSET_TP raMaskDontEnregFloat; // mask for additional restrictions
8576
8577     VARSET_TP raLclRegIntfFloat[REG_FPCOUNT];
8578
8579     unsigned raCntStkStackFP;
8580     unsigned raCntWtdStkDblStackFP;
8581     unsigned raCntStkParamDblStackFP;
8582
8583     // Payload in mem accesses for enregistering a variable (we dont want to mix with refcounts)
8584     // TODO: Do we want to put this in LclVarDsc?
8585     unsigned raPayloadStackFP[lclMAX_TRACKED];
8586     unsigned raHeightsStackFP[lclMAX_TRACKED][FP_VIRTUALREGISTERS + 1];
8587 #ifdef DEBUG
8588     // Useful for debugging
8589     unsigned raHeightsNonWeightedStackFP[lclMAX_TRACKED][FP_VIRTUALREGISTERS + 1];
8590 #endif
8591 #endif // FEATURE_STACK_FP_X87
8592
8593 #ifdef DEBUG
8594     // One line log function. Default level is 0. Increasing it gives you
8595     // more log information
8596
8597     // levels are currently unused: #define JITDUMP(level,...)                     ();
8598     void JitLogEE(unsigned level, const char* fmt, ...);
8599
8600     bool compDebugBreak;
8601
8602     bool compJitHaltMethod();
8603
8604 #endif
8605
8606     /*
8607     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8608     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8609     XX                                                                           XX
8610     XX                   GS Security checks for unsafe buffers                   XX
8611     XX                                                                           XX
8612     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8613     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8614     */
8615 public:
8616     struct ShadowParamVarInfo
8617     {
8618         FixedBitVect* assignGroup; // the closure set of variables whose values depend on each other
8619         unsigned      shadowCopy;  // Lcl var num, valid only if not set to NO_SHADOW_COPY
8620
8621         static bool mayNeedShadowCopy(LclVarDsc* varDsc)
8622         {
8623 #if defined(_TARGET_AMD64_) && !defined(LEGACY_BACKEND)
8624             // GS cookie logic to create shadow slots, create trees to copy reg args to shadow
8625             // slots and update all trees to refer to shadow slots is done immediately after
8626             // fgMorph().  Lsra could potentially mark a param as DoNotEnregister after JIT determines
8627             // not to shadow a parameter.  Also, LSRA could potentially spill a param which is passed
8628             // in register. Therefore, conservatively all params may need a shadow copy.  Note that
8629             // GS cookie logic further checks whether the param is a ptr or an unsafe buffer before
8630             // creating a shadow slot even though this routine returns true.
8631             //
8632             // TODO-AMD64-CQ: Revisit this conservative approach as it could create more shadow slots than
8633             // required. There are two cases under which a reg arg could potentially be used from its
8634             // home location:
8635             //   a) LSRA marks it as DoNotEnregister (see LinearScan::identifyCandidates())
8636             //   b) LSRA spills it
8637             //
8638             // Possible solution to address case (a)
8639             //   - The conditions under which LSRA marks a varDsc as DoNotEnregister could be checked
8640             //     in this routine.  Note that live out of exception handler is something we may not be
8641             //     able to do it here since GS cookie logic is invoked ahead of liveness computation.
8642             //     Therefore, for methods with exception handling and need GS cookie check we might have
8643             //     to take conservative approach.
8644             //
8645             // Possible solution to address case (b)
8646             //   - Whenver a parameter passed in an argument register needs to be spilled by LSRA, we
8647             //     create a new spill temp if the method needs GS cookie check.
8648             return varDsc->lvIsParam;
8649 #else // !(defined(_TARGET_AMD64_) && defined(LEGACY_BACKEND))
8650             return varDsc->lvIsParam && !varDsc->lvIsRegArg;
8651 #endif
8652         }
8653
8654 #ifdef DEBUG
8655         void Print()
8656         {
8657             printf("assignGroup [%p]; shadowCopy: [%d];\n", assignGroup, shadowCopy);
8658         }
8659 #endif
8660     };
8661
8662     GSCookie*           gsGlobalSecurityCookieAddr; // Address of global cookie for unsafe buffer checks
8663     GSCookie            gsGlobalSecurityCookieVal;  // Value of global cookie if addr is NULL
8664     ShadowParamVarInfo* gsShadowVarInfo;            // Table used by shadow param analysis code
8665
8666     void gsGSChecksInitCookie();   // Grabs cookie variable
8667     void gsCopyShadowParams();     // Identify vulnerable params and create dhadow copies
8668     bool gsFindVulnerableParams(); // Shadow param analysis code
8669     void gsParamsToShadows();      // Insert copy code and replave param uses by shadow
8670
8671     static fgWalkPreFn gsMarkPtrsAndAssignGroups; // Shadow param analysis tree-walk
8672     static fgWalkPreFn gsReplaceShadowParams;     // Shadow param replacement tree-walk
8673
8674 #define DEFAULT_MAX_INLINE_SIZE 100 // Methods with >  DEFAULT_MAX_INLINE_SIZE IL bytes will never be inlined.
8675                                     // This can be overwritten by setting complus_JITInlineSize env variable.
8676
8677 #define DEFAULT_MAX_INLINE_DEPTH 20 // Methods at more than this level deep will not be inlined
8678
8679 private:
8680 #ifdef FEATURE_JIT_METHOD_PERF
8681     JitTimer*                  pCompJitTimer;         // Timer data structure (by phases) for current compilation.
8682     static CompTimeSummaryInfo s_compJitTimerSummary; // Summary of the Timer information for the whole run.
8683
8684     static LPCWSTR JitTimeLogCsv();        // Retrieve the file name for CSV from ConfigDWORD.
8685     static LPCWSTR compJitTimeLogFilename; // If a log file for JIT time is desired, filename to write it to.
8686 #endif
8687     inline void EndPhase(Phases phase); // Indicate the end of the given phase.
8688
8689 #if defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
8690     // These variables are associated with maintaining SQM data about compile time.
8691     unsigned __int64 m_compCyclesAtEndOfInlining; // The thread-virtualized cycle count at the end of the inlining phase
8692                                                   // in the current compilation.
8693     unsigned __int64 m_compCycles;                // Net cycle count for current compilation
8694     DWORD m_compTickCountAtEndOfInlining; // The result of GetTickCount() (# ms since some epoch marker) at the end of
8695                                           // the inlining phase in the current compilation.
8696 #endif                                    // defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
8697
8698     // Records the SQM-relevant (cycles and tick count).  Should be called after inlining is complete.
8699     // (We do this after inlining because this marks the last point at which the JIT is likely to cause
8700     // type-loading and class initialization).
8701     void RecordStateAtEndOfInlining();
8702     // Assumes being called at the end of compilation.  Update the SQM state.
8703     void RecordStateAtEndOfCompilation();
8704
8705 #ifdef FEATURE_CLRSQM
8706     // Does anything SQM related necessary at process shutdown time.
8707     static void ProcessShutdownSQMWork(ICorStaticInfo* statInfo);
8708 #endif // FEATURE_CLRSQM
8709
8710 public:
8711 #if FUNC_INFO_LOGGING
8712     static LPCWSTR compJitFuncInfoFilename; // If a log file for per-function information is required, this is the
8713                                             // filename to write it to.
8714     static FILE* compJitFuncInfoFile;       // And this is the actual FILE* to write to.
8715 #endif                                      // FUNC_INFO_LOGGING
8716
8717     Compiler* prevCompiler; // Previous compiler on stack for TLS Compiler* linked list for reentrant compilers.
8718
8719     // Is the compilation in a full trust context?
8720     bool compIsFullTrust();
8721
8722 #ifndef FEATURE_TRACELOGGING
8723     // Should we actually fire the noway assert body and the exception handler?
8724     bool compShouldThrowOnNoway();
8725 #else  // FEATURE_TRACELOGGING
8726     // Should we actually fire the noway assert body and the exception handler?
8727     bool compShouldThrowOnNoway(const char* filename, unsigned line);
8728
8729     // Telemetry instance to use per method compilation.
8730     JitTelemetry compJitTelemetry;
8731
8732     // Get common parameters that have to be logged with most telemetry data.
8733     void compGetTelemetryDefaults(const char** assemblyName,
8734                                   const char** scopeName,
8735                                   const char** methodName,
8736                                   unsigned*    methodHash);
8737 #endif // !FEATURE_TRACELOGGING
8738
8739 #ifdef DEBUG
8740 private:
8741     NodeToTestDataMap* m_nodeTestData;
8742
8743     static const unsigned FIRST_LOOP_HOIST_CSE_CLASS = 1000;
8744     unsigned              m_loopHoistCSEClass; // LoopHoist test annotations turn into CSE requirements; we
8745                                                // label them with CSE Class #'s starting at FIRST_LOOP_HOIST_CSE_CLASS.
8746                                                // Current kept in this.
8747 public:
8748     NodeToTestDataMap* GetNodeTestData()
8749     {
8750         Compiler* compRoot = impInlineRoot();
8751         if (compRoot->m_nodeTestData == nullptr)
8752         {
8753             compRoot->m_nodeTestData = new (getAllocatorDebugOnly()) NodeToTestDataMap(getAllocatorDebugOnly());
8754         }
8755         return compRoot->m_nodeTestData;
8756     }
8757
8758     typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, int, JitSimplerHashBehavior> NodeToIntMap;
8759
8760     // Returns the set (i.e., the domain of the result map) of nodes that are keys in m_nodeTestData, and
8761     // currently occur in the AST graph.
8762     NodeToIntMap* FindReachableNodesInNodeTestData();
8763
8764     // Node "from" is being eliminated, and being replaced by node "to".  If "from" had any associated
8765     // test data, associate that data with "to".
8766     void TransferTestDataToNode(GenTreePtr from, GenTreePtr to);
8767
8768     // Requires that "to" is a clone of "from".  If any nodes in the "from" tree
8769     // have annotations, attach similar annotations to the corresponding nodes in "to".
8770     void CopyTestDataToCloneTree(GenTreePtr from, GenTreePtr to);
8771
8772     // These are the methods that test that the various conditions implied by the
8773     // test attributes are satisfied.
8774     void JitTestCheckSSA(); // SSA builder tests.
8775     void JitTestCheckVN();  // Value numbering tests.
8776 #endif                      // DEBUG
8777
8778     // The "FieldSeqStore", for canonicalizing field sequences.  See the definition of FieldSeqStore for
8779     // operations.
8780     FieldSeqStore* m_fieldSeqStore;
8781
8782     FieldSeqStore* GetFieldSeqStore()
8783     {
8784         Compiler* compRoot = impInlineRoot();
8785         if (compRoot->m_fieldSeqStore == nullptr)
8786         {
8787             // Create a CompAllocator that labels sub-structure with CMK_FieldSeqStore, and use that for allocation.
8788             IAllocator* ialloc        = new (this, CMK_FieldSeqStore) CompAllocator(this, CMK_FieldSeqStore);
8789             compRoot->m_fieldSeqStore = new (ialloc) FieldSeqStore(ialloc);
8790         }
8791         return compRoot->m_fieldSeqStore;
8792     }
8793
8794     typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, FieldSeqNode*, JitSimplerHashBehavior> NodeToFieldSeqMap;
8795
8796     // Some nodes of "TYP_BYREF" or "TYP_I_IMPL" actually represent the address of a field within a struct, but since
8797     // the offset of the field is zero, there's no "GT_ADD" node.  We normally attach a field sequence to the constant
8798     // that is added, but what do we do when that constant is zero, and is thus not present?  We use this mechanism to
8799     // attach the field sequence directly to the address node.
8800     NodeToFieldSeqMap* m_zeroOffsetFieldMap;
8801
8802     NodeToFieldSeqMap* GetZeroOffsetFieldMap()
8803     {
8804         // Don't need to worry about inlining here
8805         if (m_zeroOffsetFieldMap == nullptr)
8806         {
8807             // Create a CompAllocator that labels sub-structure with CMK_ZeroOffsetFieldMap, and use that for
8808             // allocation.
8809             IAllocator* ialloc   = new (this, CMK_ZeroOffsetFieldMap) CompAllocator(this, CMK_ZeroOffsetFieldMap);
8810             m_zeroOffsetFieldMap = new (ialloc) NodeToFieldSeqMap(ialloc);
8811         }
8812         return m_zeroOffsetFieldMap;
8813     }
8814
8815     // Requires that "op1" is a node of type "TYP_BYREF" or "TYP_I_IMPL".  We are dereferencing this with the fields in
8816     // "fieldSeq", whose offsets are required all to be zero.  Ensures that any field sequence annotation currently on
8817     // "op1" or its components is augmented by appending "fieldSeq".  In practice, if "op1" is a GT_LCL_FLD, it has
8818     // a field sequence as a member; otherwise, it may be the addition of an a byref and a constant, where the const
8819     // has a field sequence -- in this case "fieldSeq" is appended to that of the constant; otherwise, we
8820     // record the the field sequence using the ZeroOffsetFieldMap described above.
8821     //
8822     // One exception above is that "op1" is a node of type "TYP_REF" where "op1" is a GT_LCL_VAR.
8823     // This happens when System.Object vtable pointer is a regular field at offset 0 in System.Private.CoreLib in
8824     // CoreRT. Such case is handled same as the default case.
8825     void fgAddFieldSeqForZeroOffset(GenTreePtr op1, FieldSeqNode* fieldSeq);
8826
8827     typedef SimplerHashTable<const GenTree*, PtrKeyFuncs<GenTree>, ArrayInfo, JitSimplerHashBehavior>
8828                         NodeToArrayInfoMap;
8829     NodeToArrayInfoMap* m_arrayInfoMap;
8830
8831     NodeToArrayInfoMap* GetArrayInfoMap()
8832     {
8833         Compiler* compRoot = impInlineRoot();
8834         if (compRoot->m_arrayInfoMap == nullptr)
8835         {
8836             // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
8837             IAllocator* ialloc       = new (this, CMK_ArrayInfoMap) CompAllocator(this, CMK_ArrayInfoMap);
8838             compRoot->m_arrayInfoMap = new (ialloc) NodeToArrayInfoMap(ialloc);
8839         }
8840         return compRoot->m_arrayInfoMap;
8841     }
8842
8843     NodeToUnsignedMap* m_heapSsaMap;
8844
8845     // In some cases, we want to assign intermediate SSA #'s to heap states, and know what nodes create those heap
8846     // states. (We do this for try blocks, where, if the try block doesn't do a call that loses track of the heap state,
8847     // all the possible heap states are possible initial states of the corresponding catch block(s).)
8848     NodeToUnsignedMap* GetHeapSsaMap()
8849     {
8850         Compiler* compRoot = impInlineRoot();
8851         if (compRoot->m_heapSsaMap == nullptr)
8852         {
8853             // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
8854             IAllocator* ialloc     = new (this, CMK_ArrayInfoMap) CompAllocator(this, CMK_ArrayInfoMap);
8855             compRoot->m_heapSsaMap = new (ialloc) NodeToUnsignedMap(ialloc);
8856         }
8857         return compRoot->m_heapSsaMap;
8858     }
8859
8860     // The Refany type is the only struct type whose structure is implicitly assumed by IL.  We need its fields.
8861     CORINFO_CLASS_HANDLE m_refAnyClass;
8862     CORINFO_FIELD_HANDLE GetRefanyDataField()
8863     {
8864         if (m_refAnyClass == nullptr)
8865         {
8866             m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
8867         }
8868         return info.compCompHnd->getFieldInClass(m_refAnyClass, 0);
8869     }
8870     CORINFO_FIELD_HANDLE GetRefanyTypeField()
8871     {
8872         if (m_refAnyClass == nullptr)
8873         {
8874             m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
8875         }
8876         return info.compCompHnd->getFieldInClass(m_refAnyClass, 1);
8877     }
8878
8879 #if VARSET_COUNTOPS
8880     static BitSetSupport::BitSetOpCounter m_varsetOpCounter;
8881 #endif
8882 #if ALLVARSET_COUNTOPS
8883     static BitSetSupport::BitSetOpCounter m_allvarsetOpCounter;
8884 #endif
8885
8886     static HelperCallProperties s_helperCallProperties;
8887
8888 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
8889     static var_types GetTypeFromClassificationAndSizes(SystemVClassificationType classType, int size);
8890     static var_types GetEightByteType(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
8891                                       unsigned                                                   slotNum);
8892     static void GetStructTypeOffset(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
8893                                     var_types*                                                 type0,
8894                                     var_types*                                                 type1,
8895                                     unsigned __int8*                                           offset0,
8896                                     unsigned __int8*                                           offset1);
8897     void fgMorphSystemVStructArgs(GenTreeCall* call, bool hasStructArgument);
8898 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
8899
8900     void fgMorphMultiregStructArgs(GenTreeCall* call);
8901     GenTreePtr fgMorphMultiregStructArg(GenTreePtr arg, fgArgTabEntryPtr fgEntryPtr);
8902
8903 }; // end of class Compiler
8904
8905 // Inline methods of CompAllocator.
8906 void* CompAllocator::Alloc(size_t sz)
8907 {
8908 #if MEASURE_MEM_ALLOC
8909     return m_comp->compGetMem(sz, m_cmk);
8910 #else
8911     return m_comp->compGetMem(sz);
8912 #endif
8913 }
8914
8915 void* CompAllocator::ArrayAlloc(size_t elems, size_t elemSize)
8916 {
8917 #if MEASURE_MEM_ALLOC
8918     return m_comp->compGetMemArray(elems, elemSize, m_cmk);
8919 #else
8920     return m_comp->compGetMemArray(elems, elemSize);
8921 #endif
8922 }
8923
8924 // LclVarDsc constructor. Uses Compiler, so must come after Compiler definition.
8925 inline LclVarDsc::LclVarDsc(Compiler* comp)
8926     : // Initialize the ArgRegs to REG_STK.
8927     // The morph will do the right thing to change
8928     // to the right register if passed in register.
8929     _lvArgReg(REG_STK)
8930     ,
8931 #if FEATURE_MULTIREG_ARGS
8932     _lvOtherArgReg(REG_STK)
8933     ,
8934 #endif // FEATURE_MULTIREG_ARGS
8935 #if ASSERTION_PROP
8936     lvRefBlks(BlockSetOps::UninitVal())
8937     ,
8938 #endif // ASSERTION_PROP
8939     lvPerSsaData(comp->getAllocator())
8940 {
8941 }
8942
8943 /*
8944 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8945 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8946 XX                                                                           XX
8947 XX                   Miscellaneous Compiler stuff                            XX
8948 XX                                                                           XX
8949 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8950 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8951 */
8952
8953 // Values used to mark the types a stack slot is used for
8954
8955 const unsigned TYPE_REF_INT      = 0x01; // slot used as a 32-bit int
8956 const unsigned TYPE_REF_LNG      = 0x02; // slot used as a 64-bit long
8957 const unsigned TYPE_REF_FLT      = 0x04; // slot used as a 32-bit float
8958 const unsigned TYPE_REF_DBL      = 0x08; // slot used as a 64-bit float
8959 const unsigned TYPE_REF_PTR      = 0x10; // slot used as a 32-bit pointer
8960 const unsigned TYPE_REF_BYR      = 0x20; // slot used as a byref pointer
8961 const unsigned TYPE_REF_STC      = 0x40; // slot used as a struct
8962 const unsigned TYPE_REF_TYPEMASK = 0x7F; // bits that represent the type
8963
8964 // const unsigned TYPE_REF_ADDR_TAKEN  = 0x80; // slots address was taken
8965
8966 /*****************************************************************************
8967  *
8968  *  Variables to keep track of total code amounts.
8969  */
8970
8971 #if DISPLAY_SIZES
8972
8973 extern size_t grossVMsize;
8974 extern size_t grossNCsize;
8975 extern size_t totalNCsize;
8976
8977 extern unsigned genMethodICnt;
8978 extern unsigned genMethodNCnt;
8979 extern size_t   gcHeaderISize;
8980 extern size_t   gcPtrMapISize;
8981 extern size_t   gcHeaderNSize;
8982 extern size_t   gcPtrMapNSize;
8983
8984 #endif // DISPLAY_SIZES
8985
8986 /*****************************************************************************
8987  *
8988  *  Variables to keep track of basic block counts (more data on 1 BB methods)
8989  */
8990
8991 #if COUNT_BASIC_BLOCKS
8992 extern Histogram bbCntTable;
8993 extern Histogram bbOneBBSizeTable;
8994 #endif
8995
8996 /*****************************************************************************
8997  *
8998  *  Used by optFindNaturalLoops to gather statistical information such as
8999  *   - total number of natural loops
9000  *   - number of loops with 1, 2, ... exit conditions
9001  *   - number of loops that have an iterator (for like)
9002  *   - number of loops that have a constant iterator
9003  */
9004
9005 #if COUNT_LOOPS
9006
9007 extern unsigned totalLoopMethods;        // counts the total number of methods that have natural loops
9008 extern unsigned maxLoopsPerMethod;       // counts the maximum number of loops a method has
9009 extern unsigned totalLoopOverflows;      // # of methods that identified more loops than we can represent
9010 extern unsigned totalLoopCount;          // counts the total number of natural loops
9011 extern unsigned totalUnnatLoopCount;     // counts the total number of (not-necessarily natural) loops
9012 extern unsigned totalUnnatLoopOverflows; // # of methods that identified more unnatural loops than we can represent
9013 extern unsigned iterLoopCount;           // counts the # of loops with an iterator (for like)
9014 extern unsigned simpleTestLoopCount;     // counts the # of loops with an iterator and a simple loop condition (iter <
9015                                          // const)
9016 extern unsigned  constIterLoopCount;     // counts the # of loops with a constant iterator (for like)
9017 extern bool      hasMethodLoops;         // flag to keep track if we already counted a method as having loops
9018 extern unsigned  loopsThisMethod;        // counts the number of loops in the current method
9019 extern bool      loopOverflowThisMethod; // True if we exceeded the max # of loops in the method.
9020 extern Histogram loopCountTable;         // Histogram of loop counts
9021 extern Histogram loopExitCountTable;     // Histogram of loop exit counts
9022
9023 #endif // COUNT_LOOPS
9024
9025 /*****************************************************************************
9026  * variables to keep track of how many iterations we go in a dataflow pass
9027  */
9028
9029 #if DATAFLOW_ITER
9030
9031 extern unsigned CSEiterCount; // counts the # of iteration for the CSE dataflow
9032 extern unsigned CFiterCount;  // counts the # of iteration for the Const Folding dataflow
9033
9034 #endif // DATAFLOW_ITER
9035
9036 #if MEASURE_BLOCK_SIZE
9037 extern size_t genFlowNodeSize;
9038 extern size_t genFlowNodeCnt;
9039 #endif // MEASURE_BLOCK_SIZE
9040
9041 #if MEASURE_NODE_SIZE
9042 struct NodeSizeStats
9043 {
9044     void Init()
9045     {
9046         genTreeNodeCnt        = 0;
9047         genTreeNodeSize       = 0;
9048         genTreeNodeActualSize = 0;
9049     }
9050
9051     size_t genTreeNodeCnt;
9052     size_t genTreeNodeSize;       // The size we allocate
9053     size_t genTreeNodeActualSize; // The actual size of the node. Note that the actual size will likely be smaller
9054                                   //   than the allocated size, but we sometimes use SetOper()/ChangeOper() to change
9055                                   //   a smaller node to a larger one. TODO-Cleanup: add stats on
9056                                   //   SetOper()/ChangeOper() usage to quanitfy this.
9057 };
9058 extern NodeSizeStats genNodeSizeStats;        // Total node size stats
9059 extern NodeSizeStats genNodeSizeStatsPerFunc; // Per-function node size stats
9060 extern Histogram     genTreeNcntHist;
9061 extern Histogram     genTreeNsizHist;
9062 #endif // MEASURE_NODE_SIZE
9063
9064 /*****************************************************************************
9065  *  Count fatal errors (including noway_asserts).
9066  */
9067
9068 #if MEASURE_FATAL
9069 extern unsigned fatal_badCode;
9070 extern unsigned fatal_noWay;
9071 extern unsigned fatal_NOMEM;
9072 extern unsigned fatal_noWayAssertBody;
9073 #ifdef DEBUG
9074 extern unsigned fatal_noWayAssertBodyArgs;
9075 #endif // DEBUG
9076 extern unsigned fatal_NYI;
9077 #endif // MEASURE_FATAL
9078
9079 /*****************************************************************************
9080  * Codegen
9081  */
9082
9083 #ifdef _TARGET_XARCH_
9084
9085 const instruction INS_SHIFT_LEFT_LOGICAL  = INS_shl;
9086 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_shr;
9087 const instruction INS_SHIFT_RIGHT_ARITHM  = INS_sar;
9088
9089 const instruction INS_AND             = INS_and;
9090 const instruction INS_OR              = INS_or;
9091 const instruction INS_XOR             = INS_xor;
9092 const instruction INS_NEG             = INS_neg;
9093 const instruction INS_TEST            = INS_test;
9094 const instruction INS_MUL             = INS_imul;
9095 const instruction INS_SIGNED_DIVIDE   = INS_idiv;
9096 const instruction INS_UNSIGNED_DIVIDE = INS_div;
9097 const instruction INS_BREAKPOINT      = INS_int3;
9098 const instruction INS_ADDC            = INS_adc;
9099 const instruction INS_SUBC            = INS_sbb;
9100 const instruction INS_NOT             = INS_not;
9101
9102 #endif
9103
9104 #ifdef _TARGET_ARM_
9105
9106 const instruction INS_SHIFT_LEFT_LOGICAL  = INS_lsl;
9107 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_lsr;
9108 const instruction INS_SHIFT_RIGHT_ARITHM  = INS_asr;
9109
9110 const instruction INS_AND             = INS_and;
9111 const instruction INS_OR              = INS_orr;
9112 const instruction INS_XOR             = INS_eor;
9113 const instruction INS_NEG             = INS_rsb;
9114 const instruction INS_TEST            = INS_tst;
9115 const instruction INS_MUL             = INS_mul;
9116 const instruction INS_SIGNED_DIVIDE   = INS_sdiv;
9117 const instruction INS_UNSIGNED_DIVIDE = INS_udiv;
9118 const instruction INS_BREAKPOINT      = INS_bkpt;
9119 const instruction INS_ADDC            = INS_adc;
9120 const instruction INS_SUBC            = INS_sbc;
9121 const instruction INS_NOT             = INS_mvn;
9122
9123 #endif
9124
9125 #ifdef _TARGET_ARM64_
9126
9127 const instruction INS_SHIFT_LEFT_LOGICAL  = INS_lsl;
9128 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_lsr;
9129 const instruction INS_SHIFT_RIGHT_ARITHM  = INS_asr;
9130
9131 const instruction INS_AND             = INS_and;
9132 const instruction INS_OR              = INS_orr;
9133 const instruction INS_XOR             = INS_eor;
9134 const instruction INS_NEG             = INS_neg;
9135 const instruction INS_TEST            = INS_tst;
9136 const instruction INS_MUL             = INS_mul;
9137 const instruction INS_SIGNED_DIVIDE   = INS_sdiv;
9138 const instruction INS_UNSIGNED_DIVIDE = INS_udiv;
9139 const instruction INS_BREAKPOINT      = INS_bkpt;
9140 const instruction INS_ADDC            = INS_adc;
9141 const instruction INS_SUBC            = INS_sbc;
9142 const instruction INS_NOT             = INS_mvn;
9143
9144 #endif
9145
9146 /*****************************************************************************/
9147
9148 extern const BYTE genTypeSizes[];
9149 extern const BYTE genTypeAlignments[];
9150 extern const BYTE genTypeStSzs[];
9151 extern const BYTE genActualTypes[];
9152
9153 /*****************************************************************************/
9154
9155 // VERY_LARGE_FRAME_SIZE_REG_MASK is the set of registers we need to use for
9156 // the probing loop generated for very large stack frames (see `getVeryLargeFrameSize`).
9157
9158 #ifdef _TARGET_ARM_
9159 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R4 | RBM_R5 | RBM_R6)
9160 #elif defined(_TARGET_ARM64_)
9161 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R9 | RBM_R10 | RBM_R11)
9162 #endif
9163
9164 /*****************************************************************************/
9165
9166 #define REG_CORRUPT regNumber(REG_NA + 1)
9167 #define RBM_CORRUPT (RBM_ILLEGAL | regMaskTP(1))
9168 #define REG_PAIR_CORRUPT regPairNo(REG_PAIR_NONE + 1)
9169
9170 /*****************************************************************************/
9171
9172 extern BasicBlock dummyBB;
9173
9174 /*****************************************************************************/
9175 /*****************************************************************************/
9176
9177 // foreach_treenode_execution_order: An iterator that iterates through all the tree
9178 // nodes of a statement in execution order.
9179 //      __stmt: a GT_STMT type GenTree*
9180 //      __node: a GenTree*, already declared, that gets updated with each node in the statement, in execution order
9181
9182 #define foreach_treenode_execution_order(__node, __stmt)                                                               \
9183     for ((__node) = (__stmt)->gtStmt.gtStmtList; (__node); (__node) = (__node)->gtNext)
9184
9185 // foreach_block: An iterator over all blocks in the function.
9186 //    __compiler: the Compiler* object
9187 //    __block   : a BasicBlock*, already declared, that gets updated each iteration.
9188
9189 #define foreach_block(__compiler, __block)                                                                             \
9190     for ((__block) = (__compiler)->fgFirstBB; (__block); (__block) = (__block)->bbNext)
9191
9192 /*****************************************************************************/
9193 /*****************************************************************************/
9194
9195 #ifdef DEBUG
9196
9197 void dumpConvertedVarSet(Compiler* comp, VARSET_VALARG_TP vars);
9198
9199 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9200 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9201 XX                                                                           XX
9202 XX                          Debugging helpers                                XX
9203 XX                                                                           XX
9204 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9205 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9206 */
9207
9208 /*****************************************************************************/
9209 /* The following functions are intended to be called from the debugger, to dump
9210  * various data structures. The can be used in the debugger Watch or Quick Watch
9211  * windows. They are designed to be short to type and take as few arguments as
9212  * possible. The 'c' versions take a Compiler*, whereas the 'd' versions use the TlsCompiler.
9213  * See the function definition comment for more details.
9214  */
9215
9216 void cBlock(Compiler* comp, BasicBlock* block);
9217 void cBlocks(Compiler* comp);
9218 void cBlocksV(Compiler* comp);
9219 void cTree(Compiler* comp, GenTree* tree);
9220 void cTrees(Compiler* comp);
9221 void cEH(Compiler* comp);
9222 void cVar(Compiler* comp, unsigned lclNum);
9223 void cVarDsc(Compiler* comp, LclVarDsc* varDsc);
9224 void cVars(Compiler* comp);
9225 void cVarsFinal(Compiler* comp);
9226 void cBlockPreds(Compiler* comp, BasicBlock* block);
9227 void cReach(Compiler* comp);
9228 void cDoms(Compiler* comp);
9229 void cLiveness(Compiler* comp);
9230 void cCVarSet(Compiler* comp, VARSET_VALARG_TP vars);
9231
9232 void cFuncIR(Compiler* comp);
9233 void cBlockIR(Compiler* comp, BasicBlock* block);
9234 void cLoopIR(Compiler* comp, Compiler::LoopDsc* loop);
9235 void cTreeIR(Compiler* comp, GenTree* tree);
9236 int cTreeTypeIR(Compiler* comp, GenTree* tree);
9237 int cTreeKindsIR(Compiler* comp, GenTree* tree);
9238 int cTreeFlagsIR(Compiler* comp, GenTree* tree);
9239 int cOperandIR(Compiler* comp, GenTree* operand);
9240 int cLeafIR(Compiler* comp, GenTree* tree);
9241 int cIndirIR(Compiler* comp, GenTree* tree);
9242 int cListIR(Compiler* comp, GenTree* list);
9243 int cSsaNumIR(Compiler* comp, GenTree* tree);
9244 int cValNumIR(Compiler* comp, GenTree* tree);
9245 int cDependsIR(Compiler* comp, GenTree* comma, bool* first);
9246
9247 void dBlock(BasicBlock* block);
9248 void dBlocks();
9249 void dBlocksV();
9250 void dTree(GenTree* tree);
9251 void dTrees();
9252 void dEH();
9253 void dVar(unsigned lclNum);
9254 void dVarDsc(LclVarDsc* varDsc);
9255 void dVars();
9256 void dVarsFinal();
9257 void dBlockPreds(BasicBlock* block);
9258 void dReach();
9259 void dDoms();
9260 void dLiveness();
9261 void dCVarSet(VARSET_VALARG_TP vars);
9262
9263 void dVarSet(VARSET_VALARG_TP vars);
9264 void dRegMask(regMaskTP mask);
9265
9266 void dFuncIR();
9267 void dBlockIR(BasicBlock* block);
9268 void dTreeIR(GenTree* tree);
9269 void dLoopIR(Compiler::LoopDsc* loop);
9270 void dLoopNumIR(unsigned loopNum);
9271 int dTabStopIR(int curr, int tabstop);
9272 int dTreeTypeIR(GenTree* tree);
9273 int dTreeKindsIR(GenTree* tree);
9274 int dTreeFlagsIR(GenTree* tree);
9275 int dOperandIR(GenTree* operand);
9276 int dLeafIR(GenTree* tree);
9277 int dIndirIR(GenTree* tree);
9278 int dListIR(GenTree* list);
9279 int dSsaNumIR(GenTree* tree);
9280 int dValNumIR(GenTree* tree);
9281 int dDependsIR(GenTree* comma);
9282 void dFormatIR();
9283
9284 GenTree* dFindTree(GenTree* tree, unsigned id);
9285 GenTree* dFindTree(unsigned id);
9286 GenTreeStmt* dFindStmt(unsigned id);
9287 BasicBlock* dFindBlock(unsigned bbNum);
9288
9289 #endif // DEBUG
9290
9291 #include "compiler.hpp" // All the shared inline functions
9292
9293 /*****************************************************************************/
9294 #endif //_COMPILER_H_
9295 /*****************************************************************************/