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

Last change on this file since 5025 was 5025, checked in by xuedongx, 3 years ago

If '-c', ignore the scanmatch kernel.

File size: 9.5 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 <cstdio>
8#include <vector>
9#include <llvm/Support/CommandLine.h>
10#include <re/re_alt.h>
11#include <re/re_parser.h>
12#include <grep_engine.h>
13#include <fstream>
14#include <string>
15
16#include <boost/uuid/sha1.hpp>
17#include <toolchain.h>
18#include <mutex>
19
20#include <iostream> // MEEE
21static cl::OptionCategory CountOnlyOptions("CountOnly Option",
22                                       "This option controls the output.");
23static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(CountOnlyOptions));
24static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
25
26static cl::OptionCategory aRegexSourceOptions("Regular Expression Options",
27                                       "These options control the regular expression source.");
28
29static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
30
31static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(aRegexSourceOptions));
32
33
34static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(aRegexSourceOptions));
35static 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));
36static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""), cl::cat(aRegexSourceOptions));
37
38static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(1));
39
40static cl::opt<bool> GrepSupport("gs", cl::desc("Grep support. Pipe the output of icgrep into grep. \
41         Gives you colored output + back-referencing capability."), cl::cat(aRegexSourceOptions));
42
43
44static std::string allREs;
45static re::ModeFlagSet globalFlags = 0;
46
47re::RE * get_icgrep_RE() {
48 
49    //std::vector<std::string> regexVector;
50    if (RegexFilename != "") {
51        std::ifstream regexFile(RegexFilename.c_str());
52        std::string r;
53        if (regexFile.is_open()) {
54            while (std::getline(regexFile, r)) {
55                regexVector.push_back(r);
56            }
57            regexFile.close();
58        }
59    }
60   
61    // if there are no regexes specified through -e or -f, the first positional argument
62    // must be a regex, not an input file.
63   
64    if (regexVector.size() == 0) {
65        regexVector.push_back(inputFiles[0]);
66        inputFiles.erase(inputFiles.begin());
67    }
68    if (CaseInsensitive) globalFlags |= re::CASE_INSENSITIVE_MODE_FLAG;
69
70 
71    std::vector<re::RE *> REs;
72    re::RE * re_ast = nullptr;
73    for (unsigned i = 0; i < regexVector.size(); i++) {
74        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
75        REs.push_back(re_ast);
76        allREs += regexVector[i] + "\n";
77    }
78    if (REs.size() > 1) {
79        re_ast = re::makeAlt(REs.begin(), REs.end());
80    }
81   
82    return re_ast;
83}
84
85std::string sha1sum(const std::string & str) {
86    char buffer[41];    // 40 hex-digits and the terminating null
87    unsigned int digest[5];     // 160 bits in total
88
89    boost::uuids::detail::sha1 sha1;
90    sha1.process_bytes(str.c_str(), str.size());
91    sha1.get_digest(digest);
92    snprintf(buffer, sizeof(buffer), "%.8x%.8x%.8x%.8x%.8x",
93             digest[0], digest[1], digest[2], digest[3], digest[4]);
94    return std::string(buffer);
95}
96
97std::vector<int> total_CountOnly;
98std::mutex count_mutex;
99size_t fileCount;
100void *DoGrep(void *args)
101{
102    size_t fileIdx;
103    GrepEngine * grepEngine = (GrepEngine *)args;
104
105    count_mutex.lock();
106    fileCount++;
107    fileIdx = fileCount;
108    count_mutex.unlock();
109
110    while (fileIdx < inputFiles.size()){
111        grepEngine->doGrep(inputFiles[fileIdx], fileIdx, CountOnly, total_CountOnly);
112       
113        count_mutex.lock();
114        fileCount++;
115        fileIdx = fileCount;
116        count_mutex.unlock();
117    }
118
119    pthread_exit(NULL);
120}
121
122
123// Returns true if the command line argument shouldn't be passed to icGrep or Grep.
124bool isArgUnwantedForAll(char *argument) {
125
126    bool isUnwated = false;
127    std::vector<std::string> unwantedFlags = {"-gs"};
128
129    for (int i=0; i<unwantedFlags.size(); i++){   
130        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
131            isUnwated = true;
132        }
133    }
134
135    return isUnwated;
136}
137// Filters out the command line strings that shouldn't be passed on to Grep
138bool isArgUnwantedForGrep(char *argument) {
139    bool isUnwated = false;
140    std::vector<std::string> unwantedFlags = {"-n"};
141
142    for (int i = 0; i < unwantedFlags.size(); i++){
143        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
144            isUnwated = true;
145        }
146    }
147
148    for (int i = 0; i < inputFiles.size(); i++){    // filter out input content files.
149        if (strcmp(argument, inputFiles[i].c_str()) == 0) {
150            isUnwated = true;
151        }
152    }
153
154    return isUnwated;
155}
156// Filters out the command line strings that shouldn't be passed on to IcGrep
157bool isArgUnwantedForIcGrep(char *argument) {
158    bool isUnwated = false;
159    std::vector<std::string> unwantedFlags = {"-c"};
160
161    for (int i=0; i<unwantedFlags.size(); i++){
162        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
163            isUnwated = true;
164        }
165    }
166
167    return isUnwated;
168}
169
170/*
171* Constructs a shell command that calls icgrep and then pipes the output to grep.
172* Then executs this shell command using the "system()" function.
173* This allows the output to be colored since all output is piped to grep.
174*/ 
175void pipeIcGrepOutputToGrep(int argc, char *argv[]) {
176    std::string icGrepArguments = "";
177    std::string grepArguments = "";
178
179    // Construct the shell arguments for icgrep and grep
180    // by filtering out the command line arguments passed into this process.
181    for (int i=1; i< argc; i++) {
182        if (!isArgUnwantedForAll(argv[i])) {
183
184            if (!isArgUnwantedForIcGrep(argv[i])) {
185                icGrepArguments.append(argv[i]);
186                icGrepArguments.append(" ");
187            }
188
189            if (!isArgUnwantedForGrep(argv[i])) {
190                grepArguments.append(argv[i]);
191                grepArguments.append(" ");
192            }
193        }
194    }
195
196    std::string systemCall = "./icgrep ";
197    systemCall.append(icGrepArguments);
198    systemCall.append(" ");
199    systemCall.append(" | grep --color=always -P ");
200    systemCall.append(grepArguments);
201    system(systemCall.c_str());
202}
203
204
205int main(int argc, char *argv[]) {
206    StringMap<cl::Option*> Map;
207    cl::getRegisteredOptions(Map);
208    Map["time-passes"]->setHiddenFlag(cl::Hidden);
209    Map["disable-spill-fusing"]->setHiddenFlag(cl::Hidden);
210    Map["enable-misched"]->setHiddenFlag(cl::Hidden);
211    Map["enable-tbaa"]->setHiddenFlag(cl::Hidden);
212    Map["exhaustive-register-search"]->setHiddenFlag(cl::Hidden);
213    Map["join-liveintervals"]->setHiddenFlag(cl::Hidden);
214    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
215    Map["mc-x86-disable-arith-relaxation"]->setHiddenFlag(cl::Hidden);
216    Map["limit-float-precision"]->setHiddenFlag(cl::Hidden);
217    Map["print-after-all"]->setHiddenFlag(cl::Hidden);
218    Map["print-before-all"]->setHiddenFlag(cl::Hidden);
219    Map["print-machineinstrs"]->setHiddenFlag(cl::Hidden);
220    Map["regalloc"]->setHiddenFlag(cl::Hidden);
221    Map["rng-seed"]->setHiddenFlag(cl::Hidden);
222    Map["stackmap-version"]->setHiddenFlag(cl::Hidden);
223    Map["x86-asm-syntax"]->setHiddenFlag(cl::Hidden);
224    Map["verify-debug-info"]->setHiddenFlag(cl::Hidden);
225    Map["verify-dom-info"]->setHiddenFlag(cl::Hidden);
226    Map["verify-loop-info"]->setHiddenFlag(cl::Hidden);
227    Map["verify-regalloc"]->setHiddenFlag(cl::Hidden);
228    Map["verify-scev"]->setHiddenFlag(cl::Hidden);
229    Map["x86-recip-refinement-steps"]->setHiddenFlag(cl::Hidden);
230    Map["rewrite-map-file"]->setHiddenFlag(cl::Hidden);
231
232    cl::ParseCommandLineOptions(argc, argv);
233   
234    re::RE * re_ast = get_icgrep_RE();
235    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
236
237    if (GrepSupport) {  // Calls icgrep again on command line and passes output to grep.
238        pipeIcGrepOutputToGrep(argc, argv);
239        return 0;   // icgrep is called again, so we need to end this process.
240    }
241   
242    GrepEngine grepEngine;
243    grepEngine.grepCodeGen(module_name, re_ast, CountOnly);
244   
245    initResult(inputFiles);
246    for (int i=0; i<inputFiles.size(); i++){
247        total_CountOnly.push_back(0);
248    }
249
250    if (Threads <= 1) {
251        for (unsigned i = 0; i != inputFiles.size(); ++i) {
252            grepEngine.doGrep(inputFiles[i], i, CountOnly, total_CountOnly);
253        }       
254    } else if (Threads > 1) {
255        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
256        pthread_t threads[numOfThreads];
257
258        for(unsigned long i = 0; i < numOfThreads; ++i){
259            const int rc = pthread_create(&threads[i], NULL, DoGrep, (void *)&grepEngine);
260            if (rc) {
261                throw std::runtime_error("Failed to create thread: code " + std::to_string(rc));
262            }
263        }
264
265        for(unsigned i = 0; i < numOfThreads; ++i) {
266            void * status = nullptr;
267            const int rc = pthread_join(threads[i], &status);
268            if (rc) {
269                throw std::runtime_error("Failed to join thread: code " + std::to_string(rc));
270            }
271        }
272    }
273    PrintResult(CountOnly, total_CountOnly);
274   
275    return 0;
276}
Note: See TracBrowser for help on using the repository browser.