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

Last change on this file since 5305 was 5295, checked in by cameron, 3 years ago

Debug Options: SerializeThreads?; unify ShowIR, ShowPablo?, ShowREs, ShowASM

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