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

Last change on this file since 5023 was 5017, checked in by lindanl, 3 years ago

Passing file index instead of file name as internal state.

File size: 9.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#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    std::string errMessage;
76    EngineBuilder builder(std::move(std::unique_ptr<Module>(m)));
77    builder.setErrorStr(&errMessage);
78    builder.setMCPU(sys::getHostCPUName());
79    TargetOptions opts = InitTargetOptionsFromCodeGenFlags();
80    #ifndef NDEBUG
81    opts.JITEmitDebugInfo = 1;
82    #endif
83    builder.setTargetOptions(opts);
84    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
85    switch (OptLevel) {
86        case '0': optLevel = CodeGenOpt::None; break;
87        case '1': optLevel = CodeGenOpt::Less; break;
88        case '2': optLevel = CodeGenOpt::Default; break;
89        case '3': optLevel = CodeGenOpt::Aggressive; break;
90        default: errs() << OptLevel << " is an invalid optimization level.\n";
91    }
92    builder.setOptLevel(optLevel);
93
94    if ((strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
95        std::vector<std::string> attrs;
96        attrs.push_back("avx2");
97        builder.setMAttrs(attrs);
98    }
99    // builder.selectTarget();
100
101    if (LLVM_UNLIKELY(DumpGeneratedIR)) {
102        if (IROutputFilename.empty()) {
103            m->dump();
104        } else {
105            std::error_code error;
106            llvm::raw_fd_ostream out(IROutputFilename, error, sys::fs::OpenFlags::F_None);
107            m->print(out, nullptr);
108        }
109    }
110
111    ExecutionEngine * engine = builder.create();
112    ICGrepObjectCache * cache = nullptr;
113    if (engine == nullptr) {
114        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
115    }
116    if (EnableObjectCache) {
117        if (ObjectCacheDir.empty())
118            // Default is $HOME/.cache/icgrep
119            cache = new ICGrepObjectCache();
120        else
121            cache = new ICGrepObjectCache(ObjectCacheDir);
122        engine->setObjectCache(cache);
123    }
124    return engine;
125}
126
127
128
129static int * total_count;
130static std::stringstream * resultStrs = nullptr;
131static std::vector<std::string> inputFiles;
132
133void initResult(std::vector<std::string> filenames){
134    const int n = filenames.size();
135    if (n > 1) {
136        ShowFileNames = true;
137    }
138    inputFiles = filenames;
139    resultStrs = new std::stringstream[n];
140    total_count = new int[n];
141    for (int i=0; i<inputFiles.size(); i++){
142        total_count[i] = 0;
143    }
144
145}
146
147extern "C" {
148    void wrapped_report_match(uint64_t lineNum, uint64_t line_start, uint64_t line_end, const char * buffer, uint64_t filesize, int fileIdx) {
149
150        int idx = fileIdx;
151
152        if(CountOnly){
153            total_count[idx]++;
154            return;
155        }
156
157        if (ShowFileNames) {
158            resultStrs[idx] << inputFiles[idx] << ':';
159        }
160        if (ShowLineNumbers) {
161            resultStrs[idx] << lineNum << ":";
162        }
163
164        if ((buffer[line_start] == 0xA) && (line_start != line_end)) {
165            // The line "starts" on the LF of a CRLF.  Really the end of the last line.
166            line_start++;
167        }
168        if (line_end == filesize) {
169            // The match position is at end-of-file.   We have a final unterminated line.
170            resultStrs[idx].write(&buffer[line_start], line_end - line_start);
171            if (NormalizeLineBreaks) {
172                resultStrs[idx] << '\n';  // terminate it
173            }
174            return;
175        }
176        unsigned char end_byte = (unsigned char)buffer[line_end]; 
177        if (NormalizeLineBreaks) {
178            if (end_byte == 0x85) {
179                // Line terminated with NEL, on the second byte.  Back up 1.
180                line_end--;
181            } else if (end_byte > 0xD) {
182                // Line terminated with PS or LS, on the third byte.  Back up 2.
183                line_end -= 2;
184            }
185            resultStrs[idx].write(&buffer[line_start], line_end - line_start);
186            resultStrs[idx] << '\n';
187        }
188        else{   
189            if (end_byte == 0x0D) {
190                // Check for line_end on first byte of CRLF;  note that we don't
191                // want to access past the end of buffer.
192                if ((line_end + 1 < filesize) && (buffer[line_end + 1] == 0x0A)) {
193                    // Found CRLF; preserve both bytes.
194                    line_end++;
195                }
196            }
197            resultStrs[idx].write(&buffer[line_start], line_end - line_start + 1);
198        }
199    }
200}
201
202void PrintResult(){
203    if(CountOnly){
204        if (!ShowFileNames) {
205           for (int i=0; i<inputFiles.size(); i++){
206               std::cout << total_count[i] << std::endl;
207           }
208        }
209        else {
210            for (int i=0; i<inputFiles.size(); i++){
211                std::cout << inputFiles[i] << ':' << total_count[i] << std::endl;
212            };
213        }
214        return;
215    }
216
217    std::string out;
218    for (int i=0; i<inputFiles.size(); i++){
219        std::cout << resultStrs[i].str();
220    }
221}
222
223re::CC * parsedCodePointSet;
224
225extern "C" {
226    void insert_codepoints(uint64_t lineNum, uint64_t line_start, uint64_t line_end, const char * buffer) {
227       re::codepoint_t c = 0;
228        ssize_t line_pos = line_start;
229        while (isxdigit(buffer[line_pos])) {
230            if (isdigit(buffer[line_pos])) {
231                c = (c << 4) | (buffer[line_pos] - '0');
232            }
233            else {
234                c = (c << 4) | (tolower(buffer[line_pos]) - 'a' + 10);
235            }
236            line_pos++;
237        }
238        assert(((line_pos - line_start) >= 4) && ((line_pos - line_start) <= 6)); // UCD format 4 to 6 hex digits.       
239        parsedCodePointSet->insert(c);
240    }
241}
242
243void setParsedCodePointSet(){
244    parsedCodePointSet = re::makeCC();
245}
246
247re::CC * getParsedCodePointSet(){
248    return parsedCodePointSet;
249}
250
251void icgrep_Linking(Module * m, ExecutionEngine * e) {
252    Module::FunctionListType & fns = m->getFunctionList();
253    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
254        std::string fnName = it->getName().str();
255        if (fnName == "s2p_block") continue;
256        if (fnName == "process_block") continue;
257        if (fnName == "process_block_initialize_carries") continue;
258       
259        if (fnName == "wrapped_report_match") {
260            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_report_match);
261        }
262        if (fnName == "insert_codepoints") {
263            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&insert_codepoints);
264        }
265#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
266        else {
267            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
268            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
269        }
270#endif
271    }
272}
Note: See TracBrowser for help on using the repository browser.