codeBuffer.cpp 39.3 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27
#include "precompiled.hpp"
#include "asm/codeBuffer.hpp"
#include "compiler/disassembler.hpp"
28 29 30
#include "memory/gcLocker.hpp"
#include "oops/methodData.hpp"
#include "oops/oop.inline.hpp"
31
#include "utilities/copy.hpp"
32
#include "utilities/xmlstream.hpp"
D
duke 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

// The structure of a CodeSection:
//
//    _start ->           +----------------+
//                        | machine code...|
//    _end ->             |----------------|
//                        |                |
//                        |    (empty)     |
//                        |                |
//                        |                |
//                        +----------------+
//    _limit ->           |                |
//
//    _locs_start ->      +----------------+
//                        |reloc records...|
//                        |----------------|
//    _locs_end ->        |                |
//                        |                |
//                        |    (empty)     |
//                        |                |
//                        |                |
//                        +----------------+
//    _locs_limit ->      |                |
// The _end (resp. _limit) pointer refers to the first
// unused (resp. unallocated) byte.

// The structure of the CodeBuffer while code is being accumulated:
//
//    _total_start ->    \
//    _insts._start ->              +----------------+
//                                  |                |
//                                  |     Code       |
//                                  |                |
//    _stubs._start ->              |----------------|
//                                  |                |
//                                  |    Stubs       | (also handlers for deopt/exception)
//                                  |                |
//    _consts._start ->             |----------------|
//                                  |                |
//                                  |   Constants    |
//                                  |                |
//                                  +----------------+
//    + _total_size ->              |                |
//
// When the code and relocations are copied to the code cache,
// the empty parts of each section are removed, and everything
// is copied into contiguous locations.

typedef CodeBuffer::csize_t csize_t;  // file-local definition

T
twisti 已提交
83
// External buffer, in a predefined CodeBlob.
D
duke 已提交
84
// Important: The code_start must be taken exactly, and not realigned.
T
twisti 已提交
85
CodeBuffer::CodeBuffer(CodeBlob* blob) {
D
duke 已提交
86
  initialize_misc("static buffer");
T
twisti 已提交
87
  initialize(blob->content_begin(), blob->content_size());
88
  verify_section_allocation();
D
duke 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
}

void CodeBuffer::initialize(csize_t code_size, csize_t locs_size) {
  // Compute maximal alignment.
  int align = _insts.alignment();
  // Always allow for empty slop around each section.
  int slop = (int) CodeSection::end_slop();

  assert(blob() == NULL, "only once");
  set_blob(BufferBlob::create(_name, code_size + (align+slop) * (SECT_LIMIT+1)));
  if (blob() == NULL) {
    // The assembler constructor will throw a fatal on an empty CodeBuffer.
    return;  // caller must test this
  }

  // Set up various pointers into the blob.
  initialize(_total_start, _total_size);

T
twisti 已提交
107
  assert((uintptr_t)insts_begin() % CodeEntryAlignment == 0, "instruction start not code entry aligned");
D
duke 已提交
108 109 110 111 112 113 114

  pd_initialize();

  if (locs_size != 0) {
    _insts.initialize_locs(locs_size / sizeof(relocInfo));
  }

115
  verify_section_allocation();
D
duke 已提交
116 117 118 119
}


CodeBuffer::~CodeBuffer() {
120 121
  verify_section_allocation();

D
duke 已提交
122 123 124 125 126 127 128 129 130 131
  // If we allocate our code buffer from the CodeCache
  // via a BufferBlob, and it's not permanent, then
  // free the BufferBlob.
  // The rest of the memory will be freed when the ResourceObj
  // is released.
  for (CodeBuffer* cb = this; cb != NULL; cb = cb->before_expand()) {
    // Previous incarnations of this buffer are held live, so that internal
    // addresses constructed before expansions will not be confused.
    cb->free_blob();
  }
132 133 134 135

  // free any overflow storage
  delete _overflow_arena;

D
duke 已提交
136
#ifdef ASSERT
137 138
  // Save allocation type to execute assert in ~ResourceObj()
  // which is called after this destructor.
139
  assert(_default_oop_recorder.allocated_on_stack(), "should be embedded object");
140
  ResourceObj::allocation_type at = _default_oop_recorder.get_allocation_type();
D
duke 已提交
141
  Copy::fill_to_bytes(this, sizeof(*this), badResourceValue);
142
  ResourceObj::set_allocation_type((address)(&_default_oop_recorder), at);
D
duke 已提交
143 144 145 146 147
#endif
}

void CodeBuffer::initialize_oop_recorder(OopRecorder* r) {
  assert(_oop_recorder == &_default_oop_recorder && _default_oop_recorder.is_unused(), "do this once");
148
  DEBUG_ONLY(_default_oop_recorder.freeze());  // force unused OR to be frozen
D
duke 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  _oop_recorder = r;
}

void CodeBuffer::initialize_section_size(CodeSection* cs, csize_t size) {
  assert(cs != &_insts, "insts is the memory provider, not the consumer");
  csize_t slop = CodeSection::end_slop();  // margin between sections
  int align = cs->alignment();
  assert(is_power_of_2(align), "sanity");
  address start  = _insts._start;
  address limit  = _insts._limit;
  address middle = limit - size;
  middle -= (intptr_t)middle & (align-1);  // align the division point downward
  guarantee(middle - slop > start, "need enough space to divide up");
  _insts._limit = middle - slop;  // subtract desired space, plus slop
  cs->initialize(middle, limit - middle);
  assert(cs->start() == middle, "sanity");
  assert(cs->limit() == limit,  "sanity");
  // give it some relocations to start with, if the main section has them
  if (_insts.has_locs())  cs->initialize_locs(1);
}

