File: optimize_match.cc

package info (click to toggle)
fparserc%2B%2B 4.5.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, sid, trixie
  • size: 6,132 kB
  • sloc: cpp: 23,297; pascal: 7,097; yacc: 1,650; ansic: 973; makefile: 307; php: 53; sh: 28
file content (766 lines) | stat: -rw-r--r-- 28,625 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
#include "fpconfig.hh"
#include "fparser.hh"
#include "extrasrc/fptypes.hh"

#ifdef FP_SUPPORT_OPTIMIZER

#include <algorithm>
#include <assert.h>
#include <cstring>
#include <cmath>

#include <memory> /* for auto_ptr */

#include "grammar.hh"
#include "optimize.hh"
#include "rangeestimation.hh"
#include "consts.hh"

using namespace FUNCTIONPARSERTYPES;
using namespace FPoptimizer_Grammar;
using namespace FPoptimizer_CodeTree;
using namespace FPoptimizer_Optimize;

namespace
{
    /* Test the given constraints to a given CodeTree */
    template<typename Value_t>
    bool TestImmedConstraints(unsigned bitmask, const CodeTree<Value_t>& tree)
    {
        switch(bitmask & ValueMask)
        {
            case Value_AnyNum: case ValueMask: break;
            case Value_EvenInt:
                if(GetEvennessInfo(tree) != IsAlways)
                    return false;
                break;
            case Value_OddInt:
                if(GetEvennessInfo(tree) != IsNever)
                    return false;
                break;
            case Value_IsInteger:
                if(GetIntegerInfo(tree) != IsAlways) return false;
                break;
            case Value_NonInteger:
                if(GetIntegerInfo(tree) != IsNever) return false;
                break;
            case Value_Logical:
                if(!IsLogicalValue(tree)) return false;
                break;
        }
        switch(bitmask & SignMask)
        {
            case Sign_AnySign: /*case SignMask:*/ break;
            case Sign_Positive:
                if(GetPositivityInfo(tree) != IsAlways) return false;
                break;
            case Sign_Negative:
                if(GetPositivityInfo(tree) != IsNever) return false;
                break;
            case Sign_NoIdea:
                if(GetPositivityInfo(tree) != Unknown) return false;
                break;
        }
        switch(bitmask & OnenessMask)
        {
            case Oneness_Any: case OnenessMask: break;
            case Oneness_One:
                if(!tree.IsImmed()) return false;
                if(!fp_equal(fp_abs(tree.GetImmed()), Value_t(1))) return false;
                break;
            case Oneness_NotOne:
                if(!tree.IsImmed()) return false;
                if(fp_equal(fp_abs(tree.GetImmed()), Value_t(1))) return false;
                break;
        }
        switch(bitmask & ConstnessMask)
        {
            case Constness_Any: /*case ConstnessMask:*/ break;
            case Constness_Const:
                if(!tree.IsImmed()) return false;
                break;
            case Constness_NotConst:
                if(tree.IsImmed()) return false;
                break;
        }
        return true;
    }

    template<unsigned extent, unsigned nbits, typename item_type=unsigned int>
    struct nbitmap
    {
    private:
        static const unsigned bits_in_char = 8;
        static const unsigned per_item = (sizeof(item_type)*bits_in_char)/nbits;
        item_type data[(extent+per_item-1) / per_item];
    public:
        void inc(unsigned index, int by=1)
        {
            data[pos(index)] += by * item_type(1 << shift(index));
        }
        inline void dec(unsigned index) { inc(index, -1); }
        int get(unsigned index) const { return (data[pos(index)] >> shift(index)) & mask(); }

        static inline unsigned pos(unsigned index) { return index/per_item; }
        static inline unsigned shift(unsigned index) { return nbits * (index%per_item); }
        static inline unsigned mask() { return (1 << nbits)-1; }
        static inline unsigned mask(unsigned index) { return mask() << shift(index); }
    };

    struct Needs
    {
        int SubTrees     : 8; // This many subtrees
        int Others       : 8; // This many others (namedholder)
        int minimum_need : 8; // At least this many leaves (restholder may require more)
        int Immeds       : 8; // This many immeds

        nbitmap<VarBegin,2> SubTreesDetail; // This many subtrees of each opcode type

