source: icGREP/icgrep-devel/icgrep/icgrep.cpp @ 4774

Last change on this file since 4774 was 4774, checked in by nmedfort, 4 years ago

Minor revisions.

File size: 16.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 "icgrep.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/SourceMgr.h>
20#include <llvm/Support/CommandLine.h>
21#include <llvm/Support/TargetSelect.h>
22#include <llvm/Support/Host.h>
23
24#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
25#include <UCD/precompiled_properties.h>
26#endif
27#include <re/re_cc.h>
28#include <re/re_nullable.h>
29#include <re/re_simplifier.h>
30#include <re/re_alt.h>
31#include <re/parsefailure.h>
32#include <re/re_parser.h>
33#include <re/re_compiler.h>
34#include <utf8_encoder.h>
35#include <cc/cc_compiler.h>
36#include <cc/cc_namemap.hpp>
37#include <pablo/pablo_compiler.h>
38#include <pablo/optimizers/pablo_simplifier.hpp>
39#include <pablo/optimizers/pablo_codesinking.hpp>
40#ifdef ENABLE_MULTIPLEXING
41#include <pablo/optimizers/pablo_automultiplexing.hpp>
42#include <pablo/optimizers/pablo_bddminimization.h>
43#include <pablo/optimizers/booleanreassociationpass.h>
44#endif
45#include <pablo/function.h>
46#include <re/printer_re.h>
47#include <pablo/printer_pablos.h>
48
49#include "do_grep.h"
50
51static cl::OptionCategory aRegexSourceOptions("Regular Expression Options",
52                                       "These options control the regular expression source.");
53
54static cl::OptionCategory bGrepOutputOptions("Output Options",
55                                      "These options control the output.");
56
57static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
58
59static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(bGrepOutputOptions));
60static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
61static cl::opt<bool> NormalizeLineBreaks("normalize-line-breaks", cl::desc("Normalize line breaks to std::endl."), cl::init(false),  cl::cat(bGrepOutputOptions));
62
63static cl::opt<bool> ShowFileNames("H", cl::desc("Show the file name with each matching line."), cl::cat(bGrepOutputOptions));
64static cl::alias ShowFileNamesLong("with-filename", cl::desc("Alias for -H"), cl::aliasopt(ShowFileNames));
65
66static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(aRegexSourceOptions));
67static cl::opt<bool> ShowLineNumbers("n", cl::desc("Show the line number with each matching line."), cl::cat(bGrepOutputOptions));
68static cl::alias ShowLineNumbersLong("line-number", cl::desc("Alias for -n"), cl::aliasopt(ShowLineNumbers));
69
70static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(aRegexSourceOptions));
71static cl::opt<std::string> RegexFilename("f", cl::desc("Take regular expressions (one per line) from a file"), cl::value_desc("regex file"), cl::init(""), cl::cat(aRegexSourceOptions));
72static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""), cl::cat(aRegexSourceOptions));
73
74static cl::OptionCategory cRegexOutputOptions("Regex Dump Options",
75                                      "These options control printing of intermediate regular expression structures.");
76
77static cl::OptionCategory dPabloDumpOptions("Pablo Dump Options",
78                                      "These options control printing of intermediate Pablo code.");
79
80static cl::opt<bool> PrintAllREs("print-REs", cl::init(false), cl::desc("print regular expression passes"), cl::cat(cRegexOutputOptions));
81static cl::opt<bool> PrintParsedREs("print-parsed-REs", cl::init(false), cl::desc("print out parsed regular expressions"), cl::cat(cRegexOutputOptions));
82static cl::opt<bool> PrintStrippedREs("print-stripped-REs", cl::init(false), cl::desc("print out REs with nullable prefixes/suffixes removed"), cl::cat(cRegexOutputOptions));
83static cl::opt<bool> PrintNamedREs("print-named-REs", cl::init(false), cl::desc("print out named REs"), cl::cat(cRegexOutputOptions));
84static cl::opt<bool> PrintUTF8REs("print-utf8-REs", cl::init(false), cl::desc("print out UTF-8 REs"), cl::cat(cRegexOutputOptions));
85static cl::opt<bool> PrintSimplifiedREs("print-simplified-REs", cl::init(false), cl::desc("print out final simplified REs"), cl::cat(cRegexOutputOptions));
86static cl::opt<bool> PrintCompiledCCcode("print-CC-pablo", cl::init(false), cl::desc("print Pablo output from character class compiler"), cl::cat(dPabloDumpOptions));
87static cl::opt<bool> PrintCompiledREcode("print-RE-pablo", cl::init(false), cl::desc("print Pablo output from the regular expression compiler"), cl::cat(dPabloDumpOptions));
88static cl::opt<bool> PrintOptimizedREcode("print-pablo", cl::init(false), cl::desc("print final optimized Pablo code"), cl::cat(dPabloDumpOptions));
89
90static cl::OptionCategory cPabloOptimizationsOptions("Pablo Optimizations", "These options control Pablo optimization passes.");
91
92static cl::opt<bool> DisablePabloCSE("disable-CSE", cl::init(false),
93                                      cl::desc("Disable Pablo common subexpression elimination/dead code elimination"),
94                                      cl::cat(cPabloOptimizationsOptions));
95static cl::opt<bool> PabloSinkingPass("sinking", cl::init(false),
96                                      cl::desc("Moves all instructions into the innermost legal If-scope so that they are only executed when needed."),
97                                      cl::cat(cPabloOptimizationsOptions));
98
99#ifdef ENABLE_MULTIPLEXING
100static cl::opt<bool> EnableMultiplexing("multiplexing", cl::init(false),
101    cl::desc("combine Advances whose inputs are mutual exclusive into the fewest number of advances possible (expensive)."),
102    cl::cat(cPabloOptimizationsOptions));
103#endif
104
105static cl::opt<bool> UseAVX2("use-AVX2", cl::init(false), cl::desc("execute with AVX2 instruction set."), cl::cat(cRegexOutputOptions));
106
107static unsigned firstInputFile = 1;  // Normal case when first positional arg is a regex.
108
109re::RE * get_icgrep_RE() {
110 
111    //std::vector<std::string> regexVector;
112    if (RegexFilename != "") {
113        std::ifstream regexFile(RegexFilename.c_str());
114        std::string r;
115        if (regexFile.is_open()) {
116            while (std::getline(regexFile, r)) {
117                regexVector.push_back(r);
118            }
119            regexFile.close();
120        }
121    }
122   
123    // if there are no regexes specified through -e or -f, the first positional argument
124    // must be a regex, not an input file.
125   
126    if (regexVector.size() == 0) {
127        regexVector.push_back(inputFiles[0]);
128        firstInputFile = 1;
129    }
130    else {
131        firstInputFile = 0;
132    }
133   
134    re::ModeFlagSet globalFlags = 0;
135    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
136
137 
138    std::vector<re::RE *> REs;
139    re::RE * re_ast = nullptr;
140    for (unsigned i = 0; i < regexVector.size(); i++) {
141        try
142        {
143            re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
144        }
145        catch (ParseFailure failure)
146        {
147            std::cerr << "Regex parsing failure: " << failure.what() << std::endl;
148            std::cerr << regexVector[i] << std::endl;
149            exit(1);
150        }
151        catch (UCD::UnicodePropertyExpressionError e)
152        {
153            std::cerr << "Unicode error: " << e.what() << std::endl;
154            std::cerr << regexVector[i] << std::endl;
155            exit(1);
156        }
157        REs.push_back(re_ast);
158    }
159    if (REs.size() > 1) {
160        re_ast = re::makeAlt(REs.begin(), REs.end());
161    }
162   
163    if (PrintAllREs || PrintParsedREs) {
164        std::cerr << "Parser:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
165    }
166    return re_ast;
167}
168
169re::RE * regular_expression_passes(const Encoding encoding, re::RE * re_ast)  {
170    //Optimization passes to simplify the AST.
171    re_ast = re::RE_Nullable::removeNullablePrefix(re_ast);
172    if (PrintAllREs || PrintStrippedREs) {
173        std::cerr << "RemoveNullablePrefix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
174    }
175    re_ast = re::RE_Nullable::removeNullableSuffix(re_ast);
176    if (PrintAllREs || PrintStrippedREs) {
177        std::cerr << "RemoveNullableSuffix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
178    }
179   
180    cc::CC_NameMap nameMap;
181    re_ast = nameMap.process(re_ast, re::UnicodeClass);
182   
183    // std::cerr << "-----------------------------" << std::endl;
184   
185    if (PrintAllREs || PrintNamedREs) {
186        std::cerr << "Namer:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
187        std::cerr << "NameMap:\n" << nameMap.printMap() << std::endl;
188    }
189   
190    //Add the UTF encoding.
191    if (encoding.getType() == Encoding::Type::UTF_8) {
192        re_ast = cc::UTF8_Encoder::toUTF8(nameMap, re_ast);
193        if (PrintAllREs || PrintUTF8REs) {
194            //Print to the terminal the AST that was generated by the utf8 encoder.
195            std::cerr << "UTF8-encoder:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
196            std::cerr << "NameMap:\n" << nameMap.printMap() << std::endl;
197        }
198    }
199   
200    re_ast = re::RE_Simplifier::simplify(re_ast);
201    if (PrintAllREs || PrintSimplifiedREs) {
202        //Print to the terminal the AST that was generated by the simplifier.
203        std::cerr << "Simplifier:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
204    }
205    return re_ast;
206}
207   
208pablo::PabloFunction * re2pablo_compiler(const Encoding encoding, re::RE * re_ast) {
209   
210    pablo::PabloFunction * function = pablo::PabloFunction::Create("process_block", 8, 2);
211   
212    cc::CC_Compiler cc_compiler(*function, encoding);
213   
214    cc_compiler.compileByteClasses(re_ast);
215   
216    if (PrintCompiledCCcode) {
217        //Print to the terminal the AST that was generated by the character class compiler.
218        llvm::raw_os_ostream cerr(std::cerr);
219        cerr << "CC AST:" << "\n";
220        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
221    }
222   
223    re::RE_Compiler re_compiler(*function, cc_compiler);
224    re_compiler.initializeRequiredStreams();
225    re_compiler.finalizeMatchResult(re_compiler.compile(re_ast));
226   
227    if (PrintCompiledREcode) {
228        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
229        llvm::raw_os_ostream cerr(std::cerr);
230        cerr << "Initial Pablo AST:\n";
231        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
232    }
233    return function;
234}
235
236void pablo_function_passes(pablo::PabloFunction * function) {
237    // Scan through the pablo code and perform DCE and CSE
238    if (!DisablePabloCSE) {
239        pablo::Simplifier::optimize(*function);
240    }
241    if (PabloSinkingPass) {
242        pablo::CodeSinking::optimize(*function);
243    }
244#ifdef ENABLE_MULTIPLEXING
245    pablo::BDDMinimizationPass::optimize(*function);
246//    if (EnableMultiplexing) {
247//        pablo::AutoMultiplexing::optimize(*function);
248//    }
249    pablo::BooleanReassociationPass::optimize(*function);
250#endif
251    if (PrintOptimizedREcode) {
252        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
253        llvm::raw_os_ostream cerr(std::cerr);
254        cerr << "Final Pablo AST:\n";
255        PabloPrinter::print(function->getEntryBlock().statements(), cerr);
256    }
257}
258
259
260
261ExecutionEngine * JIT_to_ExecutionEngine (llvm::Function * f) {
262
263    InitializeNativeTarget();
264    InitializeNativeTargetAsmPrinter();
265    InitializeNativeTargetAsmParser();
266
267    std::string errMessage;
268    EngineBuilder builder(std::move(std::unique_ptr<Module>(f->getParent())));
269    builder.setErrorStr(&errMessage);
270    builder.setMCPU(sys::getHostCPUName());
271    builder.setOptLevel(CodeGenOpt::Level::None);
272#if (BLOCK_SIZE == 256)
273    if(UseAVX2){
274            std::vector<std::string> attrs;
275            attrs.push_back("avx2");
276            builder.setMAttrs(attrs);
277    }
278#endif
279    //builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
280    ExecutionEngine * engine = builder.create();
281    if (engine == nullptr) {
282        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
283    }
284    //engine->addGlobalMapping(cast<GlobalValue>(mPrintRegisterFunction), (void *)&wrapped_print_register);
285    // engine->addGlobalMapping(externalFunction, proto->getFunctionPtr());
286
287    return engine;
288}
289
290
291extern "C" {
292  void wrapped_print_register(char * regName, BitBlock bit_block) {
293      print_register<BitBlock>(regName, bit_block);
294  }
295}
296
297void icgrep_Linking(Module * m, ExecutionEngine * e) {
298    Module::FunctionListType & fns = m->getFunctionList();
299    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
300        std::string fnName = it->getName().str();
301        if (fnName == "process_block") continue;
302        if (fnName == "wrapped_print_register") {
303            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_print_register);
304        }
305#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
306        else {
307            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
308            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
309        }
310#endif
311    }
312}
313
314
315int main(int argc, char *argv[]) {
316    StringMap<cl::Option*> Map;
317    cl::getRegisteredOptions(Map);
318    Map["time-passes"]->setHiddenFlag(cl::Hidden);
319    Map["disable-spill-fusing"]->setHiddenFlag(cl::Hidden);
320    Map["enable-misched"]->setHiddenFlag(cl::Hidden);
321    Map["enable-tbaa"]->setHiddenFlag(cl::Hidden);
322    Map["exhaustive-register-search"]->setHiddenFlag(cl::Hidden);
323    Map["join-liveintervals"]->setHiddenFlag(cl::Hidden);
324    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
325    Map["mc-x86-disable-arith-relaxation"]->setHiddenFlag(cl::Hidden);
326    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
327    Map["print-after-all"]->setHiddenFlag(cl::Hidden);
328    Map["print-before-all"]->setHiddenFlag(cl::Hidden);
329    Map["print-machineinstrs"]->setHiddenFlag(cl::Hidden);
330    Map["regalloc"]->setHiddenFlag(cl::Hidden);
331    Map["rng-seed"]->setHiddenFlag(cl::Hidden);
332    Map["stackmap-version"]->setHiddenFlag(cl::Hidden);
333    Map["x86-asm-syntax"]->setHiddenFlag(cl::Hidden);
334    Map["verify-debug-info"]->setHiddenFlag(cl::Hidden);
335    Map["verify-dom-info"]->setHiddenFlag(cl::Hidden);
336    Map["verify-loop-info"]->setHiddenFlag(cl::Hidden);
337    Map["verify-regalloc"]->setHiddenFlag(cl::Hidden);
338    Map["verify-scev"]->setHiddenFlag(cl::Hidden);
339    Map["x86-recip-refinement-steps"]->setHiddenFlag(cl::Hidden);
340    Map["rewrite-map-file"]->setHiddenFlag(cl::Hidden);
341
342    cl::ParseCommandLineOptions(argc, argv);
343   
344    Encoding encoding(Encoding::Type::UTF_8, 8);
345
346    llvm::Function * icgrep_IR = nullptr;
347   
348    if (IRFileName == "") {       
349        re::RE * re_ast = get_icgrep_RE();
350        re_ast = regular_expression_passes(encoding, re_ast);
351       
352        pablo::PabloFunction * function = re2pablo_compiler(encoding, re_ast);
353
354        pablo_function_passes(function);
355        pablo::PabloCompiler pablo_compiler;
356        try {
357            icgrep_IR = pablo_compiler.compile(function);
358            releaseSlabAllocatorMemory();
359        }
360        catch (std::runtime_error e) {
361            releaseSlabAllocatorMemory();
362            std::cerr << "Runtime error: " << e.what() << std::endl;
363            exit(1);
364        }
365    }
366    else {
367        firstInputFile = 0;  // No regexp arguments; first positional argument is a file to process.
368        SMDiagnostic ParseErr;
369        Module * M = parseIRFile(IRFileName, ParseErr, getGlobalContext()).release();
370        if (!M) {
371            throw std::runtime_error("Error in Parsing IR File " + IRFileName);
372        }
373        icgrep_IR = M->getFunction("process_block");
374    }
375   
376    llvm::ExecutionEngine * engine = JIT_to_ExecutionEngine(icgrep_IR);
377   
378    icgrep_Linking(icgrep_IR->getParent(), engine);
379   
380    // Ensure everything is ready to go.
381    engine->finalizeObject();
382   
383    void * icgrep_MCptr = engine->getPointerToFunction(icgrep_IR);
384   
385    if (icgrep_MCptr) {
386        GrepExecutor grepEngine = GrepExecutor(icgrep_MCptr);
387        grepEngine.setCountOnlyOption(CountOnly);
388        grepEngine.setNormalizeLineBreaksOption(NormalizeLineBreaks);
389        grepEngine.setShowLineNumberOption(ShowLineNumbers);
390            if (inputFiles.size() > (firstInputFile + 1) || ShowFileNames) {
391            grepEngine.setShowFileNameOption();
392        }
393        for (unsigned i = firstInputFile; i != inputFiles.size(); ++i) {
394            grepEngine.doGrep(inputFiles[i].c_str());
395        }
396    }
397   
398    //engine->freeMachineCodeForFunction(icgrep_IR); // This function only prints a "not supported" message. Reevaluate with LLVM 3.6.
399    delete engine;
400
401    return 0;
402}
403
Note: See TracBrowser for help on using the repository browser.