void CodeBuffer::freeze_section(CodeSection* cs) {
  CodeSection* next_cs = (cs == consts())? NULL: code_section(cs->index()+1);
  csize_t frozen_size = cs->size();
  if (next_cs != NULL) {
    frozen_size = next_cs->align_at_start(frozen_size);
  }
  address old_limit = cs->limit();
  address new_limit = cs->start() + frozen_size;
  relocInfo* old_locs_limit = cs->locs_limit();
  relocInfo* new_locs_limit = cs->locs_end();
  // Patch the limits.
  cs->_limit = new_limit;
  cs->_locs_limit = new_locs_limit;
  cs->_frozen = true;
  if (!next_cs->is_allocated() && !next_cs->is_frozen()) {
    // Give remaining buffer space to the following section.
    next_cs->initialize(new_limit, old_limit - new_limit);
    next_cs->initialize_shared_locs(new_locs_limit,
                                    old_locs_limit - new_locs_limit);
  }
}

void CodeBuffer::set_blob(BufferBlob* blob) {
  _blob = blob;
  if (blob != NULL) {
T
twisti 已提交
195 196
    address start = blob->content_begin();
    address end   = blob->content_end();
D
duke 已提交
197 198 199 200 201 202
    // Round up the starting address.
    int align = _insts.alignment();
    start += (-(intptr_t)start) & (align-1);
    _total_start = start;
    _total_size  = end - start;
  } else {
203
#ifdef ASSERT
D
duke 已提交
204 205
    // Clean out dangling pointers.
    _total_start    = badAddress;
206
    _consts._start  = _consts._end  = badAddress;
D
duke 已提交
207 208
    _insts._start   = _insts._end   = badAddress;
    _stubs._start   = _stubs._end   = badAddress;
209
#endif //ASSERT
D
duke 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
  }
}

void CodeBuffer::free_blob() {
  if (_blob != NULL) {
    BufferBlob::free(_blob);
    set_blob(NULL);
  }
}

const char* CodeBuffer::code_section_name(int n) {
#ifdef PRODUCT
  return NULL;
#else //PRODUCT
  switch (n) {
225
  case SECT_CONSTS:            return "consts";
D
duke 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
  case SECT_INSTS:             return "insts";
  case SECT_STUBS:             return "stubs";
  default:                     return NULL;
  }
#endif //PRODUCT
}

int CodeBuffer::section_index_of(address addr) const {
  for (int n = 0; n < (int)SECT_LIMIT; n++) {
    const CodeSection* cs = code_section(n);
    if (cs->allocates(addr))  return n;
  }
  return SECT_NONE;
}

int CodeBuffer::locator(address addr) const {
  for (int n = 0; n < (int)SECT_LIMIT; n++) {
    const CodeSection* cs = code_section(n);
    if (cs->allocates(addr)) {
      return locator(addr - cs->start(), n);
    }
  }
  return -1;
}

address CodeBuffer::locator_address(int locator) const {
  if (locator < 0)  return NULL;
  address start = code_section(locator_sect(locator))->start();
  return start + locator_pos(locator);
}

257 258 259 260
bool CodeBuffer::is_backward_branch(Label& L) {
  return L.is_bound() && insts_end() <= locator_address(L.loc());
}

D
duke 已提交
261 262 263 264 265 266 267 268 269 270
address CodeBuffer::decode_begin() {
  address begin = _insts.start();
  if (_decode_begin != NULL && _decode_begin > begin)
    begin = _decode_begin;
  return begin;
}


GrowableArray<int>* CodeBuffer::create_patch_overflow() {
  if (_overflow_arena == NULL) {
Z
zgu 已提交
271
    _overflow_arena = new (mtCode) Arena();
D
duke 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
  }
  return new (_overflow_arena) GrowableArray<int>(_overflow_arena, 8, 0, 0);
}


// Helper function for managing labels and their target addresses.
// Returns a sensible address, and if it is not the label's final
// address, notes the dependency (at 'branch_pc') on the label.
address CodeSection::target(Label& L, address branch_pc) {
  if (L.is_bound()) {
    int loc = L.loc();
    if (index() == CodeBuffer::locator_sect(loc)) {
      return start() + CodeBuffer::locator_pos(loc);
    } else {
      return outer()->locator_address(loc);
    }
  } else {
    assert(allocates2(branch_pc), "sanity");
    address base = start();
    int patch_loc = CodeBuffer::locator(branch_pc - base, index());
    L.add_patch_at(outer(), patch_loc);

    // Need to return a pc, doesn't matter what it is since it will be
    // replaced during resolution later.
296 297 298 299
    // Don't return NULL or badAddress, since branches shouldn't overflow.
    // Don't return base either because that could overflow displacements
    // for shorter branches.  It will get checked when bound.
    return branch_pc;
D
duke 已提交
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
  }
}

