source: icGREP/icgrep-devel/icgrep/grep_engine.cpp @ 5584

Last change on this file since 5584 was 5574, checked in by cameron, 2 years ago

Refactor to make a common grep pipeline

File size: 28.3 KB
Line 
1/*
2 *  Copyright (c) 2017 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 "grep_engine.h"
8#include "grep_interface.h"
9#include <llvm/IR/Module.h>
10#include <boost/filesystem.hpp>
11#include <UCD/UnicodeNameData.h>
12#include <UCD/resolve_properties.h>
13#include <kernels/cc_kernel.h>
14#include <kernels/grep_kernel.h>
15#include <kernels/linebreak_kernel.h>
16#include <kernels/streams_merge.h>
17#include <kernels/source_kernel.h>
18#include <kernels/s2p_kernel.h>
19#include <kernels/scanmatchgen.h>
20#include <kernels/streamset.h>
21#include <kernels/until_n.h>
22#include <kernels/kernel_builder.h>
23#include <pablo/pablo_kernel.h>
24#include <re/re_cc.h>
25#include <re/re_toolchain.h>
26#include <toolchain/toolchain.h>
27#include <toolchain/cpudriver.h>
28#include <toolchain/NVPTXDriver.h>
29#include <iostream>
30#include <sstream>
31#include <cc/multiplex_CCs.h>
32#include <llvm/Support/raw_ostream.h>
33#include <util/aligned_allocator.h>
34#include <sys/stat.h>
35#include <fcntl.h>
36#include <errno.h>
37#include <mutex>
38#ifdef CUDA_ENABLED
39#include <preprocess.cpp>
40#include <IR_Gen/CudaDriver.h>
41#endif
42
43using namespace parabix;
44using namespace llvm;
45
46namespace grep {
47
48static std::stringstream * resultStrs = nullptr;
49static std::vector<std::string> inputFiles;
50static std::vector<std::string> linePrefix;
51static bool grepMatchFound;
52
53size_t * startPoints = nullptr;
54size_t * accumBytes = nullptr;
55
56
57std::mutex count_mutex;
58size_t fileCount;
59
60// DoGrep thread function.
61void *DoGrepThreadFunction(void *args)
62{
63    size_t fileIdx;
64    grep::GrepEngine * grepEngine = (grep::GrepEngine *)args;
65
66    count_mutex.lock();
67    fileIdx = fileCount;
68    fileCount++;
69    count_mutex.unlock();
70
71    while (fileIdx < inputFiles.size()) {
72        size_t grepResult = grepEngine->doGrep(inputFiles[fileIdx], fileIdx);
73       
74        count_mutex.lock();
75        if (grepResult > 0) grepMatchFound = true;
76        fileIdx = fileCount;
77        fileCount++;
78        count_mutex.unlock();
79        if (QuietMode && grepMatchFound) pthread_exit(nullptr);
80    }
81
82    pthread_exit(nullptr);
83}
84
85bool matchesNeedToBeMovedToEOL() {
86    if ((Mode == QuietMode) | (Mode == FilesWithMatch) | (Mode == FilesWithoutMatch)) {
87        return false;
88    }
89    else if (LineRegexpFlag) {
90        return false;
91    }
92    // TODO: return false for other cases based on regexp analysis, e.g., regexp ends with $.
93    return true;
94}
95   
96void GrepEngine::doGrep(const std::string & fileName, std::string & PTXFilename) const{
97#ifdef CUDA_ENABLED
98    const bool CountOnly = true;
99    boost::filesystem::path file(fileName);
100    if (exists(file)) {
101        if (is_directory(file)) {
102            return;
103        }
104    } else {
105        if (!NoMessagesFlag) {
106            std::cerr << "Error: cannot open " << fileName << " for processing. Skipped.\n";
107            return;
108        }
109    }
110
111    const auto fileSize = file_size(file);
112   
113    if (fileSize > 0) {
114        try {
115            boost::iostreams::mapped_file_source source(fileName, fileSize, 0);
116            char * fileBuffer = const_cast<char *>(source.data());
117           
118            codegen::BlockSize = 128;
119            std::vector<size_t> LFPositions = preprocess(fileBuffer, fileSize);
120           
121            const unsigned numOfGroups = codegen::GroupNum;
122            if (posix_memalign((void**)&startPoints, 8, (numOfGroups+1)*sizeof(size_t)) ||
123                posix_memalign((void**)&accumBytes, 8, (numOfGroups+1)*sizeof(size_t))) {
124                std::cerr << "Cannot allocate memory for startPoints or accumBytes.\n";
125                exit(-1);
126            }
127            if(PTXFilename=="")
128                PTXFilename = mGrepDriver->getBuilder()->getModule()->getModuleIdentifier() + ".ptx";
129            RunPTX(PTXFilename, fileBuffer, fileSize, CountOnly, LFPositions, startPoints, accumBytes);
130            source.close();
131        } catch (std::exception & e) {
132            if (!NoMessagesFlag) {
133                std::cerr << "Boost mmap error: " + fileName + ": " + e.what() + " Skipped.\n";
134                return;
135            }
136        }
137    } else {
138        std::cout << 0 << std::endl;
139    }
140#endif
141}
142
143uint64_t GrepEngine::doGrep(const std::string & fileName, const uint32_t fileIdx) const {
144    struct stat sb;
145    const int32_t fd = open(fileName.c_str(), O_RDONLY);
146    if (LLVM_UNLIKELY(fd == -1)) {
147        if (!NoMessagesFlag  && !(Mode == QuietMode)) {
148            if (errno == EACCES) {
149                resultStrs[fileIdx] << "icgrep: " << fileName << ": Permission denied.\n";
150            }
151            else if (errno == ENOENT) {
152                resultStrs[fileIdx] << "icgrep: " << fileName << ": No such file.\n";
153            }
154            else {
155                resultStrs[fileIdx] << "icgrep: " << fileName << ": Failed.\n";
156            }
157        }
158        return 0;
159    }
160    if (stat(fileName.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
161        if (!NoMessagesFlag  && !(Mode == QuietMode)) {
162            resultStrs[fileIdx] << "icgrep: " << fileName << ": Is a directory.\n";
163        }
164        close(fd);
165        return 0;
166    }
167    const auto result = doGrep(fd, fileIdx);
168    close(fd);
169    return result;
170}
171
172uint64_t GrepEngine::doGrep(const int32_t fileDescriptor, const uint32_t fileIdx) const {
173    assert (mGrepDriver);
174    typedef uint64_t (*GrepFunctionType)(int32_t fileDescriptor, const uint32_t fileIdx);
175    auto f = reinterpret_cast<GrepFunctionType>(mGrepDriver->getMain());
176   
177    uint64_t grepResult = f(fileDescriptor, fileIdx);
178    if (grepResult > 0) grepMatchFound = true;
179    else if ((Mode == NormalMode) && !resultStrs[fileIdx].str().empty()) grepMatchFound = true;
180   
181    if (Mode == CountOnly) {
182        resultStrs[fileIdx] << linePrefix[fileIdx] << grepResult << "\n";
183    }
184    else if (Mode == FilesWithMatch || Mode == FilesWithoutMatch ) {
185        size_t requiredCount = Mode == FilesWithMatch ? 1 : 0;
186        if (grepResult == requiredCount) {
187            resultStrs[fileIdx] << linePrefix[fileIdx];
188        }
189    }
190    else if (Mode == QuietMode) {
191        if (grepMatchFound) exit(MatchFoundExitCode);
192    }
193    return grepResult;
194}
195
196void initFileResult(std::vector<std::string> filenames){
197    grepMatchFound = false;
198    const int n = filenames.size();
199    linePrefix.resize(n);
200    if ((n > 1) && !NoFilenameFlag) {
201        WithFilenameFlag = true;
202    }
203    std::string fileSuffix = "";
204    bool setLinePrefix = WithFilenameFlag || (Mode == FilesWithMatch) || (Mode == FilesWithoutMatch);
205    if (setLinePrefix) {
206        if (NullFlag) {
207            fileSuffix = std::string("\0", 1);
208        }
209        else if ((Mode == NormalMode) && InitialTabFlag && !(LineNumberFlag || ByteOffsetFlag)) {
210            fileSuffix = "\t:";
211        }
212        else if ((Mode == NormalMode) || (Mode == CountOnly)) {
213            fileSuffix = ":";
214        }
215        else if ((Mode == FilesWithMatch) || (Mode == FilesWithoutMatch)) {
216            fileSuffix = "\n";
217        }
218    }
219    inputFiles = filenames;
220    resultStrs = new std::stringstream[n];
221    for (unsigned i = 0; i < inputFiles.size(); ++i) {
222        if (setLinePrefix) {
223            if (inputFiles[i] == "-") {
224                linePrefix[i] = LabelFlag + fileSuffix;
225            }
226            else {
227                linePrefix[i] = inputFiles[i] + fileSuffix;
228            }
229        }
230    }
231}
232
233template<typename CodeUnit>
234void wrapped_report_match(const size_t lineNum, size_t line_start, size_t line_end, const CodeUnit * const buffer, const size_t filesize, const size_t fileIdx) {
235
236//    errs().write_hex((size_t)buffer) << " : " << lineNum << " (" << line_start << ", " << line_end << ", " << filesize << ")\n";
237
238    assert (buffer);
239    assert (line_start <= line_end);
240    assert (line_end <= filesize);
241
242    if (WithFilenameFlag) {
243        resultStrs[fileIdx] << linePrefix[fileIdx];
244    }
245    if (LineNumberFlag) {
246        // Internally line numbers are counted from 0.  For display, adjust
247        // the line number so that lines are numbered from 1.
248        if (InitialTabFlag) {
249            resultStrs[fileIdx] << lineNum+1 << "\t:";
250        }
251        else {
252            resultStrs[fileIdx] << lineNum+1 << ":";
253        }
254    }
255
256    // If the line "starts" on the LF of a CRLF, it is actually the end of the last line.
257    if ((buffer[line_start] == 0xA) && (line_start != line_end)) {
258        ++line_start;
259    }
260
261    if (LLVM_UNLIKELY(line_end == filesize)) {
262        // The match position is at end-of-file.   We have a final unterminated line.
263        resultStrs[fileIdx].write((char *)&buffer[line_start], (line_end - line_start) * sizeof(CodeUnit));
264        if (NormalizeLineBreaksFlag) {
265            resultStrs[fileIdx] << '\n';  // terminate it
266        }
267    } else {
268        const auto end_byte = buffer[line_end];
269        if (grep::NormalizeLineBreaksFlag) {
270            if (LLVM_UNLIKELY(end_byte == 0x85)) {
271                // Line terminated with NEL, on the second byte.  Back up 1.
272                line_end -= 1;
273            } else if (LLVM_UNLIKELY(end_byte > 0xD)) {
274                // Line terminated with PS or LS, on the third byte.  Back up 2.
275                line_end -= 2;
276            }
277            resultStrs[fileIdx].write((char *)&buffer[line_start], (line_end - line_start) * sizeof(CodeUnit));
278            resultStrs[fileIdx] << '\n';
279        } else {
280            if (end_byte == 0x0D) {
281                // Check for line_end on first byte of CRLF; we don't want to access past the end of buffer.
282                if ((line_end + 1) < filesize) {
283                    if (buffer[line_end + 1] == 0x0A) {
284                        // Found CRLF; preserve both bytes.
285                        ++line_end;
286                    }
287                }
288            }
289            resultStrs[fileIdx].write((char *)&buffer[line_start], (line_end - line_start + 1) * sizeof(CodeUnit));
290        }
291    }
292}
293
294void PrintResults(){
295   
296    for (unsigned i = 0; i < inputFiles.size(); ++i){
297        std::cout << resultStrs[i].str();
298    }
299    exit(grepMatchFound ? MatchFoundExitCode : MatchNotFoundExitCode);
300}
301
302   
303std::pair<StreamSetBuffer *, StreamSetBuffer *> grepPipeline(Driver * grepDriver, std::vector<re::RE *> REs, const GrepModeType grepMode, unsigned encodingBits, StreamSetBuffer * ByteStream) {
304    auto & idb = grepDriver->getBuilder();
305    const unsigned segmentSize = codegen::SegmentSize;
306    const unsigned bufferSegments = codegen::BufferSegments * codegen::ThreadNum;
307    size_t MatchLimit = ((grepMode == QuietMode) | (grepMode == FilesWithMatch) | (grepMode == FilesWithoutMatch)) ? 1 : MaxCountFlag;
308   
309
310    StreamSetBuffer * BasisBits = grepDriver->addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(encodingBits, 1), segmentSize * bufferSegments));
311    kernel::Kernel * s2pk = grepDriver->addKernelInstance(make_unique<kernel::S2PKernel>(idb));
312    grepDriver->makeKernelCall(s2pk, {ByteStream}, {BasisBits});
313   
314    StreamSetBuffer * LineBreakStream = grepDriver->addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments));
315    kernel::Kernel * linebreakK = grepDriver->addKernelInstance(make_unique<kernel::LineBreakKernelBuilder>(idb, encodingBits));
316    grepDriver->makeKernelCall(linebreakK, {BasisBits}, {LineBreakStream});
317   
318    kernel::Kernel * requiredStreamsK = grepDriver->addKernelInstance(make_unique<kernel::RequiredStreams_UTF8>(idb));
319    StreamSetBuffer * RequiredStreams = grepDriver->addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(4, 1), segmentSize * bufferSegments));
320    grepDriver->makeKernelCall(requiredStreamsK, {BasisBits}, {RequiredStreams});
321   
322    const auto n = REs.size();
323   
324    std::vector<StreamSetBuffer *> MatchResultsBufs(n);
325   
326    for(unsigned i = 0; i < n; ++i){
327        StreamSetBuffer * MatchResults = grepDriver->addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments));
328        kernel::Kernel * icgrepK = grepDriver->addKernelInstance(make_unique<kernel::ICGrepKernel>(idb, REs[i]));
329        grepDriver->makeKernelCall(icgrepK, {BasisBits, LineBreakStream, RequiredStreams}, {MatchResults});
330        MatchResultsBufs[i] = MatchResults;
331    }
332    StreamSetBuffer * MergedResults = MatchResultsBufs[0];
333    if (REs.size() > 1) {
334        MergedResults = grepDriver->addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments));
335        kernel::Kernel * streamsMergeK = grepDriver->addKernelInstance(make_unique<kernel::StreamsMerge>(idb, 1, REs.size()));
336        grepDriver->makeKernelCall(streamsMergeK, MatchResultsBufs, {MergedResults});
337    }
338    StreamSetBuffer * Matches = MergedResults;
339   
340    if (matchesNeedToBeMovedToEOL()) {
341        StreamSetBuffer * OriginalMatches = Matches;
342        kernel::Kernel * matchedLinesK = grepDriver->addKernelInstance(make_unique<kernel::MatchedLinesKernel>(idb));
343        Matches = grepDriver->addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments));
344        grepDriver->makeKernelCall(matchedLinesK, {OriginalMatches, LineBreakStream}, {Matches});
345    }
346   
347    if (InvertMatchFlag) {
348        kernel::Kernel * invertK = grepDriver->addKernelInstance(make_unique<kernel::InvertMatchesKernel>(idb));
349        StreamSetBuffer * OriginalMatches = Matches;
350        Matches = grepDriver->addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments));
351        grepDriver->makeKernelCall(invertK, {OriginalMatches, LineBreakStream}, {Matches});
352    }
353    if (MatchLimit > 0) {
354        kernel::Kernel * untilK = grepDriver->addKernelInstance(make_unique<kernel::UntilNkernel>(idb));
355        untilK->setInitialArguments({idb->getSize(MatchLimit)});
356        StreamSetBuffer * AllMatches = Matches;
357        Matches = grepDriver->addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize * bufferSegments));
358        grepDriver->makeKernelCall(untilK, {AllMatches}, {Matches});
359    }
360    return std::pair<StreamSetBuffer *, StreamSetBuffer *>(LineBreakStream, Matches);
361}
362
363
364   
365void GrepEngine::grepCodeGen_nvptx(std::vector<re::RE *> REs, const GrepModeType grepMode, const bool UTF_16) {
366
367    assert (mGrepDriver == nullptr);
368
369    mGrepDriver = new NVPTXDriver("engine");
370    auto & idb = mGrepDriver->getBuilder();
371    Module * M = idb->getModule();
372
373    const unsigned segmentSize = codegen::SegmentSize;
374    const unsigned encodingBits = UTF_16 ? 16 : 8;
375
376    Type * const int64Ty = idb->getInt64Ty();
377    Type * const int32Ty = idb->getInt32Ty();
378    Type * const size_ty = idb->getSizeTy();
379    Type * const sizeTyPtr = PointerType::get(size_ty, 1);
380    Type * const int64tyPtr = PointerType::get(int64Ty, 1);
381    Type * const voidTy = idb->getVoidTy();
382   
383    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", voidTy, int64tyPtr, sizeTyPtr, sizeTyPtr, int64tyPtr, nullptr));
384    mainFunc->setCallingConv(CallingConv::C);
385    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
386    auto args = mainFunc->arg_begin();
387
388    Value * const inputPtr = &*(args++);
389    inputPtr->setName("inputPtr");
390    Value * const startPointsPtr = &*(args++);
391    startPointsPtr->setName("startPointsPtr");
392    Value * const bufferSizesPtr = &*(args++);
393    bufferSizesPtr->setName("bufferSizesPtr");
394    Value * const outputPtr = &*(args++);
395    outputPtr->setName("outputPtr");
396
397    Function * tidFunc = M->getFunction("llvm.nvvm.read.ptx.sreg.tid.x");
398    Value * tid = idb->CreateCall(tidFunc);
399    Function * bidFunc = cast<Function>(M->getOrInsertFunction("llvm.nvvm.read.ptx.sreg.ctaid.x", int32Ty, nullptr));
400    Value * bid = idb->CreateCall(bidFunc);
401
402    Value * startPoint = idb->CreateLoad(idb->CreateGEP(startPointsPtr, bid));
403    Value * startBlock = idb->CreateUDiv(startPoint, ConstantInt::get(int64Ty, idb->getBitBlockWidth()));
404    Type * const inputStreamType = PointerType::get(ArrayType::get(ArrayType::get(idb->getBitBlockType(), 8), 1), 1);   
405    Value * inputStreamPtr = idb->CreateGEP(idb->CreateBitCast(inputPtr, inputStreamType), startBlock);
406    Value * inputStream = idb->CreateGEP(inputStreamPtr, tid);
407    Value * bufferSize = idb->CreateLoad(idb->CreateGEP(bufferSizesPtr, bid));
408
409    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer(make_unique<SourceBuffer>(idb, idb->getStreamSetTy(1, 8), 1));
410    kernel::Kernel * sourceK = mGrepDriver->addKernelInstance(make_unique<kernel::MemorySourceKernel>(idb, inputStreamType, segmentSize));
411    sourceK->setInitialArguments({inputStream, bufferSize});
412    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
413
414    StreamSetBuffer * Matches = std::get<1>(grepPipeline(mGrepDriver, REs, grepMode, encodingBits, ByteStream));
415   
416    kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance(make_unique<kernel::PopcountKernel>(idb));
417    mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
418    mGrepDriver->generatePipelineIR();
419    idb->setKernel(matchCountK);
420    Value * matchedLineCount = idb->getAccumulator("countResult");
421    matchedLineCount = idb->CreateZExt(matchedLineCount, int64Ty);
422   
423    Value * strideBlocks = ConstantInt::get(int32Ty, idb->getStride() / idb->getBitBlockWidth());
424    Value * outputThreadPtr = idb->CreateGEP(outputPtr, idb->CreateAdd(idb->CreateMul(bid, strideBlocks), tid));
425    idb->CreateStore(matchedLineCount, outputThreadPtr);
426    idb->CreateRetVoid();
427
428    mGrepDriver->finalizeObject();
429}
430
431void GrepEngine::grepCodeGen(std::vector<re::RE *> REs, const GrepModeType grepMode, const bool UTF_16, GrepSource grepSource) {
432
433    assert (mGrepDriver == nullptr);
434    mGrepDriver = new ParabixDriver("engine");
435    auto & idb = mGrepDriver->getBuilder();
436    Module * M = idb->getModule();
437
438    const unsigned segmentSize = codegen::SegmentSize;
439    const unsigned encodingBits = UTF_16 ? 16 : 8;
440
441    Type * const int64Ty = idb->getInt64Ty();
442    Type * const int32Ty = idb->getInt32Ty();
443
444    kernel::Kernel * sourceK = nullptr;
445   
446    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", int64Ty, idb->getInt32Ty(), int32Ty, nullptr));
447    mainFunc->setCallingConv(CallingConv::C);
448    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
449    auto args = mainFunc->arg_begin();
450
451    Value * const fileDescriptor = &*(args++);
452    fileDescriptor->setName("fileDescriptor");
453    Value * fileIdx = &*(args++);
454    fileIdx->setName("fileIdx");
455
456    StreamSetBuffer * ByteStream = mGrepDriver->addBuffer(make_unique<SourceBuffer>(idb, idb->getStreamSetTy(1, 8)));
457
458    if (grepSource == GrepSource::File) {
459        sourceK = mGrepDriver->addKernelInstance(make_unique<kernel::MMapSourceKernel>(idb, segmentSize));
460    } else {
461        sourceK = mGrepDriver->addKernelInstance(make_unique<kernel::ReadSourceKernel>(idb, segmentSize));
462    }
463    sourceK->setInitialArguments({fileDescriptor});
464
465    mGrepDriver->makeKernelCall(sourceK, {}, {ByteStream});
466   
467    StreamSetBuffer * LineBreakStream;
468    StreamSetBuffer * Matches;
469    std::tie(LineBreakStream, Matches) = grepPipeline(mGrepDriver, REs, grepMode, encodingBits, ByteStream);
470   
471    if (grepMode == NormalMode) {
472        kernel::Kernel * scanMatchK = mGrepDriver->addKernelInstance(make_unique<kernel::ScanMatchKernel>(idb, GrepType::Normal, encodingBits));
473        scanMatchK->setInitialArguments({fileIdx});
474        mGrepDriver->makeKernelCall(scanMatchK, {Matches, LineBreakStream, ByteStream}, {});
475        if (UTF_16) {
476            mGrepDriver->LinkFunction(*scanMatchK, "matcher", &wrapped_report_match<uint16_t>);
477        } else {
478            mGrepDriver->LinkFunction(*scanMatchK, "matcher", &wrapped_report_match<uint8_t>);
479        }
480        mGrepDriver->generatePipelineIR();
481        mGrepDriver->deallocateBuffers();
482
483        idb->CreateRet(idb->getInt64(0));
484    } else {
485        kernel::Kernel * matchCountK = mGrepDriver->addKernelInstance(make_unique<kernel::PopcountKernel>(idb));
486        mGrepDriver->makeKernelCall(matchCountK, {Matches}, {});
487        mGrepDriver->generatePipelineIR();
488        idb->setKernel(matchCountK);
489        Value * matchedLineCount = idb->getAccumulator("countResult");
490        matchedLineCount = idb->CreateZExt(matchedLineCount, int64Ty);
491        mGrepDriver->deallocateBuffers();
492        idb->CreateRet(matchedLineCount);
493    }
494    mGrepDriver->finalizeObject();
495}
496
497GrepEngine::GrepEngine()
498: mGrepDriver(nullptr) {
499
500}
501
502GrepEngine::~GrepEngine() {
503    delete mGrepDriver;
504}
505
506
507   
508static re::CC * parsedCodePointSet = nullptr;
509
510void insert_codepoints(const size_t lineNum, const size_t line_start, const size_t line_end, const char * const buffer) {
511    assert (buffer);
512    assert (line_start <= line_end);
513    re::codepoint_t c = 0;
514    size_t line_pos = line_start;
515    while (isxdigit(buffer[line_pos])) {
516        assert (line_pos < line_end);
517        if (isdigit(buffer[line_pos])) {
518            c = (c << 4) | (buffer[line_pos] - '0');
519        }
520        else {
521            c = (c << 4) | (tolower(buffer[line_pos]) - 'a' + 10);
522        }
523        line_pos++;
524    }
525    assert(((line_pos - line_start) >= 4) && ((line_pos - line_start) <= 6)); // UCD format 4 to 6 hex digits.
526    parsedCodePointSet->insert(c);
527}
528
529re::CC * grepCodepoints(re::RE * pattern, char * UnicodeDataBuffer, size_t bufferLength) {
530    parsedCodePointSet = re::makeCC();       
531    const unsigned segmentSize = 8;
532
533    ParabixDriver pxDriver("codepointEngine");
534    auto & idb = pxDriver.getBuilder();
535    Module * M = idb->getModule();
536   
537    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getVoidTy(), idb->getInt8PtrTy(), idb->getSizeTy(), nullptr));
538    mainFunc->setCallingConv(CallingConv::C);
539    auto args = mainFunc->arg_begin();
540    Value * const buffer = &*(args++);
541    buffer->setName("buffer");
542    Value * length = &*(args++);
543    length->setName("length");
544   
545    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
546   
547    StreamSetBuffer * ByteStream = pxDriver.addBuffer(make_unique<SourceBuffer>(idb, idb->getStreamSetTy(1, 8)));
548    kernel::Kernel * sourceK = pxDriver.addKernelInstance(make_unique<kernel::MemorySourceKernel>(idb, idb->getInt8PtrTy(), segmentSize));
549    sourceK->setInitialArguments({buffer, length});
550    pxDriver.makeKernelCall(sourceK, {}, {ByteStream});
551   
552    StreamSetBuffer * BasisBits = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(8, 1), segmentSize));
553   
554    kernel::Kernel * s2pk = pxDriver.addKernelInstance(make_unique<kernel::S2PKernel>(idb));
555    pxDriver.makeKernelCall(s2pk, {ByteStream}, {BasisBits});
556   
557    kernel::Kernel * linebreakK = pxDriver.addKernelInstance(make_unique<kernel::LineBreakKernelBuilder>(idb, 8));
558    StreamSetBuffer * LineBreakStream = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize));
559    pxDriver.makeKernelCall(linebreakK, {BasisBits}, {LineBreakStream});
560   
561    kernel::Kernel * requiredStreamsK = pxDriver.addKernelInstance(make_unique<kernel::RequiredStreams_UTF8>(idb));
562    StreamSetBuffer * RequiredStreams = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(4, 1), segmentSize));
563    pxDriver.makeKernelCall(requiredStreamsK, {BasisBits}, {RequiredStreams});
564   
565    StreamSetBuffer * MatchResults = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize));
566    kernel::Kernel * icgrepK = pxDriver.addKernelInstance(make_unique<kernel::ICGrepKernel>(idb, pattern));
567    pxDriver.makeKernelCall(icgrepK, {BasisBits, LineBreakStream, RequiredStreams}, {MatchResults});
568   
569    StreamSetBuffer * MatchedLines = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize));
570    kernel::Kernel * matchedLinesK = pxDriver.addKernelInstance(make_unique<kernel::MatchedLinesKernel>(idb));
571    pxDriver.makeKernelCall(matchedLinesK, {MatchResults, LineBreakStream}, {MatchedLines});
572   
573    kernel::Kernel * scanMatchK = pxDriver.addKernelInstance(make_unique<kernel::ScanMatchKernel>(idb, GrepType::NameExpression, 8));
574    scanMatchK->setInitialArguments({idb->getInt32(0)});
575    pxDriver.makeKernelCall(scanMatchK, {MatchedLines, LineBreakStream, ByteStream}, {});
576    pxDriver.LinkFunction(*scanMatchK, "matcher", &insert_codepoints);
577    pxDriver.generatePipelineIR();
578    idb->CreateRetVoid();
579    pxDriver.finalizeObject();
580   
581    typedef void (*GrepFunctionType)(const char * buffer, const size_t length);
582    auto f = reinterpret_cast<GrepFunctionType>(pxDriver.getMain());
583    f(UnicodeDataBuffer, bufferLength);
584   
585    return parsedCodePointSet;   
586}
587
588   
589static std::vector<std::string> parsedPropertyValues;
590
591void insert_property_values(size_t lineNum, size_t line_start, size_t line_end, const char * buffer) {
592    assert (line_start <= line_end);
593    parsedPropertyValues.emplace_back(buffer + line_start, buffer + line_end);
594}
595
596
597const std::vector<std::string> & grepPropertyValues(const std::string& propertyName, re::RE * propertyValuePattern) {
598    ParabixDriver pxDriver("propertyValueEngine");
599    AlignedAllocator<char, 32> alloc;
600
601    parsedPropertyValues.clear();
602
603    const std::string & str = UCD::getPropertyValueGrepString(propertyName);
604
605    auto & idb = pxDriver.getBuilder();
606
607    const unsigned segmentSize = 8;
608    const auto n = str.length();
609    const auto w = idb->getBitBlockWidth() * segmentSize;
610    const auto m = w - (n % w);
611
612    char * aligned = alloc.allocate(n + m, 0);
613    std::memcpy(aligned, str.data(), n);
614    std::memset(aligned + n, 0, m);
615
616    Module * M = idb->getModule();
617   
618    Function * mainFunc = cast<Function>(M->getOrInsertFunction("Main", idb->getVoidTy(), idb->getInt8PtrTy(), idb->getSizeTy(), nullptr));
619    mainFunc->setCallingConv(CallingConv::C);
620    auto args = mainFunc->arg_begin();
621    Value * const buffer = &*(args++);
622    buffer->setName("buffer");
623    Value * length = &*(args++);
624    length->setName("length");
625   
626    idb->SetInsertPoint(BasicBlock::Create(M->getContext(), "entry", mainFunc, 0));
627   
628    StreamSetBuffer * ByteStream = pxDriver.addBuffer(make_unique<SourceBuffer>(idb, idb->getStreamSetTy(1, 8)));
629    kernel::Kernel * sourceK = pxDriver.addKernelInstance(make_unique<kernel::MemorySourceKernel>(idb, idb->getInt8PtrTy(), segmentSize));
630    sourceK->setInitialArguments({buffer, length});
631    pxDriver.makeKernelCall(sourceK, {}, {ByteStream});
632   
633    StreamSetBuffer * BasisBits = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(8, 1), segmentSize));
634   
635    kernel::Kernel * s2pk = pxDriver.addKernelInstance(make_unique<kernel::S2PKernel>(idb));
636    pxDriver.makeKernelCall(s2pk, {ByteStream}, {BasisBits});
637   
638    kernel::Kernel * linebreakK = pxDriver.addKernelInstance(make_unique<kernel::LineBreakKernelBuilder>(idb, 8));
639    StreamSetBuffer * LineBreakStream = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize));
640    pxDriver.makeKernelCall(linebreakK, {BasisBits}, {LineBreakStream});
641   
642    kernel::Kernel * requiredStreamsK = pxDriver.addKernelInstance(make_unique<kernel::RequiredStreams_UTF8>(idb));
643    StreamSetBuffer * RequiredStreams = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(4, 1), segmentSize));
644    pxDriver.makeKernelCall(requiredStreamsK, {BasisBits}, {RequiredStreams});
645   
646    StreamSetBuffer * MatchResults = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize));
647    kernel::Kernel * icgrepK = pxDriver.addKernelInstance(make_unique<kernel::ICGrepKernel>(idb, propertyValuePattern));
648    pxDriver.makeKernelCall(icgrepK, {BasisBits, LineBreakStream, RequiredStreams}, {MatchResults});
649
650    StreamSetBuffer * MatchedLines = pxDriver.addBuffer(make_unique<CircularBuffer>(idb, idb->getStreamSetTy(1, 1), segmentSize));
651    kernel::Kernel * matchedLinesK = pxDriver.addKernelInstance(make_unique<kernel::MatchedLinesKernel>(idb));
652    pxDriver.makeKernelCall(matchedLinesK, {MatchResults, LineBreakStream}, {MatchedLines});
653
654    kernel::Kernel * scanMatchK = pxDriver.addKernelInstance(make_unique<kernel::ScanMatchKernel>(idb, GrepType::PropertyValue, 8));
655    scanMatchK->setInitialArguments({idb->getInt32(0)});
656    pxDriver.makeKernelCall(scanMatchK, {MatchedLines, LineBreakStream, ByteStream}, {});
657    pxDriver.LinkFunction(*scanMatchK, "matcher", &insert_property_values);
658    pxDriver.generatePipelineIR();
659    idb->CreateRetVoid();
660    pxDriver.finalizeObject();
661
662    typedef void (*GrepFunctionType)(const char * buffer, const size_t length);
663    auto f = reinterpret_cast<GrepFunctionType>(pxDriver.getMain());
664    f(aligned, n);
665   
666    alloc.deallocate(aligned, 0);
667    return parsedPropertyValues;
668}
669
670   
671}
Note: See TracBrowser for help on using the repository browser.