        Needs()
        {
            std::memset(this, 0, sizeof(*this));
        }
        Needs(const Needs& b)
        {
            std::memcpy(this, &b, sizeof(b));
        }
        Needs& operator= (const Needs& b)
        {
            std::memcpy(this, &b, sizeof(b));
            return *this;
        }
    };

    template<typename Value_t>
    Needs CreateNeedList_uncached(const ParamSpec_SubFunctionData& params)
    {
        Needs NeedList;

        // Figure out what we need
        for(unsigned a = 0; a < params.param_count; ++a)
        {
            const ParamSpec& parampair = ParamSpec_Extract<Value_t>(params.param_list, a);
            switch(parampair.first)
            {
                case SubFunction:
                {
                    const ParamSpec_SubFunction& param = *(const ParamSpec_SubFunction*) parampair.second;
                    if(param.data.match_type == GroupFunction)
                        ++NeedList.Immeds;
                    else
                    {
                        ++NeedList.SubTrees;
                        assert( param.data.subfunc_opcode < VarBegin );
                        NeedList.SubTreesDetail.inc(param.data.subfunc_opcode);
                    }
                    ++NeedList.minimum_need;
                    break;
                }
                case NumConstant:
                case ParamHolder:
                    ++NeedList.Others;
                    ++NeedList.minimum_need;
                    break;
            }
        }

        return NeedList;
    }

    template<typename Value_t>
    Needs& CreateNeedList(const ParamSpec_SubFunctionData& params)
    {
        typedef std::map<const ParamSpec_SubFunctionData*, Needs> needlist_cached_t;
        static needlist_cached_t needlist_cached;

        needlist_cached_t::iterator i = needlist_cached.lower_bound(&params);
        if(i != needlist_cached.end() && i->first == &params)
            return i->second;

        return
            needlist_cached.insert(i,
                 std::make_pair(&params, CreateNeedList_uncached<Value_t> (params))
            )->second;
    }
    /* Construct CodeTree from a GroupFunction, hopefully evaluating to a constant value */

    template<typename Value_t>
    CodeTree<Value_t> CalculateGroupFunction(
        const ParamSpec& parampair,
        const MatchInfo<Value_t>& info)
    {
        switch( parampair.first )
        {
            case NumConstant:
            {
                const ParamSpec_NumConstant<Value_t>& param = *(const ParamSpec_NumConstant<Value_t>*) parampair.second;
                return CodeTreeImmed( param.constvalue ); // Note: calculates hash too.
            }
            case ParamHolder:
            {
                const ParamSpec_ParamHolder& param = *(const ParamSpec_ParamHolder*) parampair.second;
                return info.GetParamHolderValueIfFound( param.index );
                // If the ParamHolder is not defined, it will simply
                // return an Undefined tree. This is ok.
            }
            case SubFunction:
            {
                const ParamSpec_SubFunction& param = *(const ParamSpec_SubFunction*) parampair.second;
                /* Synthesize a CodeTree which will take care of
                 * constant-folding our expression. It will also
                 * indicate whether the result is, in fact,
                 * a constant at all. */
                CodeTree<Value_t> result;
                result.SetOpcode( param.data.subfunc_opcode );
                result.GetParams().reserve(param.data.param_count);
                for(unsigned a=0; a<param.data.param_count; ++a)
                {
                    CodeTree<Value_t> tmp(
                        CalculateGroupFunction
                        (ParamSpec_Extract<Value_t> (param.data.param_list, a), info)
                                );
                    result.AddParamMove(tmp);
                }
                result.Rehash(); // This will also call ConstantFolding().
                return result;
            }
        }
        // Issue an un-calculatable tree. (This should be unreachable)
        return CodeTree<Value_t>(); // cNop
    }
}