void CodeSection::relocate(address at, RelocationHolder const& spec, int format) {
  Relocation* reloc = spec.reloc();
  relocInfo::relocType rtype = (relocInfo::relocType) reloc->type();
  if (rtype == relocInfo::none)  return;

  // The assertion below has been adjusted, to also work for
  // relocation for fixup.  Sometimes we want to put relocation
  // information for the next instruction, since it will be patched
  // with a call.
  assert(start() <= at && at <= end()+1,
         "cannot relocate data outside code boundaries");

  if (!has_locs()) {
    // no space for relocation information provided => code cannot be
    // relocated.  Make sure that relocate is only called with rtypes
    // that can be ignored for this kind of code.
    assert(rtype == relocInfo::none              ||
           rtype == relocInfo::runtime_call_type ||
           rtype == relocInfo::internal_word_type||
           rtype == relocInfo::section_word_type ||
           rtype == relocInfo::external_word_type,
           "code needs relocation information");
    // leave behind an indication that we attempted a relocation
    DEBUG_ONLY(_locs_start = _locs_limit = (relocInfo*)badAddress);
    return;
  }

  // Advance the point, noting the offset we'll have to record.
  csize_t offset = at - locs_point();
  set_locs_point(at);

  // Test for a couple of overflow conditions; maybe expand the buffer.
  relocInfo* end = locs_end();
  relocInfo* req = end + relocInfo::length_limit;
  // Check for (potential) overflow
  if (req >= locs_limit() || offset >= relocInfo::offset_limit()) {
    req += (uint)offset / (uint)relocInfo::offset_limit();
    if (req >= locs_limit()) {
      // Allocate or reallocate.
      expand_locs(locs_count() + (req - end));
      // reload pointer
      end = locs_end();
    }
  }

  // If the offset is giant, emit filler relocs, of type 'none', but
  // each carrying the largest possible offset, to advance the locs_point.
  while (offset >= relocInfo::offset_limit()) {
    assert(end < locs_limit(), "adjust previous paragraph of code");
    *end++ = filler_relocInfo();
    offset -= filler_relocInfo().addr_offset();
  }

  // If it's a simple reloc with no data, we'll just write (rtype | offset).
  (*end) = relocInfo(rtype, offset, format);

  // If it has data, insert the prefix, as (data_prefix_tag | data1), data2.
  end->initialize(this, reloc);
}

void CodeSection::initialize_locs(int locs_capacity) {
  assert(_locs_start == NULL, "only one locs init step, please");
  // Apply a priori lower limits to relocation size:
  csize_t min_locs = MAX2(size() / 16, (csize_t)4);
  if (locs_capacity < min_locs)  locs_capacity = min_locs;
  relocInfo* locs_start = NEW_RESOURCE_ARRAY(relocInfo, locs_capacity);
  _locs_start    = locs_start;
  _locs_end      = locs_start;
  _locs_limit    = locs_start + locs_capacity;
  _locs_own      = true;
}

void CodeSection::initialize_shared_locs(relocInfo* buf, int length) {
  assert(_locs_start == NULL, "do this before locs are allocated");
  // Internal invariant:  locs buf must be fully aligned.
  // See copy_relocations_to() below.
  while ((uintptr_t)buf % HeapWordSize != 0 && length > 0) {
    ++buf; --length;
  }
  if (length > 0) {
    _locs_start = buf;
    _locs_end   = buf;
    _locs_limit = buf + length;
    _locs_own   = false;
  }
}

void CodeSection::initialize_locs_from(const CodeSection* source_cs) {
  int lcount = source_cs->locs_count();
  if (lcount != 0) {
    initialize_shared_locs(source_cs->locs_start(), lcount);
    _locs_end = _locs_limit = _locs_start + lcount;
    assert(is_allocated(), "must have copied code already");
    set_locs_point(start() + source_cs->locs_point_off());
  }
  assert(this->locs_count() == source_cs->locs_count(), "sanity");
}

void CodeSection::expand_locs(int new_capacity) {
  if (_locs_start == NULL) {
    initialize_locs(new_capacity);
    return;
  } else {
    int old_count    = locs_count();
    int old_capacity = locs_capacity();
    if (new_capacity < old_capacity * 2)
      new_capacity = old_capacity * 2;
    relocInfo* locs_start;
    if (_locs_own) {
      locs_start = REALLOC_RESOURCE_ARRAY(relocInfo, _locs_start, old_capacity, new_capacity);
    } else {
      locs_start = NEW_RESOURCE_ARRAY(relocInfo, new_capacity);
415
      Copy::conjoint_jbytes(_locs_start, locs_start, old_capacity * sizeof(relocInfo));
D
duke 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428
      _locs_own = true;
    }
    _locs_start    = locs_start;
    _locs_end      = locs_start + old_count;
    _locs_limit    = locs_start + new_capacity;
  }
}


/// Support for emitting the code to its final location.
/// The pattern is the same for all functions.
/// We iterate over all the sections, padding each to alignment.

T
twisti 已提交
429 430
csize_t CodeBuffer::total_content_size() const {
  csize_t size_so_far = 0;
D
duke 已提交
431 432 433
  for (int n = 0; n < (int)SECT_LIMIT; n++) {
    const CodeSection* cs = code_section(n);
    if (cs->is_empty())  continue;  // skip trivial section
T
twisti 已提交
434 435
    size_so_far = cs->align_at_start(size_so_far);
    size_so_far += cs->size();
D
duke 已提交
436
  }
T
twisti 已提交
437
  return size_so_far;
D
duke 已提交
438 439 440 441 442
}

