1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 /*****************************************************************************/
15 #include "jitgcinfo.h"
17 /*****************************************************************************/
19 #ifndef _ADDRMAP_INCLUDED_
22 #ifndef _LOCALMAP_INCLUDED_
25 #ifndef _PDBREWRITE_H_
26 #include "pdbrewrite.h"
28 #endif // TRANSLATE_PDB
30 /*****************************************************************************/
32 #pragma warning(disable : 4200) // allow arrays of 0 size inside structs
34 #define TRACK_GC_TEMP_LIFETIMES 0
36 /*****************************************************************************/
41 #define EMITVERBOSE (emitComp->verbose)
45 #define EMIT_GC_VERBOSE 0
47 #define EMIT_GC_VERBOSE (emitComp->verbose)
51 #define EMIT_INSTLIST_VERBOSE 0
53 #define EMIT_INSTLIST_VERBOSE (emitComp->verbose)
56 /*****************************************************************************/
65 void emitterStats(FILE* fout);
66 void emitterStaticStats(FILE* fout); // Static stats about the emitter (data structure offsets, sizes, etc.)
69 void printRegMaskInt(regMaskTP mask);
71 /*****************************************************************************/
72 /* Forward declarations */
78 typedef void (*emitSplitCallbackType)(void* context, emitLocation* emitLoc);
80 /*****************************************************************************/
82 //-----------------------------------------------------------------------------
84 inline bool needsGC(GCtype gcType)
86 if (gcType == GCT_NONE)
92 assert(gcType == GCT_GCREF || gcType == GCT_BYREF);
97 //-----------------------------------------------------------------------------
101 inline bool IsValidGCtype(GCtype gcType)
103 return (gcType == GCT_NONE || gcType == GCT_GCREF || gcType == GCT_BYREF);
106 // Get a string name to represent the GC type
108 inline const char* GCtypeStr(GCtype gcType)
119 assert(!"Invalid GCtype");
126 /*****************************************************************************/
129 #define INTERESTING_JUMP_NUM -1 // set to 0 to see all jump info
130 //#define INTERESTING_JUMP_NUM 0
133 /*****************************************************************************
135 * Represent an emitter location.
141 emitLocation() : ig(nullptr), codePos(0)
145 emitLocation(insGroup* _ig) : ig(_ig), codePos(0)
149 emitLocation(void* emitCookie) : ig((insGroup*)emitCookie), codePos(0)
153 // A constructor for code that needs to call it explicitly.
156 this->emitLocation::emitLocation();
159 void CaptureLocation(emitter* emit);
161 bool IsCurrentLocation(emitter* emit) const;
163 // This function is highly suspect, since it presumes knowledge of the codePos "cookie",
164 // and doesn't look at the 'ig' pointer.
165 bool IsOffsetZero() const
167 return (codePos == 0);
170 UNATIVE_OFFSET CodeOffset(emitter* emit) const;
172 insGroup* GetIG() const
177 int GetInsNum() const;
179 bool operator!=(const emitLocation& other) const
181 return (ig != other.ig) || (codePos != other.codePos);
184 bool operator==(const emitLocation& other) const
186 return !(*this != other);
191 // Things we could validate:
192 // 1. the instruction group pointer is non-nullptr.
193 // 2. 'ig' is a legal pointer to an instruction group.
194 // 3. 'codePos' is a legal offset into 'ig'.
195 // Currently, we just do #1.
196 // #2 and #3 should only be done in DEBUG, if they are implemented.
206 #ifdef _TARGET_AMD64_
207 UNATIVE_OFFSET GetFuncletPrologOffset(emitter* emit) const;
208 #endif // _TARGET_AMD64_
215 insGroup* ig; // the instruction group
216 unsigned codePos; // the code position within the IG (see emitCurOffset())
219 /************************************************************************/
220 /* The following describes an instruction group */
221 /************************************************************************/
223 DECLARE_TYPED_ENUM(insGroupPlaceholderType, unsigned char)
225 IGPT_PROLOG, // currently unused
227 #if FEATURE_EH_FUNCLETS
228 IGPT_FUNCLET_PROLOG, IGPT_FUNCLET_EPILOG,
229 #endif // FEATURE_EH_FUNCLETS
231 END_DECLARE_TYPED_ENUM(insGroupPlaceholderType, unsigned char)
233 #if defined(_MSC_VER) && defined(_TARGET_ARM_)
234 // ARM aligns structures that contain 64-bit ints or doubles on 64-bit boundaries. This causes unwanted
235 // padding to be added to the end, so sizeof() is unnecessarily big.
238 #endif // defined(_MSC_VER) && defined(_TARGET_ARM_)
240 struct insPlaceholderGroupData
244 VARSET_TP igPhInitGCrefVars;
245 regMaskTP igPhInitGCrefRegs;
246 regMaskTP igPhInitByrefRegs;
247 VARSET_TP igPhPrevGCrefVars;
248 regMaskTP igPhPrevGCrefRegs;
249 regMaskTP igPhPrevByrefRegs;
250 insGroupPlaceholderType igPhType;
251 }; // end of struct insPlaceholderGroupData
258 insGroup* igSelf; // for consistency checking
261 UNATIVE_OFFSET igNum; // for ordering (and display) purposes
262 UNATIVE_OFFSET igOffs; // offset of this group within method
263 unsigned int igFuncIdx; // Which function/funclet does this belong to? (Index into Compiler::compFuncInfos array.)
264 unsigned short igFlags; // see IGF_xxx below
265 unsigned short igSize; // # of bytes of code in this group
267 #define IGF_GC_VARS 0x0001 // new set of live GC ref variables
268 #define IGF_BYREF_REGS 0x0002 // new set of live by-ref registers
269 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
270 #define IGF_FINALLY_TARGET 0x0004 // this group is the start of a basic block that is returned to after a finally.
271 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
272 #define IGF_FUNCLET_PROLOG 0x0008 // this group belongs to a funclet prolog
273 #define IGF_FUNCLET_EPILOG 0x0010 // this group belongs to a funclet epilog.
274 #define IGF_EPILOG 0x0020 // this group belongs to a main function epilog
275 #define IGF_NOGCINTERRUPT 0x0040 // this IG is is a no-interrupt region (prolog, epilog, etc.)
276 #define IGF_UPD_ISZ 0x0080 // some instruction sizes updated
277 #define IGF_PLACEHOLDER 0x0100 // this is a placeholder group, to be filled in later
278 #define IGF_EMIT_ADD 0x0200 // this is a block added by the emitter
279 // because the codegen block was too big. Also used for
280 // placeholder IGs that aren't also labels.
282 // Mask of IGF_* flags that should be propagated to new blocks when they are created.
283 // This allows prologs and epilogs to be any number of IGs, but still be
284 // automatically marked properly.
285 #if FEATURE_EH_FUNCLETS
287 #define IGF_PROPAGATE_MASK (IGF_EPILOG | IGF_FUNCLET_PROLOG | IGF_FUNCLET_EPILOG)
289 #define IGF_PROPAGATE_MASK (IGF_EPILOG | IGF_FUNCLET_PROLOG)
291 #else // FEATURE_EH_FUNCLETS
292 #define IGF_PROPAGATE_MASK (IGF_EPILOG)
293 #endif // FEATURE_EH_FUNCLETS
295 // Try to do better packing based on how large regMaskSmall is (8, 16, or 64 bits).
296 CLANG_FORMAT_COMMENT_ANCHOR;
297 #if REGMASK_BITS <= 32
300 BYTE* igData; // addr of instruction descriptors
301 insPlaceholderGroupData* igPhData; // when igFlags & IGF_PLACEHOLDER
304 #if EMIT_TRACK_STACK_DEPTH
305 unsigned igStkLvl; // stack level on entry
307 regMaskSmall igGCregs; // set of registers with live GC refs
308 unsigned char igInsCnt; // # of instructions in this group
310 #else // REGMASK_BITS
312 regMaskSmall igGCregs; // set of registers with live GC refs
315 BYTE* igData; // addr of instruction descriptors
316 insPlaceholderGroupData* igPhData; // when igFlags & IGF_PLACEHOLDER
319 #if EMIT_TRACK_STACK_DEPTH
320 unsigned igStkLvl; // stack level on entry
323 unsigned char igInsCnt; // # of instructions in this group
325 #endif // REGMASK_BITS
327 VARSET_VALRET_TP igGCvars() const
329 assert(igFlags & IGF_GC_VARS);
331 BYTE* ptr = (BYTE*)igData;
332 ptr -= sizeof(VARSET_TP);
334 return *(VARSET_TP*)ptr;
337 unsigned igByrefRegs() const
339 assert(igFlags & IGF_BYREF_REGS);
341 BYTE* ptr = (BYTE*)igData;
343 if (igFlags & IGF_GC_VARS)
345 ptr -= sizeof(VARSET_TP);
348 ptr -= sizeof(unsigned);
350 return *(unsigned*)ptr;
353 }; // end of struct insGroup
355 // For AMD64 the maximum prolog/epilog size supported on the OS is 256 bytes
356 // Since it is incorrect for us to be jumping across funclet prolog/epilogs
357 // we will use the following estimate as the maximum placeholder size.
359 #define MAX_PLACEHOLDER_IG_SIZE 256
361 #if defined(_MSC_VER) && defined(_TARGET_ARM_)
363 #endif // defined(_MSC_VER) && defined(_TARGET_ARM_)
365 /*****************************************************************************/
367 #define DEFINE_ID_OPS
368 #include "emitfmts.h"
373 LVA_STANDARD_ENCODING = 0,
374 LVA_LARGE_OFFSET = 1,
375 LVA_COMPILER_TEMP = 2,
379 struct emitLclVarAddr
382 void initLclVarAddr(int varNum, unsigned offset);
384 int lvaVarNum(); // Returns the variable to access. Note that it returns a negative number for compiler spill temps.
385 unsigned lvaOffset(); // returns the offset into the variable to access
387 // This struct should be 32 bits in size for the release build.
388 // We have this constraint because this type is used in a union
389 // with several other pointer sized types in the instrDesc struct.
392 unsigned _lvaVarNum : 15; // Usually the lvaVarNum
393 unsigned _lvaExtra : 15; // Usually the lvaOffset
394 unsigned _lvaTag : 2; // tag field to support larger varnums
399 iaut_ALIGNED_POINTER = 0x0,
400 iaut_DATA_OFFSET = 0x1,
401 iaut_INST_COUNT = 0x2,
402 iaut_UNUSED_TAG = 0x3,
410 friend class emitLocation;
411 friend class Compiler;
412 friend class CodeGen;
413 friend class CodeGenInterface;
416 /*************************************************************************
418 * Define the public entry points.
425 // There seem to be some cases where this is used without being initialized via CodeGen::inst_set_SV_var().
429 #ifdef _TARGET_XARCH_
431 #endif // _TARGET_XARCH_
433 #ifdef FEATURE_AVX_SUPPORT
435 #endif // FEATURE_AVX_SUPPORT
441 /************************************************************************/
442 /* Miscellaneous stuff */
443 /************************************************************************/
449 typedef GCInfo::varPtrDsc varPtrDsc;
450 typedef GCInfo::regPtrDsc regPtrDsc;
451 typedef GCInfo::CallDsc callDsc;
453 void* emitGetMem(size_t sz);
455 DECLARE_TYPED_ENUM(opSize, unsigned)
457 OPSZ1 = 0, OPSZ2 = 1, OPSZ4 = 2, OPSZ8 = 3, OPSZ16 = 4, OPSZ32 = 5, OPSZ_COUNT = 6,
458 #ifdef _TARGET_AMD64_
464 END_DECLARE_TYPED_ENUM(opSize, unsigned)
466 #define OPSIZE_INVALID ((opSize)0xffff)
468 static const emitter::opSize emitSizeEncode[];
469 static const emitAttr emitSizeDecode[];
471 static emitter::opSize emitEncodeSize(emitAttr size);
472 static emitAttr emitDecodeSize(emitter::opSize ensz);
474 // Currently, we only allow one IG for the prolog
475 bool emitIGisInProlog(const insGroup* ig)
477 return ig == emitPrologIG;
480 bool emitIGisInEpilog(const insGroup* ig)
482 return (ig != nullptr) && ((ig->igFlags & IGF_EPILOG) != 0);
485 #if FEATURE_EH_FUNCLETS
487 bool emitIGisInFuncletProlog(const insGroup* ig)
489 return (ig != nullptr) && ((ig->igFlags & IGF_FUNCLET_PROLOG) != 0);
492 bool emitIGisInFuncletEpilog(const insGroup* ig)
494 return (ig != nullptr) && ((ig->igFlags & IGF_FUNCLET_EPILOG) != 0);
497 #endif // FEATURE_EH_FUNCLETS
499 // If "ig" corresponds to the start of a basic block that is the
500 // target of a funclet return, generate GC information for it's start
501 // address "cp", as if it were the return address of a call.
502 void emitGenGCInfoIfFuncletRetTarget(insGroup* ig, BYTE* cp);
504 void emitRecomputeIGoffsets();
506 /************************************************************************/
507 /* The following describes a single instruction */
508 /************************************************************************/
510 DECLARE_TYPED_ENUM(insFormat, unsigned)
512 #define IF_DEF(en, op1, op2) IF_##en,
513 #include "emitfmts.h"
517 END_DECLARE_TYPED_ENUM(insFormat, unsigned)
519 #define AM_DISP_BITS ((sizeof(unsigned) * 8) - 2 * (REGNUM_BITS + 1) - 2)
520 #define AM_DISP_BIG_VAL (-(1 << (AM_DISP_BITS - 1)))
521 #define AM_DISP_MIN (-((1 << (AM_DISP_BITS - 1)) - 1))
522 #define AM_DISP_MAX (+((1 << (AM_DISP_BITS - 1)) - 1))
526 regNumber amBaseReg : REGNUM_BITS + 1;
527 regNumber amIndxReg : REGNUM_BITS + 1;
528 emitter::opSize amScale : 2;
529 int amDisp : AM_DISP_BITS;
532 #if defined(DEBUG) || defined(LATE_DISASM) // LATE_DISASM needs the idMemCookie on calls to display the call target name
536 struct instrDescDebugInfo
539 size_t idSize; // size of the instruction descriptor
540 unsigned idVarRefOffs; // IL offset for LclVar reference
541 size_t idMemCookie; // for display of member names in addr modes
542 void* idClsCookie; // for display of member names in addr modes
544 unsigned int idilStart; // instruction descriptor source information for PDB translation
546 bool idFinallyCall; // Branch instruction is a call to finally
547 bool idCatchRet; // Instruction is for a catch 'return'
548 CORINFO_SIG_INFO* idCallSig; // Used to report native call site signatures to the EE
551 #endif // defined(DEBUG) || defined(LATE_DISASM)
554 unsigned insEncodeSetFlags(insFlags sf);
556 DECLARE_TYPED_ENUM(insSize, unsigned)
558 ISZ_16BIT, ISZ_32BIT, ISZ_48BIT // pseudo-instruction for conditional branch with imm24 range,
559 // encoded as IT of condition followed by an unconditional branch
561 END_DECLARE_TYPED_ENUM(insSize, unsigned)
563 unsigned insEncodeShiftOpts(insOpts opt);
564 unsigned insEncodePUW_G0(insOpts opt, int imm);
565 unsigned insEncodePUW_H0(insOpts opt, int imm);
567 #endif // _TARGET_ARM_
569 #if defined(_TARGET_X86_) && defined(LEGACY_BACKEND)
570 #define HAS_TINY_DESC 1
572 #define HAS_TINY_DESC 0
580 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
581 // The assembly instruction
582 instruction _idIns : 9;
583 #else // !defined(_TARGET_XARCH_) || defined(LEGACY_BACKEND)
584 // The assembly instruction
585 instruction _idIns : 8;
586 #endif // !defined(_TARGET_XARCH_) || defined(LEGACY_BACKEND)
587 // The format for the instruction
588 insFormat _idInsFmt : 8;
591 instruction idIns() const
595 void idIns(instruction ins)
598 assert(_idIns == ins);
601 insFormat idInsFmt() const
605 void idInsFmt(insFormat insFmt)
607 #if defined(_TARGET_ARM64_)
608 noway_assert(insFmt != IF_NONE); // Only the x86 emitter uses IF_NONE, it is invalid for ARM64 (and ARM32)
611 assert(_idInsFmt == insFmt);
615 The idReg1 and idReg2 fields hold the first and second register
616 operand(s), whenever these are present. Note that the size of
617 these fields ranges from 3 to 6 bits, and care needs to be taken
618 to make sure all of these fields stay reasonably packed.
621 void idSetRelocFlags(emitAttr attr)
623 _idCnsReloc = (EA_IS_CNS_RELOC(attr) ? 1 : 0);
624 _idDspReloc = (EA_IS_DSP_RELOC(attr) ? 1 : 0);
627 ////////////////////////////////////////////////////////////////////////
628 // Space taken up to here:
635 #ifdef _TARGET_XARCH_
636 unsigned _idCodeSize : 4; // size of instruction in bytes
639 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
640 opSize _idOpSize : 3; // operand size: 0=1 , 1=2 , 2=4 , 3=8, 4=16, 5=32
641 // At this point we have fully consumed first DWORD so that next field
642 // doesn't cross a byte boundary.
643 #elif defined(_TARGET_ARM64_)
644 // Moved the definition of '_idOpSize' later so that we don't cross a 32-bit boundary when laying out bitfields
645 #else // ARM or x86-LEGACY_BACKEND
646 opSize _idOpSize : 2; // operand size: 0=1 , 1=2 , 2=4 , 3=8
647 #endif // ARM or x86-LEGACY_BACKEND
649 // On Amd64, this is where the second DWORD begins
650 // On System V a call could return a struct in 2 registers. The instrDescCGCA struct below has member that
651 // stores the GC-ness of the second register.
652 // It is added to the instrDescCGCA and not here (the base struct) since it is not needed by all the
653 // instructions. This struct (instrDesc) is very carefully kept to be no more than 128 bytes. There is no more
654 // space to add members for keeping GC-ness of the second return registers. It will also bloat the base struct
655 // unnecessarily since the GC-ness of the second register is only needed for call instructions.
656 // The instrDescCGCA struct's member keeping the GC-ness of the first return register is _idcSecondRetRegGCType.
657 GCtype _idGCref : 2; // GCref operand? (value is a "GCtype")
658 #ifdef _TARGET_ARM64_
659 GCtype _idGCref2 : 2;
662 // Note that we use the _idReg1 and _idReg2 fields to hold
663 // the live gcrefReg mask for the call instructions on x86/x64
665 regNumber _idReg1 : REGNUM_BITS; // register num
667 regNumber _idReg2 : REGNUM_BITS;
669 ////////////////////////////////////////////////////////////////////////
670 // Space taken up to here:
675 CLANG_FORMAT_COMMENT_ANCHOR;
679 // For x86 use last two bits to differentiate if we are tiny or small
681 unsigned _idTinyDsc : 1; // is this a "tiny" descriptor?
682 unsigned _idSmallDsc : 1; // is this a "small" descriptor?
684 #else // !HAS_TINY_DESC
687 // On x86/arm platforms we have used 32 bits so far (4 bytes)
688 // On amd64 we have used 38 bits so far (4 bytes + 6 bits)
692 // For amd64 we just can't fit anything useful into a single DWORD
693 // So we eliminate the notion of 'tiny', and have small (2 DWORDS)
694 // or not small (which is bigger, just like x86)
697 unsigned _idSmallDsc : 1; // is this a "small" descriptor?
698 unsigned _idLargeCns : 1; // does a large constant follow?
699 unsigned _idLargeDsp : 1; // does a large displacement follow?
700 unsigned _idLargeCall : 1; // large call descriptor used
702 unsigned _idBound : 1; // jump target / frame offset bound
703 unsigned _idCallRegPtr : 1; // IL indirect calls: addr in reg
704 unsigned _idCallAddr : 1; // IL indirect calls: can make a direct call to iiaAddr
705 unsigned _idNoGC : 1; // Some helpers don't get recorded in GC tables
707 #ifdef _TARGET_ARM64_
708 opSize _idOpSize : 3; // operand size: 0=1 , 1=2 , 2=4 , 3=8, 4=16
709 insOpts _idInsOpt : 6; // options for instructions
710 unsigned _idLclVar : 1; // access a local on stack
714 insSize _idInsSize : 2; // size of instruction: 16, 32 or 48 bits
715 insFlags _idInsFlags : 1; // will this instruction set the flags
716 unsigned _idLclVar : 1; // access a local on stack
717 unsigned _idLclFPBase : 1; // access a local on stack - SP based offset
718 insOpts _idInsOpt : 3; // options for Load/Store instructions
720 // For arm we have used 16 bits
721 #define ID_EXTRA_BITFIELD_BITS (16)
723 #elif defined(_TARGET_ARM64_)
724 // For Arm64, we have used 18 bits from the second DWORD.
725 #define ID_EXTRA_BITFIELD_BITS (18)
726 #elif defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
727 // For xarch !LEGACY_BACKEND, we have used 14 bits from the second DWORD.
728 #define ID_EXTRA_BITFIELD_BITS (14)
729 #elif defined(_TARGET_X86_)
730 // For x86, we have used 6 bits from the second DWORD.
731 #define ID_EXTRA_BITFIELD_BITS (6)
733 #error Unsupported or unset target architecture
736 ////////////////////////////////////////////////////////////////////////
737 // Space taken up to here:
738 // x86: 38 bits // if HAS_TINY_DESC is not defined (which it is)
742 CLANG_FORMAT_COMMENT_ANCHOR;
744 unsigned _idCnsReloc : 1; // LargeCns is an RVA and needs reloc tag
745 unsigned _idDspReloc : 1; // LargeDsp is an RVA and needs reloc tag
747 #define ID_EXTRA_RELOC_BITS (2)
749 ////////////////////////////////////////////////////////////////////////
750 // Space taken up to here:
755 CLANG_FORMAT_COMMENT_ANCHOR;
757 #define ID_EXTRA_BITS (ID_EXTRA_RELOC_BITS + ID_EXTRA_BITFIELD_BITS)
759 /* Use whatever bits are left over for small constants */
761 #define ID_BIT_SMALL_CNS (32 - ID_EXTRA_BITS)
762 #define ID_MIN_SMALL_CNS 0
763 #define ID_MAX_SMALL_CNS (int)((1 << ID_BIT_SMALL_CNS) - 1U)
765 ////////////////////////////////////////////////////////////////////////
766 // Small constant size:
772 unsigned _idSmallCns : ID_BIT_SMALL_CNS;
774 ////////////////////////////////////////////////////////////////////////
775 // Space taken up to here: 64 bits, all architectures, by design.
776 ////////////////////////////////////////////////////////////////////////
777 CLANG_FORMAT_COMMENT_ANCHOR;
779 #endif // !HAS_TINY_DESC
781 #if defined(DEBUG) || defined(LATE_DISASM)
783 instrDescDebugInfo* _idDebugOnlyInfo;
786 instrDescDebugInfo* idDebugOnlyInfo() const
788 return _idDebugOnlyInfo;
790 void idDebugOnlyInfo(instrDescDebugInfo* info)
792 _idDebugOnlyInfo = info;
796 #endif // defined(DEBUG) || defined(LATE_DISASM)
799 // This is the end of the smallest instrDesc we can allocate for all
802 // x86: 32 bits, and it is called the 'tiny' descriptor.
803 // amd64/arm/arm64: 64 bits, and it is called the 'small' descriptor.
804 // DEBUG sizes (includes one pointer):
805 // x86: 2 DWORDs, 64 bits
806 // amd64: 4 DWORDs, 128 bits
807 // arm: 3 DWORDs, 96 bits
808 // arm64: 4 DWORDs, 128 bits
809 // There should no padding or alignment issues on any platform or
810 // configuration (including DEBUG which has 1 extra pointer).
812 CLANG_FORMAT_COMMENT_ANCHOR;
816 unsigned _idLargeCns : 1; // does a large constant follow?
817 unsigned _idLargeDsp : 1; // does a large displacement follow?
818 unsigned _idLargeCall : 1; // large call descriptor used
819 unsigned _idBound : 1; // jump target / frame offset bound
821 unsigned _idCallRegPtr : 1; // IL indirect calls: addr in reg
822 unsigned _idCallAddr : 1; // IL indirect calls: can make a direct call to iiaAddr
823 unsigned _idNoGC : 1; // Some helpers don't get recorded in GC tables
825 #define ID_EXTRA_BITFIELD_BITS (7)
828 // For x86, we are using 7 bits from the second DWORD for bitfields.
831 unsigned _idCnsReloc : 1; // LargeCns is an RVA and needs reloc tag
832 unsigned _idDspReloc : 1; // LargeDsp is an RVA and needs reloc tag
834 #define ID_EXTRA_REG_BITS (0)
836 #define ID_EXTRA_BITS (ID_EXTRA_BITFIELD_BITS + ID_EXTRA_RELOC_BITS + ID_EXTRA_REG_BITS)
838 /* Use whatever bits are left over for small constants */
840 #define ID_BIT_SMALL_CNS (32 - ID_EXTRA_BITS)
841 #define ID_MIN_SMALL_CNS 0
842 #define ID_MAX_SMALL_CNS (int)((1 << ID_BIT_SMALL_CNS) - 1U)
844 // For x86 we have 23 bits remaining for the
845 // small constant in this extra DWORD.
847 unsigned _idSmallCns : ID_BIT_SMALL_CNS;
849 #endif // HAS_TINY_DESC
852 // This is the end of the 'small' instrDesc which is the same on all
853 // platforms (except 64-bit DEBUG which is a little bigger).
855 // x86/amd64/arm/arm64: 64 bits
856 // DEBUG sizes (includes one pointer):
857 // x86: 2 DWORDs, 64 bits
858 // amd64: 4 DWORDs, 128 bits
859 // arm: 3 DWORDs, 96 bits
860 // arm64: 4 DWORDs, 128 bits
861 // There should no padding or alignment issues on any platform or
862 // configuration (including DEBUG which has 1 extra pointer).
866 If you add lots more fields that need to be cleared (such
867 as various flags), you might need to update the body of
868 emitter::emitAllocInstr() to clear them.
871 #if defined(DEBUG) || defined(LATE_DISASM)
872 #define TINY_IDSC_DEBUG_EXTRA (sizeof(void*))
874 #define TINY_IDSC_DEBUG_EXTRA (0)
878 #define TINY_IDSC_SIZE (4 + TINY_IDSC_DEBUG_EXTRA)
879 #define SMALL_IDSC_SIZE (8 + TINY_IDSC_DEBUG_EXTRA)
881 #define TINY_IDSC_SIZE (8 + TINY_IDSC_DEBUG_EXTRA)
882 #define SMALL_IDSC_SIZE TINY_IDSC_SIZE
888 // TODO-Cleanup: We should really add a DEBUG-only tag to this union so we can add asserts
889 // about reading what we think is here, to avoid unexpected corruption issues.
891 emitLclVarAddr iiaLclVar;
892 BasicBlock* iiaBBlabel;
893 insGroup* iiaIGlabel;
895 emitAddrMode iiaAddrMode;
897 CORINFO_FIELD_HANDLE iiaFieldHnd; // iiaFieldHandle is also used to encode
898 // an offset into the JIT data constant area
899 bool iiaIsJitDataOffset() const;
900 int iiaGetJitDataOffset() const;
902 #ifdef _TARGET_ARMARCH_
904 // iiaEncodedInstrCount and its accessor functions are used to specify an instruction
905 // count for jumps, instead of using a label and multiple blocks. This is used in the
906 // prolog as well as for IF_LARGEJMP pseudo-branch instructions.
907 int iiaEncodedInstrCount;
909 bool iiaHasInstrCount() const
911 return (iiaEncodedInstrCount & iaut_MASK) == iaut_INST_COUNT;
913 int iiaGetInstrCount() const
915 assert(iiaHasInstrCount());
916 return (iiaEncodedInstrCount >> iaut_SHIFT);
918 void iiaSetInstrCount(int count)
920 assert(abs(count) < 10);
921 iiaEncodedInstrCount = (count << iaut_SHIFT) | iaut_INST_COUNT;
926 regNumber _idReg3 : REGNUM_BITS;
927 regNumber _idReg4 : REGNUM_BITS;
928 #ifdef _TARGET_ARM64_
929 unsigned _idReg3Scaled : 1; // Reg3 is scaled by idOpSize bits
932 #elif defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
935 regNumber _idReg3 : REGNUM_BITS;
937 #endif // defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
941 /* Trivial wrappers to return properly typed enums */
945 bool idIsTiny() const
947 return (_idTinyDsc != 0);
956 bool idIsTiny() const
965 #endif // HAS_TINY_DESC
967 bool idIsSmallDsc() const
969 return (_idSmallDsc != 0);
971 void idSetIsSmallDsc()
976 #if defined(_TARGET_XARCH_)
978 unsigned idCodeSize() const
982 void idCodeSize(unsigned sz)
985 assert(sz == _idCodeSize);
988 #elif defined(_TARGET_ARM64_)
989 unsigned idCodeSize() const
997 // b<cond> + b<uncond>
1001 if (isVectorRegister(idReg1()))
1003 // adrp + ldr + fmov
1019 #elif defined(_TARGET_ARM_)
1021 bool idInstrIsT1() const
1023 return (_idInsSize == ISZ_16BIT);
1025 unsigned idCodeSize() const
1027 unsigned result = (_idInsSize == ISZ_16BIT) ? 2 : (_idInsSize == ISZ_32BIT) ? 4 : 6;
1030 insSize idInsSize() const
1034 void idInsSize(insSize isz)
1037 assert(isz == _idInsSize);
1039 insFlags idInsFlags() const
1043 void idInsFlags(insFlags sf)
1046 assert(sf == _idInsFlags);
1048 #endif // _TARGET_ARM_
1052 return emitDecodeSize(_idOpSize);
1054 void idOpSize(emitAttr opsz)
1056 _idOpSize = emitEncodeSize(opsz);
1059 GCtype idGCref() const
1061 return (GCtype)_idGCref;
1063 void idGCref(GCtype gctype)
1068 regNumber idReg1() const
1072 void idReg1(regNumber reg)
1075 assert(reg == _idReg1);
1078 #ifdef _TARGET_ARM64_
1079 GCtype idGCrefReg2() const
1081 return (GCtype)_idGCref2;
1083 void idGCrefReg2(GCtype gctype)
1087 #endif // _TARGET_ARM64_
1089 regNumber idReg2() const
1093 void idReg2(regNumber reg)
1096 assert(reg == _idReg2);
1099 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
1100 regNumber idReg3() const
1102 assert(!idIsTiny());
1103 assert(!idIsSmallDsc());
1104 return idAddr()->_idReg3;
1106 void idReg3(regNumber reg)
1108 assert(!idIsTiny());
1109 assert(!idIsSmallDsc());
1110 idAddr()->_idReg3 = reg;
1111 assert(reg == idAddr()->_idReg3);
1113 #endif // defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
1114 #ifdef _TARGET_ARMARCH_
1115 insOpts idInsOpt() const
1117 return (insOpts)_idInsOpt;
1119 void idInsOpt(insOpts opt)
1122 assert(opt == _idInsOpt);
1125 regNumber idReg3() const
1127 assert(!idIsTiny());
1128 assert(!idIsSmallDsc());
1129 return idAddr()->_idReg3;
1131 void idReg3(regNumber reg)
1133 assert(!idIsTiny());
1134 assert(!idIsSmallDsc());
1135 idAddr()->_idReg3 = reg;
1136 assert(reg == idAddr()->_idReg3);
1138 regNumber idReg4() const
1140 assert(!idIsTiny());
1141 assert(!idIsSmallDsc());
1142 return idAddr()->_idReg4;
1144 void idReg4(regNumber reg)
1146 assert(!idIsTiny());
1147 assert(!idIsSmallDsc());
1148 idAddr()->_idReg4 = reg;
1149 assert(reg == idAddr()->_idReg4);
1151 #ifdef _TARGET_ARM64_
1152 bool idReg3Scaled() const
1154 assert(!idIsTiny());
1155 assert(!idIsSmallDsc());
1156 return (idAddr()->_idReg3Scaled == 1);
1158 void idReg3Scaled(bool val)
1160 assert(!idIsTiny());
1161 assert(!idIsSmallDsc());
1162 idAddr()->_idReg3Scaled = val ? 1 : 0;
1164 #endif // _TARGET_ARM64_
1166 #endif // _TARGET_ARMARCH_
1168 inline static bool fitsInSmallCns(ssize_t val)
1170 return ((val >= ID_MIN_SMALL_CNS) && (val <= ID_MAX_SMALL_CNS));
1173 bool idIsLargeCns() const
1175 assert(!idIsTiny());
1176 return _idLargeCns != 0;
1178 void idSetIsLargeCns()
1180 assert(!idIsTiny());
1184 bool idIsLargeDsp() const
1186 assert(!idIsTiny());
1187 return _idLargeDsp != 0;
1189 void idSetIsLargeDsp()
1191 assert(!idIsTiny());
1194 void idSetIsSmallDsp()
1196 assert(!idIsTiny());
1200 bool idIsLargeCall() const
1202 assert(!idIsTiny());
1203 return _idLargeCall != 0;
1205 void idSetIsLargeCall()
1207 assert(!idIsTiny());
1211 bool idIsBound() const
1213 assert(!idIsTiny());
1214 return _idBound != 0;
1218 assert(!idIsTiny());
1222 bool idIsCallRegPtr() const
1224 assert(!idIsTiny());
1225 return _idCallRegPtr != 0;
1227 void idSetIsCallRegPtr()
1229 assert(!idIsTiny());
1233 bool idIsCallAddr() const
1235 assert(!idIsTiny());
1236 return _idCallAddr != 0;
1238 void idSetIsCallAddr()
1240 assert(!idIsTiny());
1244 // Only call instructions that call helper functions may be marked as "IsNoGC", indicating
1245 // that a thread executing such a call cannot be stopped for GC. Thus, in partially-interruptible
1246 // code, it is not necessary to generate GC info for a call so labeled.
1247 bool idIsNoGC() const
1249 assert(!idIsTiny());
1250 return _idNoGC != 0;
1252 void idSetIsNoGC(bool val)
1254 assert(!idIsTiny());
1258 #ifdef _TARGET_ARMARCH_
1259 bool idIsLclVar() const
1261 return !idIsTiny() && _idLclVar != 0;
1263 void idSetIsLclVar()
1265 assert(!idIsTiny());
1268 #endif // _TARGET_ARMARCH_
1270 #if defined(_TARGET_ARM_)
1271 bool idIsLclFPBase() const
1273 return !idIsTiny() && _idLclFPBase != 0;
1275 void idSetIsLclFPBase()
1277 assert(!idIsTiny());
1280 #endif // defined(_TARGET_ARM_)
1282 bool idIsCnsReloc() const
1284 assert(!idIsTiny());
1285 return _idCnsReloc != 0;
1287 void idSetIsCnsReloc()
1289 assert(!idIsTiny());
1293 bool idIsDspReloc() const
1295 assert(!idIsTiny());
1296 return _idDspReloc != 0;
1298 void idSetIsDspReloc(bool val = true)
1300 assert(!idIsTiny());
1305 return idIsDspReloc() || idIsCnsReloc();
1308 unsigned idSmallCns() const
1310 assert(!idIsTiny());
1313 void idSmallCns(size_t value)
1315 assert(!idIsTiny());
1316 assert(fitsInSmallCns(value));
1317 _idSmallCns = value;
1320 inline const idAddrUnion* idAddr() const
1322 assert(!idIsSmallDsc() && !idIsTiny());
1323 return &this->_idAddrUnion;
1326 inline idAddrUnion* idAddr()
1328 assert(!idIsSmallDsc() && !idIsTiny());
1329 return &this->_idAddrUnion;
1331 }; // End of struct instrDesc
1333 void dispIns(instrDesc* id);
1335 void appendToCurIG(instrDesc* id);
1337 /********************************************************************************************/
1339 struct instrDescJmp : instrDesc
1341 instrDescJmp* idjNext; // next jump in the group/method
1342 insGroup* idjIG; // containing group
1345 BYTE* idjAddr; // address of jump ins (for patching)
1348 unsigned idjOffs : 30; // Before jump emission, this is the byte offset within IG of the jump instruction.
1349 // After emission, for forward jumps, this is the target offset -- in bytes from the
1350 // beginning of the function -- of the target instruction of the jump, used to
1351 // determine if this jump needs to be patched.
1352 unsigned idjShort : 1; // is the jump known to be a short one?
1353 unsigned idjKeepLong : 1; // should the jump be kept long? (used for
1354 // hot to cold and cold to hot jumps)
1357 #if !defined(_TARGET_ARM64_) // This shouldn't be needed for ARM32, either, but I don't want to touch the ARM32 JIT.
1358 struct instrDescLbl : instrDescJmp
1360 emitLclVarAddr dstLclVar;
1362 #endif // !_TARGET_ARM64_
1364 struct instrDescCns : instrDesc // large const
1369 struct instrDescDsp : instrDesc // large displacement
1374 struct instrDescCnsDsp : instrDesc // large cons + disp
1380 struct instrDescAmd : instrDesc // large addrmode disp
1385 struct instrDescCnsAmd : instrDesc // large cons + addrmode disp
1391 struct instrDescCGCA : instrDesc // call with ...
1393 VARSET_TP idcGCvars; // ... updated GC vars or
1394 ssize_t idcDisp; // ... big addrmode disp
1395 regMaskTP idcGcrefRegs; // ... gcref registers
1396 regMaskTP idcByrefRegs; // ... byref registers
1397 unsigned idcArgCnt; // ... lots of args or (<0 ==> caller pops args)
1399 #if MULTIREG_HAS_SECOND_GC_RET
1400 // This method handle the GC-ness of the second register in a 2 register returned struct on System V.
1401 GCtype idSecondGCref() const
1403 return (GCtype)_idcSecondRetRegGCType;
1405 void idSecondGCref(GCtype gctype)
1407 _idcSecondRetRegGCType = gctype;
1411 // This member stores the GC-ness of the second register in a 2 register returned struct on System V.
1412 // It is added to the call struct since it is not needed by the base instrDesc struct, which keeps GC-ness
1413 // of the first register for the instCall nodes.
1414 // The base instrDesc is very carefully kept to be no more than 128 bytes. There is no more space to add members
1415 // for keeping GC-ness of the second return registers. It will also bloat the base struct unnecessarily
1416 // since the GC-ness of the second register is only needed for call instructions.
1417 // The base struct's member keeping the GC-ness of the first return register is _idGCref.
1418 GCtype _idcSecondRetRegGCType : 2; // ... GC type for the second return register.
1419 #endif // MULTIREG_HAS_SECOND_GC_RET
1422 struct instrDescArmFP : instrDesc
1429 insUpdateModes emitInsUpdateMode(instruction ins);
1430 insFormat emitInsModeFormat(instruction ins, insFormat base);
1432 static const BYTE emitInsModeFmtTab[];
1434 static const unsigned emitInsModeFmtCnt;
1437 size_t emitGetInstrDescSize(const instrDesc* id);
1438 size_t emitGetInstrDescSizeSC(const instrDesc* id);
1440 ssize_t emitGetInsCns(instrDesc* id);
1441 ssize_t emitGetInsDsp(instrDesc* id);
1442 ssize_t emitGetInsAmd(instrDesc* id);
1443 ssize_t emitGetInsCnsDsp(instrDesc* id, ssize_t* dspPtr);
1444 ssize_t emitGetInsSC(instrDesc* id);
1445 ssize_t emitGetInsCIdisp(instrDesc* id);
1446 unsigned emitGetInsCIargs(instrDesc* id);
1448 // Return the argument count for a direct call "id".
1449 int emitGetInsCDinfo(instrDesc* id);
1451 unsigned emitInsCount;
1453 /************************************************************************/
1454 /* A few routines used for debug display purposes */
1455 /************************************************************************/
1457 #if defined(DEBUG) || EMITTER_STATS
1459 static const char* emitIfName(unsigned f);
1461 #endif // defined(DEBUG) || EMITTER_STATS
1465 unsigned emitVarRefOffs;
1467 const char* emitRegName(regNumber reg, emitAttr size = EA_PTRSIZE, bool varName = true);
1468 const char* emitFloatRegName(regNumber reg, emitAttr size = EA_PTRSIZE, bool varName = true);
1470 const char* emitFldName(CORINFO_FIELD_HANDLE fieldVal);
1471 const char* emitFncName(CORINFO_METHOD_HANDLE callVal);
1473 void emitDispIGflags(unsigned flags);
1474 void emitDispIG(insGroup* ig, insGroup* igPrev = nullptr, bool verbose = false);
1475 void emitDispIGlist(bool verbose = false);
1476 void emitDispGCinfo();
1477 void emitDispClsVar(CORINFO_FIELD_HANDLE fldHnd, ssize_t offs, bool reloc = false);
1478 void emitDispFrameRef(int varx, int disp, int offs, bool asmfm);
1479 void emitDispInsOffs(unsigned offs, bool doffs);
1480 void emitDispInsHex(BYTE* code, size_t sz);
1483 #define emitVarRefOffs 0
1486 /************************************************************************/
1487 /* Method prolog and epilog */
1488 /************************************************************************/
1490 unsigned emitPrologEndPos;
1492 unsigned emitEpilogCnt;
1493 UNATIVE_OFFSET emitEpilogSize;
1495 #ifdef _TARGET_XARCH_
1497 void emitStartExitSeq(); // Mark the start of the "return" sequence
1498 emitLocation emitExitSeqBegLoc;
1499 UNATIVE_OFFSET emitExitSeqSize; // minimum size of any return sequence - the 'ret' after the epilog
1501 #endif // _TARGET_XARCH_
1503 insGroup* emitPlaceholderList; // per method placeholder list - head
1504 insGroup* emitPlaceholderLast; // per method placeholder list - tail
1506 #ifdef JIT32_GCENCODER
1508 // The x86 GC encoder needs to iterate over a list of epilogs to generate a table of
1509 // epilog offsets. Epilogs always start at the beginning of an IG, so save the first
1510 // IG of the epilog, and use it to find the epilog offset at the end of code generation.
1516 EpilogList() : elNext(nullptr), elLoc()
1521 EpilogList* emitEpilogList; // per method epilog list - head
1522 EpilogList* emitEpilogLast; // per method epilog list - tail
1525 void emitStartEpilog();
1527 bool emitHasEpilogEnd();
1529 size_t emitGenEpilogLst(size_t (*fp)(void*, unsigned), void* cp);
1531 #endif // JIT32_GCENCODER
1533 void emitBegPrologEpilog(insGroup* igPh);
1534 void emitEndPrologEpilog();
1536 void emitBegFnEpilog(insGroup* igPh);
1537 void emitEndFnEpilog();
1539 #if FEATURE_EH_FUNCLETS
1541 void emitBegFuncletProlog(insGroup* igPh);
1542 void emitEndFuncletProlog();
1544 void emitBegFuncletEpilog(insGroup* igPh);
1545 void emitEndFuncletEpilog();
1547 #endif // FEATURE_EH_FUNCLETS
1549 /************************************************************************/
1550 /* Members and methods used in PDB translation */
1551 /************************************************************************/
1553 #ifdef TRANSLATE_PDB
1555 inline void SetIDSource(instrDesc* pID);
1556 void MapCode(int ilOffset, BYTE* imgDest);
1557 void MapFunc(int imgOff,
1564 OptJit::LclVarDsc* lvaTable,
1568 int emitInstrDescILBase; // code offset of IL that produced this instruction desctriptor
1569 int emitInstrDescILBase; // code offset of IL that produced this instruction desctriptor
1570 static AddrMap* emitPDBOffsetTable; // translation table for mapping IL addresses to native addresses
1571 static LocalMap* emitPDBLocalTable; // local symbol translation table
1572 static bool emitIsPDBEnabled; // flag to disable PDB translation code when a PDB is not found
1573 static BYTE* emitILBaseOfCode; // start of IL .text section
1574 static BYTE* emitILMethodBase; // beginning of IL method (start of header)
1575 static BYTE* emitILMethodStart; // beginning of IL method code (right after the header)
1576 static BYTE* emitImgBaseOfCode; // start of the image .text section
1580 /************************************************************************/
1581 /* Methods to record a code position and later convert to offset */
1582 /************************************************************************/
1584 unsigned emitFindInsNum(insGroup* ig, instrDesc* id);
1585 UNATIVE_OFFSET emitFindOffset(insGroup* ig, unsigned insNum);
1587 /************************************************************************/
1588 /* Members and methods used to issue (encode) instructions. */
1589 /************************************************************************/
1592 // If we have started issuing instructions from the list of instrDesc, this is set
1596 BYTE* emitCodeBlock; // Hot code block
1597 BYTE* emitColdCodeBlock; // Cold code block
1598 BYTE* emitConsBlock; // Read-only (constant) data block
1600 UNATIVE_OFFSET emitTotalHotCodeSize;
1601 UNATIVE_OFFSET emitTotalColdCodeSize;
1603 UNATIVE_OFFSET emitCurCodeOffs(BYTE* dst)
1606 if ((dst >= emitCodeBlock) && (dst <= (emitCodeBlock + emitTotalHotCodeSize)))
1608 distance = (dst - emitCodeBlock);
1612 assert(emitFirstColdIG);
1613 assert(emitColdCodeBlock);
1614 assert((dst >= emitColdCodeBlock) && (dst <= (emitColdCodeBlock + emitTotalColdCodeSize)));
1616 distance = (dst - emitColdCodeBlock + emitTotalHotCodeSize);
1618 noway_assert((UNATIVE_OFFSET)distance == distance);
1619 return (UNATIVE_OFFSET)distance;
1622 BYTE* emitOffsetToPtr(UNATIVE_OFFSET offset)
1624 if (offset < emitTotalHotCodeSize)
1626 return emitCodeBlock + offset;
1630 assert(offset < (emitTotalHotCodeSize + emitTotalColdCodeSize));
1632 return emitColdCodeBlock + (offset - emitTotalHotCodeSize);
1636 BYTE* emitDataOffsetToPtr(UNATIVE_OFFSET offset)
1638 assert(offset < emitDataSize());
1639 return emitConsBlock + offset;
1642 bool emitJumpCrossHotColdBoundary(size_t srcOffset, size_t dstOffset)
1644 if (emitTotalColdCodeSize == 0)
1649 assert(srcOffset < (emitTotalHotCodeSize + emitTotalColdCodeSize));
1650 assert(dstOffset < (emitTotalHotCodeSize + emitTotalColdCodeSize));
1652 return ((srcOffset < emitTotalHotCodeSize) != (dstOffset < emitTotalHotCodeSize));
1655 unsigned char emitOutputByte(BYTE* dst, ssize_t val);
1656 unsigned char emitOutputWord(BYTE* dst, ssize_t val);
1657 unsigned char emitOutputLong(BYTE* dst, ssize_t val);
1658 unsigned char emitOutputSizeT(BYTE* dst, ssize_t val);
1660 #if !defined(LEGACY_BACKEND) && defined(_TARGET_X86_)
1661 unsigned char emitOutputByte(BYTE* dst, size_t val);
1662 unsigned char emitOutputWord(BYTE* dst, size_t val);
1663 unsigned char emitOutputLong(BYTE* dst, size_t val);
1664 unsigned char emitOutputSizeT(BYTE* dst, size_t val);
1666 unsigned char emitOutputByte(BYTE* dst, unsigned __int64 val);
1667 unsigned char emitOutputWord(BYTE* dst, unsigned __int64 val);
1668 unsigned char emitOutputLong(BYTE* dst, unsigned __int64 val);
1669 unsigned char emitOutputSizeT(BYTE* dst, unsigned __int64 val);
1670 #endif // !defined(LEGACY_BACKEND) && defined(_TARGET_X86_)
1672 size_t emitIssue1Instr(insGroup* ig, instrDesc* id, BYTE** dp);
1673 size_t emitOutputInstr(insGroup* ig, instrDesc* id, BYTE** dp);
1675 bool emitHasFramePtr;
1677 #ifdef PSEUDORANDOM_NOP_INSERTION
1678 bool emitInInstrumentation;
1679 #endif // PSEUDORANDOM_NOP_INSERTION
1681 unsigned emitMaxTmpSize;
1683 #ifdef LEGACY_BACKEND
1684 unsigned emitLclSize;
1685 unsigned emitGrowableMaxByteOffs;
1686 void emitTmpSizeChanged(unsigned tmpSize);
1688 unsigned emitMaxByteOffsIdNum;
1690 #endif // LEGACY_BACKEND
1693 bool emitChkAlign; // perform some alignment checks
1696 insGroup* emitCurIG;
1698 void emitSetShortJump(instrDescJmp* id);
1699 void emitSetMediumJump(instrDescJmp* id);
1700 UNATIVE_OFFSET emitSizeOfJump(instrDescJmp* jmp);
1701 UNATIVE_OFFSET emitInstCodeSz(instrDesc* id);
1703 #ifndef LEGACY_BACKEND
1704 CORINFO_FIELD_HANDLE emitLiteralConst(ssize_t cnsValIn, emitAttr attr = EA_8BYTE);
1705 CORINFO_FIELD_HANDLE emitFltOrDblConst(GenTreeDblCon* tree, emitAttr attr = EA_UNKNOWN);
1706 regNumber emitInsBinary(instruction ins, emitAttr attr, GenTree* dst, GenTree* src);
1707 regNumber emitInsTernary(instruction ins, emitAttr attr, GenTree* dst, GenTree* src1, GenTree* src2);
1708 void emitInsMov(instruction ins, emitAttr attr, GenTree* node);
1709 insFormat emitMapFmtForIns(insFormat fmt, instruction ins);
1710 insFormat emitMapFmtAtoM(insFormat fmt);
1711 void emitHandleMemOp(GenTreeIndir* indir, instrDesc* id, insFormat fmt, instruction ins);
1712 void spillIntArgRegsToShadowSlots();
1713 #endif // !LEGACY_BACKEND
1715 /************************************************************************/
1716 /* The logic that creates and keeps track of instruction groups */
1717 /************************************************************************/
1720 // The only place where this limited instruction group size is a problem is
1721 // in the prolog, where we only support a single instruction group. We should really fix that.
1722 // ARM can require a bigger prolog instruction group. One scenario is where a
1723 // function uses all the incoming integer and single-precision floating-point arguments,
1724 // and must store them all to the frame on entry. If the frame is very large, we generate
1725 // ugly code like "movw r10, 0x488; add r10, sp; vstr s0, [r10]" for each store, which
1726 // eats up our insGroup buffer.
1727 #define SC_IG_BUFFER_SIZE (100 * sizeof(instrDesc) + 14 * TINY_IDSC_SIZE)
1728 #else // !_TARGET_ARM_
1729 #define SC_IG_BUFFER_SIZE (50 * sizeof(instrDesc) + 14 * TINY_IDSC_SIZE)
1730 #endif // !_TARGET_ARM_
1732 size_t emitIGbuffSize;
1734 insGroup* emitIGlist; // first instruction group
1735 insGroup* emitIGlast; // last instruction group
1736 insGroup* emitIGthis; // issued instruction group
1738 insGroup* emitPrologIG; // prolog instruction group
1740 instrDescJmp* emitJumpList; // list of local jumps in method
1741 instrDescJmp* emitJumpLast; // last of local jumps in method
1742 void emitJumpDistBind(); // Bind all the local jumps in method
1744 void emitCheckFuncletBranch(instrDesc* jmp, insGroup* jmpIG); // Check for illegal branches between funclets
1746 bool emitFwdJumps; // forward jumps present?
1747 bool emitNoGCIG; // Are we generating IGF_NOGCINTERRUPT insGroups (for prologs, epilogs, etc.)
1748 bool emitForceNewIG; // If we generate an instruction, and not another instruction group, force create a new emitAdd
1749 // instruction group.
1751 BYTE* emitCurIGfreeNext; // next available byte in buffer
1752 BYTE* emitCurIGfreeEndp; // one byte past the last available byte in buffer
1753 BYTE* emitCurIGfreeBase; // first byte address
1755 unsigned emitCurIGinsCnt; // # of collected instr's in buffer
1756 unsigned emitCurIGsize; // estimated code size of current group in bytes
1757 UNATIVE_OFFSET emitCurCodeOffset; // current code offset within group
1758 UNATIVE_OFFSET emitTotalCodeSize; // bytes of code in entire method
1760 insGroup* emitFirstColdIG; // first cold instruction group
1762 void emitSetFirstColdIGCookie(void* bbEmitCookie)
1764 emitFirstColdIG = (insGroup*)bbEmitCookie;
1767 int emitOffsAdj; // current code offset adjustment
1769 instrDescJmp* emitCurIGjmpList; // list of jumps in current IG
1771 // emitPrev* and emitInit* are only used during code generation, not during
1772 // emission (issuing), to determine what GC values to store into an IG.
1773 // Note that only the Vars ones are actually used, apparently due to bugs
1774 // in that tracking. See emitSavIG(): the important use of ByrefRegs is commented
1775 // out, and GCrefRegs is always saved.
1777 VARSET_TP emitPrevGCrefVars;
1778 regMaskTP emitPrevGCrefRegs;
1779 regMaskTP emitPrevByrefRegs;
1781 VARSET_TP emitInitGCrefVars;
1782 regMaskTP emitInitGCrefRegs;
1783 regMaskTP emitInitByrefRegs;
1785 // If this is set, we ignore comparing emitPrev* and emitInit* to determine
1786 // whether to save GC state (to save space in the IG), and always save it.
1788 bool emitForceStoreGCState;
1790 // emitThis* variables are used during emission, to track GC updates
1791 // on a per-instruction basis. During code generation, per-instruction
1792 // tracking is done with variables gcVarPtrSetCur, gcRegGCrefSetCur,
1793 // and gcRegByrefSetCur. However, these are also used for a slightly
1794 // different purpose during code generation: to try to minimize the
1795 // amount of GC data stored to an IG, by only storing deltas from what
1796 // we expect to see at an IG boundary. Also, only emitThisGCrefVars is
1797 // really the only one used; the others seem to be calculated, but not
1798 // used due to bugs.
1800 VARSET_TP emitThisGCrefVars;
1801 regMaskTP emitThisGCrefRegs; // Current set of registers holding GC references
1802 regMaskTP emitThisByrefRegs; // Current set of registers holding BYREF references
1804 bool emitThisGCrefVset; // Is "emitThisGCrefVars" up to date?
1806 regNumber emitSyncThisObjReg; // where is "this" enregistered for synchronized methods?
1808 #if MULTIREG_HAS_SECOND_GC_RET
1809 void emitSetSecondRetRegGCType(instrDescCGCA* id, emitAttr secondRetSize);
1810 #endif // MULTIREG_HAS_SECOND_GC_RET
1812 static void emitEncodeCallGCregs(regMaskTP regs, instrDesc* id);
1813 static unsigned emitDecodeCallGCregs(instrDesc* id);
1815 unsigned emitNxtIGnum;
1817 // random nop insertion to break up nop sleds
1818 unsigned emitNextNop;
1819 bool emitRandomNops;
1820 void emitEnableRandomNops()
1822 emitRandomNops = true;
1824 void emitDisableRandomNops()
1826 emitRandomNops = false;
1829 insGroup* emitAllocAndLinkIG();
1830 insGroup* emitAllocIG();
1831 void emitInitIG(insGroup* ig);
1832 void emitInsertIGAfter(insGroup* insertAfterIG, insGroup* ig);
1836 #if !defined(JIT32_GCENCODER)
1837 void emitDisableGC();
1838 void emitEnableGC();
1839 #endif // !defined(JIT32_GCENCODER)
1841 void emitGenIG(insGroup* ig);
1842 insGroup* emitSavIG(bool emitAdd = false);
1843 void emitNxtIG(bool emitAdd = false);
1845 bool emitCurIGnonEmpty()
1847 return (emitCurIG && emitCurIGfreeNext > emitCurIGfreeBase);
1850 instrDesc* emitLastIns;
1853 void emitCheckIGoffsets();
1856 // Terminates any in-progress instruction group, making the current IG a new empty one.
1857 // Mark this instruction group as having a label; return the the new instruction group.
1858 // Sets the emitter's record of the currently live GC variables
1859 // and registers. The "isFinallyTarget" parameter indicates that the current location is
1860 // the start of a basic block that is returned to after a finally clause in non-exceptional execution.
1861 void* emitAddLabel(VARSET_VALARG_TP GCvars, regMaskTP gcrefRegs, regMaskTP byrefRegs, BOOL isFinallyTarget = FALSE);
1863 #ifdef _TARGET_ARMARCH_
1865 void emitGetInstrDescs(insGroup* ig, instrDesc** id, int* insCnt);
1867 bool emitGetLocationInfo(emitLocation* emitLoc, insGroup** pig, instrDesc** pid, int* pinsRemaining = NULL);
1869 bool emitNextID(insGroup*& ig, instrDesc*& id, int& insRemaining);
1871 typedef void (*emitProcessInstrFunc_t)(instrDesc* id, void* context);
1873 void emitWalkIDs(emitLocation* locFrom, emitProcessInstrFunc_t processFunc, void* context);
1875 static void emitGenerateUnwindNop(instrDesc* id, void* context);
1877 #endif // _TARGET_ARMARCH_
1879 #if defined(_TARGET_ARM_)
1880 emitter::insFormat emitInsFormat(instruction ins);
1881 size_t emitInsCode(instruction ins, insFormat fmt);
1885 void emitMarkStackLvl(unsigned stackLevel);
1888 int emitNextRandomNop();
1890 void* emitAllocInstr(size_t sz, emitAttr attr);
1892 instrDesc* emitAllocInstr(emitAttr attr)
1894 return (instrDesc*)emitAllocInstr(sizeof(instrDesc), attr);
1897 instrDescJmp* emitAllocInstrJmp()
1899 return (instrDescJmp*)emitAllocInstr(sizeof(instrDescJmp), EA_1BYTE);
1902 #if !defined(_TARGET_ARM64_)
1903 instrDescLbl* emitAllocInstrLbl()
1905 return (instrDescLbl*)emitAllocInstr(sizeof(instrDescLbl), EA_4BYTE);
1907 #endif // !_TARGET_ARM64_
1909 instrDescCns* emitAllocInstrCns(emitAttr attr)
1911 return (instrDescCns*)emitAllocInstr(sizeof(instrDescCns), attr);
1913 instrDescCns* emitAllocInstrCns(emitAttr attr, int cns)
1915 instrDescCns* result = (instrDescCns*)emitAllocInstr(sizeof(instrDescCns), attr);
1916 result->idSetIsLargeCns();
1917 result->idcCnsVal = cns;
1921 instrDescDsp* emitAllocInstrDsp(emitAttr attr)
1923 return (instrDescDsp*)emitAllocInstr(sizeof(instrDescDsp), attr);
1926 instrDescCnsDsp* emitAllocInstrCnsDsp(emitAttr attr)
1928 return (instrDescCnsDsp*)emitAllocInstr(sizeof(instrDescCnsDsp), attr);
1931 instrDescAmd* emitAllocInstrAmd(emitAttr attr)
1933 return (instrDescAmd*)emitAllocInstr(sizeof(instrDescAmd), attr);
1936 instrDescCnsAmd* emitAllocInstrCnsAmd(emitAttr attr)
1938 return (instrDescCnsAmd*)emitAllocInstr(sizeof(instrDescCnsAmd), attr);
1941 instrDescCGCA* emitAllocInstrCGCA(emitAttr attr)
1943 return (instrDescCGCA*)emitAllocInstr(sizeof(instrDescCGCA), attr);
1946 instrDesc* emitNewInstrTiny(emitAttr attr);
1947 instrDesc* emitNewInstrSmall(emitAttr attr);
1948 instrDesc* emitNewInstr(emitAttr attr = EA_4BYTE);
1949 instrDesc* emitNewInstrSC(emitAttr attr, ssize_t cns);
1950 instrDesc* emitNewInstrCns(emitAttr attr, ssize_t cns);
1951 instrDesc* emitNewInstrDsp(emitAttr attr, ssize_t dsp);
1952 instrDesc* emitNewInstrCnsDsp(emitAttr attr, ssize_t cns, int dsp);
1953 instrDescJmp* emitNewInstrJmp();
1955 #if !defined(_TARGET_ARM64_)
1956 instrDescLbl* emitNewInstrLbl();
1957 #endif // !_TARGET_ARM64_
1959 static const BYTE emitFmtToOps[];
1962 static const unsigned emitFmtCount;
1965 bool emitIsTinyInsDsc(instrDesc* id);
1966 bool emitIsScnsInsDsc(instrDesc* id);
1968 size_t emitSizeOfInsDsc(instrDesc* id);
1970 /************************************************************************/
1971 /* The following keeps track of stack-based GC values */
1972 /************************************************************************/
1974 unsigned emitTrkVarCnt;
1975 int* emitGCrFrameOffsTab; // Offsets of tracked stack ptr vars (varTrkIndex -> stkOffs)
1977 unsigned emitGCrFrameOffsCnt; // Number of tracked stack ptr vars
1978 int emitGCrFrameOffsMin; // Min offset of a tracked stack ptr var
1979 int emitGCrFrameOffsMax; // Max offset of a tracked stack ptr var
1980 bool emitContTrkPtrLcls; // All lcl between emitGCrFrameOffsMin/Max are only tracked stack ptr vars
1981 varPtrDsc** emitGCrFrameLiveTab; // Cache of currently live varPtrs (stkOffs -> varPtrDsc)
1983 int emitArgFrameOffsMin;
1984 int emitArgFrameOffsMax;
1986 int emitLclFrameOffsMin;
1987 int emitLclFrameOffsMax;
1989 int emitSyncThisObjOffs; // what is the offset of "this" for synchronized methods?
1992 void emitSetFrameRangeGCRs(int offsLo, int offsHi);
1993 void emitSetFrameRangeLcls(int offsLo, int offsHi);
1994 void emitSetFrameRangeArgs(int offsLo, int offsHi);
1996 static instruction emitJumpKindToIns(emitJumpKind jumpKind);
1997 static emitJumpKind emitInsToJumpKind(instruction ins);
1998 static emitJumpKind emitReverseJumpKind(emitJumpKind jumpKind);
2001 static unsigned emitJumpKindCondCode(emitJumpKind jumpKind);
2005 void emitInsSanityCheck(instrDesc* id);
2008 #ifdef _TARGET_ARMARCH_
2009 // Returns true if instruction "id->idIns()" writes to a register that might be used to contain a GC
2010 // pointer. This exempts the SP and PC registers, and floating point registers. Memory access
2011 // instructions that pre- or post-increment their memory address registers are *not* considered to write
2012 // to GC registers, even if that memory address is a by-ref: such an instruction cannot change the GC
2013 // status of that register, since it must be a byref before and remains one after.
2015 // This may return false positives.
2016 bool emitInsMayWriteToGCReg(instrDesc* id);
2018 // Returns "true" if instruction "id->idIns()" writes to a LclVar stack location.
2019 bool emitInsWritesToLclVarStackLoc(instrDesc* id);
2021 // Returns true if the instruction may write to more than one register.
2022 bool emitInsMayWriteMultipleRegs(instrDesc* id);
2023 #endif // _TARGET_ARMARCH_
2025 /************************************************************************/
2026 /* The following is used to distinguish helper vs non-helper calls */
2027 /************************************************************************/
2029 static bool emitNoGChelper(unsigned IHX);
2031 /************************************************************************/
2032 /* The following logic keeps track of live GC ref values */
2033 /************************************************************************/
2035 bool emitFullArgInfo; // full arg info (including non-ptr arg)?
2036 bool emitFullGCinfo; // full GC pointer maps?
2037 bool emitFullyInt; // fully interruptible code?
2039 #if EMIT_TRACK_STACK_DEPTH
2040 unsigned emitCntStackDepth; // 0 in prolog/epilog, One DWORD elsewhere
2041 unsigned emitMaxStackDepth; // actual computed max. stack depth
2044 /* Stack modelling wrt GC */
2046 bool emitSimpleStkUsed; // using the "simple" stack table?
2049 struct // if emitSimpleStkUsed==true
2051 #define BITS_IN_BYTE (8)
2052 #define MAX_SIMPLE_STK_DEPTH (BITS_IN_BYTE * sizeof(unsigned))
2054 unsigned emitSimpleStkMask; // bit per pushed dword (if it fits. Lowest bit <==> last pushed arg)
2055 unsigned emitSimpleByrefStkMask; // byref qualifier for emitSimpleStkMask
2058 struct // if emitSimpleStkUsed==false
2060 BYTE emitArgTrackLcl[16]; // small local table to avoid malloc
2061 BYTE* emitArgTrackTab; // base of the argument tracking stack
2062 BYTE* emitArgTrackTop; // top of the argument tracking stack
2063 USHORT emitGcArgTrackCnt; // count of pending arg records (stk-depth for frameless methods, gc ptrs on stk
2064 // for framed methods)
2068 unsigned emitCurStackLvl; // amount of bytes pushed on stack
2070 #if EMIT_TRACK_STACK_DEPTH
2071 /* Functions for stack tracking */
2073 void emitStackPush(BYTE* addr, GCtype gcType);
2075 void emitStackPushN(BYTE* addr, unsigned count);
2077 void emitStackPop(BYTE* addr, bool isCall, unsigned char callInstrSize, unsigned count = 1);
2079 void emitStackKillArgs(BYTE* addr, unsigned count, unsigned char callInstrSize);
2081 void emitRecordGCcall(BYTE* codePos, unsigned char callInstrSize);
2083 // Helpers for the above
2085 void emitStackPushLargeStk(BYTE* addr, GCtype gcType, unsigned count = 1);
2086 void emitStackPopLargeStk(BYTE* addr, bool isCall, unsigned char callInstrSize, unsigned count = 1);
2087 #endif // EMIT_TRACK_STACK_DEPTH
2089 /* Liveness of stack variables, and registers */
2091 void emitUpdateLiveGCvars(int offs, BYTE* addr, bool birth);
2092 void emitUpdateLiveGCvars(VARSET_VALARG_TP vars, BYTE* addr);
2093 void emitUpdateLiveGCregs(GCtype gcType, regMaskTP regs, BYTE* addr);
2096 const char* emitGetFrameReg();
2097 void emitDispRegSet(regMaskTP regs);
2098 void emitDispVarSet();
2101 void emitGCregLiveUpd(GCtype gcType, regNumber reg, BYTE* addr);
2102 void emitGCregLiveSet(GCtype gcType, regMaskTP mask, BYTE* addr, bool isThis);
2103 void emitGCregDeadUpdMask(regMaskTP, BYTE* addr);
2104 void emitGCregDeadUpd(regNumber reg, BYTE* addr);
2105 void emitGCregDeadSet(GCtype gcType, regMaskTP mask, BYTE* addr);
2107 void emitGCvarLiveUpd(int offs, int varNum, GCtype gcType, BYTE* addr);
2108 void emitGCvarLiveSet(int offs, GCtype gcType, BYTE* addr, ssize_t disp = -1);
2109 void emitGCvarDeadUpd(int offs, BYTE* addr);
2110 void emitGCvarDeadSet(int offs, BYTE* addr, ssize_t disp = -1);
2112 GCtype emitRegGCtype(regNumber reg);
2114 // We have a mixture of code emission methods, some of which return the size of the emitted instruction,
2115 // requiring the caller to add this to the current code pointer (dst += <call to emit code>), others of which
2116 // return the updated code pointer (dst = <call to emit code>). Sometimes we'd like to get the size of
2117 // the generated instruction for the latter style. This method accomplishes that --
2118 // "emitCodeWithInstructionSize(dst, <call to emitCode>, &instrSize)" will do the call, and set
2119 // "*instrSize" to the after-before code pointer difference. Returns the result of the call. (And
2120 // asserts that the instruction size fits in an unsigned char.)
2121 static BYTE* emitCodeWithInstructionSize(BYTE* codePtrBefore, BYTE* newCodePointer, unsigned char* instrSize);
2123 /************************************************************************/
2124 /* The following logic keeps track of initialized data sections */
2125 /************************************************************************/
2127 /* One of these is allocated for every blob of initialized data */
2138 dataSection* dsNext;
2139 UNATIVE_OFFSET dsSize;
2141 // variable-sized array used to store the constant data
2142 // or BasicBlock* array in the block cases.
2146 /* These describe the entire initialized/uninitialized data sections */
2150 dataSection* dsdList;
2151 dataSection* dsdLast;
2152 UNATIVE_OFFSET dsdOffs;
2155 dataSecDsc emitConsDsc;
2157 dataSection* emitDataSecCur;
2159 void emitOutputDataSec(dataSecDsc* sec, BYTE* dst);
2161 /************************************************************************/
2162 /* Handles to the current class and method. */
2163 /************************************************************************/
2165 COMP_HANDLE emitCmpHandle;
2167 /************************************************************************/
2168 /* Helpers for interface to EE */
2169 /************************************************************************/
2171 void emitRecordRelocation(void* location, /* IN */
2172 void* target, /* IN */
2173 WORD fRelocType, /* IN */
2174 WORD slotNum = 0, /* IN */
2175 INT32 addlDelta = 0); /* IN */
2177 void emitRecordCallSite(ULONG instrOffset, /* IN */
2178 CORINFO_SIG_INFO* callSig, /* IN */
2179 CORINFO_METHOD_HANDLE methodHandle); /* IN */
2182 // This is a scratch buffer used to minimize the number of sig info structs
2183 // we have to allocate for recordCallSite.
2184 CORINFO_SIG_INFO* emitScratchSigInfo;
2187 /************************************************************************/
2188 /* Logic to collect and display statistics */
2189 /************************************************************************/
2193 friend void emitterStats(FILE* fout);
2194 friend void emitterStaticStats(FILE* fout);
2196 static size_t emitSizeMethod;
2198 static unsigned emitTotalInsCnt;
2200 static unsigned emitTotalIGcnt; // total number of insGroup allocated
2201 static unsigned emitTotalPhIGcnt; // total number of insPlaceholderGroupData allocated
2202 static unsigned emitTotalIGicnt;
2203 static size_t emitTotalIGsize;
2204 static unsigned emitTotalIGmcnt; // total method count
2205 static unsigned emitTotalIGjmps;
2206 static unsigned emitTotalIGptrs;
2208 static size_t emitTotMemAlloc;
2210 static unsigned emitSmallDspCnt;
2211 static unsigned emitLargeDspCnt;
2213 static unsigned emitSmallCnsCnt;
2214 #define SMALL_CNS_TSZ 256
2215 static unsigned emitSmallCns[SMALL_CNS_TSZ];
2216 static unsigned emitLargeCnsCnt;
2218 static unsigned emitIFcounts[IF_COUNT];
2220 #endif // EMITTER_STATS
2222 /*************************************************************************
2224 * Define any target-dependent emitter members.
2227 #include "emitdef.h"
2229 // It would be better if this were a constructor, but that would entail revamping the allocation
2230 // infrastructure of the entire JIT...
2233 VarSetOps::AssignNoCopy(emitComp, emitPrevGCrefVars, VarSetOps::MakeEmpty(emitComp));
2234 VarSetOps::AssignNoCopy(emitComp, emitInitGCrefVars, VarSetOps::MakeEmpty(emitComp));
2235 VarSetOps::AssignNoCopy(emitComp, emitThisGCrefVars, VarSetOps::MakeEmpty(emitComp));
2239 /*****************************************************************************
2241 * Define any target-dependent inlines.
2244 #include "emitinl.h"
2246 inline void emitter::instrDesc::checkSizes()
2250 C_ASSERT(TINY_IDSC_SIZE == (offsetof(instrDesc, _idDebugOnlyInfo) + sizeof(instrDescDebugInfo*)));
2252 C_ASSERT(SMALL_IDSC_SIZE == (offsetof(instrDesc, _idDebugOnlyInfo) + sizeof(instrDescDebugInfo*)));
2255 C_ASSERT(SMALL_IDSC_SIZE == offsetof(instrDesc, _idAddrUnion));
2258 /*****************************************************************************
2260 * Returns true if the given instruction descriptor is a "tiny" or a "small
2261 * constant" one (i.e. one of the descriptors that don't have all instrDesc
2262 * fields allocated).
2265 inline bool emitter::emitIsTinyInsDsc(instrDesc* id)
2267 return id->idIsTiny();
2270 inline bool emitter::emitIsScnsInsDsc(instrDesc* id)
2272 return id->idIsSmallDsc();
2275 /*****************************************************************************
2277 * Given an instruction, return its "update mode" (RD/WR/RW).
2280 inline insUpdateModes emitter::emitInsUpdateMode(instruction ins)
2283 assert((unsigned)ins < emitInsModeFmtCnt);
2285 return (insUpdateModes)emitInsModeFmtTab[ins];
2288 /*****************************************************************************
2290 * Return the number of epilog blocks generated so far.
2293 inline unsigned emitter::emitGetEpilogCnt()
2295 return emitEpilogCnt;
2298 /*****************************************************************************
2300 * Return the current size of the specified data section.
2303 inline UNATIVE_OFFSET emitter::emitDataSize()
2305 return emitConsDsc.dsdOffs;
2308 /*****************************************************************************
2310 * Return a handle to the current position in the output stream. This can
2311 * be later converted to an actual code offset in bytes.
2314 inline void* emitter::emitCurBlock()
2319 /*****************************************************************************
2321 * The emitCurOffset() method returns a cookie that identifies the current
2322 * position in the instruction stream. Due to things like scheduling (and
2323 * the fact that the final size of some instructions cannot be known until
2324 * the end of code generation), we return a value with the instruction number
2325 * and its estimated offset to the caller.
2328 inline unsigned emitGetInsNumFromCodePos(unsigned codePos)
2330 return (codePos & 0xFFFF);
2333 inline unsigned emitGetInsOfsFromCodePos(unsigned codePos)
2335 return (codePos >> 16);
2338 inline unsigned emitter::emitCurOffset()
2340 unsigned codePos = emitCurIGinsCnt + (emitCurIGsize << 16);
2342 assert(emitGetInsOfsFromCodePos(codePos) == emitCurIGsize);
2343 assert(emitGetInsNumFromCodePos(codePos) == emitCurIGinsCnt);
2345 // printf("[IG=%02u;ID=%03u;OF=%04X] => %08X\n", emitCurIG->igNum, emitCurIGinsCnt, emitCurIGsize, codePos);
2350 extern const unsigned short emitTypeSizes[TYP_COUNT];
2353 inline emitAttr emitTypeSize(T type)
2355 assert(TypeGet(type) < TYP_COUNT);
2356 assert(emitTypeSizes[TypeGet(type)] > 0);
2357 return (emitAttr)emitTypeSizes[TypeGet(type)];
2360 extern const unsigned short emitTypeActSz[TYP_COUNT];
2362 inline emitAttr emitActualTypeSize(var_types type)
2364 assert(type < TYP_COUNT);
2365 assert(emitTypeActSz[type] > 0);
2366 return (emitAttr)emitTypeActSz[type];
2369 /*****************************************************************************
2371 * Convert between an operand size in bytes and a smaller encoding used for
2372 * storage in instruction descriptors.
2375 /* static */ inline emitter::opSize emitter::emitEncodeSize(emitAttr size)
2377 assert(size == EA_1BYTE || size == EA_2BYTE || size == EA_4BYTE || size == EA_8BYTE || size == EA_16BYTE ||
2380 return emitSizeEncode[((int)size) - 1];
2383 /* static */ inline emitAttr emitter::emitDecodeSize(emitter::opSize ensz)
2385 assert(((unsigned)ensz) < OPSZ_COUNT);
2387 return emitSizeDecode[ensz];
2390 /*****************************************************************************
2392 * Little helpers to allocate various flavors of instructions.
2395 inline emitter::instrDesc* emitter::emitNewInstrTiny(emitAttr attr)
2399 id = (instrDesc*)emitAllocInstr(TINY_IDSC_SIZE, attr);
2405 inline emitter::instrDesc* emitter::emitNewInstrSmall(emitAttr attr)
2409 // This is larger than the Tiny Descr
2410 id = (instrDesc*)emitAllocInstr(SMALL_IDSC_SIZE, attr);
2411 id->idSetIsSmallDsc();
2416 inline emitter::instrDesc* emitter::emitNewInstr(emitAttr attr)
2418 // This is larger than the Small Descr
2419 return emitAllocInstr(attr);
2422 inline emitter::instrDescJmp* emitter::emitNewInstrJmp()
2424 return emitAllocInstrJmp();
2427 #if !defined(_TARGET_ARM64_)
2428 inline emitter::instrDescLbl* emitter::emitNewInstrLbl()
2430 return emitAllocInstrLbl();
2432 #endif // !_TARGET_ARM64_
2434 inline emitter::instrDesc* emitter::emitNewInstrDsp(emitAttr attr, ssize_t dsp)
2438 instrDesc* id = emitAllocInstr(attr);
2448 instrDescDsp* id = emitAllocInstrDsp(attr);
2450 id->idSetIsLargeDsp();
2451 id->iddDspVal = dsp;
2461 /*****************************************************************************
2463 * Allocate an instruction descriptor for an instruction with a constant operand.
2464 * The instruction descriptor uses the idAddrUnion to save additional info
2465 * so the smallest size that this can be is sizeof(instrDesc).
2466 * Note that this very similar to emitter::emitNewInstrSC(), except it never
2467 * allocates a small descriptor.
2469 inline emitter::instrDesc* emitter::emitNewInstrCns(emitAttr attr, ssize_t cns)
2471 if (instrDesc::fitsInSmallCns(cns))
2473 instrDesc* id = emitAllocInstr(attr);
2475 id->idSmallCns(cns);
2479 if (cns - ID_MIN_SMALL_CNS >= SMALL_CNS_TSZ)
2480 emitSmallCns[SMALL_CNS_TSZ - 1]++;
2482 emitSmallCns[cns - ID_MIN_SMALL_CNS]++;
2489 instrDescCns* id = emitAllocInstrCns(attr);
2491 id->idSetIsLargeCns();
2492 id->idcCnsVal = cns;
2502 /*****************************************************************************
2504 * Get the instrDesc size, general purpose version
2508 inline size_t emitter::emitGetInstrDescSize(const instrDesc* id)
2512 return TINY_IDSC_SIZE;
2515 if (id->idIsSmallDsc())
2517 return SMALL_IDSC_SIZE;
2520 if (id->idIsLargeCns())
2522 return sizeof(instrDescCns);
2525 return sizeof(instrDesc);
2528 /*****************************************************************************
2530 * Allocate an instruction descriptor for an instruction with a small integer
2531 * constant operand. This is the same as emitNewInstrCns() except that here
2532 * any constant that is small enough for instrDesc::fitsInSmallCns() only gets
2533 * allocated SMALL_IDSC_SIZE bytes (and is thus a small descriptor, whereas
2534 * emitNewInstrCns() always allocates at least sizeof(instrDesc).
2537 inline emitter::instrDesc* emitter::emitNewInstrSC(emitAttr attr, ssize_t cns)
2541 if (instrDesc::fitsInSmallCns(cns))
2543 id = (instrDesc*)emitAllocInstr(SMALL_IDSC_SIZE, attr);
2545 id->idSmallCns(cns);
2546 id->idSetIsSmallDsc();
2550 id = (instrDesc*)emitAllocInstr(sizeof(instrDescCns), attr);
2552 id->idSetIsLargeCns();
2553 ((instrDescCns*)id)->idcCnsVal = cns;
2559 /*****************************************************************************
2561 * Get the instrDesc size for something that contains a constant
2564 inline size_t emitter::emitGetInstrDescSizeSC(const instrDesc* id)
2566 if (id->idIsSmallDsc())
2568 return SMALL_IDSC_SIZE;
2570 else if (id->idIsLargeCns())
2572 return sizeof(instrDescCns);
2576 return sizeof(instrDesc);
2580 /*****************************************************************************
2582 * The following helpers should be used to access the various values that
2583 * get stored in different places within the instruction descriptor.
2586 inline ssize_t emitter::emitGetInsCns(instrDesc* id)
2588 return id->idIsLargeCns() ? ((instrDescCns*)id)->idcCnsVal : id->idSmallCns();
2591 inline ssize_t emitter::emitGetInsDsp(instrDesc* id)
2593 if (id->idIsLargeDsp())
2595 if (id->idIsLargeCns())
2597 return ((instrDescCnsDsp*)id)->iddcDspVal;
2599 return ((instrDescDsp*)id)->iddDspVal;
2604 inline ssize_t emitter::emitGetInsCnsDsp(instrDesc* id, ssize_t* dspPtr)
2606 if (id->idIsLargeCns())
2608 if (id->idIsLargeDsp())
2610 *dspPtr = ((instrDescCnsDsp*)id)->iddcDspVal;
2611 return ((instrDescCnsDsp*)id)->iddcCnsVal;
2616 return ((instrDescCns*)id)->idcCnsVal;
2621 if (id->idIsLargeDsp())
2623 *dspPtr = ((instrDescDsp*)id)->iddDspVal;
2624 return id->idSmallCns();
2629 return id->idSmallCns();
2634 /*****************************************************************************
2636 * Get hold of the argument count for an indirect call.
2639 inline unsigned emitter::emitGetInsCIargs(instrDesc* id)
2641 if (id->idIsLargeCall())
2643 return ((instrDescCGCA*)id)->idcArgCnt;
2647 assert(id->idIsLargeDsp() == false);
2648 assert(id->idIsLargeCns() == false);
2650 ssize_t cns = emitGetInsCns(id);
2651 assert((unsigned)cns == (size_t)cns);
2652 return (unsigned)cns;
2656 /*****************************************************************************
2658 * Returns true if the given register contains a live GC ref.
2661 inline GCtype emitter::emitRegGCtype(regNumber reg)
2663 assert(emitIssuing);
2665 if ((emitThisGCrefRegs & genRegMask(reg)) != 0)
2669 else if ((emitThisByrefRegs & genRegMask(reg)) != 0)
2681 #if EMIT_TRACK_STACK_DEPTH
2682 #define CHECK_STACK_DEPTH() assert((int)emitCurStackLvl >= 0)
2684 #define CHECK_STACK_DEPTH()
2689 /*****************************************************************************
2691 * Return true when a given code offset is properly aligned for the target
2694 inline bool IsCodeAligned(UNATIVE_OFFSET offset)
2696 return ((offset & (CODE_ALIGN - 1)) == 0);
2700 inline BYTE* emitter::emitCodeWithInstructionSize(BYTE* codePtrBefore, BYTE* newCodePointer, unsigned char* instrSize)
2702 // DLD: Perhaps this method should return the instruction size, and we should do dst += <that size>
2703 // as is done in other cases?
2704 assert(newCodePointer >= codePtrBefore);
2705 ClrSafeInt<unsigned char> callInstrSizeSafe = ClrSafeInt<unsigned char>(newCodePointer - codePtrBefore);
2706 assert(!callInstrSizeSafe.IsOverflow());
2707 *instrSize = callInstrSizeSafe.Value();
2708 return newCodePointer;
2711 /*****************************************************************************
2713 * Add a new IG to the current list, and get it ready to receive code.
2716 inline void emitter::emitNewIG()
2718 insGroup* ig = emitAllocAndLinkIG();
2720 /* It's linked in. Now, set it up to accept code */
2725 #if !defined(JIT32_GCENCODER)
2726 // Start a new instruction group that is not interruptable
2727 inline void emitter::emitDisableGC()
2731 if (emitCurIGnonEmpty())
2737 emitCurIG->igFlags |= IGF_NOGCINTERRUPT;
2741 // Start a new instruction group that is interruptable
2742 inline void emitter::emitEnableGC()
2746 // The next time an instruction needs to be generated, force a new instruction group.
2747 // It will be an emitAdd group in that case. Note that the next thing we see might be
2748 // a label, which will force a non-emitAdd group.
2750 // Note that we can't just create a new instruction group here, because we don't know
2751 // if there are going to be any instructions added to it, and we don't support empty
2752 // instruction groups.
2753 emitForceNewIG = true;
2755 #endif // !defined(JIT32_GCENCODER)
2757 /*****************************************************************************/
2759 /*****************************************************************************/