Пример #1
0
int main()
{
    InitializeNativeTarget();
    llvm_start_multithreaded();
    LLVMContext context;
    string error;
    OwningPtr<llvm::MemoryBuffer> fileBuf;
    MemoryBuffer::getFile("hw.bc", fileBuf);
    ErrorOr<Module*> m = parseBitcodeFile(fileBuf.get(), context);
    ExecutionEngine *ee = ExecutionEngine::create(m.get());

    Function* func = ee->FindFunctionNamed("main");
    std::cout << "hop " << m.get()  << " ee " << ee << " f " << func << std::endl;

    typedef void (*PFN)();
    PFN pfn = reinterpret_cast<PFN>(ee->getPointerToFunction(func));
    pfn();

    Function* f = ee->FindFunctionNamed("fib");
    std::cout << "big " << f << std::endl;

    //    typedef std::function<int(int)> fibType;
    typedef int (*fibType)(int);
    fibType ffib = reinterpret_cast<fibType>(ee->getPointerToFunction(f));
    std::cout << "fib " << ffib(7) << std::endl;



    delete ee;
}
Пример #2
0
int main()
{
   TestClass tc;
   tc.setHealth(100);
   tc.printHealth();
   
   InitializeNativeTarget();
   LLVMContext context;
   string error;

   auto mb = MemoryBuffer::getFile("bitcode/damage.bc");
   if (!mb) {
      cout << "ERROR: Failed to getFile" << endl;
      return 0;
   }

   auto m = parseBitcodeFile(mb->get(), context);
   if(!m) {
      cout << "ERROR: Failed to load script file." << endl;
      return 0;
   }
   
   ExecutionEngine *ee = ExecutionEngine::create(m.get());

   // NOTE: Function names are mangled by the compiler.
   Function* init_func = ee->FindFunctionNamed("_Z9initilizev");
   if(!init_func) {
      cout << "ERROR: Failed to find 'initilize' function." << endl;
      return 0;
   }

   Function* attack_func = ee->FindFunctionNamed("_Z6attackP9TestClass");
   if(!attack_func) {
      cout << "ERROR: Failed to find 'attack' function." << endl;
      return 0;
   }

   typedef void (*init_pfn)();
   init_pfn initilize = reinterpret_cast<init_pfn>(ee->getPointerToFunction(init_func));
   if(!initilize) {
      cout << "ERROR: Failed to cast 'initilize' function." << endl;
      return 0;
   }

   initilize();
   cout << "Running attacking script..." << endl;

   typedef void (*attack_pfn)(TestClass*);
   attack_pfn attack = reinterpret_cast<attack_pfn>(ee->getPointerToFunction(attack_func));
   if(!attack) {
      cout << "ERROR: Failed to cast 'attack' function." << endl;
      return 0;
   }

   attack(&tc);
   
   tc.printHealth();
   delete ee;
}
Пример #3
0
int main(int argc, char **argv)
{
  using namespace llvm;

  std::cout << "hello_world_ir: " << std::endl;
  std::cout << std::endl;
  std::cout << hello_world_ir << std::endl;
  std::cout << std::endl;

  InitializeNativeTarget();

  LLVMContext context;
  SMDiagnostic error;

  Module *m = ParseIR(MemoryBuffer::getMemBuffer(StringRef(hello_world_ir)), error, context);
  if(!m)
  {
    error.print(argv[0], errs());
  }

  ExecutionEngine *ee = ExecutionEngine::create(m);

  Function *func = ee->FindFunctionNamed("hello_world");

  typedef void (*fcn_ptr)();
  fcn_ptr hello_world = reinterpret_cast<fcn_ptr>(ee->getPointerToFunction(func));
  hello_world();
  delete ee;

  return 0;
}
int main(int argc, char **argv) {
  int n = argc > 1 ? atol(argv[1]) : 10;

  InitializeNativeTarget();
 
  LLVMContext Context;
 
  Module *M = new Module("test", Context);
  ExecutionEngine* EE = llvm::EngineBuilder(M).setEngineKind(EngineKind::JIT).create();
 
  for (int i = 0; i < n; ++i) {
    SMDiagnostic error;
    ParseAssemblyString(function_assembly,
                        M,
                        error,
                        Context);
 
    Function *func = M->getFunction( "factorial" );
 
    typedef int(*func_t)(int);
    func_t f = (func_t)(uintptr_t)(EE->getPointerToFunction(func));
 
    EE->freeMachineCodeForFunction(func);
    func->eraseFromParent();
  }
 
  delete EE;
 
  llvm_shutdown();
 
  return 0;
}
Пример #5
0
casefoldFunctionType caseFoldCodeGen(void) {
                            
    Module * M = new Module("casefold", getGlobalContext());
    
    IDISA::IDISA_Builder * idb = GetIDISA_Builder(M);

    kernel::PipelineBuilder pipelineBuilder(M, idb);

    Encoding encoding(Encoding::Type::UTF_8, 8);
    
    pablo::PabloFunction * function = casefold2pablo(encoding);
    

    pipelineBuilder.CreateKernels(function);

    pipelineBuilder.ExecuteKernels();

    //std::cerr << "ExecuteKernels(); done\n";
    llvm::Function * main_IR = M->getFunction("Main");
    ExecutionEngine * mEngine = JIT_to_ExecutionEngine(M);
    
    mEngine->finalizeObject();
    //std::cerr << "finalizeObject(); done\n";

    delete idb;

    return reinterpret_cast<casefoldFunctionType>(mEngine->getPointerToFunction(main_IR));
}
Пример #6
0
void* getPointerToFunction(Module * mod, Function * func)
{
    ExecutionEngine * execEngine = createExecutionEngine(mod);
    if (!execEngine) exit(-1);

    return execEngine->getPointerToFunction(func);
}
Пример #7
0
extern "C" void*
LLVMRustExecuteJIT(void* mem,
                   LLVMPassManagerRef PMR,
                   LLVMModuleRef M,
                   CodeGenOpt::Level OptLevel,
                   bool EnableSegmentedStacks) {

  InitializeNativeTarget();
  InitializeNativeTargetAsmPrinter();
  InitializeNativeTargetAsmParser();

  std::string Err;
  TargetOptions Options;
  Options.JITExceptionHandling = true;
  Options.JITEmitDebugInfo = true;
  Options.NoFramePointerElim = true;
  Options.EnableSegmentedStacks = EnableSegmentedStacks;
  PassManager *PM = unwrap<PassManager>(PMR);
  RustMCJITMemoryManager* MM = (RustMCJITMemoryManager*) mem;

  assert(MM);

  PM->add(createBasicAliasAnalysisPass());
  PM->add(createInstructionCombiningPass());
  PM->add(createReassociatePass());
  PM->add(createGVNPass());
  PM->add(createCFGSimplificationPass());
  PM->add(createFunctionInliningPass());
  PM->add(createPromoteMemoryToRegisterPass());
  PM->run(*unwrap(M));

  ExecutionEngine* EE = EngineBuilder(unwrap(M))
    .setErrorStr(&Err)
    .setTargetOptions(Options)
    .setJITMemoryManager(MM)
    .setOptLevel(OptLevel)
    .setUseMCJIT(true)
    .setAllocateGVsWithCode(false)
    .create();

  if(!EE || Err != "") {
    LLVMRustError = Err.c_str();
    return 0;
  }

  MM->invalidateInstructionCache();
  Function* func = EE->FindFunctionNamed("_rust_main");

  if(!func || Err != "") {
    LLVMRustError = Err.c_str();
    return 0;
  }

  void* entry = EE->getPointerToFunction(func);
  assert(entry);

  return entry;
}
Пример #8
0
void * compile(llvm::Module * m) {
    ExecutionEngine * engine =
      EngineBuilder(std::unique_ptr<Module>(m))
      .create();
    engine->finalizeObject();

    return engine->getPointerToFunction(
        m->getFunction("aFun"));
}
Пример #9
0
int
main (int argc, char const *argv[])
{
	Module* mod = makeLLVMModule();
	verifyModule(*mod, PrintMessageAction);

	ExecutionEngine* jit = ExecutionEngine::create(mod);
	Function* factorial = mod->getFunction("factorial");
	int (*native_factorial)(int) = (int (*)(int)) jit->getPointerToFunction(factorial);
	int arg1 = argc > 1 ? atoi(argv[1]) : 1;
	printf("Factorial(%d) = %d.\n", arg1, native_factorial(arg1));
	return 0;
}
Пример #10
0
void* getPointerToFunction(Module* mod, std::string functionName) {

    ExecutionEngine *execEngine = createExecutionEngine(mod);
    if (!execEngine) exit(-1);

    Function* f = mod->getFunction(functionName);
    if (!f) {
        errs() << "Error: Function '" << functionName << "' not found in module "
            << mod->getModuleIdentifier() << "!\n";
        exit(-1);
    }

    return execEngine->getPointerToFunction(f);
}
Ret(*compile(const pegsolitaire::ast::Function<Ret, Types...> & function))(Types...) {
    using namespace llvm;

    Module * module = new Module("compiledModule", getGlobalContext());
    IRBuilder<> builder(getGlobalContext());
    pegsolitaire::codegen::CodeGenerator cg(module, builder);
    auto f = cg(function);
#ifndef NDEBUG
    module->dump();
#endif
    ExecutionEngine * executionEngine = EngineBuilder(module).create();
    // TODO we actually need a mapping from Types... to NativeTypes... here:
    return reinterpret_cast<Ret(*)(Types...)>(executionEngine->getPointerToFunction(f));
}
Пример #12
0
 main_func_type jit_engine::compile(const ast::Program &prog) {
     llvm::LLVMContext &c=llvm::getGlobalContext();
     llvm::Module *m=new llvm::Module("brainfuck", c);
     brainfuck::codegen(*m, prog);
     //m->dump();
     
     std::string ErrStr;
     ExecutionEngine *TheExecutionEngine = EngineBuilder(m).setErrorStr(&ErrStr).create();
     if (!TheExecutionEngine) {
         fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
         exit(1);
     }
     Function *f_main=m->getFunction("main");
     
     // Optimize, target dependant
     if(optimization_level_>0)
     {
         FunctionPassManager OurFPM(m);
         
         // Set up the optimizer pipeline.  Start with registering info about how the
         // target lays out data structures.
         OurFPM.add(new TargetData(*TheExecutionEngine->getTargetData()));
         // Provide basic AliasAnalysis support for GVN.
         OurFPM.add(createBasicAliasAnalysisPass());
         // Do simple "peephole" optimizations and bit-twiddling optzns.
         OurFPM.add(createInstructionCombiningPass());
         // Reassociate expressions.
         OurFPM.add(createReassociatePass());
         // Eliminate Common SubExpressions.
         OurFPM.add(createGVNPass());
         // Simplify the control flow graph (deleting unreachable blocks, etc).
         OurFPM.add(createCFGSimplificationPass());
         //OurFPM.add(createLoopSimplifyPass());
         //OurFPM.add(createBlockPlacementPass());
         //OurFPM.add(createConstantPropagationPass());
         
         OurFPM.doInitialization();
      
         OurFPM.run(*f_main);
     }
     
     //m->dump();
     
     void *rp=TheExecutionEngine->getPointerToFunction(f_main);
     main_func_type fp=reinterpret_cast<main_func_type>(rp);
     return fp;
 }