void CodeBuffer::compute_final_layout(CodeBuffer* dest) const {
  address buf = dest->_total_start;
  csize_t buf_offset = 0;
T
twisti 已提交
443
  assert(dest->_total_size >= total_content_size(), "must be big enough");
D
duke 已提交
444 445 446 447 448 449 450 451 452

  {
    // not sure why this is here, but why not...
    int alignSize = MAX2((intx) sizeof(jdouble), CodeEntryAlignment);
    assert( (dest->_total_start - _insts.start()) % alignSize == 0, "copy must preserve alignment");
  }

  const CodeSection* prev_cs      = NULL;
  CodeSection*       prev_dest_cs = NULL;
453 454

  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
D
duke 已提交
455 456
    // figure compact layout of each section
    const CodeSection* cs = code_section(n);
457
    csize_t csize = cs->size();
D
duke 已提交
458 459 460 461 462 463 464 465 466 467 468 469

    CodeSection* dest_cs = dest->code_section(n);
    if (!cs->is_empty()) {
      // Compute initial padding; assign it to the previous non-empty guy.
      // Cf. figure_expanded_capacities.
      csize_t padding = cs->align_at_start(buf_offset) - buf_offset;
      if (padding != 0) {
        buf_offset += padding;
        assert(prev_dest_cs != NULL, "sanity");
        prev_dest_cs->_limit += padding;
      }
      #ifdef ASSERT
470
      if (prev_cs != NULL && prev_cs->is_frozen() && n < (SECT_LIMIT - 1)) {
D
duke 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        // Make sure the ends still match up.
        // This is important because a branch in a frozen section
        // might target code in a following section, via a Label,
        // and without a relocation record.  See Label::patch_instructions.
        address dest_start = buf+buf_offset;
        csize_t start2start = cs->start() - prev_cs->start();
        csize_t dest_start2start = dest_start - prev_dest_cs->start();
        assert(start2start == dest_start2start, "cannot stretch frozen sect");
      }
      #endif //ASSERT
      prev_dest_cs = dest_cs;
      prev_cs      = cs;
    }

    debug_only(dest_cs->_start = NULL);  // defeat double-initialization assert
    dest_cs->initialize(buf+buf_offset, csize);
    dest_cs->set_end(buf+buf_offset+csize);
    assert(dest_cs->is_allocated(), "must always be allocated");
    assert(cs->is_empty() == dest_cs->is_empty(), "sanity");

    buf_offset += csize;
  }

  // Done calculating sections; did it come out to the right end?
T
twisti 已提交
495
  assert(buf_offset == total_content_size(), "sanity");
496
  dest->verify_section_allocation();
D
duke 已提交
497 498
}

499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
// Anonymous classes need mirror to keep the metadata alive but
// for regular classes, the class_loader is sufficient.
static void append_oop_references(GrowableArray<oop>* oops, Klass* k) {
  if (k->oop_is_instance()) {
    InstanceKlass* ik = InstanceKlass::cast(k);
    if (ik->is_anonymous()) {
      oop o = ik->java_mirror();
      assert (o != NULL, "should have a mirror");
      if (!oops->contains(o)) {
        oops->append(o);
      }
      return;  // only need the mirror
    }
  }
  oop cl = k->class_loader();
  if (cl != NULL && !oops->contains(cl)) {
    oops->append(cl);
  }
}

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
void CodeBuffer::finalize_oop_references(methodHandle mh) {
  No_Safepoint_Verifier nsv;

  GrowableArray<oop> oops;

  // Make sure that immediate metadata records something in the OopRecorder
  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
    // pull code out of each section
    CodeSection* cs = code_section(n);
    if (cs->is_empty())  continue;  // skip trivial section
    RelocIterator iter(cs);
    while (iter.next()) {
      if (iter.type() == relocInfo::metadata_type) {
        metadata_Relocation* md = iter.metadata_reloc();
        if (md->metadata_is_immediate()) {
          Metadata* m = md->metadata_value();
          if (oop_recorder()->is_real(m)) {
            if (m->is_methodData()) {
              m = ((MethodData*)m)->method();
            }
            if (m->is_method()) {
              m = ((Method*)m)->method_holder();
            }
            if (m->is_klass()) {
543
              append_oop_references(&oops, (Klass*)m);
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
            } else {
              // XXX This will currently occur for MDO which don't
              // have a backpointer.  This has to be fixed later.
              m->print();
              ShouldNotReachHere();
            }
          }
        }
      }
    }
  }

  if (!oop_recorder()->is_unused()) {
    for (int i = 0; i < oop_recorder()->metadata_count(); i++) {
      Metadata* m = oop_recorder()->metadata_at(i);
      if (oop_recorder()->is_real(m)) {
        if (m->is_methodData()) {
          m = ((MethodData*)m)->method();
        }
        if (m->is_method()) {
          m = ((Method*)m)->method_holder();
        }
        if (m->is_klass()) {
567
          append_oop_references(&oops, (Klass*)m);
568 569 570 571 572 573 574 575 576 577
        } else {
          m->print();
          ShouldNotReachHere();
        }
      }
    }

  }

  // Add the class loader of Method* for the nmethod itself
578
  append_oop_references(&oops, mh->method_holder());
579 580 581 582 583 584 585 586 587 588

  // Add any oops that we've found
  Thread* thread = Thread::current();
  for (int i = 0; i < oops.length(); i++) {
    oop_recorder()->find_index((jobject)thread->handle_area()->allocate_handle(oops.at(i)));
  }
}



589 590 591 592 593 594
csize_t CodeBuffer::total_offset_of(CodeSection* cs) const {
  csize_t size_so_far = 0;
  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
    const CodeSection* cur_cs = code_section(n);
    if (!cur_cs->is_empty()) {
      size_so_far = cur_cs->align_at_start(size_so_far);
D
duke 已提交
595
    }
596 597
    if (cur_cs->index() == cs->index()) {
      return size_so_far;
D
duke 已提交
598
    }
599
    size_so_far += cur_cs->size();
D
duke 已提交
600 601 602 603 604 605 606
  }
  ShouldNotReachHere();
  return -1;
}