namespace FPoptimizer_Optimize
{
    /* Test the list of parameters to a given CodeTree */
    /* A helper function which simply checks whether the
     * basic shape of the tree matches what we are expecting
     * i.e. given number of numeric constants, etc.
     */
    template<typename Value_t>
    bool IsLogisticallyPlausibleParamsMatch(
        const ParamSpec_SubFunctionData& params,
        const CodeTree<Value_t>& tree)
    {
        /* First, check if the tree has any chances of matching... */
        /* Figure out what we need. */
        Needs NeedList ( CreateNeedList<Value_t> (params) );

        size_t nparams = tree.GetParamCount();

        if(nparams < size_t(NeedList.minimum_need))
        {
            // Impossible to satisfy
            return false;
        }

        // Figure out what we have (note: we already assume that the opcode of the tree matches!)
        for(size_t a=0; a<nparams; ++a)
        {
            unsigned opcode = tree.GetParam(a).GetOpcode();
            switch(opcode)
            {
                case cImmed:
                    if(NeedList.Immeds > 0) --NeedList.Immeds;
                    else --NeedList.Others;
                    break;
                case VarBegin:
                case cFCall:
                case cPCall:
                    --NeedList.Others;
                    break;
                default:
                    assert( opcode < VarBegin );
                    if(NeedList.SubTrees > 0
                    && NeedList.SubTreesDetail.get(opcode) > 0)
                    {
                        --NeedList.SubTrees;
                        NeedList.SubTreesDetail.dec(opcode);
                    }
                    else --NeedList.Others;
            }
        }

        // Check whether all needs were satisfied
        if(NeedList.Immeds > 0
        || NeedList.SubTrees > 0
        || NeedList.Others > 0)
        {
            // Something came short, impossible to satisfy.
            return false;
        }

        if(params.match_type != AnyParams)
        {
            if(0
            //|| NeedList.Immeds < 0 - already checked
            || NeedList.SubTrees < 0
            || NeedList.Others < 0
            //|| params.count != nparams - already checked
              )
            {
                // Something was too much.
                return false;
            }
        }
        return true;
    }

    /* Test the given parameter to a given CodeTree */
    template<typename Value_t>
    MatchResultType TestParam(
        const ParamSpec& parampair,
        const CodeTree<Value_t>& tree,
        const MatchPositionSpecBaseP& start_at,
        MatchInfo<Value_t>& info)
    {
        /*std::cout << "TestParam(";
        DumpParam(parampair);
        std::cout << ", ";
        DumpTree(tree);
        std::cout << ")\n";*/

        /* What kind of param are we expecting */
        switch( parampair.first )
        {
            case NumConstant: /* A particular numeric value */
            {
                const ParamSpec_NumConstant<Value_t>& param = *(const ParamSpec_NumConstant<Value_t>*) parampair.second;
                if(!tree.IsImmed()) return false;
                Value_t imm = tree.GetImmed();
                switch(param.modulo)
                {
                    case Modulo_None: break;
                    case Modulo_Radians:
                        imm = fp_mod(imm, fp_const_twopi<Value_t>());
                        if(imm < Value_t(0))
                            imm += fp_const_twopi<Value_t>();
                        if(imm > fp_const_pi<Value_t>())
                            imm -= fp_const_twopi<Value_t>();
                        break;
                }
                return fp_equal(imm, param.constvalue);
            }
            case ParamHolder: /* Any arbitrary node */
            {
                const ParamSpec_ParamHolder& param = *(const ParamSpec_ParamHolder*) parampair.second;
                if(!TestImmedConstraints(param.constraints, tree)) return false;
                return info.SaveOrTestParamHolder(param.index, tree);
            }
            case SubFunction:
            {
                const ParamSpec_SubFunction& param = *(const ParamSpec_SubFunction*) parampair.second;
                if(param.data.match_type == GroupFunction)
                { /* A constant value acquired from this formula */
                    if(!TestImmedConstraints(param.constraints, tree)) return false;
                    /* Construct the formula */
                    CodeTree<Value_t> grammar_func = CalculateGroupFunction(parampair, info);
        #ifdef DEBUG_SUBSTITUTIONS
                    DumpHashes(grammar_func);
                    std::cout << *(const void**)&grammar_func.GetImmed();
                    std::cout << "\n";
                    std::cout << *(const void**)&tree.GetImmed();
                    std::cout << "\n";
                    DumpHashes(tree);
                    std::cout << "Comparing ";
                    DumpTree(grammar_func);
                    std::cout << " and ";
                    DumpTree(tree);
                    std::cout << ": ";
                    std::cout << (grammar_func.IsIdenticalTo(tree) ? "true" : "false");
                    std::cout << "\n";
        #endif
                    /* Evaluate it and compare */
                    return grammar_func.IsIdenticalTo(tree);
                }
                else /* A subtree conforming these specs */
                {
                    if(start_at.isnull())
                    {
                        if(!TestImmedConstraints(param.constraints, tree)) return false;
                        if(tree.GetOpcode() != param.data.subfunc_opcode) return false;
                    }
                    return TestParams(param.data, tree, start_at, info, false);
                }
            }
        }
        return false;
    }

