Merge pull request #19040 from CarolEidt/DiffFix
[platform/upstream/coreclr.git] / src / jit / emit.h
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4 /*****************************************************************************/
5
6 #ifndef _EMIT_H_
7 #define _EMIT_H_
8
9 #include "instr.h"
10
11 #ifndef _GCINFO_H_
12 #include "gcinfo.h"
13 #endif
14
15 #include "jitgcinfo.h"
16
17 /*****************************************************************************/
18 #ifdef TRANSLATE_PDB
19 #ifndef _ADDRMAP_INCLUDED_
20 #include "addrmap.h"
21 #endif
22 #ifndef _LOCALMAP_INCLUDED_
23 #include "localmap.h"
24 #endif
25 #ifndef _PDBREWRITE_H_
26 #include "pdbrewrite.h"
27 #endif
28 #endif // TRANSLATE_PDB
29
30 /*****************************************************************************/
31 #ifdef _MSC_VER
32 #pragma warning(disable : 4200) // allow arrays of 0 size inside structs
33 #endif
34 #define TRACK_GC_TEMP_LIFETIMES 0
35
36 /*****************************************************************************/
37
38 #if 0
39 #define EMITVERBOSE 1
40 #else
41 #define EMITVERBOSE (emitComp->verbose)
42 #endif
43
44 #if 0
45 #define EMIT_GC_VERBOSE 0
46 #else
47 #define EMIT_GC_VERBOSE (emitComp->verbose)
48 #endif
49
50 #if 1
51 #define EMIT_INSTLIST_VERBOSE 0
52 #else
53 #define EMIT_INSTLIST_VERBOSE (emitComp->verbose)
54 #endif
55
56 /*****************************************************************************/
57
58 #ifdef DEBUG
59 #define DEBUG_EMIT 1
60 #else
61 #define DEBUG_EMIT 0
62 #endif
63
64 #if EMITTER_STATS
65 void emitterStats(FILE* fout);
66 void emitterStaticStats(FILE* fout); // Static stats about the emitter (data structure offsets, sizes, etc.)
67 #endif
68
69 void printRegMaskInt(regMaskTP mask);
70
71 /*****************************************************************************/
72 /* Forward declarations */
73
74 class emitLocation;
75 class emitter;
76 struct insGroup;
77
78 typedef void (*emitSplitCallbackType)(void* context, emitLocation* emitLoc);
79
80 /*****************************************************************************/
81
82 //-----------------------------------------------------------------------------
83
84 inline bool needsGC(GCtype gcType)
85 {
86     if (gcType == GCT_NONE)
87     {
88         return false;
89     }
90     else
91     {
92         assert(gcType == GCT_GCREF || gcType == GCT_BYREF);
93         return true;
94     }
95 }
96
97 //-----------------------------------------------------------------------------
98
99 #ifdef DEBUG
100
101 inline bool IsValidGCtype(GCtype gcType)
102 {
103     return (gcType == GCT_NONE || gcType == GCT_GCREF || gcType == GCT_BYREF);
104 }
105
106 // Get a string name to represent the GC type
107
108 inline const char* GCtypeStr(GCtype gcType)
109 {
110     switch (gcType)
111     {
112         case GCT_NONE:
113             return "npt";
114         case GCT_GCREF:
115             return "gcr";
116         case GCT_BYREF:
117             return "byr";
118         default:
119             assert(!"Invalid GCtype");
120             return "err";
121     }
122 }
123
124 #endif // DEBUG
125
126 /*****************************************************************************/
127
128 #if DEBUG_EMIT
129 #define INTERESTING_JUMP_NUM -1 // set to 0 to see all jump info
130 //#define INTERESTING_JUMP_NUM    0
131 #endif
132
133 /*****************************************************************************
134  *
135  *  Represent an emitter location.
136  */
137
138 class emitLocation
139 {
140 public:
141     emitLocation() : ig(nullptr), codePos(0)
142     {
143     }
144
145     emitLocation(insGroup* _ig) : ig(_ig), codePos(0)
146     {
147     }
148
149     emitLocation(void* emitCookie) : ig((insGroup*)emitCookie), codePos(0)
150     {
151     }
152
153     // A constructor for code that needs to call it explicitly.
154     void Init()
155     {
156         this->emitLocation::emitLocation();
157     }
158
159     void CaptureLocation(emitter* emit);
160
161     bool IsCurrentLocation(emitter* emit) const;
162
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
166     {
167         return (codePos == 0);
168     }
169
170     UNATIVE_OFFSET CodeOffset(emitter* emit) const;
171
172     insGroup* GetIG() const
173     {
174         return ig;
175     }
176
177     int GetInsNum() const;
178
179     bool operator!=(const emitLocation& other) const
180     {
181         return (ig != other.ig) || (codePos != other.codePos);
182     }
183
184     bool operator==(const emitLocation& other) const
185     {
186         return !(*this != other);
187     }
188
189     bool Valid() const
190     {
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.
197
198         if (ig == nullptr)
199         {
200             return false;
201         }
202
203         return true;
204     }
205
206 #ifdef _TARGET_AMD64_
207     UNATIVE_OFFSET GetFuncletPrologOffset(emitter* emit) const;
208 #endif // _TARGET_AMD64_
209
210 #ifdef DEBUG
211     void Print() const;
212 #endif // DEBUG
213
214 private:
215     insGroup* ig;      // the instruction group
216     unsigned  codePos; // the code position within the IG (see emitCurOffset())
217 };
218
219 /************************************************************************/
220 /*          The following describes an instruction group                */
221 /************************************************************************/
222
223 enum insGroupPlaceholderType : unsigned char
224 {
225     IGPT_PROLOG, // currently unused
226     IGPT_EPILOG,
227 #if FEATURE_EH_FUNCLETS
228     IGPT_FUNCLET_PROLOG,
229     IGPT_FUNCLET_EPILOG,
230 #endif // FEATURE_EH_FUNCLETS
231 };
232
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.
236 #pragma pack(push)
237 #pragma pack(4)
238 #endif // defined(_MSC_VER) && defined(_TARGET_ARM_)
239
240 struct insPlaceholderGroupData
241 {
242     insGroup*               igPhNext;
243     BasicBlock*             igPhBB;
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
252
253 struct insGroup
254 {
255     insGroup* igNext;
256
257 #ifdef DEBUG
258     insGroup* igSelf; // for consistency checking
259 #endif
260
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
266
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.
281
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
286 #ifdef DEBUG
287 #define IGF_PROPAGATE_MASK (IGF_EPILOG | IGF_FUNCLET_PROLOG | IGF_FUNCLET_EPILOG)
288 #else // DEBUG
289 #define IGF_PROPAGATE_MASK (IGF_EPILOG | IGF_FUNCLET_PROLOG)
290 #endif // DEBUG
291 #else  // FEATURE_EH_FUNCLETS
292 #define IGF_PROPAGATE_MASK (IGF_EPILOG)
293 #endif // FEATURE_EH_FUNCLETS
294
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
298
299     union {
300         BYTE*                    igData;   // addr of instruction descriptors
301         insPlaceholderGroupData* igPhData; // when igFlags & IGF_PLACEHOLDER
302     };
303
304 #if EMIT_TRACK_STACK_DEPTH
305     unsigned igStkLvl; // stack level on entry
306 #endif
307     regMaskSmall  igGCregs; // set of registers with live GC refs
308     unsigned char igInsCnt; // # of instructions  in this group
309
310 #else // REGMASK_BITS
311
312     regMaskSmall igGCregs; // set of registers with live GC refs
313
314     union {
315         BYTE*                    igData;   // addr of instruction descriptors
316         insPlaceholderGroupData* igPhData; // when igFlags & IGF_PLACEHOLDER
317     };
318
319 #if EMIT_TRACK_STACK_DEPTH
320     unsigned igStkLvl; // stack level on entry
321 #endif
322
323     unsigned char igInsCnt; // # of instructions  in this group
324
325 #endif // REGMASK_BITS
326
327     VARSET_VALRET_TP igGCvars() const
328     {
329         assert(igFlags & IGF_GC_VARS);
330
331         BYTE* ptr = (BYTE*)igData;
332         ptr -= sizeof(VARSET_TP);
333
334         return *(VARSET_TP*)ptr;
335     }
336
337     unsigned igByrefRegs() const
338     {
339         assert(igFlags & IGF_BYREF_REGS);
340
341         BYTE* ptr = (BYTE*)igData;
342
343         if (igFlags & IGF_GC_VARS)
344         {
345             ptr -= sizeof(VARSET_TP);
346         }
347
348         ptr -= sizeof(unsigned);
349
350         return *(unsigned*)ptr;
351     }
352
353 }; // end of struct insGroup
354
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.
358 //
359 #define MAX_PLACEHOLDER_IG_SIZE 256
360
361 #if defined(_MSC_VER) && defined(_TARGET_ARM_)
362 #pragma pack(pop)
363 #endif // defined(_MSC_VER) && defined(_TARGET_ARM_)
364
365 /*****************************************************************************/
366
367 #define DEFINE_ID_OPS
368 #include "emitfmts.h"
369 #undef DEFINE_ID_OPS
370
371 enum LclVarAddrTag
372 {
373     LVA_STANDARD_ENCODING = 0,
374     LVA_LARGE_OFFSET      = 1,
375     LVA_COMPILER_TEMP     = 2,
376     LVA_LARGE_VARNUM      = 3
377 };
378
379 struct emitLclVarAddr
380 {
381     // Constructor
382     void initLclVarAddr(int varNum, unsigned offset);
383
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
386
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.
390     //
391 protected:
392     unsigned _lvaVarNum : 15; // Usually the lvaVarNum
393     unsigned _lvaExtra : 15;  // Usually the lvaOffset
394     unsigned _lvaTag : 2;     // tag field to support larger varnums
395 };
396
397 enum idAddrUnionTag
398 {
399     iaut_ALIGNED_POINTER = 0x0,
400     iaut_DATA_OFFSET     = 0x1,
401     iaut_INST_COUNT      = 0x2,
402     iaut_UNUSED_TAG      = 0x3,
403
404     iaut_MASK  = 0x3,
405     iaut_SHIFT = 2
406 };
407
408 class emitter
409 {
410     friend class emitLocation;
411     friend class Compiler;
412     friend class CodeGen;
413     friend class CodeGenInterface;
414
415 public:
416     /*************************************************************************
417      *
418      *  Define the public entry points.
419      */
420
421     // Constructor.
422     emitter()
423     {
424 #ifdef DEBUG
425         // There seem to be some cases where this is used without being initialized via CodeGen::inst_set_SV_var().
426         emitVarRefOffs = 0;
427 #endif // DEBUG
428
429 #ifdef _TARGET_XARCH_
430         SetUseSSE4(false);
431         SetUseVEXEncoding(false);
432 #endif // _TARGET_XARCH_
433     }
434
435 #include "emitpub.h"
436
437 protected:
438     /************************************************************************/
439     /*                        Miscellaneous stuff                           */
440     /************************************************************************/
441
442     Compiler* emitComp;
443     GCInfo*   gcInfo;
444     CodeGen*  codeGen;
445
446     typedef GCInfo::varPtrDsc varPtrDsc;
447     typedef GCInfo::regPtrDsc regPtrDsc;
448     typedef GCInfo::CallDsc   callDsc;
449
450     void* emitGetMem(size_t sz);
451
452     enum opSize : unsigned
453     {
454         OPSZ1      = 0,
455         OPSZ2      = 1,
456         OPSZ4      = 2,
457         OPSZ8      = 3,
458         OPSZ16     = 4,
459         OPSZ32     = 5,
460         OPSZ_COUNT = 6,
461 #ifdef _TARGET_AMD64_
462         OPSZP = OPSZ8,
463 #else
464         OPSZP = OPSZ4,
465 #endif
466     };
467
468 #define OPSIZE_INVALID ((opSize)0xffff)
469
470     static const emitter::opSize emitSizeEncode[];
471     static const emitAttr        emitSizeDecode[];
472
473     static emitter::opSize emitEncodeSize(emitAttr size);
474     static emitAttr emitDecodeSize(emitter::opSize ensz);
475
476     // Currently, we only allow one IG for the prolog
477     bool emitIGisInProlog(const insGroup* ig)
478     {
479         return ig == emitPrologIG;
480     }
481
482     bool emitIGisInEpilog(const insGroup* ig)
483     {
484         return (ig != nullptr) && ((ig->igFlags & IGF_EPILOG) != 0);
485     }
486
487 #if FEATURE_EH_FUNCLETS
488
489     bool emitIGisInFuncletProlog(const insGroup* ig)
490     {
491         return (ig != nullptr) && ((ig->igFlags & IGF_FUNCLET_PROLOG) != 0);
492     }
493
494     bool emitIGisInFuncletEpilog(const insGroup* ig)
495     {
496         return (ig != nullptr) && ((ig->igFlags & IGF_FUNCLET_EPILOG) != 0);
497     }
498
499 #endif // FEATURE_EH_FUNCLETS
500
501     // If "ig" corresponds to the start of a basic block that is the
502     // target of a funclet return, generate GC information for it's start
503     // address "cp", as if it were the return address of a call.
504     void emitGenGCInfoIfFuncletRetTarget(insGroup* ig, BYTE* cp);
505
506     void emitRecomputeIGoffsets();
507
508     /************************************************************************/
509     /*          The following describes a single instruction                */
510     /************************************************************************/
511
512     enum insFormat : unsigned
513     {
514 #define IF_DEF(en, op1, op2) IF_##en,
515 #include "emitfmts.h"
516
517         IF_COUNT
518     };
519
520 #define AM_DISP_BITS ((sizeof(unsigned) * 8) - 2 * (REGNUM_BITS + 1) - 2)
521 #define AM_DISP_BIG_VAL (-(1 << (AM_DISP_BITS - 1)))
522 #define AM_DISP_MIN (-((1 << (AM_DISP_BITS - 1)) - 1))
523 #define AM_DISP_MAX (+((1 << (AM_DISP_BITS - 1)) - 1))
524
525     struct emitAddrMode
526     {
527         regNumber       amBaseReg : REGNUM_BITS + 1;
528         regNumber       amIndxReg : REGNUM_BITS + 1;
529         emitter::opSize amScale : 2;
530         int             amDisp : AM_DISP_BITS;
531     };
532
533 #ifdef DEBUG // This information is used in DEBUG builds to display the method name for call instructions
534
535     struct instrDesc;
536
537     struct instrDescDebugInfo
538     {
539         unsigned idNum;
540         size_t   idSize;       // size of the instruction descriptor
541         unsigned idVarRefOffs; // IL offset for LclVar reference
542         size_t   idMemCookie;  // for display of method name  (also used by switch table)
543 #ifdef TRANSLATE_PDB
544         unsigned int idilStart; // instruction descriptor source information for PDB translation
545 #endif
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
549     };
550
551 #endif // DEBUG
552
553 #ifdef _TARGET_ARM_
554     unsigned insEncodeSetFlags(insFlags sf);
555
556     enum insSize : unsigned
557     {
558         ISZ_16BIT,
559         ISZ_32BIT,
560         ISZ_48BIT // pseudo-instruction for conditional branch with imm24 range,
561                   // encoded as IT of condition followed by an unconditional branch
562     };
563
564     unsigned insEncodeShiftOpts(insOpts opt);
565     unsigned insEncodePUW_G0(insOpts opt, int imm);
566     unsigned insEncodePUW_H0(insOpts opt, int imm);
567
568 #endif // _TARGET_ARM_
569
570     struct instrDescCns;
571
572     struct instrDesc
573     {
574     private:
575 // The assembly instruction
576 #if defined(_TARGET_XARCH_)
577         static_assert_no_msg(INS_count <= 1024);
578         instruction _idIns : 10;
579 #elif defined(_TARGET_ARM64_)
580         static_assert_no_msg(INS_count <= 512);
581         instruction _idIns : 9;
582 #else  // !(defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_))
583         static_assert_no_msg(INS_count <= 256);
584         instruction _idIns : 8;
585 #endif // !(defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_))
586        // The format for the instruction
587 #if defined(_TARGET_XARCH_)
588         static_assert_no_msg(IF_COUNT <= 128);
589         insFormat _idInsFmt : 7;
590 #else
591         static_assert_no_msg(IF_COUNT <= 256);
592         insFormat _idInsFmt : 8;
593 #endif
594
595     public:
596         instruction idIns() const
597         {
598             return _idIns;
599         }
600         void idIns(instruction ins)
601         {
602             assert((ins != INS_invalid) && (ins < INS_count));
603             _idIns = ins;
604         }
605
606         insFormat idInsFmt() const
607         {
608             return _idInsFmt;
609         }
610         void idInsFmt(insFormat insFmt)
611         {
612 #if defined(_TARGET_ARM64_)
613             noway_assert(insFmt != IF_NONE); // Only the x86 emitter uses IF_NONE, it is invalid for ARM64 (and ARM32)
614 #endif
615             assert(insFmt < IF_COUNT);
616             _idInsFmt = insFmt;
617         }
618
619         void idSetRelocFlags(emitAttr attr)
620         {
621             _idCnsReloc = (EA_IS_CNS_RELOC(attr) ? 1 : 0);
622             _idDspReloc = (EA_IS_DSP_RELOC(attr) ? 1 : 0);
623         }
624
625         ////////////////////////////////////////////////////////////////////////
626         // Space taken up to here:
627         // x86:   17 bits
628         // amd64: 17 bits
629         // arm:   16 bits
630         // arm64: 17 bits
631
632     private:
633 #if defined(_TARGET_XARCH_)
634         unsigned _idCodeSize : 4; // size of instruction in bytes
635         opSize   _idOpSize : 3;   // operand size: 0=1 , 1=2 , 2=4 , 3=8, 4=16, 5=32
636                                   // At this point we have fully consumed first DWORD so that next field
637                                   // doesn't cross a byte boundary.
638 #elif defined(_TARGET_ARM64_)
639 // Moved the definition of '_idOpSize' later so that we don't cross a 32-bit boundary when laying out bitfields
640 #else  // ARM
641         opSize      _idOpSize : 2; // operand size: 0=1 , 1=2 , 2=4 , 3=8
642 #endif // ARM
643
644         // On Amd64, this is where the second DWORD begins
645         // On System V a call could return a struct in 2 registers. The instrDescCGCA struct below has  member that
646         // stores the GC-ness of the second register.
647         // It is added to the instrDescCGCA and not here (the base struct) since it is not needed by all the
648         // instructions. This struct (instrDesc) is very carefully kept to be no more than 128 bytes. There is no more
649         // space to add members for keeping GC-ness of the second return registers. It will also bloat the base struct
650         // unnecessarily since the GC-ness of the second register is only needed for call instructions.
651         // The instrDescCGCA struct's member keeping the GC-ness of the first return register is _idcSecondRetRegGCType.
652         GCtype _idGCref : 2; // GCref operand? (value is a "GCtype")
653
654         // The idReg1 and idReg2 fields hold the first and second register
655         // operand(s), whenever these are present. Note that currently the
656         // size of these fields is 6 bits on all targets, and care needs to
657         // be taken to make sure all of these fields stay reasonably packed.
658
659         // Note that we use the _idReg1 and _idReg2 fields to hold
660         // the live gcrefReg mask for the call instructions on x86/x64
661         //
662         regNumber _idReg1 : REGNUM_BITS; // register num
663
664         regNumber _idReg2 : REGNUM_BITS;
665
666         ////////////////////////////////////////////////////////////////////////
667         // Space taken up to here:
668         // x86:   38 bits
669         // amd64: 38 bits
670         // arm:   32 bits
671         // arm64: 31 bits
672         CLANG_FORMAT_COMMENT_ANCHOR;
673
674         unsigned _idSmallDsc : 1;  // is this a "small" descriptor?
675         unsigned _idLargeCns : 1;  // does a large constant     follow?
676         unsigned _idLargeDsp : 1;  // does a large displacement follow?
677         unsigned _idLargeCall : 1; // large call descriptor used
678
679         unsigned _idBound : 1;      // jump target / frame offset bound
680         unsigned _idCallRegPtr : 1; // IL indirect calls: addr in reg
681         unsigned _idCallAddr : 1;   // IL indirect calls: can make a direct call to iiaAddr
682         unsigned _idNoGC : 1;       // Some helpers don't get recorded in GC tables
683
684 #ifdef _TARGET_ARM64_
685         opSize   _idOpSize : 3; // operand size: 0=1 , 1=2 , 2=4 , 3=8, 4=16
686         insOpts  _idInsOpt : 6; // options for instructions
687         unsigned _idLclVar : 1; // access a local on stack
688 #endif
689
690 #ifdef _TARGET_ARM_
691         insSize  _idInsSize : 2;   // size of instruction: 16, 32 or 48 bits
692         insFlags _idInsFlags : 1;  // will this instruction set the flags
693         unsigned _idLclVar : 1;    // access a local on stack
694         unsigned _idLclFPBase : 1; // access a local on stack - SP based offset
695         insOpts  _idInsOpt : 3;    // options for Load/Store instructions
696
697 // For arm we have used 16 bits
698 #define ID_EXTRA_BITFIELD_BITS (16)
699
700 #elif defined(_TARGET_ARM64_)
701 // For Arm64, we have used 17 bits from the second DWORD.
702 #define ID_EXTRA_BITFIELD_BITS (17)
703 #elif defined(_TARGET_XARCH_)
704                                    // For xarch, we have used 14 bits from the second DWORD.
705 #define ID_EXTRA_BITFIELD_BITS (14)
706 #else
707 #error Unsupported or unset target architecture
708 #endif
709
710         ////////////////////////////////////////////////////////////////////////
711         // Space taken up to here:
712         // x86:   46 bits
713         // amd64: 46 bits
714         // arm:   48 bits
715         // arm64: 49 bits
716
717         unsigned _idCnsReloc : 1; // LargeCns is an RVA and needs reloc tag
718         unsigned _idDspReloc : 1; // LargeDsp is an RVA and needs reloc tag
719
720 #define ID_EXTRA_RELOC_BITS (2)
721
722         ////////////////////////////////////////////////////////////////////////
723         // Space taken up to here:
724         // x86:   48 bits
725         // amd64: 48 bits
726         // arm:   50 bits
727         // arm64: 51 bits
728         CLANG_FORMAT_COMMENT_ANCHOR;
729
730 #define ID_EXTRA_BITS (ID_EXTRA_RELOC_BITS + ID_EXTRA_BITFIELD_BITS)
731
732 /* Use whatever bits are left over for small constants */
733
734 #define ID_BIT_SMALL_CNS (32 - ID_EXTRA_BITS)
735 #define ID_MIN_SMALL_CNS 0
736 #define ID_MAX_SMALL_CNS (int)((1 << ID_BIT_SMALL_CNS) - 1U)
737
738         ////////////////////////////////////////////////////////////////////////
739         // Small constant size:
740         // x86:   16 bits
741         // amd64: 16 bits
742         // arm:   14 bits
743         // arm64: 13 bits
744
745         unsigned _idSmallCns : ID_BIT_SMALL_CNS;
746
747         ////////////////////////////////////////////////////////////////////////
748         // Space taken up to here: 64 bits, all architectures, by design.
749         ////////////////////////////////////////////////////////////////////////
750         CLANG_FORMAT_COMMENT_ANCHOR;
751
752 #ifdef DEBUG
753
754         instrDescDebugInfo* _idDebugOnlyInfo;
755
756     public:
757         instrDescDebugInfo* idDebugOnlyInfo() const
758         {
759             return _idDebugOnlyInfo;
760         }
761         void idDebugOnlyInfo(instrDescDebugInfo* info)
762         {
763             _idDebugOnlyInfo = info;
764         }
765
766     private:
767 #endif // DEBUG
768
769         CLANG_FORMAT_COMMENT_ANCHOR;
770
771 //
772 // This is the end of the 'small' instrDesc which is the same on all
773 //   platforms (except 64-bit DEBUG which is a little bigger).
774 // Non-DEBUG sizes:
775 //   x86/amd64/arm/arm64: 64 bits
776 // DEBUG sizes (includes one pointer):
777 //   x86:   2 DWORDs, 96 bits
778 //   amd64: 4 DWORDs, 128 bits
779 //   arm:   3 DWORDs, 96 bits
780 //   arm64: 4 DWORDs, 128 bits
781 // There should no padding or alignment issues on any platform or
782 //   configuration (including DEBUG which has 1 extra pointer).
783 //
784
785 /*
786     If you add lots more fields that need to be cleared (such
787     as various flags), you might need to update the body of
788     emitter::emitAllocInstr() to clear them.
789  */
790
791 #if DEBUG
792 #define SMALL_IDSC_DEBUG_EXTRA (sizeof(void*))
793 #else
794 #define SMALL_IDSC_DEBUG_EXTRA (0)
795 #endif
796
797 #define SMALL_IDSC_SIZE (8 + SMALL_IDSC_DEBUG_EXTRA)
798
799         void checkSizes();
800
801         union idAddrUnion {
802 // TODO-Cleanup: We should really add a DEBUG-only tag to this union so we can add asserts
803 // about reading what we think is here, to avoid unexpected corruption issues.
804
805 #ifndef _TARGET_ARM64_
806             emitLclVarAddr iiaLclVar;
807 #endif
808             BasicBlock*  iiaBBlabel;
809             insGroup*    iiaIGlabel;
810             BYTE*        iiaAddr;
811             emitAddrMode iiaAddrMode;
812
813             CORINFO_FIELD_HANDLE iiaFieldHnd; // iiaFieldHandle is also used to encode
814                                               // an offset into the JIT data constant area
815             bool iiaIsJitDataOffset() const;
816             int  iiaGetJitDataOffset() const;
817
818 #ifdef _TARGET_ARMARCH_
819
820             // iiaEncodedInstrCount and its accessor functions are used to specify an instruction
821             // count for jumps, instead of using a label and multiple blocks. This is used in the
822             // prolog as well as for IF_LARGEJMP pseudo-branch instructions.
823             int iiaEncodedInstrCount;
824
825             bool iiaHasInstrCount() const
826             {
827                 return (iiaEncodedInstrCount & iaut_MASK) == iaut_INST_COUNT;
828             }
829             int iiaGetInstrCount() const
830             {
831                 assert(iiaHasInstrCount());
832                 return (iiaEncodedInstrCount >> iaut_SHIFT);
833             }
834             void iiaSetInstrCount(int count)
835             {
836                 assert(abs(count) < 10);
837                 iiaEncodedInstrCount = (count << iaut_SHIFT) | iaut_INST_COUNT;
838             }
839
840             struct
841             {
842 #ifdef _TARGET_ARM64_
843                 // For 64-bit architecture this 32-bit structure can pack with these unsigned bit fields
844                 emitLclVarAddr iiaLclVar;
845                 unsigned       _idReg3Scaled : 1; // Reg3 is scaled by idOpSize bits
846                 GCtype         _idGCref2 : 2;
847 #endif
848                 regNumber _idReg3 : REGNUM_BITS;
849                 regNumber _idReg4 : REGNUM_BITS;
850             };
851 #elif defined(_TARGET_XARCH_)
852             struct
853             {
854                 regNumber _idReg3 : REGNUM_BITS;
855                 regNumber _idReg4 : REGNUM_BITS;
856             };
857 #endif // defined(_TARGET_XARCH_)
858
859         } _idAddrUnion;
860
861         /* Trivial wrappers to return properly typed enums */
862     public:
863         bool idIsSmallDsc() const
864         {
865             return (_idSmallDsc != 0);
866         }
867         void idSetIsSmallDsc()
868         {
869             _idSmallDsc = 1;
870         }
871
872 #if defined(_TARGET_XARCH_)
873
874         unsigned idCodeSize() const
875         {
876             return _idCodeSize;
877         }
878         void idCodeSize(unsigned sz)
879         {
880             _idCodeSize = sz;
881             assert(sz == _idCodeSize);
882         }
883
884 #elif defined(_TARGET_ARM64_)
885         unsigned idCodeSize() const
886         {
887             int size = 4;
888             switch (idInsFmt())
889             {
890                 case IF_LARGEADR:
891                 // adrp + add
892                 case IF_LARGEJMP:
893                     // b<cond> + b<uncond>
894                     size = 8;
895                     break;
896                 case IF_LARGELDC:
897                     if (isVectorRegister(idReg1()))
898                     {
899                         // adrp + ldr + fmov
900                         size = 12;
901                     }
902                     else
903                     {
904                         // adrp + ldr
905                         size = 8;
906                     }
907                     break;
908                 default:
909                     break;
910             }
911
912             return size;
913         }
914
915 #elif defined(_TARGET_ARM_)
916
917         bool idInstrIsT1() const
918         {
919             return (_idInsSize == ISZ_16BIT);
920         }
921         unsigned idCodeSize() const
922         {
923             unsigned result = (_idInsSize == ISZ_16BIT) ? 2 : (_idInsSize == ISZ_32BIT) ? 4 : 6;
924             return result;
925         }
926         insSize idInsSize() const
927         {
928             return _idInsSize;
929         }
930         void idInsSize(insSize isz)
931         {
932             _idInsSize = isz;
933             assert(isz == _idInsSize);
934         }
935         insFlags idInsFlags() const
936         {
937             return _idInsFlags;
938         }
939         void idInsFlags(insFlags sf)
940         {
941             _idInsFlags = sf;
942             assert(sf == _idInsFlags);
943         }
944 #endif // _TARGET_ARM_
945
946         emitAttr idOpSize()
947         {
948             return emitDecodeSize(_idOpSize);
949         }
950         void idOpSize(emitAttr opsz)
951         {
952             _idOpSize = emitEncodeSize(opsz);
953         }
954
955         GCtype idGCref() const
956         {
957             return (GCtype)_idGCref;
958         }
959         void idGCref(GCtype gctype)
960         {
961             _idGCref = gctype;
962         }
963
964         regNumber idReg1() const
965         {
966             return _idReg1;
967         }
968         void idReg1(regNumber reg)
969         {
970             _idReg1 = reg;
971             assert(reg == _idReg1);
972         }
973
974 #ifdef _TARGET_ARM64_
975         GCtype idGCrefReg2() const
976         {
977             assert(!idIsSmallDsc());
978             return (GCtype)idAddr()->_idGCref2;
979         }
980         void idGCrefReg2(GCtype gctype)
981         {
982             assert(!idIsSmallDsc());
983             idAddr()->_idGCref2 = gctype;
984         }
985 #endif // _TARGET_ARM64_
986
987         regNumber idReg2() const
988         {
989             return _idReg2;
990         }
991         void idReg2(regNumber reg)
992         {
993             _idReg2 = reg;
994             assert(reg == _idReg2);
995         }
996
997 #if defined(_TARGET_XARCH_)
998         regNumber idReg3() const
999         {
1000             assert(!idIsSmallDsc());
1001             return idAddr()->_idReg3;
1002         }
1003         void idReg3(regNumber reg)
1004         {
1005             assert(!idIsSmallDsc());
1006             idAddr()->_idReg3 = reg;
1007             assert(reg == idAddr()->_idReg3);
1008         }
1009         regNumber idReg4() const
1010         {
1011             assert(!idIsSmallDsc());
1012             return idAddr()->_idReg4;
1013         }
1014         void idReg4(regNumber reg)
1015         {
1016             assert(!idIsSmallDsc());
1017             idAddr()->_idReg4 = reg;
1018             assert(reg == idAddr()->_idReg4);
1019         }
1020 #endif // defined(_TARGET_XARCH_)
1021 #ifdef _TARGET_ARMARCH_
1022         insOpts idInsOpt() const
1023         {
1024             return (insOpts)_idInsOpt;
1025         }
1026         void idInsOpt(insOpts opt)
1027         {
1028             _idInsOpt = opt;
1029             assert(opt == _idInsOpt);
1030         }
1031
1032         regNumber idReg3() const
1033         {
1034             assert(!idIsSmallDsc());
1035             return idAddr()->_idReg3;
1036         }
1037         void idReg3(regNumber reg)
1038         {
1039             assert(!idIsSmallDsc());
1040             idAddr()->_idReg3 = reg;
1041             assert(reg == idAddr()->_idReg3);
1042         }
1043         regNumber idReg4() const
1044         {
1045             assert(!idIsSmallDsc());
1046             return idAddr()->_idReg4;
1047         }
1048         void idReg4(regNumber reg)
1049         {
1050             assert(!idIsSmallDsc());
1051             idAddr()->_idReg4 = reg;
1052             assert(reg == idAddr()->_idReg4);
1053         }
1054 #ifdef _TARGET_ARM64_
1055         bool idReg3Scaled() const
1056         {
1057             assert(!idIsSmallDsc());
1058             return (idAddr()->_idReg3Scaled == 1);
1059         }
1060         void idReg3Scaled(bool val)
1061         {
1062             assert(!idIsSmallDsc());
1063             idAddr()->_idReg3Scaled = val ? 1 : 0;
1064         }
1065 #endif // _TARGET_ARM64_
1066
1067 #endif // _TARGET_ARMARCH_
1068
1069         inline static bool fitsInSmallCns(ssize_t val)
1070         {
1071             return ((val >= ID_MIN_SMALL_CNS) && (val <= ID_MAX_SMALL_CNS));
1072         }
1073
1074         bool idIsLargeCns() const
1075         {
1076             return _idLargeCns != 0;
1077         }
1078         void idSetIsLargeCns()
1079         {
1080             _idLargeCns = 1;
1081         }
1082
1083         bool idIsLargeDsp() const
1084         {
1085             return _idLargeDsp != 0;
1086         }
1087         void idSetIsLargeDsp()
1088         {
1089             _idLargeDsp = 1;
1090         }
1091         void idSetIsSmallDsp()
1092         {
1093             _idLargeDsp = 0;
1094         }
1095
1096         bool idIsLargeCall() const
1097         {
1098             return _idLargeCall != 0;
1099         }
1100         void idSetIsLargeCall()
1101         {
1102             _idLargeCall = 1;
1103         }
1104
1105         bool idIsBound() const
1106         {
1107             return _idBound != 0;
1108         }
1109         void idSetIsBound()
1110         {
1111             _idBound = 1;
1112         }
1113
1114         bool idIsCallRegPtr() const
1115         {
1116             return _idCallRegPtr != 0;
1117         }
1118         void idSetIsCallRegPtr()
1119         {
1120             _idCallRegPtr = 1;
1121         }
1122
1123         bool idIsCallAddr() const
1124         {
1125             return _idCallAddr != 0;
1126         }
1127         void idSetIsCallAddr()
1128         {
1129             _idCallAddr = 1;
1130         }
1131
1132         // Only call instructions that call helper functions may be marked as "IsNoGC", indicating
1133         // that a thread executing such a call cannot be stopped for GC.  Thus, in partially-interruptible
1134         // code, it is not necessary to generate GC info for a call so labeled.
1135         bool idIsNoGC() const
1136         {
1137             return _idNoGC != 0;
1138         }
1139         void idSetIsNoGC(bool val)
1140         {
1141             _idNoGC = val;
1142         }
1143
1144 #ifdef _TARGET_ARMARCH_
1145         bool idIsLclVar() const
1146         {
1147             return _idLclVar != 0;
1148         }
1149         void idSetIsLclVar()
1150         {
1151             _idLclVar = 1;
1152         }
1153 #endif // _TARGET_ARMARCH_
1154
1155 #if defined(_TARGET_ARM_)
1156         bool idIsLclFPBase() const
1157         {
1158             return _idLclFPBase != 0;
1159         }
1160         void idSetIsLclFPBase()
1161         {
1162             _idLclFPBase = 1;
1163         }
1164 #endif // defined(_TARGET_ARM_)
1165
1166         bool idIsCnsReloc() const
1167         {
1168             return _idCnsReloc != 0;
1169         }
1170         void idSetIsCnsReloc()
1171         {
1172             _idCnsReloc = 1;
1173         }
1174
1175         bool idIsDspReloc() const
1176         {
1177             return _idDspReloc != 0;
1178         }
1179         void idSetIsDspReloc(bool val = true)
1180         {
1181             _idDspReloc = val;
1182         }
1183         bool idIsReloc()
1184         {
1185             return idIsDspReloc() || idIsCnsReloc();
1186         }
1187
1188         unsigned idSmallCns() const
1189         {
1190             return _idSmallCns;
1191         }
1192         void idSmallCns(size_t value)
1193         {
1194             assert(fitsInSmallCns(value));
1195             _idSmallCns = value;
1196         }
1197
1198         inline const idAddrUnion* idAddr() const
1199         {
1200             assert(!idIsSmallDsc());
1201             return &this->_idAddrUnion;
1202         }
1203
1204         inline idAddrUnion* idAddr()
1205         {
1206             assert(!idIsSmallDsc());
1207             return &this->_idAddrUnion;
1208         }
1209     }; // End of  struct instrDesc
1210
1211     void dispIns(instrDesc* id);
1212
1213     void appendToCurIG(instrDesc* id);
1214
1215     /********************************************************************************************/
1216
1217     struct instrDescJmp : instrDesc
1218     {
1219         instrDescJmp* idjNext; // next jump in the group/method
1220         insGroup*     idjIG;   // containing group
1221
1222         union {
1223             BYTE* idjAddr; // address of jump ins (for patching)
1224         } idjTemp;
1225
1226         unsigned idjOffs : 30;    // Before jump emission, this is the byte offset within IG of the jump instruction.
1227                                   // After emission, for forward jumps, this is the target offset -- in bytes from the
1228                                   // beginning of the function -- of the target instruction of the jump, used to
1229                                   // determine if this jump needs to be patched.
1230         unsigned idjShort : 1;    // is the jump known to be a short  one?
1231         unsigned idjKeepLong : 1; // should the jump be kept long? (used for
1232                                   // hot to cold and cold to hot jumps)
1233     };
1234
1235 #if !defined(_TARGET_ARM64_) // This shouldn't be needed for ARM32, either, but I don't want to touch the ARM32 JIT.
1236     struct instrDescLbl : instrDescJmp
1237     {
1238         emitLclVarAddr dstLclVar;
1239     };
1240 #endif // !_TARGET_ARM64_
1241
1242     struct instrDescCns : instrDesc // large const
1243     {
1244         ssize_t idcCnsVal;
1245     };
1246
1247     struct instrDescDsp : instrDesc // large displacement
1248     {
1249         ssize_t iddDspVal;
1250     };
1251
1252     struct instrDescCnsDsp : instrDesc // large cons + disp
1253     {
1254         ssize_t iddcCnsVal;
1255         int     iddcDspVal;
1256     };
1257
1258 #ifdef _TARGET_XARCH_
1259
1260     struct instrDescAmd : instrDesc // large addrmode disp
1261     {
1262         ssize_t idaAmdVal;
1263     };
1264
1265     struct instrDescCnsAmd : instrDesc // large cons + addrmode disp
1266     {
1267         ssize_t idacCnsVal;
1268         ssize_t idacAmdVal;
1269     };
1270
1271 #endif // _TARGET_XARCH_
1272
1273     struct instrDescCGCA : instrDesc // call with ...
1274     {
1275         VARSET_TP idcGCvars;    // ... updated GC vars or
1276         ssize_t   idcDisp;      // ... big addrmode disp
1277         regMaskTP idcGcrefRegs; // ... gcref registers
1278         regMaskTP idcByrefRegs; // ... byref registers
1279         unsigned  idcArgCnt;    // ... lots of args or (<0 ==> caller pops args)
1280
1281 #if MULTIREG_HAS_SECOND_GC_RET
1282         // This method handle the GC-ness of the second register in a 2 register returned struct on System V.
1283         GCtype idSecondGCref() const
1284         {
1285             return (GCtype)_idcSecondRetRegGCType;
1286         }
1287         void idSecondGCref(GCtype gctype)
1288         {
1289             _idcSecondRetRegGCType = gctype;
1290         }
1291
1292     private:
1293         // This member stores the GC-ness of the second register in a 2 register returned struct on System V.
1294         // It is added to the call struct since it is not needed by the base instrDesc struct, which keeps GC-ness
1295         // of the first register for the instCall nodes.
1296         // The base instrDesc is very carefully kept to be no more than 128 bytes. There is no more space to add members
1297         // for keeping GC-ness of the second return registers. It will also bloat the base struct unnecessarily
1298         // since the GC-ness of the second register is only needed for call instructions.
1299         // The base struct's member keeping the GC-ness of the first return register is _idGCref.
1300         GCtype _idcSecondRetRegGCType : 2; // ... GC type for the second return register.
1301 #endif                                     // MULTIREG_HAS_SECOND_GC_RET
1302     };
1303
1304     insUpdateModes emitInsUpdateMode(instruction ins);
1305     insFormat emitInsModeFormat(instruction ins, insFormat base);
1306
1307     static const BYTE emitInsModeFmtTab[];
1308 #ifdef DEBUG
1309     static const unsigned emitInsModeFmtCnt;
1310 #endif
1311
1312     size_t emitGetInstrDescSize(const instrDesc* id);
1313     size_t emitGetInstrDescSizeSC(const instrDesc* id);
1314
1315 #ifdef _TARGET_XARCH_
1316
1317     ssize_t emitGetInsCns(instrDesc* id);
1318     ssize_t emitGetInsDsp(instrDesc* id);
1319     ssize_t emitGetInsAmd(instrDesc* id);
1320
1321     ssize_t emitGetInsCIdisp(instrDesc* id);
1322     unsigned emitGetInsCIargs(instrDesc* id);
1323
1324     // Return the argument count for a direct call "id".
1325     int emitGetInsCDinfo(instrDesc* id);
1326
1327 #endif // _TARGET_XARCH_
1328
1329     ssize_t emitGetInsSC(instrDesc* id);
1330     unsigned emitInsCount;
1331
1332 /************************************************************************/
1333 /*           A few routines used for debug display purposes             */
1334 /************************************************************************/
1335
1336 #if defined(DEBUG) || EMITTER_STATS
1337
1338     static const char* emitIfName(unsigned f);
1339
1340 #endif // defined(DEBUG) || EMITTER_STATS
1341
1342 #ifdef DEBUG
1343
1344     unsigned emitVarRefOffs;
1345
1346     const char* emitRegName(regNumber reg, emitAttr size = EA_PTRSIZE, bool varName = true);
1347     const char* emitFloatRegName(regNumber reg, emitAttr size = EA_PTRSIZE, bool varName = true);
1348
1349     const char* emitFldName(CORINFO_FIELD_HANDLE fieldVal);
1350     const char* emitFncName(CORINFO_METHOD_HANDLE callVal);
1351
1352     void emitDispIGflags(unsigned flags);
1353     void emitDispIG(insGroup* ig, insGroup* igPrev = nullptr, bool verbose = false);
1354     void emitDispIGlist(bool verbose = false);
1355     void emitDispGCinfo();
1356     void emitDispClsVar(CORINFO_FIELD_HANDLE fldHnd, ssize_t offs, bool reloc = false);
1357     void emitDispFrameRef(int varx, int disp, int offs, bool asmfm);
1358     void emitDispInsOffs(unsigned offs, bool doffs);
1359     void emitDispInsHex(BYTE* code, size_t sz);
1360
1361 #else // !DEBUG
1362 #define emitVarRefOffs 0
1363 #endif // !DEBUG
1364
1365     /************************************************************************/
1366     /*                      Method prolog and epilog                        */
1367     /************************************************************************/
1368
1369     unsigned emitPrologEndPos;
1370
1371     unsigned       emitEpilogCnt;
1372     UNATIVE_OFFSET emitEpilogSize;
1373
1374 #ifdef _TARGET_XARCH_
1375
1376     void           emitStartExitSeq(); // Mark the start of the "return" sequence
1377     emitLocation   emitExitSeqBegLoc;
1378     UNATIVE_OFFSET emitExitSeqSize; // minimum size of any return sequence - the 'ret' after the epilog
1379
1380 #endif // _TARGET_XARCH_
1381
1382     insGroup* emitPlaceholderList; // per method placeholder list - head
1383     insGroup* emitPlaceholderLast; // per method placeholder list - tail
1384
1385 #ifdef JIT32_GCENCODER
1386
1387     // The x86 GC encoder needs to iterate over a list of epilogs to generate a table of
1388     // epilog offsets. Epilogs always start at the beginning of an IG, so save the first
1389     // IG of the epilog, and use it to find the epilog offset at the end of code generation.
1390     struct EpilogList
1391     {
1392         EpilogList*  elNext;
1393         emitLocation elLoc;
1394
1395         EpilogList() : elNext(nullptr), elLoc()
1396         {
1397         }
1398     };
1399
1400     EpilogList* emitEpilogList; // per method epilog list - head
1401     EpilogList* emitEpilogLast; // per method epilog list - tail
1402
1403 public:
1404     void emitStartEpilog();
1405
1406     bool emitHasEpilogEnd();
1407
1408     size_t emitGenEpilogLst(size_t (*fp)(void*, unsigned), void* cp);
1409
1410 #endif // JIT32_GCENCODER
1411
1412     void emitBegPrologEpilog(insGroup* igPh);
1413     void emitEndPrologEpilog();
1414
1415     void emitBegFnEpilog(insGroup* igPh);
1416     void emitEndFnEpilog();
1417
1418 #if FEATURE_EH_FUNCLETS
1419
1420     void emitBegFuncletProlog(insGroup* igPh);
1421     void emitEndFuncletProlog();
1422
1423     void emitBegFuncletEpilog(insGroup* igPh);
1424     void emitEndFuncletEpilog();
1425
1426 #endif // FEATURE_EH_FUNCLETS
1427
1428 /************************************************************************/
1429 /*           Members and methods used in PDB translation                */
1430 /************************************************************************/
1431
1432 #ifdef TRANSLATE_PDB
1433
1434     inline void SetIDSource(instrDesc* pID);
1435     void MapCode(int ilOffset, BYTE* imgDest);
1436     void MapFunc(int                imgOff,
1437                  int                procLen,
1438                  int                dbgStart,
1439                  int                dbgEnd,
1440                  short              frameReg,
1441                  int                stkAdjust,
1442                  int                lvaCount,
1443                  OptJit::LclVarDsc* lvaTable,
1444                  bool               framePtr);
1445
1446 private:
1447     int              emitInstrDescILBase; // code offset of IL that produced this instruction desctriptor
1448     int              emitInstrDescILBase; // code offset of IL that produced this instruction desctriptor
1449     static AddrMap*  emitPDBOffsetTable;  // translation table for mapping IL addresses to native addresses
1450     static LocalMap* emitPDBLocalTable;   // local symbol translation table
1451     static bool      emitIsPDBEnabled;    // flag to disable PDB translation code when a PDB is not found
1452     static BYTE*     emitILBaseOfCode;    // start of IL .text section
1453     static BYTE*     emitILMethodBase;    // beginning of IL method (start of header)
1454     static BYTE*     emitILMethodStart;   // beginning of IL method code (right after the header)
1455     static BYTE*     emitImgBaseOfCode;   // start of the image .text section
1456
1457 #endif
1458
1459     /************************************************************************/
1460     /*    Methods to record a code position and later convert to offset     */
1461     /************************************************************************/
1462
1463     unsigned emitFindInsNum(insGroup* ig, instrDesc* id);
1464     UNATIVE_OFFSET emitFindOffset(insGroup* ig, unsigned insNum);
1465
1466 /************************************************************************/
1467 /*        Members and methods used to issue (encode) instructions.      */
1468 /************************************************************************/
1469
1470 #ifdef DEBUG
1471     // If we have started issuing instructions from the list of instrDesc, this is set
1472     bool emitIssuing;
1473 #endif
1474
1475     BYTE* emitCodeBlock;     // Hot code block
1476     BYTE* emitColdCodeBlock; // Cold code block
1477     BYTE* emitConsBlock;     // Read-only (constant) data block
1478
1479     UNATIVE_OFFSET emitTotalHotCodeSize;
1480     UNATIVE_OFFSET emitTotalColdCodeSize;
1481
1482     UNATIVE_OFFSET emitCurCodeOffs(BYTE* dst)
1483     {
1484         size_t distance;
1485         if ((dst >= emitCodeBlock) && (dst <= (emitCodeBlock + emitTotalHotCodeSize)))
1486         {
1487             distance = (dst - emitCodeBlock);
1488         }
1489         else
1490         {
1491             assert(emitFirstColdIG);
1492             assert(emitColdCodeBlock);
1493             assert((dst >= emitColdCodeBlock) && (dst <= (emitColdCodeBlock + emitTotalColdCodeSize)));
1494
1495             distance = (dst - emitColdCodeBlock + emitTotalHotCodeSize);
1496         }
1497         noway_assert((UNATIVE_OFFSET)distance == distance);
1498         return (UNATIVE_OFFSET)distance;
1499     }
1500
1501     BYTE* emitOffsetToPtr(UNATIVE_OFFSET offset)
1502     {
1503         if (offset < emitTotalHotCodeSize)
1504         {
1505             return emitCodeBlock + offset;
1506         }
1507         else
1508         {
1509             assert(offset < (emitTotalHotCodeSize + emitTotalColdCodeSize));
1510
1511             return emitColdCodeBlock + (offset - emitTotalHotCodeSize);
1512         }
1513     }
1514
1515     BYTE* emitDataOffsetToPtr(UNATIVE_OFFSET offset)
1516     {
1517         assert(offset < emitDataSize());
1518         return emitConsBlock + offset;
1519     }
1520
1521     bool emitJumpCrossHotColdBoundary(size_t srcOffset, size_t dstOffset)
1522     {
1523         if (emitTotalColdCodeSize == 0)
1524         {
1525             return false;
1526         }
1527
1528         assert(srcOffset < (emitTotalHotCodeSize + emitTotalColdCodeSize));
1529         assert(dstOffset < (emitTotalHotCodeSize + emitTotalColdCodeSize));
1530
1531         return ((srcOffset < emitTotalHotCodeSize) != (dstOffset < emitTotalHotCodeSize));
1532     }
1533
1534     unsigned char emitOutputByte(BYTE* dst, ssize_t val);
1535     unsigned char emitOutputWord(BYTE* dst, ssize_t val);
1536     unsigned char emitOutputLong(BYTE* dst, ssize_t val);
1537     unsigned char emitOutputSizeT(BYTE* dst, ssize_t val);
1538
1539 #if defined(_TARGET_X86_)
1540     unsigned char emitOutputByte(BYTE* dst, size_t val);
1541     unsigned char emitOutputWord(BYTE* dst, size_t val);
1542     unsigned char emitOutputLong(BYTE* dst, size_t val);
1543     unsigned char emitOutputSizeT(BYTE* dst, size_t val);
1544
1545     unsigned char emitOutputByte(BYTE* dst, unsigned __int64 val);
1546     unsigned char emitOutputWord(BYTE* dst, unsigned __int64 val);
1547     unsigned char emitOutputLong(BYTE* dst, unsigned __int64 val);
1548     unsigned char emitOutputSizeT(BYTE* dst, unsigned __int64 val);
1549 #endif // defined(_TARGET_X86_)
1550
1551     size_t emitIssue1Instr(insGroup* ig, instrDesc* id, BYTE** dp);
1552     size_t emitOutputInstr(insGroup* ig, instrDesc* id, BYTE** dp);
1553
1554     bool emitHasFramePtr;
1555
1556 #ifdef PSEUDORANDOM_NOP_INSERTION
1557     bool emitInInstrumentation;
1558 #endif // PSEUDORANDOM_NOP_INSERTION
1559
1560     unsigned emitMaxTmpSize;
1561
1562 #ifdef DEBUG
1563     bool emitChkAlign; // perform some alignment checks
1564 #endif
1565
1566     insGroup* emitCurIG;
1567
1568     void emitSetShortJump(instrDescJmp* id);
1569     void emitSetMediumJump(instrDescJmp* id);
1570     UNATIVE_OFFSET emitSizeOfJump(instrDescJmp* jmp);
1571     UNATIVE_OFFSET emitInstCodeSz(instrDesc* id);
1572     CORINFO_FIELD_HANDLE emitAnyConst(const void* cnsAddr, unsigned cnsSize, bool dblAlign);
1573     CORINFO_FIELD_HANDLE emitFltOrDblConst(double constValue, emitAttr attr);
1574     regNumber emitInsBinary(instruction ins, emitAttr attr, GenTree* dst, GenTree* src);
1575     regNumber emitInsTernary(instruction ins, emitAttr attr, GenTree* dst, GenTree* src1, GenTree* src2);
1576     void emitInsLoadInd(instruction ins, emitAttr attr, regNumber dstReg, GenTreeIndir* mem);
1577     void emitInsStoreInd(instruction ins, emitAttr attr, GenTreeStoreInd* mem);
1578     void emitInsStoreLcl(instruction ins, emitAttr attr, GenTreeLclVarCommon* varNode);
1579     insFormat emitMapFmtForIns(insFormat fmt, instruction ins);
1580     insFormat emitMapFmtAtoM(insFormat fmt);
1581     void emitHandleMemOp(GenTreeIndir* indir, instrDesc* id, insFormat fmt, instruction ins);
1582     void spillIntArgRegsToShadowSlots();
1583
1584 /************************************************************************/
1585 /*      The logic that creates and keeps track of instruction groups    */
1586 /************************************************************************/
1587
1588 #ifdef _TARGET_ARMARCH_
1589 // The only place where this limited instruction group size is a problem is
1590 // in the prolog, where we only support a single instruction group. We should really fix that.
1591 // ARM32 and ARM64 both can require a bigger prolog instruction group. One scenario is where
1592 // a function uses all the incoming integer and single-precision floating-point arguments,
1593 // and must store them all to the frame on entry. If the frame is very large, we generate
1594 // ugly code like "movw r10, 0x488; add r10, sp; vstr s0, [r10]" for each store, which
1595 // eats up our insGroup buffer.
1596 #define SC_IG_BUFFER_SIZE (100 * sizeof(instrDesc) + 14 * SMALL_IDSC_SIZE)
1597 #else // !_TARGET_ARMARCH_
1598 #define SC_IG_BUFFER_SIZE (50 * sizeof(instrDesc) + 14 * SMALL_IDSC_SIZE)
1599 #endif // !_TARGET_ARMARCH_
1600
1601     size_t emitIGbuffSize;
1602
1603     insGroup* emitIGlist; // first  instruction group
1604     insGroup* emitIGlast; // last   instruction group
1605     insGroup* emitIGthis; // issued instruction group
1606
1607     insGroup* emitPrologIG; // prolog instruction group
1608
1609     instrDescJmp* emitJumpList;       // list of local jumps in method
1610     instrDescJmp* emitJumpLast;       // last of local jumps in method
1611     void          emitJumpDistBind(); // Bind all the local jumps in method
1612
1613     void emitCheckFuncletBranch(instrDesc* jmp, insGroup* jmpIG); // Check for illegal branches between funclets
1614
1615     bool emitFwdJumps;   // forward jumps present?
1616     bool emitNoGCIG;     // Are we generating IGF_NOGCINTERRUPT insGroups (for prologs, epilogs, etc.)
1617     bool emitForceNewIG; // If we generate an instruction, and not another instruction group, force create a new emitAdd
1618                          // instruction group.
1619
1620     BYTE* emitCurIGfreeNext; // next available byte in buffer
1621     BYTE* emitCurIGfreeEndp; // one byte past the last available byte in buffer
1622     BYTE* emitCurIGfreeBase; // first byte address
1623
1624     unsigned       emitCurIGinsCnt;   // # of collected instr's in buffer
1625     unsigned       emitCurIGsize;     // estimated code size of current group in bytes
1626     UNATIVE_OFFSET emitCurCodeOffset; // current code offset within group
1627     UNATIVE_OFFSET emitTotalCodeSize; // bytes of code in entire method
1628
1629     insGroup* emitFirstColdIG; // first cold instruction group
1630
1631     void emitSetFirstColdIGCookie(void* bbEmitCookie)
1632     {
1633         emitFirstColdIG = (insGroup*)bbEmitCookie;
1634     }
1635
1636     int emitOffsAdj; // current code offset adjustment
1637
1638     instrDescJmp* emitCurIGjmpList; // list of jumps   in current IG
1639
1640     // emitPrev* and emitInit* are only used during code generation, not during
1641     // emission (issuing), to determine what GC values to store into an IG.
1642     // Note that only the Vars ones are actually used, apparently due to bugs
1643     // in that tracking. See emitSavIG(): the important use of ByrefRegs is commented
1644     // out, and GCrefRegs is always saved.
1645
1646     VARSET_TP emitPrevGCrefVars;
1647     regMaskTP emitPrevGCrefRegs;
1648     regMaskTP emitPrevByrefRegs;
1649
1650     VARSET_TP emitInitGCrefVars;
1651     regMaskTP emitInitGCrefRegs;
1652     regMaskTP emitInitByrefRegs;
1653
1654     // If this is set, we ignore comparing emitPrev* and emitInit* to determine
1655     // whether to save GC state (to save space in the IG), and always save it.
1656
1657     bool emitForceStoreGCState;
1658
1659     // emitThis* variables are used during emission, to track GC updates
1660     // on a per-instruction basis. During code generation, per-instruction
1661     // tracking is done with variables gcVarPtrSetCur, gcRegGCrefSetCur,
1662     // and gcRegByrefSetCur. However, these are also used for a slightly
1663     // different purpose during code generation: to try to minimize the
1664     // amount of GC data stored to an IG, by only storing deltas from what
1665     // we expect to see at an IG boundary. Also, only emitThisGCrefVars is
1666     // really the only one used; the others seem to be calculated, but not
1667     // used due to bugs.
1668
1669     VARSET_TP emitThisGCrefVars;
1670     regMaskTP emitThisGCrefRegs; // Current set of registers holding GC references
1671     regMaskTP emitThisByrefRegs; // Current set of registers holding BYREF references
1672
1673     bool emitThisGCrefVset; // Is "emitThisGCrefVars" up to date?
1674
1675     regNumber emitSyncThisObjReg; // where is "this" enregistered for synchronized methods?
1676
1677 #if MULTIREG_HAS_SECOND_GC_RET
1678     void emitSetSecondRetRegGCType(instrDescCGCA* id, emitAttr secondRetSize);
1679 #endif // MULTIREG_HAS_SECOND_GC_RET
1680
1681     static void emitEncodeCallGCregs(regMaskTP regs, instrDesc* id);
1682     static unsigned emitDecodeCallGCregs(instrDesc* id);
1683
1684     unsigned emitNxtIGnum;
1685
1686     // random nop insertion to break up nop sleds
1687     unsigned emitNextNop;
1688     bool     emitRandomNops;
1689     void     emitEnableRandomNops()
1690     {
1691         emitRandomNops = true;
1692     }
1693     void emitDisableRandomNops()
1694     {
1695         emitRandomNops = false;
1696     }
1697
1698     insGroup* emitAllocAndLinkIG();
1699     insGroup* emitAllocIG();
1700     void emitInitIG(insGroup* ig);
1701     void emitInsertIGAfter(insGroup* insertAfterIG, insGroup* ig);
1702
1703     void emitNewIG();
1704
1705 #if !defined(JIT32_GCENCODER)
1706     void emitDisableGC();
1707     void emitEnableGC();
1708 #endif // !defined(JIT32_GCENCODER)
1709
1710     void emitGenIG(insGroup* ig);
1711     insGroup* emitSavIG(bool emitAdd = false);
1712     void emitNxtIG(bool emitAdd = false);
1713
1714     bool emitCurIGnonEmpty()
1715     {
1716         return (emitCurIG && emitCurIGfreeNext > emitCurIGfreeBase);
1717     }
1718
1719     instrDesc* emitLastIns;
1720
1721 #ifdef DEBUG
1722     void emitCheckIGoffsets();
1723 #endif
1724
1725     // Terminates any in-progress instruction group, making the current IG a new empty one.
1726     // Mark this instruction group as having a label; return the the new instruction group.
1727     // Sets the emitter's record of the currently live GC variables
1728     // and registers.  The "isFinallyTarget" parameter indicates that the current location is
1729     // the start of a basic block that is returned to after a finally clause in non-exceptional execution.
1730     void* emitAddLabel(VARSET_VALARG_TP GCvars, regMaskTP gcrefRegs, regMaskTP byrefRegs, BOOL isFinallyTarget = FALSE);
1731
1732 #ifdef _TARGET_ARMARCH_
1733
1734     void emitGetInstrDescs(insGroup* ig, instrDesc** id, int* insCnt);
1735
1736     bool emitGetLocationInfo(emitLocation* emitLoc, insGroup** pig, instrDesc** pid, int* pinsRemaining = NULL);
1737
1738     bool emitNextID(insGroup*& ig, instrDesc*& id, int& insRemaining);
1739
1740     typedef void (*emitProcessInstrFunc_t)(instrDesc* id, void* context);
1741
1742     void emitWalkIDs(emitLocation* locFrom, emitProcessInstrFunc_t processFunc, void* context);
1743
1744     static void emitGenerateUnwindNop(instrDesc* id, void* context);
1745
1746 #endif // _TARGET_ARMARCH_
1747
1748 #ifdef _TARGET_X86_
1749     void emitMarkStackLvl(unsigned stackLevel);
1750 #endif
1751
1752     int emitNextRandomNop();
1753
1754     void* emitAllocInstr(size_t sz, emitAttr attr);
1755
1756     instrDesc* emitAllocInstr(emitAttr attr)
1757     {
1758         return (instrDesc*)emitAllocInstr(sizeof(instrDesc), attr);
1759     }
1760
1761     instrDescJmp* emitAllocInstrJmp()
1762     {
1763         return (instrDescJmp*)emitAllocInstr(sizeof(instrDescJmp), EA_1BYTE);
1764     }
1765
1766 #if !defined(_TARGET_ARM64_)
1767     instrDescLbl* emitAllocInstrLbl()
1768     {
1769         return (instrDescLbl*)emitAllocInstr(sizeof(instrDescLbl), EA_4BYTE);
1770     }
1771 #endif // !_TARGET_ARM64_
1772
1773     instrDescCns* emitAllocInstrCns(emitAttr attr)
1774     {
1775         return (instrDescCns*)emitAllocInstr(sizeof(instrDescCns), attr);
1776     }
1777     instrDescCns* emitAllocInstrCns(emitAttr attr, int cns)
1778     {
1779         instrDescCns* result = (instrDescCns*)emitAllocInstr(sizeof(instrDescCns), attr);
1780         result->idSetIsLargeCns();
1781         result->idcCnsVal = cns;
1782         return result;
1783     }
1784
1785     instrDescDsp* emitAllocInstrDsp(emitAttr attr)
1786     {
1787         return (instrDescDsp*)emitAllocInstr(sizeof(instrDescDsp), attr);
1788     }
1789
1790     instrDescCnsDsp* emitAllocInstrCnsDsp(emitAttr attr)
1791     {
1792         return (instrDescCnsDsp*)emitAllocInstr(sizeof(instrDescCnsDsp), attr);
1793     }
1794
1795 #ifdef _TARGET_XARCH_
1796
1797     instrDescAmd* emitAllocInstrAmd(emitAttr attr)
1798     {
1799         return (instrDescAmd*)emitAllocInstr(sizeof(instrDescAmd), attr);
1800     }
1801
1802     instrDescCnsAmd* emitAllocInstrCnsAmd(emitAttr attr)
1803     {
1804         return (instrDescCnsAmd*)emitAllocInstr(sizeof(instrDescCnsAmd), attr);
1805     }
1806
1807 #endif // _TARGET_XARCH_
1808
1809     instrDescCGCA* emitAllocInstrCGCA(emitAttr attr)
1810     {
1811         return (instrDescCGCA*)emitAllocInstr(sizeof(instrDescCGCA), attr);
1812     }
1813
1814     instrDesc* emitNewInstrSmall(emitAttr attr);
1815     instrDesc* emitNewInstr(emitAttr attr = EA_4BYTE);
1816     instrDesc* emitNewInstrSC(emitAttr attr, ssize_t cns);
1817     instrDesc* emitNewInstrCns(emitAttr attr, ssize_t cns);
1818     instrDesc* emitNewInstrDsp(emitAttr attr, ssize_t dsp);
1819     instrDesc* emitNewInstrCnsDsp(emitAttr attr, ssize_t cns, int dsp);
1820     instrDescJmp* emitNewInstrJmp();
1821
1822 #if !defined(_TARGET_ARM64_)
1823     instrDescLbl* emitNewInstrLbl();
1824 #endif // !_TARGET_ARM64_
1825
1826     static const BYTE emitFmtToOps[];
1827
1828 #ifdef DEBUG
1829     static const unsigned emitFmtCount;
1830 #endif
1831
1832     bool emitIsScnsInsDsc(instrDesc* id);
1833
1834     size_t emitSizeOfInsDsc(instrDesc* id);
1835
1836     /************************************************************************/
1837     /*        The following keeps track of stack-based GC values            */
1838     /************************************************************************/
1839
1840     unsigned emitTrkVarCnt;
1841     int*     emitGCrFrameOffsTab; // Offsets of tracked stack ptr vars (varTrkIndex -> stkOffs)
1842
1843     unsigned    emitGCrFrameOffsCnt; // Number of       tracked stack ptr vars
1844     int         emitGCrFrameOffsMin; // Min offset of a tracked stack ptr var
1845     int         emitGCrFrameOffsMax; // Max offset of a tracked stack ptr var
1846     bool        emitContTrkPtrLcls;  // All lcl between emitGCrFrameOffsMin/Max are only tracked stack ptr vars
1847     varPtrDsc** emitGCrFrameLiveTab; // Cache of currently live varPtrs (stkOffs -> varPtrDsc)
1848
1849     int emitArgFrameOffsMin;
1850     int emitArgFrameOffsMax;
1851
1852     int emitLclFrameOffsMin;
1853     int emitLclFrameOffsMax;
1854
1855     int emitSyncThisObjOffs; // what is the offset of "this" for synchronized methods?
1856
1857 public:
1858     void emitSetFrameRangeGCRs(int offsLo, int offsHi);
1859     void emitSetFrameRangeLcls(int offsLo, int offsHi);
1860     void emitSetFrameRangeArgs(int offsLo, int offsHi);
1861
1862     static instruction emitJumpKindToIns(emitJumpKind jumpKind);
1863     static emitJumpKind emitInsToJumpKind(instruction ins);
1864     static emitJumpKind emitReverseJumpKind(emitJumpKind jumpKind);
1865
1866 #ifdef _TARGET_ARM_
1867     static unsigned emitJumpKindCondCode(emitJumpKind jumpKind);
1868 #endif
1869
1870 #ifdef DEBUG
1871     void emitInsSanityCheck(instrDesc* id);
1872 #endif
1873
1874 #ifdef _TARGET_ARMARCH_
1875     // Returns true if instruction "id->idIns()" writes to a register that might be used to contain a GC
1876     // pointer. This exempts the SP and PC registers, and floating point registers. Memory access
1877     // instructions that pre- or post-increment their memory address registers are *not* considered to write
1878     // to GC registers, even if that memory address is a by-ref: such an instruction cannot change the GC
1879     // status of that register, since it must be a byref before and remains one after.
1880     //
1881     // This may return false positives.
1882     bool emitInsMayWriteToGCReg(instrDesc* id);
1883
1884     // Returns "true" if instruction "id->idIns()" writes to a LclVar stack location.
1885     bool emitInsWritesToLclVarStackLoc(instrDesc* id);
1886
1887     // Returns true if the instruction may write to more than one register.
1888     bool emitInsMayWriteMultipleRegs(instrDesc* id);
1889
1890     // Returns "true" if instruction "id->idIns()" writes to a LclVar stack slot pair.
1891     bool emitInsWritesToLclVarStackLocPair(instrDesc* id);
1892 #endif // _TARGET_ARMARCH_
1893
1894     /************************************************************************/
1895     /*    The following is used to distinguish helper vs non-helper calls   */
1896     /************************************************************************/
1897
1898     static bool emitNoGChelper(unsigned IHX);
1899
1900     /************************************************************************/
1901     /*         The following logic keeps track of live GC ref values        */
1902     /************************************************************************/
1903
1904     bool emitFullArgInfo; // full arg info (including non-ptr arg)?
1905     bool emitFullGCinfo;  // full GC pointer maps?
1906     bool emitFullyInt;    // fully interruptible code?
1907
1908 #if EMIT_TRACK_STACK_DEPTH
1909     unsigned emitCntStackDepth; // 0 in prolog/epilog, One DWORD elsewhere
1910     unsigned emitMaxStackDepth; // actual computed max. stack depth
1911 #endif
1912
1913     /* Stack modelling wrt GC */
1914
1915     bool emitSimpleStkUsed; // using the "simple" stack table?
1916
1917     union {
1918         struct // if emitSimpleStkUsed==true
1919         {
1920 #define BITS_IN_BYTE (8)
1921 #define MAX_SIMPLE_STK_DEPTH (BITS_IN_BYTE * sizeof(unsigned))
1922
1923             unsigned emitSimpleStkMask;      // bit per pushed dword (if it fits. Lowest bit <==> last pushed arg)
1924             unsigned emitSimpleByrefStkMask; // byref qualifier for emitSimpleStkMask
1925         } u1;
1926
1927         struct // if emitSimpleStkUsed==false
1928         {
1929             BYTE   emitArgTrackLcl[16]; // small local table to avoid malloc
1930             BYTE*  emitArgTrackTab;     // base of the argument tracking stack
1931             BYTE*  emitArgTrackTop;     // top  of the argument tracking stack
1932             USHORT emitGcArgTrackCnt;   // count of pending arg records (stk-depth for frameless methods, gc ptrs on stk
1933                                         // for framed methods)
1934         } u2;
1935     };
1936
1937     unsigned emitCurStackLvl; // amount of bytes pushed on stack
1938
1939 #if EMIT_TRACK_STACK_DEPTH
1940     /* Functions for stack tracking */
1941
1942     void emitStackPush(BYTE* addr, GCtype gcType);
1943
1944     void emitStackPushN(BYTE* addr, unsigned count);
1945
1946     void emitStackPop(BYTE* addr, bool isCall, unsigned char callInstrSize, unsigned count = 1);
1947
1948     void emitStackKillArgs(BYTE* addr, unsigned count, unsigned char callInstrSize);
1949
1950     void emitRecordGCcall(BYTE* codePos, unsigned char callInstrSize);
1951
1952     // Helpers for the above
1953
1954     void emitStackPushLargeStk(BYTE* addr, GCtype gcType, unsigned count = 1);
1955     void emitStackPopLargeStk(BYTE* addr, bool isCall, unsigned char callInstrSize, unsigned count = 1);
1956 #endif // EMIT_TRACK_STACK_DEPTH
1957
1958     /* Liveness of stack variables, and registers */
1959
1960     void emitUpdateLiveGCvars(int offs, BYTE* addr, bool birth);
1961     void emitUpdateLiveGCvars(VARSET_VALARG_TP vars, BYTE* addr);
1962     void emitUpdateLiveGCregs(GCtype gcType, regMaskTP regs, BYTE* addr);
1963
1964 #ifdef DEBUG
1965     const char* emitGetFrameReg();
1966     void emitDispRegSet(regMaskTP regs);
1967     void emitDispVarSet();
1968 #endif
1969
1970     void emitGCregLiveUpd(GCtype gcType, regNumber reg, BYTE* addr);
1971     void emitGCregLiveSet(GCtype gcType, regMaskTP mask, BYTE* addr, bool isThis);
1972     void emitGCregDeadUpdMask(regMaskTP, BYTE* addr);
1973     void emitGCregDeadUpd(regNumber reg, BYTE* addr);
1974     void emitGCregDeadSet(GCtype gcType, regMaskTP mask, BYTE* addr);
1975
1976     void emitGCvarLiveUpd(int offs, int varNum, GCtype gcType, BYTE* addr);
1977     void emitGCvarLiveSet(int offs, GCtype gcType, BYTE* addr, ssize_t disp = -1);
1978     void emitGCvarDeadUpd(int offs, BYTE* addr);
1979     void emitGCvarDeadSet(int offs, BYTE* addr, ssize_t disp = -1);
1980
1981     GCtype emitRegGCtype(regNumber reg);
1982
1983     // We have a mixture of code emission methods, some of which return the size of the emitted instruction,
1984     // requiring the caller to add this to the current code pointer (dst += <call to emit code>), others of which
1985     // return the updated code pointer (dst = <call to emit code>).  Sometimes we'd like to get the size of
1986     // the generated instruction for the latter style.  This method accomplishes that --
1987     // "emitCodeWithInstructionSize(dst, <call to emitCode>, &instrSize)" will do the call, and set
1988     // "*instrSize" to the after-before code pointer difference.  Returns the result of the call.  (And
1989     // asserts that the instruction size fits in an unsigned char.)
1990     static BYTE* emitCodeWithInstructionSize(BYTE* codePtrBefore, BYTE* newCodePointer, unsigned char* instrSize);
1991
1992     /************************************************************************/
1993     /*      The following logic keeps track of initialized data sections    */
1994     /************************************************************************/
1995
1996     /* One of these is allocated for every blob of initialized data */
1997
1998     struct dataSection
1999     {
2000         enum sectionType
2001         {
2002             data,
2003             blockAbsoluteAddr,
2004             blockRelative32
2005         };
2006
2007         dataSection*   dsNext;
2008         UNATIVE_OFFSET dsSize;
2009         sectionType    dsType;
2010         // variable-sized array used to store the constant data
2011         // or BasicBlock* array in the block cases.
2012         BYTE dsCont[0];
2013     };
2014
2015     /* These describe the entire initialized/uninitialized data sections */
2016
2017     struct dataSecDsc
2018     {
2019         dataSection*   dsdList;
2020         dataSection*   dsdLast;
2021         UNATIVE_OFFSET dsdOffs;
2022     };
2023
2024     dataSecDsc emitConsDsc;
2025
2026     dataSection* emitDataSecCur;
2027
2028     void emitOutputDataSec(dataSecDsc* sec, BYTE* dst);
2029
2030     /************************************************************************/
2031     /*              Handles to the current class and method.                */
2032     /************************************************************************/
2033
2034     COMP_HANDLE emitCmpHandle;
2035
2036     /************************************************************************/
2037     /*               Helpers for interface to EE                            */
2038     /************************************************************************/
2039
2040     void emitRecordRelocation(void* location,       /* IN */
2041                               void* target,         /* IN */
2042                               WORD  fRelocType,     /* IN */
2043                               WORD  slotNum   = 0,  /* IN */
2044                               INT32 addlDelta = 0); /* IN */
2045
2046 #ifdef _TARGET_ARM_
2047     void emitHandlePCRelativeMov32(void* location, /* IN */
2048                                    void* target);  /* IN */
2049 #endif
2050
2051     void emitRecordCallSite(ULONG                 instrOffset,   /* IN */
2052                             CORINFO_SIG_INFO*     callSig,       /* IN */
2053                             CORINFO_METHOD_HANDLE methodHandle); /* IN */
2054
2055 #ifdef DEBUG
2056     // This is a scratch buffer used to minimize the number of sig info structs
2057     // we have to allocate for recordCallSite.
2058     CORINFO_SIG_INFO* emitScratchSigInfo;
2059 #endif // DEBUG
2060
2061 /************************************************************************/
2062 /*               Logic to collect and display statistics                */
2063 /************************************************************************/
2064
2065 #if EMITTER_STATS
2066
2067     friend void emitterStats(FILE* fout);
2068     friend void emitterStaticStats(FILE* fout);
2069
2070     static size_t emitSizeMethod;
2071
2072     static unsigned emitTotalInsCnt;
2073
2074     static unsigned emitTotalIGcnt;   // total number of insGroup allocated
2075     static unsigned emitTotalPhIGcnt; // total number of insPlaceholderGroupData allocated
2076     static unsigned emitTotalIGicnt;
2077     static size_t   emitTotalIGsize;
2078     static unsigned emitTotalIGmcnt; // total method count
2079     static unsigned emitTotalIGjmps;
2080     static unsigned emitTotalIGptrs;
2081
2082     static size_t emitTotMemAlloc;
2083
2084     static unsigned emitSmallDspCnt;
2085     static unsigned emitLargeDspCnt;
2086
2087     static unsigned emitSmallCnsCnt;
2088 #define SMALL_CNS_TSZ 256
2089     static unsigned emitSmallCns[SMALL_CNS_TSZ];
2090     static unsigned emitLargeCnsCnt;
2091
2092     static unsigned emitIFcounts[IF_COUNT];
2093
2094 #endif // EMITTER_STATS
2095
2096 /*************************************************************************
2097  *
2098  *  Define any target-dependent emitter members.
2099  */
2100
2101 #include "emitdef.h"
2102
2103     // It would be better if this were a constructor, but that would entail revamping the allocation
2104     // infrastructure of the entire JIT...
2105     void Init()
2106     {
2107         VarSetOps::AssignNoCopy(emitComp, emitPrevGCrefVars, VarSetOps::MakeEmpty(emitComp));
2108         VarSetOps::AssignNoCopy(emitComp, emitInitGCrefVars, VarSetOps::MakeEmpty(emitComp));
2109         VarSetOps::AssignNoCopy(emitComp, emitThisGCrefVars, VarSetOps::MakeEmpty(emitComp));
2110     }
2111 };
2112
2113 /*****************************************************************************
2114  *
2115  *  Define any target-dependent inlines.
2116  */
2117
2118 #include "emitinl.h"
2119
2120 inline void emitter::instrDesc::checkSizes()
2121 {
2122 #ifdef DEBUG
2123     C_ASSERT(SMALL_IDSC_SIZE == (offsetof(instrDesc, _idDebugOnlyInfo) + sizeof(instrDescDebugInfo*)));
2124 #endif
2125     C_ASSERT(SMALL_IDSC_SIZE == offsetof(instrDesc, _idAddrUnion));
2126 }
2127
2128 /*****************************************************************************
2129  *
2130  *  Returns true if the given instruction descriptor is a "small
2131  *  constant" one (i.e. one of the descriptors that don't have all instrDesc
2132  *  fields allocated).
2133  */
2134
2135 inline bool emitter::emitIsScnsInsDsc(instrDesc* id)
2136 {
2137     return id->idIsSmallDsc();
2138 }
2139
2140 /*****************************************************************************
2141  *
2142  *  Given an instruction, return its "update mode" (RD/WR/RW).
2143  */
2144
2145 inline insUpdateModes emitter::emitInsUpdateMode(instruction ins)
2146 {
2147 #ifdef DEBUG
2148     assert((unsigned)ins < emitInsModeFmtCnt);
2149 #endif
2150     return (insUpdateModes)emitInsModeFmtTab[ins];
2151 }
2152
2153 /*****************************************************************************
2154  *
2155  *  Return the number of epilog blocks generated so far.
2156  */
2157
2158 inline unsigned emitter::emitGetEpilogCnt()
2159 {
2160     return emitEpilogCnt;
2161 }
2162
2163 /*****************************************************************************
2164  *
2165  *  Return the current size of the specified data section.
2166  */
2167
2168 inline UNATIVE_OFFSET emitter::emitDataSize()
2169 {
2170     return emitConsDsc.dsdOffs;
2171 }
2172
2173 /*****************************************************************************
2174  *
2175  *  Return a handle to the current position in the output stream. This can
2176  *  be later converted to an actual code offset in bytes.
2177  */
2178
2179 inline void* emitter::emitCurBlock()
2180 {
2181     return emitCurIG;
2182 }
2183
2184 /*****************************************************************************
2185  *
2186  *  The emitCurOffset() method returns a cookie that identifies the current
2187  *  position in the instruction stream. Due to things like scheduling (and
2188  *  the fact that the final size of some instructions cannot be known until
2189  *  the end of code generation), we return a value with the instruction number
2190  *  and its estimated offset to the caller.
2191  */
2192
2193 inline unsigned emitGetInsNumFromCodePos(unsigned codePos)
2194 {
2195     return (codePos & 0xFFFF);
2196 }
2197
2198 inline unsigned emitGetInsOfsFromCodePos(unsigned codePos)
2199 {
2200     return (codePos >> 16);
2201 }
2202
2203 inline unsigned emitter::emitCurOffset()
2204 {
2205     unsigned codePos = emitCurIGinsCnt + (emitCurIGsize << 16);
2206
2207     assert(emitGetInsOfsFromCodePos(codePos) == emitCurIGsize);
2208     assert(emitGetInsNumFromCodePos(codePos) == emitCurIGinsCnt);
2209
2210     // printf("[IG=%02u;ID=%03u;OF=%04X] => %08X\n", emitCurIG->igNum, emitCurIGinsCnt, emitCurIGsize, codePos);
2211
2212     return codePos;
2213 }
2214
2215 extern const unsigned short emitTypeSizes[TYP_COUNT];
2216
2217 template <class T>
2218 inline emitAttr emitTypeSize(T type)
2219 {
2220     assert(TypeGet(type) < TYP_COUNT);
2221     assert(emitTypeSizes[TypeGet(type)] > 0);
2222     return (emitAttr)emitTypeSizes[TypeGet(type)];
2223 }
2224
2225 extern const unsigned short emitTypeActSz[TYP_COUNT];
2226
2227 template <class T>
2228 inline emitAttr emitActualTypeSize(T type)
2229 {
2230     assert(TypeGet(type) < TYP_COUNT);
2231     assert(emitTypeActSz[TypeGet(type)] > 0);
2232     return (emitAttr)emitTypeActSz[TypeGet(type)];
2233 }
2234
2235 /*****************************************************************************
2236  *
2237  *  Convert between an operand size in bytes and a smaller encoding used for
2238  *  storage in instruction descriptors.
2239  */
2240
2241 /* static */ inline emitter::opSize emitter::emitEncodeSize(emitAttr size)
2242 {
2243     assert(size == EA_1BYTE || size == EA_2BYTE || size == EA_4BYTE || size == EA_8BYTE || size == EA_16BYTE ||
2244            size == EA_32BYTE);
2245
2246     return emitSizeEncode[((int)size) - 1];
2247 }
2248
2249 /* static */ inline emitAttr emitter::emitDecodeSize(emitter::opSize ensz)
2250 {
2251     assert(((unsigned)ensz) < OPSZ_COUNT);
2252
2253     return emitSizeDecode[ensz];
2254 }
2255
2256 /*****************************************************************************
2257  *
2258  *  Little helpers to allocate various flavors of instructions.
2259  */
2260
2261 inline emitter::instrDesc* emitter::emitNewInstrSmall(emitAttr attr)
2262 {
2263     instrDesc* id;
2264
2265     // This is larger than the Tiny Descr
2266     id = (instrDesc*)emitAllocInstr(SMALL_IDSC_SIZE, attr);
2267     id->idSetIsSmallDsc();
2268
2269     return id;
2270 }
2271
2272 inline emitter::instrDesc* emitter::emitNewInstr(emitAttr attr)
2273 {
2274     // This is larger than the Small Descr
2275     return emitAllocInstr(attr);
2276 }
2277
2278 inline emitter::instrDescJmp* emitter::emitNewInstrJmp()
2279 {
2280     return emitAllocInstrJmp();
2281 }
2282
2283 #if !defined(_TARGET_ARM64_)
2284 inline emitter::instrDescLbl* emitter::emitNewInstrLbl()
2285 {
2286     return emitAllocInstrLbl();
2287 }
2288 #endif // !_TARGET_ARM64_
2289
2290 inline emitter::instrDesc* emitter::emitNewInstrDsp(emitAttr attr, ssize_t dsp)
2291 {
2292     if (dsp == 0)
2293     {
2294         instrDesc* id = emitAllocInstr(attr);
2295
2296 #if EMITTER_STATS
2297         emitSmallDspCnt++;
2298 #endif
2299
2300         return id;
2301     }
2302     else
2303     {
2304         instrDescDsp* id = emitAllocInstrDsp(attr);
2305
2306         id->idSetIsLargeDsp();
2307         id->iddDspVal = dsp;
2308
2309 #if EMITTER_STATS
2310         emitLargeDspCnt++;
2311 #endif
2312
2313         return id;
2314     }
2315 }
2316
2317 /*****************************************************************************
2318  *
2319  *  Allocate an instruction descriptor for an instruction with a constant operand.
2320  *  The instruction descriptor uses the idAddrUnion to save additional info
2321  *  so the smallest size that this can be is sizeof(instrDesc).
2322  *  Note that this very similar to emitter::emitNewInstrSC(), except it never
2323  *  allocates a small descriptor.
2324  */
2325 inline emitter::instrDesc* emitter::emitNewInstrCns(emitAttr attr, ssize_t cns)
2326 {
2327     if (instrDesc::fitsInSmallCns(cns))
2328     {
2329         instrDesc* id = emitAllocInstr(attr);
2330
2331         id->idSmallCns(cns);
2332
2333 #if EMITTER_STATS
2334         emitSmallCnsCnt++;
2335         if (cns - ID_MIN_SMALL_CNS >= SMALL_CNS_TSZ)
2336             emitSmallCns[SMALL_CNS_TSZ - 1]++;
2337         else
2338             emitSmallCns[cns - ID_MIN_SMALL_CNS]++;
2339 #endif
2340
2341         return id;
2342     }
2343     else
2344     {
2345         instrDescCns* id = emitAllocInstrCns(attr);
2346
2347         id->idSetIsLargeCns();
2348         id->idcCnsVal = cns;
2349
2350 #if EMITTER_STATS
2351         emitLargeCnsCnt++;
2352 #endif
2353
2354         return id;
2355     }
2356 }
2357
2358 /*****************************************************************************
2359  *
2360  *  Get the instrDesc size, general purpose version
2361  *
2362  */
2363
2364 inline size_t emitter::emitGetInstrDescSize(const instrDesc* id)
2365 {
2366     if (id->idIsSmallDsc())
2367     {
2368         return SMALL_IDSC_SIZE;
2369     }
2370
2371     if (id->idIsLargeCns())
2372     {
2373         return sizeof(instrDescCns);
2374     }
2375
2376     return sizeof(instrDesc);
2377 }
2378
2379 /*****************************************************************************
2380  *
2381  *  Allocate an instruction descriptor for an instruction with a small integer
2382  *  constant operand. This is the same as emitNewInstrCns() except that here
2383  *  any constant that is small enough for instrDesc::fitsInSmallCns() only gets
2384  *  allocated SMALL_IDSC_SIZE bytes (and is thus a small descriptor, whereas
2385  *  emitNewInstrCns() always allocates at least sizeof(instrDesc).
2386  */
2387
2388 inline emitter::instrDesc* emitter::emitNewInstrSC(emitAttr attr, ssize_t cns)
2389 {
2390     instrDesc* id;
2391
2392     if (instrDesc::fitsInSmallCns(cns))
2393     {
2394         id = (instrDesc*)emitAllocInstr(SMALL_IDSC_SIZE, attr);
2395
2396         id->idSmallCns(cns);
2397         id->idSetIsSmallDsc();
2398     }
2399     else
2400     {
2401         id = (instrDesc*)emitAllocInstr(sizeof(instrDescCns), attr);
2402
2403         id->idSetIsLargeCns();
2404         ((instrDescCns*)id)->idcCnsVal = cns;
2405     }
2406
2407     return id;
2408 }
2409
2410 /*****************************************************************************
2411  *
2412  *  Get the instrDesc size for something that contains a constant
2413  */
2414
2415 inline size_t emitter::emitGetInstrDescSizeSC(const instrDesc* id)
2416 {
2417     if (id->idIsSmallDsc())
2418     {
2419         return SMALL_IDSC_SIZE;
2420     }
2421     else if (id->idIsLargeCns())
2422     {
2423         return sizeof(instrDescCns);
2424     }
2425     else
2426     {
2427         return sizeof(instrDesc);
2428     }
2429 }
2430
2431 #ifdef _TARGET_XARCH_
2432
2433 /*****************************************************************************
2434  *
2435  *  The following helpers should be used to access the various values that
2436  *  get stored in different places within the instruction descriptor.
2437  */
2438
2439 inline ssize_t emitter::emitGetInsCns(instrDesc* id)
2440 {
2441     return id->idIsLargeCns() ? ((instrDescCns*)id)->idcCnsVal : id->idSmallCns();
2442 }
2443
2444 inline ssize_t emitter::emitGetInsDsp(instrDesc* id)
2445 {
2446     if (id->idIsLargeDsp())
2447     {
2448         if (id->idIsLargeCns())
2449         {
2450             return ((instrDescCnsDsp*)id)->iddcDspVal;
2451         }
2452         return ((instrDescDsp*)id)->iddDspVal;
2453     }
2454     return 0;
2455 }
2456
2457 /*****************************************************************************
2458  *
2459  *  Get hold of the argument count for an indirect call.
2460  */
2461
2462 inline unsigned emitter::emitGetInsCIargs(instrDesc* id)
2463 {
2464     if (id->idIsLargeCall())
2465     {
2466         return ((instrDescCGCA*)id)->idcArgCnt;
2467     }
2468     else
2469     {
2470         assert(id->idIsLargeDsp() == false);
2471         assert(id->idIsLargeCns() == false);
2472
2473         ssize_t cns = emitGetInsCns(id);
2474         assert((unsigned)cns == (size_t)cns);
2475         return (unsigned)cns;
2476     }
2477 }
2478
2479 #endif // _TARGET_XARCH_
2480
2481 /*****************************************************************************
2482  *
2483  *  Returns true if the given register contains a live GC ref.
2484  */
2485
2486 inline GCtype emitter::emitRegGCtype(regNumber reg)
2487 {
2488     assert(emitIssuing);
2489
2490     if ((emitThisGCrefRegs & genRegMask(reg)) != 0)
2491     {
2492         return GCT_GCREF;
2493     }
2494     else if ((emitThisByrefRegs & genRegMask(reg)) != 0)
2495     {
2496         return GCT_BYREF;
2497     }
2498     else
2499     {
2500         return GCT_NONE;
2501     }
2502 }
2503
2504 #ifdef DEBUG
2505
2506 #if EMIT_TRACK_STACK_DEPTH
2507 #define CHECK_STACK_DEPTH() assert((int)emitCurStackLvl >= 0)
2508 #else
2509 #define CHECK_STACK_DEPTH()
2510 #endif
2511
2512 #endif // DEBUG
2513
2514 /*****************************************************************************
2515  *
2516  *  Return true when a given code offset is properly aligned for the target
2517  */
2518
2519 inline bool IsCodeAligned(UNATIVE_OFFSET offset)
2520 {
2521     return ((offset & (CODE_ALIGN - 1)) == 0);
2522 }
2523
2524 // Static:
2525 inline BYTE* emitter::emitCodeWithInstructionSize(BYTE* codePtrBefore, BYTE* newCodePointer, unsigned char* instrSize)
2526 {
2527     // DLD: Perhaps this method should return the instruction size, and we should do dst += <that size>
2528     // as is done in other cases?
2529     assert(newCodePointer >= codePtrBefore);
2530     ClrSafeInt<unsigned char> callInstrSizeSafe = ClrSafeInt<unsigned char>(newCodePointer - codePtrBefore);
2531     assert(!callInstrSizeSafe.IsOverflow());
2532     *instrSize = callInstrSizeSafe.Value();
2533     return newCodePointer;
2534 }
2535
2536 /*****************************************************************************
2537  *
2538  *  Add a new IG to the current list, and get it ready to receive code.
2539  */
2540
2541 inline void emitter::emitNewIG()
2542 {
2543     insGroup* ig = emitAllocAndLinkIG();
2544
2545     /* It's linked in. Now, set it up to accept code */
2546
2547     emitGenIG(ig);
2548 }
2549
2550 #if !defined(JIT32_GCENCODER)
2551 // Start a new instruction group that is not interruptable
2552 inline void emitter::emitDisableGC()
2553 {
2554     emitNoGCIG = true;
2555
2556     if (emitCurIGnonEmpty())
2557     {
2558         emitNxtIG(true);
2559     }
2560     else
2561     {
2562         emitCurIG->igFlags |= IGF_NOGCINTERRUPT;
2563     }
2564 }
2565
2566 // Start a new instruction group that is interruptable
2567 inline void emitter::emitEnableGC()
2568 {
2569     emitNoGCIG = false;
2570
2571     // The next time an instruction needs to be generated, force a new instruction group.
2572     // It will be an emitAdd group in that case. Note that the next thing we see might be
2573     // a label, which will force a non-emitAdd group.
2574     //
2575     // Note that we can't just create a new instruction group here, because we don't know
2576     // if there are going to be any instructions added to it, and we don't support empty
2577     // instruction groups.
2578     emitForceNewIG = true;
2579 }
2580 #endif // !defined(JIT32_GCENCODER)
2581
2582 /*****************************************************************************/
2583 #endif // _EMIT_H_
2584 /*****************************************************************************/