1 //===-- LlvmState.cpp -------------------------------------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "LlvmState.h"
11 #include "Target.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/MC/MCCodeEmitter.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCFixup.h"
16 #include "llvm/MC/MCObjectFileInfo.h"
17 #include "llvm/Support/TargetRegistry.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetOptions.h"
21
22 namespace exegesis {
23
LLVMState(const std::string & Triple,const std::string & CpuName)24 LLVMState::LLVMState(const std::string &Triple, const std::string &CpuName) {
25 std::string Error;
26 const llvm::Target *const TheTarget =
27 llvm::TargetRegistry::lookupTarget(Triple, Error);
28 assert(TheTarget && "unknown target for host");
29 const llvm::TargetOptions Options;
30 TargetMachine.reset(static_cast<llvm::LLVMTargetMachine *>(
31 TheTarget->createTargetMachine(Triple, CpuName, /*Features*/ "", Options,
32 llvm::Reloc::Model::Static)));
33 TheExegesisTarget = ExegesisTarget::lookup(TargetMachine->getTargetTriple());
34 if (!TheExegesisTarget) {
35 llvm::errs() << "no exegesis target for " << Triple << ", using default\n";
36 TheExegesisTarget = &ExegesisTarget::getDefault();
37 }
38 }
39
LLVMState()40 LLVMState::LLVMState()
41 : LLVMState(llvm::sys::getProcessTriple(),
42 llvm::sys::getHostCPUName().str()) {}
43
44 std::unique_ptr<llvm::LLVMTargetMachine>
createTargetMachine() const45 LLVMState::createTargetMachine() const {
46 return std::unique_ptr<llvm::LLVMTargetMachine>(
47 static_cast<llvm::LLVMTargetMachine *>(
48 TargetMachine->getTarget().createTargetMachine(
49 TargetMachine->getTargetTriple().normalize(),
50 TargetMachine->getTargetCPU(),
51 TargetMachine->getTargetFeatureString(), TargetMachine->Options,
52 llvm::Reloc::Model::Static)));
53 }
54
canAssemble(const llvm::MCInst & Inst) const55 bool LLVMState::canAssemble(const llvm::MCInst &Inst) const {
56 llvm::MCObjectFileInfo ObjectFileInfo;
57 llvm::MCContext Context(TargetMachine->getMCAsmInfo(),
58 TargetMachine->getMCRegisterInfo(), &ObjectFileInfo);
59 std::unique_ptr<const llvm::MCCodeEmitter> CodeEmitter(
60 TargetMachine->getTarget().createMCCodeEmitter(
61 *TargetMachine->getMCInstrInfo(), *TargetMachine->getMCRegisterInfo(),
62 Context));
63 llvm::SmallVector<char, 16> Tmp;
64 llvm::raw_svector_ostream OS(Tmp);
65 llvm::SmallVector<llvm::MCFixup, 4> Fixups;
66 CodeEmitter->encodeInstruction(Inst, OS, Fixups,
67 *TargetMachine->getMCSubtargetInfo());
68 return Tmp.size() > 0;
69 }
70
71 } // namespace exegesis
72