    template<typename Value_t>
    struct PositionalParams_Rec
    {
        MatchPositionSpecBaseP start_at; /* child's start_at */
        MatchInfo<Value_t>     info;     /* backup of "info" at start */

        PositionalParams_Rec(): start_at(), info() { }
    };

    template<typename Value_t>
    class MatchPositionSpec_PositionalParams
        : public MatchPositionSpecBase,
          public std::vector<PositionalParams_Rec<Value_t> >
    {
    public:
        explicit MatchPositionSpec_PositionalParams(size_t n)
            : MatchPositionSpecBase(),
              std::vector<PositionalParams_Rec<Value_t> > (n)
              { }
    };

    struct AnyWhere_Rec
    {
        MatchPositionSpecBaseP start_at; /* child's start_at */
        AnyWhere_Rec() : start_at() { }
    };
    class MatchPositionSpec_AnyWhere
        : public MatchPositionSpecBase,
          public std::vector<AnyWhere_Rec>
    {
    public:
        unsigned trypos;   /* which param index to try next */

        explicit MatchPositionSpec_AnyWhere(size_t n)
            : MatchPositionSpecBase(),
              std::vector<AnyWhere_Rec> (n),
              trypos(0)
              { }
    };

    template<typename Value_t>
    MatchResultType TestParam_AnyWhere(
        const ParamSpec& parampair,
        const CodeTree<Value_t>& tree,
        const MatchPositionSpecBaseP& start_at,
        MatchInfo<Value_t>& info,
        std::vector<bool>&  used,
        bool TopLevel)
    {
        FPOPT_autoptr<MatchPositionSpec_AnyWhere> position;
        unsigned a;
        if(!start_at.isnull())
        {
            position = (MatchPositionSpec_AnyWhere*) start_at.get();
            a = position->trypos;
            goto retry_anywhere_2;
        }
        else
        {
            position = new MatchPositionSpec_AnyWhere(tree.GetParamCount());
            a = 0;
        }
        for(; a < tree.GetParamCount(); ++a)
        {
            if(used[a]) continue;

        retry_anywhere:
          { MatchResultType r = TestParam(
                parampair,
                tree.GetParam(a),
                (*position)[a].start_at,
                info);

            (*position)[a].start_at = r.specs;
            if(r.found)
            {
                used[a]               = true; // matched
                if(TopLevel) info.SaveMatchedParamIndex(a);

                position->trypos = a; // in case of backtrack, try a again
                return MatchResultType(true, position.get());
            } }
        retry_anywhere_2:
            if((*position)[a].start_at.get()) // is there another try?
            {
                goto retry_anywhere;
            }
            // no, move on
        }
        return false;
    }

    template<typename Value_t>
    struct AnyParams_Rec
    {
        MatchPositionSpecBaseP start_at; /* child's start_at */
        MatchInfo<Value_t>     info;     /* backup of "info" at start */
        std::vector<bool>      used;     /* which params are remaining */

        explicit AnyParams_Rec(size_t nparams)
            : start_at(), info(), used(nparams) { }
    };
    template<typename Value_t>
    class MatchPositionSpec_AnyParams
        : public MatchPositionSpecBase,
          public std::vector<AnyParams_Rec<Value_t> >
    {
    public:
        explicit MatchPositionSpec_AnyParams(size_t n, size_t m)
            : MatchPositionSpecBase(),
              std::vector<AnyParams_Rec<Value_t> > (n, AnyParams_Rec<Value_t>(m))
              { }
    };

