Merge pull request #14588 from hqueue/arm/ryujit/issue_14374_pr1
[platform/upstream/coreclr.git] / src / jit / emit.cpp
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4
5 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7 XX                                                                           XX
8 XX                              emit.cpp                                     XX
9 XX                                                                           XX
10 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
11 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
12 */
13
14 #include "jitpch.h"
15 #ifdef _MSC_VER
16 #pragma hdrstop
17 #endif
18
19 #include "hostallocator.h"
20 #include "instr.h"
21 #include "emit.h"
22 #include "codegen.h"
23
24 /*****************************************************************************
25  *
26  *  Represent an emitter location.
27  */
28
29 void emitLocation::CaptureLocation(emitter* emit)
30 {
31     ig      = emit->emitCurIG;
32     codePos = emit->emitCurOffset();
33
34     assert(Valid());
35 }
36
37 bool emitLocation::IsCurrentLocation(emitter* emit) const
38 {
39     assert(Valid());
40     return (ig == emit->emitCurIG) && (codePos == emit->emitCurOffset());
41 }
42
43 UNATIVE_OFFSET emitLocation::CodeOffset(emitter* emit) const
44 {
45     assert(Valid());
46     return emit->emitCodeOffset(ig, codePos);
47 }
48
49 int emitLocation::GetInsNum() const
50 {
51     return emitGetInsNumFromCodePos(codePos);
52 }
53
54 #ifdef _TARGET_AMD64_
55 // Get the instruction offset in the current instruction group, which must be a funclet prolog group.
56 // This is used to find an instruction offset used in unwind data.
57 // TODO-AMD64-Bug?: We only support a single main function prolog group, but allow for multiple funclet prolog
58 // groups (not that we actually use that flexibility, since the funclet prolog will be small). How to
59 // handle that?
60 UNATIVE_OFFSET emitLocation::GetFuncletPrologOffset(emitter* emit) const
61 {
62     assert(ig->igFuncIdx != 0);
63     assert((ig->igFlags & IGF_FUNCLET_PROLOG) != 0);
64     assert(ig == emit->emitCurIG);
65
66     return emit->emitCurIGsize;
67 }
68 #endif // _TARGET_AMD64_
69
70 #ifdef DEBUG
71 void emitLocation::Print() const
72 {
73     unsigned insNum = emitGetInsNumFromCodePos(codePos);
74     unsigned insOfs = emitGetInsOfsFromCodePos(codePos);
75     printf("(G_M%03u_IG%02u,ins#%d,ofs#%d)", Compiler::s_compMethodsCount, ig->igNum, insNum, insOfs);
76 }
77 #endif // DEBUG
78
79 /*****************************************************************************
80  *
81  *  Return the name of an instruction format.
82  */
83
84 #if defined(DEBUG) || EMITTER_STATS
85
86 const char* emitter::emitIfName(unsigned f)
87 {
88     static const char* const ifNames[] = {
89 #define IF_DEF(en, op1, op2) "IF_" #en,
90 #include "emitfmts.h"
91     };
92
93     static char errBuff[32];
94
95     if (f < sizeof(ifNames) / sizeof(*ifNames))
96     {
97         return ifNames[f];
98     }
99
100     sprintf_s(errBuff, sizeof(errBuff), "??%u??", f);
101     return errBuff;
102 }
103
104 #endif
105
106 #ifdef TRANSLATE_PDB
107
108 /* these are protected */
109
110 AddrMap*  emitter::emitPDBOffsetTable = 0;
111 LocalMap* emitter::emitPDBLocalTable  = 0;
112 bool      emitter::emitIsPDBEnabled   = true;
113 BYTE*     emitter::emitILBaseOfCode   = 0;
114 BYTE*     emitter::emitILMethodBase   = 0;
115 BYTE*     emitter::emitILMethodStart  = 0;
116 BYTE*     emitter::emitImgBaseOfCode  = 0;
117
118 void emitter::MapCode(int ilOffset, BYTE* imgDest)
119 {
120     if (emitIsPDBEnabled)
121     {
122         emitPDBOffsetTable->MapSrcToDest(ilOffset, (int)(imgDest - emitImgBaseOfCode));
123     }
124 }
125
126 void emitter::MapFunc(int                imgOff,
127                       int                procLen,
128                       int                dbgStart,
129                       int                dbgEnd,
130                       short              frameReg,
131                       int                stkAdjust,
132                       int                lvaCount,
133                       OptJit::LclVarDsc* lvaTable,
134                       bool               framePtr)
135 {
136     if (emitIsPDBEnabled)
137     {
138         // this code stores information about local symbols for the PDB translation
139
140         assert(lvaCount >= 0); // don't allow a negative count
141
142         LvaDesc* rgLvaDesc = 0;
143
144         if (lvaCount > 0)
145         {
146             rgLvaDesc = new LvaDesc[lvaCount];
147
148             if (!rgLvaDesc)
149             {
150                 NOMEM();
151             }
152
153             LvaDesc*           pDst = rgLvaDesc;
154             OptJit::LclVarDsc* pSrc = lvaTable;
155             for (int i = 0; i < lvaCount; ++i, ++pDst, ++pSrc)
156             {
157                 pDst->slotNum = pSrc->lvSlotNum;
158                 pDst->isReg   = pSrc->lvRegister;
159                 pDst->reg     = (pSrc->lvRegister ? pSrc->lvRegNum : frameReg);
160                 pDst->off     = pSrc->lvStkOffs + stkAdjust;
161             }
162         }
163
164         emitPDBLocalTable->AddFunc((int)(emitILMethodBase - emitILBaseOfCode), imgOff - (int)emitImgBaseOfCode, procLen,
165                                    dbgStart - imgOff, dbgEnd - imgOff, lvaCount, rgLvaDesc, framePtr);
166         // do not delete rgLvaDesc here -- responsibility is now on emitPDBLocalTable destructor
167     }
168 }
169
170 /* these are public */
171
172 void emitter::SetILBaseOfCode(BYTE* pTextBase)
173 {
174     emitILBaseOfCode = pTextBase;
175 }
176
177 void emitter::SetILMethodBase(BYTE* pMethodEntry)
178 {
179     emitILMethodBase = pMethodEntry;
180 }
181
182 void emitter::SetILMethodStart(BYTE* pMethodCode)
183 {
184     emitILMethodStart = pMethodCode;
185 }
186
187 void emitter::SetImgBaseOfCode(BYTE* pTextBase)
188 {
189     emitImgBaseOfCode = pTextBase;
190 }
191
192 void emitter::SetIDBaseToProlog()
193 {
194     emitInstrDescILBase = (int)(emitILMethodBase - emitILBaseOfCode);
195 }
196
197 void emitter::SetIDBaseToOffset(int methodOffset)
198 {
199     emitInstrDescILBase = methodOffset + (int)(emitILMethodStart - emitILBaseOfCode);
200 }
201
202 void emitter::DisablePDBTranslation()
203 {
204     // this function should disable PDB translation code
205     emitIsPDBEnabled = false;
206 }
207
208 bool emitter::IsPDBEnabled()
209 {
210     return emitIsPDBEnabled;
211 }
212
213 void emitter::InitTranslationMaps(int ilCodeSize)
214 {
215     if (emitIsPDBEnabled)
216     {
217         emitPDBOffsetTable = AddrMap::Create(ilCodeSize);
218         emitPDBLocalTable  = LocalMap::Create();
219     }
220 }
221
222 void emitter::DeleteTranslationMaps()
223 {
224     if (emitPDBOffsetTable)
225     {
226         delete emitPDBOffsetTable;
227         emitPDBOffsetTable = 0;
228     }
229     if (emitPDBLocalTable)
230     {
231         delete emitPDBLocalTable;
232         emitPDBLocalTable = 0;
233     }
234 }
235
236 void emitter::InitTranslator(PDBRewriter* pPDB, int* rgSecMap, IMAGE_SECTION_HEADER** rgpHeader, int numSections)
237 {
238     if (emitIsPDBEnabled)
239     {
240         pPDB->InitMaps(rgSecMap,           // new PE section header order
241                        rgpHeader,          // array of section headers
242                        numSections,        // number of sections
243                        emitPDBOffsetTable, // code offset translation table
244                        emitPDBLocalTable); // slot variable translation table
245     }
246 }
247
248 #endif // TRANSLATE_PDB
249
250 /*****************************************************************************/
251
252 #if EMITTER_STATS
253
254 static unsigned totAllocdSize;
255 static unsigned totActualSize;
256
257 unsigned emitter::emitIFcounts[emitter::IF_COUNT];
258
259 static unsigned  emitSizeBuckets[] = {100, 1024 * 1, 1024 * 2, 1024 * 3, 1024 * 4, 1024 * 5, 1024 * 10, 0};
260 static Histogram emitSizeTable(HostAllocator::getHostAllocator(), emitSizeBuckets);
261
262 static unsigned  GCrefsBuckets[] = {0, 1, 2, 5, 10, 20, 50, 128, 256, 512, 1024, 0};
263 static Histogram GCrefsTable(HostAllocator::getHostAllocator(), GCrefsBuckets);
264
265 static unsigned  stkDepthBuckets[] = {0, 1, 2, 5, 10, 16, 32, 128, 1024, 0};
266 static Histogram stkDepthTable(HostAllocator::getHostAllocator(), stkDepthBuckets);
267
268 size_t emitter::emitSizeMethod;
269
270 size_t   emitter::emitTotMemAlloc;
271 unsigned emitter::emitTotalInsCnt;
272 unsigned emitter::emitTotalIGcnt;
273 unsigned emitter::emitTotalPhIGcnt;
274 unsigned emitter::emitTotalIGjmps;
275 unsigned emitter::emitTotalIGptrs;
276 unsigned emitter::emitTotalIGicnt;
277 size_t   emitter::emitTotalIGsize;
278 unsigned emitter::emitTotalIGmcnt;
279
280 unsigned emitter::emitSmallDspCnt;
281 unsigned emitter::emitLargeDspCnt;
282
283 unsigned emitter::emitSmallCnsCnt;
284 unsigned emitter::emitLargeCnsCnt;
285 unsigned emitter::emitSmallCns[SMALL_CNS_TSZ];
286
287 void emitterStaticStats(FILE* fout)
288 {
289     // insGroup members
290
291     fprintf(fout, "\n");
292     fprintf(fout, "insGroup:\n");
293     fprintf(fout, "Offset of igNext              = %2u\n", offsetof(insGroup, igNext));
294 #ifdef DEBUG
295     fprintf(fout, "Offset of igSelf              = %2u\n", offsetof(insGroup, igSelf));
296 #endif
297     fprintf(fout, "Offset of igNum               = %2u\n", offsetof(insGroup, igNum));
298     fprintf(fout, "Offset of igOffs              = %2u\n", offsetof(insGroup, igOffs));
299     fprintf(fout, "Offset of igFuncIdx           = %2u\n", offsetof(insGroup, igFuncIdx));
300     fprintf(fout, "Offset of igFlags             = %2u\n", offsetof(insGroup, igFlags));
301     fprintf(fout, "Offset of igSize              = %2u\n", offsetof(insGroup, igSize));
302     fprintf(fout, "Offset of igData              = %2u\n", offsetof(insGroup, igData));
303 #if EMIT_TRACK_STACK_DEPTH
304     fprintf(fout, "Offset of igStkLvl            = %2u\n", offsetof(insGroup, igStkLvl));
305 #endif
306     fprintf(fout, "Offset of igGCregs            = %2u\n", offsetof(insGroup, igGCregs));
307     fprintf(fout, "Offset of igInsCnt            = %2u\n", offsetof(insGroup, igInsCnt));
308     fprintf(fout, "Size   of insGroup            = %u\n", sizeof(insGroup));
309
310     // insPlaceholderGroupData members
311
312     fprintf(fout, "\n");
313     fprintf(fout, "insPlaceholderGroupData:\n");
314     fprintf(fout, "Offset of igPhNext                = %2u\n", offsetof(insPlaceholderGroupData, igPhNext));
315     fprintf(fout, "Offset of igPhBB                  = %2u\n", offsetof(insPlaceholderGroupData, igPhBB));
316     fprintf(fout, "Offset of igPhInitGCrefVars       = %2u\n", offsetof(insPlaceholderGroupData, igPhInitGCrefVars));
317     fprintf(fout, "Offset of igPhInitGCrefRegs       = %2u\n", offsetof(insPlaceholderGroupData, igPhInitGCrefRegs));
318     fprintf(fout, "Offset of igPhInitByrefRegs       = %2u\n", offsetof(insPlaceholderGroupData, igPhInitByrefRegs));
319     fprintf(fout, "Offset of igPhPrevGCrefVars       = %2u\n", offsetof(insPlaceholderGroupData, igPhPrevGCrefVars));
320     fprintf(fout, "Offset of igPhPrevGCrefRegs       = %2u\n", offsetof(insPlaceholderGroupData, igPhPrevGCrefRegs));
321     fprintf(fout, "Offset of igPhPrevByrefRegs       = %2u\n", offsetof(insPlaceholderGroupData, igPhPrevByrefRegs));
322     fprintf(fout, "Offset of igPhType                = %2u\n", offsetof(insPlaceholderGroupData, igPhType));
323     fprintf(fout, "Size   of insPlaceholderGroupData = %u\n", sizeof(insPlaceholderGroupData));
324
325     fprintf(fout, "\n");
326     fprintf(fout, "Size   of tinyID      = %2u\n", TINY_IDSC_SIZE);
327     fprintf(fout, "Size   of instrDesc   = %2u\n", sizeof(emitter::instrDesc));
328     // fprintf(fout, "Offset of _idIns      = %2u\n", offsetof(emitter::instrDesc, _idIns      ));
329     // fprintf(fout, "Offset of _idInsFmt   = %2u\n", offsetof(emitter::instrDesc, _idInsFmt   ));
330     // fprintf(fout, "Offset of _idOpSize   = %2u\n", offsetof(emitter::instrDesc, _idOpSize   ));
331     // fprintf(fout, "Offset of idSmallCns  = %2u\n", offsetof(emitter::instrDesc, idSmallCns  ));
332     // fprintf(fout, "Offset of _idAddrUnion= %2u\n", offsetof(emitter::instrDesc, _idAddrUnion));
333     // fprintf(fout, "\n");
334     // fprintf(fout, "Size   of _idAddrUnion= %2u\n", sizeof(((emitter::instrDesc*)0)->_idAddrUnion));
335
336     fprintf(fout, "\n");
337     fprintf(fout, "GCInfo::regPtrDsc:\n");
338     fprintf(fout, "Offset of rpdNext           = %2u\n", offsetof(GCInfo::regPtrDsc, rpdNext));
339     fprintf(fout, "Offset of rpdOffs           = %2u\n", offsetof(GCInfo::regPtrDsc, rpdOffs));
340     fprintf(fout, "Offset of <union>           = %2u\n", offsetof(GCInfo::regPtrDsc, rpdPtrArg));
341     fprintf(fout, "Size   of GCInfo::regPtrDsc = %2u\n", sizeof(GCInfo::regPtrDsc));
342
343     fprintf(fout, "\n");
344 }
345
346 void emitterStats(FILE* fout)
347 {
348     if (totAllocdSize > 0)
349     {
350         assert(totActualSize <= totAllocdSize);
351
352         fprintf(fout, "\nTotal allocated code size = %u\n", totAllocdSize);
353
354         if (totActualSize < totAllocdSize)
355         {
356             fprintf(fout, "Total generated code size = %u  ", totActualSize);
357
358             fprintf(fout, "(%4.3f%% waste)", 100 * ((totAllocdSize - totActualSize) / (double)totActualSize));
359             fprintf(fout, "\n");
360         }
361
362         assert(emitter::emitTotalInsCnt);
363
364         fprintf(fout, "Average of %4.2f bytes of code generated per instruction\n",
365                 (double)totActualSize / emitter::emitTotalInsCnt);
366     }
367
368     fprintf(fout, "\nInstruction format frequency table:\n\n");
369
370     unsigned f, ic = 0, dc = 0;
371
372     for (f = 0; f < emitter::IF_COUNT; f++)
373     {
374         ic += emitter::emitIFcounts[f];
375     }
376
377     for (f = 0; f < emitter::IF_COUNT; f++)
378     {
379         unsigned c = emitter::emitIFcounts[f];
380
381         if ((c > 0) && (1000 * c >= ic))
382         {
383             dc += c;
384             fprintf(fout, "          %-13s %8u (%5.2f%%)\n", emitter::emitIfName(f), c, 100.0 * c / ic);
385         }
386     }
387
388     fprintf(fout, "         --------------------------------\n");
389     fprintf(fout, "          %-13s %8u (%5.2f%%)\n", "Total shown", dc, 100.0 * dc / ic);
390
391     if (emitter::emitTotalIGmcnt)
392     {
393         fprintf(fout, "Total of %8u methods\n", emitter::emitTotalIGmcnt);
394         fprintf(fout, "Total of %8u insGroup\n", emitter::emitTotalIGcnt);
395         fprintf(fout, "Total of %8u insPlaceholderGroupData\n", emitter::emitTotalPhIGcnt);
396         fprintf(fout, "Total of %8u instructions\n", emitter::emitTotalIGicnt);
397         fprintf(fout, "Total of %8u jumps\n", emitter::emitTotalIGjmps);
398         fprintf(fout, "Total of %8u GC livesets\n", emitter::emitTotalIGptrs);
399         fprintf(fout, "\n");
400         fprintf(fout, "Average of %8.1lf insGroup     per method\n",
401                 (double)emitter::emitTotalIGcnt / emitter::emitTotalIGmcnt);
402         fprintf(fout, "Average of %8.1lf insPhGroup   per method\n",
403                 (double)emitter::emitTotalPhIGcnt / emitter::emitTotalIGmcnt);
404         fprintf(fout, "Average of %8.1lf instructions per method\n",
405                 (double)emitter::emitTotalIGicnt / emitter::emitTotalIGmcnt);
406         fprintf(fout, "Average of %8.1lf desc.  bytes per method\n",
407                 (double)emitter::emitTotalIGsize / emitter::emitTotalIGmcnt);
408         fprintf(fout, "Average of %8.1lf jumps        per method\n",
409                 (double)emitter::emitTotalIGjmps / emitter::emitTotalIGmcnt);
410         fprintf(fout, "Average of %8.1lf GC livesets  per method\n",
411                 (double)emitter::emitTotalIGptrs / emitter::emitTotalIGmcnt);
412         fprintf(fout, "\n");
413         fprintf(fout, "Average of %8.1lf instructions per group \n",
414                 (double)emitter::emitTotalIGicnt / emitter::emitTotalIGcnt);
415         fprintf(fout, "Average of %8.1lf desc.  bytes per group \n",
416                 (double)emitter::emitTotalIGsize / emitter::emitTotalIGcnt);
417         fprintf(fout, "Average of %8.1lf jumps        per group \n",
418                 (double)emitter::emitTotalIGjmps / emitter::emitTotalIGcnt);
419         fprintf(fout, "\n");
420         fprintf(fout, "Average of %8.1lf bytes        per instrDesc\n",
421                 (double)emitter::emitTotalIGsize / emitter::emitTotalIGicnt);
422         fprintf(fout, "\n");
423         fprintf(fout, "A total of %8u desc.  bytes\n", emitter::emitTotalIGsize);
424         fprintf(fout, "\n");
425     }
426
427     fprintf(fout, "Descriptor size distribution:\n");
428     emitSizeTable.dump(fout);
429     fprintf(fout, "\n");
430
431     fprintf(fout, "GC ref frame variable counts:\n");
432     GCrefsTable.dump(fout);
433     fprintf(fout, "\n");
434
435     fprintf(fout, "Max. stack depth distribution:\n");
436     stkDepthTable.dump(fout);
437     fprintf(fout, "\n");
438
439     int      i;
440     unsigned c;
441     unsigned m;
442
443     if (emitter::emitSmallCnsCnt || emitter::emitLargeCnsCnt)
444     {
445         fprintf(fout, "SmallCnsCnt = %6u\n", emitter::emitSmallCnsCnt);
446         fprintf(fout, "LargeCnsCnt = %6u (%3u %% of total)\n", emitter::emitLargeCnsCnt,
447                 100 * emitter::emitLargeCnsCnt / (emitter::emitLargeCnsCnt + emitter::emitSmallCnsCnt));
448     }
449
450 #if 0
451     // TODO-Cleanup: WHy is this in #if 0 - Is EMITTER_STATS ever used? Fix or delete this.
452     if  (emitter::emitSmallCnsCnt)
453     {
454         fprintf(fout, "\n");
455
456         m = emitter::emitSmallCnsCnt/1000 + 1;
457
458         for (i = ID_MIN_SMALL_CNS; i < ID_MAX_SMALL_CNS; i++)
459         {
460             c = emitter::emitSmallCns[i-ID_MIN_SMALL_CNS];
461             if  (c >= m)
462                 fprintf(fout, "cns[%4d] = %u\n", i, c);
463         }
464     }
465 #endif // 0
466
467     fprintf(fout, "%8u bytes allocated in the emitter\n", emitter::emitTotMemAlloc);
468 }
469
470 #endif // EMITTER_STATS
471
472 /*****************************************************************************/
473
474 const unsigned short emitTypeSizes[] = {
475 #define DEF_TP(tn, nm, jitType, verType, sz, sze, asze, st, al, tf, howUsed) sze,
476 #include "typelist.h"
477 #undef DEF_TP
478 };
479
480 const unsigned short emitTypeActSz[] = {
481 #define DEF_TP(tn, nm, jitType, verType, sz, sze, asze, st, al, tf, howUsed) asze,
482 #include "typelist.h"
483 #undef DEF_TP
484 };
485
486 /*****************************************************************************/
487 /*****************************************************************************
488  *
489  *  Initialize the emitter - called once, at DLL load time.
490  */
491
492 void emitter::emitInit()
493 {
494 }
495
496 /*****************************************************************************
497  *
498  *  Shut down the emitter - called once, at DLL exit time.
499  */
500
501 void emitter::emitDone()
502 {
503 }
504
505 /*****************************************************************************
506  *
507  *  Allocate memory.
508  */
509
510 void* emitter::emitGetMem(size_t sz)
511 {
512     assert(sz % sizeof(int) == 0);
513
514 #if EMITTER_STATS
515     emitTotMemAlloc += sz;
516 #endif
517
518     return emitComp->compGetMem(sz, CMK_InstDesc);
519 }
520
521 /*****************************************************************************
522  *
523  *  emitLclVarAddr support methods
524  */
525 void emitLclVarAddr::initLclVarAddr(int varNum, unsigned offset)
526 {
527     if (varNum < 32768)
528     {
529         if (varNum >= 0)
530         {
531             if (offset < 32768)
532             {
533                 _lvaTag    = LVA_STANDARD_ENCODING;
534                 _lvaExtra  = offset;           // offset known to be in [0..32767]
535                 _lvaVarNum = (unsigned)varNum; // varNum known to be in [0..32767]
536             }
537             else // offset >= 32768
538             {
539                 // We could support larger local offsets here at the cost of less varNums
540                 if (offset >= 65536)
541                 {
542                     IMPL_LIMITATION("JIT doesn't support offsets larger than 65535 into valuetypes\n");
543                 }
544
545                 _lvaTag    = LVA_LARGE_OFFSET;
546                 _lvaExtra  = (offset - 32768); // (offset-32768) is known to be in [0..32767]
547                 _lvaVarNum = (unsigned)varNum; // varNum known to be in [0..32767]
548             }
549         }
550         else // varNum < 0, These are used for Compiler spill temps
551         {
552             if (varNum < -32767)
553             {
554                 IMPL_LIMITATION("JIT doesn't support more than 32767 Compiler Spill temps\n");
555             }
556             if (offset > 32767)
557             {
558                 IMPL_LIMITATION(
559                     "JIT doesn't support offsets larger than 32767 into valuetypes for Compiler Spill temps\n");
560             }
561
562             _lvaTag    = LVA_COMPILER_TEMP;
563             _lvaExtra  = offset;              //  offset known to be in [0..32767]
564             _lvaVarNum = (unsigned)(-varNum); // -varNum known to be in [1..32767]
565         }
566     }
567     else // varNum >= 32768
568     {
569         if (offset >= 256)
570         {
571             IMPL_LIMITATION("JIT doesn't support offsets larger than 255 into valuetypes for local vars > 32767\n");
572         }
573         if (varNum >= 0x00400000)
574         { // 0x00400000 == 2^22
575             IMPL_LIMITATION("JIT doesn't support more than 2^22 variables\n");
576         }
577
578         _lvaTag    = LVA_LARGE_VARNUM;
579         _lvaVarNum = varNum & 0x00007FFF;         // varNum bits 14 to 0
580         _lvaExtra  = (varNum & 0x003F8000) >> 15; // varNum bits 21 to 15 in _lvaExtra bits  6 to 0, 7 bits total
581         _lvaExtra |= (offset << 7);               // offset bits  7 to 0  in _lvaExtra bits 14 to 7, 8 bits total
582     }
583 }
584
585 // Returns the variable to access. Note that it returns a negative number for compiler spill temps.
586 int emitLclVarAddr::lvaVarNum()
587 {
588     switch (_lvaTag)
589     {
590         case LVA_COMPILER_TEMP:
591             return -((int)_lvaVarNum);
592         case LVA_LARGE_VARNUM:
593             return (int)(((_lvaExtra & 0x007F) << 15) + _lvaVarNum);
594         default: // LVA_STANDARD_ENCODING or LVA_LARGE_OFFSET
595             assert((_lvaTag == LVA_STANDARD_ENCODING) || (_lvaTag == LVA_LARGE_OFFSET));
596             return (int)_lvaVarNum;
597     }
598 }
599
600 unsigned emitLclVarAddr::lvaOffset() // returns the offset into the variable to access
601 {
602     switch (_lvaTag)
603     {
604         case LVA_LARGE_OFFSET:
605             return (32768 + _lvaExtra);
606         case LVA_LARGE_VARNUM:
607             return (_lvaExtra & 0x7F80) >> 7;
608         default: // LVA_STANDARD_ENCODING or LVA_COMPILER_TEMP
609             assert((_lvaTag == LVA_STANDARD_ENCODING) || (_lvaTag == LVA_COMPILER_TEMP));
610             return _lvaExtra;
611     }
612 }
613
614 /*****************************************************************************
615  *
616  *  Record some info about the method about to be emitted.
617  */
618
619 void emitter::emitBegCG(Compiler* comp, COMP_HANDLE cmpHandle)
620 {
621     emitComp      = comp;
622     emitCmpHandle = cmpHandle;
623 }
624
625 void emitter::emitEndCG()
626 {
627 }
628
629 /*****************************************************************************
630  *
631  *  Prepare the given IG for emission of code.
632  */
633
634 void emitter::emitGenIG(insGroup* ig)
635 {
636     /* Set the "current IG" value */
637
638     emitCurIG = ig;
639
640 #if EMIT_TRACK_STACK_DEPTH
641
642     /* Record the stack level on entry to this group */
643
644     ig->igStkLvl = emitCurStackLvl;
645
646     // If we don't have enough bits in igStkLvl, refuse to compile
647
648     if (ig->igStkLvl != emitCurStackLvl)
649     {
650         IMPL_LIMITATION("Too many arguments pushed on stack");
651     }
652
653 //  printf("Start IG #%02u [stk=%02u]\n", ig->igNum, emitCurStackLvl);
654
655 #endif
656
657     if (emitNoGCIG)
658     {
659         ig->igFlags |= IGF_NOGCINTERRUPT;
660     }
661
662     /* Prepare to issue instructions */
663
664     emitCurIGinsCnt = 0;
665     emitCurIGsize   = 0;
666
667     assert(emitCurIGjmpList == nullptr);
668
669     /* Allocate the temp instruction buffer if we haven't done so */
670
671     if (emitCurIGfreeBase == nullptr)
672     {
673         emitIGbuffSize    = SC_IG_BUFFER_SIZE;
674         emitCurIGfreeBase = (BYTE*)emitGetMem(emitIGbuffSize);
675     }
676
677     emitCurIGfreeNext = emitCurIGfreeBase;
678     emitCurIGfreeEndp = emitCurIGfreeBase + emitIGbuffSize;
679 }
680
681 /*****************************************************************************
682  *
683  *  Finish and save the current IG.
684  */
685
686 insGroup* emitter::emitSavIG(bool emitAdd)
687 {
688     insGroup* ig;
689     BYTE*     id;
690
691     size_t sz;
692     size_t gs;
693
694     assert(emitCurIGfreeNext <= emitCurIGfreeEndp);
695
696     /* Get hold of the IG descriptor */
697
698     ig = emitCurIG;
699     assert(ig);
700
701     /* Compute how much code we've generated */
702
703     sz = emitCurIGfreeNext - emitCurIGfreeBase;
704
705     /* Compute the total size we need to allocate */
706
707     gs = roundUp(sz);
708
709     /* Do we need space for GC? */
710
711     if (!(ig->igFlags & IGF_EMIT_ADD))
712     {
713         /* Is the initial set of live GC vars different from the previous one? */
714
715         if (emitForceStoreGCState || !VarSetOps::Equal(emitComp, emitPrevGCrefVars, emitInitGCrefVars))
716         {
717             /* Remember that we will have a new set of live GC variables */
718
719             ig->igFlags |= IGF_GC_VARS;
720
721 #if EMITTER_STATS
722             emitTotalIGptrs++;
723 #endif
724
725             /* We'll allocate extra space to record the liveset */
726
727             gs += sizeof(VARSET_TP);
728         }
729
730         /* Is the initial set of live Byref regs different from the previous one? */
731
732         /* Remember that we will have a new set of live GC variables */
733
734         ig->igFlags |= IGF_BYREF_REGS;
735
736         /* We'll allocate extra space (DWORD aligned) to record the GC regs */
737
738         gs += sizeof(int);
739     }
740
741     /* Allocate space for the instructions and optional liveset */
742
743     id = (BYTE*)emitGetMem(gs);
744
745     /* Do we need to store the byref regs */
746
747     if (ig->igFlags & IGF_BYREF_REGS)
748     {
749         /* Record the byref regs in front the of the instructions */
750
751         *castto(id, unsigned*)++ = (unsigned)emitInitByrefRegs;
752     }
753
754     /* Do we need to store the liveset? */
755
756     if (ig->igFlags & IGF_GC_VARS)
757     {
758         /* Record the liveset in front the of the instructions */
759         VarSetOps::AssignNoCopy(emitComp, (*castto(id, VARSET_TP*)), VarSetOps::MakeEmpty(emitComp));
760         VarSetOps::Assign(emitComp, (*castto(id, VARSET_TP*)++), emitInitGCrefVars);
761     }
762
763     /* Record the collected instructions */
764
765     assert((ig->igFlags & IGF_PLACEHOLDER) == 0);
766     ig->igData = id;
767
768     memcpy(id, emitCurIGfreeBase, sz);
769
770 #ifdef DEBUG
771     if (false && emitComp->verbose) // this is not useful in normal dumps (hence it is normally under if (false)
772     {
773         // If there's an error during emission, we may want to connect the post-copy address
774         // of an instrDesc with the pre-copy address (the one that was originally created).  This
775         // printing enables that.
776         printf("copying instruction group from [0x%x..0x%x) to [0x%x..0x%x).\n", dspPtr(emitCurIGfreeBase),
777                dspPtr(emitCurIGfreeBase + sz), dspPtr(id), dspPtr(id + sz));
778     }
779 #endif
780
781     /* Record how many instructions and bytes of code this group contains */
782
783     noway_assert((BYTE)emitCurIGinsCnt == emitCurIGinsCnt);
784     noway_assert((unsigned short)emitCurIGsize == emitCurIGsize);
785
786     ig->igInsCnt = (BYTE)emitCurIGinsCnt;
787     ig->igSize   = (unsigned short)emitCurIGsize;
788     emitCurCodeOffset += emitCurIGsize;
789     assert(IsCodeAligned(emitCurCodeOffset));
790
791 #if EMITTER_STATS
792     emitTotalIGicnt += emitCurIGinsCnt;
793     emitTotalIGsize += sz;
794     emitSizeMethod += sz;
795 #endif
796
797     // printf("Group [%08X]%3u has %2u instructions (%4u bytes at %08X)\n", ig, ig->igNum, emitCurIGinsCnt, sz, id);
798
799     /* Record the live GC register set - if and only if it is not an emitter added block */
800
801     if (!(ig->igFlags & IGF_EMIT_ADD))
802     {
803         ig->igGCregs = (regMaskSmall)emitInitGCrefRegs;
804     }
805
806     if (!emitAdd)
807     {
808         /* Update the previous recorded live GC ref sets, but not if
809            if we are starting an "overflow" buffer. Note that this is
810            only used to determine whether we need to store or not store
811            the GC ref sets for the next IG, which is dependent on exactly
812            what the state of the emitter GC ref sets will be when the
813            next IG is processed in the emitter.
814          */
815
816         VarSetOps::Assign(emitComp, emitPrevGCrefVars, emitThisGCrefVars);
817         emitPrevGCrefRegs = emitThisGCrefRegs;
818         emitPrevByrefRegs = emitThisByrefRegs;
819
820         emitForceStoreGCState = false;
821     }
822
823 #ifdef DEBUG
824     if (emitComp->opts.dspCode)
825     {
826         printf("\n      G_M%03u_IG%02u:", Compiler::s_compMethodsCount, ig->igNum);
827         if (emitComp->verbose)
828         {
829             printf("        ; offs=%06XH, funclet=%02u", ig->igOffs, ig->igFuncIdx);
830         }
831         else
832         {
833             printf("        ; funclet=%02u", ig->igFuncIdx);
834         }
835         printf("\n");
836     }
837 #endif
838
839     /* Did we have any jumps in this group? */
840
841     if (emitCurIGjmpList)
842     {
843         instrDescJmp* list = nullptr;
844         instrDescJmp* last = nullptr;
845
846         /* Move jumps to the global list, update their 'next' links */
847
848         do
849         {
850             /* Grab the jump and remove it from the list */
851
852             instrDescJmp* oj = emitCurIGjmpList;
853             emitCurIGjmpList = oj->idjNext;
854
855             /* Figure out the address of where the jump got copied */
856
857             size_t        of = (BYTE*)oj - emitCurIGfreeBase;
858             instrDescJmp* nj = (instrDescJmp*)(ig->igData + of);
859
860             // printf("Jump moved from %08X to %08X\n", oj, nj);
861             // printf("jmp [%08X] at %08X + %03u\n", nj, ig, nj->idjOffs);
862
863             assert(nj->idjIG == ig);
864             assert(nj->idIns() == oj->idIns());
865             assert(nj->idjNext == oj->idjNext);
866
867             /* Make sure the jumps are correctly ordered */
868
869             assert(last == nullptr || last->idjOffs > nj->idjOffs);
870
871             if (ig->igFlags & IGF_FUNCLET_PROLOG)
872             {
873                 // Our funclet prologs have short jumps, if the prolog would ever have
874                 // long jumps, then we'd have to insert the list in sorted order than
875                 // just append to the emitJumpList.
876                 noway_assert(nj->idjShort);
877                 if (nj->idjShort)
878                 {
879                     continue;
880                 }
881             }
882
883             /* Append the new jump to the list */
884
885             nj->idjNext = list;
886             list        = nj;
887
888             if (last == nullptr)
889             {
890                 last = nj;
891             }
892         } while (emitCurIGjmpList);
893
894         if (last != nullptr)
895         {
896             /* Append the jump(s) from this IG to the global list */
897             bool prologJump = (ig == emitPrologIG);
898             if ((emitJumpList == nullptr) || prologJump)
899             {
900                 last->idjNext = emitJumpList;
901                 emitJumpList  = list;
902             }
903             else
904             {
905                 last->idjNext         = nullptr;
906                 emitJumpLast->idjNext = list;
907             }
908
909             if (!prologJump || (emitJumpLast == nullptr))
910             {
911                 emitJumpLast = last;
912             }
913         }
914     }
915
916     /* Fix the last instruction field */
917
918     if (sz != 0)
919     {
920         assert(emitLastIns != nullptr);
921         assert(emitCurIGfreeBase <= (BYTE*)emitLastIns);
922         assert((BYTE*)emitLastIns < emitCurIGfreeBase + sz);
923         emitLastIns = (instrDesc*)((BYTE*)id + ((BYTE*)emitLastIns - (BYTE*)emitCurIGfreeBase));
924     }
925
926     /* Reset the buffer free pointers */
927
928     emitCurIGfreeNext = emitCurIGfreeBase;
929
930     return ig;
931 }
932
933 #ifdef LEGACY_BACKEND
934 void emitter::emitTmpSizeChanged(unsigned tmpSize)
935 {
936     assert(emitGrowableMaxByteOffs <= SCHAR_MAX);
937
938 #ifdef DEBUG
939     // Workaround for FP code
940     bool bAssert = JitConfig.JitMaxTempAssert() ? true : false;
941
942     if (tmpSize > emitMaxTmpSize && bAssert)
943     {
944         // TODO-Review: We have a known issue involving floating point code and this assert.
945         // The generated code will be ok, This is only a warning.
946         // To not receive this assert again you can set the registry key: JITMaxTempAssert=0.
947         //
948         assert(!"Incorrect max tmp size set.");
949     }
950 #endif
951
952     if (tmpSize <= emitMaxTmpSize)
953         return;
954
955     unsigned change = tmpSize - emitMaxTmpSize;
956
957     /* If we have used a small offset to access a variable, growing the
958        temp size is a problem if we should have used a large offset instead.
959        Detect if such a situation happens and bail */
960
961     if (emitGrowableMaxByteOffs <= SCHAR_MAX && (emitGrowableMaxByteOffs + change) > SCHAR_MAX)
962     {
963 #ifdef DEBUG
964         if (emitComp->verbose)
965             printf("Under-estimated var offset encoding size for ins #%Xh\n", emitMaxByteOffsIdNum);
966 #endif
967         IMPL_LIMITATION("Should have used large offset to access var");
968     }
969
970     emitMaxTmpSize = tmpSize;
971     emitGrowableMaxByteOffs += change;
972 }
973 #endif // LEGACY_BACKEND
974
975 /*****************************************************************************
976  *
977  *  Start generating code to be scheduled; called once per method.
978  */
979
980 void emitter::emitBegFN(bool hasFramePtr
981 #if defined(DEBUG)
982                         ,
983                         bool chkAlign
984 #endif
985 #ifdef LEGACY_BACKEND
986                         ,
987                         unsigned lclSize
988 #endif // LEGACY_BACKEND
989                         ,
990                         unsigned maxTmpSize)
991 {
992     insGroup* ig;
993
994     /* Assume we won't need the temp instruction buffer */
995
996     emitCurIGfreeBase = nullptr;
997     emitIGbuffSize    = 0;
998
999     /* Record stack frame info (the temp size is just an estimate) */
1000
1001     emitHasFramePtr = hasFramePtr;
1002
1003     emitMaxTmpSize = maxTmpSize;
1004
1005 #ifdef LEGACY_BACKEND
1006     emitLclSize             = lclSize;
1007     emitGrowableMaxByteOffs = 0;
1008 #ifdef DEBUG
1009     emitMaxByteOffsIdNum = (unsigned)-1;
1010 #endif // DEBUG
1011 #endif // LEGACY_BACKEND
1012
1013 #ifdef DEBUG
1014     emitChkAlign = chkAlign;
1015 #endif
1016
1017     /* We have no epilogs yet */
1018
1019     emitEpilogSize = 0;
1020     emitEpilogCnt  = 0;
1021
1022 #ifdef _TARGET_XARCH_
1023     emitExitSeqBegLoc.Init();
1024     emitExitSeqSize = INT_MAX;
1025 #endif // _TARGET_XARCH_
1026
1027     emitPlaceholderList = emitPlaceholderLast = nullptr;
1028
1029 #ifdef JIT32_GCENCODER
1030     emitEpilogList = emitEpilogLast = nullptr;
1031 #endif // JIT32_GCENCODER
1032
1033     /* We don't have any jumps */
1034
1035     emitJumpList = emitJumpLast = nullptr;
1036     emitCurIGjmpList            = nullptr;
1037
1038     emitFwdJumps   = false;
1039     emitNoGCIG     = false;
1040     emitForceNewIG = false;
1041
1042     /* We have not recorded any live sets */
1043
1044     assert(VarSetOps::IsEmpty(emitComp, emitThisGCrefVars));
1045     assert(VarSetOps::IsEmpty(emitComp, emitInitGCrefVars));
1046     assert(VarSetOps::IsEmpty(emitComp, emitPrevGCrefVars));
1047     emitThisGCrefRegs = RBM_NONE;
1048     emitInitGCrefRegs = RBM_NONE;
1049     emitPrevGCrefRegs = RBM_NONE;
1050     emitThisByrefRegs = RBM_NONE;
1051     emitInitByrefRegs = RBM_NONE;
1052     emitPrevByrefRegs = RBM_NONE;
1053
1054     emitForceStoreGCState = false;
1055
1056 #ifdef DEBUG
1057
1058     emitIssuing = false;
1059
1060 #endif
1061
1062     /* Assume there will be no GC ref variables */
1063
1064     emitGCrFrameOffsMin = emitGCrFrameOffsMax = emitGCrFrameOffsCnt = 0;
1065 #ifdef DEBUG
1066     emitGCrFrameLiveTab = nullptr;
1067 #endif
1068
1069     /* We have no groups / code at this point */
1070
1071     emitIGlist = emitIGlast = nullptr;
1072
1073     emitCurCodeOffset = 0;
1074     emitFirstColdIG   = nullptr;
1075     emitTotalCodeSize = 0;
1076
1077 #if EMITTER_STATS
1078     emitTotalIGmcnt++;
1079     emitSizeMethod = 0;
1080 #endif
1081
1082     emitInsCount = 0;
1083
1084     /* The stack is empty now */
1085
1086     emitCurStackLvl = 0;
1087
1088 #if EMIT_TRACK_STACK_DEPTH
1089     emitMaxStackDepth = 0;
1090     emitCntStackDepth = sizeof(int);
1091 #endif
1092
1093     /* No data sections have been created */
1094
1095     emitDataSecCur = nullptr;
1096
1097     memset(&emitConsDsc, 0, sizeof(emitConsDsc));
1098
1099 #ifdef PSEUDORANDOM_NOP_INSERTION
1100     // for random NOP insertion
1101
1102     emitEnableRandomNops();
1103     emitComp->info.compRNG.Init(emitComp->info.compChecksum);
1104     emitNextNop           = emitNextRandomNop();
1105     emitInInstrumentation = false;
1106 #endif // PSEUDORANDOM_NOP_INSERTION
1107
1108     /* Create the first IG, it will be used for the prolog */
1109
1110     emitNxtIGnum = 1;
1111
1112     emitPrologIG = emitIGlist = emitIGlast = emitCurIG = ig = emitAllocIG();
1113
1114     emitLastIns = nullptr;
1115
1116     ig->igNext = nullptr;
1117
1118 #ifdef DEBUG
1119     emitScratchSigInfo = nullptr;
1120 #endif // DEBUG
1121
1122     /* Append another group, to start generating the method body */
1123
1124     emitNewIG();
1125 }
1126
1127 #ifdef PSEUDORANDOM_NOP_INSERTION
1128 int emitter::emitNextRandomNop()
1129 {
1130     return emitComp->info.compRNG.Next(1, 9);
1131 }
1132 #endif
1133
1134 /*****************************************************************************
1135  *
1136  *  Done generating code to be scheduled; called once per method.
1137  */
1138
1139 void emitter::emitEndFN()
1140 {
1141 }
1142
1143 // member function iiaIsJitDataOffset for idAddrUnion, defers to Compiler::eeIsJitDataOffs
1144 bool emitter::instrDesc::idAddrUnion::iiaIsJitDataOffset() const
1145 {
1146     return Compiler::eeIsJitDataOffs(iiaFieldHnd);
1147 }
1148
1149 // member function iiaGetJitDataOffset for idAddrUnion, defers to Compiler::eeGetJitDataOffs
1150 int emitter::instrDesc::idAddrUnion::iiaGetJitDataOffset() const
1151 {
1152     assert(iiaIsJitDataOffset());
1153     return Compiler::eeGetJitDataOffs(iiaFieldHnd);
1154 }
1155
1156 void emitter::dispIns(instrDesc* id)
1157 {
1158 #ifdef DEBUG
1159     emitInsSanityCheck(id);
1160
1161     if (emitComp->opts.dspCode)
1162     {
1163         emitDispIns(id, true, false, false);
1164     }
1165
1166 #if EMIT_TRACK_STACK_DEPTH
1167     assert((int)emitCurStackLvl >= 0);
1168 #endif
1169     size_t sz = emitSizeOfInsDsc(id);
1170     assert(id->idDebugOnlyInfo()->idSize == sz);
1171 #endif // DEBUG
1172
1173 #if EMITTER_STATS
1174     emitIFcounts[id->idInsFmt()]++;
1175 #endif
1176 }
1177
1178 void emitter::appendToCurIG(instrDesc* id)
1179 {
1180     emitCurIGsize += id->idCodeSize();
1181 }
1182
1183 /*****************************************************************************
1184  *
1185  *  Display (optionally) an instruction offset.
1186  */
1187
1188 #ifdef DEBUG
1189
1190 void emitter::emitDispInsOffs(unsigned offs, bool doffs)
1191 {
1192     if (doffs)
1193     {
1194         printf("%06X", offs);
1195     }
1196     else
1197     {
1198         printf("      ");
1199     }
1200 }
1201
1202 #endif // DEBUG
1203
1204 #ifdef JIT32_GCENCODER
1205
1206 /*****************************************************************************
1207  *
1208  *  Call the specified function pointer for each epilog block in the current
1209  *  method with the epilog's relative code offset. Returns the sum of the
1210  *  values returned by the callback.
1211  */
1212
1213 size_t emitter::emitGenEpilogLst(size_t (*fp)(void*, unsigned), void* cp)
1214 {
1215     EpilogList* el;
1216     size_t      sz;
1217
1218     for (el = emitEpilogList, sz = 0; el != nullptr; el = el->elNext)
1219     {
1220         assert(el->elLoc.GetIG()->igFlags & IGF_EPILOG);
1221
1222         // The epilog starts at the location recorded in the epilog list.
1223         sz += fp(cp, el->elLoc.CodeOffset(this));
1224     }
1225
1226     return sz;
1227 }
1228
1229 #endif // JIT32_GCENCODER
1230
1231 /*****************************************************************************
1232  *
1233  *  The following series of methods allocates instruction descriptors.
1234  */
1235
1236 void* emitter::emitAllocInstr(size_t sz, emitAttr opsz)
1237 {
1238     instrDesc* id;
1239
1240 #ifdef DEBUG
1241     // Under STRESS_EMITTER, put every instruction in its own instruction group.
1242     // We can't do this for a prolog, epilog, funclet prolog, or funclet epilog,
1243     // because those are generated out of order. We currently have a limitation
1244     // where the jump shortening pass uses the instruction group number to determine
1245     // if something is earlier or later in the code stream. This implies that
1246     // these groups cannot be more than a single instruction group. Note that
1247     // the prolog/epilog placeholder groups ARE generated in order, and are
1248     // re-used. But generating additional groups would not work.
1249     if (emitComp->compStressCompile(Compiler::STRESS_EMITTER, 1) && emitCurIGinsCnt && !emitIGisInProlog(emitCurIG) &&
1250         !emitIGisInEpilog(emitCurIG)
1251 #if FEATURE_EH_FUNCLETS
1252         && !emitIGisInFuncletProlog(emitCurIG) && !emitIGisInFuncletEpilog(emitCurIG)
1253 #endif // FEATURE_EH_FUNCLETS
1254             )
1255     {
1256         emitNxtIG(true);
1257     }
1258 #endif
1259
1260 #ifdef PSEUDORANDOM_NOP_INSERTION
1261     // TODO-ARM-Bug?: PSEUDORANDOM_NOP_INSERTION is not defined for _TARGET_ARM_
1262     //     ARM - This is currently broken on _TARGET_ARM_
1263     //     When nopSize is odd we misalign emitCurIGsize
1264     //
1265     if (!emitComp->opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT) && !emitInInstrumentation &&
1266         !emitIGisInProlog(emitCurIG) && // don't do this in prolog or epilog
1267         !emitIGisInEpilog(emitCurIG) &&
1268         emitRandomNops // sometimes we turn off where exact codegen is needed (pinvoke inline)
1269         )
1270     {
1271         if (emitNextNop == 0)
1272         {
1273             int nopSize           = 4;
1274             emitInInstrumentation = true;
1275             instrDesc* idnop      = emitNewInstr();
1276             emitInInstrumentation = false;
1277             idnop->idInsFmt(IF_NONE);
1278             idnop->idIns(INS_nop);
1279 #if defined(_TARGET_XARCH_)
1280             idnop->idCodeSize(nopSize);
1281 #else
1282 #error "Undefined target for pseudorandom NOP insertion"
1283 #endif
1284
1285             emitCurIGsize += nopSize;
1286             emitNextNop = emitNextRandomNop();
1287         }
1288         else
1289             emitNextNop--;
1290     }
1291 #endif // PSEUDORANDOM_NOP_INSERTION
1292
1293     assert(IsCodeAligned(emitCurIGsize));
1294
1295     /* Make sure we have enough space for the new instruction */
1296
1297     if ((emitCurIGfreeNext + sz >= emitCurIGfreeEndp) || emitForceNewIG)
1298     {
1299         emitNxtIG(true);
1300     }
1301
1302     /* Grab the space for the instruction */
1303
1304     emitLastIns = id = (instrDesc*)emitCurIGfreeNext;
1305     emitCurIGfreeNext += sz;
1306
1307     assert(sz >= sizeof(void*));
1308     memset(id, 0, sz);
1309
1310     // These fields should have been zero-ed by the above
1311     assert(id->idReg1() == regNumber(0));
1312     assert(id->idReg2() == regNumber(0));
1313 #ifdef _TARGET_XARCH_
1314     assert(id->idCodeSize() == 0);
1315 #endif
1316
1317 #if HAS_TINY_DESC
1318     /* Is the second area to be cleared actually present? */
1319     if (sz >= SMALL_IDSC_SIZE)
1320     {
1321         /* Clear the second 4 bytes, or the 'SMALL' part */
1322         *(int*)((BYTE*)id + (SMALL_IDSC_SIZE - sizeof(int))) = 0;
1323
1324         // These fields should have been zero-ed by the above
1325         assert(id->idIsLargeCns() == false);
1326         assert(id->idIsLargeDsp() == false);
1327         assert(id->idIsLargeCall() == false);
1328     }
1329 #endif
1330
1331     // Make sure that idAddrUnion is just a union of various pointer sized things
1332     C_ASSERT(sizeof(CORINFO_FIELD_HANDLE) <= sizeof(void*));
1333     C_ASSERT(sizeof(CORINFO_METHOD_HANDLE) <= sizeof(void*));
1334     C_ASSERT(sizeof(emitter::emitAddrMode) <= sizeof(void*));
1335     C_ASSERT(sizeof(emitLclVarAddr) <= sizeof(void*));
1336     C_ASSERT(sizeof(emitter::instrDesc) == (SMALL_IDSC_SIZE + sizeof(void*)));
1337
1338     emitInsCount++;
1339
1340 #if defined(DEBUG)
1341     /* In debug mode we clear/set some additional fields */
1342
1343     instrDescDebugInfo* info = (instrDescDebugInfo*)emitGetMem(sizeof(*info));
1344
1345     info->idNum        = emitInsCount;
1346     info->idSize       = sz;
1347     info->idVarRefOffs = 0;
1348     info->idMemCookie  = 0;
1349 #ifdef TRANSLATE_PDB
1350     info->idilStart = emitInstrDescILBase;
1351 #endif
1352     info->idFinallyCall = false;
1353     info->idCatchRet    = false;
1354     info->idCallSig     = nullptr;
1355
1356     id->idDebugOnlyInfo(info);
1357
1358 #endif // defined(DEBUG)
1359
1360     /* Store the size and handle the two special values
1361        that indicate GCref and ByRef */
1362
1363     if (EA_IS_GCREF(opsz))
1364     {
1365         /* A special value indicates a GCref pointer value */
1366
1367         id->idGCref(GCT_GCREF);
1368         id->idOpSize(EA_PTRSIZE);
1369     }
1370     else if (EA_IS_BYREF(opsz))
1371     {
1372         /* A special value indicates a Byref pointer value */
1373
1374         id->idGCref(GCT_BYREF);
1375         id->idOpSize(EA_PTRSIZE);
1376     }
1377     else
1378     {
1379         id->idGCref(GCT_NONE);
1380         id->idOpSize(EA_SIZE(opsz));
1381     }
1382
1383     // Amd64: ip-relative addressing is supported even when not generating relocatable ngen code
1384     if (EA_IS_DSP_RELOC(opsz)
1385 #ifndef _TARGET_AMD64_
1386         && emitComp->opts.compReloc
1387 #endif //_TARGET_AMD64_
1388         )
1389     {
1390         /* Mark idInfo()->idDspReloc to remember that the            */
1391         /* address mode has a displacement that is relocatable       */
1392         id->idSetIsDspReloc();
1393     }
1394
1395     if (EA_IS_CNS_RELOC(opsz) && emitComp->opts.compReloc)
1396     {
1397         /* Mark idInfo()->idCnsReloc to remember that the            */
1398         /* instruction has an immediate constant that is relocatable */
1399         id->idSetIsCnsReloc();
1400     }
1401
1402 #if EMITTER_STATS
1403     emitTotalInsCnt++;
1404 #endif
1405
1406     /* Update the instruction count */
1407
1408     emitCurIGinsCnt++;
1409
1410     return id;
1411 }
1412
1413 #ifdef DEBUG
1414
1415 /*****************************************************************************
1416  *
1417  *  Make sure the code offsets of all instruction groups look reasonable.
1418  */
1419 void emitter::emitCheckIGoffsets()
1420 {
1421     insGroup* tempIG;
1422     size_t    offsIG;
1423
1424     for (tempIG = emitIGlist, offsIG = 0; tempIG; tempIG = tempIG->igNext)
1425     {
1426         if (tempIG->igOffs != offsIG)
1427         {
1428             printf("Block #%u has offset %08X, expected %08X\n", tempIG->igNum, tempIG->igOffs, offsIG);
1429             assert(!"bad block offset");
1430         }
1431
1432         offsIG += tempIG->igSize;
1433     }
1434
1435     if (emitTotalCodeSize && emitTotalCodeSize != offsIG)
1436     {
1437         printf("Total code size is %08X, expected %08X\n", emitTotalCodeSize, offsIG);
1438
1439         assert(!"bad total code size");
1440     }
1441 }
1442
1443 #endif // DEBUG
1444
1445 /*****************************************************************************
1446  *
1447  *  Begin generating a method prolog.
1448  */
1449
1450 void emitter::emitBegProlog()
1451 {
1452     assert(emitComp->compGeneratingProlog);
1453
1454 #if EMIT_TRACK_STACK_DEPTH
1455
1456     /* Don't measure stack depth inside the prolog, it's misleading */
1457
1458     emitCntStackDepth = 0;
1459
1460     assert(emitCurStackLvl == 0);
1461
1462 #endif
1463
1464     emitNoGCIG     = true;
1465     emitForceNewIG = false;
1466
1467     /* Switch to the pre-allocated prolog IG */
1468
1469     emitGenIG(emitPrologIG);
1470
1471     /* Nothing is live on entry to the prolog */
1472
1473     // These were initialized to Empty at the start of compilation.
1474     VarSetOps::OldStyleClearD(emitComp, emitInitGCrefVars);
1475     VarSetOps::OldStyleClearD(emitComp, emitPrevGCrefVars);
1476     emitInitGCrefRegs = RBM_NONE;
1477     emitPrevGCrefRegs = RBM_NONE;
1478     emitInitByrefRegs = RBM_NONE;
1479     emitPrevByrefRegs = RBM_NONE;
1480 }
1481
1482 /*****************************************************************************
1483  *
1484  *  Return the code offset of the current location in the prolog.
1485  */
1486
1487 unsigned emitter::emitGetPrologOffsetEstimate()
1488 {
1489     /* For now only allow a single prolog ins group */
1490
1491     assert(emitPrologIG);
1492     assert(emitPrologIG == emitCurIG);
1493
1494     return emitCurIGsize;
1495 }
1496
1497 /*****************************************************************************
1498  *
1499  *  Mark the code offset of the current location as the end of the prolog,
1500  *  so it can be used later to compute the actual size of the prolog.
1501  */
1502
1503 void emitter::emitMarkPrologEnd()
1504 {
1505     assert(emitComp->compGeneratingProlog);
1506
1507     /* For now only allow a single prolog ins group */
1508
1509     assert(emitPrologIG);
1510     assert(emitPrologIG == emitCurIG);
1511
1512     emitPrologEndPos = emitCurOffset();
1513 }
1514
1515 /*****************************************************************************
1516  *
1517  *  Finish generating a method prolog.
1518  */
1519
1520 void emitter::emitEndProlog()
1521 {
1522     assert(emitComp->compGeneratingProlog);
1523
1524     emitNoGCIG = false;
1525
1526     /* Save the prolog IG if non-empty or if only one block */
1527
1528     if (emitCurIGnonEmpty() || emitCurIG == emitPrologIG)
1529     {
1530         emitSavIG();
1531     }
1532
1533 #if EMIT_TRACK_STACK_DEPTH
1534     /* Reset the stack depth values */
1535
1536     emitCurStackLvl   = 0;
1537     emitCntStackDepth = sizeof(int);
1538 #endif
1539 }
1540
1541 /*****************************************************************************
1542  *
1543  *  Create a placeholder instruction group to be used by a prolog or epilog,
1544  *  either for the main function, or a funclet.
1545  */
1546
1547 void emitter::emitCreatePlaceholderIG(insGroupPlaceholderType igType,
1548                                       BasicBlock*             igBB,
1549                                       VARSET_VALARG_TP        GCvars,
1550                                       regMaskTP               gcrefRegs,
1551                                       regMaskTP               byrefRegs,
1552                                       bool                    last)
1553 {
1554     assert(igBB != nullptr);
1555
1556     bool emitAdd = false;
1557
1558     if (igType == IGPT_EPILOG
1559 #if FEATURE_EH_FUNCLETS
1560         || igType == IGPT_FUNCLET_EPILOG
1561 #endif // FEATURE_EH_FUNCLETS
1562         )
1563     {
1564 #ifdef _TARGET_AMD64_
1565         emitOutputPreEpilogNOP();
1566 #endif // _TARGET_AMD64_
1567
1568         emitAdd = true;
1569     }
1570
1571     if (emitCurIGnonEmpty())
1572     {
1573         emitNxtIG(emitAdd);
1574     }
1575
1576     /* Update GC tracking for the beginning of the placeholder IG */
1577
1578     if (!emitAdd)
1579     {
1580         VarSetOps::Assign(emitComp, emitThisGCrefVars, GCvars);
1581         VarSetOps::Assign(emitComp, emitInitGCrefVars, GCvars);
1582         emitThisGCrefRegs = emitInitGCrefRegs = gcrefRegs;
1583         emitThisByrefRegs = emitInitByrefRegs = byrefRegs;
1584     }
1585
1586     /* Convert the group to a placeholder group */
1587
1588     insGroup* igPh = emitCurIG;
1589
1590     igPh->igFlags |= IGF_PLACEHOLDER;
1591
1592     /* Note that we might be re-using a previously created but empty IG. In this
1593      * case, we need to make sure any re-used fields, such as igFuncIdx, are correct.
1594      */
1595
1596     igPh->igFuncIdx = emitComp->compCurrFuncIdx;
1597
1598     /* Create a separate block of memory to store placeholder information.
1599      * We could use unions to put some of this into the insGroup itself, but we don't
1600      * want to grow the insGroup, and it's difficult to make sure the
1601      * insGroup fields are getting set and used elsewhere.
1602      */
1603
1604     igPh->igPhData = new (emitComp, CMK_InstDesc) insPlaceholderGroupData;
1605
1606     igPh->igPhData->igPhNext = nullptr;
1607     igPh->igPhData->igPhType = igType;
1608     igPh->igPhData->igPhBB   = igBB;
1609
1610     VarSetOps::AssignNoCopy(emitComp, igPh->igPhData->igPhPrevGCrefVars, VarSetOps::UninitVal());
1611     VarSetOps::Assign(emitComp, igPh->igPhData->igPhPrevGCrefVars, emitPrevGCrefVars);
1612     igPh->igPhData->igPhPrevGCrefRegs = emitPrevGCrefRegs;
1613     igPh->igPhData->igPhPrevByrefRegs = emitPrevByrefRegs;
1614
1615     VarSetOps::AssignNoCopy(emitComp, igPh->igPhData->igPhInitGCrefVars, VarSetOps::UninitVal());
1616     VarSetOps::Assign(emitComp, igPh->igPhData->igPhInitGCrefVars, emitInitGCrefVars);
1617     igPh->igPhData->igPhInitGCrefRegs = emitInitGCrefRegs;
1618     igPh->igPhData->igPhInitByrefRegs = emitInitByrefRegs;
1619
1620 #if EMITTER_STATS
1621     emitTotalPhIGcnt += 1;
1622 #endif
1623
1624     // Mark function prologs and epilogs properly in the igFlags bits. These bits
1625     // will get used and propagated when the placeholder is converted to a non-placeholder
1626     // during prolog/epilog generation.
1627
1628     if (igType == IGPT_EPILOG)
1629     {
1630         igPh->igFlags |= IGF_EPILOG;
1631     }
1632 #if FEATURE_EH_FUNCLETS
1633     else if (igType == IGPT_FUNCLET_PROLOG)
1634     {
1635         igPh->igFlags |= IGF_FUNCLET_PROLOG;
1636     }
1637     else if (igType == IGPT_FUNCLET_EPILOG)
1638     {
1639         igPh->igFlags |= IGF_FUNCLET_EPILOG;
1640     }
1641 #endif // FEATURE_EH_FUNCLETS
1642
1643     /* Link it into the placeholder list */
1644
1645     if (emitPlaceholderList)
1646     {
1647         emitPlaceholderLast->igPhData->igPhNext = igPh;
1648     }
1649     else
1650     {
1651         emitPlaceholderList = igPh;
1652     }
1653
1654     emitPlaceholderLast = igPh;
1655
1656     // Give an estimated size of this placeholder IG and
1657     // increment emitCurCodeOffset since we are not calling emitNewIG()
1658     //
1659     emitCurIGsize += MAX_PLACEHOLDER_IG_SIZE;
1660     emitCurCodeOffset += emitCurIGsize;
1661
1662 #if FEATURE_EH_FUNCLETS
1663     // Add the appropriate IP mapping debugging record for this placeholder
1664     // group. genExitCode() adds the mapping for main function epilogs.
1665     if (emitComp->opts.compDbgInfo)
1666     {
1667         if (igType == IGPT_FUNCLET_PROLOG)
1668         {
1669             codeGen->genIPmappingAdd((IL_OFFSETX)ICorDebugInfo::PROLOG, true);
1670         }
1671         else if (igType == IGPT_FUNCLET_EPILOG)
1672         {
1673             codeGen->genIPmappingAdd((IL_OFFSETX)ICorDebugInfo::EPILOG, true);
1674         }
1675     }
1676 #endif // FEATURE_EH_FUNCLETS
1677
1678     /* Start a new IG if more code follows */
1679
1680     if (last)
1681     {
1682         emitCurIG = nullptr;
1683     }
1684     else
1685     {
1686         if (igType == IGPT_EPILOG
1687 #if FEATURE_EH_FUNCLETS
1688             || igType == IGPT_FUNCLET_EPILOG
1689 #endif // FEATURE_EH_FUNCLETS
1690             )
1691         {
1692             // If this was an epilog, then assume this is the end of any currently in progress
1693             // no-GC region. If a block after the epilog needs to be no-GC, it needs to call
1694             // emitter::emitDisableGC() directly. This behavior is depended upon by the fast
1695             // tailcall implementation, which disables GC at the beginning of argument setup,
1696             // but assumes that after the epilog it will be re-enabled.
1697             emitNoGCIG = false;
1698         }
1699
1700         emitNewIG();
1701
1702         // We don't know what the GC ref state will be at the end of the placeholder
1703         // group. So, force the next IG to store all the GC ref state variables;
1704         // don't omit them because emitPrev* is the same as emitInit*, because emitPrev*
1705         // will be inaccurate. (Note that, currently, GCrefRegs and ByrefRegs are always
1706         // saved anyway.)
1707         //
1708         // There is no need to re-initialize the emitPrev* variables, as they won't be used
1709         // with emitForceStoreGCState==true, and will be re-initialized just before
1710         // emitForceStoreGCState is set to false;
1711
1712         emitForceStoreGCState = true;
1713
1714         /* The group after the placeholder group doesn't get the "propagate" flags */
1715
1716         emitCurIG->igFlags &= ~IGF_PROPAGATE_MASK;
1717     }
1718
1719 #ifdef DEBUG
1720     if (emitComp->verbose)
1721     {
1722         printf("*************** After placeholder IG creation\n");
1723         emitDispIGlist(false);
1724     }
1725 #endif
1726 }
1727
1728 /*****************************************************************************
1729  *
1730  *  Generate all prologs and epilogs
1731  */
1732
1733 void emitter::emitGeneratePrologEpilog()
1734 {
1735 #ifdef DEBUG
1736     unsigned prologCnt = 0;
1737     unsigned epilogCnt = 0;
1738 #if FEATURE_EH_FUNCLETS
1739     unsigned funcletPrologCnt = 0;
1740     unsigned funcletEpilogCnt = 0;
1741 #endif // FEATURE_EH_FUNCLETS
1742 #endif // DEBUG
1743
1744     insGroup* igPh;
1745     insGroup* igPhNext;
1746
1747     // Generating the prolog/epilog is going to destroy the placeholder group,
1748     // so save the "next" pointer before that happens.
1749
1750     for (igPh = emitPlaceholderList; igPh != nullptr; igPh = igPhNext)
1751     {
1752         assert(igPh->igFlags & IGF_PLACEHOLDER);
1753
1754         igPhNext = igPh->igPhData->igPhNext;
1755
1756         BasicBlock* igPhBB = igPh->igPhData->igPhBB;
1757
1758         switch (igPh->igPhData->igPhType)
1759         {
1760             case IGPT_PROLOG: // currently unused
1761                 INDEBUG(++prologCnt);
1762                 break;
1763
1764             case IGPT_EPILOG:
1765                 INDEBUG(++epilogCnt);
1766                 emitBegFnEpilog(igPh);
1767                 codeGen->genFnEpilog(igPhBB);
1768                 emitEndFnEpilog();
1769                 break;
1770
1771 #if FEATURE_EH_FUNCLETS
1772
1773             case IGPT_FUNCLET_PROLOG:
1774                 INDEBUG(++funcletPrologCnt);
1775                 emitBegFuncletProlog(igPh);
1776                 codeGen->genFuncletProlog(igPhBB);
1777                 emitEndFuncletProlog();
1778                 break;
1779
1780             case IGPT_FUNCLET_EPILOG:
1781                 INDEBUG(++funcletEpilogCnt);
1782                 emitBegFuncletEpilog(igPh);
1783                 codeGen->genFuncletEpilog();
1784                 emitEndFuncletEpilog();
1785                 break;
1786
1787 #endif // FEATURE_EH_FUNCLETS
1788
1789             default:
1790                 unreached();
1791         }
1792     }
1793
1794 #ifdef DEBUG
1795     if (emitComp->verbose)
1796     {
1797         printf("%d prologs, %d epilogs", prologCnt, epilogCnt);
1798 #if FEATURE_EH_FUNCLETS
1799         printf(", %d funclet prologs, %d funclet epilogs", funcletPrologCnt, funcletEpilogCnt);
1800 #endif // FEATURE_EH_FUNCLETS
1801         printf("\n");
1802
1803 // prolog/epilog code doesn't use this yet
1804 // noway_assert(prologCnt == 1);
1805 // noway_assert(epilogCnt == emitEpilogCnt); // Is this correct?
1806 #if FEATURE_EH_FUNCLETS
1807         assert(funcletPrologCnt == emitComp->ehFuncletCount());
1808 #endif // FEATURE_EH_FUNCLETS
1809     }
1810 #endif // DEBUG
1811 }
1812
1813 /*****************************************************************************
1814  *
1815  *  Begin all prolog and epilog generation
1816  */
1817
1818 void emitter::emitStartPrologEpilogGeneration()
1819 {
1820     /* Save the current IG if it's non-empty */
1821
1822     if (emitCurIGnonEmpty())
1823     {
1824         emitSavIG();
1825     }
1826     else
1827     {
1828         assert(emitCurIG == nullptr);
1829     }
1830 }
1831
1832 /*****************************************************************************
1833  *
1834  *  Finish all prolog and epilog generation
1835  */
1836
1837 void emitter::emitFinishPrologEpilogGeneration()
1838 {
1839     /* Update the offsets of all the blocks */
1840
1841     emitRecomputeIGoffsets();
1842
1843     /* We should not generate any more code after this */
1844
1845     emitCurIG = nullptr;
1846 }
1847
1848 /*****************************************************************************
1849  *
1850  *  Common code for prolog / epilog beginning. Convert the placeholder group to actual code IG,
1851  *  and set it as the current group.
1852  */
1853
1854 void emitter::emitBegPrologEpilog(insGroup* igPh)
1855 {
1856     assert(igPh->igFlags & IGF_PLACEHOLDER);
1857
1858     /* Save the current IG if it's non-empty */
1859
1860     if (emitCurIGnonEmpty())
1861     {
1862         emitSavIG();
1863     }
1864
1865     /* Convert the placeholder group to a normal group.
1866      * We need to be very careful to re-initialize the IG properly.
1867      * It turns out, this means we only need to clear the placeholder bit
1868      * and clear the igPhData field, and emitGenIG() will do the rest,
1869      * since in the placeholder IG we didn't touch anything that is set by emitAllocIG().
1870      */
1871
1872     igPh->igFlags &= ~IGF_PLACEHOLDER;
1873     emitNoGCIG     = true;
1874     emitForceNewIG = false;
1875
1876     /* Set up the GC info that we stored in the placeholder */
1877
1878     VarSetOps::Assign(emitComp, emitPrevGCrefVars, igPh->igPhData->igPhPrevGCrefVars);
1879     emitPrevGCrefRegs = igPh->igPhData->igPhPrevGCrefRegs;
1880     emitPrevByrefRegs = igPh->igPhData->igPhPrevByrefRegs;
1881
1882     VarSetOps::Assign(emitComp, emitThisGCrefVars, igPh->igPhData->igPhInitGCrefVars);
1883     VarSetOps::Assign(emitComp, emitInitGCrefVars, igPh->igPhData->igPhInitGCrefVars);
1884     emitThisGCrefRegs = emitInitGCrefRegs = igPh->igPhData->igPhInitGCrefRegs;
1885     emitThisByrefRegs = emitInitByrefRegs = igPh->igPhData->igPhInitByrefRegs;
1886
1887     igPh->igPhData = nullptr;
1888
1889     /* Create a non-placeholder group pointer that we'll now use */
1890
1891     insGroup* ig = igPh;
1892
1893     /* Set the current function using the function index we stored */
1894
1895     emitComp->funSetCurrentFunc(ig->igFuncIdx);
1896
1897     /* Set the new IG as the place to generate code */
1898
1899     emitGenIG(ig);
1900
1901 #if EMIT_TRACK_STACK_DEPTH
1902
1903     /* Don't measure stack depth inside the prolog / epilog, it's misleading */
1904
1905     emitCntStackDepth = 0;
1906
1907     assert(emitCurStackLvl == 0);
1908
1909 #endif
1910 }
1911
1912 /*****************************************************************************
1913  *
1914  *  Common code for end of prolog / epilog
1915  */
1916
1917 void emitter::emitEndPrologEpilog()
1918 {
1919     emitNoGCIG = false;
1920
1921     /* Save the IG if non-empty */
1922
1923     if (emitCurIGnonEmpty())
1924     {
1925         emitSavIG();
1926     }
1927
1928     assert(emitCurIGsize <= MAX_PLACEHOLDER_IG_SIZE);
1929
1930 #if EMIT_TRACK_STACK_DEPTH
1931     /* Reset the stack depth values */
1932
1933     emitCurStackLvl   = 0;
1934     emitCntStackDepth = sizeof(int);
1935 #endif
1936 }
1937
1938 /*****************************************************************************
1939  *
1940  *  Begin generating a main function epilog.
1941  */
1942
1943 void emitter::emitBegFnEpilog(insGroup* igPh)
1944 {
1945     emitEpilogCnt++;
1946
1947     emitBegPrologEpilog(igPh);
1948
1949 #ifdef JIT32_GCENCODER
1950
1951     EpilogList* el = new (emitComp, CMK_GC) EpilogList();
1952
1953     if (emitEpilogLast != nullptr)
1954     {
1955         emitEpilogLast->elNext = el;
1956     }
1957     else
1958     {
1959         emitEpilogList = el;
1960     }
1961
1962     emitEpilogLast = el;
1963
1964 #endif // JIT32_GCENCODER
1965 }
1966
1967 /*****************************************************************************
1968  *
1969  *  Finish generating a funclet epilog.
1970  */
1971
1972 void emitter::emitEndFnEpilog()
1973 {
1974     emitEndPrologEpilog();
1975
1976 #ifdef JIT32_GCENCODER
1977     assert(emitEpilogLast != nullptr);
1978
1979     UNATIVE_OFFSET epilogBegCodeOffset          = emitEpilogLast->elLoc.CodeOffset(this);
1980     UNATIVE_OFFSET epilogExitSeqStartCodeOffset = emitExitSeqBegLoc.CodeOffset(this);
1981     UNATIVE_OFFSET newSize                      = epilogExitSeqStartCodeOffset - epilogBegCodeOffset;
1982
1983     /* Compute total epilog size */
1984     assert(emitEpilogSize == 0 || emitEpilogSize == newSize); // All epilogs must be identical
1985     emitEpilogSize = newSize;
1986
1987     UNATIVE_OFFSET epilogEndCodeOffset = emitCodeOffset(emitCurIG, emitCurOffset());
1988     assert(epilogExitSeqStartCodeOffset != epilogEndCodeOffset);
1989
1990     newSize = epilogEndCodeOffset - epilogExitSeqStartCodeOffset;
1991     if (newSize < emitExitSeqSize)
1992     {
1993         // We expect either the epilog to be the same every time, or that
1994         // one will be a ret or a ret <n> and others will be a jmp addr or jmp [addr];
1995         // we make the epilogs the minimum of these.  Note that this ONLY works
1996         // because the only instruction is the last one and thus a slight
1997         // underestimation of the epilog size is harmless (since the EIP
1998         // can not be between instructions).
1999         assert(emitEpilogCnt == 1 ||
2000                (emitExitSeqSize - newSize) <= 5 // delta between size of various forms of jmp (size is either 6 or 5)
2001                                                 // and various forms of ret (size is either 1 or 3). The combination can
2002                                                 // be anything been 1 and 5.
2003                );
2004         emitExitSeqSize = newSize;
2005     }
2006 #endif // JIT32_GCENCODER
2007 }
2008
2009 #if FEATURE_EH_FUNCLETS
2010
2011 /*****************************************************************************
2012  *
2013  *  Begin generating a funclet prolog.
2014  */
2015
2016 void emitter::emitBegFuncletProlog(insGroup* igPh)
2017 {
2018     emitBegPrologEpilog(igPh);
2019 }
2020
2021 /*****************************************************************************
2022  *
2023  *  Finish generating a funclet prolog.
2024  */
2025
2026 void emitter::emitEndFuncletProlog()
2027 {
2028     emitEndPrologEpilog();
2029 }
2030
2031 /*****************************************************************************
2032  *
2033  *  Begin generating a funclet epilog.
2034  */
2035
2036 void emitter::emitBegFuncletEpilog(insGroup* igPh)
2037 {
2038     emitBegPrologEpilog(igPh);
2039 }
2040
2041 /*****************************************************************************
2042  *
2043  *  Finish generating a funclet epilog.
2044  */
2045
2046 void emitter::emitEndFuncletEpilog()
2047 {
2048     emitEndPrologEpilog();
2049 }
2050
2051 #endif // FEATURE_EH_FUNCLETS
2052
2053 #ifdef JIT32_GCENCODER
2054
2055 //
2056 // emitter::emitStartEpilog:
2057 //   Mark the current position so that we can later compute the total epilog size.
2058 //
2059 void emitter::emitStartEpilog()
2060 {
2061     assert(emitEpilogLast != nullptr);
2062     emitEpilogLast->elLoc.CaptureLocation(this);
2063 }
2064
2065 /*****************************************************************************
2066  *
2067  *  Return non-zero if the current method only has one epilog, which is
2068  *  at the very end of the method body.
2069  */
2070
2071 bool emitter::emitHasEpilogEnd()
2072 {
2073     if (emitEpilogCnt == 1 && (emitIGlast->igFlags & IGF_EPILOG)) // This wouldn't work for funclets
2074         return true;
2075     else
2076         return false;
2077 }
2078
2079 #endif // JIT32_GCENCODER
2080
2081 #ifdef _TARGET_XARCH_
2082
2083 /*****************************************************************************
2084  *
2085  *  Mark the beginning of the epilog exit sequence by remembering our position.
2086  */
2087
2088 void emitter::emitStartExitSeq()
2089 {
2090     assert(emitComp->compGeneratingEpilog);
2091
2092     emitExitSeqBegLoc.CaptureLocation(this);
2093 }
2094
2095 #endif // _TARGET_XARCH_
2096
2097 /*****************************************************************************
2098  *
2099  *  The code generator tells us the range of GC ref locals through this
2100  *  method. Needless to say, locals and temps should be allocated so that
2101  *  the size of the range is as small as possible.
2102  *
2103  * offsLo - The FP offset from which the GC pointer range starts.
2104  * offsHi - The FP offset at which the GC pointer region ends (exclusive).
2105  */
2106
2107 void emitter::emitSetFrameRangeGCRs(int offsLo, int offsHi)
2108 {
2109     assert(emitComp->compGeneratingProlog);
2110     assert(offsHi > offsLo);
2111
2112 #ifdef DEBUG
2113
2114     //  A total of    47254 methods compiled.
2115     //
2116     //  GC ref frame variable counts:
2117     //
2118     //      <=         0 ===>  43175 count ( 91% of total)
2119     //       1 ..      1 ===>   2367 count ( 96% of total)
2120     //       2 ..      2 ===>    887 count ( 98% of total)
2121     //       3 ..      5 ===>    579 count ( 99% of total)
2122     //       6 ..     10 ===>    141 count ( 99% of total)
2123     //      11 ..     20 ===>     40 count ( 99% of total)
2124     //      21 ..     50 ===>     42 count ( 99% of total)
2125     //      51 ..    128 ===>     15 count ( 99% of total)
2126     //     129 ..    256 ===>      4 count ( 99% of total)
2127     //     257 ..    512 ===>      4 count (100% of total)
2128     //     513 ..   1024 ===>      0 count (100% of total)
2129
2130     if (emitComp->verbose)
2131     {
2132         unsigned count = (offsHi - offsLo) / sizeof(void*);
2133         printf("%u tracked GC refs are at stack offsets ", count);
2134
2135         if (offsLo >= 0)
2136         {
2137             printf(" %04X ...  %04X\n", offsLo, offsHi);
2138             assert(offsHi >= 0);
2139         }
2140         else
2141 #if defined(_TARGET_ARM_) && defined(PROFILING_SUPPORTED)
2142             if (!emitComp->compIsProfilerHookNeeded())
2143 #endif
2144         {
2145 #ifdef _TARGET_AMD64_
2146             // doesn't have to be all negative on amd
2147             printf("-%04X ... %04X\n", -offsLo, offsHi);
2148 #else
2149             printf("-%04X ... -%04X\n", -offsLo, -offsHi);
2150             assert(offsHi <= 0);
2151 #endif
2152         }
2153 #if defined(_TARGET_ARM_) && defined(PROFILING_SUPPORTED)
2154         else
2155         {
2156             // Under profiler due to prespilling of arguments, offHi need not be < 0
2157             if (offsHi < 0)
2158                 printf("-%04X ... -%04X\n", -offsLo, -offsHi);
2159             else
2160                 printf("-%04X ... %04X\n", -offsLo, offsHi);
2161         }
2162 #endif
2163     }
2164
2165 #endif // DEBUG
2166
2167     assert(((offsHi - offsLo) % sizeof(void*)) == 0);
2168     assert((offsLo % sizeof(void*)) == 0);
2169     assert((offsHi % sizeof(void*)) == 0);
2170
2171     emitGCrFrameOffsMin = offsLo;
2172     emitGCrFrameOffsMax = offsHi;
2173     emitGCrFrameOffsCnt = (offsHi - offsLo) / sizeof(void*);
2174 }
2175
2176 /*****************************************************************************
2177  *
2178  *  The code generator tells us the range of local variables through this
2179  *  method.
2180  */
2181
2182 void emitter::emitSetFrameRangeLcls(int offsLo, int offsHi)
2183 {
2184 }
2185
2186 /*****************************************************************************
2187  *
2188  *  The code generator tells us the range of used arguments through this
2189  *  method.
2190  */
2191
2192 void emitter::emitSetFrameRangeArgs(int offsLo, int offsHi)
2193 {
2194 }
2195
2196 /*****************************************************************************
2197  *
2198  *  A conversion table used to map an operand size value (in bytes) into its
2199  *  small encoding (0 through 3), and vice versa.
2200  */
2201
2202 const emitter::opSize emitter::emitSizeEncode[] = {
2203     emitter::OPSZ1, emitter::OPSZ2,  OPSIZE_INVALID, emitter::OPSZ4,  OPSIZE_INVALID, OPSIZE_INVALID, OPSIZE_INVALID,
2204     emitter::OPSZ8, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID, OPSIZE_INVALID,
2205     OPSIZE_INVALID, emitter::OPSZ16, OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID, OPSIZE_INVALID,
2206     OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID, OPSIZE_INVALID,
2207     OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, emitter::OPSZ32,
2208 };
2209
2210 const emitAttr emitter::emitSizeDecode[emitter::OPSZ_COUNT] = {EA_1BYTE, EA_2BYTE,  EA_4BYTE,
2211                                                                EA_8BYTE, EA_16BYTE, EA_32BYTE};
2212
2213 /*****************************************************************************
2214  *
2215  *  Allocate an instruction descriptor for an instruction that uses both
2216  *  a displacement and a constant.
2217  */
2218
2219 emitter::instrDesc* emitter::emitNewInstrCnsDsp(emitAttr size, ssize_t cns, int dsp)
2220 {
2221     if (dsp == 0)
2222     {
2223         if (instrDesc::fitsInSmallCns(cns))
2224         {
2225             instrDesc* id = emitAllocInstr(size);
2226
2227             id->idSmallCns(cns);
2228
2229 #if EMITTER_STATS
2230             emitSmallCnsCnt++;
2231             emitSmallCns[cns - ID_MIN_SMALL_CNS]++;
2232             emitSmallDspCnt++;
2233 #endif
2234
2235             return id;
2236         }
2237         else
2238         {
2239             instrDescCns* id = emitAllocInstrCns(size);
2240
2241             id->idSetIsLargeCns();
2242             id->idcCnsVal = cns;
2243
2244 #if EMITTER_STATS
2245             emitLargeCnsCnt++;
2246             emitSmallDspCnt++;
2247 #endif
2248
2249             return id;
2250         }
2251     }
2252     else
2253     {
2254         if (instrDesc::fitsInSmallCns(cns))
2255         {
2256             instrDescDsp* id = emitAllocInstrDsp(size);
2257
2258             id->idSetIsLargeDsp();
2259             id->iddDspVal = dsp;
2260
2261             id->idSmallCns(cns);
2262
2263 #if EMITTER_STATS
2264             emitLargeDspCnt++;
2265             emitSmallCnsCnt++;
2266             emitSmallCns[cns - ID_MIN_SMALL_CNS]++;
2267 #endif
2268
2269             return id;
2270         }
2271         else
2272         {
2273             instrDescCnsDsp* id = emitAllocInstrCnsDsp(size);
2274
2275             id->idSetIsLargeCns();
2276             id->iddcCnsVal = cns;
2277
2278             id->idSetIsLargeDsp();
2279             id->iddcDspVal = dsp;
2280
2281 #if EMITTER_STATS
2282             emitLargeDspCnt++;
2283             emitLargeCnsCnt++;
2284 #endif
2285
2286             return id;
2287         }
2288     }
2289 }
2290
2291 /*****************************************************************************
2292  *
2293  *  Returns true if garbage-collection won't happen within the helper call.
2294  *  Don't need to record live pointers for such call sites.
2295  */
2296
2297 bool emitter::emitNoGChelper(unsigned IHX)
2298 {
2299     // TODO-Throughput: Make this faster (maybe via a simple table of bools?)
2300
2301     switch (IHX)
2302     {
2303         case CORINFO_HELP_UNDEF:
2304             return false;
2305
2306         case CORINFO_HELP_PROF_FCN_LEAVE:
2307         case CORINFO_HELP_PROF_FCN_ENTER:
2308 #if defined(_TARGET_AMD64_) || (defined(_TARGET_X86_) && !defined(LEGACY_BACKEND))
2309         case CORINFO_HELP_PROF_FCN_TAILCALL:
2310 #endif
2311         case CORINFO_HELP_LLSH:
2312         case CORINFO_HELP_LRSH:
2313         case CORINFO_HELP_LRSZ:
2314
2315 //  case CORINFO_HELP_LMUL:
2316 //  case CORINFO_HELP_LDIV:
2317 //  case CORINFO_HELP_LMOD:
2318 //  case CORINFO_HELP_ULDIV:
2319 //  case CORINFO_HELP_ULMOD:
2320
2321 #ifdef _TARGET_X86_
2322         case CORINFO_HELP_ASSIGN_REF_EAX:
2323         case CORINFO_HELP_ASSIGN_REF_ECX:
2324         case CORINFO_HELP_ASSIGN_REF_EBX:
2325         case CORINFO_HELP_ASSIGN_REF_EBP:
2326         case CORINFO_HELP_ASSIGN_REF_ESI:
2327         case CORINFO_HELP_ASSIGN_REF_EDI:
2328
2329         case CORINFO_HELP_CHECKED_ASSIGN_REF_EAX:
2330         case CORINFO_HELP_CHECKED_ASSIGN_REF_ECX:
2331         case CORINFO_HELP_CHECKED_ASSIGN_REF_EBX:
2332         case CORINFO_HELP_CHECKED_ASSIGN_REF_EBP:
2333         case CORINFO_HELP_CHECKED_ASSIGN_REF_ESI:
2334         case CORINFO_HELP_CHECKED_ASSIGN_REF_EDI:
2335 #endif
2336
2337         case CORINFO_HELP_ASSIGN_REF:
2338
2339         case CORINFO_HELP_CHECKED_ASSIGN_REF:
2340
2341         case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR:
2342
2343         case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR:
2344
2345         case CORINFO_HELP_ASSIGN_BYREF:
2346
2347         case CORINFO_HELP_INIT_PINVOKE_FRAME:
2348
2349             return true;
2350     }
2351
2352     return false;
2353 }
2354
2355 /*****************************************************************************
2356  *
2357  *  Mark the current spot as having a label.
2358  */
2359
2360 void* emitter::emitAddLabel(VARSET_VALARG_TP GCvars, regMaskTP gcrefRegs, regMaskTP byrefRegs, BOOL isFinallyTarget)
2361 {
2362     /* Create a new IG if the current one is non-empty */
2363
2364     if (emitCurIGnonEmpty())
2365     {
2366         emitNxtIG();
2367     }
2368
2369     VarSetOps::Assign(emitComp, emitThisGCrefVars, GCvars);
2370     VarSetOps::Assign(emitComp, emitInitGCrefVars, GCvars);
2371     emitThisGCrefRegs = emitInitGCrefRegs = gcrefRegs;
2372     emitThisByrefRegs = emitInitByrefRegs = byrefRegs;
2373
2374 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
2375     if (isFinallyTarget)
2376     {
2377         emitCurIG->igFlags |= IGF_FINALLY_TARGET;
2378     }
2379 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
2380
2381 #ifdef DEBUG
2382     if (EMIT_GC_VERBOSE)
2383     {
2384         printf("Label: IG%02u, GCvars=%s ", emitCurIG->igNum, VarSetOps::ToString(emitComp, GCvars));
2385         dumpConvertedVarSet(emitComp, GCvars);
2386         printf(", gcrefRegs=");
2387         printRegMaskInt(gcrefRegs);
2388         emitDispRegSet(gcrefRegs);
2389         printf(", byrefRegs=");
2390         printRegMaskInt(byrefRegs);
2391         emitDispRegSet(byrefRegs);
2392         printf("\n");
2393     }
2394 #endif
2395     return emitCurIG;
2396 }
2397
2398 #ifdef _TARGET_ARMARCH_
2399
2400 // Does the argument location point to an IG at the end of a function or funclet?
2401 // We can ignore the codePos part of the location, since it doesn't affect the
2402 // determination. If 'emitLocNextFragment' is non-NULL, it indicates the first
2403 // IG of the next fragment, so it represents a function end.
2404 bool emitter::emitIsFuncEnd(emitLocation* emitLoc, emitLocation* emitLocNextFragment /* = NULL */)
2405 {
2406     assert(emitLoc);
2407
2408     insGroup* ig = emitLoc->GetIG();
2409     assert(ig);
2410
2411     // Are we at the end of the IG list?
2412     if ((emitLocNextFragment != NULL) && (ig->igNext == emitLocNextFragment->GetIG()))
2413         return true;
2414
2415     // Safety check
2416     if (ig->igNext == NULL)
2417         return true;
2418
2419     // Is the next IG the start of a funclet prolog?
2420     if (ig->igNext->igFlags & IGF_FUNCLET_PROLOG)
2421         return true;
2422
2423 #if FEATURE_EH_FUNCLETS
2424
2425     // Is the next IG a placeholder group for a funclet prolog?
2426     if ((ig->igNext->igFlags & IGF_PLACEHOLDER) && (ig->igNext->igPhData->igPhType == IGPT_FUNCLET_PROLOG))
2427     {
2428         return true;
2429     }
2430
2431 #endif // FEATURE_EH_FUNCLETS
2432
2433     return false;
2434 }
2435
2436 /*****************************************************************************
2437  *
2438  * Split the region from 'startLoc' to 'endLoc' into fragments by calling
2439  * a callback function to indicate the beginning of a fragment. The initial code,
2440  * starting at 'startLoc', doesn't get a callback, but the first code fragment,
2441  * about 'maxSplitSize' bytes out does, as does the beginning of each fragment
2442  * after that. There is no callback for the end (only the beginning of the last
2443  * fragment gets a callback). A fragment must contain at least one instruction
2444  * group. It should be smaller than 'maxSplitSize', although it may be larger to
2445  * satisfy the "at least one instruction group" rule. Do not split prologs or
2446  * epilogs. (Currently, prologs exist in a single instruction group at the main
2447  * function beginning, so they aren't split. Funclets, however, might span IGs,
2448  * so we can't split in between them.)
2449  *
2450  * Note that the locations must be the start of instruction groups; the part of
2451  * the location indicating offset within a group must be zero.
2452  *
2453  * If 'startLoc' is NULL, it means the start of the code.
2454  * If 'endLoc'   is NULL, it means the end   of the code.
2455  */
2456
2457 void emitter::emitSplit(emitLocation*         startLoc,
2458                         emitLocation*         endLoc,
2459                         UNATIVE_OFFSET        maxSplitSize,
2460                         void*                 context,
2461                         emitSplitCallbackType callbackFunc)
2462 {
2463     insGroup*      igStart = (startLoc == NULL) ? emitIGlist : startLoc->GetIG();
2464     insGroup*      igEnd   = (endLoc == NULL) ? NULL : endLoc->GetIG();
2465     insGroup*      igPrev;
2466     insGroup*      ig;
2467     insGroup*      igLastReported;
2468     insGroup*      igLastCandidate;
2469     UNATIVE_OFFSET curSize;
2470     UNATIVE_OFFSET candidateSize;
2471
2472     for (igPrev = NULL, ig = igLastReported = igStart, igLastCandidate = NULL, candidateSize = 0, curSize = 0;
2473          ig != igEnd && ig != NULL; igPrev = ig, ig = ig->igNext)
2474     {
2475         // Keep looking until we've gone past the maximum split size
2476         if (curSize >= maxSplitSize)
2477         {
2478             bool reportCandidate = true;
2479
2480             // Is there a candidate?
2481             if (igLastCandidate == NULL)
2482             {
2483 #ifdef DEBUG
2484                 if (EMITVERBOSE)
2485                     printf("emitSplit: can't split at IG%02u; we don't have a candidate to report\n", ig->igNum);
2486 #endif
2487                 reportCandidate = false;
2488             }
2489
2490             // Don't report the same thing twice (this also happens for the first block, since igLastReported is
2491             // initialized to igStart).
2492             if (igLastCandidate == igLastReported)
2493             {
2494 #ifdef DEBUG
2495                 if (EMITVERBOSE)
2496                     printf("emitSplit: can't split at IG%02u; we already reported it\n", igLastCandidate->igNum);
2497 #endif
2498                 reportCandidate = false;
2499             }
2500
2501             // Report it!
2502             if (reportCandidate)
2503             {
2504 #ifdef DEBUG
2505                 if (EMITVERBOSE && (candidateSize >= maxSplitSize))
2506                     printf("emitSplit: split at IG%02u is size %d, larger than requested maximum size of %d\n",
2507                            igLastCandidate->igNum, candidateSize, maxSplitSize);
2508 #endif
2509
2510                 // hand memory ownership to the callback function
2511                 emitLocation* pEmitLoc = new (emitComp, CMK_Unknown) emitLocation(igLastCandidate);
2512                 callbackFunc(context, pEmitLoc);
2513                 igLastReported  = igLastCandidate;
2514                 igLastCandidate = NULL;
2515                 curSize -= candidateSize;
2516             }
2517         }
2518
2519         // Update the current candidate to be this block, if it isn't in the middle of a
2520         // prolog or epilog, which we can't split. All we know is that certain
2521         // IGs are marked as prolog or epilog. We don't actually know if two adjacent
2522         // IGs are part of the *same* prolog or epilog, so we have to assume they are.
2523
2524         if (igPrev && (((igPrev->igFlags & IGF_FUNCLET_PROLOG) && (ig->igFlags & IGF_FUNCLET_PROLOG)) ||
2525                        ((igPrev->igFlags & IGF_EPILOG) && (ig->igFlags & IGF_EPILOG))))
2526         {
2527             // We can't update the candidate
2528         }
2529         else
2530         {
2531             igLastCandidate = ig;
2532             candidateSize   = curSize;
2533         }
2534
2535         curSize += ig->igSize;
2536
2537     } // end for loop
2538 }
2539
2540 /*****************************************************************************
2541  *
2542  * Given an instruction group, find the array of instructions (instrDesc) and
2543  * number of instructions in the array. If the IG is the current IG, we assume
2544  * that igData does NOT hold the instructions; they are unsaved and pointed
2545  * to by emitCurIGfreeBase.
2546  *
2547  * This function can't be called for placeholder groups, which have no instrDescs.
2548  */
2549
2550 void emitter::emitGetInstrDescs(insGroup* ig, instrDesc** id, int* insCnt)
2551 {
2552     assert(!(ig->igFlags & IGF_PLACEHOLDER));
2553     if (ig == emitCurIG)
2554     {
2555         *id     = (instrDesc*)emitCurIGfreeBase;
2556         *insCnt = emitCurIGinsCnt;
2557     }
2558     else
2559     {
2560         *id     = (instrDesc*)ig->igData;
2561         *insCnt = ig->igInsCnt;
2562     }
2563
2564     assert(*id);
2565 }
2566
2567 /*****************************************************************************
2568  *
2569  * Given a location (an 'emitLocation'), find the instruction group (IG) and
2570  * instruction descriptor (instrDesc) corresponding to that location. Returns
2571  * 'true' if there is an instruction, 'false' if there is no instruction
2572  * (i.e., we're at the end of the instruction list). Also, optionally return
2573  * the number of instructions that follow that instruction in the IG (in *pinsRemaining,
2574  * if pinsRemaining is non-NULL), which can be used for iterating over the
2575  * remaining instrDescs in the IG.
2576  *
2577  * We assume that emitCurIG points to the end of the instructions we care about.
2578  * For the prologs or epilogs, it points to the last IG of the prolog or epilog
2579  * that is being generated. For body code gen, it points to the place we are currently
2580  * adding code, namely, the end of currently generated code.
2581  */
2582
2583 bool emitter::emitGetLocationInfo(emitLocation* emitLoc,
2584                                   insGroup**    pig,
2585                                   instrDesc**   pid,
2586                                   int*          pinsRemaining /* = NULL */)
2587 {
2588     assert(emitLoc != nullptr);
2589     assert(emitLoc->Valid());
2590     assert(emitLoc->GetIG() != nullptr);
2591     assert(pig != nullptr);
2592     assert(pid != nullptr);
2593
2594     insGroup*  ig = emitLoc->GetIG();
2595     instrDesc* id;
2596     int        insNum = emitLoc->GetInsNum();
2597     int        insCnt;
2598
2599     emitGetInstrDescs(ig, &id, &insCnt);
2600     assert(insNum <= insCnt);
2601
2602     // There is a special-case: if the insNum points to the end, then we "wrap" and
2603     // consider that the instruction it is pointing at is actually the first instruction
2604     // of the next non-empty IG (which has its own valid emitLocation). This handles the
2605     // case where you capture a location, then the next instruction creates a new IG.
2606
2607     if (insNum == insCnt)
2608     {
2609         if (ig == emitCurIG)
2610         {
2611             // No instructions beyond the current location.
2612             return false;
2613         }
2614
2615         for (ig = ig->igNext; ig; ig = ig->igNext)
2616         {
2617             emitGetInstrDescs(ig, &id, &insCnt);
2618
2619             if (insCnt > 0)
2620             {
2621                 insNum = 0; // Pretend the index is 0 -- the first instruction
2622                 break;
2623             }
2624
2625             if (ig == emitCurIG)
2626             {
2627                 // There aren't any instructions in the current IG, and this is
2628                 // the current location, so we're at the end.
2629                 return false;
2630             }
2631         }
2632
2633         if (ig == NULL)
2634         {
2635             // 'ig' can't be NULL, or we went past the current IG represented by 'emitCurIG'.
2636             // Perhaps 'loc' was corrupt coming in?
2637             noway_assert(!"corrupt emitter location");
2638             return false;
2639         }
2640     }
2641
2642     // Now find the instrDesc within this group that corresponds to the location
2643
2644     assert(insNum < insCnt);
2645
2646     int i;
2647     for (i = 0; i != insNum; ++i)
2648     {
2649         castto(id, BYTE*) += emitSizeOfInsDsc(id);
2650     }
2651
2652     // Return the info we found
2653
2654     *pig = ig;
2655     *pid = id;
2656
2657     if (pinsRemaining)
2658     {
2659         *pinsRemaining = insCnt - insNum - 1;
2660     }
2661
2662     return true;
2663 }
2664
2665 /*****************************************************************************
2666  *
2667  * Compute the next instrDesc, either in this IG, or in a subsequent IG. 'id'
2668  * will point to this instrDesc. 'ig' and 'insRemaining' will also be updated.
2669  * Returns true if there is an instruction, or false if we've iterated over all
2670  * the instructions up to the current instruction (based on 'emitCurIG').
2671  */
2672
2673 bool emitter::emitNextID(insGroup*& ig, instrDesc*& id, int& insRemaining)
2674 {
2675     if (insRemaining > 0)
2676     {
2677         castto(id, BYTE*) += emitSizeOfInsDsc(id);
2678         --insRemaining;
2679         return true;
2680     }
2681
2682     // We're out of instrDesc in 'ig'. Is this the current IG? If so, we're done.
2683
2684     if (ig == emitCurIG)
2685     {
2686         return false;
2687     }
2688
2689     for (ig = ig->igNext; ig; ig = ig->igNext)
2690     {
2691         int insCnt;
2692         emitGetInstrDescs(ig, &id, &insCnt);
2693
2694         if (insCnt > 0)
2695         {
2696             insRemaining = insCnt - 1;
2697             return true;
2698         }
2699
2700         if (ig == emitCurIG)
2701         {
2702             return false;
2703         }
2704     }
2705
2706     return false;
2707 }
2708
2709 /*****************************************************************************
2710  *
2711  * Walk instrDesc's from the location given by 'locFrom', up to the current location.
2712  * For each instruction, call the callback function 'processFunc'. 'context' is simply
2713  * passed through to the callback function.
2714  */
2715
2716 void emitter::emitWalkIDs(emitLocation* locFrom, emitProcessInstrFunc_t processFunc, void* context)
2717 {
2718     insGroup*  ig;
2719     instrDesc* id;
2720     int        insRemaining;
2721
2722     if (!emitGetLocationInfo(locFrom, &ig, &id, &insRemaining))
2723         return; // no instructions at the 'from' location
2724
2725     do
2726     {
2727         // process <<id>>
2728         (*processFunc)(id, context);
2729
2730     } while (emitNextID(ig, id, insRemaining));
2731 }
2732
2733 /*****************************************************************************
2734  *
2735  * A callback function for emitWalkIDs() that calls Compiler::unwindNop().
2736  */
2737
2738 void emitter::emitGenerateUnwindNop(instrDesc* id, void* context)
2739 {
2740     Compiler* comp = (Compiler*)context;
2741 #if defined(_TARGET_ARM_)
2742     comp->unwindNop(id->idCodeSize());
2743 #elif defined(_TARGET_ARM64_)
2744     comp->unwindNop();
2745 #endif // defined(_TARGET_ARM64_)
2746 }
2747
2748 /*****************************************************************************
2749  *
2750  * emitUnwindNopPadding: call unwindNop() for every instruction from a given
2751  * location 'emitLoc' up to the current location.
2752  */
2753
2754 void emitter::emitUnwindNopPadding(emitLocation* locFrom, Compiler* comp)
2755 {
2756     emitWalkIDs(locFrom, emitGenerateUnwindNop, comp);
2757 }
2758
2759 #endif // _TARGET_ARMARCH_
2760
2761 #if defined(_TARGET_ARM_)
2762
2763 /*****************************************************************************
2764  *
2765  * Return the instruction size in bytes for the instruction at the specified location.
2766  * This is used to assert that the unwind code being generated on ARM has the
2767  * same size as the instruction for which it is being generated (since on ARM
2768  * the unwind codes have a one-to-one relationship with instructions, and the
2769  * unwind codes have an implicit instruction size that must match the instruction size.)
2770  * An instruction must exist at the specified location.
2771  */
2772
2773 unsigned emitter::emitGetInstructionSize(emitLocation* emitLoc)
2774 {
2775     insGroup*  ig;
2776     instrDesc* id;
2777
2778     bool anyInstrs = emitGetLocationInfo(emitLoc, &ig, &id);
2779     assert(anyInstrs); // There better be an instruction at this location (otherwise, we're at the end of the
2780                        // instruction list)
2781     return id->idCodeSize();
2782 }
2783
2784 #endif // defined(_TARGET_ARM_)
2785
2786 /*****************************************************************************/
2787 #ifdef DEBUG
2788 /*****************************************************************************
2789  *
2790  *  Returns the name for the register to use to access frame based variables
2791  */
2792
2793 const char* emitter::emitGetFrameReg()
2794 {
2795     if (emitHasFramePtr)
2796     {
2797         return STR_FPBASE;
2798     }
2799     else
2800     {
2801         return STR_SPBASE;
2802     }
2803 }
2804
2805 /*****************************************************************************
2806  *
2807  *  Display a register set in a readable form.
2808  */
2809
2810 void emitter::emitDispRegSet(regMaskTP regs)
2811 {
2812     regNumber reg;
2813     bool      sp = false;
2814
2815     printf(" {");
2816
2817     for (reg = REG_FIRST; reg < ACTUAL_REG_COUNT; reg = REG_NEXT(reg))
2818     {
2819         if ((regs & genRegMask(reg)) == 0)
2820         {
2821             continue;
2822         }
2823
2824         if (sp)
2825         {
2826             printf(" ");
2827         }
2828         else
2829         {
2830             sp = true;
2831         }
2832
2833         printf("%s", emitRegName(reg));
2834     }
2835
2836     printf("}");
2837 }
2838
2839 /*****************************************************************************
2840  *
2841  *  Display the current GC ref variable set in a readable form.
2842  */
2843
2844 void emitter::emitDispVarSet()
2845 {
2846     unsigned vn;
2847     int      of;
2848     bool     sp = false;
2849
2850     for (vn = 0, of = emitGCrFrameOffsMin; vn < emitGCrFrameOffsCnt; vn += 1, of += sizeof(void*))
2851     {
2852         if (emitGCrFrameLiveTab[vn])
2853         {
2854             if (sp)
2855             {
2856                 printf(" ");
2857             }
2858             else
2859             {
2860                 sp = true;
2861             }
2862
2863             printf("[%s", emitGetFrameReg());
2864
2865             if (of < 0)
2866             {
2867                 printf("-%02XH", -of);
2868             }
2869             else if (of > 0)
2870             {
2871                 printf("+%02XH", +of);
2872             }
2873
2874             printf("]");
2875         }
2876     }
2877
2878     if (!sp)
2879     {
2880         printf("none");
2881     }
2882 }
2883
2884 /*****************************************************************************/
2885 #endif // DEBUG
2886
2887 #if MULTIREG_HAS_SECOND_GC_RET
2888 //------------------------------------------------------------------------
2889 // emitSetSecondRetRegGCType: Sets the GC type of the second return register for instrDescCGCA struct.
2890 //
2891 // Arguments:
2892 //    id            - The large call instr descriptor to set the second GC return register type on.
2893 //    secondRetSize - The EA_SIZE for second return register type.
2894 //
2895 // Return Value:
2896 //    None
2897 //
2898
2899 void emitter::emitSetSecondRetRegGCType(instrDescCGCA* id, emitAttr secondRetSize)
2900 {
2901     if (EA_IS_GCREF(secondRetSize))
2902     {
2903         id->idSecondGCref(GCT_GCREF);
2904     }
2905     else if (EA_IS_BYREF(secondRetSize))
2906     {
2907         id->idSecondGCref(GCT_BYREF);
2908     }
2909     else
2910     {
2911         id->idSecondGCref(GCT_NONE);
2912     }
2913 }
2914 #endif // MULTIREG_HAS_SECOND_GC_RET
2915
2916 /*****************************************************************************
2917  *
2918  *  Allocate an instruction descriptor for an indirect call.
2919  *
2920  *  We use two different descriptors to save space - the common case records
2921  *  no GC variables and has both a very small argument count and an address
2922  *  mode displacement; the other case records the current GC var set,
2923  *  the call scope, and an arbitrarily large argument count and the
2924  *  address mode displacement.
2925  */
2926
2927 emitter::instrDesc* emitter::emitNewInstrCallInd(int              argCnt,
2928                                                  ssize_t          disp,
2929                                                  VARSET_VALARG_TP GCvars,
2930                                                  regMaskTP        gcrefRegs,
2931                                                  regMaskTP        byrefRegs,
2932                                                  emitAttr         retSizeIn
2933                                                      MULTIREG_HAS_SECOND_GC_RET_ONLY_ARG(emitAttr secondRetSize))
2934 {
2935     emitAttr retSize = (retSizeIn != EA_UNKNOWN) ? retSizeIn : EA_PTRSIZE;
2936
2937     bool gcRefRegsInScratch = ((gcrefRegs & RBM_CALLEE_TRASH) != 0);
2938
2939     // Allocate a larger descriptor if any GC values need to be saved
2940     // or if we have an absurd number of arguments or a large address
2941     // mode displacement, or we have some byref registers
2942     //
2943     // On Amd64 System V OSs a larger descriptor is also needed if the
2944     // call returns a two-register-returned struct and the second
2945     // register (RDX) is a GCRef or ByRef pointer.
2946
2947     if (!VarSetOps::IsEmpty(emitComp, GCvars) || // any frame GCvars live
2948         (gcRefRegsInScratch) ||                  // any register gc refs live in scratch regs
2949         (byrefRegs != 0) ||                      // any register byrefs live
2950         (disp < AM_DISP_MIN) ||                  // displacement too negative
2951         (disp > AM_DISP_MAX) ||                  // displacement too positive
2952         (argCnt > ID_MAX_SMALL_CNS) ||           // too many args
2953         (argCnt < 0)                             // caller pops arguments
2954                                                  // There is a second ref/byref return register.
2955         MULTIREG_HAS_SECOND_GC_RET_ONLY(|| EA_IS_GCREF_OR_BYREF(secondRetSize)))
2956     {
2957         instrDescCGCA* id;
2958
2959         id = emitAllocInstrCGCA(retSize);
2960
2961         id->idSetIsLargeCall();
2962
2963         VarSetOps::Assign(emitComp, id->idcGCvars, GCvars);
2964         id->idcGcrefRegs = gcrefRegs;
2965         id->idcByrefRegs = byrefRegs;
2966         id->idcArgCnt    = argCnt;
2967         id->idcDisp      = disp;
2968
2969 #if MULTIREG_HAS_SECOND_GC_RET
2970         emitSetSecondRetRegGCType(id, secondRetSize);
2971 #endif // MULTIREG_HAS_SECOND_GC_RET
2972
2973         return id;
2974     }
2975     else
2976     {
2977         instrDesc* id;
2978
2979         id = emitNewInstrCns(retSize, argCnt);
2980
2981         /* Make sure we didn't waste space unexpectedly */
2982         assert(!id->idIsLargeCns());
2983
2984         /* Store the displacement and make sure the value fit */
2985         id->idAddr()->iiaAddrMode.amDisp = disp;
2986         assert(id->idAddr()->iiaAddrMode.amDisp == disp);
2987
2988         /* Save the the live GC registers in the unused register fields */
2989         emitEncodeCallGCregs(gcrefRegs, id);
2990
2991         return id;
2992     }
2993 }
2994
2995 /*****************************************************************************
2996  *
2997  *  Allocate an instruction descriptor for a direct call.
2998  *
2999  *  We use two different descriptors to save space - the common case records
3000  *  with no GC variables or byrefs and has a very small argument count, and no
3001  *  explicit scope;
3002  *  the other case records the current GC var set, the call scope,
3003  *  and an arbitrarily large argument count.
3004  */
3005
3006 emitter::instrDesc* emitter::emitNewInstrCallDir(int              argCnt,
3007                                                  VARSET_VALARG_TP GCvars,
3008                                                  regMaskTP        gcrefRegs,
3009                                                  regMaskTP        byrefRegs,
3010                                                  emitAttr         retSizeIn
3011                                                      MULTIREG_HAS_SECOND_GC_RET_ONLY_ARG(emitAttr secondRetSize))
3012 {
3013     emitAttr retSize = (retSizeIn != EA_UNKNOWN) ? retSizeIn : EA_PTRSIZE;
3014
3015     // Allocate a larger descriptor if new GC values need to be saved
3016     // or if we have an absurd number of arguments or if we need to
3017     // save the scope.
3018     //
3019     // On Amd64 System V OSs a larger descriptor is also needed if the
3020     // call returns a two-register-returned struct and the second
3021     // register (RDX) is a GCRef or ByRef pointer.
3022
3023     bool gcRefRegsInScratch = ((gcrefRegs & RBM_CALLEE_TRASH) != 0);
3024
3025     if (!VarSetOps::IsEmpty(emitComp, GCvars) || // any frame GCvars live
3026         gcRefRegsInScratch ||                    // any register gc refs live in scratch regs
3027         (byrefRegs != 0) ||                      // any register byrefs live
3028         (argCnt > ID_MAX_SMALL_CNS) ||           // too many args
3029         (argCnt < 0)                             // caller pops arguments
3030                                                  // There is a second ref/byref return register.
3031         MULTIREG_HAS_SECOND_GC_RET_ONLY(|| EA_IS_GCREF_OR_BYREF(secondRetSize)))
3032     {
3033         instrDescCGCA* id = emitAllocInstrCGCA(retSize);
3034
3035         // printf("Direct call with GC vars / big arg cnt / explicit scope\n");
3036
3037         id->idSetIsLargeCall();
3038
3039         VarSetOps::Assign(emitComp, id->idcGCvars, GCvars);
3040         id->idcGcrefRegs = gcrefRegs;
3041         id->idcByrefRegs = byrefRegs;
3042         id->idcDisp      = 0;
3043         id->idcArgCnt    = argCnt;
3044
3045 #if MULTIREG_HAS_SECOND_GC_RET
3046         emitSetSecondRetRegGCType(id, secondRetSize);
3047 #endif // MULTIREG_HAS_SECOND_GC_RET
3048
3049         return id;
3050     }
3051     else
3052     {
3053         instrDesc* id = emitNewInstrCns(retSize, argCnt);
3054
3055         // printf("Direct call w/o  GC vars / big arg cnt / explicit scope\n");
3056
3057         /* Make sure we didn't waste space unexpectedly */
3058         assert(!id->idIsLargeCns());
3059
3060         /* Save the the live GC registers in the unused register fields */
3061         emitEncodeCallGCregs(gcrefRegs, id);
3062
3063         return id;
3064     }
3065 }
3066
3067 /*****************************************************************************/
3068 #ifdef DEBUG
3069 /*****************************************************************************
3070  *
3071  *  Return a string with the name of the given class field (blank string (not
3072  *  NULL) is returned when the name isn't available).
3073  */
3074
3075 const char* emitter::emitFldName(CORINFO_FIELD_HANDLE fieldVal)
3076 {
3077     if (emitComp->opts.varNames)
3078     {
3079         const char* memberName;
3080         const char* className;
3081
3082         const int   TEMP_BUFFER_LEN = 1024;
3083         static char buff[TEMP_BUFFER_LEN];
3084
3085         memberName = emitComp->eeGetFieldName(fieldVal, &className);
3086
3087         sprintf_s(buff, TEMP_BUFFER_LEN, "'<%s>.%s'", className, memberName);
3088         return buff;
3089     }
3090     else
3091     {
3092         return "";
3093     }
3094 }
3095
3096 /*****************************************************************************
3097  *
3098  *  Return a string with the name of the given function (blank string (not
3099  *  NULL) is returned when the name isn't available).
3100  */
3101
3102 const char* emitter::emitFncName(CORINFO_METHOD_HANDLE methHnd)
3103 {
3104     return emitComp->eeGetMethodFullName(methHnd);
3105 }
3106
3107 #endif // DEBUG
3108
3109 /*****************************************************************************
3110  *
3111  *  Be very careful, some instruction descriptors are allocated as "tiny" and
3112  *  don't have some of the tail fields of instrDesc (in particular, "idInfo").
3113  */
3114
3115 const BYTE emitter::emitFmtToOps[] = {
3116 #define IF_DEF(en, op1, op2) ID_OP_##op2,
3117 #include "emitfmts.h"
3118 };
3119
3120 #ifdef DEBUG
3121 const unsigned emitter::emitFmtCount = sizeof(emitFmtToOps) / sizeof(emitFmtToOps[0]);
3122 #endif
3123
3124 /*****************************************************************************
3125  *
3126  *  Display the current instruction group list.
3127  */
3128
3129 #ifdef DEBUG
3130
3131 void emitter::emitDispIGflags(unsigned flags)
3132 {
3133     if (flags & IGF_GC_VARS)
3134     {
3135         printf(", gcvars");
3136     }
3137     if (flags & IGF_BYREF_REGS)
3138     {
3139         printf(", byref");
3140     }
3141 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
3142     if (flags & IGF_FINALLY_TARGET)
3143     {
3144         printf(", ftarget");
3145     }
3146 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
3147     if (flags & IGF_FUNCLET_PROLOG)
3148     {
3149         printf(", funclet prolog");
3150     }
3151     if (flags & IGF_FUNCLET_EPILOG)
3152     {
3153         printf(", funclet epilog");
3154     }
3155     if (flags & IGF_EPILOG)
3156     {
3157         printf(", epilog");
3158     }
3159     if (flags & IGF_NOGCINTERRUPT)
3160     {
3161         printf(", nogc");
3162     }
3163     if (flags & IGF_UPD_ISZ)
3164     {
3165         printf(", isz");
3166     }
3167     if (flags & IGF_EMIT_ADD)
3168     {
3169         printf(", emitadd");
3170     }
3171 }
3172
3173 void emitter::emitDispIG(insGroup* ig, insGroup* igPrev, bool verbose)
3174 {
3175     const int TEMP_BUFFER_LEN = 40;
3176     char      buff[TEMP_BUFFER_LEN];
3177
3178     sprintf_s(buff, TEMP_BUFFER_LEN, "G_M%03u_IG%02u:        ", Compiler::s_compMethodsCount, ig->igNum);
3179     printf("%s; ", buff);
3180     if ((igPrev == nullptr) || (igPrev->igFuncIdx != ig->igFuncIdx))
3181     {
3182         printf("func=%02u, ", ig->igFuncIdx);
3183     }
3184
3185     if (ig->igFlags & IGF_PLACEHOLDER)
3186     {
3187         insGroup* igPh = ig;
3188
3189         const char* pszType;
3190         switch (igPh->igPhData->igPhType)
3191         {
3192             case IGPT_PROLOG:
3193                 pszType = "prolog";
3194                 break;
3195             case IGPT_EPILOG:
3196                 pszType = "epilog";
3197                 break;
3198 #if FEATURE_EH_FUNCLETS
3199             case IGPT_FUNCLET_PROLOG:
3200                 pszType = "funclet prolog";
3201                 break;
3202             case IGPT_FUNCLET_EPILOG:
3203                 pszType = "funclet epilog";
3204                 break;
3205 #endif // FEATURE_EH_FUNCLETS
3206             default:
3207                 pszType = "UNKNOWN";
3208                 break;
3209         }
3210         printf("%s placeholder, next placeholder=", pszType);
3211         if (igPh->igPhData->igPhNext)
3212         {
3213             printf("IG%02u ", igPh->igPhData->igPhNext->igNum);
3214         }
3215         else
3216         {
3217             printf("<END>");
3218         }
3219
3220         if (igPh->igPhData->igPhBB != nullptr)
3221         {
3222             printf(", %s", igPh->igPhData->igPhBB->dspToString());
3223         }
3224
3225         emitDispIGflags(igPh->igFlags);
3226
3227         if (ig == emitCurIG)
3228         {
3229             printf(" <-- Current IG");
3230         }
3231         if (igPh == emitPlaceholderList)
3232         {
3233             printf(" <-- First placeholder");
3234         }
3235         if (igPh == emitPlaceholderLast)
3236         {
3237             printf(" <-- Last placeholder");
3238         }
3239         printf("\n");
3240
3241         printf("%*s;   PrevGCVars=%s ", strlen(buff), "",
3242                VarSetOps::ToString(emitComp, igPh->igPhData->igPhPrevGCrefVars));
3243         dumpConvertedVarSet(emitComp, igPh->igPhData->igPhPrevGCrefVars);
3244         printf(", PrevGCrefRegs=");
3245         printRegMaskInt(igPh->igPhData->igPhPrevGCrefRegs);
3246         emitDispRegSet(igPh->igPhData->igPhPrevGCrefRegs);
3247         printf(", PrevByrefRegs=");
3248         printRegMaskInt(igPh->igPhData->igPhPrevByrefRegs);
3249         emitDispRegSet(igPh->igPhData->igPhPrevByrefRegs);
3250         printf("\n");
3251
3252         printf("%*s;   InitGCVars=%s ", strlen(buff), "",
3253                VarSetOps::ToString(emitComp, igPh->igPhData->igPhInitGCrefVars));
3254         dumpConvertedVarSet(emitComp, igPh->igPhData->igPhInitGCrefVars);
3255         printf(", InitGCrefRegs=");
3256         printRegMaskInt(igPh->igPhData->igPhInitGCrefRegs);
3257         emitDispRegSet(igPh->igPhData->igPhInitGCrefRegs);
3258         printf(", InitByrefRegs=");
3259         printRegMaskInt(igPh->igPhData->igPhInitByrefRegs);
3260         emitDispRegSet(igPh->igPhData->igPhInitByrefRegs);
3261         printf("\n");
3262
3263         assert(!(ig->igFlags & IGF_GC_VARS));
3264         assert(!(ig->igFlags & IGF_BYREF_REGS));
3265     }
3266     else
3267     {
3268         printf("offs=%06XH, size=%04XH", ig->igOffs, ig->igSize);
3269
3270         if (ig->igFlags & IGF_GC_VARS)
3271         {
3272             printf(", gcVars=%s ", VarSetOps::ToString(emitComp, ig->igGCvars()));
3273             dumpConvertedVarSet(emitComp, ig->igGCvars());
3274         }
3275
3276         if (!(ig->igFlags & IGF_EMIT_ADD))
3277         {
3278             printf(", gcrefRegs=");
3279             printRegMaskInt(ig->igGCregs);
3280             emitDispRegSet(ig->igGCregs);
3281         }
3282
3283         if (ig->igFlags & IGF_BYREF_REGS)
3284         {
3285             printf(", byrefRegs=");
3286             printRegMaskInt(ig->igByrefRegs());
3287             emitDispRegSet(ig->igByrefRegs());
3288         }
3289
3290         emitDispIGflags(ig->igFlags);
3291
3292         if (ig == emitCurIG)
3293         {
3294             printf(" <-- Current IG");
3295         }
3296         if (ig == emitPrologIG)
3297         {
3298             printf(" <-- Prolog IG");
3299         }
3300         printf("\n");
3301
3302         if (verbose)
3303         {
3304             BYTE*          ins = ig->igData;
3305             UNATIVE_OFFSET ofs = ig->igOffs;
3306             unsigned       cnt = ig->igInsCnt;
3307
3308             if (cnt)
3309             {
3310                 printf("\n");
3311
3312                 do
3313                 {
3314                     instrDesc* id = (instrDesc*)ins;
3315
3316                     emitDispIns(id, false, true, false, ofs, nullptr, 0, ig);
3317
3318                     ins += emitSizeOfInsDsc(id);
3319                     ofs += emitInstCodeSz(id);
3320                 } while (--cnt);
3321
3322                 printf("\n");
3323             }
3324         }
3325     }
3326 }
3327
3328 void emitter::emitDispIGlist(bool verbose)
3329 {
3330     insGroup* ig;
3331     insGroup* igPrev;
3332
3333     for (igPrev = nullptr, ig = emitIGlist; ig; igPrev = ig, ig = ig->igNext)
3334     {
3335         emitDispIG(ig, igPrev, verbose);
3336     }
3337 }
3338
3339 void emitter::emitDispGCinfo()
3340 {
3341     printf("Emitter GC tracking info:");
3342     printf("\n  emitPrevGCrefVars ");
3343     dumpConvertedVarSet(emitComp, emitPrevGCrefVars);
3344     printf("\n  emitPrevGCrefRegs(0x%p)=", dspPtr(&emitPrevGCrefRegs));
3345     printRegMaskInt(emitPrevGCrefRegs);
3346     emitDispRegSet(emitPrevGCrefRegs);
3347     printf("\n  emitPrevByrefRegs(0x%p)=", dspPtr(&emitPrevByrefRegs));
3348     printRegMaskInt(emitPrevByrefRegs);
3349     emitDispRegSet(emitPrevByrefRegs);
3350     printf("\n  emitInitGCrefVars ");
3351     dumpConvertedVarSet(emitComp, emitInitGCrefVars);
3352     printf("\n  emitInitGCrefRegs(0x%p)=", dspPtr(&emitInitGCrefRegs));
3353     printRegMaskInt(emitInitGCrefRegs);
3354     emitDispRegSet(emitInitGCrefRegs);
3355     printf("\n  emitInitByrefRegs(0x%p)=", dspPtr(&emitInitByrefRegs));
3356     printRegMaskInt(emitInitByrefRegs);
3357     emitDispRegSet(emitInitByrefRegs);
3358     printf("\n  emitThisGCrefVars ");
3359     dumpConvertedVarSet(emitComp, emitThisGCrefVars);
3360     printf("\n  emitThisGCrefRegs(0x%p)=", dspPtr(&emitThisGCrefRegs));
3361     printRegMaskInt(emitThisGCrefRegs);
3362     emitDispRegSet(emitThisGCrefRegs);
3363     printf("\n  emitThisByrefRegs(0x%p)=", dspPtr(&emitThisByrefRegs));
3364     printRegMaskInt(emitThisByrefRegs);
3365     emitDispRegSet(emitThisByrefRegs);
3366     printf("\n\n");
3367 }
3368
3369 #endif // DEBUG
3370
3371 /*****************************************************************************
3372  *
3373  *  Issue the given instruction. Basically, this is just a thin wrapper around
3374  *  emitOutputInstr() that does a few debug checks.
3375  */
3376
3377 size_t emitter::emitIssue1Instr(insGroup* ig, instrDesc* id, BYTE** dp)
3378 {
3379     size_t is;
3380
3381     /* Record the beginning offset of the instruction */
3382
3383     BYTE* curInsAdr = *dp;
3384
3385     /* Issue the next instruction */
3386
3387     // printf("[S=%02u] " , emitCurStackLvl);
3388
3389     is = emitOutputInstr(ig, id, dp);
3390
3391 // printf("[S=%02u]\n", emitCurStackLvl);
3392
3393 #if EMIT_TRACK_STACK_DEPTH
3394
3395     /*
3396         If we're generating a full pointer map and the stack
3397         is empty, there better not be any "pending" argument
3398         push entries.
3399      */
3400
3401     assert(emitFullGCinfo == false || emitCurStackLvl != 0 || u2.emitGcArgTrackCnt == 0);
3402
3403 #endif
3404
3405     /* Did the size of the instruction match our expectations? */
3406
3407     UNATIVE_OFFSET csz = (UNATIVE_OFFSET)(*dp - curInsAdr);
3408
3409     if (csz != id->idCodeSize())
3410     {
3411         /* It is fatal to under-estimate the instruction size */
3412         noway_assert(emitInstCodeSz(id) >= csz);
3413
3414 #if DEBUG_EMIT
3415         if (EMITVERBOSE)
3416         {
3417             printf("Instruction predicted size = %u, actual = %u\n", emitInstCodeSz(id), csz);
3418         }
3419 #endif // DEBUG_EMIT
3420
3421         /* The instruction size estimate wasn't accurate; remember this */
3422
3423         ig->igFlags |= IGF_UPD_ISZ;
3424 #if defined(_TARGET_XARCH_)
3425         id->idCodeSize(csz);
3426 #elif defined(_TARGET_ARM_)
3427 // This is done as part of emitSetShortJump();
3428 // insSize isz = emitInsSize(id->idInsFmt());
3429 // id->idInsSize(isz);
3430 #else
3431         /* It is fatal to over-estimate the instruction size */
3432         IMPL_LIMITATION("Over-estimated instruction size");
3433 #endif
3434     }
3435
3436 #ifdef DEBUG
3437     /* Make sure the instruction descriptor size also matches our expectations */
3438     if (is != emitSizeOfInsDsc(id))
3439     {
3440         printf("%s at %u: Expected size = %u , actual size = %u\n", emitIfName(id->idInsFmt()),
3441                id->idDebugOnlyInfo()->idNum, is, emitSizeOfInsDsc(id));
3442         assert(is == emitSizeOfInsDsc(id));
3443     }
3444 #endif
3445
3446     return is;
3447 }
3448
3449 /*****************************************************************************
3450  *
3451  *  Update the offsets of all the instruction groups (note: please don't be
3452  *  lazy and call this routine frequently, it walks the list of instruction
3453  *  groups and thus it isn't cheap).
3454  */
3455
3456 void emitter::emitRecomputeIGoffsets()
3457 {
3458     UNATIVE_OFFSET offs;
3459     insGroup*      ig;
3460
3461     for (ig = emitIGlist, offs = 0; ig; ig = ig->igNext)
3462     {
3463         ig->igOffs = offs;
3464         assert(IsCodeAligned(ig->igOffs));
3465         offs += ig->igSize;
3466     }
3467
3468     /* Set the total code size */
3469
3470     emitTotalCodeSize = offs;
3471
3472 #ifdef DEBUG
3473     emitCheckIGoffsets();
3474 #endif
3475 }
3476
3477 /*****************************************************************************
3478  *  Bind targets of relative jumps to choose the smallest possible encoding.
3479  *  X86 and AMD64 have a small and large encoding.
3480  *  ARM has a small, medium, and large encoding. The large encoding is a pseudo-op
3481  *      to handle greater range than the conditional branch instructions can handle.
3482  *  ARM64 has a small and large encoding for both conditional branch and loading label addresses.
3483  *      The large encodings are pseudo-ops that represent a multiple instruction sequence, similar to ARM. (Currently
3484  *      NYI).
3485  */
3486
3487 void emitter::emitJumpDistBind()
3488 {
3489 #ifdef DEBUG
3490     if (emitComp->verbose)
3491     {
3492         printf("*************** In emitJumpDistBind()\n");
3493     }
3494     if (EMIT_INSTLIST_VERBOSE)
3495     {
3496         printf("\nInstruction list before jump distance binding:\n\n");
3497         emitDispIGlist(true);
3498     }
3499 #endif
3500
3501     instrDescJmp* jmp;
3502
3503     UNATIVE_OFFSET minShortExtra; // The smallest offset greater than that required for a jump to be converted
3504                                   // to a small jump. If it is small enough, we will iterate in hopes of
3505                                   // converting those jumps we missed converting the first (or second...) time.
3506
3507 #if defined(_TARGET_ARM_)
3508     UNATIVE_OFFSET minMediumExtra; // Same as 'minShortExtra', but for medium-sized jumps.
3509 #endif                             // _TARGET_ARM_
3510
3511     UNATIVE_OFFSET adjIG;
3512     UNATIVE_OFFSET adjLJ;
3513     insGroup*      lstIG;
3514 #ifdef DEBUG
3515     insGroup* prologIG = emitPrologIG;
3516 #endif // DEBUG
3517
3518     int jmp_iteration = 1;
3519
3520 /*****************************************************************************/
3521 /* If we iterate to look for more jumps to shorten, we start again here.     */
3522 /*****************************************************************************/
3523
3524 AGAIN:
3525
3526 #ifdef DEBUG
3527     emitCheckIGoffsets();
3528 #endif
3529
3530 /*
3531     In the following loop we convert all jump targets from "BasicBlock *"
3532     to "insGroup *" values. We also estimate which jumps will be short.
3533  */
3534
3535 #ifdef DEBUG
3536     insGroup*     lastIG = nullptr;
3537     instrDescJmp* lastLJ = nullptr;
3538 #endif
3539
3540     lstIG         = nullptr;
3541     adjLJ         = 0;
3542     adjIG         = 0;
3543     minShortExtra = (UNATIVE_OFFSET)-1;
3544
3545 #if defined(_TARGET_ARM_)
3546     minMediumExtra = (UNATIVE_OFFSET)-1;
3547 #endif // _TARGET_ARM_
3548
3549     for (jmp = emitJumpList; jmp; jmp = jmp->idjNext)
3550     {
3551         insGroup* jmpIG;
3552         insGroup* tgtIG;
3553
3554         UNATIVE_OFFSET jsz; // size of the jump instruction in bytes
3555
3556         UNATIVE_OFFSET ssz = 0; // small  jump size
3557         NATIVE_OFFSET  nsd = 0; // small  jump max. neg distance
3558         NATIVE_OFFSET  psd = 0; // small  jump max. pos distance
3559
3560 #if defined(_TARGET_ARM_)
3561         UNATIVE_OFFSET msz = 0; // medium jump size
3562         NATIVE_OFFSET  nmd = 0; // medium jump max. neg distance
3563         NATIVE_OFFSET  pmd = 0; // medium jump max. pos distance
3564         NATIVE_OFFSET  mextra;  // How far beyond the medium jump range is this jump offset?
3565 #endif                          // _TARGET_ARM_
3566
3567         NATIVE_OFFSET  extra;           // How far beyond the short jump range is this jump offset?
3568         UNATIVE_OFFSET srcInstrOffs;    // offset of the source instruction of the jump
3569         UNATIVE_OFFSET srcEncodingOffs; // offset of the source used by the instruction set to calculate the relative
3570                                         // offset of the jump
3571         UNATIVE_OFFSET dstOffs;
3572         NATIVE_OFFSET  jmpDist; // the relative jump distance, as it will be encoded
3573         UNATIVE_OFFSET oldSize;
3574         UNATIVE_OFFSET sizeDif;
3575
3576 #ifdef _TARGET_XARCH_
3577         assert(jmp->idInsFmt() == IF_LABEL || jmp->idInsFmt() == IF_RWR_LABEL || jmp->idInsFmt() == IF_SWR_LABEL);
3578
3579         /* Figure out the smallest size we can end up with */
3580
3581         if (jmp->idInsFmt() == IF_LABEL)
3582         {
3583             if (emitIsCondJump(jmp))
3584             {
3585                 ssz = JCC_SIZE_SMALL;
3586                 nsd = JCC_DIST_SMALL_MAX_NEG;
3587                 psd = JCC_DIST_SMALL_MAX_POS;
3588             }
3589             else
3590             {
3591                 ssz = JMP_SIZE_SMALL;
3592                 nsd = JMP_DIST_SMALL_MAX_NEG;
3593                 psd = JMP_DIST_SMALL_MAX_POS;
3594             }
3595         }
3596 #endif // _TARGET_XARCH_
3597
3598 #ifdef _TARGET_ARM_
3599         assert((jmp->idInsFmt() == IF_T2_J1) || (jmp->idInsFmt() == IF_T2_J2) || (jmp->idInsFmt() == IF_T1_I) ||
3600                (jmp->idInsFmt() == IF_T1_K) || (jmp->idInsFmt() == IF_T1_M) || (jmp->idInsFmt() == IF_T2_M1) ||
3601                (jmp->idInsFmt() == IF_T2_N1) || (jmp->idInsFmt() == IF_T1_J3) || (jmp->idInsFmt() == IF_LARGEJMP));
3602
3603         /* Figure out the smallest size we can end up with */
3604
3605         if (emitIsCondJump(jmp))
3606         {
3607             ssz = JCC_SIZE_SMALL;
3608             nsd = JCC_DIST_SMALL_MAX_NEG;
3609             psd = JCC_DIST_SMALL_MAX_POS;
3610
3611             msz = JCC_SIZE_MEDIUM;
3612             nmd = JCC_DIST_MEDIUM_MAX_NEG;
3613             pmd = JCC_DIST_MEDIUM_MAX_POS;
3614         }
3615         else if (emitIsCmpJump(jmp))
3616         {
3617             ssz = JMP_SIZE_SMALL;
3618             nsd = 0;
3619             psd = 126;
3620         }
3621         else if (emitIsUncondJump(jmp))
3622         {
3623             ssz = JMP_SIZE_SMALL;
3624             nsd = JMP_DIST_SMALL_MAX_NEG;
3625             psd = JMP_DIST_SMALL_MAX_POS;
3626         }
3627         else if (emitIsLoadLabel(jmp))
3628         {
3629             ssz = LBL_SIZE_SMALL;
3630             nsd = LBL_DIST_SMALL_MAX_NEG;
3631             psd = LBL_DIST_SMALL_MAX_POS;
3632         }
3633         else
3634         {
3635             assert(!"Unknown jump instruction");
3636         }
3637 #endif // _TARGET_ARM_
3638
3639 #ifdef _TARGET_ARM64_
3640         /* Figure out the smallest size we can end up with */
3641
3642         if (emitIsCondJump(jmp))
3643         {
3644             ssz         = JCC_SIZE_SMALL;
3645             bool isTest = (jmp->idIns() == INS_tbz) || (jmp->idIns() == INS_tbnz);
3646
3647             nsd = (isTest) ? TB_DIST_SMALL_MAX_NEG : JCC_DIST_SMALL_MAX_NEG;
3648             psd = (isTest) ? TB_DIST_SMALL_MAX_POS : JCC_DIST_SMALL_MAX_POS;
3649         }
3650         else if (emitIsUncondJump(jmp))
3651         {
3652             // Nothing to do; we don't shrink these.
3653             assert(jmp->idjShort);
3654             ssz = JMP_SIZE_SMALL;
3655         }
3656         else if (emitIsLoadLabel(jmp))
3657         {
3658             ssz = LBL_SIZE_SMALL;
3659             nsd = LBL_DIST_SMALL_MAX_NEG;
3660             psd = LBL_DIST_SMALL_MAX_POS;
3661         }
3662         else if (emitIsLoadConstant(jmp))
3663         {
3664             ssz = LDC_SIZE_SMALL;
3665             nsd = LDC_DIST_SMALL_MAX_NEG;
3666             psd = LDC_DIST_SMALL_MAX_POS;
3667         }
3668         else
3669         {
3670             assert(!"Unknown jump instruction");
3671         }
3672 #endif // _TARGET_ARM64_
3673
3674 /* Make sure the jumps are properly ordered */
3675
3676 #ifdef DEBUG
3677         assert(lastLJ == nullptr || lastIG != jmp->idjIG || lastLJ->idjOffs < jmp->idjOffs);
3678         lastLJ = (lastIG == jmp->idjIG) ? jmp : nullptr;
3679
3680         assert(lastIG == nullptr || lastIG->igNum <= jmp->idjIG->igNum || jmp->idjIG == prologIG ||
3681                emitNxtIGnum > unsigned(0xFFFF)); // igNum might overflow
3682         lastIG = jmp->idjIG;
3683 #endif // DEBUG
3684
3685         /* Get hold of the current jump size */
3686
3687         jsz = emitSizeOfJump(jmp);
3688
3689         /* Get the group the jump is in */
3690
3691         jmpIG = jmp->idjIG;
3692
3693         /* Are we in a group different from the previous jump? */
3694
3695         if (lstIG != jmpIG)
3696         {
3697             /* Were there any jumps before this one? */
3698
3699             if (lstIG)
3700             {
3701                 /* Adjust the offsets of the intervening blocks */
3702
3703                 do
3704                 {
3705                     lstIG = lstIG->igNext;
3706                     assert(lstIG);
3707                     // printf("Adjusted offset of block %02u from %04X to %04X\n", lstIG->igNum, lstIG->igOffs,
3708                     // lstIG->igOffs - adjIG);
3709                     lstIG->igOffs -= adjIG;
3710                     assert(IsCodeAligned(lstIG->igOffs));
3711                 } while (lstIG != jmpIG);
3712             }
3713
3714             /* We've got the first jump in a new group */
3715
3716             adjLJ = 0;
3717             lstIG = jmpIG;
3718         }
3719
3720         /* Apply any local size adjustment to the jump's relative offset */
3721
3722         jmp->idjOffs -= adjLJ;
3723
3724         // If this is a jump via register, the instruction size does not change, so we are done.
3725         CLANG_FORMAT_COMMENT_ANCHOR;
3726
3727 #if defined(_TARGET_ARM64_)
3728         // JIT code and data will be allocated together for arm64 so the relative offset to JIT data is known.
3729         // In case such offset can be encodeable for `ldr` (+-1MB), shorten it.
3730         if (jmp->idAddr()->iiaIsJitDataOffset())
3731         {
3732             // Reference to JIT data
3733             assert(jmp->idIsBound());
3734             UNATIVE_OFFSET srcOffs = jmpIG->igOffs + jmp->idjOffs;
3735
3736             int doff = jmp->idAddr()->iiaGetJitDataOffset();
3737             assert(doff >= 0);
3738             ssize_t imm = emitGetInsSC(jmp);
3739             assert((imm >= 0) && (imm < 0x1000)); // 0x1000 is arbitrary, currently 'imm' is always 0
3740
3741             unsigned dataOffs = (unsigned)(doff + imm);
3742             assert(dataOffs < emitDataSize());
3743
3744             // Conservately assume JIT data starts after the entire code size.
3745             // TODO-ARM64: we might consider only hot code size which will be computed later in emitComputeCodeSizes().
3746             assert(emitTotalCodeSize > 0);
3747             UNATIVE_OFFSET maxDstOffs = emitTotalCodeSize + dataOffs;
3748
3749             // Check if the distance is within the encoding length.
3750             jmpDist = maxDstOffs - srcOffs;
3751             extra   = jmpDist - psd;
3752             if (extra <= 0)
3753             {
3754                 goto SHORT_JMP;
3755             }
3756
3757             // Keep the large form.
3758             continue;
3759         }
3760 #endif
3761
3762         /* Have we bound this jump's target already? */
3763
3764         if (jmp->idIsBound())
3765         {
3766             /* Does the jump already have the smallest size? */
3767
3768             if (jmp->idjShort)
3769             {
3770                 assert(emitSizeOfJump(jmp) == ssz);
3771
3772                 // We should not be jumping/branching across funclets/functions
3773                 emitCheckFuncletBranch(jmp, jmpIG);
3774
3775                 continue;
3776             }
3777
3778             tgtIG = jmp->idAddr()->iiaIGlabel;
3779         }
3780         else
3781         {
3782             /* First time we've seen this label, convert its target */
3783             CLANG_FORMAT_COMMENT_ANCHOR;
3784
3785 #ifdef DEBUG
3786             if (EMITVERBOSE)
3787             {
3788                 printf("Binding: ");
3789                 emitDispIns(jmp, false, false, false);
3790                 printf("Binding L_M%03u_BB%02u ", Compiler::s_compMethodsCount, jmp->idAddr()->iiaBBlabel->bbNum);
3791             }
3792 #endif // DEBUG
3793
3794             tgtIG = (insGroup*)emitCodeGetCookie(jmp->idAddr()->iiaBBlabel);
3795
3796 #ifdef DEBUG
3797             if (EMITVERBOSE)
3798             {
3799                 if (tgtIG)
3800                 {
3801                     printf("to G_M%03u_IG%02u\n", Compiler::s_compMethodsCount, tgtIG->igNum);
3802                 }
3803                 else
3804                 {
3805                     printf("-- ERROR, no emitter cookie for BB%02u; it is probably missing BBF_JMP_TARGET or "
3806                            "BBF_HAS_LABEL.\n",
3807                            jmp->idAddr()->iiaBBlabel->bbNum);
3808                 }
3809             }
3810             assert(tgtIG);
3811 #endif // DEBUG
3812
3813             /* Record the bound target */
3814
3815             jmp->idAddr()->iiaIGlabel = tgtIG;
3816             jmp->idSetIsBound();
3817         }
3818
3819         // We should not be jumping/branching across funclets/functions
3820         emitCheckFuncletBranch(jmp, jmpIG);
3821
3822 #ifdef _TARGET_XARCH_
3823         /* Done if this is not a variable-sized jump */
3824
3825         if ((jmp->idIns() == INS_push) || (jmp->idIns() == INS_mov) || (jmp->idIns() == INS_call) ||
3826             (jmp->idIns() == INS_push_hide))
3827         {
3828             continue;
3829         }
3830 #endif
3831 #ifdef _TARGET_ARM_
3832         if ((jmp->idIns() == INS_push) || (jmp->idIns() == INS_mov) || (jmp->idIns() == INS_movt) ||
3833             (jmp->idIns() == INS_movw))
3834         {
3835             continue;
3836         }
3837 #endif
3838 #ifdef _TARGET_ARM64_
3839         // There is only one size of unconditional branch; we don't support functions larger than 2^28 bytes (our branch
3840         // range).
3841         if (emitIsUncondJump(jmp))
3842         {
3843             continue;
3844         }
3845 #endif
3846
3847         /*
3848             In the following distance calculations, if we're not actually
3849             scheduling the code (i.e. reordering instructions), we can
3850             use the actual offset of the jump (rather than the beg/end of
3851             the instruction group) since the jump will not be moved around
3852             and thus its offset is accurate.
3853
3854             First we need to figure out whether this jump is a forward or
3855             backward one; to do this we simply look at the ordinals of the
3856             group that contains the jump and the target.
3857          */
3858
3859         srcInstrOffs = jmpIG->igOffs + jmp->idjOffs;
3860
3861         /* Note that the destination is always the beginning of an IG, so no need for an offset inside it */
3862         dstOffs = tgtIG->igOffs;
3863
3864 #if defined(_TARGET_ARM_)
3865         srcEncodingOffs =
3866             srcInstrOffs + 4; // For relative branches, ARM PC is always considered to be the instruction address + 4
3867 #elif defined(_TARGET_ARM64_)
3868         srcEncodingOffs =
3869             srcInstrOffs; // For relative branches, ARM64 PC is always considered to be the instruction address
3870 #else
3871         srcEncodingOffs = srcInstrOffs + ssz; // Encoding offset of relative offset for small branch
3872 #endif
3873
3874         if (jmpIG->igNum < tgtIG->igNum)
3875         {
3876             /* Forward jump */
3877
3878             /* Adjust the target offset by the current delta. This is a worst-case estimate, as jumps between
3879                here and the target could be shortened, causing the actual distance to shrink.
3880              */
3881
3882             dstOffs -= adjIG;
3883
3884             /* Compute the distance estimate */
3885
3886             jmpDist = dstOffs - srcEncodingOffs;
3887
3888             /* How much beyond the max. short distance does the jump go? */
3889
3890             extra = jmpDist - psd;
3891
3892 #if DEBUG_EMIT
3893             assert(jmp->idDebugOnlyInfo() != nullptr);
3894             if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
3895             {
3896                 if (INTERESTING_JUMP_NUM == 0)
3897                 {
3898                     printf("[1] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
3899                 }
3900                 printf("[1] Jump  block is at %08X\n", jmpIG->igOffs);
3901                 printf("[1] Jump reloffset is %04X\n", jmp->idjOffs);
3902                 printf("[1] Jump source is at %08X\n", srcEncodingOffs);
3903                 printf("[1] Label block is at %08X\n", dstOffs);
3904                 printf("[1] Jump  dist. is    %04X\n", jmpDist);
3905                 if (extra > 0)
3906                 {
3907                     printf("[1] Dist excess [S] = %d  \n", extra);
3908                 }
3909             }
3910             if (EMITVERBOSE)
3911             {
3912                 printf("Estimate of fwd jump [%08X/%03u]: %04X -> %04X = %04X\n", dspPtr(jmp),
3913                        jmp->idDebugOnlyInfo()->idNum, srcInstrOffs, dstOffs, jmpDist);
3914             }
3915 #endif // DEBUG_EMIT
3916
3917             if (extra <= 0)
3918             {
3919                 /* This jump will be a short one */
3920                 goto SHORT_JMP;
3921             }
3922         }
3923         else
3924         {
3925             /* Backward jump */
3926
3927             /* Compute the distance estimate */
3928
3929             jmpDist = srcEncodingOffs - dstOffs;
3930
3931             /* How much beyond the max. short distance does the jump go? */
3932
3933             extra = jmpDist + nsd;
3934
3935 #if DEBUG_EMIT
3936             assert(jmp->idDebugOnlyInfo() != nullptr);
3937             if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
3938             {
3939                 if (INTERESTING_JUMP_NUM == 0)
3940                 {
3941                     printf("[2] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
3942                 }
3943                 printf("[2] Jump  block is at %08X\n", jmpIG->igOffs);
3944                 printf("[2] Jump reloffset is %04X\n", jmp->idjOffs);
3945                 printf("[2] Jump source is at %08X\n", srcEncodingOffs);
3946                 printf("[2] Label block is at %08X\n", dstOffs);
3947                 printf("[2] Jump  dist. is    %04X\n", jmpDist);
3948                 if (extra > 0)
3949                 {
3950                     printf("[2] Dist excess [S] = %d  \n", extra);
3951                 }
3952             }
3953             if (EMITVERBOSE)
3954             {
3955                 printf("Estimate of bwd jump [%08X/%03u]: %04X -> %04X = %04X\n", dspPtr(jmp),
3956                        jmp->idDebugOnlyInfo()->idNum, srcInstrOffs, dstOffs, jmpDist);
3957             }
3958 #endif // DEBUG_EMIT
3959
3960             if (extra <= 0)
3961             {
3962                 /* This jump will be a short one */
3963                 goto SHORT_JMP;
3964             }
3965         }
3966
3967         /* We arrive here if the jump couldn't be made short, at least for now */
3968
3969         /* We had better not have eagerly marked the jump as short
3970          * in emitIns_J(). If we did, then it has to be able to stay short
3971          * as emitIns_J() uses the worst case scenario, and blocks can
3972          * only move closer together after that.
3973          */
3974         assert(jmp->idjShort == 0);
3975
3976         /* Keep track of the closest distance we got */
3977
3978         if (minShortExtra > (unsigned)extra)
3979         {
3980             minShortExtra = (unsigned)extra;
3981         }
3982
3983 #if defined(_TARGET_ARM_)
3984
3985         // If we're here, we couldn't convert to a small jump.
3986         // Handle conversion to medium-sized conditional jumps.
3987         // 'srcInstrOffs', 'srcEncodingOffs', 'dstOffs', 'jmpDist' have already been computed
3988         // and don't need to be recomputed.
3989
3990         if (emitIsCondJump(jmp))
3991         {
3992             if (jmpIG->igNum < tgtIG->igNum)
3993             {
3994                 /* Forward jump */
3995
3996                 /* How much beyond the max. medium distance does the jump go? */
3997
3998                 mextra = jmpDist - pmd;
3999
4000 #if DEBUG_EMIT
4001                 assert(jmp->idDebugOnlyInfo() != NULL);
4002                 if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
4003                 {
4004                     if (mextra > 0)
4005                     {
4006                         if (INTERESTING_JUMP_NUM == 0)
4007                             printf("[6] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
4008                         printf("[6] Dist excess [S] = %d  \n", mextra);
4009                     }
4010                 }
4011 #endif // DEBUG_EMIT
4012
4013                 if (mextra <= 0)
4014                 {
4015                     /* This jump will be a medium one */
4016                     goto MEDIUM_JMP;
4017                 }
4018             }
4019             else
4020             {
4021                 /* Backward jump */
4022
4023                 /* How much beyond the max. medium distance does the jump go? */
4024
4025                 mextra = jmpDist + nmd;
4026
4027 #if DEBUG_EMIT
4028                 assert(jmp->idDebugOnlyInfo() != NULL);
4029                 if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
4030                 {
4031                     if (mextra > 0)
4032                     {
4033                         if (INTERESTING_JUMP_NUM == 0)
4034                             printf("[7] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
4035                         printf("[7] Dist excess [S] = %d  \n", mextra);
4036                     }
4037                 }
4038 #endif // DEBUG_EMIT
4039
4040                 if (mextra <= 0)
4041                 {
4042                     /* This jump will be a medium one */
4043                     goto MEDIUM_JMP;
4044                 }
4045             }
4046
4047             /* We arrive here if the jump couldn't be made medium, at least for now */
4048
4049             /* Keep track of the closest distance we got */
4050
4051             if (minMediumExtra > (unsigned)mextra)
4052                 minMediumExtra = (unsigned)mextra;
4053         }
4054
4055 #endif // _TARGET_ARM_
4056
4057         /*****************************************************************************
4058          * We arrive here if the jump must stay long, at least for now.
4059          * Go try the next one.
4060          */
4061
4062         continue;
4063
4064     /*****************************************************************************/
4065     /* Handle conversion to short jump                                           */
4066     /*****************************************************************************/
4067
4068     SHORT_JMP:
4069
4070         /* Try to make this jump a short one */
4071
4072         emitSetShortJump(jmp);
4073
4074         if (!jmp->idjShort)
4075         {
4076             continue; // This jump must be kept long
4077         }
4078
4079         /* This jump is becoming either short or medium */
4080
4081         oldSize = jsz;
4082         jsz     = ssz;
4083         assert(oldSize >= jsz);
4084         sizeDif = oldSize - jsz;
4085
4086 #if defined(_TARGET_XARCH_)
4087         jmp->idCodeSize(jsz);
4088 #elif defined(_TARGET_ARM_)
4089 #if 0
4090         // This is done as part of emitSetShortJump():
4091         insSize isz = emitInsSize(jmp->idInsFmt());
4092         jmp->idInsSize(isz);
4093 #endif
4094 #elif defined(_TARGET_ARM64_)
4095         // The size of IF_LARGEJMP/IF_LARGEADR/IF_LARGELDC are 8 or 12.
4096         // All other code size is 4.
4097         assert((sizeDif == 4) || (sizeDif == 8));
4098 #else
4099 #error Unsupported or unset target architecture
4100 #endif
4101
4102         goto NEXT_JMP;
4103
4104 #if defined(_TARGET_ARM_)
4105
4106     /*****************************************************************************/
4107     /* Handle conversion to medium jump                                          */
4108     /*****************************************************************************/
4109
4110     MEDIUM_JMP:
4111
4112         /* Try to make this jump a medium one */
4113
4114         emitSetMediumJump(jmp);
4115
4116         if (jmp->idCodeSize() > msz)
4117         {
4118             continue; // This jump wasn't shortened
4119         }
4120         assert(jmp->idCodeSize() == msz);
4121
4122         /* This jump is becoming medium */
4123
4124         oldSize = jsz;
4125         jsz     = msz;
4126         assert(oldSize >= jsz);
4127         sizeDif = oldSize - jsz;
4128
4129         goto NEXT_JMP;
4130
4131 #endif // _TARGET_ARM_
4132
4133     /*****************************************************************************/
4134
4135     NEXT_JMP:
4136
4137         /* Make sure the size of the jump is marked correctly */
4138
4139         assert((0 == (jsz | jmpDist)) || (jsz == emitSizeOfJump(jmp)));
4140
4141 #ifdef DEBUG
4142         if (EMITVERBOSE)
4143         {
4144             printf("Shrinking jump [%08X/%03u]\n", dspPtr(jmp), jmp->idDebugOnlyInfo()->idNum);
4145         }
4146 #endif
4147         noway_assert((unsigned short)sizeDif == sizeDif);
4148
4149         adjIG += sizeDif;
4150         adjLJ += sizeDif;
4151         jmpIG->igSize -= (unsigned short)sizeDif;
4152         emitTotalCodeSize -= sizeDif;
4153
4154         /* The jump size estimate wasn't accurate; flag its group */
4155
4156         jmpIG->igFlags |= IGF_UPD_ISZ;
4157
4158     } // end for each jump
4159
4160     /* Did we shorten any jumps? */
4161
4162     if (adjIG)
4163     {
4164         /* Adjust offsets of any remaining blocks */
4165
4166         assert(lstIG);
4167
4168         for (;;)
4169         {
4170             lstIG = lstIG->igNext;
4171             if (!lstIG)
4172             {
4173                 break;
4174             }
4175             // printf("Adjusted offset of block %02u from %04X to %04X\n", lstIG->igNum, lstIG->igOffs,
4176             // lstIG->igOffs - adjIG);
4177             lstIG->igOffs -= adjIG;
4178             assert(IsCodeAligned(lstIG->igOffs));
4179         }
4180
4181 #ifdef DEBUG
4182         emitCheckIGoffsets();
4183 #endif
4184
4185         /* Is there a chance of other jumps becoming short? */
4186         CLANG_FORMAT_COMMENT_ANCHOR;
4187 #ifdef DEBUG
4188 #if defined(_TARGET_ARM_)
4189         if (EMITVERBOSE)
4190             printf("Total shrinkage = %3u, min extra short jump size = %3u, min extra medium jump size = %u\n", adjIG,
4191                    minShortExtra, minMediumExtra);
4192 #else
4193         if (EMITVERBOSE)
4194         {
4195             printf("Total shrinkage = %3u, min extra jump size = %3u\n", adjIG, minShortExtra);
4196         }
4197 #endif
4198 #endif
4199
4200         if ((minShortExtra <= adjIG)
4201 #if defined(_TARGET_ARM_)
4202             || (minMediumExtra <= adjIG)
4203 #endif // _TARGET_ARM_
4204                 )
4205         {
4206             jmp_iteration++;
4207
4208 #ifdef DEBUG
4209             if (EMITVERBOSE)
4210             {
4211                 printf("Iterating branch shortening. Iteration = %d\n", jmp_iteration);
4212             }
4213 #endif
4214
4215             goto AGAIN;
4216         }
4217     }
4218 }
4219
4220 void emitter::emitCheckFuncletBranch(instrDesc* jmp, insGroup* jmpIG)
4221 {
4222 #ifdef DEBUG
4223     // We should not be jumping/branching across funclets/functions
4224     // Except possibly a 'call' to a finally funclet for a local unwind
4225     // or a 'return' from a catch handler (that can go just about anywhere)
4226     // This routine attempts to validate that any branches across funclets
4227     // meets one of those criteria...
4228     assert(jmp->idIsBound());
4229
4230 #ifdef _TARGET_XARCH_
4231     // An lea of a code address (for constant data stored with the code)
4232     // is treated like a jump for emission purposes but is not really a jump so
4233     // we don't have to check anything here.
4234     if (jmp->idIns() == INS_lea)
4235     {
4236         return;
4237     }
4238 #endif
4239
4240 #ifdef _TARGET_ARMARCH_
4241     if (jmp->idAddr()->iiaHasInstrCount())
4242     {
4243         // Too hard to figure out funclets from just an instruction count
4244         // You're on your own!
4245         return;
4246     }
4247 #endif // _TARGET_ARMARCH_
4248
4249 #ifdef _TARGET_ARM64_
4250     // No interest if it's not jmp.
4251     if (emitIsLoadLabel(jmp) || emitIsLoadConstant(jmp))
4252     {
4253         return;
4254     }
4255 #endif // _TARGET_ARM64_
4256
4257     insGroup* tgtIG = jmp->idAddr()->iiaIGlabel;
4258     assert(tgtIG);
4259     if (tgtIG->igFuncIdx != jmpIG->igFuncIdx)
4260     {
4261         if (jmp->idDebugOnlyInfo()->idFinallyCall)
4262         {
4263             // We don't record enough information to determine this accurately, so instead
4264             // we assume that any branch to the very start of a finally is OK.
4265
4266             // No branches back to the root method
4267             assert(tgtIG->igFuncIdx > 0);
4268             FuncInfoDsc* tgtFunc = emitComp->funGetFunc(tgtIG->igFuncIdx);
4269             assert(tgtFunc->funKind == FUNC_HANDLER);
4270             EHblkDsc* tgtEH = emitComp->ehGetDsc(tgtFunc->funEHIndex);
4271
4272             // Only branches to finallys (not faults, catches, filters, etc.)
4273             assert(tgtEH->HasFinallyHandler());
4274
4275             // Only to the first block of the finally (which is properly marked)
4276             BasicBlock* tgtBlk = tgtEH->ebdHndBeg;
4277             assert(tgtBlk->bbFlags & BBF_FUNCLET_BEG);
4278
4279             // And now we made it back to where we started
4280             assert(tgtIG == emitCodeGetCookie(tgtBlk));
4281             assert(tgtIG->igFuncIdx == emitComp->funGetFuncIdx(tgtBlk));
4282         }
4283         else if (jmp->idDebugOnlyInfo()->idCatchRet)
4284         {
4285             // Again there isn't enough information to prove this correct
4286             // so just allow a 'branch' to any other 'parent' funclet
4287
4288             FuncInfoDsc* jmpFunc = emitComp->funGetFunc(jmpIG->igFuncIdx);
4289             assert(jmpFunc->funKind == FUNC_HANDLER);
4290             EHblkDsc* jmpEH = emitComp->ehGetDsc(jmpFunc->funEHIndex);
4291
4292             // Only branches out of catches
4293             assert(jmpEH->HasCatchHandler());
4294
4295             FuncInfoDsc* tgtFunc = emitComp->funGetFunc(tgtIG->igFuncIdx);
4296             assert(tgtFunc);
4297             if (tgtFunc->funKind == FUNC_HANDLER)
4298             {
4299                 // An outward chain to the containing funclet/EH handler
4300                 // Note that it might be anywhere within nested try bodies
4301                 assert(jmpEH->ebdEnclosingHndIndex == tgtFunc->funEHIndex);
4302             }
4303             else
4304             {
4305                 // This funclet is 'top level' and so it is branching back to the
4306                 // root function, and should have no containing EH handlers
4307                 // but it could be nested within try bodies...
4308                 assert(tgtFunc->funKind == FUNC_ROOT);
4309                 assert(jmpEH->ebdEnclosingHndIndex == EHblkDsc::NO_ENCLOSING_INDEX);
4310             }
4311         }
4312         else
4313         {
4314             printf("Hit an illegal branch between funclets!");
4315             assert(tgtIG->igFuncIdx == jmpIG->igFuncIdx);
4316         }
4317     }
4318 #endif // DEBUG
4319 }
4320
4321 /*****************************************************************************
4322  *
4323  *  Compute the code sizes that we're going to use to allocate the code buffers.
4324  *
4325  *  This sets:
4326  *
4327  *      emitTotalHotCodeSize
4328  *      emitTotalColdCodeSize
4329  *      Compiler::info.compTotalHotCodeSize
4330  *      Compiler::info.compTotalColdCodeSize
4331  */
4332
4333 void emitter::emitComputeCodeSizes()
4334 {
4335     assert((emitComp->fgFirstColdBlock == nullptr) == (emitFirstColdIG == nullptr));
4336
4337     if (emitFirstColdIG)
4338     {
4339         emitTotalHotCodeSize  = emitFirstColdIG->igOffs;
4340         emitTotalColdCodeSize = emitTotalCodeSize - emitTotalHotCodeSize;
4341     }
4342     else
4343     {
4344         emitTotalHotCodeSize  = emitTotalCodeSize;
4345         emitTotalColdCodeSize = 0;
4346     }
4347
4348     emitComp->info.compTotalHotCodeSize  = emitTotalHotCodeSize;
4349     emitComp->info.compTotalColdCodeSize = emitTotalColdCodeSize;
4350
4351 #ifdef DEBUG
4352     if (emitComp->verbose)
4353     {
4354         printf("\nHot  code size = 0x%X bytes\n", emitTotalHotCodeSize);
4355         printf("Cold code size = 0x%X bytes\n", emitTotalColdCodeSize);
4356     }
4357 #endif
4358 }
4359
4360 /*****************************************************************************
4361  *
4362  *  Called at the end of code generation, this method creates the code, data
4363  *  and GC info blocks for the method.  Returns the size of the method (which must fit in an unsigned).
4364  */
4365
4366 unsigned emitter::emitEndCodeGen(Compiler* comp,
4367                                  bool      contTrkPtrLcls,
4368                                  bool      fullyInt,
4369                                  bool      fullPtrMap,
4370                                  bool      returnsGCr,
4371                                  unsigned  xcptnsCount,
4372                                  unsigned* prologSize,
4373                                  unsigned* epilogSize,
4374                                  void**    codeAddr,
4375                                  void**    coldCodeAddr,
4376                                  void**    consAddr)
4377 {
4378 #ifdef DEBUG
4379     if (emitComp->verbose)
4380     {
4381         printf("*************** In emitEndCodeGen()\n");
4382     }
4383 #endif
4384
4385     insGroup* ig;
4386
4387     BYTE* consBlock;
4388     BYTE* codeBlock;
4389     BYTE* coldCodeBlock;
4390     BYTE* cp;
4391
4392     assert(emitCurIG == nullptr);
4393
4394     emitCodeBlock = nullptr;
4395     emitConsBlock = nullptr;
4396
4397     /* Tell everyone whether we have fully interruptible code or not */
4398
4399     emitFullyInt   = fullyInt;
4400     emitFullGCinfo = fullPtrMap;
4401
4402 #ifndef UNIX_X86_ABI
4403     emitFullArgInfo = !emitHasFramePtr;
4404 #else
4405     emitFullArgInfo = fullPtrMap;
4406 #endif
4407
4408 #if EMITTER_STATS
4409     GCrefsTable.record(emitGCrFrameOffsCnt);
4410     emitSizeTable.record(static_cast<unsigned>(emitSizeMethod));
4411     stkDepthTable.record(emitMaxStackDepth);
4412 #endif // EMITTER_STATS
4413
4414     // Default values, correct even if EMIT_TRACK_STACK_DEPTH is 0.
4415     emitSimpleStkUsed         = true;
4416     u1.emitSimpleStkMask      = 0;
4417     u1.emitSimpleByrefStkMask = 0;
4418
4419 #if EMIT_TRACK_STACK_DEPTH
4420     /* Convert max. stack depth from # of bytes to # of entries */
4421
4422     unsigned maxStackDepthIn4ByteElements = emitMaxStackDepth / sizeof(int);
4423     JITDUMP("Converting emitMaxStackDepth from bytes (%d) to elements (%d)\n", emitMaxStackDepth,
4424             maxStackDepthIn4ByteElements);
4425     emitMaxStackDepth = maxStackDepthIn4ByteElements;
4426
4427     /* Should we use the simple stack */
4428
4429     if (emitMaxStackDepth > MAX_SIMPLE_STK_DEPTH || emitFullGCinfo)
4430     {
4431         /* We won't use the "simple" argument table */
4432
4433         emitSimpleStkUsed = false;
4434
4435         /* Allocate the argument tracking table */
4436
4437         if (emitMaxStackDepth <= sizeof(u2.emitArgTrackLcl))
4438         {
4439             u2.emitArgTrackTab = (BYTE*)u2.emitArgTrackLcl;
4440         }
4441         else
4442         {
4443             u2.emitArgTrackTab = (BYTE*)emitGetMem(roundUp(emitMaxStackDepth));
4444         }
4445
4446         u2.emitArgTrackTop   = u2.emitArgTrackTab;
4447         u2.emitGcArgTrackCnt = 0;
4448     }
4449 #endif
4450
4451     if (emitEpilogCnt == 0)
4452     {
4453         /* No epilogs, make sure the epilog size is set to 0 */
4454
4455         emitEpilogSize = 0;
4456
4457 #ifdef _TARGET_XARCH_
4458         emitExitSeqSize = 0;
4459 #endif // _TARGET_XARCH_
4460     }
4461
4462     /* Return the size of the epilog to the caller */
4463
4464     *epilogSize = emitEpilogSize;
4465
4466 #ifdef _TARGET_XARCH_
4467     *epilogSize += emitExitSeqSize;
4468 #endif // _TARGET_XARCH_
4469
4470 #ifdef DEBUG
4471     if (EMIT_INSTLIST_VERBOSE)
4472     {
4473         printf("\nInstruction list before instruction issue:\n\n");
4474         emitDispIGlist(true);
4475     }
4476
4477     emitCheckIGoffsets();
4478 #endif
4479
4480     /* Allocate the code block (and optionally the data blocks) */
4481
4482     // If we're doing procedure splitting and we found cold blocks, then
4483     // allocate hot and cold buffers.  Otherwise only allocate a hot
4484     // buffer.
4485
4486     coldCodeBlock = nullptr;
4487
4488     CorJitAllocMemFlag allocMemFlag = CORJIT_ALLOCMEM_DEFAULT_CODE_ALIGN;
4489
4490 #ifdef _TARGET_X86_
4491     //
4492     // These are the heuristics we use to decide whether or not to force the
4493     // code to be 16-byte aligned.
4494     //
4495     // 1. For ngen code with IBC data, use 16-byte alignment if the method
4496     //    has been called more than BB_VERY_HOT_WEIGHT times.
4497     // 2. For JITed code and ngen code without IBC data, use 16-byte alignment
4498     //    when the code is 16 bytes or smaller. We align small getters/setters
4499     //    because of they are penalized heavily on certain hardware when not 16-byte
4500     //    aligned (VSWhidbey #373938). To minimize size impact of this optimization,
4501     //    we do not align large methods because of the penalty is amortized for them.
4502     //
4503     if (emitComp->fgHaveProfileData())
4504     {
4505         if (emitComp->fgCalledCount > (BB_VERY_HOT_WEIGHT * emitComp->fgProfileRunsCount()))
4506         {
4507             allocMemFlag = CORJIT_ALLOCMEM_FLG_16BYTE_ALIGN;
4508         }
4509     }
4510     else
4511     {
4512         if (emitTotalHotCodeSize <= 16)
4513         {
4514             allocMemFlag = CORJIT_ALLOCMEM_FLG_16BYTE_ALIGN;
4515         }
4516     }
4517 #endif
4518
4519 #ifdef _TARGET_ARM64_
4520     // For arm64, we want to allocate JIT data always adjacent to code similar to what native compiler does.
4521     // This way allows us to use a single `ldr` to access such data like float constant/jmp table.
4522     if (emitTotalColdCodeSize > 0)
4523     {
4524         // JIT data might be far away from the cold code.
4525         NYI_ARM64("Need to handle fix-up to data from cold code.");
4526     }
4527
4528     UNATIVE_OFFSET roDataAlignmentDelta = 0;
4529     if (emitConsDsc.dsdOffs)
4530     {
4531         UNATIVE_OFFSET roDataAlignment = sizeof(void*); // 8 Byte align by default.
4532         roDataAlignmentDelta = (UNATIVE_OFFSET)ALIGN_UP(emitTotalHotCodeSize, roDataAlignment) - emitTotalHotCodeSize;
4533         assert((roDataAlignmentDelta == 0) || (roDataAlignmentDelta == 4));
4534     }
4535     emitCmpHandle->allocMem(emitTotalHotCodeSize + roDataAlignmentDelta + emitConsDsc.dsdOffs, emitTotalColdCodeSize, 0,
4536                             xcptnsCount, allocMemFlag, (void**)&codeBlock, (void**)&coldCodeBlock, (void**)&consBlock);
4537
4538     consBlock = codeBlock + emitTotalHotCodeSize + roDataAlignmentDelta;
4539
4540 #else
4541     emitCmpHandle->allocMem(emitTotalHotCodeSize, emitTotalColdCodeSize, emitConsDsc.dsdOffs, xcptnsCount, allocMemFlag,
4542                             (void**)&codeBlock, (void**)&coldCodeBlock, (void**)&consBlock);
4543 #endif
4544
4545     // if (emitConsDsc.dsdOffs)
4546     //     printf("Cons=%08X\n", consBlock);
4547
4548     /* Give the block addresses to the caller and other functions here */
4549
4550     *codeAddr = emitCodeBlock = codeBlock;
4551     *coldCodeAddr = emitColdCodeBlock = coldCodeBlock;
4552     *consAddr = emitConsBlock = consBlock;
4553
4554     /* Nothing has been pushed on the stack */
4555     CLANG_FORMAT_COMMENT_ANCHOR;
4556
4557 #if EMIT_TRACK_STACK_DEPTH
4558     emitCurStackLvl = 0;
4559 #endif
4560
4561     /* Assume no live GC ref variables on entry */
4562
4563     VarSetOps::OldStyleClearD(emitComp, emitThisGCrefVars); // This is initialized to Empty at the start of codegen.
4564     emitThisGCrefRegs = emitThisByrefRegs = RBM_NONE;
4565     emitThisGCrefVset                     = true;
4566
4567 #ifdef DEBUG
4568
4569     emitIssuing = true;
4570
4571     // We don't use these after this point
4572
4573     VarSetOps::AssignNoCopy(emitComp, emitPrevGCrefVars, VarSetOps::UninitVal());
4574     emitPrevGCrefRegs = emitPrevByrefRegs = 0xBAADFEED;
4575
4576     VarSetOps::AssignNoCopy(emitComp, emitInitGCrefVars, VarSetOps::UninitVal());
4577     emitInitGCrefRegs = emitInitByrefRegs = 0xBAADFEED;
4578
4579 #endif
4580
4581     /* Initialize the GC ref variable lifetime tracking logic */
4582
4583     codeGen->gcInfo.gcVarPtrSetInit();
4584
4585     emitSyncThisObjOffs = -1;     /* -1  means no offset set */
4586     emitSyncThisObjReg  = REG_NA; /* REG_NA  means not set */
4587
4588 #ifdef JIT32_GCENCODER
4589     if (emitComp->lvaKeepAliveAndReportThis())
4590     {
4591         assert(emitComp->lvaIsOriginalThisArg(0));
4592         LclVarDsc* thisDsc = &emitComp->lvaTable[0];
4593
4594         /* If "this" (which is passed in as a register argument in REG_ARG_0)
4595            is enregistered, we normally spot the "mov REG_ARG_0 -> thisReg"
4596            in the prolog and note the location of "this" at that point.
4597            However, if 'this' is enregistered into REG_ARG_0 itself, no code
4598            will be generated in the prolog, so we explicitly need to note
4599            the location of "this" here.
4600            NOTE that we can do this even if "this" is not enregistered in
4601            REG_ARG_0, and it will result in more accurate "this" info over the
4602            prolog. However, as methods are not interruptible over the prolog,
4603            we try to save space by avoiding that.
4604          */
4605
4606         if (thisDsc->lvRegister)
4607         {
4608             emitSyncThisObjReg = thisDsc->lvRegNum;
4609
4610             if (emitSyncThisObjReg == (int)REG_ARG_0 &&
4611                 (codeGen->intRegState.rsCalleeRegArgMaskLiveIn & genRegMask(REG_ARG_0)))
4612             {
4613                 if (emitFullGCinfo)
4614                 {
4615                     emitGCregLiveSet(GCT_GCREF, genRegMask(REG_ARG_0),
4616                                      emitCodeBlock, // from offset 0
4617                                      true);
4618                 }
4619                 else
4620                 {
4621                     /* If emitFullGCinfo==false, the we don't use any
4622                        regPtrDsc's and so explictly note the location
4623                        of "this" in GCEncode.cpp
4624                      */
4625                 }
4626             }
4627         }
4628     }
4629 #endif // JIT32_GCENCODER
4630
4631     emitContTrkPtrLcls = contTrkPtrLcls;
4632
4633     /* Are there any GC ref variables on the stack? */
4634
4635     if (emitGCrFrameOffsCnt)
4636     {
4637         size_t     siz;
4638         unsigned   cnt;
4639         unsigned   num;
4640         LclVarDsc* dsc;
4641         int*       tab;
4642
4643         /* Allocate and clear emitGCrFrameLiveTab[]. This is the table
4644            mapping "stkOffs -> varPtrDsc". It holds a pointer to
4645            the liveness descriptor that was created when the
4646            variable became alive. When the variable becomes dead, the
4647            descriptor will be appended to the liveness descriptor list, and
4648            the entry in emitGCrFrameLiveTab[] will be made NULL.
4649
4650            Note that if all GC refs are assigned consecutively,
4651            emitGCrFrameLiveTab[] can be only as big as the number of GC refs
4652            present, instead of lvaTrackedCount.
4653          */
4654
4655         siz                 = emitGCrFrameOffsCnt * sizeof(*emitGCrFrameLiveTab);
4656         emitGCrFrameLiveTab = (varPtrDsc**)emitGetMem(roundUp(siz));
4657         memset(emitGCrFrameLiveTab, 0, siz);
4658
4659         /* Allocate and fill in emitGCrFrameOffsTab[]. This is the table
4660            mapping "varIndex -> stkOffs".
4661            Non-ptrs or reg vars have entries of -1.
4662            Entries of Tracked stack byrefs have the lower bit set to 1.
4663         */
4664
4665         emitTrkVarCnt = cnt = emitComp->lvaTrackedCount;
4666         assert(cnt);
4667         emitGCrFrameOffsTab = tab = (int*)emitGetMem(cnt * sizeof(int));
4668
4669         memset(emitGCrFrameOffsTab, -1, cnt * sizeof(int));
4670
4671         /* Now fill in all the actual used entries */
4672
4673         for (num = 0, dsc = emitComp->lvaTable, cnt = emitComp->lvaCount; num < cnt; num++, dsc++)
4674         {
4675             if (!dsc->lvOnFrame || (dsc->lvIsParam && !dsc->lvIsRegArg))
4676             {
4677                 continue;
4678             }
4679
4680 #if FEATURE_FIXED_OUT_ARGS
4681             if (num == emitComp->lvaOutgoingArgSpaceVar)
4682             {
4683                 continue;
4684             }
4685 #endif // FEATURE_FIXED_OUT_ARGS
4686
4687             int offs = dsc->lvStkOffs;
4688
4689             /* Is it within the interesting range of offsets */
4690
4691             if (offs >= emitGCrFrameOffsMin && offs < emitGCrFrameOffsMax)
4692             {
4693                 /* Are tracked stack ptr locals laid out contiguously?
4694                    If not, skip non-ptrs. The emitter is optimized to work
4695                    with contiguous ptrs, but for EditNContinue, the variables
4696                    are laid out in the order they occur in the local-sig.
4697                  */
4698
4699                 if (!emitContTrkPtrLcls)
4700                 {
4701                     if (!emitComp->lvaIsGCTracked(dsc))
4702                     {
4703                         continue;
4704                     }
4705                 }
4706
4707                 unsigned indx = dsc->lvVarIndex;
4708
4709                 assert(!dsc->lvRegister);
4710                 assert(dsc->lvTracked);
4711                 assert(dsc->lvRefCnt != 0);
4712
4713                 assert(dsc->TypeGet() == TYP_REF || dsc->TypeGet() == TYP_BYREF);
4714
4715                 assert(indx < emitComp->lvaTrackedCount);
4716
4717 // printf("Variable #%2u/%2u is at stack offset %d\n", num, indx, offs);
4718
4719 #ifdef JIT32_GCENCODER
4720 #ifndef WIN64EXCEPTIONS
4721                 /* Remember the frame offset of the "this" argument for synchronized methods */
4722                 if (emitComp->lvaIsOriginalThisArg(num) && emitComp->lvaKeepAliveAndReportThis())
4723                 {
4724                     emitSyncThisObjOffs = offs;
4725                     offs |= this_OFFSET_FLAG;
4726                 }
4727 #endif
4728 #endif // JIT32_GCENCODER
4729
4730                 if (dsc->TypeGet() == TYP_BYREF)
4731                 {
4732                     offs |= byref_OFFSET_FLAG;
4733                 }
4734                 tab[indx] = offs;
4735             }
4736         }
4737     }
4738     else
4739     {
4740 #ifdef DEBUG
4741         emitTrkVarCnt       = 0;
4742         emitGCrFrameOffsTab = nullptr;
4743 #endif
4744     }
4745
4746 #ifdef DEBUG
4747     if (emitComp->verbose)
4748     {
4749         printf("\n***************************************************************************\n");
4750         printf("Instructions as they come out of the scheduler\n\n");
4751     }
4752 #endif
4753
4754     /* Issue all instruction groups in order */
4755     cp = codeBlock;
4756
4757 #define DEFAULT_CODE_BUFFER_INIT 0xcc
4758
4759     for (ig = emitIGlist; ig; ig = ig->igNext)
4760     {
4761         assert(!(ig->igFlags & IGF_PLACEHOLDER)); // There better not be any placeholder groups left
4762
4763         /* Is this the first cold block? */
4764         if (ig == emitFirstColdIG)
4765         {
4766             unsigned actualHotCodeSize = emitCurCodeOffs(cp);
4767
4768             /* Fill in eventual unused space */
4769             while (emitCurCodeOffs(cp) < emitTotalHotCodeSize)
4770             {
4771                 *cp++ = DEFAULT_CODE_BUFFER_INIT;
4772             }
4773
4774             assert(coldCodeBlock);
4775             cp = coldCodeBlock;
4776 #ifdef DEBUG
4777             if (emitComp->opts.disAsm || emitComp->opts.dspEmit || emitComp->verbose)
4778             {
4779                 printf("\n************** Beginning of cold code **************\n");
4780             }
4781 #endif
4782         }
4783
4784         /* Are we overflowing? */
4785         if (ig->igNext && ig->igNum + 1 != ig->igNext->igNum)
4786         {
4787             NO_WAY("Too many instruction groups");
4788         }
4789
4790         // If this instruction group is returned to from a funclet implementing a finally,
4791         // on architectures where it is necessary generate GC info for the current instruction as
4792         // if it were the instruction following a call.
4793         emitGenGCInfoIfFuncletRetTarget(ig, cp);
4794
4795         instrDesc* id = (instrDesc*)ig->igData;
4796
4797 #ifdef DEBUG
4798
4799         /* Print the IG label, but only if it is a branch label */
4800
4801         if (emitComp->opts.disAsm || emitComp->opts.dspEmit || emitComp->verbose)
4802         {
4803             if (emitComp->verbose)
4804             {
4805                 printf("\n");
4806                 emitDispIG(ig); // Display the flags, IG data, etc.
4807             }
4808             else
4809             {
4810                 printf("\nG_M%03u_IG%02u:\n", Compiler::s_compMethodsCount, ig->igNum);
4811             }
4812         }
4813
4814 #endif // DEBUG
4815
4816         BYTE* bp = cp;
4817
4818         /* Record the actual offset of the block, noting the difference */
4819
4820         emitOffsAdj = ig->igOffs - emitCurCodeOffs(cp);
4821         assert(emitOffsAdj >= 0);
4822
4823 #if DEBUG_EMIT
4824         if ((emitOffsAdj != 0) && emitComp->verbose)
4825         {
4826             printf("Block predicted offs = %08X, actual = %08X -> size adj = %d\n", ig->igOffs, emitCurCodeOffs(cp),
4827                    emitOffsAdj);
4828         }
4829 #endif // DEBUG_EMIT
4830
4831         ig->igOffs = emitCurCodeOffs(cp);
4832         assert(IsCodeAligned(ig->igOffs));
4833
4834 #if EMIT_TRACK_STACK_DEPTH
4835
4836         /* Set the proper stack level if appropriate */
4837
4838         if (ig->igStkLvl != emitCurStackLvl)
4839         {
4840             /* We are pushing stuff implicitly at this label */
4841
4842             assert((unsigned)ig->igStkLvl > (unsigned)emitCurStackLvl);
4843             emitStackPushN(cp, (ig->igStkLvl - (unsigned)emitCurStackLvl) / sizeof(int));
4844         }
4845
4846 #endif
4847
4848         /* Update current GC information for non-overflow IG (not added implicitly by the emitter) */
4849
4850         if (!(ig->igFlags & IGF_EMIT_ADD))
4851         {
4852             /* Is there a new set of live GC ref variables? */
4853
4854             if (ig->igFlags & IGF_GC_VARS)
4855             {
4856                 emitUpdateLiveGCvars(ig->igGCvars(), cp);
4857             }
4858             else if (!emitThisGCrefVset)
4859             {
4860                 emitUpdateLiveGCvars(emitThisGCrefVars, cp);
4861             }
4862
4863             /* Update the set of live GC ref registers */
4864
4865             {
4866                 regMaskTP GCregs = ig->igGCregs;
4867
4868                 if (GCregs != emitThisGCrefRegs)
4869                 {
4870                     emitUpdateLiveGCregs(GCT_GCREF, GCregs, cp);
4871                 }
4872             }
4873
4874             /* Is there a new set of live byref registers? */
4875
4876             if (ig->igFlags & IGF_BYREF_REGS)
4877             {
4878                 unsigned byrefRegs = ig->igByrefRegs();
4879
4880                 if (byrefRegs != emitThisByrefRegs)
4881                 {
4882                     emitUpdateLiveGCregs(GCT_BYREF, byrefRegs, cp);
4883                 }
4884             }
4885         }
4886         else
4887         {
4888             // These are not set for "overflow" groups
4889             assert(!(ig->igFlags & IGF_GC_VARS));
4890             assert(!(ig->igFlags & IGF_BYREF_REGS));
4891         }
4892
4893         /* Issue each instruction in order */
4894
4895         emitCurIG = ig;
4896
4897         for (unsigned cnt = ig->igInsCnt; cnt; cnt--)
4898         {
4899             castto(id, BYTE*) += emitIssue1Instr(ig, id, &cp);
4900         }
4901
4902         emitCurIG = nullptr;
4903
4904         assert(ig->igSize >= cp - bp);
4905         ig->igSize = (unsigned short)(cp - bp);
4906     }
4907
4908 #if EMIT_TRACK_STACK_DEPTH
4909     assert(emitCurStackLvl == 0);
4910 #endif
4911
4912     /* Output any initialized data we may have */
4913
4914     if (emitConsDsc.dsdOffs)
4915     {
4916         emitOutputDataSec(&emitConsDsc, consBlock);
4917     }
4918
4919     /* Make sure all GC ref variables are marked as dead */
4920
4921     if (emitGCrFrameOffsCnt)
4922     {
4923         unsigned    vn;
4924         int         of;
4925         varPtrDsc** dp;
4926
4927         for (vn = 0, of = emitGCrFrameOffsMin, dp = emitGCrFrameLiveTab; vn < emitGCrFrameOffsCnt;
4928              vn++, of += sizeof(void*), dp++)
4929         {
4930             if (*dp)
4931             {
4932                 emitGCvarDeadSet(of, cp, vn);
4933             }
4934         }
4935     }
4936
4937     /* No GC registers are live any more */
4938
4939     if (emitThisByrefRegs)
4940     {
4941         emitUpdateLiveGCregs(GCT_BYREF, RBM_NONE, cp);
4942     }
4943     if (emitThisGCrefRegs)
4944     {
4945         emitUpdateLiveGCregs(GCT_GCREF, RBM_NONE, cp);
4946     }
4947
4948     /* Patch any forward jumps */
4949
4950     if (emitFwdJumps)
4951     {
4952         instrDescJmp* jmp;
4953
4954         for (jmp = emitJumpList; jmp; jmp = jmp->idjNext)
4955         {
4956             insGroup* tgt;
4957 #ifdef _TARGET_XARCH_
4958             assert(jmp->idInsFmt() == IF_LABEL || jmp->idInsFmt() == IF_RWR_LABEL || jmp->idInsFmt() == IF_SWR_LABEL);
4959 #endif
4960             tgt = jmp->idAddr()->iiaIGlabel;
4961
4962             if (jmp->idjTemp.idjAddr == nullptr)
4963             {
4964                 continue;
4965             }
4966
4967             if (jmp->idjOffs != tgt->igOffs)
4968             {
4969                 BYTE* adr = jmp->idjTemp.idjAddr;
4970                 int   adj = jmp->idjOffs - tgt->igOffs;
4971 #ifdef _TARGET_ARM_
4972                 // On Arm, the offset is encoded in unit of 2 bytes.
4973                 adj >>= 1;
4974 #endif
4975
4976 #if DEBUG_EMIT
4977                 if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
4978                 {
4979 #ifdef _TARGET_ARM_
4980                     printf("[5] This output is broken for ARM, since it doesn't properly decode the jump offsets of "
4981                            "the instruction at adr\n");
4982 #endif
4983
4984                     if (INTERESTING_JUMP_NUM == 0)
4985                     {
4986                         printf("[5] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
4987                     }
4988
4989                     if (jmp->idjShort)
4990                     {
4991                         printf("[5] Jump        is at %08X\n", (adr + 1 - emitCodeBlock));
4992                         printf("[5] Jump distance is  %02X - %02X = %02X\n", *(BYTE*)adr, adj, *(BYTE*)adr - adj);
4993                     }
4994                     else
4995                     {
4996                         printf("[5] Jump        is at %08X\n", (adr + 4 - emitCodeBlock));
4997                         printf("[5] Jump distance is  %08X - %02X = %08X\n", *(int*)adr, adj, *(int*)adr - adj);
4998                     }
4999                 }
5000 #endif // DEBUG_EMIT
5001
5002                 if (jmp->idjShort)
5003                 {
5004                     // Patch Forward Short Jump
5005                     CLANG_FORMAT_COMMENT_ANCHOR;
5006 #if defined(_TARGET_XARCH_)
5007                     *(BYTE*)adr -= (BYTE)adj;
5008 #elif defined(_TARGET_ARM_)
5009                     // The following works because the jump offset is in the low order bits of the instruction.
5010                     // Presumably we could also just call "emitOutputLJ(NULL, adr, jmp)", like for long jumps?
5011                     *(short int*)adr -= (short)adj;
5012 #elif defined(_TARGET_ARM64_)
5013                     assert(!jmp->idAddr()->iiaHasInstrCount());
5014                     emitOutputLJ(NULL, adr, jmp);
5015 #else
5016 #error Unsupported or unset target architecture
5017 #endif
5018                 }
5019                 else
5020                 {
5021                     // Patch Forward non-Short Jump
5022                     CLANG_FORMAT_COMMENT_ANCHOR;
5023 #if defined(_TARGET_XARCH_)
5024                     *(int*)adr -= adj;
5025 #elif defined(_TARGET_ARMARCH_)
5026                     assert(!jmp->idAddr()->iiaHasInstrCount());
5027                     emitOutputLJ(NULL, adr, jmp);
5028 #else
5029 #error Unsupported or unset target architecture
5030 #endif
5031                 }
5032             }
5033         }
5034     }
5035
5036 #ifdef DEBUG
5037     if (emitComp->opts.disAsm)
5038     {
5039         printf("\n");
5040     }
5041
5042     if (emitComp->verbose)
5043     {
5044         printf("Allocated method code size = %4u , actual size = %4u\n", emitTotalCodeSize, cp - codeBlock);
5045     }
5046 #endif
5047
5048     unsigned actualCodeSize = emitCurCodeOffs(cp);
5049
5050     /* Fill in eventual unused space */
5051     while (emitCurCodeOffs(cp) < emitTotalCodeSize)
5052     {
5053         *cp++ = DEFAULT_CODE_BUFFER_INIT;
5054     }
5055
5056 #if EMITTER_STATS
5057     totAllocdSize += emitTotalCodeSize;
5058     totActualSize += actualCodeSize;
5059 #endif
5060
5061 #ifdef DEBUG
5062
5063     // Make sure these didn't change during the "issuing" phase
5064
5065     assert(VarSetOps::MayBeUninit(emitPrevGCrefVars));
5066     assert(emitPrevGCrefRegs == 0xBAADFEED);
5067     assert(emitPrevByrefRegs == 0xBAADFEED);
5068
5069     assert(VarSetOps::MayBeUninit(emitInitGCrefVars));
5070     assert(emitInitGCrefRegs == 0xBAADFEED);
5071     assert(emitInitByrefRegs == 0xBAADFEED);
5072
5073 #endif
5074
5075     // Assign the real prolog size
5076     *prologSize = emitCodeOffset(emitPrologIG, emitPrologEndPos);
5077
5078     /* Return the amount of code we've generated */
5079
5080     return actualCodeSize;
5081 }
5082
5083 // See specification comment at the declaration.
5084 void emitter::emitGenGCInfoIfFuncletRetTarget(insGroup* ig, BYTE* cp)
5085 {
5086 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
5087     // We only emit this GC information on targets where finally's are implemented via funclets,
5088     // and the finally is invoked, during non-exceptional execution, via a branch with a predefined
5089     // link register, rather than a "true call" for which we would already generate GC info.  Currently,
5090     // this means precisely ARM.
5091     if (ig->igFlags & IGF_FINALLY_TARGET)
5092     {
5093         // We don't actually have a call instruction in this case, so we don't have
5094         // a real size for that instruction.  We'll use 1.
5095         emitStackPop(cp, /*isCall*/ true, /*callInstrSize*/ 1, /*args*/ 0);
5096
5097         /* Do we need to record a call location for GC purposes? */
5098         if (!emitFullGCinfo)
5099         {
5100             emitRecordGCcall(cp, /*callInstrSize*/ 1);
5101         }
5102     }
5103 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
5104 }
5105
5106 /*****************************************************************************
5107  *
5108  *  We have an instruction in an insGroup and we need to know the
5109  *  instruction number for this instruction
5110  */
5111
5112 unsigned emitter::emitFindInsNum(insGroup* ig, instrDesc* idMatch)
5113 {
5114     instrDesc* id = (instrDesc*)ig->igData;
5115
5116     // Check if we are the first instruction in the group
5117     if (id == idMatch)
5118     {
5119         return 0;
5120     }
5121
5122     /* Walk the list of instructions until we find a match */
5123     unsigned insNum       = 0;
5124     unsigned insRemaining = ig->igInsCnt;
5125
5126     while (insRemaining > 0)
5127     {
5128         castto(id, BYTE*) += emitSizeOfInsDsc(id);
5129         insNum++;
5130         insRemaining--;
5131
5132         if (id == idMatch)
5133         {
5134             return insNum;
5135         }
5136     }
5137     assert(!"emitFindInsNum failed");
5138     return -1;
5139 }
5140
5141 /*****************************************************************************
5142  *
5143  *  We've been asked for the code offset of an instruction but alas one or
5144  *  more instruction sizes in the block have been mis-predicted, so we have
5145  *  to find the true offset by looking for the instruction within the group.
5146  */
5147
5148 UNATIVE_OFFSET emitter::emitFindOffset(insGroup* ig, unsigned insNum)
5149 {
5150     instrDesc*     id = (instrDesc*)ig->igData;
5151     UNATIVE_OFFSET of = 0;
5152
5153 #ifdef DEBUG
5154     /* Make sure we were passed reasonable arguments */
5155     assert(ig && ig->igSelf == ig);
5156     assert(ig->igInsCnt >= insNum);
5157 #endif
5158
5159     /* Walk the instruction list until all are counted */
5160
5161     while (insNum > 0)
5162     {
5163         of += emitInstCodeSz(id);
5164
5165         castto(id, BYTE*) += emitSizeOfInsDsc(id);
5166
5167         insNum--;
5168     }
5169
5170     return of;
5171 }
5172
5173 /*****************************************************************************
5174  *
5175  *  Start generating a constant data section for the current
5176  *  function. Returns the offset of the section in the appropriate data
5177  *  block.
5178  */
5179
5180 UNATIVE_OFFSET emitter::emitDataGenBeg(UNATIVE_OFFSET size, bool dblAlign, bool codeLtab)
5181 {
5182     unsigned     secOffs;
5183     dataSection* secDesc;
5184
5185     assert(emitDataSecCur == nullptr);
5186
5187     /* The size better not be some kind of an odd thing */
5188
5189     assert(size && size % sizeof(int) == 0);
5190
5191     /* Get hold of the current offset */
5192
5193     secOffs = emitConsDsc.dsdOffs;
5194
5195     /* Are we require to align this request on an eight byte boundry? */
5196     if (dblAlign && (secOffs % sizeof(double) != 0))
5197     {
5198         /* Need to skip 4 bytes to honor dblAlign */
5199         /* Must allocate a dummy 4 byte integer */
5200         int zero = 0;
5201         emitDataGenBeg(4, false, false);
5202         emitDataGenData(0, &zero, 4);
5203         emitDataGenEnd();
5204
5205         /* Get the new secOffs */
5206         secOffs = emitConsDsc.dsdOffs;
5207         /* Now it should be a multiple of 8 */
5208         assert(secOffs % sizeof(double) == 0);
5209     }
5210
5211     /* Advance the current offset */
5212
5213     emitConsDsc.dsdOffs += size;
5214
5215     /* Allocate a data section descriptor and add it to the list */
5216
5217     secDesc = emitDataSecCur = (dataSection*)emitGetMem(roundUp(sizeof(*secDesc) + size));
5218
5219     secDesc->dsSize = size;
5220
5221     secDesc->dsType = dataSection::data;
5222
5223     secDesc->dsNext = nullptr;
5224
5225     if (emitConsDsc.dsdLast)
5226     {
5227         emitConsDsc.dsdLast->dsNext = secDesc;
5228     }
5229     else
5230     {
5231         emitConsDsc.dsdList = secDesc;
5232     }
5233     emitConsDsc.dsdLast = secDesc;
5234
5235     return secOffs;
5236 }
5237
5238 //  Start generating a constant data section for the current function
5239 //  populated with BasicBlock references.
5240 //  You can choose the references to be either absolute pointers, or
5241 //  4-byte relative addresses.
5242 //  Currently the relative references are relative to the start of the
5243 //  first block (this is somewhat arbitrary)
5244
5245 UNATIVE_OFFSET emitter::emitBBTableDataGenBeg(unsigned numEntries, bool relativeAddr)
5246 {
5247     unsigned     secOffs;
5248     dataSection* secDesc;
5249
5250     assert(emitDataSecCur == nullptr);
5251
5252     UNATIVE_OFFSET emittedSize;
5253
5254     if (relativeAddr)
5255     {
5256         emittedSize = numEntries * 4;
5257     }
5258     else
5259     {
5260         emittedSize = numEntries * TARGET_POINTER_SIZE;
5261     }
5262
5263     /* Get hold of the current offset */
5264
5265     secOffs = emitConsDsc.dsdOffs;
5266
5267     /* Advance the current offset */
5268
5269     emitConsDsc.dsdOffs += emittedSize;
5270
5271     /* Allocate a data section descriptor and add it to the list */
5272
5273     secDesc = emitDataSecCur = (dataSection*)emitGetMem(roundUp(sizeof(*secDesc) + numEntries * sizeof(BasicBlock*)));
5274
5275     secDesc->dsSize = emittedSize;
5276
5277     secDesc->dsType = relativeAddr ? dataSection::blockRelative32 : dataSection::blockAbsoluteAddr;
5278
5279     secDesc->dsNext = nullptr;
5280
5281     if (emitConsDsc.dsdLast)
5282     {
5283         emitConsDsc.dsdLast->dsNext = secDesc;
5284     }
5285     else
5286     {
5287         emitConsDsc.dsdList = secDesc;
5288     }
5289
5290     emitConsDsc.dsdLast = secDesc;
5291
5292     return secOffs;
5293 }
5294
5295 /*****************************************************************************
5296  *
5297  *  Emit the given block of bits into the current data section.
5298  */
5299
5300 void emitter::emitDataGenData(unsigned offs, const void* data, size_t size)
5301 {
5302     assert(emitDataSecCur && (emitDataSecCur->dsSize >= offs + size));
5303
5304     assert(emitDataSecCur->dsType == dataSection::data);
5305
5306     memcpy(emitDataSecCur->dsCont + offs, data, size);
5307 }
5308
5309 /*****************************************************************************
5310  *
5311  *  Emit the address of the given basic block into the current data section.
5312  */
5313
5314 void emitter::emitDataGenData(unsigned index, BasicBlock* label)
5315 {
5316     assert(emitDataSecCur != nullptr);
5317     assert(emitDataSecCur->dsType == dataSection::blockAbsoluteAddr ||
5318            emitDataSecCur->dsType == dataSection::blockRelative32);
5319
5320     unsigned emittedElemSize = emitDataSecCur->dsType == dataSection::blockAbsoluteAddr ? TARGET_POINTER_SIZE : 4;
5321
5322     assert(emitDataSecCur->dsSize >= emittedElemSize * (index + 1));
5323
5324     ((BasicBlock**)(emitDataSecCur->dsCont))[index] = label;
5325 }
5326
5327 /*****************************************************************************
5328  *
5329  *  We're done generating a data section.
5330  */
5331
5332 void emitter::emitDataGenEnd()
5333 {
5334
5335 #ifdef DEBUG
5336     assert(emitDataSecCur);
5337     emitDataSecCur = nullptr;
5338 #endif
5339 }
5340
5341 /********************************************************************************
5342  * Generates a data section constant
5343  *
5344  * Parameters:
5345  *     cnsAddr  - memory location containing constant value
5346  *     cnsSize  - size of constant in bytes
5347  *     dblAlign - whether to double align the data section constant
5348  *
5349  * Returns constant number as offset into data section.
5350  */
5351 UNATIVE_OFFSET emitter::emitDataConst(const void* cnsAddr, unsigned cnsSize, bool dblAlign)
5352 {
5353     // When generating SMALL_CODE, we don't bother with dblAlign
5354     if (dblAlign && (emitComp->compCodeOpt() == Compiler::SMALL_CODE))
5355     {
5356         dblAlign = false;
5357     }
5358
5359     UNATIVE_OFFSET cnum = emitDataGenBeg(cnsSize, dblAlign, false);
5360     emitDataGenData(0, cnsAddr, cnsSize);
5361     emitDataGenEnd();
5362
5363     return cnum;
5364 }
5365
5366 /*****************************************************************************
5367  *
5368  *  Output the given data section at the specified address.
5369  */
5370
5371 void emitter::emitOutputDataSec(dataSecDsc* sec, BYTE* dst)
5372 {
5373 #ifdef DEBUG
5374     if (EMITVERBOSE)
5375     {
5376         printf("\nEmitting data sections: %u total bytes\n", sec->dsdOffs);
5377     }
5378
5379     unsigned secNum = 0;
5380 #endif
5381
5382     assert(dst);
5383     assert(sec->dsdOffs);
5384     assert(sec->dsdList);
5385
5386     /* Walk and emit the contents of all the data blocks */
5387
5388     dataSection* dsc;
5389
5390     for (dsc = sec->dsdList; dsc; dsc = dsc->dsNext)
5391     {
5392         size_t dscSize = dsc->dsSize;
5393
5394         // absolute label table
5395         if (dsc->dsType == dataSection::blockAbsoluteAddr)
5396         {
5397             JITDUMP("  section %u, size %u, block absolute addr\n", secNum++, dscSize);
5398
5399             assert(dscSize && dscSize % sizeof(BasicBlock*) == 0);
5400             size_t numElems = dscSize / TARGET_POINTER_SIZE;
5401             BYTE** bDst     = (BYTE**)dst;
5402             for (unsigned i = 0; i < numElems; i++)
5403             {
5404                 BasicBlock* block = ((BasicBlock**)dsc->dsCont)[i];
5405
5406                 // Convert the BasicBlock* value to an IG address
5407                 insGroup* lab = (insGroup*)emitCodeGetCookie(block);
5408
5409                 // Append the appropriate address to the destination
5410                 BYTE* target = emitOffsetToPtr(lab->igOffs);
5411
5412 #ifdef _TARGET_ARM_
5413                 target = (BYTE*)((size_t)target | 1); // Or in thumb bit
5414 #endif
5415                 bDst[i] = target;
5416                 if (emitComp->opts.compReloc)
5417                 {
5418                     emitRecordRelocation(&(bDst[i]), target, IMAGE_REL_BASED_HIGHLOW);
5419                 }
5420
5421                 JITDUMP("  BB%02u: 0x%p\n", block->bbNum, bDst[i]);
5422             }
5423         }
5424         // relative label table
5425         else if (dsc->dsType == dataSection::blockRelative32)
5426         {
5427             JITDUMP("  section %u, size %u, block relative addr\n", secNum++, dscSize);
5428
5429             unsigned  elemSize = 4;
5430             size_t    numElems = dscSize / 4;
5431             unsigned* uDst     = (unsigned*)dst;
5432             insGroup* labFirst = (insGroup*)emitCodeGetCookie(emitComp->fgFirstBB);
5433
5434             for (unsigned i = 0; i < numElems; i++)
5435             {
5436                 BasicBlock* block = ((BasicBlock**)dsc->dsCont)[i];
5437
5438                 // Convert the BasicBlock* value to an IG address
5439                 insGroup* lab = (insGroup*)emitCodeGetCookie(block);
5440
5441                 assert(FitsIn<uint32_t>(lab->igOffs - labFirst->igOffs));
5442                 uDst[i] = lab->igOffs - labFirst->igOffs;
5443
5444                 JITDUMP("  BB%02u: 0x%x\n", block->bbNum, uDst[i]);
5445             }
5446         }
5447         else
5448         {
5449             JITDUMP("  section %u, size %u, raw data\n", secNum++, dscSize);
5450
5451             // Simple binary data: copy the bytes to the target
5452             assert(dsc->dsType == dataSection::data);
5453
5454             memcpy(dst, dsc->dsCont, dscSize);
5455
5456 #ifdef DEBUG
5457             if (EMITVERBOSE)
5458             {
5459                 printf("  ");
5460                 for (size_t i = 0; i < dscSize; i++)
5461                 {
5462                     printf("%02x ", dsc->dsCont[i]);
5463                     if ((((i + 1) % 16) == 0) && (i + 1 != dscSize))
5464                     {
5465                         printf("\n  ");
5466                     }
5467                 }
5468                 printf("\n");
5469             }
5470 #endif // DEBUG
5471         }
5472         dst += dscSize;
5473     }
5474 }
5475
5476 /*****************************************************************************/
5477 /*****************************************************************************
5478  *
5479  *  Record the fact that the given variable now contains a live GC ref.
5480  */
5481
5482 void emitter::emitGCvarLiveSet(int offs, GCtype gcType, BYTE* addr, ssize_t disp)
5483 {
5484     assert(emitIssuing);
5485
5486     varPtrDsc* desc;
5487
5488     assert((abs(offs) % sizeof(ssize_t)) == 0);
5489     assert(needsGC(gcType));
5490
5491     /* Compute the index into the GC frame table if the caller didn't do it */
5492
5493     if (disp == -1)
5494     {
5495         disp = (offs - emitGCrFrameOffsMin) / sizeof(void*);
5496     }
5497
5498     assert((size_t)disp < emitGCrFrameOffsCnt);
5499
5500     /* Allocate a lifetime record */
5501
5502     desc = new (emitComp, CMK_GC) varPtrDsc;
5503
5504     desc->vpdBegOfs = emitCurCodeOffs(addr);
5505 #ifdef DEBUG
5506     desc->vpdEndOfs = 0xFACEDEAD;
5507 #endif
5508
5509     desc->vpdVarNum = offs;
5510
5511     desc->vpdNext = nullptr;
5512
5513 #if !defined(JIT32_GCENCODER) || !defined(WIN64EXCEPTIONS)
5514     /* the lower 2 bits encode props about the stk ptr */
5515
5516     if (offs == emitSyncThisObjOffs)
5517     {
5518         desc->vpdVarNum |= this_OFFSET_FLAG;
5519     }
5520 #endif
5521
5522     if (gcType == GCT_BYREF)
5523     {
5524         desc->vpdVarNum |= byref_OFFSET_FLAG;
5525     }
5526
5527     /* Append the new entry to the end of the list */
5528     if (codeGen->gcInfo.gcVarPtrLast == nullptr)
5529     {
5530         assert(codeGen->gcInfo.gcVarPtrList == nullptr);
5531         codeGen->gcInfo.gcVarPtrList = codeGen->gcInfo.gcVarPtrLast = desc;
5532     }
5533     else
5534     {
5535         assert(codeGen->gcInfo.gcVarPtrList != nullptr);
5536         codeGen->gcInfo.gcVarPtrLast->vpdNext = desc;
5537         codeGen->gcInfo.gcVarPtrLast          = desc;
5538     }
5539
5540     /* Record the variable descriptor in the table */
5541
5542     assert(emitGCrFrameLiveTab[disp] == nullptr);
5543     emitGCrFrameLiveTab[disp] = desc;
5544
5545 #ifdef DEBUG
5546     if (EMITVERBOSE)
5547     {
5548         printf("[%08X] %s var born at [%s", dspPtr(desc), GCtypeStr(gcType), emitGetFrameReg());
5549
5550         if (offs < 0)
5551         {
5552             printf("-%02XH", -offs);
5553         }
5554         else if (offs > 0)
5555         {
5556             printf("+%02XH", +offs);
5557         }
5558
5559         printf("]\n");
5560     }
5561 #endif
5562
5563     /* The "global" live GC variable mask is no longer up-to-date */
5564
5565     emitThisGCrefVset = false;
5566 }
5567
5568 /*****************************************************************************
5569  *
5570  *  Record the fact that the given variable no longer contains a live GC ref.
5571  */
5572
5573 void emitter::emitGCvarDeadSet(int offs, BYTE* addr, ssize_t disp)
5574 {
5575     assert(emitIssuing);
5576
5577     varPtrDsc* desc;
5578
5579     assert(abs(offs) % sizeof(int) == 0);
5580
5581     /* Compute the index into the GC frame table if the caller didn't do it */
5582
5583     if (disp == -1)
5584     {
5585         disp = (offs - emitGCrFrameOffsMin) / sizeof(void*);
5586     }
5587
5588     assert((unsigned)disp < emitGCrFrameOffsCnt);
5589
5590     /* Get hold of the lifetime descriptor and clear the entry */
5591
5592     desc                      = emitGCrFrameLiveTab[disp];
5593     emitGCrFrameLiveTab[disp] = nullptr;
5594
5595     assert(desc);
5596     assert((desc->vpdVarNum & ~OFFSET_MASK) == (unsigned)offs);
5597
5598     /* Record the death code offset */
5599
5600     assert(desc->vpdEndOfs == 0xFACEDEAD);
5601     desc->vpdEndOfs = emitCurCodeOffs(addr);
5602
5603 #ifdef DEBUG
5604     if (EMITVERBOSE)
5605     {
5606         GCtype gcType = (desc->vpdVarNum & byref_OFFSET_FLAG) ? GCT_BYREF : GCT_GCREF;
5607 #if !defined(JIT32_GCENCODER) || !defined(WIN64EXCEPTIONS)
5608         bool isThis = (desc->vpdVarNum & this_OFFSET_FLAG) != 0;
5609
5610         printf("[%08X] %s%s var died at [%s", dspPtr(desc), GCtypeStr(gcType), isThis ? "this-ptr" : "",
5611                emitGetFrameReg());
5612 #else
5613         bool isPinned = (desc->vpdVarNum & pinned_OFFSET_FLAG) != 0;
5614
5615         printf("[%08X] %s%s var died at [%s", dspPtr(desc), GCtypeStr(gcType), isPinned ? "pinned" : "",
5616                emitGetFrameReg());
5617 #endif
5618
5619         if (offs < 0)
5620         {
5621             printf("-%02XH", -offs);
5622         }
5623         else if (offs > 0)
5624         {
5625             printf("+%02XH", +offs);
5626         }
5627
5628         printf("]\n");
5629     }
5630 #endif
5631
5632     /* The "global" live GC variable mask is no longer up-to-date */
5633
5634     emitThisGCrefVset = false;
5635 }
5636
5637 /*****************************************************************************
5638  *
5639  *  Record a new set of live GC ref variables.
5640  */
5641
5642 void emitter::emitUpdateLiveGCvars(VARSET_VALARG_TP vars, BYTE* addr)
5643 {
5644     assert(emitIssuing);
5645
5646     // Don't track GC changes in epilogs
5647     if (emitIGisInEpilog(emitCurIG))
5648     {
5649         return;
5650     }
5651
5652     /* Is the current set accurate and unchanged? */
5653
5654     if (emitThisGCrefVset && VarSetOps::Equal(emitComp, emitThisGCrefVars, vars))
5655     {
5656         return;
5657     }
5658
5659 #ifdef DEBUG
5660     if (EMIT_GC_VERBOSE)
5661     {
5662         printf("New GC ref live vars=%s ", VarSetOps::ToString(emitComp, vars));
5663         dumpConvertedVarSet(emitComp, vars);
5664         printf("\n");
5665     }
5666 #endif
5667
5668     VarSetOps::Assign(emitComp, emitThisGCrefVars, vars);
5669
5670     /* Are there any GC ref variables on the stack? */
5671
5672     if (emitGCrFrameOffsCnt)
5673     {
5674         int*     tab;
5675         unsigned cnt = emitTrkVarCnt;
5676         unsigned num;
5677
5678         /* Test all the tracked variable bits in the mask */
5679
5680         for (num = 0, tab = emitGCrFrameOffsTab; num < cnt; num++, tab++)
5681         {
5682             int val = *tab;
5683
5684             if (val != -1)
5685             {
5686                 // byref_OFFSET_FLAG and this_OFFSET_FLAG are set
5687                 //  in the table-offsets for byrefs and this-ptr
5688
5689                 int offs = val & ~OFFSET_MASK;
5690
5691                 // printf("var #%2u at %3d is now %s\n", num, offs, (vars & 1) ? "live" : "dead");
5692
5693                 if (VarSetOps::IsMember(emitComp, vars, num))
5694                 {
5695                     GCtype gcType = (val & byref_OFFSET_FLAG) ? GCT_BYREF : GCT_GCREF;
5696                     emitGCvarLiveUpd(offs, INT_MAX, gcType, addr);
5697                 }
5698                 else
5699                 {
5700                     emitGCvarDeadUpd(offs, addr);
5701                 }
5702             }
5703         }
5704     }
5705
5706     emitThisGCrefVset = true;
5707 }
5708
5709 /*****************************************************************************
5710  *
5711  *  Record a call location for GC purposes (we know that this is a method that
5712  *  will not be fully interruptible).
5713  */
5714
5715 void emitter::emitRecordGCcall(BYTE* codePos, unsigned char callInstrSize)
5716 {
5717     assert(emitIssuing);
5718     assert(!emitFullGCinfo);
5719
5720     unsigned offs = emitCurCodeOffs(codePos);
5721     unsigned regs = (emitThisGCrefRegs | emitThisByrefRegs) & ~RBM_INTRET;
5722     callDsc* call;
5723
5724 #ifdef JIT32_GCENCODER
5725     // The JIT32 GCInfo encoder allows us to (as the comment previously here said):
5726     // "Bail if this is a totally boring call", but the GCInfoEncoder/Decoder interface
5727     // requires a definition for every call site, so we skip these "early outs" when we're
5728     // using the general encoder.
5729     if (regs == 0)
5730     {
5731 #if EMIT_TRACK_STACK_DEPTH
5732         if (emitCurStackLvl == 0)
5733             return;
5734 #endif
5735         /* Nope, only interesting calls get recorded */
5736
5737         if (emitSimpleStkUsed)
5738         {
5739             if (!u1.emitSimpleStkMask)
5740                 return;
5741         }
5742         else
5743         {
5744             if (u2.emitGcArgTrackCnt == 0)
5745                 return;
5746         }
5747     }
5748 #endif // JIT32_GCENCODER
5749
5750 #ifdef DEBUG
5751
5752     if (EMIT_GC_VERBOSE)
5753     {
5754         printf("; Call at %04X [stk=%u], GCvars=", offs - callInstrSize, emitCurStackLvl);
5755         emitDispVarSet();
5756         printf(", gcrefRegs=");
5757         printRegMaskInt(emitThisGCrefRegs);
5758         emitDispRegSet(emitThisGCrefRegs);
5759         // printRegMaskInt(emitThisGCrefRegs & ~RBM_INTRET & RBM_CALLEE_SAVED);    // only display callee-saved
5760         // emitDispRegSet (emitThisGCrefRegs & ~RBM_INTRET & RBM_CALLEE_SAVED);    // only display callee-saved
5761         printf(", byrefRegs=");
5762         printRegMaskInt(emitThisByrefRegs);
5763         emitDispRegSet(emitThisByrefRegs);
5764         // printRegMaskInt(emitThisByrefRegs & ~RBM_INTRET & RBM_CALLEE_SAVED);    // only display callee-saved
5765         // emitDispRegSet (emitThisByrefRegs & ~RBM_INTRET & RBM_CALLEE_SAVED);    // only display callee-saved
5766         printf("\n");
5767     }
5768
5769 #endif
5770
5771     /* Allocate a 'call site' descriptor and start filling it in */
5772
5773     call = new (emitComp, CMK_GC) callDsc;
5774
5775     call->cdBlock = nullptr;
5776     call->cdOffs  = offs;
5777 #ifndef JIT32_GCENCODER
5778     call->cdCallInstrSize = callInstrSize;
5779 #endif
5780     call->cdNext = nullptr;
5781
5782     call->cdGCrefRegs = (regMaskSmall)emitThisGCrefRegs;
5783     call->cdByrefRegs = (regMaskSmall)emitThisByrefRegs;
5784
5785 #if EMIT_TRACK_STACK_DEPTH
5786 #ifndef FEATURE_UNIX_AMD64_STRUCT_PASSING
5787     noway_assert(FitsIn<USHORT>(emitCurStackLvl / ((unsigned)sizeof(unsigned))));
5788 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
5789 #endif
5790
5791     // Append the call descriptor to the list */
5792     if (codeGen->gcInfo.gcCallDescLast == nullptr)
5793     {
5794         assert(codeGen->gcInfo.gcCallDescList == nullptr);
5795         codeGen->gcInfo.gcCallDescList = codeGen->gcInfo.gcCallDescLast = call;
5796     }
5797     else
5798     {
5799         assert(codeGen->gcInfo.gcCallDescList != nullptr);
5800         codeGen->gcInfo.gcCallDescLast->cdNext = call;
5801         codeGen->gcInfo.gcCallDescLast         = call;
5802     }
5803
5804     /* Record the current "pending" argument list */
5805
5806     if (emitSimpleStkUsed)
5807     {
5808         /* The biggest call is less than MAX_SIMPLE_STK_DEPTH. So use
5809            small format */
5810
5811         call->u1.cdArgMask      = u1.emitSimpleStkMask;
5812         call->u1.cdByrefArgMask = u1.emitSimpleByrefStkMask;
5813         call->cdArgCnt          = 0;
5814     }
5815     else
5816     {
5817         /* The current call has too many arguments, so we need to report the
5818            offsets of each individual GC arg. */
5819
5820         call->cdArgCnt = u2.emitGcArgTrackCnt;
5821         if (call->cdArgCnt == 0)
5822         {
5823             call->u1.cdArgMask = call->u1.cdByrefArgMask = 0;
5824             return;
5825         }
5826
5827         call->cdArgTable = new (emitComp, CMK_GC) unsigned[u2.emitGcArgTrackCnt];
5828
5829         unsigned gcArgs = 0;
5830         unsigned stkLvl = emitCurStackLvl / sizeof(int);
5831
5832         for (unsigned i = 0; i < stkLvl; i++)
5833         {
5834             GCtype gcType = (GCtype)u2.emitArgTrackTab[stkLvl - i - 1];
5835
5836             if (needsGC(gcType))
5837             {
5838                 call->cdArgTable[gcArgs] = i * sizeof(void*);
5839
5840                 if (gcType == GCT_BYREF)
5841                 {
5842                     call->cdArgTable[gcArgs] |= byref_OFFSET_FLAG;
5843                 }
5844
5845                 gcArgs++;
5846             }
5847         }
5848
5849         assert(gcArgs == u2.emitGcArgTrackCnt);
5850     }
5851 }
5852
5853 /*****************************************************************************
5854  *
5855  *  Record a new set of live GC ref registers.
5856  */
5857
5858 void emitter::emitUpdateLiveGCregs(GCtype gcType, regMaskTP regs, BYTE* addr)
5859 {
5860     assert(emitIssuing);
5861
5862     // Don't track GC changes in epilogs
5863     if (emitIGisInEpilog(emitCurIG))
5864     {
5865         return;
5866     }
5867
5868     regMaskTP life;
5869     regMaskTP dead;
5870     regMaskTP chg;
5871
5872 #ifdef DEBUG
5873     if (EMIT_GC_VERBOSE)
5874     {
5875         printf("New %sReg live regs=", GCtypeStr(gcType));
5876         printRegMaskInt(regs);
5877         emitDispRegSet(regs);
5878         printf("\n");
5879     }
5880 #endif
5881
5882     assert(needsGC(gcType));
5883
5884     regMaskTP& emitThisXXrefRegs = (gcType == GCT_GCREF) ? emitThisGCrefRegs : emitThisByrefRegs;
5885     regMaskTP& emitThisYYrefRegs = (gcType == GCT_GCREF) ? emitThisByrefRegs : emitThisGCrefRegs;
5886     assert(emitThisXXrefRegs != regs);
5887
5888     if (emitFullGCinfo)
5889     {
5890         /* Figure out which GC registers are becoming live/dead at this point */
5891
5892         dead = (emitThisXXrefRegs & ~regs);
5893         life = (~emitThisXXrefRegs & regs);
5894
5895         /* Can't simultaneously become live and dead at the same time */
5896
5897         assert((dead | life) != 0);
5898         assert((dead & life) == 0);
5899
5900         /* Compute the 'changing state' mask */
5901
5902         chg = (dead | life);
5903
5904         do
5905         {
5906             regMaskTP bit = genFindLowestBit(chg);
5907             regNumber reg = genRegNumFromMask(bit);
5908
5909             if (life & bit)
5910             {
5911                 emitGCregLiveUpd(gcType, reg, addr);
5912             }
5913             else
5914             {
5915                 emitGCregDeadUpd(reg, addr);
5916             }
5917
5918             chg -= bit;
5919         } while (chg);
5920
5921         assert(emitThisXXrefRegs == regs);
5922     }
5923     else
5924     {
5925         emitThisYYrefRegs &= ~regs; // Kill the regs from the other GC type (if live)
5926         emitThisXXrefRegs = regs;   // Mark them as live in the requested GC type
5927     }
5928
5929     // The 2 GC reg masks can't be overlapping
5930
5931     assert((emitThisGCrefRegs & emitThisByrefRegs) == 0);
5932 }
5933
5934 /*****************************************************************************
5935  *
5936  *  Record the fact that the given register now contains a live GC ref.
5937  */
5938
5939 void emitter::emitGCregLiveSet(GCtype gcType, regMaskTP regMask, BYTE* addr, bool isThis)
5940 {
5941     assert(emitIssuing);
5942     assert(needsGC(gcType));
5943
5944     regPtrDsc* regPtrNext;
5945
5946     assert(!isThis || emitComp->lvaKeepAliveAndReportThis());
5947     // assert(emitFullyInt || isThis);
5948     assert(emitFullGCinfo);
5949
5950     assert(((emitThisGCrefRegs | emitThisByrefRegs) & regMask) == 0);
5951
5952     /* Allocate a new regptr entry and fill it in */
5953
5954     regPtrNext            = codeGen->gcInfo.gcRegPtrAllocDsc();
5955     regPtrNext->rpdGCtype = gcType;
5956
5957     regPtrNext->rpdOffs            = emitCurCodeOffs(addr);
5958     regPtrNext->rpdArg             = FALSE;
5959     regPtrNext->rpdCall            = FALSE;
5960     regPtrNext->rpdIsThis          = isThis;
5961     regPtrNext->rpdCompiler.rpdAdd = (regMaskSmall)regMask;
5962     regPtrNext->rpdCompiler.rpdDel = 0;
5963 }
5964
5965 /*****************************************************************************
5966  *
5967  *  Record the fact that the given register no longer contains a live GC ref.
5968  */
5969
5970 void emitter::emitGCregDeadSet(GCtype gcType, regMaskTP regMask, BYTE* addr)
5971 {
5972     assert(emitIssuing);
5973     assert(needsGC(gcType));
5974
5975     regPtrDsc* regPtrNext;
5976
5977     // assert(emitFullyInt);
5978     assert(emitFullGCinfo);
5979
5980     assert(((emitThisGCrefRegs | emitThisByrefRegs) & regMask) != 0);
5981
5982     /* Allocate a new regptr entry and fill it in */
5983
5984     regPtrNext            = codeGen->gcInfo.gcRegPtrAllocDsc();
5985     regPtrNext->rpdGCtype = gcType;
5986
5987     regPtrNext->rpdOffs            = emitCurCodeOffs(addr);
5988     regPtrNext->rpdCall            = FALSE;
5989     regPtrNext->rpdIsThis          = FALSE;
5990     regPtrNext->rpdArg             = FALSE;
5991     regPtrNext->rpdCompiler.rpdAdd = 0;
5992     regPtrNext->rpdCompiler.rpdDel = (regMaskSmall)regMask;
5993 }
5994
5995 /*****************************************************************************
5996  *
5997  *  Emit an 8-bit integer as code.
5998  */
5999
6000 unsigned char emitter::emitOutputByte(BYTE* dst, ssize_t val)
6001 {
6002     *castto(dst, unsigned char*) = (unsigned char)val;
6003
6004 #ifdef DEBUG
6005     if (emitComp->opts.dspEmit)
6006     {
6007         printf("; emit_byte 0%02XH\n", val & 0xFF);
6008     }
6009 #ifdef _TARGET_AMD64_
6010     // if we're emitting code bytes, ensure that we've already emitted the rex prefix!
6011     assert(((val & 0xFF00000000LL) == 0) || ((val & 0xFFFFFFFF00000000LL) == 0xFFFFFFFF00000000LL));
6012 #endif // _TARGET_AMD64_
6013 #endif
6014
6015     return sizeof(unsigned char);
6016 }
6017
6018 /*****************************************************************************
6019  *
6020  *  Emit a 16-bit integer as code.
6021  */
6022
6023 unsigned char emitter::emitOutputWord(BYTE* dst, ssize_t val)
6024 {
6025     MISALIGNED_WR_I2(dst, (short)val);
6026
6027 #ifdef DEBUG
6028     if (emitComp->opts.dspEmit)
6029     {
6030         printf("; emit_word 0%02XH,0%02XH\n", (val & 0xFF), (val >> 8) & 0xFF);
6031     }
6032 #ifdef _TARGET_AMD64_
6033     // if we're emitting code bytes, ensure that we've already emitted the rex prefix!
6034     assert(((val & 0xFF00000000LL) == 0) || ((val & 0xFFFFFFFF00000000LL) == 0xFFFFFFFF00000000LL));
6035 #endif // _TARGET_AMD64_
6036 #endif
6037
6038     return sizeof(short);
6039 }
6040
6041 /*****************************************************************************
6042  *
6043  *  Emit a 32-bit integer as code.
6044  */
6045
6046 unsigned char emitter::emitOutputLong(BYTE* dst, ssize_t val)
6047 {
6048     MISALIGNED_WR_I4(dst, (int)val);
6049
6050 #ifdef DEBUG
6051     if (emitComp->opts.dspEmit)
6052     {
6053         printf("; emit_long 0%08XH\n", (int)val);
6054     }
6055 #ifdef _TARGET_AMD64_
6056     // if we're emitting code bytes, ensure that we've already emitted the rex prefix!
6057     assert(((val & 0xFF00000000LL) == 0) || ((val & 0xFFFFFFFF00000000LL) == 0xFFFFFFFF00000000LL));
6058 #endif // _TARGET_AMD64_
6059 #endif
6060
6061     return sizeof(int);
6062 }
6063
6064 /*****************************************************************************
6065  *
6066  *  Emit a pointer-sized integer as code.
6067  */
6068
6069 unsigned char emitter::emitOutputSizeT(BYTE* dst, ssize_t val)
6070 {
6071     MISALIGNED_WR_ST(dst, val);
6072
6073 #ifdef DEBUG
6074     if (emitComp->opts.dspEmit)
6075     {
6076 #ifdef _TARGET_AMD64_
6077         printf("; emit_size_t 0%016llXH\n", val);
6078 #else  // _TARGET_AMD64_
6079         printf("; emit_size_t 0%08XH\n", val);
6080 #endif // _TARGET_AMD64_
6081     }
6082 #endif // DEBUG
6083
6084     return sizeof(size_t);
6085 }
6086
6087 //------------------------------------------------------------------------
6088 // Wrappers to emitOutputByte, emitOutputWord, emitOutputLong, emitOutputSizeT
6089 // that take unsigned __int64 or size_t type instead of ssize_t. Used on RyuJIT/x86.
6090 //
6091 // Arguments:
6092 //    dst - passed through
6093 //    val - passed through
6094 //
6095 // Return Value:
6096 //    Same as wrapped function.
6097 //
6098
6099 #if !defined(LEGACY_BACKEND) && defined(_TARGET_X86_)
6100 unsigned char emitter::emitOutputByte(BYTE* dst, size_t val)
6101 {
6102     return emitOutputByte(dst, (ssize_t)val);
6103 }
6104
6105 unsigned char emitter::emitOutputWord(BYTE* dst, size_t val)
6106 {
6107     return emitOutputWord(dst, (ssize_t)val);
6108 }
6109
6110 unsigned char emitter::emitOutputLong(BYTE* dst, size_t val)
6111 {
6112     return emitOutputLong(dst, (ssize_t)val);
6113 }
6114
6115 unsigned char emitter::emitOutputSizeT(BYTE* dst, size_t val)
6116 {
6117     return emitOutputSizeT(dst, (ssize_t)val);
6118 }
6119
6120 unsigned char emitter::emitOutputByte(BYTE* dst, unsigned __int64 val)
6121 {
6122     return emitOutputByte(dst, (ssize_t)val);
6123 }
6124
6125 unsigned char emitter::emitOutputWord(BYTE* dst, unsigned __int64 val)
6126 {
6127     return emitOutputWord(dst, (ssize_t)val);
6128 }
6129
6130 unsigned char emitter::emitOutputLong(BYTE* dst, unsigned __int64 val)
6131 {
6132     return emitOutputLong(dst, (ssize_t)val);
6133 }
6134
6135 unsigned char emitter::emitOutputSizeT(BYTE* dst, unsigned __int64 val)
6136 {
6137     return emitOutputSizeT(dst, (ssize_t)val);
6138 }
6139 #endif // !defined(LEGACY_BACKEND) && defined(_TARGET_X86_)
6140
6141 /*****************************************************************************
6142  *
6143  *  Given a block cookie and a code position, return the actual code offset;
6144  *  this can only be called at the end of code generation.
6145  */
6146
6147 UNATIVE_OFFSET emitter::emitCodeOffset(void* blockPtr, unsigned codePos)
6148 {
6149     insGroup* ig;
6150
6151     UNATIVE_OFFSET of;
6152     unsigned       no = emitGetInsNumFromCodePos(codePos);
6153
6154     /* Make sure we weren't passed some kind of a garbage thing */
6155
6156     ig = (insGroup*)blockPtr;
6157 #ifdef DEBUG
6158     assert(ig && ig->igSelf == ig);
6159 #endif
6160
6161     /* The first and last offsets are always easy */
6162
6163     if (no == 0)
6164     {
6165         of = 0;
6166     }
6167     else if (no == ig->igInsCnt)
6168     {
6169         of = ig->igSize;
6170     }
6171     else if (ig->igFlags & IGF_UPD_ISZ)
6172     {
6173         /*
6174             Some instruction sizes have changed, so we'll have to figure
6175             out the instruction offset "the hard way".
6176          */
6177
6178         of = emitFindOffset(ig, no);
6179     }
6180     else
6181     {
6182         /* All instructions correctly predicted, the offset stays the same */
6183
6184         of = emitGetInsOfsFromCodePos(codePos);
6185
6186         // printf("[IG=%02u;ID=%03u;OF=%04X] <= %08X\n", ig->igNum, emitGetInsNumFromCodePos(codePos), of, codePos);
6187
6188         /* Make sure the offset estimate is accurate */
6189
6190         assert(of == emitFindOffset(ig, emitGetInsNumFromCodePos(codePos)));
6191     }
6192
6193     return ig->igOffs + of;
6194 }
6195
6196 /*****************************************************************************
6197  *
6198  *  Record the fact that the given register now contains a live GC ref.
6199  */
6200
6201 void emitter::emitGCregLiveUpd(GCtype gcType, regNumber reg, BYTE* addr)
6202 {
6203     assert(emitIssuing);
6204
6205     // Don't track GC changes in epilogs
6206     if (emitIGisInEpilog(emitCurIG))
6207     {
6208         return;
6209     }
6210
6211     assert(needsGC(gcType));
6212
6213     regMaskTP regMask = genRegMask(reg);
6214
6215     regMaskTP& emitThisXXrefRegs = (gcType == GCT_GCREF) ? emitThisGCrefRegs : emitThisByrefRegs;
6216     regMaskTP& emitThisYYrefRegs = (gcType == GCT_GCREF) ? emitThisByrefRegs : emitThisGCrefRegs;
6217
6218     if ((emitThisXXrefRegs & regMask) == 0)
6219     {
6220         // If the register was holding the other GC type, that type should
6221         // go dead now
6222
6223         if (emitThisYYrefRegs & regMask)
6224         {
6225             emitGCregDeadUpd(reg, addr);
6226         }
6227
6228         // For synchronized methods, "this" is always alive and in the same register.
6229         // However, if we generate any code after the epilog block (where "this"
6230         // goes dead), "this" will come alive again. We need to notice that.
6231         // Note that we only expect isThis to be true at an insGroup boundary.
6232
6233         bool isThis = (reg == emitSyncThisObjReg) ? true : false;
6234
6235         if (emitFullGCinfo)
6236         {
6237             emitGCregLiveSet(gcType, regMask, addr, isThis);
6238         }
6239
6240         emitThisXXrefRegs |= regMask;
6241
6242 #ifdef DEBUG
6243         if (EMIT_GC_VERBOSE)
6244         {
6245             printf("%sReg +[%s]\n", GCtypeStr(gcType), emitRegName(reg));
6246         }
6247 #endif
6248     }
6249
6250     // The 2 GC reg masks can't be overlapping
6251
6252     assert((emitThisGCrefRegs & emitThisByrefRegs) == 0);
6253 }
6254
6255 /*****************************************************************************
6256  *
6257  *  Record the fact that the given set of registers no longer contain live GC refs.
6258  */
6259
6260 void emitter::emitGCregDeadUpdMask(regMaskTP regs, BYTE* addr)
6261 {
6262     assert(emitIssuing);
6263
6264     // Don't track GC changes in epilogs
6265     if (emitIGisInEpilog(emitCurIG))
6266     {
6267         return;
6268     }
6269
6270     // First, handle the gcref regs going dead
6271
6272     regMaskTP gcrefRegs = emitThisGCrefRegs & regs;
6273
6274     // "this" can never go dead in synchronized methods, except in the epilog
6275     // after the call to CORINFO_HELP_MON_EXIT.
6276     assert(emitSyncThisObjReg == REG_NA || (genRegMask(emitSyncThisObjReg) & regs) == 0);
6277
6278     if (gcrefRegs)
6279     {
6280         assert((emitThisByrefRegs & gcrefRegs) == 0);
6281
6282         if (emitFullGCinfo)
6283         {
6284             emitGCregDeadSet(GCT_GCREF, gcrefRegs, addr);
6285         }
6286
6287         emitThisGCrefRegs &= ~gcrefRegs;
6288
6289 #ifdef DEBUG
6290         if (EMIT_GC_VERBOSE)
6291         {
6292             printf("gcrReg ");
6293             printRegMaskInt(gcrefRegs);
6294             printf(" -");
6295             emitDispRegSet(gcrefRegs);
6296             printf("\n");
6297         }
6298 #endif
6299     }
6300
6301     // Second, handle the byref regs going dead
6302
6303     regMaskTP byrefRegs = emitThisByrefRegs & regs;
6304
6305     if (byrefRegs)
6306     {
6307         assert((emitThisGCrefRegs & byrefRegs) == 0);
6308
6309         if (emitFullGCinfo)
6310         {
6311             emitGCregDeadSet(GCT_BYREF, byrefRegs, addr);
6312         }
6313
6314         emitThisByrefRegs &= ~byrefRegs;
6315
6316 #ifdef DEBUG
6317         if (EMIT_GC_VERBOSE)
6318         {
6319             printf("byrReg ");
6320             printRegMaskInt(byrefRegs);
6321             printf(" -");
6322             emitDispRegSet(byrefRegs);
6323             printf("\n");
6324         }
6325 #endif
6326     }
6327 }
6328
6329 /*****************************************************************************
6330  *
6331  *  Record the fact that the given register no longer contains a live GC ref.
6332  */
6333
6334 void emitter::emitGCregDeadUpd(regNumber reg, BYTE* addr)
6335 {
6336     assert(emitIssuing);
6337
6338     // Don't track GC changes in epilogs
6339     if (emitIGisInEpilog(emitCurIG))
6340     {
6341         return;
6342     }
6343
6344     regMaskTP regMask = genRegMask(reg);
6345
6346     if ((emitThisGCrefRegs & regMask) != 0)
6347     {
6348         assert((emitThisByrefRegs & regMask) == 0);
6349
6350         if (emitFullGCinfo)
6351         {
6352             emitGCregDeadSet(GCT_GCREF, regMask, addr);
6353         }
6354
6355         emitThisGCrefRegs &= ~regMask;
6356
6357 #ifdef DEBUG
6358         if (EMIT_GC_VERBOSE)
6359         {
6360             printf("%s -[%s]\n", "gcrReg", emitRegName(reg));
6361         }
6362 #endif
6363     }
6364     else if ((emitThisByrefRegs & regMask) != 0)
6365     {
6366         if (emitFullGCinfo)
6367         {
6368             emitGCregDeadSet(GCT_BYREF, regMask, addr);
6369         }
6370
6371         emitThisByrefRegs &= ~regMask;
6372
6373 #ifdef DEBUG
6374         if (EMIT_GC_VERBOSE)
6375         {
6376             printf("%s -[%s]\n", "byrReg", emitRegName(reg));
6377         }
6378 #endif
6379     }
6380 }
6381
6382 /*****************************************************************************
6383  *
6384  *  Record the fact that the given variable now contains a live GC ref.
6385  *  varNum may be INT_MAX or negative (indicating a spill temp) only if
6386  *    offs is guaranteed to be the offset of a tracked GC ref. Else we
6387  *    need a valid value to check if the variable is tracked or not.
6388  */
6389
6390 void emitter::emitGCvarLiveUpd(int offs, int varNum, GCtype gcType, BYTE* addr)
6391 {
6392     assert(abs(offs) % sizeof(int) == 0);
6393     assert(needsGC(gcType));
6394
6395 #if FEATURE_FIXED_OUT_ARGS
6396     if ((unsigned)varNum == emitComp->lvaOutgoingArgSpaceVar)
6397     {
6398         if (emitFullGCinfo)
6399         {
6400             /* Append an "arg push" entry to track a GC written to the
6401                outgoing argument space.
6402                Allocate a new ptr arg entry and fill it in */
6403
6404             regPtrDsc* regPtrNext = gcInfo->gcRegPtrAllocDsc();
6405             regPtrNext->rpdGCtype = gcType;
6406             regPtrNext->rpdOffs   = emitCurCodeOffs(addr);
6407             regPtrNext->rpdArg    = TRUE;
6408             regPtrNext->rpdCall   = FALSE;
6409             noway_assert(FitsIn<unsigned short>(offs));
6410             regPtrNext->rpdPtrArg  = (unsigned short)offs;
6411             regPtrNext->rpdArgType = (unsigned short)GCInfo::rpdARG_PUSH;
6412             regPtrNext->rpdIsThis  = FALSE;
6413
6414 #ifdef DEBUG
6415             if (EMIT_GC_VERBOSE)
6416             {
6417                 printf("[%04X] %s arg write\n", offs, GCtypeStr(gcType));
6418             }
6419 #endif
6420         }
6421     }
6422     else
6423 #endif // FEATURE_FIXED_OUT_ARGS
6424     {
6425         /* Is the frame offset within the "interesting" range? */
6426
6427         if (offs >= emitGCrFrameOffsMin && offs < emitGCrFrameOffsMax)
6428         {
6429             /* Normally all variables in this range must be tracked stack
6430                pointers. However, for EnC, we relax this condition. So we
6431                must check if this is not such a variable.
6432                Note that varNum might be negative, indicating a spill temp.
6433             */
6434
6435             if (varNum != INT_MAX)
6436             {
6437                 bool isTracked = false;
6438                 if (varNum >= 0)
6439                 {
6440                     // This is NOT a spill temp
6441                     LclVarDsc* varDsc = &emitComp->lvaTable[varNum];
6442                     isTracked         = emitComp->lvaIsGCTracked(varDsc);
6443                 }
6444                 else
6445                 {
6446                     // Is it an untracked spill temp?
6447                     isTracked = TRACK_GC_TEMP_LIFETIMES;
6448                 }
6449                 if (!isTracked)
6450                 {
6451 #if DOUBLE_ALIGN
6452                     assert(!emitContTrkPtrLcls ||
6453                            // EBP based variables in the double-aligned frames are indeed input arguments.
6454                            // and we don't require them to fall into the "interesting" range.
6455                            ((emitComp->rpFrameType == FT_DOUBLE_ALIGN_FRAME) && (varNum >= 0) &&
6456                             (emitComp->lvaTable[varNum].lvFramePointerBased == 1)));
6457 #else
6458                     assert(!emitContTrkPtrLcls);
6459 #endif
6460                     return;
6461                 }
6462             }
6463
6464             size_t disp;
6465
6466             /* Compute the index into the GC frame table */
6467
6468             disp = (offs - emitGCrFrameOffsMin) / sizeof(void*);
6469             assert(disp < emitGCrFrameOffsCnt);
6470
6471             /* If the variable is currently dead, mark it as live */
6472
6473             if (emitGCrFrameLiveTab[disp] == nullptr)
6474             {
6475                 emitGCvarLiveSet(offs, gcType, addr, disp);
6476             }
6477         }
6478     }
6479 }
6480
6481 /*****************************************************************************
6482  *
6483  *  Record the fact that the given variable no longer contains a live GC ref.
6484  */
6485
6486 void emitter::emitGCvarDeadUpd(int offs, BYTE* addr)
6487 {
6488     assert(emitIssuing);
6489     assert(abs(offs) % sizeof(int) == 0);
6490
6491     /* Is the frame offset within the "interesting" range? */
6492
6493     if (offs >= emitGCrFrameOffsMin && offs < emitGCrFrameOffsMax)
6494     {
6495         size_t disp;
6496
6497         /* Compute the index into the GC frame table */
6498
6499         disp = (offs - emitGCrFrameOffsMin) / sizeof(void*);
6500         assert(disp < emitGCrFrameOffsCnt);
6501
6502         /* If the variable is currently live, mark it as dead */
6503
6504         if (emitGCrFrameLiveTab[disp] != nullptr)
6505         {
6506             emitGCvarDeadSet(offs, addr, disp);
6507         }
6508     }
6509 }
6510
6511 /*****************************************************************************
6512  *
6513  *  Allocate a new IG and link it in to the global list after the current IG
6514  */
6515
6516 insGroup* emitter::emitAllocAndLinkIG()
6517 {
6518     insGroup* ig = emitAllocIG();
6519
6520     assert(emitCurIG);
6521
6522     emitInsertIGAfter(emitCurIG, ig);
6523
6524     /* Propagate some IG flags from the current group to the new group */
6525
6526     ig->igFlags |= (emitCurIG->igFlags & IGF_PROPAGATE_MASK);
6527
6528     /* Set the new IG as the current IG */
6529
6530     emitCurIG = ig;
6531
6532     return ig;
6533 }
6534
6535 /*****************************************************************************
6536  *
6537  *  Allocate an instruction group descriptor and assign it the next index.
6538  */
6539
6540 insGroup* emitter::emitAllocIG()
6541 {
6542     insGroup* ig;
6543
6544     /* Allocate a group descriptor */
6545
6546     size_t sz = sizeof(insGroup);
6547     ig        = (insGroup*)emitGetMem(sz);
6548
6549 #ifdef DEBUG
6550     ig->igSelf = ig;
6551 #endif
6552
6553 #if EMITTER_STATS
6554     emitTotalIGcnt += 1;
6555     emitTotalIGsize += sz;
6556     emitSizeMethod += sz;
6557 #endif
6558
6559     /* Do basic initialization */
6560
6561     emitInitIG(ig);
6562
6563     return ig;
6564 }
6565
6566 /*****************************************************************************
6567  *
6568  *  Initialize an instruction group
6569  */
6570
6571 void emitter::emitInitIG(insGroup* ig)
6572 {
6573     /* Assign the next available index to the instruction group */
6574
6575     ig->igNum = emitNxtIGnum;
6576
6577     emitNxtIGnum++;
6578
6579     /* Record the (estimated) code offset of the group */
6580
6581     ig->igOffs = emitCurCodeOffset;
6582     assert(IsCodeAligned(ig->igOffs));
6583
6584     /* Set the current function index */
6585
6586     ig->igFuncIdx = emitComp->compCurrFuncIdx;
6587
6588     ig->igFlags = 0;
6589
6590     /* Zero out some fields to avoid printing garbage in JitDumps. These
6591        really only need to be set in DEBUG, but do it in all cases to make
6592        sure we act the same in non-DEBUG builds.
6593     */
6594
6595     ig->igSize   = 0;
6596     ig->igGCregs = RBM_NONE;
6597     ig->igInsCnt = 0;
6598 }
6599
6600 /*****************************************************************************
6601  *
6602  *  Insert instruction group 'ig' after 'igInsertAfterIG'
6603  */
6604
6605 void emitter::emitInsertIGAfter(insGroup* insertAfterIG, insGroup* ig)
6606 {
6607     assert(emitIGlist);
6608     assert(emitIGlast);
6609
6610     ig->igNext            = insertAfterIG->igNext;
6611     insertAfterIG->igNext = ig;
6612
6613     if (emitIGlast == insertAfterIG)
6614     {
6615         // If we are inserting at the end, then update the 'last' pointer
6616         emitIGlast = ig;
6617     }
6618 }
6619
6620 /*****************************************************************************
6621  *
6622  *  Save the current IG and start a new one.
6623  */
6624
6625 void emitter::emitNxtIG(bool emitAdd)
6626 {
6627     /* Right now we don't allow multi-IG prologs */
6628
6629     assert(emitCurIG != emitPrologIG);
6630
6631     /* First save the current group */
6632
6633     emitSavIG(emitAdd);
6634
6635     /* Update the GC live sets for the group's start
6636      * Do it only if not an emitter added block */
6637
6638     if (!emitAdd)
6639     {
6640         VarSetOps::Assign(emitComp, emitInitGCrefVars, emitThisGCrefVars);
6641         emitInitGCrefRegs = emitThisGCrefRegs;
6642         emitInitByrefRegs = emitThisByrefRegs;
6643     }
6644
6645     /* Start generating the new group */
6646
6647     emitNewIG();
6648
6649     /* If this is an emitter added block, flag it */
6650
6651     if (emitAdd)
6652     {
6653         emitCurIG->igFlags |= IGF_EMIT_ADD;
6654     }
6655
6656     // We've created a new IG; no need to force another one.
6657     emitForceNewIG = false;
6658 }
6659
6660 /*****************************************************************************
6661  *
6662  *  emitGetInsSC: Get the instruction's constant value.
6663  */
6664
6665 ssize_t emitter::emitGetInsSC(instrDesc* id)
6666 {
6667 #ifdef _TARGET_ARM_ // should it be _TARGET_ARMARCH_? Why do we need this? Note that on ARM64 we store scaled immediates
6668                     // for some formats
6669     if (id->idIsLclVar())
6670     {
6671         int varNum = id->idAddr()->iiaLclVar.lvaVarNum();
6672
6673         regNumber baseReg;
6674         int       offs = id->idAddr()->iiaLclVar.lvaOffset();
6675 #if defined(_TARGET_ARM_)
6676         int adr = emitComp->lvaFrameAddress(varNum, id->idIsLclFPBase(), &baseReg, offs);
6677         int dsp = adr + offs;
6678         if ((id->idIns() == INS_sub) || (id->idIns() == INS_subw))
6679             dsp = -dsp;
6680 #elif defined(_TARGET_ARM64_)
6681         // TODO-ARM64-Cleanup: this is currently unreachable. Do we need it?
6682         bool FPbased;
6683         int  adr = emitComp->lvaFrameAddress(varNum, &FPbased);
6684         int  dsp = adr + offs;
6685         if (id->idIns() == INS_sub)
6686             dsp = -dsp;
6687 #endif
6688         return dsp;
6689     }
6690     else
6691 #endif // _TARGET_ARM_
6692         if (id->idIsLargeCns())
6693     {
6694         return ((instrDescCns*)id)->idcCnsVal;
6695     }
6696     else
6697     {
6698         return id->idSmallCns();
6699     }
6700 }
6701
6702 /*****************************************************************************/
6703 #if EMIT_TRACK_STACK_DEPTH
6704 /*****************************************************************************
6705  *
6706  *  Record a push of a single dword on the stack.
6707  */
6708
6709 void emitter::emitStackPush(BYTE* addr, GCtype gcType)
6710 {
6711 #ifdef DEBUG
6712     assert(IsValidGCtype(gcType));
6713 #endif
6714
6715     if (emitSimpleStkUsed)
6716     {
6717         assert(!emitFullGCinfo); // Simple stk not used for emitFullGCinfo
6718         assert(emitCurStackLvl / sizeof(int) < MAX_SIMPLE_STK_DEPTH);
6719
6720         u1.emitSimpleStkMask <<= 1;
6721         u1.emitSimpleStkMask |= (unsigned)needsGC(gcType);
6722
6723         u1.emitSimpleByrefStkMask <<= 1;
6724         u1.emitSimpleByrefStkMask |= (gcType == GCT_BYREF);
6725
6726         assert((u1.emitSimpleStkMask & u1.emitSimpleByrefStkMask) == u1.emitSimpleByrefStkMask);
6727     }
6728     else
6729     {
6730         emitStackPushLargeStk(addr, gcType);
6731     }
6732
6733     emitCurStackLvl += sizeof(int);
6734 }
6735
6736 /*****************************************************************************
6737  *
6738  *  Record a push of a bunch of non-GC dwords on the stack.
6739  */
6740
6741 void emitter::emitStackPushN(BYTE* addr, unsigned count)
6742 {
6743     assert(count);
6744
6745     if (emitSimpleStkUsed)
6746     {
6747         assert(!emitFullGCinfo); // Simple stk not used for emitFullGCinfo
6748
6749         u1.emitSimpleStkMask <<= count;
6750         u1.emitSimpleByrefStkMask <<= count;
6751     }
6752     else
6753     {
6754         emitStackPushLargeStk(addr, GCT_NONE, count);
6755     }
6756
6757     emitCurStackLvl += count * sizeof(int);
6758 }
6759
6760 /*****************************************************************************
6761  *
6762  *  Record a pop of the given number of dwords from the stack.
6763  */
6764
6765 void emitter::emitStackPop(BYTE* addr, bool isCall, unsigned char callInstrSize, unsigned count)
6766 {
6767     assert(emitCurStackLvl / sizeof(int) >= count);
6768     assert(!isCall || callInstrSize > 0);
6769
6770     if (count)
6771     {
6772         if (emitSimpleStkUsed)
6773         {
6774             assert(!emitFullGCinfo); // Simple stk not used for emitFullGCinfo
6775
6776             unsigned cnt = count;
6777
6778             do
6779             {
6780                 u1.emitSimpleStkMask >>= 1;
6781                 u1.emitSimpleByrefStkMask >>= 1;
6782             } while (--cnt);
6783         }
6784         else
6785         {
6786             emitStackPopLargeStk(addr, isCall, callInstrSize, count);
6787         }
6788
6789         emitCurStackLvl -= count * sizeof(int);
6790     }
6791     else
6792     {
6793         assert(isCall);
6794
6795         // For the general encoder we do the call below always when it's a call, to ensure that the call is
6796         // recorded (when we're doing the ptr reg map for a non-fully-interruptible method).
6797         if (emitFullGCinfo
6798 #ifndef JIT32_GCENCODER
6799             || (emitComp->genFullPtrRegMap && (!emitComp->genInterruptible) && isCall)
6800 #endif // JIT32_GCENCODER
6801                 )
6802         {
6803             emitStackPopLargeStk(addr, isCall, callInstrSize, 0);
6804         }
6805     }
6806 }
6807
6808 /*****************************************************************************
6809  *
6810  *  Record a push of a single word on the stack for a full pointer map.
6811  */
6812
6813 void emitter::emitStackPushLargeStk(BYTE* addr, GCtype gcType, unsigned count)
6814 {
6815     S_UINT32 level(emitCurStackLvl / sizeof(int));
6816
6817     assert(IsValidGCtype(gcType));
6818     assert(count);
6819     assert(!emitSimpleStkUsed);
6820
6821     do
6822     {
6823         /* Push an entry for this argument on the tracking stack */
6824
6825         // printf("Pushed [%d] at lvl %2u [max=%u]\n", isGCref, emitArgTrackTop - emitArgTrackTab, emitMaxStackDepth);
6826
6827         assert(level.IsOverflow() || u2.emitArgTrackTop == u2.emitArgTrackTab + level.Value());
6828         *u2.emitArgTrackTop++ = (BYTE)gcType;
6829         assert(u2.emitArgTrackTop <= u2.emitArgTrackTab + emitMaxStackDepth);
6830
6831         if (emitFullArgInfo || needsGC(gcType))
6832         {
6833             if (emitFullGCinfo)
6834             {
6835                 /* Append an "arg push" entry if this is a GC ref or
6836                    FPO method. Allocate a new ptr arg entry and fill it in */
6837
6838                 regPtrDsc* regPtrNext = codeGen->gcInfo.gcRegPtrAllocDsc();
6839                 regPtrNext->rpdGCtype = gcType;
6840
6841                 regPtrNext->rpdOffs = emitCurCodeOffs(addr);
6842                 regPtrNext->rpdArg  = TRUE;
6843                 regPtrNext->rpdCall = FALSE;
6844                 if (level.IsOverflow() || !FitsIn<unsigned short>(level.Value()))
6845                 {
6846                     IMPL_LIMITATION("Too many/too big arguments to encode GC information");
6847                 }
6848                 regPtrNext->rpdPtrArg  = (unsigned short)level.Value();
6849                 regPtrNext->rpdArgType = (unsigned short)GCInfo::rpdARG_PUSH;
6850                 regPtrNext->rpdIsThis  = FALSE;
6851
6852 #ifdef DEBUG
6853                 if (EMIT_GC_VERBOSE)
6854                 {
6855                     printf("[%08X] %s arg push %u\n", dspPtr(regPtrNext), GCtypeStr(gcType), level.Value());
6856                 }
6857 #endif
6858             }
6859
6860             /* This is an "interesting" argument push */
6861
6862             u2.emitGcArgTrackCnt++;
6863         }
6864         level += 1;
6865         assert(!level.IsOverflow());
6866     } while (--count);
6867 }
6868
6869 /*****************************************************************************
6870  *
6871  *  Record a pop of the given number of words from the stack for a full ptr
6872  *  map.
6873  */
6874
6875 void emitter::emitStackPopLargeStk(BYTE* addr, bool isCall, unsigned char callInstrSize, unsigned count)
6876 {
6877     assert(emitIssuing);
6878
6879     unsigned argStkCnt;
6880     S_UINT16 argRecCnt(0); // arg count for ESP, ptr-arg count for EBP
6881     unsigned gcrefRegs, byrefRegs;
6882
6883 #ifdef JIT32_GCENCODER
6884     // For the general encoder, we always need to record calls, so we make this call
6885     // even when emitSimpleStkUsed is true.
6886     assert(!emitSimpleStkUsed);
6887 #endif
6888
6889     /* Count how many pointer records correspond to this "pop" */
6890
6891     for (argStkCnt = count; argStkCnt; argStkCnt--)
6892     {
6893         assert(u2.emitArgTrackTop > u2.emitArgTrackTab);
6894
6895         GCtype gcType = (GCtype)(*--u2.emitArgTrackTop);
6896
6897         assert(IsValidGCtype(gcType));
6898
6899         // printf("Popped [%d] at lvl %u\n", GCtypeStr(gcType), emitArgTrackTop - emitArgTrackTab);
6900
6901         // This is an "interesting" argument
6902
6903         if (emitFullArgInfo || needsGC(gcType))
6904         {
6905             argRecCnt += 1;
6906         }
6907     }
6908
6909     assert(u2.emitArgTrackTop >= u2.emitArgTrackTab);
6910     assert(u2.emitArgTrackTop == u2.emitArgTrackTab + emitCurStackLvl / sizeof(int) - count);
6911     noway_assert(!argRecCnt.IsOverflow());
6912
6913     /* We're about to pop the corresponding arg records */
6914
6915     u2.emitGcArgTrackCnt -= argRecCnt.Value();
6916
6917 #ifdef JIT32_GCENCODER
6918     // For the general encoder, we always have to record calls, so we don't take this early return.
6919     if (!emitFullGCinfo)
6920         return;
6921 #endif
6922
6923     // Do we have any interesting (i.e., callee-saved) registers live here?
6924
6925     gcrefRegs = byrefRegs = 0;
6926
6927     // We make a bitmask whose bits correspond to callee-saved register indices (in the sequence
6928     // of callee-saved registers only).
6929     for (unsigned calleeSavedRegIdx = 0; calleeSavedRegIdx < CNT_CALLEE_SAVED; calleeSavedRegIdx++)
6930     {
6931         regMaskTP calleeSavedRbm = raRbmCalleeSaveOrder[calleeSavedRegIdx];
6932         if (emitThisGCrefRegs & calleeSavedRbm)
6933         {
6934             gcrefRegs |= (1 << calleeSavedRegIdx);
6935         }
6936         if (emitThisByrefRegs & calleeSavedRbm)
6937         {
6938             byrefRegs |= (1 << calleeSavedRegIdx);
6939         }
6940     }
6941
6942 #ifdef JIT32_GCENCODER
6943     // For the general encoder, we always have to record calls, so we don't take this early return.    /* Are there any
6944     // args to pop at this call site?
6945
6946     if (argRecCnt.Value() == 0)
6947     {
6948         /*
6949             Or do we have a partially interruptible EBP-less frame, and any
6950             of EDI,ESI,EBX,EBP are live, or is there an outer/pending call?
6951          */
6952         CLANG_FORMAT_COMMENT_ANCHOR;
6953
6954 #if !FPO_INTERRUPTIBLE
6955         if (emitFullyInt || (gcrefRegs == 0 && byrefRegs == 0 && u2.emitGcArgTrackCnt == 0))
6956 #endif
6957             return;
6958     }
6959 #endif // JIT32_GCENCODER
6960
6961     /* Only calls may pop more than one value */
6962     // More detail:
6963     // _cdecl calls accomplish this popping via a post-call-instruction SP adjustment.
6964     // The "rpdCall" field below should be interpreted as "the instruction accomplishes
6965     // call-related popping, even if it's not itself a call".  Therefore, we don't just
6966     // use the "isCall" input argument, which means that the instruction actually is a call --
6967     // we use the OR of "isCall" or the "pops more than one value."
6968
6969     bool isCallRelatedPop = (argRecCnt.Value() > 1);
6970
6971     /* Allocate a new ptr arg entry and fill it in */
6972
6973     regPtrDsc* regPtrNext = codeGen->gcInfo.gcRegPtrAllocDsc();
6974     regPtrNext->rpdGCtype = GCT_GCREF; // Pops need a non-0 value (??)
6975
6976     regPtrNext->rpdOffs = emitCurCodeOffs(addr);
6977     regPtrNext->rpdCall = (isCall || isCallRelatedPop);
6978 #ifndef JIT32_GCENCODER
6979     if (regPtrNext->rpdCall)
6980     {
6981         assert(isCall || callInstrSize == 0);
6982         regPtrNext->rpdCallInstrSize = callInstrSize;
6983     }
6984 #endif
6985     regPtrNext->rpdCallGCrefRegs = gcrefRegs;
6986     regPtrNext->rpdCallByrefRegs = byrefRegs;
6987     regPtrNext->rpdArg           = TRUE;
6988     regPtrNext->rpdArgType       = (unsigned short)GCInfo::rpdARG_POP;
6989     regPtrNext->rpdPtrArg        = argRecCnt.Value();
6990
6991 #ifdef DEBUG
6992     if (EMIT_GC_VERBOSE)
6993     {
6994         printf("[%08X] ptr arg pop  %u\n", dspPtr(regPtrNext), count);
6995     }
6996 #endif
6997 }
6998
6999 /*****************************************************************************
7000  *  For caller-pop arguments, we report the arguments as pending arguments.
7001  *  However, any GC arguments are now dead, so we need to report them
7002  *  as non-GC.
7003  */
7004
7005 void emitter::emitStackKillArgs(BYTE* addr, unsigned count, unsigned char callInstrSize)
7006 {
7007     assert(count > 0);
7008
7009     if (emitSimpleStkUsed)
7010     {
7011         assert(!emitFullGCinfo); // Simple stk not used for emitFullGCInfo
7012
7013         /* We don't need to report this to the GC info, but we do need
7014            to kill mark the ptrs on the stack as non-GC */
7015
7016         assert(emitCurStackLvl / sizeof(int) >= count);
7017
7018         for (unsigned lvl = 0; lvl < count; lvl++)
7019         {
7020             u1.emitSimpleStkMask &= ~(1 << lvl);
7021             u1.emitSimpleByrefStkMask &= ~(1 << lvl);
7022         }
7023     }
7024     else
7025     {
7026         BYTE*    argTrackTop = u2.emitArgTrackTop;
7027         S_UINT16 gcCnt(0);
7028
7029         for (unsigned i = 0; i < count; i++)
7030         {
7031             assert(argTrackTop > u2.emitArgTrackTab);
7032
7033             --argTrackTop;
7034
7035             GCtype gcType = (GCtype)(*argTrackTop);
7036             assert(IsValidGCtype(gcType));
7037
7038             if (needsGC(gcType))
7039             {
7040                 // printf("Killed %s at lvl %u\n", GCtypeStr(gcType), argTrackTop - emitArgTrackTab);
7041
7042                 *argTrackTop = GCT_NONE;
7043                 gcCnt += 1;
7044             }
7045         }
7046
7047         noway_assert(!gcCnt.IsOverflow());
7048
7049         /* We're about to kill the corresponding (pointer) arg records */
7050
7051         if (!emitFullArgInfo)
7052         {
7053             u2.emitGcArgTrackCnt -= gcCnt.Value();
7054         }
7055
7056         if (!emitFullGCinfo)
7057         {
7058             return;
7059         }
7060
7061         /* Right after the call, the arguments are still sitting on the
7062            stack, but they are effectively dead. For fully-interruptible
7063            methods, we need to report that */
7064
7065         if (emitFullGCinfo && gcCnt.Value())
7066         {
7067             /* Allocate a new ptr arg entry and fill it in */
7068
7069             regPtrDsc* regPtrNext = codeGen->gcInfo.gcRegPtrAllocDsc();
7070             regPtrNext->rpdGCtype = GCT_GCREF; // Kills need a non-0 value (??)
7071
7072             regPtrNext->rpdOffs = emitCurCodeOffs(addr);
7073
7074             regPtrNext->rpdArg     = TRUE;
7075             regPtrNext->rpdArgType = (unsigned short)GCInfo::rpdARG_KILL;
7076             regPtrNext->rpdPtrArg  = gcCnt.Value();
7077
7078 #ifdef DEBUG
7079             if (EMIT_GC_VERBOSE)
7080             {
7081                 printf("[%08X] ptr arg kill %u\n", dspPtr(regPtrNext), count);
7082             }
7083 #endif
7084         }
7085
7086         /* Now that ptr args have been marked as non-ptrs, we need to record
7087            the call itself as one that has no arguments. */
7088
7089         emitStackPopLargeStk(addr, true, callInstrSize, 0);
7090     }
7091 }
7092
7093 /*****************************************************************************
7094  *  A helper for recording a relocation with the EE.
7095  */
7096 void emitter::emitRecordRelocation(void* location,            /* IN */
7097                                    void* target,              /* IN */
7098                                    WORD  fRelocType,          /* IN */
7099                                    WORD  slotNum /* = 0 */,   /* IN */
7100                                    INT32 addlDelta /* = 0 */) /* IN */
7101 {
7102     // If we're an unmatched altjit, don't tell the VM anything. We still record the relocation for
7103     // late disassembly; maybe we'll need it?
7104     if (emitComp->info.compMatchedVM)
7105     {
7106         emitCmpHandle->recordRelocation(location, target, fRelocType, slotNum, addlDelta);
7107     }
7108 #if defined(LATE_DISASM)
7109     codeGen->getDisAssembler().disRecordRelocation((size_t)location, (size_t)target);
7110 #endif // defined(LATE_DISASM)
7111 }
7112
7113 #ifdef _TARGET_ARM_
7114 /*****************************************************************************
7115  *  A helper for handling a Thumb-Mov32 of position-independent (PC-relative) value
7116  *
7117  *  This routine either records relocation for the location with the EE,
7118  *  or creates a virtual relocation entry to perform offset fixup during
7119  *  compilation without recording it with EE - depending on which of
7120  *  absolute/relocative relocations mode are used for code section.
7121  */
7122 void emitter::emitHandlePCRelativeMov32(void* location, /* IN */
7123                                         void* target)   /* IN */
7124 {
7125     if (emitComp->opts.jitFlags->IsSet(JitFlags::JIT_FLAG_RELATIVE_CODE_RELOCS))
7126     {
7127         emitRecordRelocation(location, target, IMAGE_REL_BASED_REL_THUMB_MOV32_PCREL);
7128     }
7129     else
7130     {
7131         emitRecordRelocation(location, target, IMAGE_REL_BASED_THUMB_MOV32);
7132     }
7133 }
7134 #endif // _TARGET_ARM_
7135
7136 /*****************************************************************************
7137  *  A helper for recording a call site with the EE.
7138  */
7139 void emitter::emitRecordCallSite(ULONG                 instrOffset,  /* IN */
7140                                  CORINFO_SIG_INFO*     callSig,      /* IN */
7141                                  CORINFO_METHOD_HANDLE methodHandle) /* IN */
7142 {
7143 #if defined(DEBUG)
7144     // Since CORINFO_SIG_INFO is a heavyweight structure, in most cases we can
7145     // lazily obtain it here using the given method handle (we only save the sig
7146     // info when we explicitly need it, i.e. for CALLI calls, vararg calls, and
7147     // tail calls).
7148     if (callSig == nullptr)
7149     {
7150         assert(methodHandle != nullptr);
7151
7152         if (Compiler::eeGetHelperNum(methodHandle) == CORINFO_HELP_UNDEF)
7153         {
7154             if (emitScratchSigInfo == nullptr)
7155             {
7156                 emitScratchSigInfo = new (emitComp, CMK_CorSig) CORINFO_SIG_INFO;
7157             }
7158
7159             emitComp->eeGetMethodSig(methodHandle, emitScratchSigInfo);
7160             callSig = emitScratchSigInfo;
7161         }
7162     }
7163
7164     emitCmpHandle->recordCallSite(instrOffset, callSig, methodHandle);
7165 #endif // defined(DEBUG)
7166 }
7167
7168 /*****************************************************************************/
7169 #endif // EMIT_TRACK_STACK_DEPTH
7170 /*****************************************************************************/
7171 /*****************************************************************************/
7172
7173 #ifdef DEBUG
7174
7175 /*****************************************************************************
7176  *  Given a code offset, return a string representing a label for that offset.
7177  *  If the code offset is just after the end of the code of the function, the
7178  *  label will be "END". If the code offset doesn't correspond to any known
7179  *  offset, the label will be "UNKNOWN". The strings are returned from static
7180  *  buffers. This function rotates amongst four such static buffers (there are
7181  *  cases where this function is called four times to provide data for a single
7182  *  printf()).
7183  */
7184
7185 const char* emitter::emitOffsetToLabel(unsigned offs)
7186 {
7187     const size_t    TEMP_BUFFER_LEN = 40;
7188     static unsigned curBuf          = 0;
7189     static char     buf[4][TEMP_BUFFER_LEN];
7190     char*           retbuf;
7191
7192     insGroup*      ig;
7193     UNATIVE_OFFSET nextof = 0;
7194
7195     for (ig = emitIGlist; ig != nullptr; ig = ig->igNext)
7196     {
7197         assert(nextof == ig->igOffs);
7198
7199         if (ig->igOffs == offs)
7200         {
7201             // Found it!
7202             sprintf_s(buf[curBuf], TEMP_BUFFER_LEN, "G_M%03u_IG%02u", Compiler::s_compMethodsCount, ig->igNum);
7203             retbuf = buf[curBuf];
7204             curBuf = (curBuf + 1) % 4;
7205             return retbuf;
7206         }
7207         else if (ig->igOffs > offs)
7208         {
7209             // We went past the requested offset but didn't find it.
7210             sprintf_s(buf[curBuf], TEMP_BUFFER_LEN, "UNKNOWN");
7211             retbuf = buf[curBuf];
7212             curBuf = (curBuf + 1) % 4;
7213             return retbuf;
7214         }
7215
7216         nextof = ig->igOffs + ig->igSize;
7217     }
7218
7219     if (nextof == offs)
7220     {
7221         // It's a pseudo-label to the end.
7222         sprintf_s(buf[curBuf], TEMP_BUFFER_LEN, "END");
7223         retbuf = buf[curBuf];
7224         curBuf = (curBuf + 1) % 4;
7225         return retbuf;
7226     }
7227     else
7228     {
7229         sprintf_s(buf[curBuf], TEMP_BUFFER_LEN, "UNKNOWN");
7230         retbuf = buf[curBuf];
7231         curBuf = (curBuf + 1) % 4;
7232         return retbuf;
7233     }
7234 }
7235
7236 #endif // DEBUG