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

Last change on this file since 4964 was 4964, checked in by hongpum, 3 years ago

Refine path representation and default CacheDir?

File size: 25.0 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
11#include <llvm/IR/Function.h>
12#include <llvm/IR/Module.h>
13#include <llvm/ExecutionEngine/ExecutionEngine.h>
14#include <llvm/ExecutionEngine/MCJIT.h>
15#include <llvm/IRReader/IRReader.h>
16#include <llvm/Support/CommandLine.h>
17#include <llvm/CodeGen/CommandFlags.h>
18#include <llvm/Support/SourceMgr.h>
19#include <llvm/Support/TargetSelect.h>
20#include <llvm/Support/Host.h>
21
22#include <IDISA/idisa_avx_builder.h>
23#include <IDISA/idisa_sse_builder.h>
24#include <IDISA/idisa_i64_builder.h>
25#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
26#include <UCD/precompiled_properties.h>
27#endif
28#include <re/re_cc.h>
29#include <re/re_nullable.h>
30#include <re/re_simplifier.h>
31#include <re/re_alt.h>
32#include <re/parsefailure.h>
33#include <re/re_parser.h>
34#include <re/re_compiler.h>
35#include <utf8_encoder.h>
36#include <cc/cc_compiler.h>
37#include <pablo/pablo_compiler.h>
38#include <pablo/optimizers/pablo_simplifier.hpp>
39#include <pablo/optimizers/codemotionpass.h>
40#include <pablo/passes/flattenassociativedfg.h>
41#include <pablo/passes/factorizedfg.h>
42#ifdef ENABLE_MULTIPLEXING
43#include <pablo/optimizers/pablo_automultiplexing.hpp>
44#include <pablo/optimizers/pablo_bddminimization.h>
45#include <pablo/optimizers/distributivepass.h>
46#include <pablo/optimizers/schedulingprepass.h>
47#endif
48#include <pablo/function.h>
49#include <pablo/analysis/pabloverifier.hpp>
50#include <re/printer_re.h>
51#include <pablo/printer_pablos.h>
52#include <object_cache.h>
53// Dynamic processor detection
54#define ISPC_LLVM_VERSION ISPC_LLVM_3_6
55#include "ispc.cpp"
56
57using namespace pablo;
58
59static cl::OptionCategory bGrepOutputOptions("Output Options",
60                                      "These options control the output.");
61
62static cl::opt<bool> CountOnly("c", cl::desc("Count and display the matching lines per file only."), cl::cat(bGrepOutputOptions));
63static cl::alias CountOnlyLong("count", cl::desc("Alias for -c"), cl::aliasopt(CountOnly));
64static cl::opt<bool> NormalizeLineBreaks("normalize-line-breaks", cl::desc("Normalize line breaks to std::endl."), cl::init(false),  cl::cat(bGrepOutputOptions));
65
66static cl::opt<bool> ShowFileNames("H", cl::desc("Show the file name with each matching line."), cl::cat(bGrepOutputOptions));
67static cl::alias ShowFileNamesLong("with-filename", cl::desc("Alias for -H"), cl::aliasopt(ShowFileNames));
68
69static cl::opt<bool> ShowLineNumbers("n", cl::desc("Show the line number with each matching line."), cl::cat(bGrepOutputOptions));
70static cl::alias ShowLineNumbersLong("line-number", cl::desc("Alias for -n"), cl::aliasopt(ShowLineNumbers));
71
72
73static cl::OptionCategory cRegexOutputOptions("Regex Dump Options",
74                                              "These options control printing of intermediate regular expression structures.");
75static cl::opt<bool> PrintAllREs("print-REs", cl::init(false), cl::desc("print regular expression passes"), cl::cat(cRegexOutputOptions));
76static cl::opt<bool> PrintParsedREs("print-parsed-REs", cl::init(false), cl::desc("print out parsed regular expressions"), cl::cat(cRegexOutputOptions));
77static cl::opt<bool> PrintStrippedREs("print-stripped-REs", cl::init(false), cl::desc("print out REs with nullable prefixes/suffixes removed"), cl::cat(cRegexOutputOptions));
78static cl::opt<bool> PrintNamedREs("print-named-REs", cl::init(false), cl::desc("print out named REs"), cl::cat(cRegexOutputOptions));
79static cl::opt<bool> PrintUTF8REs("print-utf8-REs", cl::init(false), cl::desc("print out UTF-8 REs"), cl::cat(cRegexOutputOptions));
80static cl::opt<bool> PrintSimplifiedREs("print-simplified-REs", cl::init(false), cl::desc("print out final simplified REs"), cl::cat(cRegexOutputOptions));
81
82static cl::OptionCategory dPabloDumpOptions("Pablo Dump Options", "These options control printing of intermediate Pablo code.");
83
84static cl::opt<bool> PrintOptimizedREcode("print-pablo", cl::init(false), cl::desc("print final optimized Pablo code"), cl::cat(dPabloDumpOptions));
85static cl::opt<bool> PrintCompiledCCcode("print-CC-pablo", cl::init(false), cl::desc("print Pablo output from character class compiler"), cl::cat(dPabloDumpOptions));
86static cl::opt<bool> PrintCompiledREcode("print-RE-pablo", cl::init(false), cl::desc("print Pablo output from the regular expression compiler"), cl::cat(dPabloDumpOptions));
87static cl::opt<std::string> PabloOutputFilename("print-pablo-output", cl::init(""), cl::desc("output Pablo filename"), cl::cat(dPabloDumpOptions));
88
89static cl::OptionCategory cMachineCodeOptimization("Machine Code Optimizations", "These options control back-end compilier optimization levels.");
90
91
92static cl::opt<char> OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] (default = '-O0')"),
93                              cl::cat(cMachineCodeOptimization), cl::Prefix, cl::ZeroOrMore, cl::init('0'));
94
95static cl::OptionCategory cPabloOptimizationsOptions("Pablo Optimizations", "These options control Pablo optimization passes.");
96
97static cl::opt<bool> DisableSimplification("disable-simplification", cl::init(false),
98                                     cl::desc("Disable Pablo Simplification pass (not recommended)"),
99                                     cl::cat(cPabloOptimizationsOptions));
100
101static cl::opt<bool> PabloSinkingPass("sinking", cl::init(false),
102                                      cl::desc("Moves all instructions into the innermost legal If-scope so that they are only executed when needed."),
103                                      cl::cat(cPabloOptimizationsOptions));
104
105#ifdef ENABLE_MULTIPLEXING
106static cl::opt<bool> PrintUnloweredCode("print-unlowered-pablo", cl::init(false), cl::desc("print Pablo output prior to lowering. "), cl::cat(dPabloDumpOptions));
107
108static cl::opt<bool> EnableMultiplexing("multiplexing", cl::init(false),
109                                        cl::desc("combine Advances whose inputs are mutual exclusive into the fewest number of advances possible (expensive)."),
110                                        cl::cat(cPabloOptimizationsOptions));
111
112static cl::opt<bool> EnableLowering("lowering", cl::init(false),
113                                         cl::desc("coalesce associative functions prior to optimization passes."),
114                                         cl::cat(cPabloOptimizationsOptions));
115
116static cl::opt<bool> EnablePreDistribution("pre-dist", cl::init(false),
117                                         cl::desc("apply distribution law optimization prior to multiplexing."),
118                                         cl::cat(cPabloOptimizationsOptions));
119
120static cl::opt<bool> EnablePostDistribution("post-dist", cl::init(false),
121                                         cl::desc("apply distribution law optimization after multiplexing."),
122                                         cl::cat(cPabloOptimizationsOptions));
123
124static cl::opt<bool> EnablePrePassScheduling("pre-pass-scheduling", cl::init(false),
125                                         cl::desc("apply pre-pass scheduling prior to LLVM IR generation."),
126                                         cl::cat(cPabloOptimizationsOptions));
127#endif
128
129static cl::OptionCategory dCodeGenOptions("Code Generation Options", "These options control code generation.");
130
131static cl::opt<bool> DisableAVX2("disable-AVX2", cl::init(false), cl::desc("disable AVX2 instruction set."), cl::cat(dCodeGenOptions));
132
133static cl::opt<int> BlockSize("BlockSize", cl::init(0), cl::desc("specify a block size (defaults to widest SIMD register width in bits)."), cl::cat(dCodeGenOptions));
134
135
136static cl::OptionCategory cObjectCache("Object Caching", "These options control back-end object caching behaviours.");
137
138static cl::opt<bool> EnableObjectCache("enable-object-cache", cl::init(false), cl::desc("Enable object caching"), cl::cat(cObjectCache));
139
140static cl::opt<std::string> ObjectCacheDir("object-cache-dir", cl::init(""), cl::desc("Path to the object cache diretory"), cl::cat(cObjectCache));
141
142re::RE * regular_expression_passes(const Encoding encoding, re::RE * re_ast)  {
143    if (PrintAllREs || PrintParsedREs) {
144        std::cerr << "Parser:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
145    }
146
147    //Optimization passes to simplify the AST.
148    re_ast = re::RE_Nullable::removeNullablePrefix(re_ast);
149    if (PrintAllREs || PrintStrippedREs) {
150        std::cerr << "RemoveNullablePrefix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
151    }
152    re_ast = re::RE_Nullable::removeNullableSuffix(re_ast);
153    if (PrintAllREs || PrintStrippedREs) {
154        std::cerr << "RemoveNullableSuffix:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
155    }
156
157    re_ast = re::RE_Simplifier::simplify(re_ast);
158    if (PrintAllREs || PrintSimplifiedREs) {
159        //Print to the terminal the AST that was generated by the simplifier.
160        std::cerr << "Simplifier:" << std::endl << Printer_RE::PrintRE(re_ast) << std::endl;
161    }
162    return re_ast;
163}
164   
165PabloFunction * re2pablo_compiler(const Encoding encoding, re::RE * re_ast) {
166    PabloFunction * function = PabloFunction::Create("process_block", 8, 2);
167    cc::CC_Compiler cc_compiler(*function, encoding);
168    re::RE_Compiler re_compiler(*function, cc_compiler);
169    re_compiler.initializeRequiredStreams();
170    re_compiler.compileUnicodeNames(re_ast);
171    re_compiler.finalizeMatchResult(re_compiler.compile(re_ast));
172
173    if (PrintCompiledREcode) {
174        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
175        llvm::raw_os_ostream cerr(std::cerr);
176        cerr << "Initial Pablo AST:\n";
177        PabloPrinter::print(*function, cerr);
178    }
179    #ifndef NDEBUG
180    PabloVerifier::verify(*function, "creation");
181    #endif
182    return function;
183}
184
185#ifdef PRINT_TIMING_INFORMATION
186#define READ_CYCLE_COUNTER(name) name = read_cycle_counter();
187#else
188#define READ_CYCLE_COUNTER(name)
189#endif
190
191#ifdef PRINT_TIMING_INFORMATION
192unsigned COUNT_STATEMENTS(const PabloFunction * const entry) {
193    std::stack<const Statement *> scope;
194    unsigned statements = 0;
195    // Scan through and collect all the advances, calls, scanthrus and matchstars ...
196    for (const Statement * stmt = entry->getEntryBlock()->front(); ; ) {
197        while ( stmt ) {
198            ++statements;
199            if (LLVM_UNLIKELY(isa<If>(stmt) || isa<While>(stmt))) {
200                // Set the next statement to be the first statement of the inner scope and push the
201                // next statement of the current statement into the scope stack.
202                const PabloBlock * const nested = isa<If>(stmt) ? cast<If>(stmt)->getBody() : cast<While>(stmt)->getBody();
203                scope.push(stmt->getNextNode());
204                stmt = nested->front();
205                assert (stmt);
206                continue;
207            }
208            stmt = stmt->getNextNode();
209        }
210        if (scope.empty()) {
211            break;
212        }
213        stmt = scope.top();
214        scope.pop();
215    }
216    return statements;
217}
218
219unsigned COUNT_ADVANCES(const PabloFunction * const entry) {
220
221    std::stack<const Statement *> scope;
222    unsigned advances = 0;
223
224    // Scan through and collect all the advances, calls, scanthrus and matchstars ...
225    for (const Statement * stmt = entry->getEntryBlock()->front(); ; ) {
226        while ( stmt ) {
227            if (isa<Advance>(stmt)) {
228                ++advances;
229            }
230            else if (LLVM_UNLIKELY(isa<If>(stmt) || isa<While>(stmt))) {
231                // Set the next statement to be the first statement of the inner scope and push the
232                // next statement of the current statement into the scope stack.
233                const PabloBlock * const nested = isa<If>(stmt) ? cast<If>(stmt)->getBody() : cast<While>(stmt)->getBody();
234                scope.push(stmt->getNextNode());
235                stmt = nested->front();
236                assert (stmt);
237                continue;
238            }
239            stmt = stmt->getNextNode();
240        }
241        if (scope.empty()) {
242            break;
243        }
244        stmt = scope.top();
245        scope.pop();
246    }
247    return advances;
248}
249
250using DistributionMap = boost::container::flat_map<unsigned, unsigned>;
251
252DistributionMap SUMMARIZE_VARIADIC_DISTRIBUTION(const PabloFunction * const entry) {
253    std::stack<const Statement *> scope;
254    DistributionMap distribution;
255    // Scan through and collect all the advances, calls, scanthrus and matchstars ...
256    for (const Statement * stmt = entry->getEntryBlock()->front(); ; ) {
257        while ( stmt ) {
258            if (isa<Variadic>(stmt)) {
259                auto f = distribution.find(stmt->getNumOperands());
260                if (f == distribution.end()) {
261                    distribution.emplace(stmt->getNumOperands(), 1);
262                } else {
263                    f->second += 1;
264                }
265            }
266            else if (LLVM_UNLIKELY(isa<If>(stmt) || isa<While>(stmt))) {
267                // Set the next statement to be the first statement of the inner scope and push the
268                // next statement of the current statement into the scope stack.
269                const PabloBlock * const nested = isa<If>(stmt) ? cast<If>(stmt)->getBody() : cast<While>(stmt)->getBody();
270                scope.push(stmt->getNextNode());
271                stmt = nested->front();
272                assert (stmt);
273                continue;
274            }
275            stmt = stmt->getNextNode();
276        }
277        if (scope.empty()) {
278            break;
279        }
280        stmt = scope.top();
281        scope.pop();
282    }
283    return distribution;
284}
285#endif
286
287void pablo_function_passes(PabloFunction * function) {
288    // Scan through the pablo code and perform DCE and CSE
289
290#ifdef PRINT_TIMING_INFORMATION
291    timestamp_t simplification_start = 0, simplification_end = 0;
292    timestamp_t coalescing_start = 0, coalescing_end = 0;
293    timestamp_t sinking_start = 0, sinking_end = 0;
294    timestamp_t pre_distribution_start = 0, pre_distribution_end = 0;
295    timestamp_t multiplexing_start = 0, multiplexing_end = 0;
296    timestamp_t post_distribution_start = 0, post_distribution_end = 0;
297    timestamp_t lowering_start = 0, lowering_end = 0;
298    timestamp_t scheduling_start = 0, scheduling_end = 0;
299    DistributionMap distribution;
300    const timestamp_t optimization_start = read_cycle_counter();
301#endif
302    if (!DisableSimplification) {
303        READ_CYCLE_COUNTER(simplification_start);
304        Simplifier::optimize(*function);
305        READ_CYCLE_COUNTER(simplification_end);
306    }
307#ifdef ENABLE_MULTIPLEXING
308    if (EnableLowering || EnablePreDistribution || EnablePostDistribution) {
309        READ_CYCLE_COUNTER(coalescing_start);
310        CanonicalizeDFG::transform(*function);
311        READ_CYCLE_COUNTER(coalescing_end);
312    }
313    if (EnablePreDistribution) {
314        READ_CYCLE_COUNTER(pre_distribution_start);
315        DistributivePass::optimize(*function);
316        READ_CYCLE_COUNTER(pre_distribution_end);
317    }
318    if (EnableMultiplexing) {
319        READ_CYCLE_COUNTER(multiplexing_start);
320        MultiplexingPass::optimize(*function);
321        READ_CYCLE_COUNTER(multiplexing_end);
322        if (EnableLowering || EnablePreDistribution || EnablePostDistribution) {
323            CanonicalizeDFG::transform(*function);
324        }
325    }
326    if (EnablePostDistribution) {
327        READ_CYCLE_COUNTER(post_distribution_start);
328        DistributivePass::optimize(*function);
329        READ_CYCLE_COUNTER(post_distribution_end);
330    }
331#endif
332    if (PabloSinkingPass) {
333        READ_CYCLE_COUNTER(sinking_start);
334        CodeMotionPass::optimize(*function);
335        READ_CYCLE_COUNTER(sinking_end);
336    }
337#ifdef ENABLE_MULTIPLEXING
338    if (PrintUnloweredCode) {
339        //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
340        llvm::raw_os_ostream cerr(std::cerr);
341        cerr << "Unlowered Pablo AST:\n";
342        PabloPrinter::print(*function, cerr);
343    }
344    #ifdef PRINT_TIMING_INFORMATION
345    distribution = SUMMARIZE_VARIADIC_DISTRIBUTION(function);
346    #endif
347    if (EnableLowering || EnablePreDistribution || EnablePostDistribution) {
348        READ_CYCLE_COUNTER(lowering_start);
349        FactorizeDFG::transform(*function);
350        READ_CYCLE_COUNTER(lowering_end);
351    }
352    if (EnablePrePassScheduling) {
353        READ_CYCLE_COUNTER(scheduling_start);
354        SchedulingPrePass::optimize(*function);
355        READ_CYCLE_COUNTER(scheduling_end);
356    }
357#endif
358#ifdef PRINT_TIMING_INFORMATION
359    const timestamp_t optimization_end = read_cycle_counter();
360#endif
361    if (PrintOptimizedREcode) {
362        if (PabloOutputFilename.empty()) {
363            //Print to the terminal the AST that was generated by the pararallel bit-stream compiler.
364            llvm::raw_os_ostream cerr(std::cerr);
365            cerr << "Final Pablo AST:\n";
366            PabloPrinter::print(*function, cerr);
367        } else {
368            std::error_code error;
369            llvm::raw_fd_ostream out(PabloOutputFilename, error, sys::fs::OpenFlags::F_None);
370            PabloPrinter::print(*function, out);
371        }
372    }
373#ifdef PRINT_TIMING_INFORMATION
374    std::cerr << "PABLO OPTIMIZATION TIME: " << (optimization_end - optimization_start) << std::endl;
375    std::cerr << "  SIMPLIFICATION TIME: " << (simplification_end - simplification_start) << std::endl;
376    std::cerr << "  COALESCING TIME: " << (coalescing_end - coalescing_start) << std::endl;
377    std::cerr << "  SINKING TIME: " << (sinking_end - sinking_start) << std::endl;
378    std::cerr << "  PRE-DISTRIBUTION TIME: " << (pre_distribution_end - pre_distribution_start) << std::endl;
379    std::cerr << "  MULTIPLEXING TIME: " << (multiplexing_end - multiplexing_start) << std::endl;
380    std::cerr << "  MULTIPLEXING SEED: " << MultiplexingPass::SEED << std::endl;
381    std::cerr << "  MULTIPLEXING NODES USED: " << MultiplexingPass::NODES_USED << std::endl;
382    std::cerr << "  MULTIPLEXING NODES ALLOCATED: " << MultiplexingPass::NODES_ALLOCATED << std::endl;
383    std::cerr << "  LOWERING TIME: " << (lowering_end - lowering_start) << std::endl;
384    std::cerr << "  POST-DISTRIBUTION TIME: " << (post_distribution_end - post_distribution_start) << std::endl;
385    std::cerr << "  SCHEDULING TIME: " << (scheduling_end - scheduling_start) << std::endl;
386    std::cerr << "PABLO STATEMENTS: " << COUNT_STATEMENTS(function) << std::endl;
387    std::cerr << "PABLO ADVANCES: " << COUNT_ADVANCES(function) << std::endl;
388    std::cerr << "PRE-LOWERING VARIADIC DISTRIBUTION: ";
389    bool join = false;
390    for (auto dist : distribution) {
391        if (join) {
392            std::cerr << ';';
393        }
394        std::cerr << dist.first << '|' << dist.second;
395        join = true;
396    }
397    std::cerr << std::endl;
398#endif
399}
400
401
402IDISA::IDISA_Builder * GetIDISA_Builder(Module * mod) {
403    bool hasAVX2 = (strncmp(lGetSystemISA(), "avx2", 4) == 0);
404   
405    unsigned theBlockSize = BlockSize;  // from command line
406   
407    if (theBlockSize == 0) {  // No BlockSize override: use processor SIMD width
408        theBlockSize = hasAVX2 ? 256 : 128;
409    }
410    Type * bitBlockType = VectorType::get(IntegerType::get(getGlobalContext(), 64), theBlockSize/64);
411   
412    int blockSize = bitBlockType->isIntegerTy() ? cast<IntegerType>(bitBlockType)->getIntegerBitWidth() : cast<VectorType>(bitBlockType)->getBitWidth();
413    if (blockSize >= 256) {
414        if (hasAVX2) {
415            return new IDISA::IDISA_AVX2_Builder(mod, bitBlockType);
416        }
417        else{
418            return new IDISA::IDISA_SSE2_Builder(mod, bitBlockType);
419        }
420    }
421    else if (blockSize == 64)
422        return new IDISA::IDISA_I64_Builder(mod, bitBlockType); 
423    return new IDISA::IDISA_SSE2_Builder(mod, bitBlockType);
424}
425
426
427
428ExecutionEngine * JIT_to_ExecutionEngine (Module * m) {
429
430    InitializeNativeTarget();
431    InitializeNativeTargetAsmPrinter();
432    InitializeNativeTargetAsmParser();
433
434    std::string errMessage;
435    EngineBuilder builder(std::move(std::unique_ptr<Module>(m)));
436    builder.setErrorStr(&errMessage);
437    builder.setMCPU(sys::getHostCPUName());
438    CodeGenOpt::Level optLevel = CodeGenOpt::Level::None;
439    switch (OptLevel) {
440        case '0': optLevel = CodeGenOpt::None; break;
441        case '1': optLevel = CodeGenOpt::Less; break;
442        case '2': optLevel = CodeGenOpt::Default; break;
443        case '3': optLevel = CodeGenOpt::Aggressive; break;
444        default: errs() << OptLevel << " is an invalid optimization level.\n";
445    }
446    builder.setOptLevel(optLevel);
447
448    if (!DisableAVX2 && (strncmp(lGetSystemISA(), "avx2", 4) == 0)) {
449            std::vector<std::string> attrs;
450            attrs.push_back("avx2");
451            builder.setMAttrs(attrs);
452    }
453
454    //builder.setOptLevel(mMaxWhileDepth ? CodeGenOpt::Level::Less : CodeGenOpt::Level::None);
455    ExecutionEngine * engine = builder.create();
456    ICGrepObjectCache * cache = nullptr;
457    if (engine == nullptr) {
458        throw std::runtime_error("Could not create ExecutionEngine: " + errMessage);
459    }
460
461    if (EnableObjectCache) {
462        if (ObjectCacheDir.empty())
463            // Default is $HOME/.cache/icgrep
464            cache = new ICGrepObjectCache();
465        else
466            cache = new ICGrepObjectCache(ObjectCacheDir);
467        engine->setObjectCache(cache);
468    }
469    return engine;
470}
471
472int total_count = 0;
473
474extern "C" {
475    void wrapped_report_match(uint64_t lineNum, uint64_t line_start, uint64_t line_end, const char * buffer, int filesize, char * filename) {
476        if(CountOnly){
477            total_count++;
478            return;
479        }
480
481        llvm::raw_os_ostream out(std::cout);
482        if (ShowFileNames) {
483            out << filename << ':';
484        }
485        if (ShowLineNumbers) {
486            out << lineNum << ":";
487        }
488
489        if ((buffer[line_start] == 0xA) && (line_start != line_end)) {
490            // The line "starts" on the LF of a CRLF.  Really the end of the last line.
491            line_start++;
492        }
493        if (line_end == filesize) {
494            // The match position is at end-of-file.   We have a final unterminated line.
495            out.write(&buffer[line_start], line_end - line_start);
496            if (NormalizeLineBreaks) {
497                out << '\n';  // terminate it
498            }
499            return;
500        }
501        unsigned char end_byte = (unsigned char)buffer[line_end]; 
502        if (NormalizeLineBreaks) {
503            if (end_byte == 0x85) {
504                // Line terminated with NEL, on the second byte.  Back up 1.
505                line_end--;
506            } else if (end_byte > 0xD) {
507                // Line terminated with PS or LS, on the third byte.  Back up 2.
508                line_end -= 2;
509            }
510            out.write(&buffer[line_start], line_end - line_start);
511            out << '\n';
512        }
513        else{   
514            if (end_byte == 0x0D) {
515                // Check for line_end on first byte of CRLF;  note that we don't
516                // want to access past the end of buffer.
517                if ((line_end + 1 < filesize) && (buffer[line_end + 1] == 0x0A)) {
518                    // Found CRLF; preserve both bytes.
519                    line_end++;
520                }
521            }
522            out.write(&buffer[line_start], line_end - line_start + 1);
523        }
524    }
525}
526
527
528void PrintTotalCount(){
529    if(CountOnly){
530        std::cout << total_count << std::endl;
531    }
532}
533
534re::CC * parsedCodePointSet;
535
536extern "C" {
537    void insert_codepoints(uint64_t lineNum, uint64_t line_start, uint64_t line_end, const char * buffer) {
538       re::codepoint_t c = 0;
539        ssize_t line_pos = line_start;
540        while (isxdigit(buffer[line_pos])) {
541            if (isdigit(buffer[line_pos])) {
542                c = (c << 4) | (buffer[line_pos] - '0');
543            }
544            else {
545                c = (c << 4) | (tolower(buffer[line_pos]) - 'a' + 10);
546            }
547            line_pos++;
548        }
549        assert(((line_pos - line_start) >= 4) && ((line_pos - line_start) <= 6)); // UCD format 4 to 6 hex digits.       
550        parsedCodePointSet->insert(c);
551    }
552}
553
554void setParsedCodePointSet(){
555    parsedCodePointSet = re::makeCC();
556}
557
558re::CC * getParsedCodePointSet(){
559    return parsedCodePointSet;
560}
561
562// extern "C" {
563//   void wrapped_print_register(char * regName, BitBlock bit_block) {
564//       print_register<BitBlock>(regName, bit_block);
565//   }
566// }
567
568void icgrep_Linking(Module * m, ExecutionEngine * e) {
569    Module::FunctionListType & fns = m->getFunctionList();
570    for (Module::FunctionListType::iterator it = fns.begin(), it_end = fns.end(); it != it_end; ++it) {
571        std::string fnName = it->getName().str();
572        if (fnName == "s2p_block") continue;
573        if (fnName == "process_block") continue;
574        if (fnName == "process_block_initialize_carries") continue;
575       
576        // if (fnName == "wrapped_print_register") {
577        //     e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_print_register);
578        // }
579        if (fnName == "wrapped_report_match") {
580            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&wrapped_report_match);
581        }
582        if (fnName == "insert_codepoints") {
583            e->addGlobalMapping(cast<GlobalValue>(it), (void *)&insert_codepoints);
584        }
585#ifndef DISABLE_PREGENERATED_UCD_FUNCTIONS
586        else {
587            const UCD::ExternalProperty & ep = UCD::resolveExternalProperty(fnName);
588            e->addGlobalMapping(cast<GlobalValue>(it), std::get<0>(ep));
589        }
590#endif
591    }
592}
Note: See TracBrowser for help on using the repository browser.