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 /*****************************************************************************/
29 #include "jithashtable.h"
38 #include "cycletimer.h"
40 #include "arraystack.h"
42 #include "jitexpandarray.h"
43 #include "tinyarray.h"
46 #include "jittelemetry.h"
47 #include "namedintrinsiclist.h"
52 #include "codegeninterface.h"
54 #include "jitgcinfo.h"
56 #if DUMP_GC_TABLES && defined(JIT32_GCENCODER)
62 #include "hwintrinsic.h"
65 // This is only used locally in the JIT to indicate that
66 // a verification block should be inserted
67 #define SEH_VERIFICATION_EXCEPTION 0xe0564552 // VER
69 /*****************************************************************************
70 * Forward declarations
73 struct InfoHdr; // defined in GCInfo.h
74 struct escapeMapping_t; // defined in flowgraph.cpp
75 class emitter; // defined in emit.h
76 struct ShadowParamVarInfo; // defined in GSChecks.cpp
77 struct InitVarDscInfo; // defined in register_arg_convention.h
78 class FgStack; // defined in flowgraph.cpp
80 class CSE_DataFlow; // defined in OptCSE.cpp
86 class Lowering; // defined in lower.h
88 // The following are defined in this file, Compiler.h
92 /*****************************************************************************
98 /*****************************************************************************/
101 // Declare global operator new overloads that use the compiler's arena allocator
104 // I wanted to make the second argument optional, with default = CMK_Unknown, but that
105 // caused these to be ambiguous with the global placement new operators.
106 void* __cdecl operator new(size_t n, Compiler* context, CompMemKind cmk);
107 void* __cdecl operator new[](size_t n, Compiler* context, CompMemKind cmk);
108 void* __cdecl operator new(size_t n, void* p, const jitstd::placement_t& syntax_difference);
110 // Requires the definitions of "operator new" so including "LoopCloning.h" after the definitions.
111 #include "loopcloning.h"
113 /*****************************************************************************/
115 /* This is included here and not earlier as it needs the definition of "CSE"
116 * which is defined in the section above */
118 /*****************************************************************************/
120 unsigned genLog2(unsigned value);
121 unsigned genLog2(unsigned __int64 value);
123 var_types genActualType(var_types type);
124 var_types genUnsignedType(var_types type);
125 var_types genSignedType(var_types type);
127 unsigned ReinterpretHexAsDecimal(unsigned);
129 /*****************************************************************************/
131 const unsigned FLG_CCTOR = (CORINFO_FLG_CONSTRUCTOR | CORINFO_FLG_STATIC);
134 const int BAD_STK_OFFS = 0xBAADF00D; // for LclVarDsc::lvStkOffs
137 // The following holds the Local var info (scope information)
138 typedef const char* VarName; // Actual ASCII string
141 IL_OFFSET vsdLifeBeg; // instr offset of beg of life
142 IL_OFFSET vsdLifeEnd; // instr offset of end of life
143 unsigned vsdVarNum; // (remapped) LclVarDsc number
146 VarName vsdName; // name of the var
149 unsigned vsdLVnum; // 'which' in eeGetLVinfo().
150 // Also, it is the index of this entry in the info.compVarScopes array,
151 // which is useful since the array is also accessed via the
152 // compEnterScopeList and compExitScopeList sorted arrays.
155 // This is the location of a SSA definition.
161 DefLoc() : m_blk(nullptr), m_tree(nullptr)
165 DefLoc(BasicBlock* block, GenTree* tree) : m_blk(block), m_tree(tree)
170 // This class stores information associated with a LclVar SSA definition.
178 LclSsaVarDsc(BasicBlock* block, GenTree* tree) : m_defLoc(block, tree)
182 ValueNumPair m_vnPair;
186 // This class stores information associated with a memory SSA definition.
190 ValueNumPair m_vnPair;
193 //------------------------------------------------------------------------
194 // SsaDefArray: A resizable array of SSA definitions.
196 // Unlike an ordinary resizable array implementation, this allows only element
197 // addition (by calling AllocSsaNum) and has special handling for RESERVED_SSA_NUM
198 // (basically it's a 1-based array). The array doesn't impose any particular
199 // requirements on the elements it stores and AllocSsaNum forwards its arguments
200 // to the array element constructor, this way the array supports both LclSsaVarDsc
201 // and SsaMemDef elements.
203 template <typename T>
207 unsigned m_arraySize;
210 static_assert_no_msg(SsaConfig::RESERVED_SSA_NUM == 0);
211 static_assert_no_msg(SsaConfig::FIRST_SSA_NUM == 1);
213 // Get the minimum valid SSA number.
214 unsigned GetMinSsaNum() const
216 return SsaConfig::FIRST_SSA_NUM;
219 // Increase (double) the size of the array.
220 void GrowArray(CompAllocator alloc)
222 unsigned oldSize = m_arraySize;
223 unsigned newSize = max(2, oldSize * 2);
225 T* newArray = alloc.allocate<T>(newSize);
227 for (unsigned i = 0; i < oldSize; i++)
229 newArray[i] = m_array[i];
233 m_arraySize = newSize;
237 // Construct an empty SsaDefArray.
238 SsaDefArray() : m_array(nullptr), m_arraySize(0), m_count(0)
242 // Reset the array (used only if the SSA form is reconstructed).
248 // Allocate a new SSA number (starting with SsaConfig::FIRST_SSA_NUM).
249 template <class... Args>
250 unsigned AllocSsaNum(CompAllocator alloc, Args&&... args)
252 if (m_count == m_arraySize)
257 unsigned ssaNum = GetMinSsaNum() + m_count;
258 m_array[m_count++] = T(jitstd::forward<Args>(args)...);
260 // Ensure that the first SSA number we allocate is SsaConfig::FIRST_SSA_NUM
261 assert((ssaNum == SsaConfig::FIRST_SSA_NUM) || (m_count > 1));
266 // Get the number of SSA definitions in the array.
267 unsigned GetCount() const
272 // Get a pointer to the SSA definition at the specified index.
273 T* GetSsaDefByIndex(unsigned index)
275 assert(index < m_count);
276 return &m_array[index];
279 // Check if the specified SSA number is valid.
280 bool IsValidSsaNum(unsigned ssaNum) const
282 return (GetMinSsaNum() <= ssaNum) && (ssaNum < (GetMinSsaNum() + m_count));
285 // Get a pointer to the SSA definition associated with the specified SSA number.
286 T* GetSsaDef(unsigned ssaNum)
288 assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
289 return GetSsaDefByIndex(ssaNum - GetMinSsaNum());
295 RCS_INVALID, // not valid to get/set ref counts
296 RCS_EARLY, // early counts for struct promotion and struct passing
297 RCS_NORMAL, // normal ref counts (from lvaMarkRefs onward)
303 // The constructor. Most things can just be zero'ed.
306 // note this only packs because var_types is a typedef of unsigned char
307 var_types lvType : 5; // TYP_INT/LONG/FLOAT/DOUBLE/REF
309 unsigned char lvIsParam : 1; // is this a parameter?
310 unsigned char lvIsRegArg : 1; // is this a register argument?
311 unsigned char lvFramePointerBased : 1; // 0 = off of REG_SPBASE (e.g., ESP), 1 = off of REG_FPBASE (e.g., EBP)
313 unsigned char lvStructGcCount : 3; // if struct, how many GC pointer (stop counting at 7). The only use of values >1
314 // is to help determine whether to use block init in the prolog.
315 unsigned char lvOnFrame : 1; // (part of) the variable lives on the frame
316 unsigned char lvRegister : 1; // assigned to live in a register? For RyuJIT backend, this is only set if the
317 // variable is in the same register for the entire function.
318 unsigned char lvTracked : 1; // is this a tracked variable?
319 bool lvTrackedNonStruct()
321 return lvTracked && lvType != TYP_STRUCT;
323 unsigned char lvPinned : 1; // is this a pinned variable?
325 unsigned char lvMustInit : 1; // must be initialized
326 unsigned char lvAddrExposed : 1; // The address of this variable is "exposed" -- passed as an argument, stored in a
327 // global location, etc.
328 // We cannot reason reliably about the value of the variable.
329 unsigned char lvDoNotEnregister : 1; // Do not enregister this variable.
330 unsigned char lvFieldAccessed : 1; // The var is a struct local, and a field of the variable is accessed. Affects
333 unsigned char lvInSsa : 1; // The variable is in SSA form (set by SsaBuilder)
336 // These further document the reasons for setting "lvDoNotEnregister". (Note that "lvAddrExposed" is one of the
338 // also, lvType == TYP_STRUCT prevents enregistration. At least one of the reasons should be true.
339 unsigned char lvVMNeedsStackAddr : 1; // The VM may have access to a stack-relative address of the variable, and
340 // read/write its value.
341 unsigned char lvLiveInOutOfHndlr : 1; // The variable was live in or out of an exception handler, and this required
342 // the variable to be
343 // in the stack (at least at those boundaries.)
344 unsigned char lvLclFieldExpr : 1; // The variable is not a struct, but was accessed like one (e.g., reading a
345 // particular byte from an int).
346 unsigned char lvLclBlockOpAddr : 1; // The variable was written to via a block operation that took its address.
347 unsigned char lvLiveAcrossUCall : 1; // The variable is live across an unmanaged call.
349 unsigned char lvIsCSE : 1; // Indicates if this LclVar is a CSE variable.
350 unsigned char lvHasLdAddrOp : 1; // has ldloca or ldarga opcode on this local.
351 unsigned char lvStackByref : 1; // This is a compiler temporary of TYP_BYREF that is known to point into our local
354 unsigned char lvHasILStoreOp : 1; // there is at least one STLOC or STARG on this local
355 unsigned char lvHasMultipleILStoreOp : 1; // there is more than one STLOC on this local
357 unsigned char lvIsTemp : 1; // Short-lifetime compiler temp (if lvIsParam is false), or implicit byref parameter
358 // (if lvIsParam is true)
360 unsigned char lvIsBoolean : 1; // set if variable is boolean
363 unsigned char lvSingleDef : 1; // variable has a single def
364 unsigned char lvDisqualify : 1; // variable is no longer OK for add copy optimization
365 unsigned char lvVolatileHint : 1; // hint for AssertionProp
368 #ifndef _TARGET_64BIT_
369 unsigned char lvStructDoubleAlign : 1; // Must we double align this struct?
370 #endif // !_TARGET_64BIT_
371 #ifdef _TARGET_64BIT_
372 unsigned char lvQuirkToLong : 1; // Quirk to allocate this LclVar as a 64-bit long
375 unsigned char lvKeepType : 1; // Don't change the type of this variable
376 unsigned char lvNoLclFldStress : 1; // Can't apply local field stress on this one
378 unsigned char lvIsPtr : 1; // Might this be used in an address computation? (used by buffer overflow security
380 unsigned char lvIsUnsafeBuffer : 1; // Does this contain an unsafe buffer requiring buffer overflow security checks?
381 unsigned char lvPromoted : 1; // True when this local is a promoted struct, a normed struct, or a "split" long on a
382 // 32-bit target. For implicit byref parameters, this gets hijacked between
383 // fgRetypeImplicitByRefArgs and fgMarkDemotedImplicitByRefArgs to indicate whether
384 // references to the arg are being rewritten as references to a promoted shadow local.
385 unsigned char lvIsStructField : 1; // Is this local var a field of a promoted struct local?
386 unsigned char lvOverlappingFields : 1; // True when we have a struct with possibly overlapping fields
387 unsigned char lvContainsHoles : 1; // True when we have a promoted struct that contains holes
388 unsigned char lvCustomLayout : 1; // True when this struct has "CustomLayout"
390 unsigned char lvIsMultiRegArg : 1; // true if this is a multireg LclVar struct used in an argument context
391 unsigned char lvIsMultiRegRet : 1; // true if this is a multireg LclVar struct assigned from a multireg call
394 unsigned char _lvIsHfa : 1; // Is this a struct variable who's class handle is an HFA type
395 unsigned char _lvIsHfaRegArg : 1; // Is this a HFA argument variable? // TODO-CLEANUP: Remove this and replace
396 // with (lvIsRegArg && lvIsHfa())
397 unsigned char _lvHfaTypeIsFloat : 1; // Is the HFA type float or double?
398 #endif // FEATURE_HFA
401 // TODO-Cleanup: See the note on lvSize() - this flag is only in use by asserts that are checking for struct
402 // types, and is needed because of cases where TYP_STRUCT is bashed to an integral type.
403 // Consider cleaning this up so this workaround is not required.
404 unsigned char lvUnusedStruct : 1; // All references to this promoted struct are through its field locals.
405 // I.e. there is no longer any reference to the struct directly.
406 // In this case we can simply remove this struct local.
409 unsigned char lvLRACandidate : 1; // Tracked for linear scan register allocation purposes
412 // Note that both SIMD vector args and locals are marked as lvSIMDType = true, but the
413 // type of an arg node is TYP_BYREF and a local node is TYP_SIMD*.
414 unsigned char lvSIMDType : 1; // This is a SIMD struct
415 unsigned char lvUsedInSIMDIntrinsic : 1; // This tells lclvar is used for simd intrinsic
416 var_types lvBaseType : 5; // Note: this only packs because var_types is a typedef of unsigned char
417 #endif // FEATURE_SIMD
418 unsigned char lvRegStruct : 1; // This is a reg-sized non-field-addressed struct.
420 unsigned char lvClassIsExact : 1; // lvClassHandle is the exact type
423 unsigned char lvClassInfoUpdated : 1; // true if this var has updated class handle or exactness
426 unsigned char lvImplicitlyReferenced : 1; // true if there are non-IR references to this local (prolog, epilog, gc,
430 unsigned lvFieldLclStart; // The index of the local var representing the first field in the promoted struct
431 // local. For implicit byref parameters, this gets hijacked between
432 // fgRetypeImplicitByRefArgs and fgMarkDemotedImplicitByRefArgs to point to the
433 // struct local created to model the parameter's struct promotion, if any.
434 unsigned lvParentLcl; // The index of the local var representing the parent (i.e. the promoted struct local).
435 // Valid on promoted struct local fields.
438 unsigned char lvFieldCnt; // Number of fields in the promoted VarDsc.
439 unsigned char lvFldOffset;
440 unsigned char lvFldOrdinal;
442 #if FEATURE_MULTIREG_ARGS
443 regNumber lvRegNumForSlot(unsigned slotNum)
449 else if (slotNum == 1)
451 return lvOtherArgReg;
455 assert(false && "Invalid slotNum!");
460 #endif // FEATURE_MULTIREG_ARGS
478 bool lvIsHfaRegArg() const
481 return _lvIsHfaRegArg;
487 void lvSetIsHfaRegArg(bool value = true)
490 _lvIsHfaRegArg = value;
494 bool lvHfaTypeIsFloat() const
497 return _lvHfaTypeIsFloat;
503 void lvSetHfaTypeIsFloat(bool value)
506 _lvHfaTypeIsFloat = value;
510 // on Arm64 - Returns 1-4 indicating the number of register slots used by the HFA
511 // on Arm32 - Returns the total number of single FP register slots used by the HFA, max is 8
513 unsigned lvHfaSlots() const
516 assert(varTypeIsStruct(lvType));
518 return lvExactSize / sizeof(float);
519 #else // _TARGET_ARM64_
520 if (lvHfaTypeIsFloat())
522 return lvExactSize / sizeof(float);
526 return lvExactSize / sizeof(double);
528 #endif // _TARGET_ARM64_
531 // lvIsMultiRegArgOrRet()
532 // returns true if this is a multireg LclVar struct used in an argument context
533 // or if this is a multireg LclVar struct assigned from a multireg call
534 bool lvIsMultiRegArgOrRet()
536 return lvIsMultiRegArg || lvIsMultiRegRet;
540 regNumberSmall _lvRegNum; // Used to store the register this variable is in (or, the low register of a
541 // register pair). It is set during codegen any time the
542 // variable is enregistered (lvRegister is only set
543 // to non-zero if the variable gets the same register assignment for its entire
545 #if !defined(_TARGET_64BIT_)
546 regNumberSmall _lvOtherReg; // Used for "upper half" of long var.
547 #endif // !defined(_TARGET_64BIT_)
549 regNumberSmall _lvArgReg; // The register in which this argument is passed.
551 #if FEATURE_MULTIREG_ARGS
552 regNumberSmall _lvOtherArgReg; // Used for the second part of the struct passed in a register.
553 // Note this is defined but not used by ARM32
554 #endif // FEATURE_MULTIREG_ARGS
556 regNumberSmall _lvArgInitReg; // the register into which the argument is moved at entry
559 // The register number is stored in a small format (8 bits), but the getters return and the setters take
560 // a full-size (unsigned) format, to localize the casts here.
562 /////////////////////
564 __declspec(property(get = GetRegNum, put = SetRegNum)) regNumber lvRegNum;
566 regNumber GetRegNum() const
568 return (regNumber)_lvRegNum;
571 void SetRegNum(regNumber reg)
573 _lvRegNum = (regNumberSmall)reg;
574 assert(_lvRegNum == reg);
577 /////////////////////
579 #if defined(_TARGET_64BIT_)
580 __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
582 regNumber GetOtherReg() const
584 assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
585 // "unreachable code" warnings
589 void SetOtherReg(regNumber reg)
591 assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
592 // "unreachable code" warnings
594 #else // !_TARGET_64BIT_
595 __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
597 regNumber GetOtherReg() const
599 return (regNumber)_lvOtherReg;
602 void SetOtherReg(regNumber reg)
604 _lvOtherReg = (regNumberSmall)reg;
605 assert(_lvOtherReg == reg);
607 #endif // !_TARGET_64BIT_
609 /////////////////////
611 __declspec(property(get = GetArgReg, put = SetArgReg)) regNumber lvArgReg;
613 regNumber GetArgReg() const
615 return (regNumber)_lvArgReg;
618 void SetArgReg(regNumber reg)
620 _lvArgReg = (regNumberSmall)reg;
621 assert(_lvArgReg == reg);
624 #if FEATURE_MULTIREG_ARGS
625 __declspec(property(get = GetOtherArgReg, put = SetOtherArgReg)) regNumber lvOtherArgReg;
627 regNumber GetOtherArgReg() const
629 return (regNumber)_lvOtherArgReg;
632 void SetOtherArgReg(regNumber reg)
634 _lvOtherArgReg = (regNumberSmall)reg;
635 assert(_lvOtherArgReg == reg);
637 #endif // FEATURE_MULTIREG_ARGS
640 // Is this is a SIMD struct?
641 bool lvIsSIMDType() const
646 // Is this is a SIMD struct which is used for SIMD intrinsic?
647 bool lvIsUsedInSIMDIntrinsic() const
649 return lvUsedInSIMDIntrinsic;
652 // If feature_simd not enabled, return false
653 bool lvIsSIMDType() const
657 bool lvIsUsedInSIMDIntrinsic() const
663 /////////////////////
665 __declspec(property(get = GetArgInitReg, put = SetArgInitReg)) regNumber lvArgInitReg;
667 regNumber GetArgInitReg() const
669 return (regNumber)_lvArgInitReg;
672 void SetArgInitReg(regNumber reg)
674 _lvArgInitReg = (regNumberSmall)reg;
675 assert(_lvArgInitReg == reg);
678 /////////////////////
680 bool lvIsRegCandidate() const
682 return lvLRACandidate != 0;
685 bool lvIsInReg() const
687 return lvIsRegCandidate() && (lvRegNum != REG_STK);
690 regMaskTP lvRegMask() const
692 regMaskTP regMask = RBM_NONE;
693 if (varTypeIsFloating(TypeGet()))
695 if (lvRegNum != REG_STK)
697 regMask = genRegMaskFloat(lvRegNum, TypeGet());
702 if (lvRegNum != REG_STK)
704 regMask = genRegMask(lvRegNum);
710 unsigned short lvVarIndex; // variable tracking index
713 unsigned short m_lvRefCnt; // unweighted (real) reference count. For implicit by reference
714 // parameters, this gets hijacked from fgMarkImplicitByRefArgs
715 // through fgMarkDemotedImplicitByRefArgs, to provide a static
716 // appearance count (computed during address-exposed analysis)
717 // that fgMakeOutgoingStructArgCopy consults during global morph
718 // to determine if eliding its copy is legal.
720 BasicBlock::weight_t m_lvRefCntWtd; // weighted reference count
723 unsigned short lvRefCnt(RefCountState state = RCS_NORMAL) const;
724 void incLvRefCnt(unsigned short delta, RefCountState state = RCS_NORMAL);
725 void setLvRefCnt(unsigned short newValue, RefCountState state = RCS_NORMAL);
727 BasicBlock::weight_t lvRefCntWtd(RefCountState state = RCS_NORMAL) const;
728 void incLvRefCntWtd(BasicBlock::weight_t delta, RefCountState state = RCS_NORMAL);
729 void setLvRefCntWtd(BasicBlock::weight_t newValue, RefCountState state = RCS_NORMAL);
731 int lvStkOffs; // stack offset of home
732 unsigned lvExactSize; // (exact) size of the type in bytes
734 // Is this a promoted struct?
735 // This method returns true only for structs (including SIMD structs), not for
736 // locals that are split on a 32-bit target.
737 // It is only necessary to use this:
738 // 1) if only structs are wanted, and
739 // 2) if Lowering has already been done.
740 // Otherwise lvPromoted is valid.
741 bool lvPromotedStruct()
743 #if !defined(_TARGET_64BIT_)
744 return (lvPromoted && !varTypeIsLong(lvType));
745 #else // defined(_TARGET_64BIT_)
747 #endif // defined(_TARGET_64BIT_)
750 unsigned lvSize() const // Size needed for storage representation. Only used for structs or TYP_BLK.
752 // TODO-Review: Sometimes we get called on ARM with HFA struct variables that have been promoted,
753 // where the struct itself is no longer used because all access is via its member fields.
754 // When that happens, the struct is marked as unused and its type has been changed to
755 // TYP_INT (to keep the GC tracking code from looking at it).
756 // See Compiler::raAssignVars() for details. For example:
757 // N002 ( 4, 3) [00EA067C] ------------- return struct $346
758 // N001 ( 3, 2) [00EA0628] ------------- lclVar struct(U) V03 loc2
759 // float V03.f1 (offs=0x00) -> V12 tmp7
760 // f8 (last use) (last use) $345
761 // Here, the "struct(U)" shows that the "V03 loc2" variable is unused. Not shown is that V03
762 // is now TYP_INT in the local variable table. It's not really unused, because it's in the tree.
764 assert(varTypeIsStruct(lvType) || (lvType == TYP_BLK) || (lvPromoted && lvUnusedStruct));
766 #if defined(FEATURE_SIMD) && !defined(_TARGET_64BIT_)
767 // For 32-bit architectures, we make local variable SIMD12 types 16 bytes instead of just 12. We can't do
768 // this for arguments, which must be passed according the defined ABI. We don't want to do this for
769 // dependently promoted struct fields, but we don't know that here. See lvaMapSimd12ToSimd16().
770 // (Note that for 64-bits, we are already rounding up to 16.)
771 if ((lvType == TYP_SIMD12) && !lvIsParam)
773 assert(lvExactSize == 12);
776 #endif // defined(FEATURE_SIMD) && !defined(_TARGET_64BIT_)
778 return roundUp(lvExactSize, TARGET_POINTER_SIZE);
781 const size_t lvArgStackSize() const;
783 unsigned lvSlotNum; // original slot # (if remapped)
785 typeInfo lvVerTypeInfo; // type info needed for verification
787 CORINFO_CLASS_HANDLE lvClassHnd; // class handle for the local, or null if not known
789 CORINFO_FIELD_HANDLE lvFieldHnd; // field handle for promoted struct fields
791 BYTE* lvGcLayout; // GC layout info for structs
794 BlockSet lvRefBlks; // Set of blocks that contain refs
795 GenTree* lvDefStmt; // Pointer to the statement with the single definition
796 void lvaDisqualifyVar(); // Call to disqualify a local variable from use in optAddCopies
798 var_types TypeGet() const
800 return (var_types)lvType;
802 bool lvStackAligned() const
804 assert(lvIsStructField);
805 return ((lvFldOffset % TARGET_POINTER_SIZE) == 0);
807 bool lvNormalizeOnLoad() const
809 return varTypeIsSmall(TypeGet()) &&
810 // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
811 (lvIsParam || lvAddrExposed || lvIsStructField);
814 bool lvNormalizeOnStore()
816 return varTypeIsSmall(TypeGet()) &&
817 // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
818 !(lvIsParam || lvAddrExposed || lvIsStructField);
821 void incRefCnts(BasicBlock::weight_t weight,
823 RefCountState state = RCS_NORMAL,
824 bool propagate = true);
825 bool IsFloatRegType() const
827 return isFloatRegType(lvType) || lvIsHfaRegArg();
829 var_types GetHfaType() const
831 return lvIsHfa() ? (lvHfaTypeIsFloat() ? TYP_FLOAT : TYP_DOUBLE) : TYP_UNDEF;
833 void SetHfaType(var_types type)
835 assert(varTypeIsFloating(type));
836 lvSetHfaTypeIsFloat(type == TYP_FLOAT);
839 var_types lvaArgType();
841 SsaDefArray<LclSsaVarDsc> lvPerSsaData;
843 // Returns the address of the per-Ssa data for the given ssaNum (which is required
844 // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
845 // not an SSA variable).
846 LclSsaVarDsc* GetPerSsaData(unsigned ssaNum)
848 return lvPerSsaData.GetSsaDef(ssaNum);
853 const char* lvReason;
855 void PrintVarReg() const
857 printf("%s", getRegName(lvRegNum));
861 }; // class LclVarDsc
864 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
865 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
869 XX The temporary lclVars allocated by the compiler for code generation XX
871 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
872 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
875 /*****************************************************************************
877 * The following keeps track of temporaries allocated in the stack frame
878 * during code-generation (after register allocation). These spill-temps are
879 * only used if we run out of registers while evaluating a tree.
881 * These are different from the more common temps allocated by lvaGrabTemp().
892 static const int BAD_TEMP_OFFSET = 0xDDDDDDDD; // used as a sentinel "bad value" for tdOffs in DEBUG
900 TempDsc(int _tdNum, unsigned _tdSize, var_types _tdType) : tdNum(_tdNum), tdSize((BYTE)_tdSize), tdType(_tdType)
904 0); // temps must have a negative number (so they have a different number from all local variables)
905 tdOffs = BAD_TEMP_OFFSET;
909 IMPL_LIMITATION("too many spill temps");
914 bool tdLegalOffset() const
916 return tdOffs != BAD_TEMP_OFFSET;
920 int tdTempOffs() const
922 assert(tdLegalOffset());
925 void tdSetTempOffs(int offs)
928 assert(tdLegalOffset());
930 void tdAdjustTempOffs(int offs)
933 assert(tdLegalOffset());
936 int tdTempNum() const
941 unsigned tdTempSize() const
945 var_types tdTempType() const
951 // interface to hide linearscan implementation from rest of compiler
952 class LinearScanInterface
955 virtual void doLinearScan() = 0;
956 virtual void recordVarLocationsAtStartOfBB(BasicBlock* bb) = 0;
957 virtual bool willEnregisterLocalVars() const = 0;
960 LinearScanInterface* getLinearScanAllocator(Compiler* comp);
962 // Information about arrays: their element type and size, and the offset of the first element.
963 // We label GT_IND's that are array indices with GTF_IND_ARR_INDEX, and, for such nodes,
964 // associate an array info via the map retrieved by GetArrayInfoMap(). This information is used,
965 // for example, in value numbering of array index expressions.
968 var_types m_elemType;
969 CORINFO_CLASS_HANDLE m_elemStructType;
971 unsigned m_elemOffset;
973 ArrayInfo() : m_elemType(TYP_UNDEF), m_elemStructType(nullptr), m_elemSize(0), m_elemOffset(0)
977 ArrayInfo(var_types elemType, unsigned elemSize, unsigned elemOffset, CORINFO_CLASS_HANDLE elemStructType)
978 : m_elemType(elemType), m_elemStructType(elemStructType), m_elemSize(elemSize), m_elemOffset(elemOffset)
983 // This enumeration names the phases into which we divide compilation. The phases should completely
984 // partition a compilation.
987 #define CompPhaseNameMacro(enum_nm, string_nm, short_nm, hasChildren, parent, measureIR) enum_nm,
988 #include "compphases.h"
992 extern const char* PhaseNames[];
993 extern const char* PhaseEnums[];
994 extern const LPCWSTR PhaseShortNames[];
996 // The following enum provides a simple 1:1 mapping to CLR API's
997 enum API_ICorJitInfo_Names
999 #define DEF_CLR_API(name) API_##name,
1000 #include "ICorJitInfo_API_names.h"
1004 //---------------------------------------------------------------
1005 // Compilation time.
1008 // A "CompTimeInfo" is a structure for tracking the compilation time of one or more methods.
1009 // We divide a compilation into a sequence of contiguous phases, and track the total (per-thread) cycles
1010 // of the compilation, as well as the cycles for each phase. We also track the number of bytecodes.
1011 // If there is a failure in reading a timer at any point, the "CompTimeInfo" becomes invalid, as indicated
1012 // by "m_timerFailure" being true.
1013 // If FEATURE_JIT_METHOD_PERF is not set, we define a minimal form of this, enough to let other code compile.
1016 #ifdef FEATURE_JIT_METHOD_PERF
1017 // The string names of the phases.
1018 static const char* PhaseNames[];
1020 static bool PhaseHasChildren[];
1021 static int PhaseParent[];
1022 static bool PhaseReportsIRSize[];
1024 unsigned m_byteCodeBytes;
1025 unsigned __int64 m_totalCycles;
1026 unsigned __int64 m_invokesByPhase[PHASE_NUMBER_OF];
1027 unsigned __int64 m_cyclesByPhase[PHASE_NUMBER_OF];
1028 #if MEASURE_CLRAPI_CALLS
1029 unsigned __int64 m_CLRinvokesByPhase[PHASE_NUMBER_OF];
1030 unsigned __int64 m_CLRcyclesByPhase[PHASE_NUMBER_OF];
1033 unsigned m_nodeCountAfterPhase[PHASE_NUMBER_OF];
1035 // For better documentation, we call EndPhase on
1036 // non-leaf phases. We should also call EndPhase on the
1037 // last leaf subphase; obviously, the elapsed cycles between the EndPhase
1038 // for the last leaf subphase and the EndPhase for an ancestor should be very small.
1039 // We add all such "redundant end phase" intervals to this variable below; we print
1040 // it out in a report, so we can verify that it is, indeed, very small. If it ever
1041 // isn't, this means that we're doing something significant between the end of the last
1042 // declared subphase and the end of its parent.
1043 unsigned __int64 m_parentPhaseEndSlop;
1044 bool m_timerFailure;
1046 #if MEASURE_CLRAPI_CALLS
1047 // The following measures the time spent inside each individual CLR API call.
1048 unsigned m_allClrAPIcalls;
1049 unsigned m_perClrAPIcalls[API_ICorJitInfo_Names::API_COUNT];
1050 unsigned __int64 m_allClrAPIcycles;
1051 unsigned __int64 m_perClrAPIcycles[API_ICorJitInfo_Names::API_COUNT];
1052 unsigned __int32 m_maxClrAPIcycles[API_ICorJitInfo_Names::API_COUNT];
1053 #endif // MEASURE_CLRAPI_CALLS
1055 CompTimeInfo(unsigned byteCodeBytes);
1059 #ifdef FEATURE_JIT_METHOD_PERF
1061 #if MEASURE_CLRAPI_CALLS
1062 struct WrapICorJitInfo;
1065 // This class summarizes the JIT time information over the course of a run: the number of methods compiled,
1066 // and the total and maximum timings. (These are instances of the "CompTimeInfo" type described above).
1067 // The operation of adding a single method's timing to the summary may be performed concurrently by several
1068 // threads, so it is protected by a lock.
1069 // This class is intended to be used as a singleton type, with only a single instance.
1070 class CompTimeSummaryInfo
1072 // This lock protects the fields of all CompTimeSummaryInfo(s) (of which we expect there to be one).
1073 static CritSecObject s_compTimeSummaryLock;
1077 CompTimeInfo m_total;
1078 CompTimeInfo m_maximum;
1080 int m_numFilteredMethods;
1081 CompTimeInfo m_filtered;
1083 // This can use what ever data you want to determine if the value to be added
1084 // belongs in the filtered section (it's always included in the unfiltered section)
1085 bool IncludedInFilteredData(CompTimeInfo& info);
1088 // This is the unique CompTimeSummaryInfo object for this instance of the runtime.
1089 static CompTimeSummaryInfo s_compTimeSummary;
1091 CompTimeSummaryInfo()
1092 : m_numMethods(0), m_totMethods(0), m_total(0), m_maximum(0), m_numFilteredMethods(0), m_filtered(0)
1096 // Assumes that "info" is a completed CompTimeInfo for a compilation; adds it to the summary.
1097 // This is thread safe.
1098 void AddInfo(CompTimeInfo& info, bool includePhases);
1100 // Print the summary information to "f".
1101 // This is not thread-safe; assumed to be called by only one thread.
1102 void Print(FILE* f);
1105 // A JitTimer encapsulates a CompTimeInfo for a single compilation. It also tracks the start of compilation,
1106 // and when the current phase started. This is intended to be part of a Compilation object. This is
1107 // disabled (FEATURE_JIT_METHOD_PERF not defined) when FEATURE_CORECLR is set, or on non-windows platforms.
1111 unsigned __int64 m_start; // Start of the compilation.
1112 unsigned __int64 m_curPhaseStart; // Start of the current phase.
1113 #if MEASURE_CLRAPI_CALLS
1114 unsigned __int64 m_CLRcallStart; // Start of the current CLR API call (if any).
1115 unsigned __int64 m_CLRcallInvokes; // CLR API invokes under current outer so far
1116 unsigned __int64 m_CLRcallCycles; // CLR API cycles under current outer so far.
1117 int m_CLRcallAPInum; // The enum/index of the current CLR API call (or -1).
1118 static double s_cyclesPerSec; // Cached for speedier measurements
1121 Phases m_lastPhase; // The last phase that was completed (or (Phases)-1 to start).
1123 CompTimeInfo m_info; // The CompTimeInfo for this compilation.
1125 static CritSecObject s_csvLock; // Lock to protect the time log file.
1126 void PrintCsvMethodStats(Compiler* comp);
1129 void* operator new(size_t);
1130 void* operator new[](size_t);
1131 void operator delete(void*);
1132 void operator delete[](void*);
1135 // Initialized the timer instance
1136 JitTimer(unsigned byteCodeSize);
1138 static JitTimer* Create(Compiler* comp, unsigned byteCodeSize)
1140 return ::new (comp, CMK_Unknown) JitTimer(byteCodeSize);
1143 static void PrintCsvHeader();
1145 // Ends the current phase (argument is for a redundant check).
1146 void EndPhase(Compiler* compiler, Phases phase);
1148 #if MEASURE_CLRAPI_CALLS
1149 // Start and end a timed CLR API call.
1150 void CLRApiCallEnter(unsigned apix);
1151 void CLRApiCallLeave(unsigned apix);
1152 #endif // MEASURE_CLRAPI_CALLS
1154 // Completes the timing of the current method, which is assumed to have "byteCodeBytes" bytes of bytecode,
1155 // and adds it to "sum".
1156 void Terminate(Compiler* comp, CompTimeSummaryInfo& sum, bool includePhases);
1158 // Attempts to query the cycle counter of the current thread. If successful, returns "true" and sets
1159 // *cycles to the cycle counter value. Otherwise, returns false and sets the "m_timerFailure" flag of
1160 // "m_info" to true.
1161 bool GetThreadCycles(unsigned __int64* cycles)
1163 bool res = CycleTimer::GetThreadCyclesS(cycles);
1166 m_info.m_timerFailure = true;
1171 #endif // FEATURE_JIT_METHOD_PERF
1173 //------------------- Function/Funclet info -------------------------------
1174 enum FuncKind : BYTE
1176 FUNC_ROOT, // The main/root function (always id==0)
1177 FUNC_HANDLER, // a funclet associated with an EH handler (finally, fault, catch, filter handler)
1178 FUNC_FILTER, // a funclet associated with an EH filter
1187 BYTE funFlags; // Currently unused, just here for padding
1188 unsigned short funEHIndex; // index, into the ebd table, of innermost EH clause corresponding to this
1189 // funclet. It is only valid if funKind field indicates this is a
1190 // EH-related funclet: FUNC_HANDLER or FUNC_FILTER
1192 #if defined(_TARGET_AMD64_)
1194 // TODO-AMD64-Throughput: make the AMD64 info more like the ARM info to avoid having this large static array.
1195 emitLocation* startLoc;
1196 emitLocation* endLoc;
1197 emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1198 emitLocation* coldEndLoc;
1199 UNWIND_INFO unwindHeader;
1200 // Maximum of 255 UNWIND_CODE 'nodes' and then the unwind header. If there are an odd
1201 // number of codes, the VM or Zapper will 4-byte align the whole thing.
1202 BYTE unwindCodes[offsetof(UNWIND_INFO, UnwindCode) + (0xFF * sizeof(UNWIND_CODE))];
1203 unsigned unwindCodeSlot;
1205 #elif defined(_TARGET_X86_)
1207 #if defined(_TARGET_UNIX_)
1208 emitLocation* startLoc;
1209 emitLocation* endLoc;
1210 emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1211 emitLocation* coldEndLoc;
1212 #endif // _TARGET_UNIX_
1214 #elif defined(_TARGET_ARMARCH_)
1216 UnwindInfo uwi; // Unwind information for this function/funclet's hot section
1217 UnwindInfo* uwiCold; // Unwind information for this function/funclet's cold section
1218 // Note: we only have a pointer here instead of the actual object,
1219 // to save memory in the JIT case (compared to the NGEN case),
1220 // where we don't have any cold section.
1221 // Note 2: we currently don't support hot/cold splitting in functions
1222 // with EH, so uwiCold will be NULL for all funclets.
1224 #if defined(_TARGET_UNIX_)
1225 emitLocation* startLoc;
1226 emitLocation* endLoc;
1227 emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1228 emitLocation* coldEndLoc;
1229 #endif // _TARGET_UNIX_
1231 #endif // _TARGET_ARMARCH_
1233 #if defined(_TARGET_UNIX_)
1234 jitstd::vector<CFI_CODE>* cfiCodes;
1235 #endif // _TARGET_UNIX_
1237 // Eventually we may want to move rsModifiedRegsMask, lvaOutgoingArgSize, and anything else
1238 // that isn't shared between the main function body and funclets.
1241 struct fgArgTabEntry
1243 GenTree* node; // Initially points at the Op1 field of 'parent', but if the argument is replaced with an GT_ASG or
1244 // placeholder it will point at the actual argument in the gtCallLateArgs list.
1245 GenTree* parent; // Points at the GT_LIST node in the gtCallArgs for this argument
1247 unsigned argNum; // The original argument number, also specifies the required argument evaluation order from the IL
1250 regNumberSmall regNums[MAX_ARG_REG_COUNT]; // The registers to use when passing this argument, set to REG_STK for
1251 // arguments passed on the stack
1253 unsigned numRegs; // Count of number of registers that this argument uses.
1254 // Note that on ARM, if we have a double hfa, this reflects the number
1255 // of DOUBLE registers.
1257 // A slot is a pointer sized region in the OutArg area.
1258 unsigned slotNum; // When an argument is passed in the OutArg area this is the slot number in the OutArg area
1259 unsigned numSlots; // Count of number of slots that this argument uses
1261 unsigned alignment; // 1 or 2 (slots/registers)
1263 unsigned _lateArgInx; // index into gtCallLateArgs list; UINT_MAX if this is not a late arg.
1265 unsigned tmpNum; // the LclVar number if we had to force evaluation of this arg
1267 var_types argType; // The type used to pass this argument. This is generally the original argument type, but when a
1268 // struct is passed as a scalar type, this is that type.
1269 // Note that if a struct is passed by reference, this will still be the struct type.
1271 bool needTmp : 1; // True when we force this argument's evaluation into a temp LclVar
1272 bool needPlace : 1; // True when we must replace this argument with a placeholder node
1273 bool isTmp : 1; // True when we setup a temp LclVar for this argument due to size issues with the struct
1274 bool processed : 1; // True when we have decided the evaluation order for this argument in the gtCallLateArgs
1275 bool isBackFilled : 1; // True when the argument fills a register slot skipped due to alignment requirements of
1276 // previous arguments.
1277 bool isNonStandard : 1; // True if it is an arg that is passed in a reg other than a standard arg reg, or is forced
1278 // to be on the stack despite its arg list position.
1279 bool isStruct : 1; // True if this is a struct arg
1280 bool _isVararg : 1; // True if the argument is in a vararg context.
1281 bool passedByRef : 1; // True iff the argument is passed by reference.
1282 #ifdef FEATURE_ARG_SPLIT
1283 bool _isSplit : 1; // True when this argument is split between the registers and OutArg area
1284 #endif // FEATURE_ARG_SPLIT
1286 bool _isHfaArg : 1; // True when the argument is an HFA type.
1287 bool _isDoubleHfa : 1; // True when the argument is an HFA, with an element type of DOUBLE.
1292 bool isLate = (_lateArgInx != UINT_MAX);
1296 __declspec(property(get = getLateArgInx, put = setLateArgInx)) unsigned lateArgInx;
1297 unsigned getLateArgInx()
1299 assert(isLateArg());
1302 void setLateArgInx(unsigned inx)
1306 __declspec(property(get = getRegNum)) regNumber regNum;
1307 regNumber getRegNum()
1309 return (regNumber)regNums[0];
1311 __declspec(property(get = getOtherRegNum)) regNumber otherRegNum;
1312 regNumber getOtherRegNum()
1314 return (regNumber)regNums[1];
1317 #if defined(UNIX_AMD64_ABI)
1318 SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR structDesc;
1321 void setRegNum(unsigned int i, regNumber regNum)
1323 assert(i < MAX_ARG_REG_COUNT);
1324 regNums[i] = (regNumberSmall)regNum;
1326 regNumber getRegNum(unsigned int i)
1328 assert(i < MAX_ARG_REG_COUNT);
1329 return (regNumber)regNums[i];
1332 __declspec(property(get = getIsSplit, put = setIsSplit)) bool isSplit;
1335 #ifdef FEATURE_ARG_SPLIT
1337 #else // FEATURE_ARG_SPLIT
1341 void setIsSplit(bool value)
1343 #ifdef FEATURE_ARG_SPLIT
1348 __declspec(property(get = getIsVararg, put = setIsVararg)) bool isVararg;
1351 #ifdef FEATURE_VARARG
1357 void setIsVararg(bool value)
1359 #ifdef FEATURE_VARARG
1361 #endif // FEATURE_VARARG
1364 __declspec(property(get = getIsHfaArg)) bool isHfaArg;
1374 __declspec(property(get = getIsHfaRegArg)) bool isHfaRegArg;
1375 bool getIsHfaRegArg()
1378 return _isHfaArg && isPassedInRegisters();
1384 __declspec(property(get = getHfaType)) var_types hfaType;
1385 var_types getHfaType()
1388 return _isHfaArg ? (_isDoubleHfa ? TYP_DOUBLE : TYP_FLOAT) : TYP_UNDEF;
1394 void setHfaType(var_types type, unsigned hfaSlots)
1397 if (type != TYP_UNDEF)
1399 // We must already have set the passing mode.
1400 assert(numRegs != 0 || numSlots != 0);
1401 // We originally set numRegs according to the size of the struct, but if the size of the
1402 // hfaType is not the same as the pointer size, we need to correct it.
1403 // Note that hfaSlots is the number of registers we will use. For ARM, that is twice
1404 // the number of "double registers".
1405 unsigned numHfaRegs = hfaSlots;
1406 if (isPassedInRegisters())
1409 if (type == TYP_DOUBLE)
1411 // Must be an even number of registers.
1412 assert((numRegs & 1) == 0);
1413 numHfaRegs = hfaSlots / 2;
1415 #endif // _TARGET_ARM_
1418 // This should already be set correctly.
1419 assert(numRegs == numHfaRegs);
1420 assert(_isDoubleHfa == (type == TYP_DOUBLE));
1424 numRegs = numHfaRegs;
1427 _isDoubleHfa = (type == TYP_DOUBLE);
1430 #endif // FEATURE_HFA
1434 void SetIsBackFilled(bool backFilled)
1436 isBackFilled = backFilled;
1439 bool IsBackFilled() const
1441 return isBackFilled;
1443 #else // !_TARGET_ARM_
1444 void SetIsBackFilled(bool backFilled)
1448 bool IsBackFilled() const
1452 #endif // !_TARGET_ARM_
1454 bool isPassedInRegisters()
1456 return !isSplit && (numRegs != 0);
1459 bool isPassedInFloatRegisters()
1464 return isValidFloatArgReg(regNum);
1468 bool isSingleRegOrSlot()
1470 return !isSplit && ((numRegs == 1) || (numSlots == 1));
1473 // Returns the number of "slots" used, where for this purpose a
1474 // register counts as a slot.
1475 unsigned getSlotCount()
1479 assert(isPassedInRegisters());
1480 assert(numRegs == 1);
1482 else if (regNum == REG_STK)
1484 assert(!isPassedInRegisters());
1485 assert(numRegs == 0);
1489 assert(numRegs > 0);
1491 return numSlots + numRegs;
1494 // Returns the size as a multiple of pointer-size.
1495 // For targets without HFAs, this is the same as getSlotCount().
1498 unsigned size = getSlotCount();
1501 // We counted the number of regs, but if they are DOUBLE hfa regs we have to double the size.
1502 if (isHfaRegArg && (hfaType == TYP_DOUBLE))
1507 #elif defined(_TARGET_ARM64_)
1508 // We counted the number of regs, but if they are FLOAT hfa regs we have to halve the size.
1509 if (isHfaRegArg && (hfaType == TYP_FLOAT))
1511 // Round up in case of odd HFA count.
1512 size = (size + 1) >> 1;
1514 #endif // _TARGET_ARM64_
1519 // Set the register numbers for a multireg argument.
1520 // There's nothing to do on x64/Ux because the structDesc has already been used to set the
1521 // register numbers.
1522 void SetMultiRegNums()
1524 #if FEATURE_MULTIREG_ARGS && !defined(UNIX_AMD64_ABI)
1530 regNumber argReg = getRegNum(0);
1532 unsigned int regSize = (hfaType == TYP_DOUBLE) ? 2 : 1;
1534 unsigned int regSize = 1;
1536 for (unsigned int regIndex = 1; regIndex < numRegs; regIndex++)
1538 argReg = (regNumber)(argReg + regSize);
1539 setRegNum(regIndex, argReg);
1541 #endif // FEATURE_MULTIREG_ARGS && !defined(UNIX_AMD64_ABI)
1544 // Check that the value of 'isStruct' is consistent.
1545 // A struct arg must be one of the following:
1546 // - A node of struct type,
1547 // - A GT_FIELD_LIST, or
1548 // - A node of a scalar type, passed in a single register or slot
1549 // (or two slots in the case of a struct pass on the stack as TYP_DOUBLE).
1551 void checkIsStruct()
1555 if (!varTypeIsStruct(node) && !node->OperIs(GT_FIELD_LIST))
1557 // This is the case where we are passing a struct as a primitive type.
1558 // On most targets, this is always a single register or slot.
1559 // However, on ARM this could be two slots if it is TYP_DOUBLE.
1560 bool isPassedAsPrimitiveType = ((numRegs == 1) || ((numRegs == 0) && (numSlots == 1)));
1562 if (!isPassedAsPrimitiveType)
1564 if (node->TypeGet() == TYP_DOUBLE && numRegs == 0 && (numSlots == 2))
1566 isPassedAsPrimitiveType = true;
1569 #endif // _TARGET_ARM_
1570 assert(isPassedAsPrimitiveType);
1575 assert(!varTypeIsStruct(node));
1584 //-------------------------------------------------------------------------
1586 // The class fgArgInfo is used to handle the arguments
1587 // when morphing a GT_CALL node.
1592 Compiler* compiler; // Back pointer to the compiler instance so that we can allocate memory
1593 GenTreeCall* callTree; // Back pointer to the GT_CALL node for this fgArgInfo
1594 unsigned argCount; // Updatable arg count value
1595 unsigned nextSlotNum; // Updatable slot count value
1596 unsigned stkLevel; // Stack depth when we make this call (for x86)
1598 #if defined(UNIX_X86_ABI)
1599 bool alignmentDone; // Updateable flag, set to 'true' after we've done any required alignment.
1600 unsigned stkSizeBytes; // Size of stack used by this call, in bytes. Calculated during fgMorphArgs().
1601 unsigned padStkAlign; // Stack alignment in bytes required before arguments are pushed for this call.
1602 // Computed dynamically during codegen, based on stkSizeBytes and the current
1603 // stack level (genStackLevel) when the first stack adjustment is made for
1607 #if FEATURE_FIXED_OUT_ARGS
1608 unsigned outArgSize; // Size of the out arg area for the call, will be at least MIN_ARG_AREA_FOR_CALL
1611 unsigned argTableSize; // size of argTable array (equal to the argCount when done with fgMorphArgs)
1612 bool hasRegArgs; // true if we have one or more register arguments
1613 bool hasStackArgs; // true if we have one or more stack arguments
1614 bool argsComplete; // marker for state
1615 bool argsSorted; // marker for state
1616 fgArgTabEntry** argTable; // variable sized array of per argument descrption: (i.e. argTable[argTableSize])
1619 void AddArg(fgArgTabEntry* curArgTabEntry);
1622 fgArgInfo(Compiler* comp, GenTreeCall* call, unsigned argCount);
1623 fgArgInfo(GenTreeCall* newCall, GenTreeCall* oldCall);
1625 fgArgTabEntry* AddRegArg(unsigned argNum,
1632 bool isVararg = false);
1634 #ifdef UNIX_AMD64_ABI
1635 fgArgTabEntry* AddRegArg(unsigned argNum,
1641 const bool isStruct,
1642 const bool isVararg,
1643 const regNumber otherRegNum,
1644 const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* const structDescPtr = nullptr);
1645 #endif // UNIX_AMD64_ABI
1647 fgArgTabEntry* AddStkArg(unsigned argNum,
1653 bool isVararg = false);
1655 void RemorphReset();
1656 void UpdateRegArg(fgArgTabEntry* argEntry, GenTree* node, bool reMorphing);
1657 void UpdateStkArg(fgArgTabEntry* argEntry, GenTree* node, bool reMorphing);
1659 void SplitArg(unsigned argNum, unsigned numRegs, unsigned numSlots);
1661 void EvalToTmp(fgArgTabEntry* curArgTabEntry, unsigned tmpNum, GenTree* newNode);
1663 void ArgsComplete();
1667 void EvalArgsToTemps();
1673 fgArgTabEntry** ArgTable()
1677 unsigned GetNextSlotNum()
1687 return hasStackArgs;
1689 bool AreArgsComplete() const
1691 return argsComplete;
1693 #if FEATURE_FIXED_OUT_ARGS
1694 unsigned GetOutArgSize() const
1698 void SetOutArgSize(unsigned newVal)
1700 outArgSize = newVal;
1702 #endif // FEATURE_FIXED_OUT_ARGS
1704 #if defined(UNIX_X86_ABI)
1705 void ComputeStackAlignment(unsigned curStackLevelInBytes)
1707 padStkAlign = AlignmentPad(curStackLevelInBytes, STACK_ALIGN);
1710 unsigned GetStkAlign()
1715 void SetStkSizeBytes(unsigned newStkSizeBytes)
1717 stkSizeBytes = newStkSizeBytes;
1720 unsigned GetStkSizeBytes() const
1722 return stkSizeBytes;
1725 bool IsStkAlignmentDone() const
1727 return alignmentDone;
1730 void SetStkAlignmentDone()
1732 alignmentDone = true;
1734 #endif // defined(UNIX_X86_ABI)
1736 // Get the fgArgTabEntry for the arg at position argNum.
1737 fgArgTabEntry* GetArgEntry(unsigned argNum, bool reMorphing = true)
1739 fgArgTabEntry* curArgTabEntry = nullptr;
1743 // The arg table has not yet been sorted.
1744 curArgTabEntry = argTable[argNum];
1745 assert(curArgTabEntry->argNum == argNum);
1746 return curArgTabEntry;
1749 for (unsigned i = 0; i < argCount; i++)
1751 curArgTabEntry = argTable[i];
1752 if (curArgTabEntry->argNum == argNum)
1754 return curArgTabEntry;
1757 noway_assert(!"GetArgEntry: argNum not found");
1761 // Get the node for the arg at position argIndex.
1762 // Caller must ensure that this index is a valid arg index.
1763 GenTree* GetArgNode(unsigned argIndex)
1765 return GetArgEntry(argIndex)->node;
1768 void Dump(Compiler* compiler);
1772 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1773 // We have the ability to mark source expressions with "Test Labels."
1774 // These drive assertions within the JIT, or internal JIT testing. For example, we could label expressions
1775 // that should be CSE defs, and other expressions that should uses of those defs, with a shared label.
1777 enum TestLabel // This must be kept identical to System.Runtime.CompilerServices.JitTestLabel.TestLabel.
1780 TL_VN, // Defines a "VN equivalence class". (For full VN, including exceptions thrown).
1781 TL_VNNorm, // Like above, but uses the non-exceptional value of the expression.
1782 TL_CSE_Def, // This must be identified in the JIT as a CSE def
1783 TL_CSE_Use, // This must be identified in the JIT as a CSE use
1784 TL_LoopHoist, // Expression must (or must not) be hoisted out of the loop.
1787 struct TestLabelAndNum
1792 TestLabelAndNum() : m_tl(TestLabel(0)), m_num(0)
1797 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, TestLabelAndNum> NodeToTestDataMap;
1799 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1803 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1804 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1806 XX The big guy. The sections are currently organized as : XX
1808 XX o GenTree and BasicBlock XX
1820 XX o PrologScopeInfo XX
1821 XX o CodeGenerator XX
1826 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1827 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1830 struct HWIntrinsicInfo;
1834 friend class emitter;
1835 friend class UnwindInfo;
1836 friend class UnwindFragmentInfo;
1837 friend class UnwindEpilogInfo;
1838 friend class JitTimer;
1839 friend class LinearScan;
1840 friend class fgArgInfo;
1841 friend class Rationalizer;
1843 friend class Lowering;
1844 friend class CSE_DataFlow;
1845 friend class CSE_Heuristic;
1846 friend class CodeGenInterface;
1847 friend class CodeGen;
1848 friend class LclVarDsc;
1849 friend class TempDsc;
1851 friend class ObjectAllocator;
1852 friend class LocalAddressVisitor;
1853 friend struct GenTree;
1855 #ifdef FEATURE_HW_INTRINSICS
1856 friend struct HWIntrinsicInfo;
1857 #endif // FEATURE_HW_INTRINSICS
1859 #ifndef _TARGET_64BIT_
1860 friend class DecomposeLongs;
1861 #endif // !_TARGET_64BIT_
1864 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1865 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1867 XX Misc structs definitions XX
1869 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1870 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1874 hashBvGlobalData hbvGlobalData; // Used by the hashBv bitvector package.
1893 bool dumpIRDataflow;
1894 bool dumpIRBlockHeaders;
1896 LPCWSTR dumpIRPhase;
1897 LPCWSTR dumpIRFormat;
1899 bool shouldUseVerboseTrees();
1900 bool asciiTrees; // If true, dump trees using only ASCII characters
1901 bool shouldDumpASCIITrees();
1902 bool verboseSsa; // If true, produce especially verbose dump output in SSA construction.
1903 bool shouldUseVerboseSsa();
1904 bool treesBeforeAfterMorph; // If true, print trees before/after morphing (paired by an intra-compilation id:
1905 int morphNum; // This counts the the trees that have been morphed, allowing us to label each uniquely.
1907 const char* VarNameToStr(VarName name)
1912 DWORD expensiveDebugCheckLevel;
1915 #if FEATURE_MULTIREG_RET
1916 GenTree* impAssignMultiRegTypeToVar(GenTree* op, CORINFO_CLASS_HANDLE hClass);
1917 #endif // FEATURE_MULTIREG_RET
1919 GenTree* impAssignSmallStructTypeToVar(GenTree* op, CORINFO_CLASS_HANDLE hClass);
1922 bool isSingleFloat32Struct(CORINFO_CLASS_HANDLE hClass);
1923 #endif // ARM_SOFTFP
1925 //-------------------------------------------------------------------------
1926 // Functions to handle homogeneous floating-point aggregates (HFAs) in ARM.
1927 // HFAs are one to four element structs where each element is the same
1928 // type, either all float or all double. They are treated specially
1929 // in the ARM Procedure Call Standard, specifically, they are passed in
1930 // floating-point registers instead of the general purpose registers.
1933 bool IsHfa(CORINFO_CLASS_HANDLE hClass);
1934 bool IsHfa(GenTree* tree);
1936 var_types GetHfaType(GenTree* tree);
1937 unsigned GetHfaCount(GenTree* tree);
1939 var_types GetHfaType(CORINFO_CLASS_HANDLE hClass);
1940 unsigned GetHfaCount(CORINFO_CLASS_HANDLE hClass);
1942 bool IsMultiRegReturnedType(CORINFO_CLASS_HANDLE hClass);
1944 //-------------------------------------------------------------------------
1945 // The following is used for validating format of EH table
1949 typedef struct EHNodeDsc* pEHNodeDsc;
1951 EHNodeDsc* ehnTree; // root of the tree comprising the EHnodes.
1952 EHNodeDsc* ehnNext; // root of the tree comprising the EHnodes.
1965 EHBlockType ehnBlockType; // kind of EH block
1966 IL_OFFSET ehnStartOffset; // IL offset of start of the EH block
1967 IL_OFFSET ehnEndOffset; // IL offset past end of the EH block. (TODO: looks like verInsertEhNode() sets this to
1968 // the last IL offset, not "one past the last one", i.e., the range Start to End is
1970 pEHNodeDsc ehnNext; // next (non-nested) block in sequential order
1971 pEHNodeDsc ehnChild; // leftmost nested block
1973 pEHNodeDsc ehnTryNode; // for filters and handlers, the corresponding try node
1974 pEHNodeDsc ehnHandlerNode; // for a try node, the corresponding handler node
1976 pEHNodeDsc ehnFilterNode; // if this is a try node and has a filter, otherwise 0
1977 pEHNodeDsc ehnEquivalent; // if blockType=tryNode, start offset and end offset is same,
1979 inline void ehnSetTryNodeType()
1981 ehnBlockType = TryNode;
1983 inline void ehnSetFilterNodeType()
1985 ehnBlockType = FilterNode;
1987 inline void ehnSetHandlerNodeType()
1989 ehnBlockType = HandlerNode;
1991 inline void ehnSetFinallyNodeType()
1993 ehnBlockType = FinallyNode;
1995 inline void ehnSetFaultNodeType()
1997 ehnBlockType = FaultNode;
2000 inline BOOL ehnIsTryBlock()
2002 return ehnBlockType == TryNode;
2004 inline BOOL ehnIsFilterBlock()
2006 return ehnBlockType == FilterNode;
2008 inline BOOL ehnIsHandlerBlock()
2010 return ehnBlockType == HandlerNode;
2012 inline BOOL ehnIsFinallyBlock()
2014 return ehnBlockType == FinallyNode;
2016 inline BOOL ehnIsFaultBlock()
2018 return ehnBlockType == FaultNode;
2021 // returns true if there is any overlap between the two nodes
2022 static inline BOOL ehnIsOverlap(pEHNodeDsc node1, pEHNodeDsc node2)
2024 if (node1->ehnStartOffset < node2->ehnStartOffset)
2026 return (node1->ehnEndOffset >= node2->ehnStartOffset);
2030 return (node1->ehnStartOffset <= node2->ehnEndOffset);
2034 // fails with BADCODE if inner is not completely nested inside outer
2035 static inline BOOL ehnIsNested(pEHNodeDsc inner, pEHNodeDsc outer)
2037 return ((inner->ehnStartOffset >= outer->ehnStartOffset) && (inner->ehnEndOffset <= outer->ehnEndOffset));
2041 //-------------------------------------------------------------------------
2042 // Exception handling functions
2045 #if !FEATURE_EH_FUNCLETS
2047 bool ehNeedsShadowSPslots()
2049 return (info.compXcptnsCount || opts.compDbgEnC);
2052 // 0 for methods with no EH
2053 // 1 for methods with non-nested EH, or where only the try blocks are nested
2054 // 2 for a method with a catch within a catch
2056 unsigned ehMaxHndNestingCount;
2058 #endif // !FEATURE_EH_FUNCLETS
2060 static bool jitIsBetween(unsigned value, unsigned start, unsigned end);
2061 static bool jitIsBetweenInclusive(unsigned value, unsigned start, unsigned end);
2063 bool bbInCatchHandlerILRange(BasicBlock* blk);
2064 bool bbInFilterILRange(BasicBlock* blk);
2065 bool bbInTryRegions(unsigned regionIndex, BasicBlock* blk);
2066 bool bbInExnFlowRegions(unsigned regionIndex, BasicBlock* blk);
2067 bool bbInHandlerRegions(unsigned regionIndex, BasicBlock* blk);
2068 bool bbInCatchHandlerRegions(BasicBlock* tryBlk, BasicBlock* hndBlk);
2069 unsigned short bbFindInnermostCommonTryRegion(BasicBlock* bbOne, BasicBlock* bbTwo);
2071 unsigned short bbFindInnermostTryRegionContainingHandlerRegion(unsigned handlerIndex);
2072 unsigned short bbFindInnermostHandlerRegionContainingTryRegion(unsigned tryIndex);
2074 // Returns true if "block" is the start of a try region.
2075 bool bbIsTryBeg(BasicBlock* block);
2077 // Returns true if "block" is the start of a handler or filter region.
2078 bool bbIsHandlerBeg(BasicBlock* block);
2080 // Returns true iff "block" is where control flows if an exception is raised in the
2081 // try region, and sets "*regionIndex" to the index of the try for the handler.
2082 // Differs from "IsHandlerBeg" in the case of filters, where this is true for the first
2083 // block of the filter, but not for the filter's handler.
2084 bool bbIsExFlowBlock(BasicBlock* block, unsigned* regionIndex);
2086 bool ehHasCallableHandlers();
2088 // Return the EH descriptor for the given region index.
2089 EHblkDsc* ehGetDsc(unsigned regionIndex);
2091 // Return the EH index given a region descriptor.
2092 unsigned ehGetIndex(EHblkDsc* ehDsc);
2094 // Return the EH descriptor index of the enclosing try, for the given region index.
2095 unsigned ehGetEnclosingTryIndex(unsigned regionIndex);
2097 // Return the EH descriptor index of the enclosing handler, for the given region index.
2098 unsigned ehGetEnclosingHndIndex(unsigned regionIndex);
2100 // Return the EH descriptor for the most nested 'try' region this BasicBlock is a member of (or nullptr if this
2101 // block is not in a 'try' region).
2102 EHblkDsc* ehGetBlockTryDsc(BasicBlock* block);
2104 // Return the EH descriptor for the most nested filter or handler region this BasicBlock is a member of (or nullptr
2105 // if this block is not in a filter or handler region).
2106 EHblkDsc* ehGetBlockHndDsc(BasicBlock* block);
2108 // Return the EH descriptor for the most nested region that may handle exceptions raised in this BasicBlock (or
2109 // nullptr if this block's exceptions propagate to caller).
2110 EHblkDsc* ehGetBlockExnFlowDsc(BasicBlock* block);
2112 EHblkDsc* ehIsBlockTryLast(BasicBlock* block);
2113 EHblkDsc* ehIsBlockHndLast(BasicBlock* block);
2114 bool ehIsBlockEHLast(BasicBlock* block);
2116 bool ehBlockHasExnFlowDsc(BasicBlock* block);
2118 // Return the region index of the most nested EH region this block is in.
2119 unsigned ehGetMostNestedRegionIndex(BasicBlock* block, bool* inTryRegion);
2121 // Find the true enclosing try index, ignoring 'mutual protect' try. Uses IL ranges to check.
2122 unsigned ehTrueEnclosingTryIndexIL(unsigned regionIndex);
2124 // Return the index of the most nested enclosing region for a particular EH region. Returns NO_ENCLOSING_INDEX
2125 // if there is no enclosing region. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion'
2126 // is set to 'true' if the enclosing region is a 'try', or 'false' if the enclosing region is a handler.
2127 // (It can never be a filter.)
2128 unsigned ehGetEnclosingRegionIndex(unsigned regionIndex, bool* inTryRegion);
2130 // A block has been deleted. Update the EH table appropriately.
2131 void ehUpdateForDeletedBlock(BasicBlock* block);
2133 // Determine whether a block can be deleted while preserving the EH normalization rules.
2134 bool ehCanDeleteEmptyBlock(BasicBlock* block);
2136 // Update the 'last' pointers in the EH table to reflect new or deleted blocks in an EH region.
2137 void ehUpdateLastBlocks(BasicBlock* oldLast, BasicBlock* newLast);
2139 // For a finally handler, find the region index that the BBJ_CALLFINALLY lives in that calls the handler,
2140 // or NO_ENCLOSING_INDEX if the BBJ_CALLFINALLY lives in the main function body. Normally, the index
2141 // is the same index as the handler (and the BBJ_CALLFINALLY lives in the 'try' region), but for AMD64 the
2142 // BBJ_CALLFINALLY lives in the enclosing try or handler region, whichever is more nested, or the main function
2143 // body. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion' is set to 'true' if the
2144 // BBJ_CALLFINALLY lives in the returned index's 'try' region, or 'false' if lives in the handler region. (It never
2145 // lives in a filter.)
2146 unsigned ehGetCallFinallyRegionIndex(unsigned finallyIndex, bool* inTryRegion);
2148 // Find the range of basic blocks in which all BBJ_CALLFINALLY will be found that target the 'finallyIndex' region's
2149 // handler. Set begBlk to the first block, and endBlk to the block after the last block of the range
2150 // (nullptr if the last block is the last block in the program).
2151 // Precondition: 'finallyIndex' is the EH region of a try/finally clause.
2152 void ehGetCallFinallyBlockRange(unsigned finallyIndex, BasicBlock** begBlk, BasicBlock** endBlk);
2155 // Given a BBJ_CALLFINALLY block and the EH region index of the finally it is calling, return
2156 // 'true' if the BBJ_CALLFINALLY is in the correct EH region.
2157 bool ehCallFinallyInCorrectRegion(BasicBlock* blockCallFinally, unsigned finallyIndex);
2160 #if FEATURE_EH_FUNCLETS
2161 // Do we need a PSPSym in the main function? For codegen purposes, we only need one
2162 // if there is a filter that protects a region with a nested EH clause (such as a
2163 // try/catch nested in the 'try' body of a try/filter/filter-handler). See
2164 // genFuncletProlog() for more details. However, the VM seems to use it for more
2165 // purposes, maybe including debugging. Until we are sure otherwise, always create
2166 // a PSPSym for functions with any EH.
2167 bool ehNeedsPSPSym() const
2171 #else // _TARGET_X86_
2172 return compHndBBtabCount > 0;
2173 #endif // _TARGET_X86_
2176 bool ehAnyFunclets(); // Are there any funclets in this function?
2177 unsigned ehFuncletCount(); // Return the count of funclets in the function
2179 unsigned bbThrowIndex(BasicBlock* blk); // Get the index to use as the cache key for sharing throw blocks
2180 #else // !FEATURE_EH_FUNCLETS
2181 bool ehAnyFunclets()
2185 unsigned ehFuncletCount()
2190 unsigned bbThrowIndex(BasicBlock* blk)
2192 return blk->bbTryIndex;
2193 } // Get the index to use as the cache key for sharing throw blocks
2194 #endif // !FEATURE_EH_FUNCLETS
2196 // Returns a flowList representing the "EH predecessors" of "blk". These are the normal predecessors of
2197 // "blk", plus one special case: if "blk" is the first block of a handler, considers the predecessor(s) of the first
2198 // first block of the corresponding try region to be "EH predecessors". (If there is a single such predecessor,
2199 // for example, we want to consider that the immediate dominator of the catch clause start block, so it's
2200 // convenient to also consider it a predecessor.)
2201 flowList* BlockPredsWithEH(BasicBlock* blk);
2203 // This table is useful for memoization of the method above.
2204 typedef JitHashTable<BasicBlock*, JitPtrKeyFuncs<BasicBlock>, flowList*> BlockToFlowListMap;
2205 BlockToFlowListMap* m_blockToEHPreds;
2206 BlockToFlowListMap* GetBlockToEHPreds()
2208 if (m_blockToEHPreds == nullptr)
2210 m_blockToEHPreds = new (getAllocator()) BlockToFlowListMap(getAllocator());
2212 return m_blockToEHPreds;
2215 void* ehEmitCookie(BasicBlock* block);
2216 UNATIVE_OFFSET ehCodeOffset(BasicBlock* block);
2218 EHblkDsc* ehInitHndRange(BasicBlock* src, IL_OFFSET* hndBeg, IL_OFFSET* hndEnd, bool* inFilter);
2220 EHblkDsc* ehInitTryRange(BasicBlock* src, IL_OFFSET* tryBeg, IL_OFFSET* tryEnd);
2222 EHblkDsc* ehInitHndBlockRange(BasicBlock* blk, BasicBlock** hndBeg, BasicBlock** hndLast, bool* inFilter);
2224 EHblkDsc* ehInitTryBlockRange(BasicBlock* blk, BasicBlock** tryBeg, BasicBlock** tryLast);
2226 void fgSetTryEnd(EHblkDsc* handlerTab, BasicBlock* newTryLast);
2228 void fgSetHndEnd(EHblkDsc* handlerTab, BasicBlock* newHndLast);
2230 void fgSkipRmvdBlocks(EHblkDsc* handlerTab);
2232 void fgAllocEHTable();
2234 void fgRemoveEHTableEntry(unsigned XTnum);
2236 #if FEATURE_EH_FUNCLETS
2238 EHblkDsc* fgAddEHTableEntry(unsigned XTnum);
2240 #endif // FEATURE_EH_FUNCLETS
2244 #endif // !FEATURE_EH
2246 void fgSortEHTable();
2248 // Causes the EH table to obey some well-formedness conditions, by inserting
2249 // empty BB's when necessary:
2250 // * No block is both the first block of a handler and the first block of a try.
2251 // * No block is the first block of multiple 'try' regions.
2252 // * No block is the last block of multiple EH regions.
2253 void fgNormalizeEH();
2254 bool fgNormalizeEHCase1();
2255 bool fgNormalizeEHCase2();
2256 bool fgNormalizeEHCase3();
2259 void dispIncomingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
2260 void dispOutgoingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
2261 void fgVerifyHandlerTab();
2262 void fgDispHandlerTab();
2265 bool fgNeedToSortEHTable;
2267 void verInitEHTree(unsigned numEHClauses);
2268 void verInsertEhNode(CORINFO_EH_CLAUSE* clause, EHblkDsc* handlerTab);
2269 void verInsertEhNodeInTree(EHNodeDsc** ppRoot, EHNodeDsc* node);
2270 void verInsertEhNodeParent(EHNodeDsc** ppRoot, EHNodeDsc* node);
2271 void verCheckNestingLevel(EHNodeDsc* initRoot);
2274 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2275 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2277 XX GenTree and BasicBlock XX
2279 XX Functions to allocate and display the GenTrees and BasicBlocks XX
2281 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2282 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2285 // Functions to create nodes
2286 GenTreeStmt* gtNewStmt(GenTree* expr = nullptr, IL_OFFSETX offset = BAD_IL_OFFSET);
2289 GenTree* gtNewOperNode(genTreeOps oper, var_types type, GenTree* op1, bool doSimplifications = TRUE);
2291 // For binary opers.
2292 GenTree* gtNewOperNode(genTreeOps oper, var_types type, GenTree* op1, GenTree* op2);
2294 GenTree* gtNewQmarkNode(var_types type, GenTree* cond, GenTree* colon);
2296 GenTree* gtNewLargeOperNode(genTreeOps oper,
2297 var_types type = TYP_I_IMPL,
2298 GenTree* op1 = nullptr,
2299 GenTree* op2 = nullptr);
2301 GenTreeIntCon* gtNewIconNode(ssize_t value, var_types type = TYP_INT);
2303 GenTree* gtNewPhysRegNode(regNumber reg, var_types type);
2305 GenTree* gtNewJmpTableNode();
2307 GenTree* gtNewIndOfIconHandleNode(var_types indType, size_t value, unsigned iconFlags, bool isInvariant);
2309 GenTree* gtNewIconHandleNode(size_t value, unsigned flags, FieldSeqNode* fields = nullptr);
2311 unsigned gtTokenToIconFlags(unsigned token);
2313 GenTree* gtNewIconEmbHndNode(void* value, void* pValue, unsigned flags, void* compileTimeHandle);
2315 GenTree* gtNewIconEmbScpHndNode(CORINFO_MODULE_HANDLE scpHnd);
2316 GenTree* gtNewIconEmbClsHndNode(CORINFO_CLASS_HANDLE clsHnd);
2317 GenTree* gtNewIconEmbMethHndNode(CORINFO_METHOD_HANDLE methHnd);
2318 GenTree* gtNewIconEmbFldHndNode(CORINFO_FIELD_HANDLE fldHnd);
2320 GenTree* gtNewStringLiteralNode(InfoAccessType iat, void* pValue);
2322 GenTree* gtNewLconNode(__int64 value);
2324 GenTree* gtNewDconNode(double value);
2326 GenTree* gtNewSconNode(int CPX, CORINFO_MODULE_HANDLE scpHandle);
2328 GenTree* gtNewZeroConNode(var_types type);
2330 GenTree* gtNewOneConNode(var_types type);
2333 GenTree* gtNewSIMDVectorZero(var_types simdType, var_types baseType, unsigned size);
2334 GenTree* gtNewSIMDVectorOne(var_types simdType, var_types baseType, unsigned size);
2337 GenTree* gtNewBlkOpNode(GenTree* dst, GenTree* srcOrFillVal, unsigned size, bool isVolatile, bool isCopyBlock);
2339 GenTree* gtNewPutArgReg(var_types type, GenTree* arg, regNumber argReg);
2341 GenTree* gtNewBitCastNode(var_types type, GenTree* arg);
2344 void gtBlockOpInit(GenTree* result, GenTree* dst, GenTree* srcOrFillVal, bool isVolatile);
2347 GenTree* gtNewObjNode(CORINFO_CLASS_HANDLE structHnd, GenTree* addr);
2348 void gtSetObjGcInfo(GenTreeObj* objNode);
2349 GenTree* gtNewStructVal(CORINFO_CLASS_HANDLE structHnd, GenTree* addr);
2350 GenTree* gtNewBlockVal(GenTree* addr, unsigned size);
2352 GenTree* gtNewCpObjNode(GenTree* dst, GenTree* src, CORINFO_CLASS_HANDLE structHnd, bool isVolatile);
2354 GenTreeArgList* gtNewListNode(GenTree* op1, GenTreeArgList* op2);
2356 GenTreeCall* gtNewCallNode(gtCallTypes callType,
2357 CORINFO_METHOD_HANDLE handle,
2359 GenTreeArgList* args,
2360 IL_OFFSETX ilOffset = BAD_IL_OFFSET);
2362 GenTreeCall* gtNewIndCallNode(GenTree* addr,
2364 GenTreeArgList* args,
2365 IL_OFFSETX ilOffset = BAD_IL_OFFSET);
2367 GenTreeCall* gtNewHelperCallNode(unsigned helper, var_types type, GenTreeArgList* args = nullptr);
2369 GenTree* gtNewLclvNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
2372 GenTreeSIMD* gtNewSIMDNode(
2373 var_types type, GenTree* op1, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
2374 GenTreeSIMD* gtNewSIMDNode(
2375 var_types type, GenTree* op1, GenTree* op2, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
2376 void SetOpLclRelatedToSIMDIntrinsic(GenTree* op);
2379 #ifdef FEATURE_HW_INTRINSICS
2380 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types type,
2381 NamedIntrinsic hwIntrinsicID,
2384 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(
2385 var_types type, GenTree* op1, NamedIntrinsic hwIntrinsicID, var_types baseType, unsigned size);
2386 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(
2387 var_types type, GenTree* op1, GenTree* op2, NamedIntrinsic hwIntrinsicID, var_types baseType, unsigned size);
2388 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types type,
2392 NamedIntrinsic hwIntrinsicID,
2395 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types type,
2400 NamedIntrinsic hwIntrinsicID,
2403 GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types type, GenTree* op1, NamedIntrinsic hwIntrinsicID);
2404 GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types type,
2407 NamedIntrinsic hwIntrinsicID);
2408 GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(
2409 var_types type, GenTree* op1, GenTree* op2, GenTree* op3, NamedIntrinsic hwIntrinsicID);
2410 GenTree* gtNewMustThrowException(unsigned helper, var_types type, CORINFO_CLASS_HANDLE clsHnd);
2411 CORINFO_CLASS_HANDLE gtGetStructHandleForHWSIMD(var_types simdType, var_types simdBaseType);
2412 #endif // FEATURE_HW_INTRINSICS
2414 GenTree* gtNewLclLNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
2415 GenTreeLclFld* gtNewLclFldNode(unsigned lnum, var_types type, unsigned offset);
2416 GenTree* gtNewInlineCandidateReturnExpr(GenTree* inlineCandidate, var_types type);
2418 GenTree* gtNewCodeRef(BasicBlock* block);
2420 GenTree* gtNewFieldRef(var_types typ, CORINFO_FIELD_HANDLE fldHnd, GenTree* obj = nullptr, DWORD offset = 0);
2422 GenTree* gtNewIndexRef(var_types typ, GenTree* arrayOp, GenTree* indexOp);
2424 GenTreeArrLen* gtNewArrLen(var_types typ, GenTree* arrayOp, int lenOffset);
2426 GenTree* gtNewIndir(var_types typ, GenTree* addr);
2428 GenTreeArgList* gtNewArgList(GenTree* op);
2429 GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2);
2430 GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2, GenTree* op3);
2431 GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2, GenTree* op3, GenTree* op4);
2433 static fgArgTabEntry* gtArgEntryByArgNum(GenTreeCall* call, unsigned argNum);
2434 static fgArgTabEntry* gtArgEntryByNode(GenTreeCall* call, GenTree* node);
2435 fgArgTabEntry* gtArgEntryByLateArgIndex(GenTreeCall* call, unsigned lateArgInx);
2436 static GenTree* gtArgNodeByLateArgInx(GenTreeCall* call, unsigned lateArgInx);
2437 bool gtArgIsThisPtr(fgArgTabEntry* argEntry);
2439 GenTree* gtNewAssignNode(GenTree* dst, GenTree* src);
2441 GenTree* gtNewTempAssign(unsigned tmp, GenTree* val);
2443 GenTree* gtNewRefCOMfield(GenTree* objPtr,
2444 CORINFO_RESOLVED_TOKEN* pResolvedToken,
2445 CORINFO_ACCESS_FLAGS access,
2446 CORINFO_FIELD_INFO* pFieldInfo,
2448 CORINFO_CLASS_HANDLE structType,
2451 GenTree* gtNewNothingNode();
2453 GenTree* gtNewArgPlaceHolderNode(var_types type, CORINFO_CLASS_HANDLE clsHnd);
2455 GenTree* gtUnusedValNode(GenTree* expr);
2457 GenTreeCast* gtNewCastNode(var_types typ, GenTree* op1, bool fromUnsigned, var_types castType);
2459 GenTreeCast* gtNewCastNodeL(var_types typ, GenTree* op1, bool fromUnsigned, var_types castType);
2461 GenTree* gtNewAllocObjNode(unsigned int helper, CORINFO_CLASS_HANDLE clsHnd, var_types type, GenTree* op1);
2463 GenTree* gtNewRuntimeLookup(CORINFO_GENERIC_HANDLE hnd, CorInfoGenericHandleType hndTyp, GenTree* lookupTree);
2465 //------------------------------------------------------------------------
2466 // Other GenTree functions
2468 GenTree* gtClone(GenTree* tree, bool complexOK = false);
2470 // If `tree` is a lclVar with lclNum `varNum`, return an IntCns with value `varVal`; otherwise,
2471 // create a copy of `tree`, adding specified flags, replacing uses of lclVar `deepVarNum` with
2472 // IntCnses with value `deepVarVal`.
2473 GenTree* gtCloneExpr(
2474 GenTree* tree, unsigned addFlags, unsigned varNum, int varVal, unsigned deepVarNum, int deepVarVal);
2476 // Create a copy of `tree`, optionally adding specifed flags, and optionally mapping uses of local
2477 // `varNum` to int constants with value `varVal`.
2478 GenTree* gtCloneExpr(GenTree* tree, unsigned addFlags = 0, unsigned varNum = (unsigned)-1, int varVal = 0)
2480 return gtCloneExpr(tree, addFlags, varNum, varVal, varNum, varVal);
2483 GenTree* gtReplaceTree(GenTree* stmt, GenTree* tree, GenTree* replacementTree);
2485 void gtUpdateSideEffects(GenTree* stmt, GenTree* tree);
2487 void gtUpdateTreeAncestorsSideEffects(GenTree* tree);
2489 void gtUpdateStmtSideEffects(GenTree* stmt);
2491 void gtUpdateNodeSideEffects(GenTree* tree);
2493 void gtUpdateNodeOperSideEffects(GenTree* tree);
2495 // Returns "true" iff the complexity (not formally defined, but first interpretation
2496 // is #of nodes in subtree) of "tree" is greater than "limit".
2497 // (This is somewhat redundant with the "gtCostEx/gtCostSz" fields, but can be used
2498 // before they have been set.)
2499 bool gtComplexityExceeds(GenTree** tree, unsigned limit);
2501 bool gtCompareTree(GenTree* op1, GenTree* op2);
2503 GenTree* gtReverseCond(GenTree* tree);
2505 bool gtHasRef(GenTree* tree, ssize_t lclNum, bool defOnly);
2507 bool gtHasLocalsWithAddrOp(GenTree* tree);
2509 unsigned gtSetListOrder(GenTree* list, bool regs, bool isListCallArgs);
2511 void gtWalkOp(GenTree** op1, GenTree** op2, GenTree* base, bool constOnly);
2514 unsigned gtHashValue(GenTree* tree);
2516 GenTree* gtWalkOpEffectiveVal(GenTree* op);
2519 void gtPrepareCost(GenTree* tree);
2520 bool gtIsLikelyRegVar(GenTree* tree);
2522 // Returns true iff the secondNode can be swapped with firstNode.
2523 bool gtCanSwapOrder(GenTree* firstNode, GenTree* secondNode);
2525 unsigned gtSetEvalOrder(GenTree* tree);
2527 void gtSetStmtInfo(GenTree* stmt);
2529 // Returns "true" iff "node" has any of the side effects in "flags".
2530 bool gtNodeHasSideEffects(GenTree* node, unsigned flags);
2532 // Returns "true" iff "tree" or its (transitive) children have any of the side effects in "flags".
2533 bool gtTreeHasSideEffects(GenTree* tree, unsigned flags);
2535 // Appends 'expr' in front of 'list'
2536 // 'list' will typically start off as 'nullptr'
2537 // when 'list' is non-null a GT_COMMA node is used to insert 'expr'
2538 GenTree* gtBuildCommaList(GenTree* list, GenTree* expr);
2540 void gtExtractSideEffList(GenTree* expr,
2542 unsigned flags = GTF_SIDE_EFFECT,
2543 bool ignoreRoot = false);
2545 GenTree* gtGetThisArg(GenTreeCall* call);
2547 // Static fields of struct types (and sometimes the types that those are reduced to) are represented by having the
2548 // static field contain an object pointer to the boxed struct. This simplifies the GC implementation...but
2549 // complicates the JIT somewhat. This predicate returns "true" iff a node with type "fieldNodeType", representing
2550 // the given "fldHnd", is such an object pointer.
2551 bool gtIsStaticFieldPtrToBoxedStruct(var_types fieldNodeType, CORINFO_FIELD_HANDLE fldHnd);
2553 // Return true if call is a recursive call; return false otherwise.
2554 // Note when inlining, this looks for calls back to the root method.
2555 bool gtIsRecursiveCall(GenTreeCall* call)
2557 return gtIsRecursiveCall(call->gtCallMethHnd);
2560 bool gtIsRecursiveCall(CORINFO_METHOD_HANDLE callMethodHandle)
2562 return (callMethodHandle == impInlineRoot()->info.compMethodHnd);
2565 //-------------------------------------------------------------------------
2567 GenTree* gtFoldExpr(GenTree* tree);
2570 // TODO-Amd64-Unix: Remove this when the clang optimizer is fixed and/or the method implementation is
2571 // refactored in a simpler code. This is a workaround for a bug in the clang-3.5 optimizer. The issue is that in
2572 // release build the optimizer is mistyping (or just wrongly decides to use 32 bit operation for a corner case
2573 // of MIN_LONG) the args of the (ltemp / lval2) to int (it does a 32 bit div operation instead of 64 bit) - see
2574 // the implementation of the method in gentree.cpp. For the case of lval1 and lval2 equal to MIN_LONG
2575 // (0x8000000000000000) this results in raising a SIGFPE. The method implementation is rather complex. Disable
2576 // optimizations for now.
2577 __attribute__((optnone))
2579 gtFoldExprConst(GenTree* tree);
2580 GenTree* gtFoldExprSpecial(GenTree* tree);
2581 GenTree* gtFoldExprCompare(GenTree* tree);
2582 GenTree* gtFoldExprCall(GenTreeCall* call);
2583 GenTree* gtFoldTypeCompare(GenTree* tree);
2584 GenTree* gtFoldTypeEqualityCall(CorInfoIntrinsics methodID, GenTree* op1, GenTree* op2);
2586 // Options to control behavior of gtTryRemoveBoxUpstreamEffects
2587 enum BoxRemovalOptions
2589 BR_REMOVE_AND_NARROW, // remove effects, minimize remaining work, return possibly narrowed source tree
2590 BR_REMOVE_AND_NARROW_WANT_TYPE_HANDLE, // remove effects and minimize remaining work, return type handle tree
2591 BR_REMOVE_BUT_NOT_NARROW, // remove effects, return original source tree
2592 BR_DONT_REMOVE, // check if removal is possible, return copy source tree
2593 BR_DONT_REMOVE_WANT_TYPE_HANDLE, // check if removal is possible, return type handle tree
2594 BR_MAKE_LOCAL_COPY // revise box to copy to temp local and return local's address
2597 GenTree* gtTryRemoveBoxUpstreamEffects(GenTree* tree, BoxRemovalOptions options = BR_REMOVE_AND_NARROW);
2598 GenTree* gtOptimizeEnumHasFlag(GenTree* thisOp, GenTree* flagOp);
2600 //-------------------------------------------------------------------------
2601 // Get the handle, if any.
2602 CORINFO_CLASS_HANDLE gtGetStructHandleIfPresent(GenTree* tree);
2603 // Get the handle, and assert if not found.
2604 CORINFO_CLASS_HANDLE gtGetStructHandle(GenTree* tree);
2605 // Get the handle for a ref type.
2606 CORINFO_CLASS_HANDLE gtGetClassHandle(GenTree* tree, bool* isExact, bool* isNonNull);
2607 // Get the class handle for an helper call
2608 CORINFO_CLASS_HANDLE gtGetHelperCallClassHandle(GenTreeCall* call, bool* isExact, bool* isNonNull);
2609 // Get the element handle for an array of ref type.
2610 CORINFO_CLASS_HANDLE gtGetArrayElementClassHandle(GenTree* array);
2611 // Get a class handle from a helper call argument
2612 CORINFO_CLASS_HANDLE gtGetHelperArgClassHandle(GenTree* array,
2613 unsigned* runtimeLookupCount = nullptr,
2614 GenTree** handleTree = nullptr);
2615 // Check if this tree is a gc static base helper call
2616 bool gtIsStaticGCBaseHelperCall(GenTree* tree);
2618 //-------------------------------------------------------------------------
2619 // Functions to display the trees
2622 void gtDispNode(GenTree* tree, IndentStack* indentStack, __in_z const char* msg, bool isLIR);
2624 void gtDispVN(GenTree* tree);
2625 void gtDispConst(GenTree* tree);
2626 void gtDispLeaf(GenTree* tree, IndentStack* indentStack);
2627 void gtDispNodeName(GenTree* tree);
2628 void gtDispRegVal(GenTree* tree);
2640 void gtDispChild(GenTree* child,
2641 IndentStack* indentStack,
2643 __in_opt const char* msg = nullptr,
2644 bool topOnly = false);
2645 void gtDispTree(GenTree* tree,
2646 IndentStack* indentStack = nullptr,
2647 __in_opt const char* msg = nullptr,
2648 bool topOnly = false,
2649 bool isLIR = false);
2650 void gtGetLclVarNameInfo(unsigned lclNum, const char** ilKindOut, const char** ilNameOut, unsigned* ilNumOut);
2651 int gtGetLclVarName(unsigned lclNum, char* buf, unsigned buf_remaining);
2652 char* gtGetLclVarName(unsigned lclNum);
2653 void gtDispLclVar(unsigned varNum, bool padForBiggestDisp = true);
2654 void gtDispTreeList(GenTree* tree, IndentStack* indentStack = nullptr);
2655 void gtGetArgMsg(GenTreeCall* call, GenTree* arg, unsigned argNum, int listCount, char* bufp, unsigned bufLength);
2656 void gtGetLateArgMsg(GenTreeCall* call, GenTree* arg, int argNum, int listCount, char* bufp, unsigned bufLength);
2657 void gtDispArgList(GenTreeCall* call, IndentStack* indentStack);
2658 void gtDispFieldSeq(FieldSeqNode* pfsn);
2660 void gtDispRange(LIR::ReadOnlyRange const& range);
2662 void gtDispTreeRange(LIR::Range& containingRange, GenTree* tree);
2664 void gtDispLIRNode(GenTree* node, const char* prefixMsg = nullptr);
2676 typedef fgWalkResult(fgWalkPreFn)(GenTree** pTree, fgWalkData* data);
2677 typedef fgWalkResult(fgWalkPostFn)(GenTree** pTree, fgWalkData* data);
2680 static fgWalkPreFn gtAssertColonCond;
2682 static fgWalkPreFn gtMarkColonCond;
2683 static fgWalkPreFn gtClearColonCond;
2685 GenTree** gtFindLink(GenTree* stmt, GenTree* node);
2686 bool gtHasCatchArg(GenTree* tree);
2688 typedef ArrayStack<GenTree*> GenTreeStack;
2690 static bool gtHasCallOnStack(GenTreeStack* parentStack);
2692 //=========================================================================
2693 // BasicBlock functions
2695 // This is a debug flag we will use to assert when creating block during codegen
2696 // as this interferes with procedure splitting. If you know what you're doing, set
2697 // it to true before creating the block. (DEBUG only)
2698 bool fgSafeBasicBlockCreation;
2701 BasicBlock* bbNewBasicBlock(BBjumpKinds jumpKind);
2704 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2705 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2709 XX The variables to be used by the code generator. XX
2711 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2712 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2716 // For both PROMOTION_TYPE_NONE and PROMOTION_TYPE_DEPENDENT the struct will
2717 // be placed in the stack frame and it's fields must be laid out sequentially.
2719 // For PROMOTION_TYPE_INDEPENDENT each of the struct's fields is replaced by
2720 // a local variable that can be enregistered or placed in the stack frame.
2721 // The fields do not need to be laid out sequentially
2723 enum lvaPromotionType
2725 PROMOTION_TYPE_NONE, // The struct local is not promoted
2726 PROMOTION_TYPE_INDEPENDENT, // The struct local is promoted,
2727 // and its field locals are independent of its parent struct local.
2728 PROMOTION_TYPE_DEPENDENT // The struct local is promoted,
2729 // but its field locals depend on its parent struct local.
2732 static int __cdecl RefCntCmp(const void* op1, const void* op2);
2733 static int __cdecl WtdRefCntCmp(const void* op1, const void* op2);
2735 /*****************************************************************************/
2737 enum FrameLayoutState
2740 INITIAL_FRAME_LAYOUT,
2741 PRE_REGALLOC_FRAME_LAYOUT,
2742 REGALLOC_FRAME_LAYOUT,
2743 TENTATIVE_FRAME_LAYOUT,
2748 RefCountState lvaRefCountState; // Current local ref count state
2750 bool lvaLocalVarRefCounted() const
2752 return lvaRefCountState == RCS_NORMAL;
2755 bool lvaTrackedFixed; // true: We cannot add new 'tracked' variable
2756 unsigned lvaCount; // total number of locals
2758 unsigned lvaRefCount; // total number of references to locals
2759 LclVarDsc* lvaTable; // variable descriptor table
2760 unsigned lvaTableCnt; // lvaTable size (>= lvaCount)
2762 LclVarDsc** lvaRefSorted; // table sorted by refcount
2764 unsigned short lvaTrackedCount; // actual # of locals being tracked
2765 unsigned lvaTrackedCountInSizeTUnits; // min # of size_t's sufficient to hold a bit for all the locals being tracked
2768 VARSET_TP lvaTrackedVars; // set of tracked variables
2770 #ifndef _TARGET_64BIT_
2771 VARSET_TP lvaLongVars; // set of long (64-bit) variables
2773 VARSET_TP lvaFloatVars; // set of floating-point (32-bit and 64-bit) variables
2775 unsigned lvaCurEpoch; // VarSets are relative to a specific set of tracked var indices.
2776 // It that changes, this changes. VarSets from different epochs
2777 // cannot be meaningfully combined.
2779 unsigned GetCurLVEpoch()
2784 // reverse map of tracked number to var number
2785 unsigned* lvaTrackedToVarNum;
2789 // # of procs compiled a with double-aligned stack
2790 static unsigned s_lvaDoubleAlignedProcsCount;
2794 // Getters and setters for address-exposed and do-not-enregister local var properties.
2795 bool lvaVarAddrExposed(unsigned varNum);
2796 void lvaSetVarAddrExposed(unsigned varNum);
2797 bool lvaVarDoNotEnregister(unsigned varNum);
2799 // Reasons why we can't enregister. Some of these correspond to debug properties of local vars.
2800 enum DoNotEnregisterReason
2805 DNER_VMNeedsStackAddr,
2806 DNER_LiveInOutOfHandler,
2807 DNER_LiveAcrossUnmanagedCall,
2808 DNER_BlockOp, // Is read or written via a block operation that explicitly takes the address.
2809 DNER_IsStructArg, // Is a struct passed as an argument in a way that requires a stack location.
2810 DNER_DepField, // It is a field of a dependently promoted struct
2811 DNER_NoRegVars, // opts.compFlags & CLFLG_REGVAR is not set
2812 DNER_MinOptsGC, // It is a GC Ref and we are compiling MinOpts
2813 #if !defined(_TARGET_64BIT_)
2814 DNER_LongParamField, // It is a decomposed field of a long parameter.
2816 #ifdef JIT32_GCENCODER
2821 void lvaSetVarDoNotEnregister(unsigned varNum DEBUGARG(DoNotEnregisterReason reason));
2823 unsigned lvaVarargsHandleArg;
2825 unsigned lvaVarargsBaseOfStkArgs; // Pointer (computed based on incoming varargs handle) to the start of the stack
2827 #endif // _TARGET_X86_
2829 unsigned lvaInlinedPInvokeFrameVar; // variable representing the InlinedCallFrame
2830 unsigned lvaReversePInvokeFrameVar; // variable representing the reverse PInvoke frame
2831 #if FEATURE_FIXED_OUT_ARGS
2832 unsigned lvaPInvokeFrameRegSaveVar; // variable representing the RegSave for PInvoke inlining.
2834 unsigned lvaMonAcquired; // boolean variable introduced into in synchronized methods
2835 // that tracks whether the lock has been taken
2837 unsigned lvaArg0Var; // The lclNum of arg0. Normally this will be info.compThisArg.
2838 // However, if there is a "ldarga 0" or "starg 0" in the IL,
2839 // we will redirect all "ldarg(a) 0" and "starg 0" to this temp.
2841 unsigned lvaInlineeReturnSpillTemp; // The temp to spill the non-VOID return expression
2842 // in case there are multiple BBJ_RETURN blocks in the inlinee
2843 // or if the inlinee has GC ref locals.
2845 #if FEATURE_FIXED_OUT_ARGS
2846 unsigned lvaOutgoingArgSpaceVar; // dummy TYP_LCLBLK var for fixed outgoing argument space
2847 PhasedVar<unsigned> lvaOutgoingArgSpaceSize; // size of fixed outgoing argument space
2848 #endif // FEATURE_FIXED_OUT_ARGS
2851 // On architectures whose ABIs allow structs to be passed in registers, struct promotion will sometimes
2852 // require us to "rematerialize" a struct from it's separate constituent field variables. Packing several sub-word
2853 // field variables into an argument register is a hard problem. It's easier to reserve a word of memory into which
2854 // such field can be copied, after which the assembled memory word can be read into the register. We will allocate
2855 // this variable to be this scratch word whenever struct promotion occurs.
2856 unsigned lvaPromotedStructAssemblyScratchVar;
2857 #endif // _TARGET_ARM_
2860 unsigned lvaReturnEspCheck; // confirms ESP not corrupted on return
2861 unsigned lvaCallEspCheck; // confirms ESP not corrupted after a call
2864 unsigned lvaGenericsContextUseCount;
2866 bool lvaKeepAliveAndReportThis(); // Synchronized instance method of a reference type, or
2867 // CORINFO_GENERICS_CTXT_FROM_THIS?
2868 bool lvaReportParamTypeArg(); // Exceptions and CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG?
2870 //-------------------------------------------------------------------------
2871 // All these frame offsets are inter-related and must be kept in sync
2873 #if !FEATURE_EH_FUNCLETS
2874 // This is used for the callable handlers
2875 unsigned lvaShadowSPslotsVar; // TYP_BLK variable for all the shadow SP slots
2876 #endif // FEATURE_EH_FUNCLETS
2878 int lvaCachedGenericContextArgOffs;
2879 int lvaCachedGenericContextArgOffset(); // For CORINFO_CALLCONV_PARAMTYPE and if generic context is passed as
2882 #ifdef JIT32_GCENCODER
2884 unsigned lvaLocAllocSPvar; // variable which stores the value of ESP after the the last alloca/localloc
2886 #endif // JIT32_GCENCODER
2888 unsigned lvaNewObjArrayArgs; // variable with arguments for new MD array helper
2890 // TODO-Review: Prior to reg predict we reserve 24 bytes for Spill temps.
2891 // after the reg predict we will use a computed maxTmpSize
2892 // which is based upon the number of spill temps predicted by reg predict
2893 // All this is necessary because if we under-estimate the size of the spill
2894 // temps we could fail when encoding instructions that reference stack offsets for ARM.
2896 // Pre codegen max spill temp size.
2897 static const unsigned MAX_SPILL_TEMP_SIZE = 24;
2899 //-------------------------------------------------------------------------
2901 unsigned lvaGetMaxSpillTempSize();
2903 bool lvaIsPreSpilled(unsigned lclNum, regMaskTP preSpillMask);
2904 #endif // _TARGET_ARM_
2905 void lvaAssignFrameOffsets(FrameLayoutState curState);
2906 void lvaFixVirtualFrameOffsets();
2907 void lvaUpdateArgsWithInitialReg();
2908 void lvaAssignVirtualFrameOffsetsToArgs();
2909 #ifdef UNIX_AMD64_ABI
2910 int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs, int* callerArgOffset);
2911 #else // !UNIX_AMD64_ABI
2912 int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs);
2913 #endif // !UNIX_AMD64_ABI
2914 void lvaAssignVirtualFrameOffsetsToLocals();
2915 int lvaAllocLocalAndSetVirtualOffset(unsigned lclNum, unsigned size, int stkOffs);
2916 #ifdef _TARGET_AMD64_
2917 // Returns true if compCalleeRegsPushed (including RBP if used as frame pointer) is even.
2918 bool lvaIsCalleeSavedIntRegCountEven();
2920 void lvaAlignFrame();
2921 void lvaAssignFrameOffsetsToPromotedStructs();
2922 int lvaAllocateTemps(int stkOffs, bool mustDoubleAlign);
2925 void lvaDumpRegLocation(unsigned lclNum);
2926 void lvaDumpFrameLocation(unsigned lclNum);
2927 void lvaDumpEntry(unsigned lclNum, FrameLayoutState curState, size_t refCntWtdWidth = 6);
2928 void lvaTableDump(FrameLayoutState curState = NO_FRAME_LAYOUT); // NO_FRAME_LAYOUT means use the current frame
2929 // layout state defined by lvaDoneFrameLayout
2932 // Limit frames size to 1GB. The maximum is 2GB in theory - make it intentionally smaller
2933 // to avoid bugs from borderline cases.
2934 #define MAX_FrameSize 0x3FFFFFFF
2935 void lvaIncrementFrameSize(unsigned size);
2937 unsigned lvaFrameSize(FrameLayoutState curState);
2939 // Returns the caller-SP-relative offset for the SP/FP relative offset determined by FP based.
2940 int lvaToCallerSPRelativeOffset(int offs, bool isFpBased);
2942 // Returns the caller-SP-relative offset for the local variable "varNum."
2943 int lvaGetCallerSPRelativeOffset(unsigned varNum);
2945 // Returns the SP-relative offset for the local variable "varNum". Illegal to ask this for functions with localloc.
2946 int lvaGetSPRelativeOffset(unsigned varNum);
2948 int lvaToInitialSPRelativeOffset(unsigned offset, bool isFpBased);
2949 int lvaGetInitialSPRelativeOffset(unsigned varNum);
2951 //------------------------ For splitting types ----------------------------
2953 void lvaInitTypeRef();
2955 void lvaInitArgs(InitVarDscInfo* varDscInfo);
2956 void lvaInitThisPtr(InitVarDscInfo* varDscInfo);
2957 void lvaInitRetBuffArg(InitVarDscInfo* varDscInfo);
2958 void lvaInitUserArgs(InitVarDscInfo* varDscInfo);
2959 void lvaInitGenericsCtxt(InitVarDscInfo* varDscInfo);
2960 void lvaInitVarArgsHandle(InitVarDscInfo* varDscInfo);
2962 void lvaInitVarDsc(LclVarDsc* varDsc,
2964 CorInfoType corInfoType,
2965 CORINFO_CLASS_HANDLE typeHnd,
2966 CORINFO_ARG_LIST_HANDLE varList,
2967 CORINFO_SIG_INFO* varSig);
2969 static unsigned lvaTypeRefMask(var_types type);
2971 var_types lvaGetActualType(unsigned lclNum);
2972 var_types lvaGetRealType(unsigned lclNum);
2974 //-------------------------------------------------------------------------
2978 LclVarDsc* lvaGetDesc(unsigned lclNum)
2980 assert(lclNum < lvaCount);
2981 return &lvaTable[lclNum];
2984 LclVarDsc* lvaGetDesc(GenTreeLclVarCommon* lclVar)
2986 assert(lclVar->GetLclNum() < lvaCount);
2987 return &lvaTable[lclVar->GetLclNum()];
2990 unsigned lvaLclSize(unsigned varNum);
2991 unsigned lvaLclExactSize(unsigned varNum);
2993 bool lvaHaveManyLocals() const;
2995 unsigned lvaGrabTemp(bool shortLifetime DEBUGARG(const char* reason));
2996 unsigned lvaGrabTemps(unsigned cnt DEBUGARG(const char* reason));
2997 unsigned lvaGrabTempWithImplicitUse(bool shortLifetime DEBUGARG(const char* reason));
3000 void lvaSortByRefCount();
3001 void lvaDumpRefCounts();
3003 void lvaMarkLocalVars(); // Local variable ref-counting
3004 void lvaComputeRefCounts(bool isRecompute, bool setSlotNumbers);
3005 void lvaMarkLocalVars(BasicBlock* block, bool isRecompute);
3007 void lvaAllocOutgoingArgSpaceVar(); // Set up lvaOutgoingArgSpaceVar
3009 VARSET_VALRET_TP lvaStmtLclMask(GenTree* stmt);
3012 struct lvaStressLclFldArgs
3014 Compiler* m_pCompiler;
3018 static fgWalkPreFn lvaStressLclFldCB;
3019 void lvaStressLclFld();
3021 void lvaDispVarSet(VARSET_VALARG_TP set, VARSET_VALARG_TP allVars);
3022 void lvaDispVarSet(VARSET_VALARG_TP set);
3027 int lvaFrameAddress(int varNum, bool mustBeFPBased, regNumber* pBaseReg, int addrModeOffset);
3029 int lvaFrameAddress(int varNum, bool* pFPbased);
3032 bool lvaIsParameter(unsigned varNum);
3033 bool lvaIsRegArgument(unsigned varNum);
3034 BOOL lvaIsOriginalThisArg(unsigned varNum); // Is this varNum the original this argument?
3035 BOOL lvaIsOriginalThisReadOnly(); // return TRUE if there is no place in the code
3036 // that writes to arg0
3038 // Struct parameters that are passed by reference are marked as both lvIsParam and lvIsTemp
3039 // (this is an overload of lvIsTemp because there are no temp parameters).
3040 // For x64 this is 3, 5, 6, 7, >8 byte structs that are passed by reference.
3041 // For ARM64, this is structs larger than 16 bytes that are passed by reference.
3042 bool lvaIsImplicitByRefLocal(unsigned varNum)
3044 #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
3045 LclVarDsc* varDsc = &(lvaTable[varNum]);
3046 if (varDsc->lvIsParam && varDsc->lvIsTemp)
3048 assert(varTypeIsStruct(varDsc) || (varDsc->lvType == TYP_BYREF));
3051 #endif // defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
3055 // Returns true if this local var is a multireg struct
3056 bool lvaIsMultiregStruct(LclVarDsc* varDsc, bool isVararg);
3058 // If the local is a TYP_STRUCT, get/set a class handle describing it
3059 CORINFO_CLASS_HANDLE lvaGetStruct(unsigned varNum);
3060 void lvaSetStruct(unsigned varNum, CORINFO_CLASS_HANDLE typeHnd, bool unsafeValueClsCheck, bool setTypeInfo = true);
3061 void lvaSetStructUsedAsVarArg(unsigned varNum);
3063 // If the local is TYP_REF, set or update the associated class information.
3064 void lvaSetClass(unsigned varNum, CORINFO_CLASS_HANDLE clsHnd, bool isExact = false);
3065 void lvaSetClass(unsigned varNum, GenTree* tree, CORINFO_CLASS_HANDLE stackHandle = nullptr);
3066 void lvaUpdateClass(unsigned varNum, CORINFO_CLASS_HANDLE clsHnd, bool isExact = false);
3067 void lvaUpdateClass(unsigned varNum, GenTree* tree, CORINFO_CLASS_HANDLE stackHandle = nullptr);
3069 #define MAX_NumOfFieldsInPromotableStruct 4 // Maximum number of fields in promotable struct
3071 // Info about struct type fields.
3072 struct lvaStructFieldInfo
3074 CORINFO_FIELD_HANDLE fldHnd;
3075 unsigned char fldOffset;
3076 unsigned char fldOrdinal;
3079 CORINFO_CLASS_HANDLE fldTypeHnd;
3081 lvaStructFieldInfo()
3082 : fldHnd(nullptr), fldOffset(0), fldOrdinal(0), fldType(TYP_UNDEF), fldSize(0), fldTypeHnd(nullptr)
3087 // Info about a struct type, instances of which may be candidates for promotion.
3088 struct lvaStructPromotionInfo
3090 CORINFO_CLASS_HANDLE typeHnd;
3095 unsigned char fieldCnt;
3096 lvaStructFieldInfo fields[MAX_NumOfFieldsInPromotableStruct];
3098 lvaStructPromotionInfo(CORINFO_CLASS_HANDLE typeHnd = nullptr)
3101 , containsHoles(false)
3102 , customLayout(false)
3103 , fieldsSorted(false)
3109 static int __cdecl lvaFieldOffsetCmp(const void* field1, const void* field2);
3111 // This class is responsible for checking validity and profitability of struct promotion.
3112 // If it is both legal and profitable, then TryPromoteStructVar promotes the struct and initializes
3113 // nessesary information for fgMorphStructField to use.
3114 class StructPromotionHelper
3117 StructPromotionHelper(Compiler* compiler);
3119 bool CanPromoteStructType(CORINFO_CLASS_HANDLE typeHnd);
3120 bool TryPromoteStructVar(unsigned lclNum);
3123 void CheckRetypedAsScalar(CORINFO_FIELD_HANDLE fieldHnd, var_types requestedType);
3127 bool GetRequiresScratchVar();
3128 #endif // _TARGET_ARM_
3131 bool CanPromoteStructVar(unsigned lclNum);
3132 bool ShouldPromoteStructVar(unsigned lclNum);
3133 void PromoteStructVar(unsigned lclNum);
3134 void SortStructFields();
3136 lvaStructFieldInfo GetFieldInfo(CORINFO_FIELD_HANDLE fieldHnd, BYTE ordinal);
3137 bool TryPromoteStructField(lvaStructFieldInfo& outerFieldInfo);
3141 lvaStructPromotionInfo structPromotionInfo;
3144 bool requiresScratchVar;
3145 #endif // _TARGET_ARM_
3148 typedef JitHashTable<CORINFO_FIELD_HANDLE, JitPtrKeyFuncs<CORINFO_FIELD_STRUCT_>, var_types>
3149 RetypedAsScalarFieldsMap;
3150 RetypedAsScalarFieldsMap retypedFieldsMap;
3154 StructPromotionHelper* structPromotionHelper;
3156 #if !defined(_TARGET_64BIT_)
3157 void lvaPromoteLongVars();
3158 #endif // !defined(_TARGET_64BIT_)
3159 unsigned lvaGetFieldLocal(const LclVarDsc* varDsc, unsigned int fldOffset);
3160 lvaPromotionType lvaGetPromotionType(const LclVarDsc* varDsc);
3161 lvaPromotionType lvaGetPromotionType(unsigned varNum);
3162 lvaPromotionType lvaGetParentPromotionType(const LclVarDsc* varDsc);
3163 lvaPromotionType lvaGetParentPromotionType(unsigned varNum);
3164 bool lvaIsFieldOfDependentlyPromotedStruct(const LclVarDsc* varDsc);
3165 bool lvaIsGCTracked(const LclVarDsc* varDsc);
3167 #if defined(FEATURE_SIMD)
3168 bool lvaMapSimd12ToSimd16(const LclVarDsc* varDsc)
3170 assert(varDsc->lvType == TYP_SIMD12);
3171 assert(varDsc->lvExactSize == 12);
3173 #if defined(_TARGET_64BIT_)
3174 assert(varDsc->lvSize() == 16);
3175 #endif // defined(_TARGET_64BIT_)
3177 // We make local variable SIMD12 types 16 bytes instead of just 12. lvSize()
3178 // already does this calculation. However, we also need to prevent mapping types if the var is a
3179 // dependently promoted struct field, which must remain its exact size within its parent struct.
3180 // However, we don't know this until late, so we may have already pretended the field is bigger
3182 if ((varDsc->lvSize() == 16) && !lvaIsFieldOfDependentlyPromotedStruct(varDsc))
3191 #endif // defined(FEATURE_SIMD)
3193 BYTE* lvaGetGcLayout(unsigned varNum);
3194 bool lvaTypeIsGC(unsigned varNum);
3195 unsigned lvaGSSecurityCookie; // LclVar number
3196 bool lvaTempsHaveLargerOffsetThanVars();
3198 // Returns "true" iff local variable "lclNum" is in SSA form.
3199 bool lvaInSsa(unsigned lclNum)
3201 assert(lclNum < lvaCount);
3202 return lvaTable[lclNum].lvInSsa;
3205 unsigned lvaSecurityObject; // variable representing the security object on the stack
3206 unsigned lvaStubArgumentVar; // variable representing the secret stub argument coming in EAX
3208 #if FEATURE_EH_FUNCLETS
3209 unsigned lvaPSPSym; // variable representing the PSPSym
3212 InlineInfo* impInlineInfo;
3213 InlineStrategy* m_inlineStrategy;
3215 // The Compiler* that is the root of the inlining tree of which "this" is a member.
3216 Compiler* impInlineRoot();
3218 #if defined(DEBUG) || defined(INLINE_DATA)
3219 unsigned __int64 getInlineCycleCount()
3221 return m_compCycles;
3223 #endif // defined(DEBUG) || defined(INLINE_DATA)
3225 bool fgNoStructPromotion; // Set to TRUE to turn off struct promotion for this method.
3226 bool fgNoStructParamPromotion; // Set to TRUE to turn off struct promotion for parameters this method.
3228 //=========================================================================
3230 //=========================================================================
3233 //---------------- Local variable ref-counting ----------------------------
3235 void lvaMarkLclRefs(GenTree* tree, BasicBlock* block, GenTreeStmt* stmt, bool isRecompute);
3236 bool IsDominatedByExceptionalEntry(BasicBlock* block);
3237 void SetVolatileHint(LclVarDsc* varDsc);
3239 // Keeps the mapping from SSA #'s to VN's for the implicit memory variables.
3240 SsaDefArray<SsaMemDef> lvMemoryPerSsaData;
3243 // Returns the address of the per-Ssa data for memory at the given ssaNum (which is required
3244 // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
3245 // not an SSA variable).
3246 SsaMemDef* GetMemoryPerSsaData(unsigned ssaNum)
3248 return lvMemoryPerSsaData.GetSsaDef(ssaNum);
3252 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3253 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3257 XX Imports the given method and converts it to semantic trees XX
3259 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3260 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3266 void impImport(BasicBlock* method);
3268 CORINFO_CLASS_HANDLE impGetRefAnyClass();
3269 CORINFO_CLASS_HANDLE impGetRuntimeArgumentHandle();
3270 CORINFO_CLASS_HANDLE impGetTypeHandleClass();
3271 CORINFO_CLASS_HANDLE impGetStringClass();
3272 CORINFO_CLASS_HANDLE impGetObjectClass();
3274 // Returns underlying type of handles returned by ldtoken instruction
3275 inline var_types GetRuntimeHandleUnderlyingType()
3277 // RuntimeTypeHandle is backed by raw pointer on CoreRT and by object reference on other runtimes
3278 return IsTargetAbi(CORINFO_CORERT_ABI) ? TYP_I_IMPL : TYP_REF;
3281 //=========================================================================
3283 //=========================================================================
3286 //-------------------- Stack manipulation ---------------------------------
3288 unsigned impStkSize; // Size of the full stack
3290 #define SMALL_STACK_SIZE 16 // number of elements in impSmallStack
3292 struct SavedStack // used to save/restore stack contents.
3294 unsigned ssDepth; // number of values on stack
3295 StackEntry* ssTrees; // saved tree values
3298 bool impIsPrimitive(CorInfoType type);
3299 bool impILConsumesAddr(const BYTE* codeAddr, CORINFO_METHOD_HANDLE fncHandle, CORINFO_MODULE_HANDLE scpHandle);
3301 void impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind);
3303 void impPushOnStack(GenTree* tree, typeInfo ti);
3304 void impPushNullObjRefOnStack();
3305 StackEntry impPopStack();
3306 StackEntry& impStackTop(unsigned n = 0);
3307 unsigned impStackHeight();
3309 void impSaveStackState(SavedStack* savePtr, bool copy);
3310 void impRestoreStackState(SavedStack* savePtr);
3312 GenTree* impImportLdvirtftn(GenTree* thisPtr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
3314 void impImportAndPushBox(CORINFO_RESOLVED_TOKEN* pResolvedToken);
3316 void impImportNewObjArray(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
3318 bool impCanPInvokeInline();
3319 bool impCanPInvokeInlineCallSite(BasicBlock* block);
3320 void impCheckForPInvokeCall(
3321 GenTreeCall* call, CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* sig, unsigned mflags, BasicBlock* block);
3322 GenTreeCall* impImportIndirectCall(CORINFO_SIG_INFO* sig, IL_OFFSETX ilOffset = BAD_IL_OFFSET);
3323 void impPopArgsForUnmanagedCall(GenTree* call, CORINFO_SIG_INFO* sig);
3325 void impInsertHelperCall(CORINFO_HELPER_DESC* helperCall);
3326 void impHandleAccessAllowed(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
3327 void impHandleAccessAllowedInternal(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
3329 var_types impImportCall(OPCODE opcode,
3330 CORINFO_RESOLVED_TOKEN* pResolvedToken,
3331 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call on a
3333 GenTree* newobjThis,
3335 CORINFO_CALL_INFO* callInfo,
3336 IL_OFFSET rawILOffset);
3338 void impDevirtualizeCall(GenTreeCall* call,
3339 CORINFO_METHOD_HANDLE* method,
3340 unsigned* methodFlags,
3341 CORINFO_CONTEXT_HANDLE* contextHandle,
3342 CORINFO_CONTEXT_HANDLE* exactContextHandle);
3344 CORINFO_CLASS_HANDLE impGetSpecialIntrinsicExactReturnType(CORINFO_METHOD_HANDLE specialIntrinsicHandle);
3346 bool impMethodInfo_hasRetBuffArg(CORINFO_METHOD_INFO* methInfo);
3348 GenTree* impFixupCallStructReturn(GenTreeCall* call, CORINFO_CLASS_HANDLE retClsHnd);
3350 GenTree* impFixupStructReturnType(GenTree* op, CORINFO_CLASS_HANDLE retClsHnd);
3353 var_types impImportJitTestLabelMark(int numArgs);
3356 GenTree* impInitClass(CORINFO_RESOLVED_TOKEN* pResolvedToken);
3358 GenTree* impImportStaticReadOnlyField(void* fldAddr, var_types lclTyp);
3360 GenTree* impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3361 CORINFO_ACCESS_FLAGS access,
3362 CORINFO_FIELD_INFO* pFieldInfo,
3365 static void impBashVarAddrsToI(GenTree* tree1, GenTree* tree2 = nullptr);
3367 GenTree* impImplicitIorI4Cast(GenTree* tree, var_types dstTyp);
3369 GenTree* impImplicitR4orR8Cast(GenTree* tree, var_types dstTyp);
3371 void impImportLeave(BasicBlock* block);
3372 void impResetLeaveBlock(BasicBlock* block, unsigned jmpAddr);
3373 GenTree* impIntrinsic(GenTree* newobjThis,
3374 CORINFO_CLASS_HANDLE clsHnd,
3375 CORINFO_METHOD_HANDLE method,
3376 CORINFO_SIG_INFO* sig,
3377 unsigned methodFlags,
3381 CORINFO_RESOLVED_TOKEN* pContstrainedResolvedToken,
3382 CORINFO_THIS_TRANSFORM constraintCallThisTransform,
3383 CorInfoIntrinsics* pIntrinsicID,
3384 bool* isSpecialIntrinsic = nullptr);
3385 GenTree* impMathIntrinsic(CORINFO_METHOD_HANDLE method,
3386 CORINFO_SIG_INFO* sig,
3388 CorInfoIntrinsics intrinsicID,
3390 NamedIntrinsic lookupNamedIntrinsic(CORINFO_METHOD_HANDLE method);
3392 #ifdef FEATURE_HW_INTRINSICS
3393 GenTree* impHWIntrinsic(NamedIntrinsic intrinsic,
3394 CORINFO_METHOD_HANDLE method,
3395 CORINFO_SIG_INFO* sig,
3397 GenTree* impUnsupportedHWIntrinsic(unsigned helper,
3398 CORINFO_METHOD_HANDLE method,
3399 CORINFO_SIG_INFO* sig,
3403 #ifdef _TARGET_XARCH_
3404 GenTree* impSSEIntrinsic(NamedIntrinsic intrinsic,
3405 CORINFO_METHOD_HANDLE method,
3406 CORINFO_SIG_INFO* sig,
3408 GenTree* impSSE2Intrinsic(NamedIntrinsic intrinsic,
3409 CORINFO_METHOD_HANDLE method,
3410 CORINFO_SIG_INFO* sig,
3412 GenTree* impSSE42Intrinsic(NamedIntrinsic intrinsic,
3413 CORINFO_METHOD_HANDLE method,
3414 CORINFO_SIG_INFO* sig,
3416 GenTree* impAvxOrAvx2Intrinsic(NamedIntrinsic intrinsic,
3417 CORINFO_METHOD_HANDLE method,
3418 CORINFO_SIG_INFO* sig,
3420 GenTree* impAESIntrinsic(NamedIntrinsic intrinsic,
3421 CORINFO_METHOD_HANDLE method,
3422 CORINFO_SIG_INFO* sig,
3424 GenTree* impBMI1Intrinsic(NamedIntrinsic intrinsic,
3425 CORINFO_METHOD_HANDLE method,
3426 CORINFO_SIG_INFO* sig,
3428 GenTree* impBMI2Intrinsic(NamedIntrinsic intrinsic,
3429 CORINFO_METHOD_HANDLE method,
3430 CORINFO_SIG_INFO* sig,
3432 GenTree* impFMAIntrinsic(NamedIntrinsic intrinsic,
3433 CORINFO_METHOD_HANDLE method,
3434 CORINFO_SIG_INFO* sig,
3436 GenTree* impLZCNTIntrinsic(NamedIntrinsic intrinsic,
3437 CORINFO_METHOD_HANDLE method,
3438 CORINFO_SIG_INFO* sig,
3440 GenTree* impPCLMULQDQIntrinsic(NamedIntrinsic intrinsic,
3441 CORINFO_METHOD_HANDLE method,
3442 CORINFO_SIG_INFO* sig,
3444 GenTree* impPOPCNTIntrinsic(NamedIntrinsic intrinsic,
3445 CORINFO_METHOD_HANDLE method,
3446 CORINFO_SIG_INFO* sig,
3448 bool compSupportsHWIntrinsic(InstructionSet isa);
3451 GenTree* getArgForHWIntrinsic(var_types argType, CORINFO_CLASS_HANDLE argClass);
3452 GenTree* impNonConstFallback(NamedIntrinsic intrinsic, var_types simdType, var_types baseType);
3453 GenTree* addRangeCheckIfNeeded(NamedIntrinsic intrinsic, GenTree* lastOp, bool mustExpand);
3454 bool hwIntrinsicSignatureTypeSupported(var_types retType, CORINFO_SIG_INFO* sig, NamedIntrinsic intrinsic);
3455 #endif // _TARGET_XARCH_
3456 #ifdef _TARGET_ARM64_
3457 InstructionSet lookupHWIntrinsicISA(const char* className);
3458 NamedIntrinsic lookupHWIntrinsic(const char* className, const char* methodName);
3459 bool impCheckImmediate(GenTree* immediateOp, unsigned int max);
3460 #endif // _TARGET_ARM64_
3461 #endif // FEATURE_HW_INTRINSICS
3462 GenTree* impArrayAccessIntrinsic(CORINFO_CLASS_HANDLE clsHnd,
3463 CORINFO_SIG_INFO* sig,
3466 CorInfoIntrinsics intrinsicID);
3467 GenTree* impInitializeArrayIntrinsic(CORINFO_SIG_INFO* sig);
3469 GenTree* impMethodPointer(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
3471 GenTree* impTransformThis(GenTree* thisPtr,
3472 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
3473 CORINFO_THIS_TRANSFORM transform);
3475 //----------------- Manipulating the trees and stmts ----------------------
3477 GenTree* impTreeList; // Trees for the BB being imported
3478 GenTree* impTreeLast; // The last tree for the current BB
3483 CHECK_SPILL_ALL = -1,
3484 CHECK_SPILL_NONE = -2
3487 void impBeginTreeList();
3488 void impEndTreeList(BasicBlock* block, GenTree* firstStmt, GenTree* lastStmt);
3489 void impEndTreeList(BasicBlock* block);
3490 void impAppendStmtCheck(GenTree* stmt, unsigned chkLevel);
3491 void impAppendStmt(GenTree* stmt, unsigned chkLevel);
3492 void impInsertStmtBefore(GenTree* stmt, GenTree* stmtBefore);
3493 GenTree* impAppendTree(GenTree* tree, unsigned chkLevel, IL_OFFSETX offset);
3494 void impInsertTreeBefore(GenTree* tree, IL_OFFSETX offset, GenTree* stmtBefore);
3495 void impAssignTempGen(unsigned tmp,
3498 GenTree** pAfterStmt = nullptr,
3499 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
3500 BasicBlock* block = nullptr);
3501 void impAssignTempGen(unsigned tmpNum,
3503 CORINFO_CLASS_HANDLE structHnd,
3505 GenTree** pAfterStmt = nullptr,
3506 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
3507 BasicBlock* block = nullptr);
3508 GenTree* impCloneExpr(GenTree* tree,
3510 CORINFO_CLASS_HANDLE structHnd,
3512 GenTree** pAfterStmt DEBUGARG(const char* reason));
3513 GenTree* impAssignStruct(GenTree* dest,
3515 CORINFO_CLASS_HANDLE structHnd,
3517 GenTree** pAfterStmt = nullptr,
3518 BasicBlock* block = nullptr);
3519 GenTree* impAssignStructPtr(GenTree* dest,
3521 CORINFO_CLASS_HANDLE structHnd,
3523 GenTree** pAfterStmt = nullptr,
3524 BasicBlock* block = nullptr);
3526 GenTree* impGetStructAddr(GenTree* structVal, CORINFO_CLASS_HANDLE structHnd, unsigned curLevel, bool willDeref);
3528 var_types impNormStructType(CORINFO_CLASS_HANDLE structHnd,
3529 BYTE* gcLayout = nullptr,
3530 unsigned* numGCVars = nullptr,
3531 var_types* simdBaseType = nullptr);
3533 GenTree* impNormStructVal(GenTree* structVal,
3534 CORINFO_CLASS_HANDLE structHnd,
3536 bool forceNormalization = false);
3538 GenTree* impTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3539 BOOL* pRuntimeLookup = nullptr,
3540 BOOL mustRestoreHandle = FALSE,
3541 BOOL importParent = FALSE);
3543 GenTree* impParentClassTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3544 BOOL* pRuntimeLookup = nullptr,
3545 BOOL mustRestoreHandle = FALSE)
3547 return impTokenToHandle(pResolvedToken, pRuntimeLookup, mustRestoreHandle, TRUE);
3550 GenTree* impLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3551 CORINFO_LOOKUP* pLookup,
3553 void* compileTimeHandle);
3555 GenTree* getRuntimeContextTree(CORINFO_RUNTIME_LOOKUP_KIND kind);
3557 GenTree* impRuntimeLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3558 CORINFO_LOOKUP* pLookup,
3559 void* compileTimeHandle);
3561 GenTree* impReadyToRunLookupToTree(CORINFO_CONST_LOOKUP* pLookup, unsigned flags, void* compileTimeHandle);
3563 GenTreeCall* impReadyToRunHelperToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3564 CorInfoHelpFunc helper,
3566 GenTreeArgList* arg = nullptr,
3567 CORINFO_LOOKUP_KIND* pGenericLookupKind = nullptr);
3569 GenTree* impCastClassOrIsInstToTree(GenTree* op1,
3571 CORINFO_RESOLVED_TOKEN* pResolvedToken,
3574 GenTree* impOptimizeCastClassOrIsInst(GenTree* op1, CORINFO_RESOLVED_TOKEN* pResolvedToken, bool isCastClass);
3576 bool VarTypeIsMultiByteAndCanEnreg(
3577 var_types type, CORINFO_CLASS_HANDLE typeClass, unsigned* typeSize, bool forReturn, bool isVarArg);
3579 bool IsIntrinsicImplementedByUserCall(CorInfoIntrinsics intrinsicId);
3580 bool IsTargetIntrinsic(CorInfoIntrinsics intrinsicId);
3581 bool IsMathIntrinsic(CorInfoIntrinsics intrinsicId);
3582 bool IsMathIntrinsic(GenTree* tree);
3585 //----------------- Importing the method ----------------------------------
3587 CORINFO_CONTEXT_HANDLE impTokenLookupContextHandle; // The context used for looking up tokens.
3590 unsigned impCurOpcOffs;
3591 const char* impCurOpcName;
3592 bool impNestedStackSpill;
3594 // For displaying instrs with generated native code (-n:B)
3595 GenTree* impLastILoffsStmt; // oldest stmt added for which we did not gtStmtLastILoffs
3596 void impNoteLastILoffs();
3599 /* IL offset of the stmt currently being imported. It gets set to
3600 BAD_IL_OFFSET after it has been set in the appended trees. Then it gets
3601 updated at IL offsets for which we have to report mapping info.
3602 It also includes flag bits, so use jitGetILoffs()
3603 to get the actual IL offset value.
3606 IL_OFFSETX impCurStmtOffs;
3607 void impCurStmtOffsSet(IL_OFFSET offs);
3609 void impNoteBranchOffs();
3611 unsigned impInitBlockLineInfo();
3613 GenTree* impCheckForNullPointer(GenTree* obj);
3614 bool impIsThis(GenTree* obj);
3615 bool impIsLDFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
3616 bool impIsDUP_LDVIRTFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
3617 bool impIsAnySTLOC(OPCODE opcode)
3619 return ((opcode == CEE_STLOC) || (opcode == CEE_STLOC_S) ||
3620 ((opcode >= CEE_STLOC_0) && (opcode <= CEE_STLOC_3)));
3623 GenTreeArgList* impPopList(unsigned count, CORINFO_SIG_INFO* sig, GenTreeArgList* prefixTree = nullptr);
3625 GenTreeArgList* impPopRevList(unsigned count, CORINFO_SIG_INFO* sig, unsigned skipReverseCount = 0);
3628 * Get current IL offset with stack-empty info incoporated
3630 IL_OFFSETX impCurILOffset(IL_OFFSET offs, bool callInstruction = false);
3632 //---------------- Spilling the importer stack ----------------------------
3634 // The maximum number of bytes of IL processed without clean stack state.
3635 // It allows to limit the maximum tree size and depth.
3636 static const unsigned MAX_TREE_SIZE = 200;
3637 bool impCanSpillNow(OPCODE prevOpcode);
3643 SavedStack pdSavedStack;
3644 ThisInitState pdThisPtrInit;
3647 PendingDsc* impPendingList; // list of BBs currently waiting to be imported.
3648 PendingDsc* impPendingFree; // Freed up dscs that can be reused
3650 // We keep a byte-per-block map (dynamically extended) in the top-level Compiler object of a compilation.
3651 JitExpandArray<BYTE> impPendingBlockMembers;
3653 // Return the byte for "b" (allocating/extending impPendingBlockMembers if necessary.)
3654 // Operates on the map in the top-level ancestor.
3655 BYTE impGetPendingBlockMember(BasicBlock* blk)
3657 return impInlineRoot()->impPendingBlockMembers.Get(blk->bbInd());
3660 // Set the byte for "b" to "val" (allocating/extending impPendingBlockMembers if necessary.)
3661 // Operates on the map in the top-level ancestor.
3662 void impSetPendingBlockMember(BasicBlock* blk, BYTE val)
3664 impInlineRoot()->impPendingBlockMembers.Set(blk->bbInd(), val);
3667 bool impCanReimport;
3669 bool impSpillStackEntry(unsigned level,
3673 bool bAssertOnRecursion,
3678 void impSpillStackEnsure(bool spillLeaves = false);
3679 void impEvalSideEffects();
3680 void impSpillSpecialSideEff();
3681 void impSpillSideEffects(bool spillGlobEffects, unsigned chkLevel DEBUGARG(const char* reason));
3682 void impSpillValueClasses();
3683 void impSpillEvalStack();
3684 static fgWalkPreFn impFindValueClasses;
3685 void impSpillLclRefs(ssize_t lclNum);
3687 BasicBlock* impPushCatchArgOnStack(BasicBlock* hndBlk, CORINFO_CLASS_HANDLE clsHnd, bool isSingleBlockFilter);
3689 void impImportBlockCode(BasicBlock* block);
3691 void impReimportMarkBlock(BasicBlock* block);
3692 void impReimportMarkSuccessors(BasicBlock* block);
3694 void impVerifyEHBlock(BasicBlock* block, bool isTryStart);
3696 void impImportBlockPending(BasicBlock* block);
3698 // Similar to impImportBlockPending, but assumes that block has already been imported once and is being
3699 // reimported for some reason. It specifically does *not* look at verCurrentState to set the EntryState
3700 // for the block, but instead, just re-uses the block's existing EntryState.
3701 void impReimportBlockPending(BasicBlock* block);
3703 var_types impGetByRefResultType(genTreeOps oper, bool fUnsigned, GenTree** pOp1, GenTree** pOp2);
3705 void impImportBlock(BasicBlock* block);
3707 // Assumes that "block" is a basic block that completes with a non-empty stack. We will assign the values
3708 // on the stack to local variables (the "spill temp" variables). The successor blocks will assume that
3709 // its incoming stack contents are in those locals. This requires "block" and its successors to agree on
3710 // the variables that will be used -- and for all the predecessors of those successors, and the
3711 // successors of those predecessors, etc. Call such a set of blocks closed under alternating
3712 // successor/predecessor edges a "spill clique." A block is a "predecessor" or "successor" member of the
3713 // clique (or, conceivably, both). Each block has a specified sequence of incoming and outgoing spill
3714 // temps. If "block" already has its outgoing spill temps assigned (they are always a contiguous series
3715 // of local variable numbers, so we represent them with the base local variable number), returns that.
3716 // Otherwise, picks a set of spill temps, and propagates this choice to all blocks in the spill clique of
3717 // which "block" is a member (asserting, in debug mode, that no block in this clique had its spill temps
3718 // chosen already. More precisely, that the incoming or outgoing spill temps are not chosen, depending
3719 // on which kind of member of the clique the block is).
3720 unsigned impGetSpillTmpBase(BasicBlock* block);
3722 // Assumes that "block" is a basic block that completes with a non-empty stack. We have previously
3723 // assigned the values on the stack to local variables (the "spill temp" variables). The successor blocks
3724 // will assume that its incoming stack contents are in those locals. This requires "block" and its
3725 // successors to agree on the variables and their types that will be used. The CLI spec allows implicit
3726 // conversions between 'int' and 'native int' or 'float' and 'double' stack types. So one predecessor can
3727 // push an int and another can push a native int. For 64-bit we have chosen to implement this by typing
3728 // the "spill temp" as native int, and then importing (or re-importing as needed) so that all the
3729 // predecessors in the "spill clique" push a native int (sign-extending if needed), and all the
3730 // successors receive a native int. Similarly float and double are unified to double.
3731 // This routine is called after a type-mismatch is detected, and it will walk the spill clique to mark
3732 // blocks for re-importation as appropriate (both successors, so they get the right incoming type, and
3733 // predecessors, so they insert an upcast if needed).
3734 void impReimportSpillClique(BasicBlock* block);
3736 // When we compute a "spill clique" (see above) these byte-maps are allocated to have a byte per basic
3737 // block, and represent the predecessor and successor members of the clique currently being computed.
3738 // *** Access to these will need to be locked in a parallel compiler.
3739 JitExpandArray<BYTE> impSpillCliquePredMembers;
3740 JitExpandArray<BYTE> impSpillCliqueSuccMembers;
3748 // Abstract class for receiving a callback while walking a spill clique
3749 class SpillCliqueWalker
3752 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk) = 0;
3755 // This class is used for setting the bbStkTempsIn and bbStkTempsOut on the blocks within a spill clique
3756 class SetSpillTempsBase : public SpillCliqueWalker
3761 SetSpillTempsBase(unsigned baseTmp) : m_baseTmp(baseTmp)
3764 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3767 // This class is used for implementing impReimportSpillClique part on each block within the spill clique
3768 class ReimportSpillClique : public SpillCliqueWalker
3773 ReimportSpillClique(Compiler* pComp) : m_pComp(pComp)
3776 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3779 // This is the heart of the algorithm for walking spill cliques. It invokes callback->Visit for each
3780 // predecessor or successor within the spill clique
3781 void impWalkSpillCliqueFromPred(BasicBlock* pred, SpillCliqueWalker* callback);
3783 // For a BasicBlock that has already been imported, the EntryState has an array of GenTrees for the
3784 // incoming locals. This walks that list an resets the types of the GenTrees to match the types of
3785 // the VarDscs. They get out of sync when we have int/native int issues (see impReimportSpillClique).
3786 void impRetypeEntryStateTemps(BasicBlock* blk);
3788 BYTE impSpillCliqueGetMember(SpillCliqueDir predOrSucc, BasicBlock* blk);
3789 void impSpillCliqueSetMember(SpillCliqueDir predOrSucc, BasicBlock* blk, BYTE val);
3791 void impPushVar(GenTree* op, typeInfo tiRetVal);
3792 void impLoadVar(unsigned lclNum, IL_OFFSET offset, typeInfo tiRetVal);
3793 void impLoadVar(unsigned lclNum, IL_OFFSET offset)
3795 impLoadVar(lclNum, offset, lvaTable[lclNum].lvVerTypeInfo);
3797 void impLoadArg(unsigned ilArgNum, IL_OFFSET offset);
3798 void impLoadLoc(unsigned ilLclNum, IL_OFFSET offset);
3799 bool impReturnInstruction(BasicBlock* block, int prefixFlags, OPCODE& opcode);
3802 void impMarkLclDstNotPromotable(unsigned tmpNum, GenTree* op, CORINFO_CLASS_HANDLE hClass);
3805 // A free list of linked list nodes used to represent to-do stacks of basic blocks.
3806 struct BlockListNode
3809 BlockListNode* m_next;
3810 BlockListNode(BasicBlock* blk, BlockListNode* next = nullptr) : m_blk(blk), m_next(next)
3813 void* operator new(size_t sz, Compiler* comp);
3815 BlockListNode* impBlockListNodeFreeList;
3817 void FreeBlockListNode(BlockListNode* node);
3819 bool impIsValueType(typeInfo* pTypeInfo);
3820 var_types mangleVarArgsType(var_types type);
3823 regNumber getCallArgIntRegister(regNumber floatReg);
3824 regNumber getCallArgFloatRegister(regNumber intReg);
3825 #endif // FEATURE_VARARG
3828 static unsigned jitTotalMethodCompiled;
3832 static LONG jitNestingLevel;
3835 static BOOL impIsAddressInLocal(GenTree* tree, GenTree** lclVarTreeOut);
3837 void impMakeDiscretionaryInlineObservations(InlineInfo* pInlineInfo, InlineResult* inlineResult);
3839 // STATIC inlining decision based on the IL code.
3840 void impCanInlineIL(CORINFO_METHOD_HANDLE fncHandle,
3841 CORINFO_METHOD_INFO* methInfo,
3843 InlineResult* inlineResult);
3845 void impCheckCanInline(GenTree* call,
3846 CORINFO_METHOD_HANDLE fncHandle,
3848 CORINFO_CONTEXT_HANDLE exactContextHnd,
3849 InlineCandidateInfo** ppInlineCandidateInfo,
3850 InlineResult* inlineResult);
3852 void impInlineRecordArgInfo(InlineInfo* pInlineInfo,
3855 InlineResult* inlineResult);
3857 void impInlineInitVars(InlineInfo* pInlineInfo);
3859 unsigned impInlineFetchLocal(unsigned lclNum DEBUGARG(const char* reason));
3861 GenTree* impInlineFetchArg(unsigned lclNum, InlArgInfo* inlArgInfo, InlLclVarInfo* lclTypeInfo);
3863 BOOL impInlineIsThis(GenTree* tree, InlArgInfo* inlArgInfo);
3865 BOOL impInlineIsGuaranteedThisDerefBeforeAnySideEffects(GenTree* additionalTreesToBeEvaluatedBefore,
3866 GenTree* variableBeingDereferenced,
3867 InlArgInfo* inlArgInfo);
3869 void impMarkInlineCandidate(GenTree* call,
3870 CORINFO_CONTEXT_HANDLE exactContextHnd,
3871 bool exactContextNeedsRuntimeLookup,
3872 CORINFO_CALL_INFO* callInfo);
3874 bool impTailCallRetTypeCompatible(var_types callerRetType,
3875 CORINFO_CLASS_HANDLE callerRetTypeClass,
3876 var_types calleeRetType,
3877 CORINFO_CLASS_HANDLE calleeRetTypeClass);
3879 bool impIsTailCallILPattern(bool tailPrefixed,
3881 const BYTE* codeAddrOfNextOpcode,
3882 const BYTE* codeEnd,
3884 bool* IsCallPopRet = nullptr);
3886 bool impIsImplicitTailCallCandidate(
3887 OPCODE curOpcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, int prefixFlags, bool isRecursive);
3889 CORINFO_RESOLVED_TOKEN* impAllocateToken(CORINFO_RESOLVED_TOKEN token);
3892 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3893 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3897 XX Info about the basic-blocks, their contents and the flow analysis XX
3899 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3900 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3904 BasicBlock* fgFirstBB; // Beginning of the basic block list
3905 BasicBlock* fgLastBB; // End of the basic block list
3906 BasicBlock* fgFirstColdBlock; // First block to be placed in the cold section
3907 #if FEATURE_EH_FUNCLETS
3908 BasicBlock* fgFirstFuncletBB; // First block of outlined funclets (to allow block insertion before the funclets)
3910 BasicBlock* fgFirstBBScratch; // Block inserted for initialization stuff. Is nullptr if no such block has been
3912 BasicBlockList* fgReturnBlocks; // list of BBJ_RETURN blocks
3913 unsigned fgEdgeCount; // # of control flow edges between the BBs
3914 unsigned fgBBcount; // # of BBs in the method
3916 unsigned fgBBcountAtCodegen; // # of BBs in the method at the start of codegen
3918 unsigned fgBBNumMax; // The max bbNum that has been assigned to basic blocks
3919 unsigned fgDomBBcount; // # of BBs for which we have dominator and reachability information
3920 BasicBlock** fgBBInvPostOrder; // The flow graph stored in an array sorted in topological order, needed to compute
3921 // dominance. Indexed by block number. Size: fgBBNumMax + 1.
3923 // After the dominance tree is computed, we cache a DFS preorder number and DFS postorder number to compute
3924 // dominance queries in O(1). fgDomTreePreOrder and fgDomTreePostOrder are arrays giving the block's preorder and
3925 // postorder number, respectively. The arrays are indexed by basic block number. (Note that blocks are numbered
3926 // starting from one. Thus, we always waste element zero. This makes debugging easier and makes the code less likely
3927 // to suffer from bugs stemming from forgetting to add or subtract one from the block number to form an array
3928 // index). The arrays are of size fgBBNumMax + 1.
3929 unsigned* fgDomTreePreOrder;
3930 unsigned* fgDomTreePostOrder;
3932 bool fgBBVarSetsInited;
3934 // Allocate array like T* a = new T[fgBBNumMax + 1];
3935 // Using helper so we don't keep forgetting +1.
3936 template <typename T>
3937 T* fgAllocateTypeForEachBlk(CompMemKind cmk = CMK_Unknown)
3939 return getAllocator(cmk).allocate<T>(fgBBNumMax + 1);
3942 // BlockSets are relative to a specific set of BasicBlock numbers. If that changes
3943 // (if the blocks are renumbered), this changes. BlockSets from different epochs
3944 // cannot be meaningfully combined. Note that new blocks can be created with higher
3945 // block numbers without changing the basic block epoch. These blocks *cannot*
3946 // participate in a block set until the blocks are all renumbered, causing the epoch
3947 // to change. This is useful if continuing to use previous block sets is valuable.
3948 // If the epoch is zero, then it is uninitialized, and block sets can't be used.
3949 unsigned fgCurBBEpoch;
3951 unsigned GetCurBasicBlockEpoch()
3953 return fgCurBBEpoch;
3956 // The number of basic blocks in the current epoch. When the blocks are renumbered,
3957 // this is fgBBcount. As blocks are added, fgBBcount increases, fgCurBBEpochSize remains
3958 // the same, until a new BasicBlock epoch is created, such as when the blocks are all renumbered.
3959 unsigned fgCurBBEpochSize;
3961 // The number of "size_t" elements required to hold a bitset large enough for fgCurBBEpochSize
3962 // bits. This is precomputed to avoid doing math every time BasicBlockBitSetTraits::GetArrSize() is called.
3963 unsigned fgBBSetCountInSizeTUnits;
3965 void NewBasicBlockEpoch()
3967 INDEBUG(unsigned oldEpochArrSize = fgBBSetCountInSizeTUnits);
3969 // We have a new epoch. Compute and cache the size needed for new BlockSets.
3971 fgCurBBEpochSize = fgBBNumMax + 1;
3972 fgBBSetCountInSizeTUnits =
3973 roundUp(fgCurBBEpochSize, (unsigned)(sizeof(size_t) * 8)) / unsigned(sizeof(size_t) * 8);
3976 // All BlockSet objects are now invalid!
3977 fgReachabilitySetsValid = false; // the bbReach sets are now invalid!
3978 fgEnterBlksSetValid = false; // the fgEnterBlks set is now invalid!
3982 unsigned epochArrSize = BasicBlockBitSetTraits::GetArrSize(this, sizeof(size_t));
3983 printf("\nNew BlockSet epoch %d, # of blocks (including unused BB00): %u, bitset array size: %u (%s)",
3984 fgCurBBEpoch, fgCurBBEpochSize, epochArrSize, (epochArrSize <= 1) ? "short" : "long");
3985 if ((fgCurBBEpoch != 1) && ((oldEpochArrSize <= 1) != (epochArrSize <= 1)))
3987 // If we're not just establishing the first epoch, and the epoch array size has changed such that we're
3988 // going to change our bitset representation from short (just a size_t bitset) to long (a pointer to an
3989 // array of size_t bitsets), then print that out.
3990 printf("; NOTE: BlockSet size was previously %s!", (oldEpochArrSize <= 1) ? "short" : "long");
3997 void EnsureBasicBlockEpoch()
3999 if (fgCurBBEpochSize != fgBBNumMax + 1)
4001 NewBasicBlockEpoch();
4005 BasicBlock* fgNewBasicBlock(BBjumpKinds jumpKind);
4006 void fgEnsureFirstBBisScratch();
4007 bool fgFirstBBisScratch();
4008 bool fgBBisScratch(BasicBlock* block);
4010 void fgExtendEHRegionBefore(BasicBlock* block);
4011 void fgExtendEHRegionAfter(BasicBlock* block);
4013 BasicBlock* fgNewBBbefore(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
4015 BasicBlock* fgNewBBafter(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
4017 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
4020 BasicBlock* nearBlk,
4021 bool putInFilter = false,
4022 bool runRarely = false,
4023 bool insertAtEnd = false);
4025 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
4027 bool runRarely = false,
4028 bool insertAtEnd = false);
4030 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind);
4032 BasicBlock* fgNewBBinRegionWorker(BBjumpKinds jumpKind,
4033 BasicBlock* afterBlk,
4034 unsigned xcptnIndex,
4035 bool putInTryRegion);
4037 void fgInsertBBbefore(BasicBlock* insertBeforeBlk, BasicBlock* newBlk);
4038 void fgInsertBBafter(BasicBlock* insertAfterBlk, BasicBlock* newBlk);
4039 void fgUnlinkBlock(BasicBlock* block);
4041 unsigned fgMeasureIR();
4043 bool fgModified; // True if the flow graph has been modified recently
4044 bool fgComputePredsDone; // Have we computed the bbPreds list
4045 bool fgCheapPredsValid; // Is the bbCheapPreds list valid?
4046 bool fgDomsComputed; // Have we computed the dominator sets?
4047 bool fgOptimizedFinally; // Did we optimize any try-finallys?
4049 bool fgHasSwitch; // any BBJ_SWITCH jumps?
4051 BlockSet fgEnterBlks; // Set of blocks which have a special transfer of control; the "entry" blocks plus EH handler
4055 bool fgReachabilitySetsValid; // Are the bbReach sets valid?
4056 bool fgEnterBlksSetValid; // Is the fgEnterBlks set valid?
4059 bool fgRemoveRestOfBlock; // true if we know that we will throw
4060 bool fgStmtRemoved; // true if we remove statements -> need new DFA
4062 // There are two modes for ordering of the trees.
4063 // - In FGOrderTree, the dominant ordering is the tree order, and the nodes contained in
4064 // each tree and sub-tree are contiguous, and can be traversed (in gtNext/gtPrev order)
4065 // by traversing the tree according to the order of the operands.
4066 // - In FGOrderLinear, the dominant ordering is the linear order.
4073 FlowGraphOrder fgOrder;
4075 // The following are boolean flags that keep track of the state of internal data structures
4077 bool fgStmtListThreaded; // true if the node list is now threaded
4078 bool fgCanRelocateEHRegions; // true if we are allowed to relocate the EH regions
4079 bool fgEdgeWeightsComputed; // true after we have called fgComputeEdgeWeights
4080 bool fgHaveValidEdgeWeights; // true if we were successful in computing all of the edge weights
4081 bool fgSlopUsedInEdgeWeights; // true if their was some slop used when computing the edge weights
4082 bool fgRangeUsedInEdgeWeights; // true if some of the edgeWeight are expressed in Min..Max form
4083 bool fgNeedsUpdateFlowGraph; // true if we need to run fgUpdateFlowGraph
4084 BasicBlock::weight_t fgCalledCount; // count of the number of times this method was called
4085 // This is derived from the profile data
4086 // or is BB_UNITY_WEIGHT when we don't have profile data
4088 #if FEATURE_EH_FUNCLETS
4089 bool fgFuncletsCreated; // true if the funclet creation phase has been run
4090 #endif // FEATURE_EH_FUNCLETS
4092 bool fgGlobalMorph; // indicates if we are during the global morphing phase
4093 // since fgMorphTree can be called from several places
4095 bool impBoxTempInUse; // the temp below is valid and available
4096 unsigned impBoxTemp; // a temporary that is used for boxing
4099 bool jitFallbackCompile; // Are we doing a fallback compile? That is, have we executed a NO_WAY assert,
4100 // and we are trying to compile again in a "safer", minopts mode?
4104 unsigned impInlinedCodeSize;
4107 //-------------------------------------------------------------------------
4113 void fgTransformFatCalli();
4117 void fgRemoveEmptyTry();
4119 void fgRemoveEmptyFinally();
4121 void fgMergeFinallyChains();
4123 void fgCloneFinally();
4125 void fgCleanupContinuation(BasicBlock* continuation);
4127 void fgUpdateFinallyTargetFlags();
4129 void fgClearAllFinallyTargetBits();
4131 void fgAddFinallyTargetFlags();
4133 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
4134 // Sometimes we need to defer updating the BBF_FINALLY_TARGET bit. fgNeedToAddFinallyTargetBits signals
4135 // when this is necessary.
4136 bool fgNeedToAddFinallyTargetBits;
4137 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
4139 bool fgRetargetBranchesToCanonicalCallFinally(BasicBlock* block,
4140 BasicBlock* handler,
4141 BlockToBlockMap& continuationMap);
4143 GenTree* fgGetCritSectOfStaticMethod();
4145 #if FEATURE_EH_FUNCLETS
4147 void fgAddSyncMethodEnterExit();
4149 GenTree* fgCreateMonitorTree(unsigned lvaMonitorBool, unsigned lvaThisVar, BasicBlock* block, bool enter);
4151 void fgConvertSyncReturnToLeave(BasicBlock* block);
4153 #endif // FEATURE_EH_FUNCLETS
4155 void fgAddReversePInvokeEnterExit();
4157 bool fgMoreThanOneReturnBlock();
4159 // The number of separate return points in the method.
4160 unsigned fgReturnCount;
4162 void fgAddInternal();
4164 bool fgFoldConditional(BasicBlock* block);
4166 void fgMorphStmts(BasicBlock* block, bool* lnot, bool* loadw);
4167 void fgMorphBlocks();
4169 bool fgMorphBlockStmt(BasicBlock* block, GenTreeStmt* stmt DEBUGARG(const char* msg));
4171 void fgSetOptions();
4174 static fgWalkPreFn fgAssertNoQmark;
4175 void fgPreExpandQmarkChecks(GenTree* expr);
4176 void fgPostExpandQmarkChecks();
4177 static void fgCheckQmarkAllowedForm(GenTree* tree);
4180 IL_OFFSET fgFindBlockILOffset(BasicBlock* block);
4182 BasicBlock* fgSplitBlockAtBeginning(BasicBlock* curr);
4183 BasicBlock* fgSplitBlockAtEnd(BasicBlock* curr);
4184 BasicBlock* fgSplitBlockAfterStatement(BasicBlock* curr, GenTree* stmt);
4185 BasicBlock* fgSplitBlockAfterNode(BasicBlock* curr, GenTree* node); // for LIR
4186 BasicBlock* fgSplitEdge(BasicBlock* curr, BasicBlock* succ);
4188 GenTreeStmt* fgNewStmtFromTree(GenTree* tree, BasicBlock* block, IL_OFFSETX offs);
4189 GenTreeStmt* fgNewStmtFromTree(GenTree* tree);
4190 GenTreeStmt* fgNewStmtFromTree(GenTree* tree, BasicBlock* block);
4191 GenTreeStmt* fgNewStmtFromTree(GenTree* tree, IL_OFFSETX offs);
4193 GenTree* fgGetTopLevelQmark(GenTree* expr, GenTree** ppDst = nullptr);
4194 void fgExpandQmarkForCastInstOf(BasicBlock* block, GenTree* stmt);
4195 void fgExpandQmarkStmt(BasicBlock* block, GenTree* expr);
4196 void fgExpandQmarkNodes();
4200 // Do "simple lowering." This functionality is (conceptually) part of "general"
4201 // lowering that is distributed between fgMorph and the lowering phase of LSRA.
4202 void fgSimpleLowering();
4204 GenTree* fgInitThisClass();
4206 GenTreeCall* fgGetStaticsCCtorHelper(CORINFO_CLASS_HANDLE cls, CorInfoHelpFunc helper);
4208 GenTreeCall* fgGetSharedCCtor(CORINFO_CLASS_HANDLE cls);
4210 inline bool backendRequiresLocalVarLifetimes()
4212 return !opts.MinOpts() || m_pLinearScan->willEnregisterLocalVars();
4215 void fgLocalVarLiveness();
4217 void fgLocalVarLivenessInit();
4219 void fgPerNodeLocalVarLiveness(GenTree* node);
4220 void fgPerBlockLocalVarLiveness();
4222 VARSET_VALRET_TP fgGetHandlerLiveVars(BasicBlock* block);
4224 void fgLiveVarAnalysis(bool updateInternalOnly = false);
4226 void fgComputeLifeCall(VARSET_TP& life, GenTreeCall* call);
4228 void fgComputeLifeTrackedLocalUse(VARSET_TP& life, LclVarDsc& varDsc, GenTreeLclVarCommon* node);
4229 bool fgComputeLifeTrackedLocalDef(VARSET_TP& life,
4230 VARSET_VALARG_TP keepAliveVars,
4232 GenTreeLclVarCommon* node);
4233 void fgComputeLifeUntrackedLocal(VARSET_TP& life,
4234 VARSET_VALARG_TP keepAliveVars,
4236 GenTreeLclVarCommon* lclVarNode);
4237 bool fgComputeLifeLocal(VARSET_TP& life, VARSET_VALARG_TP keepAliveVars, GenTree* lclVarNode);
4239 void fgComputeLife(VARSET_TP& life,
4242 VARSET_VALARG_TP volatileVars,
4243 bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
4245 void fgComputeLifeLIR(VARSET_TP& life, BasicBlock* block, VARSET_VALARG_TP volatileVars);
4247 bool fgRemoveDeadStore(GenTree** pTree,
4249 VARSET_VALARG_TP life,
4251 bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
4253 // For updating liveset during traversal AFTER fgComputeLife has completed
4254 VARSET_VALRET_TP fgGetVarBits(GenTree* tree);
4255 VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTree* tree);
4257 // Returns the set of live variables after endTree,
4258 // assuming that liveSet is the set of live variables BEFORE tree.
4259 // Requires that fgComputeLife has completed, and that tree is in the same
4260 // statement as endTree, and that it comes before endTree in execution order
4262 VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTree* tree, GenTree* endTree)
4264 VARSET_TP newLiveSet(VarSetOps::MakeCopy(this, liveSet));
4265 while (tree != nullptr && tree != endTree->gtNext)
4267 VarSetOps::AssignNoCopy(this, newLiveSet, fgUpdateLiveSet(newLiveSet, tree));
4268 tree = tree->gtNext;
4270 assert(tree == endTree->gtNext);
4274 void fgInterBlockLocalVarLiveness();
4276 // The presence of a partial definition presents some difficulties for SSA: this is both a use of some SSA name
4277 // of "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
4278 // whether to treat that as the use or def. It chooses the "use", and thus the old SSA name. This map allows us
4279 // to record/recover the "def" SSA number, given the lcl var node for "x" in such a tree.
4280 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, unsigned> NodeToUnsignedMap;
4281 NodeToUnsignedMap* m_opAsgnVarDefSsaNums;
4282 NodeToUnsignedMap* GetOpAsgnVarDefSsaNums()
4284 if (m_opAsgnVarDefSsaNums == nullptr)
4286 m_opAsgnVarDefSsaNums = new (getAllocator()) NodeToUnsignedMap(getAllocator());
4288 return m_opAsgnVarDefSsaNums;
4291 // Requires value numbering phase to have completed. Returns the value number ("gtVN") of the
4292 // "tree," EXCEPT in the case of GTF_VAR_USEASG, because the tree node's gtVN member is the
4293 // "use" VN. Performs a lookup into the map of (use asg tree -> def VN.) to return the "def's"
4295 inline ValueNum GetUseAsgDefVNOrTreeVN(GenTree* tree);
4297 // Requires that "lcl" has the GTF_VAR_DEF flag set. Returns the SSA number of "lcl".
4298 // Except: assumes that lcl is a def, and if it is
4299 // a partial def (GTF_VAR_USEASG), looks up and returns the SSA number for the "def",
4300 // rather than the "use" SSA number recorded in the tree "lcl".
4301 inline unsigned GetSsaNumForLocalVarDef(GenTree* lcl);
4303 // Performs SSA conversion.
4306 // Reset any data structures to the state expected by "fgSsaBuild", so it can be run again.
4307 void fgResetForSsa();
4309 unsigned fgSsaPassesCompleted; // Number of times fgSsaBuild has been run.
4311 // Returns "true" if a struct temp of the given type requires needs zero init in this block
4312 inline bool fgStructTempNeedsExplicitZeroInit(LclVarDsc* varDsc, BasicBlock* block);
4314 // The value numbers for this compilation.
4315 ValueNumStore* vnStore;
4318 ValueNumStore* GetValueNumStore()
4323 // Do value numbering (assign a value number to each
4325 void fgValueNumber();
4327 // Computes new GcHeap VN via the assignment H[elemTypeEq][arrVN][inx][fldSeq] = rhsVN.
4328 // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
4329 // The 'indType' is the indirection type of the lhs of the assignment and will typically
4330 // match the element type of the array or fldSeq. When this type doesn't match
4331 // or if the fldSeq is 'NotAField' we invalidate the array contents H[elemTypeEq][arrVN]
4333 ValueNum fgValueNumberArrIndexAssign(CORINFO_CLASS_HANDLE elemTypeEq,
4336 FieldSeqNode* fldSeq,
4340 // Requires that "tree" is a GT_IND marked as an array index, and that its address argument
4341 // has been parsed to yield the other input arguments. If evaluation of the address
4342 // can raise exceptions, those should be captured in the exception set "excVN."
4343 // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
4344 // Marks "tree" with the VN for H[elemTypeEq][arrVN][inx][fldSeq] (for the liberal VN; a new unique
4345 // VN for the conservative VN.) Also marks the tree's argument as the address of an array element.
4346 // The type tree->TypeGet() will typically match the element type of the array or fldSeq.
4347 // When this type doesn't match or if the fldSeq is 'NotAField' we return a new unique VN
4349 ValueNum fgValueNumberArrIndexVal(GenTree* tree,
4350 CORINFO_CLASS_HANDLE elemTypeEq,
4354 FieldSeqNode* fldSeq);
4356 // Requires "funcApp" to be a VNF_PtrToArrElem, and "addrXvn" to represent the exception set thrown
4357 // by evaluating the array index expression "tree". Returns the value number resulting from
4358 // dereferencing the array in the current GcHeap state. If "tree" is non-null, it must be the
4359 // "GT_IND" that does the dereference, and it is given the returned value number.
4360 ValueNum fgValueNumberArrIndexVal(GenTree* tree, struct VNFuncApp* funcApp, ValueNum addrXvn);
4362 // Compute the value number for a byref-exposed load of the given type via the given pointerVN.
4363 ValueNum fgValueNumberByrefExposedLoad(var_types type, ValueNum pointerVN);
4365 unsigned fgVNPassesCompleted; // Number of times fgValueNumber has been run.
4367 // Utility functions for fgValueNumber.
4369 // Perform value-numbering for the trees in "blk".
4370 void fgValueNumberBlock(BasicBlock* blk);
4372 // Requires that "entryBlock" is the entry block of loop "loopNum", and that "loopNum" is the
4373 // innermost loop of which "entryBlock" is the entry. Returns the value number that should be
4374 // assumed for the memoryKind at the start "entryBlk".
4375 ValueNum fgMemoryVNForLoopSideEffects(MemoryKind memoryKind, BasicBlock* entryBlock, unsigned loopNum);
4377 // Called when an operation (performed by "tree", described by "msg") may cause the GcHeap to be mutated.
4378 // As GcHeap is a subset of ByrefExposed, this will also annotate the ByrefExposed mutation.
4379 void fgMutateGcHeap(GenTree* tree DEBUGARG(const char* msg));
4381 // Called when an operation (performed by "tree", described by "msg") may cause an address-exposed local to be
4383 void fgMutateAddressExposedLocal(GenTree* tree DEBUGARG(const char* msg));
4385 // For a GC heap store at curTree, record the new curMemoryVN's and update curTree's MemorySsaMap.
4386 // As GcHeap is a subset of ByrefExposed, this will also record the ByrefExposed store.
4387 void recordGcHeapStore(GenTree* curTree, ValueNum gcHeapVN DEBUGARG(const char* msg));
4389 // For a store to an address-exposed local at curTree, record the new curMemoryVN and update curTree's MemorySsaMap.
4390 void recordAddressExposedLocalStore(GenTree* curTree, ValueNum memoryVN DEBUGARG(const char* msg));
4392 // Tree caused an update in the current memory VN. If "tree" has an associated heap SSA #, record that
4393 // value in that SSA #.
4394 void fgValueNumberRecordMemorySsa(MemoryKind memoryKind, GenTree* tree);
4396 // The input 'tree' is a leaf node that is a constant
4397 // Assign the proper value number to the tree
4398 void fgValueNumberTreeConst(GenTree* tree);
4400 // Assumes that all inputs to "tree" have had value numbers assigned; assigns a VN to tree.
4401 // (With some exceptions: the VN of the lhs of an assignment is assigned as part of the
4403 void fgValueNumberTree(GenTree* tree);
4405 // Does value-numbering for a block assignment.
4406 void fgValueNumberBlockAssignment(GenTree* tree);
4408 // Does value-numbering for a cast tree.
4409 void fgValueNumberCastTree(GenTree* tree);
4411 // Does value-numbering for an intrinsic tree.
4412 void fgValueNumberIntrinsic(GenTree* tree);
4414 // Does value-numbering for a call. We interpret some helper calls.
4415 void fgValueNumberCall(GenTreeCall* call);
4417 // The VN of some nodes in "args" may have changed -- reassign VNs to the arg list nodes.
4418 void fgUpdateArgListVNs(GenTreeArgList* args);
4420 // Does value-numbering for a helper "call" that has a VN function symbol "vnf".
4421 void fgValueNumberHelperCallFunc(GenTreeCall* call, VNFunc vnf, ValueNumPair vnpExc);
4423 // Requires "helpCall" to be a helper call. Assigns it a value number;
4424 // we understand the semantics of some of the calls. Returns "true" if
4425 // the call may modify the heap (we assume arbitrary memory side effects if so).
4426 bool fgValueNumberHelperCall(GenTreeCall* helpCall);
4428 // Requires that "helpFunc" is one of the pure Jit Helper methods.
4429 // Returns the corresponding VNFunc to use for value numbering
4430 VNFunc fgValueNumberJitHelperMethodVNFunc(CorInfoHelpFunc helpFunc);
4432 // Adds the exception set for the current tree node which is performing a memory indirection operation
4433 void fgValueNumberAddExceptionSetForIndirection(GenTree* tree);
4435 // Adds the exception sets for the current tree node which is performing a division or modulus operation
4436 void fgValueNumberAddExceptionSetForDivision(GenTree* tree);
4438 // Adds the exception set for the current tree node which is performing a overflow checking operation
4439 void fgValueNumberAddExceptionSetForOverflow(GenTree* tree);
4441 // Adds the exception set for the current tree node which is performing a ckfinite operation
4442 void fgValueNumberAddExceptionSetForCkFinite(GenTree* tree);
4444 // Adds the exception sets for the current tree node
4445 void fgValueNumberAddExceptionSet(GenTree* tree);
4447 // These are the current value number for the memory implicit variables while
4448 // doing value numbering. These are the value numbers under the "liberal" interpretation
4449 // of memory values; the "conservative" interpretation needs no VN, since every access of
4450 // memory yields an unknown value.
4451 ValueNum fgCurMemoryVN[MemoryKindCount];
4453 // Return a "pseudo"-class handle for an array element type. If "elemType" is TYP_STRUCT,
4454 // requires "elemStructType" to be non-null (and to have a low-order zero). Otherwise, low order bit
4455 // is 1, and the rest is an encoding of "elemTyp".
4456 static CORINFO_CLASS_HANDLE EncodeElemType(var_types elemTyp, CORINFO_CLASS_HANDLE elemStructType)
4458 if (elemStructType != nullptr)
4460 assert(varTypeIsStruct(elemTyp) || elemTyp == TYP_REF || elemTyp == TYP_BYREF ||
4461 varTypeIsIntegral(elemTyp));
4462 assert((size_t(elemStructType) & 0x1) == 0x0); // Make sure the encoding below is valid.
4463 return elemStructType;
4467 elemTyp = varTypeUnsignedToSigned(elemTyp);
4468 return CORINFO_CLASS_HANDLE(size_t(elemTyp) << 1 | 0x1);
4471 // If "clsHnd" is the result of an "EncodePrim" call, returns true and sets "*pPrimType" to the
4472 // var_types it represents. Otherwise, returns TYP_STRUCT (on the assumption that "clsHnd" is
4473 // the struct type of the element).
4474 static var_types DecodeElemType(CORINFO_CLASS_HANDLE clsHnd)
4476 size_t clsHndVal = size_t(clsHnd);
4477 if (clsHndVal & 0x1)
4479 return var_types(clsHndVal >> 1);
4487 // Convert a BYTE which represents the VM's CorInfoGCtype to the JIT's var_types
4488 var_types getJitGCType(BYTE gcType);
4490 enum structPassingKind
4492 SPK_Unknown, // Invalid value, never returned
4493 SPK_PrimitiveType, // The struct is passed/returned using a primitive type.
4494 SPK_EnclosingType, // Like SPK_Primitive type, but used for return types that
4495 // require a primitive type temp that is larger than the struct size.
4496 // Currently used for structs of size 3, 5, 6, or 7 bytes.
4497 SPK_ByValue, // The struct is passed/returned by value (using the ABI rules)
4498 // for ARM64 and UNIX_X64 in multiple registers. (when all of the
4499 // parameters registers are used, then the stack will be used)
4500 // for X86 passed on the stack, for ARM32 passed in registers
4501 // or the stack or split between registers and the stack.
4502 SPK_ByValueAsHfa, // The struct is passed/returned as an HFA in multiple registers.
4504 }; // The struct is passed/returned by reference to a copy/buffer.
4506 // Get the "primitive" type that is is used when we are given a struct of size 'structSize'.
4507 // For pointer sized structs the 'clsHnd' is used to determine if the struct contains GC ref.
4508 // A "primitive" type is one of the scalar types: byte, short, int, long, ref, float, double
4509 // If we can't or shouldn't use a "primitive" type then TYP_UNKNOWN is returned.
4511 // isVarArg is passed for use on Windows Arm64 to change the decision returned regarding
4514 var_types getPrimitiveTypeForStruct(unsigned structSize, CORINFO_CLASS_HANDLE clsHnd, bool isVarArg);
4516 // Get the type that is used to pass values of the given struct type.
4517 // isVarArg is passed for use on Windows Arm64 to change the decision returned regarding
4520 var_types getArgTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
4521 structPassingKind* wbPassStruct,
4523 unsigned structSize);
4525 // Get the type that is used to return values of the given struct type.
4526 // If the size is unknown, pass 0 and it will be determined from 'clsHnd'.
4527 var_types getReturnTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
4528 structPassingKind* wbPassStruct = nullptr,
4529 unsigned structSize = 0);
4532 // Print a representation of "vnp" or "vn" on standard output.
4533 // If "level" is non-zero, we also print out a partial expansion of the value.
4534 void vnpPrint(ValueNumPair vnp, unsigned level);
4535 void vnPrint(ValueNum vn, unsigned level);
4538 bool fgDominate(BasicBlock* b1, BasicBlock* b2); // Return true if b1 dominates b2
4540 // Dominator computation member functions
4541 // Not exposed outside Compiler
4543 bool fgReachable(BasicBlock* b1, BasicBlock* b2); // Returns true if block b1 can reach block b2
4545 void fgComputeDoms(); // Computes the immediate dominators for each basic block in the
4546 // flow graph. We first assume the fields bbIDom on each
4547 // basic block are invalid. This computation is needed later
4548 // by fgBuildDomTree to build the dominance tree structure.
4549 // Based on: A Simple, Fast Dominance Algorithm
4550 // by Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy
4552 void fgCompDominatedByExceptionalEntryBlocks();
4554 BlockSet_ValRet_T fgGetDominatorSet(BasicBlock* block); // Returns a set of blocks that dominate the given block.
4555 // Note: this is relatively slow compared to calling fgDominate(),
4556 // especially if dealing with a single block versus block check.
4558 void fgComputeReachabilitySets(); // Compute bbReach sets. (Also sets BBF_GC_SAFE_POINT flag on blocks.)
4560 void fgComputeEnterBlocksSet(); // Compute the set of entry blocks, 'fgEnterBlks'.
4562 bool fgRemoveUnreachableBlocks(); // Remove blocks determined to be unreachable by the bbReach sets.
4564 void fgComputeReachability(); // Perform flow graph node reachability analysis.
4566 BasicBlock* fgIntersectDom(BasicBlock* a, BasicBlock* b); // Intersect two immediate dominator sets.
4568 void fgDfsInvPostOrder(); // In order to compute dominance using fgIntersectDom, the flow graph nodes must be
4569 // processed in topological sort, this function takes care of that.
4571 void fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count);
4573 BlockSet_ValRet_T fgDomFindStartNodes(); // Computes which basic blocks don't have incoming edges in the flow graph.
4574 // Returns this as a set.
4576 BlockSet_ValRet_T fgDomTreeEntryNodes(BasicBlockList** domTree); // Computes which nodes in the dominance forest are
4577 // root nodes. Returns this as a set.
4580 void fgDispDomTree(BasicBlockList** domTree); // Helper that prints out the Dominator Tree in debug builds.
4583 void fgBuildDomTree(); // Once we compute all the immediate dominator sets for each node in the flow graph
4584 // (performed by fgComputeDoms), this procedure builds the dominance tree represented
4587 // In order to speed up the queries of the form 'Does A dominates B', we can perform a DFS preorder and postorder
4588 // traversal of the dominance tree and the dominance query will become A dominates B iif preOrder(A) <= preOrder(B)
4589 // && postOrder(A) >= postOrder(B) making the computation O(1).
4590 void fgTraverseDomTree(unsigned bbNum, BasicBlockList** domTree, unsigned* preNum, unsigned* postNum);
4592 // When the flow graph changes, we need to update the block numbers, predecessor lists, reachability sets, and
4594 void fgUpdateChangedFlowGraph();
4597 // Compute the predecessors of the blocks in the control flow graph.
4598 void fgComputePreds();
4600 // Remove all predecessor information.
4601 void fgRemovePreds();
4603 // Compute the cheap flow graph predecessors lists. This is used in some early phases
4604 // before the full predecessors lists are computed.
4605 void fgComputeCheapPreds();
4608 void fgAddCheapPred(BasicBlock* block, BasicBlock* blockPred);
4610 void fgRemoveCheapPred(BasicBlock* block, BasicBlock* blockPred);
4620 // Initialize the per-block variable sets (used for liveness analysis).
4621 void fgInitBlockVarSets();
4623 // true if we've gone through and created GC Poll calls.
4624 bool fgGCPollsCreated;
4625 void fgMarkGCPollBlocks();
4626 void fgCreateGCPolls();
4627 bool fgCreateGCPoll(GCPollType pollType, BasicBlock* block);
4629 // Requires that "block" is a block that returns from
4630 // a finally. Returns the number of successors (jump targets of
4631 // of blocks in the covered "try" that did a "LEAVE".)
4632 unsigned fgNSuccsOfFinallyRet(BasicBlock* block);
4634 // Requires that "block" is a block that returns (in the sense of BBJ_EHFINALLYRET) from
4635 // a finally. Returns its "i"th successor (jump targets of
4636 // of blocks in the covered "try" that did a "LEAVE".)
4637 // Requires that "i" < fgNSuccsOfFinallyRet(block).
4638 BasicBlock* fgSuccOfFinallyRet(BasicBlock* block, unsigned i);
4641 // Factor out common portions of the impls of the methods above.
4642 void fgSuccOfFinallyRetWork(BasicBlock* block, unsigned i, BasicBlock** bres, unsigned* nres);
4645 // For many purposes, it is desirable to be able to enumerate the *distinct* targets of a switch statement,
4646 // skipping duplicate targets. (E.g., in flow analyses that are only interested in the set of possible targets.)
4647 // SwitchUniqueSuccSet contains the non-duplicated switch targets.
4648 // (Code that modifies the jump table of a switch has an obligation to call Compiler::UpdateSwitchTableTarget,
4649 // which in turn will call the "UpdateTarget" method of this type if a SwitchUniqueSuccSet has already
4650 // been computed for the switch block. If a switch block is deleted or is transformed into a non-switch,
4651 // we leave the entry associated with the block, but it will no longer be accessed.)
4652 struct SwitchUniqueSuccSet
4654 unsigned numDistinctSuccs; // Number of distinct targets of the switch.
4655 BasicBlock** nonDuplicates; // Array of "numDistinctSuccs", containing all the distinct switch target
4658 // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
4659 // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
4660 // remove it from "this", and ensure that "to" is a member. Use "alloc" to do any required allocation.
4661 void UpdateTarget(CompAllocator alloc, BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
4664 typedef JitHashTable<BasicBlock*, JitPtrKeyFuncs<BasicBlock>, SwitchUniqueSuccSet> BlockToSwitchDescMap;
4667 // Maps BasicBlock*'s that end in switch statements to SwitchUniqueSuccSets that allow
4668 // iteration over only the distinct successors.
4669 BlockToSwitchDescMap* m_switchDescMap;
4672 BlockToSwitchDescMap* GetSwitchDescMap(bool createIfNull = true)
4674 if ((m_switchDescMap == nullptr) && createIfNull)
4676 m_switchDescMap = new (getAllocator()) BlockToSwitchDescMap(getAllocator());
4678 return m_switchDescMap;
4681 // Invalidate the map of unique switch block successors. For example, since the hash key of the map
4682 // depends on block numbers, we must invalidate the map when the blocks are renumbered, to ensure that
4683 // we don't accidentally look up and return the wrong switch data.
4684 void InvalidateUniqueSwitchSuccMap()
4686 m_switchDescMap = nullptr;
4689 // Requires "switchBlock" to be a block that ends in a switch. Returns
4690 // the corresponding SwitchUniqueSuccSet.
4691 SwitchUniqueSuccSet GetDescriptorForSwitch(BasicBlock* switchBlk);
4693 // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
4694 // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
4695 // remove it from "this", and ensure that "to" is a member.
4696 void UpdateSwitchTableTarget(BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
4698 // Remove the "SwitchUniqueSuccSet" of "switchBlk" in the BlockToSwitchDescMap.
4699 void fgInvalidateSwitchDescMapEntry(BasicBlock* switchBlk);
4701 BasicBlock* fgFirstBlockOfHandler(BasicBlock* block);
4703 flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred);
4705 flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred, flowList*** ptrToPred);
4707 flowList* fgSpliceOutPred(BasicBlock* block, BasicBlock* blockPred);
4709 flowList* fgRemoveRefPred(BasicBlock* block, BasicBlock* blockPred);
4711 flowList* fgRemoveAllRefPreds(BasicBlock* block, BasicBlock* blockPred);
4713 flowList* fgRemoveAllRefPreds(BasicBlock* block, flowList** ptrToPred);
4715 void fgRemoveBlockAsPred(BasicBlock* block);
4717 void fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock);
4719 void fgReplaceSwitchJumpTarget(BasicBlock* blockSwitch, BasicBlock* newTarget, BasicBlock* oldTarget);
4721 void fgReplaceJumpTarget(BasicBlock* block, BasicBlock* newTarget, BasicBlock* oldTarget);
4723 void fgReplacePred(BasicBlock* block, BasicBlock* oldPred, BasicBlock* newPred);
4725 flowList* fgAddRefPred(BasicBlock* block,
4726 BasicBlock* blockPred,
4727 flowList* oldEdge = nullptr,
4728 bool initializingPreds = false); // Only set to 'true' when we are computing preds in
4731 void fgFindBasicBlocks();
4733 bool fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt);
4735 bool fgCheckEHCanInsertAfterBlock(BasicBlock* blk, unsigned regionIndex, bool putInTryRegion);
4737 BasicBlock* fgFindInsertPoint(unsigned regionIndex,
4738 bool putInTryRegion,
4739 BasicBlock* startBlk,
4741 BasicBlock* nearBlk,
4742 BasicBlock* jumpBlk,
4745 unsigned fgGetNestingLevel(BasicBlock* block, unsigned* pFinallyNesting = nullptr);
4747 void fgRemoveEmptyBlocks();
4749 void fgRemoveStmt(BasicBlock* block, GenTree* stmt);
4751 bool fgCheckRemoveStmt(BasicBlock* block, GenTree* stmt);
4753 void fgCreateLoopPreHeader(unsigned lnum);
4755 void fgUnreachableBlock(BasicBlock* block);
4757 void fgRemoveConditionalJump(BasicBlock* block);
4759 BasicBlock* fgLastBBInMainFunction();
4761 BasicBlock* fgEndBBAfterMainFunction();
4763 void fgUnlinkRange(BasicBlock* bBeg, BasicBlock* bEnd);
4765 void fgRemoveBlock(BasicBlock* block, bool unreachable);
4767 bool fgCanCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4769 void fgCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4771 void fgUpdateLoopsAfterCompacting(BasicBlock* block, BasicBlock* bNext);
4773 BasicBlock* fgConnectFallThrough(BasicBlock* bSrc, BasicBlock* bDst);
4775 bool fgRenumberBlocks();
4777 bool fgExpandRarelyRunBlocks();
4779 bool fgEhAllowsMoveBlock(BasicBlock* bBefore, BasicBlock* bAfter);
4781 void fgMoveBlocksAfter(BasicBlock* bStart, BasicBlock* bEnd, BasicBlock* insertAfterBlk);
4783 enum FG_RELOCATE_TYPE
4785 FG_RELOCATE_TRY, // relocate the 'try' region
4786 FG_RELOCATE_HANDLER // relocate the handler region (including the filter if necessary)
4788 BasicBlock* fgRelocateEHRange(unsigned regionIndex, FG_RELOCATE_TYPE relocateType);
4790 #if FEATURE_EH_FUNCLETS
4791 #if defined(_TARGET_ARM_)
4792 void fgClearFinallyTargetBit(BasicBlock* block);
4793 #endif // defined(_TARGET_ARM_)
4794 bool fgIsIntraHandlerPred(BasicBlock* predBlock, BasicBlock* block);
4795 bool fgAnyIntraHandlerPreds(BasicBlock* block);
4796 void fgInsertFuncletPrologBlock(BasicBlock* block);
4797 void fgCreateFuncletPrologBlocks();
4798 void fgCreateFunclets();
4799 #else // !FEATURE_EH_FUNCLETS
4800 bool fgRelocateEHRegions();
4801 #endif // !FEATURE_EH_FUNCLETS
4803 bool fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* target);
4805 bool fgBlockEndFavorsTailDuplication(BasicBlock* block);
4807 bool fgBlockIsGoodTailDuplicationCandidate(BasicBlock* block);
4809 bool fgOptimizeEmptyBlock(BasicBlock* block);
4811 bool fgOptimizeBranchToEmptyUnconditional(BasicBlock* block, BasicBlock* bDest);
4813 bool fgOptimizeBranch(BasicBlock* bJump);
4815 bool fgOptimizeSwitchBranches(BasicBlock* block);
4817 bool fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev);
4819 bool fgOptimizeSwitchJumps();
4821 void fgPrintEdgeWeights();
4823 void fgComputeBlockAndEdgeWeights();
4824 BasicBlock::weight_t fgComputeMissingBlockWeights();
4825 void fgComputeCalledCount(BasicBlock::weight_t returnWeight);
4826 void fgComputeEdgeWeights();
4828 void fgReorderBlocks();
4830 void fgDetermineFirstColdBlock();
4832 bool fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc = nullptr);
4834 bool fgUpdateFlowGraph(bool doTailDup = false);
4836 void fgFindOperOrder();
4838 // method that returns if you should split here
4839 typedef bool(fgSplitPredicate)(GenTree* tree, GenTree* parent, fgWalkData* data);
4841 void fgSetBlockOrder();
4843 void fgRemoveReturnBlock(BasicBlock* block);
4845 /* Helper code that has been factored out */
4846 inline void fgConvertBBToThrowBB(BasicBlock* block);
4848 bool fgCastNeeded(GenTree* tree, var_types toType);
4849 GenTree* fgDoNormalizeOnStore(GenTree* tree);
4850 GenTree* fgMakeTmpArgNode(fgArgTabEntry* curArgTabEntry);
4852 // The following check for loops that don't execute calls
4853 bool fgLoopCallMarked;
4855 void fgLoopCallTest(BasicBlock* srcBB, BasicBlock* dstBB);
4856 void fgLoopCallMark();
4858 void fgMarkLoopHead(BasicBlock* block);
4860 unsigned fgGetCodeEstimate(BasicBlock* block);
4863 const char* fgProcessEscapes(const char* nameIn, escapeMapping_t* map);
4864 FILE* fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type);
4865 bool fgDumpFlowGraph(Phases phase);
4867 #endif // DUMP_FLOWGRAPHS
4872 void fgDispBBLiveness(BasicBlock* block);
4873 void fgDispBBLiveness();
4874 void fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth = 0);
4875 void fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees);
4876 void fgDispBasicBlocks(bool dumpTrees = false);
4877 void fgDumpStmtTree(GenTree* stmt, unsigned bbNum);
4878 void fgDumpBlock(BasicBlock* block);
4879 void fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock);
4881 static fgWalkPreFn fgStress64RsltMulCB;
4882 void fgStress64RsltMul();
4883 void fgDebugCheckUpdate();
4884 void fgDebugCheckBBlist(bool checkBBNum = false, bool checkBBRefs = true);
4885 void fgDebugCheckBlockLinks();
4886 void fgDebugCheckLinks(bool morphTrees = false);
4887 void fgDebugCheckStmtsList(BasicBlock* block, bool morphTrees);
4888 void fgDebugCheckNodeLinks(BasicBlock* block, GenTree* stmt);
4889 void fgDebugCheckNodesUniqueness();
4891 void fgDebugCheckFlags(GenTree* tree);
4892 void fgDebugCheckFlagsHelper(GenTree* tree, unsigned treeFlags, unsigned chkFlags);
4893 void fgDebugCheckTryFinallyExits();
4896 static GenTree* fgGetFirstNode(GenTree* tree);
4898 //--------------------- Walking the trees in the IR -----------------------
4903 fgWalkPreFn* wtprVisitorFn;
4904 fgWalkPostFn* wtpoVisitorFn;
4905 void* pCallbackData; // user-provided data
4906 bool wtprLclsOnly; // whether to only visit lclvar nodes
4907 GenTree* parent; // parent of current node, provided to callback
4908 GenTreeStack* parentStack; // stack of parent nodes, if asked for
4910 bool printModified; // callback can use this
4914 fgWalkResult fgWalkTreePre(GenTree** pTree,
4915 fgWalkPreFn* visitor,
4916 void* pCallBackData = nullptr,
4917 bool lclVarsOnly = false,
4918 bool computeStack = false);
4920 fgWalkResult fgWalkTree(GenTree** pTree,
4921 fgWalkPreFn* preVisitor,
4922 fgWalkPostFn* postVisitor,
4923 void* pCallBackData = nullptr);
4925 void fgWalkAllTreesPre(fgWalkPreFn* visitor, void* pCallBackData);
4929 fgWalkResult fgWalkTreePost(GenTree** pTree,
4930 fgWalkPostFn* visitor,
4931 void* pCallBackData = nullptr,
4932 bool computeStack = false);
4934 // An fgWalkPreFn that looks for expressions that have inline throws in
4935 // minopts mode. Basically it looks for tress with gtOverflowEx() or
4936 // GTF_IND_RNGCHK. It returns WALK_ABORT if one is found. It
4937 // returns WALK_SKIP_SUBTREES if GTF_EXCEPT is not set (assumes flags
4938 // properly propagated to parent trees). It returns WALK_CONTINUE
4940 static fgWalkResult fgChkThrowCB(GenTree** pTree, Compiler::fgWalkData* data);
4941 static fgWalkResult fgChkLocAllocCB(GenTree** pTree, Compiler::fgWalkData* data);
4942 static fgWalkResult fgChkQmarkCB(GenTree** pTree, Compiler::fgWalkData* data);
4944 /**************************************************************************
4946 *************************************************************************/
4949 friend class SsaBuilder;
4950 friend struct ValueNumberState;
4952 //--------------------- Detect the basic blocks ---------------------------
4954 BasicBlock** fgBBs; // Table of pointers to the BBs
4956 void fgInitBBLookup();
4957 BasicBlock* fgLookupBB(unsigned addr);
4959 void fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget);
4961 void fgMarkBackwardJump(BasicBlock* startBlock, BasicBlock* endBlock);
4963 void fgLinkBasicBlocks();
4965 unsigned fgMakeBasicBlocks(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget);
4967 void fgCheckBasicBlockControlFlow();
4969 void fgControlFlowPermitted(BasicBlock* blkSrc,
4970 BasicBlock* blkDest,
4971 BOOL IsLeave = false /* is the src a leave block */);
4973 bool fgFlowToFirstBlockOfInnerTry(BasicBlock* blkSrc, BasicBlock* blkDest, bool sibling);
4975 void fgObserveInlineConstants(OPCODE opcode, const FgStack& stack, bool isInlining);
4977 void fgAdjustForAddressExposedOrWrittenThis();
4979 bool fgProfileData_ILSizeMismatch;
4980 ICorJitInfo::ProfileBuffer* fgProfileBuffer;
4981 ULONG fgProfileBufferCount;
4982 ULONG fgNumProfileRuns;
4984 unsigned fgStressBBProf()
4987 unsigned result = JitConfig.JitStressBBProf();
4990 if (compStressCompile(STRESS_BB_PROFILE, 15))
5001 bool fgHaveProfileData();
5002 bool fgGetProfileWeightForBasicBlock(IL_OFFSET offset, unsigned* weight);
5003 void fgInstrumentMethod();
5006 // fgIsUsingProfileWeights - returns true if we have real profile data for this method
5007 // or if we have some fake profile data for the stress mode
5008 bool fgIsUsingProfileWeights()
5010 return (fgHaveProfileData() || fgStressBBProf());
5013 // fgProfileRunsCount - returns total number of scenario runs for the profile data
5014 // or BB_UNITY_WEIGHT when we aren't using profile data.
5015 unsigned fgProfileRunsCount()
5017 return fgIsUsingProfileWeights() ? fgNumProfileRuns : BB_UNITY_WEIGHT;
5020 //-------- Insert a statement at the start or end of a basic block --------
5024 static bool fgBlockContainsStatementBounded(BasicBlock* block, GenTree* stmt, bool answerOnBoundExceeded = true);
5028 GenTreeStmt* fgInsertStmtAtEnd(BasicBlock* block, GenTree* node);
5030 public: // Used by linear scan register allocation
5031 GenTreeStmt* fgInsertStmtNearEnd(BasicBlock* block, GenTree* node);
5034 GenTree* fgInsertStmtAtBeg(BasicBlock* block, GenTree* stmt);
5035 GenTree* fgInsertStmtAfter(BasicBlock* block, GenTree* insertionPoint, GenTree* stmt);
5037 public: // Used by linear scan register allocation
5038 GenTree* fgInsertStmtBefore(BasicBlock* block, GenTree* insertionPoint, GenTree* stmt);
5041 GenTree* fgInsertStmtListAfter(BasicBlock* block, GenTree* stmtAfter, GenTree* stmtList);
5043 // Create a new temporary variable to hold the result of *ppTree,
5044 // and transform the graph accordingly.
5045 GenTree* fgInsertCommaFormTemp(GenTree** ppTree, CORINFO_CLASS_HANDLE structType = nullptr);
5046 GenTree* fgMakeMultiUse(GenTree** ppTree);
5049 // Recognize a bitwise rotation pattern and convert into a GT_ROL or a GT_ROR node.
5050 GenTree* fgRecognizeAndMorphBitwiseRotation(GenTree* tree);
5051 bool fgOperIsBitwiseRotationRoot(genTreeOps oper);
5053 //-------- Determine the order in which the trees will be evaluated -------
5055 unsigned fgTreeSeqNum;
5056 GenTree* fgTreeSeqLst;
5057 GenTree* fgTreeSeqBeg;
5059 GenTree* fgSetTreeSeq(GenTree* tree, GenTree* prev = nullptr, bool isLIR = false);
5060 void fgSetTreeSeqHelper(GenTree* tree, bool isLIR);
5061 void fgSetTreeSeqFinish(GenTree* tree, bool isLIR);
5062 void fgSetStmtSeq(GenTree* tree);
5063 void fgSetBlockOrder(BasicBlock* block);
5065 //------------------------- Morphing --------------------------------------
5067 unsigned fgPtrArgCntMax;
5070 //------------------------------------------------------------------------
5071 // fgGetPtrArgCntMax: Return the maximum number of pointer-sized stack arguments that calls inside this method
5072 // can push on the stack. This value is calculated during morph.
5075 // Returns fgPtrArgCntMax, that is a private field.
5077 unsigned fgGetPtrArgCntMax() const
5079 return fgPtrArgCntMax;
5082 //------------------------------------------------------------------------
5083 // fgSetPtrArgCntMax: Set the maximum number of pointer-sized stack arguments that calls inside this method
5084 // can push on the stack. This function is used during StackLevelSetter to fix incorrect morph calculations.
5086 void fgSetPtrArgCntMax(unsigned argCntMax)
5088 fgPtrArgCntMax = argCntMax;
5091 bool compCanEncodePtrArgCntMax();
5094 hashBv* fgOutgoingArgTemps;
5095 hashBv* fgCurrentlyInUseArgTemps;
5097 void fgSetRngChkTarget(GenTree* tree, bool delay = true);
5099 BasicBlock* fgSetRngChkTargetInner(SpecialCodeKind kind, bool delay);
5102 void fgMoveOpsLeft(GenTree* tree);
5105 bool fgIsCommaThrow(GenTree* tree, bool forFolding = false);
5107 bool fgIsThrow(GenTree* tree);
5109 bool fgInDifferentRegions(BasicBlock* blk1, BasicBlock* blk2);
5110 bool fgIsBlockCold(BasicBlock* block);
5112 GenTree* fgMorphCastIntoHelper(GenTree* tree, int helper, GenTree* oper);
5114 GenTree* fgMorphIntoHelperCall(GenTree* tree, int helper, GenTreeArgList* args, bool morphArgs = true);
5116 GenTree* fgMorphStackArgForVarArgs(unsigned lclNum, var_types varType, unsigned lclOffs);
5118 // A "MorphAddrContext" carries information from the surrounding context. If we are evaluating a byref address,
5119 // it is useful to know whether the address will be immediately dereferenced, or whether the address value will
5120 // be used, perhaps by passing it as an argument to a called method. This affects how null checking is done:
5121 // for sufficiently small offsets, we can rely on OS page protection to implicitly null-check addresses that we
5122 // know will be dereferenced. To know that reliance on implicit null checking is sound, we must further know that
5123 // all offsets between the top-level indirection and the bottom are constant, and that their sum is sufficiently
5124 // small; hence the other fields of MorphAddrContext.
5125 enum MorphAddrContextKind
5130 struct MorphAddrContext
5132 MorphAddrContextKind m_kind;
5133 bool m_allConstantOffsets; // Valid only for "m_kind == MACK_Ind". True iff all offsets between
5134 // top-level indirection and here have been constants.
5135 size_t m_totalOffset; // Valid only for "m_kind == MACK_Ind", and if "m_allConstantOffsets" is true.
5136 // In that case, is the sum of those constant offsets.
5138 MorphAddrContext(MorphAddrContextKind kind) : m_kind(kind), m_allConstantOffsets(true), m_totalOffset(0)
5143 // A MACK_CopyBlock context is immutable, so we can just make one of these and share it.
5144 static MorphAddrContext s_CopyBlockMAC;
5147 GenTree* getSIMDStructFromField(GenTree* tree,
5148 var_types* baseTypeOut,
5150 unsigned* simdSizeOut,
5151 bool ignoreUsedInSIMDIntrinsic = false);
5152 GenTree* fgMorphFieldAssignToSIMDIntrinsicSet(GenTree* tree);
5153 GenTree* fgMorphFieldToSIMDIntrinsicGet(GenTree* tree);
5154 bool fgMorphCombineSIMDFieldAssignments(BasicBlock* block, GenTree* stmt);
5155 void impMarkContiguousSIMDFieldAssignments(GenTree* stmt);
5157 // fgPreviousCandidateSIMDFieldAsgStmt is only used for tracking previous simd field assignment
5158 // in function: Complier::impMarkContiguousSIMDFieldAssignments.
5159 GenTree* fgPreviousCandidateSIMDFieldAsgStmt;
5161 #endif // FEATURE_SIMD
5162 GenTree* fgMorphArrayIndex(GenTree* tree);
5163 GenTree* fgMorphCast(GenTree* tree);
5164 GenTree* fgUnwrapProxy(GenTree* objRef);
5165 GenTreeFieldList* fgMorphLclArgToFieldlist(GenTreeLclVarCommon* lcl);
5166 void fgInitArgInfo(GenTreeCall* call);
5167 GenTreeCall* fgMorphArgs(GenTreeCall* call);
5168 GenTreeArgList* fgMorphArgList(GenTreeArgList* args, MorphAddrContext* mac);
5170 void fgMakeOutgoingStructArgCopy(GenTreeCall* call,
5173 CORINFO_CLASS_HANDLE copyBlkClass);
5175 void fgFixupStructReturn(GenTree* call);
5176 GenTree* fgMorphLocalVar(GenTree* tree, bool forceRemorph);
5179 bool fgAddrCouldBeNull(GenTree* addr);
5182 GenTree* fgMorphField(GenTree* tree, MorphAddrContext* mac);
5183 bool fgCanFastTailCall(GenTreeCall* call);
5184 bool fgCheckStmtAfterTailCall();
5185 void fgMorphTailCall(GenTreeCall* call, void* pfnCopyArgs);
5186 GenTree* fgGetStubAddrArg(GenTreeCall* call);
5187 void fgMorphRecursiveFastTailCallIntoLoop(BasicBlock* block, GenTreeCall* recursiveTailCall);
5188 GenTree* fgAssignRecursiveCallArgToCallerParam(GenTree* arg,
5189 fgArgTabEntry* argTabEntry,
5191 IL_OFFSETX callILOffset,
5192 GenTree* tmpAssignmentInsertionPoint,
5193 GenTree* paramAssignmentInsertionPoint);
5194 static int fgEstimateCallStackSize(GenTreeCall* call);
5195 GenTree* fgMorphCall(GenTreeCall* call);
5196 void fgMorphCallInline(GenTreeCall* call, InlineResult* result);
5197 void fgMorphCallInlineHelper(GenTreeCall* call, InlineResult* result);
5199 void fgNoteNonInlineCandidate(GenTreeStmt* stmt, GenTreeCall* call);
5200 static fgWalkPreFn fgFindNonInlineCandidate;
5202 GenTree* fgOptimizeDelegateConstructor(GenTreeCall* call,
5203 CORINFO_CONTEXT_HANDLE* ExactContextHnd,
5204 CORINFO_RESOLVED_TOKEN* ldftnToken);
5205 GenTree* fgMorphLeaf(GenTree* tree);
5206 void fgAssignSetVarDef(GenTree* tree);
5207 GenTree* fgMorphOneAsgBlockOp(GenTree* tree);
5208 GenTree* fgMorphInitBlock(GenTree* tree);
5209 GenTree* fgMorphBlkToInd(GenTreeBlk* tree, var_types type);
5210 GenTree* fgMorphGetStructAddr(GenTree** pTree, CORINFO_CLASS_HANDLE clsHnd, bool isRValue = false);
5211 GenTree* fgMorphBlkNode(GenTree* tree, bool isDest);
5212 GenTree* fgMorphBlockOperand(GenTree* tree, var_types asgType, unsigned blockWidth, bool isDest);
5213 void fgMorphUnsafeBlk(GenTreeObj* obj);
5214 GenTree* fgMorphCopyBlock(GenTree* tree);
5215 GenTree* fgMorphForRegisterFP(GenTree* tree);
5216 GenTree* fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac = nullptr);
5217 GenTree* fgMorphModToSubMulDiv(GenTreeOp* tree);
5218 GenTree* fgMorphSmpOpOptional(GenTreeOp* tree);
5219 GenTree* fgMorphRecognizeBoxNullable(GenTree* compare);
5221 GenTree* fgMorphToEmulatedFP(GenTree* tree);
5222 GenTree* fgMorphConst(GenTree* tree);
5225 GenTree* fgMorphTree(GenTree* tree, MorphAddrContext* mac = nullptr);
5228 #if LOCAL_ASSERTION_PROP
5229 void fgKillDependentAssertionsSingle(unsigned lclNum DEBUGARG(GenTree* tree));
5230 void fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTree* tree));
5232 void fgMorphTreeDone(GenTree* tree, GenTree* oldTree = nullptr DEBUGARG(int morphNum = 0));
5234 GenTreeStmt* fgMorphStmt;
5236 unsigned fgGetBigOffsetMorphingTemp(var_types type); // We cache one temp per type to be
5237 // used when morphing big offset.
5239 //----------------------- Liveness analysis -------------------------------
5241 VARSET_TP fgCurUseSet; // vars used by block (before an assignment)
5242 VARSET_TP fgCurDefSet; // vars assigned by block (before a use)
5244 MemoryKindSet fgCurMemoryUse; // True iff the current basic block uses memory.
5245 MemoryKindSet fgCurMemoryDef; // True iff the current basic block modifies memory.
5246 MemoryKindSet fgCurMemoryHavoc; // True if the current basic block is known to set memory to a "havoc" value.
5248 bool byrefStatesMatchGcHeapStates; // True iff GcHeap and ByrefExposed memory have all the same def points.
5250 void fgMarkUseDef(GenTreeLclVarCommon* tree);
5252 void fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
5253 void fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
5255 void fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope);
5256 void fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope);
5258 void fgExtendDbgScopes();
5259 void fgExtendDbgLifetimes();
5262 void fgDispDebugScopes();
5265 //-------------------------------------------------------------------------
5267 // The following keeps track of any code we've added for things like array
5268 // range checking or explicit calls to enable GC, and so on.
5273 AddCodeDsc* acdNext;
5274 BasicBlock* acdDstBlk; // block to which we jump
5276 SpecialCodeKind acdKind; // what kind of a special block is this?
5277 #if !FEATURE_FIXED_OUT_ARGS
5278 bool acdStkLvlInit; // has acdStkLvl value been already set?
5280 #endif // !FEATURE_FIXED_OUT_ARGS
5284 static unsigned acdHelper(SpecialCodeKind codeKind);
5286 AddCodeDsc* fgAddCodeList;
5288 bool fgRngChkThrowAdded;
5289 AddCodeDsc* fgExcptnTargetCache[SCK_COUNT];
5291 BasicBlock* fgRngChkTarget(BasicBlock* block, SpecialCodeKind kind);
5293 BasicBlock* fgAddCodeRef(BasicBlock* srcBlk, unsigned refData, SpecialCodeKind kind);
5296 AddCodeDsc* fgFindExcptnTarget(SpecialCodeKind kind, unsigned refData);
5298 bool fgUseThrowHelperBlocks();
5300 AddCodeDsc* fgGetAdditionalCodeDescriptors()
5302 return fgAddCodeList;
5306 bool fgIsCodeAdded();
5308 bool fgIsThrowHlpBlk(BasicBlock* block);
5310 #if !FEATURE_FIXED_OUT_ARGS
5311 unsigned fgThrowHlpBlkStkLevel(BasicBlock* block);
5312 #endif // !FEATURE_FIXED_OUT_ARGS
5314 unsigned fgBigOffsetMorphingTemps[TYP_COUNT];
5316 unsigned fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo);
5317 void fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* result);
5318 void fgInsertInlineeBlocks(InlineInfo* pInlineInfo);
5319 GenTree* fgInlinePrependStatements(InlineInfo* inlineInfo);
5320 void fgInlineAppendStatements(InlineInfo* inlineInfo, BasicBlock* block, GenTree* stmt);
5322 #if FEATURE_MULTIREG_RET
5323 GenTree* fgGetStructAsStructPtr(GenTree* tree);
5324 GenTree* fgAssignStructInlineeToVar(GenTree* child, CORINFO_CLASS_HANDLE retClsHnd);
5325 void fgAttachStructInlineeToAsg(GenTree* tree, GenTree* child, CORINFO_CLASS_HANDLE retClsHnd);
5326 #endif // FEATURE_MULTIREG_RET
5328 static fgWalkPreFn fgUpdateInlineReturnExpressionPlaceHolder;
5329 static fgWalkPostFn fgLateDevirtualization;
5332 static fgWalkPreFn fgDebugCheckInlineCandidates;
5334 void CheckNoFatPointerCandidatesLeft();
5335 static fgWalkPreFn fgDebugCheckFatPointerCandidates;
5338 void fgPromoteStructs();
5339 void fgMorphStructField(GenTree* tree, GenTree* parent);
5340 void fgMorphLocalField(GenTree* tree, GenTree* parent);
5342 // Identify which parameters are implicit byrefs, and flag their LclVarDscs.
5343 void fgMarkImplicitByRefArgs();
5345 // Change implicit byrefs' types from struct to pointer, and for any that were
5346 // promoted, create new promoted struct temps.
5347 void fgRetypeImplicitByRefArgs();
5349 // Rewrite appearances of implicit byrefs (manifest the implied additional level of indirection).
5350 bool fgMorphImplicitByRefArgs(GenTree* tree);
5351 GenTree* fgMorphImplicitByRefArgs(GenTree* tree, bool isAddr);
5353 // Clear up annotations for any struct promotion temps created for implicit byrefs.
5354 void fgMarkDemotedImplicitByRefArgs();
5356 void fgMarkAddressExposedLocals();
5358 static fgWalkPreFn fgUpdateSideEffectsPre;
5359 static fgWalkPostFn fgUpdateSideEffectsPost;
5361 // The given local variable, required to be a struct variable, is being assigned via
5362 // a "lclField", to make it masquerade as an integral type in the ABI. Make sure that
5363 // the variable is not enregistered, and is therefore not promoted independently.
5364 void fgLclFldAssign(unsigned lclNum);
5366 static fgWalkPreFn gtHasLocalsWithAddrOpCB;
5368 enum TypeProducerKind
5370 TPK_Unknown = 0, // May not be a RuntimeType
5371 TPK_Handle = 1, // RuntimeType via handle
5372 TPK_GetType = 2, // RuntimeType via Object.get_Type()
5373 TPK_Null = 3, // Tree value is null
5374 TPK_Other = 4 // RuntimeType via other means
5377 TypeProducerKind gtGetTypeProducerKind(GenTree* tree);
5378 bool gtIsTypeHandleToRuntimeTypeHelper(GenTreeCall* call);
5379 bool gtIsActiveCSE_Candidate(GenTree* tree);
5382 bool fgPrintInlinedMethods;
5385 bool fgIsBigOffset(size_t offset);
5387 bool fgNeedReturnSpillTemp();
5390 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5391 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5395 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5396 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5402 void optRemoveRangeCheck(GenTree* tree, GenTree* stmt);
5403 bool optIsRangeCheckRemovable(GenTree* tree);
5406 static fgWalkPreFn optValidRangeCheckIndex;
5407 static fgWalkPreFn optRemoveTreeVisitor; // Helper passed to Compiler::fgWalkAllTreesPre() to decrement the LclVar
5410 void optRemoveTree(GenTree* deadTree, GenTree* keepList);
5412 /**************************************************************************
5414 *************************************************************************/
5417 // Do hoisting for all loops.
5418 void optHoistLoopCode();
5420 // To represent sets of VN's that have already been hoisted in outer loops.
5421 typedef JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, bool> VNToBoolMap;
5422 typedef VNToBoolMap VNSet;
5424 struct LoopHoistContext
5427 // The set of variables hoisted in the current loop (or nullptr if there are none).
5428 VNSet* m_pHoistedInCurLoop;
5431 // Value numbers of expressions that have been hoisted in parent loops in the loop nest.
5432 VNSet m_hoistedInParentLoops;
5433 // Value numbers of expressions that have been hoisted in the current (or most recent) loop in the nest.
5434 // Previous decisions on loop-invariance of value numbers in the current loop.
5435 VNToBoolMap m_curLoopVnInvariantCache;
5437 VNSet* GetHoistedInCurLoop(Compiler* comp)
5439 if (m_pHoistedInCurLoop == nullptr)
5441 m_pHoistedInCurLoop = new (comp->getAllocatorLoopHoist()) VNSet(comp->getAllocatorLoopHoist());
5443 return m_pHoistedInCurLoop;
5446 VNSet* ExtractHoistedInCurLoop()
5448 VNSet* res = m_pHoistedInCurLoop;
5449 m_pHoistedInCurLoop = nullptr;
5453 LoopHoistContext(Compiler* comp)
5454 : m_pHoistedInCurLoop(nullptr)
5455 , m_hoistedInParentLoops(comp->getAllocatorLoopHoist())
5456 , m_curLoopVnInvariantCache(comp->getAllocatorLoopHoist())
5461 // Do hoisting for loop "lnum" (an index into the optLoopTable), and all loops nested within it.
5462 // Tracks the expressions that have been hoisted by containing loops by temporary recording their
5463 // value numbers in "m_hoistedInParentLoops". This set is not modified by the call.
5464 void optHoistLoopNest(unsigned lnum, LoopHoistContext* hoistCtxt);
5466 // Do hoisting for a particular loop ("lnum" is an index into the optLoopTable.)
5467 // Assumes that expressions have been hoisted in containing loops if their value numbers are in
5468 // "m_hoistedInParentLoops".
5470 void optHoistThisLoop(unsigned lnum, LoopHoistContext* hoistCtxt);
5472 // Hoist all expressions in "blk" that are invariant in loop "lnum" (an index into the optLoopTable)
5473 // outside of that loop. Exempt expressions whose value number is in "m_hoistedInParentLoops"; add VN's of hoisted
5474 // expressions to "hoistInLoop".
5475 void optHoistLoopExprsForBlock(BasicBlock* blk, unsigned lnum, LoopHoistContext* hoistCtxt);
5477 // Return true if the tree looks profitable to hoist out of loop 'lnum'.
5478 bool optIsProfitableToHoistableTree(GenTree* tree, unsigned lnum);
5480 // Hoist all proper sub-expressions of "tree" (which occurs in "stmt", which occurs in "blk")
5481 // that are invariant in loop "lnum" (an index into the optLoopTable)
5482 // outside of that loop. Exempt expressions whose value number is in "hoistedInParents"; add VN's of hoisted
5483 // expressions to "hoistInLoop".
5484 // Returns "true" iff "tree" is loop-invariant (wrt "lnum").
5485 // Assumes that the value of "*firstBlockAndBeforeSideEffect" indicates that we're in the first block, and before
5486 // any possible globally visible side effects. Assume is called in evaluation order, and updates this.
5487 bool optHoistLoopExprsForTree(GenTree* tree,
5489 LoopHoistContext* hoistCtxt,
5490 bool* firstBlockAndBeforeSideEffect,
5492 bool* pCctorDependent);
5494 // Performs the hoisting 'tree' into the PreHeader for loop 'lnum'
5495 void optHoistCandidate(GenTree* tree, unsigned lnum, LoopHoistContext* hoistCtxt);
5497 // Returns true iff the ValueNum "vn" represents a value that is loop-invariant in "lnum".
5498 // Constants and init values are always loop invariant.
5499 // VNPhi's connect VN's to the SSA definition, so we can know if the SSA def occurs in the loop.
5500 bool optVNIsLoopInvariant(ValueNum vn, unsigned lnum, VNToBoolMap* recordedVNs);
5502 // Returns "true" iff "tree" is valid at the head of loop "lnum", in the context of the hoist substitution
5503 // "subst". If "tree" is a local SSA var, it is valid if its SSA definition occurs outside of the loop, or
5504 // if it is in the domain of "subst" (meaning that it's definition has been previously hoisted, with a "standin"
5505 // local.) If tree is a constant, it is valid. Otherwise, if it is an operator, it is valid iff its children are.
5506 bool optTreeIsValidAtLoopHead(GenTree* tree, unsigned lnum);
5508 // If "blk" is the entry block of a natural loop, returns true and sets "*pLnum" to the index of the loop
5509 // in the loop table.
5510 bool optBlockIsLoopEntry(BasicBlock* blk, unsigned* pLnum);
5512 // Records the set of "side effects" of all loops: fields (object instance and static)
5513 // written to, and SZ-array element type equivalence classes updated.
5514 void optComputeLoopSideEffects();
5517 // Requires "lnum" to be the index of an outermost loop in the loop table. Traverses the body of that loop,
5518 // including all nested loops, and records the set of "side effects" of the loop: fields (object instance and
5519 // static) written to, and SZ-array element type equivalence classes updated.
5520 void optComputeLoopNestSideEffects(unsigned lnum);
5522 // Add the side effects of "blk" (which is required to be within a loop) to all loops of which it is a part.
5523 void optComputeLoopSideEffectsOfBlock(BasicBlock* blk);
5525 // Hoist the expression "expr" out of loop "lnum".
5526 void optPerformHoistExpr(GenTree* expr, unsigned lnum);
5529 void optOptimizeBools();
5532 GenTree* optIsBoolCond(GenTree* condBranch, GenTree** compPtr, bool* boolPtr);
5534 void optOptimizeBoolsGcStress(BasicBlock* condBlock);
5537 void optOptimizeLayout(); // Optimize the BasicBlock layout of the method
5539 void optOptimizeLoops(); // for "while-do" loops duplicates simple loop conditions and transforms
5540 // the loop into a "do-while" loop
5541 // Also finds all natural loops and records them in the loop table
5543 // Optionally clone loops in the loop table.
5544 void optCloneLoops();
5546 // Clone loop "loopInd" in the loop table.
5547 void optCloneLoop(unsigned loopInd, LoopCloneContext* context);
5549 // Ensure that loop "loopInd" has a unique head block. (If the existing entry has
5550 // non-loop predecessors other than the head entry, create a new, empty block that goes (only) to the entry,
5551 // and redirects the preds of the entry to this new block.) Sets the weight of the newly created block to
5553 void optEnsureUniqueHead(unsigned loopInd, unsigned ambientWeight);
5555 void optUnrollLoops(); // Unrolls loops (needs to have cost info)
5558 // This enumeration describes what is killed by a call.
5562 CALLINT_NONE, // no interference (most helpers)
5563 CALLINT_REF_INDIRS, // kills GC ref indirections (SETFIELD OBJ)
5564 CALLINT_SCL_INDIRS, // kills non GC ref indirections (SETFIELD non-OBJ)
5565 CALLINT_ALL_INDIRS, // kills both GC ref and non GC ref indirections (SETFIELD STRUCT)
5566 CALLINT_ALL, // kills everything (normal method call)
5570 // A "LoopDsc" describes a ("natural") loop. We (currently) require the body of a loop to be a contiguous (in
5571 // bbNext order) sequence of basic blocks. (At times, we may require the blocks in a loop to be "properly numbered"
5572 // in bbNext order; we use comparisons on the bbNum to decide order.)
5573 // The blocks that define the body are
5574 // first <= top <= entry <= bottom .
5575 // The "head" of the loop is a block outside the loop that has "entry" as a successor. We only support loops with a
5576 // single 'head' block. The meanings of these blocks are given in the definitions below. Also see the picture at
5577 // Compiler::optFindNaturalLoops().
5580 BasicBlock* lpHead; // HEAD of the loop (not part of the looping of the loop) -- has ENTRY as a successor.
5581 BasicBlock* lpFirst; // FIRST block (in bbNext order) reachable within this loop. (May be part of a nested
5582 // loop, but not the outer loop.)
5583 BasicBlock* lpTop; // loop TOP (the back edge from lpBottom reaches here) (in most cases FIRST and TOP are the
5585 BasicBlock* lpEntry; // the ENTRY in the loop (in most cases TOP or BOTTOM)
5586 BasicBlock* lpBottom; // loop BOTTOM (from here we have a back edge to the TOP)
5587 BasicBlock* lpExit; // if a single exit loop this is the EXIT (in most cases BOTTOM)
5589 callInterf lpAsgCall; // "callInterf" for calls in the loop
5590 ALLVARSET_TP lpAsgVars; // set of vars assigned within the loop (all vars, not just tracked)
5591 varRefKinds lpAsgInds : 8; // set of inds modified within the loop
5593 unsigned short lpFlags; // Mask of the LPFLG_* constants
5595 unsigned char lpExitCnt; // number of exits from the loop
5597 unsigned char lpParent; // The index of the most-nested loop that completely contains this one,
5598 // or else BasicBlock::NOT_IN_LOOP if no such loop exists.
5599 unsigned char lpChild; // The index of a nested loop, or else BasicBlock::NOT_IN_LOOP if no child exists.
5600 // (Actually, an "immediately" nested loop --
5601 // no other child of this loop is a parent of lpChild.)
5602 unsigned char lpSibling; // The index of another loop that is an immediate child of lpParent,
5603 // or else BasicBlock::NOT_IN_LOOP. One can enumerate all the children of a loop
5604 // by following "lpChild" then "lpSibling" links.
5606 #define LPFLG_DO_WHILE 0x0001 // it's a do-while loop (i.e ENTRY is at the TOP)
5607 #define LPFLG_ONE_EXIT 0x0002 // the loop has only one exit
5609 #define LPFLG_ITER 0x0004 // for (i = icon or lclVar; test_condition(); i++)
5610 #define LPFLG_HOISTABLE 0x0008 // the loop is in a form that is suitable for hoisting expressions
5611 #define LPFLG_CONST 0x0010 // for (i=icon;i<icon;i++){ ... } - constant loop
5613 #define LPFLG_VAR_INIT 0x0020 // iterator is initialized with a local var (var # found in lpVarInit)
5614 #define LPFLG_CONST_INIT 0x0040 // iterator is initialized with a constant (found in lpConstInit)
5616 #define LPFLG_VAR_LIMIT 0x0100 // iterator is compared with a local var (var # found in lpVarLimit)
5617 #define LPFLG_CONST_LIMIT 0x0200 // iterator is compared with a constant (found in lpConstLimit)
5618 #define LPFLG_ARRLEN_LIMIT 0x0400 // iterator is compared with a.len or a[i].len (found in lpArrLenLimit)
5619 #define LPFLG_SIMD_LIMIT 0x0080 // iterator is compared with Vector<T>.Count (found in lpConstLimit)
5621 #define LPFLG_HAS_PREHEAD 0x0800 // lpHead is known to be a preHead for this loop
5622 #define LPFLG_REMOVED 0x1000 // has been removed from the loop table (unrolled or optimized away)
5623 #define LPFLG_DONT_UNROLL 0x2000 // do not unroll this loop
5625 #define LPFLG_ASGVARS_YES 0x4000 // "lpAsgVars" has been computed
5626 #define LPFLG_ASGVARS_INC 0x8000 // "lpAsgVars" is incomplete -- vars beyond those representable in an AllVarSet
5627 // type are assigned to.
5629 bool lpLoopHasMemoryHavoc[MemoryKindCount]; // The loop contains an operation that we assume has arbitrary
5630 // memory side effects. If this is set, the fields below
5631 // may not be accurate (since they become irrelevant.)
5632 bool lpContainsCall; // True if executing the loop body *may* execute a call
5634 VARSET_TP lpVarInOut; // The set of variables that are IN or OUT during the execution of this loop
5635 VARSET_TP lpVarUseDef; // The set of variables that are USE or DEF during the execution of this loop
5637 int lpHoistedExprCount; // The register count for the non-FP expressions from inside this loop that have been
5639 int lpLoopVarCount; // The register count for the non-FP LclVars that are read/written inside this loop
5640 int lpVarInOutCount; // The register count for the non-FP LclVars that are alive inside or accross this loop
5642 int lpHoistedFPExprCount; // The register count for the FP expressions from inside this loop that have been
5644 int lpLoopVarFPCount; // The register count for the FP LclVars that are read/written inside this loop
5645 int lpVarInOutFPCount; // The register count for the FP LclVars that are alive inside or accross this loop
5647 typedef JitHashTable<CORINFO_FIELD_HANDLE, JitPtrKeyFuncs<struct CORINFO_FIELD_STRUCT_>, bool> FieldHandleSet;
5648 FieldHandleSet* lpFieldsModified; // This has entries (mappings to "true") for all static field and object
5649 // instance fields modified
5652 typedef JitHashTable<CORINFO_CLASS_HANDLE, JitPtrKeyFuncs<struct CORINFO_CLASS_STRUCT_>, bool> ClassHandleSet;
5653 ClassHandleSet* lpArrayElemTypesModified; // Bits set indicate the set of sz array element types such that
5654 // arrays of that type are modified
5657 // Adds the variable liveness information for 'blk' to 'this' LoopDsc
5658 void AddVariableLiveness(Compiler* comp, BasicBlock* blk);
5660 inline void AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd);
5661 // This doesn't *always* take a class handle -- it can also take primitive types, encoded as class handles
5662 // (shifted left, with a low-order bit set to distinguish.)
5663 // Use the {Encode/Decode}ElemType methods to construct/destruct these.
5664 inline void AddModifiedElemType(Compiler* comp, CORINFO_CLASS_HANDLE structHnd);
5666 /* The following values are set only for iterator loops, i.e. has the flag LPFLG_ITER set */
5668 GenTree* lpIterTree; // The "i = i <op> const" tree
5669 unsigned lpIterVar(); // iterator variable #
5670 int lpIterConst(); // the constant with which the iterator is incremented
5671 genTreeOps lpIterOper(); // the type of the operation on the iterator (ASG_ADD, ASG_SUB, etc.)
5672 void VERIFY_lpIterTree();
5674 var_types lpIterOperType(); // For overflow instructions
5677 int lpConstInit; // initial constant value of iterator : Valid if LPFLG_CONST_INIT
5678 unsigned lpVarInit; // initial local var number to which we initialize the iterator : Valid if
5682 /* The following is for LPFLG_ITER loops only (i.e. the loop condition is "i RELOP const or var" */
5684 GenTree* lpTestTree; // pointer to the node containing the loop test
5685 genTreeOps lpTestOper(); // the type of the comparison between the iterator and the limit (GT_LE, GT_GE, etc.)
5686 void VERIFY_lpTestTree();
5688 bool lpIsReversed(); // true if the iterator node is the second operand in the loop condition
5689 GenTree* lpIterator(); // the iterator node in the loop test
5690 GenTree* lpLimit(); // the limit node in the loop test
5692 int lpConstLimit(); // limit constant value of iterator - loop condition is "i RELOP const" : Valid if
5693 // LPFLG_CONST_LIMIT
5694 unsigned lpVarLimit(); // the lclVar # in the loop condition ( "i RELOP lclVar" ) : Valid if
5696 bool lpArrLenLimit(Compiler* comp, ArrIndex* index); // The array length in the loop condition ( "i RELOP
5697 // arr.len" or "i RELOP arr[i][j].len" ) : Valid if
5698 // LPFLG_ARRLEN_LIMIT
5700 // Returns "true" iff "*this" contains the blk.
5701 bool lpContains(BasicBlock* blk)
5703 return lpFirst->bbNum <= blk->bbNum && blk->bbNum <= lpBottom->bbNum;
5705 // Returns "true" iff "*this" (properly) contains the range [first, bottom] (allowing firsts
5706 // to be equal, but requiring bottoms to be different.)
5707 bool lpContains(BasicBlock* first, BasicBlock* bottom)
5709 return lpFirst->bbNum <= first->bbNum && bottom->bbNum < lpBottom->bbNum;
5712 // Returns "true" iff "*this" (properly) contains "lp2" (allowing firsts to be equal, but requiring
5713 // bottoms to be different.)
5714 bool lpContains(const LoopDsc& lp2)
5716 return lpContains(lp2.lpFirst, lp2.lpBottom);
5719 // Returns "true" iff "*this" is (properly) contained by the range [first, bottom]
5720 // (allowing firsts to be equal, but requiring bottoms to be different.)
5721 bool lpContainedBy(BasicBlock* first, BasicBlock* bottom)
5723 return first->bbNum <= lpFirst->bbNum && lpBottom->bbNum < bottom->bbNum;
5726 // Returns "true" iff "*this" is (properly) contained by "lp2"
5727 // (allowing firsts to be equal, but requiring bottoms to be different.)
5728 bool lpContainedBy(const LoopDsc& lp2)
5730 return lpContains(lp2.lpFirst, lp2.lpBottom);
5733 // Returns "true" iff "*this" is disjoint from the range [top, bottom].
5734 bool lpDisjoint(BasicBlock* first, BasicBlock* bottom)
5736 return bottom->bbNum < lpFirst->bbNum || lpBottom->bbNum < first->bbNum;
5738 // Returns "true" iff "*this" is disjoint from "lp2".
5739 bool lpDisjoint(const LoopDsc& lp2)
5741 return lpDisjoint(lp2.lpFirst, lp2.lpBottom);
5743 // Returns "true" iff the loop is well-formed (see code for defn).
5746 return lpFirst->bbNum <= lpTop->bbNum && lpTop->bbNum <= lpEntry->bbNum &&
5747 lpEntry->bbNum <= lpBottom->bbNum &&
5748 (lpHead->bbNum < lpTop->bbNum || lpHead->bbNum > lpBottom->bbNum);
5753 bool fgMightHaveLoop(); // returns true if there are any backedges
5754 bool fgHasLoops; // True if this method has any loops, set in fgComputeReachability
5757 LoopDsc* optLoopTable; // loop descriptor table
5758 unsigned char optLoopCount; // number of tracked loops
5760 bool optRecordLoop(BasicBlock* head,
5766 unsigned char exitCnt);
5769 unsigned optCallCount; // number of calls made in the method
5770 unsigned optIndirectCallCount; // number of virtual, interface and indirect calls made in the method
5771 unsigned optNativeCallCount; // number of Pinvoke/Native calls made in the method
5772 unsigned optLoopsCloned; // number of loops cloned in the current method.
5775 unsigned optFindLoopNumberFromBeginBlock(BasicBlock* begBlk);
5776 void optPrintLoopInfo(unsigned loopNum,
5778 BasicBlock* lpFirst,
5780 BasicBlock* lpEntry,
5781 BasicBlock* lpBottom,
5782 unsigned char lpExitCnt,
5784 unsigned parentLoop = BasicBlock::NOT_IN_LOOP);
5785 void optPrintLoopInfo(unsigned lnum);
5786 void optPrintLoopRecording(unsigned lnum);
5788 void optCheckPreds();
5791 void optSetBlockWeights();
5793 void optMarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk, bool excludeEndBlk);
5795 void optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk);
5797 void optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmarkLoop = false);
5799 bool optIsLoopTestEvalIntoTemp(GenTree* test, GenTree** newTest);
5800 unsigned optIsLoopIncrTree(GenTree* incr);
5801 bool optCheckIterInLoopTest(unsigned loopInd, GenTree* test, BasicBlock* from, BasicBlock* to, unsigned iterVar);
5802 bool optComputeIterInfo(GenTree* incr, BasicBlock* from, BasicBlock* to, unsigned* pIterVar);
5803 bool optPopulateInitInfo(unsigned loopInd, GenTree* init, unsigned iterVar);
5804 bool optExtractInitTestIncr(
5805 BasicBlock* head, BasicBlock* bottom, BasicBlock* exit, GenTree** ppInit, GenTree** ppTest, GenTree** ppIncr);
5807 void optFindNaturalLoops();
5809 // Ensures that all the loops in the loop nest rooted at "loopInd" (an index into the loop table) are 'canonical' --
5810 // each loop has a unique "top." Returns "true" iff the flowgraph has been modified.
5811 bool optCanonicalizeLoopNest(unsigned char loopInd);
5813 // Ensures that the loop "loopInd" (an index into the loop table) is 'canonical' -- it has a unique "top,"
5814 // unshared with any other loop. Returns "true" iff the flowgraph has been modified
5815 bool optCanonicalizeLoop(unsigned char loopInd);
5817 // Requires "l1" to be a valid loop table index, and not "BasicBlock::NOT_IN_LOOP". Requires "l2" to be
5818 // a valid loop table index, or else "BasicBlock::NOT_IN_LOOP". Returns true
5819 // iff "l2" is not NOT_IN_LOOP, and "l1" contains "l2".
5820 bool optLoopContains(unsigned l1, unsigned l2);
5822 // Requires "loopInd" to be a valid index into the loop table.
5823 // Updates the loop table by changing loop "loopInd", whose head is required
5824 // to be "from", to be "to". Also performs this transformation for any
5825 // loop nested in "loopInd" that shares the same head as "loopInd".
5826 void optUpdateLoopHead(unsigned loopInd, BasicBlock* from, BasicBlock* to);
5828 // Updates the successors of "blk": if "blk2" is a successor of "blk", and there is a mapping for "blk2->blk3" in
5829 // "redirectMap", change "blk" so that "blk3" is this successor. Note that the predecessor lists are not updated.
5830 void optRedirectBlock(BasicBlock* blk, BlockToBlockMap* redirectMap);
5832 // Marks the containsCall information to "lnum" and any parent loops.
5833 void AddContainsCallAllContainingLoops(unsigned lnum);
5834 // Adds the variable liveness information from 'blk' to "lnum" and any parent loops.
5835 void AddVariableLivenessAllContainingLoops(unsigned lnum, BasicBlock* blk);
5836 // Adds "fldHnd" to the set of modified fields of "lnum" and any parent loops.
5837 void AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd);
5838 // Adds "elemType" to the set of modified array element types of "lnum" and any parent loops.
5839 void AddModifiedElemTypeAllContainingLoops(unsigned lnum, CORINFO_CLASS_HANDLE elemType);
5841 // Requires that "from" and "to" have the same "bbJumpKind" (perhaps because "to" is a clone
5842 // of "from".) Copies the jump destination from "from" to "to".
5843 void optCopyBlkDest(BasicBlock* from, BasicBlock* to);
5845 // The depth of the loop described by "lnum" (an index into the loop table.) (0 == top level)
5846 unsigned optLoopDepth(unsigned lnum)
5848 unsigned par = optLoopTable[lnum].lpParent;
5849 if (par == BasicBlock::NOT_IN_LOOP)
5855 return 1 + optLoopDepth(par);
5859 void fgOptWhileLoop(BasicBlock* block);
5861 bool optComputeLoopRep(int constInit,
5864 genTreeOps iterOper,
5866 genTreeOps testOper,
5869 unsigned* iterCount);
5872 static fgWalkPreFn optIsVarAssgCB;
5875 bool optIsVarAssigned(BasicBlock* beg, BasicBlock* end, GenTree* skip, unsigned var);
5877 bool optIsVarAssgLoop(unsigned lnum, unsigned var);
5879 int optIsSetAssgLoop(unsigned lnum, ALLVARSET_VALARG_TP vars, varRefKinds inds = VR_NONE);
5881 bool optNarrowTree(GenTree* tree, var_types srct, var_types dstt, ValueNumPair vnpNarrow, bool doit);
5883 /**************************************************************************
5884 * Optimization conditions
5885 *************************************************************************/
5887 bool optFastCodeOrBlendedLoop(BasicBlock::weight_t bbWeight);
5888 bool optPentium4(void);
5889 bool optAvoidIncDec(BasicBlock::weight_t bbWeight);
5890 bool optAvoidIntMult(void);
5895 // The following is the upper limit on how many expressions we'll keep track
5896 // of for the CSE analysis.
5898 static const unsigned MAX_CSE_CNT = EXPSET_SZ;
5900 static const int MIN_CSE_COST = 2;
5902 // Keeps tracked cse indices
5903 BitVecTraits* cseTraits;
5906 /* Generic list of nodes - used by the CSE logic */
5916 treeStmtLst* tslNext;
5917 GenTree* tslTree; // tree node
5918 GenTree* tslStmt; // statement containing the tree
5919 BasicBlock* tslBlock; // block containing the statement
5922 // The following logic keeps track of expressions via a simple hash table.
5926 CSEdsc* csdNextInBucket; // used by the hash table
5928 unsigned csdHashKey; // the orginal hashkey
5930 unsigned csdIndex; // 1..optCSECandidateCount
5931 char csdLiveAcrossCall; // 0 or 1
5933 unsigned short csdDefCount; // definition count
5934 unsigned short csdUseCount; // use count (excluding the implicit uses at defs)
5936 unsigned csdDefWtCnt; // weighted def count
5937 unsigned csdUseWtCnt; // weighted use count (excluding the implicit uses at defs)
5939 GenTree* csdTree; // treenode containing the 1st occurance
5940 GenTree* csdStmt; // stmt containing the 1st occurance
5941 BasicBlock* csdBlock; // block containing the 1st occurance
5943 treeStmtLst* csdTreeList; // list of matching tree nodes: head
5944 treeStmtLst* csdTreeLast; // list of matching tree nodes: tail
5946 ValueNum defExcSetPromise; // The exception set that is now required for all defs of this CSE.
5947 // This will be set to NoVN if we decide to abandon this CSE
5949 ValueNum defExcSetCurrent; // The set of exceptions we currently can use for CSE uses.
5951 ValueNum defConservNormVN; // if all def occurrences share the same conservative normal value
5952 // number, this will reflect it; otherwise, NoVN.
5955 static const size_t s_optCSEhashSize;
5956 CSEdsc** optCSEhash;
5959 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, GenTree*> NodeToNodeMap;
5961 NodeToNodeMap* optCseCheckedBoundMap; // Maps bound nodes to ancestor compares that should be
5962 // re-numbered with the bound to improve range check elimination
5964 // Given a compare, look for a cse candidate checked bound feeding it and add a map entry if found.
5965 void optCseUpdateCheckedBoundMap(GenTree* compare);
5969 CSEdsc* optCSEfindDsc(unsigned index);
5970 bool optUnmarkCSE(GenTree* tree);
5972 // user defined callback data for the tree walk function optCSE_MaskHelper()
5973 struct optCSE_MaskData
5975 EXPSET_TP CSE_defMask;
5976 EXPSET_TP CSE_useMask;
5979 // Treewalk helper for optCSE_DefMask and optCSE_UseMask
5980 static fgWalkPreFn optCSE_MaskHelper;
5982 // This function walks all the node for an given tree
5983 // and return the mask of CSE definitions and uses for the tree
5985 void optCSE_GetMaskData(GenTree* tree, optCSE_MaskData* pMaskData);
5987 // Given a binary tree node return true if it is safe to swap the order of evaluation for op1 and op2.
5988 bool optCSE_canSwap(GenTree* firstNode, GenTree* secondNode);
5989 bool optCSE_canSwap(GenTree* tree);
5991 static int __cdecl optCSEcostCmpEx(const void* op1, const void* op2);
5992 static int __cdecl optCSEcostCmpSz(const void* op1, const void* op2);
5994 void optCleanupCSEs();
5997 void optEnsureClearCSEInfo();
6000 #endif // FEATURE_ANYCSE
6002 #if FEATURE_VALNUM_CSE
6003 /**************************************************************************
6004 * Value Number based CSEs
6005 *************************************************************************/
6008 void optOptimizeValnumCSEs();
6011 void optValnumCSE_Init();
6012 unsigned optValnumCSE_Index(GenTree* tree, GenTree* stmt);
6013 unsigned optValnumCSE_Locate();
6014 void optValnumCSE_InitDataFlow();
6015 void optValnumCSE_DataFlow();
6016 void optValnumCSE_Availablity();
6017 void optValnumCSE_Heuristic();
6019 #endif // FEATURE_VALNUM_CSE
6022 bool optDoCSE; // True when we have found a duplicate CSE tree
6023 bool optValnumCSE_phase; // True when we are executing the optValnumCSE_phase
6024 unsigned optCSECandidateTotal; // Grand total of CSE candidates for both Lexical and ValNum
6025 unsigned optCSECandidateCount; // Count of CSE's candidates, reset for Lexical and ValNum CSE's
6026 unsigned optCSEstart; // The first local variable number that is a CSE
6027 unsigned optCSEcount; // The total count of CSE's introduced.
6028 unsigned optCSEweight; // The weight of the current block when we are
6029 // scanning for CSE expressions
6031 bool optIsCSEcandidate(GenTree* tree);
6033 // lclNumIsTrueCSE returns true if the LclVar was introduced by the CSE phase of the compiler
6035 bool lclNumIsTrueCSE(unsigned lclNum) const
6037 return ((optCSEcount > 0) && (lclNum >= optCSEstart) && (lclNum < optCSEstart + optCSEcount));
6040 // lclNumIsCSE returns true if the LclVar should be treated like a CSE with regards to constant prop.
6042 bool lclNumIsCSE(unsigned lclNum) const
6044 return lvaTable[lclNum].lvIsCSE;
6048 bool optConfigDisableCSE();
6049 bool optConfigDisableCSE2();
6051 void optOptimizeCSEs();
6053 #endif // FEATURE_ANYCSE
6061 unsigned ivaVar; // Variable we are interested in, or -1
6062 ALLVARSET_TP ivaMaskVal; // Set of variables assigned to. This is a set of all vars, not tracked vars.
6063 bool ivaMaskIncomplete; // Variables not representable in ivaMaskVal were assigned to.
6064 varRefKinds ivaMaskInd; // What kind of indirect assignments are there?
6065 callInterf ivaMaskCall; // What kind of calls are there?
6068 static callInterf optCallInterf(GenTreeCall* call);
6071 // VN based copy propagation.
6072 typedef ArrayStack<GenTree*> GenTreePtrStack;
6073 typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, GenTreePtrStack*> LclNumToGenTreePtrStack;
6075 // Kill set to track variables with intervening definitions.
6076 VARSET_TP optCopyPropKillSet;
6078 // Copy propagation functions.
6079 void optCopyProp(BasicBlock* block, GenTree* stmt, GenTree* tree, LclNumToGenTreePtrStack* curSsaName);
6080 void optBlockCopyPropPopStacks(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
6081 void optBlockCopyProp(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
6082 bool optIsSsaLocal(GenTree* tree);
6083 int optCopyProp_LclVarScore(LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc, bool preferOp2);
6084 void optVnCopyProp();
6085 INDEBUG(void optDumpCopyPropStack(LclNumToGenTreePtrStack* curSsaName));
6087 /**************************************************************************
6088 * Early value propagation
6089 *************************************************************************/
6095 SSAName(unsigned lvNum, unsigned ssaNum) : m_lvNum(lvNum), m_ssaNum(ssaNum)
6099 static unsigned GetHashCode(SSAName ssaNm)
6101 return (ssaNm.m_lvNum << 16) | (ssaNm.m_ssaNum);
6104 static bool Equals(SSAName ssaNm1, SSAName ssaNm2)
6106 return (ssaNm1.m_lvNum == ssaNm2.m_lvNum) && (ssaNm1.m_ssaNum == ssaNm2.m_ssaNum);
6110 #define OMF_HAS_NEWARRAY 0x00000001 // Method contains 'new' of an array
6111 #define OMF_HAS_NEWOBJ 0x00000002 // Method contains 'new' of an object type.
6112 #define OMF_HAS_ARRAYREF 0x00000004 // Method contains array element loads or stores.
6113 #define OMF_HAS_VTABLEREF 0x00000008 // Method contains method table reference.
6114 #define OMF_HAS_NULLCHECK 0x00000010 // Method contains null check.
6115 #define OMF_HAS_FATPOINTER 0x00000020 // Method contains call, that needs fat pointer transformation.
6117 bool doesMethodHaveFatPointer()
6119 return (optMethodFlags & OMF_HAS_FATPOINTER) != 0;
6122 void setMethodHasFatPointer()
6124 optMethodFlags |= OMF_HAS_FATPOINTER;
6127 void clearMethodHasFatPointer()
6129 optMethodFlags &= ~OMF_HAS_FATPOINTER;
6132 void addFatPointerCandidate(GenTreeCall* call);
6134 unsigned optMethodFlags;
6136 // Recursion bound controls how far we can go backwards tracking for a SSA value.
6137 // No throughput diff was found with backward walk bound between 3-8.
6138 static const int optEarlyPropRecurBound = 5;
6140 enum class optPropKind
6148 bool gtIsVtableRef(GenTree* tree);
6149 GenTree* getArrayLengthFromAllocation(GenTree* tree);
6150 GenTree* getObjectHandleNodeFromAllocation(GenTree* tree);
6151 GenTree* optPropGetValueRec(unsigned lclNum, unsigned ssaNum, optPropKind valueKind, int walkDepth);
6152 GenTree* optPropGetValue(unsigned lclNum, unsigned ssaNum, optPropKind valueKind);
6153 GenTree* optEarlyPropRewriteTree(GenTree* tree);
6154 bool optDoEarlyPropForBlock(BasicBlock* block);
6155 bool optDoEarlyPropForFunc();
6156 void optEarlyProp();
6157 void optFoldNullCheck(GenTree* tree);
6158 bool optCanMoveNullCheckPastTree(GenTree* tree, bool isInsideTry);
6161 /**************************************************************************
6162 * Value/Assertion propagation
6163 *************************************************************************/
6165 // Data structures for assertion prop
6166 BitVecTraits* apTraits;
6169 enum optAssertionKind
6186 O1K_CONSTANT_LOOP_BND,
6207 optAssertionKind assertionKind;
6210 unsigned lclNum; // assigned to or property of this local var number
6218 struct AssertionDscOp1
6220 optOp1Kind kind; // a normal LclVar, or Exact-type or Subtype
6227 struct AssertionDscOp2
6229 optOp2Kind kind; // a const or copy assignment
6233 ssize_t iconVal; // integer
6234 unsigned iconFlags; // gtFlags
6236 struct Range // integer subrange
6250 bool IsCheckedBoundArithBound()
6252 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_BOUND_OPER_BND);
6254 bool IsCheckedBoundBound()
6256 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_BOUND_LOOP_BND);
6258 bool IsConstantBound()
6260 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) &&
6261 op1.kind == O1K_CONSTANT_LOOP_BND);
6263 bool IsBoundsCheckNoThrow()
6265 return ((assertionKind == OAK_NO_THROW) && (op1.kind == O1K_ARR_BND));
6268 bool IsCopyAssertion()
6270 return ((assertionKind == OAK_EQUAL) && (op1.kind == O1K_LCLVAR) && (op2.kind == O2K_LCLVAR_COPY));
6273 static bool SameKind(AssertionDsc* a1, AssertionDsc* a2)
6275 return a1->assertionKind == a2->assertionKind && a1->op1.kind == a2->op1.kind &&
6276 a1->op2.kind == a2->op2.kind;
6279 static bool ComplementaryKind(optAssertionKind kind, optAssertionKind kind2)
6281 if (kind == OAK_EQUAL)
6283 return kind2 == OAK_NOT_EQUAL;
6285 else if (kind == OAK_NOT_EQUAL)
6287 return kind2 == OAK_EQUAL;
6292 static ssize_t GetLowerBoundForIntegralType(var_types type)
6311 static ssize_t GetUpperBoundForIntegralType(var_types type)
6334 bool HasSameOp1(AssertionDsc* that, bool vnBased)
6336 if (op1.kind != that->op1.kind)
6340 else if (op1.kind == O1K_ARR_BND)
6343 return (op1.bnd.vnIdx == that->op1.bnd.vnIdx) && (op1.bnd.vnLen == that->op1.bnd.vnLen);
6347 return ((vnBased && (op1.vn == that->op1.vn)) ||
6348 (!vnBased && (op1.lcl.lclNum == that->op1.lcl.lclNum)));
6352 bool HasSameOp2(AssertionDsc* that, bool vnBased)
6354 if (op2.kind != that->op2.kind)
6360 case O2K_IND_CNS_INT:
6362 return ((op2.u1.iconVal == that->op2.u1.iconVal) && (op2.u1.iconFlags == that->op2.u1.iconFlags));
6364 case O2K_CONST_LONG:
6365 return (op2.lconVal == that->op2.lconVal);
6367 case O2K_CONST_DOUBLE:
6368 // exact match because of positive and negative zero.
6369 return (memcmp(&op2.dconVal, &that->op2.dconVal, sizeof(double)) == 0);
6371 case O2K_LCLVAR_COPY:
6373 return (op2.lcl.lclNum == that->op2.lcl.lclNum) &&
6374 (!vnBased || op2.lcl.ssaNum == that->op2.lcl.ssaNum);
6377 return ((op2.u2.loBound == that->op2.u2.loBound) && (op2.u2.hiBound == that->op2.u2.hiBound));
6380 // we will return false
6384 assert(!"Unexpected value for op2.kind in AssertionDsc.");
6390 bool Complementary(AssertionDsc* that, bool vnBased)
6392 return ComplementaryKind(assertionKind, that->assertionKind) && HasSameOp1(that, vnBased) &&
6393 HasSameOp2(that, vnBased);
6396 bool Equals(AssertionDsc* that, bool vnBased)
6398 if (assertionKind != that->assertionKind)
6402 else if (assertionKind == OAK_NO_THROW)
6404 assert(op2.kind == O2K_INVALID);
6405 return HasSameOp1(that, vnBased);
6409 return HasSameOp1(that, vnBased) && HasSameOp2(that, vnBased);
6415 static fgWalkPreFn optAddCopiesCallback;
6416 static fgWalkPreFn optVNAssertionPropCurStmtVisitor;
6417 unsigned optAddCopyLclNum;
6418 GenTree* optAddCopyAsgnNode;
6420 bool optLocalAssertionProp; // indicates that we are performing local assertion prop
6421 bool optAssertionPropagated; // set to true if we modified the trees
6422 bool optAssertionPropagatedCurrentStmt;
6424 GenTree* optAssertionPropCurrentTree;
6426 AssertionIndex* optComplementaryAssertionMap;
6427 JitExpandArray<ASSERT_TP>* optAssertionDep; // table that holds dependent assertions (assertions
6428 // using the value of a local var) for each local var
6429 AssertionDsc* optAssertionTabPrivate; // table that holds info about value assignments
6430 AssertionIndex optAssertionCount; // total number of assertions in the assertion table
6431 AssertionIndex optMaxAssertionCount;
6434 void optVnNonNullPropCurStmt(BasicBlock* block, GenTree* stmt, GenTree* tree);
6435 fgWalkResult optVNConstantPropCurStmt(BasicBlock* block, GenTree* stmt, GenTree* tree);
6436 GenTree* optVNConstantPropOnJTrue(BasicBlock* block, GenTree* stmt, GenTree* test);
6437 GenTree* optVNConstantPropOnTree(BasicBlock* block, GenTree* stmt, GenTree* tree);
6438 GenTree* optPrepareTreeForReplacement(GenTree* extractTree, GenTree* replaceTree);
6440 AssertionIndex GetAssertionCount()
6442 return optAssertionCount;
6444 ASSERT_TP* bbJtrueAssertionOut;
6445 typedef JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, ASSERT_TP> ValueNumToAssertsMap;
6446 ValueNumToAssertsMap* optValueNumToAsserts;
6448 // Assertion prop helpers.
6449 ASSERT_TP& GetAssertionDep(unsigned lclNum);
6450 AssertionDsc* optGetAssertion(AssertionIndex assertIndex);
6451 void optAssertionInit(bool isLocalProp);
6452 void optAssertionTraitsInit(AssertionIndex assertionCount);
6453 #if LOCAL_ASSERTION_PROP
6454 void optAssertionReset(AssertionIndex limit);
6455 void optAssertionRemove(AssertionIndex index);
6458 // Assertion prop data flow functions.
6459 void optAssertionPropMain();
6460 GenTree* optVNAssertionPropCurStmt(BasicBlock* block, GenTree* stmt);
6461 bool optIsTreeKnownIntValue(bool vnBased, GenTree* tree, ssize_t* pConstant, unsigned* pIconFlags);
6462 ASSERT_TP* optInitAssertionDataflowFlags();
6463 ASSERT_TP* optComputeAssertionGen();
6465 // Assertion Gen functions.
6466 void optAssertionGen(GenTree* tree);
6467 AssertionIndex optAssertionGenPhiDefn(GenTree* tree);
6468 AssertionInfo optCreateJTrueBoundsAssertion(GenTree* tree);
6469 AssertionInfo optAssertionGenJtrue(GenTree* tree);
6470 AssertionIndex optCreateJtrueAssertions(GenTree* op1, GenTree* op2, Compiler::optAssertionKind assertionKind);
6471 AssertionIndex optFindComplementary(AssertionIndex assertionIndex);
6472 void optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index);
6474 // Assertion creation functions.
6475 AssertionIndex optCreateAssertion(GenTree* op1, GenTree* op2, optAssertionKind assertionKind);
6476 AssertionIndex optCreateAssertion(GenTree* op1,
6478 optAssertionKind assertionKind,
6479 AssertionDsc* assertion);
6480 void optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTree* op1, GenTree* op2);
6482 bool optAssertionVnInvolvesNan(AssertionDsc* assertion);
6483 AssertionIndex optAddAssertion(AssertionDsc* assertion);
6484 void optAddVnAssertionMapping(ValueNum vn, AssertionIndex index);
6486 void optPrintVnAssertionMapping();
6488 ASSERT_TP optGetVnMappedAssertions(ValueNum vn);
6490 // Used for respective assertion propagations.
6491 AssertionIndex optAssertionIsSubrange(GenTree* tree, var_types toType, ASSERT_VALARG_TP assertions);
6492 AssertionIndex optAssertionIsSubtype(GenTree* tree, GenTree* methodTableArg, ASSERT_VALARG_TP assertions);
6493 AssertionIndex optAssertionIsNonNullInternal(GenTree* op, ASSERT_VALARG_TP assertions);
6494 bool optAssertionIsNonNull(GenTree* op,
6495 ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex));
6497 // Used for Relop propagation.
6498 AssertionIndex optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTree* op1, GenTree* op2);
6499 AssertionIndex optLocalAssertionIsEqualOrNotEqual(
6500 optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions);
6502 // Assertion prop for lcl var functions.
6503 bool optAssertionProp_LclVarTypeCheck(GenTree* tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc);
6504 GenTree* optCopyAssertionProp(AssertionDsc* curAssertion,
6506 GenTree* stmt DEBUGARG(AssertionIndex index));
6507 GenTree* optConstantAssertionProp(AssertionDsc* curAssertion,
6509 GenTree* stmt DEBUGARG(AssertionIndex index));
6511 // Assertion propagation functions.
6512 GenTree* optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6513 GenTree* optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6514 GenTree* optAssertionProp_Ind(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6515 GenTree* optAssertionProp_Cast(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6516 GenTree* optAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, GenTree* stmt);
6517 GenTree* optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6518 GenTree* optAssertionProp_Comma(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6519 GenTree* optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6520 GenTree* optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6521 GenTree* optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6522 GenTree* optAssertionProp_Update(GenTree* newTree, GenTree* tree, GenTree* stmt);
6523 GenTree* optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, GenTree* stmt);
6525 // Implied assertion functions.
6526 void optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions);
6527 void optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions);
6528 void optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result);
6529 void optImpliedByConstAssertion(AssertionDsc* curAssertion, ASSERT_TP& result);
6532 void optPrintAssertion(AssertionDsc* newAssertion, AssertionIndex assertionIndex = 0);
6533 void optDebugCheckAssertion(AssertionDsc* assertion);
6534 void optDebugCheckAssertions(AssertionIndex AssertionIndex);
6536 void optAddCopies();
6537 #endif // ASSERTION_PROP
6539 /**************************************************************************
6541 *************************************************************************/
6544 struct LoopCloneVisitorInfo
6546 LoopCloneContext* context;
6549 LoopCloneVisitorInfo(LoopCloneContext* context, unsigned loopNum, GenTree* stmt)
6550 : context(context), loopNum(loopNum), stmt(nullptr)
6555 bool optIsStackLocalInvariant(unsigned loopNum, unsigned lclNum);
6556 bool optExtractArrIndex(GenTree* tree, ArrIndex* result, unsigned lhsNum);
6557 bool optReconstructArrIndex(GenTree* tree, ArrIndex* result, unsigned lhsNum);
6558 bool optIdentifyLoopOptInfo(unsigned loopNum, LoopCloneContext* context);
6559 static fgWalkPreFn optCanOptimizeByLoopCloningVisitor;
6560 fgWalkResult optCanOptimizeByLoopCloning(GenTree* tree, LoopCloneVisitorInfo* info);
6561 void optObtainLoopCloningOpts(LoopCloneContext* context);
6562 bool optIsLoopClonable(unsigned loopInd);
6564 bool optCanCloneLoops();
6567 void optDebugLogLoopCloning(BasicBlock* block, GenTree* insertBefore);
6569 void optPerformStaticOptimizations(unsigned loopNum, LoopCloneContext* context DEBUGARG(bool fastPath));
6570 bool optComputeDerefConditions(unsigned loopNum, LoopCloneContext* context);
6571 bool optDeriveLoopCloningConditions(unsigned loopNum, LoopCloneContext* context);
6572 BasicBlock* optInsertLoopChoiceConditions(LoopCloneContext* context,
6578 ssize_t optGetArrayRefScaleAndIndex(GenTree* mul, GenTree** pIndex DEBUGARG(bool bRngChk));
6580 bool optReachWithoutCall(BasicBlock* srcBB, BasicBlock* dstBB);
6583 bool optLoopsMarked;
6586 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6587 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6591 XX Does the register allocation and puts the remaining lclVars on the stack XX
6593 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6594 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6598 regNumber raUpdateRegStateForArg(RegState* regState, LclVarDsc* argDsc);
6600 void raMarkStkVars();
6603 // Some things are used by both LSRA and regpredict allocators.
6605 FrameType rpFrameType;
6606 bool rpMustCreateEBPCalled; // Set to true after we have called rpMustCreateEBPFrame once
6608 bool rpMustCreateEBPFrame(INDEBUG(const char** wbReason));
6611 Lowering* m_pLowering; // Lowering; needed to Lower IR that's added or modified after Lowering.
6612 LinearScanInterface* m_pLinearScan; // Linear Scan allocator
6614 /* raIsVarargsStackArg is called by raMaskStkVars and by
6615 lvaSortByRefCount. It identifies the special case
6616 where a varargs function has a parameter passed on the
6617 stack, other than the special varargs handle. Such parameters
6618 require special treatment, because they cannot be tracked
6619 by the GC (their offsets in the stack are not known
6623 bool raIsVarargsStackArg(unsigned lclNum)
6627 LclVarDsc* varDsc = &lvaTable[lclNum];
6629 assert(varDsc->lvIsParam);
6631 return (info.compIsVarArgs && !varDsc->lvIsRegArg && (lclNum != lvaVarargsHandleArg));
6633 #else // _TARGET_X86_
6637 #endif // _TARGET_X86_
6641 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6642 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6646 XX Get to the class and method info from the Execution Engine given XX
6647 XX tokens for the class and method XX
6649 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6650 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6654 /* These are the different addressing modes used to access a local var.
6655 * The JIT has to report the location of the locals back to the EE
6656 * for debugging purposes.
6662 VLT_REG_BYREF, // this type is currently only used for value types on X64
6665 VLT_STK_BYREF, // this type is currently only used for value types on X64
6679 siVarLocType vlType;
6682 // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc)
6684 // VLT_REG_BYREF -- the specified register contains the address of the variable
6692 // VLT_STK -- Any 32 bit value which is on the stack
6693 // eg. [ESP+0x20], or [EBP-0x28]
6694 // VLT_STK_BYREF -- the specified stack location contains the address of the variable
6695 // eg. mov EAX, [ESP+0x20]; [EAX]
6699 regNumber vlsBaseReg;
6700 NATIVE_OFFSET vlsOffset;
6703 // VLT_REG_REG -- TYP_LONG/TYP_DOUBLE with both DWords enregistered
6712 // VLT_REG_STK -- Partly enregistered TYP_LONG/TYP_DOUBLE
6713 // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] }
6721 regNumber vlrssBaseReg;
6722 NATIVE_OFFSET vlrssOffset;
6726 // VLT_STK_REG -- Partly enregistered TYP_LONG/TYP_DOUBLE
6727 // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX }
6733 regNumber vlsrsBaseReg;
6734 NATIVE_OFFSET vlsrsOffset;
6740 // VLT_STK2 -- Any 64 bit value which is on the stack, in 2 successsive DWords
6741 // eg 2 DWords at [ESP+0x10]
6745 regNumber vls2BaseReg;
6746 NATIVE_OFFSET vls2Offset;
6749 // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack)
6750 // eg. ST(3). Actually it is ST("FPstkHeight - vpFpStk")
6757 // VLT_FIXED_VA -- fixed argument of a varargs function.
6758 // The argument location depends on the size of the variable
6759 // arguments (...). Inspecting the VARARGS_HANDLE indicates the
6760 // location of the first arg. This argument can then be accessed
6761 // relative to the position of the first arg
6765 unsigned vlfvOffset;
6772 void* rpValue; // pointer to the in-process
6773 // location of the value.
6779 bool vlIsInReg(regNumber reg);
6780 bool vlIsOnStk(regNumber reg, signed offset);
6783 /*************************************************************************/
6788 void eeGetCallInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6789 CORINFO_RESOLVED_TOKEN* pConstrainedToken,
6790 CORINFO_CALLINFO_FLAGS flags,
6791 CORINFO_CALL_INFO* pResult);
6792 inline CORINFO_CALLINFO_FLAGS addVerifyFlag(CORINFO_CALLINFO_FLAGS flags);
6794 void eeGetFieldInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6795 CORINFO_ACCESS_FLAGS flags,
6796 CORINFO_FIELD_INFO* pResult);
6800 BOOL eeIsValueClass(CORINFO_CLASS_HANDLE clsHnd);
6802 #if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) || defined(TRACK_LSRA_STATS)
6804 bool IsSuperPMIException(unsigned code)
6806 // Copied from NDP\clr\src\ToolBox\SuperPMI\SuperPMI-Shared\ErrorHandling.h
6808 const unsigned EXCEPTIONCODE_DebugBreakorAV = 0xe0421000;
6809 const unsigned EXCEPTIONCODE_MC = 0xe0422000;
6810 const unsigned EXCEPTIONCODE_LWM = 0xe0423000;
6811 const unsigned EXCEPTIONCODE_SASM = 0xe0424000;
6812 const unsigned EXCEPTIONCODE_SSYM = 0xe0425000;
6813 const unsigned EXCEPTIONCODE_CALLUTILS = 0xe0426000;
6814 const unsigned EXCEPTIONCODE_TYPEUTILS = 0xe0427000;
6815 const unsigned EXCEPTIONCODE_ASSERT = 0xe0440000;
6819 case EXCEPTIONCODE_DebugBreakorAV:
6820 case EXCEPTIONCODE_MC:
6821 case EXCEPTIONCODE_LWM:
6822 case EXCEPTIONCODE_SASM:
6823 case EXCEPTIONCODE_SSYM:
6824 case EXCEPTIONCODE_CALLUTILS:
6825 case EXCEPTIONCODE_TYPEUTILS:
6826 case EXCEPTIONCODE_ASSERT:
6833 const char* eeGetMethodName(CORINFO_METHOD_HANDLE hnd, const char** className);
6834 const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd);
6836 bool eeIsNativeMethod(CORINFO_METHOD_HANDLE method);
6837 CORINFO_METHOD_HANDLE eeGetMethodHandleForNative(CORINFO_METHOD_HANDLE method);
6840 var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6841 var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig, bool* isPinned);
6842 unsigned eeGetArgSize(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6844 // VOM info, method sigs
6846 void eeGetSig(unsigned sigTok,
6847 CORINFO_MODULE_HANDLE scope,
6848 CORINFO_CONTEXT_HANDLE context,
6849 CORINFO_SIG_INFO* retSig);
6851 void eeGetCallSiteSig(unsigned sigTok,
6852 CORINFO_MODULE_HANDLE scope,
6853 CORINFO_CONTEXT_HANDLE context,
6854 CORINFO_SIG_INFO* retSig);
6856 void eeGetMethodSig(CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* retSig, CORINFO_CLASS_HANDLE owner = nullptr);
6858 // Method entry-points, instrs
6860 CORINFO_METHOD_HANDLE eeMarkNativeTarget(CORINFO_METHOD_HANDLE method);
6862 CORINFO_EE_INFO eeInfo;
6863 bool eeInfoInitialized;
6865 CORINFO_EE_INFO* eeGetEEInfo();
6867 // Gets the offset of a SDArray's first element
6868 unsigned eeGetArrayDataOffset(var_types type);
6869 // Gets the offset of a MDArray's first element
6870 unsigned eeGetMDArrayDataOffset(var_types type, unsigned rank);
6872 GenTree* eeGetPInvokeCookie(CORINFO_SIG_INFO* szMetaSig);
6874 // Returns the page size for the target machine as reported by the EE.
6875 inline target_size_t eeGetPageSize()
6877 return (target_size_t)eeGetEEInfo()->osPageSize;
6880 // Returns the frame size at which we will generate a loop to probe the stack.
6881 inline target_size_t getVeryLargeFrameSize()
6884 // The looping probe code is 40 bytes, whereas the straight-line probing for
6885 // the (0x2000..0x3000) case is 44, so use looping for anything 0x2000 bytes
6886 // or greater, to generate smaller code.
6887 return 2 * eeGetPageSize();
6889 return 3 * eeGetPageSize();
6893 //------------------------------------------------------------------------
6894 // VirtualStubParam: virtual stub dispatch extra parameter (slot address).
6896 // It represents Abi and target specific registers for the parameter.
6898 class VirtualStubParamInfo
6901 VirtualStubParamInfo(bool isCoreRTABI)
6903 #if defined(_TARGET_X86_)
6906 #elif defined(_TARGET_AMD64_)
6917 #elif defined(_TARGET_ARM_)
6928 #elif defined(_TARGET_ARM64_)
6932 #error Unsupported or unset target architecture
6936 regNumber GetReg() const
6941 _regMask_enum GetRegMask() const
6948 _regMask_enum regMask;
6951 VirtualStubParamInfo* virtualStubParamInfo;
6953 inline bool IsTargetAbi(CORINFO_RUNTIME_ABI abi)
6955 return eeGetEEInfo()->targetAbi == abi;
6958 inline bool generateCFIUnwindCodes()
6960 #if defined(_TARGET_UNIX_)
6961 return IsTargetAbi(CORINFO_CORERT_ABI);
6967 // Debugging support - Line number info
6969 void eeGetStmtOffsets();
6971 unsigned eeBoundariesCount;
6973 struct boundariesDsc
6975 UNATIVE_OFFSET nativeIP;
6977 unsigned sourceReason;
6978 } * eeBoundaries; // Boundaries to report to EE
6979 void eeSetLIcount(unsigned count);
6980 void eeSetLIinfo(unsigned which, UNATIVE_OFFSET offs, unsigned srcIP, bool stkEmpty, bool callInstruction);
6984 static void eeDispILOffs(IL_OFFSET offs);
6985 static void eeDispLineInfo(const boundariesDsc* line);
6986 void eeDispLineInfos();
6989 // Debugging support - Local var info
6993 unsigned eeVarsCount;
6995 struct VarResultInfo
6997 UNATIVE_OFFSET startOffset;
6998 UNATIVE_OFFSET endOffset;
7002 void eeSetLVcount(unsigned count);
7003 void eeSetLVinfo(unsigned which,
7004 UNATIVE_OFFSET startOffs,
7005 UNATIVE_OFFSET length,
7010 const siVarLoc& loc);
7014 void eeDispVar(ICorDebugInfo::NativeVarInfo* var);
7015 void eeDispVars(CORINFO_METHOD_HANDLE ftn, ULONG32 cVars, ICorDebugInfo::NativeVarInfo* vars);
7018 // ICorJitInfo wrappers
7020 void eeReserveUnwindInfo(BOOL isFunclet, BOOL isColdCode, ULONG unwindSize);
7022 void eeAllocUnwindInfo(BYTE* pHotCode,
7028 CorJitFuncKind funcKind);
7030 void eeSetEHcount(unsigned cEH);
7032 void eeSetEHinfo(unsigned EHnumber, const CORINFO_EH_CLAUSE* clause);
7034 WORD eeGetRelocTypeHint(void* target);
7036 // ICorStaticInfo wrapper functions
7038 bool eeTryResolveToken(CORINFO_RESOLVED_TOKEN* resolvedToken);
7040 #if defined(UNIX_AMD64_ABI)
7042 static void dumpSystemVClassificationType(SystemVClassificationType ct);
7045 void eeGetSystemVAmd64PassStructInRegisterDescriptor(
7046 /*IN*/ CORINFO_CLASS_HANDLE structHnd,
7047 /*OUT*/ SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr);
7048 #endif // UNIX_AMD64_ABI
7050 template <typename ParamType>
7051 bool eeRunWithErrorTrap(void (*function)(ParamType*), ParamType* param)
7053 return eeRunWithErrorTrapImp(reinterpret_cast<void (*)(void*)>(function), reinterpret_cast<void*>(param));
7056 bool eeRunWithErrorTrapImp(void (*function)(void*), void* param);
7058 // Utility functions
7060 const char* eeGetFieldName(CORINFO_FIELD_HANDLE fieldHnd, const char** classNamePtr = nullptr);
7063 const wchar_t* eeGetCPString(size_t stringHandle);
7066 const char* eeGetClassName(CORINFO_CLASS_HANDLE clsHnd);
7068 static CORINFO_METHOD_HANDLE eeFindHelper(unsigned helper);
7069 static CorInfoHelpFunc eeGetHelperNum(CORINFO_METHOD_HANDLE method);
7071 static fgWalkPreFn CountSharedStaticHelper;
7072 static bool IsSharedStaticHelper(GenTree* tree);
7073 static bool IsTreeAlwaysHoistable(GenTree* tree);
7074 static bool IsGcSafePoint(GenTree* tree);
7076 static CORINFO_FIELD_HANDLE eeFindJitDataOffs(unsigned jitDataOffs);
7077 // returns true/false if 'field' is a Jit Data offset
7078 static bool eeIsJitDataOffs(CORINFO_FIELD_HANDLE field);
7079 // returns a number < 0 if 'field' is not a Jit Data offset, otherwise the data offset (limited to 2GB)
7080 static int eeGetJitDataOffs(CORINFO_FIELD_HANDLE field);
7082 /*****************************************************************************/
7085 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7086 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7090 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7091 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7095 CodeGenInterface* codeGen;
7097 // The following holds information about instr offsets in terms of generated code.
7101 IPmappingDsc* ipmdNext; // next line# record
7102 IL_OFFSETX ipmdILoffsx; // the instr offset
7103 emitLocation ipmdNativeLoc; // the emitter location of the native code corresponding to the IL offset
7104 bool ipmdIsLabel; // Can this code be a branch label?
7107 // Record the instr offset mapping to the generated code
7109 IPmappingDsc* genIPmappingList;
7110 IPmappingDsc* genIPmappingLast;
7112 // Managed RetVal - A side hash table meant to record the mapping from a
7113 // GT_CALL node to its IL offset. This info is used to emit sequence points
7114 // that can be used by debugger to determine the native offset at which the
7115 // managed RetVal will be available.
7117 // In fact we can store IL offset in a GT_CALL node. This was ruled out in
7118 // favor of a side table for two reasons: 1) We need IL offset for only those
7119 // GT_CALL nodes (created during importation) that correspond to an IL call and
7120 // whose return type is other than TYP_VOID. 2) GT_CALL node is a frequently used
7121 // structure and IL offset is needed only when generating debuggable code. Therefore
7122 // it is desirable to avoid memory size penalty in retail scenarios.
7123 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, IL_OFFSETX> CallSiteILOffsetTable;
7124 CallSiteILOffsetTable* genCallSite2ILOffsetMap;
7126 unsigned genReturnLocal; // Local number for the return value when applicable.
7127 BasicBlock* genReturnBB; // jumped to when not optimizing for speed.
7129 // The following properties are part of CodeGenContext. Getters are provided here for
7130 // convenience and backward compatibility, but the properties can only be set by invoking
7131 // the setter on CodeGenContext directly.
7133 __declspec(property(get = getEmitter)) emitter* genEmitter;
7134 emitter* getEmitter()
7136 return codeGen->getEmitter();
7139 const bool isFramePointerUsed()
7141 return codeGen->isFramePointerUsed();
7144 __declspec(property(get = getInterruptible, put = setInterruptible)) bool genInterruptible;
7145 bool getInterruptible()
7147 return codeGen->genInterruptible;
7149 void setInterruptible(bool value)
7151 codeGen->setInterruptible(value);
7154 #ifdef _TARGET_ARMARCH_
7155 __declspec(property(get = getHasTailCalls, put = setHasTailCalls)) bool hasTailCalls;
7156 bool getHasTailCalls()
7158 return codeGen->hasTailCalls;
7160 void setHasTailCalls(bool value)
7162 codeGen->setHasTailCalls(value);
7164 #endif // _TARGET_ARMARCH_
7167 const bool genDoubleAlign()
7169 return codeGen->doDoubleAlign();
7171 DWORD getCanDoubleAlign();
7172 bool shouldDoubleAlign(unsigned refCntStk,
7174 unsigned refCntWtdReg,
7175 unsigned refCntStkParam,
7176 unsigned refCntWtdStkDbl);
7177 #endif // DOUBLE_ALIGN
7179 __declspec(property(get = getFullPtrRegMap, put = setFullPtrRegMap)) bool genFullPtrRegMap;
7180 bool getFullPtrRegMap()
7182 return codeGen->genFullPtrRegMap;
7184 void setFullPtrRegMap(bool value)
7186 codeGen->setFullPtrRegMap(value);
7189 // Things that MAY belong either in CodeGen or CodeGenContext
7191 #if FEATURE_EH_FUNCLETS
7192 FuncInfoDsc* compFuncInfos;
7193 unsigned short compCurrFuncIdx;
7194 unsigned short compFuncInfoCount;
7196 unsigned short compFuncCount()
7198 assert(fgFuncletsCreated);
7199 return compFuncInfoCount;
7202 #else // !FEATURE_EH_FUNCLETS
7204 // This is a no-op when there are no funclets!
7205 void genUpdateCurrentFunclet(BasicBlock* block)
7210 FuncInfoDsc compFuncInfoRoot;
7212 static const unsigned compCurrFuncIdx = 0;
7214 unsigned short compFuncCount()
7219 #endif // !FEATURE_EH_FUNCLETS
7221 FuncInfoDsc* funCurrentFunc();
7222 void funSetCurrentFunc(unsigned funcIdx);
7223 FuncInfoDsc* funGetFunc(unsigned funcIdx);
7224 unsigned int funGetFuncIdx(BasicBlock* block);
7228 VARSET_TP compCurLife; // current live variables
7229 GenTree* compCurLifeTree; // node after which compCurLife has been computed
7231 template <bool ForCodeGen>
7232 void compChangeLife(VARSET_VALARG_TP newLife);
7234 void genChangeLife(VARSET_VALARG_TP newLife)
7236 compChangeLife</*ForCodeGen*/ true>(newLife);
7239 template <bool ForCodeGen>
7240 inline void compUpdateLife(VARSET_VALARG_TP newLife);
7242 // Gets a register mask that represent the kill set for a helper call since
7243 // not all JIT Helper calls follow the standard ABI on the target architecture.
7244 regMaskTP compHelperCallKillSet(CorInfoHelpFunc helper);
7246 // Gets a register mask that represent the kill set for a NoGC helper call.
7247 regMaskTP compNoGCHelperCallKillSet(CorInfoHelpFunc helper);
7250 // Requires that "varDsc" be a promoted struct local variable being passed as an argument, beginning at
7251 // "firstArgRegNum", which is assumed to have already been aligned to the register alignment restriction of the
7252 // struct type. Adds bits to "*pArgSkippedRegMask" for any argument registers *not* used in passing "varDsc" --
7253 // i.e., internal "holes" caused by internal alignment constraints. For example, if the struct contained an int and
7254 // a double, and we at R0 (on ARM), then R1 would be skipped, and the bit for R1 would be added to the mask.
7255 void fgAddSkippedRegsInPromotedStructArg(LclVarDsc* varDsc, unsigned firstArgRegNum, regMaskTP* pArgSkippedRegMask);
7256 #endif // _TARGET_ARM_
7258 // 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
7260 static GenTree* fgIsIndirOfAddrOfLocal(GenTree* tree);
7262 // This map is indexed by GT_OBJ nodes that are address of promoted struct variables, which
7263 // have been annotated with the GTF_VAR_DEATH flag. If such a node is *not* mapped in this
7264 // table, one may assume that all the (tracked) field vars die at this GT_OBJ. Otherwise,
7265 // the node maps to a pointer to a VARSET_TP, containing set bits for each of the tracked field
7266 // vars of the promoted struct local that go dead at the given node (the set bits are the bits
7267 // for the tracked var indices of the field vars, as in a live var set).
7269 // The map is allocated on demand so all map operations should use one of the following three
7272 NodeToVarsetPtrMap* m_promotedStructDeathVars;
7274 NodeToVarsetPtrMap* GetPromotedStructDeathVars()
7276 if (m_promotedStructDeathVars == nullptr)
7278 m_promotedStructDeathVars = new (getAllocator()) NodeToVarsetPtrMap(getAllocator());
7280 return m_promotedStructDeathVars;
7283 void ClearPromotedStructDeathVars()
7285 if (m_promotedStructDeathVars != nullptr)
7287 m_promotedStructDeathVars->RemoveAll();
7291 bool LookupPromotedStructDeathVars(GenTree* tree, VARSET_TP** bits)
7294 bool result = false;
7296 if (m_promotedStructDeathVars != nullptr)
7298 result = m_promotedStructDeathVars->Lookup(tree, bits);
7305 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7306 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7310 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7311 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7314 #if !defined(__GNUC__)
7315 #pragma region Unwind information
7320 // Infrastructure functions: start/stop/reserve/emit.
7323 void unwindBegProlog();
7324 void unwindEndProlog();
7325 void unwindBegEpilog();
7326 void unwindEndEpilog();
7327 void unwindReserve();
7328 void unwindEmit(void* pHotCode, void* pColdCode);
7331 // Specific unwind information functions: called by code generation to indicate a particular
7332 // prolog or epilog unwindable instruction has been generated.
7335 void unwindPush(regNumber reg);
7336 void unwindAllocStack(unsigned size);
7337 void unwindSetFrameReg(regNumber reg, unsigned offset);
7338 void unwindSaveReg(regNumber reg, unsigned offset);
7340 #if defined(_TARGET_ARM_)
7341 void unwindPushMaskInt(regMaskTP mask);
7342 void unwindPushMaskFloat(regMaskTP mask);
7343 void unwindPopMaskInt(regMaskTP mask);
7344 void unwindPopMaskFloat(regMaskTP mask);
7345 void unwindBranch16(); // The epilog terminates with a 16-bit branch (e.g., "bx lr")
7346 void unwindNop(unsigned codeSizeInBytes); // Generate unwind NOP code. 'codeSizeInBytes' is 2 or 4 bytes. Only
7347 // called via unwindPadding().
7348 void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
7349 // instruction and the current location.
7350 #endif // _TARGET_ARM_
7352 #if defined(_TARGET_ARM64_)
7354 void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
7355 // instruction and the current location.
7356 void unwindSaveReg(regNumber reg, int offset); // str reg, [sp, #offset]
7357 void unwindSaveRegPreindexed(regNumber reg, int offset); // str reg, [sp, #offset]!
7358 void unwindSaveRegPair(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]
7359 void unwindSaveRegPairPreindexed(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]!
7360 void unwindSaveNext(); // unwind code: save_next
7361 void unwindReturn(regNumber reg); // ret lr
7362 #endif // defined(_TARGET_ARM64_)
7365 // Private "helper" functions for the unwind implementation.
7369 #if FEATURE_EH_FUNCLETS
7370 void unwindGetFuncLocations(FuncInfoDsc* func,
7371 bool getHotSectionData,
7372 /* OUT */ emitLocation** ppStartLoc,
7373 /* OUT */ emitLocation** ppEndLoc);
7374 #endif // FEATURE_EH_FUNCLETS
7376 void unwindReserveFunc(FuncInfoDsc* func);
7377 void unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
7379 #if defined(_TARGET_AMD64_) || (defined(_TARGET_X86_) && FEATURE_EH_FUNCLETS)
7381 void unwindReserveFuncHelper(FuncInfoDsc* func, bool isHotCode);
7382 void unwindEmitFuncHelper(FuncInfoDsc* func, void* pHotCode, void* pColdCode, bool isHotCode);
7384 #endif // _TARGET_AMD64_ || (_TARGET_X86_ && FEATURE_EH_FUNCLETS)
7386 UNATIVE_OFFSET unwindGetCurrentOffset(FuncInfoDsc* func);
7388 #if defined(_TARGET_AMD64_)
7390 void unwindBegPrologWindows();
7391 void unwindPushWindows(regNumber reg);
7392 void unwindAllocStackWindows(unsigned size);
7393 void unwindSetFrameRegWindows(regNumber reg, unsigned offset);
7394 void unwindSaveRegWindows(regNumber reg, unsigned offset);
7396 #ifdef UNIX_AMD64_ABI
7397 void unwindSaveRegCFI(regNumber reg, unsigned offset);
7398 #endif // UNIX_AMD64_ABI
7399 #elif defined(_TARGET_ARM_)
7401 void unwindPushPopMaskInt(regMaskTP mask, bool useOpsize16);
7402 void unwindPushPopMaskFloat(regMaskTP mask);
7404 #endif // _TARGET_ARM_
7406 #if defined(_TARGET_UNIX_)
7407 int mapRegNumToDwarfReg(regNumber reg);
7408 void createCfiCode(FuncInfoDsc* func, UCHAR codeOffset, UCHAR opcode, USHORT dwarfReg, INT offset = 0);
7409 void unwindPushPopCFI(regNumber reg);
7410 void unwindBegPrologCFI();
7411 void unwindPushPopMaskCFI(regMaskTP regMask, bool isFloat);
7412 void unwindAllocStackCFI(unsigned size);
7413 void unwindSetFrameRegCFI(regNumber reg, unsigned offset);
7414 void unwindEmitFuncCFI(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
7416 void DumpCfiInfo(bool isHotCode,
7417 UNATIVE_OFFSET startOffset,
7418 UNATIVE_OFFSET endOffset,
7420 const CFI_CODE* const pCfiCode);
7422 #if defined(_TARGET_ARM_)
7423 bool unwindCfiEpilogFormed; // Avoid duplicated unwind info for methods with multiple epilogs (we expect and require
7424 // all the epilogs to be precisely the same)
7427 #endif // _TARGET_UNIX_
7429 #if !defined(__GNUC__)
7430 #pragma endregion // Note: region is NOT under !defined(__GNUC__)
7434 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7435 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7439 XX Info about SIMD types, methods and the SIMD assembly (i.e. the assembly XX
7440 XX that contains the distinguished, well-known SIMD type definitions). XX
7442 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7443 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7446 // Get highest available level for SIMD codegen
7447 SIMDLevel getSIMDSupportLevel()
7449 #if defined(_TARGET_XARCH_)
7450 if (compSupports(InstructionSet_AVX2))
7452 return SIMD_AVX2_Supported;
7455 // SIMD_SSE4_Supported actually requires all of SSE3, SSSE3, SSE4.1, and SSE4.2
7456 // to be supported. We can only enable it if all four are enabled in the compiler
7457 if (compSupports(InstructionSet_SSE42) && compSupports(InstructionSet_SSE41) &&
7458 compSupports(InstructionSet_SSSE3) && compSupports(InstructionSet_SSE3))
7460 return SIMD_SSE4_Supported;
7464 return SIMD_SSE2_Supported;
7466 assert(!"Available instruction set(s) for SIMD codegen is not defined for target arch");
7468 return SIMD_Not_Supported;
7474 // Should we support SIMD intrinsics?
7477 // Have we identified any SIMD types?
7478 // This is currently used by struct promotion to avoid getting type information for a struct
7479 // field to see if it is a SIMD type, if we haven't seen any SIMD types or operations in
7481 bool _usesSIMDTypes;
7482 bool usesSIMDTypes()
7484 return _usesSIMDTypes;
7486 void setUsesSIMDTypes(bool value)
7488 _usesSIMDTypes = value;
7491 // This is a temp lclVar allocated on the stack as TYP_SIMD. It is used to implement intrinsics
7492 // that require indexed access to the individual fields of the vector, which is not well supported
7493 // by the hardware. It is allocated when/if such situations are encountered during Lowering.
7494 unsigned lvaSIMDInitTempVarNum;
7496 struct SIMDHandlesCache
7499 CORINFO_CLASS_HANDLE SIMDFloatHandle;
7500 CORINFO_CLASS_HANDLE SIMDDoubleHandle;
7501 CORINFO_CLASS_HANDLE SIMDIntHandle;
7502 CORINFO_CLASS_HANDLE SIMDUShortHandle;
7503 CORINFO_CLASS_HANDLE SIMDUByteHandle;
7504 CORINFO_CLASS_HANDLE SIMDShortHandle;
7505 CORINFO_CLASS_HANDLE SIMDByteHandle;
7506 CORINFO_CLASS_HANDLE SIMDLongHandle;
7507 CORINFO_CLASS_HANDLE SIMDUIntHandle;
7508 CORINFO_CLASS_HANDLE SIMDULongHandle;
7509 CORINFO_CLASS_HANDLE SIMDVector2Handle;
7510 CORINFO_CLASS_HANDLE SIMDVector3Handle;
7511 CORINFO_CLASS_HANDLE SIMDVector4Handle;
7512 CORINFO_CLASS_HANDLE SIMDVectorHandle;
7514 #ifdef FEATURE_HW_INTRINSICS
7515 #if defined(_TARGET_ARM64_)
7516 CORINFO_CLASS_HANDLE Vector64FloatHandle;
7517 CORINFO_CLASS_HANDLE Vector64UIntHandle;
7518 CORINFO_CLASS_HANDLE Vector64UShortHandle;
7519 CORINFO_CLASS_HANDLE Vector64UByteHandle;
7520 CORINFO_CLASS_HANDLE Vector64ShortHandle;
7521 CORINFO_CLASS_HANDLE Vector64ByteHandle;
7522 CORINFO_CLASS_HANDLE Vector64IntHandle;
7523 #endif // defined(_TARGET_ARM64_)
7524 CORINFO_CLASS_HANDLE Vector128FloatHandle;
7525 CORINFO_CLASS_HANDLE Vector128DoubleHandle;
7526 CORINFO_CLASS_HANDLE Vector128IntHandle;
7527 CORINFO_CLASS_HANDLE Vector128UShortHandle;
7528 CORINFO_CLASS_HANDLE Vector128UByteHandle;
7529 CORINFO_CLASS_HANDLE Vector128ShortHandle;
7530 CORINFO_CLASS_HANDLE Vector128ByteHandle;
7531 CORINFO_CLASS_HANDLE Vector128LongHandle;
7532 CORINFO_CLASS_HANDLE Vector128UIntHandle;
7533 CORINFO_CLASS_HANDLE Vector128ULongHandle;
7534 #if defined(_TARGET_XARCH_)
7535 CORINFO_CLASS_HANDLE Vector256FloatHandle;
7536 CORINFO_CLASS_HANDLE Vector256DoubleHandle;
7537 CORINFO_CLASS_HANDLE Vector256IntHandle;
7538 CORINFO_CLASS_HANDLE Vector256UShortHandle;
7539 CORINFO_CLASS_HANDLE Vector256UByteHandle;
7540 CORINFO_CLASS_HANDLE Vector256ShortHandle;
7541 CORINFO_CLASS_HANDLE Vector256ByteHandle;
7542 CORINFO_CLASS_HANDLE Vector256LongHandle;
7543 CORINFO_CLASS_HANDLE Vector256UIntHandle;
7544 CORINFO_CLASS_HANDLE Vector256ULongHandle;
7545 #endif // defined(_TARGET_XARCH_)
7546 #endif // FEATURE_HW_INTRINSICS
7550 memset(this, 0, sizeof(*this));
7554 SIMDHandlesCache* m_simdHandleCache;
7556 // Get the handle for a SIMD type.
7557 CORINFO_CLASS_HANDLE gtGetStructHandleForSIMD(var_types simdType, var_types simdBaseType)
7559 if (m_simdHandleCache == nullptr)
7561 // This may happen if the JIT generates SIMD node on its own, without importing them.
7562 // Otherwise getBaseTypeAndSizeOfSIMDType should have created the cache.
7563 return NO_CLASS_HANDLE;
7566 if (simdBaseType == TYP_FLOAT)
7571 return m_simdHandleCache->SIMDVector2Handle;
7573 return m_simdHandleCache->SIMDVector3Handle;
7575 if ((getSIMDVectorType() == TYP_SIMD32) ||
7576 (m_simdHandleCache->SIMDVector4Handle != NO_CLASS_HANDLE))
7578 return m_simdHandleCache->SIMDVector4Handle;
7587 assert(simdType == getSIMDVectorType());
7588 switch (simdBaseType)
7591 return m_simdHandleCache->SIMDFloatHandle;
7593 return m_simdHandleCache->SIMDDoubleHandle;
7595 return m_simdHandleCache->SIMDIntHandle;
7597 return m_simdHandleCache->SIMDUShortHandle;
7599 return m_simdHandleCache->SIMDUByteHandle;
7601 return m_simdHandleCache->SIMDShortHandle;
7603 return m_simdHandleCache->SIMDByteHandle;
7605 return m_simdHandleCache->SIMDLongHandle;
7607 return m_simdHandleCache->SIMDUIntHandle;
7609 return m_simdHandleCache->SIMDULongHandle;
7611 assert(!"Didn't find a class handle for simdType");
7613 return NO_CLASS_HANDLE;
7616 // Returns true if the tree corresponds to a TYP_SIMD lcl var.
7617 // Note that both SIMD vector args and locals are mared as lvSIMDType = true, but
7618 // type of an arg node is TYP_BYREF and a local node is TYP_SIMD or TYP_STRUCT.
7619 bool isSIMDTypeLocal(GenTree* tree)
7621 return tree->OperIsLocal() && lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
7624 // Returns true if the type of the tree is a byref of TYP_SIMD
7625 bool isAddrOfSIMDType(GenTree* tree)
7627 if (tree->TypeGet() == TYP_BYREF || tree->TypeGet() == TYP_I_IMPL)
7629 switch (tree->OperGet())
7632 return varTypeIsSIMD(tree->gtGetOp1());
7634 case GT_LCL_VAR_ADDR:
7635 return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
7638 return isSIMDTypeLocal(tree);
7645 static bool isRelOpSIMDIntrinsic(SIMDIntrinsicID intrinsicId)
7647 return (intrinsicId == SIMDIntrinsicEqual || intrinsicId == SIMDIntrinsicLessThan ||
7648 intrinsicId == SIMDIntrinsicLessThanOrEqual || intrinsicId == SIMDIntrinsicGreaterThan ||
7649 intrinsicId == SIMDIntrinsicGreaterThanOrEqual);
7652 // Returns base type of a TYP_SIMD local.
7653 // Returns TYP_UNKNOWN if the local is not TYP_SIMD.
7654 var_types getBaseTypeOfSIMDLocal(GenTree* tree)
7656 if (isSIMDTypeLocal(tree))
7658 return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvBaseType;
7664 bool isSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7666 return info.compCompHnd->isInSIMDModule(clsHnd);
7669 bool isIntrinsicType(CORINFO_CLASS_HANDLE clsHnd)
7671 return (info.compCompHnd->getClassAttribs(clsHnd) & CORINFO_FLG_INTRINSIC_TYPE) != 0;
7674 const char* getClassNameFromMetadata(CORINFO_CLASS_HANDLE cls, const char** namespaceName)
7676 return info.compCompHnd->getClassNameFromMetadata(cls, namespaceName);
7679 CORINFO_CLASS_HANDLE getTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, unsigned index)
7681 return info.compCompHnd->getTypeInstantiationArgument(cls, index);
7684 bool isSIMDClass(typeInfo* pTypeInfo)
7686 return pTypeInfo->IsStruct() && isSIMDClass(pTypeInfo->GetClassHandleForValueClass());
7689 bool isHWSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7691 #ifdef FEATURE_HW_INTRINSICS
7692 if (isIntrinsicType(clsHnd))
7694 const char* namespaceName = nullptr;
7695 (void)getClassNameFromMetadata(clsHnd, &namespaceName);
7696 return strcmp(namespaceName, "System.Runtime.Intrinsics") == 0;
7698 #endif // FEATURE_HW_INTRINSICS
7702 bool isHWSIMDClass(typeInfo* pTypeInfo)
7704 #ifdef FEATURE_HW_INTRINSICS
7705 return pTypeInfo->IsStruct() && isHWSIMDClass(pTypeInfo->GetClassHandleForValueClass());
7711 bool isSIMDorHWSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7713 return isSIMDClass(clsHnd) || isHWSIMDClass(clsHnd);
7716 bool isSIMDorHWSIMDClass(typeInfo* pTypeInfo)
7718 return isSIMDClass(pTypeInfo) || isHWSIMDClass(pTypeInfo);
7721 // Get the base (element) type and size in bytes for a SIMD type. Returns TYP_UNKNOWN
7722 // if it is not a SIMD type or is an unsupported base type.
7723 var_types getBaseTypeAndSizeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd, unsigned* sizeBytes = nullptr);
7725 var_types getBaseTypeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd)
7727 return getBaseTypeAndSizeOfSIMDType(typeHnd, nullptr);
7730 // Get SIMD Intrinsic info given the method handle.
7731 // Also sets typeHnd, argCount, baseType and sizeBytes out params.
7732 const SIMDIntrinsicInfo* getSIMDIntrinsicInfo(CORINFO_CLASS_HANDLE* typeHnd,
7733 CORINFO_METHOD_HANDLE methodHnd,
7734 CORINFO_SIG_INFO* sig,
7737 var_types* baseType,
7738 unsigned* sizeBytes);
7740 // Pops and returns GenTree node from importers type stack.
7741 // Normalizes TYP_STRUCT value in case of GT_CALL, GT_RET_EXPR and arg nodes.
7742 GenTree* impSIMDPopStack(var_types type, bool expectAddr = false, CORINFO_CLASS_HANDLE structType = nullptr);
7744 // Create a GT_SIMD tree for a Get property of SIMD vector with a fixed index.
7745 GenTreeSIMD* impSIMDGetFixed(var_types simdType, var_types baseType, unsigned simdSize, int index);
7747 // Creates a GT_SIMD tree for Select operation
7748 GenTree* impSIMDSelect(CORINFO_CLASS_HANDLE typeHnd,
7750 unsigned simdVectorSize,
7755 // Creates a GT_SIMD tree for Min/Max operation
7756 GenTree* impSIMDMinMax(SIMDIntrinsicID intrinsicId,
7757 CORINFO_CLASS_HANDLE typeHnd,
7759 unsigned simdVectorSize,
7763 // Transforms operands and returns the SIMD intrinsic to be applied on
7764 // transformed operands to obtain given relop result.
7765 SIMDIntrinsicID impSIMDRelOp(SIMDIntrinsicID relOpIntrinsicId,
7766 CORINFO_CLASS_HANDLE typeHnd,
7767 unsigned simdVectorSize,
7768 var_types* baseType,
7772 // Creates a GT_SIMD tree for Abs intrinsic.
7773 GenTree* impSIMDAbs(CORINFO_CLASS_HANDLE typeHnd, var_types baseType, unsigned simdVectorSize, GenTree* op1);
7775 #if defined(_TARGET_XARCH_)
7777 // Transforms operands and returns the SIMD intrinsic to be applied on
7778 // transformed operands to obtain == comparison result.
7779 SIMDIntrinsicID impSIMDLongRelOpEqual(CORINFO_CLASS_HANDLE typeHnd,
7780 unsigned simdVectorSize,
7784 // Transforms operands and returns the SIMD intrinsic to be applied on
7785 // transformed operands to obtain > comparison result.
7786 SIMDIntrinsicID impSIMDLongRelOpGreaterThan(CORINFO_CLASS_HANDLE typeHnd,
7787 unsigned simdVectorSize,
7791 // Transforms operands and returns the SIMD intrinsic to be applied on
7792 // transformed operands to obtain >= comparison result.
7793 SIMDIntrinsicID impSIMDLongRelOpGreaterThanOrEqual(CORINFO_CLASS_HANDLE typeHnd,
7794 unsigned simdVectorSize,
7798 // Transforms operands and returns the SIMD intrinsic to be applied on
7799 // transformed operands to obtain >= comparison result in case of int32
7800 // and small int base type vectors.
7801 SIMDIntrinsicID impSIMDIntegralRelOpGreaterThanOrEqual(
7802 CORINFO_CLASS_HANDLE typeHnd, unsigned simdVectorSize, var_types baseType, GenTree** op1, GenTree** op2);
7804 #endif // defined(_TARGET_XARCH_)
7806 void setLclRelatedToSIMDIntrinsic(GenTree* tree);
7807 bool areFieldsContiguous(GenTree* op1, GenTree* op2);
7808 bool areArrayElementsContiguous(GenTree* op1, GenTree* op2);
7809 bool areArgumentsContiguous(GenTree* op1, GenTree* op2);
7810 GenTree* createAddressNodeForSIMDInit(GenTree* tree, unsigned simdSize);
7812 // check methodHnd to see if it is a SIMD method that is expanded as an intrinsic in the JIT.
7813 GenTree* impSIMDIntrinsic(OPCODE opcode,
7814 GenTree* newobjThis,
7815 CORINFO_CLASS_HANDLE clsHnd,
7816 CORINFO_METHOD_HANDLE method,
7817 CORINFO_SIG_INFO* sig,
7820 GenTree* getOp1ForConstructor(OPCODE opcode, GenTree* newobjThis, CORINFO_CLASS_HANDLE clsHnd);
7822 // Whether SIMD vector occupies part of SIMD register.
7823 // SSE2: vector2f/3f are considered sub register SIMD types.
7824 // AVX: vector2f, 3f and 4f are all considered sub register SIMD types.
7825 bool isSubRegisterSIMDType(CORINFO_CLASS_HANDLE typeHnd)
7827 unsigned sizeBytes = 0;
7828 var_types baseType = getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7829 return (baseType == TYP_FLOAT) && (sizeBytes < getSIMDVectorRegisterByteLength());
7832 bool isSubRegisterSIMDType(GenTreeSIMD* simdNode)
7834 return (simdNode->gtSIMDSize < getSIMDVectorRegisterByteLength());
7837 // Get the type for the hardware SIMD vector.
7838 // This is the maximum SIMD type supported for this target.
7839 var_types getSIMDVectorType()
7841 #if defined(_TARGET_XARCH_)
7842 if (getSIMDSupportLevel() == SIMD_AVX2_Supported)
7848 assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
7851 #elif defined(_TARGET_ARM64_)
7854 assert(!"getSIMDVectorType() unimplemented on target arch");
7859 // Get the size of the SIMD type in bytes
7860 int getSIMDTypeSizeInBytes(CORINFO_CLASS_HANDLE typeHnd)
7862 unsigned sizeBytes = 0;
7863 (void)getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7867 // Get the the number of elements of basetype of SIMD vector given by its size and baseType
7868 static int getSIMDVectorLength(unsigned simdSize, var_types baseType);
7870 // Get the the number of elements of basetype of SIMD vector given by its type handle
7871 int getSIMDVectorLength(CORINFO_CLASS_HANDLE typeHnd);
7873 // Get preferred alignment of SIMD type.
7874 int getSIMDTypeAlignment(var_types simdType);
7876 // Get the number of bytes in a System.Numeric.Vector<T> for the current compilation.
7877 // Note - cannot be used for System.Runtime.Intrinsic
7878 unsigned getSIMDVectorRegisterByteLength()
7880 #if defined(_TARGET_XARCH_)
7881 if (getSIMDSupportLevel() == SIMD_AVX2_Supported)
7883 return YMM_REGSIZE_BYTES;
7887 assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
7888 return XMM_REGSIZE_BYTES;
7890 #elif defined(_TARGET_ARM64_)
7891 return FP_REGSIZE_BYTES;
7893 assert(!"getSIMDVectorRegisterByteLength() unimplemented on target arch");
7898 // The minimum and maximum possible number of bytes in a SIMD vector.
7900 // maxSIMDStructBytes
7901 // The minimum SIMD size supported by System.Numeric.Vectors or System.Runtime.Intrinsic
7902 // SSE: 16-byte Vector<T> and Vector128<T>
7903 // AVX: 32-byte Vector256<T> (Vector<T> is 16-byte)
7904 // AVX2: 32-byte Vector<T> and Vector256<T>
7905 unsigned int maxSIMDStructBytes()
7907 #if defined(FEATURE_HW_INTRINSICS) && defined(_TARGET_XARCH_)
7908 if (compSupports(InstructionSet_AVX))
7910 return YMM_REGSIZE_BYTES;
7914 assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
7915 return XMM_REGSIZE_BYTES;
7918 return getSIMDVectorRegisterByteLength();
7921 unsigned int minSIMDStructBytes()
7923 return emitTypeSize(TYP_SIMD8);
7926 // Returns the codegen type for a given SIMD size.
7927 var_types getSIMDTypeForSize(unsigned size)
7929 var_types simdType = TYP_UNDEF;
7932 simdType = TYP_SIMD8;
7934 else if (size == 12)
7936 simdType = TYP_SIMD12;
7938 else if (size == 16)
7940 simdType = TYP_SIMD16;
7942 else if (size == 32)
7944 simdType = TYP_SIMD32;
7948 noway_assert(!"Unexpected size for SIMD type");
7953 unsigned getSIMDInitTempVarNum()
7955 if (lvaSIMDInitTempVarNum == BAD_VAR_NUM)
7957 lvaSIMDInitTempVarNum = lvaGrabTempWithImplicitUse(false DEBUGARG("SIMDInitTempVar"));
7958 lvaTable[lvaSIMDInitTempVarNum].lvType = getSIMDVectorType();
7960 return lvaSIMDInitTempVarNum;
7963 #endif // FEATURE_SIMD
7966 //------------------------------------------------------------------------
7967 // largestEnregisterableStruct: The size in bytes of the largest struct that can be enregistered.
7969 // Notes: It is not guaranteed that the struct of this size or smaller WILL be a
7970 // candidate for enregistration.
7972 unsigned largestEnregisterableStructSize()
7975 unsigned vectorRegSize = getSIMDVectorRegisterByteLength();
7976 if (vectorRegSize > TARGET_POINTER_SIZE)
7978 return vectorRegSize;
7981 #endif // FEATURE_SIMD
7983 return TARGET_POINTER_SIZE;
7988 // These routines need not be enclosed under FEATURE_SIMD since lvIsSIMDType()
7989 // is defined for both FEATURE_SIMD and !FEATURE_SIMD apropriately. The use
7990 // of this routines also avoids the need of #ifdef FEATURE_SIMD specific code.
7992 // Is this var is of type simd struct?
7993 bool lclVarIsSIMDType(unsigned varNum)
7995 LclVarDsc* varDsc = lvaTable + varNum;
7996 return varDsc->lvIsSIMDType();
7999 // Is this Local node a SIMD local?
8000 bool lclVarIsSIMDType(GenTreeLclVarCommon* lclVarTree)
8002 return lclVarIsSIMDType(lclVarTree->gtLclNum);
8005 // Returns true if the TYP_SIMD locals on stack are aligned at their
8006 // preferred byte boundary specified by getSIMDTypeAlignment().
8008 // As per the Intel manual, the preferred alignment for AVX vectors is 32-bytes. On Amd64,
8009 // RSP/EBP is aligned at 16-bytes, therefore to align SIMD types at 32-bytes we need even
8010 // RSP/EBP to be 32-byte aligned. It is not clear whether additional stack space used in
8011 // aligning stack is worth the benefit and for now will use 16-byte alignment for AVX
8012 // 256-bit vectors with unaligned load/stores to/from memory. On x86, the stack frame
8013 // is aligned to 4 bytes. We need to extend existing support for double (8-byte) alignment
8014 // to 16 or 32 byte alignment for frames with local SIMD vars, if that is determined to be
8017 bool isSIMDTypeLocalAligned(unsigned varNum)
8019 #if defined(FEATURE_SIMD) && ALIGN_SIMD_TYPES
8020 if (lclVarIsSIMDType(varNum) && lvaTable[varNum].lvType != TYP_BYREF)
8023 int off = lvaFrameAddress(varNum, &ebpBased);
8024 // TODO-Cleanup: Can't this use the lvExactSize on the varDsc?
8025 int alignment = getSIMDTypeAlignment(lvaTable[varNum].lvType);
8026 bool isAligned = (alignment <= STACK_ALIGN) && ((off % alignment) == 0);
8029 #endif // FEATURE_SIMD
8034 bool compSupports(InstructionSet isa) const
8036 #if defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_)
8037 return (opts.compSupportsISA & (1ULL << isa)) != 0;
8043 bool canUseVexEncoding() const
8045 #ifdef _TARGET_XARCH_
8046 return compSupports(InstructionSet_AVX);
8053 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8054 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8058 XX Generic info about the compilation and the method being compiled. XX
8059 XX It is responsible for driving the other phases. XX
8060 XX It is also responsible for all the memory management. XX
8062 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8063 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8067 Compiler* InlineeCompiler; // The Compiler instance for the inlinee
8069 InlineResult* compInlineResult; // The result of importing the inlinee method.
8071 bool compDoAggressiveInlining; // If true, mark every method as CORINFO_FLG_FORCEINLINE
8072 bool compJmpOpUsed; // Does the method do a JMP
8073 bool compLongUsed; // Does the method use TYP_LONG
8074 bool compFloatingPointUsed; // Does the method use TYP_FLOAT or TYP_DOUBLE
8075 bool compTailCallUsed; // Does the method do a tailcall
8076 bool compLocallocUsed; // Does the method use localloc.
8077 bool compLocallocOptimized; // Does the method have an optimized localloc
8078 bool compQmarkUsed; // Does the method use GT_QMARK/GT_COLON
8079 bool compQmarkRationalized; // Is it allowed to use a GT_QMARK/GT_COLON node.
8080 bool compUnsafeCastUsed; // Does the method use LDIND/STIND to cast between scalar/refernce types
8082 // NOTE: These values are only reliable after
8083 // the importing is completely finished.
8086 // State information - which phases have completed?
8087 // These are kept together for easy discoverability
8089 bool bRangeAllowStress;
8090 bool compCodeGenDone;
8091 int64_t compNumStatementLinksTraversed; // # of links traversed while doing debug checks
8092 bool fgNormalizeEHDone; // Has the flowgraph EH normalization phase been done?
8093 size_t compSizeEstimate; // The estimated size of the method as per `gtSetEvalOrder`.
8094 size_t compCycleEstimate; // The estimated cycle count of the method as per `gtSetEvalOrder`
8097 bool fgLocalVarLivenessDone; // Note that this one is used outside of debug.
8098 bool fgLocalVarLivenessChanged;
8100 bool compStackProbePrologDone;
8103 bool compRationalIRForm;
8105 bool compUsesThrowHelper; // There is a call to a THOROW_HELPER for the compiled method.
8107 bool compGeneratingProlog;
8108 bool compGeneratingEpilog;
8109 bool compNeedsGSSecurityCookie; // There is an unsafe buffer (or localloc) on the stack.
8110 // Insert cookie on frame and code to check the cookie, like VC++ -GS.
8111 bool compGSReorderStackLayout; // There is an unsafe buffer on the stack, reorder locals and make local
8112 // copies of susceptible parameters to avoid buffer overrun attacks through locals/params
8113 bool getNeedsGSSecurityCookie() const
8115 return compNeedsGSSecurityCookie;
8117 void setNeedsGSSecurityCookie()
8119 compNeedsGSSecurityCookie = true;
8122 FrameLayoutState lvaDoneFrameLayout; // The highest frame layout state that we've completed. During
8123 // frame layout calculations, this is the level we are currently
8126 //---------------------------- JITing options -----------------------------
8139 JitFlags* jitFlags; // all flags passed from the EE
8140 unsigned compFlags; // method attributes
8142 codeOptimize compCodeOpt; // what type of code optimizations
8147 #if defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_)
8148 uint64_t compSupportsISA;
8149 void setSupportedISA(InstructionSet isa)
8151 compSupportsISA |= 1ULL << isa;
8155 // optimize maximally and/or favor speed over size?
8157 #define DEFAULT_MIN_OPTS_CODE_SIZE 60000
8158 #define DEFAULT_MIN_OPTS_INSTR_COUNT 20000
8159 #define DEFAULT_MIN_OPTS_BB_COUNT 2000
8160 #define DEFAULT_MIN_OPTS_LV_NUM_COUNT 2000
8161 #define DEFAULT_MIN_OPTS_LV_REF_COUNT 8000
8163 // Maximun number of locals before turning off the inlining
8164 #define MAX_LV_NUM_COUNT_FOR_INLINING 512
8167 unsigned instrCount;
8168 unsigned lvRefCount;
8169 bool compMinOptsIsSet;
8171 bool compMinOptsIsUsed;
8173 inline bool MinOpts()
8175 assert(compMinOptsIsSet);
8176 compMinOptsIsUsed = true;
8179 inline bool IsMinOptsSet()
8181 return compMinOptsIsSet;
8184 inline bool MinOpts()
8188 inline bool IsMinOptsSet()
8190 return compMinOptsIsSet;
8193 inline void SetMinOpts(bool val)
8195 assert(!compMinOptsIsUsed);
8196 assert(!compMinOptsIsSet || (compMinOpts == val));
8198 compMinOptsIsSet = true;
8201 // true if the CLFLG_* for an optimization is set.
8202 inline bool OptEnabled(unsigned optFlag)
8204 return !!(compFlags & optFlag);
8207 #ifdef FEATURE_READYTORUN_COMPILER
8208 inline bool IsReadyToRun()
8210 return jitFlags->IsSet(JitFlags::JIT_FLAG_READYTORUN);
8213 inline bool IsReadyToRun()
8219 // true if we should use the PINVOKE_{BEGIN,END} helpers instead of generating
8220 // PInvoke transitions inline (e.g. when targeting CoreRT).
8221 inline bool ShouldUsePInvokeHelpers()
8223 return jitFlags->IsSet(JitFlags::JIT_FLAG_USE_PINVOKE_HELPERS);
8226 // true if we should use insert the REVERSE_PINVOKE_{ENTER,EXIT} helpers in the method
8228 inline bool IsReversePInvoke()
8230 return jitFlags->IsSet(JitFlags::JIT_FLAG_REVERSE_PINVOKE);
8233 // true if we must generate code compatible with JIT32 quirks
8234 inline bool IsJit32Compat()
8236 #if defined(_TARGET_X86_)
8237 return jitFlags->IsSet(JitFlags::JIT_FLAG_DESKTOP_QUIRKS);
8243 // true if we must generate code compatible with Jit64 quirks
8244 inline bool IsJit64Compat()
8246 #if defined(_TARGET_AMD64_)
8247 return jitFlags->IsSet(JitFlags::JIT_FLAG_DESKTOP_QUIRKS);
8248 #elif !defined(FEATURE_CORECLR)
8255 bool compScopeInfo; // Generate the LocalVar info ?
8256 bool compDbgCode; // Generate debugger-friendly code?
8257 bool compDbgInfo; // Gather debugging info?
8260 #ifdef PROFILING_SUPPORTED
8261 bool compNoPInvokeInlineCB;
8263 static const bool compNoPInvokeInlineCB;
8267 bool compGcChecks; // Check arguments and return values to ensure they are sane
8268 bool compStackCheckOnRet; // Check ESP on return to ensure it is correct
8269 bool compStackCheckOnCall; // Check ESP after every call to ensure it is correct
8273 bool compNeedSecurityCheck; // This flag really means where or not a security object needs
8274 // to be allocated on the stack.
8275 // It will be set to true in the following cases:
8276 // 1. When the method being compiled has a declarative security
8277 // (i.e. when CORINFO_FLG_NOSECURITYWRAP is reset for the current method).
8278 // This is also the case when we inject a prolog and epilog in the method.
8280 // 2. When the method being compiled has imperative security (i.e. the method
8281 // calls into another method that has CORINFO_FLG_SECURITYCHECK flag set).
8283 // 3. When opts.compDbgEnC is true. (See also Compiler::compCompile).
8285 // When this flag is set, jit will allocate a gc-reference local variable (lvaSecurityObject),
8286 // which gets reported as a GC root to stackwalker.
8287 // (See also ICodeManager::GetAddrOfSecurityObject.)
8289 bool compReloc; // Generate relocs for pointers in code, true for all ngen/prejit codegen
8292 #if defined(_TARGET_XARCH_)
8293 bool compEnablePCRelAddr; // Whether absolute addr be encoded as PC-rel offset by RyuJIT where possible
8297 #ifdef UNIX_AMD64_ABI
8298 // This flag is indicating if there is a need to align the frame.
8299 // On AMD64-Windows, if there are calls, 4 slots for the outgoing ars are allocated, except for
8300 // FastTailCall. This slots makes the frame size non-zero, so alignment logic will be called.
8301 // On AMD64-Unix, there are no such slots. There is a possibility to have calls in the method with frame size of
8302 // 0. The frame alignment logic won't kick in. This flags takes care of the AMD64-Unix case by remembering that
8303 // there are calls and making sure the frame alignment logic is executed.
8304 bool compNeedToAlignFrame;
8305 #endif // UNIX_AMD64_ABI
8307 bool compProcedureSplitting; // Separate cold code from hot code
8309 bool genFPorder; // Preserve FP order (operations are non-commutative)
8310 bool genFPopt; // Can we do frame-pointer-omission optimization?
8311 bool altJit; // True if we are an altjit and are compiling this method
8314 bool optRepeat; // Repeat optimizer phases k times
8318 bool compProcedureSplittingEH; // Separate cold code from hot code for functions with EH
8319 bool dspCode; // Display native code generated
8320 bool dspEHTable; // Display the EH table reported to the VM
8321 bool dspDebugInfo; // Display the Debug info reported to the VM
8322 bool dspInstrs; // Display the IL instructions intermixed with the native code output
8323 bool dspEmit; // Display emitter output
8324 bool dspLines; // Display source-code lines intermixed with native code output
8325 bool dmpHex; // Display raw bytes in hex of native code output
8326 bool varNames; // Display variables names in native code output
8327 bool disAsm; // Display native code as it is generated
8328 bool disAsmSpilled; // Display native code when any register spilling occurs
8329 bool disDiffable; // Makes the Disassembly code 'diff-able'
8330 bool disAsm2; // Display native code after it is generated using external disassembler
8331 bool dspOrder; // Display names of each of the methods that we ngen/jit
8332 bool dspUnwind; // Display the unwind info output
8333 bool dspDiffable; // Makes the Jit Dump 'diff-able' (currently uses same COMPlus_* flag as disDiffable)
8334 bool compLongAddress; // Force using large pseudo instructions for long address
8335 // (IF_LARGEJMP/IF_LARGEADR/IF_LARGLDC)
8336 bool dspGCtbls; // Display the GC tables
8340 bool doLateDisasm; // Run the late disassembler
8341 #endif // LATE_DISASM
8343 #if DUMP_GC_TABLES && !defined(DEBUG) && defined(JIT32_GCENCODER)
8344 // Only the JIT32_GCENCODER implements GC dumping in non-DEBUG code.
8345 #pragma message("NOTE: this non-debug build has GC ptr table dumping always enabled!")
8346 static const bool dspGCtbls = true;
8349 // We need stack probes to guarantee that we won't trigger a stack overflow
8350 // when calling unmanaged code until they get a chance to set up a frame, because
8351 // the EE will have no idea where it is.
8353 // We will only be doing this currently for hosted environments. Unfortunately
8354 // we need to take care of stubs, so potentially, we will have to do the probes
8355 // for any call. We have a plan for not needing for stubs though
8356 bool compNeedStackProbes;
8358 #ifdef PROFILING_SUPPORTED
8359 // Whether to emit Enter/Leave/TailCall hooks using a dummy stub (DummyProfilerELTStub()).
8360 // This option helps make the JIT behave as if it is running under a profiler.
8361 bool compJitELTHookEnabled;
8362 #endif // PROFILING_SUPPORTED
8364 #if FEATURE_TAILCALL_OPT
8365 // Whether opportunistic or implicit tail call optimization is enabled.
8366 bool compTailCallOpt;
8367 // Whether optimization of transforming a recursive tail call into a loop is enabled.
8368 bool compTailCallLoopOpt;
8372 static const bool compUseSoftFP = true;
8373 #else // !ARM_SOFTFP
8374 static const bool compUseSoftFP = false;
8377 GCPollType compGCPollType;
8381 static bool s_pAltJitExcludeAssembliesListInitialized;
8382 static AssemblyNamesList2* s_pAltJitExcludeAssembliesList;
8386 static bool s_pJitDisasmIncludeAssembliesListInitialized;
8387 static AssemblyNamesList2* s_pJitDisasmIncludeAssembliesList;
8392 template <typename T>
8395 return (p == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : p);
8398 template <typename T>
8401 return (o == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : o);
8404 static int dspTreeID(GenTree* tree)
8406 return tree->gtTreeID;
8408 static void printTreeID(GenTree* tree)
8410 if (tree == nullptr)
8416 printf("[%06d]", dspTreeID(tree));
8423 #define STRESS_MODES \
8427 /* "Variations" stress areas which we try to mix up with each other. */ \
8428 /* These should not be exhaustively used as they might */ \
8429 /* hide/trivialize other areas */ \
8432 STRESS_MODE(DBL_ALN) \
8433 STRESS_MODE(LCL_FLDS) \
8434 STRESS_MODE(UNROLL_LOOPS) \
8435 STRESS_MODE(MAKE_CSE) \
8436 STRESS_MODE(LEGACY_INLINE) \
8437 STRESS_MODE(CLONE_EXPR) \
8438 STRESS_MODE(USE_FCOMI) \
8439 STRESS_MODE(USE_CMOV) \
8441 STRESS_MODE(BB_PROFILE) \
8442 STRESS_MODE(OPT_BOOLS_GC) \
8443 STRESS_MODE(REMORPH_TREES) \
8444 STRESS_MODE(64RSLT_MUL) \
8445 STRESS_MODE(DO_WHILE_LOOPS) \
8446 STRESS_MODE(MIN_OPTS) \
8447 STRESS_MODE(REVERSE_FLAG) /* Will set GTF_REVERSE_OPS whenever we can */ \
8448 STRESS_MODE(REVERSE_COMMA) /* Will reverse commas created with gtNewCommaNode */ \
8449 STRESS_MODE(TAILCALL) /* Will make the call as a tailcall whenever legal */ \
8450 STRESS_MODE(CATCH_ARG) /* Will spill catch arg */ \
8451 STRESS_MODE(UNSAFE_BUFFER_CHECKS) \
8452 STRESS_MODE(NULL_OBJECT_CHECK) \
8453 STRESS_MODE(PINVOKE_RESTORE_ESP) \
8454 STRESS_MODE(RANDOM_INLINE) \
8455 STRESS_MODE(SWITCH_CMP_BR_EXPANSION) \
8456 STRESS_MODE(GENERIC_VARN) \
8458 /* After COUNT_VARN, stress level 2 does all of these all the time */ \
8460 STRESS_MODE(COUNT_VARN) \
8462 /* "Check" stress areas that can be exhaustively used if we */ \
8463 /* dont care about performance at all */ \
8465 STRESS_MODE(FORCE_INLINE) /* Treat every method as AggressiveInlining */ \
8466 STRESS_MODE(CHK_FLOW_UPDATE) \
8467 STRESS_MODE(EMITTER) \
8468 STRESS_MODE(CHK_REIMPORT) \
8469 STRESS_MODE(FLATFP) \
8470 STRESS_MODE(GENERIC_CHECK) \
8475 #define STRESS_MODE(mode) STRESS_##mode,
8482 static const LPCWSTR s_compStressModeNames[STRESS_COUNT + 1];
8483 BYTE compActiveStressModes[STRESS_COUNT];
8486 #define MAX_STRESS_WEIGHT 100
8488 bool compStressCompile(compStressArea stressArea, unsigned weightPercentage);
8492 bool compInlineStress()
8494 return compStressCompile(STRESS_LEGACY_INLINE, 50);
8497 bool compRandomInlineStress()
8499 return compStressCompile(STRESS_RANDOM_INLINE, 50);
8504 bool compTailCallStress()
8507 return (JitConfig.TailcallStress() != 0 || compStressCompile(STRESS_TAILCALL, 5));
8513 codeOptimize compCodeOpt()
8516 // Switching between size & speed has measurable throughput impact
8517 // (3.5% on NGen mscorlib when measured). It used to be enabled for
8518 // DEBUG, but should generate identical code between CHK & RET builds,
8519 // so that's not acceptable.
8520 // TODO-Throughput: Figure out what to do about size vs. speed & throughput.
8521 // Investigate the cause of the throughput regression.
8523 return opts.compCodeOpt;
8525 return BLENDED_CODE;
8529 //--------------------- Info about the procedure --------------------------
8533 COMP_HANDLE compCompHnd;
8534 CORINFO_MODULE_HANDLE compScopeHnd;
8535 CORINFO_CLASS_HANDLE compClassHnd;
8536 CORINFO_METHOD_HANDLE compMethodHnd;
8537 CORINFO_METHOD_INFO* compMethodInfo;
8539 BOOL hasCircularClassConstraints;
8540 BOOL hasCircularMethodConstraints;
8542 #if defined(DEBUG) || defined(LATE_DISASM)
8543 const char* compMethodName;
8544 const char* compClassName;
8545 const char* compFullName;
8546 #endif // defined(DEBUG) || defined(LATE_DISASM)
8548 #if defined(DEBUG) || defined(INLINE_DATA)
8549 // Method hash is logcally const, but computed
8551 mutable unsigned compMethodHashPrivate;
8552 unsigned compMethodHash() const;
8553 #endif // defined(DEBUG) || defined(INLINE_DATA)
8555 #ifdef PSEUDORANDOM_NOP_INSERTION
8556 // things for pseudorandom nop insertion
8557 unsigned compChecksum;
8561 // The following holds the FLG_xxxx flags for the method we're compiling.
8564 // The following holds the class attributes for the method we're compiling.
8565 unsigned compClassAttr;
8567 const BYTE* compCode;
8568 IL_OFFSET compILCodeSize; // The IL code size
8569 UNATIVE_OFFSET compNativeCodeSize; // The native code size, after instructions are issued. This
8570 // is less than (compTotalHotCodeSize + compTotalColdCodeSize) only if:
8571 // (1) the code is not hot/cold split, and we issued less code than we expected, or
8572 // (2) the code is hot/cold split, and we issued less code than we expected
8573 // in the cold section (the hot section will always be padded out to compTotalHotCodeSize).
8575 bool compIsStatic : 1; // Is the method static (no 'this' pointer)?
8576 bool compIsVarArgs : 1; // Does the method have varargs parameters?
8577 bool compIsContextful : 1; // contextful method
8578 bool compInitMem : 1; // Is the CORINFO_OPT_INIT_LOCALS bit set in the method info options?
8579 bool compUnwrapContextful : 1; // JIT should unwrap proxies when possible
8580 bool compProfilerCallback : 1; // JIT inserted a profiler Enter callback
8581 bool compPublishStubParam : 1; // EAX captured in prolog will be available through an instrinsic
8582 bool compRetBuffDefStack : 1; // The ret buff argument definitely points into the stack.
8584 var_types compRetType; // Return type of the method as declared in IL
8585 var_types compRetNativeType; // Normalized return type as per target arch ABI
8586 unsigned compILargsCount; // Number of arguments (incl. implicit but not hidden)
8587 unsigned compArgsCount; // Number of arguments (incl. implicit and hidden)
8589 #if FEATURE_FASTTAILCALL
8590 size_t compArgStackSize; // Incoming argument stack size in bytes
8591 #endif // FEATURE_FASTTAILCALL
8593 unsigned compRetBuffArg; // position of hidden return param var (0, 1) (BAD_VAR_NUM means not present);
8594 int compTypeCtxtArg; // position of hidden param for type context for generic code (CORINFO_CALLCONV_PARAMTYPE)
8595 unsigned compThisArg; // position of implicit this pointer param (not to be confused with lvaArg0Var)
8596 unsigned compILlocalsCount; // Number of vars : args + locals (incl. implicit but not hidden)
8597 unsigned compLocalsCount; // Number of vars : args + locals (incl. implicit and hidden)
8598 unsigned compMaxStack;
8599 UNATIVE_OFFSET compTotalHotCodeSize; // Total number of bytes of Hot Code in the method
8600 UNATIVE_OFFSET compTotalColdCodeSize; // Total number of bytes of Cold Code in the method
8602 unsigned compCallUnmanaged; // count of unmanaged calls
8603 unsigned compLvFrameListRoot; // lclNum for the Frame root
8604 unsigned compXcptnsCount; // Number of exception-handling clauses read in the method's IL.
8605 // You should generally use compHndBBtabCount instead: it is the
8606 // current number of EH clauses (after additions like synchronized
8607 // methods and funclets, and removals like unreachable code deletion).
8609 bool compMatchedVM; // true if the VM is "matched": either the JIT is a cross-compiler
8610 // and the VM expects that, or the JIT is a "self-host" compiler
8611 // (e.g., x86 hosted targeting x86) and the VM expects that.
8613 /* The following holds IL scope information about local variables.
8616 unsigned compVarScopesCount;
8617 VarScopeDsc* compVarScopes;
8619 /* The following holds information about instr offsets for
8620 * which we need to report IP-mappings
8623 IL_OFFSET* compStmtOffsets; // sorted
8624 unsigned compStmtOffsetsCount;
8625 ICorDebugInfo::BoundaryTypes compStmtOffsetsImplicit;
8627 #define CPU_X86 0x0100 // The generic X86 CPU
8628 #define CPU_X86_PENTIUM_4 0x0110
8630 #define CPU_X64 0x0200 // The generic x64 CPU
8631 #define CPU_AMD_X64 0x0210 // AMD x64 CPU
8632 #define CPU_INTEL_X64 0x0240 // Intel x64 CPU
8634 #define CPU_ARM 0x0300 // The generic ARM CPU
8635 #define CPU_ARM64 0x0400 // The generic ARM64 CPU
8637 unsigned genCPU; // What CPU are we running on
8640 // Returns true if the method being compiled returns a non-void and non-struct value.
8641 // Note that lvaInitTypeRef() normalizes compRetNativeType for struct returns in a
8642 // single register as per target arch ABI (e.g on Amd64 Windows structs of size 1, 2,
8643 // 4 or 8 gets normalized to TYP_BYTE/TYP_SHORT/TYP_INT/TYP_LONG; On Arm HFA structs).
8644 // Methods returning such structs are considered to return non-struct return value and
8645 // this method returns true in that case.
8646 bool compMethodReturnsNativeScalarType()
8648 return (info.compRetType != TYP_VOID) && !varTypeIsStruct(info.compRetNativeType);
8651 // Returns true if the method being compiled returns RetBuf addr as its return value
8652 bool compMethodReturnsRetBufAddr()
8654 // There are cases where implicit RetBuf argument should be explicitly returned in a register.
8655 // In such cases the return type is changed to TYP_BYREF and appropriate IR is generated.
8657 // 1. Profiler Leave calllback expects the address of retbuf as return value for
8658 // methods with hidden RetBuf argument. impReturnInstruction() when profiler
8659 // callbacks are needed creates GT_RETURN(TYP_BYREF, op1 = Addr of RetBuf) for
8660 // methods with hidden RetBufArg.
8662 // 2. As per the System V ABI, the address of RetBuf needs to be returned by
8663 // methods with hidden RetBufArg in RAX. In such case GT_RETURN is of TYP_BYREF,
8664 // returning the address of RetBuf.
8666 // 3. Windows 64-bit native calling convention also requires the address of RetBuff
8667 // to be returned in RAX.
8668 CLANG_FORMAT_COMMENT_ANCHOR;
8670 #ifdef _TARGET_AMD64_
8671 return (info.compRetBuffArg != BAD_VAR_NUM);
8672 #else // !_TARGET_AMD64_
8673 return (compIsProfilerHookNeeded()) && (info.compRetBuffArg != BAD_VAR_NUM);
8674 #endif // !_TARGET_AMD64_
8677 // Returns true if the method returns a value in more than one return register
8678 // TODO-ARM-Bug: Deal with multi-register genReturnLocaled structs?
8679 // TODO-ARM64: Does this apply for ARM64 too?
8680 bool compMethodReturnsMultiRegRetType()
8682 #if FEATURE_MULTIREG_RET
8683 #if defined(_TARGET_X86_)
8684 // On x86 only 64-bit longs are returned in multiple registers
8685 return varTypeIsLong(info.compRetNativeType);
8686 #else // targets: X64-UNIX, ARM64 or ARM32
8687 // On all other targets that support multireg return values:
8688 // Methods returning a struct in multiple registers have a return value of TYP_STRUCT.
8689 // Such method's compRetNativeType is TYP_STRUCT without a hidden RetBufArg
8690 return varTypeIsStruct(info.compRetNativeType) && (info.compRetBuffArg == BAD_VAR_NUM);
8691 #endif // TARGET_XXX
8693 #else // not FEATURE_MULTIREG_RET
8695 // For this architecture there are no multireg returns
8698 #endif // FEATURE_MULTIREG_RET
8701 #if FEATURE_MULTIREG_ARGS
8702 // Given a GenTree node of TYP_STRUCT that represents a pass by value argument
8703 // return the gcPtr layout for the pointers sized fields
8704 void getStructGcPtrsFromOp(GenTree* op, BYTE* gcPtrsOut);
8705 #endif // FEATURE_MULTIREG_ARGS
8707 // Returns true if the method being compiled returns a value
8708 bool compMethodHasRetVal()
8710 return compMethodReturnsNativeScalarType() || compMethodReturnsRetBufAddr() ||
8711 compMethodReturnsMultiRegRetType();
8716 void compDispLocalVars();
8720 //-------------------------- Global Compiler Data ------------------------------------
8723 static unsigned s_compMethodsCount; // to produce unique label names
8724 unsigned compGenTreeID;
8725 unsigned compBasicBlockID;
8728 BasicBlock* compCurBB; // the current basic block in process
8729 GenTree* compCurStmt; // the current statement in process
8731 unsigned compCurStmtNum; // to give all statements an increasing StmtNum when printing dumps
8734 // The following is used to create the 'method JIT info' block.
8735 size_t compInfoBlkSize;
8736 BYTE* compInfoBlkAddr;
8738 EHblkDsc* compHndBBtab; // array of EH data
8739 unsigned compHndBBtabCount; // element count of used elements in EH data array
8740 unsigned compHndBBtabAllocCount; // element count of allocated elements in EH data array
8742 #if defined(_TARGET_X86_)
8744 //-------------------------------------------------------------------------
8745 // Tracking of region covered by the monitor in synchronized methods
8746 void* syncStartEmitCookie; // the emitter cookie for first instruction after the call to MON_ENTER
8747 void* syncEndEmitCookie; // the emitter cookie for first instruction after the call to MON_EXIT
8749 #endif // !_TARGET_X86_
8751 Phases previousCompletedPhase; // the most recently completed phase
8753 //-------------------------------------------------------------------------
8754 // The following keeps track of how many bytes of local frame space we've
8755 // grabbed so far in the current function, and how many argument bytes we
8756 // need to pop when we return.
8759 unsigned compLclFrameSize; // secObject+lclBlk+locals+temps
8761 // Count of callee-saved regs we pushed in the prolog.
8762 // Does not include EBP for isFramePointerUsed() and double-aligned frames.
8763 // In case of Amd64 this doesn't include float regs saved on stack.
8764 unsigned compCalleeRegsPushed;
8766 #if defined(_TARGET_XARCH_)
8767 // Mask of callee saved float regs on stack.
8768 regMaskTP compCalleeFPRegsSavedMask;
8770 #ifdef _TARGET_AMD64_
8771 // Quirk for VS debug-launch scenario to work:
8772 // Bytes of padding between save-reg area and locals.
8773 #define VSQUIRK_STACK_PAD (2 * REGSIZE_BYTES)
8774 unsigned compVSQuirkStackPaddingNeeded;
8775 bool compQuirkForPPPflag;
8778 unsigned compArgSize; // total size of arguments in bytes (including register args (lvIsRegArg))
8780 unsigned compMapILargNum(unsigned ILargNum); // map accounting for hidden args
8781 unsigned compMapILvarNum(unsigned ILvarNum); // map accounting for hidden args
8782 unsigned compMap2ILvarNum(unsigned varNum); // map accounting for hidden args
8784 //-------------------------------------------------------------------------
8786 static void compStartup(); // One-time initialization
8787 static void compShutdown(); // One-time finalization
8789 void compInit(ArenaAllocator* pAlloc, InlineInfo* inlineInfo);
8792 static void compDisplayStaticSizes(FILE* fout);
8794 //------------ Some utility functions --------------
8796 void* compGetHelperFtn(CorInfoHelpFunc ftnNum, /* IN */
8797 void** ppIndirection); /* OUT */
8799 // Several JIT/EE interface functions return a CorInfoType, and also return a
8800 // class handle as an out parameter if the type is a value class. Returns the
8801 // size of the type these describe.
8802 unsigned compGetTypeSize(CorInfoType cit, CORINFO_CLASS_HANDLE clsHnd);
8805 // Components used by the compiler may write unit test suites, and
8806 // have them run within this method. They will be run only once per process, and only
8807 // in debug. (Perhaps should be under the control of a COMPlus_ flag.)
8808 // These should fail by asserting.
8809 void compDoComponentUnitTestsOnce();
8812 int compCompile(CORINFO_METHOD_HANDLE methodHnd,
8813 CORINFO_MODULE_HANDLE classPtr,
8814 COMP_HANDLE compHnd,
8815 CORINFO_METHOD_INFO* methodInfo,
8816 void** methodCodePtr,
8817 ULONG* methodCodeSize,
8818 JitFlags* compileFlags);
8819 void compCompileFinish();
8820 int compCompileHelper(CORINFO_MODULE_HANDLE classPtr,
8821 COMP_HANDLE compHnd,
8822 CORINFO_METHOD_INFO* methodInfo,
8823 void** methodCodePtr,
8824 ULONG* methodCodeSize,
8825 JitFlags* compileFlags,
8826 CorInfoInstantiationVerification instVerInfo);
8828 ArenaAllocator* compGetArenaAllocator();
8830 #if MEASURE_MEM_ALLOC
8831 static bool s_dspMemStats; // Display per-phase memory statistics for every function
8832 #endif // MEASURE_MEM_ALLOC
8834 #if LOOP_HOIST_STATS
8835 unsigned m_loopsConsidered;
8836 bool m_curLoopHasHoistedExpression;
8837 unsigned m_loopsWithHoistedExpressions;
8838 unsigned m_totalHoistedExpressions;
8840 void AddLoopHoistStats();
8841 void PrintPerMethodLoopHoistStats();
8843 static CritSecObject s_loopHoistStatsLock; // This lock protects the data structures below.
8844 static unsigned s_loopsConsidered;
8845 static unsigned s_loopsWithHoistedExpressions;
8846 static unsigned s_totalHoistedExpressions;
8848 static void PrintAggregateLoopHoistStats(FILE* f);
8849 #endif // LOOP_HOIST_STATS
8851 bool compIsForImportOnly();
8852 bool compIsForInlining();
8853 bool compDonotInline();
8856 unsigned char compGetJitDefaultFill(); // Get the default fill char value
8857 // we randomize this value when JitStress is enabled
8859 const char* compLocalVarName(unsigned varNum, unsigned offs);
8860 VarName compVarName(regNumber reg, bool isFloatReg = false);
8861 const char* compRegVarName(regNumber reg, bool displayVar = false, bool isFloatReg = false);
8862 const char* compRegNameForSize(regNumber reg, size_t size);
8863 const char* compFPregVarName(unsigned fpReg, bool displayVar = false);
8864 void compDspSrcLinesByNativeIP(UNATIVE_OFFSET curIP);
8865 void compDspSrcLinesByLineNum(unsigned line, bool seek = false);
8868 //-------------------------------------------------------------------------
8870 struct VarScopeListNode
8873 VarScopeListNode* next;
8874 static VarScopeListNode* Create(VarScopeDsc* value, CompAllocator alloc)
8876 VarScopeListNode* node = new (alloc) VarScopeListNode;
8878 node->next = nullptr;
8883 struct VarScopeMapInfo
8885 VarScopeListNode* head;
8886 VarScopeListNode* tail;
8887 static VarScopeMapInfo* Create(VarScopeListNode* node, CompAllocator alloc)
8889 VarScopeMapInfo* info = new (alloc) VarScopeMapInfo;
8896 // Max value of scope count for which we would use linear search; for larger values we would use hashtable lookup.
8897 static const unsigned MAX_LINEAR_FIND_LCL_SCOPELIST = 32;
8899 typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, VarScopeMapInfo*> VarNumToScopeDscMap;
8901 // Map to keep variables' scope indexed by varNum containing it's scope dscs at the index.
8902 VarNumToScopeDscMap* compVarScopeMap;
8904 VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned lifeBeg, unsigned lifeEnd);
8906 VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned offs);
8908 VarScopeDsc* compFindLocalVarLinear(unsigned varNum, unsigned offs);
8910 void compInitVarScopeMap();
8912 VarScopeDsc** compEnterScopeList; // List has the offsets where variables
8913 // enter scope, sorted by instr offset
8914 unsigned compNextEnterScope;
8916 VarScopeDsc** compExitScopeList; // List has the offsets where variables
8917 // go out of scope, sorted by instr offset
8918 unsigned compNextExitScope;
8920 void compInitScopeLists();
8922 void compResetScopeLists();
8924 VarScopeDsc* compGetNextEnterScope(unsigned offs, bool scan = false);
8926 VarScopeDsc* compGetNextExitScope(unsigned offs, bool scan = false);
8928 void compProcessScopesUntil(unsigned offset,
8930 void (Compiler::*enterScopeFn)(VARSET_TP* inScope, VarScopeDsc*),
8931 void (Compiler::*exitScopeFn)(VARSET_TP* inScope, VarScopeDsc*));
8934 void compDispScopeLists();
8937 bool compIsProfilerHookNeeded();
8939 //-------------------------------------------------------------------------
8940 /* Statistical Data Gathering */
8942 void compJitStats(); // call this function and enable
8943 // various ifdef's below for statistical data
8946 void compCallArgStats();
8947 static void compDispCallArgStats(FILE* fout);
8950 //-------------------------------------------------------------------------
8957 ArenaAllocator* compArenaAllocator;
8960 void compFunctionTraceStart();
8961 void compFunctionTraceEnd(void* methodCodePtr, ULONG methodCodeSize, bool isNYI);
8964 size_t compMaxUncheckedOffsetForNullObject;
8966 void compInitOptions(JitFlags* compileFlags);
8968 void compSetProcessor();
8969 void compInitDebuggingInfo();
8970 void compSetOptimizationLevel();
8971 #ifdef _TARGET_ARMARCH_
8972 bool compRsvdRegCheck(FrameLayoutState curState);
8974 void compCompile(void** methodCodePtr, ULONG* methodCodeSize, JitFlags* compileFlags);
8976 // Clear annotations produced during optimizations; to be used between iterations when repeating opts.
8977 void ResetOptAnnotations();
8979 // Regenerate loop descriptors; to be used between iterations when repeating opts.
8980 void RecomputeLoopInfo();
8982 #ifdef PROFILING_SUPPORTED
8983 // Data required for generating profiler Enter/Leave/TailCall hooks
8985 bool compProfilerHookNeeded; // Whether profiler Enter/Leave/TailCall hook needs to be generated for the method
8986 void* compProfilerMethHnd; // Profiler handle of the method being compiled. Passed as param to ELT callbacks
8987 bool compProfilerMethHndIndirected; // Whether compProfilerHandle is pointer to the handle or is an actual handle
8990 #ifdef _TARGET_AMD64_
8991 bool compQuirkForPPP(); // Check if this method should be Quirked for the PPP issue
8994 // Assumes called as part of process shutdown; does any compiler-specific work associated with that.
8995 static void ProcessShutdownWork(ICorStaticInfo* statInfo);
8997 CompAllocator getAllocator(CompMemKind cmk = CMK_Generic)
8999 return CompAllocator(compArenaAllocator, cmk);
9002 CompAllocator getAllocatorGC()
9004 return getAllocator(CMK_GC);
9007 CompAllocator getAllocatorLoopHoist()
9009 return getAllocator(CMK_LoopHoist);
9013 CompAllocator getAllocatorDebugOnly()
9015 return getAllocator(CMK_DebugOnly);
9020 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9021 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9025 XX Checks for type compatibility and merges types XX
9027 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9028 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9032 // Set to TRUE if verification cannot be skipped for this method
9033 // If we detect unverifiable code, we will lazily check
9034 // canSkipMethodVerification() to see if verification is REALLY needed.
9035 BOOL tiVerificationNeeded;
9037 // It it initially TRUE, and it gets set to FALSE if we run into unverifiable code
9038 // Note that this is valid only if tiVerificationNeeded was ever TRUE.
9039 BOOL tiIsVerifiableCode;
9041 // Set to TRUE if runtime callout is needed for this method
9042 BOOL tiRuntimeCalloutNeeded;
9044 // Set to TRUE if security prolog/epilog callout is needed for this method
9045 // Note: This flag is different than compNeedSecurityCheck.
9046 // compNeedSecurityCheck means whether or not a security object needs
9047 // to be allocated on the stack, which is currently true for EnC as well.
9048 // tiSecurityCalloutNeeded means whether or not security callouts need
9049 // to be inserted in the jitted code.
9050 BOOL tiSecurityCalloutNeeded;
9052 // Returns TRUE if child is equal to or a subtype of parent for merge purposes
9053 // This support is necessary to suport attributes that are not described in
9054 // for example, signatures. For example, the permanent home byref (byref that
9055 // points to the gc heap), isn't a property of method signatures, therefore,
9056 // it is safe to have mismatches here (that tiCompatibleWith will not flag),
9057 // but when deciding if we need to reimport a block, we need to take these
9059 BOOL tiMergeCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
9061 // Returns TRUE if child is equal to or a subtype of parent.
9062 // normalisedForStack indicates that both types are normalised for the stack
9063 BOOL tiCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
9065 // Merges pDest and pSrc. Returns FALSE if merge is undefined.
9066 // *pDest is modified to represent the merged type. Sets "*changed" to true
9067 // if this changes "*pDest".
9068 BOOL tiMergeToCommonParent(typeInfo* pDest, const typeInfo* pSrc, bool* changed) const;
9071 // <BUGNUM> VSW 471305
9072 // IJW allows assigning REF to BYREF. The following allows us to temporarily
9073 // bypass the assert check in gcMarkRegSetGCref and gcMarkRegSetByref
9074 // We use a "short" as we need to push/pop this scope.
9076 short compRegSetCheckLevel;
9080 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9081 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9083 XX IL verification stuff XX
9086 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9087 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9091 // The following is used to track liveness of local variables, initialization
9092 // of valueclass constructors, and type safe use of IL instructions.
9094 // dynamic state info needed for verification
9095 EntryState verCurrentState;
9097 // this ptr of object type .ctors are considered intited only after
9098 // the base class ctor is called, or an alternate ctor is called.
9099 // An uninited this ptr can be used to access fields, but cannot
9100 // be used to call a member function.
9101 BOOL verTrackObjCtorInitState;
9103 void verInitBBEntryState(BasicBlock* block, EntryState* currentState);
9105 // Requires that "tis" is not TIS_Bottom -- it's a definite init/uninit state.
9106 void verSetThisInit(BasicBlock* block, ThisInitState tis);
9107 void verInitCurrentState();
9108 void verResetCurrentState(BasicBlock* block, EntryState* currentState);
9110 // Merges the current verification state into the entry state of "block", return FALSE if that merge fails,
9111 // TRUE if it succeeds. Further sets "*changed" to true if this changes the entry state of "block".
9112 BOOL verMergeEntryStates(BasicBlock* block, bool* changed);
9114 void verConvertBBToThrowVerificationException(BasicBlock* block DEBUGARG(bool logMsg));
9115 void verHandleVerificationFailure(BasicBlock* block DEBUGARG(bool logMsg));
9116 typeInfo verMakeTypeInfo(CORINFO_CLASS_HANDLE clsHnd,
9117 bool bashStructToRef = false); // converts from jit type representation to typeInfo
9118 typeInfo verMakeTypeInfo(CorInfoType ciType,
9119 CORINFO_CLASS_HANDLE clsHnd); // converts from jit type representation to typeInfo
9120 BOOL verIsSDArray(typeInfo ti);
9121 typeInfo verGetArrayElemType(typeInfo ti);
9123 typeInfo verParseArgSigToTypeInfo(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_HANDLE args);
9124 BOOL verNeedsVerification();
9125 BOOL verIsByRefLike(const typeInfo& ti);
9126 BOOL verIsSafeToReturnByRef(const typeInfo& ti);
9128 // generic type variables range over types that satisfy IsBoxable
9129 BOOL verIsBoxable(const typeInfo& ti);
9131 void DECLSPEC_NORETURN verRaiseVerifyException(INDEBUG(const char* reason) DEBUGARG(const char* file)
9132 DEBUGARG(unsigned line));
9133 void verRaiseVerifyExceptionIfNeeded(INDEBUG(const char* reason) DEBUGARG(const char* file)
9134 DEBUGARG(unsigned line));
9135 bool verCheckTailCallConstraint(OPCODE opcode,
9136 CORINFO_RESOLVED_TOKEN* pResolvedToken,
9137 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call
9138 // on a type parameter?
9139 bool speculative // If true, won't throw if verificatoin fails. Instead it will
9140 // return false to the caller.
9141 // If false, it will throw.
9143 bool verIsBoxedValueType(typeInfo ti);
9145 void verVerifyCall(OPCODE opcode,
9146 CORINFO_RESOLVED_TOKEN* pResolvedToken,
9147 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
9149 bool readonlyCall, // is this a "readonly." call?
9150 const BYTE* delegateCreateStart,
9151 const BYTE* codeAddr,
9152 CORINFO_CALL_INFO* callInfo DEBUGARG(const char* methodName));
9154 BOOL verCheckDelegateCreation(const BYTE* delegateCreateStart, const BYTE* codeAddr, mdMemberRef& targetMemberRef);
9156 typeInfo verVerifySTIND(const typeInfo& ptr, const typeInfo& value, const typeInfo& instrType);
9157 typeInfo verVerifyLDIND(const typeInfo& ptr, const typeInfo& instrType);
9158 void verVerifyField(CORINFO_RESOLVED_TOKEN* pResolvedToken,
9159 const CORINFO_FIELD_INFO& fieldInfo,
9160 const typeInfo* tiThis,
9162 BOOL allowPlainStructAsThis = FALSE);
9163 void verVerifyCond(const typeInfo& tiOp1, const typeInfo& tiOp2, unsigned opcode);
9164 void verVerifyThisPtrInitialised();
9165 BOOL verIsCallToInitThisPtr(CORINFO_CLASS_HANDLE context, CORINFO_CLASS_HANDLE target);
9169 // One line log function. Default level is 0. Increasing it gives you
9170 // more log information
9172 // levels are currently unused: #define JITDUMP(level,...) ();
9173 void JitLogEE(unsigned level, const char* fmt, ...);
9175 bool compDebugBreak;
9177 bool compJitHaltMethod();
9182 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9183 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9185 XX GS Security checks for unsafe buffers XX
9187 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9188 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9191 struct ShadowParamVarInfo
9193 FixedBitVect* assignGroup; // the closure set of variables whose values depend on each other
9194 unsigned shadowCopy; // Lcl var num, valid only if not set to NO_SHADOW_COPY
9196 static bool mayNeedShadowCopy(LclVarDsc* varDsc)
9198 #if defined(_TARGET_AMD64_)
9199 // GS cookie logic to create shadow slots, create trees to copy reg args to shadow
9200 // slots and update all trees to refer to shadow slots is done immediately after
9201 // fgMorph(). Lsra could potentially mark a param as DoNotEnregister after JIT determines
9202 // not to shadow a parameter. Also, LSRA could potentially spill a param which is passed
9203 // in register. Therefore, conservatively all params may need a shadow copy. Note that
9204 // GS cookie logic further checks whether the param is a ptr or an unsafe buffer before
9205 // creating a shadow slot even though this routine returns true.
9207 // TODO-AMD64-CQ: Revisit this conservative approach as it could create more shadow slots than
9208 // required. There are two cases under which a reg arg could potentially be used from its
9210 // a) LSRA marks it as DoNotEnregister (see LinearScan::identifyCandidates())
9211 // b) LSRA spills it
9213 // Possible solution to address case (a)
9214 // - The conditions under which LSRA marks a varDsc as DoNotEnregister could be checked
9215 // in this routine. Note that live out of exception handler is something we may not be
9216 // able to do it here since GS cookie logic is invoked ahead of liveness computation.
9217 // Therefore, for methods with exception handling and need GS cookie check we might have
9218 // to take conservative approach.
9220 // Possible solution to address case (b)
9221 // - Whenver a parameter passed in an argument register needs to be spilled by LSRA, we
9222 // create a new spill temp if the method needs GS cookie check.
9223 return varDsc->lvIsParam;
9224 #else // !defined(_TARGET_AMD64_)
9225 return varDsc->lvIsParam && !varDsc->lvIsRegArg;
9232 printf("assignGroup [%p]; shadowCopy: [%d];\n", assignGroup, shadowCopy);
9237 GSCookie* gsGlobalSecurityCookieAddr; // Address of global cookie for unsafe buffer checks
9238 GSCookie gsGlobalSecurityCookieVal; // Value of global cookie if addr is NULL
9239 ShadowParamVarInfo* gsShadowVarInfo; // Table used by shadow param analysis code
9241 void gsGSChecksInitCookie(); // Grabs cookie variable
9242 void gsCopyShadowParams(); // Identify vulnerable params and create dhadow copies
9243 bool gsFindVulnerableParams(); // Shadow param analysis code
9244 void gsParamsToShadows(); // Insert copy code and replave param uses by shadow
9246 static fgWalkPreFn gsMarkPtrsAndAssignGroups; // Shadow param analysis tree-walk
9247 static fgWalkPreFn gsReplaceShadowParams; // Shadow param replacement tree-walk
9249 #define DEFAULT_MAX_INLINE_SIZE 100 // Methods with > DEFAULT_MAX_INLINE_SIZE IL bytes will never be inlined.
9250 // This can be overwritten by setting complus_JITInlineSize env variable.
9252 #define DEFAULT_MAX_INLINE_DEPTH 20 // Methods at more than this level deep will not be inlined
9254 #define DEFAULT_MAX_LOCALLOC_TO_LOCAL_SIZE 32 // fixed locallocs of this size or smaller will convert to local buffers
9257 #ifdef FEATURE_JIT_METHOD_PERF
9258 JitTimer* pCompJitTimer; // Timer data structure (by phases) for current compilation.
9259 static CompTimeSummaryInfo s_compJitTimerSummary; // Summary of the Timer information for the whole run.
9261 static LPCWSTR JitTimeLogCsv(); // Retrieve the file name for CSV from ConfigDWORD.
9262 static LPCWSTR compJitTimeLogFilename; // If a log file for JIT time is desired, filename to write it to.
9264 inline void EndPhase(Phases phase); // Indicate the end of the given phase.
9266 #if MEASURE_CLRAPI_CALLS
9267 // Thin wrappers that call into JitTimer (if present).
9268 inline void CLRApiCallEnter(unsigned apix);
9269 inline void CLRApiCallLeave(unsigned apix);
9272 inline void CLR_API_Enter(API_ICorJitInfo_Names ename);
9273 inline void CLR_API_Leave(API_ICorJitInfo_Names ename);
9278 #if defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
9279 // These variables are associated with maintaining SQM data about compile time.
9280 unsigned __int64 m_compCyclesAtEndOfInlining; // The thread-virtualized cycle count at the end of the inlining phase
9281 // in the current compilation.
9282 unsigned __int64 m_compCycles; // Net cycle count for current compilation
9283 DWORD m_compTickCountAtEndOfInlining; // The result of GetTickCount() (# ms since some epoch marker) at the end of
9284 // the inlining phase in the current compilation.
9285 #endif // defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
9287 // Records the SQM-relevant (cycles and tick count). Should be called after inlining is complete.
9288 // (We do this after inlining because this marks the last point at which the JIT is likely to cause
9289 // type-loading and class initialization).
9290 void RecordStateAtEndOfInlining();
9291 // Assumes being called at the end of compilation. Update the SQM state.
9292 void RecordStateAtEndOfCompilation();
9294 #ifdef FEATURE_CLRSQM
9295 // Does anything SQM related necessary at process shutdown time.
9296 static void ProcessShutdownSQMWork(ICorStaticInfo* statInfo);
9297 #endif // FEATURE_CLRSQM
9300 #if FUNC_INFO_LOGGING
9301 static LPCWSTR compJitFuncInfoFilename; // If a log file for per-function information is required, this is the
9302 // filename to write it to.
9303 static FILE* compJitFuncInfoFile; // And this is the actual FILE* to write to.
9304 #endif // FUNC_INFO_LOGGING
9306 Compiler* prevCompiler; // Previous compiler on stack for TLS Compiler* linked list for reentrant compilers.
9308 // Is the compilation in a full trust context?
9309 bool compIsFullTrust();
9312 void RecordNowayAssert(const char* filename, unsigned line, const char* condStr);
9313 #endif // MEASURE_NOWAY
9315 #ifndef FEATURE_TRACELOGGING
9316 // Should we actually fire the noway assert body and the exception handler?
9317 bool compShouldThrowOnNoway();
9318 #else // FEATURE_TRACELOGGING
9319 // Should we actually fire the noway assert body and the exception handler?
9320 bool compShouldThrowOnNoway(const char* filename, unsigned line);
9322 // Telemetry instance to use per method compilation.
9323 JitTelemetry compJitTelemetry;
9325 // Get common parameters that have to be logged with most telemetry data.
9326 void compGetTelemetryDefaults(const char** assemblyName,
9327 const char** scopeName,
9328 const char** methodName,
9329 unsigned* methodHash);
9330 #endif // !FEATURE_TRACELOGGING
9334 NodeToTestDataMap* m_nodeTestData;
9336 static const unsigned FIRST_LOOP_HOIST_CSE_CLASS = 1000;
9337 unsigned m_loopHoistCSEClass; // LoopHoist test annotations turn into CSE requirements; we
9338 // label them with CSE Class #'s starting at FIRST_LOOP_HOIST_CSE_CLASS.
9339 // Current kept in this.
9341 NodeToTestDataMap* GetNodeTestData()
9343 Compiler* compRoot = impInlineRoot();
9344 if (compRoot->m_nodeTestData == nullptr)
9346 compRoot->m_nodeTestData = new (getAllocatorDebugOnly()) NodeToTestDataMap(getAllocatorDebugOnly());
9348 return compRoot->m_nodeTestData;
9351 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, int> NodeToIntMap;
9353 // Returns the set (i.e., the domain of the result map) of nodes that are keys in m_nodeTestData, and
9354 // currently occur in the AST graph.
9355 NodeToIntMap* FindReachableNodesInNodeTestData();
9357 // Node "from" is being eliminated, and being replaced by node "to". If "from" had any associated
9358 // test data, associate that data with "to".
9359 void TransferTestDataToNode(GenTree* from, GenTree* to);
9361 // Requires that "to" is a clone of "from". If any nodes in the "from" tree
9362 // have annotations, attach similar annotations to the corresponding nodes in "to".
9363 void CopyTestDataToCloneTree(GenTree* from, GenTree* to);
9365 // These are the methods that test that the various conditions implied by the
9366 // test attributes are satisfied.
9367 void JitTestCheckSSA(); // SSA builder tests.
9368 void JitTestCheckVN(); // Value numbering tests.
9371 // The "FieldSeqStore", for canonicalizing field sequences. See the definition of FieldSeqStore for
9373 FieldSeqStore* m_fieldSeqStore;
9375 FieldSeqStore* GetFieldSeqStore()
9377 Compiler* compRoot = impInlineRoot();
9378 if (compRoot->m_fieldSeqStore == nullptr)
9380 // Create a CompAllocator that labels sub-structure with CMK_FieldSeqStore, and use that for allocation.
9381 CompAllocator ialloc(getAllocator(CMK_FieldSeqStore));
9382 compRoot->m_fieldSeqStore = new (ialloc) FieldSeqStore(ialloc);
9384 return compRoot->m_fieldSeqStore;
9387 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, FieldSeqNode*> NodeToFieldSeqMap;
9389 // Some nodes of "TYP_BYREF" or "TYP_I_IMPL" actually represent the address of a field within a struct, but since
9390 // the offset of the field is zero, there's no "GT_ADD" node. We normally attach a field sequence to the constant
9391 // that is added, but what do we do when that constant is zero, and is thus not present? We use this mechanism to
9392 // attach the field sequence directly to the address node.
9393 NodeToFieldSeqMap* m_zeroOffsetFieldMap;
9395 NodeToFieldSeqMap* GetZeroOffsetFieldMap()
9397 // Don't need to worry about inlining here
9398 if (m_zeroOffsetFieldMap == nullptr)
9400 // Create a CompAllocator that labels sub-structure with CMK_ZeroOffsetFieldMap, and use that for
9402 CompAllocator ialloc(getAllocator(CMK_ZeroOffsetFieldMap));
9403 m_zeroOffsetFieldMap = new (ialloc) NodeToFieldSeqMap(ialloc);
9405 return m_zeroOffsetFieldMap;
9408 // Requires that "op1" is a node of type "TYP_BYREF" or "TYP_I_IMPL". We are dereferencing this with the fields in
9409 // "fieldSeq", whose offsets are required all to be zero. Ensures that any field sequence annotation currently on
9410 // "op1" or its components is augmented by appending "fieldSeq". In practice, if "op1" is a GT_LCL_FLD, it has
9411 // a field sequence as a member; otherwise, it may be the addition of an a byref and a constant, where the const
9412 // has a field sequence -- in this case "fieldSeq" is appended to that of the constant; otherwise, we
9413 // record the the field sequence using the ZeroOffsetFieldMap described above.
9415 // One exception above is that "op1" is a node of type "TYP_REF" where "op1" is a GT_LCL_VAR.
9416 // This happens when System.Object vtable pointer is a regular field at offset 0 in System.Private.CoreLib in
9417 // CoreRT. Such case is handled same as the default case.
9418 void fgAddFieldSeqForZeroOffset(GenTree* op1, FieldSeqNode* fieldSeq);
9420 typedef JitHashTable<const GenTree*, JitPtrKeyFuncs<GenTree>, ArrayInfo> NodeToArrayInfoMap;
9421 NodeToArrayInfoMap* m_arrayInfoMap;
9423 NodeToArrayInfoMap* GetArrayInfoMap()
9425 Compiler* compRoot = impInlineRoot();
9426 if (compRoot->m_arrayInfoMap == nullptr)
9428 // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
9429 CompAllocator ialloc(getAllocator(CMK_ArrayInfoMap));
9430 compRoot->m_arrayInfoMap = new (ialloc) NodeToArrayInfoMap(ialloc);
9432 return compRoot->m_arrayInfoMap;
9435 //-----------------------------------------------------------------------------------------------------------------
9436 // Compiler::TryGetArrayInfo:
9437 // Given an indirection node, checks to see whether or not that indirection represents an array access, and
9438 // if so returns information about the array.
9441 // indir - The `GT_IND` node.
9442 // arrayInfo (out) - Information about the accessed array if this function returns true. Undefined otherwise.
9445 // True if the `GT_IND` node represents an array access; false otherwise.
9446 inline bool TryGetArrayInfo(GenTreeIndir* indir, ArrayInfo* arrayInfo)
9448 if ((indir->gtFlags & GTF_IND_ARR_INDEX) == 0)
9453 if (indir->gtOp1->OperIs(GT_INDEX_ADDR))
9455 GenTreeIndexAddr* const indexAddr = indir->gtOp1->AsIndexAddr();
9456 *arrayInfo = ArrayInfo(indexAddr->gtElemType, indexAddr->gtElemSize, indexAddr->gtElemOffset,
9457 indexAddr->gtStructElemClass);
9461 bool found = GetArrayInfoMap()->Lookup(indir, arrayInfo);
9466 NodeToUnsignedMap* m_memorySsaMap[MemoryKindCount];
9468 // In some cases, we want to assign intermediate SSA #'s to memory states, and know what nodes create those memory
9469 // states. (We do this for try blocks, where, if the try block doesn't do a call that loses track of the memory
9470 // state, all the possible memory states are possible initial states of the corresponding catch block(s).)
9471 NodeToUnsignedMap* GetMemorySsaMap(MemoryKind memoryKind)
9473 if (memoryKind == GcHeap && byrefStatesMatchGcHeapStates)
9475 // Use the same map for GCHeap and ByrefExposed when their states match.
9476 memoryKind = ByrefExposed;
9479 assert(memoryKind < MemoryKindCount);
9480 Compiler* compRoot = impInlineRoot();
9481 if (compRoot->m_memorySsaMap[memoryKind] == nullptr)
9483 // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
9484 CompAllocator ialloc(getAllocator(CMK_ArrayInfoMap));
9485 compRoot->m_memorySsaMap[memoryKind] = new (ialloc) NodeToUnsignedMap(ialloc);
9487 return compRoot->m_memorySsaMap[memoryKind];
9490 // The Refany type is the only struct type whose structure is implicitly assumed by IL. We need its fields.
9491 CORINFO_CLASS_HANDLE m_refAnyClass;
9492 CORINFO_FIELD_HANDLE GetRefanyDataField()
9494 if (m_refAnyClass == nullptr)
9496 m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
9498 return info.compCompHnd->getFieldInClass(m_refAnyClass, 0);
9500 CORINFO_FIELD_HANDLE GetRefanyTypeField()
9502 if (m_refAnyClass == nullptr)
9504 m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
9506 return info.compCompHnd->getFieldInClass(m_refAnyClass, 1);
9510 static BitSetSupport::BitSetOpCounter m_varsetOpCounter;
9512 #if ALLVARSET_COUNTOPS
9513 static BitSetSupport::BitSetOpCounter m_allvarsetOpCounter;
9516 static HelperCallProperties s_helperCallProperties;
9518 #ifdef UNIX_AMD64_ABI
9519 static var_types GetTypeFromClassificationAndSizes(SystemVClassificationType classType, int size);
9520 static var_types GetEightByteType(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
9523 static void GetStructTypeOffset(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
9526 unsigned __int8* offset0,
9527 unsigned __int8* offset1);
9529 void GetStructTypeOffset(CORINFO_CLASS_HANDLE typeHnd,
9532 unsigned __int8* offset0,
9533 unsigned __int8* offset1);
9535 #endif // defined(UNIX_AMD64_ABI)
9537 void fgMorphMultiregStructArgs(GenTreeCall* call);
9538 GenTree* fgMorphMultiregStructArg(GenTree* arg, fgArgTabEntry* fgEntryPtr);
9540 bool killGCRefs(GenTree* tree);
9542 }; // end of class Compiler
9544 // LclVarDsc constructor. Uses Compiler, so must come after Compiler definition.
9545 inline LclVarDsc::LclVarDsc()
9546 : // Initialize the ArgRegs to REG_STK.
9547 // The morph will do the right thing to change
9548 // to the right register if passed in register.
9551 #if FEATURE_MULTIREG_ARGS
9552 _lvOtherArgReg(REG_STK)
9554 #endif // FEATURE_MULTIREG_ARGS
9556 lvRefBlks(BlockSetOps::UninitVal())
9558 #endif // ASSERTION_PROP
9563 //---------------------------------------------------------------------------------------------------------------------
9564 // GenTreeVisitor: a flexible tree walker implemented using the curiosly-recurring-template pattern.
9566 // This class implements a configurable walker for IR trees. There are five configuration options (defaults values are
9567 // shown in parentheses):
9569 // - ComputeStack (false): when true, the walker will push each node onto the `m_ancestors` stack. "Ancestors" is a bit
9570 // of a misnomer, as the first entry will always be the current node.
9572 // - DoPreOrder (false): when true, the walker will invoke `TVisitor::PreOrderVisit` with the current node as an
9573 // argument before visiting the node's operands.
9575 // - DoPostOrder (false): when true, the walker will invoke `TVisitor::PostOrderVisit` with the current node as an
9576 // argument after visiting the node's operands.
9578 // - DoLclVarsOnly (false): when true, the walker will only invoke `TVisitor::PreOrderVisit` for lclVar nodes.
9579 // `DoPreOrder` must be true if this option is true.
9581 // - UseExecutionOrder (false): when true, then walker will visit a node's operands in execution order (e.g. if a
9582 // binary operator has the `GTF_REVERSE_OPS` flag set, the second operand will be
9583 // visited before the first).
9585 // At least one of `DoPreOrder` and `DoPostOrder` must be specified.
9587 // A simple pre-order visitor might look something like the following:
9589 // class CountingVisitor final : public GenTreeVisitor<CountingVisitor>
9594 // DoPreOrder = true
9597 // unsigned m_count;
9599 // CountingVisitor(Compiler* compiler)
9600 // : GenTreeVisitor<CountingVisitor>(compiler), m_count(0)
9604 // Compiler::fgWalkResult PreOrderVisit(GenTree* node)
9610 // This visitor would then be used like so:
9612 // CountingVisitor countingVisitor(compiler);
9613 // countingVisitor.WalkTree(root);
9615 template <typename TVisitor>
9616 class GenTreeVisitor
9619 typedef Compiler::fgWalkResult fgWalkResult;
9623 ComputeStack = false,
9625 DoPostOrder = false,
9626 DoLclVarsOnly = false,
9627 UseExecutionOrder = false,
9630 Compiler* m_compiler;
9631 ArrayStack<GenTree*> m_ancestors;
9633 GenTreeVisitor(Compiler* compiler) : m_compiler(compiler), m_ancestors(compiler->getAllocator(CMK_ArrayStack))
9635 assert(compiler != nullptr);
9637 static_assert_no_msg(TVisitor::DoPreOrder || TVisitor::DoPostOrder);
9638 static_assert_no_msg(!TVisitor::DoLclVarsOnly || TVisitor::DoPreOrder);
9641 fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
9643 return fgWalkResult::WALK_CONTINUE;
9646 fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
9648 return fgWalkResult::WALK_CONTINUE;
9652 fgWalkResult WalkTree(GenTree** use, GenTree* user)
9654 assert(use != nullptr);
9656 GenTree* node = *use;
9658 if (TVisitor::ComputeStack)
9660 m_ancestors.Push(node);
9663 fgWalkResult result = fgWalkResult::WALK_CONTINUE;
9664 if (TVisitor::DoPreOrder && !TVisitor::DoLclVarsOnly)
9666 result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9667 if (result == fgWalkResult::WALK_ABORT)
9673 if ((node == nullptr) || (result == fgWalkResult::WALK_SKIP_SUBTREES))
9679 switch (node->OperGet())
9684 case GT_LCL_VAR_ADDR:
9685 case GT_LCL_FLD_ADDR:
9686 if (TVisitor::DoLclVarsOnly)
9688 result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9689 if (result == fgWalkResult::WALK_ABORT)
9705 case GT_MEMORYBARRIER:
9710 case GT_START_NONGC:
9712 #if !FEATURE_EH_FUNCLETS
9714 #endif // !FEATURE_EH_FUNCLETS
9719 case GT_CLS_VAR_ADDR:
9723 case GT_PINVOKE_PROLOG:
9724 case GT_PINVOKE_EPILOG:
9728 // Lclvar unary operators
9729 case GT_STORE_LCL_VAR:
9730 case GT_STORE_LCL_FLD:
9731 if (TVisitor::DoLclVarsOnly)
9733 result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9734 if (result == fgWalkResult::WALK_ABORT)
9741 // Standard unary operators
9768 case GT_RUNTIMELOOKUP:
9770 GenTreeUnOp* const unOp = node->AsUnOp();
9771 if (unOp->gtOp1 != nullptr)
9773 result = WalkTree(&unOp->gtOp1, unOp);
9774 if (result == fgWalkResult::WALK_ABORT)
9785 GenTreeCmpXchg* const cmpXchg = node->AsCmpXchg();
9787 result = WalkTree(&cmpXchg->gtOpLocation, cmpXchg);
9788 if (result == fgWalkResult::WALK_ABORT)
9792 result = WalkTree(&cmpXchg->gtOpValue, cmpXchg);
9793 if (result == fgWalkResult::WALK_ABORT)
9797 result = WalkTree(&cmpXchg->gtOpComparand, cmpXchg);
9798 if (result == fgWalkResult::WALK_ABORT)
9805 case GT_ARR_BOUNDS_CHECK:
9808 #endif // FEATURE_SIMD
9809 #ifdef FEATURE_HW_INTRINSICS
9810 case GT_HW_INTRINSIC_CHK:
9811 #endif // FEATURE_HW_INTRINSICS
9813 GenTreeBoundsChk* const boundsChk = node->AsBoundsChk();
9815 result = WalkTree(&boundsChk->gtIndex, boundsChk);
9816 if (result == fgWalkResult::WALK_ABORT)
9820 result = WalkTree(&boundsChk->gtArrLen, boundsChk);
9821 if (result == fgWalkResult::WALK_ABORT)
9830 GenTreeField* const field = node->AsField();
9832 if (field->gtFldObj != nullptr)
9834 result = WalkTree(&field->gtFldObj, field);
9835 if (result == fgWalkResult::WALK_ABORT)
9845 GenTreeArrElem* const arrElem = node->AsArrElem();
9847 result = WalkTree(&arrElem->gtArrObj, arrElem);
9848 if (result == fgWalkResult::WALK_ABORT)
9853 const unsigned rank = arrElem->gtArrRank;
9854 for (unsigned dim = 0; dim < rank; dim++)
9856 result = WalkTree(&arrElem->gtArrInds[dim], arrElem);
9857 if (result == fgWalkResult::WALK_ABORT)
9867 GenTreeArrOffs* const arrOffs = node->AsArrOffs();
9869 result = WalkTree(&arrOffs->gtOffset, arrOffs);
9870 if (result == fgWalkResult::WALK_ABORT)
9874 result = WalkTree(&arrOffs->gtIndex, arrOffs);
9875 if (result == fgWalkResult::WALK_ABORT)
9879 result = WalkTree(&arrOffs->gtArrObj, arrOffs);
9880 if (result == fgWalkResult::WALK_ABORT)
9889 GenTreeDynBlk* const dynBlock = node->AsDynBlk();
9891 GenTree** op1Use = &dynBlock->gtOp1;
9892 GenTree** op2Use = &dynBlock->gtDynamicSize;
9894 if (TVisitor::UseExecutionOrder && dynBlock->gtEvalSizeFirst)
9896 std::swap(op1Use, op2Use);
9899 result = WalkTree(op1Use, dynBlock);
9900 if (result == fgWalkResult::WALK_ABORT)
9904 result = WalkTree(op2Use, dynBlock);
9905 if (result == fgWalkResult::WALK_ABORT)
9912 case GT_STORE_DYN_BLK:
9914 GenTreeDynBlk* const dynBlock = node->AsDynBlk();
9916 GenTree** op1Use = &dynBlock->gtOp1;
9917 GenTree** op2Use = &dynBlock->gtOp2;
9918 GenTree** op3Use = &dynBlock->gtDynamicSize;
9920 if (TVisitor::UseExecutionOrder)
9922 if (dynBlock->IsReverseOp())
9924 std::swap(op1Use, op2Use);
9926 if (dynBlock->gtEvalSizeFirst)
9928 std::swap(op3Use, op2Use);
9929 std::swap(op2Use, op1Use);
9933 result = WalkTree(op1Use, dynBlock);
9934 if (result == fgWalkResult::WALK_ABORT)
9938 result = WalkTree(op2Use, dynBlock);
9939 if (result == fgWalkResult::WALK_ABORT)
9943 result = WalkTree(op3Use, dynBlock);
9944 if (result == fgWalkResult::WALK_ABORT)
9953 GenTreeCall* const call = node->AsCall();
9955 if (call->gtCallObjp != nullptr)
9957 result = WalkTree(&call->gtCallObjp, call);
9958 if (result == fgWalkResult::WALK_ABORT)
9964 for (GenTreeArgList* args = call->gtCallArgs; args != nullptr; args = args->Rest())
9966 result = WalkTree(args->pCurrent(), call);
9967 if (result == fgWalkResult::WALK_ABORT)
9973 for (GenTreeArgList* args = call->gtCallLateArgs; args != nullptr; args = args->Rest())
9975 result = WalkTree(args->pCurrent(), call);
9976 if (result == fgWalkResult::WALK_ABORT)
9982 if (call->gtCallType == CT_INDIRECT)
9984 if (call->gtCallCookie != nullptr)
9986 result = WalkTree(&call->gtCallCookie, call);
9987 if (result == fgWalkResult::WALK_ABORT)
9993 result = WalkTree(&call->gtCallAddr, call);
9994 if (result == fgWalkResult::WALK_ABORT)
10000 if (call->gtControlExpr != nullptr)
10002 result = WalkTree(&call->gtControlExpr, call);
10003 if (result == fgWalkResult::WALK_ABORT)
10015 assert(node->OperIsBinary());
10017 GenTreeOp* const op = node->AsOp();
10019 GenTree** op1Use = &op->gtOp1;
10020 GenTree** op2Use = &op->gtOp2;
10022 if (TVisitor::UseExecutionOrder && node->IsReverseOp())
10024 std::swap(op1Use, op2Use);
10027 if (*op1Use != nullptr)
10029 result = WalkTree(op1Use, op);
10030 if (result == fgWalkResult::WALK_ABORT)
10036 if (*op2Use != nullptr)
10038 result = WalkTree(op2Use, op);
10039 if (result == fgWalkResult::WALK_ABORT)
10049 // Finally, visit the current node
10050 if (TVisitor::DoPostOrder)
10052 result = reinterpret_cast<TVisitor*>(this)->PostOrderVisit(use, user);
10055 if (TVisitor::ComputeStack)
10064 template <bool computeStack, bool doPreOrder, bool doPostOrder, bool doLclVarsOnly, bool useExecutionOrder>
10065 class GenericTreeWalker final
10066 : public GenTreeVisitor<GenericTreeWalker<computeStack, doPreOrder, doPostOrder, doLclVarsOnly, useExecutionOrder>>
10071 ComputeStack = computeStack,
10072 DoPreOrder = doPreOrder,
10073 DoPostOrder = doPostOrder,
10074 DoLclVarsOnly = doLclVarsOnly,
10075 UseExecutionOrder = useExecutionOrder,
10079 Compiler::fgWalkData* m_walkData;
10082 GenericTreeWalker(Compiler::fgWalkData* walkData)
10083 : GenTreeVisitor<GenericTreeWalker<computeStack, doPreOrder, doPostOrder, doLclVarsOnly, useExecutionOrder>>(
10084 walkData->compiler)
10085 , m_walkData(walkData)
10087 assert(walkData != nullptr);
10091 walkData->parentStack = &this->m_ancestors;
10095 Compiler::fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
10097 m_walkData->parent = user;
10098 return m_walkData->wtprVisitorFn(use, m_walkData);
10101 Compiler::fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
10103 m_walkData->parent = user;
10104 return m_walkData->wtpoVisitorFn(use, m_walkData);
10109 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10110 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10112 XX Miscellaneous Compiler stuff XX
10114 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10115 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10118 // Values used to mark the types a stack slot is used for
10120 const unsigned TYPE_REF_INT = 0x01; // slot used as a 32-bit int
10121 const unsigned TYPE_REF_LNG = 0x02; // slot used as a 64-bit long
10122 const unsigned TYPE_REF_FLT = 0x04; // slot used as a 32-bit float
10123 const unsigned TYPE_REF_DBL = 0x08; // slot used as a 64-bit float
10124 const unsigned TYPE_REF_PTR = 0x10; // slot used as a 32-bit pointer
10125 const unsigned TYPE_REF_BYR = 0x20; // slot used as a byref pointer
10126 const unsigned TYPE_REF_STC = 0x40; // slot used as a struct
10127 const unsigned TYPE_REF_TYPEMASK = 0x7F; // bits that represent the type
10129 // const unsigned TYPE_REF_ADDR_TAKEN = 0x80; // slots address was taken
10131 /*****************************************************************************
10133 * Variables to keep track of total code amounts.
10138 extern size_t grossVMsize;
10139 extern size_t grossNCsize;
10140 extern size_t totalNCsize;
10142 extern unsigned genMethodICnt;
10143 extern unsigned genMethodNCnt;
10144 extern size_t gcHeaderISize;
10145 extern size_t gcPtrMapISize;
10146 extern size_t gcHeaderNSize;
10147 extern size_t gcPtrMapNSize;
10149 #endif // DISPLAY_SIZES
10151 /*****************************************************************************
10153 * Variables to keep track of basic block counts (more data on 1 BB methods)
10156 #if COUNT_BASIC_BLOCKS
10157 extern Histogram bbCntTable;
10158 extern Histogram bbOneBBSizeTable;
10161 /*****************************************************************************
10163 * Used by optFindNaturalLoops to gather statistical information such as
10164 * - total number of natural loops
10165 * - number of loops with 1, 2, ... exit conditions
10166 * - number of loops that have an iterator (for like)
10167 * - number of loops that have a constant iterator
10172 extern unsigned totalLoopMethods; // counts the total number of methods that have natural loops
10173 extern unsigned maxLoopsPerMethod; // counts the maximum number of loops a method has
10174 extern unsigned totalLoopOverflows; // # of methods that identified more loops than we can represent
10175 extern unsigned totalLoopCount; // counts the total number of natural loops
10176 extern unsigned totalUnnatLoopCount; // counts the total number of (not-necessarily natural) loops
10177 extern unsigned totalUnnatLoopOverflows; // # of methods that identified more unnatural loops than we can represent
10178 extern unsigned iterLoopCount; // counts the # of loops with an iterator (for like)
10179 extern unsigned simpleTestLoopCount; // counts the # of loops with an iterator and a simple loop condition (iter <
10181 extern unsigned constIterLoopCount; // counts the # of loops with a constant iterator (for like)
10182 extern bool hasMethodLoops; // flag to keep track if we already counted a method as having loops
10183 extern unsigned loopsThisMethod; // counts the number of loops in the current method
10184 extern bool loopOverflowThisMethod; // True if we exceeded the max # of loops in the method.
10185 extern Histogram loopCountTable; // Histogram of loop counts
10186 extern Histogram loopExitCountTable; // Histogram of loop exit counts
10188 #endif // COUNT_LOOPS
10190 /*****************************************************************************
10191 * variables to keep track of how many iterations we go in a dataflow pass
10196 extern unsigned CSEiterCount; // counts the # of iteration for the CSE dataflow
10197 extern unsigned CFiterCount; // counts the # of iteration for the Const Folding dataflow
10199 #endif // DATAFLOW_ITER
10201 #if MEASURE_BLOCK_SIZE
10202 extern size_t genFlowNodeSize;
10203 extern size_t genFlowNodeCnt;
10204 #endif // MEASURE_BLOCK_SIZE
10206 #if MEASURE_NODE_SIZE
10207 struct NodeSizeStats
10211 genTreeNodeCnt = 0;
10212 genTreeNodeSize = 0;
10213 genTreeNodeActualSize = 0;
10216 // Count of tree nodes allocated.
10217 unsigned __int64 genTreeNodeCnt;
10219 // The size we allocate.
10220 unsigned __int64 genTreeNodeSize;
10222 // The actual size of the node. Note that the actual size will likely be smaller
10223 // than the allocated size, but we sometimes use SetOper()/ChangeOper() to change
10224 // a smaller node to a larger one. TODO-Cleanup: add stats on
10225 // SetOper()/ChangeOper() usage to quantify this.
10226 unsigned __int64 genTreeNodeActualSize;
10228 extern NodeSizeStats genNodeSizeStats; // Total node size stats
10229 extern NodeSizeStats genNodeSizeStatsPerFunc; // Per-function node size stats
10230 extern Histogram genTreeNcntHist;
10231 extern Histogram genTreeNsizHist;
10232 #endif // MEASURE_NODE_SIZE
10234 /*****************************************************************************
10235 * Count fatal errors (including noway_asserts).
10239 extern unsigned fatal_badCode;
10240 extern unsigned fatal_noWay;
10241 extern unsigned fatal_NOMEM;
10242 extern unsigned fatal_noWayAssertBody;
10244 extern unsigned fatal_noWayAssertBodyArgs;
10246 extern unsigned fatal_NYI;
10247 #endif // MEASURE_FATAL
10249 /*****************************************************************************
10253 #ifdef _TARGET_XARCH_
10255 const instruction INS_SHIFT_LEFT_LOGICAL = INS_shl;
10256 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_shr;
10257 const instruction INS_SHIFT_RIGHT_ARITHM = INS_sar;
10259 const instruction INS_AND = INS_and;
10260 const instruction INS_OR = INS_or;
10261 const instruction INS_XOR = INS_xor;
10262 const instruction INS_NEG = INS_neg;
10263 const instruction INS_TEST = INS_test;
10264 const instruction INS_MUL = INS_imul;
10265 const instruction INS_SIGNED_DIVIDE = INS_idiv;
10266 const instruction INS_UNSIGNED_DIVIDE = INS_div;
10267 const instruction INS_BREAKPOINT = INS_int3;
10268 const instruction INS_ADDC = INS_adc;
10269 const instruction INS_SUBC = INS_sbb;
10270 const instruction INS_NOT = INS_not;
10272 #endif // _TARGET_XARCH_
10274 #ifdef _TARGET_ARM_
10276 const instruction INS_SHIFT_LEFT_LOGICAL = INS_lsl;
10277 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_lsr;
10278 const instruction INS_SHIFT_RIGHT_ARITHM = INS_asr;
10280 const instruction INS_AND = INS_and;
10281 const instruction INS_OR = INS_orr;
10282 const instruction INS_XOR = INS_eor;
10283 const instruction INS_NEG = INS_rsb;
10284 const instruction INS_TEST = INS_tst;
10285 const instruction INS_MUL = INS_mul;
10286 const instruction INS_MULADD = INS_mla;
10287 const instruction INS_SIGNED_DIVIDE = INS_sdiv;
10288 const instruction INS_UNSIGNED_DIVIDE = INS_udiv;
10289 const instruction INS_BREAKPOINT = INS_bkpt;
10290 const instruction INS_ADDC = INS_adc;
10291 const instruction INS_SUBC = INS_sbc;
10292 const instruction INS_NOT = INS_mvn;
10294 const instruction INS_ABS = INS_vabs;
10295 const instruction INS_SQRT = INS_vsqrt;
10297 #endif // _TARGET_ARM_
10299 #ifdef _TARGET_ARM64_
10301 const instruction INS_MULADD = INS_madd;
10302 const instruction INS_BREAKPOINT = INS_bkpt;
10304 const instruction INS_ABS = INS_fabs;
10305 const instruction INS_SQRT = INS_fsqrt;
10307 #endif // _TARGET_ARM64_
10309 /*****************************************************************************/
10311 extern const BYTE genTypeSizes[];
10312 extern const BYTE genTypeAlignments[];
10313 extern const BYTE genTypeStSzs[];
10314 extern const BYTE genActualTypes[];
10316 /*****************************************************************************/
10318 // VERY_LARGE_FRAME_SIZE_REG_MASK is the set of registers we need to use for
10319 // the probing loop generated for very large stack frames (see `getVeryLargeFrameSize`).
10321 #ifdef _TARGET_ARM_
10322 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R4 | RBM_R5 | RBM_R6)
10323 #elif defined(_TARGET_ARM64_)
10324 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R9 | RBM_R10 | RBM_R11)
10327 /*****************************************************************************/
10329 extern BasicBlock dummyBB;
10331 /*****************************************************************************/
10332 /*****************************************************************************/
10334 // foreach_treenode_execution_order: An iterator that iterates through all the tree
10335 // nodes of a statement in execution order.
10336 // __stmt: a GT_STMT type GenTree*
10337 // __node: a GenTree*, already declared, that gets updated with each node in the statement, in execution order
10339 #define foreach_treenode_execution_order(__node, __stmt) \
10340 for ((__node) = (__stmt)->gtStmt.gtStmtList; (__node); (__node) = (__node)->gtNext)
10342 // foreach_block: An iterator over all blocks in the function.
10343 // __compiler: the Compiler* object
10344 // __block : a BasicBlock*, already declared, that gets updated each iteration.
10346 #define foreach_block(__compiler, __block) \
10347 for ((__block) = (__compiler)->fgFirstBB; (__block); (__block) = (__block)->bbNext)
10349 /*****************************************************************************/
10350 /*****************************************************************************/
10354 void dumpConvertedVarSet(Compiler* comp, VARSET_VALARG_TP vars);
10356 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10357 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10359 XX Debugging helpers XX
10361 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10362 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10365 /*****************************************************************************/
10366 /* The following functions are intended to be called from the debugger, to dump
10367 * various data structures. The can be used in the debugger Watch or Quick Watch
10368 * windows. They are designed to be short to type and take as few arguments as
10369 * possible. The 'c' versions take a Compiler*, whereas the 'd' versions use the TlsCompiler.
10370 * See the function definition comment for more details.
10373 void cBlock(Compiler* comp, BasicBlock* block);
10374 void cBlocks(Compiler* comp);
10375 void cBlocksV(Compiler* comp);
10376 void cTree(Compiler* comp, GenTree* tree);
10377 void cTrees(Compiler* comp);
10378 void cEH(Compiler* comp);
10379 void cVar(Compiler* comp, unsigned lclNum);
10380 void cVarDsc(Compiler* comp, LclVarDsc* varDsc);
10381 void cVars(Compiler* comp);
10382 void cVarsFinal(Compiler* comp);
10383 void cBlockPreds(Compiler* comp, BasicBlock* block);
10384 void cReach(Compiler* comp);
10385 void cDoms(Compiler* comp);
10386 void cLiveness(Compiler* comp);
10387 void cCVarSet(Compiler* comp, VARSET_VALARG_TP vars);
10389 void cFuncIR(Compiler* comp);
10390 void cBlockIR(Compiler* comp, BasicBlock* block);
10391 void cLoopIR(Compiler* comp, Compiler::LoopDsc* loop);
10392 void cTreeIR(Compiler* comp, GenTree* tree);
10393 int cTreeTypeIR(Compiler* comp, GenTree* tree);
10394 int cTreeKindsIR(Compiler* comp, GenTree* tree);
10395 int cTreeFlagsIR(Compiler* comp, GenTree* tree);
10396 int cOperandIR(Compiler* comp, GenTree* operand);
10397 int cLeafIR(Compiler* comp, GenTree* tree);
10398 int cIndirIR(Compiler* comp, GenTree* tree);
10399 int cListIR(Compiler* comp, GenTree* list);
10400 int cSsaNumIR(Compiler* comp, GenTree* tree);
10401 int cValNumIR(Compiler* comp, GenTree* tree);
10402 int cDependsIR(Compiler* comp, GenTree* comma, bool* first);
10404 void dBlock(BasicBlock* block);
10407 void dTree(GenTree* tree);
10410 void dVar(unsigned lclNum);
10411 void dVarDsc(LclVarDsc* varDsc);
10414 void dBlockPreds(BasicBlock* block);
10418 void dCVarSet(VARSET_VALARG_TP vars);
10420 void dRegMask(regMaskTP mask);
10423 void dBlockIR(BasicBlock* block);
10424 void dTreeIR(GenTree* tree);
10425 void dLoopIR(Compiler::LoopDsc* loop);
10426 void dLoopNumIR(unsigned loopNum);
10427 int dTabStopIR(int curr, int tabstop);
10428 int dTreeTypeIR(GenTree* tree);
10429 int dTreeKindsIR(GenTree* tree);
10430 int dTreeFlagsIR(GenTree* tree);
10431 int dOperandIR(GenTree* operand);
10432 int dLeafIR(GenTree* tree);
10433 int dIndirIR(GenTree* tree);
10434 int dListIR(GenTree* list);
10435 int dSsaNumIR(GenTree* tree);
10436 int dValNumIR(GenTree* tree);
10437 int dDependsIR(GenTree* comma);
10440 GenTree* dFindTree(GenTree* tree, unsigned id);
10441 GenTree* dFindTree(unsigned id);
10442 GenTreeStmt* dFindStmt(unsigned id);
10443 BasicBlock* dFindBlock(unsigned bbNum);
10447 #include "compiler.hpp" // All the shared inline functions
10449 /*****************************************************************************/
10450 #endif //_COMPILER_H_
10451 /*****************************************************************************/