Пример #13
0
int main() {
  // The registers.
  int registers[2] = {0, 0};

  // Our program.
  int program[20] = {0, 0, 3,
                     1, 0, 0, 4,
                     2, 0};

  int* ops = (int*)program;

  // Create our function and give us the Module and Function back.
  Module* jit;
  Function* func = create(&jit);

  // Add in optimizations. These were taken from a list that 'opt', LLVMs optimization tool, uses.
  PassManager p;

  /* Comment out optimize
  p.add(new TargetData(jit));
  p.add(createVerifierPass());
  p.add(createLowerSetJmpPass());
  p.add(createRaiseAllocationsPass());
  p.add(createCFGSimplificationPass());
  p.add(createPromoteMemoryToRegisterPass());
  p.add(createGlobalOptimizerPass());
  p.add(createGlobalDCEPass());
  p.add(createFunctionInliningPass());
  */

  // Run these optimizations on our Module
  p.run(*jit);

  // Setup for JIT
  ExistingModuleProvider* mp = new ExistingModuleProvider(jit);
  ExecutionEngine* engine = ExecutionEngine::create(mp);

  // Show us what we've created!
  std::cout << "Created\n" << *jit;

  // Have our function JIT'd into machine code and return. We cast it to a particular C function pointer signature so we can call in nicely.
  void (*fp)(int*, int*) = (void (*)(int*, int*))engine->getPointerToFunction(func);

  // Call what we've created!
  fp(ops, registers);
}
Пример #14
0
int main(int argc, char **argv)
{
    InitializeNativeTarget();
    LLVMContext &Context = getGlobalContext();
    Module *m = new Module("test", Context);
    Type *intTy  = Type::getInt64Ty(Context);

    StructType* structTy = StructType::create(Context, "struct.list");
    std::vector<Type*> fields;
    fields.push_back(intTy);
    fields.push_back(PointerType::get(structTy, 0));
    if (structTy->isOpaque()) {
        structTy->setBody(fields, false);
    }

    /*
     * int f1(struct x *p) { return p->next->l1; }
     */
    std::vector<Type*> args_type;
    args_type.push_back(PointerType::get(structTy, 0));

    FunctionType *fnTy = FunctionType::get(intTy, args_type, false);
    Function *func = Function::Create(fnTy,
            GlobalValue::ExternalLinkage, "f1", m);
    Value *v = func->arg_begin();
    BasicBlock *bb = BasicBlock::Create(Context, "EntryBlock", func);
    IRBuilder<> *builder = new IRBuilder<>(bb);
    v = builder->CreateStructGEP(v, 1);
    v = builder->CreateLoad(v, "load0");
    v = builder->CreateStructGEP(v, 0);
    v = builder->CreateLoad(v, "load1");
    builder->CreateRet(v);

    (*m).dump();
    {
        ExecutionEngine *ee = EngineBuilder(m). 
            setEngineKind(EngineKind::JIT).create();
        void *f = ee->getPointerToFunction(func);
        typedef int (*func_t) (struct x *);
        struct x o = {10, NULL}, v = {};
        v.next = &o;
        std::cout << ((func_t)f)(&v) << std::endl;
    }
    return 0;
}
int main()
{
    // Module Construction
    LLVMContext &context = llvm::getGlobalContext();
    Module *module = new Module("test", context);

    //declare 'value' and 'foo' in module 'test'
    GlobalVariable *v = cast<GlobalVariable>(module->getOrInsertGlobal("value", Type::getInt32Ty(context)));
    // prototype of foo is: int foo(int x)
    Function *f = cast<Function>(module->getOrInsertFunction("foo", Type::getInt32Ty(context),
                                   Type::getInt32Ty(context), NULL));

    //create a LLVM function 'bar'
    Function* bar = cast<Function>(module->getOrInsertFunction("bar", Type::getInt32Ty(context),NULL));

    //basic block construction
    BasicBlock* entry = BasicBlock::Create(context, "entry", bar);
    IRBuilder<> builder(entry);

    //read 'value'
    Value * v_IR = builder.CreateLoad(v);
    //call foo(value)
    Value * ret = builder.CreateCall(f, v_IR);
    //return return value of 'foo'
    builder.CreateRet(ret);

    //now bind global value and global function
    //create execution engine first
    InitializeNativeTarget();
    ExecutionEngine *ee = EngineBuilder(module).setEngineKind(EngineKind::JIT).create();

    //map global variable
    ee->addGlobalMapping(v, &value);

    //map global function
    ee->addGlobalMapping(f, (void *)foo);

    // JIT and run
    void *barAddr = ee->getPointerToFunction(bar);
    typedef int (*FuncType)();
    FuncType barFunc = (FuncType)barAddr;

    std::cout << barFunc() << std::endl;
    return 0;
}
Пример #16
0
pair<int, string> execute( string input ){
	out = "";
	
	CodeGenerator * codeGen = new CodeGenerator();
	node_struct data;
	Node * ast = Node::createAST( data );
	makeLLVMModule( *ast );
	verifyModule( *theModule, PrintMessageAction );

	ExecutionEngine *ee = EngineBuilder( theModule ).create();
    Function* func = ee -> FindFunctionNamed("main");

    typedef int (*PFN)();
    PFN pfn = reinterpret_cast<PFN>(ee->getPointerToFunction(func));
    int result = pfn();

    //printf( "%s\n", out.c_str() );
    delete theModule;

    return make_pair( result, out );
}
Пример #17
0
void *MCJITHelper::getPointerToNamedFunction(const std::string &Name)
{
  // Look for the functions in our modules, compiling only as necessary
  ModuleVector::iterator begin = Modules.begin();
  ModuleVector::iterator end = Modules.end();
  ModuleVector::iterator it;
  for (it = begin; it != end; ++it) {
    Function *F = (*it)->getFunction(Name);
    if (F && !F->empty()) {
      std::map<Module*, ExecutionEngine*>::iterator eeIt = EngineMap.find(*it);
      if (eeIt != EngineMap.end()) {
        void *P = eeIt->second->getPointerToFunction(F);
        if (P)
          return P;
      } else {
        ExecutionEngine *EE = compileModule(*it);
        void *P = EE->getPointerToFunction(F);
        if (P)
          return P;
      }
    }
  }
  return NULL;
}
Пример #18
0
void *MCJITHelper::getPointerToFunction(Function* F) {
  // Look for this function in an existing module
  ModuleVector::iterator begin = Modules.begin();
  ModuleVector::iterator end = Modules.end();
  ModuleVector::iterator it;
  std::string FnName = F->getName();
  for (it = begin; it != end; ++it) {
    Function *MF = (*it)->getFunction(FnName);
    if (MF == F) {
      std::map<Module*, ExecutionEngine*>::iterator eeIt = EngineMap.find(*it);
      if (eeIt != EngineMap.end()) {
        void *P = eeIt->second->getPointerToFunction(F);
        if (P)
          return P;
      } else {
        ExecutionEngine *EE = compileModule(*it);
        void *P = EE->getPointerToFunction(F);
        if (P)
          return P;
      }
    }
  }
  return NULL;
}
Пример #19
0
bool CompiledCondition::compile(){
	InitializeNativeTarget();
	// Assume we're on main thread...
	LLVMContext &context = getGlobalContext();

	// Initialize module
	Module* module = new Module("Compiled function", context);

	// Create exection engine
	ExecutionEngine* engine = EngineBuilder(module).create();

	/********** Generate code **********/

	//Get a type for representing an integer pointer
	//Maybe this should be unsigned integer pointer type...
	PointerType* integerPointerType = PointerType::get(IntegerType::get(module->getContext(), 32), 0);

	//Create function type, for our function, int*, int* -> bool
	vector<const Type*> paramType;
	paramType.push_back(integerPointerType);
	paramType.push_back(integerPointerType);
	FunctionType* functionType = FunctionType::get(IntegerType::get(module->getContext(), 8), paramType, false);

	//Declare new function
	Function* function = Function::Create(functionType, GlobalValue::ExternalLinkage, "evaluate", module);
	//Use C calling convention
	function->setCallingConv(CallingConv::C);	//TODO: Read documentation and reconsider this

	//Get arguments from function
	Function::arg_iterator args = function->arg_begin();
	Value* marking = args++;
	Value* valuation = args++;
	marking->setName("marking");
	valuation->setName("valuation");

	//Create function block
	BasicBlock* functionBlock = BasicBlock::Create(module->getContext(), "functionBlock", function, 0);

	//Generate code
	CodeGenerationContext codeGenContext(marking, valuation, functionBlock, context);
	Value* result = _cond->codegen(codeGenContext);

	//Zero extend the result, e.g. make it a 8 bit bool
	CastInst* retval = new ZExtInst(result, IntegerType::get(module->getContext(), 8), "retval", functionBlock);

	//Create a return instruction
	ReturnInst::Create(module->getContext(), retval, functionBlock);

	/********** Optimize and Compile **********/

	// Create function pass manager, to optimize query
	FunctionPassManager optimizer(module);
	optimizer.add(new TargetData(*engine->getTargetData()));
	optimizer.add(createBasicAliasAnalysisPass());
	optimizer.add(createInstructionCombiningPass());
	optimizer.add(createReassociatePass());
	optimizer.add(createGVNPass());
	optimizer.add(createCFGSimplificationPass());
	optimizer.doInitialization();

	// Verify function, errors written to stderr
	if(verifyFunction(*function))
		return false;

	// Optimize function
	optimizer.run(*function);

	// Compile the function
	_nativeFunction = (bool(*)(const MarkVal*, const VarVal*))engine->getPointerToFunction(function);

	return _nativeFunction != NULL;
}
Пример #20
0
int main(int argc, char **argv)
{
  using namespace llvm;

  InitializeNativeTarget();

  LLVMContext context;
  SMDiagnostic error;

  Module *generic_module = ParseIR(MemoryBuffer::getMemBuffer(StringRef(mul_add_ir)), error, context);
  if(!generic_module)
  {
    std::cerr << "Error after first ParseIR" << std::endl;
    error.print(argv[0], errs());
    std::exit(-1);
  }

  // create a new module to hold the i32 specialization of generic_module
  Module module_i32(StringRef("module_i32"), context);

  // maps generic forms to their specializations
  ValueToValueMapTy vmap;

  specialize_declarations(context, generic_module, vmap, &module_i32);

  specialize_definitions(context, generic_module, vmap, &module_i32);

  Module *user_module = ParseIR(MemoryBuffer::getMemBuffer(StringRef(int_math_ir)), error, context);
  if(!user_module)
  {
    std::cerr << "Error after second ParseIR" << std::endl;
    error.print(argv[0], errs());
    std::exit(-1);
  }

  Linker ld(StringRef(argv[0]), StringRef("mul_add_prog"), context);

  std::string error_msg;
  if(ld.LinkInModule(&module_i32, &error_msg))
  {
    std::cerr << "Error after linkInModule(m1)" << std::endl;
    std::cerr << error_msg << std::endl;
    std::exit(-1);
  }

  if(ld.LinkInModule(user_module, &error_msg))
  {
    std::cerr << "Error after linkInModule(user_module)" << std::endl;
    std::cerr << error_msg << std::endl;
    std::exit(-1);
  }

  Module *composite = ld.releaseModule();

  composite->dump();

  ExecutionEngine *ee = ExecutionEngine::create(composite);

  Function *func = ee->FindFunctionNamed("mul_add");
  if(!func)
  {
    std::cerr << "Couldn't find mul_add" << std::endl;
    std::exit(-1);
  }

  std::cout << std::endl;

  typedef int (*fcn_ptr)(int,int,int);
  fcn_ptr mul_add = reinterpret_cast<fcn_ptr>(ee->getPointerToFunction(func));
  std::cout << "mul_add(1,2,3): " << mul_add(1,2,3) << std::endl;
  delete ee;

  return 0;
}
Пример #21
0
void
gen_and_load_llvm_code (mathmap_t *mathmap, char *template_filename, filter_code_t **filter_codes)
{
    MemoryBuffer *buffer = MemoryBuffer::getFile(template_filename, NULL);

    g_assert(buffer != NULL);

    Module *module = ParseBitcodeFile (buffer, NULL);
    int i;
    filter_t *filter;

    assert(module != NULL);
    delete buffer;

    for (i = 0, filter = mathmap->filters;
	 filter != 0;
	 ++i, filter = filter->next)
    {
	if (filter->kind != FILTER_MATHMAP)
	    continue;

	make_init_frame_function(module, filter);
	make_init_x_or_y_function(module, filter, init_x_function_name(filter));
	make_init_x_or_y_function(module, filter, init_y_function_name(filter));
	make_main_filter_function(module, filter);
	make_filter_function(module, filter);
    }

    for (i = 0, filter = mathmap->filters;
	 filter != 0;
	 ++i, filter = filter->next)
    {
	filter_code_t *code = filter_codes[i];
	code_emitter *emitter;

	if (filter->kind != FILTER_MATHMAP)
	    continue;

	g_assert(code->filter == filter);

	emitter = new code_emitter (module, filter, code);
	try
	{
	    emitter->emit_init_frame_function();
	    emitter->emit_filter_function();
	    emitter->emit_main_filter_funcs();
	}
	catch (compiler_error error)
	{
	    delete emitter;
	    delete module;

	    strcpy(error_string, error.info.c_str());
	    return;
	}
	delete emitter;
    }

    PassManager pm;

    pm.add(new TargetData(module));
    pm.add(createFunctionInliningPass());
    pm.add(createInstructionCombiningPass());
    pm.add(createReassociatePass());
    pm.add(createLowerSetJmpPass());
    pm.add(createRaiseAllocationsPass());
    pm.add(createGVNPass());
    pm.add(createCFGSimplificationPass());
    pm.add(createPromoteMemoryToRegisterPass());
    pm.add(createGlobalOptimizerPass());
    pm.add(createGlobalDCEPass());

    pm.run(*module);

#ifdef DEBUG_OUTPUT
    module->dump();

    verifyModule(*module, PrintMessageAction);
#endif

    ExecutionEngine *ee = ExecutionEngine::create (module);

    ee->InstallLazyFunctionCreator(lazy_creator);

    module_info_t *module_info = g_new0(module_info_t, 1);

    module_info->ee = ee;

    void *init_frame_fptr = ee->getPointerToFunction(lookup_init_frame_function(module, mathmap->main_filter));
    void *main_filter_fptr = ee->getPointerToFunction(lookup_main_filter_function(module, mathmap->main_filter));
    void *init_x_fptr = ee->getPointerToFunction(lookup_init_x_function(module, mathmap->main_filter));
    void *init_y_fptr = ee->getPointerToFunction(lookup_init_y_function(module, mathmap->main_filter));
    g_assert(main_filter_fptr && init_x_fptr && init_y_fptr);

    module_info->mathfuncs.llvm_init_frame_func = (llvm_init_frame_func_t)init_frame_fptr;
    module_info->mathfuncs.main_filter_func = (llvm_filter_func_t)main_filter_fptr;
    module_info->mathfuncs.init_x_func = (init_x_or_y_func_t)init_x_fptr;
    module_info->mathfuncs.init_y_func = (init_x_or_y_func_t)init_y_fptr;

    mathmap->module_info = module_info;

    mathmap->mathfuncs = &module_info->mathfuncs;
}
Пример #22
0
int main(int argc, char** argv){
  // verif M unit
#ifdef CORE_DBG
  verif_m_unit();
#endif

  if(argc < 2)
  {
    return 0;
  }

  Core *pCore = Core::start();
  pCore->init();
  COFF_parser parser(argv[1]);
  pCore->set_mode(BK_AT_MAIN);

  if(argc >= 3)
  {
    core_mode_t mode = (core_mode_t)strtoul(argv[2],NULL,10);
    pCore->set_mode(mode);
  }

  if(argc >= 4)
  {
    word_t thres = strtoul(argv[3],NULL,10);
    Profiler::set_jit_threshold_times(thres);
  }

  if(argc >= 5)
  {
    word_t thres = strtoul(argv[4],NULL,10);
    Profiler::set_jit_threshold_len(thres);
  }

  parser.connect(pCore);
  parser.set_reverse(false);
  parser.parse();
  
  pCore->init();
#if 0
  pCore->reg_write(0,0,2); // A0 = 2
  pCore->reg_write(1,0,3); // B0 = 3

  llvm::Function *func = llvm::cast<llvm::Function>(Core::get_llvm_module().getOrInsertFunction("func",
    Type::getInt32Ty(getGlobalContext()),(Type*)0));
  llvm::BasicBlock* bb = llvm::BasicBlock::Create(getGlobalContext(),"entry",func);
  Core::get_llvm_builder().SetInsertPoint(bb);
  llvm::Constant* a_side_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext())
    ,(uint64_t)pCore->get_reg_a());
  llvm::Constant* b_side_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext())
    ,(uint64_t)pCore->get_reg_b());
  llvm::Constant* dst_addr = llvm::ConstantInt::get(llvm::Type::getInt32Ty(getGlobalContext())
    ,(uint64_t)(pCore->get_reg_b()+1)); // B1
  llvm::Value* a_side = llvm::ConstantExpr::getIntToPtr(a_side_addr,
    llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext())));
  llvm::Value* b_side = llvm::ConstantExpr::getIntToPtr(b_side_addr,
    llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext())));

  llvm::Value* b1 = llvm::ConstantExpr::getIntToPtr(dst_addr,
    llvm::PointerType::getUnqual(llvm::Type::getInt32Ty(getGlobalContext())));

  llvm::Value* left = Core::get_llvm_builder().CreateLoad(a_side);
  llvm::Value* right = Core::get_llvm_builder().CreateLoad(b_side);
  llvm::Value* re = Core::get_llvm_builder().CreateAdd(left,right);
  Core::get_llvm_builder().CreateStore(re,b1,true);

  Core::get_llvm_builder().CreateRet(re);

  ExecutionEngine* EE = EngineBuilder(&Core::get_llvm_module()).create();

  // Call the `foo' function with no arguments:
  //std::vector<GenericValue> noargs;
  //GenericValue gv = EE->runFunction(func, noargs);
  void* FPtr = EE->getPointerToFunction(func);
  int (*FP)() = (int (*)())(intptr_t)FPtr;
  FP();

  // Import result of execution:
  std::cout << "Result: " << pCore->reg_read(B_SIDE,1) << "\n";
  //outs() << "re: " << gv.IntVal << "\n";
