codeBuffer.cpp revision 1879:f95d63e2154a
1262266Sbapt/*
2289123Sbapt * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
3262266Sbapt * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4262266Sbapt *
5262266Sbapt * This code is free software; you can redistribute it and/or modify it
6289123Sbapt * under the terms of the GNU General Public License version 2 only, as
7262266Sbapt * published by the Free Software Foundation.
8262266Sbapt *
9262266Sbapt * This code is distributed in the hope that it will be useful, but WITHOUT
10262266Sbapt * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11262266Sbapt * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12262266Sbapt * version 2 for more details (a copy is included in the LICENSE file that
13262266Sbapt * accompanied this code).
14262266Sbapt *
15262266Sbapt * You should have received a copy of the GNU General Public License version
16262266Sbapt * 2 along with this work; if not, write to the Free Software Foundation,
17262266Sbapt * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18262266Sbapt *
19262266Sbapt * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20262266Sbapt * or visit www.oracle.com if you need additional information or have any
21262266Sbapt * questions.
22262266Sbapt *
23262266Sbapt */
24262266Sbapt
25262266Sbapt#include "precompiled.hpp"
26262266Sbapt#include "asm/codeBuffer.hpp"
27262266Sbapt#include "compiler/disassembler.hpp"
28262266Sbapt#include "utilities/copy.hpp"
29262266Sbapt
30262266Sbapt// The structure of a CodeSection:
31262266Sbapt//
32262266Sbapt//    _start ->           +----------------+
33262266Sbapt//                        | machine code...|
34262266Sbapt//    _end ->             |----------------|
35262266Sbapt//                        |                |
36262266Sbapt//                        |    (empty)     |
37262266Sbapt//                        |                |
38262266Sbapt//                        |                |
39262266Sbapt//                        +----------------+
40262266Sbapt//    _limit ->           |                |
41262266Sbapt//
42262266Sbapt//    _locs_start ->      +----------------+
43262266Sbapt//                        |reloc records...|
44262266Sbapt//                        |----------------|
45262266Sbapt//    _locs_end ->        |                |
46262266Sbapt//                        |                |
47262266Sbapt//                        |    (empty)     |
48262266Sbapt//                        |                |
49262266Sbapt//                        |                |
50262266Sbapt//                        +----------------+
51262266Sbapt//    _locs_limit ->      |                |
52262266Sbapt// The _end (resp. _limit) pointer refers to the first
53262266Sbapt// unused (resp. unallocated) byte.
54262266Sbapt
55262266Sbapt// The structure of the CodeBuffer while code is being accumulated:
56262266Sbapt//
57262266Sbapt//    _total_start ->    \
58262266Sbapt//    _insts._start ->              +----------------+
59262266Sbapt//                                  |                |
60262266Sbapt//                                  |     Code       |
61262266Sbapt//                                  |                |
62262266Sbapt//    _stubs._start ->              |----------------|
63262266Sbapt//                                  |                |
64262266Sbapt//                                  |    Stubs       | (also handlers for deopt/exception)
65262266Sbapt//                                  |                |
66262266Sbapt//    _consts._start ->             |----------------|
67262266Sbapt//                                  |                |
68262266Sbapt//                                  |   Constants    |
69262266Sbapt//                                  |                |
70262266Sbapt//                                  +----------------+
71262266Sbapt//    + _total_size ->              |                |
72262266Sbapt//
73262266Sbapt// When the code and relocations are copied to the code cache,
74262266Sbapt// the empty parts of each section are removed, and everything
75262266Sbapt// is copied into contiguous locations.
76262266Sbapt
77262266Sbapttypedef CodeBuffer::csize_t csize_t;  // file-local definition
78262266Sbapt
79262266Sbapt// External buffer, in a predefined CodeBlob.
80262266Sbapt// Important: The code_start must be taken exactly, and not realigned.
81262266SbaptCodeBuffer::CodeBuffer(CodeBlob* blob) {
82262266Sbapt  initialize_misc("static buffer");
83262266Sbapt  initialize(blob->content_begin(), blob->content_size());
84262266Sbapt  assert(verify_section_allocation(), "initial use of buffer OK");
85262266Sbapt}
86262266Sbapt
87262266Sbaptvoid CodeBuffer::initialize(csize_t code_size, csize_t locs_size) {
88262266Sbapt  // Compute maximal alignment.
89262266Sbapt  int align = _insts.alignment();
90262266Sbapt  // Always allow for empty slop around each section.
91262266Sbapt  int slop = (int) CodeSection::end_slop();
92262266Sbapt
93262266Sbapt  assert(blob() == NULL, "only once");
94262266Sbapt  set_blob(BufferBlob::create(_name, code_size + (align+slop) * (SECT_LIMIT+1)));
95262266Sbapt  if (blob() == NULL) {
96262266Sbapt    // The assembler constructor will throw a fatal on an empty CodeBuffer.
97262266Sbapt    return;  // caller must test this
98262266Sbapt  }
99262266Sbapt
100262266Sbapt  // Set up various pointers into the blob.
101262266Sbapt  initialize(_total_start, _total_size);
102262266Sbapt
103262266Sbapt  assert((uintptr_t)insts_begin() % CodeEntryAlignment == 0, "instruction start not code entry aligned");
104262266Sbapt
105262266Sbapt  pd_initialize();
106262266Sbapt
107262266Sbapt  if (locs_size != 0) {
108262266Sbapt    _insts.initialize_locs(locs_size / sizeof(relocInfo));
109262266Sbapt  }
110262266Sbapt
111262266Sbapt  assert(verify_section_allocation(), "initial use of blob is OK");
112262266Sbapt}
113262266Sbapt
114262266Sbapt
115262266SbaptCodeBuffer::~CodeBuffer() {
116262266Sbapt  // If we allocate our code buffer from the CodeCache
117262266Sbapt  // via a BufferBlob, and it's not permanent, then
118262266Sbapt  // free the BufferBlob.
119262266Sbapt  // The rest of the memory will be freed when the ResourceObj
120262266Sbapt  // is released.
121262266Sbapt  assert(verify_section_allocation(), "final storage configuration still OK");
122262266Sbapt  for (CodeBuffer* cb = this; cb != NULL; cb = cb->before_expand()) {
123262266Sbapt    // Previous incarnations of this buffer are held live, so that internal
124262266Sbapt    // addresses constructed before expansions will not be confused.
125262266Sbapt    cb->free_blob();
126262266Sbapt  }
127262266Sbapt
128262266Sbapt  // free any overflow storage
129262266Sbapt  delete _overflow_arena;
130262266Sbapt
131262266Sbapt#ifdef ASSERT
132262266Sbapt  // Save allocation type to execute assert in ~ResourceObj()
133262266Sbapt  // which is called after this destructor.
134262266Sbapt  ResourceObj::allocation_type at = _default_oop_recorder.get_allocation_type();
135262266Sbapt  Copy::fill_to_bytes(this, sizeof(*this), badResourceValue);
136262266Sbapt  ResourceObj::set_allocation_type((address)(&_default_oop_recorder), at);
137262266Sbapt#endif
138262266Sbapt}
139262266Sbapt
140262266Sbaptvoid CodeBuffer::initialize_oop_recorder(OopRecorder* r) {
141262266Sbapt  assert(_oop_recorder == &_default_oop_recorder && _default_oop_recorder.is_unused(), "do this once");
142262266Sbapt  DEBUG_ONLY(_default_oop_recorder.oop_size());  // force unused OR to be frozen
143262266Sbapt  _oop_recorder = r;
144262266Sbapt}
145262266Sbapt
146262266Sbaptvoid CodeBuffer::initialize_section_size(CodeSection* cs, csize_t size) {
147262266Sbapt  assert(cs != &_insts, "insts is the memory provider, not the consumer");
148262266Sbapt  csize_t slop = CodeSection::end_slop();  // margin between sections
149262266Sbapt  int align = cs->alignment();
150262266Sbapt  assert(is_power_of_2(align), "sanity");
151262266Sbapt  address start  = _insts._start;
152262266Sbapt  address limit  = _insts._limit;
153262266Sbapt  address middle = limit - size;
154262266Sbapt  middle -= (intptr_t)middle & (align-1);  // align the division point downward
155262266Sbapt  guarantee(middle - slop > start, "need enough space to divide up");
156262266Sbapt  _insts._limit = middle - slop;  // subtract desired space, plus slop
157262266Sbapt  cs->initialize(middle, limit - middle);
158262266Sbapt  assert(cs->start() == middle, "sanity");
159262266Sbapt  assert(cs->limit() == limit,  "sanity");
160262266Sbapt  // give it some relocations to start with, if the main section has them
161262266Sbapt  if (_insts.has_locs())  cs->initialize_locs(1);
162262266Sbapt}
163262266Sbapt
164262266Sbaptvoid CodeBuffer::freeze_section(CodeSection* cs) {
165262266Sbapt  CodeSection* next_cs = (cs == consts())? NULL: code_section(cs->index()+1);
166262266Sbapt  csize_t frozen_size = cs->size();
167262266Sbapt  if (next_cs != NULL) {
168262266Sbapt    frozen_size = next_cs->align_at_start(frozen_size);
169262266Sbapt  }
170262266Sbapt  address old_limit = cs->limit();
171262266Sbapt  address new_limit = cs->start() + frozen_size;
172262266Sbapt  relocInfo* old_locs_limit = cs->locs_limit();
173262266Sbapt  relocInfo* new_locs_limit = cs->locs_end();
174262266Sbapt  // Patch the limits.
175262266Sbapt  cs->_limit = new_limit;
176262266Sbapt  cs->_locs_limit = new_locs_limit;
177262266Sbapt  cs->_frozen = true;
178262266Sbapt  if (!next_cs->is_allocated() && !next_cs->is_frozen()) {
179262266Sbapt    // Give remaining buffer space to the following section.
180262266Sbapt    next_cs->initialize(new_limit, old_limit - new_limit);
181262266Sbapt    next_cs->initialize_shared_locs(new_locs_limit,
182262266Sbapt                                    old_locs_limit - new_locs_limit);
183262266Sbapt  }
184262266Sbapt}
185262266Sbapt
186262266Sbaptvoid CodeBuffer::set_blob(BufferBlob* blob) {
187262266Sbapt  _blob = blob;
188262266Sbapt  if (blob != NULL) {
189262266Sbapt    address start = blob->content_begin();
190262266Sbapt    address end   = blob->content_end();
191262266Sbapt    // Round up the starting address.
192262266Sbapt    int align = _insts.alignment();
193262266Sbapt    start += (-(intptr_t)start) & (align-1);
194262266Sbapt    _total_start = start;
195262266Sbapt    _total_size  = end - start;
196262266Sbapt  } else {
197262266Sbapt#ifdef ASSERT
198262266Sbapt    // Clean out dangling pointers.
199262266Sbapt    _total_start    = badAddress;
200262266Sbapt    _consts._start  = _consts._end  = badAddress;
201262266Sbapt    _insts._start   = _insts._end   = badAddress;
202262266Sbapt    _stubs._start   = _stubs._end   = badAddress;
203262266Sbapt#endif //ASSERT
204262266Sbapt  }
205262266Sbapt}
206262266Sbapt
207262266Sbaptvoid CodeBuffer::free_blob() {
208262266Sbapt  if (_blob != NULL) {
209262266Sbapt    BufferBlob::free(_blob);
210262266Sbapt    set_blob(NULL);
211262266Sbapt  }
212262266Sbapt}
213262266Sbapt
214262266Sbaptconst char* CodeBuffer::code_section_name(int n) {
215262266Sbapt#ifdef PRODUCT
216262266Sbapt  return NULL;
217262266Sbapt#else //PRODUCT
218262266Sbapt  switch (n) {
219262266Sbapt  case SECT_CONSTS:            return "consts";
220262266Sbapt  case SECT_INSTS:             return "insts";
221262266Sbapt  case SECT_STUBS:             return "stubs";
222262266Sbapt  default:                     return NULL;
223262266Sbapt  }
224262266Sbapt#endif //PRODUCT
225262266Sbapt}
226262266Sbapt
227262266Sbaptint CodeBuffer::section_index_of(address addr) const {
228262266Sbapt  for (int n = 0; n < (int)SECT_LIMIT; n++) {
229262266Sbapt    const CodeSection* cs = code_section(n);
230262266Sbapt    if (cs->allocates(addr))  return n;
231262266Sbapt  }
232262266Sbapt  return SECT_NONE;
233262266Sbapt}
234262266Sbapt
235262266Sbaptint CodeBuffer::locator(address addr) const {
236262266Sbapt  for (int n = 0; n < (int)SECT_LIMIT; n++) {
237262266Sbapt    const CodeSection* cs = code_section(n);
238262266Sbapt    if (cs->allocates(addr)) {
239262266Sbapt      return locator(addr - cs->start(), n);
240262266Sbapt    }
241262266Sbapt  }
242262266Sbapt  return -1;
243262266Sbapt}
244262266Sbapt
245262266Sbaptaddress CodeBuffer::locator_address(int locator) const {
246262266Sbapt  if (locator < 0)  return NULL;
247262266Sbapt  address start = code_section(locator_sect(locator))->start();
248262266Sbapt  return start + locator_pos(locator);
249262266Sbapt}
250262266Sbapt
251262266Sbaptaddress CodeBuffer::decode_begin() {
252262266Sbapt  address begin = _insts.start();
253262266Sbapt  if (_decode_begin != NULL && _decode_begin > begin)
254262266Sbapt    begin = _decode_begin;
255262266Sbapt  return begin;
256262266Sbapt}
257262266Sbapt
258262266Sbapt
259262266SbaptGrowableArray<int>* CodeBuffer::create_patch_overflow() {
260262266Sbapt  if (_overflow_arena == NULL) {
261262266Sbapt    _overflow_arena = new Arena();
262262266Sbapt  }
263262266Sbapt  return new (_overflow_arena) GrowableArray<int>(_overflow_arena, 8, 0, 0);
264262266Sbapt}
265262266Sbapt
266262266Sbapt
267262266Sbapt// Helper function for managing labels and their target addresses.
268262266Sbapt// Returns a sensible address, and if it is not the label's final
269262266Sbapt// address, notes the dependency (at 'branch_pc') on the label.
270262266Sbaptaddress CodeSection::target(Label& L, address branch_pc) {
271262266Sbapt  if (L.is_bound()) {
272262266Sbapt    int loc = L.loc();
273262266Sbapt    if (index() == CodeBuffer::locator_sect(loc)) {
274262266Sbapt      return start() + CodeBuffer::locator_pos(loc);
275262266Sbapt    } else {
276262266Sbapt      return outer()->locator_address(loc);
277262266Sbapt    }
278262266Sbapt  } else {
279262266Sbapt    assert(allocates2(branch_pc), "sanity");
280262266Sbapt    address base = start();
281262266Sbapt    int patch_loc = CodeBuffer::locator(branch_pc - base, index());
282262266Sbapt    L.add_patch_at(outer(), patch_loc);
283262266Sbapt
284262266Sbapt    // Need to return a pc, doesn't matter what it is since it will be
285262266Sbapt    // replaced during resolution later.
286262266Sbapt    // Don't return NULL or badAddress, since branches shouldn't overflow.
287262266Sbapt    // Don't return base either because that could overflow displacements
288262266Sbapt    // for shorter branches.  It will get checked when bound.
289262266Sbapt    return branch_pc;
290262266Sbapt  }
291262266Sbapt}
292262266Sbapt
293262266Sbaptvoid CodeSection::relocate(address at, RelocationHolder const& spec, int format) {
294262266Sbapt  Relocation* reloc = spec.reloc();
295262266Sbapt  relocInfo::relocType rtype = (relocInfo::relocType) reloc->type();
296262266Sbapt  if (rtype == relocInfo::none)  return;
297262266Sbapt
298262266Sbapt  // The assertion below has been adjusted, to also work for
299262266Sbapt  // relocation for fixup.  Sometimes we want to put relocation
300262266Sbapt  // information for the next instruction, since it will be patched
301262266Sbapt  // with a call.
302262266Sbapt  assert(start() <= at && at <= end()+1,
303262266Sbapt         "cannot relocate data outside code boundaries");
304262266Sbapt
305262266Sbapt  if (!has_locs()) {
306262266Sbapt    // no space for relocation information provided => code cannot be
307262266Sbapt    // relocated.  Make sure that relocate is only called with rtypes
308262266Sbapt    // that can be ignored for this kind of code.
309262266Sbapt    assert(rtype == relocInfo::none              ||
310262266Sbapt           rtype == relocInfo::runtime_call_type ||
311262266Sbapt           rtype == relocInfo::internal_word_type||
312262266Sbapt           rtype == relocInfo::section_word_type ||
313262266Sbapt           rtype == relocInfo::external_word_type,
314262266Sbapt           "code needs relocation information");
315262266Sbapt    // leave behind an indication that we attempted a relocation
316262266Sbapt    DEBUG_ONLY(_locs_start = _locs_limit = (relocInfo*)badAddress);
317262266Sbapt    return;
318262266Sbapt  }
319262266Sbapt
320262266Sbapt  // Advance the point, noting the offset we'll have to record.
321262266Sbapt  csize_t offset = at - locs_point();
322262266Sbapt  set_locs_point(at);
323262266Sbapt
324262266Sbapt  // Test for a couple of overflow conditions; maybe expand the buffer.
325262266Sbapt  relocInfo* end = locs_end();
326262266Sbapt  relocInfo* req = end + relocInfo::length_limit;
327262266Sbapt  // Check for (potential) overflow
328262266Sbapt  if (req >= locs_limit() || offset >= relocInfo::offset_limit()) {
329262266Sbapt    req += (uint)offset / (uint)relocInfo::offset_limit();
330262266Sbapt    if (req >= locs_limit()) {
331262266Sbapt      // Allocate or reallocate.
332262266Sbapt      expand_locs(locs_count() + (req - end));
333262266Sbapt      // reload pointer
334262266Sbapt      end = locs_end();
335262266Sbapt    }
336262266Sbapt  }
337262266Sbapt
338262266Sbapt  // If the offset is giant, emit filler relocs, of type 'none', but
339262266Sbapt  // each carrying the largest possible offset, to advance the locs_point.
340262266Sbapt  while (offset >= relocInfo::offset_limit()) {
341262266Sbapt    assert(end < locs_limit(), "adjust previous paragraph of code");
342262266Sbapt    *end++ = filler_relocInfo();
343262266Sbapt    offset -= filler_relocInfo().addr_offset();
344262266Sbapt  }
345262266Sbapt
346262266Sbapt  // If it's a simple reloc with no data, we'll just write (rtype | offset).
347  (*end) = relocInfo(rtype, offset, format);
348
349  // If it has data, insert the prefix, as (data_prefix_tag | data1), data2.
350  end->initialize(this, reloc);
351}
352
353void CodeSection::initialize_locs(int locs_capacity) {
354  assert(_locs_start == NULL, "only one locs init step, please");
355  // Apply a priori lower limits to relocation size:
356  csize_t min_locs = MAX2(size() / 16, (csize_t)4);
357  if (locs_capacity < min_locs)  locs_capacity = min_locs;
358  relocInfo* locs_start = NEW_RESOURCE_ARRAY(relocInfo, locs_capacity);
359  _locs_start    = locs_start;
360  _locs_end      = locs_start;
361  _locs_limit    = locs_start + locs_capacity;
362  _locs_own      = true;
363}
364
365void CodeSection::initialize_shared_locs(relocInfo* buf, int length) {
366  assert(_locs_start == NULL, "do this before locs are allocated");
367  // Internal invariant:  locs buf must be fully aligned.
368  // See copy_relocations_to() below.
369  while ((uintptr_t)buf % HeapWordSize != 0 && length > 0) {
370    ++buf; --length;
371  }
372  if (length > 0) {
373    _locs_start = buf;
374    _locs_end   = buf;
375    _locs_limit = buf + length;
376    _locs_own   = false;
377  }
378}
379
380void CodeSection::initialize_locs_from(const CodeSection* source_cs) {
381  int lcount = source_cs->locs_count();
382  if (lcount != 0) {
383    initialize_shared_locs(source_cs->locs_start(), lcount);
384    _locs_end = _locs_limit = _locs_start + lcount;
385    assert(is_allocated(), "must have copied code already");
386    set_locs_point(start() + source_cs->locs_point_off());
387  }
388  assert(this->locs_count() == source_cs->locs_count(), "sanity");
389}
390
391void CodeSection::expand_locs(int new_capacity) {
392  if (_locs_start == NULL) {
393    initialize_locs(new_capacity);
394    return;
395  } else {
396    int old_count    = locs_count();
397    int old_capacity = locs_capacity();
398    if (new_capacity < old_capacity * 2)
399      new_capacity = old_capacity * 2;
400    relocInfo* locs_start;
401    if (_locs_own) {
402      locs_start = REALLOC_RESOURCE_ARRAY(relocInfo, _locs_start, old_capacity, new_capacity);
403    } else {
404      locs_start = NEW_RESOURCE_ARRAY(relocInfo, new_capacity);
405      Copy::conjoint_jbytes(_locs_start, locs_start, old_capacity * sizeof(relocInfo));
406      _locs_own = true;
407    }
408    _locs_start    = locs_start;
409    _locs_end      = locs_start + old_count;
410    _locs_limit    = locs_start + new_capacity;
411  }
412}
413
414
415/// Support for emitting the code to its final location.
416/// The pattern is the same for all functions.
417/// We iterate over all the sections, padding each to alignment.
418
419csize_t CodeBuffer::total_content_size() const {
420  csize_t size_so_far = 0;
421  for (int n = 0; n < (int)SECT_LIMIT; n++) {
422    const CodeSection* cs = code_section(n);
423    if (cs->is_empty())  continue;  // skip trivial section
424    size_so_far = cs->align_at_start(size_so_far);
425    size_so_far += cs->size();
426  }
427  return size_so_far;
428}
429
430void CodeBuffer::compute_final_layout(CodeBuffer* dest) const {
431  address buf = dest->_total_start;
432  csize_t buf_offset = 0;
433  assert(dest->_total_size >= total_content_size(), "must be big enough");
434
435  {
436    // not sure why this is here, but why not...
437    int alignSize = MAX2((intx) sizeof(jdouble), CodeEntryAlignment);
438    assert( (dest->_total_start - _insts.start()) % alignSize == 0, "copy must preserve alignment");
439  }
440
441  const CodeSection* prev_cs      = NULL;
442  CodeSection*       prev_dest_cs = NULL;
443
444  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
445    // figure compact layout of each section
446    const CodeSection* cs = code_section(n);
447    csize_t csize = cs->size();
448
449    CodeSection* dest_cs = dest->code_section(n);
450    if (!cs->is_empty()) {
451      // Compute initial padding; assign it to the previous non-empty guy.
452      // Cf. figure_expanded_capacities.
453      csize_t padding = cs->align_at_start(buf_offset) - buf_offset;
454      if (padding != 0) {
455        buf_offset += padding;
456        assert(prev_dest_cs != NULL, "sanity");
457        prev_dest_cs->_limit += padding;
458      }
459      #ifdef ASSERT
460      if (prev_cs != NULL && prev_cs->is_frozen() && n < (SECT_LIMIT - 1)) {
461        // Make sure the ends still match up.
462        // This is important because a branch in a frozen section
463        // might target code in a following section, via a Label,
464        // and without a relocation record.  See Label::patch_instructions.
465        address dest_start = buf+buf_offset;
466        csize_t start2start = cs->start() - prev_cs->start();
467        csize_t dest_start2start = dest_start - prev_dest_cs->start();
468        assert(start2start == dest_start2start, "cannot stretch frozen sect");
469      }
470      #endif //ASSERT
471      prev_dest_cs = dest_cs;
472      prev_cs      = cs;
473    }
474
475    debug_only(dest_cs->_start = NULL);  // defeat double-initialization assert
476    dest_cs->initialize(buf+buf_offset, csize);
477    dest_cs->set_end(buf+buf_offset+csize);
478    assert(dest_cs->is_allocated(), "must always be allocated");
479    assert(cs->is_empty() == dest_cs->is_empty(), "sanity");
480
481    buf_offset += csize;
482  }
483
484  // Done calculating sections; did it come out to the right end?
485  assert(buf_offset == total_content_size(), "sanity");
486  assert(dest->verify_section_allocation(), "final configuration works");
487}
488
489csize_t CodeBuffer::total_offset_of(CodeSection* cs) const {
490  csize_t size_so_far = 0;
491  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
492    const CodeSection* cur_cs = code_section(n);
493    if (!cur_cs->is_empty()) {
494      size_so_far = cur_cs->align_at_start(size_so_far);
495    }
496    if (cur_cs->index() == cs->index()) {
497      return size_so_far;
498    }
499    size_so_far += cur_cs->size();
500  }
501  ShouldNotReachHere();
502  return -1;
503}
504
505csize_t CodeBuffer::total_relocation_size() const {
506  csize_t lsize = copy_relocations_to(NULL);  // dry run only
507  csize_t csize = total_content_size();
508  csize_t total = RelocIterator::locs_and_index_size(csize, lsize);
509  return (csize_t) align_size_up(total, HeapWordSize);
510}
511
512csize_t CodeBuffer::copy_relocations_to(CodeBlob* dest) const {
513  address buf = NULL;
514  csize_t buf_offset = 0;
515  csize_t buf_limit = 0;
516  if (dest != NULL) {
517    buf = (address)dest->relocation_begin();
518    buf_limit = (address)dest->relocation_end() - buf;
519    assert((uintptr_t)buf % HeapWordSize == 0, "buf must be fully aligned");
520    assert(buf_limit % HeapWordSize == 0, "buf must be evenly sized");
521  }
522  // if dest == NULL, this is just the sizing pass
523
524  csize_t code_end_so_far = 0;
525  csize_t code_point_so_far = 0;
526  for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {
527    // pull relocs out of each section
528    const CodeSection* cs = code_section(n);
529    assert(!(cs->is_empty() && cs->locs_count() > 0), "sanity");
530    if (cs->is_empty())  continue;  // skip trivial section
531    relocInfo* lstart = cs->locs_start();
532    relocInfo* lend   = cs->locs_end();
533    csize_t    lsize  = (csize_t)( (address)lend - (address)lstart );
534    csize_t    csize  = cs->size();
535    code_end_so_far = cs->align_at_start(code_end_so_far);
536
537    if (lsize > 0) {
538      // Figure out how to advance the combined relocation point
539      // first to the beginning of this section.
540      // We'll insert one or more filler relocs to span that gap.
541      // (Don't bother to improve this by editing the first reloc's offset.)
542      csize_t new_code_point = code_end_so_far;
543      for (csize_t jump;
544           code_point_so_far < new_code_point;
545           code_point_so_far += jump) {
546        jump = new_code_point - code_point_so_far;
547        relocInfo filler = filler_relocInfo();
548        if (jump >= filler.addr_offset()) {
549          jump = filler.addr_offset();
550        } else {  // else shrink the filler to fit
551          filler = relocInfo(relocInfo::none, jump);
552        }
553        if (buf != NULL) {
554          assert(buf_offset + (csize_t)sizeof(filler) <= buf_limit, "filler in bounds");
555          *(relocInfo*)(buf+buf_offset) = filler;
556        }
557        buf_offset += sizeof(filler);
558      }
559
560      // Update code point and end to skip past this section:
561      csize_t last_code_point = code_end_so_far + cs->locs_point_off();
562      assert(code_point_so_far <= last_code_point, "sanity");
563      code_point_so_far = last_code_point; // advance past this guy's relocs
564    }
565    code_end_so_far += csize;  // advance past this guy's instructions too
566
567    // Done with filler; emit the real relocations:
568    if (buf != NULL && lsize != 0) {
569      assert(buf_offset + lsize <= buf_limit, "target in bounds");
570      assert((uintptr_t)lstart % HeapWordSize == 0, "sane start");
571      if (buf_offset % HeapWordSize == 0) {
572        // Use wordwise copies if possible:
573        Copy::disjoint_words((HeapWord*)lstart,
574                             (HeapWord*)(buf+buf_offset),
575                             (lsize + HeapWordSize-1) / HeapWordSize);
576      } else {
577        Copy::conjoint_jbytes(lstart, buf+buf_offset, lsize);
578      }
579    }
580    buf_offset += lsize;
581  }
582
583  // Align end of relocation info in target.
584  while (buf_offset % HeapWordSize != 0) {
585    if (buf != NULL) {
586      relocInfo padding = relocInfo(relocInfo::none, 0);
587      assert(buf_offset + (csize_t)sizeof(padding) <= buf_limit, "padding in bounds");
588      *(relocInfo*)(buf+buf_offset) = padding;
589    }
590    buf_offset += sizeof(relocInfo);
591  }
592
593  assert(code_end_so_far == total_content_size(), "sanity");
594
595  // Account for index:
596  if (buf != NULL) {
597    RelocIterator::create_index(dest->relocation_begin(),
598                                buf_offset / sizeof(relocInfo),
599                                dest->relocation_end());
600  }
601
602  return buf_offset;
603}
604
605void CodeBuffer::copy_code_to(CodeBlob* dest_blob) {
606#ifndef PRODUCT
607  if (PrintNMethods && (WizardMode || Verbose)) {
608    tty->print("done with CodeBuffer:");
609    ((CodeBuffer*)this)->print();
610  }
611#endif //PRODUCT
612
613  CodeBuffer dest(dest_blob);
614  assert(dest_blob->content_size() >= total_content_size(), "good sizing");
615  this->compute_final_layout(&dest);
616  relocate_code_to(&dest);
617
618  // transfer comments from buffer to blob
619  dest_blob->set_comments(_comments);
620
621  // Done moving code bytes; were they the right size?
622  assert(round_to(dest.total_content_size(), oopSize) == dest_blob->content_size(), "sanity");
623
624  // Flush generated code
625  ICache::invalidate_range(dest_blob->code_begin(), dest_blob->code_size());
626}
627
628// Move all my code into another code buffer.  Consult applicable
629// relocs to repair embedded addresses.  The layout in the destination
630// CodeBuffer is different to the source CodeBuffer: the destination
631// CodeBuffer gets the final layout (consts, insts, stubs in order of
632// ascending address).
633void CodeBuffer::relocate_code_to(CodeBuffer* dest) const {
634  DEBUG_ONLY(address dest_end = dest->_total_start + dest->_total_size);
635  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
636    // pull code out of each section
637    const CodeSection* cs = code_section(n);
638    if (cs->is_empty())  continue;  // skip trivial section
639    CodeSection* dest_cs = dest->code_section(n);
640    assert(cs->size() == dest_cs->size(), "sanity");
641    csize_t usize = dest_cs->size();
642    csize_t wsize = align_size_up(usize, HeapWordSize);
643    assert(dest_cs->start() + wsize <= dest_end, "no overflow");
644    // Copy the code as aligned machine words.
645    // This may also include an uninitialized partial word at the end.
646    Copy::disjoint_words((HeapWord*)cs->start(),
647                         (HeapWord*)dest_cs->start(),
648                         wsize / HeapWordSize);
649
650    if (dest->blob() == NULL) {
651      // Destination is a final resting place, not just another buffer.
652      // Normalize uninitialized bytes in the final padding.
653      Copy::fill_to_bytes(dest_cs->end(), dest_cs->remaining(),
654                          Assembler::code_fill_byte());
655    }
656
657    assert(cs->locs_start() != (relocInfo*)badAddress,
658           "this section carries no reloc storage, but reloc was attempted");
659
660    // Make the new code copy use the old copy's relocations:
661    dest_cs->initialize_locs_from(cs);
662
663    { // Repair the pc relative information in the code after the move
664      RelocIterator iter(dest_cs);
665      while (iter.next()) {
666        iter.reloc()->fix_relocation_after_move(this, dest);
667      }
668    }
669  }
670}
671
672csize_t CodeBuffer::figure_expanded_capacities(CodeSection* which_cs,
673                                               csize_t amount,
674                                               csize_t* new_capacity) {
675  csize_t new_total_cap = 0;
676
677  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
678    const CodeSection* sect = code_section(n);
679
680    if (!sect->is_empty()) {
681      // Compute initial padding; assign it to the previous section,
682      // even if it's empty (e.g. consts section can be empty).
683      // Cf. compute_final_layout
684      csize_t padding = sect->align_at_start(new_total_cap) - new_total_cap;
685      if (padding != 0) {
686        new_total_cap += padding;
687        assert(n - 1 >= SECT_FIRST, "sanity");
688        new_capacity[n - 1] += padding;
689      }
690    }
691
692    csize_t exp = sect->size();  // 100% increase
693    if ((uint)exp < 4*K)  exp = 4*K;       // minimum initial increase
694    if (sect == which_cs) {
695      if (exp < amount)  exp = amount;
696      if (StressCodeBuffers)  exp = amount;  // expand only slightly
697    } else if (n == SECT_INSTS) {
698      // scale down inst increases to a more modest 25%
699      exp = 4*K + ((exp - 4*K) >> 2);
700      if (StressCodeBuffers)  exp = amount / 2;  // expand only slightly
701    } else if (sect->is_empty()) {
702      // do not grow an empty secondary section
703      exp = 0;
704    }
705    // Allow for inter-section slop:
706    exp += CodeSection::end_slop();
707    csize_t new_cap = sect->size() + exp;
708    if (new_cap < sect->capacity()) {
709      // No need to expand after all.
710      new_cap = sect->capacity();
711    }
712    new_capacity[n] = new_cap;
713    new_total_cap += new_cap;
714  }
715
716  return new_total_cap;
717}
718
719void CodeBuffer::expand(CodeSection* which_cs, csize_t amount) {
720#ifndef PRODUCT
721  if (PrintNMethods && (WizardMode || Verbose)) {
722    tty->print("expanding CodeBuffer:");
723    this->print();
724  }
725
726  if (StressCodeBuffers && blob() != NULL) {
727    static int expand_count = 0;
728    if (expand_count >= 0)  expand_count += 1;
729    if (expand_count > 100 && is_power_of_2(expand_count)) {
730      tty->print_cr("StressCodeBuffers: have expanded %d times", expand_count);
731      // simulate an occasional allocation failure:
732      free_blob();
733    }
734  }
735#endif //PRODUCT
736
737  // Resizing must be allowed
738  {
739    if (blob() == NULL)  return;  // caller must check for blob == NULL
740    for (int n = 0; n < (int)SECT_LIMIT; n++) {
741      guarantee(!code_section(n)->is_frozen(), "resizing not allowed when frozen");
742    }
743  }
744
745  // Figure new capacity for each section.
746  csize_t new_capacity[SECT_LIMIT];
747  csize_t new_total_cap
748    = figure_expanded_capacities(which_cs, amount, new_capacity);
749
750  // Create a new (temporary) code buffer to hold all the new data
751  CodeBuffer cb(name(), new_total_cap, 0);
752  if (cb.blob() == NULL) {
753    // Failed to allocate in code cache.
754    free_blob();
755    return;
756  }
757
758  // Create an old code buffer to remember which addresses used to go where.
759  // This will be useful when we do final assembly into the code cache,
760  // because we will need to know how to warp any internal address that
761  // has been created at any time in this CodeBuffer's past.
762  CodeBuffer* bxp = new CodeBuffer(_total_start, _total_size);
763  bxp->take_over_code_from(this);  // remember the old undersized blob
764  DEBUG_ONLY(this->_blob = NULL);  // silence a later assert
765  bxp->_before_expand = this->_before_expand;
766  this->_before_expand = bxp;
767
768  // Give each section its required (expanded) capacity.
769  for (int n = (int)SECT_LIMIT-1; n >= SECT_FIRST; n--) {
770    CodeSection* cb_sect   = cb.code_section(n);
771    CodeSection* this_sect = code_section(n);
772    if (new_capacity[n] == 0)  continue;  // already nulled out
773    if (n != SECT_INSTS) {
774      cb.initialize_section_size(cb_sect, new_capacity[n]);
775    }
776    assert(cb_sect->capacity() >= new_capacity[n], "big enough");
777    address cb_start = cb_sect->start();
778    cb_sect->set_end(cb_start + this_sect->size());
779    if (this_sect->mark() == NULL) {
780      cb_sect->clear_mark();
781    } else {
782      cb_sect->set_mark(cb_start + this_sect->mark_off());
783    }
784  }
785
786  // Move all the code and relocations to the new blob:
787  relocate_code_to(&cb);
788
789  // Copy the temporary code buffer into the current code buffer.
790  // Basically, do {*this = cb}, except for some control information.
791  this->take_over_code_from(&cb);
792  cb.set_blob(NULL);
793
794  // Zap the old code buffer contents, to avoid mistakenly using them.
795  debug_only(Copy::fill_to_bytes(bxp->_total_start, bxp->_total_size,
796                                 badCodeHeapFreeVal));
797
798  _decode_begin = NULL;  // sanity
799
800  // Make certain that the new sections are all snugly inside the new blob.
801  assert(verify_section_allocation(), "expanded allocation is ship-shape");
802
803#ifndef PRODUCT
804  if (PrintNMethods && (WizardMode || Verbose)) {
805    tty->print("expanded CodeBuffer:");
806    this->print();
807  }
808#endif //PRODUCT
809}
810
811void CodeBuffer::take_over_code_from(CodeBuffer* cb) {
812  // Must already have disposed of the old blob somehow.
813  assert(blob() == NULL, "must be empty");
814#ifdef ASSERT
815
816#endif
817  // Take the new blob away from cb.
818  set_blob(cb->blob());
819  // Take over all the section pointers.
820  for (int n = 0; n < (int)SECT_LIMIT; n++) {
821    CodeSection* cb_sect   = cb->code_section(n);
822    CodeSection* this_sect = code_section(n);
823    this_sect->take_over_code_from(cb_sect);
824  }
825  _overflow_arena = cb->_overflow_arena;
826  // Make sure the old cb won't try to use it or free it.
827  DEBUG_ONLY(cb->_blob = (BufferBlob*)badAddress);
828}
829
830#ifdef ASSERT
831bool CodeBuffer::verify_section_allocation() {
832  address tstart = _total_start;
833  if (tstart == badAddress)  return true;  // smashed by set_blob(NULL)
834  address tend   = tstart + _total_size;
835  if (_blob != NULL) {
836    assert(tstart >= _blob->content_begin(), "sanity");
837    assert(tend   <= _blob->content_end(),   "sanity");
838  }
839  // Verify disjointness.
840  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
841    CodeSection* sect = code_section(n);
842    if (!sect->is_allocated() || sect->is_empty())  continue;
843    assert((intptr_t)sect->start() % sect->alignment() == 0
844           || sect->is_empty() || _blob == NULL,
845           "start is aligned");
846    for (int m = (int) SECT_FIRST; m < (int) SECT_LIMIT; m++) {
847      CodeSection* other = code_section(m);
848      if (!other->is_allocated() || other == sect)  continue;
849      assert(!other->contains(sect->start()    ), "sanity");
850      // limit is an exclusive address and can be the start of another
851      // section.
852      assert(!other->contains(sect->limit() - 1), "sanity");
853    }
854    assert(sect->end() <= tend, "sanity");
855  }
856  return true;
857}
858#endif //ASSERT
859
860#ifndef PRODUCT
861
862void CodeSection::dump() {
863  address ptr = start();
864  for (csize_t step; ptr < end(); ptr += step) {
865    step = end() - ptr;
866    if (step > jintSize * 4)  step = jintSize * 4;
867    tty->print(PTR_FORMAT ": ", ptr);
868    while (step > 0) {
869      tty->print(" " PTR32_FORMAT, *(jint*)ptr);
870      ptr += jintSize;
871    }
872    tty->cr();
873  }
874}
875
876
877void CodeSection::decode() {
878  Disassembler::decode(start(), end());
879}
880
881
882void CodeBuffer::block_comment(intptr_t offset, const char * comment) {
883  _comments.add_comment(offset, comment);
884}
885
886
887class CodeComment: public CHeapObj {
888 private:
889  friend class CodeComments;
890  intptr_t     _offset;
891  const char * _comment;
892  CodeComment* _next;
893
894  ~CodeComment() {
895    assert(_next == NULL, "wrong interface for freeing list");
896    os::free((void*)_comment);
897  }
898
899 public:
900  CodeComment(intptr_t offset, const char * comment) {
901    _offset = offset;
902    _comment = os::strdup(comment);
903    _next = NULL;
904  }
905
906  intptr_t     offset()  const { return _offset;  }
907  const char * comment() const { return _comment; }
908  CodeComment* next()          { return _next; }
909
910  void set_next(CodeComment* next) { _next = next; }
911
912  CodeComment* find(intptr_t offset) {
913    CodeComment* a = this;
914    while (a != NULL && a->_offset != offset) {
915      a = a->_next;
916    }
917    return a;
918  }
919};
920
921
922void CodeComments::add_comment(intptr_t offset, const char * comment) {
923  CodeComment* c = new CodeComment(offset, comment);
924  CodeComment* insert = NULL;
925  if (_comments != NULL) {
926    CodeComment* c = _comments->find(offset);
927    insert = c;
928    while (c && c->offset() == offset) {
929      insert = c;
930      c = c->next();
931    }
932  }
933  if (insert) {
934    // insert after comments with same offset
935    c->set_next(insert->next());
936    insert->set_next(c);
937  } else {
938    c->set_next(_comments);
939    _comments = c;
940  }
941}
942
943
944void CodeComments::assign(CodeComments& other) {
945  assert(_comments == NULL, "don't overwrite old value");
946  _comments = other._comments;
947}
948
949
950void CodeComments::print_block_comment(outputStream* stream, intptr_t offset) {
951  if (_comments != NULL) {
952    CodeComment* c = _comments->find(offset);
953    while (c && c->offset() == offset) {
954      stream->bol();
955      stream->print("  ;; ");
956      stream->print_cr(c->comment());
957      c = c->next();
958    }
959  }
960}
961
962
963void CodeComments::free() {
964  CodeComment* n = _comments;
965  while (n) {
966    // unlink the node from the list saving a pointer to the next
967    CodeComment* p = n->_next;
968    n->_next = NULL;
969    delete n;
970    n = p;
971  }
972  _comments = NULL;
973}
974
975
976
977void CodeBuffer::decode() {
978  Disassembler::decode(decode_begin(), insts_end());
979  _decode_begin = insts_end();
980}
981
982
983void CodeBuffer::skip_decode() {
984  _decode_begin = insts_end();
985}
986
987
988void CodeBuffer::decode_all() {
989  for (int n = 0; n < (int)SECT_LIMIT; n++) {
990    // dump contents of each section
991    CodeSection* cs = code_section(n);
992    tty->print_cr("! %s:", code_section_name(n));
993    if (cs != consts())
994      cs->decode();
995    else
996      cs->dump();
997  }
998}
999
1000
1001void CodeSection::print(const char* name) {
1002  csize_t locs_size = locs_end() - locs_start();
1003  tty->print_cr(" %7s.code = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d)%s",
1004                name, start(), end(), limit(), size(), capacity(),
1005                is_frozen()? " [frozen]": "");
1006  tty->print_cr(" %7s.locs = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d) point=%d",
1007                name, locs_start(), locs_end(), locs_limit(), locs_size, locs_capacity(), locs_point_off());
1008  if (PrintRelocations) {
1009    RelocIterator iter(this);
1010    iter.print();
1011  }
1012}
1013
1014void CodeBuffer::print() {
1015  if (this == NULL) {
1016    tty->print_cr("NULL CodeBuffer pointer");
1017    return;
1018  }
1019
1020  tty->print_cr("CodeBuffer:");
1021  for (int n = 0; n < (int)SECT_LIMIT; n++) {
1022    // print each section
1023    CodeSection* cs = code_section(n);
1024    cs->print(code_section_name(n));
1025  }
1026}
1027
1028#endif // PRODUCT
1029