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

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

Fix for first positional arg not a filename

File size: 9.8 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#include <sstream>
11
12#include <llvm/IR/Function.h>
13#include <llvm/IR/Module.h>
14#include <llvm/ExecutionEngine/ExecutionEngine.h>
15#include <llvm/ExecutionEngine/MCJIT.h>
16#include <llvm/IRReader/IRReader.h>
17#include <llvm/Support/CommandLine.h>
18#include <llvm/CodeGen/CommandFlags.h>
19#include <llvm/Support/SourceMgr.h>
20#include <llvm/Support/TargetSelect.h>
21#include <llvm/Support/Host.h>
22#include <llvm/Support/raw_ostream.h>
23
24// Dynamic processor detection
25#define ISPC_LLVM_VERSION ISPC_LLVM_3_6
26#include <util/ispc.cpp>
27
28#include <re/re_cc.h>
29#include <object_cache.h>
30
31static cl::OptionCategory bGrepOutputOptions("Output Options",
32                                      "These options control the output.");
33
34static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(bGrepOutputOptions));
35static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
36static cl::opt<bool> NormalizeLineBreaks("normalize-line-breaks", cl::desc("Normalize line breaks to std::endl."), cl::init(false),  cl::cat(bGrepOutputOptions));
37
38static cl::opt<bool> ShowFileNames("H", cl::desc("Show the file name with each matching line."), cl::cat(bGrepOutputOptions));
39static cl::alias ShowFileNamesLong("with-filename", cl::desc("Alias for -H"), cl::aliasopt(ShowFileNames));
40
41static cl::opt<bool> ShowLineNumbers("n", cl::desc("Show the line number with each matching line."), cl::cat(bGrepOutputOptions));
42static cl::alias ShowLineNumbersLong("line-number", cl::desc("Alias for -n"), cl::aliasopt(ShowLineNumbers));
43
44static cl::OptionCategory eIRDumpOptions("LLVM IR Dump Options", "These options control dumping of LLVM IR.");
45static cl::opt<bool> DumpGeneratedIR("dump-generated-IR", cl::init(false), cl::desc("Print LLVM IR generated by Pablo Compiler."), cl::cat(eIRDumpOptions));
46static cl::opt<std::string> IROutputFilename("dump-generated-IR-output", cl::init(""), cl::desc("output IR filename"), cl::cat(eIRDumpOptions));
47
48
49static cl::OptionCategory cMachineCodeOptimization("Machine Code Optimizations", "These options control back-end compilier optimization levels.");
50
51
52static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O1')"),
53                              cl::cat(cMachineCodeOptimization), cl::Prefix, cl::ZeroOrMore, cl::init('1'));
54
55
56static cl::OptionCategory cObjectCache("Object Caching", "These options control back-end object caching behaviours.");
57
58static cl::opt<bool> EnableObjectCache("enable-object-cache", cl::init(false), cl::desc("Enable object caching"), cl::cat(cObjectCache));
59
60static cl::opt<std::string> ObjectCacheDir("object-cache-dir", cl::init(""), cl::desc("Path to the object cache diretory"), cl::cat(cObjectCache));
61
62
63
64ExecutionEngine * JIT_to_ExecutionEngine (Module * m) {
65
66    InitializeNativeTarget();
67    InitializeNativeTargetAsmPrinter();
68    InitializeNativeTargetAsmParser();
69
70    PassRegistry * Registry = PassRegistry::getPassRegistry();
71    initializeCore(*Registry);
72    initializeCodeGen(*Registry);
73    initializeLowerIntrinsicsPass(*Registry);
74
75//    llvm::PassManager pm;
76//    pm.add(createBasicAliasAnalysisPass());
77//    pm.add(createEarlyCSEPass());
78//    pm.add(createPromoteMemoryToRegisterPass());
79//    pm.add(createInstructionCombiningPass());
80//    pm.add(createConstantPropagationPass());
81//    pm.add(createDeadCodeEliminationPass());
82//    pm.run(*m);
83
84    std::string errMessage;
85    EngineBuilder builder(std::move(std::unique_ptr<Module>(m)));
86    builder.setErrorStr(&errMessage);
87    builder.setMCPU(sys::getHostCPUName());
88    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
89    switch (OptLevel) {
90        case '0': optLevel = CodeGenOpt::None; break;
91        case '1': optLevel = CodeGenOpt::Less; break;
92        case '2': optLevel = CodeGenOpt::Default; break;
93        case '3': optLevel = CodeGenOpt::Aggressive; break;
94        default: errs() << OptLevel << " is an invalid optimization level.\n";
95    }
96    builder.setOptLevel(optLevel);
97
98    if ((strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
99        std::vector<std::string> attrs;
100        attrs.push_back("avx2");
101        builder.setMAttrs(attrs);
102    }
103    // builder.selectTarget();
104
105    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
106        if (IROutputFilename.empty()) {
107            m->dump();
108        } else {
109            std::error_code error;
110            llvm::raw_fd_ostream out(IROutputFilename, error, sys::fs::OpenFlags::F_None);
111            m->print(out, nullptr);
112        }
113    }
114
115    ExecutionEngine * engine = builder.create();
116    ICGrepObjectCache * cache = nullptr;
117    if (engine == nullptr) {
118        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
119    }
120    if (EnableObjectCache) {
121        if (ObjectCacheDir.empty())
122            // Default is $HOME/.cache/icgrep
123            cache = new ICGrepObjectCache();
124        else
125            cache = new ICGrepObjectCache(ObjectCacheDir);
126        engine->setObjectCache(cache);
127    }
128    return engine;
129}
130
131
132
133static int * total_count;
134static std::stringstream * resultStrs = nullptr;
135static std::vector<std::string> inputFiles;
136
137void initResult(std::vector<std::string> filenames, const int firstName, const int n){
138    if (n - firstName > 1) {
139        ShowFileNames = true;
140    }
141    inputFiles = filenames;
142    resultStrs = new std::stringstream[n];
143    total_count = new int[n];
144    for (int i=1; i<inputFiles.size(); i++){
145        total_count[i-1] = 0;
146    }
147
148}
149
150extern "C" {
151    void wrapped_report_match(uint64_t lineNum, uint64_t line_start, uint64_t line_end, const char * buffer, uint64_t filesize, char * filename) {
152
153        int idx = 0;
154        for (int i=1; i<inputFiles.size(); i++){
155            if (inputFiles[i] == filename){
156                idx = i-1;
157                break;
158            }
159        }
160
161        if(CountOnly){
162            total_count[idx]++;
163            return;
164        }
165
166        if (ShowFileNames) {
167            resultStrs[idx] << filename << ':';
168        }
169        if (ShowLineNumbers) {
170            resultStrs[idx] << lineNum << ":";
171        }
172
173        if ((buffer[line_start] == 0xA) && (line_start != line_end)) {
174            // The line "starts" on the LF of a CRLF.  Really the end of the last line.
175            line_start++;
176        }
177        if (line_end == filesize) {
178            // The match position is at end-of-file.   We have a final unterminated line.
179            resultStrs[idx].write(&buffer[line_start], line_end - line_start);
180            if (NormalizeLineBreaks) {
181                resultStrs[idx] << '\n';  // terminate it
182            }
183            return;
184        }
185        unsigned char end_byte = (unsigned char)buffer[line_end]; 
186        if (NormalizeLineBreaks) {
187            if (end_byte == 0x85) {
188                // Line terminated with NEL, on the second byte.  Back up 1.
189                line_end--;
190            } else if (end_byte > 0xD) {
191                // Line terminated with PS or LS, on the third byte.  Back up 2.
192                line_end -= 2;
193            }
194            resultStrs[idx].write(&buffer[line_start], line_end - line_start);
195            resultStrs[idx] << '\n';
196        }
197        else{   
198            if (end_byte == 0x0D) {
199                // Check for line_end on first byte of CRLF;  note that we don't
200                // want to access past the end of buffer.
201                if ((line_end + 1 < filesize) && (buffer[line_end + 1] == 0x0A)) {
202                    // Found CRLF; preserve both bytes.
203                    line_end++;
204                }
205            }
206            resultStrs[idx].write(&buffer[line_start], line_end - line_start + 1);
207        }
208    }
209}
210
211void PrintResult(){
212    if(CountOnly){
213        for (int i=1; i<inputFiles.size(); i++){
214            std::cout << total_count[i-1] << std::endl;
215        }
216        return;
217    }
218
219    std::string out;
220    for (int i=1; i<inputFiles.size(); i++){
221        std::cout << resultStrs[i-1].str();
222    }
223}
224
225re::CC * parsedCodePointSet;
226
227extern "C" {
228    void insert_codepoints(uint64_t lineNum, uint64_t line_start, uint64_t line_end, const char * buffer) {
229       re::codepoint_t c = 0;
230        ssize_t line_pos = line_start;
231        while (isxdigit(buffer[line_pos])) {
232            if (isdigit(buffer[line_pos])) {
233                c = (c << 4) | (buffer[line_pos] - '0');
234            }
235            else {
236                c = (c << 4) | (tolower(buffer[line_pos]) - 'a' + 10);
237            }
238            line_pos++;
239        }
240        assert(((line_pos - line_start) >= 4) && ((line_pos - line_start) <= 6)); // UCD format 4 to 6 hex digits.       
241        parsedCodePointSet->insert(c);
242    }
243}
244
245void setParsedCodePointSet(){
246    parsedCodePointSet = re::makeCC();
247}
248
249re::CC * getParsedCodePointSet(){
250    return parsedCodePointSet;
251}
252
253void icgrep_Linking(Module * m, ExecutionEngine * e) {
254    Module::FunctionListType & fns = m->getFunctionList();
255    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
256        std::string fnName = it->getName().str();
257        if (fnName == "s2p_block") continue;
258        if (fnName == "process_block") continue;
259        if (fnName == "process_block_initialize_carries") continue;
260       
261        if (fnName == "wrapped_report_match") {
262            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_report_match);
263        }
264        if (fnName == "insert_codepoints") {
265            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&insert_codepoints);
266        }
267#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
268        else {
269            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
270            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
271        }
272#endif
273    }
274}
Note: See TracBrowser for help on using the repository browser.