csize_t CodeBuffer::total_relocation_size() const {
  csize_t lsize = copy_relocations_to(NULL);  // dry run only
T
twisti 已提交
607
  csize_t csize = total_content_size();
D
duke 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
  csize_t total = RelocIterator::locs_and_index_size(csize, lsize);
  return (csize_t) align_size_up(total, HeapWordSize);
}

csize_t CodeBuffer::copy_relocations_to(CodeBlob* dest) const {
  address buf = NULL;
  csize_t buf_offset = 0;
  csize_t buf_limit = 0;
  if (dest != NULL) {
    buf = (address)dest->relocation_begin();
    buf_limit = (address)dest->relocation_end() - buf;
    assert((uintptr_t)buf % HeapWordSize == 0, "buf must be fully aligned");
    assert(buf_limit % HeapWordSize == 0, "buf must be evenly sized");
  }
  // if dest == NULL, this is just the sizing pass

  csize_t code_end_so_far = 0;
  csize_t code_point_so_far = 0;
626
  for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {
D
duke 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    // pull relocs out of each section
    const CodeSection* cs = code_section(n);
    assert(!(cs->is_empty() && cs->locs_count() > 0), "sanity");
    if (cs->is_empty())  continue;  // skip trivial section
    relocInfo* lstart = cs->locs_start();
    relocInfo* lend   = cs->locs_end();
    csize_t    lsize  = (csize_t)( (address)lend - (address)lstart );
    csize_t    csize  = cs->size();
    code_end_so_far = cs->align_at_start(code_end_so_far);

    if (lsize > 0) {
      // Figure out how to advance the combined relocation point
      // first to the beginning of this section.
      // We'll insert one or more filler relocs to span that gap.
      // (Don't bother to improve this by editing the first reloc's offset.)
      csize_t new_code_point = code_end_so_far;
      for (csize_t jump;
           code_point_so_far < new_code_point;
           code_point_so_far += jump) {
        jump = new_code_point - code_point_so_far;
        relocInfo filler = filler_relocInfo();
        if (jump >= filler.addr_offset()) {
          jump = filler.addr_offset();
        } else {  // else shrink the filler to fit
          filler = relocInfo(relocInfo::none, jump);
        }
        if (buf != NULL) {
          assert(buf_offset + (csize_t)sizeof(filler) <= buf_limit, "filler in bounds");
          *(relocInfo*)(buf+buf_offset) = filler;
        }
        buf_offset += sizeof(filler);
      }

      // Update code point and end to skip past this section:
      csize_t last_code_point = code_end_so_far + cs->locs_point_off();
      assert(code_point_so_far <= last_code_point, "sanity");
      code_point_so_far = last_code_point; // advance past this guy's relocs
    }
    code_end_so_far += csize;  // advance past this guy's instructions too

    // Done with filler; emit the real relocations:
    if (buf != NULL && lsize != 0) {
      assert(buf_offset + lsize <= buf_limit, "target in bounds");
      assert((uintptr_t)lstart % HeapWordSize == 0, "sane start");
      if (buf_offset % HeapWordSize == 0) {
        // Use wordwise copies if possible:
        Copy::disjoint_words((HeapWord*)lstart,
                             (HeapWord*)(buf+buf_offset),
                             (lsize + HeapWordSize-1) / HeapWordSize);
      } else {
677
        Copy::conjoint_jbytes(lstart, buf+buf_offset, lsize);
D
duke 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
      }
    }
    buf_offset += lsize;
  }

  // Align end of relocation info in target.
  while (buf_offset % HeapWordSize != 0) {
    if (buf != NULL) {
      relocInfo padding = relocInfo(relocInfo::none, 0);
      assert(buf_offset + (csize_t)sizeof(padding) <= buf_limit, "padding in bounds");
      *(relocInfo*)(buf+buf_offset) = padding;
    }
    buf_offset += sizeof(relocInfo);
  }

T
twisti 已提交
693
  assert(code_end_so_far == total_content_size(), "sanity");
D
duke 已提交
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

  // Account for index:
  if (buf != NULL) {
    RelocIterator::create_index(dest->relocation_begin(),
                                buf_offset / sizeof(relocInfo),
                                dest->relocation_end());
  }

  return buf_offset;
}

void CodeBuffer::copy_code_to(CodeBlob* dest_blob) {
#ifndef PRODUCT
  if (PrintNMethods && (WizardMode || Verbose)) {
    tty->print("done with CodeBuffer:");
    ((CodeBuffer*)this)->print();
  }
#endif //PRODUCT

T
twisti 已提交
713 714
  CodeBuffer dest(dest_blob);
  assert(dest_blob->content_size() >= total_content_size(), "good sizing");
D
duke 已提交
715 716 717 718 719 720 721
  this->compute_final_layout(&dest);
  relocate_code_to(&dest);

  // transfer comments from buffer to blob
  dest_blob->set_comments(_comments);

  // Done moving code bytes; were they the right size?
T
twisti 已提交
722
  assert(round_to(dest.total_content_size(), oopSize) == dest_blob->content_size(), "sanity");
D
duke 已提交
723 724

  // Flush generated code
T
twisti 已提交
725
  ICache::invalidate_range(dest_blob->code_begin(), dest_blob->code_size());
D
duke 已提交
726 727
}

