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.
5 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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
16 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
17 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
20 /*****************************************************************************/
23 /*****************************************************************************/
36 #include "simplerhash.h"
37 #include "cycletimer.h"
40 #include "arraystack.h"
43 #include "expandarray.h"
44 #include "tinyarray.h"
47 #include "jittelemetry.h"
52 #include "codegeninterface.h"
54 #include "jitgcinfo.h"
56 #if DUMP_GC_TABLES && defined(JIT32_GCENCODER)
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
68 /*****************************************************************************
69 * Forward declarations
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
82 class CSE_DataFlow; // defined in OptCSE.cpp
88 // The following are defined in this file, Compiler.h
92 /*****************************************************************************
98 /*****************************************************************************/
101 // Declare global operator new overloads that use the Compiler::compGetMem() function for allocation.
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);
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);
114 // Requires the definitions of "operator new" so including "LoopCloning.h" after the definitions.
115 #include "loopcloning.h"
117 /*****************************************************************************/
119 /* This is included here and not earlier as it needs the definition of "CSE"
120 * which is defined in the section above */
122 /*****************************************************************************/
124 unsigned genLog2(unsigned value);
125 unsigned genLog2(unsigned __int64 value);
127 var_types genActualType(var_types type);
128 var_types genUnsignedType(var_types type);
129 var_types genSignedType(var_types type);
131 unsigned ReinterpretHexAsDecimal(unsigned);
133 /*****************************************************************************/
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));
146 const unsigned FLG_CCTOR = (CORINFO_FLG_CONSTRUCTOR | CORINFO_FLG_STATIC);
149 const int BAD_STK_OFFS = 0xBAADF00D; // for LclVarDsc::lvStkOffs
152 // The following holds the Local var info (scope information)
153 typedef const char* VarName; // Actual ASCII string
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
161 VarName vsdName; // name of the var
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.
170 /*****************************************************************************
172 * The following holds the local variable counts and the descriptor table.
175 // This is the location of a definition.
181 DefLoc() : m_blk(nullptr), m_tree(nullptr)
186 // This class encapsulates all info about a local variable that may vary for different SSA names
191 ValueNumPair m_vnPair;
199 typedef ExpandArray<LclSsaVarDsc> PerSsaArray;
204 // The constructor. Most things can just be zero'ed.
205 LclVarDsc(Compiler* comp);
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
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)
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()
223 return lvTracked && lvType != TYP_STRUCT;
225 unsigned char lvPinned : 1; // is this a pinned variable?
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
236 // These further document the reasons for setting "lvDoNotEnregister". (Note that "lvAddrExposed" is one of the
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.
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
255 unsigned char lvArgWrite : 1; // variable is a parameter and STARG was used on it
256 unsigned char lvIsTemp : 1; // Short-lifetime compiler temp
258 unsigned char lvIsBoolean : 1; // set if variable is boolean
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
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
272 unsigned char lvAssignOne : 1; // assigned at least once?
273 unsigned char lvAssignTwo : 1; // assigned at least twice?
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
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
287 unsigned char lvIsPtr : 1; // Might this be used in an address computation? (used by buffer overflow security
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
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"
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
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
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.
316 #ifndef LEGACY_BACKEND
317 unsigned char lvLRACandidate : 1; // Tracked for linear scan register allocation purposes
318 #endif // !LEGACY_BACKEND
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.
329 unsigned lvFieldLclStart; // The index of the local var representing the first field in the promoted struct
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.
334 var_types lvBaseType; // The base type of a SIMD local var. Valid on TYP_SIMD locals.
335 #endif // FEATURE_SIMD
338 unsigned char lvFieldCnt; // Number of fields in the promoted VarDsc.
339 unsigned char lvFldOffset;
340 unsigned char lvFldOrdinal;
342 #if FEATURE_MULTIREG_ARGS
343 regNumber lvRegNumForSlot(unsigned slotNum)
349 else if (slotNum == 1)
351 return lvOtherArgReg;
355 assert(false && "Invalid slotNum!");
360 #endif // FEATURE_MULTIREG_ARGS
378 bool lvIsHfaRegArg() const
381 return _lvIsHfaRegArg;
387 void lvSetIsHfaRegArg()
390 _lvIsHfaRegArg = true;
394 bool lvHfaTypeIsFloat() const
397 return _lvHfaTypeIsFloat;
403 void lvSetHfaTypeIsFloat(bool value)
406 _lvHfaTypeIsFloat = value;
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
413 unsigned lvHfaSlots() const
416 assert(lvType == TYP_STRUCT);
418 return lvExactSize / sizeof(float);
419 #else // _TARGET_ARM64_
420 if (lvHfaTypeIsFloat())
422 return lvExactSize / sizeof(float);
426 return lvExactSize / sizeof(double);
428 #endif // _TARGET_ARM64_
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()
436 return lvIsMultiRegArg || lvIsMultiRegRet;
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
446 #if !defined(_TARGET_64BIT_)
447 regNumberSmall _lvOtherReg; // Used for "upper half" of long var.
448 #endif // !defined(_TARGET_64BIT_)
450 regNumberSmall _lvArgReg; // The register in which this argument is passed.
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
457 #ifndef LEGACY_BACKEND
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
462 #endif // !LEGACY_BACKEND
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.
468 /////////////////////
470 __declspec(property(get = GetRegNum, put = SetRegNum)) regNumber lvRegNum;
472 regNumber GetRegNum() const
474 return (regNumber)_lvRegNum;
477 void SetRegNum(regNumber reg)
479 _lvRegNum = (regNumberSmall)reg;
480 assert(_lvRegNum == reg);
483 /////////////////////
485 #if defined(_TARGET_64BIT_)
486 __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
488 regNumber GetOtherReg() const
490 assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
491 // "unreachable code" warnings
495 void SetOtherReg(regNumber reg)
497 assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
498 // "unreachable code" warnings
500 #else // !_TARGET_64BIT_
501 __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
503 regNumber GetOtherReg() const
505 return (regNumber)_lvOtherReg;
508 void SetOtherReg(regNumber reg)
510 _lvOtherReg = (regNumberSmall)reg;
511 assert(_lvOtherReg == reg);
513 #endif // !_TARGET_64BIT_
515 /////////////////////
517 __declspec(property(get = GetArgReg, put = SetArgReg)) regNumber lvArgReg;
519 regNumber GetArgReg() const
521 return (regNumber)_lvArgReg;
524 void SetArgReg(regNumber reg)
526 _lvArgReg = (regNumberSmall)reg;
527 assert(_lvArgReg == reg);
530 #if FEATURE_MULTIREG_ARGS
531 __declspec(property(get = GetOtherArgReg, put = SetOtherArgReg)) regNumber lvOtherArgReg;
533 regNumber GetOtherArgReg() const
535 return (regNumber)_lvOtherArgReg;
538 void SetOtherArgReg(regNumber reg)
540 _lvOtherArgReg = (regNumberSmall)reg;
541 assert(_lvOtherArgReg == reg);
543 #endif // FEATURE_MULTIREG_ARGS
546 // Is this is a SIMD struct?
547 bool lvIsSIMDType() const
552 // Is this is a SIMD struct which is used for SIMD intrinsic?
553 bool lvIsUsedInSIMDIntrinsic() const
555 return lvUsedInSIMDIntrinsic;
558 // If feature_simd not enabled, return false
559 bool lvIsSIMDType() const
563 bool lvIsUsedInSIMDIntrinsic() const
569 /////////////////////
571 #ifndef LEGACY_BACKEND
572 __declspec(property(get = GetArgInitReg, put = SetArgInitReg)) regNumber lvArgInitReg;
574 regNumber GetArgInitReg() const
576 return (regNumber)_lvArgInitReg;
579 void SetArgInitReg(regNumber reg)
581 _lvArgInitReg = (regNumberSmall)reg;
582 assert(_lvArgInitReg == reg);
585 /////////////////////
587 __declspec(property(get = GetArgInitRegPair, put = SetArgInitRegPair)) regPairNo lvArgInitRegPair;
589 regPairNo GetArgInitRegPair() const
591 regPairNo regPair = (regPairNo)_lvArgInitRegPair;
592 assert(regPair >= REG_PAIR_FIRST && regPair <= REG_PAIR_LAST);
596 void SetArgInitRegPair(regPairNo regPair)
598 assert(regPair >= REG_PAIR_FIRST && regPair <= REG_PAIR_LAST);
599 _lvArgInitRegPair = (regPairNoSmall)regPair;
600 assert(_lvArgInitRegPair == regPair);
603 /////////////////////
605 bool lvIsRegCandidate() const
607 return lvLRACandidate != 0;
610 bool lvIsInReg() const
612 return lvIsRegCandidate() && (lvRegNum != REG_STK);
615 #else // LEGACY_BACKEND
617 bool lvIsRegCandidate() const
619 return lvTracked != 0;
622 bool lvIsInReg() const
624 return lvRegister != 0;
627 #endif // LEGACY_BACKEND
629 regMaskTP lvRegMask() const
631 regMaskTP regMask = RBM_NONE;
632 if (varTypeIsFloating(TypeGet()))
634 if (lvRegNum != REG_STK)
636 regMask = genRegMaskFloat(lvRegNum, TypeGet());
641 if (lvRegNum != REG_STK)
643 regMask = genRegMask(lvRegNum);
646 // For longs we may have two regs
647 if (isRegPairType(lvType) && lvOtherReg != REG_STK)
649 regMask |= genRegMask(lvOtherReg);
655 regMaskSmall lvPrefReg; // set of regs it prefers to live in
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
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()
672 #if !defined(_TARGET_64BIT_)
673 return (lvPromoted && !varTypeIsLong(lvType));
674 #else // defined(_TARGET_64BIT_)
676 #endif // defined(_TARGET_64BIT_)
679 unsigned lvSize() // Size needed for storage representation. Only used for structs or TYP_BLK.
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.
693 assert(varTypeIsStruct(lvType) || (lvType == TYP_BLK) || (lvPromoted && lvUnusedStruct));
694 return (unsigned)(roundUp(lvExactSize, TARGET_POINTER_SIZE));
697 #if defined(DEBUGGING_SUPPORT) || defined(DEBUG)
698 unsigned lvSlotNum; // original slot # (if remapped)
701 typeInfo lvVerTypeInfo; // type info needed for verification
703 BYTE* lvGcLayout; // GC layout info for structs
706 GenTreePtr lvKnownDim; // array size if known
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
714 var_types TypeGet() const
716 return (var_types)lvType;
718 bool lvStackAligned() const
720 assert(lvIsStructField);
721 return ((lvFldOffset % sizeof(void*)) == 0);
723 bool lvNormalizeOnLoad() const
725 return varTypeIsSmall(TypeGet()) &&
726 // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
727 (lvIsParam || lvAddrExposed || lvIsStructField);
730 bool lvNormalizeOnStore()
732 return varTypeIsSmall(TypeGet()) &&
733 // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
734 !(lvIsParam || lvAddrExposed || lvIsStructField);
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
744 return isFloatRegType(lvType) || lvIsHfaRegArg();
746 var_types GetHfaType() const
748 return lvIsHfa() ? (lvHfaTypeIsFloat() ? TYP_FLOAT : TYP_DOUBLE) : TYP_UNDEF;
750 void SetHfaType(var_types type)
752 assert(varTypeIsFloating(type));
753 lvSetHfaTypeIsFloat(type == TYP_FLOAT);
756 #ifndef LEGACY_BACKEND
757 var_types lvaArgType();
760 PerSsaArray lvPerSsaData;
763 // Keep track of the # of SsaNames, for a bounds check.
764 unsigned lvNumSsaNames;
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)
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);
781 void PrintVarReg() const
783 if (isRegPairType(TypeGet()))
785 printf("%s:%s", getRegName(lvOtherReg), // hi32
786 getRegName(lvRegNum)); // lo32
790 printf("%s", getRegName(lvRegNum));
795 }; // class LclVarDsc
798 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
799 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
803 XX The temporary lclVars allocated by the compiler for code generation XX
805 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
806 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
809 /*****************************************************************************
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.
815 * These are different from the more common temps allocated by lvaGrabTemp().
826 static const int BAD_TEMP_OFFSET = 0xDDDDDDDD; // used as a sentinel "bad value" for tdOffs in DEBUG
834 TempDsc(int _tdNum, unsigned _tdSize, var_types _tdType) : tdNum(_tdNum), tdSize((BYTE)_tdSize), tdType(_tdType)
838 0); // temps must have a negative number (so they have a different number from all local variables)
839 tdOffs = BAD_TEMP_OFFSET;
843 IMPL_LIMITATION("too many spill temps");
848 bool tdLegalOffset() const
850 return tdOffs != BAD_TEMP_OFFSET;
854 int tdTempOffs() const
856 assert(tdLegalOffset());
859 void tdSetTempOffs(int offs)
862 assert(tdLegalOffset());
864 void tdAdjustTempOffs(int offs)
867 assert(tdLegalOffset());
870 int tdTempNum() const
875 unsigned tdTempSize() const
879 var_types tdTempType() const
885 // interface to hide linearscan implementation from rest of compiler
886 class LinearScanInterface
889 virtual void doLinearScan() = 0;
890 virtual void recordVarLocationsAtStartOfBB(BasicBlock* bb) = 0;
893 LinearScanInterface* getLinearScanAllocator(Compiler* comp);
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.
901 var_types m_elemType;
902 CORINFO_CLASS_HANDLE m_elemStructType;
904 unsigned m_elemOffset;
906 ArrayInfo() : m_elemType(TYP_UNDEF), m_elemStructType(nullptr), m_elemSize(0), m_elemOffset(0)
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)
916 // This enumeration names the phases into which we divide compilation. The phases should completely
917 // partition a compilation.
920 #define CompPhaseNameMacro(enum_nm, string_nm, short_nm, hasChildren, parent) enum_nm,
921 #include "compphases.h"
925 extern const char* PhaseNames[];
926 extern const char* PhaseEnums[];
927 extern const LPCWSTR PhaseShortNames[];
929 //---------------------------------------------------------------
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.
941 #ifdef FEATURE_JIT_METHOD_PERF
942 // The string names of the phases.
943 static const char* PhaseNames[];
945 static bool PhaseHasChildren[];
946 static int PhaseParent[];
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;
963 CompTimeInfo(unsigned byteCodeBytes);
967 #ifdef FEATURE_JIT_METHOD_PERF
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
976 // This lock protects the fields of all CompTimeSummaryInfo(s) (of which we expect there to be one).
977 static CritSecObject s_compTimeSummaryLock;
980 CompTimeInfo m_total;
981 CompTimeInfo m_maximum;
983 int m_numFilteredMethods;
984 CompTimeInfo m_filtered;
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();
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);
996 // This is the unique CompTimeSummaryInfo object for this instance of the runtime.
997 static CompTimeSummaryInfo s_compTimeSummary;
999 CompTimeSummaryInfo() : m_total(0), m_maximum(0), m_numMethods(0), m_filtered(0), m_numFilteredMethods(0)
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);
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);
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.
1018 unsigned __int64 m_start; // Start of the compilation.
1019 unsigned __int64 m_curPhaseStart; // Start of the current phase.
1021 Phases m_lastPhase; // The last phase that was completed (or (Phases)-1 to start).
1023 CompTimeInfo m_info; // The CompTimeInfo for this compilation.
1025 static CritSecObject s_csvLock; // Lock to protect the time log file.
1026 void PrintCsvMethodStats(Compiler* comp);
1029 void* operator new(size_t);
1030 void* operator new[](size_t);
1031 void operator delete(void*);
1032 void operator delete[](void*);
1035 // Initialized the timer instance
1036 JitTimer(unsigned byteCodeSize);
1038 static JitTimer* Create(Compiler* comp, unsigned byteCodeSize)
1040 return ::new (comp, CMK_Unknown) JitTimer(byteCodeSize);
1043 static void PrintCsvHeader();
1045 // Ends the current phase (argument is for a redundant check).
1046 void EndPhase(Phases phase);
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);
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)
1057 bool res = CycleTimer::GetThreadCyclesS(cycles);
1060 m_info.m_timerFailure = true;
1065 #endif // FEATURE_JIT_METHOD_PERF
1067 //------------------- Function/Funclet info -------------------------------
1068 DECLARE_TYPED_ENUM(FuncKind, BYTE)
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
1075 END_DECLARE_TYPED_ENUM(FuncKind, BYTE)
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
1087 #if defined(_TARGET_AMD64_)
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;
1100 #ifdef UNIX_AMD64_ABI
1101 jitstd::vector<CFI_CODE>* cfiCodes;
1102 #endif // UNIX_AMD64_ABI
1104 #elif defined(_TARGET_ARMARCH_)
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.
1114 #endif // _TARGET_ARMARCH_
1116 // Eventually we may want to move rsModifiedRegsMask, lvaOutgoingArgSize, and anything else
1117 // that isn't shared between the main function body and funclets.
1120 struct fgArgTabEntry
1123 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1126 otherRegNum = REG_NA;
1127 isStruct = false; // is this a struct arg
1129 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1131 GenTreePtr node; // Initially points at the Op1 field of 'parent', but if the argument is replaced with an GT_ASG or
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
1136 unsigned argNum; // The original argument number, also specifies the required argument evaluation order from the IL
1138 regNumber regNum; // The (first) register to use when passing this argument, set to REG_STK for arguments passed on
1140 unsigned numRegs; // Count of number of registers that this argument uses
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
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
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.
1161 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1162 bool isStruct : 1; // True if this is a struct arg
1164 regNumber otherRegNum; // The (second) register to use when passing this argument.
1166 SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR structDesc;
1167 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1170 void SetIsHfaRegArg(bool hfaRegArg)
1172 isHfaRegArg = hfaRegArg;
1175 void SetIsBackFilled(bool backFilled)
1177 isBackFilled = backFilled;
1180 bool IsBackFilled() const
1182 return isBackFilled;
1184 #else // !_TARGET_ARM_
1185 // To make the callers easier, we allow these calls (and the isHfaRegArg and isBackFilled data members) for all
1187 void SetIsHfaRegArg(bool hfaRegArg)
1191 void SetIsBackFilled(bool backFilled)
1195 bool IsBackFilled() const
1199 #endif // !_TARGET_ARM_
1205 typedef struct fgArgTabEntry* fgArgTabEntryPtr;
1207 //-------------------------------------------------------------------------
1209 // The class fgArgInfo is used to handle the arguments
1210 // when morphing a GT_CALL node.
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)
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])
1229 void AddArg(fgArgTabEntryPtr curArgTabEntry);
1232 fgArgInfo(Compiler* comp, GenTreePtr call, unsigned argCount);
1233 fgArgInfo(GenTreePtr newCall, GenTreePtr oldCall);
1235 fgArgTabEntryPtr AddRegArg(
1236 unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment);
1238 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
1239 fgArgTabEntryPtr AddRegArg(
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
1251 fgArgTabEntryPtr AddStkArg(unsigned argNum,
1255 unsigned alignment FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool isStruct));
1257 void RemorphReset();
1258 fgArgTabEntryPtr RemorphRegArg(
1259 unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment);
1261 void RemorphStkArg(unsigned argNum, GenTreePtr node, GenTreePtr parent, unsigned numSlots, unsigned alignment);
1263 void SplitArg(unsigned argNum, unsigned numRegs, unsigned numSlots);
1265 void EvalToTmp(unsigned argNum, unsigned tmpNum, GenTreePtr newNode);
1267 void ArgsComplete();
1271 void EvalArgsToTemps();
1273 void RecordStkLevel(unsigned stkLvl);
1274 unsigned RetrieveStkLevel();
1280 fgArgTabEntryPtr* ArgTable()
1284 unsigned GetNextSlotNum()
1294 return hasStackArgs;
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.
1304 enum TestLabel // This must be kept identical to System.Runtime.CompilerServices.JitTestLabel.TestLabel.
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.
1314 struct TestLabelAndNum
1319 TestLabelAndNum() : m_tl(TestLabel(0)), m_num(0)
1324 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, TestLabelAndNum, JitSimplerHashBehavior> NodeToTestDataMap;
1326 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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.
1332 class CompAllocator : public IAllocator
1335 #if MEASURE_MEM_ALLOC
1339 CompAllocator(Compiler* comp, CompMemKind cmk)
1341 #if MEASURE_MEM_ALLOC
1347 inline void* Alloc(size_t sz);
1349 inline void* ArrayAlloc(size_t elems, size_t elemSize);
1351 // For the compiler's no-release allocator, free operations are no-ops.
1358 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1359 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1361 XX The big guy. The sections are currently organized as : XX
1363 XX o GenTree and BasicBlock XX
1375 XX o PrologScopeInfo XX
1376 XX o CodeGenerator XX
1381 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1382 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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;
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;
1404 friend class ObjectAllocator;
1406 #ifndef _TARGET_64BIT_
1407 friend class DecomposeLongs;
1408 #endif // !_TARGET_64BIT_
1411 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1412 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1414 XX Misc structs definitions XX
1416 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1417 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1421 hashBvGlobalData hbvGlobalData; // Used by the hashBv bitvector package.
1440 bool dumpIRDataflow;
1441 bool dumpIRBlockHeaders;
1443 LPCWSTR dumpIRPhase;
1444 LPCWSTR dumpIRFormat;
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.
1454 const char* VarNameToStr(VarName name)
1459 DWORD expensiveDebugCheckLevel;
1462 #if FEATURE_MULTIREG_RET
1463 GenTreePtr impAssignMultiRegTypeToVar(GenTreePtr op, CORINFO_CLASS_HANDLE hClass);
1464 #endif // FEATURE_MULTIREG_RET
1467 bool isSingleFloat32Struct(CORINFO_CLASS_HANDLE hClass);
1468 #endif // ARM_SOFTFP
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.
1478 bool IsHfa(CORINFO_CLASS_HANDLE hClass);
1479 bool IsHfa(GenTreePtr tree);
1481 var_types GetHfaType(GenTreePtr tree);
1482 unsigned GetHfaCount(GenTreePtr tree);
1484 var_types GetHfaType(CORINFO_CLASS_HANDLE hClass);
1485 unsigned GetHfaCount(CORINFO_CLASS_HANDLE hClass);
1487 bool IsMultiRegPassedType(CORINFO_CLASS_HANDLE hClass);
1488 bool IsMultiRegReturnedType(CORINFO_CLASS_HANDLE hClass);
1490 //-------------------------------------------------------------------------
1491 // The following is used for validating format of EH table
1495 typedef struct EHNodeDsc* pEHNodeDsc;
1497 EHNodeDsc* ehnTree; // root of the tree comprising the EHnodes.
1498 EHNodeDsc* ehnNext; // root of the tree comprising the EHnodes.
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
1516 pEHNodeDsc ehnNext; // next (non-nested) block in sequential order
1517 pEHNodeDsc ehnChild; // leftmost nested block
1519 pEHNodeDsc ehnTryNode; // for filters and handlers, the corresponding try node
1520 pEHNodeDsc ehnHandlerNode; // for a try node, the corresponding handler node
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,
1525 inline void ehnSetTryNodeType()
1527 ehnBlockType = TryNode;
1529 inline void ehnSetFilterNodeType()
1531 ehnBlockType = FilterNode;
1533 inline void ehnSetHandlerNodeType()
1535 ehnBlockType = HandlerNode;
1537 inline void ehnSetFinallyNodeType()
1539 ehnBlockType = FinallyNode;
1541 inline void ehnSetFaultNodeType()
1543 ehnBlockType = FaultNode;
1546 inline BOOL ehnIsTryBlock()
1548 return ehnBlockType == TryNode;
1550 inline BOOL ehnIsFilterBlock()
1552 return ehnBlockType == FilterNode;
1554 inline BOOL ehnIsHandlerBlock()
1556 return ehnBlockType == HandlerNode;
1558 inline BOOL ehnIsFinallyBlock()
1560 return ehnBlockType == FinallyNode;
1562 inline BOOL ehnIsFaultBlock()
1564 return ehnBlockType == FaultNode;
1567 // returns true if there is any overlap between the two nodes
1568 static inline BOOL ehnIsOverlap(pEHNodeDsc node1, pEHNodeDsc node2)
1570 if (node1->ehnStartOffset < node2->ehnStartOffset)
1572 return (node1->ehnEndOffset >= node2->ehnStartOffset);
1576 return (node1->ehnStartOffset <= node2->ehnEndOffset);
1580 // fails with BADCODE if inner is not completely nested inside outer
1581 static inline BOOL ehnIsNested(pEHNodeDsc inner, pEHNodeDsc outer)
1583 return ((inner->ehnStartOffset >= outer->ehnStartOffset) && (inner->ehnEndOffset <= outer->ehnEndOffset));
1587 //-------------------------------------------------------------------------
1588 // Exception handling functions
1591 #if !FEATURE_EH_FUNCLETS
1593 bool ehNeedsShadowSPslots()
1595 return (info.compXcptnsCount || opts.compDbgEnC);
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
1602 unsigned ehMaxHndNestingCount;
1604 #endif // !FEATURE_EH_FUNCLETS
1606 static bool jitIsBetween(unsigned value, unsigned start, unsigned end);
1607 static bool jitIsBetweenInclusive(unsigned value, unsigned start, unsigned end);
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);
1617 unsigned short bbFindInnermostTryRegionContainingHandlerRegion(unsigned handlerIndex);
1618 unsigned short bbFindInnermostHandlerRegionContainingTryRegion(unsigned tryIndex);
1620 // Returns true if "block" is the start of a try region.
1621 bool bbIsTryBeg(BasicBlock* block);
1623 // Returns true if "block" is the start of a handler or filter region.
1624 bool bbIsHandlerBeg(BasicBlock* block);
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);
1632 bool ehHasCallableHandlers();
1634 // Return the EH descriptor for the given region index.
1635 EHblkDsc* ehGetDsc(unsigned regionIndex);
1637 // Return the EH index given a region descriptor.
1638 unsigned ehGetIndex(EHblkDsc* ehDsc);
1640 // Return the EH descriptor index of the enclosing try, for the given region index.
1641 unsigned ehGetEnclosingTryIndex(unsigned regionIndex);
1643 // Return the EH descriptor index of the enclosing handler, for the given region index.
1644 unsigned ehGetEnclosingHndIndex(unsigned regionIndex);
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);
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);
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);
1658 EHblkDsc* ehIsBlockTryLast(BasicBlock* block);
1659 EHblkDsc* ehIsBlockHndLast(BasicBlock* block);
1660 bool ehIsBlockEHLast(BasicBlock* block);
1662 bool ehBlockHasExnFlowDsc(BasicBlock* block);
1664 // Return the region index of the most nested EH region this block is in.
1665 unsigned ehGetMostNestedRegionIndex(BasicBlock* block, bool* inTryRegion);
1667 // Find the true enclosing try index, ignoring 'mutual protect' try. Uses IL ranges to check.
1668 unsigned ehTrueEnclosingTryIndexIL(unsigned regionIndex);
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);
1676 // A block has been deleted. Update the EH table appropriately.
1677 void ehUpdateForDeletedBlock(BasicBlock* block);
1679 // Determine whether a block can be deleted while preserving the EH normalization rules.
1680 bool ehCanDeleteEmptyBlock(BasicBlock* block);
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);
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);
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);
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);
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
1715 return compHndBBtabCount > 0;
1718 bool ehAnyFunclets(); // Are there any funclets in this function?
1719 unsigned ehFuncletCount(); // Return the count of funclets in the function
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()
1727 unsigned ehFuncletCount()
1732 unsigned bbThrowIndex(BasicBlock* blk)
1734 return blk->bbTryIndex;
1735 } // Get the index to use as the cache key for sharing throw blocks
1736 #endif // !FEATURE_EH_FUNCLETS
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);
1745 // This table is useful for memoization of the method above.
1746 typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, flowList*, JitSimplerHashBehavior>
1748 BlockToFlowListMap* m_blockToEHPreds;
1749 BlockToFlowListMap* GetBlockToEHPreds()
1751 if (m_blockToEHPreds == nullptr)
1753 m_blockToEHPreds = new (getAllocator()) BlockToFlowListMap(getAllocator());
1755 return m_blockToEHPreds;
1758 void* ehEmitCookie(BasicBlock* block);
1759 UNATIVE_OFFSET ehCodeOffset(BasicBlock* block);
1761 EHblkDsc* ehInitHndRange(BasicBlock* src, IL_OFFSET* hndBeg, IL_OFFSET* hndEnd, bool* inFilter);
1763 EHblkDsc* ehInitTryRange(BasicBlock* src, IL_OFFSET* tryBeg, IL_OFFSET* tryEnd);
1765 EHblkDsc* ehInitHndBlockRange(BasicBlock* blk, BasicBlock** hndBeg, BasicBlock** hndLast, bool* inFilter);
1767 EHblkDsc* ehInitTryBlockRange(BasicBlock* blk, BasicBlock** tryBeg, BasicBlock** tryLast);
1769 void fgSetTryEnd(EHblkDsc* handlerTab, BasicBlock* newTryLast);
1771 void fgSetHndEnd(EHblkDsc* handlerTab, BasicBlock* newHndLast);
1773 void fgSkipRmvdBlocks(EHblkDsc* handlerTab);
1775 void fgAllocEHTable();
1777 void fgRemoveEHTableEntry(unsigned XTnum);
1779 #if FEATURE_EH_FUNCLETS
1781 EHblkDsc* fgAddEHTableEntry(unsigned XTnum);
1783 #endif // FEATURE_EH_FUNCLETS
1787 #endif // !FEATURE_EH
1789 void fgSortEHTable();
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();
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();
1808 bool fgNeedToSortEHTable;
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);
1817 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1818 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1820 XX GenTree and BasicBlock XX
1822 XX Functions to allocate and display the GenTrees and BasicBlocks XX
1824 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1825 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1828 // Functions to create nodes
1829 GenTreeStmt* gtNewStmt(GenTreePtr expr = nullptr, IL_OFFSETX offset = BAD_IL_OFFSET);
1832 GenTreePtr gtNewOperNode(genTreeOps oper, var_types type, GenTreePtr op1, bool doSimplifications = TRUE);
1834 // For binary opers.
1835 GenTreePtr gtNewOperNode(genTreeOps oper, var_types type, GenTreePtr op1, GenTreePtr op2);
1837 GenTreePtr gtNewQmarkNode(var_types type, GenTreePtr cond, GenTreePtr colon);
1839 GenTreePtr gtNewLargeOperNode(genTreeOps oper,
1840 var_types type = TYP_I_IMPL,
1841 GenTreePtr op1 = nullptr,
1842 GenTreePtr op2 = nullptr);
1844 GenTreeIntCon* gtNewIconNode(ssize_t value, var_types type = TYP_INT);
1846 GenTree* gtNewPhysRegNode(regNumber reg, var_types type);
1848 GenTree* gtNewPhysRegNode(regNumber reg, GenTree* src);
1850 GenTreePtr gtNewJmpTableNode();
1851 GenTreePtr gtNewIconHandleNode(
1852 size_t value, unsigned flags, FieldSeqNode* fields = nullptr, unsigned handle1 = 0, void* handle2 = nullptr);
1854 unsigned gtTokenToIconFlags(unsigned token);
1856 GenTreePtr gtNewIconEmbHndNode(void* value,
1859 unsigned handle1 = 0,
1860 void* handle2 = nullptr,
1861 void* compileTimeHandle = nullptr);
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);
1868 GenTreePtr gtNewStringLiteralNode(InfoAccessType iat, void* pValue);
1870 GenTreePtr gtNewLconNode(__int64 value);
1872 GenTreePtr gtNewDconNode(double value);
1874 GenTreePtr gtNewSconNode(int CPX, CORINFO_MODULE_HANDLE scpHandle);
1876 GenTreePtr gtNewZeroConNode(var_types type);
1878 GenTreePtr gtNewOneConNode(var_types type);
1880 GenTreeBlkOp* gtNewBlkOpNode(
1881 genTreeOps oper, GenTreePtr dst, GenTreePtr srcOrFillVal, GenTreePtr sizeOrClsTok, bool volatil);
1884 void gtBlockOpInit(GenTreePtr node, genTreeOps oper, GenTreePtr dst, GenTreePtr src, GenTreePtr size, bool volatil);
1887 GenTreeObj* gtNewObjNode(CORINFO_CLASS_HANDLE structHnd, GenTreePtr addr);
1889 GenTreeBlkOp* gtNewCpObjNode(GenTreePtr dst, GenTreePtr src, CORINFO_CLASS_HANDLE structHnd, bool volatil);
1891 GenTreeBlkOp* gtCloneCpObjNode(GenTreeCpObj* source);
1893 GenTreeArgList* gtNewListNode(GenTreePtr op1, GenTreeArgList* op2);
1895 GenTreeCall* gtNewCallNode(gtCallTypes callType,
1896 CORINFO_METHOD_HANDLE handle,
1898 GenTreeArgList* args,
1899 IL_OFFSETX ilOffset = BAD_IL_OFFSET);
1901 GenTreeCall* gtNewIndCallNode(GenTreePtr addr,
1903 GenTreeArgList* args,
1904 IL_OFFSETX ilOffset = BAD_IL_OFFSET);
1906 GenTreeCall* gtNewHelperCallNode(unsigned helper,
1909 GenTreeArgList* args = nullptr);
1911 GenTreePtr gtNewLclvNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
1914 GenTreeSIMD* gtNewSIMDNode(
1915 var_types type, GenTreePtr op1, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
1916 GenTreeSIMD* gtNewSIMDNode(var_types type,
1919 SIMDIntrinsicID simdIntrinsicID,
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);
1928 GenTreePtr gtNewCodeRef(BasicBlock* block);
1930 GenTreePtr gtNewFieldRef(
1931 var_types typ, CORINFO_FIELD_HANDLE fldHnd, GenTreePtr obj = nullptr, DWORD offset = 0, bool nullcheck = false);
1933 GenTreePtr gtNewIndexRef(var_types typ, GenTreePtr arrayOp, GenTreePtr indexOp);
1935 GenTreeArgList* gtNewArgList(GenTreePtr op);
1936 GenTreeArgList* gtNewArgList(GenTreePtr op1, GenTreePtr op2);
1937 GenTreeArgList* gtNewArgList(GenTreePtr op1, GenTreePtr op2, GenTreePtr op3);
1939 GenTreeArgList* gtNewAggregate(GenTree* element);
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);
1946 GenTreePtr gtNewAssignNode(GenTreePtr dst, GenTreePtr src);
1948 GenTreePtr gtNewTempAssign(unsigned tmp, GenTreePtr val);
1950 GenTreePtr gtNewRefCOMfield(GenTreePtr objPtr,
1951 CORINFO_RESOLVED_TOKEN* pResolvedToken,
1952 CORINFO_ACCESS_FLAGS access,
1953 CORINFO_FIELD_INFO* pFieldInfo,
1955 CORINFO_CLASS_HANDLE structType,
1958 GenTreePtr gtNewNothingNode();
1960 GenTreePtr gtNewArgPlaceHolderNode(var_types type, CORINFO_CLASS_HANDLE clsHnd);
1962 GenTreePtr gtUnusedValNode(GenTreePtr expr);
1964 GenTreePtr gtNewCastNode(var_types typ, GenTreePtr op1, var_types castType);
1966 GenTreePtr gtNewCastNodeL(var_types typ, GenTreePtr op1, var_types castType);
1968 GenTreePtr gtNewAllocObjNode(unsigned int helper, CORINFO_CLASS_HANDLE clsHnd, var_types type, GenTreePtr op1);
1970 //------------------------------------------------------------------------
1971 // Other GenTree functions
1973 GenTreePtr gtClone(GenTree* tree, bool complexOK = false);
1975 GenTreePtr gtCloneExpr(GenTree* tree, unsigned addFlags = 0, unsigned varNum = (unsigned)-1, int varVal = 0);
1977 GenTreePtr gtReplaceTree(GenTreePtr stmt, GenTreePtr tree, GenTreePtr replacementTree);
1979 void gtUpdateSideEffects(GenTreePtr tree, unsigned oldGtFlags, unsigned newGtFlags);
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);
1987 bool gtCompareTree(GenTree* op1, GenTree* op2);
1989 GenTreePtr gtReverseCond(GenTree* tree);
1991 bool gtHasRef(GenTree* tree, ssize_t lclNum, bool defOnly);
1993 bool gtHasLocalsWithAddrOp(GenTreePtr tree);
1995 unsigned gtHashValue(GenTree* tree);
1997 unsigned gtSetListOrder(GenTree* list, bool regs, bool isListCallArgs);
1999 void gtWalkOp(GenTree** op1, GenTree** op2, GenTree* adr, bool constOnly);
2002 GenTreePtr gtWalkOpEffectiveVal(GenTreePtr op);
2005 void gtPrepareCost(GenTree* tree);
2006 bool gtIsLikelyRegVar(GenTree* tree);
2008 unsigned gtSetEvalOrderAndRestoreFPstkLevel(GenTree* tree);
2010 // Returns true iff the secondNode can be swapped with firstNode.
2011 bool gtCanSwapOrder(GenTree* firstNode, GenTree* secondNode);
2013 unsigned gtSetEvalOrder(GenTree* tree);
2015 #if FEATURE_STACK_FP_X87
2017 void gtComputeFPlvls(GenTreePtr tree);
2018 #endif // FEATURE_STACK_FP_X87
2020 void gtSetStmtInfo(GenTree* stmt);
2022 // Returns "true" iff "node" has any of the side effects in "flags".
2023 bool gtNodeHasSideEffects(GenTreePtr node, unsigned flags);
2025 // Returns "true" iff "tree" or its (transitive) children have any of the side effects in "flags".
2026 bool gtTreeHasSideEffects(GenTreePtr tree, unsigned flags);
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);
2033 void gtExtractSideEffList(GenTreePtr expr,
2035 unsigned flags = GTF_SIDE_EFFECT,
2036 bool ignoreRoot = false);
2038 GenTreePtr gtGetThisArg(GenTreePtr call);
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);
2046 // Return true if call is a recursive call; return false otherwise.
2047 bool gtIsRecursiveCall(GenTreeCall* call)
2049 return (call->gtCallMethHnd == info.compMethodHnd);
2052 //-------------------------------------------------------------------------
2054 GenTreePtr gtFoldExpr(GenTreePtr tree);
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))
2066 gtFoldExprConst(GenTreePtr tree);
2067 GenTreePtr gtFoldExprSpecial(GenTreePtr tree);
2068 GenTreePtr gtFoldExprCompare(GenTreePtr tree);
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);
2076 //-------------------------------------------------------------------------
2077 // Functions to display the trees
2080 void gtDispNode(GenTreePtr tree, IndentStack* indentStack, __in_z const char* msg, bool isLIR);
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);
2098 void gtDispChild(GenTreePtr child,
2099 IndentStack* indentStack,
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);
2118 void gtDispRange(LIR::ReadOnlyRange const& range);
2120 void gtDispTreeRange(LIR::Range& containingRange, GenTree* tree);
2122 void gtDispLIRNode(GenTree* node);
2134 typedef fgWalkResult(fgWalkPreFn)(GenTreePtr* pTree, fgWalkData* data);
2135 typedef fgWalkResult(fgWalkPostFn)(GenTreePtr* pTree, fgWalkData* data);
2138 static fgWalkPreFn gtAssertColonCond;
2140 static fgWalkPreFn gtMarkColonCond;
2141 static fgWalkPreFn gtClearColonCond;
2143 GenTreePtr* gtFindLink(GenTreePtr stmt, GenTreePtr node);
2144 bool gtHasCatchArg(GenTreePtr tree);
2145 bool gtHasUnmanagedCall(GenTreePtr tree);
2147 typedef ArrayStack<GenTree*> GenTreeStack;
2149 static bool gtHasCallOnStack(GenTreeStack* parentStack);
2150 void gtCheckQuirkAddrExposedLclVar(GenTreePtr argTree, GenTreeStack* parentStack);
2152 //=========================================================================
2153 // BasicBlock functions
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;
2161 BasicBlock* bbNewBasicBlock(BBjumpKinds jumpKind);
2164 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2165 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2169 XX The variables to be used by the code generator. XX
2171 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2172 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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.
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
2183 enum lvaPromotionType
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.
2192 static int __cdecl RefCntCmp(const void* op1, const void* op2);
2193 static int __cdecl WtdRefCntCmp(const void* op1, const void* op2);
2195 /*****************************************************************************/
2197 enum FrameLayoutState
2200 INITIAL_FRAME_LAYOUT,
2201 PRE_REGALLOC_FRAME_LAYOUT,
2202 REGALLOC_FRAME_LAYOUT,
2203 TENTATIVE_FRAME_LAYOUT,
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
2214 unsigned lvaRefCount; // total number of references to locals
2215 LclVarDsc* lvaTable; // variable descriptor table
2216 unsigned lvaTableCnt; // lvaTable size (>= lvaCount)
2218 LclVarDsc** lvaRefSorted; // table sorted by refcount
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
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
2229 VARSET_TP lvaTrackedVars; // set of tracked variables
2231 #ifndef _TARGET_64BIT_
2232 VARSET_TP lvaLongVars; // set of long (64-bit) variables
2234 VARSET_TP lvaFloatVars; // set of floating-point (32-bit and 64-bit) variables
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.
2240 unsigned GetCurLVEpoch()
2245 // reverse map of tracked number to var number
2246 unsigned lvaTrackedToVarNum[lclMAX_TRACKED];
2248 #ifdef LEGACY_BACKEND
2249 // variable interference graph
2250 VARSET_TP lvaVarIntf[lclMAX_TRACKED];
2253 // variable preference graph
2254 VARSET_TP lvaVarPref[lclMAX_TRACKED];
2258 // # of procs compiled a with double-aligned stack
2259 static unsigned s_lvaDoubleAlignedProcsCount;
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);
2268 // Reasons why we can't enregister. Some of these correspond to debug properties of local vars.
2269 enum DoNotEnregisterReason
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
2283 void lvaSetVarDoNotEnregister(unsigned varNum DEBUGARG(DoNotEnregisterReason reason));
2285 unsigned lvaVarargsHandleArg;
2287 unsigned lvaVarargsBaseOfStkArgs; // Pointer (computed based on incoming varargs handle) to the start of the stack
2289 #endif // _TARGET_X86_
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.
2296 unsigned lvaMonAcquired; // boolean variable introduced into in synchronized methods
2297 // that tracks whether the lock has been taken
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.
2303 unsigned lvaInlineeReturnSpillTemp; // The temp to spill the non-VOID return expression
2304 // in case there are multiple BBJ_RETURN blocks in the inlinee.
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
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_
2321 unsigned lvaReturnEspCheck; // confirms ESP not corrupted on return
2322 unsigned lvaCallEspCheck; // confirms ESP not corrupted after a call
2325 bool lvaGenericsContextUsed;
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?
2331 //-------------------------------------------------------------------------
2332 // All these frame offsets are inter-related and must be kept in sync
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
2339 unsigned lvaCachedGenericContextArgOffs;
2340 unsigned lvaCachedGenericContextArgOffset(); // For CORINFO_CALLCONV_PARAMTYPE and if generic context is passed as
2343 unsigned lvaLocAllocSPvar; // variable which has the result of the last alloca/localloc
2345 unsigned lvaNewObjArrayArgs; // variable with arguments for new MD array helper
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.
2353 // Pre codegen max spill temp size.
2354 static const unsigned MAX_SPILL_TEMP_SIZE = 24;
2356 //-------------------------------------------------------------------------
2358 unsigned lvaGetMaxSpillTempSize();
2360 bool lvaIsPreSpilled(unsigned lclNum, regMaskTP preSpillMask);
2361 #endif // _TARGET_ARM_
2362 void lvaAssignFrameOffsets(FrameLayoutState curState);
2363 void lvaFixVirtualFrameOffsets();
2365 #ifndef LEGACY_BACKEND
2366 void lvaUpdateArgsWithInitialReg();
2367 #endif // !LEGACY_BACKEND
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();
2381 void lvaAlignFrame();
2382 void lvaAssignFrameOffsetsToPromotedStructs();
2383 int lvaAllocateTemps(int stkOffs, bool mustDoubleAlign);
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
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);
2398 unsigned lvaFrameSize(FrameLayoutState curState);
2400 // Returns the caller-SP-relative offset for the SP/FP relative offset determined by FP based.
2401 int lvaToCallerSPRelativeOffset(int offs, bool isFpBased);
2403 // Returns the caller-SP-relative offset for the local variable "varNum."
2404 int lvaGetCallerSPRelativeOffset(unsigned varNum);
2406 // Returns the SP-relative offset for the local variable "varNum". Illegal to ask this for functions with localloc.
2407 int lvaGetSPRelativeOffset(unsigned varNum);
2409 int lvaToInitialSPRelativeOffset(unsigned offset, bool isFpBased);
2410 int lvaGetInitialSPRelativeOffset(unsigned varNum);
2412 //------------------------ For splitting types ----------------------------
2414 void lvaInitTypeRef();
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);
2423 void lvaInitVarDsc(LclVarDsc* varDsc,
2425 CorInfoType corInfoType,
2426 CORINFO_CLASS_HANDLE typeHnd,
2427 CORINFO_ARG_LIST_HANDLE varList,
2428 CORINFO_SIG_INFO* varSig);
2430 static unsigned lvaTypeRefMask(var_types type);
2432 var_types lvaGetActualType(unsigned lclNum);
2433 var_types lvaGetRealType(unsigned lclNum);
2435 //-------------------------------------------------------------------------
2439 unsigned lvaArgSize(const void* argTok);
2440 unsigned lvaLclSize(unsigned varNum);
2441 unsigned lvaLclExactSize(unsigned varNum);
2443 bool lvaLclVarRefs(GenTreePtr tree, GenTreePtr* findPtr, varRefKinds* refsPtr, void* result);
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);
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,
2456 ALLVARSET_VALARG_TP allVars,
2457 VARSET_VALARG_TP trkdVars);
2459 bool lvaHaveManyLocals() const;
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));
2466 void lvaSortByRefCount();
2467 void lvaDumpRefCounts();
2469 void lvaMarkLocalVars(BasicBlock* block);
2471 void lvaMarkLocalVars(); // Local variable ref-counting
2473 void lvaAllocOutgoingArgSpace(); // 'Commit' lvaOutgoingArgSpaceSize and lvaOutgoingArgSpaceVar
2475 VARSET_VALRET_TP lvaStmtLclMask(GenTreePtr stmt);
2477 static fgWalkPreFn lvaIncRefCntsCB;
2478 void lvaIncRefCnts(GenTreePtr tree);
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);
2487 struct lvaStressLclFldArgs
2489 Compiler* m_pCompiler;
2493 static fgWalkPreFn lvaStressLclFldCB;
2494 void lvaStressLclFld();
2496 void lvaDispVarSet(VARSET_VALARG_TP set, VARSET_VALARG_TP allVars);
2497 void lvaDispVarSet(VARSET_VALARG_TP set);
2502 int lvaFrameAddress(int varNum, bool mustBeFPBased, regNumber* pBaseReg, int addrModeOffset);
2504 int lvaFrameAddress(int varNum, bool* pFPbased);
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
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)
2519 #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
2520 LclVarDsc* varDsc = &(lvaTable[varNum]);
2521 if (varDsc->lvIsParam && varDsc->lvIsTemp)
2523 assert((varDsc->lvType == TYP_STRUCT) || (varDsc->lvType == TYP_BYREF));
2526 #endif // defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
2530 // Returns true if this local var is a multireg struct
2531 bool lvaIsMultiregStruct(LclVarDsc* varDsc);
2533 // If the class is a TYP_STRUCT, get/set a class handle describing it
2535 CORINFO_CLASS_HANDLE lvaGetStruct(unsigned varNum);
2536 void lvaSetStruct(unsigned varNum, CORINFO_CLASS_HANDLE typeHnd, bool unsafeValueClsCheck, bool setTypeInfo = true);
2538 #define MAX_NumOfFieldsInPromotableStruct 4 // Maximum number of fields in promotable struct
2540 // Info about struct fields
2541 struct lvaStructFieldInfo
2543 CORINFO_FIELD_HANDLE fldHnd;
2544 unsigned char fldOffset;
2545 unsigned char fldOrdinal;
2548 CORINFO_CLASS_HANDLE fldTypeHnd;
2551 // Info about struct to be promoted.
2552 struct lvaStructPromotionInfo
2554 CORINFO_CLASS_HANDLE typeHnd;
2556 bool requiresScratchVar;
2559 unsigned char fieldCnt;
2560 lvaStructFieldInfo fields[MAX_NumOfFieldsInPromotableStruct];
2562 lvaStructPromotionInfo()
2563 : typeHnd(nullptr), canPromote(false), requiresScratchVar(false), containsHoles(false), customLayout(false)
2568 static int __cdecl lvaFieldOffsetCmp(const void* field1, const void* field2);
2569 void lvaCanPromoteStructType(CORINFO_CLASS_HANDLE typeHnd,
2570 lvaStructPromotionInfo* StructPromotionInfo,
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);
2585 BYTE* lvaGetGcLayout(unsigned varNum);
2586 bool lvaTypeIsGC(unsigned varNum);
2587 unsigned lvaGSSecurityCookie; // LclVar number
2588 bool lvaTempsHaveLargerOffsetThanVars();
2590 unsigned lvaSecurityObject; // variable representing the security object on the stack
2591 unsigned lvaStubArgumentVar; // variable representing the secret stub argument coming in EAX
2593 #if FEATURE_EH_FUNCLETS
2594 unsigned lvaPSPSym; // variable representing the PSPSym
2597 InlineInfo* impInlineInfo;
2598 InlineStrategy* m_inlineStrategy;
2600 // The Compiler* that is the root of the inlining tree of which "this" is a member.
2601 Compiler* impInlineRoot();
2603 #if defined(DEBUG) || defined(INLINE_DATA)
2604 unsigned __int64 getInlineCycleCount()
2606 return m_compCycles;
2608 #endif // defined(DEBUG) || defined(INLINE_DATA)
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.
2613 //=========================================================================
2615 //=========================================================================
2618 //---------------- Local variable ref-counting ----------------------------
2621 BasicBlock* lvaMarkRefsCurBlock;
2622 GenTreePtr lvaMarkRefsCurStmt;
2624 BasicBlock::weight_t lvaMarkRefsWeight;
2626 static fgWalkPreFn lvaMarkLclRefsCallback;
2627 void lvaMarkLclRefs(GenTreePtr tree);
2629 // Keeps the mapping from SSA #'s to VN's for the implicit "Heap" variable.
2630 PerSsaArray lvHeapPerSsaData;
2631 unsigned lvHeapNumSsaNames;
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)
2639 assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
2640 assert(SsaConfig::RESERVED_SSA_NUM == 0);
2642 assert(ssaNum < lvHeapNumSsaNames);
2643 return &lvHeapPerSsaData.GetRef(ssaNum);
2647 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2648 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2652 XX Imports the given method and converts it to semantic trees XX
2654 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2655 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2661 void impImport(BasicBlock* method);
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();
2669 //=========================================================================
2671 //=========================================================================
2674 //-------------------- Stack manipulation ---------------------------------
2676 unsigned impStkSize; // Size of the full stack
2678 #define SMALL_STACK_SIZE 16 // number of elements in impSmallStack
2680 StackEntry impSmallStack[SMALL_STACK_SIZE]; // Use this array if possible
2682 struct SavedStack // used to save/restore stack contents.
2684 unsigned ssDepth; // number of values on stack
2685 StackEntry* ssTrees; // saved tree values
2688 bool impIsPrimitive(CorInfoType type);
2689 bool impILConsumesAddr(const BYTE* codeAddr, CORINFO_METHOD_HANDLE fncHandle, CORINFO_MODULE_HANDLE scpHandle);
2691 void impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind);
2692 void impPushOnStackNoType(GenTreePtr tree);
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);
2701 void impSaveStackState(SavedStack* savePtr, bool copy);
2702 void impRestoreStackState(SavedStack* savePtr);
2704 GenTreePtr impImportLdvirtftn(GenTreePtr thisPtr,
2705 CORINFO_RESOLVED_TOKEN* pResolvedToken,
2706 CORINFO_CALL_INFO* pCallInfo);
2708 void impImportAndPushBox(CORINFO_RESOLVED_TOKEN* pResolvedToken);
2710 void impImportNewObjArray(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
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);
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);
2722 void impInsertCalloutForDelegate(CORINFO_METHOD_HANDLE callerMethodHnd,
2723 CORINFO_METHOD_HANDLE calleeMethodHnd,
2724 CORINFO_CLASS_HANDLE delegateTypeHnd);
2726 var_types impImportCall(OPCODE opcode,
2727 CORINFO_RESOLVED_TOKEN* pResolvedToken,
2728 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call on a
2730 GenTreePtr newobjThis,
2732 CORINFO_CALL_INFO* callInfo,
2733 IL_OFFSET rawILOffset);
2735 bool impMethodInfo_hasRetBuffArg(CORINFO_METHOD_INFO* methInfo);
2737 GenTreePtr impFixupCallStructReturn(GenTreePtr call, CORINFO_CLASS_HANDLE retClsHnd);
2739 GenTreePtr impInitCallLongReturn(GenTreePtr call);
2741 GenTreePtr impFixupStructReturnType(GenTreePtr op, CORINFO_CLASS_HANDLE retClsHnd);
2744 var_types impImportJitTestLabelMark(int numArgs);
2747 GenTreePtr impInitClass(CORINFO_RESOLVED_TOKEN* pResolvedToken);
2749 GenTreePtr impImportStaticReadOnlyField(void* fldAddr, var_types lclTyp);
2751 GenTreePtr impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2752 CORINFO_ACCESS_FLAGS access,
2753 CORINFO_FIELD_INFO* pFieldInfo,
2756 static void impBashVarAddrsToI(GenTreePtr tree1, GenTreePtr tree2 = nullptr);
2758 GenTreePtr impImplicitIorI4Cast(GenTreePtr tree, var_types dstTyp);
2760 GenTreePtr impImplicitR4orR8Cast(GenTreePtr tree, var_types dstTyp);
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,
2771 CorInfoIntrinsics* pIntrinsicID);
2772 GenTreePtr impArrayAccessIntrinsic(CORINFO_CLASS_HANDLE clsHnd,
2773 CORINFO_SIG_INFO* sig,
2776 CorInfoIntrinsics intrinsicID);
2777 GenTreePtr impInitializeArrayIntrinsic(CORINFO_SIG_INFO* sig);
2779 GenTreePtr impMethodPointer(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
2781 GenTreePtr impTransformThis(GenTreePtr thisPtr,
2782 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
2783 CORINFO_THIS_TRANSFORM transform);
2785 //----------------- Manipulating the trees and stmts ----------------------
2787 GenTreePtr impTreeList; // Trees for the BB being imported
2788 GenTreePtr impTreeLast; // The last tree for the current BB
2792 CHECK_SPILL_ALL = -1,
2793 CHECK_SPILL_NONE = -2
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,
2808 GenTreePtr* pAfterStmt = nullptr,
2809 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
2810 BasicBlock* block = nullptr);
2811 void impAssignTempGen(unsigned tmpNum,
2813 CORINFO_CLASS_HANDLE structHnd,
2815 GenTreePtr* pAfterStmt = nullptr,
2816 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
2817 BasicBlock* block = nullptr);
2818 GenTreePtr impCloneExpr(GenTreePtr tree,
2820 CORINFO_CLASS_HANDLE structHnd,
2822 GenTreePtr* pAfterStmt DEBUGARG(const char* reason));
2823 GenTreePtr impAssignStruct(GenTreePtr dest,
2825 CORINFO_CLASS_HANDLE structHnd,
2827 GenTreePtr* pAfterStmt = nullptr,
2828 BasicBlock* block = nullptr);
2829 GenTreePtr impAssignStructPtr(GenTreePtr dest,
2831 CORINFO_CLASS_HANDLE structHnd,
2833 GenTreePtr* pAfterStmt = nullptr,
2834 BasicBlock* block = nullptr);
2836 GenTreePtr impGetStructAddr(GenTreePtr structVal,
2837 CORINFO_CLASS_HANDLE structHnd,
2841 var_types impNormStructType(CORINFO_CLASS_HANDLE structHnd,
2842 BYTE* gcLayout = nullptr,
2843 unsigned* numGCVars = nullptr,
2844 var_types* simdBaseType = nullptr);
2846 GenTreePtr impNormStructVal(GenTreePtr structVal,
2847 CORINFO_CLASS_HANDLE structHnd,
2849 bool forceNormalization = false);
2851 GenTreePtr impTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2852 BOOL* pRuntimeLookup = nullptr,
2853 BOOL mustRestoreHandle = FALSE,
2854 BOOL importParent = FALSE);
2856 GenTreePtr impParentClassTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2857 BOOL* pRuntimeLookup = nullptr,
2858 BOOL mustRestoreHandle = FALSE)
2860 return impTokenToHandle(pResolvedToken, pRuntimeLookup, mustRestoreHandle, TRUE);
2863 GenTreePtr impLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2864 CORINFO_LOOKUP* pLookup,
2866 void* compileTimeHandle);
2868 GenTreePtr impRuntimeLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2869 CORINFO_LOOKUP* pLookup,
2870 void* compileTimeHandle);
2872 GenTreePtr impReadyToRunLookupToTree(CORINFO_CONST_LOOKUP* pLookup, unsigned flags, void* compileTimeHandle);
2874 GenTreePtr impReadyToRunHelperToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2875 CorInfoHelpFunc helper,
2877 GenTreeArgList* arg = nullptr,
2878 CORINFO_LOOKUP_KIND* pGenericLookupKind = nullptr);
2880 GenTreePtr impCastClassOrIsInstToTree(GenTreePtr op1,
2882 CORINFO_RESOLVED_TOKEN* pResolvedToken,
2885 bool VarTypeIsMultiByteAndCanEnreg(var_types type,
2886 CORINFO_CLASS_HANDLE typeClass,
2890 static bool IsIntrinsicImplementedByUserCall(CorInfoIntrinsics intrinsicId);
2891 static bool IsTargetIntrinsic(CorInfoIntrinsics intrinsicId);
2892 static bool IsMathIntrinsic(CorInfoIntrinsics intrinsicId);
2893 static bool IsMathIntrinsic(GenTreePtr tree);
2896 //----------------- Importing the method ----------------------------------
2898 CORINFO_CONTEXT_HANDLE impTokenLookupContextHandle; // The context used for looking up tokens.
2901 unsigned impCurOpcOffs;
2902 const char* impCurOpcName;
2903 bool impNestedStackSpill;
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();
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.
2917 IL_OFFSETX impCurStmtOffs;
2918 void impCurStmtOffsSet(IL_OFFSET offs);
2920 void impNoteBranchOffs();
2922 unsigned impInitBlockLineInfo();
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)
2930 return ((opcode == CEE_STLOC) || (opcode == CEE_STLOC_S) ||
2931 ((opcode >= CEE_STLOC_0) && (opcode <= CEE_STLOC_3)));
2934 GenTreeArgList* impPopList(unsigned count,
2936 CORINFO_SIG_INFO* sig,
2937 GenTreeArgList* prefixTree = nullptr);
2939 GenTreeArgList* impPopRevList(unsigned count,
2941 CORINFO_SIG_INFO* sig,
2942 unsigned skipReverseCount = 0);
2945 * Get current IL offset with stack-empty info incoporated
2947 IL_OFFSETX impCurILOffset(IL_OFFSET offs, bool callInstruction = false);
2949 //---------------- Spilling the importer stack ----------------------------
2955 SavedStack pdSavedStack;
2956 ThisInitState pdThisPtrInit;
2959 PendingDsc* impPendingList; // list of BBs currently waiting to be imported.
2960 PendingDsc* impPendingFree; // Freed up dscs that can be reused
2962 // We keep a byte-per-block map (dynamically extended) in the top-level Compiler object of a compilation.
2963 ExpandArray<BYTE> impPendingBlockMembers;
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)
2969 return impInlineRoot()->impPendingBlockMembers.Get(blk->bbInd());
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)
2976 impInlineRoot()->impPendingBlockMembers.Set(blk->bbInd(), val);
2979 bool impCanReimport;
2981 bool impSpillStackEntry(unsigned level,
2985 bool bAssertOnRecursion,
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);
2999 BasicBlock* impPushCatchArgOnStack(BasicBlock* hndBlk, CORINFO_CLASS_HANDLE clsHnd);
3001 void impImportBlockCode(BasicBlock* block);
3003 void impReimportMarkBlock(BasicBlock* block);
3004 void impReimportMarkSuccessors(BasicBlock* block);
3006 void impVerifyEHBlock(BasicBlock* block, bool isTryStart);
3008 void impImportBlockPending(BasicBlock* block);
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);
3015 var_types impGetByRefResultType(genTreeOps oper, bool fUnsigned, GenTreePtr* pOp1, GenTreePtr* pOp2);
3017 void impImportBlock(BasicBlock* block);
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);
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);
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;
3060 // Abstract class for receiving a callback while walking a spill clique
3061 class SpillCliqueWalker
3064 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk) = 0;
3067 // This class is used for setting the bbStkTempsIn and bbStkTempsOut on the blocks within a spill clique
3068 class SetSpillTempsBase : public SpillCliqueWalker
3073 SetSpillTempsBase(unsigned baseTmp) : m_baseTmp(baseTmp)
3076 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3079 // This class is used for implementing impReimportSpillClique part on each block within the spill clique
3080 class ReimportSpillClique : public SpillCliqueWalker
3085 ReimportSpillClique(Compiler* pComp) : m_pComp(pComp)
3088 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
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);
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);
3100 BYTE impSpillCliqueGetMember(SpillCliqueDir predOrSucc, BasicBlock* blk);
3101 void impSpillCliqueSetMember(SpillCliqueDir predOrSucc, BasicBlock* blk, BYTE val);
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)
3107 impLoadVar(lclNum, offset, lvaTable[lclNum].lvVerTypeInfo);
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);
3114 void impMarkLclDstNotPromotable(unsigned tmpNum, GenTreePtr op, CORINFO_CLASS_HANDLE hClass);
3117 // A free list of linked list nodes used to represent to-do stacks of basic blocks.
3118 struct BlockListNode
3121 BlockListNode* m_next;
3122 BlockListNode(BasicBlock* blk, BlockListNode* next = nullptr) : m_blk(blk), m_next(next)
3125 void* operator new(size_t sz, Compiler* comp);
3127 BlockListNode* impBlockListNodeFreeList;
3129 BlockListNode* AllocBlockListNode();
3130 void FreeBlockListNode(BlockListNode* node);
3132 bool impIsValueType(typeInfo* pTypeInfo);
3133 var_types mangleVarArgsType(var_types type);
3136 regNumber getCallArgIntRegister(regNumber floatReg);
3137 regNumber getCallArgFloatRegister(regNumber intReg);
3138 #endif // FEATURE_VARARG
3141 static unsigned jitTotalMethodCompiled;
3145 static LONG jitNestingLevel;
3148 bool seenConditionalJump;
3150 static BOOL impIsAddressInLocal(GenTreePtr tree, GenTreePtr* lclVarTreeOut);
3152 void impMakeDiscretionaryInlineObservations(InlineInfo* pInlineInfo, InlineResult* inlineResult);
3154 // STATIC inlining decision based on the IL code.
3155 void impCanInlineIL(CORINFO_METHOD_HANDLE fncHandle,
3156 CORINFO_METHOD_INFO* methInfo,
3158 InlineResult* inlineResult);
3160 void impCheckCanInline(GenTreePtr call,
3161 CORINFO_METHOD_HANDLE fncHandle,
3163 CORINFO_CONTEXT_HANDLE exactContextHnd,
3164 InlineCandidateInfo** ppInlineCandidateInfo,
3165 InlineResult* inlineResult);
3167 void impInlineRecordArgInfo(InlineInfo* pInlineInfo,
3168 GenTreePtr curArgVal,
3170 InlineResult* inlineResult);
3172 void impInlineInitVars(InlineInfo* pInlineInfo);
3174 unsigned impInlineFetchLocal(unsigned lclNum DEBUGARG(const char* reason));
3176 GenTreePtr impInlineFetchArg(unsigned lclNum, InlArgInfo* inlArgInfo, InlLclVarInfo* lclTypeInfo);
3178 BOOL impInlineIsThis(GenTreePtr tree, InlArgInfo* inlArgInfo);
3180 BOOL impInlineIsGuaranteedThisDerefBeforeAnySideEffects(GenTreePtr additionalTreesToBeEvaluatedBefore,
3181 GenTreePtr variableBeingDereferenced,
3182 InlArgInfo* inlArgInfo);
3184 void impMarkInlineCandidate(GenTreePtr call, CORINFO_CONTEXT_HANDLE exactContextHnd, CORINFO_CALL_INFO* callInfo);
3186 bool impTailCallRetTypeCompatible(var_types callerRetType,
3187 CORINFO_CLASS_HANDLE callerRetTypeClass,
3188 var_types calleeRetType,
3189 CORINFO_CLASS_HANDLE calleeRetTypeClass);
3191 bool impIsTailCallILPattern(bool tailPrefixed,
3193 const BYTE* codeAddrOfNextOpcode,
3194 const BYTE* codeEnd,
3196 bool* IsCallPopRet = nullptr);
3198 bool impIsImplicitTailCallCandidate(
3199 OPCODE curOpcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, int prefixFlags, bool isRecursive);
3202 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3203 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3207 XX Info about the basic-blocks, their contents and the flow analysis XX
3209 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3210 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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)
3220 BasicBlock* fgFirstBBScratch; // Block inserted for initialization stuff. Is nullptr if no such block has been
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
3226 unsigned fgBBcountAtCodegen; // # of BBs in the method at the start of codegen
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.
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;
3242 bool fgBBVarSetsInited;
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)
3249 return (T*)compGetMem((fgBBNumMax + 1) * sizeof(T), cmk);
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;
3261 unsigned GetCurBasicBlockEpoch()
3263 return fgCurBBEpoch;
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;
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;
3275 void NewBasicBlockEpoch()
3277 INDEBUG(unsigned oldEpochArrSize = fgBBSetCountInSizeTUnits);
3279 // We have a new epoch. Compute and cache the size needed for new BlockSets.
3281 fgCurBBEpochSize = fgBBNumMax + 1;
3282 fgBBSetCountInSizeTUnits =
3283 unsigned(roundUp(fgCurBBEpochSize, sizeof(size_t) * 8)) / unsigned(sizeof(size_t) * 8);
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!
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)))
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");
3307 void EnsureBasicBlockEpoch()
3309 if (fgCurBBEpochSize != fgBBNumMax + 1)
3311 NewBasicBlockEpoch();
3315 BasicBlock* fgNewBasicBlock(BBjumpKinds jumpKind);
3316 void fgEnsureFirstBBisScratch();
3317 bool fgFirstBBisScratch();
3318 bool fgBBisScratch(BasicBlock* block);
3320 void fgExtendEHRegionBefore(BasicBlock* block);
3321 void fgExtendEHRegionAfter(BasicBlock* block);
3323 BasicBlock* fgNewBBbefore(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
3325 BasicBlock* fgNewBBafter(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
3327 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
3330 BasicBlock* nearBlk,
3331 bool putInFilter = false,
3332 bool runRarely = false,
3333 bool insertAtEnd = false);
3335 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
3337 bool runRarely = false,
3338 bool insertAtEnd = false);
3340 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind);
3342 BasicBlock* fgNewBBinRegionWorker(BBjumpKinds jumpKind,
3343 BasicBlock* afterBlk,
3344 unsigned xcptnIndex,
3345 bool putInTryRegion);
3347 void fgInsertBBbefore(BasicBlock* insertBeforeBlk, BasicBlock* newBlk);
3348 void fgInsertBBafter(BasicBlock* insertAfterBlk, BasicBlock* newBlk);
3349 void fgUnlinkBlock(BasicBlock* block);
3351 #if OPT_BOOL_OPS // Used to detect multiple logical "not" assignments.
3352 bool fgMultipleNots;
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?
3360 bool fgHasSwitch; // any BBJ_SWITCH jumps?
3361 bool fgHasPostfix; // any postfix ++/-- found?
3362 unsigned fgIncrCount; // number of increment nodes found
3364 BlockSet fgEnterBlks; // Set of blocks which have a special transfer of control; the "entry" blocks plus EH handler
3368 bool fgReachabilitySetsValid; // Are the bbReach sets valid?
3369 bool fgEnterBlksSetValid; // Is the fgEnterBlks set valid?
3372 bool fgRemoveRestOfBlock; // true if we know that we will throw
3373 bool fgStmtRemoved; // true if we remove statements -> need new DFA
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.
3386 FlowGraphOrder fgOrder;
3388 // The following are boolean flags that keep track of the state of internal data structures
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
3401 #if FEATURE_EH_FUNCLETS
3402 bool fgFuncletsCreated; // true if the funclet creation phase has been run
3403 #endif // FEATURE_EH_FUNCLETS
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
3409 bool impBoxTempInUse; // the temp below is valid and available
3410 unsigned impBoxTemp; // a temporary that is used for boxing
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?
3418 unsigned impInlinedCodeSize;
3421 //-------------------------------------------------------------------------
3429 GenTreePtr fgGetCritSectOfStaticMethod();
3431 #if !defined(_TARGET_X86_)
3433 void fgAddSyncMethodEnterExit();
3435 GenTree* fgCreateMonitorTree(unsigned lvaMonitorBool, unsigned lvaThisVar, BasicBlock* block, bool enter);
3437 void fgConvertSyncReturnToLeave(BasicBlock* block);
3439 #endif // !_TARGET_X86_
3441 void fgAddReversePInvokeEnterExit();
3443 bool fgMoreThanOneReturnBlock();
3445 // The number of separate return points in the method.
3446 unsigned fgReturnCount;
3448 void fgAddInternal();
3450 bool fgFoldConditional(BasicBlock* block);
3452 void fgMorphStmts(BasicBlock* block, bool* mult, bool* lnot, bool* loadw);
3453 void fgMorphBlocks();
3455 bool fgMorphBlockStmt(BasicBlock* block, GenTreePtr stmt DEBUGARG(const char* msg));
3457 void fgSetOptions();
3460 static fgWalkPreFn fgAssertNoQmark;
3461 void fgPreExpandQmarkChecks(GenTreePtr expr);
3462 void fgPostExpandQmarkChecks();
3463 static void fgCheckQmarkAllowedForm(GenTreePtr tree);
3466 IL_OFFSET fgFindBlockILOffset(BasicBlock* block);
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);
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);
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();
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();
3490 bool fgShouldCreateAssignOp(GenTreePtr tree, bool* bReverse);
3492 GenTreePtr fgInitThisClass();
3494 GenTreePtr fgGetStaticsCCtorHelper(CORINFO_CLASS_HANDLE cls, CorInfoHelpFunc helper);
3496 GenTreePtr fgGetSharedCCtor(CORINFO_CLASS_HANDLE cls);
3498 void fgLocalVarLiveness();
3500 void fgLocalVarLivenessInit();
3502 #ifdef LEGACY_BACKEND
3503 GenTreePtr fgLegacyPerStatementLocalVarLiveness(GenTreePtr startNode, GenTreePtr relopNode, GenTreePtr asgdLclVar);
3505 void fgPerNodeLocalVarLiveness(GenTree* node, GenTree* asgdLclVar);
3506 void fgPerStatementLocalVarLiveness(GenTree* node, GenTree* asgdLclVar);
3508 void fgPerBlockLocalVarLiveness();
3510 VARSET_VALRET_TP fgGetHandlerLiveVars(BasicBlock* block);
3512 void fgLiveVarAnalysis(bool updateInternalOnly = false);
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
3517 VARSET_TP fgMarkIntfUnionVS;
3519 bool fgMarkIntf(VARSET_VALARG_TP varSet);
3521 bool fgMarkIntf(VARSET_VALARG_TP varSet1, VARSET_VALARG_TP varSet2);
3523 void fgUpdateRefCntForClone(BasicBlock* addedToBlock, GenTreePtr clonedTree);
3525 void fgUpdateRefCntForExtract(GenTreePtr wholeTree, GenTreePtr keptTree);
3527 void fgComputeLifeCall(VARSET_TP& life, GenTreeCall* call);
3529 bool fgComputeLifeLocal(VARSET_TP& life, VARSET_TP& keepAliveVars, GenTree* lclVarNode, GenTree* node);
3531 VARSET_VALRET_TP fgComputeLife(VARSET_VALARG_TP life,
3532 GenTreePtr startNode,
3534 VARSET_VALARG_TP volatileVars,
3535 bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
3537 VARSET_VALRET_TP fgComputeLifeLIR(VARSET_VALARG_TP life, BasicBlock* block, VARSET_VALARG_TP volatileVars);
3539 bool fgRemoveDeadStore(GenTree** pTree,
3543 bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
3545 bool fgTryRemoveDeadLIRStore(LIR::Range& blockRange, GenTree* node, GenTree** next);
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);
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
3556 VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTreePtr tree, GenTreePtr endTree)
3558 VARSET_TP VARSET_INIT(this, newLiveSet, liveSet);
3559 while (tree != nullptr && tree != endTree->gtNext)
3561 VarSetOps::AssignNoCopy(this, newLiveSet, fgUpdateLiveSet(newLiveSet, tree));
3562 tree = tree->gtNext;
3564 assert(tree == endTree->gtNext);
3568 void fgInterBlockLocalVarLiveness();
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()
3578 if (m_opAsgnVarDefSsaNums == nullptr)
3580 m_opAsgnVarDefSsaNums = new (getAllocator()) NodeToUnsignedMap(getAllocator());
3582 return m_opAsgnVarDefSsaNums;
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"
3589 inline ValueNum GetUseAsgDefVNOrTreeVN(GenTreePtr tree);
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);
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
3603 // (byref addrS1 = &s1,
3604 // *(addrS1 * offsetof(f0)) = s2f0,
3606 // *(addrS1 * offsetof(fn)) = s2fn)
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?
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
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
3627 IndirectAssignmentAnnotation(unsigned lclNum,
3628 FieldSeqNode* fldSeq,
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)
3636 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, IndirectAssignmentAnnotation*, JitSimplerHashBehavior>
3637 NodeToIndirAssignMap;
3638 NodeToIndirAssignMap* m_indirAssignMap;
3639 NodeToIndirAssignMap* GetIndirAssignMap()
3641 if (m_indirAssignMap == nullptr)
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);
3647 return m_indirAssignMap;
3650 // Performs SSA conversion.
3653 // Reset any data structures to the state expected by "fgSsaBuild", so it can be run again.
3654 void fgResetForSsa();
3656 unsigned fgSsaPassesCompleted; // Number of times fgSsaBuild has been run.
3658 // Returns "true" iff lcl "lclNum" should be excluded from SSA.
3659 inline bool fgExcludeFromSsa(unsigned lclNum);
3661 // The value numbers for this compilation.
3662 ValueNumStore* vnStore;
3665 ValueNumStore* GetValueNumStore()
3670 // Do value numbering (assign a value number to each
3672 void fgValueNumber();
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]
3680 void fgValueNumberArrIndexAssign(CORINFO_CLASS_HANDLE elemTypeEq,
3683 FieldSeqNode* fldSeq,
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
3696 ValueNum fgValueNumberArrIndexVal(GenTreePtr tree,
3697 CORINFO_CLASS_HANDLE elemTypeEq,
3701 FieldSeqNode* fldSeq);
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);
3709 unsigned fgVNPassesCompleted; // Number of times fgValueNumber has been run.
3711 // Utility functions for fgValueNumber.
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);
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);
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));
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);
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);
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
3740 // If "evalAsgLhsInd" is true, evaluate a GT_IND node, even if it's labeled as the LHS of
3742 void fgValueNumberTree(GenTreePtr tree, bool evalAsgLhsInd = false);
3744 // Does value-numbering for a block assignment.
3745 void fgValueNumberBlockAssignment(GenTreePtr tree, bool evalAsgLhsInd);
3747 // Does value-numbering for a cast tree.
3748 void fgValueNumberCastTree(GenTreePtr tree);
3750 // Does value-numbering for an intrinsic tree.
3751 void fgValueNumberIntrinsic(GenTreePtr tree);
3753 // Does value-numbering for a call. We interpret some helper calls.
3754 void fgValueNumberCall(GenTreeCall* call);
3756 // The VN of some nodes in "args" may have changed -- reassign VNs to the arg list nodes.
3757 void fgUpdateArgListVNs(GenTreeArgList* args);
3759 // Does value-numbering for a helper "call" that has a VN function symbol "vnf".
3760 void fgValueNumberHelperCallFunc(GenTreeCall* call, VNFunc vnf, ValueNumPair vnpExc);
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);
3767 // Requires "helpFunc" to be pure. Returns the corresponding VNFunc.
3768 VNFunc fgValueNumberHelperMethVNFunc(CorInfoHelpFunc helpFunc);
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;
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)
3781 if (elemStructType != nullptr)
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;
3790 elemTyp = varTypeUnsignedToSigned(elemTyp);
3791 return CORINFO_CLASS_HANDLE(size_t(elemTyp) << 1 | 0x1);
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)
3799 size_t clsHndVal = size_t(clsHnd);
3800 if (clsHndVal & 0x1)
3802 return var_types(clsHndVal >> 1);
3810 // Convert a BYTE which represents the VM's CorInfoGCtype to the JIT's var_types
3811 var_types getJitGCType(BYTE gcType);
3813 enum structPassingKind
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.
3824 }; // The struct is passed/returned by reference to a copy/buffer.
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.
3831 var_types getPrimitiveTypeForStruct(unsigned structSize, CORINFO_CLASS_HANDLE clsHnd);
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
3836 var_types getArgTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
3837 structPassingKind* wbPassStruct,
3838 unsigned structSize = 0);
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
3843 var_types getReturnTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
3844 structPassingKind* wbPassStruct = nullptr,
3845 unsigned structSize = 0);
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);
3854 // Dominator computation member functions
3855 // Not exposed outside Compiler
3857 bool fgDominate(BasicBlock* b1, BasicBlock* b2); // Return true if b1 dominates b2
3859 bool fgReachable(BasicBlock* b1, BasicBlock* b2); // Returns true if block b1 can reach block b2
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
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.
3872 void fgComputeReachabilitySets(); // Compute bbReach sets. (Also sets BBF_GC_SAFE_POINT flag on blocks.)
3874 void fgComputeEnterBlocksSet(); // Compute the set of entry blocks, 'fgEnterBlks'.
3876 bool fgRemoveUnreachableBlocks(); // Remove blocks determined to be unreachable by the bbReach sets.
3878 void fgComputeReachability(); // Perform flow graph node reachability analysis.
3880 BasicBlock* fgIntersectDom(BasicBlock* a, BasicBlock* b); // Intersect two immediate dominator sets.
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.
3885 void fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count);
3887 BlockSet_ValRet_T fgDomFindStartNodes(); // Computes which basic blocks don't have incoming edges in the flow graph.
3888 // Returns this as a set.
3890 BlockSet_ValRet_T fgDomTreeEntryNodes(BasicBlockList** domTree); // Computes which nodes in the dominance forest are
3891 // root nodes. Returns this as a set.
3894 void fgDispDomTree(BasicBlockList** domTree); // Helper that prints out the Dominator Tree in debug builds.
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
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);
3906 // When the flow graph changes, we need to update the block numbers, predecessor lists, reachability sets, and
3908 void fgUpdateChangedFlowGraph();
3911 // Compute the predecessors of the blocks in the control flow graph.
3912 void fgComputePreds();
3914 // Remove all predecessor information.
3915 void fgRemovePreds();
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();
3922 void fgAddCheapPred(BasicBlock* block, BasicBlock* blockPred);
3924 void fgRemoveCheapPred(BasicBlock* block, BasicBlock* blockPred);
3934 // Initialize the per-block variable sets (used for liveness analysis).
3935 void fgInitBlockVarSets();
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);
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);
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);
3955 // Factor out common portions of the impls of the methods above.
3956 void fgSuccOfFinallyRetWork(BasicBlock* block, unsigned i, BasicBlock** bres, unsigned* nres);
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
3968 unsigned numDistinctSuccs; // Number of distinct targets of the switch.
3969 BasicBlock** nonDuplicates; // Array of "numDistinctSuccs", containing all the distinct switch target
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);
3978 typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, SwitchUniqueSuccSet, JitSimplerHashBehavior>
3979 BlockToSwitchDescMap;
3982 // Maps BasicBlock*'s that end in switch statements to SwitchUniqueSuccSets that allow
3983 // iteration over only the distinct successors.
3984 BlockToSwitchDescMap* m_switchDescMap;
3987 BlockToSwitchDescMap* GetSwitchDescMap()
3989 if (m_switchDescMap == nullptr)
3991 m_switchDescMap = new (getAllocator()) BlockToSwitchDescMap(getAllocator());
3993 return m_switchDescMap;
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()
4001 m_switchDescMap = nullptr;
4004 // Requires "switchBlock" to be a block that ends in a switch. Returns
4005 // the corresponding SwitchUniqueSuccSet.
4006 SwitchUniqueSuccSet GetDescriptorForSwitch(BasicBlock* switchBlk);
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);
4013 // Remove the "SwitchUniqueSuccSet" of "switchBlk" in the BlockToSwitchDescMap.
4014 void fgInvalidateSwitchDescMapEntry(BasicBlock* switchBlk);
4016 BasicBlock* fgFirstBlockOfHandler(BasicBlock* block);
4018 flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred);
4020 flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred, flowList*** ptrToPred);
4022 flowList* fgSpliceOutPred(BasicBlock* block, BasicBlock* blockPred);
4024 flowList* fgRemoveRefPred(BasicBlock* block, BasicBlock* blockPred);
4026 flowList* fgRemoveAllRefPreds(BasicBlock* block, BasicBlock* blockPred);
4028 flowList* fgRemoveAllRefPreds(BasicBlock* block, flowList** ptrToPred);
4030 void fgRemoveBlockAsPred(BasicBlock* block);
4032 void fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock);
4034 void fgReplaceSwitchJumpTarget(BasicBlock* blockSwitch, BasicBlock* newTarget, BasicBlock* oldTarget);
4036 void fgReplaceJumpTarget(BasicBlock* block, BasicBlock* newTarget, BasicBlock* oldTarget);
4038 void fgReplacePred(BasicBlock* block, BasicBlock* oldPred, BasicBlock* newPred);
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
4046 void fgFindBasicBlocks();
4048 bool fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt);
4050 bool fgCheckEHCanInsertAfterBlock(BasicBlock* blk, unsigned regionIndex, bool putInTryRegion);
4052 BasicBlock* fgFindInsertPoint(unsigned regionIndex,
4053 bool putInTryRegion,
4054 BasicBlock* startBlk,
4056 BasicBlock* nearBlk,
4057 BasicBlock* jumpBlk,
4060 unsigned fgGetNestingLevel(BasicBlock* block, unsigned* pFinallyNesting = nullptr);
4062 void fgRemoveEmptyBlocks();
4064 void fgRemoveStmt(BasicBlock* block, GenTreePtr stmt, bool updateRefCnt = true);
4066 bool fgCheckRemoveStmt(BasicBlock* block, GenTreePtr stmt);
4068 void fgCreateLoopPreHeader(unsigned lnum);
4070 void fgUnreachableBlock(BasicBlock* block);
4072 void fgRemoveJTrue(BasicBlock* block);
4074 BasicBlock* fgLastBBInMainFunction();
4076 BasicBlock* fgEndBBAfterMainFunction();
4078 void fgUnlinkRange(BasicBlock* bBeg, BasicBlock* bEnd);
4080 void fgRemoveBlock(BasicBlock* block, bool unreachable);
4082 bool fgCanCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4084 void fgCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4086 void fgUpdateLoopsAfterCompacting(BasicBlock* block, BasicBlock* bNext);
4088 BasicBlock* fgConnectFallThrough(BasicBlock* bSrc, BasicBlock* bDst);
4090 bool fgRenumberBlocks();
4092 bool fgExpandRarelyRunBlocks();
4094 bool fgEhAllowsMoveBlock(BasicBlock* bBefore, BasicBlock* bAfter);
4096 void fgMoveBlocksAfter(BasicBlock* bStart, BasicBlock* bEnd, BasicBlock* insertAfterBlk);
4098 enum FG_RELOCATE_TYPE
4100 FG_RELOCATE_TRY, // relocate the 'try' region
4101 FG_RELOCATE_HANDLER // relocate the handler region (including the filter if necessary)
4103 BasicBlock* fgRelocateEHRange(unsigned regionIndex, FG_RELOCATE_TYPE relocateType);
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
4118 bool fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* target);
4120 bool fgBlockEndFavorsTailDuplication(BasicBlock* block);
4122 bool fgBlockIsGoodTailDuplicationCandidate(BasicBlock* block);
4124 bool fgOptimizeFallthroughTailDup(BasicBlock* block, BasicBlock* target);
4126 bool fgOptimizeEmptyBlock(BasicBlock* block);
4128 bool fgOptimizeBranchToEmptyUnconditional(BasicBlock* block, BasicBlock* bDest);
4130 bool fgOptimizeBranch(BasicBlock* bJump);
4132 bool fgOptimizeSwitchBranches(BasicBlock* block);
4134 bool fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev);
4136 bool fgOptimizeSwitchJumps();
4138 void fgPrintEdgeWeights();
4140 void fgComputeEdgeWeights();
4142 void fgReorderBlocks();
4144 void fgDetermineFirstColdBlock();
4146 bool fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc = nullptr);
4148 bool fgUpdateFlowGraph(bool doTailDup = false);
4150 void fgFindOperOrder();
4152 // method that returns if you should split here
4153 typedef bool(fgSplitPredicate)(GenTree* tree, GenTree* parent, fgWalkData* data);
4155 void fgSetBlockOrder();
4157 void fgRemoveReturnBlock(BasicBlock* block);
4159 /* Helper code that has been factored out */
4160 inline void fgConvertBBToThrowBB(BasicBlock* block);
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));
4167 // The following check for loops that don't execute calls
4168 bool fgLoopCallMarked;
4170 void fgLoopCallTest(BasicBlock* srcBB, BasicBlock* dstBB);
4171 void fgLoopCallMark();
4173 void fgMarkLoopHead(BasicBlock* block);
4175 unsigned fgGetCodeEstimate(BasicBlock* block);
4178 const char* fgProcessEscapes(const char* nameIn, escapeMapping_t* map);
4179 FILE* fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type);
4180 bool fgDumpFlowGraph(Phases phase);
4182 #endif // DUMP_FLOWGRAPHS
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);
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);
4207 #ifdef LEGACY_BACKEND
4208 static void fgOrderBlockOps(GenTreePtr tree,
4212 GenTreePtr* opsPtr, // OUT
4213 regMaskTP* regsPtr); // OUT
4214 #endif // LEGACY_BACKEND
4216 static GenTreePtr fgGetFirstNode(GenTreePtr tree);
4217 static bool fgTreeIsInStmt(GenTree* tree, GenTreeStmt* stmt);
4219 inline bool fgIsInlining()
4221 return fgExpandInline;
4224 void fgTraverseRPO();
4226 //--------------------- Walking the trees in the IR -----------------------
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
4238 bool printModified; // callback can use this
4242 template <bool computeStack>
4243 static fgWalkResult fgWalkTreePreRec(GenTreePtr* pTree, fgWalkData* fgWalkPre);
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);
4250 fgWalkResult fgWalkTreePre(GenTreePtr* pTree,
4251 fgWalkPreFn* visitor,
4252 void* pCallBackData = nullptr,
4253 bool lclVarsOnly = false,
4254 bool computeStack = false);
4256 fgWalkResult fgWalkTree(GenTreePtr* pTree,
4257 fgWalkPreFn* preVisitor,
4258 fgWalkPostFn* postVisitor,
4259 void* pCallBackData = nullptr);
4261 void fgWalkAllTreesPre(fgWalkPreFn* visitor, void* pCallBackData);
4265 template <bool computeStack>
4266 static fgWalkResult fgWalkTreePostRec(GenTreePtr* pTree, fgWalkData* fgWalkPre);
4268 fgWalkResult fgWalkTreePost(GenTreePtr* pTree,
4269 fgWalkPostFn* visitor,
4270 void* pCallBackData = nullptr,
4271 bool computeStack = false);
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
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);
4283 /**************************************************************************
4285 *************************************************************************/
4288 friend class SsaBuilder;
4289 friend struct ValueNumberState;
4291 //--------------------- Detect the basic blocks ---------------------------
4293 BasicBlock** fgBBs; // Table of pointers to the BBs
4295 void fgInitBBLookup();
4296 BasicBlock* fgLookupBB(unsigned addr);
4298 void fgMarkJumpTarget(BYTE* jumpTarget, IL_OFFSET offs);
4300 void fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, BYTE* jumpTarget);
4302 void fgMarkBackwardJump(BasicBlock* startBlock, BasicBlock* endBlock);
4304 void fgLinkBasicBlocks();
4306 void fgMakeBasicBlocks(const BYTE* codeAddr, IL_OFFSET codeSize, BYTE* jumpTarget);
4308 void fgCheckBasicBlockControlFlow();
4310 void fgControlFlowPermitted(BasicBlock* blkSrc,
4311 BasicBlock* blkDest,
4312 BOOL IsLeave = false /* is the src a leave block */);
4314 bool fgFlowToFirstBlockOfInnerTry(BasicBlock* blkSrc, BasicBlock* blkDest, bool sibling);
4316 void fgObserveInlineConstants(OPCODE opcode, const FgStack& stack, bool isInlining);
4318 void fgAdjustForAddressExposedOrWrittenThis();
4320 bool fgProfileData_ILSizeMismatch;
4321 ICorJitInfo::ProfileBuffer* fgProfileBuffer;
4322 ULONG fgProfileBufferCount;
4323 ULONG fgNumProfileRuns;
4325 unsigned fgStressBBProf()
4328 unsigned result = JitConfig.JitStressBBProf();
4331 if (compStressCompile(STRESS_BB_PROFILE, 15))
4342 bool fgHaveProfileData();
4343 bool fgGetProfileWeightForBasicBlock(IL_OFFSET offset, unsigned* weight);
4345 bool fgIsUsingProfileWeights()
4347 return (fgHaveProfileData() || fgStressBBProf());
4349 void fgInstrumentMethod();
4351 //-------- Insert a statement at the start or end of a basic block --------
4355 static bool fgBlockContainsStatementBounded(BasicBlock* block, GenTree* stmt, bool answerOnBoundExceeded = true);
4359 GenTreeStmt* fgInsertStmtAtEnd(BasicBlock* block, GenTreePtr node);
4361 public: // Used by linear scan register allocation
4362 GenTreeStmt* fgInsertStmtNearEnd(BasicBlock* block, GenTreePtr node);
4365 GenTreePtr fgInsertStmtAtBeg(BasicBlock* block, GenTreePtr stmt);
4366 GenTreePtr fgInsertStmtAfter(BasicBlock* block, GenTreePtr insertionPoint, GenTreePtr stmt);
4368 public: // Used by linear scan register allocation
4369 GenTreePtr fgInsertStmtBefore(BasicBlock* block, GenTreePtr insertionPoint, GenTreePtr stmt);
4372 GenTreePtr fgInsertStmtListAfter(BasicBlock* block, GenTreePtr stmtAfter, GenTreePtr stmtList);
4374 GenTreePtr fgMorphSplitTree(GenTree** splitPoint, GenTree* stmt, BasicBlock* blk);
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);
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);
4386 void fgFixupArgTabEntryPtr(GenTreePtr parentCall, GenTreePtr oldArg, GenTreePtr newArg);
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);
4393 //-------- Determine the order in which the trees will be evaluated -------
4395 unsigned fgTreeSeqNum;
4396 GenTree* fgTreeSeqLst;
4397 GenTree* fgTreeSeqBeg;
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);
4405 //------------------------- Morphing --------------------------------------
4407 unsigned fgPtrArgCntCur;
4408 unsigned fgPtrArgCntMax;
4409 hashBv* fgOutgoingArgTemps;
4410 hashBv* fgCurrentlyInUseArgTemps;
4412 bool compCanEncodePtrArgCntMax();
4414 void fgSetRngChkTarget(GenTreePtr tree, bool delay = true);
4417 void fgMoveOpsLeft(GenTreePtr tree);
4420 bool fgIsCommaThrow(GenTreePtr tree, bool forFolding = false);
4422 bool fgIsThrow(GenTreePtr tree);
4424 bool fgInDifferentRegions(BasicBlock* blk1, BasicBlock* blk2);
4425 bool fgIsBlockCold(BasicBlock* block);
4427 GenTreePtr fgMorphCastIntoHelper(GenTreePtr tree, int helper, GenTreePtr oper);
4429 GenTreePtr fgMorphIntoHelperCall(GenTreePtr tree, int helper, GenTreeArgList* args);
4431 GenTreePtr fgMorphStackArgForVarArgs(unsigned lclNum, var_types varType, unsigned lclOffs);
4433 bool fgMorphRelopToQmark(GenTreePtr tree);
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
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.
4452 struct MorphAddrContext
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.
4460 MorphAddrContext(MorphAddrContextKind kind) : m_kind(kind), m_allConstantOffsets(true), m_totalOffset(0)
4465 // A MACK_CopyBlock context is immutable, so we can just make one of these and share it.
4466 static MorphAddrContext s_CopyBlockMAC;
4469 GenTreePtr fgCopySIMDNode(GenTreeSIMD* simdNode);
4470 GenTreePtr getSIMDStructFromField(GenTreePtr tree,
4471 var_types* baseTypeOut,
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);
4480 // fgPreviousCandidateSIMDFieldAsgStmt is only used for tracking previous simd field assignment
4481 // in function: Complier::impMarkContiguousSIMDFieldAssignments.
4482 GenTreePtr fgPreviousCandidateSIMDFieldAsgStmt;
4484 #endif // FEATURE_SIMD
4485 GenTreePtr fgMorphArrayIndex(GenTreePtr tree);
4486 GenTreePtr fgMorphCast(GenTreePtr tree);
4487 GenTreePtr fgUnwrapProxy(GenTreePtr objRef);
4488 GenTreeCall* fgMorphArgs(GenTreeCall* call);
4490 void fgMakeOutgoingStructArgCopy(GenTreeCall* call,
4493 CORINFO_CLASS_HANDLE copyBlkClass FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(
4494 const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structDescPtr));
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,
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);
4514 void fgNoteNonInlineCandidate(GenTreePtr tree, GenTreeCall* call);
4515 static fgWalkPreFn fgFindNonInlineCandidate;
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);
4533 GenTreePtr fgMorphToEmulatedFP(GenTreePtr tree);
4534 GenTreePtr fgMorphConst(GenTreePtr tree);
4537 GenTreePtr fgMorphTree(GenTreePtr tree, MorphAddrContext* mac = nullptr);
4540 #if LOCAL_ASSERTION_PROP
4541 void fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTreePtr tree));
4543 void fgMorphTreeDone(GenTreePtr tree, GenTreePtr oldTree = nullptr DEBUGARG(int morphNum = 0));
4545 GenTreePtr fgMorphStmt;
4547 unsigned fgGetBigOffsetMorphingTemp(var_types type); // We cache one temp per type to be
4548 // used when morphing big offset.
4550 //----------------------- Liveness analysis -------------------------------
4552 VARSET_TP fgCurUseSet; // vars used by block (before an assignment)
4553 VARSET_TP fgCurDefSet; // vars assigned by block (before a use)
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.
4559 void fgMarkUseDef(GenTreeLclVarCommon* tree, GenTree* asgdLclVar = nullptr);
4561 #ifdef DEBUGGING_SUPPORT
4562 void fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
4563 void fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
4565 void fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope);
4566 void fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope);
4568 void fgExtendDbgScopes();
4569 void fgExtendDbgLifetimes();
4572 void fgDispDebugScopes();
4575 #endif // DEBUGGING_SUPPORT
4577 //-------------------------------------------------------------------------
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.
4585 AddCodeDsc* acdNext;
4586 BasicBlock* acdDstBlk; // block to which we jump
4588 SpecialCodeKind acdKind; // what kind of a special block is this?
4589 unsigned short acdStkLvl;
4593 static unsigned acdHelper(SpecialCodeKind codeKind);
4595 AddCodeDsc* fgAddCodeList;
4597 bool fgRngChkThrowAdded;
4598 AddCodeDsc* fgExcptnTargetCache[SCK_COUNT];
4600 BasicBlock* fgRngChkTarget(BasicBlock* block, unsigned stkDepth, SpecialCodeKind kind);
4602 BasicBlock* fgAddCodeRef(BasicBlock* srcBlk, unsigned refData, SpecialCodeKind kind, unsigned stkDepth = 0);
4605 AddCodeDsc* fgFindExcptnTarget(SpecialCodeKind kind, unsigned refData);
4608 bool fgIsCodeAdded();
4610 bool fgIsThrowHlpBlk(BasicBlock* block);
4611 unsigned fgThrowHlpBlkStkLevel(BasicBlock* block);
4613 unsigned fgBigOffsetMorphingTemps[TYP_COUNT];
4615 unsigned fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo);
4616 void fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* result);
4617 void fgInsertInlineeBlocks(InlineInfo* pInlineInfo);
4618 GenTreePtr fgInlinePrependStatements(InlineInfo* inlineInfo);
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
4626 static fgWalkPreFn fgUpdateInlineReturnExpressionPlaceHolder;
4629 static fgWalkPreFn fgDebugCheckInlineCandidates;
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);
4642 // Returns true if the type of tree is of size at least "width", or if "tree" is not a
4644 bool fgFitsInOrNotLoc(GenTreePtr tree, unsigned width);
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);
4651 static fgWalkPreFn gtHasLocalsWithAddrOpCB;
4652 bool gtCanOptimizeTypeEquality(GenTreePtr tree);
4653 bool gtIsTypeHandleToRuntimeTypeHelper(GenTreePtr tree);
4654 bool gtIsActiveCSE_Candidate(GenTreePtr tree);
4657 bool fgPrintInlinedMethods;
4660 bool fgIsBigOffset(size_t offset);
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);
4669 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4670 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4674 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4675 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4682 LclVarDsc* optIsTrackedLocal(GenTreePtr tree);
4685 void optRemoveRangeCheck(
4686 GenTreePtr tree, GenTreePtr stmt, bool updateCSEcounts, unsigned sideEffFlags = 0, bool forceRemove = false);
4687 bool optIsRangeCheckRemovable(GenTreePtr tree);
4690 static fgWalkPreFn optValidRangeCheckIndex;
4691 static fgWalkPreFn optRemoveTreeVisitor; // Helper passed to Compiler::fgWalkAllTreesPre() to decrement the LclVar
4694 void optRemoveTree(GenTreePtr deadTree, GenTreePtr keepList);
4696 /**************************************************************************
4698 *************************************************************************/
4701 // Do hoisting for all loops.
4702 void optHoistLoopCode();
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;
4708 struct LoopHoistContext
4711 // The set of variables hoisted in the current loop (or nullptr if there are none).
4712 VNSet* m_pHoistedInCurLoop;
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;
4721 VNSet* GetHoistedInCurLoop(Compiler* comp)
4723 if (m_pHoistedInCurLoop == nullptr)
4725 m_pHoistedInCurLoop = new (comp->getAllocatorLoopHoist()) VNSet(comp->getAllocatorLoopHoist());
4727 return m_pHoistedInCurLoop;
4730 VNSet* ExtractHoistedInCurLoop()
4732 VNSet* res = m_pHoistedInCurLoop;
4733 m_pHoistedInCurLoop = nullptr;
4737 LoopHoistContext(Compiler* comp)
4738 : m_pHoistedInCurLoop(nullptr)
4739 , m_hoistedInParentLoops(comp->getAllocatorLoopHoist())
4740 , m_curLoopVnInvariantCache(comp->getAllocatorLoopHoist())
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);
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".
4754 void optHoistThisLoop(unsigned lnum, LoopHoistContext* hoistCtxt);
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);
4761 // Return true if the tree looks profitable to hoist out of loop 'lnum'.
4762 bool optIsProfitableToHoistableTree(GenTreePtr tree, unsigned lnum);
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,
4773 LoopHoistContext* hoistCtxt,
4774 bool* firstBlockAndBeforeSideEffect,
4777 // Performs the hoisting 'tree' into the PreHeader for loop 'lnum'
4778 void optHoistCandidate(GenTreePtr tree, unsigned lnum, LoopHoistContext* hoistCtxt);
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);
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);
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);
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();
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);
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);
4808 // Hoist the expression "expr" out of loop "lnum".
4809 void optPerformHoistExpr(GenTreePtr expr, unsigned lnum);
4812 void optOptimizeBools();
4815 GenTree* optIsBoolCond(GenTree* condBranch, GenTree** compPtr, bool* boolPtr);
4817 void optOptimizeBoolsGcStress(BasicBlock* condBlock);
4820 void optOptimizeLayout(); // Optimize the BasicBlock layout of the method
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
4826 // Optionally clone loops in the loop table.
4827 void optCloneLoops();
4829 // Clone loop "loopInd" in the loop table.
4830 void optCloneLoop(unsigned loopInd, LoopCloneContext* context);
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
4836 void optEnsureUniqueHead(unsigned loopInd, unsigned ambientWeight);
4838 void optUnrollLoops(); // Unrolls loops (needs to have cost info)
4841 // This enumeration describes what is killed by a call.
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)
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().
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
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)
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
4876 unsigned short lpFlags; // Mask of the LPFLG_* constants
4878 unsigned char lpExitCnt; // number of exits from the loop
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.
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
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
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)
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)
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
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.
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
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
4918 int lpHoistedExprCount; // The register count for the non-FP expressions from inside this loop that have been
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
4923 int lpHoistedFPExprCount; // The register count for the FP expressions from inside this loop that have been
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
4928 typedef SimplerHashTable<CORINFO_FIELD_HANDLE,
4929 PtrKeyFuncs<struct CORINFO_FIELD_STRUCT_>,
4931 JitSimplerHashBehavior>
4933 FieldHandleSet* lpFieldsModified; // This has entries (mappings to "true") for all static field and object
4934 // instance fields modified
4937 typedef SimplerHashTable<CORINFO_CLASS_HANDLE,
4938 PtrKeyFuncs<struct CORINFO_CLASS_STRUCT_>,
4940 JitSimplerHashBehavior>
4942 ClassHandleSet* lpArrayElemTypesModified; // Bits set indicate the set of sz array element types such that
4943 // arrays of that type are modified
4946 // Adds the variable liveness information for 'blk' to 'this' LoopDsc
4947 void AddVariableLiveness(Compiler* comp, BasicBlock* blk);
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);
4955 /* The following values are set only for iterator loops, i.e. has the flag LPFLG_ITER set */
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();
4963 var_types lpIterOperType(); // For overflow instructions
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
4971 /* The following is for LPFLG_ITER loops only (i.e. the loop condition is "i RELOP const or var" */
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();
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
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
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
4989 // Returns "true" iff "*this" contains the blk.
4990 bool lpContains(BasicBlock* blk)
4992 return lpFirst->bbNum <= blk->bbNum && blk->bbNum <= lpBottom->bbNum;
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)
4998 return lpFirst->bbNum <= first->bbNum && bottom->bbNum < lpBottom->bbNum;
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)
5005 return lpContains(lp2.lpFirst, lp2.lpBottom);
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)
5012 return first->bbNum <= lpFirst->bbNum && lpBottom->bbNum < bottom->bbNum;
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)
5019 return lpContains(lp2.lpFirst, lp2.lpBottom);
5022 // Returns "true" iff "*this" is disjoint from the range [top, bottom].
5023 bool lpDisjoint(BasicBlock* first, BasicBlock* bottom)
5025 return bottom->bbNum < lpFirst->bbNum || lpBottom->bbNum < first->bbNum;
5027 // Returns "true" iff "*this" is disjoint from "lp2".
5028 bool lpDisjoint(const LoopDsc& lp2)
5030 return lpDisjoint(lp2.lpFirst, lp2.lpBottom);
5032 // Returns "true" iff the loop is well-formed (see code for defn).
5035 return lpFirst->bbNum <= lpTop->bbNum && lpTop->bbNum <= lpEntry->bbNum &&
5036 lpEntry->bbNum <= lpBottom->bbNum &&
5037 (lpHead->bbNum < lpTop->bbNum || lpHead->bbNum > lpBottom->bbNum);
5042 bool fgMightHaveLoop(); // returns true if there are any backedges
5043 bool fgHasLoops; // True if this method has any loops, set in fgComputeReachability
5046 LoopDsc optLoopTable[MAX_LOOP_NUM]; // loop descriptor table
5047 unsigned char optLoopCount; // number of tracked loops
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.
5056 unsigned optFindLoopNumberFromBeginBlock(BasicBlock* begBlk);
5057 void optPrintLoopInfo(unsigned loopNum,
5059 BasicBlock* lpFirst,
5061 BasicBlock* lpEntry,
5062 BasicBlock* lpBottom,
5063 unsigned char lpExitCnt,
5065 unsigned parentLoop = BasicBlock::NOT_IN_LOOP);
5066 void optPrintLoopInfo(unsigned lnum);
5067 void optPrintLoopRecording(unsigned lnum);
5069 void optCheckPreds();
5072 void optSetBlockWeights();
5074 void optMarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk, bool excludeEndBlk);
5076 void optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk);
5078 void optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmarkLoop = false);
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,
5090 GenTreePtr* ppIncr);
5092 void optRecordLoop(BasicBlock* head,
5098 unsigned char exitCnt);
5100 void optFindNaturalLoops();
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);
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);
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);
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);
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);
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);
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);
5138 // The depth of the loop described by "lnum" (an index into the loop table.) (0 == top level)
5139 unsigned optLoopDepth(unsigned lnum)
5141 unsigned par = optLoopTable[lnum].lpParent;
5142 if (par == BasicBlock::NOT_IN_LOOP)
5148 return 1 + optLoopDepth(par);
5152 void fgOptWhileLoop(BasicBlock* block);
5154 bool optComputeLoopRep(int constInit,
5157 genTreeOps iterOper,
5159 genTreeOps testOper,
5162 unsigned* iterCount);
5163 #if FEATURE_STACK_FP_X87
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
5172 static fgWalkPreFn optIsVarAssgCB;
5175 bool optIsVarAssigned(BasicBlock* beg, BasicBlock* end, GenTreePtr skip, unsigned var);
5177 bool optIsVarAssgLoop(unsigned lnum, unsigned var);
5179 int optIsSetAssgLoop(unsigned lnum, ALLVARSET_VALARG_TP vars, varRefKinds inds = VR_NONE);
5181 bool optNarrowTree(GenTreePtr tree, var_types srct, var_types dstt, ValueNumPair vnpNarrow, bool doit);
5183 /**************************************************************************
5184 * Optimization conditions
5185 *************************************************************************/
5187 bool optFastCodeOrBlendedLoop(BasicBlock::weight_t bbWeight);
5188 bool optPentium4(void);
5189 bool optAvoidIncDec(BasicBlock::weight_t bbWeight);
5190 bool optAvoidIntMult(void);
5195 // The following is the upper limit on how many expressions we'll keep track
5196 // of for the CSE analysis.
5198 static const unsigned MAX_CSE_CNT = EXPSET_SZ;
5200 static const int MIN_CSE_COST = 2;
5202 /* Generic list of nodes - used by the CSE logic */
5210 typedef struct treeLst* treeLstPtr;
5214 treeStmtLst* tslNext;
5215 GenTreePtr tslTree; // tree node
5216 GenTreePtr tslStmt; // statement containing the tree
5217 BasicBlock* tslBlock; // block containing the statement
5220 typedef struct treeStmtLst* treeStmtLstPtr;
5222 // The following logic keeps track of expressions via a simple hash table.
5226 CSEdsc* csdNextInBucket; // used by the hash table
5228 unsigned csdHashValue; // the orginal hashkey
5230 unsigned csdIndex; // 1..optCSECandidateCount
5231 char csdLiveAcrossCall; // 0 or 1
5233 unsigned short csdDefCount; // definition count
5234 unsigned short csdUseCount; // use count (excluding the implicit uses at defs)
5236 unsigned csdDefWtCnt; // weighted def count
5237 unsigned csdUseWtCnt; // weighted use count (excluding the implicit uses at defs)
5239 GenTreePtr csdTree; // treenode containing the 1st occurance
5240 GenTreePtr csdStmt; // stmt containing the 1st occurance
5241 BasicBlock* csdBlock; // block containing the 1st occurance
5243 treeStmtLstPtr csdTreeList; // list of matching tree nodes: head
5244 treeStmtLstPtr csdTreeLast; // list of matching tree nodes: tail
5247 static const size_t s_optCSEhashSize;
5248 CSEdsc** optCSEhash;
5253 CSEdsc* optCSEfindDsc(unsigned index);
5254 void optUnmarkCSE(GenTreePtr tree);
5256 // user defined callback data for the tree walk function optCSE_MaskHelper()
5257 struct optCSE_MaskData
5259 EXPSET_TP CSE_defMask;
5260 EXPSET_TP CSE_useMask;
5263 // Treewalk helper for optCSE_DefMask and optCSE_UseMask
5264 static fgWalkPreFn optCSE_MaskHelper;
5266 // This function walks all the node for an given tree
5267 // and return the mask of CSE definitions and uses for the tree
5269 void optCSE_GetMaskData(GenTreePtr tree, optCSE_MaskData* pMaskData);
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);
5275 static fgWalkPostFn optPropagateNonCSE;
5276 static fgWalkPreFn optHasNonCSEChild;
5278 static fgWalkPreFn optUnmarkCSEs;
5280 static int __cdecl optCSEcostCmpEx(const void* op1, const void* op2);
5281 static int __cdecl optCSEcostCmpSz(const void* op1, const void* op2);
5283 void optCleanupCSEs();
5286 void optEnsureClearCSEInfo();
5289 #endif // FEATURE_ANYCSE
5291 #if FEATURE_VALNUM_CSE
5292 /**************************************************************************
5293 * Value Number based CSEs
5294 *************************************************************************/
5297 void optOptimizeValnumCSEs();
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);
5309 #endif // FEATURE_VALNUM_CSE
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
5321 bool optIsCSEcandidate(GenTreePtr tree);
5323 // lclNumIsTrueCSE returns true if the LclVar was introduced by the CSE phase of the compiler
5325 bool lclNumIsTrueCSE(unsigned lclNum) const
5327 return ((optCSEcount > 0) && (lclNum >= optCSEstart) && (lclNum < optCSEstart + optCSEcount));
5330 // lclNumIsCSE returns true if the LclVar should be treated like a CSE with regards to constant prop.
5332 bool lclNumIsCSE(unsigned lclNum) const
5334 return lvaTable[lclNum].lvIsCSE;
5338 bool optConfigDisableCSE();
5339 bool optConfigDisableCSE2();
5341 void optOptimizeCSEs();
5343 #endif // FEATURE_ANYCSE
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?
5358 static callInterf optCallInterf(GenTreePtr call);
5361 // VN based copy propagation.
5362 typedef ArrayStack<GenTreePtr> GenTreePtrStack;
5363 typedef SimplerHashTable<unsigned, SmallPrimitiveKeyFuncs<unsigned>, GenTreePtrStack*, JitSimplerHashBehavior>
5364 LclNumToGenTreePtrStack;
5366 // Kill set to track variables with intervening definitions.
5367 VARSET_TP optCopyPropKillSet;
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();
5377 /**************************************************************************
5378 * Early value propagation
5379 *************************************************************************/
5385 SSAName(unsigned lvNum, unsigned ssaNum) : m_lvNum(lvNum), m_ssaNum(ssaNum)
5389 static unsigned GetHashCode(SSAName ssaNm)
5391 return (ssaNm.m_lvNum << 16) | (ssaNm.m_ssaNum);
5394 static bool Equals(SSAName ssaNm1, SSAName ssaNm2)
5396 return (ssaNm1.m_lvNum == ssaNm2.m_lvNum) && (ssaNm1.m_ssaNum == ssaNm2.m_ssaNum);
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.
5406 unsigned optMethodFlags;
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;
5412 enum class optPropKind
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);
5433 /**************************************************************************
5434 * Value/Assertion propagation
5435 *************************************************************************/
5437 // Data structures for assertion prop
5438 BitVecTraits* apTraits;
5442 enum optAssertionKind
5457 O1K_ARRLEN_OPER_BND,
5458 O1K_ARRLEN_LOOP_BND,
5459 O1K_CONSTANT_LOOP_BND,
5480 optAssertionKind assertionKind;
5483 unsigned lclNum; // assigned to or property of this local var number
5491 struct AssertionDscOp1
5493 optOp1Kind kind; // a normal LclVar, or Exact-type or Subtype
5500 struct AssertionDscOp2
5502 optOp2Kind kind; // a const or copy assignment
5506 ssize_t iconVal; // integer
5507 unsigned iconFlags; // gtFlags
5509 struct Range // integer subrange
5523 bool IsArrLenArithBound()
5525 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_ARRLEN_OPER_BND);
5527 bool IsArrLenBound()
5529 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_ARRLEN_LOOP_BND);
5531 bool IsConstantBound()
5533 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) &&
5534 op1.kind == O1K_CONSTANT_LOOP_BND);
5536 bool IsBoundsCheckNoThrow()
5538 return ((assertionKind == OAK_NO_THROW) && (op1.kind == O1K_ARR_BND));
5541 bool IsCopyAssertion()
5543 return ((assertionKind == OAK_EQUAL) && (op1.kind == O1K_LCLVAR) && (op2.kind == O2K_LCLVAR_COPY));
5546 static bool SameKind(AssertionDsc* a1, AssertionDsc* a2)
5548 return a1->assertionKind == a2->assertionKind && a1->op1.kind == a2->op1.kind &&
5549 a1->op2.kind == a2->op2.kind;
5552 static bool ComplementaryKind(optAssertionKind kind, optAssertionKind kind2)
5554 if (kind == OAK_EQUAL)
5556 return kind2 == OAK_NOT_EQUAL;
5558 else if (kind == OAK_NOT_EQUAL)
5560 return kind2 == OAK_EQUAL;
5565 static ssize_t GetLowerBoundForIntegralType(var_types type)
5585 static ssize_t GetUpperBoundForIntegralType(var_types type)
5609 bool HasSameOp1(AssertionDsc* that, bool vnBased)
5611 return (op1.kind == that->op1.kind) &&
5612 ((vnBased && (op1.vn == that->op1.vn)) || (!vnBased && (op1.lcl.lclNum == that->op1.lcl.lclNum)));
5615 bool HasSameOp2(AssertionDsc* that, bool vnBased)
5617 if (op2.kind != that->op2.kind)
5623 case O2K_IND_CNS_INT:
5625 return ((op2.u1.iconVal == that->op2.u1.iconVal) && (op2.u1.iconFlags == that->op2.u1.iconFlags));
5627 case O2K_CONST_LONG:
5628 return (op2.lconVal == that->op2.lconVal);
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);
5634 case O2K_LCLVAR_COPY:
5636 return (op2.lcl.lclNum == that->op2.lcl.lclNum) &&
5637 (!vnBased || op2.lcl.ssaNum == that->op2.lcl.ssaNum);
5640 return ((op2.u2.loBound == that->op2.u2.loBound) && (op2.u2.hiBound == that->op2.u2.hiBound));
5643 // we will return false
5647 assert(!"Unexpected value for op2.kind in AssertionDsc.");
5653 bool Complementary(AssertionDsc* that, bool vnBased)
5655 return ComplementaryKind(assertionKind, that->assertionKind) && HasSameOp1(that, vnBased) &&
5656 HasSameOp2(that, vnBased);
5659 bool Equals(AssertionDsc* that, bool vnBased)
5661 return (assertionKind == that->assertionKind) && HasSameOp1(that, vnBased) && HasSameOp2(that, vnBased);
5665 typedef unsigned short AssertionIndex;
5668 static fgWalkPreFn optAddCopiesCallback;
5669 static fgWalkPreFn optVNAssertionPropCurStmtVisitor;
5670 unsigned optAddCopyLclNum;
5671 GenTreePtr optAddCopyAsgnNode;
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;
5677 GenTreePtr optAssertionPropCurrentTree;
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;
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);
5694 AssertionIndex GetAssertionCount()
5696 return optAssertionCount;
5698 ASSERT_TP* bbJtrueAssertionOut;
5699 typedef SimplerHashTable<ValueNum, SmallPrimitiveKeyFuncs<ValueNum>, ASSERT_TP, JitSimplerHashBehavior>
5700 ValueNumToAssertsMap;
5701 ValueNumToAssertsMap* optValueNumToAsserts;
5703 static const AssertionIndex NO_ASSERTION_INDEX = 0;
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);
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();
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);
5731 // Assertion creation functions.
5732 AssertionIndex optCreateAssertion(GenTreePtr op1, GenTreePtr op2, optAssertionKind assertionKind);
5733 AssertionIndex optCreateAssertion(GenTreePtr op1,
5735 optAssertionKind assertionKind,
5736 AssertionDsc* assertion);
5737 void optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTreePtr op1, GenTreePtr op2);
5739 bool optAssertionVnInvolvesNan(AssertionDsc* assertion);
5740 AssertionIndex optAddAssertion(AssertionDsc* assertion);
5741 void optAddVnAssertionMapping(ValueNum vn, AssertionIndex index);
5743 void optPrintVnAssertionMapping();
5745 ASSERT_TP optGetVnMappedAssertions(ValueNum vn);
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));
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);
5759 // Assertion prop for lcl var functions.
5760 bool optAssertionProp_LclVarTypeCheck(GenTreePtr tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc);
5761 GenTreePtr optCopyAssertionProp(AssertionDsc* curAssertion,
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);
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);
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);
5789 ASSERT_VALRET_TP optNewFullAssertSet();
5790 ASSERT_VALRET_TP optNewEmptyAssertSet();
5793 void optPrintAssertion(AssertionDsc* newAssertion, AssertionIndex assertionIndex = 0);
5794 void optDebugCheckAssertion(AssertionDsc* assertion);
5795 void optDebugCheckAssertions(AssertionIndex AssertionIndex);
5797 void optAddCopies();
5798 #endif // ASSERTION_PROP
5800 /**************************************************************************
5802 *************************************************************************/
5805 struct LoopCloneVisitorInfo
5807 LoopCloneContext* context;
5810 LoopCloneVisitorInfo(LoopCloneContext* context, unsigned loopNum, GenTreePtr stmt)
5811 : context(context), loopNum(loopNum), stmt(nullptr)
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);
5825 bool optCanCloneLoops();
5828 void optDebugLogLoopCloning(BasicBlock* block, GenTreePtr insertBefore);
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,
5837 void optInsertLoopCloningStress(BasicBlock* head);
5839 #if COUNT_RANGECHECKS
5840 static unsigned optRangeChkRmv;
5841 static unsigned optRangeChkAll;
5850 #define MAX_ARRAYS 4 // a magic max number of arrays tracked for bounds check elimination
5855 RngChkDsc* rcdNextInBucket; // used by the hash table
5857 unsigned short rcdHashValue; // to make matching faster
5858 unsigned short rcdIndex; // 0..optRngChkCount-1
5860 GenTreePtr rcdTree; // the array index tree
5863 unsigned optRngChkCount;
5864 static const size_t optRngChkHashSize;
5866 ssize_t optGetArrayRefScaleAndIndex(GenTreePtr mul, GenTreePtr* pIndex DEBUGARG(bool bRngChk));
5867 GenTreePtr optFindLocalInit(BasicBlock* block, GenTreePtr local, VARSET_TP* pKilledInOut, bool* isKilledAfterInit);
5870 bool optIsNoMore(GenTreePtr op1, GenTreePtr op2, int add1 = 0, int add2 = 0);
5873 bool optReachWithoutCall(BasicBlock* srcBB, BasicBlock* dstBB);
5876 bool optLoopsMarked;
5879 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5880 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5884 XX Does the register allocation and puts the remaining lclVars on the stack XX
5886 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5887 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5891 #ifndef LEGACY_BACKEND
5896 #else // LEGACY_BACKEND
5901 #endif // LEGACY_BACKEND
5903 #ifdef LEGACY_BACKEND
5905 void raAssignVars(); // register allocation
5906 #endif // LEGACY_BACKEND
5908 VARSET_TP raRegVarsMask; // Set of all enregistered variables (not including FEATURE_STACK_FP_X87 enregistered
5910 regNumber raUpdateRegStateForArg(RegState* regState, LclVarDsc* argDsc);
5912 void raMarkStkVars();
5915 // Some things are used by both LSRA and regpredict allocators.
5917 FrameType rpFrameType;
5918 bool rpMustCreateEBPCalled; // Set to true after we have called rpMustCreateEBPFrame once
5920 #ifdef LEGACY_BACKEND
5921 regMaskTP rpMaskPInvokeEpilogIntf; // pinvoke epilog trashes esi/edi holding stack args needed to setup tail call's
5923 #endif // LEGACY_BACKEND
5925 bool rpMustCreateEBPFrame(INDEBUG(const char** wbReason));
5927 #if FEATURE_FP_REGALLOC
5928 enum enumConfigRegisterFP
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,
5935 enumConfigRegisterFP raConfigRegisterFP();
5936 #endif // FEATURE_FP_REGALLOC
5939 regMaskTP raConfigRestrictMaskFP();
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
5962 bool rpRegAllocDone; // Set to true after we have completed register allocation
5964 regMaskTP rpPredictMap[PREDICT_COUNT]; // Holds the regMaskTP for each of the enum values
5966 void raSetupArgMasks(RegState* r);
5968 const regNumber* raGetRegVarOrder(var_types regType, unsigned* wbVarOrderSize);
5970 void raDumpVarIntf(); // Dump the variable to variable interference graph
5971 void raDumpRegIntf(); // Dump the variable to register interference graph
5973 void raAdjustVarIntf();
5975 regMaskTP rpPredictRegMask(rpPredictReg predictReg, var_types type);
5977 bool rpRecordRegIntf(regMaskTP regMask, VARSET_VALARG_TP life DEBUGARG(const char* msg));
5979 bool rpRecordVarIntf(unsigned varNum, VARSET_VALARG_TP intfVar DEBUGARG(const char* msg));
5980 regMaskTP rpPredictRegPick(var_types type, rpPredictReg predictReg, regMaskTP lockedRegs);
5982 regMaskTP rpPredictGrabReg(var_types type, rpPredictReg predictReg, regMaskTP lockedRegs);
5984 static fgWalkPreFn rpMarkRegIntf;
5986 regMaskTP rpPredictAddressMode(
5987 GenTreePtr tree, var_types type, regMaskTP lockedRegs, regMaskTP rsvdRegs, GenTreePtr lenCSE);
5989 void rpPredictRefAssign(unsigned lclNum);
5991 regMaskTP rpPredictBlkAsgRegUse(GenTreePtr tree, rpPredictReg predictReg, regMaskTP lockedRegs, regMaskTP rsvdRegs);
5993 regMaskTP rpPredictTreeRegUse(GenTreePtr tree, rpPredictReg predictReg, regMaskTP lockedRegs, regMaskTP rsvdRegs);
5995 regMaskTP rpPredictAssignRegVars(regMaskTP regAvail);
5997 void rpPredictRegUse(); // Entry point
5999 unsigned raPredictTreeRegUse(GenTreePtr tree);
6000 unsigned raPredictListRegUse(GenTreePtr list);
6002 void raSetRegVarOrder(var_types regType,
6003 regNumber* customVarOrder,
6004 unsigned* customVarOrderSize,
6006 regMaskTP avoidReg);
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)
6013 unsigned newStkPredict = rpStkPredict + val;
6014 if ((newStkPredict < rpStkPredict) || (newStkPredict == UINT_MAX))
6015 rpStkPredict = UINT_MAX - 1;
6017 rpStkPredict = newStkPredict;
6021 #if !FEATURE_FP_REGALLOC
6022 void raDispFPlifeInfo();
6026 regMaskTP genReturnRegForTree(GenTreePtr tree);
6027 #endif // LEGACY_BACKEND
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
6038 bool raIsVarargsStackArg(unsigned lclNum)
6042 LclVarDsc* varDsc = &lvaTable[lclNum];
6044 assert(varDsc->lvIsParam);
6046 return (info.compIsVarArgs && !varDsc->lvIsRegArg && (lclNum != lvaVarargsHandleArg));
6048 #else // _TARGET_X86_
6052 #endif // _TARGET_X86_
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();
6061 // Data members used in the methods above.
6062 unsigned rpBestRecordedStkPredict;
6063 struct VarRegPrediction
6065 bool m_isEnregistered;
6066 regNumberSmall m_regNum;
6067 regNumberSmall m_otherReg;
6069 VarRegPrediction* rpBestRecordedPrediction;
6070 #endif // LEGACY_BACKEND
6073 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6074 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6078 XX Get to the class and method info from the Execution Engine given XX
6079 XX tokens for the class and method XX
6081 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6082 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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.
6094 VLT_REG_BYREF, // this type is currently only used for value types on X64
6097 VLT_STK_BYREF, // this type is currently only used for value types on X64
6111 siVarLocType vlType;
6114 // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc)
6116 // VLT_REG_BYREF -- the specified register contains the address of the variable
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]
6131 regNumber vlsBaseReg;
6132 NATIVE_OFFSET vlsOffset;
6135 // VLT_REG_REG -- TYP_LONG/TYP_DOUBLE with both DWords enregistered
6144 // VLT_REG_STK -- Partly enregistered TYP_LONG/TYP_DOUBLE
6145 // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] }
6153 regNumber vlrssBaseReg;
6154 NATIVE_OFFSET vlrssOffset;
6158 // VLT_STK_REG -- Partly enregistered TYP_LONG/TYP_DOUBLE
6159 // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX }
6165 regNumber vlsrsBaseReg;
6166 NATIVE_OFFSET vlsrsOffset;
6172 // VLT_STK2 -- Any 64 bit value which is on the stack, in 2 successsive DWords
6173 // eg 2 DWords at [ESP+0x10]
6177 regNumber vls2BaseReg;
6178 NATIVE_OFFSET vls2Offset;
6181 // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack)
6182 // eg. ST(3). Actually it is ST("FPstkHeight - vpFpStk")
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
6197 unsigned vlfvOffset;
6204 void* rpValue; // pointer to the in-process
6205 // location of the value.
6211 bool vlIsInReg(regNumber reg);
6212 bool vlIsOnStk(regNumber reg, signed offset);
6215 /*************************************************************************/
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);
6226 void eeGetFieldInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6227 CORINFO_ACCESS_FLAGS flags,
6228 CORINFO_FIELD_INFO* pResult);
6232 BOOL eeIsValueClass(CORINFO_CLASS_HANDLE clsHnd);
6234 #if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD)
6236 bool IsSuperPMIException(unsigned code)
6238 // Copied from NDP\clr\src\ToolBox\SuperPMI\SuperPMI-Shared\ErrorHandling.h
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;
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:
6265 const char* eeGetMethodName(CORINFO_METHOD_HANDLE hnd, const char** className);
6266 const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd);
6268 bool eeIsNativeMethod(CORINFO_METHOD_HANDLE method);
6269 CORINFO_METHOD_HANDLE eeGetMethodHandleForNative(CORINFO_METHOD_HANDLE method);
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);
6276 // VOM info, method sigs
6278 void eeGetSig(unsigned sigTok,
6279 CORINFO_MODULE_HANDLE scope,
6280 CORINFO_CONTEXT_HANDLE context,
6281 CORINFO_SIG_INFO* retSig);
6283 void eeGetCallSiteSig(unsigned sigTok,
6284 CORINFO_MODULE_HANDLE scope,
6285 CORINFO_CONTEXT_HANDLE context,
6286 CORINFO_SIG_INFO* retSig);
6288 void eeGetMethodSig(CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* retSig, CORINFO_CLASS_HANDLE owner = nullptr);
6290 // Method entry-points, instrs
6292 void* eeGetFieldAddress(CORINFO_FIELD_HANDLE handle, void*** ppIndir);
6294 CORINFO_METHOD_HANDLE eeMarkNativeTarget(CORINFO_METHOD_HANDLE method);
6296 CORINFO_EE_INFO eeInfo;
6297 bool eeInfoInitialized;
6299 CORINFO_EE_INFO* eeGetEEInfo();
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);
6306 GenTreePtr eeGetPInvokeCookie(CORINFO_SIG_INFO* szMetaSig);
6308 // Returns the page size for the target machine as reported by the EE.
6309 inline size_t eeGetPageSize()
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
6318 // Returns the frame size at which we will generate a loop to probe the stack.
6319 inline size_t getVeryLargeFrameSize()
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();
6327 return 3 * eeGetPageSize();
6331 inline bool generateCFIUnwindCodes()
6333 #if COR_JIT_EE_VERSION > 460 && defined(UNIX_AMD64_ABI)
6334 return eeGetEEInfo()->targetAbi == CORINFO_CORERT_ABI;
6342 unsigned eeGetEHcount(CORINFO_METHOD_HANDLE handle);
6344 // Debugging support - Line number info
6346 void eeGetStmtOffsets();
6348 unsigned eeBoundariesCount;
6350 struct boundariesDsc
6352 UNATIVE_OFFSET nativeIP;
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);
6361 static void eeDispILOffs(IL_OFFSET offs);
6362 static void eeDispLineInfo(const boundariesDsc* line);
6363 void eeDispLineInfos();
6366 // Debugging support - Local var info
6370 unsigned eeVarsCount;
6372 struct VarResultInfo
6374 UNATIVE_OFFSET startOffset;
6375 UNATIVE_OFFSET endOffset;
6379 void eeSetLVcount(unsigned count);
6380 void eeSetLVinfo(unsigned which,
6381 UNATIVE_OFFSET startOffs,
6382 UNATIVE_OFFSET length,
6387 const siVarLoc& loc);
6391 void eeDispVar(ICorDebugInfo::NativeVarInfo* var);
6392 void eeDispVars(CORINFO_METHOD_HANDLE ftn, ULONG32 cVars, ICorDebugInfo::NativeVarInfo* vars);
6395 // ICorJitInfo wrappers
6397 void eeReserveUnwindInfo(BOOL isFunclet, BOOL isColdCode, ULONG unwindSize);
6399 void eeAllocUnwindInfo(BYTE* pHotCode,
6405 CorJitFuncKind funcKind);
6407 void eeSetEHcount(unsigned cEH);
6409 void eeSetEHinfo(unsigned EHnumber, const CORINFO_EH_CLAUSE* clause);
6411 WORD eeGetRelocTypeHint(void* target);
6413 // ICorStaticInfo wrapper functions
6415 bool eeTryResolveToken(CORINFO_RESOLVED_TOKEN* resolvedToken);
6417 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
6419 static void dumpSystemVClassificationType(SystemVClassificationType ct);
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
6427 template <typename ParamType>
6428 bool eeRunWithErrorTrap(void (*function)(ParamType*), ParamType* param)
6430 return eeRunWithErrorTrapImp(reinterpret_cast<void (*)(void*)>(function), reinterpret_cast<void*>(param));
6433 bool eeRunWithErrorTrapImp(void (*function)(void*), void* param);
6435 // Utility functions
6437 const char* eeGetFieldName(CORINFO_FIELD_HANDLE fieldHnd, const char** classNamePtr = nullptr);
6440 const wchar_t* eeGetCPString(size_t stringHandle);
6443 const char* eeGetClassName(CORINFO_CLASS_HANDLE clsHnd);
6445 static CORINFO_METHOD_HANDLE eeFindHelper(unsigned helper);
6446 static CorInfoHelpFunc eeGetHelperNum(CORINFO_METHOD_HANDLE method);
6448 static fgWalkPreFn CountSharedStaticHelper;
6449 static bool IsSharedStaticHelper(GenTreePtr tree);
6450 static bool IsTreeAlwaysHoistable(GenTreePtr tree);
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);
6458 /*****************************************************************************/
6463 enum TEMP_USAGE_TYPE
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;
6475 TempDsc* tmpListBeg(TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
6476 TempDsc* tmpListNxt(TempDsc* curTemp, TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
6480 bool tmpAllFree() const;
6483 #ifndef LEGACY_BACKEND
6484 void tmpPreAllocateTemps(var_types type, unsigned count);
6485 #endif // !LEGACY_BACKEND
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
6493 unsigned tmpCount; // Number of temps
6494 unsigned tmpSize; // Size of all the temps
6497 // Used by RegSet::rsSpillChk()
6498 unsigned tmpGetCount; // Temps which haven't been released yet
6501 static unsigned tmpSlot(unsigned size); // which slot in tmpFree[] or tmpUsed[] to use
6503 TempDsc* tmpFree[TEMP_MAX_SIZE / sizeof(int)];
6504 TempDsc* tmpUsed[TEMP_MAX_SIZE / sizeof(int)];
6507 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6508 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6512 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6513 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6517 CodeGenInterface* codeGen;
6519 #ifdef DEBUGGING_SUPPORT
6521 // The following holds information about instr offsets in terms of generated code.
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?
6531 // Record the instr offset mapping to the generated code
6533 IPmappingDsc* genIPmappingList;
6534 IPmappingDsc* genIPmappingLast;
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.
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
6552 unsigned genReturnLocal; // Local number for the return value when applicable.
6553 BasicBlock* genReturnBB; // jumped to when not optimizing for speed.
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.
6559 __declspec(property(get = getEmitter)) emitter* genEmitter;
6560 emitter* getEmitter()
6562 return codeGen->getEmitter();
6565 const bool isFramePointerUsed()
6567 return codeGen->isFramePointerUsed();
6570 __declspec(property(get = getInterruptible, put = setInterruptible)) bool genInterruptible;
6571 bool getInterruptible()
6573 return codeGen->genInterruptible;
6575 void setInterruptible(bool value)
6577 codeGen->setInterruptible(value);
6581 const bool genDoubleAlign()
6583 return codeGen->doDoubleAlign();
6585 DWORD getCanDoubleAlign(); // Defined & used only by RegAlloc
6586 #endif // DOUBLE_ALIGN
6587 __declspec(property(get = getFullPtrRegMap, put = setFullPtrRegMap)) bool genFullPtrRegMap;
6588 bool getFullPtrRegMap()
6590 return codeGen->genFullPtrRegMap;
6592 void setFullPtrRegMap(bool value)
6594 codeGen->setFullPtrRegMap(value);
6597 // Things that MAY belong either in CodeGen or CodeGenContext
6599 #if FEATURE_EH_FUNCLETS
6600 FuncInfoDsc* compFuncInfos;
6601 unsigned short compCurrFuncIdx;
6602 unsigned short compFuncInfoCount;
6604 unsigned short compFuncCount()
6606 assert(fgFuncletsCreated);
6607 return compFuncInfoCount;
6610 #else // !FEATURE_EH_FUNCLETS
6612 // This is a no-op when there are no funclets!
6613 void genUpdateCurrentFunclet(BasicBlock* block)
6618 FuncInfoDsc compFuncInfoRoot;
6620 static const unsigned compCurrFuncIdx = 0;
6622 unsigned short compFuncCount()
6627 #endif // !FEATURE_EH_FUNCLETS
6629 FuncInfoDsc* funCurrentFunc();
6630 void funSetCurrentFunc(unsigned funcIdx);
6631 FuncInfoDsc* funGetFunc(unsigned funcIdx);
6632 unsigned int funGetFuncIdx(BasicBlock* block);
6636 VARSET_TP compCurLife; // current live variables
6637 GenTreePtr compCurLifeTree; // node after which compCurLife has been computed
6639 template <bool ForCodeGen>
6640 void compChangeLife(VARSET_VALARG_TP newLife DEBUGARG(GenTreePtr tree));
6642 void genChangeLife(VARSET_VALARG_TP newLife DEBUGARG(GenTreePtr tree))
6644 compChangeLife</*ForCodeGen*/ true>(newLife DEBUGARG(tree));
6647 template <bool ForCodeGen>
6648 void compUpdateLife(GenTreePtr tree);
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);
6656 template <bool ForCodeGen>
6657 inline void compUpdateLife(VARSET_VALARG_TP newLife);
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);
6663 // Gets a register mask that represent the kill set for a NoGC helper call.
6664 regMaskTP compNoGCHelperCallKillSet(CorInfoHelpFunc helper);
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_
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
6677 static GenTreePtr fgIsIndirOfAddrOfLocal(GenTreePtr tree);
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;
6687 NodeToVarsetPtrMap* GetPromotedStructDeathVars()
6689 if (m_promotedStructDeathVars == nullptr)
6691 m_promotedStructDeathVars = new (getAllocator()) NodeToVarsetPtrMap(getAllocator());
6693 return m_promotedStructDeathVars;
6697 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6698 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6702 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6703 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6706 #if !defined(__GNUC__)
6707 #pragma region Unwind information
6712 // Infrastructure functions: start/stop/reserve/emit.
6715 void unwindBegProlog();
6716 void unwindEndProlog();
6717 void unwindBegEpilog();
6718 void unwindEndEpilog();
6719 void unwindReserve();
6720 void unwindEmit(void* pHotCode, void* pColdCode);
6723 // Specific unwind information functions: called by code generation to indicate a particular
6724 // prolog or epilog unwindable instruction has been generated.
6727 void unwindPush(regNumber reg);
6728 void unwindAllocStack(unsigned size);
6729 void unwindSetFrameReg(regNumber reg, unsigned offset);
6730 void unwindSaveReg(regNumber reg, unsigned offset);
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_
6744 #if defined(_TARGET_ARM64_)
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_)
6757 // Private "helper" functions for the unwind implementation.
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
6768 void unwindReserveFunc(FuncInfoDsc* func);
6769 void unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
6771 #if defined(_TARGET_AMD64_)
6773 void unwindReserveFuncHelper(FuncInfoDsc* func, bool isHotCode);
6774 void unwindEmitFuncHelper(FuncInfoDsc* func, void* pHotCode, void* pColdCode, bool isHotCode);
6775 UNATIVE_OFFSET unwindGetCurrentOffset(FuncInfoDsc* func);
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);
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_)
6794 void unwindPushPopMaskInt(regMaskTP mask, bool useOpsize16);
6795 void unwindPushPopMaskFloat(regMaskTP mask);
6796 void unwindSplit(FuncInfoDsc* func);
6798 #endif // _TARGET_ARM_
6800 #if !defined(__GNUC__)
6801 #pragma endregion // Note: region is NOT under !defined(__GNUC__)
6805 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6806 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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
6813 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6814 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6817 // Get highest available instruction set for floating point codegen
6818 InstructionSet getFloatingPointInstructionSet()
6820 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
6823 return InstructionSet_AVX;
6827 assert(canUseSSE2());
6828 return InstructionSet_SSE2;
6830 assert(!"getFPInstructionSet() is not implemented for target arch");
6832 return InstructionSet_NONE;
6836 // Get highest available instruction set for SIMD codegen
6837 InstructionSet getSIMDInstructionSet()
6839 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
6840 return getFloatingPointInstructionSet();
6842 assert(!"Available instruction set(s) for SIMD codegen is not defined for target arch");
6844 return InstructionSet_NONE;
6850 // Should we support SIMD intrinsics?
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;
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;
6874 // Get the handle for a SIMD type.
6875 CORINFO_CLASS_HANDLE gtGetStructHandleForSIMD(var_types simdType, var_types simdBaseType)
6877 if (simdBaseType == TYP_FLOAT)
6882 return SIMDVector2Handle;
6884 return SIMDVector3Handle;
6886 if ((getSIMDVectorType() == TYP_SIMD32) || (SIMDVector4Handle != NO_CLASS_HANDLE))
6888 return SIMDVector4Handle;
6897 assert(simdType == getSIMDVectorType());
6898 switch (simdBaseType)
6901 return SIMDFloatHandle;
6903 return SIMDDoubleHandle;
6905 return SIMDIntHandle;
6907 return SIMDUShortHandle;
6909 return SIMDUShortHandle;
6911 return SIMDUByteHandle;
6913 return SIMDShortHandle;
6915 return SIMDByteHandle;
6917 return SIMDLongHandle;
6919 return SIMDUIntHandle;
6921 return SIMDULongHandle;
6923 assert(!"Didn't find a class handle for simdType");
6925 return NO_CLASS_HANDLE;
6929 CORINFO_METHOD_HANDLE SIMDVectorFloat_set_Item;
6930 CORINFO_METHOD_HANDLE SIMDVectorFloat_get_Length;
6931 CORINFO_METHOD_HANDLE SIMDVectorFloat_op_Addition;
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)
6938 return tree->OperIsLocal() && lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
6941 // Returns true if the type of the tree is a byref of TYP_SIMD
6942 bool isAddrOfSIMDType(GenTree* tree)
6944 if (tree->TypeGet() == TYP_BYREF || tree->TypeGet() == TYP_I_IMPL)
6946 switch (tree->OperGet())
6949 return varTypeIsSIMD(tree->gtGetOp1());
6951 case GT_LCL_VAR_ADDR:
6952 return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
6955 return isSIMDTypeLocal(tree);
6962 static bool isRelOpSIMDIntrinsic(SIMDIntrinsicID intrinsicId)
6964 return (intrinsicId == SIMDIntrinsicEqual || intrinsicId == SIMDIntrinsicLessThan ||
6965 intrinsicId == SIMDIntrinsicLessThanOrEqual || intrinsicId == SIMDIntrinsicGreaterThan ||
6966 intrinsicId == SIMDIntrinsicGreaterThanOrEqual);
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)
6973 if (isSIMDTypeLocal(tree))
6975 return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvBaseType;
6981 bool isSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
6983 return info.compCompHnd->isInSIMDModule(clsHnd);
6986 bool isSIMDClass(typeInfo* pTypeInfo)
6988 return pTypeInfo->IsStruct() && isSIMDClass(pTypeInfo->GetClassHandleForValueClass());
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);
6995 var_types getBaseTypeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd)
6997 return getBaseTypeAndSizeOfSIMDType(typeHnd, nullptr);
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,
7007 var_types* baseType,
7008 unsigned* sizeBytes);
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);
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);
7017 // Creates a GT_SIMD tree for Select operation
7018 GenTreePtr impSIMDSelect(CORINFO_CLASS_HANDLE typeHnd,
7020 unsigned simdVectorSize,
7025 // Creates a GT_SIMD tree for Min/Max operation
7026 GenTreePtr impSIMDMinMax(SIMDIntrinsicID intrinsicId,
7027 CORINFO_CLASS_HANDLE typeHnd,
7029 unsigned simdVectorSize,
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,
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,
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,
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,
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)
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);
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,
7085 GenTreePtr getOp1ForConstructor(OPCODE opcode, GenTreePtr newobjThis, CORINFO_CLASS_HANDLE clsHnd);
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)
7092 unsigned sizeBytes = 0;
7093 var_types baseType = getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7094 return (baseType == TYP_FLOAT) && (sizeBytes < getSIMDVectorRegisterByteLength());
7097 bool isSubRegisterSIMDType(GenTreeSIMD* simdNode)
7099 return (simdNode->gtSIMDSize < getSIMDVectorRegisterByteLength());
7102 // Get the type for the hardware SIMD vector.
7103 // This is the maximum SIMD type supported for this target.
7104 var_types getSIMDVectorType()
7106 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7113 assert(canUseSSE2());
7117 assert(!"getSIMDVectorType() unimplemented on target arch");
7122 // Get the size of the SIMD type in bytes
7123 int getSIMDTypeSizeInBytes(CORINFO_CLASS_HANDLE typeHnd)
7125 unsigned sizeBytes = 0;
7126 (void)getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
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);
7133 // Get the the number of elements of basetype of SIMD vector given by its type handle
7134 int getSIMDVectorLength(CORINFO_CLASS_HANDLE typeHnd);
7136 // Get preferred alignment of SIMD type.
7137 int getSIMDTypeAlignment(var_types simdType);
7139 // Get the number of bytes in a SIMD Vector for the current compilation.
7140 unsigned getSIMDVectorRegisterByteLength()
7142 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7145 return YMM_REGSIZE_BYTES;
7149 assert(canUseSSE2());
7150 return XMM_REGSIZE_BYTES;
7153 assert(!"getSIMDVectorRegisterByteLength() unimplemented on target arch");
7158 // The minimum and maximum possible number of bytes in a SIMD vector.
7159 unsigned int maxSIMDStructBytes()
7161 return getSIMDVectorRegisterByteLength();
7163 unsigned int minSIMDStructBytes()
7165 return emitTypeSize(TYP_SIMD8);
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
7175 // Returns the codegen type for a given SIMD size.
7176 var_types getSIMDTypeForSize(unsigned size)
7178 var_types simdType = TYP_UNDEF;
7181 simdType = TYP_SIMD8;
7183 else if (size == 12)
7185 simdType = TYP_SIMD12;
7187 else if (size == 16)
7189 simdType = TYP_SIMD16;
7191 #ifdef FEATURE_AVX_SUPPORT
7192 else if (size == 32)
7194 simdType = TYP_SIMD32;
7196 #endif // FEATURE_AVX_SUPPORT
7199 noway_assert(!"Unexpected size for SIMD type");
7204 unsigned getSIMDInitTempVarNum()
7206 if (lvaSIMDInitTempVarNum == BAD_VAR_NUM)
7208 lvaSIMDInitTempVarNum = lvaGrabTempWithImplicitUse(false DEBUGARG("SIMDInitTempVar"));
7209 lvaTable[lvaSIMDInitTempVarNum].lvType = getSIMDVectorType();
7211 return lvaSIMDInitTempVarNum;
7214 #endif // FEATURE_SIMD
7217 //------------------------------------------------------------------------
7218 // largestEnregisterableStruct: The size in bytes of the largest struct that can be enregistered.
7220 // Notes: It is not guaranteed that the struct of this size or smaller WILL be a
7221 // candidate for enregistration.
7223 unsigned largestEnregisterableStructSize()
7226 unsigned vectorRegSize = getSIMDVectorRegisterByteLength();
7227 if (vectorRegSize > TARGET_POINTER_SIZE)
7229 return vectorRegSize;
7232 #endif // FEATURE_SIMD
7234 return TARGET_POINTER_SIZE;
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.
7243 // Is this var is of type simd struct?
7244 bool lclVarIsSIMDType(unsigned varNum)
7246 LclVarDsc* varDsc = lvaTable + varNum;
7247 return varDsc->lvIsSIMDType();
7250 // Is this Local node a SIMD local?
7251 bool lclVarIsSIMDType(GenTreeLclVarCommon* lclVarTree)
7253 return lclVarIsSIMDType(lclVarTree->gtLclNum);
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)
7260 #if defined(FEATURE_SIMD) && ALIGN_SIMD_TYPES
7261 if (lclVarIsSIMDType(varNum) && lvaTable[varNum].lvType != TYP_BYREF)
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);
7271 #endif // FEATURE_SIMD
7276 // Whether SSE2 is available
7277 bool canUseSSE2() const
7279 #ifdef _TARGET_XARCH_
7280 return opts.compCanUseSSE2;
7286 bool canUseAVX() const
7288 #ifdef FEATURE_AVX_SUPPORT
7289 return opts.compCanUseAVX;
7296 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7297 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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
7305 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7306 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7310 Compiler* InlineeCompiler; // The Compiler instance for the inlinee
7312 InlineResult* compInlineResult; // The result of importing the inlinee method.
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
7324 // NOTE: These values are only reliable after
7325 // the importing is completely finished.
7327 ExpandArrayStack<GenTreePtr>* compQMarks; // The set of QMark nodes created in the current compilation, so
7328 // we can iterate over these efficiently.
7330 #if CPU_USES_BLOCK_MOVE
7331 bool compBlkOpUsed; // Does the method do a COPYBLK or INITBLK
7335 // State information - which phases have completed?
7336 // These are kept together for easy discoverability
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`
7346 bool fgLocalVarLivenessDone; // Note that this one is used outside of debug.
7347 bool fgLocalVarLivenessChanged;
7349 bool compStackProbePrologDone;
7351 #ifndef LEGACY_BACKEND
7353 #endif // !LEGACY_BACKEND
7354 bool compRationalIRForm;
7356 bool compUsesThrowHelper; // There is a call to a THOROW_HELPER for the compiled method.
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
7366 return compNeedsGSSecurityCookie;
7368 void setNeedsGSSecurityCookie()
7370 compNeedsGSSecurityCookie = true;
7373 FrameLayoutState lvaDoneFrameLayout; // The highest frame layout state that we've completed. During
7374 // frame layout calculations, this is the level we are currently
7377 //---------------------------- JITing options -----------------------------
7390 CORJIT_FLAGS* jitFlags; // all flags passed from the EE
7391 unsigned eeFlags; // CorJitFlag flags passed from the EE
7392 unsigned compFlags; // method attributes
7394 codeOptimize compCodeOpt; // what type of code optimizations
7398 #ifdef _TARGET_XARCH_
7399 bool compCanUseSSE2; // Allow CodeGen to use "movq XMM" instructions
7401 #ifdef FEATURE_AVX_SUPPORT
7402 bool compCanUseAVX; // Allow CodeGen to use AVX 256-bit vectors for SIMD operations
7406 // optimize maximally and/or favor speed over size?
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
7414 // Maximun number of locals before turning off the inlining
7415 #define MAX_LV_NUM_COUNT_FOR_INLINING 512
7418 unsigned instrCount;
7419 unsigned lvRefCount;
7420 bool compMinOptsIsSet;
7422 bool compMinOptsIsUsed;
7424 inline bool MinOpts()
7426 assert(compMinOptsIsSet);
7427 compMinOptsIsUsed = true;
7430 inline bool IsMinOptsSet()
7432 return compMinOptsIsSet;
7435 inline bool MinOpts()
7439 inline bool IsMinOptsSet()
7441 return compMinOptsIsSet;
7444 inline void SetMinOpts(bool val)
7446 assert(!compMinOptsIsUsed);
7447 assert(!compMinOptsIsSet || (compMinOpts == val));
7449 compMinOptsIsSet = true;
7452 // true if the CLFLG_* for an optimization is set.
7453 inline bool OptEnabled(unsigned optFlag)
7455 return !!(compFlags & optFlag);
7458 #ifdef FEATURE_READYTORUN_COMPILER
7459 inline bool IsReadyToRun()
7461 return (eeFlags & CORJIT_FLG_READYTORUN) != 0;
7464 inline bool IsReadyToRun()
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()
7474 #if COR_JIT_EE_VERSION > 460
7475 return (jitFlags->corJitFlags2 & CORJIT_FLG2_USE_PINVOKE_HELPERS) != 0;
7481 // true if we should use insert the REVERSE_PINVOKE_{ENTER,EXIT} helpers in the method
7483 inline bool IsReversePInvoke()
7485 #if COR_JIT_EE_VERSION > 460
7486 return (jitFlags->corJitFlags2 & CORJIT_FLG2_REVERSE_PINVOKE) != 0;
7492 // true if we must generate code compatible with JIT32 quirks
7493 inline bool IsJit32Compat()
7495 #if defined(_TARGET_X86_) && COR_JIT_EE_VERSION > 460
7496 return (jitFlags->corJitFlags2 & CORJIT_FLG2_DESKTOP_QUIRKS) != 0;
7502 // true if we must generate code compatible with Jit64 quirks
7503 inline bool IsJit64Compat()
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)
7514 #ifdef DEBUGGING_SUPPORT
7515 bool compScopeInfo; // Generate the LocalVar info ?
7516 bool compDbgCode; // Generate debugger-friendly code?
7517 bool compDbgInfo; // Gather debugging info?
7520 static const bool compDbgCode;
7523 #ifdef PROFILING_SUPPORTED
7524 bool compNoPInvokeInlineCB;
7526 static const bool compNoPInvokeInlineCB;
7529 bool compMustInlinePInvokeCalli; // Unmanaged CALLI in IL stubs must be inlined
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
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.
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).
7548 // 3. When opts.compDbgEnC is true. (See also Compiler::compCompile).
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.)
7559 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7560 bool compEnablePCRelAddr; // Whether absolute addr be encoded as PC-rel offset by RyuJIT where possible
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
7574 bool compProcedureSplitting; // Separate cold code from hot code
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
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
7602 bool doLateDisasm; // Run the late disassembler
7603 #endif // LATE_DISASM
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;
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.
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;
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;
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;
7632 static const bool compUseSoftFP = true;
7633 #else // !ARM_SOFTFP
7634 static const bool compUseSoftFP = false;
7637 GCPollType compGCPollType;
7641 static bool s_pAltJitExcludeAssembliesListInitialized;
7642 static AssemblyNamesList2* s_pAltJitExcludeAssembliesList;
7647 static bool s_dspMemStats; // Display per-phase memory statistics for every function
7649 template <typename T>
7652 return (p == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : p);
7655 template <typename T>
7658 return (o == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : o);
7661 static int dspTreeID(GenTree* tree)
7663 return tree->gtTreeID;
7665 static void printTreeID(GenTree* tree)
7667 if (tree == nullptr)
7673 printf("[%06d]", dspTreeID(tree));
7680 #define STRESS_MODES \
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 */ \
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) \
7702 STRESS_MODE(GENERIC_VARN) STRESS_MODE(COUNT_VARN) \
7704 /* "Check" stress areas that can be exhaustively used if we */ \
7705 /* dont care about performance at all */ \
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) \
7711 STRESS_MODE(GENERIC_CHECK) STRESS_MODE(COUNT) \
7715 #define STRESS_MODE(mode) STRESS_##mode,
7722 static const LPCWSTR s_compStressModeNames[STRESS_COUNT + 1];
7723 BYTE compActiveStressModes[STRESS_COUNT];
7726 #define MAX_STRESS_WEIGHT 100
7728 bool compStressCompile(compStressArea stressArea, unsigned weightPercentage);
7732 bool compInlineStress()
7734 return compStressCompile(STRESS_LEGACY_INLINE, 50);
7737 bool compRandomInlineStress()
7739 return compStressCompile(STRESS_RANDOM_INLINE, 50);
7744 bool compTailCallStress()
7747 return (JitConfig.TailcallStress() != 0 || compStressCompile(STRESS_TAILCALL, 5));
7753 codeOptimize compCodeOpt()
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.
7763 return opts.compCodeOpt;
7765 return BLENDED_CODE;
7773 //--------------------- Info about the procedure --------------------------
7777 COMP_HANDLE compCompHnd;
7778 CORINFO_MODULE_HANDLE compScopeHnd;
7779 CORINFO_CLASS_HANDLE compClassHnd;
7780 CORINFO_METHOD_HANDLE compMethodHnd;
7781 CORINFO_METHOD_INFO* compMethodInfo;
7783 BOOL hasCircularClassConstraints;
7784 BOOL hasCircularMethodConstraints;
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)
7792 #if defined(DEBUG) || defined(INLINE_DATA)
7793 // Method hash is logcally const, but computed
7795 mutable unsigned compMethodHashPrivate;
7796 unsigned compMethodHash() const;
7797 #endif // defined(DEBUG) || defined(INLINE_DATA)
7799 #ifdef PSEUDORANDOM_NOP_INSERTION
7800 // things for pseudorandom nop insertion
7801 unsigned compChecksum;
7805 // The following holds the FLG_xxxx flags for the method we're compiling.
7808 // The following holds the class attributes for the method we're compiling.
7809 unsigned compClassAttr;
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).
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.
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
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).
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.
7852 #if defined(DEBUGGING_SUPPORT) || defined(DEBUG)
7854 /* The following holds IL scope information about local variables.
7857 unsigned compVarScopesCount;
7858 VarScopeDsc* compVarScopes;
7860 /* The following holds information about instr offsets for
7861 * which we need to report IP-mappings
7864 IL_OFFSET* compStmtOffsets; // sorted
7865 unsigned compStmtOffsetsCount;
7866 ICorDebugInfo::BoundaryTypes compStmtOffsetsImplicit;
7868 #endif // DEBUGGING_SUPPORT || DEBUG
7870 #define CPU_X86 0x0100 // The generic X86 CPU
7871 #define CPU_X86_PENTIUM_4 0x0110
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
7877 #define CPU_ARM 0x0300 // The generic ARM CPU
7879 unsigned genCPU; // What CPU are we running on
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()
7890 return (info.compRetType != TYP_VOID) && !varTypeIsStruct(info.compRetNativeType);
7893 // Returns true if the method being compiled returns RetBuf addr as its return value
7894 bool compMethodReturnsRetBufAddr()
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.
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.
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.
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;
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_
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()
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
7937 #endif // FEATURE_MULTIREG_RET
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
7946 // Returns true if the method being compiled returns a value
7947 bool compMethodHasRetVal()
7949 return compMethodReturnsNativeScalarType() || compMethodReturnsRetBufAddr() ||
7950 compMethodReturnsMultiRegRetType();
7955 void compDispLocalVars();
7957 #endif // DEBUGGING_SUPPORT || DEBUG
7959 //-------------------------- Global Compiler Data ------------------------------------
7962 static unsigned s_compMethodsCount; // to produce unique label names
7963 unsigned compGenTreeID;
7966 BasicBlock* compCurBB; // the current basic block in process
7967 GenTreePtr compCurStmt; // the current statement in process
7969 unsigned compCurStmtNum; // to give all statements an increasing StmtNum when printing dumps
7972 // The following is used to create the 'method JIT info' block.
7973 size_t compInfoBlkSize;
7974 BYTE* compInfoBlkAddr;
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
7980 #if defined(_TARGET_X86_)
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
7987 #endif // !_TARGET_X86_
7989 Phases previousCompletedPhase; // the most recently completed phase
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.
7997 unsigned compLclFrameSize; // secObject+lclBlk+locals+temps
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;
8004 #if defined(_TARGET_XARCH_) && !FEATURE_STACK_FP_X87
8005 // Mask of callee saved float regs on stack.
8006 regMaskTP compCalleeFPRegsSavedMask;
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;
8016 unsigned compArgSize; // total size of arguments in bytes (including register args (lvIsRegArg))
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
8022 //-------------------------------------------------------------------------
8024 static void compStartup(); // One-time initialization
8025 static void compShutdown(); // One-time finalization
8027 void compInit(ArenaAllocator* pAlloc, InlineInfo* inlineInfo);
8030 static void compDisplayStaticSizes(FILE* fout);
8032 //------------ Some utility functions --------------
8034 void* compGetHelperFtn(CorInfoHelpFunc ftnNum, /* IN */
8035 void** ppIndirection); /* OUT */
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);
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();
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);
8066 ArenaAllocator* compGetAllocator();
8068 #if MEASURE_MEM_ALLOC
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;
8078 static const char* s_CompMemKindNames[]; // Names of the kinds.
8080 MemStats() : allocCnt(0), allocSz(0), allocSzMax(0), nraTotalSizeAlloc(0), nraTotalSizeUsed(0)
8082 for (int i = 0; i < CMK_Count; i++)
8084 allocSzByKind[i] = 0;
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)
8094 for (int i = 0; i < CMK_Count; i++)
8096 allocSzByKind[i] = ms.allocSzByKind[i];
8100 // Until we have ubiquitous constructors.
8103 this->MemStats::MemStats();
8106 void AddAlloc(size_t sz, CompMemKind cmk)
8110 if (sz > allocSzMax)
8114 allocSzByKind[cmk] += sz;
8117 void Print(FILE* f); // Print these stats to f.
8118 void PrintByKind(FILE* f); // Do just the by-kind histogram part.
8120 MemStats genMemStats;
8122 struct AggregateMemStats : public MemStats
8126 AggregateMemStats() : MemStats(), nMethods(0)
8130 void Add(const MemStats& ms)
8133 allocCnt += ms.allocCnt;
8134 allocSz += ms.allocSz;
8135 allocSzMax = max(allocSzMax, ms.allocSzMax);
8136 for (int i = 0; i < CMK_Count; i++)
8138 allocSzByKind[i] += ms.allocSzByKind[i];
8140 nraTotalSizeAlloc += ms.nraTotalSizeAlloc;
8141 nraTotalSizeUsed += ms.nraTotalSizeUsed;
8144 void Print(FILE* f); // Print these stats to jitstdout.
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.
8151 #endif // MEASURE_MEM_ALLOC
8153 #if LOOP_HOIST_STATS
8154 unsigned m_loopsConsidered;
8155 bool m_curLoopHasHoistedExpression;
8156 unsigned m_loopsWithHoistedExpressions;
8157 unsigned m_totalHoistedExpressions;
8159 void AddLoopHoistStats();
8160 void PrintPerMethodLoopHoistStats();
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;
8167 static void PrintAggregateLoopHoistStats(FILE* f);
8168 #endif // LOOP_HOIST_STATS
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*);
8177 bool compIsForImportOnly();
8178 bool compIsForInlining();
8179 bool compDonotInline();
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);
8192 //-------------------------------------------------------------------------
8194 #ifdef DEBUGGING_SUPPORT
8195 typedef ListNode<VarScopeDsc*> VarScopeListNode;
8197 struct VarScopeMapInfo
8199 VarScopeListNode* head;
8200 VarScopeListNode* tail;
8201 static VarScopeMapInfo* Create(VarScopeListNode* node, IAllocator* alloc)
8203 VarScopeMapInfo* info = new (alloc) VarScopeMapInfo;
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;
8213 typedef SimplerHashTable<unsigned, SmallPrimitiveKeyFuncs<unsigned>, VarScopeMapInfo*, JitSimplerHashBehavior>
8214 VarNumToScopeDscMap;
8216 // Map to keep variables' scope indexed by varNum containing it's scope dscs at the index.
8217 VarNumToScopeDscMap* compVarScopeMap;
8219 VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned lifeBeg, unsigned lifeEnd);
8221 VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned offs);
8223 VarScopeDsc* compFindLocalVarLinear(unsigned varNum, unsigned offs);
8225 void compInitVarScopeMap();
8227 VarScopeDsc** compEnterScopeList; // List has the offsets where variables
8228 // enter scope, sorted by instr offset
8229 unsigned compNextEnterScope;
8231 VarScopeDsc** compExitScopeList; // List has the offsets where variables
8232 // go out of scope, sorted by instr offset
8233 unsigned compNextExitScope;
8235 void compInitScopeLists();
8237 void compResetScopeLists();
8239 VarScopeDsc* compGetNextEnterScope(unsigned offs, bool scan = false);
8241 VarScopeDsc* compGetNextExitScope(unsigned offs, bool scan = false);
8243 void compProcessScopesUntil(unsigned offset,
8245 void (Compiler::*enterScopeFn)(VARSET_TP* inScope, VarScopeDsc*),
8246 void (Compiler::*exitScopeFn)(VARSET_TP* inScope, VarScopeDsc*));
8249 void compDispScopeLists();
8252 #endif // DEBUGGING_SUPPORT
8254 bool compIsProfilerHookNeeded();
8256 //-------------------------------------------------------------------------
8257 /* Statistical Data Gathering */
8259 void compJitStats(); // call this function and enable
8260 // various ifdef's below for statistical data
8263 void compCallArgStats();
8264 static void compDispCallArgStats(FILE* fout);
8267 //-------------------------------------------------------------------------
8274 ArenaAllocator* compAllocator;
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;
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.
8286 IAllocator* compAsIAllocatorDebugOnly; // An allocator that uses the CMK_DebugOnly tracker.
8288 #endif // MEASURE_MEM_ALLOC
8290 void compFunctionTraceStart();
8291 void compFunctionTraceEnd(void* methodCodePtr, ULONG methodCodeSize, bool isNYI);
8294 size_t compMaxUncheckedOffsetForNullObject;
8296 void compInitOptions(CORJIT_FLAGS* compileFlags);
8298 void compSetProcessor();
8299 void compInitDebuggingInfo();
8300 void compSetOptimizationLevel();
8301 #ifdef _TARGET_ARMARCH_
8302 bool compRsvdRegCheck(FrameLayoutState curState);
8304 void compCompile(void** methodCodePtr, ULONG* methodCodeSize, CORJIT_FLAGS* compileFlags);
8306 // Data required for generating profiler Enter/Leave/TailCall hooks
8307 CLANG_FORMAT_COMMENT_ANCHOR;
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
8314 #ifdef _TARGET_AMD64_
8315 bool compQuirkForPPP(); // Check if this method should be Quirked for the PPP issue
8318 // Assumes called as part of process shutdown; does any compiler-specific work associated with that.
8319 static void ProcessShutdownWork(ICorStaticInfo* statInfo);
8321 IAllocator* getAllocator()
8323 return compAsIAllocator;
8326 #if MEASURE_MEM_ALLOC
8327 IAllocator* getAllocatorBitset()
8329 return compAsIAllocatorBitset;
8331 IAllocator* getAllocatorGC()
8333 return compAsIAllocatorGC;
8335 IAllocator* getAllocatorLoopHoist()
8337 return compAsIAllocatorLoopHoist;
8339 #else // !MEASURE_MEM_ALLOC
8340 IAllocator* getAllocatorBitset()
8342 return compAsIAllocator;
8344 IAllocator* getAllocatorGC()
8346 return compAsIAllocator;
8348 IAllocator* getAllocatorLoopHoist()
8350 return compAsIAllocator;
8352 #endif // !MEASURE_MEM_ALLOC
8355 IAllocator* getAllocatorDebugOnly()
8357 #if MEASURE_MEM_ALLOC
8358 return compAsIAllocatorDebugOnly;
8359 #else // !MEASURE_MEM_ALLOC
8360 return compAsIAllocator;
8361 #endif // !MEASURE_MEM_ALLOC
8366 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8367 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8371 XX Checks for type compatibility and merges types XX
8373 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8374 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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;
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;
8387 // Set to TRUE if runtime callout is needed for this method
8388 BOOL tiRuntimeCalloutNeeded;
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;
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
8405 BOOL tiMergeCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
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;
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;
8416 // Set pDest from the primitive value type.
8417 // Eg. System.Int32 -> ELEMENT_TYPE_I4
8419 BOOL tiFromPrimitiveValueClass(typeInfo* pDest, const typeInfo* pVC) const;
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.
8427 short compRegSetCheckLevel;
8431 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8432 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8434 XX IL verification stuff XX
8437 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8438 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8442 // The following is used to track liveness of local variables, initialization
8443 // of valueclass constructors, and type safe use of IL instructions.
8445 // dynamic state info needed for verification
8446 EntryState verCurrentState;
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;
8454 void verInitBBEntryState(BasicBlock* block, EntryState* currentState);
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);
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);
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);
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);
8479 // generic type variables range over types that satisfy IsBoxable
8480 BOOL verIsBoxable(const typeInfo& ti);
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.
8494 bool verIsBoxedValueType(typeInfo ti);
8496 void verVerifyCall(OPCODE opcode,
8497 CORINFO_RESOLVED_TOKEN* pResolvedToken,
8498 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
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));
8505 BOOL verCheckDelegateCreation(const BYTE* delegateCreateStart, const BYTE* codeAddr, mdMemberRef& targetMemberRef);
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,
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);
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);
8527 regNumber raRegForVarStackFP(unsigned varTrackedIndex);
8528 void raAddPayloadStackFP(VARSET_VALARG_TP mask, unsigned weight);
8530 // returns true if enregistering v1 would save more mem accesses than v2
8531 bool raVarIsGreaterValueStackFP(LclVarDsc* lv1, LclVarDsc* lv2);
8534 void raDumpHeightsStackFP();
8535 void raDumpVariableRegIntfFloat();
8538 #if FEATURE_STACK_FP_X87
8540 // Currently, we use FP transition blocks in only 2 situations:
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.
8549 // However, transition blocks have 2 problems
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.
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.
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:
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.
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;
8575 VARSET_TP raMaskDontEnregFloat; // mask for additional restrictions
8577 VARSET_TP raLclRegIntfFloat[REG_FPCOUNT];
8579 unsigned raCntStkStackFP;
8580 unsigned raCntWtdStkDblStackFP;
8581 unsigned raCntStkParamDblStackFP;
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];
8588 // Useful for debugging
8589 unsigned raHeightsNonWeightedStackFP[lclMAX_TRACKED][FP_VIRTUALREGISTERS + 1];
8591 #endif // FEATURE_STACK_FP_X87
8594 // One line log function. Default level is 0. Increasing it gives you
8595 // more log information
8597 // levels are currently unused: #define JITDUMP(level,...) ();
8598 void JitLogEE(unsigned level, const char* fmt, ...);
8600 bool compDebugBreak;
8602 bool compJitHaltMethod();
8607 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8608 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8610 XX GS Security checks for unsafe buffers XX
8612 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8613 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8616 struct ShadowParamVarInfo
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
8621 static bool mayNeedShadowCopy(LclVarDsc* varDsc)
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.
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
8635 // a) LSRA marks it as DoNotEnregister (see LinearScan::identifyCandidates())
8636 // b) LSRA spills it
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.
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;
8657 printf("assignGroup [%p]; shadowCopy: [%d];\n", assignGroup, shadowCopy);
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
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
8671 static fgWalkPreFn gsMarkPtrsAndAssignGroups; // Shadow param analysis tree-walk
8672 static fgWalkPreFn gsReplaceShadowParams; // Shadow param replacement tree-walk
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.
8677 #define DEFAULT_MAX_INLINE_DEPTH 20 // Methods at more than this level deep will not be inlined
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.
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.
8687 inline void EndPhase(Phases phase); // Indicate the end of the given phase.
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)
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();
8705 #ifdef FEATURE_CLRSQM
8706 // Does anything SQM related necessary at process shutdown time.
8707 static void ProcessShutdownSQMWork(ICorStaticInfo* statInfo);
8708 #endif // FEATURE_CLRSQM
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
8717 Compiler* prevCompiler; // Previous compiler on stack for TLS Compiler* linked list for reentrant compilers.
8719 // Is the compilation in a full trust context?
8720 bool compIsFullTrust();
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);
8729 // Telemetry instance to use per method compilation.
8730 JitTelemetry compJitTelemetry;
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
8741 NodeToTestDataMap* m_nodeTestData;
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.
8748 NodeToTestDataMap* GetNodeTestData()
8750 Compiler* compRoot = impInlineRoot();
8751 if (compRoot->m_nodeTestData == nullptr)
8753 compRoot->m_nodeTestData = new (getAllocatorDebugOnly()) NodeToTestDataMap(getAllocatorDebugOnly());
8755 return compRoot->m_nodeTestData;
8758 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, int, JitSimplerHashBehavior> NodeToIntMap;
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();
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);
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);
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.
8778 // The "FieldSeqStore", for canonicalizing field sequences. See the definition of FieldSeqStore for
8780 FieldSeqStore* m_fieldSeqStore;
8782 FieldSeqStore* GetFieldSeqStore()
8784 Compiler* compRoot = impInlineRoot();
8785 if (compRoot->m_fieldSeqStore == nullptr)
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);
8791 return compRoot->m_fieldSeqStore;
8794 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, FieldSeqNode*, JitSimplerHashBehavior> NodeToFieldSeqMap;
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;
8802 NodeToFieldSeqMap* GetZeroOffsetFieldMap()
8804 // Don't need to worry about inlining here
8805 if (m_zeroOffsetFieldMap == nullptr)
8807 // Create a CompAllocator that labels sub-structure with CMK_ZeroOffsetFieldMap, and use that for
8809 IAllocator* ialloc = new (this, CMK_ZeroOffsetFieldMap) CompAllocator(this, CMK_ZeroOffsetFieldMap);
8810 m_zeroOffsetFieldMap = new (ialloc) NodeToFieldSeqMap(ialloc);
8812 return m_zeroOffsetFieldMap;
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.
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);
8827 typedef SimplerHashTable<const GenTree*, PtrKeyFuncs<GenTree>, ArrayInfo, JitSimplerHashBehavior>
8829 NodeToArrayInfoMap* m_arrayInfoMap;
8831 NodeToArrayInfoMap* GetArrayInfoMap()
8833 Compiler* compRoot = impInlineRoot();
8834 if (compRoot->m_arrayInfoMap == nullptr)
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);
8840 return compRoot->m_arrayInfoMap;
8843 NodeToUnsignedMap* m_heapSsaMap;
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()
8850 Compiler* compRoot = impInlineRoot();
8851 if (compRoot->m_heapSsaMap == nullptr)
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);
8857 return compRoot->m_heapSsaMap;
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()
8864 if (m_refAnyClass == nullptr)
8866 m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
8868 return info.compCompHnd->getFieldInClass(m_refAnyClass, 0);
8870 CORINFO_FIELD_HANDLE GetRefanyTypeField()
8872 if (m_refAnyClass == nullptr)
8874 m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
8876 return info.compCompHnd->getFieldInClass(m_refAnyClass, 1);
8880 static BitSetSupport::BitSetOpCounter m_varsetOpCounter;
8882 #if ALLVARSET_COUNTOPS
8883 static BitSetSupport::BitSetOpCounter m_allvarsetOpCounter;
8886 static HelperCallProperties s_helperCallProperties;
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,
8892 static void GetStructTypeOffset(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
8895 unsigned __int8* offset0,
8896 unsigned __int8* offset1);
8897 void fgMorphSystemVStructArgs(GenTreeCall* call, bool hasStructArgument);
8898 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
8900 void fgMorphMultiregStructArgs(GenTreeCall* call);
8901 GenTreePtr fgMorphMultiregStructArg(GenTreePtr arg, fgArgTabEntryPtr fgEntryPtr);
8903 }; // end of class Compiler
8905 // Inline methods of CompAllocator.
8906 void* CompAllocator::Alloc(size_t sz)
8908 #if MEASURE_MEM_ALLOC
8909 return m_comp->compGetMem(sz, m_cmk);
8911 return m_comp->compGetMem(sz);
8915 void* CompAllocator::ArrayAlloc(size_t elems, size_t elemSize)
8917 #if MEASURE_MEM_ALLOC
8918 return m_comp->compGetMemArray(elems, elemSize, m_cmk);
8920 return m_comp->compGetMemArray(elems, elemSize);
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.
8931 #if FEATURE_MULTIREG_ARGS
8932 _lvOtherArgReg(REG_STK)
8934 #endif // FEATURE_MULTIREG_ARGS
8936 lvRefBlks(BlockSetOps::UninitVal())
8938 #endif // ASSERTION_PROP
8939 lvPerSsaData(comp->getAllocator())
8944 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8945 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8947 XX Miscellaneous Compiler stuff XX
8949 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8950 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8953 // Values used to mark the types a stack slot is used for
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
8964 // const unsigned TYPE_REF_ADDR_TAKEN = 0x80; // slots address was taken
8966 /*****************************************************************************
8968 * Variables to keep track of total code amounts.
8973 extern size_t grossVMsize;
8974 extern size_t grossNCsize;
8975 extern size_t totalNCsize;
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;
8984 #endif // DISPLAY_SIZES
8986 /*****************************************************************************
8988 * Variables to keep track of basic block counts (more data on 1 BB methods)
8991 #if COUNT_BASIC_BLOCKS
8992 extern Histogram bbCntTable;
8993 extern Histogram bbOneBBSizeTable;
8996 /*****************************************************************************
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
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 <
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
9023 #endif // COUNT_LOOPS
9025 /*****************************************************************************
9026 * variables to keep track of how many iterations we go in a dataflow pass
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
9034 #endif // DATAFLOW_ITER
9036 #if MEASURE_BLOCK_SIZE
9037 extern size_t genFlowNodeSize;
9038 extern size_t genFlowNodeCnt;
9039 #endif // MEASURE_BLOCK_SIZE
9041 #if MEASURE_NODE_SIZE
9042 struct NodeSizeStats
9047 genTreeNodeSize = 0;
9048 genTreeNodeActualSize = 0;
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.
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
9064 /*****************************************************************************
9065 * Count fatal errors (including noway_asserts).
9069 extern unsigned fatal_badCode;
9070 extern unsigned fatal_noWay;
9071 extern unsigned fatal_NOMEM;
9072 extern unsigned fatal_noWayAssertBody;
9074 extern unsigned fatal_noWayAssertBodyArgs;
9076 extern unsigned fatal_NYI;
9077 #endif // MEASURE_FATAL
9079 /*****************************************************************************
9083 #ifdef _TARGET_XARCH_
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;
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;
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;
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;
9125 #ifdef _TARGET_ARM64_
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;
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;
9146 /*****************************************************************************/
9148 extern const BYTE genTypeSizes[];
9149 extern const BYTE genTypeAlignments[];
9150 extern const BYTE genTypeStSzs[];
9151 extern const BYTE genActualTypes[];
9153 /*****************************************************************************/
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`).
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)
9164 /*****************************************************************************/
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)
9170 /*****************************************************************************/
9172 extern BasicBlock dummyBB;
9174 /*****************************************************************************/
9175 /*****************************************************************************/
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
9182 #define foreach_treenode_execution_order(__node, __stmt) \
9183 for ((__node) = (__stmt)->gtStmt.gtStmtList; (__node); (__node) = (__node)->gtNext)
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.
9189 #define foreach_block(__compiler, __block) \
9190 for ((__block) = (__compiler)->fgFirstBB; (__block); (__block) = (__block)->bbNext)
9192 /*****************************************************************************/
9193 /*****************************************************************************/
9197 void dumpConvertedVarSet(Compiler* comp, VARSET_VALARG_TP vars);
9199 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9200 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9202 XX Debugging helpers XX
9204 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9205 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
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.
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);
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);
9247 void dBlock(BasicBlock* block);
9250 void dTree(GenTree* tree);
9253 void dVar(unsigned lclNum);
9254 void dVarDsc(LclVarDsc* varDsc);
9257 void dBlockPreds(BasicBlock* block);
9261 void dCVarSet(VARSET_VALARG_TP vars);
9263 void dVarSet(VARSET_VALARG_TP vars);
9264 void dRegMask(regMaskTP mask);
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);
9284 GenTree* dFindTree(GenTree* tree, unsigned id);
9285 GenTree* dFindTree(unsigned id);
9286 GenTreeStmt* dFindStmt(unsigned id);
9287 BasicBlock* dFindBlock(unsigned bbNum);
9291 #include "compiler.hpp" // All the shared inline functions
9293 /*****************************************************************************/
9294 #endif //_COMPILER_H_
9295 /*****************************************************************************/