1 /*
   2  * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright 2008, 2009, 2010, 2011 Red Hat, Inc.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "ci/ciEnv.hpp"
  28 #include "ci/ciMethod.hpp"
  29 #include "code/debugInfoRec.hpp"
  30 #include "code/dependencies.hpp"
  31 #include "code/exceptionHandlerTable.hpp"
  32 #include "code/oopRecorder.hpp"
  33 #include "compiler/abstractCompiler.hpp"
  34 #include "compiler/oopMap.hpp"
  35 #include "shark/llvmHeaders.hpp"
  36 #include "shark/sharkBuilder.hpp"
  37 #include "shark/sharkCodeBuffer.hpp"
  38 #include "shark/sharkCompiler.hpp"
  39 #include "shark/sharkContext.hpp"
  40 #include "shark/sharkEntry.hpp"
  41 #include "shark/sharkFunction.hpp"
  42 #include "shark/sharkMemoryManager.hpp"
  43 #include "shark/sharkNativeWrapper.hpp"
  44 #include "shark/shark_globals.hpp"
  45 #include "utilities/debug.hpp"
  46 
  47 #include <fnmatch.h>
  48 
  49 using namespace llvm;
  50 
  51 namespace {
  52   cl::opt<std::string>
  53   MCPU("mcpu");
  54 
  55   cl::list<std::string>
  56   MAttrs("mattr",
  57          cl::CommaSeparated);
  58 }
  59 
  60 SharkCompiler::SharkCompiler()
  61   : AbstractCompiler(shark) {
  62   // Create the lock to protect the memory manager and execution engine
  63   _execution_engine_lock = new Monitor(Mutex::leaf, "SharkExecutionEngineLock");
  64   {
  65     MutexLocker locker(execution_engine_lock());
  66     init_llvm();
  67   }
  68   // All done
  69   set_state(initialized);
  70 }
  71 
  72 void SharkCompiler::init_llvm() {
  73 
  74   // Make LLVM safe for multithreading
  75   if (!llvm_start_multithreaded())
  76     fatal("llvm_start_multithreaded() failed");
  77 
  78   // Initialize the native target
  79   InitializeNativeTarget();
  80 
  81   // MCJIT require a native AsmPrinter
  82   InitializeNativeTargetAsmPrinter();
  83 
  84   // Create the two contexts which we'll use
  85   _normal_context = new SharkContext("normal");
  86   _native_context = new SharkContext("native");
  87 
  88   // Create the memory manager
  89   _memory_manager = new SharkMemoryManager();
  90 
  91   // Finetune LLVM for the current host CPU.
  92   StringMap<bool> Features;
  93   bool gotCpuFeatures = llvm::sys::getHostCPUFeatures(Features);
  94   std::string cpu("-mcpu=" + llvm::sys::getHostCPUName());
  95 
  96   std::vector<const char*> args;
  97   args.push_back(""); // program name
  98   args.push_back(cpu.c_str());
  99 
 100   std::string mattr("-mattr=");
 101   if(gotCpuFeatures){
 102     for(StringMap<bool>::iterator I = Features.begin(),
 103       E = Features.end(); I != E; ++I){
 104       if(I->second){
 105         std::string attr(I->first());
 106         mattr+="+"+attr+",";
 107       }
 108     }
 109     args.push_back(mattr.c_str());
 110   }
 111 
 112   args.push_back(0);  // terminator
 113   cl::ParseCommandLineOptions(args.size() - 1, (char **) &args[0]);
 114 
 115   // Create the JIT
 116   std::string ErrorMsg;
 117 
 118   EngineBuilder builder(_normal_context->module());
 119   builder.setMCPU(MCPU);
 120   builder.setMAttrs(MAttrs);
 121   builder.setJITMemoryManager(memory_manager());
 122   builder.setEngineKind(EngineKind::JIT);
 123   builder.setErrorStr(&ErrorMsg);
 124   if (! fnmatch(SharkOptimizationLevel, "None", 0)) {
 125     tty->print_cr("Shark optimization level set to: None");
 126     builder.setOptLevel(llvm::CodeGenOpt::None);
 127   } else if (! fnmatch(SharkOptimizationLevel, "Less", 0)) {
 128     tty->print_cr("Shark optimization level set to: Less");
 129     builder.setOptLevel(llvm::CodeGenOpt::Less);
 130   } else if (! fnmatch(SharkOptimizationLevel, "Aggressive", 0)) {
 131     tty->print_cr("Shark optimization level set to: Aggressive");
 132     builder.setOptLevel(llvm::CodeGenOpt::Aggressive);
 133   } // else Default is selected by, well, default :-)
 134   _execution_engine = builder.create();
 135 
 136   if (!execution_engine()) {
 137     if (!ErrorMsg.empty())
 138       printf("Error while creating Shark JIT: %s\n",ErrorMsg.c_str());
 139     else
 140       printf("Unknown error while creating Shark JIT\n");
 141     exit(1);
 142   }
 143 
 144   execution_engine()->addModule(_native_context->module());
 145 }
 146 
 147 void SharkCompiler::initialize() {
 148   ShouldNotCallThis();
 149 }
 150 
 151 void SharkCompiler::compile_method(ciEnv*    env,
 152                                    ciMethod* target,
 153                                    int       entry_bci) {
 154   assert(is_initialized(), "should be");
 155   ResourceMark rm;
 156   const char *name = methodname(
 157     target->holder()->name()->as_utf8(), target->name()->as_utf8());
 158 
 159   // Do the typeflow analysis
 160   ciTypeFlow *flow;
 161   if (entry_bci == InvocationEntryBci)
 162     flow = target->get_flow_analysis();
 163   else
 164     flow = target->get_osr_flow_analysis(entry_bci);
 165   if (flow->failing())
 166     return;
 167   if (SharkPrintTypeflowOf != NULL) {
 168     if (!fnmatch(SharkPrintTypeflowOf, name, 0))
 169       flow->print_on(tty);
 170   }
 171 
 172   // Create the recorders
 173   Arena arena(mtCompiler);
 174   env->set_oop_recorder(new OopRecorder(&arena));
 175   OopMapSet oopmaps;
 176   env->set_debug_info(new DebugInformationRecorder(env->oop_recorder()));
 177   env->debug_info()->set_oopmaps(&oopmaps);
 178   env->set_dependencies(new Dependencies(env));
 179 
 180   // Create the code buffer and builder
 181   CodeBuffer hscb("Shark", 256 * K, 64 * K);
 182   hscb.initialize_oop_recorder(env->oop_recorder());
 183   MacroAssembler *masm = new MacroAssembler(&hscb);
 184   SharkCodeBuffer cb(masm);
 185   SharkBuilder builder(&cb);
 186 
 187   // Emit the entry point
 188   SharkEntry *entry = (SharkEntry *) cb.malloc(sizeof(SharkEntry));
 189 
 190   // Build the LLVM IR for the method
 191   Function *function = SharkFunction::build(env, &builder, flow, name);
 192   if (env->failing()) {
 193     return;
 194   }
 195 
 196   // Generate native code.  It's unpleasant that we have to drop into
 197   // the VM to do this -- it blocks safepoints -- but I can't see any
 198   // other way to handle the locking.
 199   {
 200     ThreadInVMfromNative tiv(JavaThread::current());
 201     generate_native_code(entry, function, name);
 202   }
 203 
 204   // Install the method into the VM
 205   CodeOffsets offsets;
 206   offsets.set_value(CodeOffsets::Deopt, 0);
 207   offsets.set_value(CodeOffsets::Exceptions, 0);
 208   offsets.set_value(CodeOffsets::Verified_Entry,
 209                     target->is_static() ? 0 : wordSize);
 210 
 211   ExceptionHandlerTable handler_table;
 212   ImplicitExceptionTable inc_table;
 213 
 214   env->register_method(target,
 215                        entry_bci,
 216                        &offsets,
 217                        0,
 218                        &hscb,
 219                        0,
 220                        &oopmaps,
 221                        &handler_table,
 222                        &inc_table,
 223                        this,
 224                        env->comp_level(),
 225                        false,
 226                        false);
 227 }
 228 
 229 nmethod* SharkCompiler::generate_native_wrapper(MacroAssembler* masm,
 230                                                 methodHandle    target,
 231                                                 int             compile_id,
 232                                                 BasicType*      arg_types,
 233                                                 BasicType       return_type) {
 234   assert(is_initialized(), "should be");
 235   ResourceMark rm;
 236   const char *name = methodname(
 237     target->klass_name()->as_utf8(), target->name()->as_utf8());
 238 
 239   // Create the code buffer and builder
 240   SharkCodeBuffer cb(masm);
 241   SharkBuilder builder(&cb);
 242 
 243   // Emit the entry point
 244   SharkEntry *entry = (SharkEntry *) cb.malloc(sizeof(SharkEntry));
 245 
 246   // Build the LLVM IR for the method
 247   SharkNativeWrapper *wrapper = SharkNativeWrapper::build(
 248     &builder, target, name, arg_types, return_type);
 249 
 250   // Generate native code
 251   generate_native_code(entry, wrapper->function(), name);
 252 
 253   // Return the nmethod for installation in the VM
 254   return nmethod::new_native_nmethod(target,
 255                                      compile_id,
 256                                      masm->code(),
 257                                      0,
 258                                      0,
 259                                      wrapper->frame_size(),
 260                                      wrapper->receiver_offset(),
 261                                      wrapper->lock_offset(),
 262                                      wrapper->oop_maps());
 263 }
 264 
 265 void SharkCompiler::generate_native_code(SharkEntry* entry,
 266                                          Function*   function,
 267                                          const char* name) {
 268   // Print the LLVM bitcode, if requested
 269   if (SharkPrintBitcodeOf != NULL) {
 270     if (!fnmatch(SharkPrintBitcodeOf, name, 0))
 271       function->dump();
 272   }
 273 
 274   if (SharkVerifyFunction != NULL) {
 275     if (!fnmatch(SharkVerifyFunction, name, 0)) {
 276       verifyFunction(*function);
 277     }
 278   }
 279 
 280   // Compile to native code
 281   address code = NULL;
 282   context()->add_function(function);
 283   {
 284     MutexLocker locker(execution_engine_lock());
 285     free_queued_methods();
 286 
 287 #ifndef NDEBUG
 288 #if SHARK_LLVM_VERSION <= 31
 289 #define setCurrentDebugType SetCurrentDebugType
 290 #endif
 291     if (SharkPrintAsmOf != NULL) {
 292       if (!fnmatch(SharkPrintAsmOf, name, 0)) {
 293         llvm::setCurrentDebugType(X86_ONLY("x86-emitter") NOT_X86("jit"));
 294         llvm::DebugFlag = true;
 295       }
 296       else {
 297         llvm::setCurrentDebugType("");
 298         llvm::DebugFlag = false;
 299       }
 300     }
 301 #ifdef setCurrentDebugType
 302 #undef setCurrentDebugType
 303 #endif
 304 #endif // !NDEBUG
 305     memory_manager()->set_entry_for_function(function, entry);
 306     code = (address) execution_engine()->getPointerToFunction(function);
 307   }
 308   assert(code != NULL, "code must be != NULL");
 309   entry->set_entry_point(code);
 310   entry->set_function(function);
 311   entry->set_context(context());
 312   address code_start = entry->code_start();
 313   address code_limit = entry->code_limit();
 314 
 315   // Register generated code for profiling, etc
 316   if (JvmtiExport::should_post_dynamic_code_generated())
 317     JvmtiExport::post_dynamic_code_generated(name, code_start, code_limit);
 318 
 319   // Print debug information, if requested
 320   if (SharkTraceInstalls) {
 321     tty->print_cr(
 322       " [%p-%p): %s (%d bytes code)",
 323       code_start, code_limit, name, code_limit - code_start);
 324   }
 325 }
 326 
 327 void SharkCompiler::free_compiled_method(address code) {
 328   // This method may only be called when the VM is at a safepoint.
 329   // All _thread_in_vm threads will be waiting for the safepoint to
 330   // finish with the exception of the VM thread, so we can consider
 331   // ourself the owner of the execution engine lock even though we
 332   // can't actually acquire it at this time.
 333   assert(Thread::current()->is_Compiler_thread(), "must be called by compiler thread");
 334   assert_locked_or_safepoint(CodeCache_lock);
 335 
 336   SharkEntry *entry = (SharkEntry *) code;
 337   entry->context()->push_to_free_queue(entry->function());
 338 }
 339 
 340 void SharkCompiler::free_queued_methods() {
 341   // The free queue is protected by the execution engine lock
 342   assert(execution_engine_lock()->owned_by_self(), "should be");
 343 
 344   while (true) {
 345     Function *function = context()->pop_from_free_queue();
 346     if (function == NULL)
 347       break;
 348 
 349     execution_engine()->freeMachineCodeForFunction(function);
 350     function->eraseFromParent();
 351   }
 352 }
 353 
 354 const char* SharkCompiler::methodname(const char* klass, const char* method) {
 355   char *buf = NEW_RESOURCE_ARRAY(char, strlen(klass) + 2 + strlen(method) + 1);
 356 
 357   char *dst = buf;
 358   for (const char *c = klass; *c; c++) {
 359     if (*c == '/')
 360       *(dst++) = '.';
 361     else
 362       *(dst++) = *c;
 363   }
 364   *(dst++) = ':';
 365   *(dst++) = ':';
 366   for (const char *c = method; *c; c++) {
 367     *(dst++) = *c;
 368   }
 369   *(dst++) = '\0';
 370   return buf;
 371 }
 372 
 373 void SharkCompiler::print_timers() {
 374   // do nothing
 375 }