728 729 730 731 732
// Move all my code into another code buffer.  Consult applicable
// relocs to repair embedded addresses.  The layout in the destination
// CodeBuffer is different to the source CodeBuffer: the destination
// CodeBuffer gets the final layout (consts, insts, stubs in order of
// ascending address).
D
duke 已提交
733
void CodeBuffer::relocate_code_to(CodeBuffer* dest) const {
734 735
  address dest_end = dest->_total_start + dest->_total_size;
  address dest_filled = NULL;
736
  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
D
duke 已提交
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    // pull code out of each section
    const CodeSection* cs = code_section(n);
    if (cs->is_empty())  continue;  // skip trivial section
    CodeSection* dest_cs = dest->code_section(n);
    assert(cs->size() == dest_cs->size(), "sanity");
    csize_t usize = dest_cs->size();
    csize_t wsize = align_size_up(usize, HeapWordSize);
    assert(dest_cs->start() + wsize <= dest_end, "no overflow");
    // Copy the code as aligned machine words.
    // This may also include an uninitialized partial word at the end.
    Copy::disjoint_words((HeapWord*)cs->start(),
                         (HeapWord*)dest_cs->start(),
                         wsize / HeapWordSize);

    if (dest->blob() == NULL) {
      // Destination is a final resting place, not just another buffer.
      // Normalize uninitialized bytes in the final padding.
      Copy::fill_to_bytes(dest_cs->end(), dest_cs->remaining(),
                          Assembler::code_fill_byte());
    }
757 758
    // Keep track of the highest filled address
    dest_filled = MAX2(dest_filled, dest_cs->end() + dest_cs->remaining());
D
duke 已提交
759 760 761 762 763 764

    assert(cs->locs_start() != (relocInfo*)badAddress,
           "this section carries no reloc storage, but reloc was attempted");

    // Make the new code copy use the old copy's relocations:
    dest_cs->initialize_locs_from(cs);
765
  }
D
duke 已提交
766

767 768 769 770 771 772 773 774 775 776
  // Do relocation after all sections are copied.
  // This is necessary if the code uses constants in stubs, which are
  // relocated when the corresponding instruction in the code (e.g., a
  // call) is relocated. Stubs are placed behind the main code
  // section, so that section has to be copied before relocating.
  for (int n = (int) SECT_FIRST; n < (int)SECT_LIMIT; n++) {
    // pull code out of each section
    const CodeSection* cs = code_section(n);
    if (cs->is_empty()) continue;  // skip trivial section
    CodeSection* dest_cs = dest->code_section(n);
D
duke 已提交
777 778 779 780 781 782 783
    { // Repair the pc relative information in the code after the move
      RelocIterator iter(dest_cs);
      while (iter.next()) {
        iter.reloc()->fix_relocation_after_move(this, dest);
      }
    }
  }
784

785
  if (dest->blob() == NULL && dest_filled != NULL) {
786 787 788 789 790 791
    // Destination is a final resting place, not just another buffer.
    // Normalize uninitialized bytes in the final padding.
    Copy::fill_to_bytes(dest_filled, dest_end - dest_filled,
                        Assembler::code_fill_byte());

  }
D
duke 已提交
792 793 794 795 796 797 798
}

csize_t CodeBuffer::figure_expanded_capacities(CodeSection* which_cs,
                                               csize_t amount,
                                               csize_t* new_capacity) {
  csize_t new_total_cap = 0;

799
  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
D
duke 已提交
800 801 802
    const CodeSection* sect = code_section(n);

    if (!sect->is_empty()) {
803 804 805
      // Compute initial padding; assign it to the previous section,
      // even if it's empty (e.g. consts section can be empty).
      // Cf. compute_final_layout
D
duke 已提交
806 807 808
      csize_t padding = sect->align_at_start(new_total_cap) - new_total_cap;
      if (padding != 0) {
        new_total_cap += padding;
809 810
        assert(n - 1 >= SECT_FIRST, "sanity");
        new_capacity[n - 1] += padding;
D
duke 已提交
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
      }
    }

    csize_t exp = sect->size();  // 100% increase
    if ((uint)exp < 4*K)  exp = 4*K;       // minimum initial increase
    if (sect == which_cs) {
      if (exp < amount)  exp = amount;
      if (StressCodeBuffers)  exp = amount;  // expand only slightly
    } else if (n == SECT_INSTS) {
      // scale down inst increases to a more modest 25%
      exp = 4*K + ((exp - 4*K) >> 2);
      if (StressCodeBuffers)  exp = amount / 2;  // expand only slightly
    } else if (sect->is_empty()) {
      // do not grow an empty secondary section
      exp = 0;
    }
    // Allow for inter-section slop:
    exp += CodeSection::end_slop();
    csize_t new_cap = sect->size() + exp;
    if (new_cap < sect->capacity()) {
      // No need to expand after all.
      new_cap = sect->capacity();
    }
    new_capacity[n] = new_cap;
    new_total_cap += new_cap;
  }

  return new_total_cap;
}

