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

Last change on this file since 5305 was 5267, checked in by nmedfort, 2 years ago

Code clean-up. Removed Pablo Call, SetIthBit? and Prototype.

File size: 16.9 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 <llvm/Support/ErrorHandling.h>
11#include <llvm/Support/Signals.h>
12#include <llvm/Support/raw_ostream.h>
13#include <re/re_alt.h>
14#include <re/re_seq.h>
15#include <re/re_start.h>
16#include <re/re_end.h>
17#include <re/re_parser.h>
18#include <re/re_utility.h>
19#include <grep_engine.h>
20#include <fstream>
21#include <string>
22#include <boost/uuid/sha1.hpp>
23#include <toolchain.h>
24#include <re/re_toolchain.h>
25#include <pablo/pablo_toolchain.h>
26#include <mutex>
27#include <boost/filesystem.hpp>
28#include <iostream> // MEEE
29#ifdef PRINT_TIMING_INFORMATION
30#include <hrtime.h>
31#include <util/papi_helper.hpp>
32#endif
33
34using namespace llvm;
35
36static cl::OptionCategory LegacyGrepOptions("A. Standard Grep Options",
37                                       "These are standard grep options intended for compatibility with typical grep usage.");
38
39#ifdef FUTURE
40static cl::OptionCategory RegexpOptions("Regular Expression Interpretation", "These options control regular expression interpretation");
41static cl::opt<re::RE_Syntax> RegexpSyntax(cl::desc("Regular expression syntax:"),
42    cl::values(
43        clEnumValN(re::RE_Syntax::FixedStrings, "F", "Fixed strings, separated by newlines"),
44        clEnumValN(re::RE_Syntax::BRE, "G", "Posix basic regular expression (BRE) syntax"),
45        clEnumValN(re::RE_Syntax::ERE, "E", "Posix extended regular expression (ERE) syntax"),
46        clEnumValN(re::RE_Syntax::PROSITE, "PRO", "PROSITE protein patterns syntax"),
47        clEnumValN(re::RE_Syntax::PCRE, "P", "Perl-compatible regular expression (PCRE) syntax - default"),
48               clEnumValEnd), cl::cat(LegacyGrepOptions), cl::Grouping, cl::init(re::RE_Syntax::PCRE));
49#endif
50
51static cl::opt<bool> EntireLineMatching("x", cl::desc("Require that entire lines be matched."), cl::cat(LegacyGrepOptions), cl::Grouping);
52static cl::alias  EntireLineMatchingAlias("line-regexp", cl::desc("Alias for -x"), cl::aliasopt(EntireLineMatching));
53
54static cl::opt<bool> WholeWordMatching("w", cl::desc("Require that whole words be matched."), cl::cat(LegacyGrepOptions), cl::Grouping);
55static cl::alias WholeWordMatchingAlias("word-regexp", cl::desc("Alias for -w"), cl::aliasopt(WholeWordMatching));
56
57static cl::opt<bool> UTF_16("UTF-16", cl::desc("Regular expressions over the UTF-16 representation of Unicode."), cl::cat(LegacyGrepOptions));
58static cl::OptionCategory EnhancedGrepOptions("B. Enhanced Grep Options",
59                                       "These are additional options for icgrep functionality and performance.");
60
61static cl::opt<bool> FileNamesOnly("l", cl::desc("Display only the names of matching files."), cl::cat(LegacyGrepOptions), cl::Grouping);
62static cl::alias FileNamesAlias("files-with-matches", cl::desc("Alias for -l"), cl::aliasopt(FileNamesOnly));
63
64static cl::opt<bool> NonMatchingFileNamesOnly("L", cl::desc("Display only the names of matching files."), cl::cat(LegacyGrepOptions), cl::Grouping);
65static cl::alias NonMatchingFileNamesAlias("files-without-match", cl::desc("Alias for -L"), cl::aliasopt(NonMatchingFileNamesOnly));
66
67
68static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(LegacyGrepOptions), cl::Grouping);
69static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
70
71
72static cl::list<std::string> inputFiles(cl::Positional, cl::desc("<regex> <input file ...>"), cl::OneOrMore);
73
74static cl::opt<bool> EnterDirectoriesRecursively("r", cl::desc("Recursively process files within directories, (but follow only top-level symlinks unless -R)."), cl::cat(LegacyGrepOptions), cl::Grouping);
75static cl::opt<bool> FollowSubdirectorySymlinks("R", cl::desc("Recursively process files within directories, following symlinks at all levels."), cl::cat(LegacyGrepOptions), cl::Grouping);
76static cl::opt<bool> CaseInsensitive("i", cl::desc("Ignore case distinctions in the pattern and the file."), cl::cat(LegacyGrepOptions), cl::Grouping);
77static cl::alias CaseInsensitiveAlisas("ignore-case", cl::desc("Ignore case distinctions in the pattern and the file."), cl::aliasopt(CaseInsensitive));
78
79static cl::list<std::string> regexVector("e", cl::desc("Regular expression"), cl::ZeroOrMore, cl::cat(LegacyGrepOptions));
80static 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(LegacyGrepOptions));
81static cl::opt<std::string> IRFileName("precompiled", cl::desc("Use precompiled regular expression"), cl::value_desc("LLVM IR file"), cl::init(""));
82
83static cl::opt<int> Threads("t", cl::desc("Total number of threads."), cl::init(1));
84
85static cl::opt<bool> GrepSupport("gs", cl::desc("Grep support. Pipe the output of icgrep into grep. \
86         Gives you colored output + back-referencing capability."), cl::cat(EnhancedGrepOptions));
87
88
89static std::vector<std::string> allFiles;
90//
91// Handler for errors reported through llvm::report_fatal_error.  Report
92// and signal error code 2 (grep convention).
93//
94static void icgrep_error_handler(void *UserData, const std::string &Message,
95                             bool GenCrashDiag) {
96
97    // Modified from LLVM's internal report_fatal_error logic.
98    SmallVector<char, 64> Buffer;
99    raw_svector_ostream OS(Buffer);
100    OS << "icgrep ERROR: " << Message << "\n";
101    StringRef MessageStr = OS.str();
102    ssize_t written = ::write(2, MessageStr.data(), MessageStr.size());
103    (void)written; // If something went wrong, we deliberately just give up.
104
105    // Run the interrupt handlers to make sure any special cleanups get done, in
106    // particular that we remove files registered with RemoveFileOnSignal.
107    llvm::sys::RunInterruptHandlers();
108    exit(2);
109}
110
111static std::string allREs;
112static re::ModeFlagSet globalFlags = 0;
113
114re::RE * get_icgrep_RE() {
115 
116    //std::vector<std::string> regexVector;
117    if (RegexFilename != "") {
118        std::ifstream regexFile(RegexFilename.c_str());
119        std::string r;
120        if (regexFile.is_open()) {
121            while (std::getline(regexFile, r)) {
122                regexVector.push_back(r);
123            }
124            regexFile.close();
125        }
126    }
127   
128    // if there are no regexes specified through -e or -f, the first positional argument
129    // must be a regex, not an input file.
130   
131    if (regexVector.size() == 0) {
132        regexVector.push_back(inputFiles[0]);
133        inputFiles.erase(inputFiles.begin());
134    }
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#ifdef FUTURE
142        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags, RegexpSyntax);
143#else
144        re_ast = re::RE_Parser::parse(regexVector[i], globalFlags);
145#endif
146        REs.push_back(re_ast);
147        allREs += regexVector[i] + "\n";
148    }
149    if (REs.size() > 1) {
150        re_ast = re::makeAlt(REs.begin(), REs.end());
151    }
152    if (WholeWordMatching) {
153        re_ast = re::makeSeq({re::makeWordBoundary(), re_ast, re::makeWordBoundary()});
154    }
155    if (EntireLineMatching) {
156        re_ast = re::makeSeq({re::makeStart(), re_ast, re::makeEnd()});
157    }   
158    return re_ast;
159}
160
161std::string sha1sum(const std::string & str) {
162    char buffer[41];    // 40 hex-digits and the terminating null
163    unsigned int digest[5];     // 160 bits in total
164
165    boost::uuids::detail::sha1 sha1;
166    sha1.process_bytes(str.c_str(), str.size());
167    sha1.get_digest(digest);
168    snprintf(buffer, sizeof(buffer), "%.8x%.8x%.8x%.8x%.8x",
169             digest[0], digest[1], digest[2], digest[3], digest[4]);
170    return std::string(buffer);
171}
172
173std::vector<size_t> total_CountOnly;
174std::mutex count_mutex;
175size_t fileCount;
176void *DoGrep(void *args)
177{
178    size_t fileIdx;
179    GrepEngine * grepEngine = (GrepEngine *)args;
180
181    count_mutex.lock();
182    fileIdx = fileCount;
183    fileCount++;
184    count_mutex.unlock();
185
186    while (fileIdx < allFiles.size()){
187        grepEngine->doGrep(allFiles[fileIdx], fileIdx, CountOnly, total_CountOnly, UTF_16);
188       
189        count_mutex.lock();
190        fileIdx = fileCount;
191        fileCount++;
192        count_mutex.unlock();
193    }
194
195    pthread_exit(nullptr);
196}
197
198
199// Returns true if the command line argument shouldn't be passed to icGrep or Grep.
200bool isArgUnwantedForAll(char *argument) {
201    std::vector<std::string> unwantedFlags = {"-gs"};
202    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
203        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
204            return true;
205        }
206    }
207    return false;
208}
209// Filters out the command line strings that shouldn't be passed on to Grep
210bool isArgUnwantedForGrep(char *argument) {
211#ifdef FUTURE
212    std::vector<std::string> unwantedFlags = {"-n", "-P", "-G", "-E", "-PRO"};
213#else
214    std::vector<std::string> unwantedFlags = {"-n"};
215#endif
216
217    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
218        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
219            return true;
220        }
221    }
222
223    for (unsigned i = 0; i < inputFiles.size(); ++i){    // filter out input content files.
224        if (strcmp(argument, inputFiles[i].c_str()) == 0) {
225            return true;
226        }
227    }
228
229    return false;
230}
231// Filters out the command line strings that shouldn't be passed on to IcGrep
232bool isArgUnwantedForIcGrep(char *argument) {
233    bool isUnwanted = false;
234    std::vector<std::string> unwantedFlags = {"-c"};
235
236    for (unsigned i = 0; i < unwantedFlags.size(); ++i){
237        if (strcmp(argument, unwantedFlags[i].c_str()) == 0) {
238            isUnwanted = true;
239        }
240    }
241
242    return isUnwanted;
243}
244
245/*
246* Constructs a shell command that calls icgrep and then pipes the output to grep.
247* Then executs this shell command using the "system()" function.
248* This allows the output to be colored since all output is piped to grep.
249*/ 
250void pipeIcGrepOutputToGrep(int argc, char *argv[]) {
251    std::string icGrepArguments = "";
252    std::string grepArguments = "";
253
254    // Construct the shell arguments for icgrep and grep
255    // by filtering out the command line arguments passed into this process.
256    for (int i = 1; i < argc; i++) {
257        if (!isArgUnwantedForAll(argv[i])) {
258
259            if (!isArgUnwantedForIcGrep(argv[i])) {
260                // Wrap everything in quotes since the arguments passed into this program had them stripped by bash.
261                icGrepArguments.append("\"");       
262                icGrepArguments.append(argv[i]);
263                icGrepArguments.append("\" ");
264            }
265
266            if (!isArgUnwantedForGrep(argv[i])) {
267                grepArguments.append("\"");
268                grepArguments.append(argv[i]);
269                grepArguments.append("\" ");
270            }
271        }
272    }
273
274#ifdef FUTURE
275    switch (RegexpSyntax) {
276        case re::RE_Syntax::BRE:
277            grepArguments.append("\"-G\" ");
278            break;
279        case re::RE_Syntax::ERE:
280            grepArguments.append("\"-E\" ");
281            break;
282        case re::RE_Syntax::PROSITE:
283            grepArguments.append("\"-PRO\" ");
284            break;
285        case re::RE_Syntax::PCRE:
286            grepArguments.append("\"-P\" ");
287            break;
288        default:
289            //TODO: handle fix string
290            break;
291    }
292#endif
293
294    std::string systemCall = argv[0];
295    systemCall.append(" ");
296    systemCall.append(icGrepArguments);
297    systemCall.append(" ");
298#ifdef FUTURE
299    systemCall.append(" | grep --color=always ");
300#else
301    systemCall.append(" | grep --color=always -P ");
302#endif
303    systemCall.append(grepArguments);
304
305    const auto rc = system(systemCall.c_str());
306    if (LLVM_UNLIKELY(rc < 0)) {
307        throw std::runtime_error("Error calling grep: " + std::string(strerror(errno)));
308    }
309}
310
311
312// This is a stub, to be expanded later.
313bool excludeDirectory(boost::filesystem::path dirpath) { return dirpath.filename() == ".svn";}
314
315std::vector<std::string> getFullFileList(cl::list<std::string> & inputFiles) {
316    using namespace boost::filesystem;
317    symlink_option follow_symlink = FollowSubdirectorySymlinks ? symlink_option::recurse : symlink_option::none;
318    std::vector<std::string> expanded_paths;
319    boost::system::error_code errc;
320    if (FollowSubdirectorySymlinks) {
321        EnterDirectoriesRecursively = true;
322    }
323    for (auto & f : inputFiles) {
324        path p(f);
325        if (EnterDirectoriesRecursively && is_directory(p)) {
326            if (!excludeDirectory(p)) {
327                recursive_directory_iterator di(p, follow_symlink, errc), end;
328                if (errc) {
329                    // If we cannot enter the directory, keep it in the list of files.
330                    expanded_paths.push_back(f); 
331                    continue;
332                }
333                while (di != end) {
334                    auto & e = di->path();
335                    if (is_directory(e)) {
336                        if (excludeDirectory(e)) di.no_push();
337                    }
338                    else expanded_paths.push_back(e.string());
339                    di.increment(errc);
340                    if (errc) {
341                        expanded_paths.push_back(e.string()); 
342                    }
343                }
344            }
345        }
346        else expanded_paths.push_back(p.string());
347    }
348    return expanded_paths;
349}
350
351
352int main(int argc, char *argv[]) {
353    llvm::install_fatal_error_handler(&icgrep_error_handler);
354#ifndef USE_LLVM_3_6
355    cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *>{&LegacyGrepOptions, &EnhancedGrepOptions, re::re_toolchain_flags(), pablo::pablo_toolchain_flags(), codegen::codegen_flags()});
356#endif
357    cl::ParseCommandLineOptions(argc, argv);
358#ifdef FUTURE
359    if (RegexpSyntax == re::RE_Syntax::FixedStrings) {
360        llvm::report_fatal_error("Sorry, FixedStrings syntax is not fully supported\n.");
361    }
362#endif
363    re::RE * re_ast = get_icgrep_RE();
364    std::string module_name = "grepcode:" + sha1sum(allREs) + ":" + std::to_string(globalFlags);
365   
366    if (GrepSupport) {  // Calls icgrep again on command line and passes output to grep.
367        pipeIcGrepOutputToGrep(argc, argv);
368        return 0;   // icgrep is called again, so we need to end this process.
369    }
370   
371    GrepEngine grepEngine;
372    grepEngine.grepCodeGen(module_name, re_ast, CountOnly, UTF_16);
373
374    allFiles = getFullFileList(inputFiles);
375   
376    if (FileNamesOnly && NonMatchingFileNamesOnly) {
377        // Strange request: print names of all matching files and all non-matching files: i.e., all of them.
378        // (Although GNU grep prints nothing.)
379        for (auto & f : allFiles) {
380            if (boost::filesystem::exists(f)) {
381                std::cout << f << "\n";
382            } else {
383                std::cerr << "Error: cannot open " << f << " for processing. Skipped.\n";
384            }
385        }
386        exit(0);
387    }
388    if (FileNamesOnly) {
389        llvm::report_fatal_error("Sorry, -l/-files-with-matches not yet supported\n.");
390    }
391    if (NonMatchingFileNamesOnly) {
392        llvm::report_fatal_error("Sorry, -L/-files-without-match not yet supported\n.");
393    }
394   
395    initResult(allFiles);
396    for (unsigned i=0; i < allFiles.size(); ++i){
397        total_CountOnly.push_back(0);
398    }
399
400    if (Threads <= 1) {
401
402        #ifdef PRINT_TIMING_INFORMATION
403        // PAPI_RES_STL, PAPI_STL_CCY, PAPI_FUL_CCY, PAPI_MEM_WCY
404        // PAPI_RES_STL, PAPI_BR_MSP, PAPI_LST_INS, PAPI_L1_TCM
405        papi::PapiCounter<4> papiCounters({PAPI_RES_STL, PAPI_STL_CCY, PAPI_FUL_CCY, PAPI_MEM_WCY});
406        #endif
407        for (unsigned i = 0; i != allFiles.size(); ++i) {
408            #ifdef PRINT_TIMING_INFORMATION
409            papiCounters.start();
410            const timestamp_t execution_start = read_cycle_counter();
411            #endif
412            grepEngine.doGrep(allFiles[i], i, CountOnly, total_CountOnly, UTF_16);
413            #ifdef PRINT_TIMING_INFORMATION
414            const timestamp_t execution_end = read_cycle_counter();
415            papiCounters.stop();
416            std::cerr << "EXECUTION TIME: " << allFiles[i] << ":" << "CYCLES|" << (execution_end - execution_start) << papiCounters << std::endl;
417            #endif
418        }       
419    } else if (Threads > 1) {
420        const unsigned numOfThreads = Threads; // <- convert the command line value into an integer to allow stack allocation
421        pthread_t threads[numOfThreads];
422
423        for(unsigned long i = 0; i < numOfThreads; ++i){
424            const int rc = pthread_create(&threads[i], nullptr, DoGrep, (void *)&grepEngine);
425            if (rc) {
426                llvm::report_fatal_error("Failed to create thread: code " + std::to_string(rc));
427            }
428        }
429
430        for(unsigned i = 0; i < numOfThreads; ++i) {
431            void * status = nullptr;
432            const int rc = pthread_join(threads[i], &status);
433            if (rc) {
434                llvm::report_fatal_error("Failed to join thread: code " + std::to_string(rc));
435            }
436        }
437    }
438   
439    PrintResult(CountOnly, total_CountOnly);
440   
441    return 0;
442}
Note: See TracBrowser for help on using the repository browser.