    /* Test the list of parameters to a given CodeTree */
    template<typename Value_t>
    MatchResultType TestParams(
        const ParamSpec_SubFunctionData& model_tree,
        const CodeTree<Value_t>& tree,
        const MatchPositionSpecBaseP& start_at,
        MatchInfo<Value_t>& info,
        bool TopLevel)
    {
        /* When PositionalParams or SelectedParams, verify that
         * the number of parameters is exactly as expected.
         */
        if(model_tree.match_type != AnyParams)
        {
            if(model_tree.param_count != tree.GetParamCount())
                return false;
        }

        /* Verify that the tree basically conforms the shape we are expecting */
        /* This test is not necessary; it may just save us some work. */
        if(!IsLogisticallyPlausibleParamsMatch(model_tree, tree))
        {
            return false;
        }

        /* Verify each parameter that they are found in the tree as expected. */
        switch(model_tree.match_type)
        {
            case PositionalParams:
            {
                /* Simple: Test all given parameters in succession. */
                FPOPT_autoptr<MatchPositionSpec_PositionalParams<Value_t> > position;
                unsigned a;
                if(start_at.get())
                {
                    position = (MatchPositionSpec_PositionalParams<Value_t> *) start_at.get();
                    a = model_tree.param_count - 1;
                    goto retry_positionalparams_2;
                }
                else
                {
                    position = new MatchPositionSpec_PositionalParams<Value_t> (model_tree.param_count);
                    a = 0;
                }

                for(; a < model_tree.param_count; ++a)
                {
                    (*position)[a].info = info;
                retry_positionalparams:
                  { MatchResultType r = TestParam(
                        ParamSpec_Extract<Value_t>(model_tree.param_list, a),
                        tree.GetParam(a),
                        (*position)[a].start_at,
                        info);

                    (*position)[a].start_at = r.specs;
                    if(r.found)
                    {
                        continue;
                  } }
                retry_positionalparams_2:
                    // doesn't match
                    if((*position)[a].start_at.get()) // is there another try?
                    {
                        info = (*position)[a].info;
                        goto retry_positionalparams;
                    }
                    // no, backtrack
                    if(a > 0)
                    {
                        --a;
                        goto retry_positionalparams_2;
                    }
                    // cannot backtrack
                    info = (*position)[0].info;
                    return false;
                }
                if(TopLevel)
                    for(unsigned a = 0; a < model_tree.param_count; ++a)
                        info.SaveMatchedParamIndex(a);
                return MatchResultType(true, position.get());
            }
            case SelectedParams:
                // same as AnyParams, except that model_tree.count==tree.GetParamCount()
                //                       and that there are no RestHolders
            case AnyParams:
            {
                /* Ensure that all given parameters are found somewhere, in any order */

                FPOPT_autoptr<MatchPositionSpec_AnyParams<Value_t> > position;
                std::vector<bool> used( tree.GetParamCount() );
                std::vector<unsigned> depcodes( model_tree.param_count );
                std::vector<unsigned> test_order( model_tree.param_count );
                for(unsigned a=0; a<model_tree.param_count; ++a)
                {
                    const ParamSpec parampair = ParamSpec_Extract<Value_t>(model_tree.param_list, a);
                    depcodes[a] = ParamSpec_GetDepCode(parampair);
                }
                { unsigned b=0;
                for(unsigned a=0; a<model_tree.param_count; ++a)
                    if(depcodes[a] != 0)
                        test_order[b++] = a;
                for(unsigned a=0; a<model_tree.param_count; ++a)
                    if(depcodes[a] == 0)
                        test_order[b++] = a;
                }

                unsigned a;
                if(start_at.get())
                {
                    position = (MatchPositionSpec_AnyParams<Value_t>*) start_at.get();
                    if(model_tree.param_count == 0)
                    {
                        a = 0;
                        goto retry_anyparams_4;
                    }
                    a = model_tree.param_count - 1;
                    goto retry_anyparams_2;
                }
                else
                {
                    position = new MatchPositionSpec_AnyParams<Value_t>
                        (model_tree.param_count, tree.GetParamCount());
                    a = 0;
                    if(model_tree.param_count != 0)
                    {
                        (*position)[0].info   = info;
                        (*position)[0].used   = used;
                    }
                }
                // Match all but restholders
                for(; a < model_tree.param_count; ++a)
                {
                    if(a > 0) // this test is not necessary, but it saves from doing
                    {         // duplicate work, because [0] was already saved above.
                        (*position)[a].info   = info;
                        (*position)[a].used   = used;
                    }
                retry_anyparams:
                  { MatchResultType r = TestParam_AnyWhere<Value_t>(
                        ParamSpec_Extract<Value_t>(model_tree.param_list, test_order[a]),
                        tree,
                        (*position)[a].start_at,
                        info,
                        used,
                        TopLevel);
                    (*position)[a].start_at = r.specs;
                    if(r.found)
                    {
                        continue;
                  } }
                retry_anyparams_2:
                    // doesn't match
                    if((*position)[a].start_at.get()) // is there another try?
                    {
                        info = (*position)[a].info;
                        used = (*position)[a].used;
                        goto retry_anyparams;
                    }
                    // no, backtrack
                retry_anyparams_3:
                    if(a > 0)
                    {
                        --a;
                        goto retry_anyparams_2;
                    }
                    // cannot backtrack
                    info = (*position)[0].info;
                    return false;
                }
            retry_anyparams_4:
                // Capture anything remaining in the restholder
                if(model_tree.restholder_index != 0)
                {
                    //std::vector<bool> used_backup(used);
                    //MatchInfo         info_backup(info);

                    if(!TopLevel
                    || !info.HasRestHolder(model_tree.restholder_index))
                    {
                        std::vector<CodeTree<Value_t> > matches;
                        matches.reserve(tree.GetParamCount());
                        for(unsigned b = 0; b < tree.GetParamCount(); ++b)
                        {
                            if(used[b]) continue; // Ignore subtrees that were already used
                            // Save this tree to this restholder

                            matches.push_back(tree.GetParam(b));
                            used[b] = true;
                            if(TopLevel) info.SaveMatchedParamIndex(b);
                        }
                        if(!info.SaveOrTestRestHolder(model_tree.restholder_index, matches))
                        {
                            // Failure at restholder matching. Backtrack if possible.
                            //used.swap(used_backup);
                            //info.swap(info_backup);
                            goto retry_anyparams_3;
                        }
                        //std::cout << "Saved restholder " << model_tree.restholder_index << "\n";
                    }
                    else
                    {
                        const std::vector<CodeTree<Value_t> >& matches
                            = info.GetRestHolderValues(model_tree.restholder_index);
                        //std::cout << "Testing restholder " << model_tree.restholder_index << std::flush;
                        for(size_t a=0; a<matches.size(); ++a)
                        {
                            bool found = false;
                            for(unsigned b = 0; b < tree.GetParamCount(); ++b)
                            {
                                if(used[b]) continue;
                                if(matches[a].IsIdenticalTo(tree.GetParam(b)))
                                {
                                    used[b] = true;
                                    if(TopLevel) info.SaveMatchedParamIndex(b);
                                    found = true;
                                    break;
                                }
                            }
                            if(!found)
                            {
                                //std::cout << " ... failed\n";
                                // Failure at restholder matching. Backtrack if possible.
                                //used.swap(used_backup);
                                //info.swap(info_backup);
                                goto retry_anyparams_3;
                            }
                        }
                        //std::cout << " ... ok\n";
                    }
                }
                return MatchResultType(true, model_tree.param_count ? position.get() : 0);
            }
            case GroupFunction: // never occurs
                break;
        }
        return false; // doesn't match
    }
}


/* BEGIN_EXPLICIT_INSTANTATION */
#include "instantiate.hh"
namespace FPoptimizer_Optimize
{
#define FP_INSTANTIATE(type) \
    template \
    MatchResultType TestParams( \
        const ParamSpec_SubFunctionData& model_tree, \
        const CodeTree<type> & tree, \
        const MatchPositionSpecBaseP& start_at, \
        MatchInfo<type>& info, \
        bool TopLevel); \
    template \
    bool IsLogisticallyPlausibleParamsMatch( \
        const ParamSpec_SubFunctionData& params, \
        const CodeTree<type>& tree);
    FPOPTIMIZER_EXPLICITLY_INSTANTIATE(FP_INSTANTIATE)
#undef FP_INSTANTIATE
}
/* END_EXPLICIT_INSTANTATION */

#endif