void CodeBuffer::expand(CodeSection* which_cs, csize_t amount) {
#ifndef PRODUCT
  if (PrintNMethods && (WizardMode || Verbose)) {
    tty->print("expanding CodeBuffer:");
    this->print();
  }

  if (StressCodeBuffers && blob() != NULL) {
    static int expand_count = 0;
    if (expand_count >= 0)  expand_count += 1;
    if (expand_count > 100 && is_power_of_2(expand_count)) {
      tty->print_cr("StressCodeBuffers: have expanded %d times", expand_count);
      // simulate an occasional allocation failure:
      free_blob();
    }
  }
#endif //PRODUCT

  // Resizing must be allowed
  {
    if (blob() == NULL)  return;  // caller must check for blob == NULL
    for (int n = 0; n < (int)SECT_LIMIT; n++) {
      guarantee(!code_section(n)->is_frozen(), "resizing not allowed when frozen");
    }
  }

  // Figure new capacity for each section.
  csize_t new_capacity[SECT_LIMIT];
  csize_t new_total_cap
    = figure_expanded_capacities(which_cs, amount, new_capacity);

  // Create a new (temporary) code buffer to hold all the new data
  CodeBuffer cb(name(), new_total_cap, 0);
  if (cb.blob() == NULL) {
    // Failed to allocate in code cache.
    free_blob();
    return;
  }

  // Create an old code buffer to remember which addresses used to go where.
  // This will be useful when we do final assembly into the code cache,
  // because we will need to know how to warp any internal address that
  // has been created at any time in this CodeBuffer's past.
  CodeBuffer* bxp = new CodeBuffer(_total_start, _total_size);
  bxp->take_over_code_from(this);  // remember the old undersized blob
  DEBUG_ONLY(this->_blob = NULL);  // silence a later assert
  bxp->_before_expand = this->_before_expand;
  this->_before_expand = bxp;

  // Give each section its required (expanded) capacity.
891
  for (int n = (int)SECT_LIMIT-1; n >= SECT_FIRST; n--) {
D
duke 已提交
892 893 894
    CodeSection* cb_sect   = cb.code_section(n);
    CodeSection* this_sect = code_section(n);
    if (new_capacity[n] == 0)  continue;  // already nulled out
895
    if (n != SECT_INSTS) {
D
duke 已提交
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
      cb.initialize_section_size(cb_sect, new_capacity[n]);
    }
    assert(cb_sect->capacity() >= new_capacity[n], "big enough");
    address cb_start = cb_sect->start();
    cb_sect->set_end(cb_start + this_sect->size());
    if (this_sect->mark() == NULL) {
      cb_sect->clear_mark();
    } else {
      cb_sect->set_mark(cb_start + this_sect->mark_off());
    }
  }

  // Move all the code and relocations to the new blob:
  relocate_code_to(&cb);

  // Copy the temporary code buffer into the current code buffer.
  // Basically, do {*this = cb}, except for some control information.
  this->take_over_code_from(&cb);
  cb.set_blob(NULL);

  // Zap the old code buffer contents, to avoid mistakenly using them.
  debug_only(Copy::fill_to_bytes(bxp->_total_start, bxp->_total_size,
                                 badCodeHeapFreeVal));

  _decode_begin = NULL;  // sanity

  // Make certain that the new sections are all snugly inside the new blob.
923
  verify_section_allocation();
D
duke 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951

#ifndef PRODUCT
  if (PrintNMethods && (WizardMode || Verbose)) {
    tty->print("expanded CodeBuffer:");
    this->print();
  }
#endif //PRODUCT
}

void CodeBuffer::take_over_code_from(CodeBuffer* cb) {
  // Must already have disposed of the old blob somehow.
  assert(blob() == NULL, "must be empty");
#ifdef ASSERT

#endif
  // Take the new blob away from cb.
  set_blob(cb->blob());
  // Take over all the section pointers.
  for (int n = 0; n < (int)SECT_LIMIT; n++) {
    CodeSection* cb_sect   = cb->code_section(n);
    CodeSection* this_sect = code_section(n);
    this_sect->take_over_code_from(cb_sect);
  }
  _overflow_arena = cb->_overflow_arena;
  // Make sure the old cb won't try to use it or free it.
  DEBUG_ONLY(cb->_blob = (BufferBlob*)badAddress);
}

952
void CodeBuffer::verify_section_allocation() {
D
duke 已提交
953
  address tstart = _total_start;
954
  if (tstart == badAddress)  return;  // smashed by set_blob(NULL)
D
duke 已提交
955 956
  address tend   = tstart + _total_size;
  if (_blob != NULL) {
957 958 959

    guarantee(tstart >= _blob->content_begin(), "sanity");
    guarantee(tend   <= _blob->content_end(),   "sanity");
D
duke 已提交
960
  }
961 962
  // Verify disjointness.
  for (int n = (int) SECT_FIRST; n < (int) SECT_LIMIT; n++) {
D
duke 已提交
963
    CodeSection* sect = code_section(n);
964
    if (!sect->is_allocated() || sect->is_empty())  continue;
965
    guarantee((intptr_t)sect->start() % sect->alignment() == 0
D
duke 已提交
966 967
           || sect->is_empty() || _blob == NULL,
           "start is aligned");
968 969 970
    for (int m = (int) SECT_FIRST; m < (int) SECT_LIMIT; m++) {
      CodeSection* other = code_section(m);
      if (!other->is_allocated() || other == sect)  continue;
971
      guarantee(!other->contains(sect->start()    ), "sanity");
972 973
      // limit is an exclusive address and can be the start of another
      // section.
974
      guarantee(!other->contains(sect->limit() - 1), "sanity");
975
    }
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
    guarantee(sect->end() <= tend, "sanity");
    guarantee(sect->end() <= sect->limit(), "sanity");
  }
}

void CodeBuffer::log_section_sizes(const char* name) {
  if (xtty != NULL) {
    // log info about buffer usage
    xtty->print_cr("<blob name='%s' size='%d'>", name, _total_size);
    for (int n = (int) CodeBuffer::SECT_FIRST; n < (int) CodeBuffer::SECT_LIMIT; n++) {
      CodeSection* sect = code_section(n);
      if (!sect->is_allocated() || sect->is_empty())  continue;
      xtty->print_cr("<sect index='%d' size='" SIZE_FORMAT "' free='" SIZE_FORMAT "'/>",
                     n, sect->limit() - sect->start(), sect->limit() - sect->end());
    }
    xtty->print_cr("</blob>");
D
duke 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
  }
}