#endif

#if 0
  pCore->reg_write(A_SIDE,3,0xFF);
  de_func_t de_func = JIT::gen_su_de_32bit_1or2_src_shl_f2_nc(pCore,0x018d0ca0);

  c6x::Instruction inst;

  pCore->reg_ch_num = 1;
  de_func(pCore,&inst);
  pCore->step();

  std::cout << to_hex_str(pCore->reg_read(A_SIDE,3)) << "\n";

  system("pause");
#endif
  pCore->run();

  return 0;
} 
Пример #23
0
int main(int argc, char* argv[])
{
   if(argc < 2)
   {
      cerr << "Usage: " << argv[0] << " bf_file" << endl;
      return -1;
   }
   ifstream sourceFile(argv[1]);
   string line, source;
   while(getline(sourceFile, line)) source += line;

   // Setup a module and engine for JIT-ing
   std::string error;
   InitializeNativeTarget();

   Module* module = new Module("bfcode", getGlobalContext());

   InitializeNativeTarget();
   LLVMLinkInJIT();
   ExecutionEngine *engine = EngineBuilder(module)
      .setErrorStr(&error)
      .setOptLevel(CodeGenOpt::Aggressive)
      .create();
   if(!engine)
   {
      cout << "No engine created: " << error << endl;
      return -1;
   }

   module->setDataLayout(engine->getTargetData()->getStringRepresentation());

   // Compile the BF to IR
   cout << "Parsing… " << flush;
   Function* func = makeFunc(module, source.c_str());
   cout << "done" << endl;

   {
       ofstream dst("out.ll");
       raw_os_ostream rawdst(dst);
       rawdst << *module;
   }

   // Run optimization passes
   cout << "Optimizing… " << flush;

   PassManagerBuilder PMBuilder;

   FunctionPassManager pm(module);
   PMBuilder.populateFunctionPassManager(pm);
   pm.add(new TargetData(*(engine->getTargetData())));
   pm.add(createVerifierPass());

   // Eliminate simple loops such as [>>++<<-]
   pm.add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
   pm.add(createLICMPass());                 // Hoist loop invariants
   pm.add(createPromoteMemoryToRegisterPass());
   pm.add(createIndVarSimplifyPass());       // Canonicalize indvars
   pm.add(createLoopDeletionPass());         // Delete dead loops
   pm.add(createConstantPropagationPass());  // Propagate constants
   pm.add(new CondProp);                     // Propagate conditionals

   // Simplify code
   for(int repeat=0; repeat < 3; repeat++)
   {
      pm.add(createPromoteMemoryToRegisterPass());
      pm.add(createGVNPass());                  // Remove redundancies
      pm.add(createSCCPPass());                 // Constant prop with SCCP
      pm.add(createLoopDeletionPass());
      pm.add(createLoopUnrollPass());
      pm.add(createCFGSimplificationPass());    // Merge & remove BBs
      pm.add(createInstructionCombiningPass());
      pm.add(createConstantPropagationPass());  // Propagate constants
      pm.add(createAggressiveDCEPass());        // Delete dead instructions
      pm.add(createCFGSimplificationPass());    // Merge & remove BBs
      pm.add(createDeadStoreEliminationPass()); // Delete dead stores
      pm.add(createMemCpyOptPass());            // Combine multiple stores into memset's
      //pm.add(new PutCharAggregatePass);
   }

   pm.add(createPromoteMemoryToRegisterPass());

   // Process
   foreach (Function& f, *module)
       if (!f.isDeclaration)
           pm.run(f);

   PassManager pmm;

   PMBuilder.populateModulePassManager(pmm);
   pmm.add(createConstantMergePass());
   pmm.add(createGlobalOptimizerPass());
   pmm.add(createGlobalDCEPass());
   pmm.add(createIPConstantPropagationPass());
   pmm.run(*module);

   foreach (Function& f, *module)
       if (!f.isDeclaration)
           pm.run(f);
   pmm.run(*module);

   cout << "done" << endl;

   {
       ofstream dst("optout.ll");
       raw_os_ostream rawdst(dst);
       rawdst << *module;
   }

   // Compile …
   cout << "Compiling…" << flush;
   int (*bf)() = (int (*)())engine->getPointerToFunction(func);
   cout << " done" << endl;

   // … and run!
   return bf();
}
Пример #24
0
void *MCJITHelper::getPointerToFunction(Function* F) {
  // See if an existing instance of MCJIT has this function.
  EngineVector::iterator begin = Engines.begin();
  EngineVector::iterator end = Engines.end();
  EngineVector::iterator it;
  for (it = begin; it != end; ++it) {
    void *P = (*it)->getPointerToFunction(F);
    if (P)
      return P;
  }

  // If we didn't find the function, see if we can generate it.
  if (OpenModule) {
    std::string ErrStr;
    ExecutionEngine *NewEngine = EngineBuilder(OpenModule)
                                              .setErrorStr(&ErrStr)
                                              .setMCJITMemoryManager(new HelpingMemoryManager(this))
                                              .create();
    if (!NewEngine) {
      fprintf(stderr, "Could not create ExecutionEngine: %s\n", ErrStr.c_str());
      exit(1);
    }

    // Create a function pass manager for this engine
    FunctionPassManager *FPM = new FunctionPassManager(OpenModule);

    // Set up the optimizer pipeline.  Start with registering info about how the
    // target lays out data structures.
    FPM->add(new DataLayout(*NewEngine->getDataLayout()));
    // Provide basic AliasAnalysis support for GVN.
    FPM->add(createBasicAliasAnalysisPass());
    // Promote allocas to registers.
    FPM->add(createPromoteMemoryToRegisterPass());
    // Do simple "peephole" optimizations and bit-twiddling optzns.
    FPM->add(createInstructionCombiningPass());
    // Reassociate expressions.
    FPM->add(createReassociatePass());
    // Eliminate Common SubExpressions.
    FPM->add(createGVNPass());
    // Simplify the control flow graph (deleting unreachable blocks, etc).
    FPM->add(createCFGSimplificationPass());
    FPM->doInitialization();

    // For each function in the module
    Module::iterator it;
    Module::iterator end = OpenModule->end();
    for (it = OpenModule->begin(); it != end; ++it) {
      // Run the FPM on this function
      FPM->run(*it);
    }

    // We don't need this anymore
    delete FPM;

    OpenModule = NULL;
    Engines.push_back(NewEngine);
    NewEngine->finalizeObject();
    return NewEngine->getPointerToFunction(F);
  }
  return NULL;
}