1 /*
  2  * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifndef SHARE_ASM_CODEBUFFER_HPP
 26 #define SHARE_ASM_CODEBUFFER_HPP
 27 
 28 #include "code/oopRecorder.hpp"
 29 #include "code/relocInfo.hpp"
 30 #include "compiler/compiler_globals.hpp"
 31 #include "utilities/align.hpp"
 32 #include "utilities/debug.hpp"
 33 #include "utilities/growableArray.hpp"
 34 #include "utilities/linkedlist.hpp"
 35 #include "utilities/resizeableResourceHash.hpp"
 36 #include "utilities/macros.hpp"
 37 
 38 template <typename T>
 39 static inline void put_native(address p, T x) {
 40     memcpy((void*)p, &x, sizeof x);
 41 }
 42 
 43 class PhaseCFG;
 44 class Compile;
 45 class BufferBlob;
 46 class CodeBuffer;
 47 class Label;
 48 class ciMethod;
 49 class SharedStubToInterpRequest;
 50 
 51 class CodeOffsets: public StackObj {
 52 public:
 53   enum Entries { Entry,
 54                  Verified_Entry,
 55                  Frame_Complete, // Offset in the code where the frame setup is (for forte stackwalks) is complete
 56                  OSR_Entry,
 57                  Exceptions,     // Offset where exception handler lives
 58                  Deopt,          // Offset where deopt handler lives
 59                  DeoptMH,        // Offset where MethodHandle deopt handler lives
 60                  UnwindHandler,  // Offset to default unwind handler
 61                  max_Entries };
 62 
 63   // special value to note codeBlobs where profile (forte) stack walking is
 64   // always dangerous and suspect.
 65 
 66   enum { frame_never_safe = -1 };
 67 
 68 private:
 69   int _values[max_Entries];
 70 
 71 public:
 72   CodeOffsets() {
 73     _values[Entry         ] = 0;
 74     _values[Verified_Entry] = 0;
 75     _values[Frame_Complete] = frame_never_safe;
 76     _values[OSR_Entry     ] = 0;
 77     _values[Exceptions    ] = -1;
 78     _values[Deopt         ] = -1;
 79     _values[DeoptMH       ] = -1;
 80     _values[UnwindHandler ] = -1;
 81   }
 82 
 83   int value(Entries e) { return _values[e]; }
 84   void set_value(Entries e, int val) { _values[e] = val; }
 85 };
 86 
 87 // This class represents a stream of code and associated relocations.
 88 // There are a few in each CodeBuffer.
 89 // They are filled concurrently, and concatenated at the end.
 90 class CodeSection {
 91   friend class CodeBuffer;
 92   friend class SCCReader;
 93  public:
 94   typedef int csize_t;  // code size type; would be size_t except for history
 95 
 96  private:
 97   address     _start;           // first byte of contents (instructions)
 98   address     _mark;            // user mark, usually an instruction beginning
 99   address     _end;             // current end address
100   address     _limit;           // last possible (allocated) end address
101   relocInfo*  _locs_start;      // first byte of relocation information
102   relocInfo*  _locs_end;        // first byte after relocation information
103   relocInfo*  _locs_limit;      // first byte after relocation information buf
104   address     _locs_point;      // last relocated position (grows upward)
105   bool        _locs_own;        // did I allocate the locs myself?
106   bool        _scratch_emit;    // Buffer is used for scratch emit, don't relocate.
107   int         _skipped_instructions_size;
108   int8_t      _index;           // my section number (SECT_INST, etc.)
109   CodeBuffer* _outer;           // enclosing CodeBuffer
110 
111   // (Note:  _locs_point used to be called _last_reloc_offset.)
112 
113   CodeSection() {
114     _start         = nullptr;
115     _mark          = nullptr;
116     _end           = nullptr;
117     _limit         = nullptr;
118     _locs_start    = nullptr;
119     _locs_end      = nullptr;
120     _locs_limit    = nullptr;
121     _locs_point    = nullptr;
122     _locs_own      = false;
123     _scratch_emit  = false;
124     _skipped_instructions_size = 0;
125     debug_only(_index = -1);
126     debug_only(_outer = (CodeBuffer*)badAddress);
127   }
128 
129   void initialize_outer(CodeBuffer* outer, int8_t index) {
130     _outer = outer;
131     _index = index;
132   }
133 
134   void initialize(address start, csize_t size = 0) {
135     assert(_start == nullptr, "only one init step, please");
136     _start         = start;
137     _mark          = nullptr;
138     _end           = start;
139 
140     _limit         = start + size;
141     _locs_point    = start;
142   }
143 
144   void initialize_locs(int locs_capacity);
145   void expand_locs(int new_capacity);
146   void initialize_locs_from(const CodeSection* source_cs);
147 
148   // helper for CodeBuffer::expand()
149   void take_over_code_from(CodeSection* cs) {
150     _start      = cs->_start;
151     _mark       = cs->_mark;
152     _end        = cs->_end;
153     _limit      = cs->_limit;
154     _locs_point = cs->_locs_point;
155     _skipped_instructions_size = cs->_skipped_instructions_size;
156   }
157 
158  public:
159   address     start() const         { return _start; }
160   address     mark() const          { return _mark; }
161   address     end() const           { return _end; }
162   address     limit() const         { return _limit; }
163   csize_t     size() const          { return (csize_t)(_end - _start); }
164   csize_t     mark_off() const      { assert(_mark != nullptr, "not an offset");
165                                       return (csize_t)(_mark - _start); }
166   csize_t     capacity() const      { return (csize_t)(_limit - _start); }
167   csize_t     remaining() const     { return (csize_t)(_limit - _end); }
168 
169   relocInfo*  locs_start() const    { return _locs_start; }
170   relocInfo*  locs_end() const      { return _locs_end; }
171   int         locs_count() const    { return (int)(_locs_end - _locs_start); }
172   relocInfo*  locs_limit() const    { return _locs_limit; }
173   address     locs_point() const    { return _locs_point; }
174   csize_t     locs_point_off() const{ return (csize_t)(_locs_point - _start); }
175   csize_t     locs_capacity() const { return (csize_t)(_locs_limit - _locs_start); }
176 
177   int8_t      index() const         { return _index; }
178   bool        is_allocated() const  { return _start != nullptr; }
179   bool        is_empty() const      { return _start == _end; }
180   bool        has_locs() const      { return _locs_end != nullptr; }
181 
182   // Mark scratch buffer.
183   void        set_scratch_emit()    { _scratch_emit = true; }
184   void        clear_scratch_emit()  { _scratch_emit = false; }
185   bool        scratch_emit()        { return _scratch_emit; }
186 
187   CodeBuffer* outer() const         { return _outer; }
188 
189   // is a given address in this section?  (2nd version is end-inclusive)
190   bool contains(address pc) const   { return pc >= _start && pc <  _end; }
191   bool contains2(address pc) const  { return pc >= _start && pc <= _end; }
192   bool allocates(address pc) const  { return pc >= _start && pc <  _limit; }
193   bool allocates2(address pc) const { return pc >= _start && pc <= _limit; }
194 
195   // checks if two CodeSections are disjoint
196   //
197   // limit is an exclusive address and can be the start of another
198   // section.
199   bool disjoint(CodeSection* cs) const { return cs->_limit <= _start || cs->_start >= _limit; }
200 
201   void    set_end(address pc)       { assert(allocates2(pc), "not in CodeBuffer memory: " INTPTR_FORMAT " <= " INTPTR_FORMAT " <= " INTPTR_FORMAT, p2i(_start), p2i(pc), p2i(_limit)); _end = pc; }
202   void    set_mark(address pc)      { assert(contains2(pc), "not in codeBuffer");
203                                       _mark = pc; }
204   void    set_mark()                { _mark = _end; }
205   void    clear_mark()              { _mark = nullptr; }
206 
207   void    set_locs_end(relocInfo* p) {
208     assert(p <= locs_limit(), "locs data fits in allocated buffer");
209     _locs_end = p;
210   }
211   void    set_locs_point(address pc) {
212     assert(pc >= locs_point(), "relocation addr may not decrease");
213     assert(allocates2(pc),     "relocation addr " INTPTR_FORMAT " must be in this section from " INTPTR_FORMAT " to " INTPTR_FORMAT, p2i(pc), p2i(_start), p2i(_limit));
214     _locs_point = pc;
215   }
216 
217   void register_skipped(int size) {
218     _skipped_instructions_size += size;
219   }
220 
221   // Code emission
222   void emit_int8(uint8_t x1) {
223     address curr = end();
224     *((uint8_t*)  curr++) = x1;
225     set_end(curr);
226   }
227 
228   template <typename T>
229   void emit_native(T x) { put_native(end(), x); set_end(end() + sizeof x); }
230 
231   void emit_int16(uint16_t x) { emit_native(x); }
232   void emit_int16(uint8_t x1, uint8_t x2) {
233     address curr = end();
234     *((uint8_t*)  curr++) = x1;
235     *((uint8_t*)  curr++) = x2;
236     set_end(curr);
237   }
238 
239   void emit_int24(uint8_t x1, uint8_t x2, uint8_t x3)  {
240     address curr = end();
241     *((uint8_t*)  curr++) = x1;
242     *((uint8_t*)  curr++) = x2;
243     *((uint8_t*)  curr++) = x3;
244     set_end(curr);
245   }
246 
247   void emit_int32(uint32_t x) { emit_native(x); }
248   void emit_int32(uint8_t x1, uint8_t x2, uint8_t x3, uint8_t x4)  {
249     address curr = end();
250     *((uint8_t*)  curr++) = x1;
251     *((uint8_t*)  curr++) = x2;
252     *((uint8_t*)  curr++) = x3;
253     *((uint8_t*)  curr++) = x4;
254     set_end(curr);
255   }
256 
257   void emit_int64(uint64_t x)  { emit_native(x); }
258   void emit_float(jfloat  x)   { emit_native(x); }
259   void emit_double(jdouble x)  { emit_native(x); }
260   void emit_address(address x) { emit_native(x); }
261 
262   // Share a scratch buffer for relocinfo.  (Hacky; saves a resource allocation.)
263   void initialize_shared_locs(relocInfo* buf, int length);
264 
265   // Manage labels and their addresses.
266   address target(Label& L, address branch_pc);
267 
268   // Emit a relocation.
269   void relocate(address at, RelocationHolder const& rspec, int format = 0);
270   void relocate(address at,    relocInfo::relocType rtype, int format = 0, jint method_index = 0);
271 
272   int alignment() const;
273 
274   // Slop between sections, used only when allocating temporary BufferBlob buffers.
275   static csize_t end_slop()         { return MAX2((int)sizeof(jdouble), (int)CodeEntryAlignment); }
276 
277   csize_t align_at_start(csize_t off) const {
278     return (csize_t) align_up(off, alignment());
279   }
280 
281   // Ensure there's enough space left in the current section.
282   // Return true if there was an expansion.
283   bool maybe_expand_to_ensure_remaining(csize_t amount);
284 
285 #ifndef PRODUCT
286   void decode();
287   void print_on(outputStream* st, const char* name);
288 #endif //PRODUCT
289 };
290 
291 
292 #ifndef PRODUCT
293 
294 class AsmRemarkCollection;
295 class DbgStringCollection;
296 
297 // The assumption made here is that most code remarks (or comments) added to
298 // the generated assembly code are unique, i.e. there is very little gain in
299 // trying to share the strings between the different offsets tracked in a
300 // buffer (or blob).
301 
302 class AsmRemarks {
303  public:
304   AsmRemarks();
305  ~AsmRemarks();
306 
307   const char* insert(uint offset, const char* remstr);
308 
309   bool is_empty() const;
310 
311   void share(const AsmRemarks &src);
312   void clear();
313   uint print(uint offset, outputStream* strm = tty) const;
314 
315   // For testing purposes only.
316   const AsmRemarkCollection* ref() const { return _remarks; }
317 
318 private:
319   AsmRemarkCollection* _remarks;
320 };
321 
322 // The assumption made here is that the number of debug strings (with a fixed
323 // address requirement) is a rather small set per compilation unit.
324 
325 class DbgStrings {
326  public:
327   DbgStrings();
328  ~DbgStrings();
329 
330   const char* insert(const char* dbgstr);
331 
332   bool is_empty() const;
333 
334   void share(const DbgStrings &src);
335   void clear();
336 
337   // For testing purposes only.
338   const DbgStringCollection* ref() const { return _strings; }
339 
340 private:
341   DbgStringCollection* _strings;
342 };
343 #endif // not PRODUCT
344 
345 
346 #ifdef ASSERT
347 #include "utilities/copy.hpp"
348 
349 class Scrubber {
350  public:
351   Scrubber(void* addr, size_t size) : _addr(addr), _size(size) {}
352  ~Scrubber() {
353     Copy::fill_to_bytes(_addr, _size, badResourceValue);
354   }
355  private:
356   void*  _addr;
357   size_t _size;
358 };
359 #endif // ASSERT
360 
361 typedef GrowableArray<SharedStubToInterpRequest> SharedStubToInterpRequests;
362 
363 // A CodeBuffer describes a memory space into which assembly
364 // code is generated.  This memory space usually occupies the
365 // interior of a single BufferBlob, but in some cases it may be
366 // an arbitrary span of memory, even outside the code cache.
367 //
368 // A code buffer comes in two variants:
369 //
370 // (1) A CodeBuffer referring to an already allocated piece of memory:
371 //     This is used to direct 'static' code generation (e.g. for interpreter
372 //     or stubroutine generation, etc.).  This code comes with NO relocation
373 //     information.
374 //
375 // (2) A CodeBuffer referring to a piece of memory allocated when the
376 //     CodeBuffer is allocated.  This is used for nmethod generation.
377 //
378 // The memory can be divided up into several parts called sections.
379 // Each section independently accumulates code (or data) an relocations.
380 // Sections can grow (at the expense of a reallocation of the BufferBlob
381 // and recopying of all active sections).  When the buffered code is finally
382 // written to an nmethod (or other CodeBlob), the contents (code, data,
383 // and relocations) of the sections are padded to an alignment and concatenated.
384 // Instructions and data in one section can contain relocatable references to
385 // addresses in a sibling section.
386 
387 class CodeBuffer: public StackObj DEBUG_ONLY(COMMA private Scrubber) {
388   friend class CodeSection;
389   friend class StubCodeGenerator;
390   friend class SCCReader;
391 
392  private:
393   // CodeBuffers must be allocated on the stack except for a single
394   // special case during expansion which is handled internally.  This
395   // is done to guarantee proper cleanup of resources.
396   void* operator new(size_t size) throw() { return resource_allocate_bytes(size); }
397   void  operator delete(void* p)          { ShouldNotCallThis(); }
398 
399  public:
400   typedef int csize_t;  // code size type; would be size_t except for history
401   enum : int8_t {
402     // Here is the list of all possible sections.  The order reflects
403     // the final layout.
404     SECT_FIRST = 0,
405     SECT_CONSTS = SECT_FIRST, // Non-instruction data:  Floats, jump tables, etc.
406     SECT_INSTS,               // Executable instructions.
407     SECT_STUBS,               // Outbound trampolines for supporting call sites.
408     SECT_LIMIT, SECT_NONE = -1
409   };
410 
411   typedef LinkedListImpl<int> Offsets;
412   typedef ResizeableResourceHashtable<address, Offsets, AnyObj::C_HEAP, mtCompiler> SharedTrampolineRequests;
413 
414  private:
415   enum {
416     sect_bits = 2,      // assert (SECT_LIMIT <= (1<<sect_bits))
417     sect_mask = (1<<sect_bits)-1
418   };
419 
420   const char*  _name;
421 
422   CodeSection  _consts;             // constants, jump tables
423   CodeSection  _insts;              // instructions (the main section)
424   CodeSection  _stubs;              // stubs (call site support), deopt, exception handling
425 
426   CodeBuffer*  _before_expand;  // dead buffer, from before the last expansion
427 
428   BufferBlob*  _blob;           // optional buffer in CodeCache for generated code
429   address      _total_start;    // first address of combined memory buffer
430   csize_t      _total_size;     // size in bytes of combined memory buffer
431 
432   // Size of code without stubs generated at the end of instructions section
433   csize_t      _main_code_size;
434 
435   OopRecorder* _oop_recorder;
436 
437   OopRecorder  _default_oop_recorder;  // override with initialize_oop_recorder
438   Arena*       _overflow_arena;
439 
440   address      _last_insn;      // used to merge consecutive memory barriers, loads or stores.
441 
442   SharedStubToInterpRequests* _shared_stub_to_interp_requests; // used to collect requests for shared iterpreter stubs
443   SharedTrampolineRequests*   _shared_trampoline_requests;     // used to collect requests for shared trampolines
444   bool         _finalize_stubs; // Indicate if we need to finalize stubs to make CodeBuffer final.
445 
446   int          _const_section_alignment;
447 
448 #ifndef PRODUCT
449   AsmRemarks   _asm_remarks;
450   DbgStrings   _dbg_strings;
451   bool         _collect_comments; // Indicate if we need to collect block comments at all.
452   address      _decode_begin;     // start address for decode
453   address      decode_begin();
454 #endif
455 
456   void initialize_misc(const char * name) {
457     // all pointers other than code_start/end and those inside the sections
458     assert(name != nullptr, "must have a name");
459     _name            = name;
460     _before_expand   = nullptr;
461     _blob            = nullptr;
462     _oop_recorder    = nullptr;
463     _overflow_arena  = nullptr;
464     _last_insn       = nullptr;
465     _main_code_size  = 0;
466     _finalize_stubs  = false;
467     _shared_stub_to_interp_requests = nullptr;
468     _shared_trampoline_requests = nullptr;
469 
470     _consts.initialize_outer(this, SECT_CONSTS);
471     _insts.initialize_outer(this,  SECT_INSTS);
472     _stubs.initialize_outer(this,  SECT_STUBS);
473 
474     // Default is to align on 8 bytes. A compiler can change this
475     // if larger alignment (e.g., 32-byte vector masks) is required.
476     _const_section_alignment = (int) sizeof(jdouble);
477 
478 #ifndef PRODUCT
479     _decode_begin    = nullptr;
480     // Collect block comments, but restrict collection to cases where a disassembly is output.
481     _collect_comments = ( PrintAssembly
482                        || PrintStubCode
483                        || PrintMethodHandleStubs
484                        || PrintInterpreter
485                        || PrintSignatureHandlers
486                        || UnlockDiagnosticVMOptions
487                         );
488 #endif
489   }
490 
491   void initialize(address code_start, csize_t code_size) {
492     _total_start = code_start;
493     _total_size  = code_size;
494     // Initialize the main section:
495     _insts.initialize(code_start, code_size);
496     assert(!_stubs.is_allocated(),  "no garbage here");
497     assert(!_consts.is_allocated(), "no garbage here");
498     _oop_recorder = &_default_oop_recorder;
499   }
500 
501   void initialize_section_size(CodeSection* cs, csize_t size);
502 
503   // helper for CodeBuffer::expand()
504   void take_over_code_from(CodeBuffer* cs);
505 
506   // ensure sections are disjoint, ordered, and contained in the blob
507   void verify_section_allocation();
508 
509   // copies combined relocations to the blob, returns bytes copied
510   // (if target is null, it is a dry run only, just for sizing)
511   csize_t copy_relocations_to(CodeBlob* blob) const;
512 
513   // copies combined code to the blob (assumes relocs are already in there)
514   void copy_code_to(CodeBlob* blob);
515 
516   // moves code sections to new buffer (assumes relocs are already in there)
517   void relocate_code_to(CodeBuffer* cb) const;
518 
519   // set up a model of the final layout of my contents
520   void compute_final_layout(CodeBuffer* dest) const;
521 
522   // Expand the given section so at least 'amount' is remaining.
523   // Creates a new, larger BufferBlob, and rewrites the code & relocs.
524   void expand(CodeSection* which_cs, csize_t amount);
525 
526   // Helper for expand.
527   csize_t figure_expanded_capacities(CodeSection* which_cs, csize_t amount, csize_t* new_capacity);
528 
529  public:
530   // (1) code buffer referring to pre-allocated instruction memory
531   CodeBuffer(address code_start, csize_t code_size)
532     DEBUG_ONLY(: Scrubber(this, sizeof(*this)))
533   {
534     assert(code_start != nullptr, "sanity");
535     initialize_misc("static buffer");
536     initialize(code_start, code_size);
537     debug_only(verify_section_allocation();)
538   }
539 
540   // (2) CodeBuffer referring to pre-allocated CodeBlob.
541   CodeBuffer(CodeBlob* blob);
542 
543   // (3) code buffer allocating codeBlob memory for code & relocation
544   // info but with lazy initialization.  The name must be something
545   // informative.
546   CodeBuffer(const char* name)
547     DEBUG_ONLY(: Scrubber(this, sizeof(*this)))
548   {
549     initialize_misc(name);
550   }
551 
552   // (4) code buffer allocating codeBlob memory for code & relocation
553   // info.  The name must be something informative and code_size must
554   // include both code and stubs sizes.
555   CodeBuffer(const char* name, csize_t code_size, csize_t locs_size)
556     DEBUG_ONLY(: Scrubber(this, sizeof(*this)))
557   {
558     initialize_misc(name);
559     initialize(code_size, locs_size);
560   }
561 
562   ~CodeBuffer();
563 
564   // Initialize a CodeBuffer constructed using constructor 3.  Using
565   // constructor 4 is equivalent to calling constructor 3 and then
566   // calling this method.  It's been factored out for convenience of
567   // construction.
568   void initialize(csize_t code_size, csize_t locs_size);
569 
570   CodeSection* consts() { return &_consts; }
571   CodeSection* insts() { return &_insts; }
572   CodeSection* stubs() { return &_stubs; }
573 
574   const CodeSection* insts() const { return &_insts; }
575 
576   // present sections in order; return null at end; consts is #0, etc.
577   CodeSection* code_section(int n) {
578     // This makes the slightly questionable but portable assumption
579     // that the various members (_consts, _insts, _stubs, etc.) are
580     // adjacent in the layout of CodeBuffer.
581     CodeSection* cs = &_consts + n;
582     assert(cs->index() == n || !cs->is_allocated(), "sanity");
583     return cs;
584   }
585   const CodeSection* code_section(int n) const {  // yucky const stuff
586     return ((CodeBuffer*)this)->code_section(n);
587   }
588   static const char* code_section_name(int n);
589   int section_index_of(address addr) const;
590   bool contains(address addr) const {
591     // handy for debugging
592     return section_index_of(addr) > SECT_NONE;
593   }
594 
595   // A stable mapping between 'locators' (small ints) and addresses.
596   static int locator_pos(int locator)   { return locator >> sect_bits; }
597   static int locator_sect(int locator)  { return locator &  sect_mask; }
598   static int locator(int pos, int sect) { return (pos << sect_bits) | sect; }
599   int        locator(address addr) const;
600   address    locator_address(int locator) const {
601     if (locator < 0)  return nullptr;
602     address start = code_section(locator_sect(locator))->start();
603     return start + locator_pos(locator);
604   }
605 
606   // Heuristic for pre-packing the taken/not-taken bit of a predicted branch.
607   bool is_backward_branch(Label& L);
608 
609   // Properties
610   const char* name() const                  { return _name; }
611   void set_name(const char* name)           { _name = name; }
612   CodeBuffer* before_expand() const         { return _before_expand; }
613   BufferBlob* blob() const                  { return _blob; }
614   void    set_blob(BufferBlob* blob);
615   void   free_blob();                       // Free the blob, if we own one.
616 
617   // Properties relative to the insts section:
618   address       insts_begin() const      { return _insts.start();      }
619   address       insts_end() const        { return _insts.end();        }
620   void      set_insts_end(address end)   {        _insts.set_end(end); }
621   address       insts_mark() const       { return _insts.mark();       }
622   void      set_insts_mark()             {        _insts.set_mark();   }
623 
624   // is there anything in the buffer other than the current section?
625   bool    is_pure() const                { return insts_size() == total_content_size(); }
626 
627   // size in bytes of output so far in the insts sections
628   csize_t insts_size() const             { return _insts.size(); }
629 
630   // same as insts_size(), except that it asserts there is no non-code here
631   csize_t pure_insts_size() const        { assert(is_pure(), "no non-code");
632                                            return insts_size(); }
633   // capacity in bytes of the insts sections
634   csize_t insts_capacity() const         { return _insts.capacity(); }
635 
636   // number of bytes remaining in the insts section
637   csize_t insts_remaining() const        { return _insts.remaining(); }
638 
639   // size of code without stubs in instruction section
640   csize_t main_code_size() const         { return _main_code_size; }
641 
642   // is a given address in the insts section?  (2nd version is end-inclusive)
643   bool insts_contains(address pc) const  { return _insts.contains(pc); }
644   bool insts_contains2(address pc) const { return _insts.contains2(pc); }
645 
646   // Record any extra oops required to keep embedded metadata alive
647   void finalize_oop_references(const methodHandle& method);
648 
649   // Allocated size in all sections, when aligned and concatenated
650   // (this is the eventual state of the content in its final
651   // CodeBlob).
652   csize_t total_content_size() const;
653 
654   // Combined offset (relative to start of first section) of given
655   // section, as eventually found in the final CodeBlob.
656   csize_t total_offset_of(const CodeSection* cs) const;
657 
658   // allocated size of all relocation data, including index, rounded up
659   csize_t total_relocation_size() const;
660 
661   int total_skipped_instructions_size() const;
662 
663   csize_t copy_relocations_to(address buf, csize_t buf_limit, bool only_inst) const;
664 
665   // allocated size of any and all recorded oops
666   csize_t total_oop_size() const {
667     OopRecorder* recorder = oop_recorder();
668     return (recorder == nullptr)? 0: recorder->oop_size();
669   }
670 
671   // allocated size of any and all recorded metadata
672   csize_t total_metadata_size() const {
673     OopRecorder* recorder = oop_recorder();
674     return (recorder == nullptr)? 0: recorder->metadata_size();
675   }
676 
677   // Configuration functions, called immediately after the CB is constructed.
678   // The section sizes are subtracted from the original insts section.
679   // Note:  Call them in reverse section order, because each steals from insts.
680   void initialize_consts_size(csize_t size)            { initialize_section_size(&_consts,  size); }
681   void initialize_stubs_size(csize_t size)             { initialize_section_size(&_stubs,   size); }
682   // Override default oop recorder.
683   void initialize_oop_recorder(OopRecorder* r);
684 
685   OopRecorder* oop_recorder() const { return _oop_recorder; }
686 
687   address last_insn() const { return _last_insn; }
688   void set_last_insn(address a) { _last_insn = a; }
689   void clear_last_insn() { set_last_insn(nullptr); }
690 
691 #ifndef PRODUCT
692   AsmRemarks &asm_remarks() { return _asm_remarks; }
693   DbgStrings &dbg_strings() { return _dbg_strings; }
694 
695   void clear_strings() {
696     _asm_remarks.clear();
697     _dbg_strings.clear();
698   }
699 #endif
700 
701   // Code generation
702   void relocate(address at, RelocationHolder const& rspec, int format = 0) {
703     _insts.relocate(at, rspec, format);
704   }
705   void relocate(address at,    relocInfo::relocType rtype, int format = 0) {
706     _insts.relocate(at, rtype, format);
707   }
708 
709   // Management of overflow storage for binding of Labels.
710   GrowableArray<int>* create_patch_overflow();
711 
712   // NMethod generation
713   void copy_code_and_locs_to(CodeBlob* blob) {
714     assert(blob != nullptr, "sane");
715     copy_relocations_to(blob);
716     copy_code_to(blob);
717   }
718   void copy_values_to(nmethod* nm) {
719     if (!oop_recorder()->is_unused()) {
720       oop_recorder()->copy_values_to(nm);
721     }
722   }
723 
724   void block_comment(ptrdiff_t offset, const char* comment) PRODUCT_RETURN;
725   const char* code_string(const char* str) PRODUCT_RETURN_(return nullptr;);
726 
727   // Log a little info about section usage in the CodeBuffer
728   void log_section_sizes(const char* name);
729 
730   // Make a set of stubs final. It can create/optimize stubs.
731   bool finalize_stubs();
732 
733   // Request for a shared stub to the interpreter
734   void shared_stub_to_interp_for(ciMethod* callee, csize_t call_offset);
735 
736   void set_const_section_alignment(int align) {
737     _const_section_alignment = align_up(align, HeapWordSize);
738   }
739 
740 #ifndef PRODUCT
741  public:
742   // Printing / Decoding
743   // decodes from decode_begin() to code_end() and sets decode_begin to end
744   void    decode();
745   void    print_on(outputStream* st);
746 #endif
747   // Directly disassemble code buffer.
748   void    decode(address start, address end);
749 
750   // The following header contains architecture-specific implementations
751 #include CPU_HEADER(codeBuffer)
752 
753 };
754 
755 // A Java method can have calls of Java methods which can be statically bound.
756 // Calls of Java methods need stubs to the interpreter. Calls sharing the same Java method
757 // can share a stub to the interpreter.
758 // A SharedStubToInterpRequest is a request for a shared stub to the interpreter.
759 class SharedStubToInterpRequest : public ResourceObj {
760  private:
761   ciMethod* _shared_method;
762   CodeBuffer::csize_t _call_offset; // The offset of the call in CodeBuffer
763 
764  public:
765   SharedStubToInterpRequest(ciMethod* method = nullptr, CodeBuffer::csize_t call_offset = -1) : _shared_method(method),
766       _call_offset(call_offset) {}
767 
768   ciMethod* shared_method() const { return _shared_method; }
769   CodeBuffer::csize_t call_offset() const { return _call_offset; }
770 };
771 
772 inline bool CodeSection::maybe_expand_to_ensure_remaining(csize_t amount) {
773   if (remaining() < amount) { _outer->expand(this, amount); return true; }
774   return false;
775 }
776 
777 #endif // SHARE_ASM_CODEBUFFER_HPP