#ifndef PRODUCT

void CodeSection::dump() {
  address ptr = start();
  for (csize_t step; ptr < end(); ptr += step) {
    step = end() - ptr;
    if (step > jintSize * 4)  step = jintSize * 4;
    tty->print(PTR_FORMAT ": ", ptr);
    while (step > 0) {
      tty->print(" " PTR32_FORMAT, *(jint*)ptr);
      ptr += jintSize;
    }
    tty->cr();
  }
}


void CodeSection::decode() {
  Disassembler::decode(start(), end());
}


void CodeBuffer::block_comment(intptr_t offset, const char * comment) {
  _comments.add_comment(offset, comment);
}

Z
zgu 已提交
1021
class CodeComment: public CHeapObj<mtCode> {
D
duke 已提交
1022 1023 1024 1025 1026 1027 1028 1029
 private:
  friend class CodeComments;
  intptr_t     _offset;
  const char * _comment;
  CodeComment* _next;

  ~CodeComment() {
    assert(_next == NULL, "wrong interface for freeing list");
Z
zgu 已提交
1030
    os::free((void*)_comment, mtCode);
D
duke 已提交
1031 1032 1033 1034 1035
  }

 public:
  CodeComment(intptr_t offset, const char * comment) {
    _offset = offset;
Z
zgu 已提交
1036
    _comment = os::strdup(comment, mtCode);
D
duke 已提交
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    _next = NULL;
  }

  intptr_t     offset()  const { return _offset;  }
  const char * comment() const { return _comment; }
  CodeComment* next()          { return _next; }

  void set_next(CodeComment* next) { _next = next; }

  CodeComment* find(intptr_t offset) {
    CodeComment* a = this;
    while (a != NULL && a->_offset != offset) {
      a = a->_next;
    }
    return a;
  }
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063

  // Convenience for add_comment.
  CodeComment* find_last(intptr_t offset) {
    CodeComment* a = find(offset);
    if (a != NULL) {
      while ((a->_next != NULL) && (a->_next->_offset == offset)) {
        a = a->_next;
      }
    }
    return a;
  }
D
duke 已提交
1064 1065 1066 1067
};


void CodeComments::add_comment(intptr_t offset, const char * comment) {
1068 1069 1070 1071 1072 1073 1074
  CodeComment* c      = new CodeComment(offset, comment);
  CodeComment* inspos = (_comments == NULL) ? NULL : _comments->find_last(offset);

  if (inspos) {
    // insert after already existing comments with same offset
    c->set_next(inspos->next());
    inspos->set_next(c);
D
duke 已提交
1075
  } else {
1076
    // no comments with such offset, yet. Insert before anything else.
D
duke 已提交
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
    c->set_next(_comments);
    _comments = c;
  }
}


void CodeComments::assign(CodeComments& other) {
  _comments = other._comments;
}


1088
void CodeComments::print_block_comment(outputStream* stream, intptr_t offset) const {
D
duke 已提交
1089 1090 1091
  if (_comments != NULL) {
    CodeComment* c = _comments->find(offset);
    while (c && c->offset() == offset) {
1092
      stream->bol();
D
duke 已提交
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
      stream->print("  ;; ");
      stream->print_cr(c->comment());
      c = c->next();
    }
  }
}


void CodeComments::free() {
  CodeComment* n = _comments;
  while (n) {
    // unlink the node from the list saving a pointer to the next
    CodeComment* p = n->_next;
    n->_next = NULL;
    delete n;
    n = p;
  }
  _comments = NULL;
}



void CodeBuffer::decode() {
1116
  ttyLocker ttyl;
T
twisti 已提交
1117 1118
  Disassembler::decode(decode_begin(), insts_end());
  _decode_begin = insts_end();
D
duke 已提交
1119 1120 1121 1122
}


void CodeBuffer::skip_decode() {
T
twisti 已提交
1123
  _decode_begin = insts_end();
D
duke 已提交
1124 1125 1126 1127
}


void CodeBuffer::decode_all() {
1128
  ttyLocker ttyl;
D
duke 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
  for (int n = 0; n < (int)SECT_LIMIT; n++) {
    // dump contents of each section
    CodeSection* cs = code_section(n);
    tty->print_cr("! %s:", code_section_name(n));
    if (cs != consts())
      cs->decode();
    else
      cs->dump();
  }
}


void CodeSection::print(const char* name) {
  csize_t locs_size = locs_end() - locs_start();
  tty->print_cr(" %7s.code = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d)%s",
                name, start(), end(), limit(), size(), capacity(),
                is_frozen()? " [frozen]": "");
  tty->print_cr(" %7s.locs = " PTR_FORMAT " : " PTR_FORMAT " : " PTR_FORMAT " (%d of %d) point=%d",
                name, locs_start(), locs_end(), locs_limit(), locs_size, locs_capacity(), locs_point_off());
  if (PrintRelocations) {
    RelocIterator iter(this);
    iter.print();
  }
}

void CodeBuffer::print() {
  if (this == NULL) {
    tty->print_cr("NULL CodeBuffer pointer");
    return;
  }

  tty->print_cr("CodeBuffer:");
  for (int n = 0; n < (int)SECT_LIMIT; n++) {
    // print each section
    CodeSection* cs = code_section(n);
    cs->print(code_section_name(n));
  }
}

#endif // PRODUCT