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

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

Work on lowering + minor bug fixes.

File size: 11.7 KB
Line 
1/*
2 *  Copyright (c) 2015 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
11#include "basis_bits.h"
12#include "utf_encoding.h"
13#include "pablo/pablo_compiler.h"
14#include <llvm/IR/Function.h>
15#include <llvm/IR/Module.h>
16#include <llvm/ExecutionEngine/ExecutionEngine.h>
17#include <llvm/ExecutionEngine/MCJIT.h>
18#include <llvm/IRReader/IRReader.h>
19#include <llvm/Support/CommandLine.h>
20#include <llvm/CodeGen/CommandFlags.h>
21#include <llvm/Support/SourceMgr.h>
22#include <llvm/Support/TargetSelect.h>
23#include <llvm/Support/Host.h>
24
25#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
26#include <UCD/precompiled_properties.h>
27#endif
28#include <re/re_cc.h>
29#include <re/re_nullable.h>
30#include <re/re_simplifier.h>
31#include <re/re_alt.h>
32#include <re/parsefailure.h>
33#include <re/re_parser.h>
34#include <re/re_compiler.h>
35#include <utf8_encoder.h>
36#include <cc/cc_compiler.h>
37#include <pablo/pablo_compiler.h>
38#include <pablo/optimizers/pablo_simplifier.hpp>
39#include <pablo/optimizers/codemotionpass.h>
40#include <pablo/passes/flattenassociativedfg.h>
41#include <pablo/passes/factorizedfg.h>
42#ifdef ENABLE_MULTIPLEXING
43#include <pablo/optimizers/pablo_automultiplexing.hpp>
44#include <pablo/optimizers/pablo_bddminimization.h>
45#include <pablo/optimizers/distributivepass.h>
46#include <pablo/optimizers/schedulingprepass.h>
47#endif
48#include <pablo/function.h>
49#include <pablo/analysis/pabloverifier.hpp>
50#include <re/printer_re.h>
51#include <pablo/printer_pablos.h>
52
53#include "do_grep.h"
54
55using namespace pablo;
56
57static cl::OptionCategory cRegexOutputOptions("Regex Dump Options",
58                                              "These options control printing of intermediate regular expression structures.");
59static cl::opt<bool> PrintAllREs("print-REs", cl::init(false), cl::desc("print regular expression passes"), cl::cat(cRegexOutputOptions));
60static cl::opt<bool> PrintParsedREs("print-parsed-REs", cl::init(false), cl::desc("print out parsed regular expressions"), cl::cat(cRegexOutputOptions));
61static cl::opt<bool> PrintStrippedREs("print-stripped-REs", cl::init(false), cl::desc("print out REs with nullable prefixes/suffixes removed"), cl::cat(cRegexOutputOptions));
62static cl::opt<bool> PrintNamedREs("print-named-REs", cl::init(false), cl::desc("print out named REs"), cl::cat(cRegexOutputOptions));
63static cl::opt<bool> PrintUTF8REs("print-utf8-REs", cl::init(false), cl::desc("print out UTF-8 REs"), cl::cat(cRegexOutputOptions));
64static cl::opt<bool> PrintSimplifiedREs("print-simplified-REs", cl::init(false), cl::desc("print out final simplified REs"), cl::cat(cRegexOutputOptions));
65static cl::OptionCategory dPabloDumpOptions("Pablo Dump Options",
66                                            "These options control printing of intermediate Pablo code.");
67
68static cl::opt<bool> PrintOptimizedREcode("print-pablo", cl::init(false), cl::desc("print final optimized Pablo code"), cl::cat(dPabloDumpOptions));
69static cl::opt<bool> PrintCompiledCCcode("print-CC-pablo", cl::init(false), cl::desc("print Pablo output from character class compiler"), cl::cat(dPabloDumpOptions));
70static cl::opt<bool> PrintCompiledREcode("print-RE-pablo", cl::init(false), cl::desc("print Pablo output from the regular expression compiler"), cl::cat(dPabloDumpOptions));
71
72static cl::OptionCategory cPabloOptimizationsOptions("Pablo Optimizations", "These options control Pablo optimization passes.");
73
74static cl::opt<bool> DisablePabloCSE("disable-CSE", cl::init(false),
75                                     cl::desc("Disable Pablo common subexpression elimination/dead code elimination"),
76                                     cl::cat(cPabloOptimizationsOptions));
77static cl::opt<bool> PabloSinkingPass("sinking", cl::init(false),
78                                      cl::desc("Moves all instructions into the innermost legal If-scope so that they are only executed when needed."),
79                                      cl::cat(cPabloOptimizationsOptions));
80
81#ifdef ENABLE_MULTIPLEXING
82static cl::opt<bool> PrintUnloweredCode("print-unlowered-pablo", cl::init(false), cl::desc("print Pablo output prior to lowering. "), cl::cat(dPabloDumpOptions));
83
84static cl::opt<bool> EnableMultiplexing("multiplexing", cl::init(false),
85                                        cl::desc("combine Advances whose inputs are mutual exclusive into the fewest number of advances possible (expensive)."),
86                                        cl::cat(cPabloOptimizationsOptions));
87
88static cl::opt<unsigned> MultiplexingSetLimit("multiplexing-set-limit", cl::init(std::numeric_limits<unsigned>::max()),
89                                        cl::desc("maximum size of any candidate multiplexing set."),
90                                        cl::cat(cPabloOptimizationsOptions));
91static cl::opt<unsigned> MultiplexingSelectionLimit("multiplexing-selection-limit", cl::init(100),
92                                        cl::desc("maximum number of selections from any partial candidate multiplexing set."),
93                                        cl::cat(cPabloOptimizationsOptions));
94static cl::opt<unsigned> MultiplexingWindowSize("multiplexing-window-size", cl::init(1),
95                                        cl::desc("maximum depth difference for computing mutual exclusion of Advance nodes."),
96                                        cl::cat(cPabloOptimizationsOptions));
97
98static cl::opt<bool> EnableLowering("lowering", cl::init(false),
99                                         cl::desc("coalesce associative functions prior to optimization passes."),
100                                         cl::cat(cPabloOptimizationsOptions));
101static cl::opt<bool> EnablePreDistribution("pre-dist", cl::init(false),
102                                         cl::desc("apply distribution law optimization."),
103                                         cl::cat(cPabloOptimizationsOptions));
104static cl::opt<bool> EnablePostDistribution("post-dist", cl::init(false),
105                                         cl::desc("apply distribution law optimization."),
106                                         cl::cat(cPabloOptimizationsOptions));
107#endif
108
109static cl::opt<bool> DisableAVX2("disable-AVX2", cl::init(false), cl::desc("disable AVX2 instruction set."), cl::cat(cPabloOptimizationsOptions));
110
111re::RE * regular_expression_passes(const Encoding encoding, re::RE * re_ast)  {
112    if (PrintAllREs || PrintParsedREs) {
113        std::cerr << "Parser:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
114    }
115
116    //Optimization passes to simplify the AST.
117    re_ast = re::RE_Nullable::removeNullablePrefix(re_ast);
118    if (PrintAllREs || PrintStrippedREs) {
119        std::cerr << "RemoveNullablePrefix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
120    }
121    re_ast = re::RE_Nullable::removeNullableSuffix(re_ast);
122    if (PrintAllREs || PrintStrippedREs) {
123        std::cerr << "RemoveNullableSuffix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
124    }
125
126    re_ast = re::RE_Simplifier::simplify(re_ast);
127    if (PrintAllREs || PrintSimplifiedREs) {
128        //Print to the terminal the AST that was generated by the simplifier.
129        std::cerr << "Simplifier:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
130    }
131    return re_ast;
132}
133   
134PabloFunction * re2pablo_compiler(const Encoding encoding, re::RE * re_ast) {
135    PabloFunction * function = PabloFunction::Create("process_block", 8, 2);
136    cc::CC_Compiler cc_compiler(*function, encoding);
137    re::RE_Compiler re_compiler(*function, cc_compiler);
138    re_compiler.initializeRequiredStreams();
139    re_compiler.compileUnicodeNames(re_ast);
140    re_compiler.finalizeMatchResult(re_compiler.compile(re_ast));
141
142    if (PrintCompiledREcode) {
143        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
144        llvm::raw_os_ostream cerr(std::cerr);
145        cerr << "Initial Pablo AST:\n";
146        PabloPrinter::print(*function, cerr);
147    }
148    #ifndef NDEBUG
149    PabloVerifier::verify(*function, "creation");
150    #endif
151    return function;
152}
153
154void pablo_function_passes(PabloFunction * function) {
155    // Scan through the pablo code and perform DCE and CSE
156    if (!DisablePabloCSE) {
157        Simplifier::optimize(*function);
158    }
159#ifdef ENABLE_MULTIPLEXING
160    if (EnableLowering || EnablePreDistribution || EnablePostDistribution || EnableMultiplexing) {
161        FlattenAssociativeDFG::transform(*function);
162    }
163#endif
164    if (PabloSinkingPass) {
165        CodeMotionPass::optimize(*function);
166    }
167#ifdef ENABLE_MULTIPLEXING   
168    if (EnablePreDistribution) {
169        DistributivePass::optimize(*function);
170    }
171    if (EnableMultiplexing) {
172        MultiplexingPass::optimize(*function, MultiplexingSetLimit, MultiplexingSelectionLimit, MultiplexingWindowSize);
173    }
174    if (EnablePostDistribution) {
175        DistributivePass::optimize(*function);
176    }
177    SchedulingPrePass::optimize(*function);
178    if (PrintUnloweredCode) {
179        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
180        llvm::raw_os_ostream cerr(std::cerr);
181        cerr << "Unlowered Pablo AST:\n";
182        PabloPrinter::print(*function, cerr);
183    }
184    if (EnableLowering || EnablePreDistribution || EnablePostDistribution || EnableMultiplexing) {
185        FactorizeDFG::transform(*function);
186    }
187#endif
188    if (PrintOptimizedREcode) {
189        PabloVerifier::verify(*function, "post-optimization");
190        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
191        llvm::raw_os_ostream cerr(std::cerr);
192        cerr << "Final Pablo AST:\n";
193        PabloPrinter::print(*function, cerr);
194    }
195}
196
197// Dynamic AVX2 confirmation
198#if (BLOCK_SIZE == 256)
199#define ISPC_LLVM_VERSION ISPC_LLVM_3_6
200#include "ispc.cpp"
201#endif
202
203
204ExecutionEngine * JIT_to_ExecutionEngine (llvm::Function * f) {
205
206    InitializeNativeTarget();
207    InitializeNativeTargetAsmPrinter();
208    InitializeNativeTargetAsmParser();
209
210    std::string errMessage;
211    EngineBuilder builder(std::move(std::unique_ptr<Module>(f->getParent())));
212    builder.setErrorStr(&errMessage);
213    builder.setMCPU(sys::getHostCPUName());
214    builder.setOptLevel(CodeGenOpt::Level::None);
215
216#if (BLOCK_SIZE == 256)
217    if (!DisableAVX2 && (strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
218            std::vector<std::string> attrs;
219            attrs.push_back("avx2");
220            builder.setMAttrs(attrs);
221    //std::cerr << "+avx2 set" << std::endl;
222    }
223#endif
224    //builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
225    ExecutionEngine * engine = builder.create();
226    if (engine == nullptr) {
227        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
228    }
229    //engine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
230    // engine->addGlobalMapping(externalFunction, proto->getFunctionPtr());
231
232    return engine;
233}
234
235
236extern "C" {
237  void wrapped_print_register(char * regName, BitBlock bit_block) {
238      print_register<BitBlock>(regName, bit_block);
239  }
240}
241
242void icgrep_Linking(Module * m, ExecutionEngine * e) {
243    Module::FunctionListType & fns = m->getFunctionList();
244    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
245        std::string fnName = it->getName().str();
246        if (fnName == "process_block") continue;
247        if (fnName == "process_block_initialize_carries") continue;
248        if (fnName == "wrapped_print_register") {
249            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_print_register);
250        }
251#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
252        else {
253            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
254            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
255        }
256#endif
257    }
258}
259
Note: See TracBrowser for help on using the repository browser.