source: icGREP/icgrep-devel/icgrep/toolchain.cpp @ 5156

Last change on this file since 5156 was 5156, checked in by nmedfort, 3 years ago

Work on multiplexing and distribution passes + a few AST modification bug fixes.

File size: 7.1 KB
Line 
1/*
2 *  Copyright (c) 2016 International Characters.
3 *  This software is licensed to the public under the Open Software License 3.0.
4 *  icgrep is a trademark of International Characters.
5 */
6
7#include <string>
8#include <iostream>
9#include <fstream>
10#include <sstream>
11
12#include <toolchain.h>
13#include <llvm/IR/Function.h>
14#include <llvm/IR/Module.h>
15#include <llvm/ExecutionEngine/ExecutionEngine.h>
16#include <llvm/ExecutionEngine/MCJIT.h>
17#include "llvm/IR/LegacyPassManager.h"
18
19#include <llvm/IRReader/IRReader.h>
20#include <llvm/Support/CommandLine.h>
21#include <llvm/CodeGen/CommandFlags.h>
22#include <llvm/Support/SourceMgr.h>
23#include <llvm/Support/TargetSelect.h>
24#include <llvm/Support/Host.h>
25#include <llvm/Support/raw_ostream.h>
26
27#include <object_cache.h>
28#include <IDISA/llvm2ptx.h>
29 
30using namespace llvm;
31
32namespace codegen {
33
34static cl::OptionCategory CodeGenOptions("Code Generation Options", "These options control code generation.");
35
36
37static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(CodeGenOptions));
38static cl::opt<std::string> IROutputFilename("dump-generated-IR-output", cl::init(""), cl::desc("output IR filename"), cl::cat(CodeGenOptions));
39static cl::opt<bool> DumpASM("DumpASM", cl::init(false), cl::desc("Print Assembly Code."), cl::cat(CodeGenOptions));
40static cl::opt<std::string> ASMOutputFilename("asm-output", cl::init(""), cl::desc("output ASM filename"), cl::cat(CodeGenOptions));
41static cl::opt<bool> AsmVerbose("asm-verbose",
42                                cl::desc("Add comments to directives."),
43                                cl::init(true), cl::cat(CodeGenOptions));
44
45char OptLevel;
46static cl::opt<char, true> OptLevelOption("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O1')"), cl::location(OptLevel),
47                              cl::cat(CodeGenOptions), cl::Prefix, cl::ZeroOrMore, cl::init('1'));
48
49
50static cl::opt<bool> EnableObjectCache("enable-object-cache", cl::init(false), cl::desc("Enable object caching"), cl::cat(CodeGenOptions));
51
52static cl::opt<std::string> ObjectCacheDir("object-cache-dir", cl::init(""), cl::desc("Path to the object cache diretory"), cl::cat(CodeGenOptions));
53
54
55int BlockSize;
56int SegmentSize;
57int BufferSegments;
58
59static cl::opt<int, true> BlockSizeOption("BlockSize", cl::location(BlockSize), cl::init(0), cl::desc("specify a block size (defaults to widest SIMD register width in bits)."), cl::cat(CodeGenOptions));
60static cl::opt<int, true> SegmentSizeOption("segment-size", cl::location(SegmentSize), cl::desc("Segment Size"), cl::value_desc("positive integer"), cl::init(1));
61static cl::opt<int, true> BufferSegmentsOption("buffer-segments", cl::location(BufferSegments), cl::desc("Buffer Segments"), cl::value_desc("positive integer"), cl::init(1));
62
63const cl::OptionCategory * codegen_flags() {return &CodeGenOptions;}
64
65#ifdef CUDA_ENABLED
66bool NVPTX;
67static cl::opt<bool> USENVPTX("NVPTX", cl::desc("Run on GPU only."), cl::init(false));
68#endif
69
70}
71
72
73#ifdef CUDA_ENABLED
74void setNVPTXOption(){
75    codegen::NVPTX = codegen::USENVPTX;
76}
77
78void Compile2PTX (Module * m, std::string IRFilename, std::string PTXFilename) {
79    InitializeAllTargets();
80    InitializeAllTargetMCs();
81    InitializeAllAsmPrinters();
82    InitializeAllAsmParsers();
83
84    PassRegistry *Registry = PassRegistry::getPassRegistry();
85    initializeCore(*Registry);
86    initializeCodeGen(*Registry);
87    initializeLoopStrengthReducePass(*Registry);
88    initializeLowerIntrinsicsPass(*Registry);
89    initializeUnreachableBlockElimPass(*Registry);
90
91    std::error_code error;
92    llvm::raw_fd_ostream out(IRFilename, error, sys::fs::OpenFlags::F_None);
93    m->print(out, nullptr);
94
95    if (LLVM_UNLIKELY(codegen::DumpGeneratedIR))
96            m->dump();
97
98    llvm2ptx(IRFilename, PTXFilename);
99}
100#endif
101
102
103void setAllFeatures(EngineBuilder &builder) {
104    llvm::StringMap<bool> HostCPUFeatures;
105    if (llvm::sys::getHostCPUFeatures(HostCPUFeatures)) {
106        std::vector<std::string> attrs;
107        for (auto &flag : HostCPUFeatures) {
108            auto enabled = flag.second ? "+" : "-";
109            attrs.push_back(enabled + flag.first().str());
110        }
111        builder.setMAttrs(attrs);
112    }
113}
114
115bool AVX2_available() {
116    llvm::StringMap<bool> HostCPUFeatures;
117    if (llvm::sys::getHostCPUFeatures(HostCPUFeatures)) {
118        auto f = HostCPUFeatures.find("avx2");
119        return ((f != HostCPUFeatures.end()) && f->second);
120    }
121    return false;
122}
123
124
125void WriteAssembly (llvm::TargetMachine *TM, Module * m) {
126    llvm::legacy::PassManager PM;
127
128    llvm::SmallString<128> Str;
129    llvm::raw_svector_ostream dest(Str);
130
131    if (TM->addPassesToEmitFile(PM, dest, llvm::TargetMachine::CGFT_AssemblyFile ) ) {
132        throw std::runtime_error("LLVM error: addPassesToEmitFile failed.");
133    }
134    PM.run(*m);
135
136    if (codegen::ASMOutputFilename.empty()) {
137        errs() << Str;
138    } else {
139        std::error_code error;
140        llvm::raw_fd_ostream out(codegen::ASMOutputFilename, error, sys::fs::OpenFlags::F_None);
141        out << Str;
142    }
143}
144
145ExecutionEngine * JIT_to_ExecutionEngine (Module * m) {
146
147    InitializeNativeTarget();
148    InitializeNativeTargetAsmPrinter();
149    InitializeNativeTargetAsmParser();
150
151    PassRegistry * Registry = PassRegistry::getPassRegistry();
152    initializeCore(*Registry);
153    initializeCodeGen(*Registry);
154    initializeLowerIntrinsicsPass(*Registry);
155
156    std::string errMessage;
157    EngineBuilder builder{std::unique_ptr<Module>(m)};
158    builder.setErrorStr(&errMessage);
159    TargetOptions opts = InitTargetOptionsFromCodeGenFlags();
160    opts.MCOptions.AsmVerbose = codegen::AsmVerbose;
161
162    builder.setTargetOptions(opts);
163    builder.setVerifyModules(true);
164    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
165    switch (codegen::OptLevel) {
166        case '0': optLevel = CodeGenOpt::None; break;
167        case '1': optLevel = CodeGenOpt::Less; break;
168        case '2': optLevel = CodeGenOpt::Default; break;
169        case '3': optLevel = CodeGenOpt::Aggressive; break;
170        default: errs() << codegen::OptLevel << " is an invalid optimization level.\n";
171    }
172    builder.setOptLevel(optLevel);
173
174    setAllFeatures(builder);
175
176    if (LLVM_UNLIKELY(codegen::DumpGeneratedIR)) {
177        if (codegen::IROutputFilename.empty()) {
178            m->dump();
179        } else {
180            std::error_code error;
181            llvm::raw_fd_ostream out(codegen::IROutputFilename, error, sys::fs::OpenFlags::F_None);
182            m->print(out, nullptr);
183        }
184    }
185
186    if (codegen::DumpASM) {
187      WriteAssembly(builder.selectTarget(), m);
188    }
189    ExecutionEngine * engine = builder.create();
190    if (engine == nullptr) {
191        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
192    }   
193    return engine;
194}
195
196void ApplyObjectCache(ExecutionEngine * e) {
197    ICGrepObjectCache * cache = nullptr;
198    if (codegen::EnableObjectCache) {
199        if (codegen::ObjectCacheDir.empty())
200            // Default is $HOME/.cache/icgrep
201            cache = new ICGrepObjectCache();
202        else
203            cache = new ICGrepObjectCache(codegen::ObjectCacheDir);
204        e->setObjectCache(cache);
205    }   
206}
207
208
Note: See TracBrowser for help on using the repository browser.