text
stringlengths
1
1.05M
;// TI File $Revision: /main/1 $ ;// Checkin $Date: December 1, 2004 11:11:32 $ ;//########################################################################### ;// ;// FILE: DSP280x_CodeStartBranch.asm ;// ;// TITLE: Branch for redirecting code execution after boot. ;// ;// For these examples, code_start is the first code that is executed after ;// exiting the boot ROM code. ;// ;// The codestart section in the linker cmd file is used to physically place ;// this code at the correct memory location. This section should be placed ;// at the location the BOOT ROM will re-direct the code to. For example, ;// for boot to FLASH this code will be located at 0x3f7ff6. ;// ;// In addition, the example DSP280x projects are setup such that the codegen ;// entry point is also set to the code_start label. This is done by linker ;// option -e in the project build options. When the debugger loads the code, ;// it will automatically set the PC to the "entry point" address indicated by ;// the -e linker option. In this case the debugger is simply assigning the PC, ;// it is not the same as a full reset of the device. ;// ;// The compiler may warn that the entry point for the project is other then ;// _c_init00. _c_init00 is the C environment setup and is run before ;// main() is entered. The code_start code will re-direct the execution ;// to _c_init00 and thus there is no worry and this warning can be ignored. ;// ;//########################################################################### ;// $TI Release: DSP280x C/C++ Header Files V1.70 $ ;// $Release Date: July 27, 2009 $ ;//########################################################################### *********************************************************************** WD_DISABLE .set 1 ;set to 1 to disable WD, else set to 0 .ref _c_int00 .global code_start *********************************************************************** * Function: codestart section * * Description: Branch to code starting point *********************************************************************** .sect "codestart" code_start: .if WD_DISABLE == 1 LB wd_disable ;Branch to watchdog disable code .else LB _c_int00 ;Branch to start of boot.asm in RTS library .endif ;end codestart section *********************************************************************** * Function: wd_disable * * Description: Disables the watchdog timer *********************************************************************** .if WD_DISABLE == 1 .text wd_disable: SETC OBJMODE ;Set OBJMODE for 28x object code EALLOW ;Enable EALLOW protected register access MOVZ DP, #7029h>>6 ;Set data page for WDCR register MOV @7029h, #0068h ;Set WDDIS bit in WDCR to disable WD EDIS ;Disable EALLOW protected register access LB _c_int00 ;Branch to start of boot.asm in RTS library .endif ;end wd_disable .end ;//=========================================================================== ;// End of file. ;//===========================================================================
.global s_prepare_buffers s_prepare_buffers: push %r14 push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0xdf06, %rsi lea addresses_WT_ht+0x1af66, %rdi nop nop nop cmp $59632, %rdx mov $50, %rcx rep movsb nop nop nop nop and %r14, %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %r14 ret .global s_faulty_load s_faulty_load: push %r13 push %r15 push %r9 push %rbp push %rdx push %rsi // Store lea addresses_A+0xf366, %r13 nop nop nop inc %r15 movw $0x5152, (%r13) nop nop nop and $30084, %rbp // Faulty Load lea addresses_A+0x3c66, %rsi nop dec %r13 movb (%rsi), %dl lea oracles, %r15 and $0xff, %rdx shlq $12, %rdx mov (%r15,%rdx,1), %rdx pop %rsi pop %rdx pop %rbp pop %r9 pop %r15 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 8, 'size': 2, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}} {'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 (c) 2013 Hiroshi Matsuike This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "EpxConvexConvexContact.h" #include "EpxClosestFunction.h" namespace EasyPhysics { #ifndef EPX_DOXYGEN_SKIP enum EpxSatType { EpxSatTypePointAFacetB, EpxSatTypePointBFacetA, EpxSatTypeEdgeEdge, }; EpxBool isValidEdge(const EpxVector3 &eA0,const EpxVector3 &eA1,const EpxVector3 &eB0,const EpxVector3 &eB1) { EpxVector3 eAX = cross(eA1,eA0); EpxVector3 eBX = cross(eB1,eB0); EpxFloat a = dot(eB0,eAX); EpxFloat b = dot(eB1,eAX); EpxFloat c = dot(eA0,eBX); EpxFloat d = dot(eA1,eBX); return a * b < 0.0f && c * d < 0.0f && a * d > 0.0f; } EpxBool epxConvexConvexContact_local( const EpxConvexMesh &convexA,const EpxTransform3 &transformA, const EpxConvexMesh &convexB,const EpxTransform3 &transformB, EpxVector3 &normal, EpxFloat &penetrationDepth, EpxVector3 &contactPointA, EpxVector3 &contactPointB) { EpxTransform3 transformAB,transformBA; EpxMatrix3 matrixAB,matrixBA; EpxVector3 offsetAB,offsetBA; // Bローカル→Aローカルへの変換 transformAB = orthoInverse(transformA) * transformB; matrixAB = transformAB.getUpper3x3(); offsetAB = transformAB.getTranslation(); // Aローカル→Bローカルへの変換 transformBA = orthoInverse(transformAB); matrixBA = transformBA.getUpper3x3(); offsetBA = transformBA.getTranslation(); // 最も浅い貫通深度とそのときの分離軸 EpxFloat distanceMin = -EPX_FLT_MAX; EpxVector3 axisMin(0.0f); EpxSatType satType = EpxSatTypeEdgeEdge; EpxBool axisFlip; //---------------------------------------------------------------------------- // 分離軸判定 int satCount = 0; // 面法線の判定を優先させたいので、エッジ外積→面法線の順に判定 // ConvexAとConvexBの外積を分離軸とする EpxUInt32 edgeIdMinA,edgeIdMinB; for(EpxUInt32 eA=0;eA<convexA.m_numEdges;eA++) { const EpxEdge &edgeA = convexA.m_edges[eA]; if(edgeA.type != EpxEdgeTypeConvex) continue; const EpxVector3 edgeVecA = convexA.m_vertices[edgeA.vertId[1]] - convexA.m_vertices[edgeA.vertId[0]]; for(EpxUInt32 eB=0;eB<convexB.m_numEdges;eB++) { const EpxEdge &edgeB = convexB.m_edges[eB]; if(edgeB.type != EpxEdgeTypeConvex) continue; const EpxVector3 edgeVecB = matrixAB * (convexB.m_vertices[edgeB.vertId[1]] - convexB.m_vertices[edgeB.vertId[0]]); // Gauss map algorithm from GDC 2013 physics tutorial EpxVector3 eA0 = convexA.m_facets[edgeA.facetId[0]].normal; EpxVector3 eA1 = convexA.m_facets[edgeA.facetId[1]].normal; EpxVector3 eB0 = -matrixAB * convexB.m_facets[edgeB.facetId[0]].normal; EpxVector3 eB1 = -matrixAB * convexB.m_facets[edgeB.facetId[1]].normal; if(!isValidEdge(eA0,eA1,eB0,eB1)) continue; EpxVector3 separatingAxis = cross(edgeVecA,edgeVecB); if(lengthSqr(separatingAxis) < EPX_EPSILON*EPX_EPSILON) continue; separatingAxis = normalize(separatingAxis); EpxVector3 pA = convexA.m_vertices[edgeA.vertId[0]]; EpxVector3 pB = offsetAB + matrixAB * convexB.m_vertices[edgeB.vertId[0]]; if(dot(separatingAxis,pA) > 0.0f) { // 原点は必ずConvexの内側に存在すること separatingAxis = -separatingAxis; } EpxFloat d = dot(separatingAxis,pA - pB); satCount++; if(d >= 0.0f) { return false; } if(distanceMin < d) { distanceMin = d; axisMin = separatingAxis; satType = EpxSatTypeEdgeEdge; edgeIdMinA = eA; edgeIdMinB = eB; } } } // ConvexAの面法線を分離軸とする for(EpxUInt32 f=0;f<convexA.m_numFacets;f++) { const EpxFacet &facet = convexA.m_facets[f]; const EpxVector3 separatingAxis = facet.normal; EpxVector3 axisB = matrixBA * separatingAxis; EpxVector3 pA = offsetBA + matrixBA * convexA.m_vertices[facet.vertId[0]]; EpxFloat minB = EPX_FLT_MAX; for(EpxUInt32 i=0;i<convexB.m_numVertices;i++) { EpxFloat prj = dot(axisB,convexB.m_vertices[i] - pA); minB = EPX_MIN(minB,prj); } satCount++; if(minB >= 0.0f) { return false; } if(distanceMin < minB) { distanceMin = minB; axisMin = -separatingAxis; satType = EpxSatTypePointBFacetA; axisFlip = true; } } // ConvexBの面法線を分離軸とする for(EpxUInt32 f=0;f<convexB.m_numFacets;f++) { const EpxFacet &facet = convexB.m_facets[f]; const EpxVector3 separatingAxis = matrixAB * facet.normal; EpxVector3 pB = offsetAB + matrixAB * convexB.m_vertices[facet.vertId[0]]; EpxFloat minA = EPX_FLT_MAX; for(EpxUInt32 i=0;i<convexA.m_numVertices;i++) { EpxFloat prj = dot(separatingAxis,convexA.m_vertices[i] - pB); minA = EPX_MIN(minA,prj); } satCount++; if(minA >= 0.0f) { return false; } if(distanceMin < minA) { distanceMin = minA; axisMin = separatingAxis; satType = EpxSatTypePointAFacetB; axisFlip = false; } } // ここまで到達したので、2つの凸メッシュは交差している。 // また、反発ベクトル(axisMin)と貫通深度(distanceMin)が求まった。 // 反発ベクトルはAを押しだす方向をプラスにとる。 //int satTotal = convexA.m_numFacets + convexB.m_numFacets + convexA.m_numEdges * convexB.m_numEdges; //epxPrintf("sat check count %d / %d\n",satCount,satTotal); //---------------------------------------------------------------------------- // 衝突座標検出 int collCount = 0; EpxFloat closestMinSqr = EPX_FLT_MAX; EpxVector3 closestPointA,closestPointB; EpxVector3 separation = 1.1f * fabs(distanceMin) * axisMin; if(satType == EpxSatTypeEdgeEdge) { const EpxEdge &edgeA = convexA.m_edges[edgeIdMinA]; const EpxEdge &edgeB = convexB.m_edges[edgeIdMinB]; EpxVector3 sA,sB; epxGetClosestTwoSegments( separation + convexA.m_vertices[edgeA.vertId[0]], separation + convexA.m_vertices[edgeA.vertId[1]], offsetAB + matrixAB * convexB.m_vertices[edgeB.vertId[0]], offsetAB + matrixAB * convexB.m_vertices[edgeB.vertId[1]], sA,sB); EpxFloat dSqr = lengthSqr(sA-sB); closestMinSqr = dSqr; closestPointA = sA; closestPointB = sB; collCount++; } else { // 分離平面を挟んで向かい合う面を抽出 EpxUInt8 facetsA[EPX_CONVEX_MESH_MAX_FACETS]; EpxUInt8 facetsB[EPX_CONVEX_MESH_MAX_FACETS]; EpxUInt8 numFacetsA = 0; EpxUInt8 numFacetsB = 0; if(satType == EpxSatTypePointBFacetA) { for(EpxUInt8 fA=0;fA<convexA.m_numFacets;fA++) { const EpxFacet &facetA = convexA.m_facets[fA]; EpxFloat checkA = dot(facetA.normal,-axisMin); if(checkA < 0.99f && axisFlip) { // 判定軸が面Aの法線のとき、向きの違うAの面は判定しない continue; } if(checkA < 0.0f) { // 衝突面と逆に向いている面は判定しない continue; } facetsA[numFacetsA++] = (EpxUInt8)fA; } EpxFloat checkBMax = -1.0f; for(EpxUInt8 fB=0;fB<convexB.m_numFacets;fB++) { const EpxFacet &facetB = convexB.m_facets[fB]; EpxFloat checkB = dot(facetB.normal,matrixBA * axisMin); if(checkB > checkBMax) { checkBMax = checkB; facetsB[0] = fB; numFacetsB = 1; } else if(checkB > checkBMax - EPX_EPSILON) { // checkB == checkBMax facetsB[numFacetsB++] = fB; } } } else { // satType == EpxSatTypePointAFacetB for(EpxUInt8 fB=0;fB<convexB.m_numFacets;fB++) { const EpxFacet &facetB = convexB.m_facets[fB]; EpxFloat checkB = dot(facetB.normal,matrixBA * axisMin); if(checkB < 0.99f && !axisFlip) { // 判定軸が面Bの法線のとき、向きの違うBの面は判定しない continue; } if(checkB < 0.0f) { // 衝突面と逆に向いている面は判定しない continue; } facetsB[numFacetsB++] = (EpxUInt8)fB; } EpxFloat checkAMax = -1.0f; for(EpxUInt8 fA=0;fA<convexA.m_numFacets;fA++) { const EpxFacet &facetA = convexA.m_facets[fA]; EpxFloat checkA = dot(facetA.normal,-axisMin); if(checkA > checkAMax) { checkAMax = checkA; facetsA[0] = fA; numFacetsA = 1; } else if(checkA > checkAMax - EPX_EPSILON) { // checkA == checkAMax facetsA[numFacetsA++] = fA; } } } for(EpxUInt8 fA=0;fA<numFacetsA;fA++) { const EpxFacet &facetA = convexA.m_facets[facetsA[fA]]; for(EpxUInt8 fB=0;fB<numFacetsB;fB++) { const EpxFacet &facetB = convexB.m_facets[facetsB[fB]]; collCount++; // 面Aと面Bの最近接点を求める EpxVector3 triangleA[3] = { separation + convexA.m_vertices[facetA.vertId[0]], separation + convexA.m_vertices[facetA.vertId[1]], separation + convexA.m_vertices[facetA.vertId[2]], }; EpxVector3 triangleB[3] = { offsetAB + matrixAB * convexB.m_vertices[facetB.vertId[0]], offsetAB + matrixAB * convexB.m_vertices[facetB.vertId[1]], offsetAB + matrixAB * convexB.m_vertices[facetB.vertId[2]], }; // 頂点A→面Bの最近接点算出 for(int i=0;i<3;i++) { EpxVector3 s; epxGetClosestPointTriangle(triangleA[i],triangleB[0],triangleB[1],triangleB[2],matrixAB * facetB.normal,s); EpxFloat dSqr = lengthSqr(triangleA[i]-s); if(dSqr < closestMinSqr) { closestMinSqr = dSqr; closestPointA = triangleA[i]; closestPointB = s; } } // 頂点B→面Aの最近接点算出 for(int i=0;i<3;i++) { EpxVector3 s; epxGetClosestPointTriangle(triangleB[i],triangleA[0],triangleA[1],triangleA[2],facetA.normal,s); EpxFloat dSqr = lengthSqr(triangleB[i]-s); if(dSqr < closestMinSqr) { closestMinSqr = dSqr; closestPointA = s; closestPointB = triangleB[i]; } } } } } //epxPrintf("intersection check count %d\n",collCount); normal = transformA.getUpper3x3() * axisMin; penetrationDepth = distanceMin; contactPointA = closestPointA - separation; contactPointB = offsetBA + matrixBA * closestPointB; return true; } #endif // EPX_DOXYGEN_SKIP EpxBool epxConvexConvexContact( const EpxConvexMesh &convexA,const EpxTransform3 &transformA, const EpxConvexMesh &convexB,const EpxTransform3 &transformB, EpxVector3 &normal, EpxFloat &penetrationDepth, EpxVector3 &contactPointA, EpxVector3 &contactPointB) { // 座標系変換の回数を減らすため、面数の多い方を座標系の基準とする EpxBool ret; if(convexA.m_numFacets >= convexB.m_numFacets) { ret = epxConvexConvexContact_local( convexA,transformA, convexB,transformB, normal,penetrationDepth,contactPointA,contactPointB); } else { ret = epxConvexConvexContact_local( convexB,transformB, convexA,transformA, normal,penetrationDepth,contactPointB,contactPointA); normal = -normal; } return ret; } } // namespace EasyPhysics
; A138997: First differences of Frobenius numbers for 6 successive numbers A138986. ; 1,1,1,1,8,2,2,2,2,14,3,3,3,3,20,4,4,4,4,26,5,5,5,5,32,6,6,6,6,38,7,7,7,7,44,8,8,8,8,50,9,9,9,9,56,10,10,10,10,62,11,11,11,11,68,12,12,12,12,74,13,13,13,13,80,14,14,14,14,86,15,15,15,15,92,16,16,16,16,98,17,17,17,17,104,18,18,18,18,110,19,19,19,19,116,20,20,20,20,122 mov $4,2 mov $6,$0 lpb $4 mov $0,$6 sub $4,1 add $0,$4 mov $2,$0 add $0,2 div $2,5 mul $2,$0 mov $0,$2 mov $3,$4 mul $3,$2 add $5,$3 lpe min $6,1 mul $6,$0 mov $0,$5 sub $0,$6 add $0,1
#include "LuxPanel.h" #include "panelComponents.h" #include "LightMeterPanelComponents.h" #include "HardwareInterfaces.h" #include "LightMeterHardwareInterfaces.h" #include <Arduino.h> #include "TeensyView.h" #include <SparkFunTSL2561.h> #include <SparkFunBQ27441.h> #define KValue 16 extern OLEDFunctions oled; // Create an SFE_TSL2561 object, here called "light": extern SFE_TSL2561 light; extern boolean gain; // Gain setting, 0 = X1, 1 = X16; extern unsigned int ms; // Integration ("shutter") time in milliseconds const float fStopTable[24] = {1.4, 1.8, 2.0, 2.2, 2.5, 2.8, 3.2, 3.5, 4, 4.5, 5, 5.6, 6.3, 7.1, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22}; const float exposureTable[3] = {0.041666666, 0.033333333, 0.016666666}; const float isoTable[7] = {100, 200, 400, 800, 1600, 3200, 6400}; uint8_t isoTableSize = 7; extern const uint8_t PIN_POWER_ON = 16; LuxPanel::LuxPanel( void ) { upButton.setHardware(new ArduinoDigitalIn( 22 ), 1); add( &upButton ); downButton.setHardware(new ArduinoDigitalIn( 23 ), 1); add( &downButton ); encButton.setHardware(new ArduinoDigitalIn( 4 ), 1); add( &encButton ); dataWheel.setHardware(new TeensyEncoderIn( 8, 9 ) ); add( &dataWheel ); fStopSetting = 7; exposureSetting = 1; isoSetting = 3; state = PInit; good = false; luxAccumulator = 0; sampleCount = 0; lux = 0; triggerState = hSRun; lipoGood = false; } void LuxPanel::tickStateMachine( int msTicksDelta ) { freshenComponents( msTicksDelta ); bool drawDisplay = false; unsigned int data0, data1; //***** PROCESS THE LOGIC *****// //Now do the states. PState_t nextState = state; switch( state ) { case PInit: //Can't be running, if button pressed move on oled.clear(PAGE); drawDisplay = true; nextState = PDisplayPhotoValueInit; break; case PDisplayPhotoValueInit: drawDisplay = true; oled.clear(PAGE); oled.drawMenu("Photo", isoTable[isoSetting], false, true ); nextState = PDisplayPhotoValue; break; case PDisplayPhotoValue: if( dataWheel.serviceChanged() ) { if( dataWheel.getDiff() > 0 ) { if( fStopSetting < 23 ) { fStopSetting++; } dataWheel.removeDiff(7); } if( dataWheel.getDiff() < 0 ) { if( fStopSetting > 0 ) { fStopSetting--; } dataWheel.removeDiff(7); } } if( upButton.serviceRisingEdge() ) { nextState = PDisplayVideoValueInit; } else { if (light.getData(data0,data1)) { //get the lux double tempLux; good = light.getLux(gain,ms,data0,data1,tempLux); // True if neither sensor is saturated updateLux( tempLux ); //exposure time = stop squared * K / ( ISO * Lux ) float T = pow(fStopTable[fStopSetting],2)*KValue/(lux*(isoTable[isoSetting])); oled.eraseLowerArea(); oled.drawLeftBracket(32,10); oled.drawRightBracket(122,10); oled.drawFNumStyle1( fStopTable[fStopSetting], 2, 13 ); oled.drawExposureStyle1( T, 60, 14 ); if( good == false ) { oled.drawNo( 33, 12 ); } if( triggerState == hSHeld ) { oled.holdStyle1( 100, 10 ); } if( triggerState == hSAveraging ) { oled.aveStyle1( 100, 10 ); } oled.setCursor( 111, 17 ); oled.print("S"); drawDisplay = true; } } downButton.serviceRisingEdge(); break; case PDisplayVideoValueInit: drawDisplay = true; oled.clear(PAGE); oled.drawMenu("Video", isoTable[isoSetting], true, true ); //oled.drawBrackets(); nextState = PDisplayVideoValue; break; case PDisplayVideoValue: if( dataWheel.serviceChanged() ) { if( dataWheel.getDiff() > 0 ) { if( exposureSetting < 2 ) { exposureSetting++; } dataWheel.removeDiff(7); } if( dataWheel.getDiff() < 0 ) { if( exposureSetting > 0 ) { exposureSetting--; } dataWheel.removeDiff(7); } } if( downButton.serviceRisingEdge() ) { nextState = PDisplayPhotoValueInit; } else if( upButton.serviceRisingEdge() ) { nextState = PSetISOInit; } else { if (light.getData(data0,data1)) { //get the lux double tempLux; good = light.getLux(gain,ms,data0,data1,tempLux); // True if neither sensor is saturated updateLux( tempLux ); //exposure time = stop squared * K / ( ISO * Lux ) //float T = pow(fStopTable[fStopSetting],2)*KValue/(lux*(isoTable[isoSetting])); float N = sqrt((exposureTable[exposureSetting]*lux*isoTable[isoSetting])/KValue); oled.eraseLowerArea(); oled.drawLeftBracket(32,10); oled.drawRightBracket(122,10); oled.drawExposureStyle2( exposureTable[exposureSetting], 2, 13 ); oled.drawFNumStyle2( N, 60, 14 ); if( good == false ) { oled.drawNo( 33, 12 ); } if( triggerState == hSHeld ) { oled.holdStyle1( 100, 10 ); } if( triggerState == hSAveraging ) { oled.aveStyle1( 100, 10 ); } drawDisplay = true; } } break; case PSetISOInit: dataWheel.clearDiff(); drawDisplay = true; oled.clear(PAGE); //menu part oled.drawMenu("ISO", true, true ); //Draw last value oled.drawISOScale( isoSetting ); nextState = PSetISO; break; case PSetISO: if( dataWheel.serviceChanged() ) { drawDisplay = true; //Erase part oled.setCursor(0,11); oled.print(" "); if( dataWheel.getDiff() > 0 ) { if( isoSetting < 6 ) { isoSetting++; } dataWheel.removeDiff(8); } if( dataWheel.getDiff() < 0 ) { if( isoSetting > 0 ) { isoSetting--; } dataWheel.removeDiff(8); } //Draw new value oled.drawISOScale( isoSetting ); } if( downButton.serviceRisingEdge() ) { nextState = PDisplayVideoValueInit; } if( upButton.serviceRisingEdge() ) { nextState = pSystemInit; } break; case pSystemInit: dataWheel.clearDiff(); drawDisplay = true; oled.clear(PAGE); //menu part oled.drawMenu("System", true, false ); //Draw last value oled.setCursor(64,11); oled.print((float)lipo.voltage()/1000, 2); oled.print("V"); oled.setCursor(0,20); oled.print((float)lipo.soc(), 0); oled.print("%"); //Clear wheel state dataWheel.serviceChanged(); nextState = pSystem; break; case pSystem: //Draw new value if( lipoGood == true ) { oled.setCursor(0,11); oled.print("OK!"); } else { oled.setCursor(0,11); oled.print("NOBATT"); } oled.setCursor(64,20); oled.print(lipo.current(AVG)); oled.print("mA "); oled.setCursor(64,11); oled.print((float)lipo.voltage()/1000, 2); if( encButton.serviceRisingEdge() ) { oled.clear(PAGE); oled.setFontType(1); oled.setCursor(6, 6); oled.print("Power down."); oled.display(); delay(1000); digitalWrite(PIN_POWER_ON, LOW); delay(4000); oled.clear(PAGE); oled.setCursor(6, 6); oled.print("Failed!!!"); oled.display(); delay(1000); oled.setFontType(0); oled.clear(PAGE); oled.display(); } drawDisplay = true; if( downButton.serviceRisingEdge() ) { nextState = PSetISOInit; } if( upButton.serviceRisingEdge() ) { nextState = pMaryInit; } break; case pMaryInit: dataWheel.clearDiff(); encButton.serviceRisingEdge(); drawDisplay = true; oled.clear(PAGE); //menu part oled.drawMenu("Mary", true, false ); heartCount = 0; nextState = pMary; break; case pMary: if( encButton.serviceRisingEdge() ) { if( heartCount < 7 ) { oled.drawHeart(heartCount * 18, 12); drawDisplay = true; heartCount++; } } //Draw new value if( downButton.serviceRisingEdge() ) { nextState = pSystemInit; } if( upButton.serviceRisingEdge() ) { nextState = PDisplayLuxValueInit; } break; case PDisplayLuxValueInit: drawDisplay = true; oled.clear(PAGE); //menu part oled.drawMenu("Lux", false, false ); nextState = PDisplayLuxValue; break; case PDisplayLuxValue: if( downButton.serviceRisingEdge() ) { nextState = pMaryInit; } if( upButton.serviceRisingEdge() ) { //nextState = ; } if (light.getData(data0,data1)) { drawDisplay = true; double tempLux; good = light.getLux(gain,ms,data0,data1,tempLux); // True if neither sensor is saturated updateLux( tempLux ); oled.setCursor(0,11); oled.print(data0); oled.print(" "); oled.setCursor(64,11); oled.print(data1); oled.print(" "); // Print out the results: oled.setCursor(0,20); oled.print(" lux: "); oled.print(lux); oled.print(" "); oled.setCursor(116,20); if (good) oled.print(" "); else oled.drawNo(120,20); } else { drawDisplay = true; oled.setCursor(0,11); oled.print("ERROR"); } break; default: nextState = PInit; break; } state = nextState; if( drawDisplay )oled.display(); holdState_t nextTriggerState = triggerState; switch( triggerState ) { case hSRun: //Can't be running, if button pressed move on if( encButton.serviceRisingEdge() ) { nextTriggerState = hSAveraging; luxAccumulator = lux; sampleCount = 1; } encButton.serviceFallingEdge(); break; case hSAveraging: if( encButton.serviceFallingEdge() ) { nextTriggerState = hSHeld; } break; case hSHeld: if( encButton.serviceRisingEdge() ) { nextTriggerState = hSRun; luxAccumulator = 0; sampleCount = 0; } break; default: luxAccumulator = 0; sampleCount = 0; lux = 0; nextTriggerState = hSRun; break; } triggerState = nextTriggerState; } void LuxPanel::updateLux( double inputLux ) { if( triggerState == hSAveraging ) { luxAccumulator += inputLux; sampleCount++; lux = luxAccumulator / sampleCount; } if( triggerState == hSRun ) { lux = inputLux; } if( triggerState == hSHeld ) { lux = luxAccumulator / sampleCount; } }
;================================================================================ ; Randomize Book of Mudora ;-------------------------------------------------------------------------------- LoadLibraryItemGFX: LDA.l LibraryItem JSL.l PrepDynamicTile RTL ;-------------------------------------------------------------------------------- DrawLibraryItemGFX: PHA LDA.l LibraryItem JSL.l DrawDynamicTile PLA RTL ;-------------------------------------------------------------------------------- SetLibraryItem: PHA LDA LibraryItem : TAY PLA JSL.l ItemSet_Library ; contains thing we wrote over RTL ;-------------------------------------------------------------------------------- ;0x0087 - Hera Room w/key ;================================================================================ ; Randomize Bonk Keys ;-------------------------------------------------------------------------------- !REDRAW = "$7F5000" ;-------------------------------------------------------------------------------- LoadBonkItemGFX: LDA.b #$08 : STA $0F50, X ; thing we wrote over LoadBonkItemGFX_inner: LDA.b #$00 : STA !REDRAW JSR LoadBonkItem JSL.l PrepDynamicTile RTL ;-------------------------------------------------------------------------------- DrawBonkItemGFX: PHA LDA !REDRAW : BEQ .skipInit ; skip init if already ready JSL.l LoadBonkItemGFX_inner BRA .done ; don't draw on the init frame .skipInit JSR LoadBonkItem JSL.l DrawDynamicTileNoShadow .done PLA RTL ;-------------------------------------------------------------------------------- GiveBonkItem: JSR LoadBonkItem CMP #$24 : BNE .notKey .key PHY : LDY.b #$24 : JSL.l AddInventory : PLY ; do inventory processing for a small key LDA $7EF36F : INC A : STA $7EF36F LDA.b #$2F : JSL.l Sound_SetSfx3PanLong JSL CountBonkItem RTL .notKey PHY : TAY : JSL.l Link_ReceiveItem : PLY JSL CountBonkItem RTL ;-------------------------------------------------------------------------------- LoadBonkItem: LDA $A0 ; check room ID - only bonk keys in 2 rooms so we're just checking the lower byte CMP #115 : BNE + ; Desert Bonk Key LDA.l BonkKey_Desert BRA ++ + : CMP #140 : BNE + ; GTower Bonk Key LDA.l BonkKey_GTower BRA ++ + LDA.b #$24 ; default to small key ++ RTS
; vim: set ft=nasm : [BITS 32] section .asm global print:function global os_getkey:function global os_putchar:function global os_malloc:function global os_free:function global os_process_load_start:function global os_process_get_arguments:function global os_system:function global os_exit:function ; void os_exit() os_exit: push ebp mov ebp, esp mov eax, 0 ; command exit int 0x80 pop ebp ret ; void print(const char* massage) print: push ebp mov ebp, esp push dword[ebp + 8] ; variable massage mov eax, 1 ; command print int 0x80 add esp, 4 pop ebp ret ; int getkey() os_getkey: push ebp mov ebp, esp mov eax, 2 ; command getkey int 0x80 pop ebp ret ; void putchar(char c) os_putchar: push ebp mov ebp, esp mov eax, 3 ; command putchar push dword[ebp + 8] ; variable c int 0x80 add esp, 4 pop ebp ret ; void* os_malloc(size_t size) os_malloc: push ebp mov ebp, esp mov eax, 4 ; command malloc push dword[ebp + 8] ; variable size int 0x80 add esp, 4 pop ebp ret ; void os_free(void* ptr) os_free: push ebp mov ebp, esp mov eax, 5 ; command free push dword[ebp + 8] int 0x80 add esp, 4 pop ebp ret ; void os_process_load_start(const char* filename) os_process_load_start: push ebp mov ebp, esp mov eax, 6 ; command process_load_start push dword[ebp + 8] int 0x80 add esp, 4 pop ebp ret ; int os_system(struct command_argument* arguments) os_system: push ebp mov ebp, esp mov eax, 7 ; command process system (runs a system command based on arguments) push dword[ebp + 8] int 0x80 add esp, 4 pop ebp ret ; void os_process_get_arguments(struct process_arguments* arguments); os_process_get_arguments: push ebp mov ebp, esp mov eax, 8 ; command get process arguments push dword[ebp + 8] ; variable arguments int 0x80 add esp, 4 pop ebp ret
#include <assert.h> #include <iostream> #include <stdint.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Verifier.h> #include <llvm/IR/IRBuilder.h> #include "eval.h" #include "func.h" #include "runtime_interface.h" using namespace std; extern type_map types_map; extern symtab_map symtabs; extern ctype_map ctypes_map; extern func_map funcs_map; extern const_map constants; extern RTInterface rt_glue; static Expr* expr_resolve_ids(const EvalCtx& ectx, const Expr* expr); static Expr* eval_rewrite_sizeof(const EvalCtx&, const FCall* fc, bool bits); class ExprRewriteConsts : public ExprRewriteAll { public: ExprRewriteConsts(const const_map& consts) : constants(consts) {} Expr* visit(const Id* id) override { Expr *new_expr; new_expr = getNewExpr(id); return (new_expr == NULL) ? id->copy() : new_expr; } private: Expr* getNewExpr(const Id* id) { const_map::const_iterator it; it = constants.find(id->getName()); if (it == constants.end()) return NULL; return ((*it).second)->copy(); } const const_map& constants; }; class ExprResolveIds : public ExprRewriteAll { public: ExprResolveIds(const EvalCtx& evalctx) : ectx(evalctx) {} Expr* visit(const Id* id) override { Expr *result = ectx.resolveVal(id); return (result == NULL) ? id->copy() : result; } Expr* visit(const IdStruct* ids) override { Expr *result = ectx.resolveVal(ids); return (result == NULL) ? ids->copy() : result; } Expr* visit(const IdArray* ida) override { Expr *result = ectx.resolveVal(ida); return (result == NULL) ? ida->copy() : result; } Expr* visit(const FCall* fc) override { if (fc->getName() == "sizeof_bits") return eval_rewrite_sizeof(ectx, fc, true); else if (fc->getName() == "sizeof_bytes") return eval_rewrite_sizeof(ectx, fc, false); return ExprRewriteAll::visit(fc); } private: const EvalCtx& ectx; }; static Expr* expr_resolve_ids(const EvalCtx& ectx, const Expr* expr) { ExprResolveIds eri(ectx); return eri.apply(expr); } /* return non-null if new expr is allocated to replace cur_expr */ Expr* expr_resolve_consts(const const_map& consts, Expr* cur_expr) { ExprRewriteConsts erc(consts); return erc.apply(cur_expr); } static Expr* eval_sizeof_type(const EvalCtx& ectx, const Id* id) { Expr *ret_size; Expr *resolved_closure; const SymbolTable *st; const Type *t; if (id == NULL) return nullptr; if (types_map.count(id->getName())) { t = types_map[id->getName()]; assert (t != nullptr); resolved_closure = FCall::mkBaseClosure(t); } else { t = ectx.getType(id); if (!t) return nullptr; resolved_closure = ectx.resolveVal(id); if (!resolved_closure) return nullptr; } /* st = symbol table for type to get size of */ st = symtabs[t->getName()]; /* get typified size expr, fill in closure param with dynamic type */ ret_size = st->getThunkType()->getSize()->copyFCall(); ret_size = Expr::rewriteReplace( ret_size, rt_glue.getThunkClosure(), resolved_closure); return ret_size; } static Expr* eval_sizeof_typedef(const Id* id) { if (ctypes_map.count(id->getName()) == 0) return NULL; return new Number(ctypes_map[id->getName()]); } static Expr* eval_rewrite_sizeof(const EvalCtx& ectx, const FCall* fc, bool bits) { const ExprList *exprs; Expr *ret_size; /* fc name is either sizeof_bytes of sizeof_bits */ /* should probably make this its own class? */ exprs = fc->getExprs(); if (exprs->size() != 1) { cerr << "sizeof expects 1 argument. Got: "; fc->print(cerr); cerr << endl; return NULL; } auto front_id = dynamic_cast<const Id*>(exprs->front().get()); if (front_id == NULL) { cerr << "sizeof expects id for argument. Got: "; fc->print(cerr); cerr << endl; return NULL; } ret_size = eval_sizeof_type(ectx, front_id); if (ret_size == NULL) ret_size = eval_sizeof_typedef(front_id); if (ret_size == NULL) { cerr << "sizeof couldn't figure out size of '"; fc->print(cerr); cerr << "'\n";; return NULL; } /* convert bits to bytes */ if (bits == false) ret_size = new AOPDiv(ret_size, new Number(8)); return ret_size; } llvm::Value* evalAndGen(const EvalCtx& ectx, const Expr* expr) { Expr *ret; llvm::Value *v; ret = eval(ectx, expr); if (ret == NULL) return NULL; v = ret->codeGen(); delete ret; return v; } Expr* eval(const EvalCtx& ectx, const Expr* expr) { Expr *our_expr, *tmp_expr; /* first, get simplified copy */ our_expr = expr->simplify(); /* resolve all labeled constants into numbers */ tmp_expr = expr_resolve_consts(constants, our_expr); if (tmp_expr != NULL) { delete our_expr; our_expr = tmp_expr; } /* resolve all unknown ids into function calls */ tmp_expr = expr_resolve_ids(ectx, our_expr); if (tmp_expr != NULL) { delete our_expr; our_expr = tmp_expr; } tmp_expr = expr_resolve_consts(constants, our_expr); if (tmp_expr != NULL) { delete our_expr; our_expr = tmp_expr; } if (*our_expr != expr) our_expr = evalReplace(ectx, our_expr); return our_expr; } Expr* evalReplace(const EvalCtx& ectx, Expr* expr) { Expr *new_expr; if (expr == NULL) return NULL; new_expr = eval(ectx, expr); delete expr; return new_expr; }
// Copyright Carl Philipp Reh 2006 - 2019. // 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) #include <sge/cegui/to_wstring.hpp> #include <sge/cegui/impl/prefix.hpp> #include <sge/cegui/impl/to_absolute_path.hpp> #include <fcppt/config/external_begin.hpp> #include <filesystem> #include <fcppt/config/external_end.hpp> std::filesystem::path sge::cegui::impl::to_absolute_path( sge::cegui::impl::prefix const &_prefix, CEGUI::String const &_filename) { return _prefix.get() / sge::cegui::to_wstring(_filename); }
ORG 0000H LXI SP,3FF0H MVI A,05H MOV B,A MOV C,B MOV D,C MOV E,D INR A STA 2050H INR A LXI H,2051H MOV M,A LDA 2050H INR A INX H MOV M,A RST 1 HLT
#include once <printnum.asm> #include once <div16.asm> #include once <neg16.asm> #include once <attr.asm> __PRINTI16: ; Prints a 16bits signed in HL ; Converts 16 to 32 bits PROC LOCAL __PRINTU_LOOP ld a, h or a jp p, __PRINTU16 call __PRINT_MINUS call __NEGHL __PRINTU16: ld b, 0 __PRINTU_LOOP: ld a, h or l jp z, __PRINTU_START push bc ld de, 10 call __DIVU16_FAST ; Divides by DE. DE = MODULUS at exit. Since < 256, E = Modulus pop bc ld a, e or '0' ; Stores ASCII digit (must be print in reversed order) push af inc b jp __PRINTU_LOOP ; Uses JP in loops ENDP
; A105968: a(n) = 4*a(n-1) - a(n-2) - 2*(-1)^n, a(0) = 1, a(1) = 4. ; 1,4,13,50,185,692,2581,9634,35953,134180,500765,1868882,6974761,26030164,97145893,362553410,1353067745,5049717572,18845802541,70333492594,262488167833,979619178740,3655988547125,13644335009762,50921351491921,190041070957924,709242932339773,2646930658401170 mov $1,4 mov $3,3 lpb $0 sub $0,1 add $3,$1 add $1,$3 add $3,$1 lpe add $2,$1 mov $1,40 mul $1,$2 sub $1,80 div $1,120 add $1,1
; A052747: a(0) = a(1) = a(2) = 0; a(n) = n!/(n-2) for n > 2. ; 0,0,0,6,12,40,180,1008,6720,51840,453600,4435200,47900160,566092800,7264857600,100590336000,1494484992000,23712495206400,400148356608000,7155594141696000,135161222676480000,2688996956405760000,56200036388880384000,1231048416137379840000,28202200078783610880000,674400436666564608000000,16803810880275234816000000,435554778016734086430720000,11726474792758225403904000000,327472666434803776094208000000,9473316421863966379868160000000,283546160488893890266398720000000 mov $2,$0 lpb $0 sub $0,1 mul $2,$0 trn $0,1 add $0,1 mov $1,$3 sub $2,$3 mov $3,$2 lpe mov $0,$1
; sprite facing directions const_def 0, $04 const SPRITE_FACING_DOWN ; $00 const SPRITE_FACING_UP ; $04 const SPRITE_FACING_LEFT ; $08 const SPRITE_FACING_RIGHT ; $0C const_def 0, $40 const NPC_MOVEMENT_DOWN ; $00 const NPC_MOVEMENT_UP ; $40 const NPC_MOVEMENT_LEFT ; $80 const NPC_MOVEMENT_RIGHT ; $C0 NPC_CHANGE_FACING EQU $E0 ; player direction constants const_def const PLAYER_DIR_BIT_RIGHT ; 0 const PLAYER_DIR_BIT_LEFT ; 1 const PLAYER_DIR_BIT_DOWN ; 2 const PLAYER_DIR_BIT_UP ; 3 PLAYER_DIR_RIGHT EQU 1 << PLAYER_DIR_BIT_RIGHT PLAYER_DIR_LEFT EQU 1 << PLAYER_DIR_BIT_LEFT PLAYER_DIR_DOWN EQU 1 << PLAYER_DIR_BIT_DOWN PLAYER_DIR_UP EQU 1 << PLAYER_DIR_BIT_UP
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>getpgrp() -> str Invokes the syscall getpgrp. See 'man 2 getpgrp' for more information. Arguments: Returns: pid_t </%docstring> <%page args=""/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = [] can_pushstr_array = [] argument_names = [] argument_values = [] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_getpgrp']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* getpgrp(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 4, 0x90 .globl UpdateSHA512 .type UpdateSHA512, @function UpdateSHA512: push %ebp mov %esp, %ebp push %esi push %edi movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %eax movl (20)(%ebp), %edx sub $(852), %esp mov %esp, %ecx and $(-16), %esp sub %esp, %ecx add $(852), %ecx mov %ecx, (848)(%esp) movq (%edi), %xmm0 movq (8)(%edi), %xmm1 movq (16)(%edi), %xmm2 movq (24)(%edi), %xmm3 movq (32)(%edi), %xmm4 movq (40)(%edi), %xmm5 movq (48)(%edi), %xmm6 movq (56)(%edi), %xmm7 movdqa %xmm0, (80)(%esp) movdqa %xmm1, (96)(%esp) movdqa %xmm2, (112)(%esp) movdqa %xmm3, (128)(%esp) movdqa %xmm4, (144)(%esp) movdqa %xmm5, (160)(%esp) movdqa %xmm6, (176)(%esp) movdqa %xmm7, (192)(%esp) .Lsha512_block_loopgas_1: mov $(0), %ecx .p2align 4, 0x90 .Lloop1gas_1: movdqu (%esi,%ecx,8), %xmm0 pshuflw $(27), %xmm0, %xmm0 pshufhw $(27), %xmm0, %xmm0 movdqa %xmm0, %xmm1 psrlw $(8), %xmm1 psllw $(8), %xmm0 por %xmm1, %xmm0 movdqa %xmm0, (208)(%esp,%ecx,8) add $(2), %ecx cmp $(16), %ecx jl .Lloop1gas_1 .p2align 4, 0x90 .Lloop2gas_1: movdqa (192)(%esp,%ecx,8), %xmm1 movdqa %xmm1, %xmm0 psrlq $(6), %xmm1 movdqa %xmm0, %xmm2 movdqa %xmm0, %xmm3 psrlq $(19), %xmm0 psllq $(45), %xmm3 por %xmm3, %xmm0 pxor %xmm1, %xmm0 movdqa %xmm2, %xmm3 psrlq $(61), %xmm2 psllq $(3), %xmm3 por %xmm3, %xmm2 pxor %xmm2, %xmm0 movdqu (88)(%esp,%ecx,8), %xmm5 movdqa %xmm5, %xmm4 psrlq $(7), %xmm5 movdqa %xmm4, %xmm6 movdqa %xmm4, %xmm3 psrlq $(1), %xmm4 psllq $(63), %xmm3 por %xmm3, %xmm4 pxor %xmm5, %xmm4 movdqa %xmm6, %xmm3 psrlq $(8), %xmm6 psllq $(56), %xmm3 por %xmm3, %xmm6 pxor %xmm6, %xmm4 movdqu (152)(%esp,%ecx,8), %xmm7 paddq %xmm4, %xmm0 paddq (80)(%esp,%ecx,8), %xmm7 paddq %xmm7, %xmm0 movdqa %xmm0, (208)(%esp,%ecx,8) add $(2), %ecx cmp $(80), %ecx jl .Lloop2gas_1 movdqa (80)(%esp), %xmm0 movdqa (96)(%esp), %xmm1 movdqa (112)(%esp), %xmm2 movdqa (128)(%esp), %xmm3 movdqa (144)(%esp), %xmm4 movdqa (160)(%esp), %xmm5 movdqa (176)(%esp), %xmm6 movdqa (192)(%esp), %xmm7 xor %ecx, %ecx .p2align 4, 0x90 .Lloop3gas_1: movdqa %xmm4, (%esp) movdqa %xmm0, (16)(%esp) movdqa %xmm3, (32)(%esp) movdqa %xmm7, (48)(%esp) movdqa %xmm5, %xmm3 pxor %xmm6, %xmm3 pand %xmm4, %xmm3 pxor %xmm6, %xmm3 movq (208)(%esp,%ecx,8), %xmm7 paddq %xmm7, %xmm3 movq (%edx,%ecx,8), %xmm7 paddq %xmm7, %xmm3 paddq (48)(%esp), %xmm3 movdqa %xmm3, (48)(%esp) movdqa %xmm1, %xmm3 movdqa %xmm0, %xmm7 pxor %xmm0, %xmm3 pand %xmm1, %xmm7 pand %xmm2, %xmm3 pxor %xmm3, %xmm7 movdqa %xmm7, (64)(%esp) movdqa %xmm4, %xmm3 movdqa %xmm3, %xmm7 psrlq $(14), %xmm3 psllq $(50), %xmm7 por %xmm7, %xmm3 movdqa %xmm4, %xmm7 psrlq $(18), %xmm4 psllq $(46), %xmm7 por %xmm7, %xmm4 pxor %xmm4, %xmm3 movdqa %xmm4, %xmm7 psrlq $(23), %xmm4 psllq $(41), %xmm7 por %xmm7, %xmm4 pxor %xmm4, %xmm3 paddq (48)(%esp), %xmm3 movdqa %xmm0, %xmm7 movdqa %xmm7, %xmm4 psrlq $(28), %xmm7 psllq $(36), %xmm4 por %xmm4, %xmm7 movdqa %xmm0, %xmm4 psrlq $(34), %xmm0 psllq $(30), %xmm4 por %xmm4, %xmm0 pxor %xmm0, %xmm7 movdqa %xmm0, %xmm4 psrlq $(5), %xmm0 psllq $(59), %xmm4 por %xmm4, %xmm0 pxor %xmm0, %xmm7 paddq (64)(%esp), %xmm7 paddq %xmm3, %xmm7 paddq (32)(%esp), %xmm3 movdqa (%esp), %xmm4 movdqa (16)(%esp), %xmm0 movdqa %xmm3, (%esp) movdqa %xmm7, (16)(%esp) movdqa %xmm2, (32)(%esp) movdqa %xmm6, (48)(%esp) movdqa %xmm4, %xmm2 pxor %xmm5, %xmm2 pand %xmm3, %xmm2 pxor %xmm5, %xmm2 movq (216)(%esp,%ecx,8), %xmm6 paddq %xmm6, %xmm2 movq (8)(%edx,%ecx,8), %xmm6 paddq %xmm6, %xmm2 paddq (48)(%esp), %xmm2 movdqa %xmm2, (48)(%esp) movdqa %xmm0, %xmm2 movdqa %xmm7, %xmm6 pxor %xmm7, %xmm2 pand %xmm0, %xmm6 pand %xmm1, %xmm2 pxor %xmm2, %xmm6 movdqa %xmm6, (64)(%esp) movdqa %xmm3, %xmm2 movdqa %xmm2, %xmm6 psrlq $(14), %xmm2 psllq $(50), %xmm6 por %xmm6, %xmm2 movdqa %xmm3, %xmm6 psrlq $(18), %xmm3 psllq $(46), %xmm6 por %xmm6, %xmm3 pxor %xmm3, %xmm2 movdqa %xmm3, %xmm6 psrlq $(23), %xmm3 psllq $(41), %xmm6 por %xmm6, %xmm3 pxor %xmm3, %xmm2 paddq (48)(%esp), %xmm2 movdqa %xmm7, %xmm6 movdqa %xmm6, %xmm3 psrlq $(28), %xmm6 psllq $(36), %xmm3 por %xmm3, %xmm6 movdqa %xmm7, %xmm3 psrlq $(34), %xmm7 psllq $(30), %xmm3 por %xmm3, %xmm7 pxor %xmm7, %xmm6 movdqa %xmm7, %xmm3 psrlq $(5), %xmm7 psllq $(59), %xmm3 por %xmm3, %xmm7 pxor %xmm7, %xmm6 paddq (64)(%esp), %xmm6 paddq %xmm2, %xmm6 paddq (32)(%esp), %xmm2 movdqa (%esp), %xmm3 movdqa (16)(%esp), %xmm7 movdqa %xmm2, (%esp) movdqa %xmm6, (16)(%esp) movdqa %xmm1, (32)(%esp) movdqa %xmm5, (48)(%esp) movdqa %xmm3, %xmm1 pxor %xmm4, %xmm1 pand %xmm2, %xmm1 pxor %xmm4, %xmm1 movq (224)(%esp,%ecx,8), %xmm5 paddq %xmm5, %xmm1 movq (16)(%edx,%ecx,8), %xmm5 paddq %xmm5, %xmm1 paddq (48)(%esp), %xmm1 movdqa %xmm1, (48)(%esp) movdqa %xmm7, %xmm1 movdqa %xmm6, %xmm5 pxor %xmm6, %xmm1 pand %xmm7, %xmm5 pand %xmm0, %xmm1 pxor %xmm1, %xmm5 movdqa %xmm5, (64)(%esp) movdqa %xmm2, %xmm1 movdqa %xmm1, %xmm5 psrlq $(14), %xmm1 psllq $(50), %xmm5 por %xmm5, %xmm1 movdqa %xmm2, %xmm5 psrlq $(18), %xmm2 psllq $(46), %xmm5 por %xmm5, %xmm2 pxor %xmm2, %xmm1 movdqa %xmm2, %xmm5 psrlq $(23), %xmm2 psllq $(41), %xmm5 por %xmm5, %xmm2 pxor %xmm2, %xmm1 paddq (48)(%esp), %xmm1 movdqa %xmm6, %xmm5 movdqa %xmm5, %xmm2 psrlq $(28), %xmm5 psllq $(36), %xmm2 por %xmm2, %xmm5 movdqa %xmm6, %xmm2 psrlq $(34), %xmm6 psllq $(30), %xmm2 por %xmm2, %xmm6 pxor %xmm6, %xmm5 movdqa %xmm6, %xmm2 psrlq $(5), %xmm6 psllq $(59), %xmm2 por %xmm2, %xmm6 pxor %xmm6, %xmm5 paddq (64)(%esp), %xmm5 paddq %xmm1, %xmm5 paddq (32)(%esp), %xmm1 movdqa (%esp), %xmm2 movdqa (16)(%esp), %xmm6 movdqa %xmm1, (%esp) movdqa %xmm5, (16)(%esp) movdqa %xmm0, (32)(%esp) movdqa %xmm4, (48)(%esp) movdqa %xmm2, %xmm0 pxor %xmm3, %xmm0 pand %xmm1, %xmm0 pxor %xmm3, %xmm0 movq (232)(%esp,%ecx,8), %xmm4 paddq %xmm4, %xmm0 movq (24)(%edx,%ecx,8), %xmm4 paddq %xmm4, %xmm0 paddq (48)(%esp), %xmm0 movdqa %xmm0, (48)(%esp) movdqa %xmm6, %xmm0 movdqa %xmm5, %xmm4 pxor %xmm5, %xmm0 pand %xmm6, %xmm4 pand %xmm7, %xmm0 pxor %xmm0, %xmm4 movdqa %xmm4, (64)(%esp) movdqa %xmm1, %xmm0 movdqa %xmm0, %xmm4 psrlq $(14), %xmm0 psllq $(50), %xmm4 por %xmm4, %xmm0 movdqa %xmm1, %xmm4 psrlq $(18), %xmm1 psllq $(46), %xmm4 por %xmm4, %xmm1 pxor %xmm1, %xmm0 movdqa %xmm1, %xmm4 psrlq $(23), %xmm1 psllq $(41), %xmm4 por %xmm4, %xmm1 pxor %xmm1, %xmm0 paddq (48)(%esp), %xmm0 movdqa %xmm5, %xmm4 movdqa %xmm4, %xmm1 psrlq $(28), %xmm4 psllq $(36), %xmm1 por %xmm1, %xmm4 movdqa %xmm5, %xmm1 psrlq $(34), %xmm5 psllq $(30), %xmm1 por %xmm1, %xmm5 pxor %xmm5, %xmm4 movdqa %xmm5, %xmm1 psrlq $(5), %xmm5 psllq $(59), %xmm1 por %xmm1, %xmm5 pxor %xmm5, %xmm4 paddq (64)(%esp), %xmm4 paddq %xmm0, %xmm4 paddq (32)(%esp), %xmm0 movdqa (%esp), %xmm1 movdqa (16)(%esp), %xmm5 movdqa %xmm0, (%esp) movdqa %xmm4, (16)(%esp) movdqa %xmm7, (32)(%esp) movdqa %xmm3, (48)(%esp) movdqa %xmm1, %xmm7 pxor %xmm2, %xmm7 pand %xmm0, %xmm7 pxor %xmm2, %xmm7 movq (240)(%esp,%ecx,8), %xmm3 paddq %xmm3, %xmm7 movq (32)(%edx,%ecx,8), %xmm3 paddq %xmm3, %xmm7 paddq (48)(%esp), %xmm7 movdqa %xmm7, (48)(%esp) movdqa %xmm5, %xmm7 movdqa %xmm4, %xmm3 pxor %xmm4, %xmm7 pand %xmm5, %xmm3 pand %xmm6, %xmm7 pxor %xmm7, %xmm3 movdqa %xmm3, (64)(%esp) movdqa %xmm0, %xmm7 movdqa %xmm7, %xmm3 psrlq $(14), %xmm7 psllq $(50), %xmm3 por %xmm3, %xmm7 movdqa %xmm0, %xmm3 psrlq $(18), %xmm0 psllq $(46), %xmm3 por %xmm3, %xmm0 pxor %xmm0, %xmm7 movdqa %xmm0, %xmm3 psrlq $(23), %xmm0 psllq $(41), %xmm3 por %xmm3, %xmm0 pxor %xmm0, %xmm7 paddq (48)(%esp), %xmm7 movdqa %xmm4, %xmm3 movdqa %xmm3, %xmm0 psrlq $(28), %xmm3 psllq $(36), %xmm0 por %xmm0, %xmm3 movdqa %xmm4, %xmm0 psrlq $(34), %xmm4 psllq $(30), %xmm0 por %xmm0, %xmm4 pxor %xmm4, %xmm3 movdqa %xmm4, %xmm0 psrlq $(5), %xmm4 psllq $(59), %xmm0 por %xmm0, %xmm4 pxor %xmm4, %xmm3 paddq (64)(%esp), %xmm3 paddq %xmm7, %xmm3 paddq (32)(%esp), %xmm7 movdqa (%esp), %xmm0 movdqa (16)(%esp), %xmm4 movdqa %xmm7, (%esp) movdqa %xmm3, (16)(%esp) movdqa %xmm6, (32)(%esp) movdqa %xmm2, (48)(%esp) movdqa %xmm0, %xmm6 pxor %xmm1, %xmm6 pand %xmm7, %xmm6 pxor %xmm1, %xmm6 movq (248)(%esp,%ecx,8), %xmm2 paddq %xmm2, %xmm6 movq (40)(%edx,%ecx,8), %xmm2 paddq %xmm2, %xmm6 paddq (48)(%esp), %xmm6 movdqa %xmm6, (48)(%esp) movdqa %xmm4, %xmm6 movdqa %xmm3, %xmm2 pxor %xmm3, %xmm6 pand %xmm4, %xmm2 pand %xmm5, %xmm6 pxor %xmm6, %xmm2 movdqa %xmm2, (64)(%esp) movdqa %xmm7, %xmm6 movdqa %xmm6, %xmm2 psrlq $(14), %xmm6 psllq $(50), %xmm2 por %xmm2, %xmm6 movdqa %xmm7, %xmm2 psrlq $(18), %xmm7 psllq $(46), %xmm2 por %xmm2, %xmm7 pxor %xmm7, %xmm6 movdqa %xmm7, %xmm2 psrlq $(23), %xmm7 psllq $(41), %xmm2 por %xmm2, %xmm7 pxor %xmm7, %xmm6 paddq (48)(%esp), %xmm6 movdqa %xmm3, %xmm2 movdqa %xmm2, %xmm7 psrlq $(28), %xmm2 psllq $(36), %xmm7 por %xmm7, %xmm2 movdqa %xmm3, %xmm7 psrlq $(34), %xmm3 psllq $(30), %xmm7 por %xmm7, %xmm3 pxor %xmm3, %xmm2 movdqa %xmm3, %xmm7 psrlq $(5), %xmm3 psllq $(59), %xmm7 por %xmm7, %xmm3 pxor %xmm3, %xmm2 paddq (64)(%esp), %xmm2 paddq %xmm6, %xmm2 paddq (32)(%esp), %xmm6 movdqa (%esp), %xmm7 movdqa (16)(%esp), %xmm3 movdqa %xmm6, (%esp) movdqa %xmm2, (16)(%esp) movdqa %xmm5, (32)(%esp) movdqa %xmm1, (48)(%esp) movdqa %xmm7, %xmm5 pxor %xmm0, %xmm5 pand %xmm6, %xmm5 pxor %xmm0, %xmm5 movq (256)(%esp,%ecx,8), %xmm1 paddq %xmm1, %xmm5 movq (48)(%edx,%ecx,8), %xmm1 paddq %xmm1, %xmm5 paddq (48)(%esp), %xmm5 movdqa %xmm5, (48)(%esp) movdqa %xmm3, %xmm5 movdqa %xmm2, %xmm1 pxor %xmm2, %xmm5 pand %xmm3, %xmm1 pand %xmm4, %xmm5 pxor %xmm5, %xmm1 movdqa %xmm1, (64)(%esp) movdqa %xmm6, %xmm5 movdqa %xmm5, %xmm1 psrlq $(14), %xmm5 psllq $(50), %xmm1 por %xmm1, %xmm5 movdqa %xmm6, %xmm1 psrlq $(18), %xmm6 psllq $(46), %xmm1 por %xmm1, %xmm6 pxor %xmm6, %xmm5 movdqa %xmm6, %xmm1 psrlq $(23), %xmm6 psllq $(41), %xmm1 por %xmm1, %xmm6 pxor %xmm6, %xmm5 paddq (48)(%esp), %xmm5 movdqa %xmm2, %xmm1 movdqa %xmm1, %xmm6 psrlq $(28), %xmm1 psllq $(36), %xmm6 por %xmm6, %xmm1 movdqa %xmm2, %xmm6 psrlq $(34), %xmm2 psllq $(30), %xmm6 por %xmm6, %xmm2 pxor %xmm2, %xmm1 movdqa %xmm2, %xmm6 psrlq $(5), %xmm2 psllq $(59), %xmm6 por %xmm6, %xmm2 pxor %xmm2, %xmm1 paddq (64)(%esp), %xmm1 paddq %xmm5, %xmm1 paddq (32)(%esp), %xmm5 movdqa (%esp), %xmm6 movdqa (16)(%esp), %xmm2 movdqa %xmm5, (%esp) movdqa %xmm1, (16)(%esp) movdqa %xmm4, (32)(%esp) movdqa %xmm0, (48)(%esp) movdqa %xmm6, %xmm4 pxor %xmm7, %xmm4 pand %xmm5, %xmm4 pxor %xmm7, %xmm4 movq (264)(%esp,%ecx,8), %xmm0 paddq %xmm0, %xmm4 movq (56)(%edx,%ecx,8), %xmm0 paddq %xmm0, %xmm4 paddq (48)(%esp), %xmm4 movdqa %xmm4, (48)(%esp) movdqa %xmm2, %xmm4 movdqa %xmm1, %xmm0 pxor %xmm1, %xmm4 pand %xmm2, %xmm0 pand %xmm3, %xmm4 pxor %xmm4, %xmm0 movdqa %xmm0, (64)(%esp) movdqa %xmm5, %xmm4 movdqa %xmm4, %xmm0 psrlq $(14), %xmm4 psllq $(50), %xmm0 por %xmm0, %xmm4 movdqa %xmm5, %xmm0 psrlq $(18), %xmm5 psllq $(46), %xmm0 por %xmm0, %xmm5 pxor %xmm5, %xmm4 movdqa %xmm5, %xmm0 psrlq $(23), %xmm5 psllq $(41), %xmm0 por %xmm0, %xmm5 pxor %xmm5, %xmm4 paddq (48)(%esp), %xmm4 movdqa %xmm1, %xmm0 movdqa %xmm0, %xmm5 psrlq $(28), %xmm0 psllq $(36), %xmm5 por %xmm5, %xmm0 movdqa %xmm1, %xmm5 psrlq $(34), %xmm1 psllq $(30), %xmm5 por %xmm5, %xmm1 pxor %xmm1, %xmm0 movdqa %xmm1, %xmm5 psrlq $(5), %xmm1 psllq $(59), %xmm5 por %xmm5, %xmm1 pxor %xmm1, %xmm0 paddq (64)(%esp), %xmm0 paddq %xmm4, %xmm0 paddq (32)(%esp), %xmm4 movdqa (%esp), %xmm5 movdqa (16)(%esp), %xmm1 add $(8), %ecx cmp $(80), %ecx jl .Lloop3gas_1 paddq (80)(%esp), %xmm0 paddq (96)(%esp), %xmm1 paddq (112)(%esp), %xmm2 paddq (128)(%esp), %xmm3 paddq (144)(%esp), %xmm4 paddq (160)(%esp), %xmm5 paddq (176)(%esp), %xmm6 paddq (192)(%esp), %xmm7 movdqa %xmm0, (80)(%esp) movdqa %xmm1, (96)(%esp) movdqa %xmm2, (112)(%esp) movdqa %xmm3, (128)(%esp) movdqa %xmm4, (144)(%esp) movdqa %xmm5, (160)(%esp) movdqa %xmm6, (176)(%esp) movdqa %xmm7, (192)(%esp) add $(128), %esi sub $(128), %eax jg .Lsha512_block_loopgas_1 movq %xmm0, (%edi) movq %xmm1, (8)(%edi) movq %xmm2, (16)(%edi) movq %xmm3, (24)(%edi) movq %xmm4, (32)(%edi) movq %xmm5, (40)(%edi) movq %xmm6, (48)(%edi) movq %xmm7, (56)(%edi) add (848)(%esp), %esp pop %edi pop %esi pop %ebp ret .Lfe1: .size UpdateSHA512, .Lfe1-(UpdateSHA512)
; SBAS_ICALL - PROC/FN Call and Unravel  1994 Tony Tebby section sbas xdef sb_icall ; procedure, function call xdef sb_icall_pas ; ditto, params (a3-a5) and addr (a0) set xref sb_clrprm include 'dev8_keys_sbasic' include 'dev8_keys_qlv' include 'dev8_keys_err' include 'dev8_mac_assert' ;+++ ; Within this routine ; D7 is returned as the called size of the arithmetic stack ; A1 was pointer to arith stack ; A3 was pointer to name table on entry ; A6 is pointer to system variables ;--- sb_icall move.l sb_retsp(a6),a2 move.l rt_def(a6,a2.l),a0 ; routine address sub.l a6,a3 move.l rt_tparm(a6,a2.l),a5 ; top parameter add.l a3,a5 add.l rt_parm(a6,a2.l),a3 ; bottom parameter sub.w #rt.pfsize,a2 ; remove return frame move.l a2,d2 cmp.l sb_retsb(a6),a2 ble.s sic_setr tst.b rt_def(a6,a2.l) ; is this frame set up? bmi.s sic_setr ; ... yes tst.b rt_type(a6,a2.l) ; proc fn? ble.s sic_setr sub.w #rt.pfsize,a2 ; ... yes sic_setr move.l a2,sb_retsp(a6) sb_icall_pas moveq #0,d7 move.l sb_nmtbb(a6),d1 sub.l a6,a1 ; set arithmetic stack move.l a1,sb_arthp(a6) sub.l sb_arthb(a6),a1 ; size of ;sbtrns is only required if sb vars are above data areas ;sbtrns bclr #7,sb_grphb(a6) ; and set to zero for Turbo movem.l d1/d2/d5/d6/a1/a3/a4/a5,-(sp) jsr (a0) movem.l (sp)+,d1/d2/d5/d6/d7/a3/a4/a5 move.l d0,-(sp) ; save error code move.l d2,sb_retsp(a6) ; restore return frame ;sbtrns move.l sb_grphp(a6),sb_grphb(a6) ; reset graph base for Turbo sub.l sb_nmtbb(a6),d1 ; name table moved sub.l d1,a3 ; adjust pointers sub.l d1,a5 cmp.l a3,a5 ; any parameter frame to clear? beq.s sic_exit jsr sb_clrprm ; clear frame (a3-a5) sic_exit move.l (sp)+,d0 ; error? rts end
; ; Fast background restore ; ; Graphics library for the Epson PX4 ; Stefano - Nov 2015 ; ; $Id: bkrestore.asm,v 1.3 2016/06/21 20:16:35 dom Exp $ ; SECTION code_clib PUBLIC bkrestore PUBLIC _bkrestore EXTERN pixeladdress INCLUDE "graphics/grafix.inc" .bkrestore ._bkrestore ; __FASTCALL__ : sprite ptr in HL push ix ;save callers push hl pop ix ld h,(ix+2) ; restore sprite position ld l,(ix+3) ld a,(ix+0) ld b,(ix+1) dec a srl a srl a srl a inc a inc a ; INT ((Xsize-1)/8+2) ld (rbytes+1),a ._sloop push bc push hl .rbytes ld b,0 .rloop ld a,(ix+4) ld (hl),a inc hl inc ix djnz rloop pop hl inc h ;Go to next line pop bc djnz _sloop pop ix ;restore caller ret
SFX_Faint_Fall_Ch5: duty_cycle 1 pitch_sweep 10, -7 square_note 15, 15, 2, 1920 pitch_sweep 0, 8 sound_ret
/* * All Video Processing kernels * Copyright © <2010>, 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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. * * This file was originally licensed under the following license * * 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. * */ // Module name: PL16x8_PL8x4.asm //---------------------------------------------------------------- #include "common.inc" #ifndef DEST_U //DEST_U, DEST_V not defined #if (nSRC_REGION==nREGION_1) #define DEST_Y uwTOP_Y #define DEST_U uwTOP_U #define DEST_V uwTOP_V #elif (nSRC_REGION==nREGION_2) #define DEST_Y uwBOT_Y #define DEST_U uwBOT_U #define DEST_V uwBOT_V #endif #endif //Convert 444 from sampler to 422 $for (0, 0; <8; 2, 1) { mov (8) DEST_U(0,%2*8)<1> DEST_U(%1)<16;8,2> mov (8) DEST_V(0,%2*8)<1> DEST_V(%1)<16;8,2> } // Re-define new number of lines #undef nUV_NUM_OF_ROWS #define nUV_NUM_OF_ROWS 4
; A189327: Number of nondecreasing arrangements of 4 numbers in 0..n with the last equal to n and each after the second equal to the sum of one or two of the preceding four ; 2,6,7,12,12,18,17,24,22,30,27,36,32,42,37,48,42,54,47,60,52,66,57,72,62,78,67,84,72,90,77,96,82,102,87,108,92,114,97,120,102,126,107,132,112,138,117,144,122,150,127,156,132,162,137,168,142,174,147,180,152,186,157,192,162,198,167,204,172,210,177,216,182,222,187,228,192,234,197,240,202,246,207,252,212,258,217,264,222,270,227,276,232,282,237,288,242,294,247,300 mov $1,$0 add $0,1 mod $1,2 add $1,5 mul $0,$1 div $0,2
#include "grid3d.h" #include <string> #ifndef ROUND #define ROUND(x) (((x)>=0.0)?int((x)+0.5):int((x)-0.5)) #endif geomGrid3D::geomGrid3D() : nx_(0), ny_(0), psx_(0), psy_(0) {} geomGrid3D::geomGrid3D(const geomGrid3D& g) : geomRect3D(g), nx_(g.numCol()), ny_(g.numRow()), psx_(g.pixelSX()), psy_(g.pixelSY()) {} geomVector3D geomGrid3D::getPointByIndex(int col, int row) const { double x = minX() + (0.5 + double(col)) * psx_; double y = minY() + (0.5 + double(row)) * psy_; return geomVector3D(x, y, 0) * mRtoP_; } void geomGrid3D::getPointByIndex(int col, int row, double& x, double& y) const { x = minX() + (0.5 + double(col)) * psx_; y = minY() + (0.5 + double(row)) * psy_; } void geomGrid3D::setGrid(int nx, int ny, double psx, double psy) { nx_ = nx; ny_ = ny; setResolution(psx, psy); } void geomGrid3D::setResolution(double x, double y) { psx_ = x; psy_ = y; if (r_ == l_) { r_ = 0.5 * nx_ * psx_; l_ = -r_; } if (t_ == b_) { t_ = 0.5 * ny_ * psy_; b_ = -t_; } } void geomGrid3D::setAdjustedResolution(double x, double y) { psx_ = x; psy_ = y; l_ = x * (ROUND(l_ / x) - 0.5); b_ = y * (ROUND(b_ / y) - 0.5); r_ = x * (ROUND(r_ / x) + 0.5); t_ = y * (ROUND(t_ / y) + 0.5); nx_ = ROUND((r_ - l_) / x); ny_ = ROUND((t_ - b_) / y); } void geomGrid3D::setSize(int nx, int ny) { nx_ = nx; ny_ = ny; psx_ = width() / nx_; psy_ = height() / ny_; } int geomGrid3D::getColIndex(double x) const { return int(nx_ * (x - l_) / (r_ - l_)); } int geomGrid3D::getRowIndex(double y) const { return int(ny_ * (y - b_) / (t_ - b_)); } double geomGrid3D::getCol(unsigned i) const { return minX() + (0.5 + double(i)) * psx_; } double geomGrid3D::getRow(unsigned j) const { return minY() + (0.5 + double(j)) * psy_; } void geomGrid3D::scale(double f) { geomFRect::scale(f); psx_ *= f; psy_ *= f; } void geomGrid3D::operator=(const geomGrid3D& g) { *static_cast<geomRect3D*>(this) = static_cast<const geomRect3D&>(g); nx_ = g.nx_; ny_ = g.ny_; psx_ = g.psx_; psy_ = g.psy_; } istream& operator >>(istream& is, geomGrid3D& g) { is >> static_cast<geomRect3D&>(g); string line; getline(is, line, '\n'); g.nx_ = atoi(line.c_str()); getline(is, line, '\n'); g.ny_ = atoi(line.c_str()); getline(is, line, '\n'); g.psx_ = atof(line.c_str()); getline(is, line, '\n'); g.psy_ = atof(line.c_str()); return is; } ostream& operator <<(ostream& os, const geomGrid3D& g) { os << (geomRect3D&)g; os << g.nx_ << endl; os << g.ny_ << endl; os << g.psx_ << endl; os << g.psy_ << endl; return os; }
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r15 push %r8 push %r9 push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x78f1, %rsi lea addresses_D_ht+0x128d1, %rdi nop nop nop nop nop cmp $51511, %rbp mov $110, %rcx rep movsq nop nop nop and %r15, %r15 lea addresses_A_ht+0x1dca1, %r13 nop nop nop nop nop add $2280, %rdi movb $0x61, (%r13) nop nop nop nop cmp %rcx, %rcx lea addresses_D_ht+0x12005, %rdi nop nop nop nop nop and $37128, %r9 movb (%rdi), %cl cmp %rsi, %rsi lea addresses_D_ht+0x1949, %rsi lea addresses_WC_ht+0x178d1, %rdi nop nop nop nop nop sub $29147, %r8 mov $63, %rcx rep movsw nop nop cmp %r15, %r15 lea addresses_UC_ht+0xc0d1, %r15 nop nop nop sub %rcx, %rcx mov $0x6162636465666768, %rbp movq %rbp, (%r15) sub $11310, %r9 lea addresses_WC_ht+0x158d1, %r15 nop nop nop nop and %rdi, %rdi mov $0x6162636465666768, %r8 movq %r8, %xmm0 vmovups %ymm0, (%r15) nop and $57878, %rcx lea addresses_A_ht+0x1ed1, %r8 clflush (%r8) nop nop nop nop add $49949, %r9 mov $0x6162636465666768, %rsi movq %rsi, %xmm0 vmovups %ymm0, (%r8) nop cmp %r15, %r15 lea addresses_D_ht+0xb9d1, %r13 mfence mov $0x6162636465666768, %r8 movq %r8, %xmm3 movups %xmm3, (%r13) nop nop nop nop nop sub $36348, %r13 lea addresses_UC_ht+0x1b1d1, %rcx nop nop sub %rdi, %rdi movb (%rcx), %r13b xor $53578, %rdi lea addresses_D_ht+0x6d1, %rsi lea addresses_UC_ht+0x3fa1, %rdi nop xor %r15, %r15 mov $48, %rcx rep movsb nop sub $52860, %rcx lea addresses_UC_ht+0x34d1, %rsi lea addresses_D_ht+0x1add1, %rdi nop nop nop nop nop add %r8, %r8 mov $56, %rcx rep movsb nop nop nop nop cmp %rbp, %rbp lea addresses_normal_ht+0x8611, %rcx nop nop xor %rbp, %rbp mov (%rcx), %esi nop nop nop nop nop xor $14890, %r15 pop %rsi pop %rdi pop %rcx pop %rbp pop %r9 pop %r8 pop %r15 pop %r13 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r14 push %r8 push %rbp push %rdx // Faulty Load lea addresses_D+0x188d1, %r8 nop nop lfence movb (%r8), %r14b lea oracles, %rdx and $0xff, %r14 shlq $12, %r14 mov (%rdx,%r14,1), %r14 pop %rdx pop %rbp pop %r8 pop %r14 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_D', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 1, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_D_ht', 'same': False, 'size': 1, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 11, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 32, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_UC_ht', 'same': True, 'size': 1, 'congruent': 8, 'NT': True, 'AVXalign': True}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': True}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 2, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
// 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 "chrome/browser/translate/translate_model_service_factory.h" #include "base/memory/scoped_refptr.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h" #include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/translate/content/browser/translate_model_service.h" #include "components/translate/core/common/translate_util.h" // static translate::TranslateModelService* TranslateModelServiceFactory::GetForProfile( Profile* profile) { return static_cast<translate::TranslateModelService*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } // static TranslateModelServiceFactory* TranslateModelServiceFactory::GetInstance() { static base::NoDestructor<TranslateModelServiceFactory> factory; return factory.get(); } TranslateModelServiceFactory::TranslateModelServiceFactory() : BrowserContextKeyedServiceFactory( "TranslateModelService", BrowserContextDependencyManager::GetInstance()) {} TranslateModelServiceFactory::~TranslateModelServiceFactory() = default; KeyedService* TranslateModelServiceFactory::BuildServiceInstanceFor( content::BrowserContext* context) const { if (!translate::IsTFLiteLanguageDetectionEnabled()) return nullptr; // The optimization guide service must be available for the translate model // service to be created. auto* opt_guide = OptimizationGuideKeyedServiceFactory::GetForProfile( Profile::FromBrowserContext(context)); if (opt_guide) { scoped_refptr<base::SequencedTaskRunner> background_task_runner = base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::BEST_EFFORT}); return new translate::TranslateModelService(opt_guide, background_task_runner); } return nullptr; } content::BrowserContext* TranslateModelServiceFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return chrome::GetBrowserContextOwnInstanceInIncognito(context); }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r12 push %r14 push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x2090, %rsi lea addresses_WT_ht+0x3ad0, %rdi nop add $35562, %r10 mov $25, %rcx rep movsq nop nop nop nop and $62615, %r11 lea addresses_D_ht+0x106d0, %r14 nop nop add $52025, %r12 movb (%r14), %r10b nop nop sub $36388, %rsi lea addresses_UC_ht+0x1a78, %r14 nop nop nop inc %r10 movb $0x61, (%r14) nop nop cmp %r10, %r10 lea addresses_WC_ht+0xeb50, %rsi lea addresses_UC_ht+0x2f90, %rdi and $19470, %rbp mov $103, %rcx rep movsw nop xor %rsi, %rsi lea addresses_WT_ht+0x11590, %r12 nop sub $22632, %r10 mov (%r12), %r11 nop nop sub %rdi, %rdi lea addresses_A_ht+0x9c98, %rsi lea addresses_normal_ht+0x17990, %rdi clflush (%rdi) cmp $45144, %rbp mov $100, %rcx rep movsl nop nop nop dec %rdi lea addresses_A_ht+0x1e190, %rsi nop nop nop nop sub $16600, %r11 mov (%rsi), %r12d nop nop sub $64337, %r12 lea addresses_D_ht+0x18fa0, %r12 clflush (%r12) nop nop nop nop xor %rbp, %rbp mov (%r12), %r11d nop nop nop cmp $4526, %rcx lea addresses_A_ht+0x19990, %rsi lea addresses_UC_ht+0x1e990, %rdi clflush (%rdi) nop sub %r14, %r14 mov $51, %rcx rep movsl nop nop nop nop nop dec %rdi lea addresses_WT_ht+0xb990, %rsi lea addresses_WC_ht+0xd710, %rdi clflush (%rsi) nop nop and %r10, %r10 mov $93, %rcx rep movsl nop nop add $55691, %r14 pop %rsi pop %rdi pop %rcx pop %rbp pop %r14 pop %r12 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r15 push %r9 push %rbp push %rcx push %rdi push %rsi // Store lea addresses_A+0xe710, %rsi nop xor %r13, %r13 mov $0x5152535455565758, %r9 movq %r9, (%rsi) nop and %rbp, %rbp // REPMOV lea addresses_WT+0x1e6d9, %rsi lea addresses_A+0x1990, %rdi nop lfence mov $48, %rcx rep movsq nop nop xor %r10, %r10 // REPMOV lea addresses_RW+0xa1a8, %rsi lea addresses_WT+0xc614, %rdi add $32161, %r10 mov $3, %rcx rep movsl nop nop nop nop xor %r9, %r9 // Faulty Load lea addresses_D+0x7190, %rcx nop nop and $62267, %r15 movb (%rcx), %r9b lea oracles, %r13 and $0xff, %r9 shlq $12, %r9 mov (%r13,%r9,1), %r9 pop %rsi pop %rdi pop %rcx pop %rbp pop %r9 pop %r15 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'AVXalign': True, 'size': 4, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 7}} {'src': {'type': 'addresses_WT', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A', 'congruent': 11, 'same': False}} {'src': {'type': 'addresses_RW', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT', 'congruent': 2, 'same': False}} [Faulty Load] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 1, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 4}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 3}} {'src': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 10}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 3, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': True, 'congruent': 11}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 3}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
dnl x86-64 mpn_div_qr_1n_pi1 dnl -- Divide an mpn number by a normalized single-limb number, dnl using a single-limb inverse. dnl Contributed to the GNU project by Niels Möller dnl Copyright 2013 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') C c/l C AMD K8,K9 13 C AMD K10 13 C AMD bull 16.5 C AMD pile 15 C AMD steam ? C AMD bobcat 16 C AMD jaguar ? C Intel P4 47 poor C Intel core 19.25 C Intel NHM 18 C Intel SBR 15 poor C Intel IBR 13 C Intel HWL 11.7 C Intel BWL ? C Intel atom 52 very poor C VIA nano 19 C INPUT Parameters define(`QP', `%rdi') define(`UP', `%rsi') define(`UN_INPUT', `%rdx') define(`U1', `%rcx') C Also in %rax define(`D', `%r8') define(`DINV', `%r9') C Invariants define(`B2', `%rbp') define(`B2md', `%rbx') C Variables define(`UN', `%r8') C Overlaps D input define(`T', `%r10') define(`U0', `%r11') define(`U2', `%r12') define(`Q0', `%r13') define(`Q1', `%r14') define(`Q2', `%r15') ABI_SUPPORT(STD64) ASM_START() TEXT ALIGN(16) PROLOGUE(mpn_div_qr_1n_pi1) FUNC_ENTRY(4) IFDOS(` mov 56(%rsp), %r8 ') IFDOS(` mov 64(%rsp), %r9 ') dec UN_INPUT jnz L(first) C Just a single 2/1 division. C T, U0 are allocated in scratch registers lea 1(U1), T mov U1, %rax mul DINV mov (UP), U0 add U0, %rax adc T, %rdx mov %rdx, T imul D, %rdx sub %rdx, U0 cmp U0, %rax lea (U0, D), %rax cmovnc U0, %rax sbb $0, T cmp D, %rax jc L(single_div_done) sub D, %rax add $1, T L(single_div_done): mov T, (QP) FUNC_EXIT() ret L(first): C FIXME: Could delay some of these until we enter the loop. push %r15 push %r14 push %r13 push %r12 push %rbx push %rbp mov D, B2 imul DINV, B2 neg B2 mov B2, B2md sub D, B2md C D not needed until final reduction push D mov UN_INPUT, UN C Clobbers D mov DINV, %rax mul U1 mov %rax, Q0 add U1, %rdx mov %rdx, T mov B2, %rax mul U1 mov -8(UP, UN, 8), U0 mov (UP, UN, 8), U1 mov T, (QP, UN, 8) add %rax, U0 adc %rdx, U1 sbb U2, U2 dec UN mov U1, %rax jz L(final) ALIGN(16) C Loop is 28 instructions, 30 decoder slots, should run in 10 cycles. C At entry, %rax holds an extra copy of U1 L(loop): C {Q2, Q1, Q0} <-- DINV * U1 + B (Q0 + U2 DINV) + B^2 U2 C Remains to add in B (U1 + c) mov DINV, Q1 mov U2, Q2 and U2, Q1 neg Q2 mul DINV add %rdx, Q1 adc $0, Q2 add Q0, Q1 mov %rax, Q0 mov B2, %rax lea (B2md, U0), T adc $0, Q2 C {U2, U1, U0} <-- (U0 + U2 B2 -c U) B + U1 B2 + u mul U1 and B2, U2 add U2, U0 cmovnc U0, T C {QP+UN, ...} <-- {QP+UN, ...} + {Q2, Q1} + U1 + c adc U1, Q1 mov -8(UP, UN, 8), U0 adc Q2, 8(QP, UN, 8) jc L(q_incr) L(q_incr_done): add %rax, U0 mov T, %rax adc %rdx, %rax mov Q1, (QP, UN, 8) sbb U2, U2 dec UN mov %rax, U1 jnz L(loop) L(final): pop D mov U2, Q1 and D, U2 sub U2, %rax neg Q1 mov %rax, U1 sub D, %rax cmovc U1, %rax sbb $-1, Q1 lea 1(%rax), T mul DINV add U0, %rax adc T, %rdx mov %rdx, T imul D, %rdx sub %rdx, U0 cmp U0, %rax lea (U0, D), %rax cmovnc U0, %rax sbb $0, T cmp D, %rax jc L(div_done) sub D, %rax add $1, T L(div_done): add T, Q0 mov Q0, (QP) adc Q1, 8(QP) jnc L(done) L(final_q_incr): addq $1, 16(QP) lea 8(QP), QP jc L(final_q_incr) L(done): pop %rbp pop %rbx pop %r12 pop %r13 pop %r14 pop %r15 FUNC_EXIT() ret L(q_incr): C U1 is not live, so use it for indexing lea 16(QP, UN, 8), U1 L(q_incr_loop): addq $1, (U1) jnc L(q_incr_done) lea 8(U1), U1 jmp L(q_incr_loop) EPILOGUE()
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r11 push %r14 push %r15 push %r9 push %rax push %rcx push %rdi push %rdx push %rsi // Load lea addresses_WC+0xd5d3, %r9 nop nop add $63874, %r15 mov (%r9), %r14d nop and %r15, %r15 // Store lea addresses_A+0x9fab, %rsi nop nop nop inc %rdx movb $0x51, (%rsi) nop nop nop sub $15935, %r14 // Store lea addresses_WT+0x1c3ab, %rax nop nop nop nop add %rsi, %rsi movb $0x51, (%rax) cmp %rax, %rax // Store lea addresses_UC+0x17ab, %r14 add $22889, %r9 mov $0x5152535455565758, %rsi movq %rsi, %xmm1 vmovups %ymm1, (%r14) nop nop nop nop dec %rax // Load lea addresses_A+0x9fab, %r11 nop nop nop nop add %r9, %r9 movups (%r11), %xmm6 vpextrq $1, %xmm6, %rsi nop sub %rsi, %rsi // REPMOV lea addresses_WT+0x87ab, %rsi lea addresses_A+0x9fab, %rdi nop nop sub $1326, %rax mov $126, %rcx rep movsb nop nop nop nop add $37939, %rax // Faulty Load lea addresses_A+0x9fab, %rax nop add %rsi, %rsi mov (%rax), %rdx lea oracles, %r14 and $0xff, %rdx shlq $12, %rdx mov (%r14,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r9 pop %r15 pop %r14 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 2}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 10}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 6}} {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_WT'}, 'dst': {'same': True, 'congruent': 0, 'type': 'addresses_A'}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}} <gen_prepare_buffer> {'39': 21829} 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 */
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// #ifndef SFML_WINDOWIMPLWIN32_HPP #define SFML_WINDOWIMPLWIN32_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Window/Event.hpp> #include <SFML/Window/WindowImpl.hpp> #include <SFML/System/String.hpp> #include <windows.h> namespace sf { namespace priv { //////////////////////////////////////////////////////////// /// \brief Windows implementation of WindowImpl /// //////////////////////////////////////////////////////////// class WindowImplWin32 : public WindowImpl { public: //////////////////////////////////////////////////////////// /// \brief Construct the window implementation from an existing control /// /// \param handle Platform-specific handle of the control /// //////////////////////////////////////////////////////////// WindowImplWin32(WindowHandle handle); //////////////////////////////////////////////////////////// /// \brief Create the window implementation /// /// \param mode Video mode to use /// \param title Title of the window /// \param style Window style /// \param settings Additional settings for the underlying OpenGL context /// //////////////////////////////////////////////////////////// WindowImplWin32(VideoMode mode, const String& title, Uint32 style, const ContextSettings& settings); //////////////////////////////////////////////////////////// /// \brief Destructor /// //////////////////////////////////////////////////////////// ~WindowImplWin32(); //////////////////////////////////////////////////////////// /// \brief Get the OS-specific handle of the window /// /// \return Handle of the window /// //////////////////////////////////////////////////////////// virtual WindowHandle getSystemHandle() const; //////////////////////////////////////////////////////////// /// \brief Get the position of the window /// /// \return Position of the window, in pixels /// //////////////////////////////////////////////////////////// virtual Vector2i getPosition() const; //////////////////////////////////////////////////////////// /// \brief Change the position of the window on screen /// /// \param position New position of the window, in pixels /// //////////////////////////////////////////////////////////// virtual void setPosition(const Vector2i& position); //////////////////////////////////////////////////////////// /// \brief Get the client size of the window /// /// \return Size of the window, in pixels /// //////////////////////////////////////////////////////////// virtual Vector2u getSize() const; //////////////////////////////////////////////////////////// /// \brief Change the size of the rendering region of the window /// /// \param size New size, in pixels /// //////////////////////////////////////////////////////////// virtual void setSize(const Vector2u& size); //////////////////////////////////////////////////////////// /// \brief Change the title of the window /// /// \param title New title /// //////////////////////////////////////////////////////////// virtual void setTitle(const String& title); //////////////////////////////////////////////////////////// /// \brief Change the window's icon /// /// \param width Icon's width, in pixels /// \param height Icon's height, in pixels /// \param pixels Pointer to the pixels in memory, format must be RGBA 32 bits /// //////////////////////////////////////////////////////////// virtual void setIcon(unsigned int width, unsigned int height, const Uint8* pixels); //////////////////////////////////////////////////////////// /// \brief Show or hide the window /// /// \param visible True to show, false to hide /// //////////////////////////////////////////////////////////// virtual void setVisible(bool visible); //////////////////////////////////////////////////////////// /// \brief Show or hide the mouse cursor /// /// \param visible True to show, false to hide /// //////////////////////////////////////////////////////////// virtual void setMouseCursorVisible(bool visible); //////////////////////////////////////////////////////////// /// \brief Grab or release the mouse cursor /// /// \param grabbed True to enable, false to disable /// //////////////////////////////////////////////////////////// virtual void setMouseCursorGrabbed(bool grabbed); //////////////////////////////////////////////////////////// /// \brief Set the displayed cursor to a native system cursor /// /// \param cursor Native system cursor type to display /// //////////////////////////////////////////////////////////// virtual void setMouseCursor(const CursorImpl& cursor); //////////////////////////////////////////////////////////// /// \brief Enable or disable automatic key-repeat /// /// \param enabled True to enable, false to disable /// //////////////////////////////////////////////////////////// virtual void setKeyRepeatEnabled(bool enabled); //////////////////////////////////////////////////////////// /// \brief Request the current window to be made the active /// foreground window /// //////////////////////////////////////////////////////////// virtual void requestFocus(); //////////////////////////////////////////////////////////// /// \brief Check whether the window has the input focus /// /// \return True if window has focus, false otherwise /// //////////////////////////////////////////////////////////// virtual bool hasFocus() const; //////////////////////////////////////////////////////////// /// \brief Give up waiting /// /// \return Boolean /// //////////////////////////////////////////////////////////// virtual bool giveUpWait(); protected: //////////////////////////////////////////////////////////// /// \brief Process incoming events from the operating system /// //////////////////////////////////////////////////////////// virtual void processEvents(bool wait); private: //////////////////////////////////////////////////////////// /// Register the window class /// //////////////////////////////////////////////////////////// void registerWindowClass(); //////////////////////////////////////////////////////////// /// \brief Switch to fullscreen mode /// /// \param mode Video mode to switch to /// //////////////////////////////////////////////////////////// void switchToFullscreen(const VideoMode& mode); //////////////////////////////////////////////////////////// /// \brief Free all the graphical resources attached to the window /// //////////////////////////////////////////////////////////// void cleanup(); //////////////////////////////////////////////////////////// /// \brief Process a Win32 event /// /// \param message Message to process /// \param wParam First parameter of the event /// \param lParam Second parameter of the event /// //////////////////////////////////////////////////////////// void processEvent(UINT message, WPARAM wParam, LPARAM lParam); //////////////////////////////////////////////////////////// /// \brief Enables or disables tracking for the mouse cursor leaving the window /// /// \param track True to enable, false to disable /// //////////////////////////////////////////////////////////// void setTracking(bool track); //////////////////////////////////////////////////////////// /// \brief Grab or release the mouse cursor /// /// This is not to be confused with setMouseCursorGrabbed. /// Here m_cursorGrabbed is not modified; it is used, /// for example, to release the cursor when switching to /// another application. /// /// \param grabbed True to enable, false to disable /// //////////////////////////////////////////////////////////// void grabCursor(bool grabbed); //////////////////////////////////////////////////////////// /// \brief Convert a Win32 virtual key code to a SFML key code /// /// \param key Virtual key code to convert /// \param flags Additional flags /// /// \return SFML key code corresponding to the key /// //////////////////////////////////////////////////////////// static Keyboard::Key virtualKeyCodeToSF(WPARAM key, LPARAM flags); //////////////////////////////////////////////////////////// /// \brief Function called whenever one of our windows receives a message /// /// \param handle Win32 handle of the window /// \param message Message received /// \param wParam First parameter of the message /// \param lParam Second parameter of the message /// /// \return True to discard the event after it has been processed /// //////////////////////////////////////////////////////////// static LRESULT CALLBACK globalOnEvent(HWND handle, UINT message, WPARAM wParam, LPARAM lParam); //////////////////////////////////////////////////////////// // Member data //////////////////////////////////////////////////////////// HWND m_handle; ///< Win32 handle of the window LONG_PTR m_callback; ///< Stores the original event callback function of the control bool m_cursorVisible; ///< Is the cursor visible or hidden? HCURSOR m_lastCursor; ///< Last cursor used -- this data is not owned by the window and is required to be always valid HICON m_icon; ///< Custom icon assigned to the window bool m_keyRepeatEnabled; ///< Automatic key-repeat state for keydown events Vector2u m_lastSize; ///< The last handled size of the window bool m_resizing; ///< Is the window being resized? Uint16 m_surrogate; ///< First half of the surrogate pair, in case we're receiving a Unicode character in two events bool m_mouseInside; ///< Mouse is inside the window? bool m_fullscreen; ///< Is the window fullscreen? bool m_cursorGrabbed; ///< Is the mouse cursor trapped? }; } // namespace priv } // namespace sf #endif // SFML_WINDOWIMPLWIN32_HPP
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1991 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: uiCreateControl.asm AUTHOR: Jon Witort REVISION HISTORY: Name Date Description ---- ---- ----------- jon 28 sept 1992 Initial version. DESCRIPTION: Code for the GrObjCreateControlClass $Id: uiCreateControl.asm,v 1.1 97/04/04 18:06:50 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrObjUIControllerCode segment resource COMMENT @---------------------------------------------------------------------- MESSAGE: GrObjCreateControlGetInfo -- MSG_GEN_CONTROL_GET_INFO for GrObjCreateControlClass DESCRIPTION: Return group PASS: *ds:si - instance data es - segment of GrObjCreateControlClass ax - The message cx:dx - GenControlBuildInfo structure to fill in RETURN: none DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 10/31/91 Initial version ------------------------------------------------------------------------------@ GrObjCreateControlGetInfo method dynamic GrObjCreateControlClass, MSG_GEN_CONTROL_GET_INFO mov si, offset GrObjCreateControl_dupInfo call CopyDupInfoCommon ret GrObjCreateControlGetInfo endm GrObjCreateControl_dupInfo GenControlBuildInfo < mask GCBF_SUSPEND_ON_APPLY, ; GCBI_flags GrObjCreateControl_IniFileKey, ; GCBI_initFileKey 0, ; GCBI_gcnList 0, ; GCBI_gcnCount 0, ; GCBI_notificationList 0, ; GCBI_notificationCount GrObjCreateControlName, ; GCBI_controllerName handle GrObjCreateControlUI, ; GCBI_dupBlock GrObjCreateControl_childList, ; GCBI_childList length GrObjCreateControl_childList, ; GCBI_childCount GrObjCreateControl_featuresList, ; GCBI_featuresList length GrObjCreateControl_featuresList, ; GCBI_featuresCount GROBJ_CREATE_CONTROL_DEFAULT_FEATURES, ; GCBI_defaultFeatures handle GrObjCreateToolControlUI, ; GCBI_dupBlock GrObjCreateControl_toolList, ; GCBI_childList length GrObjCreateControl_toolList, ; GCBI_childCount GrObjCreateControl_toolFeaturesList, ; GCBI_featuresList length GrObjCreateControl_toolFeaturesList, ; GCBI_featuresCount GROBJ_CREATE_CONTROL_DEFAULT_TOOLBOX_FEATURES, ; GCBI_defaultFeatures GrObjCreateControl_helpContext> ; GCBI_helpContext if FULL_EXECUTE_IN_PLACE GrObjControlInfoXIP segment resource endif GrObjCreateControl_helpContext char "dbGrObjCreat", 0 GrObjCreateControl_IniFileKey char "GrObjCreate", 0 ;--- GrObjCreateControl_childList GenControlChildInfo \ <offset GrObjCreateRectangleTrigger, mask GOCCF_RECTANGLE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateEllipseTrigger, mask GOCCF_ELLIPSE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateLineTrigger, mask GOCCF_LINE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateRoundedRectTrigger, mask GOCCF_ROUNDED_RECTANGLE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateArcTrigger, mask GOCCF_ARC, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateTriangleTrigger, mask GOCCF_TRIANGLE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateHexagonTrigger, mask GOCCF_HEXAGON, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateOctogonTrigger, mask GOCCF_OCTOGON, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateFiveStarTrigger, mask GOCCF_FIVE_POINTED_STAR, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateEightStarTrigger, mask GOCCF_EIGHT_POINTED_STAR, mask GCCF_IS_DIRECTLY_A_FEATURE> GrObjCreateControl_featuresList GenControlFeaturesInfo \ <offset GrObjCreateEightStarTrigger, CreateEightStarName, 0>, <offset GrObjCreateFiveStarTrigger, CreateFiveStarName, 0>, <offset GrObjCreateOctogonTrigger, CreateOctogonName, 0>, <offset GrObjCreateHexagonTrigger, CreateHexagonName, 0>, <offset GrObjCreateTriangleTrigger, CreateTriangleName, 0>, <offset GrObjCreateArcTrigger, CreateArcName, 0>, <offset GrObjCreateRoundedRectTrigger, CreateRoundedRectName, 0>, <offset GrObjCreateLineTrigger, CreateLineName, 0>, <offset GrObjCreateEllipseTrigger, CreateEllipseName, 0>, <offset GrObjCreateRectangleTrigger, CreateRectangleName, 0> GrObjCreateControl_toolList GenControlChildInfo \ <offset GrObjCreateRectangleTool, mask GOCCF_RECTANGLE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateEllipseTool, mask GOCCF_ELLIPSE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateLineTool, mask GOCCF_LINE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateRoundedRectTool, mask GOCCF_ROUNDED_RECTANGLE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateArcTool, mask GOCCF_ARC, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateTriangleTool, mask GOCCF_TRIANGLE, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateHexagonTool, mask GOCCF_HEXAGON, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateOctogonTool, mask GOCCF_OCTOGON, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateFiveStarTool, mask GOCCF_FIVE_POINTED_STAR, mask GCCF_IS_DIRECTLY_A_FEATURE>, <offset GrObjCreateEightStarTool, mask GOCCF_EIGHT_POINTED_STAR, mask GCCF_IS_DIRECTLY_A_FEATURE> GrObjCreateControl_toolFeaturesList GenControlFeaturesInfo \ <offset GrObjCreateEightStarTool, CreateEightStarName, 0>, <offset GrObjCreateFiveStarTool, CreateFiveStarName, 0>, <offset GrObjCreateOctogonTool, CreateOctogonName, 0>, <offset GrObjCreateHexagonTool, CreateHexagonName, 0>, <offset GrObjCreateTriangleTool, CreateTriangleName, 0>, <offset GrObjCreateArcTool, CreateArcName, 0>, <offset GrObjCreateRoundedRectTool, CreateRoundedRectName, 0>, <offset GrObjCreateLineTool, CreateLineName, 0>, <offset GrObjCreateEllipseTool, CreateEllipseName, 0>, <offset GrObjCreateRectangleTool, CreateRectangleName, 0> if FULL_EXECUTE_IN_PLACE GrObjControlInfoXIP ends endif GrObjUIControllerCode ends GrObjUIControllerActionCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrObjCreateControlCreateGrObj %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: GrObjCreateControl method for MSG_GOCC_CREATE_GROBJ Called by: Pass: *ds:si = GrObjCreateControl object ds:di = GrObjCreateControl instance cx:dx - segment:offset of grobj class to create (eg. RectClass) Return: nothing Destroyed: ax, bx, di Comments: Revision History: Name Date Description ---- ------------ ----------- jon Feb 24, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrObjCreateControlCreateGrObj method dynamic GrObjCreateControlClass, MSG_GOCC_CREATE_GROBJ .enter sub sp, size GrObjBodyCreateGrObjParams mov bp, sp movdw ss:[bp].GBCGP_class, cxdx mov ss:[bp].GBCGP_width.WWF_int, 100 mov ss:[bp].GBCGP_width.WWF_frac, 0 mov ss:[bp].GBCGP_height.WWF_int, 100 mov ss:[bp].GBCGP_height.WWF_frac, 0 mov dx, size GrObjBodyCreateGrObjParams mov ax, MSG_GB_CREATE_GROBJ call GrObjControlOutputActionStackToBody add sp, size GrObjBodyCreateGrObjParams .leave ret GrObjCreateControlCreateGrObj endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrObjCreateControlCreatePolygon %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: GrObjCreateControl method for MSG_GOCC_CREATE_POLYGON Called by: Pass: *ds:si = GrObjCreateControl object ds:di = GrObjCreateControl instance cx - # of polygon sides Return: nothing Destroyed: ax, bx, di Comments: Revision History: Name Date Description ---- ------------ ----------- jon Feb 24, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrObjCreateControlCreatePolygon method dynamic GrObjCreateControlClass, MSG_GOCC_CREATE_POLYGON .enter mov bp, cx ;cx <- # sides mov cx, 100 mov dx, cx mov ax, MSG_GB_CREATE_POLYGON call GrObjControlOutputActionRegsToBody .leave ret GrObjCreateControlCreatePolygon endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GrObjCreateControlCreateStar %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Description: GrObjCreateControl method for MSG_GOCC_CREATE_STAR Called by: Pass: *ds:si = GrObjCreateControl object ds:di = GrObjCreateControl instance cx - # of star points Return: nothing Destroyed: ax, bx, di Comments: Revision History: Name Date Description ---- ------------ ----------- jon Feb 24, 1992 Initial version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GrObjCreateControlCreateStar method dynamic GrObjCreateControlClass, MSG_GOCC_CREATE_STAR .enter sub sp, size SplineMakeStarParams mov bp, sp mov ss:[bp].SMSP_outerRadius.P_y, 50 mov ss:[bp].SMSP_outerRadius.P_x, 50 mov ss:[bp].SMSP_innerRadius.P_y, 19 mov ss:[bp].SMSP_innerRadius.P_x, 19 mov ss:[bp].SMSP_starPoints, cx mov dx, size SplineMakeStarParams mov ax, MSG_GB_CREATE_STAR call GrObjControlOutputActionStackToBody add sp, size SplineMakeStarParams .leave ret GrObjCreateControlCreateStar endm GrObjUIControllerActionCode ends
/* The Jinx library is distributed under the MIT License (MIT) https://opensource.org/licenses/MIT See LICENSE.TXT or Jinx.h for license details. Copyright (c) 2016 James Boer */ #include <chrono> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <stdexcept> #include "../../Source/Jinx.h" using namespace Jinx; #ifndef NDEBUG #define REQUIRE assert #else #define REQUIRE(x) { if (!(x)) throw new std::runtime_error("Failure for condition: " #x); } #endif Jinx::RuntimePtr TestCreateRuntime() { return Jinx::CreateRuntime(); } Jinx::ScriptPtr TestCreateScript(const char * scriptText, Jinx::RuntimePtr runtime = nullptr) { if (!runtime) runtime = CreateRuntime(); // Compile the text to bytecode auto bytecode = runtime->Compile(scriptText, "Test Script"/*, { "core" }*/); if (!bytecode) return nullptr; // Create a runtime script with the given bytecode return runtime->CreateScript(bytecode); } Jinx::ScriptPtr TestExecuteScript(const char * scriptText, Jinx::RuntimePtr runtime = nullptr) { // Create a runtime script auto script = TestCreateScript(scriptText, runtime); if (!script) return nullptr; // Execute script until finished do { if (!script->Execute()) return nullptr; } while (!script->IsFinished()); return script; } int main(int argc, char ** argv) { printf("Jinx version: %s\n", Jinx::GetVersionString().c_str()); GlobalParams params; params.logBytecode = true; params.logSymbols = true; params.errorOnMaxInstrunctions = false; params.maxInstructions = std::numeric_limits<uint32_t>::max(); Initialize(params); const char * scriptText = u8R"( set private a to 123 set private a to 234 )"; auto script = TestExecuteScript(scriptText); REQUIRE(!script); auto memStats = GetMemoryStats(); printf("\nMemory Stats\n"); printf("-------------\n"); printf("Allocation count: %zu\n", memStats.allocationCount); printf("Free count: %zu\n", memStats.freeCount); printf("Allocated memory: %zu bytes\n", memStats.allocatedMemory); return 0; }
; ; print16.asm ; KripayaOS Project ; Author(s): [Ashwin: ashwonixer123@gmail.com] ; [bits 16] print16: ; Save the registers push ax push bx ; Allow Printing to the screen mov ah, 0x0E .loop: ; Check if character is null cmp byte[bx], 0 je .done ; Print to the screen mov al, byte[bx] int 0x10 ; Increment bx and loop again inc bx jmp .loop .done: ; Restore the registers and return pop bx pop ax ret print_hex16: ; Save the registers push ax push bx push cx ; Allow Printing to the screen mov ah, 0x0E ; Print the prefix mov al, '0' int 0x10 mov al, 'x' int 0x10 ; Change the value of cx (counter) mov cx, 4 .loop_hex: ; Check if character is null cmp cx, 0 jmp .hex_done ; Save bx and shift of upper bit push bx shr bx, 12 ; Check if it's a character cmp bx, 10 jge .hex_alpha ; Set al = 0 and add bl mov al, '0' add al, bl ; End of loop jmp .hex_loop_done .hex_alpha: ; Subtract 10 from dl to get the amount sub bl, 10 ; Move 'A' to al and then add bl mov al, 'A' add al, bl .hex_loop_done: ; Print the character int 0x10 ; Restore bx and shift to next 4 bits pop bx shl bx, 4 ; Decrement the cx counter dec cx ; Loop again jmp .loop_hex .hex_done: ; Restore the registers and return pop cx pop bx pop ax ret
; ====================== ZagrOS ====================== ; Zagros Open Source Operating System ; Saeid Bostandoust (ssbostan@linuxmail.org) ; Bostandoust.IR ; ====================== ZagrOS ====================== ; ================ precompile section ================ #make_bin# #load_segment=2000h# #load_offset=0000h# #cs=2000h# #ds=2000h# #es=2000h# #ss=0000h# #bp=fdfeh# #sp=fffeh# #ax=0# #bx=0# #cx=0# #dx=0# #si=0# #di=0# ; ================ precompile section ================ ; ====================== kernel ====================== xor ax, ax mov ax, 2000h mov ds, ax mov es, ax cli mov ax, 0000h mov ss, ax mov bp, 0fdfeh mov sp, 0fffeh sti include "lib.asm" include "tools.asm" start: mov ah, 00h mov al, 03h int 10h mov ah, 02h mov al, 07h int 91h mov ah, 01h int 91h mov ah, 02h mov bh, 00h mov dh, 00h mov dl, 00h int 10h mov ah, 01h mov ch, 07h mov cl, 07h int 10h mov al, 02h call setcolor mov dh, 01h mov dl, 02h call gotoxy mov si, offset OS_NAME call putstr mov al, 20h call putchr mov si, offset OS_VERSION call putstr mov al, 20h call putchr mov si, offset OS_RELEASE call putstr mov al, 07h call setcolor call endl call endl include "command.asm" ; ====================== kernel ====================== ; ================= define variables ================= OS_NAME db "ZagrOS", 24h OS_VERSION db "v.0.0.4", 24h OS_RELEASE db "01/11/2012", 24h OS_AUTHOR db "Saeid Bostandoust", 24h ; ================= define variables =================
; >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> ; simplifying macros and functions ; makes a VDP address difference vdpCommDelta function addr,((addr&$3FFF)<<16)|((addr&$C000)>>14) ; makes a VDP command vdpComm function addr,type,rwd,(((type&rwd)&3)<<30)|((addr&$3FFF)<<16)|(((type&rwd)&$FC)<<2)|((addr&$C000)>>14) ; values for the type argument VRAM = %100001 CRAM = %101011 VSRAM = %100101 ; values for the rwd argument READ = %001100 WRITE = %000111 DMA = %100111 ; tells the VDP to copy a region of 68k memory to VRAM or CRAM or VSRAM dma68kToVDP macro source,dest,length,type lea (VDP_control_port).l,a5 move.l #(($9400|((((length)>>1)&$FF00)>>8))<<16)|($9300|(((length)>>1)&$FF)),(a5) move.l #(($9600|((((source)>>1)&$FF00)>>8))<<16)|($9500|(((source)>>1)&$FF)),(a5) move.w #$9700|(((((source)>>1)&$FF0000)>>16)&$7F),(a5) move.w #((vdpComm(dest,type,DMA)>>16)&$FFFF),(a5) move.w #(vdpComm(dest,type,DMA)&$FFFF),(DMA_data_thunk).w move.w (DMA_data_thunk).w,(a5) endm ; tells the VDP to fill a region of VRAM with a certain byte dmaFillVRAM macro byte,addr,length lea (VDP_control_port).l,a5 move.w #$8F01,(a5) ; VRAM pointer increment: $0001 move.l #(($9400|((((length)-1)&$FF00)>>8))<<16)|($9300|(((length)-1)&$FF)),(a5) ; DMA length ... move.w #$9780,(a5) ; VRAM fill move.l #$40000080|(((addr)&$3FFF)<<16)|(((addr)&$C000)>>14),(a5) ; Start at ... move.w #(byte)<<8,(VDP_data_port).l ; Fill with byte .loop: move.w (a5),d1 btst #1,d1 bne.s .loop ; busy loop until the VDP is finished filling... move.w #$8F02,(a5) ; VRAM pointer increment: $0002 endm ; calculates initial loop counter value for a dbf loop ; that writes n bytes total at 4 bytes per iteration bytesToLcnt function n,n>>2-1 ; calculates initial loop counter value for a dbf loop ; that writes n bytes total at 2 bytes per iteration bytesToWcnt function n,n>>1-1 ; fills a region of 68k RAM with 0 clearRAM macro startaddr,endaddr if startaddr>endaddr fatal "Starting address of clearRAM \{startaddr} is after ending address \{endaddr}." elseif startaddr==endaddr warning "clearRAM is clearing zero bytes. Turning this into a nop instead." exitm endif if ((startaddr)&$8000)==0 lea (startaddr).l,a1 else lea (startaddr).w,a1 endif moveq #0,d0 if ((startaddr)&1) move.b d0,(a1)+ endif move.w #bytesToLcnt((endaddr-startaddr) - ((startaddr)&1)),d1 .loop: move.l d0,(a1)+ dbf d1,.loop if (((endaddr-startaddr) - ((startaddr)&1))&2) move.w d0,(a1)+ endif if (((endaddr-startaddr) - ((startaddr)&1))&1) move.b d0,(a1)+ endif endm ; tells the Z80 to stop, and waits for it to finish stopping (acquire bus) stopZ80 macro move.w #$100,(Z80_Bus_Request).l ; stop the Z80 .loop: btst #0,(Z80_Bus_Request).l bne.s .loop ; loop until it says it's stopped endm ; tells the Z80 to start again startZ80 macro move.w #0,(Z80_Bus_Request).l ; start the Z80 endm ; function to make a little-endian 16-bit pointer for the Z80 sound driver z80_ptr function x,(x)<<8&$FF00|(x)>>8&$7F|$80 ; macro to declare a little-endian 16-bit pointer for the Z80 sound driver rom_ptr_z80 macro addr dc.w z80_ptr(addr) endm ; aligns the start of a bank, and detects when the bank's contents is too large ; can also print the amount of free space in a bank with DebugSoundbanks set startBank macro {INTLABEL} align $8000 __LABEL__ label * soundBankStart := __LABEL__ soundBankName := "__LABEL__" endm DebugSoundbanks := 0 finishBank macro if * > soundBankStart + $8000 fatal "soundBank \{soundBankName} must fit in $8000 bytes but was $\{*-soundBankStart}. Try moving something to the other bank." elseif (DebugSoundbanks<>0)&&(MOMPASS=1) message "soundBank \{soundBankName} has $\{$8000+soundBankStart-*} bytes free at end." endif endm ; macro to replace the destination with its absolute value abs macro destination tst.ATTRIBUTE destination bpl.s .skip neg.ATTRIBUTE destination .skip: endm if 0|allOptimizations absw macro destination ; use a short branch instead abs.ATTRIBUTE destination endm else ; macro to replace the destination with its absolute value using a word-sized branch absw macro destination tst.ATTRIBUTE destination bpl.w .skip neg.ATTRIBUTE destination .skip: endm endif ; macro to move the absolute value of the source in the destination mvabs macro source,destination move.ATTRIBUTE source,destination bpl.s .skip neg.ATTRIBUTE destination .skip: endm ; macro to declare an offset table offsetTable macro {INTLABEL} current_offset_table := __LABEL__ __LABEL__ label * endm ; macro to declare an entry in an offset table offsetTableEntry macro ptr dc.ATTRIBUTE ptr-current_offset_table endm ; macro to declare a zone-ordered table ; entryLen is the length of each table entry, and zoneEntries is the number of entries per zone zoneOrderedTable macro entryLen,zoneEntries,{INTLABEL} __LABEL__ label * ; set some global variables zone_table_name := "__LABEL__" zone_table_addr := * zone_entry_len := entryLen zone_entries := zoneEntries zone_entries_left := 0 cur_zone_id := 0 cur_zone_str := "0" endm zoneOrderedOffsetTable macro entryLen,zoneEntries,{INTLABEL} current_offset_table := __LABEL__ __LABEL__ zoneOrderedTable entryLen,zoneEntries endm ; macro to declare one or more entries in a zone-ordered table zoneTableEntry macro value if "value"<>"" if zone_entries_left dc.ATTRIBUTE value zone_entries_left := zone_entries_left-1 else !org zone_table_addr+zone_id_{cur_zone_str}*zone_entry_len*zone_entries dc.ATTRIBUTE value zone_entries_left := zone_entries-1 cur_zone_id := cur_zone_id+1 cur_zone_str := "\{cur_zone_id}" endif shift zoneTableEntry.ATTRIBUTE ALLARGS endif endm ; macro to declare one or more BINCLUDE entries in a zone-ordered table zoneTableBinEntry macro numEntries,path if zone_entries_left BINCLUDE path zone_entries_left := zone_entries_left-numEntries else !org zone_table_addr+zone_id_{cur_zone_str}*zone_entry_len*zone_entries BINCLUDE path zone_entries_left := zone_entries-numEntries cur_zone_id := cur_zone_id+1 cur_zone_str := "\{cur_zone_id}" endif endm ; macro to declare one entry in a zone-ordered offset table zoneOffsetTableEntry macro value zoneTableEntry.ATTRIBUTE value-current_offset_table endm ; macro which sets the PC to the correct value at the end of a zone offset table and checks if the correct ; number of entries were declared zoneTableEnd macro if (cur_zone_id<>no_of_zones)&&(MOMPASS=1) message "Warning: Table \{zone_table_name} has \{cur_zone_id/1.0} entries, but it should have \{(no_of_zones)/1.0} entries" endif !org zone_table_addr+cur_zone_id*zone_entry_len*zone_entries endm ; macro to declare sub-object data subObjData macro mappings,vram,renderflags,priority,width,collision dc.l mappings dc.w vram dc.b renderflags,priority,width,collision endm ; macros for defining animated PLC script lists zoneanimstart macro {INTLABEL} __LABEL__ label * zoneanimcount := 0 zoneanimcur := "__LABEL__" dc.w zoneanimcount___LABEL__ ; Number of scripts for a zone (-1) endm zoneanimend macro zoneanimcount_{"\{zoneanimcur}"} = zoneanimcount-1 endm zoneanimdeclanonid := 0 zoneanimdecl macro duration,artaddr,vramaddr,numentries,numvramtiles zoneanimdeclanonid := zoneanimdeclanonid + 1 start: dc.l (duration&$FF)<<24|artaddr dc.w tiles_to_bytes(vramaddr) dc.b numentries, numvramtiles zoneanimcount := zoneanimcount + 1 endm ; macros to convert from tile index to art tiles, block mapping or VRAM address. make_art_tile function addr,pal,pri,((pri&1)<<15)|((pal&3)<<13)|(addr&tile_mask) make_art_tile_2p function addr,pal,pri,((pri&1)<<15)|((pal&3)<<13)|((addr&tile_mask)>>1) make_block_tile function addr,flx,fly,pal,pri,((pri&1)<<15)|((pal&3)<<13)|((fly&1)<<12)|((flx&1)<<11)|(addr&tile_mask) make_block_tile_2p function addr,flx,fly,pal,pri,((pri&1)<<15)|((pal&3)<<13)|((fly&1)<<12)|((flx&1)<<11)|((addr&tile_mask)>>1) tiles_to_bytes function addr,((addr&$7FF)<<5) make_block_tile_pair function addr,flx,fly,pal,pri,((make_block_tile(addr,flx,fly,pal,pri)<<16)|make_block_tile(addr,flx,fly,pal,pri)) make_block_tile_pair_2p function addr,flx,fly,pal,pri,((make_block_tile_2p(addr,flx,fly,pal,pri)<<16)|make_block_tile_2p(addr,flx,fly,pal,pri)) ; function to calculate the location of a tile in plane mappings with a width of 64 cells planeLocH40 function col,line,(($80 * line) + (2 * col)) ; function to calculate the location of a tile in plane mappings with a width of 128 cells planeLocH80 function col,line,(($100 * line) + (2 * col))
Elf64_Sym <0> Elf64_Sym <offset aItmDeregistert - offset unk_470, 20h, 0, 0, \ ; "_ITM_deregisterTMCloneTable" offset dword_0, 0> Elf64_Sym <offset aPrintf - offset unk_470, 12h, 0, 0, offset dword_0,\ ; "printf" 0> Elf64_Sym <offset aLibcStartMain - offset unk_470, 12h, 0, 0, \ ; "__libc_start_main" offset dword_0, 0> Elf64_Sym <offset aGmonStart - offset unk_470, 20h, 0, 0, \ ; "__gmon_start__" offset dword_0, 0> Elf64_Sym <offset aItmRegistertmc - offset unk_470, 20h, 0, 0, \ ; "_ITM_registerTMCloneTable" offset dword_0, 0> Elf64_Sym <offset aCxaFinalize - offset unk_470, 22h, 0, 0, \ ; "__cxa_finalize" offset dword_0, 0>
/*============================================================================= Spirit v1.6.0 Copyright (c) 2002-2003 Joel de Guzman Copyright (c) 2002-2003 Hartmut Kaiser http://spirit.sourceforge.net/ Permission to copy, use, modify, sell and distribute this software is granted provided this copyright notice appears in all copies. This software is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose. =============================================================================*/ #if !defined(BOOST_SPIRIT_PARSER_TYPE_HPP) #define BOOST_SPIRIT_PARSER_TYPE_HPP /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace spirit { #if !defined(BOOST_SPIRIT_PRIMITIVES_IPP) #include "boost/spirit/core/primitives/primitives.hpp" #endif /////////////////////////////////////////////////////////////////////////////// // // Helper templates to derive the parser type from an auxilliary type and to // generate an object of the required parser type given an auxilliary object. // Supported types to convert are parsers, single characters and character // strings. // /////////////////////////////////////////////////////////////////////////////// namespace impl { template<typename T> struct default_as_parser { typedef T type; static type const& convert(type const& p) { return p; } }; struct char_as_parser { typedef chlit<char> type; static type convert(char ch) { return type(ch); } }; struct wchar_as_parser { typedef chlit<wchar_t> type; static type convert(wchar_t ch) { return type(ch); } }; struct string_as_parser { typedef strlit<char const*> type; static type convert(char const* str) { return type(str); } }; struct wstring_as_parser { typedef strlit<wchar_t const*> type; static type convert(wchar_t const* str) { return type(str); } }; } #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template<typename T> struct as_parser : impl::default_as_parser<T> {}; #else // !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template<typename T> struct as_parser { enum { is_cptr = boost::is_convertible<T, char const*>::value, is_wcptr = is_cptr ? false : boost::is_convertible<T, wchar_t const*>::value }; typedef typename mpl::if_c<is_cptr, strlit<char const*>, typename mpl::if_c<is_wcptr, strlit<wchar_t const*>, T >::type >::type type; typedef typename mpl::if_c<is_cptr, char const*, typename mpl::if_c<is_wcptr, wchar_t const*, T const& >::type >::type param_type; typedef typename mpl::if_c<(is_cptr || is_wcptr), type, type const& >::type return_type; static return_type convert(param_type p) { return p; } }; #endif // !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template<> struct as_parser<char> : impl::char_as_parser {}; template<> struct as_parser<wchar_t> : impl::wchar_as_parser {}; template<> struct as_parser<char const*> : impl::string_as_parser {}; template<> struct as_parser<wchar_t const*> : impl::wstring_as_parser {}; #ifdef __BORLANDC__ template<> struct as_parser<char*> : impl::string_as_parser {}; template<> struct as_parser<wchar_t*> : impl::wstring_as_parser {}; #endif // __BORLANDC__ #if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template<int N> struct as_parser<char[N]> : impl::string_as_parser {}; template<int N> struct as_parser<wchar_t[N]> : impl::wstring_as_parser {}; #if !defined(__MWERKS__) || (__MWERKS__ > 0x2407) template<int N> struct as_parser<char const[N]> : impl::string_as_parser {}; template<int N> struct as_parser<wchar_t const[N]> : impl::string_as_parser {}; #endif // !defined(__MWERKS__) || (__MWERKS__ > 0x2407) #endif // !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) }} // namespace boost::spirit #endif
IF !__CPU_INTEL__ && !__CPU_GBZ80__ SECTION code_psg PUBLIC ay_vt2_init PUBLIC _ay_vt2_init EXTERN asm_VT_INIT ay_vt2_init: _ay_vt2_init: push ix push iy call asm_VT_INIT pop iy pop ix ret ENDIF
; A173495: a(n) = Lucas(n) - floor(Lucas(n)/2). ; 1,1,2,2,4,6,9,15,24,38,62,100,161,261,422,682,1104,1786,2889,4675,7564,12238,19802,32040,51841,83881,135722,219602,355324,574926,930249,1505175,2435424,3940598,6376022,10316620,16692641,27009261,43701902,70711162,114413064,185124226,299537289,484661515,784198804,1268860318,2053059122,3321919440,5374978561,8696898001,14071876562,22768774562,36840651124,59609425686,96450076809,156059502495,252509579304,408569081798,661078661102,1069647742900,1730726404001,2800374146901,4531100550902,7331474697802,11862575248704,19194049946506,31056625195209,50250675141715,81307300336924,131557975478638,212865275815562,344423251294200,557288527109761,901711778403961,1459000305513722,2360712083917682,3819712389431404,6180424473349086 mov $2,$0 add $0,1 mov $1,2 mov $5,1 mov $6,$2 lpb $0,1 mov $3,1 mov $4,$5 add $5,$1 mov $1,$4 trn $6,1 mov $0,$6 mov $7,2 lpe add $1,$3 add $1,$7 div $1,$7 sub $1,1
; A164900: a(2n) = 4*n*(n+1) + 3; a(2n+1) = 2*n*(n+2) + 3. ; 3,3,11,9,27,19,51,33,83,51,123,73,171,99,227,129,291,163,363,201,443,243,531,289,627,339,731,393,843,451,963,513,1091,579,1227,649,1371,723,1523,801,1683,883,1851,969,2027,1059,2211,1153,2403,1251,2603,1353,2811,1459,3027,1569,3251,1683,3483,1801,3723,1923,3971,2049,4227,2179,4491,2313,4763,2451,5043,2593,5331,2739,5627,2889,5931,3043,6243,3201,6563,3363,6891,3529,7227,3699,7571,3873,7923,4051,8283,4233,8651,4419,9027,4609,9411,4803,9803,5001,10203,5203,10611,5409,11027,5619,11451,5833,11883,6051,12323,6273,12771,6499,13227,6729,13691,6963,14163,7201,14643,7443,15131,7689,15627,7939,16131,8193,16643,8451,17163,8713,17691,8979,18227,9249,18771,9523,19323,9801,19883,10083,20451,10369,21027,10659,21611,10953,22203,11251,22803,11553,23411,11859,24027,12169,24651,12483,25283,12801,25923,13123,26571,13449,27227,13779,27891,14113,28563,14451,29243,14793,29931,15139,30627,15489,31331,15843,32043,16201,32763,16563,33491,16929,34227,17299,34971,17673,35723,18051,36483,18433,37251,18819,38027,19209,38811,19603,39603,20001,40403,20403,41211,20809,42027,21219,42851,21633,43683,22051,44523,22473,45371,22899,46227,23329,47091,23763,47963,24201,48843,24643,49731,25089,50627,25539,51531,25993,52443,26451,53363,26913,54291,27379,55227,27849,56171,28323,57123,28801,58083,29283,59051,29769,60027,30259,61011,30753,62003,31251 add $0,1 mov $1,1 mov $2,9 lpb $0,1 pow $0,2 sub $0,1 add $1,$2 div $1,2 add $1,$0 mod $0,2 mov $2,2 lpe sub $1,$2
// This file is a part of Julia. License is MIT: https://julialang.org/license #include "llvm-version.h" #include "platform.h" #include "options.h" #if defined(_OS_WINDOWS_) // use ELF because RuntimeDyld COFF i686 support didn't exist // use ELF because RuntimeDyld COFF X86_64 doesn't seem to work (fails to generate function pointers)? #define FORCE_ELF #endif #if defined(_CPU_X86_) #define JL_NEED_FLOATTEMP_VAR 1 #endif #if defined(_OS_WINDOWS_) || defined(_OS_FREEBSD_) #define JL_DISABLE_FPO #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #define __STDC_CONSTANT_MACROS #endif #include <setjmp.h> #include <string> #include <fstream> #include <map> #include <array> #include <vector> #include <set> #include <functional> // target machine computation #include <llvm/CodeGen/TargetSubtargetInfo.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Target/TargetOptions.h> #include <llvm/Support/Host.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Object/SymbolSize.h> #include <llvm/InitializePasses.h> // IR building #include <llvm/IR/IntrinsicInst.h> #include <llvm/Object/ObjectFile.h> #include <llvm/IR/DIBuilder.h> #include <llvm/AsmParser/Parser.h> #include <llvm/DebugInfo/DIContext.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Intrinsics.h> #include <llvm/IR/Attributes.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/MDBuilder.h> // support #include <llvm/ADT/SmallBitVector.h> #include <llvm/ADT/Optional.h> #include <llvm/ADT/Statistic.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Support/FormattedStream.h> #include <llvm/Support/SourceMgr.h> // for llvmcall #include <llvm/Transforms/Utils/Cloning.h> // for llvmcall inlining #include <llvm/Transforms/Utils/BasicBlockUtils.h> #include <llvm/IR/Verifier.h> // for llvmcall validation #include <llvm/IR/PassTimingInfo.h> #include <llvm/Bitcode/BitcodeWriter.h> // C API #include <llvm-c/Types.h> // for configuration options #include <llvm/Support/PrettyStackTrace.h> #include <llvm/Support/CommandLine.h> #include <llvm/IR/InlineAsm.h> #if defined(_CPU_ARM_) || defined(_CPU_AARCH64_) # include <sys/utsname.h> #endif #if defined(USE_POLLY) #include <polly/RegisterPasses.h> #include <polly/ScopDetection.h> #endif #include <llvm/Target/TargetMachine.h> using namespace llvm; typedef Instruction TerminatorInst; #if defined(_OS_WINDOWS_) && !defined(NOMINMAX) #define NOMINMAX #endif #include "julia.h" #include "julia_internal.h" #include "jitlayers.h" #include "codegen_shared.h" #include "processor.h" #include "julia_assert.h" extern "C" { #include "builtin_proto.h" #ifdef HAVE_SSP extern uintptr_t __stack_chk_guard; extern void __stack_chk_fail(); #else JL_DLLEXPORT uintptr_t __stack_chk_guard = (uintptr_t)0xBAD57ACCBAD67ACC; // 0xBADSTACKBADSTACK JL_DLLEXPORT void __stack_chk_fail() { /* put your panic function or similar in here */ fprintf(stderr, "fatal error: stack corruption detected\n"); gc_debug_critical_error(); abort(); // end with abort, since the compiler destroyed the stack upon entry to this function, there's no going back now } #endif #ifdef _OS_WINDOWS_ #if defined(_CPU_X86_64_) #if defined(_COMPILER_GCC_) extern void ___chkstk_ms(void); #else extern void __chkstk(void); #endif #else #if defined(_COMPILER_GCC_) #undef _alloca extern void _alloca(void); #else extern void _chkstk(void); #endif #endif //void *force_chkstk(void) { // return alloca(40960); //} #endif } #if defined(_COMPILER_MICROSOFT_) && !defined(__alignof__) #define __alignof__ __alignof #endif #define DISABLE_FLOAT16 // llvm state extern JITEventListener *CreateJuliaJITEventListener(); // for image reloading bool imaging_mode = false; // shared llvm state JL_DLLEXPORT LLVMContext &jl_LLVMContext = *(new LLVMContext()); TargetMachine *jl_TargetMachine; static DataLayout &jl_data_layout = *(new DataLayout("")); #define jl_Module ctx.f->getParent() #define jl_builderModule(builder) (builder).GetInsertBlock()->getParent()->getParent() #define prepare_call(Callee) prepare_call_in(jl_Module, (Callee)) // types static Type *T_jlvalue; static Type *T_pjlvalue; static Type *T_prjlvalue; static Type *T_ppjlvalue; static Type *T_pprjlvalue; static Type *jl_array_llvmt; static Type *jl_parray_llvmt; static FunctionType *jl_func_sig; static FunctionType *jl_func_sig_sparams; static Type *T_pvoidfunc; static IntegerType *T_int1; static IntegerType *T_int8; static IntegerType *T_int16; static IntegerType *T_int32; static IntegerType *T_int64; static IntegerType *T_uint8; static IntegerType *T_uint16; static IntegerType *T_uint32; static IntegerType *T_uint64; static IntegerType *T_char; static IntegerType *T_size; static IntegerType *T_sigatomic; static Type *T_float16; static Type *T_float32; static Type *T_float64; static Type *T_float128; static Type *T_pint8; static Type *T_pint16; static Type *T_pint32; static Type *T_pint64; static Type *T_psize; static Type *T_pfloat32; static Type *T_pfloat64; static Type *T_ppint8; static Type *T_pppint8; static Type *T_void; // type-based alias analysis nodes. Indentation of comments indicates hierarchy. static MDNode *tbaa_root; // Everything static MDNode *tbaa_gcframe; // GC frame // LLVM should have enough info for alias analysis of non-gcframe stack slot // this is mainly a place holder for `jl_cgval_t::tbaa` static MDNode *tbaa_stack; // stack slot static MDNode *tbaa_unionselbyte; // a selector byte in isbits Union struct fields static MDNode *tbaa_data; // Any user data that `pointerset/ref` are allowed to alias static MDNode *tbaa_binding; // jl_binding_t::value static MDNode *tbaa_value; // jl_value_t, that is not jl_array_t static MDNode *tbaa_mutab; // mutable type static MDNode *tbaa_immut; // immutable type static MDNode *tbaa_ptrarraybuf; // Data in an array of boxed values static MDNode *tbaa_arraybuf; // Data in an array of POD static MDNode *tbaa_array; // jl_array_t static MDNode *tbaa_arrayptr; // The pointer inside a jl_array_t static MDNode *tbaa_arraysize; // A size in a jl_array_t static MDNode *tbaa_arraylen; // The len in a jl_array_t static MDNode *tbaa_arrayflags; // The flags in a jl_array_t static MDNode *tbaa_arrayoffset; // The offset in a jl_array_t static MDNode *tbaa_arrayselbyte; // a selector byte in a isbits Union jl_array_t static MDNode *tbaa_const; // Memory that is immutable by the time LLVM can see it static Attribute Thunk; // Basic DITypes static DICompositeType *jl_value_dillvmt; static DIDerivedType *jl_pvalue_dillvmt; static DIDerivedType *jl_ppvalue_dillvmt; static DISubroutineType *jl_di_func_sig; static DISubroutineType *jl_di_func_null_sig; // constants static Constant *V_null; static bool type_is_ghost(Type *ty) { return (ty == T_void || ty->isEmptyTy()); } // should agree with `Core.Compiler.hasuniquerep` static bool type_has_unique_rep(jl_value_t *t) { if (t == (jl_value_t*)jl_typeofbottom_type) return false; if (t == jl_bottom_type) return true; if (jl_is_typevar(t)) return false; if (!jl_is_kind(jl_typeof(t))) return true; if (jl_is_concrete_type(t)) return true; if (jl_is_datatype(t)) { jl_datatype_t *dt = (jl_datatype_t*)t; if (dt->name != jl_tuple_typename && !jl_is_vararg_type(t)) { for (size_t i = 0; i < jl_nparams(dt); i++) if (!type_has_unique_rep(jl_tparam(dt, i))) return false; return true; } } return false; } static bool is_uniquerep_Type(jl_value_t *t) { return jl_is_type_type(t) && type_has_unique_rep(jl_tparam0(t)); } class jl_codectx_t; struct JuliaVariable { public: StringLiteral name; bool isconst; Type *(*_type)(LLVMContext &C); JuliaVariable(const JuliaVariable&) = delete; JuliaVariable(const JuliaVariable&&) = delete; GlobalVariable *realize(Module *m) { if (GlobalValue *V = m->getNamedValue(name)) return cast<GlobalVariable>(V); return new GlobalVariable(*m, _type(m->getContext()), isconst, GlobalVariable::ExternalLinkage, NULL, name); } GlobalVariable *realize(jl_codectx_t &ctx); }; static inline void add_named_global(JuliaVariable *name, void *addr) { add_named_global(name->name, addr); } struct JuliaFunction { public: StringLiteral name; FunctionType *(*_type)(LLVMContext &C); AttributeList (*_attrs)(LLVMContext &C); JuliaFunction(const JuliaFunction&) = delete; JuliaFunction(const JuliaFunction&&) = delete; Function *realize(Module *m) { if (GlobalValue *V = m->getNamedValue(name)) return cast<Function>(V); Function *F = Function::Create(_type(m->getContext()), Function::ExternalLinkage, name, m); if (_attrs) F->setAttributes(_attrs(m->getContext())); return F; } Function *realize(jl_codectx_t &ctx); }; template<typename T> static inline void add_named_global(JuliaFunction *name, T *addr) { // cast through integer to avoid c++ pedantic warning about casting between // data and code pointers add_named_global(name->name, (void*)(uintptr_t)addr); } template<typename T> static inline void add_named_global(StringRef name, T *addr) { // cast through integer to avoid c++ pedantic warning about casting between // data and code pointers add_named_global(name, (void*)(uintptr_t)addr); } AttributeSet Attributes(LLVMContext &C, std::initializer_list<Attribute::AttrKind> attrkinds) { SmallVector<Attribute, 8> attrs(attrkinds.size()); for (size_t i = 0; i < attrkinds.size(); i++) attrs[i] = Attribute::get(C, attrkinds.begin()[i]); return AttributeSet::get(C, makeArrayRef(attrs)); } static Type *get_pjlvalue(LLVMContext &C) { return T_pjlvalue; } static FunctionType *get_func_sig(LLVMContext &C) { return jl_func_sig; } static AttributeList get_func_attrs(LLVMContext &C) { return AttributeList::get(C, AttributeSet::get(C, makeArrayRef({Thunk})), Attributes(C, {Attribute::NonNull}), None); } static AttributeList get_attrs_noreturn(LLVMContext &C) { return AttributeList::get(C, Attributes(C, {Attribute::NoReturn}), AttributeSet(), None); } static AttributeList get_attrs_sext(LLVMContext &C) { return AttributeList::get(C, AttributeSet(), AttributeSet(), {Attributes(C, {Attribute::SExt})}); } static AttributeList get_attrs_zext(LLVMContext &C) { return AttributeList::get(C, AttributeSet(), AttributeSet(), {Attributes(C, {Attribute::ZExt})}); } // global vars static const auto jlRTLD_DEFAULT_var = new JuliaVariable{ "jl_RTLD_DEFAULT_handle", true, [](LLVMContext &C) { return T_pint8; }, }; #ifdef _OS_WINDOWS_ static const auto jlexe_var = new JuliaVariable{ "jl_exe_handle", true, [](LLVMContext &C) { return T_pint8; }, }; static const auto jldll_var = new JuliaVariable{ "jl_dl_handle", true, [](LLVMContext &C) { return T_pint8; }, }; #endif //_OS_WINDOWS_ static const auto jlstack_chk_guard_var = new JuliaVariable{ "__stack_chk_guard", true, get_pjlvalue, }; static const auto jlgetworld_global = new JuliaVariable{ "jl_world_counter", false, [](LLVMContext &C) { return (Type*)T_size; }, }; static const auto jltls_states_func = new JuliaFunction{ "julia.ptls_states", [](LLVMContext &C) { return FunctionType::get(PointerType::get(T_ppjlvalue, 0), false); }, nullptr, }; // important functions // Symbols are not gc-tracked, but we'll treat them as callee rooted anyway, // because they may come from a gc-rooted location static const auto jlnew_func = new JuliaFunction{ "jl_new_structv", get_func_sig, get_func_attrs, }; static const auto jlsplatnew_func = new JuliaFunction{ "jl_new_structt", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_prjlvalue, T_prjlvalue}, false); }, get_func_attrs, }; static const auto jlthrow_func = new JuliaFunction{ "jl_throw", [](LLVMContext &C) { return FunctionType::get(T_void, {PointerType::get(T_jlvalue, AddressSpace::CalleeRooted)}, false); }, get_attrs_noreturn, }; static const auto jlerror_func = new JuliaFunction{ "jl_error", [](LLVMContext &C) { return FunctionType::get(T_void, {T_pint8}, false); }, get_attrs_noreturn, }; static const auto jltypeerror_func = new JuliaFunction{ "jl_type_error", [](LLVMContext &C) { return FunctionType::get(T_void, {T_pint8, T_prjlvalue, PointerType::get(T_jlvalue, AddressSpace::CalleeRooted)}, false); }, get_attrs_noreturn, }; static const auto jlundefvarerror_func = new JuliaFunction{ "jl_undefined_var_error", [](LLVMContext &C) { return FunctionType::get(T_void, {PointerType::get(T_jlvalue, AddressSpace::CalleeRooted)}, false); }, get_attrs_noreturn, }; static const auto jlboundserrorv_func = new JuliaFunction{ "jl_bounds_error_ints", [](LLVMContext &C) { return FunctionType::get(T_void, {PointerType::get(T_jlvalue, AddressSpace::CalleeRooted), T_psize, T_size}, false); }, get_attrs_noreturn, }; static const auto jlboundserror_func = new JuliaFunction{ "jl_bounds_error_int", [](LLVMContext &C) { return FunctionType::get(T_void, {PointerType::get(T_jlvalue, AddressSpace::CalleeRooted), T_size}, false); }, get_attrs_noreturn, }; static const auto jlvboundserror_func = new JuliaFunction{ "jl_bounds_error_tuple_int", [](LLVMContext &C) { return FunctionType::get(T_void, {T_pprjlvalue, T_size, T_size}, false); }, get_attrs_noreturn, }; static const auto jluboundserror_func = new JuliaFunction{ "jl_bounds_error_unboxed_int", [](LLVMContext &C) { return FunctionType::get(T_void, {PointerType::get(T_int8, AddressSpace::Derived), T_pjlvalue, T_size}, false); }, get_attrs_noreturn, }; static const auto jlcheckassign_func = new JuliaFunction{ "jl_checked_assignment", [](LLVMContext &C) { return FunctionType::get(T_void, {T_pjlvalue, PointerType::get(T_jlvalue, AddressSpace::CalleeRooted)}, false); }, nullptr, }; static const auto jldeclareconst_func = new JuliaFunction{ "jl_declare_constant", [](LLVMContext &C) { return FunctionType::get(T_void, {T_pjlvalue}, false); }, nullptr, }; static const auto jlgetbindingorerror_func = new JuliaFunction{ "jl_get_binding_or_error", [](LLVMContext &C) { return FunctionType::get(T_pjlvalue, {T_pjlvalue, T_pjlvalue}, false); }, nullptr, }; static const auto jlboundp_func = new JuliaFunction{ "jl_boundp", [](LLVMContext &C) { return FunctionType::get(T_int32, {T_pjlvalue, T_pjlvalue}, false); }, nullptr, }; static const auto jltopeval_func = new JuliaFunction{ "jl_toplevel_eval", [](LLVMContext &C) { return FunctionType::get(T_pjlvalue, {T_pjlvalue, T_pjlvalue}, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet(), Attributes(C, {Attribute::NonNull}), None); }, }; static const auto jlcopyast_func = new JuliaFunction{ "jl_copy_ast", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_prjlvalue}, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet(), Attributes(C, {Attribute::NonNull}), None); }, }; //static const auto jlnsvec_func = new JuliaFunction{ // "jl_svec", // [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, // {T_size}, true); }, // [](LLVMContext &C) { return AttributeList::get(C, // AttributeSet(), // Attributes(C, {Attribute::NonNull}), // None); }, //}; static const auto jlapplygeneric_func = new JuliaFunction{ "jl_apply_generic", get_func_sig, get_func_attrs, }; static const auto jlinvoke_func = new JuliaFunction{ "jl_invoke", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_prjlvalue, T_pprjlvalue, T_uint32, T_prjlvalue}, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet(), Attributes(C, {Attribute::NonNull}), {AttributeSet(), Attributes(C, {Attribute::ReadOnly, Attribute::NoCapture})}); }, }; static const auto jlmethod_func = new JuliaFunction{ "jl_method_def", [](LLVMContext &C) { return FunctionType::get(T_void, {T_prjlvalue, T_prjlvalue, T_pjlvalue}, false); }, nullptr, }; static const auto jlgenericfunction_func = new JuliaFunction{ "jl_generic_function_def", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_pjlvalue, T_pjlvalue, T_pprjlvalue, T_pjlvalue, T_pjlvalue}, false); }, nullptr, }; static const auto jlenter_func = new JuliaFunction{ "jl_enter_handler", [](LLVMContext &C) { return FunctionType::get(T_void, {T_pint8}, false); }, nullptr, }; static const auto jl_current_exception_func = new JuliaFunction{ "jl_current_exception", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, false); }, nullptr, }; static const auto jlleave_func = new JuliaFunction{ "jl_pop_handler", [](LLVMContext &C) { return FunctionType::get(T_void, {T_int32}, false); }, nullptr, }; static const auto jl_restore_excstack_func = new JuliaFunction{ "jl_restore_excstack", [](LLVMContext &C) { return FunctionType::get(T_void, {T_size}, false); }, nullptr, }; static const auto jl_excstack_state_func = new JuliaFunction{ "jl_excstack_state", [](LLVMContext &C) { return FunctionType::get(T_size, false); }, nullptr, }; static const auto jlegal_func = new JuliaFunction{ "jl_egal", [](LLVMContext &C) { Type *T = PointerType::get(T_jlvalue, AddressSpace::CalleeRooted); return FunctionType::get(T_int32, {T, T}, false); }, nullptr, }; static const auto jl_alloc_obj_func = new JuliaFunction{ "julia.gc_alloc_obj", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_pint8, T_size, T_prjlvalue}, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet::get(C, makeArrayRef({Attribute::getWithAllocSizeArgs(C, 1, None)})), // returns %1 bytes Attributes(C, {Attribute::NoAlias, Attribute::NonNull}), None); }, }; static const auto jl_newbits_func = new JuliaFunction{ "jl_new_bits", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_prjlvalue, T_pint8}, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet(), Attributes(C, {Attribute::NoAlias, Attribute::NonNull}), None); }, }; static const auto jl_typeof_func = new JuliaFunction{ "julia.typeof", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_prjlvalue}, false); }, [](LLVMContext &C) { return AttributeList::get(C, Attributes(C, {Attribute::ReadOnly, Attribute::NoUnwind, Attribute::ArgMemOnly, Attribute::NoRecurse}), Attributes(C, {Attribute::NonNull}), None); }, }; static const auto jl_loopinfo_marker_func = new JuliaFunction{ "julia.loopinfo_marker", [](LLVMContext &C) { return FunctionType::get(T_void, false); }, [](LLVMContext &C) { return AttributeList::get(C, Attributes(C, {Attribute::ReadOnly, Attribute::NoRecurse, Attribute::InaccessibleMemOnly}), AttributeSet(), None); }, }; static const auto jl_write_barrier_func = new JuliaFunction{ "julia.write_barrier", [](LLVMContext &C) { return FunctionType::get(T_void, {T_prjlvalue}, true); }, [](LLVMContext &C) { return AttributeList::get(C, Attributes(C, {Attribute::NoUnwind, Attribute::NoRecurse, Attribute::InaccessibleMemOnly}), AttributeSet(), None); }, }; static const auto jlisa_func = new JuliaFunction{ "jl_isa", [](LLVMContext &C) { return FunctionType::get(T_int32, {T_prjlvalue, T_prjlvalue}, false); }, nullptr, }; static const auto jlsubtype_func = new JuliaFunction{ "jl_subtype", [](LLVMContext &C) { return FunctionType::get(T_int32, {T_prjlvalue, T_prjlvalue}, false); }, nullptr, }; static const auto jlapplytype_func = new JuliaFunction{ "jl_instantiate_type_in_env", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_pjlvalue, T_pjlvalue, T_pprjlvalue}, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet(), Attributes(C, {Attribute::NonNull}), None); }, }; static const auto jl_object_id__func = new JuliaFunction{ "jl_object_id_", [](LLVMContext &C) { return FunctionType::get(T_size, {T_prjlvalue, PointerType::get(T_int8, AddressSpace::Derived)}, false); }, nullptr, }; static const auto setjmp_func = new JuliaFunction{ jl_setjmp_name, [](LLVMContext &C) { return FunctionType::get(T_int32, {T_pint8, #ifndef _OS_WINDOWS_ T_int32, #endif }, false); }, [](LLVMContext &C) { return AttributeList::get(C, Attributes(C, {Attribute::ReturnsTwice}), AttributeSet(), None); }, }; static const auto memcmp_func = new JuliaFunction{ "memcmp", [](LLVMContext &C) { return FunctionType::get(T_int32, {T_pint8, T_pint8, T_size}, false); }, [](LLVMContext &C) { return AttributeList::get(C, Attributes(C, {Attribute::ReadOnly, Attribute::NoUnwind, Attribute::ArgMemOnly}), AttributeSet(), None); }, // TODO: inferLibFuncAttributes(*memcmp_func, TLI); }; static const auto jldlsym_func = new JuliaFunction{ "jl_load_and_lookup", [](LLVMContext &C) { return FunctionType::get(T_pvoidfunc, {T_pint8, T_pint8, PointerType::get(T_pint8, 0)}, false); }, nullptr, }; static const auto jltypeassert_func = new JuliaFunction{ "jl_typeassert", [](LLVMContext &C) { return FunctionType::get(T_void, {T_prjlvalue, T_prjlvalue}, false); }, nullptr, }; static const auto jlgetnthfieldchecked_func = new JuliaFunction{ "jl_get_nth_field_checked", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_prjlvalue, T_size}, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet(), Attributes(C, {Attribute::NonNull}), None); }, }; static const auto jlgetcfunctiontrampoline_func = new JuliaFunction{ "jl_get_cfunction_trampoline", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, { T_prjlvalue, // f (object) T_pjlvalue, // result T_pint8, // cache T_pjlvalue, // fill FunctionType::get(T_pint8, { T_pint8, T_ppjlvalue }, false)->getPointerTo(), // trampoline T_pjlvalue, // env T_pprjlvalue, // vals }, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet(), Attributes(C, {Attribute::NonNull}), None); }, }; static const auto diff_gc_total_bytes_func = new JuliaFunction{ "jl_gc_diff_total_bytes", [](LLVMContext &C) { return FunctionType::get(T_int64, false); }, nullptr, }; static const auto sync_gc_total_bytes_func = new JuliaFunction{ "jl_gc_sync_total_bytes", [](LLVMContext &C) { return FunctionType::get(T_int64, {T_int64}, false); }, nullptr, }; static const auto jlarray_data_owner_func = new JuliaFunction{ "jl_array_data_owner", [](LLVMContext &C) { return FunctionType::get(T_prjlvalue, {T_prjlvalue}, false); }, [](LLVMContext &C) { return AttributeList::get(C, Attributes(C, {Attribute::ReadOnly, Attribute::NoUnwind}), Attributes(C, {Attribute::NonNull}), None); }, }; #define BOX_FUNC(ct,rt,at,attrs) \ static const auto box_##ct##_func = new JuliaFunction{ \ "jl_box_"#ct, \ [](LLVMContext &C) { return FunctionType::get(rt, \ {at}, false); }, \ attrs, \ } BOX_FUNC(int8, T_pjlvalue, T_int8, get_attrs_sext); BOX_FUNC(uint8, T_pjlvalue, T_int8, get_attrs_zext); BOX_FUNC(int16, T_prjlvalue, T_int16, get_attrs_sext); BOX_FUNC(uint16, T_prjlvalue, T_int16, get_attrs_zext); BOX_FUNC(int32, T_prjlvalue, T_int32, get_attrs_sext); BOX_FUNC(uint32, T_prjlvalue, T_int32, get_attrs_zext); BOX_FUNC(int64, T_prjlvalue, T_int64, get_attrs_sext); BOX_FUNC(uint64, T_prjlvalue, T_int64, get_attrs_zext); BOX_FUNC(char, T_prjlvalue, T_char, get_attrs_zext); BOX_FUNC(float32, T_prjlvalue, T_float32, nullptr); BOX_FUNC(float64, T_prjlvalue, T_float64, nullptr); BOX_FUNC(ssavalue, T_prjlvalue, T_size, nullptr); #undef BOX_FUNC // placeholder functions static const auto gcroot_flush_func = new JuliaFunction{ "julia.gcroot_flush", [](LLVMContext &C) { return FunctionType::get(T_void, false); }, nullptr, }; static const auto gc_preserve_begin_func = new JuliaFunction{ "llvm.julia.gc_preserve_begin", [](LLVMContext &C) { return FunctionType::get(Type::getTokenTy(C), true); }, nullptr, }; static const auto gc_preserve_end_func = new JuliaFunction { "llvm.julia.gc_preserve_end", [](LLVMContext &C) { return FunctionType::get(T_void, {Type::getTokenTy(C)}, false); }, nullptr, }; static const auto except_enter_func = new JuliaFunction{ "julia.except_enter", [](LLVMContext &C) { return FunctionType::get(T_int32, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet::get(C, makeArrayRef({Attribute::get(C, Attribute::ReturnsTwice)})), AttributeSet(), None); }, }; static const auto pointer_from_objref_func = new JuliaFunction{ "julia.pointer_from_objref", [](LLVMContext &C) { return FunctionType::get(T_pjlvalue, {PointerType::get(T_jlvalue, AddressSpace::Derived)}, false); }, [](LLVMContext &C) { return AttributeList::get(C, AttributeSet::get(C, makeArrayRef({Attribute::get(C, Attribute::ReadNone), Attribute::get(C, Attribute::NoUnwind)})), AttributeSet(), None); }, }; static const auto jltuple_func = new JuliaFunction{"jl_f_tuple", get_func_sig, get_func_attrs}; static const auto jlgetfield_func = new JuliaFunction{"jl_f_getfield", get_func_sig, get_func_attrs}; static const std::map<jl_fptr_args_t, JuliaFunction*> builtin_func_map = { { &jl_f_is, new JuliaFunction{"jl_f_is", get_func_sig, get_func_attrs} }, { &jl_f_typeof, new JuliaFunction{"jl_f_typeof", get_func_sig, get_func_attrs} }, { &jl_f_sizeof, new JuliaFunction{"jl_f_sizeof", get_func_sig, get_func_attrs} }, { &jl_f_issubtype, new JuliaFunction{"jl_f_issubtype", get_func_sig, get_func_attrs} }, { &jl_f_isa, new JuliaFunction{"jl_f_isa", get_func_sig, get_func_attrs} }, { &jl_f_typeassert, new JuliaFunction{"jl_f_typeassert", get_func_sig, get_func_attrs} }, { &jl_f_ifelse, new JuliaFunction{"jl_f_ifelse", get_func_sig, get_func_attrs} }, { &jl_f__apply, new JuliaFunction{"jl_f__apply", get_func_sig, get_func_attrs} }, { &jl_f__apply_iterate, new JuliaFunction{"jl_f__apply_iterate", get_func_sig, get_func_attrs} }, { &jl_f__apply_pure, new JuliaFunction{"jl_f__apply_pure", get_func_sig, get_func_attrs} }, { &jl_f__apply_latest, new JuliaFunction{"jl_f__apply_latest", get_func_sig, get_func_attrs} }, { &jl_f__apply_in_world, new JuliaFunction{"jl_f__apply_in_world", get_func_sig, get_func_attrs} }, { &jl_f_throw, new JuliaFunction{"jl_f_throw", get_func_sig, get_func_attrs} }, { &jl_f_tuple, jltuple_func }, { &jl_f_svec, new JuliaFunction{"jl_f_svec", get_func_sig, get_func_attrs} }, { &jl_f_applicable, new JuliaFunction{"jl_f_applicable", get_func_sig, get_func_attrs} }, { &jl_f_invoke, new JuliaFunction{"jl_f_invoke", get_func_sig, get_func_attrs} }, { &jl_f_invoke_kwsorter, new JuliaFunction{"jl_f_invoke_kwsorter", get_func_sig, get_func_attrs} }, { &jl_f_isdefined, new JuliaFunction{"jl_f_isdefined", get_func_sig, get_func_attrs} }, { &jl_f_getfield, jlgetfield_func }, { &jl_f_setfield, new JuliaFunction{"jl_f_setfield", get_func_sig, get_func_attrs} }, { &jl_f_fieldtype, new JuliaFunction{"jl_f_fieldtype", get_func_sig, get_func_attrs} }, { &jl_f_nfields, new JuliaFunction{"jl_f_nfields", get_func_sig, get_func_attrs} }, { &jl_f__expr, new JuliaFunction{"jl_f__expr", get_func_sig, get_func_attrs} }, { &jl_f__typevar, new JuliaFunction{"jl_f__typevar", get_func_sig, get_func_attrs} }, { &jl_f_arrayref, new JuliaFunction{"jl_f_arrayref", get_func_sig, get_func_attrs} }, { &jl_f_const_arrayref, new JuliaFunction{"jl_f_const_arrayref", get_func_sig, get_func_attrs} }, { &jl_f_arrayset, new JuliaFunction{"jl_f_arrayset", get_func_sig, get_func_attrs} }, { &jl_f_arraysize, new JuliaFunction{"jl_f_arraysize", get_func_sig, get_func_attrs} }, { &jl_f_apply_type, new JuliaFunction{"jl_f_apply_type", get_func_sig, get_func_attrs} }, }; static int globalUnique = 0; // --- code generation --- extern "C" { int jl_default_debug_info_kind = (int) DICompileUnit::DebugEmissionKind::FullDebug; jl_cgparams_t jl_default_cgparams = {1, 1, 1, 0, #ifdef _OS_WINDOWS_ 0, #else 1, #endif jl_default_debug_info_kind, NULL, NULL, NULL, NULL, NULL, jl_rettype_inferred, NULL }; } template<typename T> static void add_return_attr(T *f, Attribute::AttrKind Kind) { f->addAttribute(AttributeList::ReturnIndex, Kind); } static MDNode *best_tbaa(jl_value_t *jt) { jt = jl_unwrap_unionall(jt); if (!jl_is_datatype(jt)) return tbaa_value; if (jl_is_abstracttype(jt)) return tbaa_value; // If we're here, we know all subtypes are (im)mutable, even if we // don't know what the exact type is return jl_is_mutable(jt) ? tbaa_mutab : tbaa_immut; } // tracks whether codegen is currently able to simply stack-allocate this type // note that this includes jl_isbits, although codegen should work regardless static bool jl_is_concrete_immutable(jl_value_t* t) { return jl_is_immutable_datatype(t) && ((jl_datatype_t*)t)->layout; } static bool jl_is_pointerfree(jl_value_t* t) { if (!jl_is_immutable_datatype(t)) return 0; const jl_datatype_layout_t *layout = ((jl_datatype_t*)t)->layout; return layout && layout->npointers == 0; } // these queries are usually related, but we split them out here // for convenience and clarity (and because it changes the calling convention) static bool deserves_stack(jl_value_t* t, bool pointerfree=false) { if (!jl_is_concrete_immutable(t)) return false; return ((jl_datatype_t*)t)->isinlinealloc; } static bool deserves_argbox(jl_value_t* t) { return !deserves_stack(t); } static bool deserves_retbox(jl_value_t* t) { return deserves_argbox(t); } static bool deserves_sret(jl_value_t *dt, Type *T) { assert(jl_is_datatype(dt)); return (size_t)jl_datatype_size(dt) > sizeof(void*) && !T->isFloatingPointTy() && !T->isVectorTy(); } // metadata tracking for a llvm Value* during codegen struct jl_cgval_t { Value *V; // may be of type T* or T, or set to NULL if ghost (or if the value has not been initialized yet, for a variable definition) // For unions, we may need to keep a reference to the boxed part individually. // If this is non-NULL, then, at runtime, we satisfy the invariant that (for the corresponding // runtime values) if `(TIndex | 0x80) != 0`, then `Vboxed == V` (by value). // For convenience, we also set this value of isboxed values, in which case // it is equal (at compile time) to V. Value *Vboxed; Value *TIndex; // if `V` is an unboxed (tagged) Union described by `typ`, this gives the DataType index (1-based, small int) as an i8 jl_value_t *constant; // constant value (rooted in linfo.def.roots) jl_value_t *typ; // the original type of V, never NULL bool isboxed; // whether this value is a jl_value_t* allocated on the heap with the right type tag bool isghost; // whether this value is "ghost" MDNode *tbaa; // The related tbaa node. Non-NULL iff this holds an address. bool ispointer() const { // whether this value is compatible with `data_pointer` return tbaa != nullptr; } jl_cgval_t(Value *V, Value *gcroot, bool isboxed, jl_value_t *typ, Value *tindex) : // general constructor (with pointer type auto-detect) V(V), // V is allowed to be NULL in a jl_varinfo_t context, but not during codegen contexts Vboxed(isboxed ? V : nullptr), TIndex(tindex), constant(NULL), typ(typ), isboxed(isboxed), isghost(false), tbaa(isboxed ? best_tbaa(typ) : nullptr) { assert(gcroot == nullptr); assert(!(isboxed && TIndex != NULL)); assert(TIndex == NULL || TIndex->getType() == T_int8); } explicit jl_cgval_t(jl_value_t *typ) : // ghost value constructor // mark explicit to avoid being used implicitly for conversion from NULL (use jl_cgval_t() instead) V(NULL), Vboxed(NULL), TIndex(NULL), constant(((jl_datatype_t*)typ)->instance), typ(typ), isboxed(false), isghost(true), tbaa(nullptr) { assert(jl_is_datatype(typ)); assert(constant); } jl_cgval_t(const jl_cgval_t &v, jl_value_t *typ, Value *tindex) : // copy constructor with new type V(v.V), Vboxed(v.Vboxed), TIndex(tindex), constant(v.constant), typ(typ), isboxed(v.isboxed), isghost(v.isghost), tbaa(v.tbaa) { // this constructor expects we had a badly or equivalently typed version // make sure we aren't discarding the actual type information if (v.TIndex) { assert((TIndex == NULL) == jl_is_concrete_type(typ)); } else { assert(isboxed || v.typ == typ || tindex); } } jl_cgval_t() : // undef / unreachable / default constructor V(UndefValue::get(T_void)), Vboxed(NULL), TIndex(NULL), constant(NULL), typ(jl_bottom_type), isboxed(false), isghost(true), tbaa(nullptr) { } }; // per-local-variable information struct jl_varinfo_t { Instruction *boxroot; // an address, if the var might be in a jl_value_t** stack slot (marked tbaa_const, if appropriate) jl_cgval_t value; // a stack slot or constant value Value *pTIndex; // i8* stack slot for the value.TIndex tag describing `value.V` DILocalVariable *dinfo; // if the variable might be used undefined and is not boxed // this i1 flag is true when it is defined Value *defFlag; bool isSA; // whether all stores dominate all uses bool isVolatile; bool isArgument; bool usedUndef; bool used; jl_varinfo_t() : boxroot(NULL), value(jl_cgval_t()), pTIndex(NULL), dinfo(NULL), defFlag(NULL), isSA(false), isVolatile(false), isArgument(false), usedUndef(false), used(false) { } }; // information about the context of a piece of code: its enclosing // function and module, and visible local variables and labels. class jl_codectx_t { public: IRBuilder<> builder; jl_codegen_params_t &emission_context; jl_codegen_call_targets_t &call_targets; std::map<void*, GlobalVariable*> &global_targets; Function *f = NULL; // local var info. globals are not in here. std::vector<jl_varinfo_t> slots; std::map<int, jl_varinfo_t> phic_slots; std::vector<jl_cgval_t> SAvalues; std::vector<std::tuple<jl_cgval_t, BasicBlock *, AllocaInst *, PHINode *, jl_value_t *>> PhiNodes; std::vector<bool> ssavalue_assigned; jl_module_t *module = NULL; jl_method_instance_t *linfo = NULL; jl_value_t *rettype = NULL; jl_code_info_t *source = NULL; jl_array_t *code = NULL; size_t world = 0; jl_array_t *roots = NULL; const char *name = NULL; StringRef file{}; ssize_t *line = NULL; Value *spvals_ptr = NULL; Value *argArray = NULL; Value *argCount = NULL; MDNode *aliasscope = NULL; std::string funcName; int vaSlot = -1; // name of vararg argument int nReqArgs = 0; int nargs = 0; int nvargs = -1; CallInst *ptlsStates = NULL; Value *signalPage = NULL; Value *world_age_field = NULL; bool debug_enabled = false; bool use_cache = false; const jl_cgparams_t *params = NULL; jl_codectx_t(LLVMContext &llvmctx, jl_codegen_params_t &params) : builder(llvmctx), emission_context(params), call_targets(params.workqueue), global_targets(params.globals), world(params.world), use_cache(params.cache), params(params.params) { } ~jl_codectx_t() { assert(this->roots == NULL); } }; GlobalVariable *JuliaVariable::realize(jl_codectx_t &ctx) { return realize(jl_Module); } static Type *julia_type_to_llvm(jl_codectx_t &ctx, jl_value_t *jt, bool *isboxed = NULL); static jl_returninfo_t get_specsig_function(jl_codectx_t &ctx, Module *M, StringRef name, jl_value_t *sig, jl_value_t *jlrettype); static jl_cgval_t emit_expr(jl_codectx_t &ctx, jl_value_t *expr, ssize_t ssaval = -1); static Value *global_binding_pointer(jl_codectx_t &ctx, jl_module_t *m, jl_sym_t *s, jl_binding_t **pbnd, bool assign); static jl_cgval_t emit_checked_var(jl_codectx_t &ctx, Value *bp, jl_sym_t *name, bool isvol, MDNode *tbaa); static jl_cgval_t emit_sparam(jl_codectx_t &ctx, size_t i); static Value *emit_condition(jl_codectx_t &ctx, const jl_cgval_t &condV, const std::string &msg); static void allocate_gc_frame(jl_codectx_t &ctx, BasicBlock *b0); static void CreateTrap(IRBuilder<> &irbuilder); static CallInst *emit_jlcall(jl_codectx_t &ctx, Function *theFptr, Value *theF, jl_cgval_t *args, size_t nargs, CallingConv::ID cc); static CallInst *emit_jlcall(jl_codectx_t &ctx, JuliaFunction *theFptr, Value *theF, jl_cgval_t *args, size_t nargs, CallingConv::ID cc); static Value *literal_pointer_val(jl_codectx_t &ctx, jl_value_t *p); static GlobalVariable *prepare_global_in(Module *M, GlobalVariable *G); static Instruction *tbaa_decorate(MDNode *md, Instruction *load_or_store); static GlobalVariable *prepare_global_in(Module *M, JuliaVariable *G) { return G->realize(M); } static Function *prepare_call_in(Module *M, JuliaFunction *G) { return G->realize(M); } static inline GlobalVariable *prepare_global_in(Module *M, GlobalVariable *G) { if (G->getParent() == M) return G; GlobalValue *local = M->getNamedValue(G->getName()); if (!local) { // Copy the GlobalVariable, but without the initializer, so it becomes a declaration GlobalVariable *proto = new GlobalVariable(*M, G->getType()->getElementType(), G->isConstant(), GlobalVariable::ExternalLinkage, nullptr, G->getName(), nullptr, G->getThreadLocalMode()); proto->copyAttributesFrom(G); // DLLImport only needs to be set for the shadow module // it just gets annoying in the JIT proto->setDLLStorageClass(GlobalValue::DefaultStorageClass); return proto; } return cast<GlobalVariable>(local); } // --- convenience functions for tagging llvm values with julia types --- static GlobalVariable *get_pointer_to_constant(jl_codegen_params_t &emission_context, Constant *val, StringRef name, Module &M) { GlobalVariable *&gv = emission_context.mergedConstants[val]; StringRef localname; std::string ssno; if (gv == nullptr) { raw_string_ostream(ssno) << name << emission_context.mergedConstants.size(); localname = StringRef(ssno); } else { localname = gv->getName(); if (gv->getParent() != &M) gv = cast_or_null<GlobalVariable>(M.getNamedValue(localname)); } if (gv == nullptr) { gv = new GlobalVariable( M, val->getType(), true, GlobalVariable::PrivateLinkage, val, localname); gv->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); } assert(localname == gv->getName()); assert(val == gv->getInitializer()); return gv; } static AllocaInst *emit_static_alloca(jl_codectx_t &ctx, Type *lty) { return new AllocaInst(lty, 0, "", /*InsertBefore=*/ctx.ptlsStates); } static void undef_derived_strct(IRBuilder<> &irbuilder, Value *ptr, jl_datatype_t *sty, MDNode *tbaa) { assert(ptr->getType()->getPointerAddressSpace() != AddressSpace::Tracked); size_t i, np = sty->layout->npointers; if (np == 0) return; ptr = irbuilder.CreateBitCast(ptr, T_prjlvalue->getPointerTo(ptr->getType()->getPointerAddressSpace())); Value *V_null = ConstantPointerNull::get(cast<PointerType>(T_prjlvalue)); for (i = 0; i < np; i++) { Value *fld = irbuilder.CreateConstInBoundsGEP1_32(T_prjlvalue, ptr, jl_ptr_offset(sty, i)); tbaa_decorate(tbaa, irbuilder.CreateStore(V_null, fld)); } } static inline jl_cgval_t ghostValue(jl_value_t *typ) { if (typ == jl_bottom_type) return jl_cgval_t(); // Undef{} if (typ == (jl_value_t*)jl_typeofbottom_type) { // normalize TypeofBottom to Type{Union{}} typ = (jl_value_t*)jl_typeofbottom_type->super; } if (jl_is_type_type(typ)) { // replace T::Type{T} with T, by assuming that T must be a leaftype of some sort jl_cgval_t constant(NULL, NULL, true, typ, NULL); constant.constant = jl_tparam0(typ); return constant; } return jl_cgval_t(typ); } static inline jl_cgval_t ghostValue(jl_datatype_t *typ) { return ghostValue((jl_value_t*)typ); } static inline jl_cgval_t mark_julia_const(jl_value_t *jv) { jl_value_t *typ; if (jl_is_type(jv)) { typ = (jl_value_t*)jl_wrap_Type(jv); // TODO: gc-root this? } else { typ = jl_typeof(jv); if (jl_is_datatype_singleton((jl_datatype_t*)typ)) return ghostValue(typ); } jl_cgval_t constant(NULL, NULL, true, typ, NULL); constant.constant = jv; return constant; } static inline jl_cgval_t mark_julia_slot(Value *v, jl_value_t *typ, Value *tindex, MDNode *tbaa) { // this enables lazy-copying of immutable values and stack or argument slots assert(tbaa); jl_cgval_t tagval(v, NULL, false, typ, tindex); tagval.tbaa = tbaa; return tagval; } static bool valid_as_globalinit(const Value *v) { if (isa<ConstantExpr>(v)) { // llvm can't handle all the things that could be inside a ConstantExpr // (such as addrspacecast), and we don't really mind losing this optimization return false; } if (const auto *CC = dyn_cast<ConstantAggregate>(v)) { for (const Value *elem : CC->operand_values()) if (!valid_as_globalinit(elem)) return false; } return isa<Constant>(v); } static inline jl_cgval_t value_to_pointer(jl_codectx_t &ctx, Value *v, jl_value_t *typ, Value *tindex) { Value *loc; if (valid_as_globalinit(v)) { // llvm can't handle all the things that could be inside a ConstantExpr loc = get_pointer_to_constant(ctx.emission_context, cast<Constant>(v), "_j_const", *jl_Module); } else { loc = emit_static_alloca(ctx, v->getType()); ctx.builder.CreateStore(v, loc); } return mark_julia_slot(loc, typ, tindex, tbaa_stack); } static inline jl_cgval_t value_to_pointer(jl_codectx_t &ctx, const jl_cgval_t &v) { if (v.ispointer()) return v; return value_to_pointer(ctx, v.V, v.typ, v.TIndex); } static inline jl_cgval_t mark_julia_type(jl_codectx_t &ctx, Value *v, bool isboxed, jl_value_t *typ) { if (jl_is_datatype(typ) && jl_is_datatype_singleton((jl_datatype_t*)typ)) { // no need to explicitly load/store a constant/ghost value return ghostValue(typ); } if (jl_is_type_type(typ)) { jl_value_t *tp0 = jl_tparam0(typ); if (jl_is_concrete_type(tp0) || tp0 == jl_bottom_type) { // replace T::Type{T} with T return ghostValue(typ); } } Type *T = julia_type_to_llvm(ctx, typ); if (type_is_ghost(T)) { return ghostValue(typ); } if (v && !isboxed && v->getType()->isAggregateType() && !jl_is_vecelement_type(typ) && CountTrackedPointers(v->getType()).count == 0) { // eagerly put this back onto the stack // llvm mem2reg pass will remove this if unneeded return value_to_pointer(ctx, v, typ, NULL); } return jl_cgval_t(v, NULL, isboxed, typ, NULL); } static inline jl_cgval_t mark_julia_type(jl_codectx_t &ctx, Value *v, bool isboxed, jl_datatype_t *typ) { return mark_julia_type(ctx, v, isboxed, (jl_value_t*)typ); } // see if it might be profitable (and cheap) to change the type of v to typ static inline jl_cgval_t update_julia_type(jl_codectx_t &ctx, const jl_cgval_t &v, jl_value_t *typ) { if (v.typ == typ || v.typ == jl_bottom_type || v.constant || typ == (jl_value_t*)jl_any_type || jl_egal(v.typ, typ)) return v; // fast-path if (jl_is_concrete_type(v.typ) && !jl_is_kind(v.typ)) { if (jl_is_concrete_type(typ) && !jl_is_kind(typ)) { // type mismatch: changing from one leaftype to another CreateTrap(ctx.builder); return jl_cgval_t(); } return v; // doesn't improve type info } if (v.TIndex) { jl_value_t *utyp = jl_unwrap_unionall(typ); if (jl_is_datatype(utyp)) { bool alwaysboxed; if (jl_is_concrete_type(utyp)) alwaysboxed = !jl_is_pointerfree(utyp); else alwaysboxed = !((jl_datatype_t*)utyp)->abstract && ((jl_datatype_t*)utyp)->mutabl; if (alwaysboxed) { // discovered that this union-split type must actually be isboxed if (v.Vboxed) { return jl_cgval_t(v.Vboxed, nullptr, true, typ, NULL); } else { // type mismatch (there weren't any boxed values in the union) CreateTrap(ctx.builder); return jl_cgval_t(); } } } if (!jl_is_concrete_type(typ)) return v; // not generally worth trying to change type info (which would require recomputing tindex) } Type *T = julia_type_to_llvm(ctx, typ); if (type_is_ghost(T)) return ghostValue(typ); return jl_cgval_t(v, typ, NULL); } static jl_cgval_t convert_julia_type(jl_codectx_t &ctx, const jl_cgval_t &v, jl_value_t *typ); // --- allocating local variables --- static jl_sym_t *slot_symbol(jl_codectx_t &ctx, int s) { return (jl_sym_t*)jl_array_ptr_ref(ctx.source->slotnames, s); } static void store_def_flag(jl_codectx_t &ctx, const jl_varinfo_t &vi, bool val) { assert((!vi.boxroot || vi.pTIndex) && "undef check is null pointer for boxed things"); assert(vi.usedUndef && vi.defFlag && "undef flag codegen corrupted"); ctx.builder.CreateStore(ConstantInt::get(T_int1, val), vi.defFlag, vi.isVolatile); } static void alloc_def_flag(jl_codectx_t &ctx, jl_varinfo_t& vi) { assert((!vi.boxroot || vi.pTIndex) && "undef check is null pointer for boxed things"); if (vi.usedUndef) { vi.defFlag = emit_static_alloca(ctx, T_int1); store_def_flag(ctx, vi, false); } } // --- utilities --- static void CreateTrap(IRBuilder<> &irbuilder) { Function *f = irbuilder.GetInsertBlock()->getParent(); Function *trap_func = Intrinsic::getDeclaration( f->getParent(), Intrinsic::trap); irbuilder.CreateCall(trap_func); irbuilder.CreateUnreachable(); BasicBlock *newBB = BasicBlock::Create(irbuilder.getContext(), "after_noret", f); irbuilder.SetInsertPoint(newBB); } #if 0 // this code is likely useful, but currently unused #ifndef JL_NDEBUG static void CreateConditionalAbort(IRBuilder<> &irbuilder, Value *test) { Function *f = irbuilder.GetInsertBlock()->getParent(); BasicBlock *abortBB = BasicBlock::Create(jl_LLVMContext, "debug_abort", f); BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_abort", f); irbuilder.CreateCondBr(test, abortBB, postBB); irbuilder.SetInsertPoint(abortBB); Function *trap_func = Intrinsic::getDeclaration( f->getParent(), Intrinsic::trap); irbuilder.CreateCall(trap_func); irbuilder.CreateUnreachable(); irbuilder.SetInsertPoint(postBB); } #endif #endif #include "cgutils.cpp" static jl_cgval_t convert_julia_type_union(jl_codectx_t &ctx, const jl_cgval_t &v, jl_value_t *typ) { // previous value was a split union, compute new index, or box Value *new_tindex = ConstantInt::get(T_int8, 0x80); SmallBitVector skip_box(1, true); Value *tindex = ctx.builder.CreateAnd(v.TIndex, ConstantInt::get(T_int8, 0x7f)); if (jl_is_uniontype(typ)) { // compute the TIndex mapping from v.typ -> typ unsigned counter = 0; for_each_uniontype_small( // for each old union-split value [&](unsigned idx, jl_datatype_t *jt) { unsigned new_idx = get_box_tindex(jt, typ); bool t; if (new_idx) { // found a matching element, // match it against either the unboxed index Value *cmp = ctx.builder.CreateICmpEQ(tindex, ConstantInt::get(T_int8, idx)); new_tindex = ctx.builder.CreateSelect(cmp, ConstantInt::get(T_int8, new_idx), new_tindex); t = true; } else if (!jl_subtype((jl_value_t*)jt, typ)) { // new value doesn't need to be boxed // since it isn't part of the new union t = true; } else { // will actually need to box this element // since it appeared as a leaftype in the original type // but not in the remark type t = false; } skip_box.resize(idx + 1, t); }, v.typ, counter); } // some of the values are still unboxed if (!isa<Constant>(new_tindex)) { Value *wasboxed = NULL; // If the old value was boxed and unknown (type tag 0x80), // it is possible that the tag was actually one of the types // that are now explicitly represented. To find out, we need // to compare typeof(v.Vboxed) (i.e. the type of the unknown // value) against all the types that are now explicitly // selected and select the appropriate one as our new tindex. if (v.Vboxed) { wasboxed = ctx.builder.CreateAnd(v.TIndex, ConstantInt::get(T_int8, 0x80)); new_tindex = ctx.builder.CreateOr(wasboxed, new_tindex); wasboxed = ctx.builder.CreateICmpNE(wasboxed, ConstantInt::get(T_int8, 0)); BasicBlock *currBB = ctx.builder.GetInsertBlock(); // We lazily create a BB for this, once we decide that we // actually need it. Value *union_box_dt = NULL; BasicBlock *union_isaBB = NULL; auto maybe_setup_union_isa = [&]() { if (!union_isaBB) { union_isaBB = BasicBlock::Create(jl_LLVMContext, "union_isa", ctx.f); ctx.builder.SetInsertPoint(union_isaBB); union_box_dt = emit_typeof(ctx, v.Vboxed); } }; // If we don't find a match. The type remains unknown // (0x80). We could use `v.Tindex`, here, since we know // it has to be 0x80, but it seems likely the backend // will like the explicit constant better. Value *union_box_tindex = ConstantInt::get(T_int8, 0x80); unsigned counter = 0; for_each_uniontype_small( // for each new union-split value [&](unsigned idx, jl_datatype_t *jt) { unsigned old_idx = get_box_tindex(jt, v.typ); if (old_idx == 0) { // didn't handle this item before, select its new union index maybe_setup_union_isa(); Value *cmp = ctx.builder.CreateICmpEQ(maybe_decay_untracked(literal_pointer_val(ctx, (jl_value_t*)jt)), union_box_dt); union_box_tindex = ctx.builder.CreateSelect(cmp, ConstantInt::get(T_int8, 0x80 | idx), union_box_tindex); } }, typ, counter); if (union_box_dt) { BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_union_isa", ctx.f); ctx.builder.CreateBr(postBB); ctx.builder.SetInsertPoint(currBB); Value *wasunknown = ctx.builder.CreateICmpEQ(v.TIndex, ConstantInt::get(T_int8, 0x80)); ctx.builder.CreateCondBr(wasunknown, union_isaBB, postBB); ctx.builder.SetInsertPoint(postBB); PHINode *tindex_phi = ctx.builder.CreatePHI(T_int8, 2); tindex_phi->addIncoming(new_tindex, currBB); tindex_phi->addIncoming(union_box_tindex, union_isaBB); new_tindex = tindex_phi; } } if (!skip_box.all()) { // some values weren't unboxed in the new union // box them now (tindex above already selected 0x80 = box for them) Value *boxv = box_union(ctx, v, skip_box); if (v.Vboxed) { // If the value is boxed both before and after, we don't need // to touch it at all. Otherwise we're either transitioning // unboxed->boxed, or leaving an unboxed value in place. Value *isboxed = ctx.builder.CreateICmpNE( ctx.builder.CreateAnd(new_tindex, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)); boxv = ctx.builder.CreateSelect( ctx.builder.CreateAnd(wasboxed, isboxed), v.Vboxed, boxv); } if (v.V == NULL) { // v.V might be NULL if it was all ghost objects before return jl_cgval_t(boxv, NULL, false, typ, new_tindex); } else { Value *isboxv = ctx.builder.CreateIsNotNull(boxv); Value *slotv; MDNode *tbaa; if (v.ispointer()) { slotv = v.V; tbaa = v.tbaa; } else { slotv = emit_static_alloca(ctx, v.V->getType()); ctx.builder.CreateStore(v.V, slotv); tbaa = tbaa_stack; } slotv = ctx.builder.CreateSelect(isboxv, decay_derived(boxv), decay_derived(emit_bitcast(ctx, slotv, boxv->getType()))); jl_cgval_t newv = jl_cgval_t(slotv, NULL, false, typ, new_tindex); newv.Vboxed = boxv; newv.tbaa = tbaa; return newv; } } } else { return jl_cgval_t(boxed(ctx, v), NULL, true, typ, NULL); } return jl_cgval_t(v, typ, new_tindex); } // given a value marked with type `v.typ`, compute the mapping and/or boxing to return a value of type `typ` // TODO: should this set TIndex when trivial (such as 0x80 or concrete types) ? static jl_cgval_t convert_julia_type(jl_codectx_t &ctx, const jl_cgval_t &v, jl_value_t *typ) { if (typ == (jl_value_t*)jl_typeofbottom_type) return ghostValue(typ); // normalize TypeofBottom to Type{Union{}} if (v.typ == typ || v.typ == jl_bottom_type || jl_egal(v.typ, typ)) return v; // fast-path Type *T = julia_type_to_llvm(ctx, typ); if (type_is_ghost(T)) return ghostValue(typ); Value *new_tindex = NULL; if (jl_is_concrete_type(typ)) { if (v.TIndex && !jl_is_pointerfree(typ)) { // discovered that this union-split type must actually be isboxed if (v.Vboxed) { return jl_cgval_t(v.Vboxed, nullptr, true, typ, NULL); } else { // type mismatch: there weren't any boxed values in the union CreateTrap(ctx.builder); return jl_cgval_t(); } } if (jl_is_concrete_type(v.typ) && !jl_is_kind(v.typ)) { if (jl_is_concrete_type(typ) && !jl_is_kind(typ)) { // type mismatch: changing from one leaftype to another CreateTrap(ctx.builder); return jl_cgval_t(); } } } else { bool makeboxed = false; if (v.TIndex) { return convert_julia_type_union(ctx, v, typ); } else if (!v.isboxed && jl_is_uniontype(typ)) { // previous value was unboxed (leaftype), statically compute union tindex assert(jl_is_concrete_type(v.typ)); unsigned new_idx = get_box_tindex((jl_datatype_t*)v.typ, typ); if (new_idx) { new_tindex = ConstantInt::get(T_int8, new_idx); if (v.V && !v.ispointer()) { // TODO: remove this branch once all consumers of v.TIndex understand how to handle a non-ispointer value Value *slotv = emit_static_alloca(ctx, v.V->getType()); ctx.builder.CreateStore(v.V, slotv); jl_cgval_t newv = jl_cgval_t(slotv, NULL, false, typ, new_tindex); newv.tbaa = tbaa_stack; return newv; } } else if (jl_subtype(v.typ, typ)) { makeboxed = true; } else { // unreachable CreateTrap(ctx.builder); return jl_cgval_t(); } } else if (!v.isboxed) { makeboxed = true; } if (makeboxed) { // convert to a simple isboxed value return jl_cgval_t(boxed(ctx, v), NULL, true, typ, NULL); } } return jl_cgval_t(v, typ, new_tindex); } static void jl_setup_module(Module *m, const jl_cgparams_t *params = &jl_default_cgparams) { if (JL_HOOK_TEST(params, module_setup)) { JL_HOOK_CALL(params, module_setup, 1, jl_box_voidpointer(wrap(m))); return; } // Some linkers (*cough* OS X) don't understand DWARF v4, so we use v2 in // imaging mode. The structure of v4 is slightly nicer for debugging JIT // code. if (!m->getModuleFlag("Dwarf Version")) { int dwarf_version = 4; #ifdef _OS_DARWIN_ if (imaging_mode) dwarf_version = 2; #endif m->addModuleFlag(llvm::Module::Warning, "Dwarf Version", dwarf_version); } if (!m->getModuleFlag("Debug Info Version")) m->addModuleFlag(llvm::Module::Error, "Debug Info Version", llvm::DEBUG_METADATA_VERSION); m->setDataLayout(jl_data_layout); m->setTargetTriple(jl_TargetMachine->getTargetTriple().str()); } Module *jl_create_llvm_module(StringRef name) { Module *M = new Module(name, jl_LLVMContext); jl_setup_module(M); return M; } static void jl_init_function(Function *F) { // set any attributes that *must* be set on all functions #if defined(_OS_WINDOWS_) && !defined(_CPU_X86_64_) // tell Win32 to realign the stack to the next 16-byte boundary // upon entry to any function. This achieves compatibility // with both MinGW-GCC (which assumes an 16-byte-aligned stack) and // i686 Windows (which uses a 4-byte-aligned stack) AttrBuilder attr; attr.addStackAlignmentAttr(16); F->addAttributes(AttributeList::FunctionIndex, attr); #endif #if defined(_OS_WINDOWS_) && defined(_CPU_X86_64_) F->setHasUWTable(); // force NeedsWinEH #endif #ifdef JL_DISABLE_FPO #if LLVM_VERSION_MAJOR >= 8 F->addFnAttr("frame-pointer", "all"); #else F->addFnAttr("no-frame-pointer-elim", "true"); #endif #endif } static std::pair<bool, bool> uses_specsig(jl_method_instance_t *lam, jl_value_t *rettype, bool prefer_specsig) { size_t nreq = jl_is_method(lam->def.method) ? lam->def.method->nargs : 0; int va = 0; if (nreq > 0 && lam->def.method->isva) { nreq--; va = 1; } jl_value_t *sig = lam->specTypes; bool needsparams = false; if (jl_is_method(lam->def.method)) { if ((size_t)jl_subtype_env_size(lam->def.method->sig) != jl_svec_len(lam->sparam_vals)) needsparams = true; for (size_t i = 0; i < jl_svec_len(lam->sparam_vals); ++i) { if (jl_is_typevar(jl_svecref(lam->sparam_vals, i))) needsparams = true; } } if (needsparams) return std::make_pair(false, true); if (sig == (jl_value_t*)jl_anytuple_type) return std::make_pair(false, false); if (!jl_is_datatype(sig)) return std::make_pair(false, false); if (jl_nparams(sig) == 0) return std::make_pair(false, false); if (va) { if (jl_is_vararg_type(jl_tparam(sig, jl_nparams(sig) - 1))) return std::make_pair(false, false); } // not invalid, consider if specialized signature is worthwhile if (prefer_specsig) return std::make_pair(true, false); if (!deserves_retbox(rettype) && !jl_is_datatype_singleton((jl_datatype_t*)rettype)) return std::make_pair(true, false); if (jl_is_uniontype(rettype)) { bool allunbox; size_t nbytes, align, min_align; union_alloca_type((jl_uniontype_t*)rettype, allunbox, nbytes, align, min_align); if (nbytes > 0) return std::make_pair(true, false); // some elements of the union could be returned unboxed avoiding allocation } bool allSingleton = true; for (size_t i = 0; i < jl_nparams(sig); i++) { jl_value_t *sigt = jl_tparam(sig, i); bool issing = jl_is_datatype(sigt) && jl_is_datatype_singleton((jl_datatype_t*)sigt); allSingleton &= issing; if (!deserves_argbox(sigt) && !issing) { return std::make_pair(true, false); } } if (allSingleton) return std::make_pair(true, false); return std::make_pair(false, false); // jlcall sig won't require any box allocations } // Logging for code coverage and memory allocation const int logdata_blocksize = 32; // target getting nearby lines in the same general cache area and reducing calls to malloc by chunking typedef uint64_t logdata_block[logdata_blocksize]; typedef StringMap< std::vector<logdata_block*> > logdata_t; static uint64_t *allocLine(std::vector<logdata_block*> &vec, int line) { unsigned block = line / logdata_blocksize; line = line % logdata_blocksize; if (vec.size() <= block) vec.resize(block + 1); if (vec[block] == NULL) { vec[block] = (logdata_block*)calloc(1, sizeof(logdata_block)); } logdata_block &data = *vec[block]; if (data[line] == 0) data[line] = 1; return &data[line]; } static void visitLine(jl_codectx_t &ctx, std::vector<logdata_block*> &vec, int line, Value *addend, const char* name) { uint64_t *ptr = allocLine(vec, line); Value *pv = ConstantExpr::getIntToPtr( ConstantInt::get(T_size, (uintptr_t)ptr), T_pint64); Value *v = ctx.builder.CreateLoad(pv, true, name); v = ctx.builder.CreateAdd(v, addend); ctx.builder.CreateStore(v, pv, true); // volatile, not atomic, so this might be an underestimate, // but it's faster this way } // Code coverage static logdata_t coverageData; static void coverageVisitLine(jl_codectx_t &ctx, StringRef filename, int line) { assert(!imaging_mode); if (filename == "" || filename == "none" || filename == "no file" || filename == "<missing>" || line < 0) return; visitLine(ctx, coverageData[filename], line, ConstantInt::get(T_int64, 1), "lcnt"); } static void coverageAllocLine(StringRef filename, int line) { assert(!imaging_mode); if (filename == "" || filename == "none" || filename == "no file" || filename == "<missing>" || line < 0) return; allocLine(coverageData[filename], line); } // Memory allocation log (malloc_log) static logdata_t mallocData; static void mallocVisitLine(jl_codectx_t &ctx, StringRef filename, int line, Value *sync) { assert(!imaging_mode); if (filename == "" || filename == "none" || filename == "no file" || filename == "<missing>" || line < 0) return; Value *addend = sync ? ctx.builder.CreateCall(prepare_call(sync_gc_total_bytes_func), {sync}) : ctx.builder.CreateCall(prepare_call(diff_gc_total_bytes_func), {}); visitLine(ctx, mallocData[filename], line, addend, "bytecnt"); } // Resets the malloc counts. extern "C" JL_DLLEXPORT void jl_clear_malloc_data(void) { logdata_t::iterator it = mallocData.begin(); for (; it != mallocData.end(); it++) { std::vector<logdata_block*> &bytes = (*it).second; std::vector<logdata_block*>::iterator itb; for (itb = bytes.begin(); itb != bytes.end(); itb++) { if (*itb) { logdata_block &data = **itb; for (int i = 0; i < logdata_blocksize; i++) { if (data[i] > 0) data[i] = 1; } } } } jl_gc_sync_total_bytes(0); } extern "C" int isabspath(const char *in); static void write_log_data(logdata_t &logData, const char *extension) { std::string base = std::string(jl_options.julia_bindir); base = base + "/../share/julia/base/"; logdata_t::iterator it = logData.begin(); for (; it != logData.end(); it++) { std::string filename(it->first()); std::vector<logdata_block*> &values = it->second; if (!values.empty()) { if (!isabspath(filename.c_str())) filename = base + filename; std::ifstream inf(filename.c_str()); if (!inf.is_open()) continue; std::string outfile = filename + extension; std::ofstream outf(outfile.c_str(), std::ofstream::trunc | std::ofstream::out | std::ofstream::binary); if (outf.is_open()) { inf.exceptions(std::ifstream::badbit); outf.exceptions(std::ifstream::failbit | std::ifstream::badbit); char line[1024]; int l = 1; unsigned block = 0; while (!inf.eof()) { inf.getline(line, sizeof(line)); if (inf.fail()) { if (inf.eof()) break; // no content on trailing line // Read through lines longer than sizeof(line) inf.clear(); inf.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } logdata_block *data = NULL; if (block < values.size()) { data = values[block]; } uint64_t value = data ? (*data)[l] : 0; if (++l >= logdata_blocksize) { l = 0; block++; } outf.width(9); if (value == 0) outf << '-'; else outf << (value - 1); outf.width(0); outf << " " << line << '\n'; } outf.close(); } inf.close(); } } } extern "C" int jl_getpid(); static void write_lcov_data(logdata_t &logData, const std::string &outfile) { std::ofstream outf(outfile.c_str(), std::ofstream::ate | std::ofstream::out | std::ofstream::binary); //std::string base = std::string(jl_options.julia_bindir); //base = base + "/../share/julia/base/"; logdata_t::iterator it = logData.begin(); for (; it != logData.end(); it++) { StringRef filename = it->first(); const std::vector<logdata_block*> &values = it->second; if (!values.empty()) { outf << "SF:" << filename.str() << '\n'; size_t n_covered = 0; size_t n_instrumented = 0; size_t lno = 0; for (auto &itv : values) { if (itv) { logdata_block &data = *itv; for (int i = 0; i < logdata_blocksize; i++) { auto cov = data[i]; if (cov > 0) { n_instrumented++; if (cov > 1) n_covered++; outf << "DA:" << lno << ',' << (cov - 1) << '\n'; } lno++; } } else { lno += logdata_blocksize; } } outf << "LH:" << n_covered << '\n'; outf << "LF:" << n_instrumented << '\n'; outf << "end_of_record\n"; } } outf.close(); } extern "C" void jl_write_coverage_data(const char *output) { if (output) { StringRef output_pattern(output); if (output_pattern.endswith(".info")) write_lcov_data(coverageData, jl_format_filename(output_pattern)); } else { std::string stm; raw_string_ostream(stm) << "." << jl_getpid() << ".cov"; write_log_data(coverageData, stm.c_str()); } } extern "C" void jl_write_malloc_log(void) { std::string stm; raw_string_ostream(stm) << "." << jl_getpid() << ".mem"; write_log_data(mallocData, stm.c_str()); } // --- constant determination --- static void show_source_loc(jl_codectx_t &ctx, JL_STREAM *out) { jl_printf(out, "in %s at %s", ctx.name, ctx.file.str().c_str()); } extern "C" void jl_binding_deprecation_warning(jl_module_t *m, jl_binding_t *b); static void cg_bdw(jl_codectx_t &ctx, jl_binding_t *b) { jl_binding_deprecation_warning(ctx.module, b); if (b->deprecated == 1 && jl_options.depwarn) { show_source_loc(ctx, JL_STDERR); jl_printf(JL_STDERR, "\n"); } } static jl_value_t *static_apply_type(jl_codectx_t &ctx, const jl_cgval_t *args, size_t nargs) { jl_value_t **v = (jl_value_t**)alloca(sizeof(jl_value_t*) * nargs); for (size_t i = 0; i < nargs; i++) { if (!args[i].constant) return NULL; v[i] = args[i].constant; } assert(v[0] == jl_builtin_apply_type); size_t last_age = jl_get_ptls_states()->world_age; // call apply_type, but ignore errors. we know that will work in world 1. jl_get_ptls_states()->world_age = 1; jl_value_t *result; JL_TRY { result = jl_apply(v, nargs); } JL_CATCH { result = NULL; } jl_get_ptls_states()->world_age = last_age; return result; } // try to statically evaluate, NULL if not possible static jl_value_t *static_eval(jl_codectx_t &ctx, jl_value_t *ex, int sparams=true, int allow_alloc=true) { if (!JL_FEAT_TEST(ctx, static_alloc)) allow_alloc = 0; if (jl_is_symbol(ex)) { jl_sym_t *sym = (jl_sym_t*)ex; if (jl_is_const(ctx.module, sym)) return jl_get_global(ctx.module, sym); return NULL; } if (jl_is_slot(ex) || jl_is_argument(ex)) return NULL; if (jl_is_ssavalue(ex)) { ssize_t idx = ((jl_ssavalue_t*)ex)->id - 1; assert(idx >= 0); if (ctx.ssavalue_assigned.at(idx)) { return ctx.SAvalues.at(idx).constant; } return NULL; } if (jl_is_quotenode(ex)) return jl_fieldref(ex, 0); if (jl_is_method_instance(ex)) return NULL; jl_module_t *m = NULL; jl_sym_t *s = NULL; if (jl_is_globalref(ex)) { s = jl_globalref_name(ex); jl_binding_t *b = jl_get_binding(jl_globalref_mod(ex), s); if (b && b->constp) { if (b->deprecated) cg_bdw(ctx, b); return b->value; } return NULL; } if (jl_is_expr(ex)) { jl_expr_t *e = (jl_expr_t*)ex; if (e->head == call_sym) { jl_value_t *f = static_eval(ctx, jl_exprarg(e, 0), sparams, allow_alloc); if (f) { if (jl_array_dim0(e->args) == 3 && f == jl_builtin_getfield) { m = (jl_module_t*)static_eval(ctx, jl_exprarg(e, 1), sparams, allow_alloc); // Check the tag before evaluating `s` so that a value of random // type won't be corrupted. if (!m || !jl_is_module(m)) return NULL; // Assumes that the module is rooted somewhere. s = (jl_sym_t*)static_eval(ctx, jl_exprarg(e, 2), sparams, allow_alloc); if (s && jl_is_symbol(s)) { jl_binding_t *b = jl_get_binding(m, s); if (b && b->constp) { if (b->deprecated) cg_bdw(ctx, b); return b->value; } } } else if (f==jl_builtin_tuple || f==jl_builtin_apply_type) { size_t i; size_t n = jl_array_dim0(e->args)-1; if (n==0 && f==jl_builtin_tuple) return (jl_value_t*)jl_emptytuple; if (!allow_alloc) return NULL; jl_value_t **v; JL_GC_PUSHARGS(v, n+1); v[0] = f; for (i = 0; i < n; i++) { v[i+1] = static_eval(ctx, jl_exprarg(e, i+1), sparams, allow_alloc); if (v[i+1] == NULL) { JL_GC_POP(); return NULL; } } size_t last_age = jl_get_ptls_states()->world_age; // here we know we're calling specific builtin functions that work in world 1. jl_get_ptls_states()->world_age = 1; jl_value_t *result; JL_TRY { result = jl_apply(v, n+1); } JL_CATCH { result = NULL; } jl_get_ptls_states()->world_age = last_age; JL_GC_POP(); return result; } } } else if (e->head == static_parameter_sym) { size_t idx = jl_unbox_long(jl_exprarg(e, 0)); if (idx <= jl_svec_len(ctx.linfo->sparam_vals)) { jl_value_t *e = jl_svecref(ctx.linfo->sparam_vals, idx - 1); if (jl_is_typevar(e)) return NULL; return e; } } return NULL; } return ex; } static bool slot_eq(jl_value_t *e, int sl) { return (jl_is_slot(e) || jl_is_argument(e)) && jl_slot_number(e)-1 == sl; } // --- code gen for intrinsic functions --- #include "intrinsics.cpp" // --- find volatile variables --- // assigned in a try block and used outside that try block static bool local_var_occurs(jl_value_t *e, int sl) { if (slot_eq(e, sl)) { return true; } else if (jl_is_expr(e)) { jl_expr_t *ex = (jl_expr_t*)e; size_t alength = jl_array_dim0(ex->args); for(int i=0; i < (int)alength; i++) { if (local_var_occurs(jl_exprarg(ex,i),sl)) return true; } } else if (jl_is_returnnode(e)) { jl_value_t *retexpr = jl_returnnode_value(e); if (retexpr != NULL) return local_var_occurs(retexpr, sl); } else if (jl_is_gotoifnot(e)) { return local_var_occurs(jl_gotoifnot_cond(e), sl); } return false; } static std::set<int> assigned_in_try(jl_array_t *stmts, int s, long l) { std::set<int> av; for(int i=s; i <= l; i++) { jl_value_t *st = jl_array_ptr_ref(stmts,i); if (jl_is_expr(st)) { if (((jl_expr_t*)st)->head == assign_sym) { jl_value_t *ar = jl_exprarg(st, 0); if (jl_is_slot(ar)) { av.insert(jl_slot_number(ar)-1); } } } } return av; } static void mark_volatile_vars(jl_array_t *stmts, std::vector<jl_varinfo_t> &slots) { size_t slength = jl_array_dim0(stmts); for (int i = 0; i < (int)slength; i++) { jl_value_t *st = jl_array_ptr_ref(stmts, i); if (jl_is_expr(st)) { if (((jl_expr_t*)st)->head == enter_sym) { int last = jl_unbox_long(jl_exprarg(st, 0)); std::set<int> as = assigned_in_try(stmts, i + 1, last); for (int j = 0; j < (int)slength; j++) { if (j < i || j > last) { std::set<int>::iterator it = as.begin(); for (; it != as.end(); it++) { if (local_var_occurs(jl_array_ptr_ref(stmts, j), *it)) { jl_varinfo_t &vi = slots[*it]; vi.isVolatile = true; } } } } } } } } // --- use analysis --- // a very simple, conservative use analysis // to eagerly remove slot assignments that are never read from static void simple_use_analysis(jl_codectx_t &ctx, jl_value_t *expr) { if (jl_is_slot(expr) || jl_is_argument(expr)) { int i = jl_slot_number(expr) - 1; ctx.slots[i].used = true; } else if (jl_is_expr(expr)) { jl_expr_t *e = (jl_expr_t*)expr; if (e->head == method_sym) { simple_use_analysis(ctx, jl_exprarg(e, 0)); if (jl_expr_nargs(e) > 1) { simple_use_analysis(ctx, jl_exprarg(e, 1)); simple_use_analysis(ctx, jl_exprarg(e, 2)); } } else if (e->head == assign_sym) { // don't consider assignment LHS as a variable "use" simple_use_analysis(ctx, jl_exprarg(e, 1)); } else { size_t i, elen = jl_array_dim0(e->args); for (i = 0; i < elen; i++) { simple_use_analysis(ctx, jl_exprarg(e, i)); } } } else if (jl_is_returnnode(expr)) { jl_value_t *retexpr = jl_returnnode_value(expr); if (retexpr != NULL) simple_use_analysis(ctx, retexpr); } else if (jl_is_gotoifnot(expr)) { simple_use_analysis(ctx, jl_gotoifnot_cond(expr)); } else if (jl_is_pinode(expr)) { simple_use_analysis(ctx, jl_fieldref_noalloc(expr, 0)); } else if (jl_is_upsilonnode(expr)) { jl_value_t *val = jl_fieldref_noalloc(expr, 0); if (val) simple_use_analysis(ctx, val); } else if (jl_is_phicnode(expr)) { jl_array_t *values = (jl_array_t*)jl_fieldref_noalloc(expr, 0); size_t i, elen = jl_array_len(values); for (i = 0; i < elen; i++) { jl_value_t *v = jl_array_ptr_ref(values, i); simple_use_analysis(ctx, v); } } else if (jl_is_phinode(expr)) { jl_array_t *values = (jl_array_t*)jl_fieldref_noalloc(expr, 1); size_t i, elen = jl_array_len(values); for (i = 0; i < elen; i++) { jl_value_t *v = jl_array_ptr_ref(values, i); if (v) simple_use_analysis(ctx, v); } } } // --- gc root utils --- // ---- Get Element Pointer (GEP) instructions within the GC frame ---- static void jl_add_method_root(jl_codectx_t &ctx, jl_value_t *val) { if (jl_is_concrete_type(val) || jl_is_bool(val) || jl_is_symbol(val) || val == jl_nothing || val == (jl_value_t*)jl_any_type || val == (jl_value_t*)jl_bottom_type || val == (jl_value_t*)jl_core_module) return; JL_GC_PUSH1(&val); if (ctx.roots == NULL) { ctx.roots = jl_alloc_vec_any(1); jl_array_ptr_set(ctx.roots, 0, val); } else { size_t rlen = jl_array_dim0(ctx.roots); for (size_t i = 0; i < rlen; i++) { if (jl_array_ptr_ref(ctx.roots,i) == val) { JL_GC_POP(); return; } } jl_array_ptr_1d_push(ctx.roots, val); } JL_GC_POP(); } // --- generating function calls --- static jl_cgval_t emit_globalref(jl_codectx_t &ctx, jl_module_t *mod, jl_sym_t *name) { jl_binding_t *bnd = NULL; Value *bp = global_binding_pointer(ctx, mod, name, &bnd, false); if (bnd && bnd->value != NULL) { if (bnd->constp) { return mark_julia_const(bnd->value); } LoadInst *v = ctx.builder.CreateAlignedLoad(T_prjlvalue, bp, sizeof(void*)); v->setOrdering(AtomicOrdering::Unordered); tbaa_decorate(tbaa_binding, v); return mark_julia_type(ctx, v, true, (jl_value_t*)jl_any_type); } // todo: use type info to avoid undef check return emit_checked_var(ctx, bp, name, false, tbaa_binding); } static jl_cgval_t emit_getfield(jl_codectx_t &ctx, const jl_cgval_t &strct, jl_sym_t *name) { if (strct.constant && jl_is_module(strct.constant)) return emit_globalref(ctx, (jl_module_t*)strct.constant, name); jl_datatype_t *sty = (jl_datatype_t*)strct.typ; if (jl_is_type_type((jl_value_t*)sty) && jl_is_concrete_type(jl_tparam0(sty))) sty = (jl_datatype_t*)jl_typeof(jl_tparam0(sty)); sty = (jl_datatype_t*)jl_unwrap_unionall((jl_value_t*)sty); if (jl_is_structtype(sty) && sty != jl_module_type && sty->layout) { unsigned idx = jl_field_index(sty, name, 0); if (idx != (unsigned)-1) { return emit_getfield_knownidx(ctx, strct, idx, sty); } } // TODO: attempt better codegen for approximate types, if the types // and offsets of some fields are independent of parameters. // TODO: generic getfield func with more efficient calling convention jl_cgval_t myargs_array[2] = { strct, mark_julia_const((jl_value_t*)name) }; Value *result = emit_jlcall(ctx, jlgetfield_func, maybe_decay_untracked(V_null), myargs_array, 2, JLCALL_F_CC); return mark_julia_type(ctx, result, true, jl_any_type); } static Value *emit_box_compare(jl_codectx_t &ctx, const jl_cgval_t &arg1, const jl_cgval_t &arg2) { if (jl_pointer_egal(arg1.typ) || jl_pointer_egal(arg2.typ)) { Value *varg1 = arg1.constant ? literal_pointer_val(ctx, arg1.constant) : arg1.V; Value *varg2 = arg2.constant ? literal_pointer_val(ctx, arg2.constant) : arg2.V; assert(varg1 && varg2 && (arg1.isboxed || arg1.TIndex) && (arg2.isboxed || arg2.TIndex) && "Only boxed types are valid for pointer comparison."); varg1 = maybe_decay_tracked(varg1); varg2 = maybe_decay_tracked(varg2); if (cast<PointerType>(varg1->getType())->getAddressSpace() != cast<PointerType>(varg2->getType())->getAddressSpace()) { varg1 = decay_derived(varg1); varg2 = decay_derived(varg2); } return ctx.builder.CreateICmpEQ(emit_bitcast(ctx, varg1, T_pint8), emit_bitcast(ctx, varg2, T_pint8)); } Value *varg1 = mark_callee_rooted(boxed(ctx, arg1)); Value *varg2 = mark_callee_rooted(boxed(ctx, arg2)); return ctx.builder.CreateTrunc(ctx.builder.CreateCall(prepare_call(jlegal_func), {varg1, varg2}), T_int1); } static Value *emit_bits_compare(jl_codectx_t &ctx, jl_cgval_t arg1, jl_cgval_t arg2); static Value *emit_bitsunion_compare(jl_codectx_t &ctx, const jl_cgval_t &arg1, const jl_cgval_t &arg2) { assert(arg1.typ == arg2.typ && arg1.TIndex && arg2.TIndex && jl_is_uniontype(arg1.typ) && "unimplemented"); Value *tindex = arg1.TIndex; BasicBlock *defaultBB = BasicBlock::Create(jl_LLVMContext, "unionbits_is_boxed", ctx.f); SwitchInst *switchInst = ctx.builder.CreateSwitch(tindex, defaultBB); BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_unionbits_is", ctx.f); ctx.builder.SetInsertPoint(postBB); PHINode *phi = ctx.builder.CreatePHI(T_int1, 2); unsigned counter = 0; for_each_uniontype_small( [&](unsigned idx, jl_datatype_t *jt) { BasicBlock *tempBB = BasicBlock::Create(jl_LLVMContext, "unionbits_is", ctx.f); ctx.builder.SetInsertPoint(tempBB); switchInst->addCase(ConstantInt::get(T_int8, idx), tempBB); jl_cgval_t sel_arg1(arg1, (jl_value_t*)jt, NULL); jl_cgval_t sel_arg2(arg2, (jl_value_t*)jt, NULL); Value *cmp = emit_bits_compare(ctx, sel_arg1, sel_arg2); tempBB = ctx.builder.GetInsertBlock(); // could have changed phi->addIncoming(cmp, tempBB); ctx.builder.CreateBr(postBB); }, arg1.typ, counter); ctx.builder.SetInsertPoint(defaultBB); Function *trap_func = Intrinsic::getDeclaration( ctx.f->getParent(), Intrinsic::trap); ctx.builder.CreateCall(trap_func); ctx.builder.CreateUnreachable(); ctx.builder.SetInsertPoint(postBB); return ctx.builder.CreateAnd(phi, ctx.builder.CreateICmpEQ(arg1.TIndex, arg2.TIndex)); } static Value *emit_bits_compare(jl_codectx_t &ctx, jl_cgval_t arg1, jl_cgval_t arg2) { bool isboxed; Type *at = julia_type_to_llvm(ctx, arg1.typ, &isboxed); assert(jl_is_datatype(arg1.typ) && arg1.typ == arg2.typ && !isboxed); if (type_is_ghost(at)) return ConstantInt::get(T_int1, 1); if (at->isIntegerTy() || at->isPointerTy() || at->isFloatingPointTy()) { Type *at_int = INTT(at); Value *varg1 = emit_unbox(ctx, at_int, arg1, arg1.typ); Value *varg2 = emit_unbox(ctx, at_int, arg2, arg2.typ); return ctx.builder.CreateICmpEQ(varg1, varg2); } if (at->isVectorTy()) { jl_svec_t *types = ((jl_datatype_t*)arg1.typ)->types; Value *answer = ConstantInt::get(T_int1, 1); Value *varg1 = emit_unbox(ctx, at, arg1, arg1.typ); Value *varg2 = emit_unbox(ctx, at, arg2, arg2.typ); for (size_t i = 0, l = jl_svec_len(types); i < l; i++) { jl_value_t *fldty = jl_svecref(types, i); Value *subAns, *fld1, *fld2; fld1 = ctx.builder.CreateExtractElement(varg1, ConstantInt::get(T_int32, i)), fld2 = ctx.builder.CreateExtractElement(varg2, ConstantInt::get(T_int32, i)), subAns = emit_bits_compare(ctx, mark_julia_type(ctx, fld1, false, fldty), mark_julia_type(ctx, fld2, false, fldty)); answer = ctx.builder.CreateAnd(answer, subAns); } return answer; } if (at->isAggregateType()) { // Struct or Array jl_datatype_t *sty = (jl_datatype_t*)arg1.typ; size_t sz = jl_datatype_size(sty); Value *varg1 = arg1.ispointer() ? maybe_decay_tracked(data_pointer(ctx, arg1)) : arg1.V; Value *varg2 = arg2.ispointer() ? maybe_decay_tracked(data_pointer(ctx, arg2)) : arg2.V; if (sz > 512 && !sty->layout->haspadding) { if (!arg1.ispointer()) varg1 = value_to_pointer(ctx, arg1).V; if (!arg2.ispointer()) varg2 = value_to_pointer(ctx, arg2).V; varg1 = emit_pointer_from_objref(ctx, varg1); varg2 = emit_pointer_from_objref(ctx, varg2); Value *gc_uses[2]; int nroots = 0; if ((gc_uses[nroots] = get_gc_root_for(arg1))) nroots++; if ((gc_uses[nroots] = get_gc_root_for(arg2))) nroots++; OperandBundleDef OpBundle("jl_roots", makeArrayRef(gc_uses, nroots)); Value *answer = ctx.builder.CreateCall(prepare_call(memcmp_func), { ctx.builder.CreateBitCast(varg1, T_pint8), ctx.builder.CreateBitCast(varg2, T_pint8), ConstantInt::get(T_size, sz) }, ArrayRef<OperandBundleDef>(&OpBundle, nroots ? 1 : 0)); return ctx.builder.CreateICmpEQ(answer, ConstantInt::get(T_int32, 0)); } else { Type *atp = at->getPointerTo(); if (arg1.ispointer()) varg1 = maybe_bitcast(ctx, varg1, atp); if (arg2.ispointer()) varg2 = maybe_bitcast(ctx, varg2, atp); jl_svec_t *types = sty->types; Value *answer = ConstantInt::get(T_int1, 1); for (size_t i = 0, l = jl_svec_len(types); i < l; i++) { // TODO: should we replace this with `subAns = emit_f_is(emit_getfield_knownidx(ctx, arg1, i, arg1.typ), emit_getfield_knownidx(ctx, arg2, i, arg2.typ))` // or is there any value in all this extra effort?? jl_value_t *fldty = jl_svecref(types, i); if (type_is_ghost(julia_type_to_llvm(ctx, fldty))) continue; unsigned byte_offset = jl_field_offset(sty, i); Value *subAns, *fld1, *fld2; unsigned llvm_idx = (i > 0 && isa<StructType>(at)) ? convert_struct_offset(ctx, at, byte_offset) : i; if (arg1.ispointer()) fld1 = ctx.builder.CreateConstInBoundsGEP2_32(at, varg1, 0, llvm_idx); else fld1 = ctx.builder.CreateExtractValue(varg1, llvm_idx); if (arg2.ispointer()) fld2 = ctx.builder.CreateConstInBoundsGEP2_32(at, varg2, 0, llvm_idx); else fld2 = ctx.builder.CreateExtractValue(varg2, llvm_idx); if (jl_field_isptr(sty, i)) { if (arg1.ispointer()) { fld1 = ctx.builder.CreateAlignedLoad(T_prjlvalue, fld1, sizeof(void*)); cast<LoadInst>(fld1)->setOrdering(AtomicOrdering::Unordered); } if (arg2.ispointer()) { fld2 = ctx.builder.CreateAlignedLoad(T_prjlvalue, fld2, sizeof(void*)); cast<LoadInst>(fld2)->setOrdering(AtomicOrdering::Unordered); } subAns = emit_box_compare(ctx, mark_julia_type(ctx, fld1, true, fldty), mark_julia_type(ctx, fld2, true, fldty)); } else if (jl_is_uniontype(fldty)) { unsigned tindex_offset = byte_offset + jl_field_size(sty, i) - 1; jl_cgval_t fld1_info; jl_cgval_t fld2_info; if (arg1.ispointer()) { Value *tindex1 = ctx.builder.CreateNUWAdd(ConstantInt::get(T_int8, 1), ctx.builder.CreateAlignedLoad(T_int8, emit_struct_gep(ctx, at, varg1, tindex_offset), 1)); fld1_info = mark_julia_slot(fld1, fldty, tindex1, arg1.tbaa); } else { fld1_info = emit_getfield_knownidx(ctx, arg1, i, sty); } if (arg2.ispointer()) { Value *tindex2 = ctx.builder.CreateNUWAdd(ConstantInt::get(T_int8, 1), ctx.builder.CreateAlignedLoad(T_int8, emit_struct_gep(ctx, at, varg2, tindex_offset), 1)); fld2_info = mark_julia_slot(fld2, fldty, tindex2, arg2.tbaa); } else { fld2_info = emit_getfield_knownidx(ctx, arg2, i, sty); } subAns = emit_bitsunion_compare(ctx, fld1_info, fld2_info); } else { assert(jl_is_concrete_type(fldty)); jl_cgval_t fld1_info = arg1.ispointer() ? mark_julia_slot(fld1, fldty, NULL, arg1.tbaa) : mark_julia_type(ctx, fld1, false, fldty); jl_cgval_t fld2_info = arg2.ispointer() ? mark_julia_slot(fld2, fldty, NULL, arg2.tbaa) : mark_julia_type(ctx, fld2, false, fldty); subAns = emit_bits_compare(ctx, fld1_info, fld2_info); } answer = ctx.builder.CreateAnd(answer, subAns); } return answer; } } assert(0 && "what is this llvm type?"); abort(); } // emit code for is (===). static Value *emit_f_is(jl_codectx_t &ctx, const jl_cgval_t &arg1, const jl_cgval_t &arg2) { jl_value_t *rt1 = arg1.typ; jl_value_t *rt2 = arg2.typ; if (jl_is_concrete_type(rt1) && jl_is_concrete_type(rt2) && !jl_is_kind(rt1) && !jl_is_kind(rt2) && rt1 != rt2) { // disjoint concrete leaf types are never equal (quick test) return ConstantInt::get(T_int1, 0); } if (arg1.isghost || arg2.isghost) { // comparing to a singleton object if (arg1.TIndex) return emit_isa(ctx, arg1, rt2, NULL).first; // rt2 is a singleton type if (arg2.TIndex) return emit_isa(ctx, arg2, rt1, NULL).first; // rt1 is a singleton type // rooting these values isn't needed since we won't load this pointer // and we know at least one of them is a unique Singleton // which is already enough to ensure pointer uniqueness for this test // even if the other pointer managed to get garbage collected return ctx.builder.CreateICmpEQ( mark_callee_rooted(boxed(ctx, arg1)), mark_callee_rooted(boxed(ctx, arg2))); } if (jl_type_intersection(rt1, rt2) == (jl_value_t*)jl_bottom_type) // types are disjoint (exhaustive test) return ConstantInt::get(T_int1, 0); bool justbits1 = jl_is_concrete_immutable(rt1); bool justbits2 = jl_is_concrete_immutable(rt2); if (justbits1 || justbits2) { // whether this type is unique'd by value jl_value_t *typ = justbits1 ? rt1 : rt2; if (rt1 == rt2) return emit_bits_compare(ctx, arg1, arg2); Value *same_type = (typ == rt2) ? emit_isa(ctx, arg1, typ, NULL).first : emit_isa(ctx, arg2, typ, NULL).first; BasicBlock *currBB = ctx.builder.GetInsertBlock(); BasicBlock *isaBB = BasicBlock::Create(jl_LLVMContext, "is", ctx.f); BasicBlock *postBB = BasicBlock::Create(jl_LLVMContext, "post_is", ctx.f); ctx.builder.CreateCondBr(same_type, isaBB, postBB); ctx.builder.SetInsertPoint(isaBB); Value *bitcmp = emit_bits_compare(ctx, jl_cgval_t(arg1, typ, NULL), jl_cgval_t(arg2, typ, NULL)); isaBB = ctx.builder.GetInsertBlock(); // might have changed ctx.builder.CreateBr(postBB); ctx.builder.SetInsertPoint(postBB); PHINode *cmp = ctx.builder.CreatePHI(T_int1, 2); cmp->addIncoming(ConstantInt::get(T_int1, 0), currBB); cmp->addIncoming(bitcmp, isaBB); return cmp; } // if (arg1.tindex || arg2.tindex) // TODO: handle with emit_bitsunion_compare return emit_box_compare(ctx, arg1, arg2); } static bool emit_builtin_call(jl_codectx_t &ctx, jl_cgval_t *ret, jl_value_t *f, const jl_cgval_t *argv, size_t nargs, jl_value_t *rt, jl_expr_t *ex) // returns true if the call has been handled { if (f == jl_builtin_is && nargs == 2) { // emit values const jl_cgval_t &v1 = argv[1]; const jl_cgval_t &v2 = argv[2]; // handle simple static expressions with no side-effects if (v1.constant) { if (v2.constant) { *ret = mark_julia_type(ctx, ConstantInt::get(T_int8, jl_egal(v1.constant, v2.constant)), false, jl_bool_type); return true; } } // emit comparison test Value *ans = emit_f_is(ctx, v1, v2); *ret = mark_julia_type(ctx, ctx.builder.CreateZExt(ans, T_int8), false, jl_bool_type); return true; } else if (f == jl_builtin_typeof && nargs == 1) { *ret = emit_typeof(ctx, argv[1]); return true; } else if (f == jl_builtin_typeassert && nargs == 2) { const jl_cgval_t &arg = argv[1]; const jl_cgval_t &ty = argv[2]; if (jl_is_type_type(ty.typ) && !jl_has_free_typevars(ty.typ)) { jl_value_t *tp0 = jl_tparam0(ty.typ); emit_typecheck(ctx, arg, tp0, "typeassert"); *ret = arg; return true; } if (jl_subtype(ty.typ, (jl_value_t*)jl_type_type)) { Value *rt_arg = boxed(ctx, arg); Value *rt_ty = boxed(ctx, ty); ctx.builder.CreateCall(prepare_call(jltypeassert_func), {rt_arg, rt_ty}); *ret = arg; return true; } } else if (f == jl_builtin_isa && nargs == 2) { const jl_cgval_t &arg = argv[1]; const jl_cgval_t &ty = argv[2]; if (jl_is_type_type(ty.typ) && !jl_has_free_typevars(ty.typ)) { jl_value_t *tp0 = jl_tparam0(ty.typ); Value *isa_result = emit_isa(ctx, arg, tp0, NULL).first; if (isa_result->getType() == T_int1) isa_result = ctx.builder.CreateZExt(isa_result, T_int8); *ret = mark_julia_type(ctx, isa_result, false, jl_bool_type); return true; } } else if (f == jl_builtin_issubtype && nargs == 2) { const jl_cgval_t &ta = argv[1]; const jl_cgval_t &tb = argv[2]; if (jl_is_type_type(ta.typ) && !jl_has_free_typevars(ta.typ) && jl_is_type_type(tb.typ) && !jl_has_free_typevars(tb.typ)) { int issub = jl_subtype(jl_tparam0(ta.typ), jl_tparam0(tb.typ)); *ret = mark_julia_type(ctx, ConstantInt::get(T_int8, issub), false, jl_bool_type); return true; } } else if (((f == jl_builtin__apply && nargs == 2) || (f == jl_builtin__apply_iterate && nargs == 3)) && ctx.vaSlot > 0) { int arg_start = f == jl_builtin__apply ? 2 : 3; // turn Core._apply(f, Tuple) ==> f(Tuple...) using the jlcall calling convention if Tuple is the va allocation if (LoadInst *load = dyn_cast_or_null<LoadInst>(argv[arg_start].V)) { if (load->getPointerOperand() == ctx.slots[ctx.vaSlot].boxroot && ctx.argArray) { Value *theF = maybe_decay_untracked(boxed(ctx, argv[arg_start-1])); Value *nva = emit_n_varargs(ctx); #ifdef _P64 nva = ctx.builder.CreateTrunc(nva, T_int32); #endif Value *theArgs = ctx.builder.CreateInBoundsGEP(T_prjlvalue, ctx.argArray, ConstantInt::get(T_size, ctx.nReqArgs)); Value *r = ctx.builder.CreateCall(prepare_call(jlapplygeneric_func), { theF, theArgs, nva }); *ret = mark_julia_type(ctx, r, true, jl_any_type); return true; } } } else if (f == jl_builtin_tuple) { if (nargs == 0) { *ret = ghostValue(jl_emptytuple_type); return true; } if (jl_is_tuple_type(rt) && jl_is_concrete_type(rt) && nargs == jl_datatype_nfields(rt)) { *ret = emit_new_struct(ctx, rt, nargs, &argv[1]); return true; } } else if (f == jl_builtin_throw && nargs == 1) { Value *arg1 = boxed(ctx, argv[1]); raise_exception(ctx, arg1); *ret = jl_cgval_t(); return true; } else if (f == jl_builtin_arraysize && nargs == 2) { const jl_cgval_t &ary = argv[1]; const jl_cgval_t &idx = argv[2]; jl_value_t *aty = jl_unwrap_unionall(ary.typ); if (jl_is_array_type(aty) && idx.typ == (jl_value_t*)jl_long_type) { jl_value_t *ndp = jl_tparam1(aty); if (jl_is_long(ndp)) { size_t ndims = jl_unbox_long(ndp); if (idx.constant) { uint32_t idx_const = (uint32_t)jl_unbox_long(idx.constant); if (idx_const > 0 && idx_const <= ndims) { jl_value_t *ary_ex = jl_exprarg(ex, 1); *ret = mark_julia_type(ctx, emit_arraysize(ctx, ary, ary_ex, idx_const), false, jl_long_type); return true; } else if (idx_const > ndims) { *ret = mark_julia_type(ctx, ConstantInt::get(T_size, 1), false, jl_long_type); return true; } } else { Value *idx_dyn = emit_unbox(ctx, T_size, idx, (jl_value_t*)jl_long_type); error_unless(ctx, ctx.builder.CreateICmpSGT(idx_dyn, ConstantInt::get(T_size, 0)), "arraysize: dimension out of range"); BasicBlock *outBB = BasicBlock::Create(jl_LLVMContext, "outofrange", ctx.f); BasicBlock *inBB = BasicBlock::Create(jl_LLVMContext, "inrange"); BasicBlock *ansBB = BasicBlock::Create(jl_LLVMContext, "arraysize"); ctx.builder.CreateCondBr(ctx.builder.CreateICmpSLE(idx_dyn, ConstantInt::get(T_size, ndims)), inBB, outBB); ctx.builder.SetInsertPoint(outBB); Value *v_one = ConstantInt::get(T_size, 1); ctx.builder.CreateBr(ansBB); ctx.f->getBasicBlockList().push_back(inBB); ctx.builder.SetInsertPoint(inBB); Value *v_sz = emit_arraysize(ctx, ary, idx_dyn); ctx.builder.CreateBr(ansBB); inBB = ctx.builder.GetInsertBlock(); // could have changed ctx.f->getBasicBlockList().push_back(ansBB); ctx.builder.SetInsertPoint(ansBB); PHINode *result = ctx.builder.CreatePHI(T_size, 2); result->addIncoming(v_one, outBB); result->addIncoming(v_sz, inBB); *ret = mark_julia_type(ctx, result, false, jl_long_type); return true; } } } } else if ((f == jl_builtin_arrayref || f == jl_builtin_const_arrayref) && nargs >= 3) { const jl_cgval_t &ary = argv[2]; bool indices_ok = true; for (size_t i = 3; i <= nargs; i++) { if (argv[i].typ != (jl_value_t*)jl_long_type) { indices_ok = false; break; } } jl_value_t *aty_dt = jl_unwrap_unionall(ary.typ); if (jl_is_array_type(aty_dt) && indices_ok) { jl_value_t *ety = jl_tparam0(aty_dt); jl_value_t *ndp = jl_tparam1(aty_dt); if (!jl_has_free_typevars(ety) && (jl_is_long(ndp) || nargs == 3)) { jl_value_t *ary_ex = jl_exprarg(ex, 2); size_t elsz = 0, al = 0; int union_max = jl_islayout_inline(ety, &elsz, &al); bool isboxed = (union_max == 0); if (isboxed) ety = (jl_value_t*)jl_any_type; ssize_t nd = jl_is_long(ndp) ? jl_unbox_long(ndp) : -1; jl_value_t *boundscheck = argv[1].constant; Value *idx = emit_array_nd_index(ctx, ary, ary_ex, nd, &argv[3], nargs - 2, boundscheck); if (!isboxed && jl_is_datatype(ety) && jl_datatype_size(ety) == 0) { assert(((jl_datatype_t*)ety)->instance != NULL); *ret = ghostValue(ety); } else if (!isboxed && jl_is_uniontype(ety)) { Type *AT = ArrayType::get(IntegerType::get(jl_LLVMContext, 8 * al), (elsz + al - 1) / al); Value *data = emit_bitcast(ctx, emit_arrayptr(ctx, ary, ary_ex), AT->getPointerTo()); // isbits union selector bytes are stored after a->maxsize Value *ndims = (nd == -1 ? emit_arrayndims(ctx, ary) : ConstantInt::get(T_int16, nd)); Value *is_vector = ctx.builder.CreateICmpEQ(ndims, ConstantInt::get(T_int16, 1)); Value *offset = emit_arrayoffset(ctx, ary, nd); Value *selidx_v = ctx.builder.CreateSub(emit_vectormaxsize(ctx, ary), ctx.builder.CreateZExt(offset, T_size)); Value *selidx_m = emit_arraylen(ctx, ary); Value *selidx = ctx.builder.CreateSelect(is_vector, selidx_v, selidx_m); Value *ptindex = ctx.builder.CreateInBoundsGEP(AT, data, selidx); ptindex = emit_bitcast(ctx, ptindex, T_pint8); ptindex = ctx.builder.CreateInBoundsGEP(T_int8, ptindex, offset); ptindex = ctx.builder.CreateInBoundsGEP(T_int8, ptindex, idx); Instruction *tindex = tbaa_decorate(tbaa_arrayselbyte, ctx.builder.CreateAlignedLoad(T_int8, ptindex, 1)); tindex->setMetadata(LLVMContext::MD_range, MDNode::get(jl_LLVMContext, { ConstantAsMetadata::get(ConstantInt::get(T_int8, 0)), ConstantAsMetadata::get(ConstantInt::get(T_int8, union_max)) })); AllocaInst *lv = emit_static_alloca(ctx, AT); if (al > 1) lv->setAlignment(Align(al)); emit_memcpy(ctx, lv, tbaa_arraybuf, ctx.builder.CreateInBoundsGEP(AT, data, idx), tbaa_arraybuf, elsz, al, false); *ret = mark_julia_slot(lv, ety, ctx.builder.CreateNUWAdd(ConstantInt::get(T_int8, 1), tindex), tbaa_arraybuf); } else { MDNode *aliasscope = (f == jl_builtin_const_arrayref) ? ctx.aliasscope : nullptr; *ret = typed_load(ctx, emit_arrayptr(ctx, ary, ary_ex), idx, ety, !isboxed ? tbaa_arraybuf : tbaa_ptrarraybuf, aliasscope); } return true; } } } else if (f == jl_builtin_arrayset && nargs >= 4) { const jl_cgval_t &ary = argv[2]; const jl_cgval_t &val = argv[3]; bool indices_ok = true; for (size_t i = 4; i <= nargs; i++) { if (argv[i].typ != (jl_value_t*)jl_long_type) { indices_ok = false; break; } } jl_value_t *aty_dt = jl_unwrap_unionall(ary.typ); if (jl_is_array_type(aty_dt) && indices_ok) { jl_value_t *ety = jl_tparam0(aty_dt); jl_value_t *ndp = jl_tparam1(aty_dt); if (!jl_has_free_typevars(ety) && (jl_is_long(ndp) || nargs == 4)) { if (jl_subtype(val.typ, ety)) { // TODO: probably should just convert this to a type-assert size_t elsz = 0, al = 0; int union_max = jl_islayout_inline(ety, &elsz, &al); bool isboxed = (union_max == 0); if (isboxed) ety = (jl_value_t*)jl_any_type; jl_value_t *ary_ex = jl_exprarg(ex, 2); ssize_t nd = jl_is_long(ndp) ? jl_unbox_long(ndp) : -1; jl_value_t *boundscheck = argv[1].constant; Value *idx = emit_array_nd_index(ctx, ary, ary_ex, nd, &argv[4], nargs - 3, boundscheck); if (!isboxed && jl_is_datatype(ety) && jl_datatype_size(ety) == 0) { // no-op } else { PHINode *data_owner = NULL; // owner object against which the write barrier must check if (isboxed || (jl_is_datatype(ety) && ((jl_datatype_t*)ety)->layout->npointers > 0)) { // if elements are just bits, don't need a write barrier Value *aryv = maybe_decay_untracked(boxed(ctx, ary)); Value *flags = emit_arrayflags(ctx, ary); // the owner of the data is ary itself except if ary->how == 3 flags = ctx.builder.CreateAnd(flags, 3); Value *is_owned = ctx.builder.CreateICmpEQ(flags, ConstantInt::get(T_int16, 3)); BasicBlock *curBB = ctx.builder.GetInsertBlock(); BasicBlock *ownedBB = BasicBlock::Create(jl_LLVMContext, "array_owned", ctx.f); BasicBlock *mergeBB = BasicBlock::Create(jl_LLVMContext, "merge_own", ctx.f); ctx.builder.CreateCondBr(is_owned, ownedBB, mergeBB); ctx.builder.SetInsertPoint(ownedBB); // load owner pointer Instruction *own_ptr; if (jl_is_long(ndp)) { own_ptr = ctx.builder.CreateAlignedLoad(T_prjlvalue, ctx.builder.CreateConstGEP1_32(T_prjlvalue, emit_bitcast(ctx, decay_derived(aryv), T_pprjlvalue), jl_array_data_owner_offset(nd) / sizeof(jl_value_t*)), sizeof(void*)); tbaa_decorate(tbaa_const, maybe_mark_load_dereferenceable(own_ptr, false, (jl_value_t*)jl_array_any_type)); } else { own_ptr = ctx.builder.CreateCall( prepare_call(jlarray_data_owner_func), {aryv}); } ctx.builder.CreateBr(mergeBB); ctx.builder.SetInsertPoint(mergeBB); data_owner = ctx.builder.CreatePHI(T_prjlvalue, 2); data_owner->addIncoming(aryv, curBB); data_owner->addIncoming(own_ptr, ownedBB); } if (jl_is_uniontype(ety)) { Type *AT = ArrayType::get(IntegerType::get(jl_LLVMContext, 8 * al), (elsz + al - 1) / al); Value *data = emit_bitcast(ctx, emit_arrayptr(ctx, ary, ary_ex), AT->getPointerTo()); // compute tindex from val jl_cgval_t rhs_union = convert_julia_type(ctx, val, ety); Value *tindex = compute_tindex_unboxed(ctx, rhs_union, ety); tindex = ctx.builder.CreateNUWSub(tindex, ConstantInt::get(T_int8, 1)); Value *ndims = (nd == -1 ? emit_arrayndims(ctx, ary) : ConstantInt::get(T_int16, nd)); Value *is_vector = ctx.builder.CreateICmpEQ(ndims, ConstantInt::get(T_int16, 1)); Value *offset = emit_arrayoffset(ctx, ary, nd); Value *selidx_v = ctx.builder.CreateSub(emit_vectormaxsize(ctx, ary), ctx.builder.CreateZExt(offset, T_size)); Value *selidx_m = emit_arraylen(ctx, ary); Value *selidx = ctx.builder.CreateSelect(is_vector, selidx_v, selidx_m); Value *ptindex = ctx.builder.CreateInBoundsGEP(AT, data, selidx); ptindex = emit_bitcast(ctx, ptindex, T_pint8); ptindex = ctx.builder.CreateInBoundsGEP(T_int8, ptindex, offset); ptindex = ctx.builder.CreateInBoundsGEP(T_int8, ptindex, idx); tbaa_decorate(tbaa_arrayselbyte, ctx.builder.CreateStore(tindex, ptindex)); if (jl_is_datatype(val.typ) && jl_datatype_size(val.typ) == 0) { // no-op } else { // copy data Value *addr = ctx.builder.CreateInBoundsGEP(AT, data, idx); emit_unionmove(ctx, addr, tbaa_arraybuf, val, nullptr); } } else { typed_store(ctx, emit_arrayptr(ctx, ary, ary_ex, isboxed), idx, val, ety, !isboxed ? tbaa_arraybuf : tbaa_ptrarraybuf, ctx.aliasscope, data_owner, 0); } } *ret = ary; return true; } } } } else if (f == jl_builtin_getfield && (nargs == 2 || nargs == 3)) { const jl_cgval_t &obj = argv[1]; const jl_cgval_t &fld = argv[2]; if (fld.constant && fld.typ == (jl_value_t*)jl_symbol_type) { *ret = emit_getfield(ctx, argv[1], (jl_sym_t*)fld.constant); return true; } if (fld.typ == (jl_value_t*)jl_long_type) { if (ctx.vaSlot > 0) { // optimize VA tuple if (LoadInst *load = dyn_cast_or_null<LoadInst>(obj.V)) { if (load->getPointerOperand() == ctx.slots[ctx.vaSlot].boxroot && ctx.argArray) { Value *valen = emit_n_varargs(ctx); jl_cgval_t va_ary( // fake instantiation of a cgval, in order to call emit_bounds_check ctx.builder.CreateInBoundsGEP(T_prjlvalue, ctx.argArray, ConstantInt::get(T_size, ctx.nReqArgs)), NULL, false, NULL, NULL); Value *idx = emit_unbox(ctx, T_size, fld, (jl_value_t*)jl_long_type); jl_value_t *boundscheck = (nargs == 3 ? argv[3].constant : jl_true); idx = emit_bounds_check(ctx, va_ary, NULL, idx, valen, boundscheck); idx = ctx.builder.CreateAdd(idx, ConstantInt::get(T_size, ctx.nReqArgs)); Instruction *v = ctx.builder.CreateAlignedLoad(T_prjlvalue, ctx.builder.CreateInBoundsGEP(ctx.argArray, idx), sizeof(void*)); // if we know the result type of this load, we will mark that information here too tbaa_decorate(tbaa_value, maybe_mark_load_dereferenceable(v, false, rt)); *ret = mark_julia_type(ctx, v, /*boxed*/ true, rt); return true; } } } jl_datatype_t *utt = (jl_datatype_t*)jl_unwrap_unionall(obj.typ); if (jl_is_datatype(utt) && utt->layout) { if ((jl_is_structtype(utt) || jl_is_tuple_type(utt)) && !jl_subtype((jl_value_t*)jl_module_type, obj.typ)) { size_t nfields = jl_datatype_nfields(utt); // integer index size_t idx; if (fld.constant && (idx = jl_unbox_long(fld.constant) - 1) < nfields) { // known index *ret = emit_getfield_knownidx(ctx, obj, idx, utt); return true; } else { // unknown index Value *vidx = emit_unbox(ctx, T_size, fld, (jl_value_t*)jl_long_type); jl_value_t *boundscheck = (nargs == 3 ? argv[3].constant : jl_true); if (emit_getfield_unknownidx(ctx, ret, obj, vidx, utt, boundscheck)) { return true; } } } } else { if (jl_is_tuple_type(utt) && is_tupletype_homogeneous(utt->types, true)) { // For tuples, we can emit code even if we don't know the exact // type (e.g. because we don't know the length). This is possible // as long as we know that all elements are of the same (leaf) type. if (obj.ispointer()) { // Determine which was the type that was homogenous jl_value_t *jt = jl_tparam0(utt); if (jl_is_vararg_type(jt)) jt = jl_unwrap_vararg(jt); Value *vidx = emit_unbox(ctx, T_size, fld, (jl_value_t*)jl_long_type); // This is not necessary for correctness, but allows to omit // the extra code for getting the length of the tuple jl_value_t *boundscheck = (nargs == 3 ? argv[3].constant : jl_true); if (!bounds_check_enabled(ctx, boundscheck)) { vidx = ctx.builder.CreateSub(vidx, ConstantInt::get(T_size, 1)); } else { vidx = emit_bounds_check(ctx, obj, (jl_value_t*)obj.typ, vidx, emit_datatype_nfields(ctx, emit_typeof_boxed(ctx, obj)), jl_true); } bool isboxed = !jl_datatype_isinlinealloc(jt); Value *ptr = maybe_decay_tracked(data_pointer(ctx, obj)); *ret = typed_load(ctx, ptr, vidx, isboxed ? (jl_value_t*)jl_any_type : jt, obj.tbaa, nullptr, false); return true; } } } } } else if (f == jl_builtin_setfield && nargs == 3) { const jl_cgval_t &obj = argv[1]; const jl_cgval_t &fld = argv[2]; const jl_cgval_t &val = argv[3]; jl_datatype_t *uty = (jl_datatype_t*)jl_unwrap_unionall(obj.typ); if (jl_is_structtype(uty) && uty != jl_module_type && uty->layout) { size_t idx = (size_t)-1; if (fld.constant && fld.typ == (jl_value_t*)jl_symbol_type) { idx = jl_field_index(uty, (jl_sym_t*)fld.constant, 0); } else if (fld.constant && fld.typ == (jl_value_t*)jl_long_type) { ssize_t i = jl_unbox_long(fld.constant); if (i > 0 && i <= jl_datatype_nfields(uty)) idx = i - 1; } if (idx != (size_t)-1) { jl_value_t *ft = jl_svecref(uty->types, idx); if (jl_subtype(val.typ, ft)) { // TODO: attempt better codegen for approximate types emit_setfield(ctx, uty, obj, idx, val, true, true); *ret = val; return true; } } } } else if (f == jl_builtin_nfields && nargs == 1) { const jl_cgval_t &obj = argv[1]; if (ctx.vaSlot > 0) { // optimize VA tuple if (LoadInst *load = dyn_cast_or_null<LoadInst>(obj.V)) { if (load->getPointerOperand() == ctx.slots[ctx.vaSlot].boxroot) { *ret = mark_julia_type(ctx, emit_n_varargs(ctx), false, jl_long_type); return true; } } } ssize_t nf = -1; if (obj.constant) { nf = jl_datatype_nfields(jl_typeof(obj.constant)); } else if (jl_is_type_type(obj.typ)) { jl_value_t *tp0 = jl_tparam0(obj.typ); if (jl_is_datatype(tp0) && jl_is_datatype_singleton((jl_datatype_t*)tp0)) nf = jl_datatype_nfields(jl_typeof(tp0)); } else if (jl_is_concrete_type(obj.typ)) { nf = jl_datatype_nfields(obj.typ); } Value *sz; if (nf != -1) sz = ConstantInt::get(T_size, nf); else sz = emit_datatype_nfields(ctx, emit_typeof_boxed(ctx, obj)); *ret = mark_julia_type(ctx, sz, false, jl_long_type); return true; } else if (f == jl_builtin_fieldtype && (nargs == 2 || nargs == 3)) { const jl_cgval_t &typ = argv[1]; const jl_cgval_t &fld = argv[2]; if ((jl_is_type_type(typ.typ) && jl_is_concrete_type(jl_tparam0(typ.typ))) || (typ.constant && jl_is_concrete_type(typ.constant))) { if (fld.typ == (jl_value_t*)jl_long_type) { assert(typ.isboxed); Value *tyv = boxed(ctx, typ); Value *types_svec = emit_datatype_types(ctx, tyv); Value *types_len = emit_datatype_nfields(ctx, tyv); Value *idx = emit_unbox(ctx, T_size, fld, (jl_value_t*)jl_long_type); jl_value_t *boundscheck = (nargs == 3 ? argv[3].constant : jl_true); emit_bounds_check(ctx, typ, (jl_value_t*)jl_datatype_type, idx, types_len, boundscheck); Value *fieldtyp_p = ctx.builder.CreateInBoundsGEP(T_prjlvalue, decay_derived(emit_bitcast(ctx, types_svec, T_pprjlvalue)), idx); Value *fieldtyp = tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_prjlvalue, fieldtyp_p, sizeof(void*))); *ret = mark_julia_type(ctx, fieldtyp, true, (jl_value_t*)jl_type_type); return true; } } } else if (f == jl_builtin_sizeof && nargs == 1) { const jl_cgval_t &obj = argv[1]; jl_datatype_t *sty = (jl_datatype_t*)jl_unwrap_unionall(obj.typ); assert(jl_string_type->mutabl); if (sty == jl_string_type || sty == jl_simplevector_type) { // String and SimpleVector's length fields have the same layout auto ptr = emit_bitcast(ctx, boxed(ctx, obj), T_psize); Value *len = tbaa_decorate(tbaa_mutab, ctx.builder.CreateAlignedLoad(T_size, ptr, sizeof(size_t))); if (sty == jl_simplevector_type) { len = ctx.builder.CreateMul(len, ConstantInt::get(T_size, sizeof(void*))); len = ctx.builder.CreateAdd(len, ConstantInt::get(T_size, sizeof(void*))); } *ret = mark_julia_type(ctx, len, false, jl_long_type); return true; } else if (jl_is_array_type(sty)) { auto len = emit_arraylen(ctx, obj); jl_value_t *ety = jl_tparam0(sty); Value *elsize; size_t elsz = 0, al = 0; int union_max = jl_islayout_inline(ety, &elsz, &al); bool isboxed = (union_max == 0); if (!jl_has_free_typevars(ety)) { if (isboxed) { elsize = ConstantInt::get(T_size, sizeof(void*)); } else if (jl_is_primitivetype(ety)) { // Primitive types should use the array element size, but // this can be different from the type's size elsize = ConstantInt::get(T_size, LLT_ALIGN(elsz, al)); } else { elsize = ConstantInt::get(T_size, elsz); } } else { elsize = ctx.builder.CreateZExt(emit_arrayelsize(ctx, obj), T_size); } *ret = mark_julia_type(ctx, ctx.builder.CreateMul(len, elsize), false, jl_long_type); return true; } } else if (f == jl_builtin_apply_type && nargs > 0) { if (jl_is_method(ctx.linfo->def.method)) { // don't bother codegen constant-folding for toplevel. jl_value_t *ty = static_apply_type(ctx, argv, nargs + 1); if (ty != NULL) { jl_add_method_root(ctx, ty); *ret = mark_julia_const(ty); return true; } } } else if (f == jl_builtin_isdefined && nargs == 2) { const jl_cgval_t &obj = argv[1]; const jl_cgval_t &fld = argv[2]; jl_datatype_t *stt = (jl_datatype_t*)obj.typ; if (jl_is_type_type((jl_value_t*)stt)) { // the representation type of Type{T} is either typeof(T), or unknown // TODO: could use `issingletontype` predicate here, providing better type knowledge // than only handling DataType if (jl_is_concrete_type(jl_tparam0(stt))) stt = (jl_datatype_t*)jl_typeof(jl_tparam0(stt)); else return false; } if (!jl_is_concrete_type((jl_value_t*)stt) || jl_is_array_type(stt) || stt == jl_module_type) { // TODO: use ->layout here instead of concrete_type return false; } assert(jl_is_datatype(stt)); ssize_t fieldidx = -1; if (fld.constant && fld.typ == (jl_value_t*)jl_symbol_type) { jl_sym_t *sym = (jl_sym_t*)fld.constant; fieldidx = jl_field_index(stt, sym, 0); } else if (fld.constant && fld.typ == (jl_value_t*)jl_long_type) { fieldidx = jl_unbox_long(fld.constant) - 1; } else { return false; } if (fieldidx < 0 || fieldidx >= jl_datatype_nfields(stt)) { *ret = mark_julia_const(jl_false); } else if (fieldidx < stt->ninitialized) { *ret = mark_julia_const(jl_true); } else if (jl_field_isptr(stt, fieldidx) || jl_type_hasptr(jl_field_type(stt, fieldidx))) { Value *fldv; size_t offs = jl_field_offset(stt, fieldidx) / sizeof(jl_value_t*); if (obj.ispointer()) { if (!jl_field_isptr(stt, fieldidx)) offs += ((jl_datatype_t*)jl_field_type(stt, fieldidx))->layout->first_ptr; Value *ptr = emit_bitcast(ctx, maybe_decay_tracked(data_pointer(ctx, obj)), T_pprjlvalue); Value *addr = ctx.builder.CreateConstInBoundsGEP1_32(T_prjlvalue, ptr, offs); // emit this using the same type as emit_getfield_knownidx // so that LLVM may be able to load-load forward them and fold the result fldv = tbaa_decorate(obj.tbaa, ctx.builder.CreateAlignedLoad(T_prjlvalue, addr, sizeof(size_t))); cast<LoadInst>(fldv)->setOrdering(AtomicOrdering::Unordered); } else { fldv = ctx.builder.CreateExtractValue(obj.V, offs); if (!jl_field_isptr(stt, fieldidx)) { fldv = extract_first_ptr(ctx, fldv); assert(fldv); } } Value *isdef = ctx.builder.CreateIsNotNull(fldv); *ret = mark_julia_type(ctx, isdef, false, jl_bool_type); } else { *ret = mark_julia_const(jl_true); } return true; } return false; } static CallInst *emit_jlcall(jl_codectx_t &ctx, Function *theFptr, Value *theF, jl_cgval_t *argv, size_t nargs, CallingConv::ID cc) { // emit arguments SmallVector<Value*, 3> theArgs; SmallVector<Type*, 3> argsT; if (theF) { theArgs.push_back(theF); argsT.push_back(T_prjlvalue); } for (size_t i = 0; i < nargs; i++) { Value *arg = maybe_decay_untracked(boxed(ctx, argv[i])); theArgs.push_back(arg); argsT.push_back(T_prjlvalue); } FunctionType *FTy = FunctionType::get(T_prjlvalue, argsT, false); CallInst *result = ctx.builder.CreateCall(FTy, ctx.builder.CreateBitCast(theFptr, FTy->getPointerTo()), theArgs); add_return_attr(result, Attribute::NonNull); result->setCallingConv(cc); return result; } static CallInst *emit_jlcall(jl_codectx_t &ctx, JuliaFunction *theFptr, Value *theF, jl_cgval_t *argv, size_t nargs, CallingConv::ID cc) { return emit_jlcall(ctx, prepare_call(theFptr), theF, argv, nargs, cc); } static jl_cgval_t emit_call_specfun_other(jl_codectx_t &ctx, jl_method_instance_t *mi, jl_value_t *jlretty, StringRef specFunctionObject, jl_cgval_t *argv, size_t nargs, jl_returninfo_t::CallingConv *cc, unsigned *return_roots, jl_value_t *inferred_retty) { // emit specialized call site jl_returninfo_t returninfo = get_specsig_function(ctx, jl_Module, specFunctionObject, mi->specTypes, jlretty); FunctionType *cft = returninfo.decl->getFunctionType(); *cc = returninfo.cc; *return_roots = returninfo.return_roots; size_t nfargs = cft->getNumParams(); Value **argvals = (Value**)alloca(nfargs * sizeof(Value*)); unsigned idx = 0; AllocaInst *result; switch (returninfo.cc) { case jl_returninfo_t::Boxed: case jl_returninfo_t::Register: case jl_returninfo_t::Ghosts: break; case jl_returninfo_t::SRet: result = emit_static_alloca(ctx, cft->getParamType(0)->getPointerElementType()); argvals[idx] = result; idx++; break; case jl_returninfo_t::Union: result = emit_static_alloca(ctx, ArrayType::get(T_int8, returninfo.union_bytes)); if (returninfo.union_align > 1) result->setAlignment(Align(returninfo.union_align)); argvals[idx] = result; idx++; break; } if (returninfo.return_roots) { AllocaInst *return_roots = emit_static_alloca(ctx, T_prjlvalue); return_roots->setOperand(0, ConstantInt::get(T_int32, returninfo.return_roots)); argvals[idx] = return_roots; idx++; } for (size_t i = 0; i < nargs; i++) { jl_value_t *jt = jl_nth_slot_type(mi->specTypes, i); if (is_uniquerep_Type(jt)) continue; bool isboxed = deserves_argbox(jt); Type *et = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, jt); if (type_is_ghost(et)) continue; assert(idx < nfargs); Type *at = cft->getParamType(idx); jl_cgval_t arg = argv[i]; if (isboxed) { assert(at == T_prjlvalue && et == T_prjlvalue); argvals[idx] = maybe_decay_untracked(boxed(ctx, arg)); } else if (et->isAggregateType()) { if (!arg.ispointer()) arg = value_to_pointer(ctx, arg); // can lazy load on demand, no copy needed assert(at == PointerType::get(et, AddressSpace::Derived)); argvals[idx] = decay_derived(maybe_bitcast(ctx, data_pointer(ctx, arg), at)); } else { assert(at == et); Value *val = emit_unbox(ctx, et, arg, jt); if (!val) { // There was a type mismatch of some sort - exit early CreateTrap(ctx.builder); return jl_cgval_t(); } argvals[idx] = val; } idx++; } assert(idx == nfargs); CallInst *call = ctx.builder.CreateCall(returninfo.decl, ArrayRef<Value*>(&argvals[0], nfargs)); call->setAttributes(returninfo.decl->getAttributes()); jl_cgval_t retval; switch (returninfo.cc) { case jl_returninfo_t::Boxed: retval = mark_julia_type(ctx, call, true, inferred_retty); break; case jl_returninfo_t::Register: retval = mark_julia_type(ctx, call, false, jlretty); break; case jl_returninfo_t::SRet: retval = mark_julia_slot(result, jlretty, NULL, tbaa_stack); break; case jl_returninfo_t::Union: { Value *box = ctx.builder.CreateExtractValue(call, 0); Value *tindex = ctx.builder.CreateExtractValue(call, 1); Value *derived = ctx.builder.CreateSelect( ctx.builder.CreateICmpEQ( ctx.builder.CreateAnd(tindex, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)), decay_derived(ctx.builder.CreateBitCast(argvals[0], T_pjlvalue)), decay_derived(box) ); retval = mark_julia_slot(derived, jlretty, tindex, tbaa_stack); retval.Vboxed = box; break; } case jl_returninfo_t::Ghosts: retval = mark_julia_slot(NULL, jlretty, call, tbaa_stack); break; } // see if inference has a different / better type for the call than the lambda if (inferred_retty != retval.typ) retval = update_julia_type(ctx, retval, inferred_retty); return retval; } static jl_cgval_t emit_call_specfun_boxed(jl_codectx_t &ctx, StringRef specFunctionObject, jl_cgval_t *argv, size_t nargs, jl_value_t *inferred_retty) { auto theFptr = cast<Function>(jl_Module->getOrInsertFunction(specFunctionObject, jl_func_sig) #if JL_LLVM_VERSION >= 90000 .getCallee() #endif ); add_return_attr(theFptr, Attribute::NonNull); theFptr->addFnAttr(Thunk); Value *ret = emit_jlcall(ctx, theFptr, nullptr, argv, nargs, JLCALL_F_CC); return mark_julia_type(ctx, ret, true, inferred_retty); } static jl_cgval_t emit_invoke(jl_codectx_t &ctx, jl_expr_t *ex, jl_value_t *rt) { jl_value_t **args = (jl_value_t**)jl_array_data(ex->args); size_t arglen = jl_array_dim0(ex->args); size_t nargs = arglen - 1; assert(arglen >= 2); jl_cgval_t lival = emit_expr(ctx, args[0]); jl_cgval_t *argv = (jl_cgval_t*)alloca(sizeof(jl_cgval_t) * nargs); for (size_t i = 0; i < nargs; ++i) { argv[i] = emit_expr(ctx, args[i + 1]); if (argv[i].typ == jl_bottom_type) return jl_cgval_t(); } bool handled = false; jl_cgval_t result; if (lival.constant) { jl_method_instance_t *mi = (jl_method_instance_t*)lival.constant; assert(jl_is_method_instance(mi)); if (mi == ctx.linfo) { // handle self-recursion specially jl_returninfo_t::CallingConv cc = jl_returninfo_t::CallingConv::Boxed; FunctionType *ft = ctx.f->getFunctionType(); StringRef protoname = ctx.f->getName(); if (ft == jl_func_sig) { result = emit_call_specfun_boxed(ctx, protoname, argv, nargs, rt); handled = true; } else if (ft != jl_func_sig_sparams) { unsigned return_roots = 0; result = emit_call_specfun_other(ctx, mi, ctx.rettype, protoname, argv, nargs, &cc, &return_roots, rt); handled = true; } } else { jl_value_t *ci = ctx.params->lookup(mi, ctx.world, ctx.world); // TODO: need to use the right pair world here jl_code_instance_t *codeinst = (jl_code_instance_t*)ci; if (ci != jl_nothing && codeinst->invoke != jl_fptr_sparam) { // check if we know we definitely can't handle this specptr if (codeinst->invoke == jl_fptr_const_return) { result = mark_julia_const(codeinst->rettype_const); handled = true; } else { bool specsig, needsparams; std::tie(specsig, needsparams) = uses_specsig(mi, codeinst->rettype, ctx.params->prefer_specsig); std::string name; StringRef protoname; bool need_to_emit = true; if (ctx.use_cache) { // optimization: emit the correct name immediately, if we know it // TODO: use `emitted` map here too to try to consolidate names? if (codeinst->specptr.fptr) { if (specsig ? codeinst->isspecsig : codeinst->invoke == jl_fptr_args) { protoname = jl_ExecutionEngine->getFunctionAtAddress((uintptr_t)codeinst->specptr.fptr, codeinst); need_to_emit = false; } } } if (need_to_emit) { raw_string_ostream(name) << (specsig ? "j_" : "j1_") << name_from_method_instance(mi) << "_" << globalUnique++; protoname = StringRef(name); } jl_returninfo_t::CallingConv cc = jl_returninfo_t::CallingConv::Boxed; unsigned return_roots = 0; if (specsig) result = emit_call_specfun_other(ctx, mi, codeinst->rettype, protoname, argv, nargs, &cc, &return_roots, rt); else result = emit_call_specfun_boxed(ctx, protoname, argv, nargs, rt); handled = true; if (need_to_emit) { Function *trampoline_decl = cast<Function>(jl_Module->getNamedValue(protoname)); ctx.call_targets.push_back(std::make_tuple(codeinst, cc, return_roots, trampoline_decl, specsig)); } } } } } if (!handled) { Value *r = emit_jlcall(ctx, jlinvoke_func, boxed(ctx, lival), argv, nargs, JLCALL_F2_CC); result = mark_julia_type(ctx, r, true, rt); } if (result.typ == jl_bottom_type) CreateTrap(ctx.builder); return result; } static jl_cgval_t emit_call(jl_codectx_t &ctx, jl_expr_t *ex, jl_value_t *rt) { jl_value_t **args = (jl_value_t**)jl_array_data(ex->args); size_t nargs = jl_array_dim0(ex->args); assert(nargs >= 1); jl_cgval_t f = emit_expr(ctx, args[0]); if (f.constant && jl_typeis(f.constant, jl_intrinsic_type)) { JL_I::intrinsic fi = (intrinsic)*(uint32_t*)jl_data_ptr(f.constant); return emit_intrinsic(ctx, fi, args, nargs - 1); } jl_value_t *context = ctx.params->generic_context == jl_nothing ? nullptr : ctx.params->generic_context; size_t n_generic_args = nargs + (context ? 1 : 0); jl_cgval_t *generic_argv = (jl_cgval_t*)alloca(sizeof(jl_cgval_t) * n_generic_args); jl_cgval_t *argv = generic_argv; if (context) { generic_argv[0] = mark_julia_const(context); argv = &generic_argv[1]; } argv[0] = f; for (size_t i = 1; i < nargs; ++i) { argv[i] = emit_expr(ctx, args[i]); if (argv[i].typ == jl_bottom_type) return jl_cgval_t(); // anything past here is unreachable } if (f.constant && jl_isa(f.constant, (jl_value_t*)jl_builtin_type)) { if (f.constant == jl_builtin_ifelse && nargs == 4) return emit_ifelse(ctx, argv[1], argv[2], argv[3], rt); jl_cgval_t result; bool handled = emit_builtin_call(ctx, &result, f.constant, argv, nargs - 1, rt, ex); if (handled) { return result; } // special case for known builtin not handled by emit_builtin_call auto it = builtin_func_map.find(jl_get_builtin_fptr(f.constant)); if (it != builtin_func_map.end()) { Value *ret = emit_jlcall(ctx, it->second, maybe_decay_untracked(V_null), &argv[1], nargs - 1, JLCALL_F_CC); return mark_julia_type(ctx, ret, true, rt); } } // emit function and arguments Value *callval = emit_jlcall(ctx, jlapplygeneric_func, nullptr, generic_argv, n_generic_args, JLCALL_F_CC); return mark_julia_type(ctx, callval, true, rt); } // --- accessing and assigning variables --- static void undef_var_error_ifnot(jl_codectx_t &ctx, Value *ok, jl_sym_t *name) { BasicBlock *err = BasicBlock::Create(jl_LLVMContext, "err", ctx.f); BasicBlock *ifok = BasicBlock::Create(jl_LLVMContext, "ok"); ctx.builder.CreateCondBr(ok, ifok, err); ctx.builder.SetInsertPoint(err); ctx.builder.CreateCall(prepare_call(jlundefvarerror_func), mark_callee_rooted(literal_pointer_val(ctx, (jl_value_t*)name))); ctx.builder.CreateUnreachable(); ctx.f->getBasicBlockList().push_back(ifok); ctx.builder.SetInsertPoint(ifok); } // returns a jl_ppvalue_t location for the global variable m.s // if the reference currently bound or assign == true, // pbnd will also be assigned with the binding address static Value *global_binding_pointer(jl_codectx_t &ctx, jl_module_t *m, jl_sym_t *s, jl_binding_t **pbnd, bool assign) { jl_binding_t *b = NULL; if (assign) { b = jl_get_binding_wr(m, s, 0); assert(b != NULL); if (b->owner != m) { char *msg; (void)asprintf(&msg, "cannot assign a value to variable %s.%s from module %s", jl_symbol_name(b->owner->name), jl_symbol_name(s), jl_symbol_name(m->name)); emit_error(ctx, msg); free(msg); } } else { b = jl_get_binding(m, s); if (b == NULL) { // var not found. switch to delayed lookup. Constant *initnul = V_null; GlobalVariable *bindinggv = new GlobalVariable(*ctx.f->getParent(), T_pjlvalue, false, GlobalVariable::PrivateLinkage, initnul); LoadInst *cachedval = ctx.builder.CreateAlignedLoad(T_pjlvalue, bindinggv, sizeof(void*)); cachedval->setOrdering(AtomicOrdering::Unordered); BasicBlock *have_val = BasicBlock::Create(jl_LLVMContext, "found"); BasicBlock *not_found = BasicBlock::Create(jl_LLVMContext, "notfound"); BasicBlock *currentbb = ctx.builder.GetInsertBlock(); ctx.builder.CreateCondBr(ctx.builder.CreateICmpNE(cachedval, initnul), have_val, not_found); ctx.f->getBasicBlockList().push_back(not_found); ctx.builder.SetInsertPoint(not_found); Value *bval = ctx.builder.CreateCall(prepare_call(jlgetbindingorerror_func), { literal_pointer_val(ctx, (jl_value_t*)m), literal_pointer_val(ctx, (jl_value_t*)s) }); ctx.builder.CreateAlignedStore(bval, bindinggv, sizeof(void*))->setOrdering(AtomicOrdering::Release); ctx.builder.CreateBr(have_val); ctx.f->getBasicBlockList().push_back(have_val); ctx.builder.SetInsertPoint(have_val); PHINode *p = ctx.builder.CreatePHI(T_pjlvalue, 2); p->addIncoming(cachedval, currentbb); p->addIncoming(bval, not_found); return julia_binding_gv(ctx, emit_bitcast(ctx, p, T_pprjlvalue)); } if (b->deprecated) cg_bdw(ctx, b); } if (pbnd) *pbnd = b; return julia_binding_gv(ctx, b); } static jl_cgval_t emit_checked_var(jl_codectx_t &ctx, Value *bp, jl_sym_t *name, bool isvol, MDNode *tbaa) { LoadInst *v = ctx.builder.CreateAlignedLoad(T_prjlvalue, bp, sizeof(void*)); if (isvol) v->setVolatile(true); v->setOrdering(AtomicOrdering::Unordered); if (tbaa) tbaa_decorate(tbaa, v); undef_var_error_ifnot(ctx, ctx.builder.CreateIsNotNull(v), name); return mark_julia_type(ctx, v, true, jl_any_type); } static jl_cgval_t emit_sparam(jl_codectx_t &ctx, size_t i) { if (jl_svec_len(ctx.linfo->sparam_vals) > 0) { jl_value_t *e = jl_svecref(ctx.linfo->sparam_vals, i); if (!jl_is_typevar(e)) { return mark_julia_const(e); } } assert(ctx.spvals_ptr != NULL); Value *bp = ctx.builder.CreateConstInBoundsGEP1_32( T_prjlvalue, ctx.spvals_ptr, i + sizeof(jl_svec_t) / sizeof(jl_value_t*)); Value *sp = tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_prjlvalue, bp, sizeof(void*))); Value *isnull = ctx.builder.CreateICmpNE(emit_typeof(ctx, sp), maybe_decay_untracked(literal_pointer_val(ctx, (jl_value_t*)jl_tvar_type))); jl_unionall_t *sparam = (jl_unionall_t*)ctx.linfo->def.method->sig; for (size_t j = 0; j < i; j++) { sparam = (jl_unionall_t*)sparam->body; assert(jl_is_unionall(sparam)); } undef_var_error_ifnot(ctx, isnull, sparam->var->name); return mark_julia_type(ctx, sp, true, jl_any_type); } static jl_cgval_t emit_global(jl_codectx_t &ctx, jl_sym_t *sym) { jl_binding_t *jbp = NULL; Value *bp = global_binding_pointer(ctx, ctx.module, sym, &jbp, false); assert(bp != NULL); if (jbp && jbp->value != NULL) { if (jbp->constp) return mark_julia_const(jbp->value); // double-check that a global variable is actually defined. this // can be a problem in parallel when a definition is missing on // one machine. LoadInst *v = ctx.builder.CreateAlignedLoad(T_prjlvalue, bp, sizeof(void*)); v->setOrdering(AtomicOrdering::Unordered); tbaa_decorate(tbaa_binding, v); return mark_julia_type(ctx, v, true, jl_any_type); } return emit_checked_var(ctx, bp, sym, false, tbaa_binding); } static jl_cgval_t emit_isdefined(jl_codectx_t &ctx, jl_value_t *sym) { Value *isnull = NULL; if (jl_is_slot(sym) || jl_is_argument(sym)) { size_t sl = jl_slot_number(sym) - 1; jl_varinfo_t &vi = ctx.slots[sl]; if (!vi.usedUndef) return mark_julia_const(jl_true); if (vi.boxroot == NULL || vi.pTIndex != NULL) { assert(vi.defFlag); isnull = ctx.builder.CreateAlignedLoad(T_int1, vi.defFlag, 1, vi.isVolatile); } if (vi.boxroot != NULL) { Value *boxed = ctx.builder.CreateAlignedLoad(T_prjlvalue, vi.boxroot, sizeof(void*), vi.isVolatile); Value *box_isnull = ctx.builder.CreateICmpNE(boxed, maybe_decay_untracked(V_null)); if (vi.pTIndex) { // value is either boxed in the stack slot, or unboxed in value // as indicated by testing (pTIndex & 0x80) Value *tindex = ctx.builder.CreateAlignedLoad(T_int8, vi.pTIndex, sizeof(void*), vi.isVolatile); Value *load_unbox = ctx.builder.CreateICmpEQ( ctx.builder.CreateAnd(tindex, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)); isnull = ctx.builder.CreateSelect(load_unbox, isnull, box_isnull); } else { isnull = box_isnull; } } } else if (jl_is_expr(sym)) { assert(((jl_expr_t*)sym)->head == static_parameter_sym && "malformed isdefined expression"); size_t i = jl_unbox_long(jl_exprarg(sym, 0)) - 1; if (jl_svec_len(ctx.linfo->sparam_vals) > 0) { jl_value_t *e = jl_svecref(ctx.linfo->sparam_vals, i); if (!jl_is_typevar(e)) { return mark_julia_const(jl_true); } } assert(ctx.spvals_ptr != NULL); Value *bp = ctx.builder.CreateConstInBoundsGEP1_32( T_prjlvalue, ctx.spvals_ptr, i + sizeof(jl_svec_t) / sizeof(jl_value_t*)); Value *sp = tbaa_decorate(tbaa_const, ctx.builder.CreateAlignedLoad(T_prjlvalue, bp, sizeof(void*))); isnull = ctx.builder.CreateICmpNE(emit_typeof(ctx, sp), maybe_decay_untracked(literal_pointer_val(ctx, (jl_value_t*)jl_tvar_type))); } else { jl_module_t *modu; jl_sym_t *name; if (jl_is_globalref(sym)) { modu = jl_globalref_mod(sym); name = jl_globalref_name(sym); } else { assert(jl_is_symbol(sym) && "malformed isdefined expression"); modu = ctx.module; name = (jl_sym_t*)sym; } jl_binding_t *bnd = jl_get_binding(modu, name); if (bnd) { if (bnd->value != NULL) return mark_julia_const(jl_true); Value *bp = julia_binding_gv(ctx, bnd); LoadInst *v = ctx.builder.CreateAlignedLoad(T_prjlvalue, bp, sizeof(void*)); tbaa_decorate(tbaa_binding, v); v->setOrdering(AtomicOrdering::Unordered); isnull = ctx.builder.CreateICmpNE(v, maybe_decay_untracked(V_null)); } else { Value *v = ctx.builder.CreateCall(prepare_call(jlboundp_func), { literal_pointer_val(ctx, (jl_value_t*)modu), literal_pointer_val(ctx, (jl_value_t*)name) }); isnull = ctx.builder.CreateICmpNE(v, ConstantInt::get(T_int32, 0)); } } return mark_julia_type(ctx, isnull, false, jl_bool_type); } static jl_cgval_t emit_varinfo(jl_codectx_t &ctx, jl_varinfo_t &vi, jl_sym_t *varname, jl_value_t *better_typ=NULL) { jl_value_t *typ = better_typ ? better_typ : vi.value.typ; jl_cgval_t v; Value *isnull = NULL; if (vi.boxroot == NULL || vi.pTIndex != NULL) { if ((!vi.isVolatile && vi.isSA) || vi.isArgument || vi.value.constant || !vi.value.V) { v = vi.value; if (vi.pTIndex) v.TIndex = ctx.builder.CreateAlignedLoad(T_int8, vi.pTIndex, 1); } else { // copy value to a non-mutable (non-volatile SSA) location AllocaInst *varslot = cast<AllocaInst>(vi.value.V); Type *T = varslot->getAllocatedType(); assert(!varslot->isArrayAllocation() && "variables not expected to be VLA"); AllocaInst *ssaslot = cast<AllocaInst>(varslot->clone()); ssaslot->insertAfter(varslot); if (vi.isVolatile) { Value *unbox = ctx.builder.CreateAlignedLoad(ssaslot->getAllocatedType(), varslot, varslot->getAlignment(), true); ctx.builder.CreateAlignedStore(unbox, ssaslot, ssaslot->getAlignment()); } else { const DataLayout &DL = jl_data_layout; uint64_t sz = DL.getTypeStoreSize(T); emit_memcpy(ctx, ssaslot, tbaa_stack, vi.value, sz, ssaslot->getAlignment()); } Value *tindex = NULL; if (vi.pTIndex) tindex = ctx.builder.CreateAlignedLoad(T_int8, vi.pTIndex, 1, vi.isVolatile); v = mark_julia_slot(ssaslot, vi.value.typ, tindex, tbaa_stack); } if (vi.boxroot == NULL) v = update_julia_type(ctx, v, typ); if (vi.usedUndef) { assert(vi.defFlag); isnull = ctx.builder.CreateAlignedLoad(T_int1, vi.defFlag, 1, vi.isVolatile); } } if (vi.boxroot != NULL) { Instruction *boxed = ctx.builder.CreateAlignedLoad(T_prjlvalue, vi.boxroot, sizeof(void*), vi.isVolatile); Value *box_isnull = NULL; if (vi.usedUndef) box_isnull = ctx.builder.CreateICmpNE(boxed, maybe_decay_untracked(V_null)); maybe_mark_load_dereferenceable(boxed, vi.usedUndef || vi.pTIndex, typ); if (vi.pTIndex) { // value is either boxed in the stack slot, or unboxed in value // as indicated by testing (pTIndex & 0x80) Value *load_unbox = ctx.builder.CreateICmpEQ( ctx.builder.CreateAnd(v.TIndex, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)); if (vi.usedUndef) isnull = ctx.builder.CreateSelect(load_unbox, isnull, box_isnull); if (v.V) { // v.V will be null if it is a union of all ghost values v.V = ctx.builder.CreateSelect(load_unbox, emit_bitcast(ctx, decay_derived(v.V), boxed->getType()), decay_derived(boxed)); } else v.V = boxed; v.Vboxed = boxed; v = update_julia_type(ctx, v, typ); } else { v = mark_julia_type(ctx, boxed, true, typ); if (vi.usedUndef) isnull = box_isnull; } } if (isnull) undef_var_error_ifnot(ctx, isnull, varname); return v; } static jl_cgval_t emit_local(jl_codectx_t &ctx, jl_value_t *slotload) { size_t sl = jl_slot_number(slotload) - 1; jl_varinfo_t &vi = ctx.slots[sl]; jl_sym_t *sym = slot_symbol(ctx, sl); jl_value_t *typ = NULL; if (jl_typeis(slotload, jl_typedslot_type)) { // use the better type from inference for this load typ = jl_typedslot_get_type(slotload); if (jl_is_typevar(typ)) typ = ((jl_tvar_t*)typ)->ub; } return emit_varinfo(ctx, vi, sym, typ); } static void emit_vi_assignment_unboxed(jl_codectx_t &ctx, jl_varinfo_t &vi, Value *isboxed, jl_cgval_t rval_info) { if (vi.usedUndef) store_def_flag(ctx, vi, true); if (!vi.value.constant) { // check that this is not a virtual store assert(vi.value.ispointer() || (vi.pTIndex && vi.value.V == NULL)); // store value if (vi.value.V == NULL) { // all ghost values in destination - nothing to copy or store } else if (rval_info.constant || !rval_info.ispointer()) { if (rval_info.isghost) { // all ghost values in source - nothing to copy or store } else { if (rval_info.typ != vi.value.typ && !vi.pTIndex && !rval_info.TIndex) { // isbits cast-on-assignment is invalid. this branch should be dead-code. CreateTrap(ctx.builder); } else { Value *dest = vi.value.V; if (vi.pTIndex) ctx.builder.CreateStore(UndefValue::get(cast<AllocaInst>(vi.value.V)->getAllocatedType()), vi.value.V); Type *store_ty = julia_type_to_llvm(ctx, rval_info.constant ? jl_typeof(rval_info.constant) : rval_info.typ); Type *dest_ty = store_ty->getPointerTo(); if (dest_ty != dest->getType()) dest = emit_bitcast(ctx, dest, dest_ty); tbaa_decorate(tbaa_stack, ctx.builder.CreateStore( emit_unbox(ctx, store_ty, rval_info, rval_info.typ), dest, vi.isVolatile)); } } } else { if (vi.pTIndex == NULL) { assert(jl_is_concrete_type(vi.value.typ)); // Sometimes we can get into situations where the LHS and RHS // are the same slot. We're not allowed to memcpy in that case // due to LLVM bugs. // This check should probably mostly catch the relevant situations. if (vi.value.V != rval_info.V) { Value *copy_bytes = ConstantInt::get(T_int32, jl_datatype_size(vi.value.typ)); emit_memcpy(ctx, vi.value.V, tbaa_stack, rval_info, copy_bytes, julia_alignment(rval_info.typ), vi.isVolatile); } } else { emit_unionmove(ctx, vi.value.V, tbaa_stack, rval_info, isboxed, vi.isVolatile); } } } else { assert(vi.pTIndex == NULL); } } static void emit_phinode_assign(jl_codectx_t &ctx, ssize_t idx, jl_value_t *r) { jl_value_t *ssavalue_types = (jl_value_t*)ctx.source->ssavaluetypes; assert(jl_is_array(ssavalue_types)); jl_array_t *edges = (jl_array_t*)jl_fieldref_noalloc(r, 0); jl_value_t *phiType = jl_array_ptr_ref(ssavalue_types, idx); BasicBlock *BB = ctx.builder.GetInsertBlock(); auto InsertPt = BB->getFirstInsertionPt(); if (phiType == jl_bottom_type) { return; } AllocaInst *dest = nullptr; // N.B.: For any memory space, used as a phi, // we need to emit space twice here. The reason for this is that // phi nodes may be arguments of other phi nodes, so if we don't // have two buffers, one may be overwritten before its value is // used. Hopefully LLVM will be able to fold this back where legal. if (jl_is_uniontype(phiType)) { bool allunbox; size_t min_align, nbytes; dest = try_emit_union_alloca(ctx, ((jl_uniontype_t*)phiType), allunbox, min_align, nbytes); if (dest) { Instruction *phi = dest->clone(); phi->insertAfter(dest); PHINode *Tindex_phi = PHINode::Create(T_int8, jl_array_len(edges), "tindex_phi"); BB->getInstList().insert(InsertPt, Tindex_phi); PHINode *ptr_phi = PHINode::Create(T_prjlvalue, jl_array_len(edges), "ptr_phi"); BB->getInstList().insert(InsertPt, ptr_phi); Value *isboxed = ctx.builder.CreateICmpNE( ctx.builder.CreateAnd(Tindex_phi, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)); #if JL_LLVM_VERSION >= 100000 ctx.builder.CreateMemCpy(phi, MaybeAlign(min_align), dest, MaybeAlign(0), nbytes, false); #else ctx.builder.CreateMemCpy(phi, min_align, dest, 0, nbytes, false); #endif ctx.builder.CreateLifetimeEnd(dest); Value *ptr = ctx.builder.CreateSelect(isboxed, maybe_bitcast(ctx, decay_derived(ptr_phi), T_pint8), maybe_bitcast(ctx, decay_derived(phi), T_pint8)); jl_cgval_t val = mark_julia_slot(ptr, phiType, Tindex_phi, tbaa_stack); // XXX: this TBAA is wrong for ptr_phi val.Vboxed = ptr_phi; ctx.PhiNodes.push_back(std::make_tuple(val, BB, dest, ptr_phi, r)); ctx.SAvalues.at(idx) = val; ctx.ssavalue_assigned.at(idx) = true; return; } else if (allunbox) { PHINode *Tindex_phi = PHINode::Create(T_int8, jl_array_len(edges), "tindex_phi"); BB->getInstList().insert(InsertPt, Tindex_phi); jl_cgval_t val = mark_julia_slot(NULL, phiType, Tindex_phi, tbaa_stack); ctx.PhiNodes.push_back(std::make_tuple(val, BB, dest, (PHINode*)NULL, r)); ctx.SAvalues.at(idx) = val; ctx.ssavalue_assigned.at(idx) = true; return; } } bool isboxed = !deserves_stack(phiType); Type *vtype = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, phiType); // The frontend should really not emit this, but we allow it // for convenience. if (type_is_ghost(vtype)) { assert(jl_is_datatype(phiType) && ((jl_datatype_t*)phiType)->instance); // Skip adding it to the PhiNodes list, since we didn't create one. ctx.SAvalues.at(idx) = mark_julia_const(((jl_datatype_t*)phiType)->instance); ctx.ssavalue_assigned.at(idx) = true; return; } jl_cgval_t slot; PHINode *value_phi = NULL; if (vtype->isAggregateType() && CountTrackedPointers(vtype).count == 0) { // the value will be moved into dest in the predecessor critical block. // here it's moved into phi in the successor (from dest) dest = emit_static_alloca(ctx, vtype); Value *phi = emit_static_alloca(ctx, vtype); #if JL_LLVM_VERSION >= 100000 ctx.builder.CreateMemCpy(phi, MaybeAlign(julia_alignment(phiType)), dest, MaybeAlign(0), jl_datatype_size(phiType), false); #else ctx.builder.CreateMemCpy(phi, julia_alignment(phiType), dest, 0, jl_datatype_size(phiType), false); #endif ctx.builder.CreateLifetimeEnd(dest); slot = mark_julia_slot(phi, phiType, NULL, tbaa_stack); } else { value_phi = PHINode::Create(vtype, jl_array_len(edges), "value_phi"); BB->getInstList().insert(InsertPt, value_phi); slot = mark_julia_type(ctx, value_phi, isboxed, phiType); } ctx.PhiNodes.push_back(std::make_tuple(slot, BB, dest, value_phi, r)); ctx.SAvalues.at(idx) = slot; ctx.ssavalue_assigned.at(idx) = true; return; } static void emit_ssaval_assign(jl_codectx_t &ctx, ssize_t idx, jl_value_t *r) { assert(!ctx.ssavalue_assigned.at(idx)); if (jl_is_phinode(r)) { return emit_phinode_assign(ctx, idx, r); } jl_cgval_t slot; if (jl_is_phicnode(r)) { jl_varinfo_t &vi = ctx.phic_slots[idx]; slot = emit_varinfo(ctx, vi, jl_symbol("phic")); } else { slot = emit_expr(ctx, r, idx); // slot could be a jl_value_t (unboxed) or jl_value_t* (ispointer) } if (slot.isboxed || slot.TIndex) { // see if inference suggested a different type for the ssavalue than the expression // e.g. sometimes the information is inconsistent after inlining getfield on a Tuple jl_value_t *ssavalue_types = (jl_value_t*)ctx.source->ssavaluetypes; if (jl_is_array(ssavalue_types)) { jl_value_t *declType = jl_array_ptr_ref(ssavalue_types, idx); if (declType != slot.typ) { slot = update_julia_type(ctx, slot, declType); } } } ctx.SAvalues.at(idx) = slot; // now SAvalues[idx] contains the SAvalue ctx.ssavalue_assigned.at(idx) = true; } static void emit_varinfo_assign(jl_codectx_t &ctx, jl_varinfo_t &vi, jl_cgval_t rval_info, jl_value_t *l=NULL) { if (!vi.used) return; // convert rval-type to lval-type jl_value_t *slot_type = vi.value.typ; rval_info = convert_julia_type(ctx, rval_info, slot_type); if (rval_info.typ == jl_bottom_type) return; // compute / store tindex info if (vi.pTIndex) { Value *tindex; if (rval_info.TIndex) { tindex = rval_info.TIndex; if (!vi.boxroot) tindex = ctx.builder.CreateAnd(tindex, ConstantInt::get(T_int8, 0x7f)); } else { assert(rval_info.isboxed || rval_info.constant); tindex = compute_tindex_unboxed(ctx, rval_info, vi.value.typ); if (vi.boxroot) tindex = ctx.builder.CreateOr(tindex, ConstantInt::get(T_int8, 0x80)); else rval_info.TIndex = tindex; } ctx.builder.CreateStore(tindex, vi.pTIndex, vi.isVolatile); } // store boxed variables Value *isboxed = NULL; if (vi.boxroot) { Value *rval; if (vi.pTIndex && rval_info.TIndex) { ctx.builder.CreateStore(rval_info.TIndex, vi.pTIndex, vi.isVolatile); isboxed = ctx.builder.CreateICmpNE( ctx.builder.CreateAnd(rval_info.TIndex, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)); rval = maybe_decay_untracked(rval_info.Vboxed ? rval_info.Vboxed : V_null); assert(!vi.value.constant); } else { assert(!vi.pTIndex || rval_info.isboxed || rval_info.constant); rval = maybe_decay_untracked(boxed(ctx, rval_info)); } ctx.builder.CreateStore(maybe_decay_untracked(rval), vi.boxroot, vi.isVolatile); } // store unboxed variables if (!vi.boxroot || (vi.pTIndex && rval_info.TIndex)) { emit_vi_assignment_unboxed(ctx, vi, isboxed, rval_info); } } static void emit_assignment(jl_codectx_t &ctx, jl_value_t *l, jl_value_t *r, ssize_t ssaval) { assert(!jl_is_ssavalue(l)); jl_sym_t *s = NULL; jl_binding_t *bnd = NULL; Value *bp = NULL; if (jl_is_symbol(l)) s = (jl_sym_t*)l; else if (jl_is_globalref(l)) bp = global_binding_pointer(ctx, jl_globalref_mod(l), jl_globalref_name(l), &bnd, true); // now bp != NULL else assert(jl_is_slot(l)); if (bp == NULL && s != NULL) bp = global_binding_pointer(ctx, ctx.module, s, &bnd, true); if (bp != NULL) { // it's a global assert(bnd); Value *rval = mark_callee_rooted(boxed(ctx, emit_expr(ctx, r, ssaval))); ctx.builder.CreateCall(prepare_call(jlcheckassign_func), { literal_pointer_val(ctx, bnd), rval }); // Global variable. Does not need debug info because the debugger knows about // its memory location. return; } int sl = jl_slot_number(l) - 1; // it's a local variable jl_varinfo_t &vi = ctx.slots[sl]; jl_cgval_t rval_info = emit_expr(ctx, r, ssaval); emit_varinfo_assign(ctx, vi, rval_info, l); } // --- convert expression to code --- static jl_cgval_t emit_cfunction(jl_codectx_t &ctx, jl_value_t *output_type, const jl_cgval_t &fexpr, jl_value_t *rt, jl_svec_t *argt); static Value *emit_condition(jl_codectx_t &ctx, const jl_cgval_t &condV, const std::string &msg) { bool isbool = (condV.typ == (jl_value_t*)jl_bool_type); if (!isbool) { if (condV.TIndex) { // check whether this might be bool isbool = jl_subtype((jl_value_t*)jl_bool_type, condV.typ); } emit_typecheck(ctx, condV, (jl_value_t*)jl_bool_type, msg); } if (isbool) { Value *cond = emit_unbox(ctx, T_int8, condV, (jl_value_t*)jl_bool_type); assert(cond->getType() == T_int8); return ctx.builder.CreateXor(ctx.builder.CreateTrunc(cond, T_int1), ConstantInt::get(T_int1, 1)); } if (condV.isboxed) { return ctx.builder.CreateICmpEQ(boxed(ctx, condV), maybe_decay_untracked(literal_pointer_val(ctx, jl_false))); } // not a boolean return ConstantInt::get(T_int1, 0); // TODO: replace with Undef } static Value *emit_condition(jl_codectx_t &ctx, jl_value_t *cond, const std::string &msg) { return emit_condition(ctx, emit_expr(ctx, cond), msg); } static void emit_stmtpos(jl_codectx_t &ctx, jl_value_t *expr, int ssaval_result) { if (jl_is_ssavalue(expr) && ssaval_result == -1) return; // value not used, no point in attempting codegen for it if (jl_is_slot(expr) && ssaval_result == -1) { size_t sl = jl_slot_number(expr) - 1; jl_varinfo_t &vi = ctx.slots[sl]; if (vi.usedUndef) (void)emit_expr(ctx, expr); return; } if (jl_is_argument(expr) && ssaval_result == -1) { return; } if (jl_is_newvarnode(expr)) { jl_value_t *var = jl_fieldref(expr, 0); assert(jl_is_slot(var)); jl_varinfo_t &vi = ctx.slots[jl_slot_number(var)-1]; if (vi.usedUndef) { // create a new uninitialized variable Value *lv = vi.boxroot; if (lv != NULL) ctx.builder.CreateStore(maybe_decay_untracked(V_null), lv); if (lv == NULL || vi.pTIndex != NULL) store_def_flag(ctx, vi, false); } return; } if (!jl_is_expr(expr)) { assert(ssaval_result != -1); emit_ssaval_assign(ctx, ssaval_result, expr); return; } jl_expr_t *ex = (jl_expr_t*)expr; jl_value_t **args = (jl_value_t**)jl_array_data(ex->args); jl_sym_t *head = ex->head; if (head == meta_sym || head == inbounds_sym || head == coverageeffect_sym || head == aliasscope_sym || head == popaliasscope_sym) { // some expression types are metadata and can be ignored // in statement position return; } else if (head == leave_sym) { assert(jl_is_long(args[0])); ctx.builder.CreateCall(prepare_call(jlleave_func), ConstantInt::get(T_int32, jl_unbox_long(args[0]))); } else if (head == pop_exception_sym) { jl_cgval_t excstack_state = emit_expr(ctx, jl_exprarg(expr, 0)); assert(excstack_state.V && excstack_state.V->getType() == T_size); ctx.builder.CreateCall(prepare_call(jl_restore_excstack_func), excstack_state.V); return; } else { if (!jl_is_method(ctx.linfo->def.method)) { // TODO: inference is invalid if this has any effect (which it often does) Value *world = ctx.builder.CreateAlignedLoad(prepare_global_in(jl_Module, jlgetworld_global), sizeof(size_t)); // TODO: world->setOrdering(AtomicOrdering::Monotonic); ctx.builder.CreateAlignedStore(world, ctx.world_age_field, sizeof(size_t)); } assert(ssaval_result != -1); emit_ssaval_assign(ctx, ssaval_result, expr); } } // `expr` is not clobbered in JL_TRY JL_GCC_IGNORE_START("-Wclobbered") static jl_cgval_t emit_expr(jl_codectx_t &ctx, jl_value_t *expr, ssize_t ssaval) { if (jl_is_symbol(expr)) { jl_sym_t *sym = (jl_sym_t*)expr; return emit_global(ctx, sym); } if (jl_is_slot(expr) || jl_is_argument(expr)) { return emit_local(ctx, expr); } if (jl_is_ssavalue(expr)) { ssize_t idx = ((jl_ssavalue_t*)expr)->id - 1; assert(idx >= 0); if (!ctx.ssavalue_assigned.at(idx)) { ctx.ssavalue_assigned.at(idx) = true; // (assignment, not comparison test) return jl_cgval_t(); // dead code branch } else { return ctx.SAvalues.at(idx); // at this point, SAvalues[idx] actually contains the SAvalue } } if (jl_is_globalref(expr)) { return emit_globalref(ctx, jl_globalref_mod(expr), jl_globalref_name(expr)); } if (jl_is_linenode(expr)) { jl_error("LineNumberNode in value position"); } if (jl_is_gotonode(expr)) { jl_error("GotoNode in value position"); } if (jl_is_gotoifnot(expr)) { jl_error("GotoIfNot in value position"); } if (jl_is_pinode(expr)) { return convert_julia_type(ctx, emit_expr(ctx, jl_fieldref_noalloc(expr, 0)), jl_fieldref_noalloc(expr, 1)); } if (!jl_is_expr(expr)) { int needroot = true; if (jl_is_quotenode(expr)) { expr = jl_fieldref_noalloc(expr,0); } // numeric literals if (jl_is_int32(expr)) { int32_t val = jl_unbox_int32(expr); if ((uint32_t)(val+512) < 1024) { // this can be gotten from the box cache needroot = false; expr = jl_box_int32(val); } } else if (jl_is_int64(expr)) { uint64_t val = jl_unbox_uint64(expr); if ((uint64_t)(val+512) < 1024) { // this can be gotten from the box cache needroot = false; expr = jl_box_int64(val); } } else if (jl_is_uint8(expr)) { expr = jl_box_uint8(jl_unbox_uint8(expr)); needroot = false; } if (needroot && jl_is_method(ctx.linfo->def.method)) { // toplevel exprs and some integers are already rooted jl_add_method_root(ctx, expr); } return mark_julia_const(expr); } jl_expr_t *ex = (jl_expr_t*)expr; jl_value_t **args = (jl_value_t**)jl_array_data(ex->args); jl_sym_t *head = ex->head; // this is object-disoriented. // however, this is a good way to do it because it should *not* be easy // to add new node types. if (head == isdefined_sym) { return emit_isdefined(ctx, args[0]); } else if (head == throw_undef_if_not_sym) { jl_sym_t *var = (jl_sym_t*)args[0]; Value *cond = ctx.builder.CreateTrunc(emit_unbox(ctx, T_int8, emit_expr(ctx, args[1]), (jl_value_t*)jl_bool_type), T_int1); if (var == getfield_undefref_sym) { raise_exception_unless(ctx, cond, literal_pointer_val(ctx, jl_undefref_exception)); } else { undef_var_error_ifnot(ctx, cond, var); } return ghostValue(jl_nothing_type); } else if (head == invoke_sym) { assert(ssaval >= 0); jl_value_t *expr_t = jl_is_long(ctx.source->ssavaluetypes) ? (jl_value_t*)jl_any_type : jl_array_ptr_ref(ctx.source->ssavaluetypes, ssaval); return emit_invoke(ctx, ex, expr_t); } else if (head == call_sym) { jl_value_t *expr_t; if (ssaval < 0) // TODO: this case is needed for the call to emit_expr in emit_llvmcall expr_t = (jl_value_t*)jl_any_type; else expr_t = jl_is_long(ctx.source->ssavaluetypes) ? (jl_value_t*)jl_any_type : jl_array_ptr_ref(ctx.source->ssavaluetypes, ssaval); jl_cgval_t res = emit_call(ctx, ex, expr_t); // some intrinsics (e.g. typeassert) can return a wider type // than what's actually possible res = update_julia_type(ctx, res, expr_t); if (res.typ == jl_bottom_type || expr_t == jl_bottom_type) { CreateTrap(ctx.builder); } return res; } else if (head == foreigncall_sym) { return emit_ccall(ctx, args, jl_array_dim0(ex->args)); } else if (head == cfunction_sym) { jl_cgval_t fexpr_rt = emit_expr(ctx, args[1]); return emit_cfunction(ctx, args[0], fexpr_rt, args[2], (jl_svec_t*)args[3]); } else if (head == assign_sym) { emit_assignment(ctx, args[0], args[1], ssaval); return ghostValue(jl_nothing_type); } else if (head == static_parameter_sym) { return emit_sparam(ctx, jl_unbox_long(args[0]) - 1); } else if (head == method_sym) { jl_value_t *mn = args[0]; assert(jl_expr_nargs(ex) != 1 || jl_is_symbol(mn) || jl_is_slot(mn)); Value *bp = NULL, *name, *bp_owner = V_null; jl_binding_t *bnd = NULL; bool issym = jl_is_symbol(mn); bool isglobalref = !issym && jl_is_globalref(mn); jl_module_t *mod = ctx.module; if (issym || isglobalref) { if (isglobalref) { mod = jl_globalref_mod(mn); mn = (jl_value_t*)jl_globalref_name(mn); } JL_TRY { if (jl_symbol_name((jl_sym_t*)mn)[0] == '@') jl_errorf("macro definition not allowed inside a local scope"); name = literal_pointer_val(ctx, mn); bnd = jl_get_binding_for_method_def(mod, (jl_sym_t*)mn); } JL_CATCH { jl_value_t *e = jl_current_exception(); // errors. boo. root it somehow :( bnd = jl_get_binding_wr(ctx.module, (jl_sym_t*)jl_gensym(), 1); bnd->value = e; bnd->constp = 1; raise_exception(ctx, literal_pointer_val(ctx, e)); return ghostValue(jl_nothing_type); } bp = julia_binding_gv(ctx, bnd); bp_owner = literal_pointer_val(ctx, (jl_value_t*)mod); } else if (jl_is_slot(mn) || jl_is_argument(mn)) { int sl = jl_slot_number(mn)-1; jl_varinfo_t &vi = ctx.slots[sl]; bp = vi.boxroot; name = literal_pointer_val(ctx, (jl_value_t*)slot_symbol(ctx, sl)); } if (bp) { Value *mdargs[5] = { name, literal_pointer_val(ctx, (jl_value_t*)mod), bp, bp_owner, literal_pointer_val(ctx, bnd) }; jl_cgval_t gf = mark_julia_type( ctx, ctx.builder.CreateCall(prepare_call(jlgenericfunction_func), makeArrayRef(mdargs)), true, jl_function_type); if (jl_expr_nargs(ex) == 1) return gf; } Value *a1 = boxed(ctx, emit_expr(ctx, args[1])); Value *a2 = boxed(ctx, emit_expr(ctx, args[2])); Value *mdargs[3] = { /*argdata*/a1, /*code*/a2, /*module*/literal_pointer_val(ctx, (jl_value_t*)ctx.module) }; ctx.builder.CreateCall(prepare_call(jlmethod_func), makeArrayRef(mdargs)); return ghostValue(jl_nothing_type); } else if (head == const_sym) { jl_sym_t *sym = (jl_sym_t*)args[0]; jl_module_t *mod = ctx.module; if (jl_is_globalref(sym)) { mod = jl_globalref_mod(sym); sym = jl_globalref_name(sym); } if (jl_is_symbol(sym)) { jl_binding_t *bnd = NULL; (void)global_binding_pointer(ctx, mod, sym, &bnd, true); assert(bnd); ctx.builder.CreateCall(prepare_call(jldeclareconst_func), literal_pointer_val(ctx, bnd)); } } else if (head == new_sym) { size_t nargs = jl_array_len(ex->args); jl_cgval_t *argv = (jl_cgval_t*)alloca(sizeof(jl_cgval_t) * nargs); for (size_t i = 0; i < nargs; ++i) { argv[i] = emit_expr(ctx, args[i]); } jl_value_t *ty = argv[0].typ; if (jl_is_type_type(ty) && jl_is_datatype(jl_tparam0(ty)) && jl_is_concrete_type(jl_tparam0(ty))) { assert(nargs <= jl_datatype_nfields(jl_tparam0(ty)) + 1); return emit_new_struct(ctx, jl_tparam0(ty), nargs - 1, &argv[1]); } Value *val = emit_jlcall(ctx, jlnew_func, nullptr, argv, nargs, JLCALL_F_CC); // temporarily mark as `Any`, expecting `emit_ssaval_assign` to update // it to the inferred type. return mark_julia_type(ctx, val, true, (jl_value_t*)jl_any_type); } else if (head == splatnew_sym) { jl_cgval_t argv[2]; argv[0] = emit_expr(ctx, args[0]); argv[1] = emit_expr(ctx, args[1]); Value *typ = boxed(ctx, argv[0]); Value *tup = boxed(ctx, argv[1]); Value *val = ctx.builder.CreateCall(prepare_call(jlsplatnew_func), { typ, tup }); // temporarily mark as `Any`, expecting `emit_ssaval_assign` to update // it to the inferred type. return mark_julia_type(ctx, val, true, (jl_value_t*)jl_any_type); } else if (head == exc_sym) { return mark_julia_type(ctx, ctx.builder.CreateCall(prepare_call(jl_current_exception_func)), true, jl_any_type); } else if (head == copyast_sym) { jl_cgval_t ast = emit_expr(ctx, args[0]); if (ast.typ != (jl_value_t*)jl_expr_type && ast.typ != (jl_value_t*)jl_any_type) { // elide call to jl_copy_ast when possible return ast; } return mark_julia_type(ctx, ctx.builder.CreateCall(prepare_call(jlcopyast_func), maybe_decay_untracked(boxed(ctx, ast))), true, jl_expr_type); } else if (head == loopinfo_sym) { // parse Expr(:loopinfo, "julia.simdloop", ("llvm.loop.vectorize.width", 4)) SmallVector<Metadata *, 8> MDs; for (int i = 0, ie = jl_expr_nargs(ex); i < ie; ++i) { Metadata *MD = to_md_tree(args[i]); if (MD) MDs.push_back(MD); } MDNode* MD = MDNode::get(jl_LLVMContext, MDs); CallInst *I = ctx.builder.CreateCall(prepare_call(jl_loopinfo_marker_func)); I->setMetadata("julia.loopinfo", MD); return jl_cgval_t(); } else if (head == leave_sym || head == coverageeffect_sym || head == pop_exception_sym || head == enter_sym || head == inbounds_sym || head == aliasscope_sym || head == popaliasscope_sym) { jl_errorf("Expr(:%s) in value position", jl_symbol_name(head)); } else if (head == boundscheck_sym) { return mark_julia_const(bounds_check_enabled(ctx, jl_true) ? jl_true : jl_false); } else if (head == gc_preserve_begin_sym) { size_t nargs = jl_array_len(ex->args); jl_cgval_t *argv = (jl_cgval_t*)alloca(sizeof(jl_cgval_t) * nargs); for (size_t i = 0; i < nargs; ++i) { argv[i] = emit_expr(ctx, args[i]); } std::vector<Value*> vals; for (size_t i = 0; i < nargs; ++i) { const jl_cgval_t &ai = argv[i]; if (ai.constant || ai.typ == jl_bottom_type) continue; if (ai.isboxed) { vals.push_back(ai.Vboxed); } else if (!jl_is_pointerfree(ai.typ)) { Type *at = julia_type_to_llvm(ctx, ai.typ); vals.push_back(emit_unbox(ctx, at, ai, ai.typ)); } } Value *token = vals.empty() ? (Value*)ConstantTokenNone::get(jl_LLVMContext) : ctx.builder.CreateCall(prepare_call(gc_preserve_begin_func), vals); jl_cgval_t tok(token, NULL, false, (jl_value_t*)jl_nothing_type, NULL); return tok; } else if (head == gc_preserve_end_sym) { // We only support ssa values as the argument. Everything else will // fall back to the default behavior of preserving the argument value // until the end of the scope, which is correct, but not optimal. if (!jl_is_ssavalue(args[0])) { return jl_cgval_t((jl_value_t*)jl_nothing_type); } jl_cgval_t token = emit_expr(ctx, args[0]); assert(token.V->getType()->isTokenTy()); if (!isa<ConstantTokenNone>(token.V)) ctx.builder.CreateCall(prepare_call(gc_preserve_end_func), {token.V}); return jl_cgval_t((jl_value_t*)jl_nothing_type); } else { if (jl_is_toplevel_only_expr(expr) && !jl_is_method(ctx.linfo->def.method)) { // call interpreter to run a toplevel expr from inside a // compiled toplevel thunk. Value *args[2] = { literal_pointer_val(ctx, (jl_value_t*)ctx.module), literal_pointer_val(ctx, expr) }; ctx.builder.CreateCall(prepare_call(jltopeval_func), args); return ghostValue(jl_nothing_type); } jl_errorf("unsupported or misplaced expression \"%s\" in function %s", jl_symbol_name(head), ctx.name); } return jl_cgval_t(); } JL_GCC_IGNORE_STOP // --- generate function bodies --- // gc frame emission static void allocate_gc_frame(jl_codectx_t &ctx, BasicBlock *b0) { // TODO: requires the runtime, but is generated unconditionally // allocate a placeholder gc instruction ctx.ptlsStates = ctx.builder.CreateCall(prepare_call(jltls_states_func)); int nthfield = offsetof(jl_tls_states_t, safepoint) / sizeof(void*); ctx.signalPage = emit_nthptr_recast(ctx, ctx.ptlsStates, nthfield, tbaa_const, PointerType::get(T_psize, 0)); } static void emit_last_age_field(jl_codectx_t &ctx) { ctx.world_age_field = ctx.builder.CreateInBoundsGEP( ctx.builder.CreateBitCast(ctx.ptlsStates, T_psize), ConstantInt::get(T_size, offsetof(jl_tls_states_t, world_age) / sizeof(size_t))); } static Function *emit_tojlinvoke(jl_code_instance_t *codeinst, Module *M, jl_codegen_params_t &params) { jl_codectx_t ctx(jl_LLVMContext, params); std::string name; raw_string_ostream(name) << "tojlinvoke" << globalUnique++; Function *f = Function::Create(jl_func_sig, GlobalVariable::PrivateLinkage, name, M); jl_init_function(f); f->addFnAttr(Thunk); //f->setAlwaysInline(); ctx.f = f; // for jl_Module BasicBlock *b0 = BasicBlock::Create(jl_LLVMContext, "top", f); ctx.builder.SetInsertPoint(b0); Function *theFunc; Value *theFarg; if (codeinst->invoke != NULL) { StringRef theFptrName = jl_ExecutionEngine->getFunctionAtAddress((uintptr_t)codeinst->invoke, codeinst); theFunc = cast<Function>(M->getOrInsertFunction(theFptrName, jlinvoke_func->_type(jl_LLVMContext)) #if JL_LLVM_VERSION >= 90000 .getCallee() #endif ); theFarg = literal_pointer_val(ctx, (jl_value_t*)codeinst); } else { theFunc = prepare_call(jlinvoke_func); theFarg = literal_pointer_val(ctx, (jl_value_t*)codeinst->def); } theFarg = maybe_decay_untracked(theFarg); auto args = f->arg_begin(); CallInst *r = ctx.builder.CreateCall(theFunc, { &*args, &*++args, &*++args, theFarg }); r->setAttributes(theFunc->getAttributes()); ctx.builder.CreateRet(r); return f; } static void emit_cfunc_invalidate( Function *gf_thunk, jl_returninfo_t::CallingConv cc, unsigned return_roots, jl_value_t *calltype, jl_value_t *rettype, size_t nargs, jl_codegen_params_t &params, Function *target) { jl_codectx_t ctx(jl_LLVMContext, params); ctx.f = gf_thunk; BasicBlock *b0 = BasicBlock::Create(jl_LLVMContext, "top", gf_thunk); ctx.builder.SetInsertPoint(b0); DebugLoc noDbg; ctx.builder.SetCurrentDebugLocation(noDbg); allocate_gc_frame(ctx, b0); Function::arg_iterator AI = gf_thunk->arg_begin(); jl_cgval_t *myargs = (jl_cgval_t*)alloca(sizeof(jl_cgval_t) * nargs); if (cc == jl_returninfo_t::SRet || cc == jl_returninfo_t::Union) ++AI; if (return_roots) ++AI; for (size_t i = 0; i < nargs; i++) { jl_value_t *jt = jl_nth_slot_type(calltype, i); bool isboxed = deserves_argbox(jt); Type *et = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, jt); if (is_uniquerep_Type(jt)) { myargs[i] = mark_julia_const(jl_tparam0(jt)); } else if (type_is_ghost(et)) { assert(jl_is_datatype(jt) && ((jl_datatype_t*)jt)->instance); myargs[i] = mark_julia_const(((jl_datatype_t*)jt)->instance); } else { Value *arg_v = &*AI; ++AI; Type *at = arg_v->getType(); if (!isboxed && et->isAggregateType()) { myargs[i] = mark_julia_slot(arg_v, jt, NULL, tbaa_const); } else { assert(at == et); myargs[i] = mark_julia_type(ctx, arg_v, isboxed, jt); } (void)at; } } assert(AI == gf_thunk->arg_end()); Value *gf_ret = emit_jlcall(ctx, target, nullptr, myargs, nargs, JLCALL_F_CC); jl_cgval_t gf_retbox = mark_julia_type(ctx, gf_ret, true, jl_any_type); if (cc != jl_returninfo_t::Boxed) { emit_typecheck(ctx, gf_retbox, rettype, "cfunction"); } switch (cc) { case jl_returninfo_t::Boxed: ctx.builder.CreateRet(gf_ret); break; case jl_returninfo_t::Register: { Type *gfrt = gf_thunk->getReturnType(); if (gfrt->isVoidTy()) { ctx.builder.CreateRetVoid(); } else { gf_ret = emit_bitcast(ctx, gf_ret, gfrt->getPointerTo()); ctx.builder.CreateRet(ctx.builder.CreateAlignedLoad(gf_ret, julia_alignment(rettype))); } break; } case jl_returninfo_t::SRet: { if (return_roots) ctx.builder.CreateStore(gf_ret, gf_thunk->arg_begin() + 1); emit_memcpy(ctx, &*gf_thunk->arg_begin(), nullptr, gf_ret, nullptr, jl_datatype_size(rettype), julia_alignment(rettype)); ctx.builder.CreateRetVoid(); break; } case jl_returninfo_t::Union: { Type *retty = gf_thunk->getReturnType(); Value *gf_retval = UndefValue::get(retty); Value *tindex = compute_box_tindex(ctx, emit_typeof_boxed(ctx, gf_retbox), (jl_value_t*)jl_any_type, rettype); tindex = ctx.builder.CreateOr(tindex, ConstantInt::get(T_int8, 0x80)); gf_retval = ctx.builder.CreateInsertValue(gf_retval, gf_ret, 0); gf_retval = ctx.builder.CreateInsertValue(gf_retval, tindex, 1); ctx.builder.CreateRet(gf_retval); break; } case jl_returninfo_t::Ghosts: { Value *gf_retval = compute_tindex_unboxed(ctx, gf_retbox, rettype); ctx.builder.CreateRet(gf_retval); break; } } } static void emit_cfunc_invalidate( Function *gf_thunk, jl_returninfo_t::CallingConv cc, unsigned return_roots, jl_value_t *calltype, jl_value_t *rettype, size_t nargs, jl_codegen_params_t &params) { emit_cfunc_invalidate(gf_thunk, cc, return_roots, calltype, rettype, nargs, params, prepare_call_in(gf_thunk->getParent(), jlapplygeneric_func)); } static Function* gen_cfun_wrapper( Module *into, jl_codegen_params_t &params, const function_sig_t &sig, jl_value_t *ff, const char *aliasname, jl_value_t *declrt, jl_method_instance_t *lam, jl_unionall_t *unionall_env, jl_svec_t *sparam_vals, jl_array_t **closure_types) { // Generate a c-callable wrapper assert(into); size_t nargs = sig.nccallargs; const char *name = "cfunction"; size_t world = jl_world_counter; jl_code_instance_t *codeinst = NULL; bool nest = (!ff || unionall_env); jl_value_t *astrt = (jl_value_t*)jl_any_type; void *callptr = NULL; int calltype = 0; if (aliasname) name = aliasname; else if (lam) name = jl_symbol_name(lam->def.method->name); if (lam && params.cache) { // TODO: this isn't ideal to be unconditionally calling type inference (and compile) from here codeinst = jl_compile_method_internal(lam, world); assert(codeinst->invoke); if (codeinst->invoke == jl_fptr_args) { callptr = codeinst->specptr.fptr; calltype = 1; } else if (codeinst->invoke == jl_fptr_const_return) { // don't need the fptr callptr = (void*)codeinst->rettype_const; calltype = 2; } else if (codeinst->isspecsig) { callptr = codeinst->specptr.fptr; calltype = 3; } astrt = codeinst->rettype; if (astrt != (jl_value_t*)jl_bottom_type && jl_type_intersection(astrt, declrt) == jl_bottom_type) { // Do not warn if the function never returns since it is // occasionally required by the C API (typically error callbacks) // even though we're likely to encounter memory errors in that case jl_printf(JL_STDERR, "WARNING: cfunction: return type of %s does not match\n", name); } } std::string funcName; raw_string_ostream(funcName) << "jlcapi_" << name << "_" << globalUnique++; Module *M = into; AttributeList attributes = sig.attributes; FunctionType *functype; if (nest) { // add nest parameter (pointer to jl_value_t* data array) after sret arg assert(closure_types); std::vector<Type*> fargt_sig(sig.fargt_sig); fargt_sig.insert(fargt_sig.begin() + sig.sret, T_pprjlvalue); functype = FunctionType::get(sig.sret ? T_void : sig.prt, fargt_sig, /*isVa*/false); attributes = attributes.addAttribute(jl_LLVMContext, 1 + sig.sret, Attribute::Nest); } else { functype = sig.functype(); } Function *cw = Function::Create(functype, GlobalVariable::ExternalLinkage, funcName, M); cw->setAttributes(attributes); jl_init_function(cw); jl_codectx_t ctx(jl_LLVMContext, params); ctx.f = cw; ctx.world = world; ctx.name = name; ctx.funcName = name; BasicBlock *b0 = BasicBlock::Create(jl_LLVMContext, "top", cw); ctx.builder.SetInsertPoint(b0); DebugLoc noDbg; ctx.builder.SetCurrentDebugLocation(noDbg); allocate_gc_frame(ctx, b0); emit_last_age_field(ctx); Value *dummy_world = ctx.builder.CreateAlloca(T_size); Value *have_tls = ctx.builder.CreateIsNotNull(ctx.ptlsStates); // TODO: in the future, try to initialize a full TLS context here // for now, just use a dummy field to avoid a branch in this function ctx.world_age_field = ctx.builder.CreateSelect(have_tls, ctx.world_age_field, dummy_world); Value *last_age = tbaa_decorate(tbaa_gcframe, ctx.builder.CreateAlignedLoad(ctx.world_age_field, sizeof(size_t))); Value *valid_tls = ctx.builder.CreateIsNotNull(last_age); have_tls = ctx.builder.CreateAnd(have_tls, valid_tls); ctx.world_age_field = ctx.builder.CreateSelect(valid_tls, ctx.world_age_field, dummy_world); Value *world_v = ctx.builder.CreateAlignedLoad(prepare_global_in(jl_Module, jlgetworld_global), sizeof(size_t)); // TODO: cast<LoadInst>(world_v)->setOrdering(AtomicOrdering::Monotonic); Value *age_ok = NULL; if (calltype) { LoadInst *lam_max = ctx.builder.CreateAlignedLoad( T_size, ctx.builder.CreateConstInBoundsGEP1_32( T_size, emit_bitcast(ctx, literal_pointer_val(ctx, (jl_value_t*)codeinst), T_psize), offsetof(jl_code_instance_t, max_world) / sizeof(size_t)), sizeof(size_t)); // XXX: age is always OK if we don't have a TLS. This is a hack required due to `@threadcall` abuse. // and adds quite a bit of complexity here, even though it's still wrong // (anything that tries to interact with the runtime will fault) age_ok = ctx.builder.CreateICmpUGE(lam_max, world_v); world_v = ctx.builder.CreateSelect(ctx.builder.CreateOr(have_tls, age_ok), world_v, lam_max); age_ok = ctx.builder.CreateOr(ctx.builder.CreateNot(have_tls), age_ok); } ctx.builder.CreateStore(world_v, ctx.world_age_field); // first emit code to record the arguments Function::arg_iterator AI = cw->arg_begin(); Value *sretPtr = sig.sret ? &*AI++ : NULL; Value *nestPtr = nest ? &*AI++ : NULL; jl_cgval_t *inputargs = (jl_cgval_t*)alloca(sizeof(jl_cgval_t) * (nargs + 1)); if (ff) { // we need to pass the function object even if (even though) it is a singleton inputargs[0] = mark_julia_const(ff); } else { assert(nest && nestPtr); Value *ff = ctx.builder.CreateAlignedLoad(T_prjlvalue, nestPtr, sizeof(void*)); inputargs[0] = mark_julia_type(ctx, ff, true, jl_any_type); } // XXX: these values may need to be rooted until the end of the function jl_value_t *rt1 = NULL; jl_value_t *rt2 = NULL; JL_GC_PUSH2(&rt1, &rt2); for (size_t i = 0; i < nargs; ++i, ++AI) { // figure out how to unpack this argument type Value *val = &*AI; assert(sig.fargt_sig.at(i + sig.sret) == val->getType()); jl_cgval_t &inputarg = inputargs[i + 1]; jl_value_t *jargty = jl_svecref(sig.at, i); bool aref = jl_is_abstract_ref_type(jargty); if (aref) // a pointer to a value jargty = jl_tparam0(jargty); // if we know the outer function sparams, try to fill those in now // so that the julia_to_native type checks are more likely to be doable (e.g. concrete types) at compile-time jl_value_t *jargty_proper = jargty; bool static_at = !(unionall_env && jl_has_typevar_from_unionall(jargty, unionall_env)); if (!static_at) { if (sparam_vals) { jargty_proper = rt1 = jl_instantiate_type_in_env(jargty, unionall_env, jl_svec_data(sparam_vals)); assert(jargty_proper != jargty); jargty = jargty_proper; static_at = true; } else { jargty_proper = rt1 = jl_rewrap_unionall(jargty, (jl_value_t*)unionall_env); } } if (aref) { if (jargty == (jl_value_t*)jl_any_type) { inputarg = mark_julia_type(ctx, ctx.builder.CreateAlignedLoad(T_prjlvalue, emit_bitcast(ctx, val, T_pprjlvalue), sizeof(void*)), true, jl_any_type); } else if (static_at && jl_is_concrete_immutable(jargty)) { // anything that could be stored unboxed bool isboxed; Type *T = julia_type_to_llvm(ctx, jargty, &isboxed); assert(!isboxed); // a T* (of unknown origin) if (type_is_ghost(T)) { inputarg = ghostValue(jargty); } else { val = emit_bitcast(ctx, val, T->getPointerTo()); val = ctx.builder.CreateAlignedLoad(val, 1); // make no alignment assumption about pointer from C inputarg = mark_julia_type(ctx, val, false, jargty); } } else if (static_at || (!jl_is_typevar(jargty) && !jl_is_immutable_datatype(jargty))) { // must be a jl_value_t* (because it's mutable or contains gc roots) inputarg = mark_julia_type(ctx, maybe_decay_untracked(emit_bitcast(ctx, val, T_prjlvalue)), true, jargty_proper); } else { // allocate val into a new box, if it might not be boxed // otherwise preserve / reuse the existing box identity // TODO: could inspect `jargty` and eliminate some of these cases if (!*closure_types) *closure_types = jl_alloc_vec_any(0); jl_array_ptr_1d_push(*closure_types, jargty); Value *runtime_dt = ctx.builder.CreateAlignedLoad(T_prjlvalue, ctx.builder.CreateConstGEP1_32(T_prjlvalue, nestPtr, jl_array_len(*closure_types)), sizeof(void*)); BasicBlock *boxedBB = BasicBlock::Create(jl_LLVMContext, "isboxed", cw); BasicBlock *loadBB = BasicBlock::Create(jl_LLVMContext, "need-load", cw); BasicBlock *unboxedBB = BasicBlock::Create(jl_LLVMContext, "maybe-unboxed", cw); BasicBlock *isanyBB = BasicBlock::Create(jl_LLVMContext, "any", cw); BasicBlock *afterBB = BasicBlock::Create(jl_LLVMContext, "after", cw); Value *isrtboxed = ctx.builder.CreateIsNull(val); ctx.builder.CreateCondBr(isrtboxed, boxedBB, loadBB); ctx.builder.SetInsertPoint(boxedBB); Value *p1 = ctx.builder.CreateBitCast(val, T_pjlvalue); p1 = maybe_decay_untracked(p1); ctx.builder.CreateBr(afterBB); ctx.builder.SetInsertPoint(loadBB); Value *isrtany = ctx.builder.CreateICmpEQ( literal_pointer_val(ctx, (jl_value_t*)jl_any_type), ctx.builder.CreateBitCast(val, T_pjlvalue)); ctx.builder.CreateCondBr(isrtany, isanyBB, unboxedBB); ctx.builder.SetInsertPoint(isanyBB); Value *p2 = ctx.builder.CreateAlignedLoad(T_prjlvalue, ctx.builder.CreateBitCast(val, T_pprjlvalue), sizeof(void*)); ctx.builder.CreateBr(afterBB); ctx.builder.SetInsertPoint(unboxedBB); Value *p3 = emit_new_bits(ctx, runtime_dt, val); unboxedBB = ctx.builder.GetInsertBlock(); // could have changed ctx.builder.CreateBr(afterBB); ctx.builder.SetInsertPoint(afterBB); PHINode *p = ctx.builder.CreatePHI(T_prjlvalue, 3); p->addIncoming(p1, boxedBB); p->addIncoming(p2, isanyBB); p->addIncoming(p3, unboxedBB); inputarg = mark_julia_type(ctx, p, true, jargty_proper); } } else { bool argboxed = sig.fargt_isboxed.at(i); if (argboxed) { // a jl_value_t*, even when represented as a struct inputarg = mark_julia_type(ctx, val, true, jargty_proper); } else { // something of type T // undo whatever we might have done to this poor argument assert(jl_is_datatype(jargty)); if (sig.byRefList.at(i)) { assert(cast<PointerType>(val->getType())->getElementType() == sig.fargt[i]); val = ctx.builder.CreateAlignedLoad(val, 1); // unknown alignment from C } else { bool issigned = jl_signed_type && jl_subtype(jargty_proper, (jl_value_t*)jl_signed_type); val = llvm_type_rewrite(ctx, val, sig.fargt[i], issigned); } // passed an unboxed T, but may need something boxed (not valid to be unboxed) if (static_at) { bool isboxed; assert(jargty == jargty_proper); (void)julia_type_to_llvm(ctx, jargty, &isboxed); if (isboxed) inputarg = mark_julia_type(ctx, box_ccall_result(ctx, val, literal_pointer_val(ctx, jargty), jargty), true, jargty_proper); else inputarg = mark_julia_type(ctx, val, false, jargty); } else { if (!*closure_types) *closure_types = jl_alloc_vec_any(0); jl_array_ptr_1d_push(*closure_types, jargty); Value *runtime_dt = ctx.builder.CreateAlignedLoad(T_prjlvalue, ctx.builder.CreateConstGEP1_32(T_prjlvalue, nestPtr, jl_array_len(*closure_types)), sizeof(void*)); Value *strct = box_ccall_result(ctx, val, runtime_dt, jargty); inputarg = mark_julia_type(ctx, strct, true, jargty_proper); } } } } JL_GC_POP(); assert(AI == cw->arg_end()); // Create the call bool jlfunc_sret; jl_cgval_t retval; if (calltype == 2) { nargs = 0; // arguments not needed -- TODO: not really true, should emit an age_ok test and jlcall jlfunc_sret = false; retval = mark_julia_const((jl_value_t*)callptr); } else if (calltype == 0 || calltype == 1) { // emit a jlcall jlfunc_sret = false; Function *theFptr = NULL; if (calltype == 1) { StringRef fname = jl_ExecutionEngine->getFunctionAtAddress((uintptr_t)callptr, codeinst); theFptr = cast_or_null<Function>(jl_Module->getNamedValue(fname)); if (!theFptr) { theFptr = Function::Create(jl_func_sig, GlobalVariable::ExternalLinkage, fname, jl_Module); jl_init_function(theFptr); } else { assert(theFptr->getFunctionType() == jl_func_sig); } add_return_attr(theFptr, Attribute::NonNull); theFptr->addFnAttr(Thunk); } BasicBlock *b_generic, *b_jlcall, *b_after; Value *ret_jlcall; if (age_ok) { assert(theFptr); b_generic = BasicBlock::Create(jl_LLVMContext, "generic", cw); b_jlcall = BasicBlock::Create(jl_LLVMContext, "apply", cw); b_after = BasicBlock::Create(jl_LLVMContext, "after", cw); ctx.builder.CreateCondBr(age_ok, b_jlcall, b_generic); ctx.builder.SetInsertPoint(b_jlcall); // for jlcall, we need to pass the function object even if it is a ghost. Value *theF = boxed(ctx, inputargs[0]); assert(theF); ret_jlcall = emit_jlcall(ctx, theFptr, theF, &inputargs[1], nargs, JLCALL_F_CC); ctx.builder.CreateBr(b_after); ctx.builder.SetInsertPoint(b_generic); } Value *ret = emit_jlcall(ctx, jlapplygeneric_func, NULL, inputargs, nargs + 1, JLCALL_F_CC); if (age_ok) { ctx.builder.CreateBr(b_after); ctx.builder.SetInsertPoint(b_after); PHINode *retphi = ctx.builder.CreatePHI(T_prjlvalue, 2); retphi->addIncoming(ret_jlcall, b_jlcall); retphi->addIncoming(ret, b_generic); ret = retphi; } retval = mark_julia_type(ctx, ret, true, astrt); } else { assert(calltype == 3); // emit a specsig call StringRef protoname = jl_ExecutionEngine->getFunctionAtAddress((uintptr_t)callptr, codeinst); jl_returninfo_t returninfo = get_specsig_function(ctx, M, protoname, lam->specTypes, astrt); FunctionType *cft = returninfo.decl->getFunctionType(); jlfunc_sret = (returninfo.cc == jl_returninfo_t::SRet); // TODO: Can use use emit_call_specfun_other here? std::vector<Value*> args; Value *result; if (jlfunc_sret || returninfo.cc == jl_returninfo_t::Union) { // fuse the two sret together, or emit an alloca to hold it if (sig.sret && jlfunc_sret) { result = emit_bitcast(ctx, sretPtr, cft->getParamType(0)); } else { result = emit_static_alloca(ctx, cft->getParamType(0)->getPointerElementType()); } args.push_back(result); } if (returninfo.return_roots) { AllocaInst *return_roots = emit_static_alloca(ctx, T_prjlvalue); return_roots->setOperand(0, ConstantInt::get(T_int32, returninfo.return_roots)); args.push_back(return_roots); } for (size_t i = 0; i < nargs + 1; i++) { // figure out how to repack the arguments jl_cgval_t &inputarg = inputargs[i]; Value *arg; jl_value_t *spect = jl_nth_slot_type(lam->specTypes, i); bool isboxed = deserves_argbox(spect); Type *T = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, spect); if (is_uniquerep_Type(spect)) { continue; } else if (isboxed) { arg = boxed(ctx, inputarg); } else if (type_is_ghost(T)) { continue; // ghost types are skipped by the specsig method signature } else if (T->isAggregateType()) { // aggregate types are passed by pointer if (!inputarg.ispointer()) inputarg = value_to_pointer(ctx, inputarg); arg = maybe_bitcast(ctx, decay_derived(data_pointer(ctx, inputarg)), T->getPointerTo()); } else { arg = emit_unbox(ctx, T, inputarg, spect); assert(!isa<UndefValue>(arg)); } // add to argument list args.push_back(arg); } Value *theFptr = returninfo.decl; assert(theFptr); if (age_ok) { funcName += "_gfthunk"; Function *gf_thunk = Function::Create(returninfo.decl->getFunctionType(), GlobalVariable::InternalLinkage, funcName, M); gf_thunk->setAttributes(returninfo.decl->getAttributes()); jl_init_function(gf_thunk); // build a specsig -> jl_apply_generic converter thunk // this builds a method that calls jl_apply_generic (as a closure over a singleton function pointer), // but which has the signature of a specsig emit_cfunc_invalidate(gf_thunk, returninfo.cc, returninfo.return_roots, lam->specTypes, codeinst->rettype, nargs + 1, ctx.emission_context); theFptr = ctx.builder.CreateSelect(age_ok, theFptr, gf_thunk); } CallInst *call = ctx.builder.CreateCall( cast<FunctionType>(theFptr->getType()->getPointerElementType()), theFptr, ArrayRef<Value*>(args)); call->setAttributes(returninfo.decl->getAttributes()); switch (returninfo.cc) { case jl_returninfo_t::Boxed: retval = mark_julia_type(ctx, call, true, astrt); break; case jl_returninfo_t::Register: retval = mark_julia_type(ctx, call, false, astrt); break; case jl_returninfo_t::SRet: retval = mark_julia_slot(result, astrt, NULL, tbaa_stack); break; case jl_returninfo_t::Union: { Value *box = ctx.builder.CreateExtractValue(call, 0); Value *tindex = ctx.builder.CreateExtractValue(call, 1); Value *derived = ctx.builder.CreateSelect( ctx.builder.CreateICmpEQ( ctx.builder.CreateAnd(tindex, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)), decay_derived(ctx.builder.CreateBitCast(result, T_pjlvalue)), decay_derived(box)); retval = mark_julia_slot(derived, astrt, tindex, tbaa_stack); retval.Vboxed = box; break; } case jl_returninfo_t::Ghosts: retval = mark_julia_slot(NULL, astrt, call, tbaa_stack); break; } } // inline a call to typeassert here, if required emit_typecheck(ctx, retval, declrt, "cfunction"); retval = update_julia_type(ctx, retval, declrt); // Prepare the return value Value *r; if (sig.retboxed) { assert(!sig.sret); // return a jl_value_t* r = boxed(ctx, retval); } else if (sig.sret && jlfunc_sret) { // nothing to do r = NULL; } else if (!type_is_ghost(sig.lrt)) { Type *prt = sig.prt; if (sig.sret) prt = sig.fargt_sig[0]->getContainedType(0); // sret is a PointerType bool issigned = jl_signed_type && jl_subtype(declrt, (jl_value_t*)jl_signed_type); Value *v = emit_unbox(ctx, sig.lrt, retval, retval.typ); r = llvm_type_rewrite(ctx, v, prt, issigned); if (sig.sret) { ctx.builder.CreateStore(r, sretPtr); r = NULL; } } else { r = NULL; } ctx.builder.CreateStore(last_age, ctx.world_age_field); ctx.builder.CreateRet(r); ctx.builder.SetCurrentDebugLocation(noDbg); ctx.builder.ClearInsertionPoint(); if (aliasname) { GlobalAlias::create(cw->getType()->getElementType(), cw->getType()->getAddressSpace(), GlobalValue::ExternalLinkage, aliasname, cw, M); } if (nest) { funcName += "make"; Function *cw_make = Function::Create( FunctionType::get(T_pint8, { T_pint8, T_ppjlvalue }, false), GlobalVariable::ExternalLinkage, funcName, M); jl_init_function(cw_make); BasicBlock *b0 = BasicBlock::Create(jl_LLVMContext, "top", cw_make); IRBuilder<> cwbuilder(b0); Function::arg_iterator AI = cw_make->arg_begin(); Argument *Tramp = &*AI; ++AI; Argument *NVal = &*AI; ++AI; Function *init_trampoline = Intrinsic::getDeclaration(cw_make->getParent(), Intrinsic::init_trampoline); Function *adjust_trampoline = Intrinsic::getDeclaration(cw_make->getParent(), Intrinsic::adjust_trampoline); cwbuilder.CreateCall(init_trampoline, { Tramp, cwbuilder.CreateBitCast(cw, T_pint8), cwbuilder.CreateBitCast(NVal, T_pint8) }); cwbuilder.CreateRet(cwbuilder.CreateCall(adjust_trampoline, { Tramp })); cw = cw_make; } return cw; } // Get the LLVM Function* for the C-callable entry point for a certain function // and argument types. // here argt does not include the leading function type argument static jl_cgval_t emit_cfunction(jl_codectx_t &ctx, jl_value_t *output_type, const jl_cgval_t &fexpr_rt, jl_value_t *declrt, jl_svec_t *argt) { jl_unionall_t *unionall_env = (jl_is_method(ctx.linfo->def.method) && jl_is_unionall(ctx.linfo->def.method->sig)) ? (jl_unionall_t*)ctx.linfo->def.method->sig : NULL; jl_svec_t *sparam_vals = NULL; if (ctx.spvals_ptr == NULL && jl_svec_len(ctx.linfo->sparam_vals) > 0) sparam_vals = ctx.linfo->sparam_vals; jl_value_t *rt = declrt; if (jl_is_abstract_ref_type(declrt)) { declrt = jl_tparam0(declrt); if (!verify_ref_type(ctx, declrt, unionall_env, 0, "cfunction")) { return jl_cgval_t(); } if (unionall_env) declrt = jl_rewrap_unionall(declrt, (jl_value_t*)unionall_env); rt = (jl_value_t*)jl_any_type; // convert return type to jl_value_t* } // some sanity checking and check whether there's a vararg size_t nargt = jl_svec_len(argt); bool isVa = (nargt > 0 && jl_is_vararg_type(jl_svecref(argt, nargt - 1))); if (isVa) { emit_error(ctx, "cfunction: Vararg syntax not allowed for argument list"); return jl_cgval_t(); } jl_array_t *closure_types = NULL; jl_value_t *sigt = NULL; // dispatch-sig = type signature with Ref{} annotations removed and applied to the env JL_GC_PUSH4(&declrt, &sigt, &rt, &closure_types); Type *lrt; bool retboxed; bool static_rt; const std::string err = verify_ccall_sig( /* inputs: */ rt, (jl_value_t*)argt, unionall_env, sparam_vals, &ctx.emission_context, /* outputs: */ lrt, retboxed, static_rt); if (!err.empty()) { emit_error(ctx, "cfunction " + err); JL_GC_POP(); return jl_cgval_t(); } if (rt != declrt && rt != (jl_value_t*)jl_any_type) jl_add_method_root(ctx, rt); function_sig_t sig("cfunction", lrt, rt, retboxed, argt, unionall_env, false, CallingConv::C, false, &ctx.emission_context); assert(sig.fargt.size() + sig.sret == sig.fargt_sig.size()); if (!sig.err_msg.empty()) { emit_error(ctx, sig.err_msg); JL_GC_POP(); return jl_cgval_t(); } // compute+verify the dispatch signature, and see if it depends on the environment sparams bool approx = false; sigt = (jl_value_t*)jl_alloc_svec(nargt + 1); jl_svecset(sigt, 0, fexpr_rt.typ); if (!fexpr_rt.constant && (!jl_is_concrete_type(fexpr_rt.typ) || jl_is_kind(fexpr_rt.typ))) approx = true; for (size_t i = 0; i < nargt; i++) { jl_value_t *jargty = jl_svecref(argt, i); if (jl_is_abstract_ref_type(jargty)) { jargty = jl_tparam0(jargty); if (!verify_ref_type(ctx, jargty, unionall_env, i + 1, "cfunction")) { JL_GC_POP(); return jl_cgval_t(); } } if (unionall_env && jl_has_typevar_from_unionall(jargty, unionall_env)) { if (sparam_vals) jargty = jl_instantiate_type_in_env(jargty, unionall_env, jl_svec_data(sparam_vals)); else approx = true; } jl_svecset(sigt, i + 1, jargty); } if (approx) { sigt = NULL; } else { sigt = (jl_value_t*)jl_apply_tuple_type((jl_svec_t*)sigt); } if (sigt && !(unionall_env && jl_has_typevar_from_unionall(rt, unionall_env))) { unionall_env = NULL; } bool nest = (!fexpr_rt.constant || unionall_env); #if defined(_CPU_AARCH64_) || defined(_CPU_ARM_) || defined(_CPU_PPC64_) if (nest) { emit_error(ctx, "cfunction: closures are not supported on this platform"); return jl_cgval_t(); } #endif size_t world = jl_world_counter; size_t min_valid = 0; size_t max_valid = ~(size_t)0; // try to look up this function for direct invoking jl_method_instance_t *lam = sigt ? jl_get_specialization1((jl_tupletype_t*)sigt, world, &min_valid, &max_valid, 0) : NULL; Value *F = gen_cfun_wrapper( jl_Module, ctx.emission_context, sig, fexpr_rt.constant, NULL, declrt, lam, unionall_env, sparam_vals, &closure_types); bool outboxed; if (nest) { // F is actually an init_trampoline function that returns the real address // Now fill in the nest parameters Value *fobj = boxed(ctx, fexpr_rt); jl_svec_t *fill = jl_emptysvec; if (closure_types) { assert(ctx.spvals_ptr); size_t n = jl_array_len(closure_types); jl_svec_t *fill = jl_alloc_svec_uninit(n); for (size_t i = 0; i < n; i++) { jl_svecset(fill, i, jl_array_ptr_ref(closure_types, i)); } jl_add_method_root(ctx, (jl_value_t*)fill); } Type *T_htable = ArrayType::get(T_size, sizeof(htable_t) / sizeof(void*)); Value *cache = new GlobalVariable(*jl_Module, T_htable, false, GlobalVariable::PrivateLinkage, ConstantAggregateZero::get(T_htable)); F = ctx.builder.CreateCall(prepare_call(jlgetcfunctiontrampoline_func), { fobj, literal_pointer_val(ctx, output_type), ctx.builder.CreateBitCast(cache, T_pint8), literal_pointer_val(ctx, (jl_value_t*)fill), F, closure_types ? literal_pointer_val(ctx, (jl_value_t*)unionall_env) : V_null, closure_types ? ctx.spvals_ptr : ConstantPointerNull::get(cast<PointerType>(T_pprjlvalue)) }); outboxed = true; } else { F = ctx.builder.CreatePtrToInt(F, T_size); outboxed = (output_type != (jl_value_t*)jl_voidpointer_type); if (outboxed) { assert(jl_datatype_size(output_type) == sizeof(void*) * 4); Value *strct = emit_allocobj(ctx, jl_datatype_size(output_type), literal_pointer_val(ctx, (jl_value_t*)output_type)); Value *derived_strct = emit_bitcast(ctx, decay_derived(strct), T_psize); MDNode *tbaa = best_tbaa(output_type); tbaa_decorate(tbaa, ctx.builder.CreateStore(F, derived_strct)); tbaa_decorate(tbaa, ctx.builder.CreateStore( ctx.builder.CreatePtrToInt(literal_pointer_val(ctx, fexpr_rt.constant), T_size), ctx.builder.CreateConstGEP1_32(T_size, derived_strct, 1))); Value *zero = ConstantInt::get(T_size, 0); tbaa_decorate(tbaa, ctx.builder.CreateStore(zero, ctx.builder.CreateConstGEP1_32(T_size, derived_strct, 2))); tbaa_decorate(tbaa, ctx.builder.CreateStore(zero, ctx.builder.CreateConstGEP1_32(T_size, derived_strct, 3))); F = strct; } } JL_GC_POP(); return mark_julia_type(ctx, F, outboxed, output_type); } // do codegen to create a C-callable alias/wrapper, or if sysimg_handle is set, // restore one from a loaded system image. void jl_generate_ccallable(void *llvmmod, void *sysimg_handle, jl_value_t *declrt, jl_value_t *sigt, jl_codegen_params_t &params) { jl_datatype_t *ft = (jl_datatype_t*)jl_tparam0(sigt); jl_value_t *ff = ft->instance; assert(ff); const char *name = jl_symbol_name(ft->name->mt->name); jl_value_t *crt = declrt; if (jl_is_abstract_ref_type(declrt)) { declrt = jl_tparam0(declrt); crt = (jl_value_t*)jl_any_type; } bool toboxed; Type *lcrt = _julia_struct_to_llvm(&params, crt, NULL, &toboxed); if (toboxed) lcrt = T_prjlvalue; size_t nargs = jl_nparams(sigt)-1; jl_svec_t *argtypes = NULL; JL_GC_PUSH1(&argtypes); argtypes = jl_alloc_svec(nargs); for (size_t i = 0; i < nargs; i++) { jl_svecset(argtypes, i, jl_tparam(sigt, i+1)); } jl_value_t *err; { // scope block for sig function_sig_t sig("cfunction", lcrt, crt, toboxed, argtypes, NULL, false, CallingConv::C, false, &params); if (sig.err_msg.empty()) { size_t world = jl_world_counter; size_t min_valid = 0; size_t max_valid = ~(size_t)0; if (sysimg_handle) { // restore a ccallable from the system image void *addr; int found = jl_dlsym(sysimg_handle, name, &addr, 0); if (found) add_named_global(name, addr); } else { jl_method_instance_t *lam = jl_get_specialization1((jl_tupletype_t*)sigt, world, &min_valid, &max_valid, 0); gen_cfun_wrapper((Module*)llvmmod, params, sig, ff, name, declrt, lam, NULL, NULL, NULL); } JL_GC_POP(); return; } err = jl_get_exceptionf(jl_errorexception_type, "%s", sig.err_msg.c_str()); } jl_throw(err); } // generate a julia-callable function that calls f (AKA lam) static Function *gen_invoke_wrapper(jl_method_instance_t *lam, jl_value_t *jlretty, const jl_returninfo_t &f, int retarg, StringRef funcName, Module *M, jl_codegen_params_t &params) { Function *w = Function::Create(jl_func_sig, GlobalVariable::ExternalLinkage, funcName, M); add_return_attr(w, Attribute::NonNull); w->addFnAttr(Thunk); jl_init_function(w); Function::arg_iterator AI = w->arg_begin(); Value *funcArg = &*AI++; Value *argArray = &*AI++; Value *argCount = &*AI++; (void)argCount; // unused //Value *mfunc = &*AI++; (void)mfunc; // unused assert(AI == w->arg_end()); jl_codectx_t ctx(jl_LLVMContext, params); ctx.f = w; ctx.linfo = lam; ctx.rettype = jlretty; ctx.world = 0; BasicBlock *b0 = BasicBlock::Create(jl_LLVMContext, "top", w); ctx.builder.SetInsertPoint(b0); DebugLoc noDbg; ctx.builder.SetCurrentDebugLocation(noDbg); allocate_gc_frame(ctx, b0); // TODO: replace this with emit_call_specfun_other? FunctionType *ftype = f.decl->getFunctionType(); size_t nfargs = ftype->getNumParams(); Value **args = (Value**) alloca(nfargs * sizeof(Value*)); unsigned idx = 0; AllocaInst *result = NULL; switch (f.cc) { case jl_returninfo_t::Boxed: case jl_returninfo_t::Register: case jl_returninfo_t::Ghosts: break; case jl_returninfo_t::SRet: result = ctx.builder.CreateAlloca(ftype->getParamType(0)->getPointerElementType()); args[idx] = result; idx++; break; case jl_returninfo_t::Union: result = ctx.builder.CreateAlloca(ArrayType::get(T_int8, f.union_bytes)); if (f.union_align > 1) result->setAlignment(Align(f.union_align)); args[idx] = result; idx++; break; } if (f.return_roots) { AllocaInst *return_roots = emit_static_alloca(ctx, T_prjlvalue); return_roots->setOperand(0, ConstantInt::get(T_int32, f.return_roots)); args[idx] = return_roots; idx++; } for (size_t i = 0; i < jl_nparams(lam->specTypes) && idx < nfargs; ++i) { jl_value_t *ty = jl_nth_slot_type(lam->specTypes, i); bool isboxed = deserves_argbox(ty); Type *lty = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, ty); if (type_is_ghost(lty) || is_uniquerep_Type(ty)) continue; Value *theArg; if (i == 0) { theArg = funcArg; } else { Value *argPtr = ctx.builder.CreateConstInBoundsGEP1_32(T_prjlvalue, argArray, i - 1); theArg = maybe_mark_load_dereferenceable( ctx.builder.CreateAlignedLoad(T_prjlvalue, argPtr, sizeof(void*)), false, ty); } if (!isboxed) { theArg = decay_derived(emit_bitcast(ctx, theArg, PointerType::get(lty, 0))); if (!lty->isAggregateType()) // keep "aggregate" type values in place as pointers theArg = ctx.builder.CreateAlignedLoad(theArg, julia_alignment(ty)); } assert(dyn_cast<UndefValue>(theArg) == NULL); args[idx] = theArg; idx++; } CallInst *call = ctx.builder.CreateCall(f.decl, ArrayRef<Value*>(&args[0], nfargs)); call->setAttributes(f.decl->getAttributes()); jl_cgval_t retval; if (retarg != -1) { Value *theArg; if (retarg == 0) theArg = funcArg; else theArg = ctx.builder.CreateAlignedLoad(T_prjlvalue, ctx.builder.CreateConstInBoundsGEP1_32(T_prjlvalue, argArray, retarg - 1), sizeof(void*)); retval = mark_julia_type(ctx, theArg, true, jl_any_type); } else { switch (f.cc) { case jl_returninfo_t::Boxed: retval = mark_julia_type(ctx, call, true, jlretty); break; case jl_returninfo_t::Register: retval = mark_julia_type(ctx, call, false, jlretty); break; case jl_returninfo_t::SRet: retval = mark_julia_slot(result, jlretty, NULL, tbaa_stack); break; case jl_returninfo_t::Union: // result is technically not right here, but `boxed` will only look at it // for the unboxed values, so it's ok. retval = mark_julia_slot(result, jlretty, ctx.builder.CreateExtractValue(call, 1), tbaa_stack); retval.Vboxed = ctx.builder.CreateExtractValue(call, 0); break; case jl_returninfo_t::Ghosts: retval = mark_julia_slot(NULL, jlretty, call, tbaa_stack); break; } } ctx.builder.CreateRet(boxed(ctx, retval)); assert(!ctx.roots); return w; } static jl_returninfo_t get_specsig_function(jl_codectx_t &ctx, Module *M, StringRef name, jl_value_t *sig, jl_value_t *jlrettype) { jl_returninfo_t props = {}; SmallVector<Type*, 8> fsig; Type *rt; if (jl_is_structtype(jlrettype) && jl_is_datatype_singleton((jl_datatype_t*)jlrettype)) { rt = T_void; props.cc = jl_returninfo_t::Register; } else if (jl_is_uniontype(jlrettype)) { bool allunbox; union_alloca_type((jl_uniontype_t*)jlrettype, allunbox, props.union_bytes, props.union_align, props.union_minalign); if (props.union_bytes) { props.cc = jl_returninfo_t::Union; Type *AT = ArrayType::get(T_int8, props.union_bytes); fsig.push_back(AT->getPointerTo()); Type *pair[] = { T_prjlvalue, T_int8 }; rt = StructType::get(jl_LLVMContext, makeArrayRef(pair)); } else if (allunbox) { props.cc = jl_returninfo_t::Ghosts; rt = T_int8; } else { rt = T_prjlvalue; } } else if (!deserves_retbox(jlrettype)) { bool retboxed; rt = julia_type_to_llvm(ctx, jlrettype, &retboxed); assert(!retboxed); if (rt != T_void && deserves_sret(jlrettype, rt)) { auto tracked = CountTrackedPointers(rt); assert(!tracked.derived); if (tracked.count && !tracked.all) props.return_roots = tracked.count; props.cc = jl_returninfo_t::SRet; fsig.push_back(rt->getPointerTo()); rt = T_void; } else { props.cc = jl_returninfo_t::Register; } } else { rt = T_prjlvalue; } AttributeList attributes; // function declaration attributes if (props.cc == jl_returninfo_t::SRet) { unsigned argno = 1; attributes = attributes.addAttribute(jl_LLVMContext, argno, Attribute::StructRet); attributes = attributes.addAttribute(jl_LLVMContext, argno, Attribute::NoAlias); attributes = attributes.addAttribute(jl_LLVMContext, argno, Attribute::NoCapture); } if (props.cc == jl_returninfo_t::Union) { unsigned argno = 1; attributes = attributes.addAttribute(jl_LLVMContext, argno, Attribute::NoAlias); attributes = attributes.addAttribute(jl_LLVMContext, argno, Attribute::NoCapture); } if (props.return_roots) { fsig.push_back(T_pprjlvalue); unsigned argno = fsig.size(); attributes = attributes.addAttribute(jl_LLVMContext, argno, Attribute::NoAlias); attributes = attributes.addAttribute(jl_LLVMContext, argno, Attribute::NoCapture); } for (size_t i = 0; i < jl_nparams(sig); i++) { jl_value_t *jt = jl_tparam(sig, i); if (is_uniquerep_Type(jt)) continue; bool isboxed = deserves_argbox(jt); Type *ty = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, jt); if (type_is_ghost(ty)) continue; unsigned argno = fsig.size(); if (ty->isAggregateType()) { // aggregate types are passed by pointer attributes = attributes.addParamAttribute(jl_LLVMContext, argno, Attribute::NoCapture); attributes = attributes.addParamAttribute(jl_LLVMContext, argno, Attribute::ReadOnly); ty = PointerType::get(ty, AddressSpace::Derived); } else if (isboxed && jl_is_immutable_datatype(jt)) { attributes = attributes.addParamAttribute(jl_LLVMContext, argno, Attribute::ReadOnly); } fsig.push_back(ty); } FunctionType *ftype = FunctionType::get(rt, fsig, false); Function *f = M ? cast_or_null<Function>(M->getNamedValue(name)) : NULL; if (f == NULL) { f = Function::Create(ftype, GlobalVariable::ExternalLinkage, name, M); f->setAttributes(attributes); jl_init_function(f); } else { assert(f->getFunctionType() == ftype); } if (rt == T_prjlvalue) add_return_attr(f, Attribute::NonNull); props.decl = f; return props; } static void emit_sret_roots(jl_codectx_t &ctx, bool isptr, Value *Src, Type *T, Value *Shadow, unsigned count) { if (isptr) Src = maybe_decay_tracked(Src); if (isptr && Src->getType()->getPointerElementType() != T) Src = ctx.builder.CreateBitCast(Src, T->getPointerTo(Src->getType()->getPointerAddressSpace())); unsigned emitted = TrackWithShadow(Src, T, isptr, Shadow, ctx.builder); assert(emitted == count); (void)emitted; (void)count; } static DISubroutineType * get_specsig_di(jl_codectx_t &ctx, jl_value_t *rt, jl_value_t *sig, DIBuilder &dbuilder) { size_t nargs = jl_nparams(sig); // TODO: if this is a Varargs function, our debug info for the `...` var may be misleading std::vector<Metadata*> ditypes(nargs + 1); ditypes[0] = julia_type_to_di(ctx, rt, &dbuilder, false); for (size_t i = 0; i < nargs; i++) { jl_value_t *jt = jl_tparam(sig, i); ditypes[i + 1] = julia_type_to_di(ctx, jt, &dbuilder, false); } return dbuilder.createSubroutineType(dbuilder.getOrCreateTypeArray(ditypes)); } static jl_datatype_t *compute_va_type(jl_method_instance_t *lam, size_t nreq) { size_t nvargs = jl_nparams(lam->specTypes)-nreq; jl_svec_t *tupargs = jl_alloc_svec(nvargs); JL_GC_PUSH1(&tupargs); for (size_t i = nreq; i < jl_nparams(lam->specTypes); ++i) { jl_value_t *argType = jl_nth_slot_type(lam->specTypes, i); jl_svecset(tupargs, i-nreq, argType); } jl_datatype_t *typ = jl_apply_tuple_type(tupargs); JL_GC_POP(); return typ; } // Compile to LLVM IR, using a specialized signature if applicable. static std::pair<std::unique_ptr<Module>, jl_llvm_functions_t> emit_function( jl_method_instance_t *lam, jl_code_info_t *src, jl_value_t *jlrettype, jl_codegen_params_t &params) { // step 1. unpack AST and allocate codegen context for this function jl_llvm_functions_t declarations; jl_codectx_t ctx(jl_LLVMContext, params); JL_GC_PUSH2(&ctx.code, &ctx.roots); ctx.code = src->code; std::map<int, BasicBlock*> labels; ctx.module = jl_is_method(lam->def.method) ? lam->def.method->module : lam->def.module; ctx.linfo = lam; ctx.rettype = jlrettype; ctx.source = src; ctx.name = name_from_method_instance(lam); ctx.funcName = ctx.name; ctx.spvals_ptr = NULL; ctx.nargs = jl_is_method(lam->def.method) ? lam->def.method->nargs : 0; bool toplevel = !jl_is_method(lam->def.method); jl_array_t *stmts = ctx.code; size_t stmtslen = jl_array_dim0(stmts); if (JL_HOOK_TEST(ctx.params, emit_function)) { JL_HOOK_CALL(ctx.params, emit_function, 2, (jl_value_t*)ctx.linfo, (jl_value_t*)ctx.source); } // step 1b. unpack debug information int coverage_mode = jl_options.code_coverage; int malloc_log_mode = jl_options.malloc_log; if (!JL_FEAT_TEST(ctx, code_coverage)) coverage_mode = JL_LOG_NONE; if (!JL_FEAT_TEST(ctx, track_allocations)) malloc_log_mode = JL_LOG_NONE; StringRef dbgFuncName = ctx.name; int toplineno = -1; if (jl_is_method(lam->def.method)) { toplineno = lam->def.method->line; ctx.file = jl_symbol_name(lam->def.method->file); } else if (jl_array_len(src->linetable) > 0) { jl_value_t *locinfo = jl_array_ptr_ref(src->linetable, 0); ctx.file = jl_symbol_name((jl_sym_t*)jl_fieldref_noalloc(locinfo, 1)); toplineno = jl_unbox_long(jl_fieldref(locinfo, 2)); } if (ctx.file.empty()) ctx.file = "<missing>"; // jl_printf(JL_STDERR, "\n*** compiling %s at %s:%d\n\n", // jl_symbol_name(ctx.name), ctx.file.str().c_str(), toplineno); ctx.debug_enabled = true; if (dbgFuncName.empty()) // Should never happen anymore? ctx.debug_enabled = 0; if (jl_options.debug_level == 0) ctx.debug_enabled = 0; // step 2. process var-info lists to see what vars need boxing int n_ssavalues = jl_is_long(src->ssavaluetypes) ? jl_unbox_long(src->ssavaluetypes) : jl_array_len(src->ssavaluetypes); size_t vinfoslen = jl_array_dim0(src->slotflags); ctx.slots.resize(vinfoslen); size_t nreq = ctx.nargs; int va = 0; assert(lam->specTypes); // the specTypes field should always be assigned if (nreq > 0 && lam->def.method->isva) { nreq--; va = 1; jl_sym_t *vn = (jl_sym_t*)jl_array_ptr_ref(src->slotnames, ctx.nargs - 1); if (vn != unused_sym) ctx.vaSlot = ctx.nargs - 1; } ctx.nReqArgs = nreq; // create SAvalue locations for SSAValue objects ctx.ssavalue_assigned.assign(n_ssavalues, false); ctx.SAvalues.assign(n_ssavalues, jl_cgval_t()); bool specsig, needsparams; std::tie(specsig, needsparams) = uses_specsig(lam, jlrettype, params.params->prefer_specsig); if (!src->inferred) specsig = false; // step 3. some variable analysis size_t i; for (i = 0; i < nreq; i++) { jl_varinfo_t &varinfo = ctx.slots[i]; varinfo.isArgument = true; jl_sym_t *argname = (jl_sym_t*)jl_array_ptr_ref(src->slotnames, i); if (argname == unused_sym) continue; jl_value_t *ty = jl_nth_slot_type(lam->specTypes, i); varinfo.value = mark_julia_type(ctx, (Value*)NULL, false, ty); } if (va && ctx.vaSlot != -1) { jl_varinfo_t &varinfo = ctx.slots[ctx.vaSlot]; varinfo.isArgument = true; jl_datatype_t *vatyp = specsig ? compute_va_type(lam, nreq) : (jl_tuple_type); varinfo.value = mark_julia_type(ctx, (Value*)NULL, false, vatyp); } for (i = 0; i < vinfoslen; i++) { jl_varinfo_t &varinfo = ctx.slots[i]; uint8_t flags = jl_array_uint8_ref(src->slotflags, i); varinfo.isSA = (jl_vinfo_sa(flags) != 0) || varinfo.isArgument; varinfo.usedUndef = (jl_vinfo_usedundef(flags) != 0) || (!varinfo.isArgument && !src->inferred); if (!varinfo.isArgument) { varinfo.value = mark_julia_type(ctx, (Value*)NULL, false, (jl_value_t*)jl_any_type); } } // finish recording variable use info for (i = 0; i < stmtslen; i++) simple_use_analysis(ctx, jl_array_ptr_ref(stmts, i)); // determine which vars need to be volatile mark_volatile_vars(stmts, ctx.slots); // step 4. determine function signature if (!specsig) ctx.nReqArgs--; // function not part of argArray in jlcall std::string _funcName; raw_string_ostream funcName(_funcName); // try to avoid conflicts in the global symbol table if (specsig) funcName << "julia_"; // api 5 else if (needsparams) funcName << "japi3_"; else funcName << "japi1_"; const char* unadorned_name = ctx.name; #if defined(_OS_LINUX_) if (unadorned_name[0] == '@') unadorned_name++; #endif funcName << unadorned_name << "_" << globalUnique++; declarations.specFunctionObject = funcName.str(); // allocate Function declarations and wrapper objects Module *M = new Module(ctx.name, jl_LLVMContext); jl_setup_module(M, ctx.params); jl_returninfo_t returninfo = {}; Function *f = NULL; bool has_sret = false; if (specsig) { // assumes !va and !needsparams returninfo = get_specsig_function(ctx, M, declarations.specFunctionObject, lam->specTypes, jlrettype); f = returninfo.decl; has_sret = (returninfo.cc == jl_returninfo_t::SRet || returninfo.cc == jl_returninfo_t::Union); jl_init_function(f); // common pattern: see if all return statements are an argument in that // case the apply-generic call can re-use the original box for the return int retarg = [stmts, nreq]() { int retarg = -1; for (size_t i = 0; i < jl_array_len(stmts); ++i) { jl_value_t *stmt = jl_array_ptr_ref(stmts, i); if (jl_is_returnnode(stmt)) { stmt = jl_returnnode_value(stmt); if (stmt == NULL) continue; if (!jl_is_argument(stmt)) return -1; unsigned sl = jl_slot_number(stmt) - 1; if (sl >= nreq) return -1; if (retarg == -1) retarg = sl; else if ((unsigned)retarg != sl) return -1; } } return retarg; }(); std::string wrapName; raw_string_ostream(wrapName) << "jfptr_" << unadorned_name << "_" << globalUnique++; declarations.functionObject = wrapName; (void)gen_invoke_wrapper(lam, jlrettype, returninfo, retarg, declarations.functionObject, M, ctx.emission_context); } else { f = Function::Create(needsparams ? jl_func_sig_sparams : jl_func_sig, GlobalVariable::ExternalLinkage, declarations.specFunctionObject, M); jl_init_function(f); add_return_attr(f, Attribute::NonNull); f->addFnAttr(Thunk); // TODO: (if needsparams) add attributes: dereferenceable<sizeof(void*) * length(sp)>, readonly, nocapture // TODO: add attributes: dereferenceable<sizeof(ft)>, readonly, nocapture - e.g. maybe_mark_argument_dereferenceable(Arg, argType); // TODO: add attributes: dereferenceable<sizeof(void*) * nreq>, readonly, nocapture returninfo.decl = f; declarations.functionObject = needsparams ? "jl_fptr_sparam" : "jl_fptr_args"; } if (jlrettype == (jl_value_t*)jl_bottom_type) f->setDoesNotReturn(); #ifdef USE_POLLY if (!jl_has_meta(stmts, polly_sym) || jl_options.polly == JL_OPTIONS_POLLY_OFF) { f->addFnAttr(polly::PollySkipFnAttr); } #endif if (jl_has_meta(stmts, noinline_sym)) { f->addFnAttr(Attribute::NoInline); } if (returninfo.cc == jl_returninfo_t::Union) { f->addAttribute(1, Attribute::getWithDereferenceableBytes(jl_LLVMContext, returninfo.union_bytes)); f->addAttribute(1, Attribute::getWithAlignment(jl_LLVMContext, Align(returninfo.union_align))); } #ifdef JL_DEBUG_BUILD f->addFnAttr(Attribute::StackProtectStrong); #endif // add the optimization level specified for this module, if any int optlevel = jl_get_module_optlevel(ctx.module); if (optlevel >= 0 && optlevel <= 3) { static const char* const optLevelStrings[] = { "0", "1", "2", "3" }; f->addFnAttr("julia-optimization-level", optLevelStrings[optlevel]); } ctx.f = f; // Step 4b. determine debug info signature and other type info for locals DIBuilder dbuilder(*M); DIFile *topfile = NULL; DISubprogram *SP = NULL; DebugLoc noDbg, topdebugloc; if (ctx.debug_enabled) { DICompileUnit::DebugEmissionKind emissionKind = (DICompileUnit::DebugEmissionKind) ctx.params->debug_info_kind; DICompileUnit::DebugNameTableKind tableKind; if (JL_FEAT_TEST(ctx, gnu_pubnames)) { tableKind = DICompileUnit::DebugNameTableKind::GNU; } else { tableKind = DICompileUnit::DebugNameTableKind::None; } topfile = dbuilder.createFile(ctx.file, "."); DICompileUnit *CU = dbuilder.createCompileUnit(llvm::dwarf::DW_LANG_Julia ,topfile // File ,"julia" // Producer ,true // isOptimized ,"" // Flags ,0 // RuntimeVersion ,"" // SplitName ,emissionKind // Kind ,0 // DWOId ,true // SplitDebugInlining ,false // DebugInfoForProfiling ,tableKind // NameTableKind ); DISubroutineType *subrty; if (jl_options.debug_level <= 1) { subrty = jl_di_func_null_sig; } else if (!specsig) { subrty = jl_di_func_sig; } else { subrty = get_specsig_di(ctx, jlrettype, lam->specTypes, dbuilder); } SP = dbuilder.createFunction(CU ,dbgFuncName // Name ,f->getName() // LinkageName ,topfile // File ,toplineno // LineNo ,subrty // Ty ,toplineno // ScopeLine ,DINode::FlagZero // Flags ,DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized // SPFlags ,nullptr // Template Parameters ,nullptr // Template Declaration ,nullptr // ThrownTypes ); topdebugloc = DebugLoc::get(toplineno, 0, SP, NULL); f->setSubprogram(SP); if (jl_options.debug_level >= 2) { const bool AlwaysPreserve = true; // Go over all arguments and local variables and initialize their debug information for (i = 0; i < nreq; i++) { jl_sym_t *argname = (jl_sym_t*)jl_array_ptr_ref(src->slotnames, i); if (argname == unused_sym) continue; jl_varinfo_t &varinfo = ctx.slots[i]; varinfo.dinfo = dbuilder.createParameterVariable( SP, // Scope (current function will be fill in later) jl_symbol_name(argname), // Variable name has_sret + i + 1, // Argument number (1-based) topfile, // File toplineno == -1 ? 0 : toplineno, // Line // Variable type julia_type_to_di(ctx, varinfo.value.typ, &dbuilder, false), AlwaysPreserve, // May be deleted if optimized out DINode::FlagZero); // Flags (TODO: Do we need any) } if (va && ctx.vaSlot != -1) { ctx.slots[ctx.vaSlot].dinfo = dbuilder.createParameterVariable( SP, // Scope (current function will be fill in later) std::string(jl_symbol_name(slot_symbol(ctx, ctx.vaSlot))) + "...", // Variable name has_sret + nreq + 1, // Argument number (1-based) topfile, // File toplineno == -1 ? 0 : toplineno, // Line (for now, use lineno of the function) julia_type_to_di(ctx, ctx.slots[ctx.vaSlot].value.typ, &dbuilder, false), AlwaysPreserve, // May be deleted if optimized out DINode::FlagZero); // Flags (TODO: Do we need any) } for (i = 0; i < vinfoslen; i++) { jl_sym_t *s = (jl_sym_t*)jl_array_ptr_ref(src->slotnames, i); jl_varinfo_t &varinfo = ctx.slots[i]; if (varinfo.isArgument || s == empty_sym || s == unused_sym) continue; // LLVM 4.0: Assume the variable has default alignment varinfo.dinfo = dbuilder.createAutoVariable( SP, // Scope (current function will be fill in later) jl_symbol_name(s), // Variable name topfile, // File toplineno == -1 ? 0 : toplineno, // Line (for now, use lineno of the function) julia_type_to_di(ctx, varinfo.value.typ, &dbuilder, false), // Variable type AlwaysPreserve, // May be deleted if optimized out DINode::FlagZero // Flags (TODO: Do we need any) ); } } } // step 5. create first basic block BasicBlock *b0 = BasicBlock::Create(jl_LLVMContext, "top", f); ctx.builder.SetInsertPoint(b0); ctx.builder.SetCurrentDebugLocation(noDbg); // spill arguments into stack slots // so it is more likely to be possible to find them when debugging Value *fArg=NULL, *argArray=NULL, *pargArray=NULL, *argCount=NULL; if (!specsig) { Function::arg_iterator AI = f->arg_begin(); fArg = &*AI++; argArray = &*AI++; pargArray = ctx.builder.CreateAlloca(argArray->getType()); ctx.builder.CreateStore(argArray, pargArray, true/*volatile store to prevent removal of this alloca*/); argCount = &*AI++; ctx.argArray = argArray; ctx.argCount = argCount; if (needsparams) { ctx.spvals_ptr = &*AI++; } } /* // step 6. (optional) check for stack overflow (the slower way) Value *cur_sp = ctx.builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::frameaddress), ConstantInt::get(T_int32, 0)); Value *sp_ok = ctx.builder.CreateICmpUGT(cur_sp, ConstantInt::get(T_size, (uptrint_t)jl_stack_lo)); error_unless(ctx, sp_ok, "stack overflow"); */ // step 7. set up GC frame allocate_gc_frame(ctx, b0); Value *last_age = NULL; if (toplevel) { emit_last_age_field(ctx); last_age = tbaa_decorate(tbaa_gcframe, ctx.builder.CreateAlignedLoad(ctx.world_age_field, sizeof(size_t))); } // step 8. allocate local variables slots // must be in the first basic block for the llvm mem2reg pass to work auto allocate_local = [&](jl_varinfo_t &varinfo, jl_sym_t *s) { jl_value_t *jt = varinfo.value.typ; assert(!varinfo.boxroot); // variables shouldn't have memory locs already if (varinfo.value.constant) { // no need to explicitly load/store a constant/ghost value alloc_def_flag(ctx, varinfo); return; } else if (varinfo.isArgument && !(specsig && i == (size_t)ctx.vaSlot)) { // if we can unbox it, just use the input pointer if (i != (size_t)ctx.vaSlot && jl_is_concrete_immutable(jt)) return; } else if (jl_is_uniontype(jt)) { bool allunbox; size_t align, nbytes; Value *lv = try_emit_union_alloca(ctx, (jl_uniontype_t*)jt, allunbox, align, nbytes); if (lv) { lv->setName(jl_symbol_name(s)); varinfo.value = mark_julia_slot(lv, jt, NULL, tbaa_stack); varinfo.pTIndex = emit_static_alloca(ctx, T_int8); } else if (allunbox) { // all ghost values just need a selector allocated AllocaInst *lv = emit_static_alloca(ctx, T_int8); lv->setName(jl_symbol_name(s)); varinfo.pTIndex = lv; varinfo.value.tbaa = NULL; varinfo.value.isboxed = false; } if (lv || allunbox) alloc_def_flag(ctx, varinfo); if (allunbox) return; } else if (deserves_stack(jt, true)) { bool isboxed; Type *vtype = julia_type_to_llvm(ctx, jt, &isboxed); assert(!isboxed); assert(!type_is_ghost(vtype) && "constants should already be handled"); // CreateAlloca is OK during prologue setup Value *lv = ctx.builder.CreateAlloca(vtype, NULL, jl_symbol_name(s)); varinfo.value = mark_julia_slot(lv, jt, NULL, tbaa_stack); alloc_def_flag(ctx, varinfo); if (ctx.debug_enabled && varinfo.dinfo) { assert((Metadata*)varinfo.dinfo->getType() != jl_pvalue_dillvmt); dbuilder.insertDeclare(lv, varinfo.dinfo, dbuilder.createExpression(), topdebugloc, ctx.builder.GetInsertBlock()); } return; } if (!varinfo.isArgument || // always need a slot if the variable is assigned specsig || // for arguments, give them stack slots if they aren't in `argArray` (otherwise, will use that pointer) (va && (int)i == ctx.vaSlot) || // or it's the va arg tuple i == 0) { // or it is the first argument (which isn't in `argArray`) AllocaInst *av = new AllocaInst(T_prjlvalue, 0, jl_symbol_name(s), /*InsertBefore*/ctx.ptlsStates); StoreInst *SI = new StoreInst( ConstantPointerNull::get(cast<PointerType>(T_prjlvalue)), av, false); SI->insertAfter(ctx.ptlsStates); varinfo.boxroot = av; if (ctx.debug_enabled && varinfo.dinfo) { DIExpression *expr; if ((Metadata*)varinfo.dinfo->getType() == jl_pvalue_dillvmt) { expr = dbuilder.createExpression(); } else { SmallVector<uint64_t, 8> addr; addr.push_back(llvm::dwarf::DW_OP_deref); expr = dbuilder.createExpression(addr); } dbuilder.insertDeclare(av, varinfo.dinfo, expr, topdebugloc, ctx.builder.GetInsertBlock()); } } }; // get pointers for locals stored in the gc frame array (argTemp) for (i = 0; i < vinfoslen; i++) { jl_sym_t *s = slot_symbol(ctx, i); if (s == unused_sym) continue; jl_varinfo_t &varinfo = ctx.slots[i]; if (!varinfo.used) { varinfo.usedUndef = false; continue; } allocate_local(varinfo, s); } std::map<int, int> upsilon_to_phic; // Scan for PhiC nodes, emit their slots and record which upsilon nodes // yield to them. { for (size_t i = 0; i < jl_array_len(stmts); ++i) { jl_value_t *stmt = jl_array_ptr_ref(stmts, i); if (jl_is_phicnode(stmt)) { jl_array_t *values = (jl_array_t*)jl_fieldref_noalloc(stmt, 0); for (size_t j = 0; j < jl_array_len(values); ++j) { jl_value_t *val = jl_array_ptr_ref(values, j); assert(jl_is_ssavalue(val)); upsilon_to_phic[((jl_ssavalue_t*)val)->id] = i; } ctx.phic_slots[i] = jl_varinfo_t{}; jl_varinfo_t &vi = ctx.phic_slots[i]; jl_value_t *typ = jl_array_ptr_ref(src->ssavaluetypes, i); vi.used = true; vi.isVolatile = true; vi.value = mark_julia_type(ctx, (Value*)NULL, false, typ); allocate_local(vi, jl_symbol("phic")); } } } // step 9. move args into local variables Function::arg_iterator AI = f->arg_begin(); auto get_specsig_arg = [&](jl_value_t *argType, Type *llvmArgType, bool isboxed) { jl_cgval_t theArg; if (type_is_ghost(llvmArgType)) { // this argument is not actually passed theArg = ghostValue(argType); } else if (is_uniquerep_Type(argType)) { theArg = mark_julia_const(jl_tparam0(argType)); } else if (llvmArgType->isAggregateType()) { Argument *Arg = &*AI; ++AI; maybe_mark_argument_dereferenceable(Arg, argType); theArg = mark_julia_slot(Arg, argType, NULL, tbaa_const); // this argument is by-pointer } else { Argument *Arg = &*AI; ++AI; if (isboxed) // e.g. is-pointer maybe_mark_argument_dereferenceable(Arg, argType); theArg = mark_julia_type(ctx, Arg, isboxed, argType); if (theArg.tbaa == tbaa_immut) theArg.tbaa = tbaa_const; } return theArg; }; if (has_sret) AI++; // skip sret slot if (returninfo.return_roots) AI++; // skip return_roots slot for (i = 0; i < nreq; i++) { jl_sym_t *s = (jl_sym_t*)jl_array_ptr_ref(src->slotnames, i); jl_value_t *argType = jl_nth_slot_type(lam->specTypes, i); bool isboxed = deserves_argbox(argType); Type *llvmArgType = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, argType); if (s == unused_sym) { if (specsig && !type_is_ghost(llvmArgType) && !is_uniquerep_Type(argType)) ++AI; continue; } jl_varinfo_t &vi = ctx.slots[i]; jl_cgval_t theArg; if (s == unused_sym || vi.value.constant) { assert(vi.boxroot == NULL); if (specsig && !type_is_ghost(llvmArgType) && !is_uniquerep_Type(argType)) ++AI; } else { if (specsig) { theArg = get_specsig_arg(argType, llvmArgType, isboxed); } else { if (i == 0) { // first (function) arg is separate in jlcall theArg = mark_julia_type(ctx, fArg, true, vi.value.typ); } else { Value *argPtr = ctx.builder.CreateInBoundsGEP(T_prjlvalue, argArray, ConstantInt::get(T_size, i-1)); Value *load = maybe_mark_load_dereferenceable( ctx.builder.CreateAlignedLoad(T_prjlvalue, argPtr, sizeof(void*)), false, vi.value.typ); theArg = mark_julia_type(ctx, load, true, vi.value.typ); if (ctx.debug_enabled && vi.dinfo && !vi.boxroot && !vi.value.V) { SmallVector<uint64_t, 8> addr; addr.push_back(llvm::dwarf::DW_OP_deref); addr.push_back(llvm::dwarf::DW_OP_plus_uconst); addr.push_back((i - 1) * sizeof(void*)); if ((Metadata*)vi.dinfo->getType() != jl_pvalue_dillvmt) addr.push_back(llvm::dwarf::DW_OP_deref); dbuilder.insertDeclare(pargArray, vi.dinfo, dbuilder.createExpression(addr), topdebugloc, ctx.builder.GetInsertBlock()); } } } if (vi.boxroot == NULL) { assert(vi.value.V == NULL && "unexpected variable slot created for argument"); // keep track of original (possibly boxed) value to avoid re-boxing or moving vi.value = theArg; if (specsig && theArg.V && ctx.debug_enabled && vi.dinfo) { SmallVector<uint64_t, 8> addr; Value *parg; if (theArg.ispointer()) { parg = theArg.V; if ((Metadata*)vi.dinfo->getType() != jl_pvalue_dillvmt) addr.push_back(llvm::dwarf::DW_OP_deref); } else { parg = ctx.builder.CreateAlloca(theArg.V->getType(), NULL, jl_symbol_name(s)); ctx.builder.CreateStore(theArg.V, parg); } dbuilder.insertDeclare(parg, vi.dinfo, dbuilder.createExpression(addr), topdebugloc, ctx.builder.GetInsertBlock()); } } else { Value *argp = boxed(ctx, theArg); ctx.builder.CreateStore(argp, vi.boxroot); } } } // step 10. allocate rest argument CallInst *restTuple = NULL; if (va && ctx.vaSlot != -1) { jl_varinfo_t &vi = ctx.slots[ctx.vaSlot]; if (vi.value.constant || !vi.used) { assert(vi.boxroot == NULL); } else if (specsig) { ctx.nvargs = jl_nparams(lam->specTypes) - nreq; jl_cgval_t *vargs = (jl_cgval_t*)alloca(sizeof(jl_cgval_t) * ctx.nvargs); for (size_t i = nreq; i < jl_nparams(lam->specTypes); ++i) { jl_value_t *argType = jl_nth_slot_type(lam->specTypes, i); bool isboxed = deserves_argbox(argType); Type *llvmArgType = isboxed ? T_prjlvalue : julia_type_to_llvm(ctx, argType); vargs[i - nreq] = get_specsig_arg(argType, llvmArgType, isboxed); } if (jl_is_concrete_type(vi.value.typ)) { jl_cgval_t tuple = emit_new_struct(ctx, vi.value.typ, ctx.nvargs, vargs); emit_varinfo_assign(ctx, vi, tuple); } else { restTuple = emit_jlcall(ctx, jltuple_func, maybe_decay_untracked(V_null), vargs, ctx.nvargs, JLCALL_F_CC); jl_cgval_t tuple = mark_julia_type(ctx, restTuple, true, vi.value.typ); emit_varinfo_assign(ctx, vi, tuple); } } else { // restarg = jl_f_tuple(NULL, &args[nreq], nargs - nreq) Function *F = prepare_call(jltuple_func); restTuple = ctx.builder.CreateCall(F, { maybe_decay_untracked(V_null), ctx.builder.CreateInBoundsGEP(T_prjlvalue, argArray, ConstantInt::get(T_size, nreq - 1)), ctx.builder.CreateSub(argCount, ConstantInt::get(T_int32, nreq - 1)) }); restTuple->setAttributes(F->getAttributes()); ctx.builder.CreateStore(restTuple, vi.boxroot); } } // step 11. Compute properties for each statements // This needs to be computed by iterating in the IR order // instead of control flow order. auto in_user_mod = [] (jl_module_t *mod) { return (!jl_is_submodule(mod, jl_base_module) && !jl_is_submodule(mod, jl_core_module)); }; bool mod_is_user_mod = in_user_mod(ctx.module); struct DebugLineTable { DebugLoc loc; StringRef file; ssize_t line; bool is_user_code; unsigned inlined_at; }; std::vector<DebugLineTable> linetable; { assert(jl_is_array(src->linetable)); size_t nlocs = jl_array_len(src->linetable); std::map<std::tuple<StringRef, StringRef>, DISubprogram*> subprograms; linetable.resize(nlocs + 1); for (size_t i = 0; i < nlocs; i++) { // LineInfoNode(mod::Module, method::Any, file::Symbol, line::Int, inlined_at::Int) jl_value_t *locinfo = jl_array_ptr_ref(src->linetable, i); DebugLineTable &info = linetable[i + 1]; assert(jl_typeis(locinfo, jl_lineinfonode_type)); jl_value_t *method = jl_fieldref_noalloc(locinfo, 0); if (jl_is_method_instance(method)) method = ((jl_method_instance_t*)method)->def.value; jl_sym_t *filesym = (jl_sym_t*)jl_fieldref_noalloc(locinfo, 1); info.line = jl_unbox_long(jl_fieldref(locinfo, 2)); info.inlined_at = jl_unbox_long(jl_fieldref(locinfo, 3)); assert(info.inlined_at <= i); if (jl_is_method(method)) { jl_module_t *module = ((jl_method_t*)method)->module; if (module == ctx.module) info.is_user_code = mod_is_user_mod; else info.is_user_code = in_user_mod(module); } else { info.is_user_code = (info.inlined_at == 0) ? mod_is_user_mod : linetable.at(info.inlined_at).is_user_code; } info.file = jl_symbol_name(filesym); if (info.file.empty()) info.file = "<missing>"; if (ctx.debug_enabled) { StringRef fname; if (jl_is_method(method)) method = (jl_value_t*)((jl_method_t*)method)->name; if (jl_is_symbol(method)) fname = jl_symbol_name((jl_sym_t*)method); if (fname.empty()) fname = "macro expansion"; if (info.inlined_at == 0 && info.file == ctx.file) { // if everything matches, emit a toplevel line number info.loc = DebugLoc::get(info.line, 0, SP, NULL); } else { // otherwise, describe this as an inlining frame DISubprogram *&inl_SP = subprograms[std::make_tuple(fname, info.file)]; if (inl_SP == NULL) { DIFile *difile = dbuilder.createFile(info.file, "."); inl_SP = dbuilder.createFunction(difile ,std::string(fname) + ";" // Name ,fname // LinkageName ,difile // File ,0 // LineNo ,jl_di_func_null_sig // Ty ,0 // ScopeLine ,DINode::FlagZero // Flags ,DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized // SPFlags ,nullptr // Template Parameters ,nullptr // Template Declaration ,nullptr // ThrownTypes ); } DebugLoc inl_loc = (info.inlined_at == 0) ? DebugLoc::get(0, 0, SP, NULL) : linetable.at(info.inlined_at).loc; info.loc = DebugLoc::get(info.line, 0, inl_SP, inl_loc); } } } } std::vector<MDNode*> aliasscopes; MDNode* current_aliasscope = nullptr; std::vector<Metadata*> scope_stack; std::vector<MDNode*> scope_list_stack; { size_t nstmts = jl_array_len(stmts); aliasscopes.resize(nstmts + 1, nullptr); MDBuilder mbuilder(jl_LLVMContext); MDNode *alias_domain = mbuilder.createAliasScopeDomain(ctx.name); for (i = 0; i < nstmts; i++) { jl_value_t *stmt = jl_array_ptr_ref(stmts, i); jl_expr_t *expr = jl_is_expr(stmt) ? (jl_expr_t*)stmt : nullptr; if (expr) { if (expr->head == aliasscope_sym) { MDNode *scope = mbuilder.createAliasScope("aliasscope", alias_domain); scope_stack.push_back(scope); MDNode *scope_list = MDNode::get(jl_LLVMContext, ArrayRef<Metadata*>(scope_stack)); scope_list_stack.push_back(scope_list); current_aliasscope = scope_list; } else if (expr->head == popaliasscope_sym) { scope_stack.pop_back(); scope_list_stack.pop_back(); if (scope_list_stack.empty()) { current_aliasscope = NULL; } else { current_aliasscope = scope_list_stack.back(); } } } aliasscopes[i+1] = current_aliasscope; } } Instruction &prologue_end = ctx.builder.GetInsertBlock()->back(); // step 12. Do codegen in control flow order std::vector<int> workstack; std::map<int, BasicBlock*> BB; std::map<size_t, BasicBlock*> come_from_bb; int cursor = 0; auto find_next_stmt = [&] (int seq_next) { // new style ir is always in dominance order, but frontend IR might not be // `seq_next` is the next statement we want to emit // i.e. if it exists, it's the next one following control flow and // should be emitted into the current insert point. if (seq_next >= 0 && (unsigned)seq_next < stmtslen) { workstack.push_back(seq_next); } else if (!ctx.builder.GetInsertBlock()->getTerminator()) { ctx.builder.CreateUnreachable(); } while (!workstack.empty()) { int item = workstack.back(); workstack.pop_back(); auto nextbb = BB.find(item + 1); if (nextbb == BB.end()) { cursor = item; return; } if (seq_next != -1 && !ctx.builder.GetInsertBlock()->getTerminator()) { come_from_bb[cursor + 1] = ctx.builder.GetInsertBlock(); ctx.builder.CreateBr(nextbb->second); } seq_next = -1; // if this BB is non-empty, we've visited it before so skip it if (!nextbb->second->getTerminator()) { ctx.builder.SetInsertPoint(nextbb->second); cursor = item; return; } } cursor = -1; }; auto do_coverage = [&] (bool in_user_code) { return (coverage_mode == JL_LOG_ALL || (coverage_mode == JL_LOG_USER && in_user_code)); }; auto do_malloc_log = [&] (bool in_user_code) { return (malloc_log_mode == JL_LOG_ALL || (malloc_log_mode == JL_LOG_USER && in_user_code)); }; std::vector<unsigned> current_lineinfo, new_lineinfo; auto coverageVisitStmt = [&] (size_t dbg) { if (dbg == 0) return; // Compute inlining stack for current line, inner frame first while (dbg) { new_lineinfo.push_back(dbg); dbg = linetable.at(dbg).inlined_at; } // Visit frames which differ from previous statement as tracked in // current_lineinfo (tracked outer frame first). current_lineinfo.resize(new_lineinfo.size(), 0); for (dbg = 0; dbg < new_lineinfo.size(); dbg++) { unsigned newdbg = new_lineinfo[new_lineinfo.size() - dbg - 1]; if (newdbg != current_lineinfo[dbg]) { current_lineinfo[dbg] = newdbg; const auto &info = linetable.at(newdbg); if (do_coverage(info.is_user_code)) coverageVisitLine(ctx, info.file, info.line); } } new_lineinfo.clear(); }; auto mallocVisitStmt = [&] (unsigned dbg, Value *sync) { if (!do_malloc_log(mod_is_user_mod) || dbg == 0) { if (do_malloc_log(true) && sync) ctx.builder.CreateCall(prepare_call(sync_gc_total_bytes_func), {sync}); return; } while (linetable.at(dbg).inlined_at) dbg = linetable.at(dbg).inlined_at; mallocVisitLine(ctx, ctx.file, linetable.at(dbg).line, sync); }; if (coverage_mode != JL_LOG_NONE) { // record all lines that could be covered for (const auto &info : linetable) if (do_coverage(info.is_user_code)) coverageAllocLine(info.file, info.line); } come_from_bb[0] = ctx.builder.GetInsertBlock(); // First go through and collect all branch targets, so we know where to // split basic blocks. std::set<int> branch_targets; // 1-indexed { for (size_t i = 0; i < stmtslen; ++i) { jl_value_t *stmt = jl_array_ptr_ref(stmts, i); if (jl_is_gotoifnot(stmt)) { int dest = jl_gotoifnot_label(stmt); branch_targets.insert(dest); // The next 1-indexed statement branch_targets.insert(i + 2); } else if (jl_is_returnnode(stmt)) { // We don't do dead branch elimination before codegen // so we need to make sure to start a BB after any // return node, even if they aren't otherwise branch // targets. if (i + 2 <= stmtslen) branch_targets.insert(i + 2); } else if (jl_is_expr(stmt)) { if (((jl_expr_t*)stmt)->head == enter_sym) { branch_targets.insert(i + 1); if (i + 2 <= stmtslen) branch_targets.insert(i + 2); int dest = jl_unbox_long(jl_array_ptr_ref(((jl_expr_t*)stmt)->args, 0)); branch_targets.insert(dest); } } else if (jl_is_gotonode(stmt)) { int dest = jl_gotonode_label(stmt); branch_targets.insert(dest); if (i + 2 <= stmtslen) branch_targets.insert(i + 2); } else if (jl_is_phinode(stmt)) { jl_array_t *edges = (jl_array_t*)jl_fieldref_noalloc(stmt, 0); for (size_t j = 0; j < jl_array_len(edges); ++j) { size_t edge = jl_unbox_long(jl_array_ptr_ref(edges, j)); if (edge == i) branch_targets.insert(i + 1); } } } } for (int label : branch_targets) { BasicBlock *bb = BasicBlock::Create(jl_LLVMContext, "L" + std::to_string(label), f); BB[label] = bb; } Value *sync_bytes = nullptr; if (do_malloc_log(true)) sync_bytes = ctx.builder.CreateCall(prepare_call(diff_gc_total_bytes_func), {}); find_next_stmt(0); while (cursor != -1) { int32_t debuginfoloc = ((int32_t*)jl_array_data(src->codelocs))[cursor]; if (debuginfoloc > 0) { if (ctx.debug_enabled) ctx.builder.SetCurrentDebugLocation(linetable.at(debuginfoloc).loc); coverageVisitStmt(debuginfoloc); } ctx.aliasscope = aliasscopes[cursor]; jl_value_t *stmt = jl_array_ptr_ref(stmts, cursor); jl_expr_t *expr = jl_is_expr(stmt) ? (jl_expr_t*)stmt : nullptr; if (jl_is_returnnode(stmt)) { jl_value_t *retexpr = jl_returnnode_value(stmt); if (retexpr == NULL) { ctx.builder.CreateUnreachable(); find_next_stmt(-1); continue; } // this is basically a copy of emit_assignment, // but where the assignment slot is the retval jl_cgval_t retvalinfo = emit_expr(ctx, retexpr); retvalinfo = convert_julia_type(ctx, retvalinfo, jlrettype); if (retvalinfo.typ == jl_bottom_type) { ctx.builder.CreateUnreachable(); find_next_stmt(-1); continue; } Value *isboxed_union = NULL; Value *retval = NULL; Value *sret = has_sret ? f->arg_begin() : NULL; Type *retty = f->getReturnType(); switch (returninfo.cc) { case jl_returninfo_t::Boxed: retval = boxed(ctx, retvalinfo); // skip the gcroot on the return path break; case jl_returninfo_t::Register: if (type_is_ghost(retty)) retval = NULL; else retval = emit_unbox(ctx, retty, retvalinfo, jlrettype); break; case jl_returninfo_t::SRet: retval = NULL; break; case jl_returninfo_t::Union: { Value *data, *tindex; if (retvalinfo.TIndex) { tindex = retvalinfo.TIndex; if (retvalinfo.V == NULL) { // treat this as a simple Ghosts data = maybe_decay_untracked(V_null); sret = NULL; } else { data = maybe_decay_untracked(V_null); if (retvalinfo.Vboxed) { // also need to account for the possibility the return object is boxed // and avoid / skip copying it to the stack isboxed_union = ctx.builder.CreateICmpNE( ctx.builder.CreateAnd(tindex, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)); data = ctx.builder.CreateSelect(isboxed_union, retvalinfo.Vboxed, data); } } } else { // treat this as a simple boxed returninfo //assert(retvalinfo.isboxed); tindex = compute_tindex_unboxed(ctx, retvalinfo, jlrettype); tindex = ctx.builder.CreateOr(tindex, ConstantInt::get(T_int8, 0x80)); data = maybe_decay_untracked(boxed(ctx, retvalinfo)); sret = NULL; } retval = UndefValue::get(retty); retval = ctx.builder.CreateInsertValue(retval, data, 0); retval = ctx.builder.CreateInsertValue(retval, tindex, 1); break; } case jl_returninfo_t::Ghosts: retval = compute_tindex_unboxed(ctx, retvalinfo, jlrettype); break; } if (sret) { if (retvalinfo.ispointer()) { if (returninfo.return_roots) { Type *store_ty = julia_type_to_llvm(ctx, retvalinfo.typ); emit_sret_roots(ctx, true, data_pointer(ctx, retvalinfo), store_ty, f->arg_begin() + 1, returninfo.return_roots); } if (returninfo.cc == jl_returninfo_t::SRet) { assert(jl_is_concrete_type(jlrettype)); emit_memcpy(ctx, sret, nullptr, retvalinfo, jl_datatype_size(jlrettype), julia_alignment(jlrettype)); } else { // must be jl_returninfo_t::Union emit_unionmove(ctx, sret, nullptr, retvalinfo, /*skip*/isboxed_union); } } else { Type *store_ty = retvalinfo.V->getType(); Type *dest_ty = store_ty->getPointerTo(); Value *Val = retvalinfo.V; if (returninfo.return_roots) { assert(julia_type_to_llvm(ctx, retvalinfo.typ) == store_ty); emit_sret_roots(ctx, false, Val, store_ty, f->arg_begin() + 1, returninfo.return_roots); } if (dest_ty != sret->getType()) sret = emit_bitcast(ctx, sret, dest_ty); ctx.builder.CreateAlignedStore(Val, sret, julia_alignment(retvalinfo.typ)); assert(retvalinfo.TIndex == NULL && "unreachable"); // unimplemented representation } } mallocVisitStmt(debuginfoloc, sync_bytes); if (toplevel) ctx.builder.CreateStore(last_age, ctx.world_age_field); assert(type_is_ghost(retty) || returninfo.cc == jl_returninfo_t::SRet || retval->getType() == ctx.f->getReturnType()); ctx.builder.CreateRet(retval); find_next_stmt(-1); continue; } if (jl_is_gotonode(stmt)) { int lname = jl_gotonode_label(stmt); come_from_bb[cursor+1] = ctx.builder.GetInsertBlock(); ctx.builder.CreateBr(BB[lname]); find_next_stmt(lname - 1); continue; } if (jl_is_upsilonnode(stmt)) { jl_value_t *val = jl_fieldref_noalloc(stmt, 0); // If the val is null, we can ignore the store. // The middle end guarantees that the value from this // upsilon node is not dynamically observed. jl_varinfo_t &vi = ctx.phic_slots[upsilon_to_phic[cursor+1]]; if (val) { jl_cgval_t rval_info = emit_expr(ctx, val); emit_varinfo_assign(ctx, vi, rval_info); } else if (vi.pTIndex) { // We don't care what the contents of the variable are, but it // does need to satisfy the union invariants (i.e. inbounds // tindex). ctx.builder.CreateStore( vi.boxroot ? ConstantInt::get(T_int8, 0x80) : ConstantInt::get(T_int8, 0x01), vi.pTIndex, true); } find_next_stmt(cursor + 1); continue; } if (jl_is_gotoifnot(stmt)) { jl_value_t *cond = jl_gotoifnot_cond(stmt); int lname = jl_gotoifnot_label(stmt); Value *isfalse = emit_condition(ctx, cond, "if"); mallocVisitStmt(debuginfoloc, nullptr); come_from_bb[cursor+1] = ctx.builder.GetInsertBlock(); workstack.push_back(lname - 1); BasicBlock *ifnot = BB[lname]; BasicBlock *ifso = BB[cursor+2]; if (ifnot == ifso) ctx.builder.CreateBr(ifnot); else ctx.builder.CreateCondBr(isfalse, ifnot, ifso); find_next_stmt(cursor + 1); continue; } else if (expr && expr->head == enter_sym) { jl_value_t **args = (jl_value_t**)jl_array_data(expr->args); assert(jl_is_long(args[0])); int lname = jl_unbox_long(args[0]); // Save exception stack depth at enter for use in pop_exception Value *excstack_state = ctx.builder.CreateCall(prepare_call(jl_excstack_state_func)); assert(!ctx.ssavalue_assigned.at(cursor)); ctx.SAvalues.at(cursor) = jl_cgval_t(excstack_state, NULL, false, (jl_value_t*)jl_ulong_type, NULL); ctx.ssavalue_assigned.at(cursor) = true; CallInst *sj = ctx.builder.CreateCall(prepare_call(except_enter_func)); // We need to mark this on the call site as well. See issue #6757 sj->setCanReturnTwice(); Value *isz = ctx.builder.CreateICmpEQ(sj, ConstantInt::get(T_int32, 0)); BasicBlock *tryblk = BasicBlock::Create(jl_LLVMContext, "try", f); BasicBlock *handlr = NULL; handlr = BB[lname]; workstack.push_back(lname - 1); come_from_bb[cursor + 1] = ctx.builder.GetInsertBlock(); ctx.builder.CreateCondBr(isz, tryblk, handlr); ctx.builder.SetInsertPoint(tryblk); } else { emit_stmtpos(ctx, stmt, cursor); mallocVisitStmt(debuginfoloc, nullptr); } find_next_stmt(cursor + 1); } // Delete any unreachable blocks for (auto &item : BB) { if (!item.second->getTerminator()) item.second->eraseFromParent(); } ctx.builder.SetCurrentDebugLocation(noDbg); ctx.builder.ClearInsertionPoint(); auto undef_value_for_type = [&](Type *T) { auto tracked = CountTrackedPointers(T); Value *undef; if (tracked.count) // make sure gc pointers (including ptr_phi of union-split) are initialized to NULL undef = Constant::getNullValue(T); else undef = UndefValue::get(T); return undef; }; // Codegen Phi nodes std::map<std::pair<BasicBlock*, BasicBlock*>, BasicBlock*> BB_rewrite_map; std::vector<llvm::PHINode*> ToDelete; for (auto &tup : ctx.PhiNodes) { jl_cgval_t phi_result; PHINode *VN; jl_value_t *r; AllocaInst *dest; BasicBlock *PhiBB; std::tie(phi_result, PhiBB, dest, VN, r) = tup; jl_value_t *phiType = phi_result.typ; jl_array_t *edges = (jl_array_t*)jl_fieldref_noalloc(r, 0); jl_array_t *values = (jl_array_t*)jl_fieldref_noalloc(r, 1); PHINode *TindexN = cast_or_null<PHINode>(phi_result.TIndex); DenseSet<BasicBlock*> preds; for (size_t i = 0; i < jl_array_len(edges); ++i) { size_t edge = jl_unbox_long(jl_array_ptr_ref(edges, i)); jl_value_t *value = jl_array_ptr_ref(values, i); // This edge value is undef, handle it the same as if the edge wasn't listed at all if (!value) continue; BasicBlock *FromBB = come_from_bb[edge]; // This edge was statically unreachable. Don't codegen it. if (!FromBB) continue; // see if this edge has already been rewritten // (we'll continue appending blocks to the current end) std::pair<BasicBlock*, BasicBlock*> LookupKey(FromBB, PhiBB); if (BB_rewrite_map.count(LookupKey)) { FromBB = BB_rewrite_map[LookupKey]; } if (!preds.insert(FromBB).second) { // Only codegen this branch once for each PHI (the expression must be the same on all branches) #ifndef NDEBUG for (size_t j = 0; j < i; ++j) { size_t j_edge = jl_unbox_long(jl_array_ptr_ref(edges, j)); if (j_edge == edge) { assert(jl_egal(value, jl_array_ptr_ref(values, j))); } } #endif continue; } assert(find(pred_begin(PhiBB), pred_end(PhiBB), FromBB) != pred_end(PhiBB)); // consistency check TerminatorInst *terminator = FromBB->getTerminator(); if (!terminator->getParent()->getUniqueSuccessor()) { // Can't use `llvm::SplitCriticalEdge` here because // we may have invalid phi nodes in the destination. BasicBlock *NewBB = BasicBlock::Create(terminator->getContext(), FromBB->getName() + "." + PhiBB->getName() + "_crit_edge"); Function::iterator FBBI = FromBB->getIterator(); ctx.f->getBasicBlockList().insert(++FBBI, NewBB); // insert after existing block #if JL_LLVM_VERSION >= 90000 terminator->replaceSuccessorWith(PhiBB, NewBB); #else for (unsigned Idx = 0, NumSuccessors = terminator->getNumSuccessors(); Idx != NumSuccessors; ++Idx) { if (terminator->getSuccessor(Idx) == PhiBB) terminator->setSuccessor(Idx, NewBB); } #endif DebugLoc Loc = terminator->getDebugLoc(); terminator = BranchInst::Create(PhiBB); terminator->setDebugLoc(Loc); ctx.builder.SetInsertPoint(NewBB); } else { terminator->removeFromParent(); ctx.builder.SetInsertPoint(FromBB); } if (dest) ctx.builder.CreateLifetimeStart(dest); jl_cgval_t val = emit_expr(ctx, value); if (val.constant) val = mark_julia_const(val.constant); // be over-conservative at making sure `.typ` is set concretely, not tindex if (!jl_is_uniontype(phiType) || !TindexN) { Type *lty = julia_type_to_llvm(ctx, phiType); if (VN) { Value *V; if (val.typ == (jl_value_t*)jl_bottom_type) { V = undef_value_for_type(VN->getType()); } else if (VN && VN->getType() == T_prjlvalue) { // Includes the jl_is_uniontype(phiType) && !TindexN case V = boxed(ctx, val); } else { V = emit_unbox(ctx, VN->getType(), val, phiType); } VN->addIncoming(V, ctx.builder.GetInsertBlock()); assert(!TindexN); } else if (dest && val.typ != (jl_value_t*)jl_bottom_type) { assert(lty != T_prjlvalue); (void)emit_unbox(ctx, lty, val, phiType, maybe_decay_tracked(dest)); } } else { Value *RTindex; Value *V; if (val.typ == (jl_value_t*)jl_bottom_type) { V = undef_value_for_type(VN->getType()); RTindex = UndefValue::get(T_int8); } else if (jl_is_concrete_type(val.typ) || val.constant) { size_t tindex = get_box_tindex((jl_datatype_t*)val.typ, phiType); if (tindex == 0) { V = boxed(ctx, val); RTindex = ConstantInt::get(T_int8, 0x80); } else { V = ConstantPointerNull::get(cast<PointerType>(T_prjlvalue)); Type *lty = julia_type_to_llvm(ctx, val.typ); if (dest && !type_is_ghost(lty)) // basically, if !ghost union emit_unbox(ctx, lty, val, val.typ, dest); RTindex = ConstantInt::get(T_int8, tindex); } } else { jl_cgval_t new_union = convert_julia_type(ctx, val, phiType); RTindex = new_union.TIndex; if (!RTindex) { assert(new_union.isboxed && new_union.Vboxed && "convert_julia_type failed"); RTindex = compute_tindex_unboxed(ctx, new_union, phiType); if (dest) { // If dest is not set, this is a ghost union, the recipient of which // is often not prepared to handle a boxed representation of the ghost. RTindex = ctx.builder.CreateOr(RTindex, ConstantInt::get(T_int8, 0x80)); } new_union.TIndex = RTindex; } V = new_union.Vboxed ? new_union.Vboxed : ConstantPointerNull::get(cast<PointerType>(T_prjlvalue)); if (dest) { // basically, if !ghost union Value *skip = NULL; if (new_union.Vboxed != nullptr) skip = ctx.builder.CreateICmpNE( // if 0x80 is set, we won't select this slot anyways ctx.builder.CreateAnd(RTindex, ConstantInt::get(T_int8, 0x80)), ConstantInt::get(T_int8, 0)); emit_unionmove(ctx, dest, tbaa_arraybuf, new_union, skip); } } if (VN) VN->addIncoming(V, ctx.builder.GetInsertBlock()); if (TindexN) TindexN->addIncoming(RTindex, ctx.builder.GetInsertBlock()); } // put the branch back at the end of our current basic block ctx.builder.Insert(terminator); // Record the current tail of this Phi edge in the rewrite map and // check any phi nodes in the Phi block to see if by emitting on the edges // we made things inconsistent. BasicBlock *NewBB = ctx.builder.GetInsertBlock(); if (FromBB != NewBB) { BB_rewrite_map[LookupKey] = NewBB; preds.insert(NewBB); #if JL_LLVM_VERSION >= 90000 PhiBB->replacePhiUsesWith(FromBB, NewBB); #else for (BasicBlock::iterator I = PhiBB->begin(); isa<PHINode>(I); ++I) { PHINode *PN = cast<PHINode>(I); ssize_t BBIdx = PN->getBasicBlockIndex(FromBB); if (BBIdx == -1) continue; PN->setIncomingBlock(BBIdx, NewBB); } #endif } ctx.builder.ClearInsertionPoint(); } // In LLVM IR it is illegal to have phi nodes without incoming values, even if // there are no operands (no incoming branches), so delete any such phi nodes if (pred_empty(PhiBB)) { if (VN) ToDelete.push_back(VN); if (TindexN) ToDelete.push_back(TindexN); continue; } // Julia PHINodes may be incomplete with respect to predecessors, LLVM's may not for (auto *FromBB : predecessors(PhiBB)) { if (preds.count(FromBB)) continue; ctx.builder.SetInsertPoint(FromBB->getTerminator()); // PHI is undef on this branch. But still may need to put a valid pointer in place. Value *RTindex = TindexN ? UndefValue::get(T_int8) : NULL; if (VN) { Value *undef = undef_value_for_type(VN->getType()); VN->addIncoming(undef, FromBB); if (TindexN) // let the runtime / optimizer know this is unknown / boxed / null, so that it won't try to union_move / copy it later RTindex = ConstantInt::get(T_int8, 0x80); } if (TindexN) TindexN->addIncoming(RTindex, FromBB); if (dest) { ctx.builder.CreateLifetimeStart(dest); if (CountTrackedPointers(dest->getAllocatedType()).count) ctx.builder.CreateStore(Constant::getNullValue(dest->getAllocatedType()), dest); } ctx.builder.ClearInsertionPoint(); } } for (PHINode *PN : ToDelete) { PN->replaceAllUsesWith(UndefValue::get(PN->getType())); PN->eraseFromParent(); } // step 13. Perform any delayed instantiations if (ctx.debug_enabled) { bool in_prologue = true; for (auto &BB : *ctx.f) { for (auto &I : BB) { CallBase *call = dyn_cast<CallBase>(&I); if (call && !I.getDebugLoc()) { // LLVM Verifier: inlinable function call in a function with debug info must have a !dbg location // make sure that anything we attempt to call has some inlining info, just in case optimization messed up // (except if we know that it is an intrinsic used in our prologue, which should never have its own debug subprogram) Function *F = call->getCalledFunction(); if (!in_prologue || !F || !(F->isIntrinsic() || F->getName().startswith("julia.") || &I == restTuple)) { I.setDebugLoc(topdebugloc); } } if (&I == &prologue_end) in_prologue = false; } } dbuilder.finalize(); } if (ctx.vaSlot > 0) { // remove VA allocation if we never referenced it Instruction *root = cast_or_null<Instruction>(ctx.slots[ctx.vaSlot].boxroot); if (root) { Instruction *store_value = NULL; bool have_real_use = false; for (Use &U : root->uses()) { User *RU = U.getUser(); if (StoreInst *SRU = dyn_cast<StoreInst>(RU)) { if (!store_value) store_value = dyn_cast<Instruction>(SRU->getValueOperand()); } else if (isa<DbgInfoIntrinsic>(RU)) { } else if (isa<LoadInst>(RU) && RU->use_empty()) { } else { have_real_use = true; break; } } if (!have_real_use) { Instruction *use = NULL; for (Use &U : root->uses()) { if (use) // erase after the iterator moves on use->eraseFromParent(); User *RU = U.getUser(); use = cast<Instruction>(RU); } if (use) use->eraseFromParent(); root->eraseFromParent(); assert(!store_value || store_value == restTuple); restTuple->eraseFromParent(); } } } // copy ctx.roots into m->roots // if we created any new roots during codegen if (ctx.roots) { jl_method_t *m = lam->def.method; JL_LOCK(&m->writelock); if (m->roots == NULL) { m->roots = ctx.roots; jl_gc_wb(m, m->roots); } else { size_t i, ilen = jl_array_dim0(ctx.roots); size_t j, jlen = jl_array_dim0(m->roots); for (i = 0; i < ilen; i++) { jl_value_t *ival = jl_array_ptr_ref(ctx.roots, i); for (j = 0; j < jlen; j++) { jl_value_t *jval = jl_array_ptr_ref(m->roots, j); if (ival == jval) break; } if (j == jlen) // not found - add to array jl_array_ptr_1d_push(m->roots, ival); } } ctx.roots = NULL; JL_UNLOCK(&m->writelock); } if (JL_HOOK_TEST(ctx.params, emitted_function)) { JL_HOOK_CALL(ctx.params, emitted_function, 2, (jl_value_t*)ctx.linfo, (jl_value_t*)ctx.source); } JL_GC_POP(); return std::make_pair(std::unique_ptr<Module>(M), declarations); } // --- entry point --- void jl_add_code_in_flight(StringRef name, jl_code_instance_t *codeinst, const DataLayout &DL); JL_GCC_IGNORE_START("-Wclobbered") jl_compile_result_t jl_emit_code( jl_method_instance_t *li, jl_code_info_t *src, jl_value_t *jlrettype, jl_codegen_params_t &params) { // caller must hold codegen_lock jl_llvm_functions_t decls = {}; std::unique_ptr<Module> m; assert((params.params == &jl_default_cgparams /* fast path */ || !params.cache || compare_cgparams(params.params, &jl_default_cgparams)) && "functions compiled with custom codegen params must not be cached"); JL_TRY { std::tie(m, decls) = emit_function(li, src, jlrettype, params); } JL_CATCH { // Something failed! This is very, very bad. // Try to pretend that it isn't and attempt to recover. m.reset(); decls.functionObject = ""; decls.specFunctionObject = ""; const char *mname = name_from_method_instance(li); jl_printf((JL_STREAM*)STDERR_FILENO, "Internal error: encountered unexpected error during compilation of %s:\n", mname); jl_static_show((JL_STREAM*)STDERR_FILENO, jl_current_exception()); jl_printf((JL_STREAM*)STDERR_FILENO, "\n"); jlbacktrace(); // written to STDERR_FILENO } return std::make_tuple(std::move(m), decls); } jl_compile_result_t jl_emit_codeinst( jl_code_instance_t *codeinst, jl_code_info_t *src, jl_codegen_params_t &params) { JL_GC_PUSH1(&src); if (!src) { src = (jl_code_info_t*)codeinst->inferred; jl_method_t *def = codeinst->def->def.method; if (src && (jl_value_t*)src != jl_nothing && jl_is_method(def)) src = jl_uncompress_ir(def, codeinst, (jl_array_t*)src); if (!src || !jl_is_code_info(src)) { JL_GC_POP(); return jl_compile_result_t(); // failed } } jl_compile_result_t result = jl_emit_code(codeinst->def, src, codeinst->rettype, params); const jl_llvm_functions_t &decls = std::get<1>(result); const std::string &specf = decls.specFunctionObject; const std::string &f = decls.functionObject; if (params.cache && !f.empty()) { const Module *m = std::get<0>(result).get(); // Prepare debug info to receive this function // record that this function name came from this linfo, // so we can build a reverse mapping for debug-info. if (!JL_HOOK_TEST(params.params, module_activation)) { bool toplevel = !jl_is_method(codeinst->def->def.method); if (!toplevel) { const DataLayout &DL = m->getDataLayout(); // but don't remember toplevel thunks because // they may not be rooted in the gc for the life of the program, // and the runtime doesn't notify us when the code becomes unreachable :( if (!specf.empty()) jl_add_code_in_flight(specf, codeinst, DL); if (!f.empty() && f != "jl_fptr_args" && f != "jl_fptr_sparam") jl_add_code_in_flight(f, codeinst, DL); } } if (// don't alter `inferred` when the code is not directly being used params.world && // don't change inferred state codeinst->inferred) { jl_method_t *def = codeinst->def->def.method; if (// keep code when keeping everything !(JL_DELETE_NON_INLINEABLE) || // aggressively keep code when debugging level >= 2 jl_options.debug_level > 1) { // update the stored code if (codeinst->inferred != (jl_value_t*)src) { if (jl_is_method(def)) src = (jl_code_info_t*)jl_compress_ir(def, src); codeinst->inferred = (jl_value_t*)src; jl_gc_wb(codeinst, src); } } else if (// don't delete toplevel code jl_is_method(def) && // and there is something to delete (test this before calling jl_ir_flag_inlineable) codeinst->inferred != jl_nothing && // don't delete inlineable code, unless it is constant (codeinst->invoke == jl_fptr_const_return || !jl_ir_flag_inlineable((jl_array_t*)codeinst->inferred)) && // don't delete code when generating a precompile file !imaging_mode) { // if not inlineable, code won't be needed again codeinst->inferred = jl_nothing; } } } JL_GC_POP(); return result; } void jl_compile_workqueue( std::map<jl_code_instance_t*, jl_compile_result_t> &emitted, jl_codegen_params_t &params, CompilationPolicy policy) { jl_code_info_t *src = NULL; JL_GC_PUSH1(&src); while (!params.workqueue.empty()) { jl_code_instance_t *codeinst; Function *protodecl; jl_returninfo_t::CallingConv proto_cc; bool proto_specsig; unsigned proto_return_roots; std::tie(codeinst, proto_cc, proto_return_roots, protodecl, proto_specsig) = params.workqueue.back(); params.workqueue.pop_back(); // try to emit code for this item from the workqueue assert(codeinst->min_world <= params.world && codeinst->max_world >= params.world && "invalid world for code-instance"); StringRef preal_decl = ""; bool preal_specsig = false; if (params.cache && codeinst->invoke != NULL) { if (codeinst->invoke == jl_fptr_args) { preal_decl = jl_ExecutionEngine->getFunctionAtAddress((uintptr_t)codeinst->specptr.fptr, codeinst); } else if (codeinst->isspecsig) { preal_decl = jl_ExecutionEngine->getFunctionAtAddress((uintptr_t)codeinst->specptr.fptr, codeinst); preal_specsig = true; } } else { jl_compile_result_t &result = emitted[codeinst]; jl_llvm_functions_t *decls = NULL; if (std::get<0>(result)) { decls = &std::get<1>(result); } else { // Reinfer the function. The JIT came along and removed the inferred // method body. See #34993 if (policy == CompilationPolicy::Extern && codeinst->inferred && codeinst->inferred == jl_nothing) { src = jl_type_infer(codeinst->def, jl_world_counter, 0); if (src) result = jl_emit_code(codeinst->def, src, src->rettype, params); } else { result = jl_emit_codeinst(codeinst, NULL, params); } if (std::get<0>(result)) decls = &std::get<1>(result); else emitted.erase(codeinst); // undo the insert above } if (decls) { if (decls->functionObject == "jl_fptr_args") { preal_decl = decls->specFunctionObject; } else if (decls->functionObject != "jl_fptr_sparam") { preal_decl = decls->specFunctionObject; preal_specsig = true; } } } // patch up the prototype we emitted earlier Module *mod = protodecl->getParent(); assert(protodecl->isDeclaration()); if (proto_specsig) { // expected specsig if (!preal_specsig) { // emit specsig-to-(jl)invoke conversion Function *preal = emit_tojlinvoke(codeinst, mod, params); protodecl->setLinkage(GlobalVariable::PrivateLinkage); //protodecl->setAlwaysInline(); protodecl->addFnAttr("no-frame-pointer-elim", "true"); size_t nrealargs = jl_nparams(codeinst->def->specTypes); // number of actual arguments being passed // TODO: maybe this can be cached in codeinst->specfptr? emit_cfunc_invalidate(protodecl, proto_cc, proto_return_roots, codeinst->def->specTypes, codeinst->rettype, nrealargs, params, preal); preal_decl = ""; // no need to fixup the name } else { assert(!preal_decl.empty()); } } else { // expected non-specsig if (preal_decl.empty() || preal_specsig) { // emit jlcall1-to-(jl)invoke conversion preal_decl = emit_tojlinvoke(codeinst, mod, params)->getName(); } } if (!preal_decl.empty()) { // merge and/or rename this prototype to the real function if (Value *specfun = mod->getNamedValue(preal_decl)) { if (protodecl != specfun) protodecl->replaceAllUsesWith(specfun); } else { protodecl->setName(preal_decl); } } } JL_GC_POP(); } // --- initialization --- std::pair<MDNode*,MDNode*> tbaa_make_child(const char *name, MDNode *parent=nullptr, bool isConstant=false) { MDBuilder mbuilder(jl_LLVMContext); if (tbaa_root == nullptr) { MDNode *jtbaa = mbuilder.createTBAARoot("jtbaa"); tbaa_root = mbuilder.createTBAAScalarTypeNode("jtbaa", jtbaa); } MDNode *scalar = mbuilder.createTBAAScalarTypeNode(name, parent ? parent : tbaa_root); MDNode *n = mbuilder.createTBAAStructTagNode(scalar, scalar, 0, isConstant); return std::make_pair(n, scalar); } std::vector<std::pair<jl_value_t**, JuliaVariable*>> gv_for_global; static void global_jlvalue_to_llvm(JuliaVariable *var, jl_value_t **addr) { gv_for_global.push_back(std::make_pair(addr, var)); } static JuliaVariable *julia_const_gv(jl_value_t *val) { for (auto &kv : gv_for_global) { if (*kv.first == val) return kv.second; } return nullptr; } static void init_julia_llvm_meta(void) { tbaa_gcframe = tbaa_make_child("jtbaa_gcframe").first; MDNode *tbaa_stack_scalar; std::tie(tbaa_stack, tbaa_stack_scalar) = tbaa_make_child("jtbaa_stack"); tbaa_unionselbyte = tbaa_make_child("jtbaa_unionselbyte", tbaa_stack_scalar).first; MDNode *tbaa_data_scalar; std::tie(tbaa_data, tbaa_data_scalar) = tbaa_make_child("jtbaa_data"); tbaa_binding = tbaa_make_child("jtbaa_binding", tbaa_data_scalar).first; MDNode *tbaa_value_scalar; std::tie(tbaa_value, tbaa_value_scalar) = tbaa_make_child("jtbaa_value", tbaa_data_scalar); tbaa_mutab = tbaa_make_child("jtbaa_mutab", tbaa_value_scalar).first; tbaa_immut = tbaa_make_child("jtbaa_immut", tbaa_value_scalar).first; tbaa_arraybuf = tbaa_make_child("jtbaa_arraybuf", tbaa_data_scalar).first; tbaa_ptrarraybuf = tbaa_make_child("jtbaa_ptrarraybuf", tbaa_data_scalar).first; MDNode *tbaa_array_scalar; std::tie(tbaa_array, tbaa_array_scalar) = tbaa_make_child("jtbaa_array"); tbaa_arrayptr = tbaa_make_child("jtbaa_arrayptr", tbaa_array_scalar).first; tbaa_arraysize = tbaa_make_child("jtbaa_arraysize", tbaa_array_scalar).first; tbaa_arraylen = tbaa_make_child("jtbaa_arraylen", tbaa_array_scalar).first; tbaa_arrayflags = tbaa_make_child("jtbaa_arrayflags", tbaa_array_scalar).first; tbaa_arrayoffset = tbaa_make_child("jtbaa_arrayoffset", tbaa_array_scalar).first; tbaa_const = tbaa_make_child("jtbaa_const", nullptr, true).first; tbaa_arrayselbyte = tbaa_make_child("jtbaa_arrayselbyte", tbaa_array_scalar).first; Thunk = Attribute::get(jl_LLVMContext, "thunk"); } static void init_julia_llvm_env(Module *m) { // every variable or function mapped in this function must be // exported from libjulia, to support static compilation T_int1 = Type::getInt1Ty(jl_LLVMContext); T_int8 = Type::getInt8Ty(jl_LLVMContext); T_pint8 = PointerType::get(T_int8, 0); T_ppint8 = PointerType::get(T_pint8, 0); T_pppint8 = PointerType::get(T_ppint8, 0); T_int16 = Type::getInt16Ty(jl_LLVMContext); T_pint16 = PointerType::get(T_int16, 0); T_int32 = Type::getInt32Ty(jl_LLVMContext); T_char = Type::getInt32Ty(jl_LLVMContext); T_pint32 = PointerType::get(T_int32, 0); T_int64 = Type::getInt64Ty(jl_LLVMContext); T_pint64 = PointerType::get(T_int64, 0); T_uint8 = T_int8; T_uint16 = T_int16; T_uint32 = T_int32; T_uint64 = T_int64; if (sizeof(size_t) == 8) T_size = T_uint64; else T_size = T_uint32; T_sigatomic = Type::getIntNTy(jl_LLVMContext, sizeof(sig_atomic_t) * 8); T_psize = PointerType::get(T_size, 0); T_float16 = Type::getHalfTy(jl_LLVMContext); T_float32 = Type::getFloatTy(jl_LLVMContext); T_pfloat32 = PointerType::get(T_float32, 0); T_float64 = Type::getDoubleTy(jl_LLVMContext); T_pfloat64 = PointerType::get(T_float64, 0); T_float128 = Type::getFP128Ty(jl_LLVMContext); T_void = Type::getVoidTy(jl_LLVMContext); T_pvoidfunc = FunctionType::get(T_void, /*isVarArg*/false)->getPointerTo(); // add needed base debugging definitions to our LLVM environment DIBuilder dbuilder(*m); DIFile *julia_h = dbuilder.createFile("julia.h", ""); jl_value_dillvmt = dbuilder.createStructType(nullptr, "jl_value_t", julia_h, 71, // At the time of this writing. Not sure if it's worth it to keep this in sync 0 * 8, // sizeof(jl_value_t) * 8, __alignof__(void*) * 8, // __alignof__(jl_value_t) * 8, DINode::FlagZero, // Flags nullptr, // Derived from nullptr); // Elements - will be corrected later jl_pvalue_dillvmt = dbuilder.createPointerType(jl_value_dillvmt, sizeof(jl_value_t*) * 8, __alignof__(jl_value_t*) * 8); SmallVector<llvm::Metadata *, 1> Elts; std::vector<Metadata*> diargs(0); Elts.push_back(jl_pvalue_dillvmt); dbuilder.replaceArrays(jl_value_dillvmt, dbuilder.getOrCreateArray(Elts)); jl_ppvalue_dillvmt = dbuilder.createPointerType(jl_pvalue_dillvmt, sizeof(jl_value_t**) * 8, __alignof__(jl_value_t**) * 8); diargs.push_back(jl_pvalue_dillvmt); // Return Type (ret value) diargs.push_back(jl_pvalue_dillvmt); // First Argument (function) diargs.push_back(jl_ppvalue_dillvmt); // Second Argument (argv) // Third argument (length(argv)) diargs.push_back(_julia_type_to_di(NULL, (jl_value_t*)jl_int32_type, &dbuilder, false)); jl_di_func_sig = dbuilder.createSubroutineType( dbuilder.getOrCreateTypeArray(diargs)); jl_di_func_null_sig = dbuilder.createSubroutineType( dbuilder.getOrCreateTypeArray(None)); T_jlvalue = StructType::get(jl_LLVMContext); T_pjlvalue = PointerType::get(T_jlvalue, 0); T_prjlvalue = PointerType::get(T_jlvalue, AddressSpace::Tracked); T_ppjlvalue = PointerType::get(T_pjlvalue, 0); T_pprjlvalue = PointerType::get(T_prjlvalue, 0); V_null = Constant::getNullValue(T_pjlvalue); std::vector<Type*> ftargs(0); ftargs.push_back(T_prjlvalue); // function ftargs.push_back(T_pprjlvalue); // args[] ftargs.push_back(T_int32); // nargs jl_func_sig = FunctionType::get(T_prjlvalue, ftargs, false); assert(jl_func_sig != NULL); ftargs.push_back(T_pprjlvalue); // linfo->sparam_vals jl_func_sig_sparams = FunctionType::get(T_prjlvalue, ftargs, false); assert(jl_func_sig_sparams != NULL); Type *vaelts[] = {PointerType::get(T_int8, AddressSpace::Loaded) #ifdef STORE_ARRAY_LEN , T_size #endif , T_int16 , T_int16 , T_int32 }; static_assert(sizeof(jl_array_flags_t) == sizeof(int16_t), "Size of jl_array_flags_t is not the same as int16_t"); jl_array_llvmt = StructType::get(jl_LLVMContext, makeArrayRef(vaelts)); jl_parray_llvmt = PointerType::get(jl_array_llvmt, 0); } static void init_jit_functions(void) { add_named_global(jlstack_chk_guard_var, &__stack_chk_guard); add_named_global(jlRTLD_DEFAULT_var, &jl_RTLD_DEFAULT_handle); #ifdef _OS_WINDOWS_ add_named_global(jlexe_var, &jl_exe_handle); add_named_global(jldll_var, &jl_dl_handle); #endif global_jlvalue_to_llvm(new JuliaVariable{"jl_true", true, get_pjlvalue}, &jl_true); global_jlvalue_to_llvm(new JuliaVariable{"jl_false", true, get_pjlvalue}, &jl_false); global_jlvalue_to_llvm(new JuliaVariable{"jl_emptysvec", true, get_pjlvalue}, (jl_value_t**)&jl_emptysvec); global_jlvalue_to_llvm(new JuliaVariable{"jl_emptytuple", true, get_pjlvalue}, &jl_emptytuple); global_jlvalue_to_llvm(new JuliaVariable{"jl_diverror_exception", true, get_pjlvalue}, &jl_diverror_exception); global_jlvalue_to_llvm(new JuliaVariable{"jl_undefref_exception", true, get_pjlvalue}, &jl_undefref_exception); add_named_global(jlgetworld_global, &jl_world_counter); add_named_global("__stack_chk_fail", &__stack_chk_fail); add_named_global(jltls_states_func, (void*)NULL); add_named_global(jlerror_func, &jl_error); add_named_global(jlthrow_func, &jl_throw); add_named_global(jlundefvarerror_func, &jl_undefined_var_error); add_named_global(jlboundserrorv_func, &jl_bounds_error_ints); add_named_global(jlboundserror_func, &jl_bounds_error_int); add_named_global(jlvboundserror_func, &jl_bounds_error_tuple_int); add_named_global(jluboundserror_func, &jl_bounds_error_unboxed_int); add_named_global(jlnew_func, &jl_new_structv); add_named_global(jlsplatnew_func, &jl_new_structt); add_named_global(setjmp_func, &jl_setjmp_f); add_named_global(memcmp_func, &memcmp); add_named_global(jltypeerror_func, &jl_type_error); add_named_global(jlcheckassign_func, &jl_checked_assignment); add_named_global(jldeclareconst_func, &jl_declare_constant); add_named_global(jlgetbindingorerror_func, &jl_get_binding_or_error); add_named_global(jlboundp_func, &jl_boundp); for (auto it : builtin_func_map) add_named_global(it.second, it.first); add_named_global(jlapplygeneric_func, &jl_apply_generic); add_named_global(jlinvoke_func, &jl_invoke); add_named_global(jltopeval_func, &jl_toplevel_eval); add_named_global(jlcopyast_func, &jl_copy_ast); //add_named_global(jlnsvec_func, &jl_svec); add_named_global(jlmethod_func, &jl_method_def); add_named_global(jlgenericfunction_func, &jl_generic_function_def); add_named_global(jlenter_func, &jl_enter_handler); add_named_global(jl_current_exception_func, &jl_current_exception); add_named_global(jlleave_func, &jl_pop_handler); add_named_global(jl_restore_excstack_func, &jl_restore_excstack); add_named_global(jl_excstack_state_func, &jl_excstack_state); add_named_global(jlegal_func, &jl_egal); add_named_global(jlisa_func, &jl_isa); add_named_global(jlsubtype_func, &jl_subtype); add_named_global(jltypeassert_func, &jl_typeassert); add_named_global(jlapplytype_func, &jl_instantiate_type_in_env); add_named_global(jl_object_id__func, &jl_object_id_); add_named_global(jl_alloc_obj_func, (void*)NULL); add_named_global(jl_newbits_func, (void*)jl_new_bits); add_named_global(jl_loopinfo_marker_func, (void*)NULL); add_named_global(jl_typeof_func, (void*)NULL); add_named_global(jl_write_barrier_func, (void*)NULL); add_named_global(jldlsym_func, &jl_load_and_lookup); add_named_global(jlgetcfunctiontrampoline_func, &jl_get_cfunction_trampoline); add_named_global(jlgetnthfieldchecked_func, &jl_get_nth_field_checked); add_named_global(diff_gc_total_bytes_func, &jl_gc_diff_total_bytes); add_named_global(sync_gc_total_bytes_func, &jl_gc_sync_total_bytes); add_named_global(jlarray_data_owner_func, &jl_array_data_owner); add_named_global(gcroot_flush_func, (void*)NULL); add_named_global(gc_preserve_begin_func, (void*)NULL); add_named_global(gc_preserve_end_func, (void*)NULL); add_named_global(pointer_from_objref_func, (void*)NULL); add_named_global(except_enter_func, (void*)NULL); #ifdef _OS_WINDOWS_ #ifndef FORCE_ELF #if defined(_CPU_X86_64_) #if defined(_COMPILER_GCC_) add_named_global("___chkstk_ms", &___chkstk_ms); #else add_named_global("__chkstk", &__chkstk); #endif #else #if defined(_COMPILER_GCC_) add_named_global("_alloca", &_alloca); #else add_named_global("_chkstk", &_chkstk); #endif #endif #endif #endif #define BOX_F(ct) add_named_global("jl_box_"#ct, &jl_box_##ct); BOX_F(int8); BOX_F(uint8); BOX_F(int16); BOX_F(uint16); BOX_F(int32); BOX_F(uint32); BOX_F(int64); BOX_F(uint64); BOX_F(float32); BOX_F(float64); BOX_F(char); BOX_F(ssavalue); #undef BOX_F } extern "C" void jl_init_llvm(void) { jl_page_size = jl_getpagesize(); imaging_mode = jl_generating_output() && !jl_options.incremental; jl_default_cgparams.module_setup = jl_nothing; jl_default_cgparams.module_activation = jl_nothing; jl_default_cgparams.raise_exception = jl_nothing; jl_default_cgparams.emit_function = jl_nothing; jl_default_cgparams.emitted_function = jl_nothing; jl_default_cgparams.generic_context = jl_nothing; jl_init_debuginfo(); InitializeNativeTarget(); InitializeNativeTargetAsmPrinter(); InitializeNativeTargetAsmParser(); InitializeNativeTargetDisassembler(); // Initialize passes PassRegistry &Registry = *PassRegistry::getPassRegistry(); initializeCore(Registry); initializeCoroutines(Registry); initializeScalarOpts(Registry); initializeVectorization(Registry); initializeAnalysis(Registry); initializeTransformUtils(Registry); initializeInstCombine(Registry); initializeAggressiveInstCombine(Registry); initializeInstrumentation(Registry); initializeTarget(Registry); #ifdef USE_POLLY polly::initializePollyPasses(Registry); #endif // Parse command line flags after initialization const char *const argv_tailmerge[] = {"", "-enable-tail-merge=0"}; // NOO TOUCHIE; NO TOUCH! See #922 cl::ParseCommandLineOptions(sizeof(argv_tailmerge)/sizeof(argv_tailmerge[0]), argv_tailmerge, "disable-tail-merge\n"); #if defined(_OS_WINDOWS_) && defined(_CPU_X86_64_) const char *const argv_copyprop[] = {"", "-disable-copyprop"}; // llvm bug 21743 cl::ParseCommandLineOptions(sizeof(argv_copyprop)/sizeof(argv_copyprop[0]), argv_copyprop, "disable-copyprop\n"); #endif #if defined(_CPU_X86_) || defined(_CPU_X86_64_) const char *const argv_avoidsfb[] = {"", "-x86-disable-avoid-SFB"}; // llvm bug 41629, see https://gist.github.com/vtjnash/192cab72a6cfc00256ff118238163b55 cl::ParseCommandLineOptions(sizeof(argv_avoidsfb)/sizeof(argv_avoidsfb[0]), argv_avoidsfb, "disable-avoidsfb\n"); #endif cl::ParseEnvironmentOptions("Julia", "JULIA_LLVM_ARGS"); // if the patch adding this option has been applied, lower its limit to provide // better DAGCombiner performance. auto &clOptions = cl::getRegisteredOptions(); if (clOptions.find("combiner-store-merge-dependence-limit") != clOptions.end()) { const char *const argv_smdl[] = {"", "-combiner-store-merge-dependence-limit=4"}; cl::ParseCommandLineOptions(sizeof(argv_smdl)/sizeof(argv_smdl[0]), argv_smdl); } TargetOptions options = TargetOptions(); //options.PrintMachineCode = true; //Print machine code produced during JIT compiling #if defined(_OS_WINDOWS_) && !defined(_CPU_X86_64_) // tell Win32 to assume the stack is always 16-byte aligned, // and to ensure that it is 16-byte aligned for out-going calls, // to ensure compatibility with GCC codes options.StackAlignmentOverride = 16; #endif Triple TheTriple(sys::getProcessTriple()); #if defined(FORCE_ELF) TheTriple.setObjectFormat(Triple::ELF); #endif uint32_t target_flags = 0; auto target = jl_get_llvm_target(imaging_mode, target_flags); auto &TheCPU = target.first; SmallVector<std::string, 10> targetFeatures(target.second.begin(), target.second.end()); std::string errorstr; const Target *TheTarget = TargetRegistry::lookupTarget("", TheTriple, errorstr); if (!TheTarget) jl_errorf("%s", errorstr.c_str()); if (jl_processor_print_help || (target_flags & JL_TARGET_UNKNOWN_NAME)) { std::unique_ptr<MCSubtargetInfo> MSTI( TheTarget->createMCSubtargetInfo(TheTriple.str(), "", "")); if (!MSTI->isCPUStringValid(TheCPU)) jl_errorf("Invalid CPU name %s.", TheCPU.c_str()); if (jl_processor_print_help) { // This is the only way I can find to print the help message once. // It'll be nice if we can iterate through the features and print our own help // message... MSTI->setDefaultFeatures("help", ""); } } // Package up features to be passed to target/subtarget std::string FeaturesStr; if (!targetFeatures.empty()) { SubtargetFeatures Features; for (unsigned i = 0; i != targetFeatures.size(); ++i) Features.AddFeature(targetFeatures[i]); FeaturesStr = Features.getString(); } // Allocate a target... Optional<CodeModel::Model> codemodel = #ifdef _P64 // Make sure we are using the large code model on 64bit // Let LLVM pick a default suitable for jitting on 32bit CodeModel::Large; #elif JL_LLVM_VERSION < 60000 CodeModel::JITDefault; #else None; #endif auto optlevel = CodeGenOptLevelFor(jl_options.opt_level); jl_TargetMachine = TheTarget->createTargetMachine( TheTriple.getTriple(), TheCPU, FeaturesStr, options, Reloc::Static, // Generate simpler code for JIT codemodel, optlevel #if JL_LLVM_VERSION >= 60000 , /*JIT*/ true #endif ); assert(jl_TargetMachine && "Failed to select target machine -" " Is the LLVM backend for this CPU enabled?"); #if (!defined(_CPU_ARM_) && !defined(_CPU_PPC64_)) // FastISel seems to be buggy for ARM. Ref #13321 if (jl_options.opt_level < 2) jl_TargetMachine->setFastISel(true); #endif init_julia_llvm_meta(); jl_ExecutionEngine = new JuliaOJIT(*jl_TargetMachine); // Mark our address spaces as non-integral jl_data_layout = jl_ExecutionEngine->getDataLayout(); std::string DL = jl_data_layout.getStringRepresentation() + "-ni:10:11:12:13"; jl_data_layout.reset(DL); // Register GDB event listener #ifdef JL_DEBUG_BUILD jl_ExecutionEngine->RegisterJITEventListener(JITEventListener::createGDBRegistrationListener()); #endif #ifdef JL_USE_INTEL_JITEVENTS if (jl_using_intel_jitevents) jl_ExecutionEngine->RegisterJITEventListener(JITEventListener::createIntelJITEventListener()); #endif #ifdef JL_USE_OPROFILE_JITEVENTS if (jl_using_oprofile_jitevents) jl_ExecutionEngine->RegisterJITEventListener(JITEventListener::createOProfileJITEventListener()); #endif #ifdef JL_USE_PERF_JITEVENTS if (jl_using_perf_jitevents) jl_ExecutionEngine->RegisterJITEventListener(JITEventListener::createPerfJITEventListener()); #endif } extern "C" void jl_init_codegen(void) { jl_init_llvm(); // Now that the execution engine exists, initialize all modules jl_init_jit(); init_jit_functions(); Module *m = new Module("julia", jl_LLVMContext); jl_setup_module(m); init_julia_llvm_env(m); jl_init_intrinsic_functions_codegen(); } extern "C" void jl_teardown_codegen() { // output LLVM timings and statistics reportAndResetTimings(); PrintStatistics(); } // the rest of this file are convenience functions // that are exported for assisting with debugging from gdb extern "C" void jl_dump_llvm_value(void *v) { llvm_dump((Value*)v); } extern "C" void jl_dump_llvm_inst_function(void *v) { llvm_dump(cast<Instruction>(((Value*)v))->getParent()->getParent()); } extern "C" void jl_dump_llvm_type(void *v) { llvm_dump((Type*)v); } extern "C" void jl_dump_llvm_module(void *v) { llvm_dump((Module*)v); } extern "C" void jl_dump_llvm_metadata(void *v) { llvm_dump((Metadata*)v); } extern "C" void jl_dump_llvm_debugloc(void *v) { llvm_dump((DebugLoc*)v); } namespace llvm { class MachineBasicBlock; class MachineFunction; raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB); void printMIR(raw_ostream &OS, const MachineFunction &MF); } extern "C" void jl_dump_llvm_mbb(void *v) { errs() << *(llvm::MachineBasicBlock*)v; } extern "C" void jl_dump_llvm_mfunction(void *v) { llvm::printMIR(errs(), *(llvm::MachineFunction*)v); } extern void jl_write_bitcode_func(void *F, char *fname) { std::error_code EC; raw_fd_ostream OS(fname, EC, sys::fs::F_None); llvm::WriteBitcodeToFile(*((llvm::Function*)F)->getParent(), OS); } extern void jl_write_bitcode_module(void *M, char *fname) { std::error_code EC; raw_fd_ostream OS(fname, EC, sys::fs::F_None); llvm::WriteBitcodeToFile(*(llvm::Module*)M, OS); }
; compile with nasm -felf64 foo.asm; ld foo.o -o foo.out bits 64 section .data should_not_trigger dq 0x0000000000000000 section .start global _start _start: ; generic push to make sure the tool is working mov rax, 0xcafebabedeadbeef push rax ; write to .data section, should not appear in json mov [should_not_trigger], rax ; exit mov rax, 60 syscall
segment .data align 4 x: dd 1 segment .text align 4 global _main:function _main: align 4 xpl: push ebp mov ebp, esp sub esp, 4 push dword 0 lea eax, [ebp+-4] push eax pop ecx pop eax mov [ecx], eax _L1: push dword $x pop eax push dword [eax] push dword 5 pop eax xor ecx, ecx cmp [esp], eax setle cl mov [esp], ecx pop eax cmp eax, byte 0 je near _L2 push dword $x pop eax push dword [eax] call printi add esp, 4 push dword $x pop eax push dword [eax] push dword 2 pop eax add dword [esp], eax push dword [esp] push dword $x pop ecx pop eax mov [ecx], eax add esp, 4 jmp dword _L1 _L2: lea eax, [ebp+-4] push eax pop eax push dword [eax] pop eax leave ret extern argc extern argv extern envp extern readi extern readd extern printi extern prints extern printd extern println
; A063258: a(n) = binomial(n+5,4) - 1. ; 4,14,34,69,125,209,329,494,714,1000,1364,1819,2379,3059,3875,4844,5984,7314,8854,10625,12649,14949,17549,20474,23750,27404,31464,35959,40919,46375,52359,58904,66044,73814,82250,91389,101269,111929,123409,135750,148994,163184,178364,194579,211875,230299,249899,270724,292824,316250,341054,367289,395009,424269,455125,487634,521854,557844,595664,635375,677039,720719,766479,814384,864500,916894,971634,1028789,1088429,1150625,1215449,1282974,1353274,1426424,1502500,1581579,1663739,1749059,1837619 add $0,5 bin $0,4 sub $0,1
.text .globl main main: addi $s1, $0, 3 # $s1 = 3 # $s1 = 3 sll $s2, $s1, 2 # $s2 = 3 * 4 # $s2 = 3 * 4
; Super Mario Bros. 3 Full Disassembly by Southbird 2012 ; For more info, see http://www.sonicepoch.com/sm3mix/ ; ; PLEASE INCLUDE A CREDIT TO THE SOUTHBIRD DISASSEMBLY ; AND THE ABOVE LINK SOMEWHERE IN YOUR WORKS :) ; ; Original disassembler source generated by DCC6502 version v1.4 ; (With labels, comments, and some syntax corrections for nesasm by Southbird) ; For more info about DCC6502, e-mail veilleux@ameth.org ; ; This source file last updated: 2012-03-06 18:57:13.927921102 -0600 ; Distribution package date: Fri Apr 6 23:46:16 UTC 2012 ;--------------------------------------------------------------------------- M2BSegData14: .byte $98, $56, $56, $90, $54, $56, $94, $7E, $98, $56, $5A, $5A, $90, $58, $5A, $94 ; $C000 - $C00F .byte $7E, $98, $5A, $00, $98, $5C, $5C, $90, $5A, $5C, $94, $7E, $98, $5C, $60, $60 ; $C010 - $C01F .byte $90, $5E, $60, $94, $7E, $98, $60, $94, $4E, $5C, $66, $5C, $4E, $5C, $66, $5C ; $C020 - $C02F .byte $52, $60, $6A, $60, $52, $60, $6A, $60 M2BSegData15: .byte $98, $5C, $5C, $90, $5A, $5C, $94, $7E ; $C030 - $C03F .byte $98, $5C, $60, $60, $90, $5E, $60, $94, $7E, $98, $60, $00, $98, $62, $62, $90 ; $C040 - $C04F .byte $60, $62, $94, $7E, $98, $62, $66, $66, $90, $64, $66, $94, $7E, $98, $66, $94 ; $C050 - $C05F .byte $54, $62, $6C, $62, $54, $62, $6C, $62, $58, $66, $70, $66, $58, $66, $70, $66 ; $C060 - $C06F .byte $98, $05, $00 M2BSegData1A: .byte $DC, $7E, $7E, $7E, $7E, $D4, $18, $30, $12, $2A, $14, $2C, $D8 ; $C070 - $C07F .byte $7E, $DC, $7E, $D4, $18, $30, $12, $2A, $14, $2C, $D8, $7E, $DC, $7E, $D4, $0A ; $C080 - $C08F .byte $22, $04, $1C, $06, $1E, $D8, $7E, $DC, $7E, $D4, $0A, $22, $04, $1C, $06, $1E ; $C090 - $C09F .byte $DC, $7E, $D2, $1E, $1C, $1A, $D8, $18, $1E, $1C, $10, $0E, $1A, $D2, $18, $24 ; $C0A0 - $C0AF .byte $22, $20, $2C, $2A, $D6, $28, $1E, $16, $14, $12, $10, $DC, $7E, $00, $8C, $7E ; $C0B0 - $C0BF .byte $7E, $7E, $7E, $84, $30, $48, $2A, $42, $2C, $44, $88, $7E, $8C, $7E, $84, $30 ; $C0C0 - $C0CF .byte $48, $2A, $42, $2C, $44, $88, $7E, $8C, $7E, $84, $22, $3A, $1C, $34, $1E, $36 ; $C0D0 - $C0DF .byte $88, $7E, $8C, $7E, $84, $22, $3A, $1C, $34, $1E, $36, $8C, $7E, $82, $36, $34 ; $C0E0 - $C0EF .byte $32, $88, $30, $36, $34, $28, $26, $32, $82, $30, $3C, $3A, $38, $44, $42, $86 ; $C0F0 - $C0FF .byte $40, $36, $2E, $2C, $2A, $28, $8C, $7E, $8A, $01, $02, $84, $01, $01, $88, $01 ; $C100 - $C10F .byte $8A, $02, $8A, $01, $89, $02, $88, $01, $01, $84, $01, $88, $02, $84, $02, $02 ; $C110 - $C11F .byte $00, $84, $02, $00 M2BSegData09: .byte $9C, $7E, $7E, $BC, $30, $48, $46, $7E, $30, $48, $46, $7E ; $C120 - $C12F .byte $00, $9C, $7E, $7E, $BC, $22, $3A, $38, $7E, $22, $3A, $38, $7E, $8C, $7E, $7E ; $C130 - $C13F .byte $BC, $30, $48, $46, $7E, $30, $48, $46, $7E, $8C, $7E, $7E, $00, $88, $0F, $86 ; $C140 - $C14F .byte $0F, $82, $0F, $82, $0F, $0F, $0F, $88, $0F, $88, $0F, $82, $0F, $0F, $0F, $84 ; $C150 - $C15F .byte $0F, $0F, $82, $0F, $0F, $0F, $00 M2BSegData0A: .byte $E8, $32, $32, $E4, $32, $32, $E2, $32, $38 ; $C160 - $C16F .byte $38, $E8, $32, $32, $E4, $32, $32, $E2, $32, $38, $38, $E8, $3E, $3E, $E4, $3E ; $C170 - $C17F .byte $3E, $E2, $3E, $44, $44, $E8, $3E, $3E, $E4, $3E, $3E, $E2, $3E, $44, $44, $00 ; $C180 - $C18F .byte $E8, $36, $36, $E4, $36, $36, $E2, $36, $3C, $3C, $E8, $36, $36, $E4, $36, $36 ; $C190 - $C19F .byte $E2, $36, $3C, $3C, $E8, $42, $42, $E4, $42, $42, $E2, $42, $48, $48, $E8, $42 ; $C1A0 - $C1AF .byte $42, $E4, $42, $42, $E2, $42, $48, $48, $E4, $58, $7E, $58, $7E, $58, $58, $E2 ; $C1B0 - $C1BF .byte $58, $5E, $5E, $E4, $58, $7E, $58, $7E, $58, $58, $E2, $58, $5E, $5E, $E4, $64 ; $C1C0 - $C1CF .byte $7E, $64, $7E, $64, $64, $E2, $64, $6A, $6A, $E4, $64, $7E, $64, $7E, $64, $64 ; $C1D0 - $C1DF .byte $E2, $64, $6A, $6A, $E8, $02, $02, $E4, $02, $02, $E2, $02, $02, $02, $00, $E8 ; $C1E0 - $C1EF .byte $0F, $0F, $E4, $0F, $0F, $E2, $0F, $0F, $0F, $E8, $0F, $0F, $E4, $0F, $0F, $E2 ; $C1F0 - $C1FF .byte $0F, $0F, $0F, $E8, $0E, $0E, $E4, $0E, $0E, $E2, $0E, $0E, $0E, $E8, $0E, $0E ; $C200 - $C20F .byte $E4, $0E, $0E, $E2, $0E, $0E, $0E, $00 M2BSegData07: .byte $B4, $18, $2E, $BB, $2C, $E0, $7E, $2A ; $C210 - $C21F .byte $28, $26, $E4, $24, $14, $EB, $7E, $00, $B4, $14, $2A, $BB, $28, $E0, $7E, $26 ; $C220 - $C22F .byte $24, $22, $E4, $20, $10, $EB, $7E, $E4, $3A, $50, $EB, $4E, $E0, $7E, $4C, $4A ; $C230 - $C23F .byte $48, $E4, $46, $36, $EB, $7E, $EC, $7E, $EA, $7E, $E4, $0E, $EC, $0F, $E4, $7E ; $C240 - $C24F .byte $00 M2BSegData08: .byte $BA, $7E, $BB, $26, $2E, $20, $2A, $EA, $7E, $00, $B8, $7E, $BB, $28, $18 ; $C250 - $C25F .byte $1A, $10, $B8, $7E, $EA, $7E, $BB, $34, $46, $2C, $3A, $BA, $7E, $EA, $7E, $BB ; $C260 - $C26F .byte $7E, $7E, $7E, $7E, $E4, $0E, $EC, $0F, $EA, $7E M12ASegData1B: .byte $D2, $56, $54, $56, $DA, $50 ; $C270 - $C27F .byte $D8, $52, $54, $DA, $56, $D8, $60, $D6, $68, $D2, $68, $D8, $64, $68, $6A, $5E ; $C280 - $C28F .byte $DA, $64, $D8, $60, $00, $D8, $2E, $30, $7E, $34, $36, $38, $30, $42, $3E, $3A ; $C290 - $C29F .byte $38, $34, $3A, $3E, $26, $30 M12ASegData1C: .byte $D6, $68, $D2, $68, $DA, $68, $D9, $5E, $D4, $64 ; $C2A0 - $C2AF .byte $D8, $64, $D2, $7E, $60, $5E, $D8, $60, $D6, $6A, $D2, $6A, $DA, $6A, $D9, $60 ; $C2B0 - $C2BF .byte $D4, $64, $DA, $68, $D8, $64, $00, $D8, $2E, $38, $3C, $40, $46, $42, $40, $42 ; $C2C0 - $C2CF .byte $3E, $3A, $3E, $40, $3A, $3E, $26, $3A M12ASegData1D: .byte $A4, $3E, $7E, $94, $56, $98, $52, $94 ; $C2D0 - $C2DF .byte $4C, $46, $42, $3E, $7E, $3E, $7E, $AA, $7E, $00, $A4, $2E, $7E, $94, $46, $98 ; $C2E0 - $C2EF .byte $42, $94, $3A, $34, $30, $2E, $7E, $2E, $7E, $AA, $7E, $A4, $3E, $7E, $56, $98 ; $C2F0 - $C2FF .byte $52, $94, $4C, $46, $42, $3E, $7E, $3E, $7E, $AA, $7E, $94, $02, $90, $02, $02 ; $C300 - $C30F .byte $94, $02, $02, $02, $02, $02, $02, $00, $A4, $06, $A0, $05, $05, $A4, $05, $05 ; $C310 - $C31F .byte $7E, $05, $05, $05, $06, $7E, $06, $8D, $7E, $7E, $08, $88, $08, $8D, $09, $09 ; $C320 - $C32F .byte $09, $94, $08 M12ASegData1E: .byte $98, $7E, $94, $50, $52, $50, $4C, $48, $46, $98, $4C, $94, $4C ; $C330 - $C33F .byte $9A, $42, $94, $7E, $98, $7E, $94, $46, $48, $46, $42, $3E, $3A, $98, $38, $94 ; $C340 - $C34F .byte $38, $9A, $3E, $94, $7E, $00, $98, $7E, $94, $48, $4C, $48, $46, $42, $3E, $98 ; $C350 - $C35F .byte $42, $94, $42, $9A, $3A, $94, $7E, $98, $7E, $94, $3E, $42, $3E, $3A, $38, $34 ; $C360 - $C36F .byte $98, $30, $94, $30, $9A, $38, $94, $7E, $99, $30, $98, $38, $94, $38, $98, $3E ; $C370 - $C37F .byte $99, $3A, $98, $42, $94, $42, $98, $48, $99, $3E, $98, $46, $94, $46, $98, $4C ; $C380 - $C38F .byte $99, $30, $98, $38, $94, $38, $98, $3E, $94, $02, $90, $02, $02, $94, $02, $02 ; $C390 - $C39F .byte $02, $02, $02, $02, $00, $A4, $01, $A0, $05, $05, $A4, $05, $01, $01, $06, $07 ; $C3A0 - $C3AF .byte $01, $00 M12ASegData1F: .byte $98, $7E, $94, $3A, $3E, $40, $48, $44, $40, $99, $3E, $9A, $38, $94 ; $C3B0 - $C3BF .byte $7E, $00, $98, $7E, $94, $30, $34, $52, $58, $56, $52, $99, $50, $9A, $48, $94 ; $C3C0 - $C3CF .byte $7E, $98, $3A, $94, $3A, $98, $40, $94, $40, $98, $48, $30, $94, $30, $98, $38 ; $C3D0 - $C3DF .byte $94, $38, $98, $3E, $94, $02, $90, $02, $02, $94, $02, $02, $02, $02, $02, $02 ; $C3E0 - $C3EF .byte $00, $A4, $01, $A0, $05, $05, $A4, $05, $01, $01, $06, $07, $01, $00 M12ASegData20: .byte $98, $7E ; $C3F0 - $C3FF .byte $94, $3A, $3E, $40, $48, $44, $40, $99, $3E, $9A, $48, $94, $7E, $98, $7E, $94 ; $C400 - $C40F .byte $42, $40, $42, $46, $48, $42, $9B, $4C, $C8, $3E, $00, $98, $7E, $94, $30, $34 ; $C410 - $C41F .byte $52, $58, $56, $52, $99, $50, $9A, $56, $94, $7E, $98, $7E, $94, $3A, $38, $3A ; $C420 - $C42F .byte $3E, $42, $3A, $9C, $46, $C8, $2E, $98, $3A, $94, $3A, $98, $40, $94, $40, $98 ; $C430 - $C43F .byte $48, $38, $94, $38, $98, $3E, $94, $3E, $98, $48, $36, $94, $36, $98, $3E, $94 ; $C440 - $C44F .byte $3E, $98, $48, $34, $94, $34, $98, $3E, $94, $3E, $98, $3E, $94, $02, $90, $02 ; $C450 - $C45F .byte $02, $94, $02, $02, $02, $02, $02, $02, $00, $A4, $01, $A0, $05, $05, $A4, $05 ; $C460 - $C46F .byte $01, $01, $06, $07, $01, $00 M12ASegData21: .byte $CA, $50, $C4, $7E, $4C, $50, $52, $CB, $56, $C8 ; $C470 - $C47F .byte $5A, $CA, $56, $C4, $7E, $52, $50, $52, $CB, $48, $C8, $56, $CA, $52, $C4, $7E ; $C480 - $C48F .byte $50, $4C, $50, $CA, $48, $C6, $46, $48, $50, $00, $C4, $30, $90, $56, $50, $94 ; $C490 - $C49F .byte $48, $3E, $C4, $7E, $46, $30, $34, $C4, $34, $90, $52, $4C, $94, $46, $3E, $C8 ; $C4A0 - $C4AF .byte $7E, $3A, $C4, $38, $90, $52, $4C, $94, $44, $3E, $C4, $7E, $34, $30, $34, $C4 ; $C4B0 - $C4BF .byte $42, $90, $52, $48, $94, $42, $3A, $C8, $7E, $34, $C4, $30, $90, $52, $48, $94 ; $C4C0 - $C4CF .byte $40, $3A, $C4, $7E, $30, $2E, $30, $C4, $3E, $90, $50, $48, $94, $3E, $38, $C6 ; $C4D0 - $C4DF .byte $26, $2A, $30, $C8, $48, $C4, $3E, $C8, $48, $C4, $3E, $C8, $48, $46, $C4, $3E ; $C4E0 - $C4EF .byte $C8, $46, $C4, $3E, $C8, $46, $44, $C4, $3E, $C8, $44, $C4, $3E, $C8, $44, $42 ; $C4F0 - $C4FF .byte $C4, $3A, $C8, $42, $C4, $3A, $C8, $42, $40, $C4, $3A, $C8, $40, $C4, $3A, $C8 ; $C500 - $C50F .byte $40, $3E, $C4, $38, $C8, $3E, $C4, $38, $C8, $3E, $C4, $02, $C0, $02, $02, $C4 ; $C510 - $C51F .byte $02, $02, $02, $02, $02, $02, $00, $A4, $01, $A0, $06, $06, $A4, $06, $07, $01 ; $C520 - $C52F .byte $06, $07, $06, $00 M12ASegData22: .byte $CA, $4C, $C4, $7E, $48, $46, $48, $CB, $4C, $C8, $3E, $00 ; $C530 - $C53F .byte $C4, $2A, $90, $54, $48, $94, $42, $3C, $C4, $7E, $2A, $28, $2A, $C4, $2E, $90 ; $C540 - $C54F .byte $52, $4C, $94, $46, $3E, $C8, $7E, $3E, $C8, $3C, $C4, $34, $C8, $3C, $C4, $34 ; $C550 - $C55F .byte $C8, $3C, $3E, $C4, $34, $C8, $3E, $C4, $34, $C8, $3E, $C4, $02, $C0, $02, $02 ; $C560 - $C56F .byte $C4, $02, $02, $02, $02, $02, $02, $00, $A4, $01, $A0, $06, $06, $A4, $06, $07 ; $C570 - $C57F .byte $01, $06, $07, $06, $00 M12ASegData23: .byte $CA, $4C, $C4, $7E, $48, $46, $48, $94, $56, $7E, $56 ; $C580 - $C58F .byte $7E, $AA, $7E, $00, $C4, $2A, $90, $54, $48, $94, $42, $3C, $C4, $7E, $2A, $28 ; $C590 - $C59F .byte $2A, $94, $2E, $7E, $2E, $7E, $AA, $7E, $C8, $3C, $C4, $34, $C8, $3C, $C4, $34 ; $C5A0 - $C5AF .byte $C8, $3C, $3E, $C4, $34, $C8, $3E, $C4, $34, $C8, $3E, $94, $3E, $7E, $3E, $7E ; $C5B0 - $C5BF .byte $AA, $7E, $C4, $02, $C0, $02, $02, $C4, $02, $02, $02, $02, $02, $02, $00, $A4 ; $C5C0 - $C5CF .byte $06, $A0, $06, $06, $A4, $06, $07, $01, $06, $07, $07, $06, $7E, $06, $8D, $7E ; $C5D0 - $C5DF .byte $7E, $08, $88, $08, $8D, $09, $09, $09, $94, $08 ;; BEGIN HUGE UNUSED SPACE .byte $FF, $FF, $FF, $FF, $FF, $FF ; $C5E0 - $C5EF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C5F0 - $C5FF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C600 - $C60F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C610 - $C61F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C620 - $C62F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C630 - $C63F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C640 - $C64F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C650 - $C65F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C660 - $C66F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C670 - $C67F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C680 - $C68F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C690 - $C69F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C6A0 - $C6AF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C6B0 - $C6BF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C6C0 - $C6CF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C6D0 - $C6DF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C6E0 - $C6EF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C6F0 - $C6FF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C700 - $C70F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C710 - $C71F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C720 - $C72F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C730 - $C73F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C740 - $C74F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C750 - $C75F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C760 - $C76F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C770 - $C77F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C780 - $C78F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C790 - $C79F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C7A0 - $C7AF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C7B0 - $C7BF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C7C0 - $C7CF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C7D0 - $C7DF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C7E0 - $C7EF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C7F0 - $C7FF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C800 - $C80F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C810 - $C81F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C820 - $C82F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C830 - $C83F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C840 - $C84F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C850 - $C85F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C860 - $C86F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C870 - $C87F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C880 - $C88F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C890 - $C89F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C8A0 - $C8AF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C8B0 - $C8BF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C8C0 - $C8CF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C8D0 - $C8DF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C8E0 - $C8EF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C8F0 - $C8FF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C900 - $C90F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C910 - $C91F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C920 - $C92F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C930 - $C93F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C940 - $C94F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C950 - $C95F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C960 - $C96F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C970 - $C97F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C980 - $C98F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C990 - $C99F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C9A0 - $C9AF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C9B0 - $C9BF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C9C0 - $C9CF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C9D0 - $C9DF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C9E0 - $C9EF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $C9F0 - $C9FF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA00 - $CA0F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA10 - $CA1F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA20 - $CA2F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA30 - $CA3F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA40 - $CA4F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA50 - $CA5F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA60 - $CA6F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA70 - $CA7F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA80 - $CA8F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CA90 - $CA9F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CAA0 - $CAAF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CAB0 - $CABF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CAC0 - $CACF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CAD0 - $CADF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CAE0 - $CAEF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CAF0 - $CAFF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB00 - $CB0F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB10 - $CB1F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB20 - $CB2F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB30 - $CB3F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB40 - $CB4F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB50 - $CB5F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB60 - $CB6F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB70 - $CB7F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB80 - $CB8F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CB90 - $CB9F .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CBA0 - $CBAF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CBB0 - $CBBF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CBC0 - $CBCF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CBD0 - $CBDF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CBE0 - $CBEF .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $CBF0 - $CBFF ;; END HUGE UNUSED SPACE ; This defines a table of offsets that point to the start of ; each Player_Frame's six patterns ; Nintendo did a minor trick here to keep the offset down to one byte... ; - They have 81 frames total, with 6 patterns each ; - Dividing by 2 (to be fixed later) means the offset into the pattern lookup table is reduced to 3 ; - 3 * 81 = 243, which fits the 1 byte offset ; But, for some reason, everything is off by 4? The SPPF function below compensates for this, and ; PRG029_CF1E loads from 4 bytes shy of the proper address. Maybe this was a mistake? SPPF .func ((\1 - SPPF_Table + 4) / 2) ; The offsets SPPF_Offsets: .byte SPPF(PF00), SPPF(PF01), SPPF(PF02), SPPF(PF03), SPPF(PF04), SPPF(PF05), SPPF(PF06), SPPF(PF07) .byte SPPF(PF08), SPPF(PF09), SPPF(PF0A), SPPF(PF0B), SPPF(PF0C), SPPF(PF0D), SPPF(PF0E), SPPF(PF0F) .byte SPPF(PF10), SPPF(PF11), SPPF(PF12), SPPF(PF13), SPPF(PF14), SPPF(PF15), SPPF(PF16), SPPF(PF17) .byte SPPF(PF18), SPPF(PF19), SPPF(PF1A), SPPF(PF1B), SPPF(PF1C), SPPF(PF1D), SPPF(PF1E), SPPF(PF1F) .byte SPPF(PF20), SPPF(PF21), SPPF(PF22), SPPF(PF23), SPPF(PF24), SPPF(PF25), SPPF(PF26), SPPF(PF27) .byte SPPF(PF28), SPPF(PF29), SPPF(PF2A), SPPF(PF2B), SPPF(PF2C), SPPF(PF2D), SPPF(PF2E), SPPF(PF2F) .byte SPPF(PF30), SPPF(PF31), SPPF(PF32), SPPF(PF33), SPPF(PF34), SPPF(PF35), SPPF(PF36), SPPF(PF37) .byte SPPF(PF38), SPPF(PF39), SPPF(PF3A), SPPF(PF3B), SPPF(PF3C), SPPF(PF3D), SPPF(PF3E), SPPF(PF3F) .byte SPPF(PF40), SPPF(PF41), SPPF(PF42), SPPF(PF43), SPPF(PF44), SPPF(PF45), SPPF(PF46), SPPF(PF47) .byte SPPF(PF48), SPPF(PF49), SPPF(PF4A), SPPF(PF4B), SPPF(PF4C), SPPF(PF4D), SPPF(PF4E), SPPF(PF4F) .byte SPPF(PF50) ; The six Patterns per Player_Frame to start each of the six Player sprites with! ; Note the order is the three patterns for the three sprites that make the upper ; half followed by the next three for the lower half. ; $F1 is a magic value reserved as a "don't display this sprite" flag SPPF_Table: PF00: .byte $01, $03, $F1, $05, $07, $09 PF01: .byte $0B, $0D, $F1, $0F, $29, $2B PF02: .byte $2D, $2F, $F1, $19, $1B, $1D PF03: .byte $2D, $2F, $F1, $19, $1B, $09 PF04: .byte $21, $21, $F1, $23, $23, $F1 PF05: .byte $25, $25, $F1, $27, $27, $F1 PF06: .byte $01, $03, $F1, $05, $07, $F1 PF07: .byte $31, $33, $F1, $35, $37, $39 PF08: .byte $01, $03, $F1, $05, $07, $39 PF09: .byte $01, $03, $F1, $05, $07, $09 PF0A: .byte $01, $03, $F1, $05, $07, $3B PF0B: .byte $F1, $F1, $F1, $3D, $3F, $F1 PF0C: .byte $01, $03, $F1, $05, $07, $F1 PF0D: .byte $0B, $0D, $F1, $0F, $29, $F1 PF0E: .byte $2D, $2F, $F1, $19, $1B, $F1 PF0F: .byte $31, $33, $F1, $35, $37, $F1 PF10: .byte $09, $2F, $F1, $1D, $1F, $F1 PF11: .byte $2D, $2F, $F1, $39, $3B, $F1 PF12: .byte $31, $31, $F1, $33, $33, $F1 PF13: .byte $35, $35, $F1, $37, $37, $F1 PF14: .byte $39, $39, $F1, $3B, $3B, $F1 PF15: .byte $01, $03, $F1, $05, $07, $09 PF16: .byte $0B, $0D, $F1, $0F, $29, $2B PF17: .byte $2D, $2F, $F1, $19, $1B, $1D PF18: .byte $2D, $2F, $F1, $A9, $AB, $F1 PF19: .byte $2D, $2F, $F1, $A9, $AD, $F1 PF1A .byte $01, $03, $05, $07, $09, $0B PF1B: .byte $0D, $0F, $39, $3B, $3D, $3F PF1C: .byte $19, $1B, $1D, $1F, $21, $23 PF1D: .byte $25, $27, $29, $2B, $2D, $2F PF1E: .byte $31, $33, $F1, $35, $37, $F1 PF1F: .byte $25, $29, $2D, $33, $37, $0D PF20: .byte $25, $29, $2D, $33, $37, $0F PF21: .byte $19, $1D, $21, $1B, $1F, $23 PF22: .byte $25, $29, $2D, $27, $2B, $2F PF23: .byte $25, $29, $2D, $33, $37, $3B PF24: .byte $01, $01, $F1, $03, $03, $F1 PF25: .byte $05, $05, $F1, $07, $07, $F1 PF26: .byte $09, $09, $F1, $0B, $0B, $F1 PF27: .byte $31, $33, $F1, $35, $37, $F1 PF28: .byte $31, $35, $F1, $39, $3D, $F1 PF29: .byte $01, $03, $F1, $05, $07, $09 ; Second page begins here PF2A: .byte $01, $03, $F1, $0B, $0D, $0F PF2B: .byte $01, $03, $F1, $21, $23, $25 PF2C: .byte $31, $33, $F1, $35, $37, $F1 PF2D: .byte $27, $19, $F1, $1D, $1F, $F1 PF2E: .byte $F1, $F1, $F1, $35, $37, $F1 PF2F: .byte $F1, $F1, $F1, $31, $33, $F1 PF30: .byte $29, $2B, $F1, $2D, $2F, $F1 PF31: .byte $39, $3B, $F1, $3D, $3F, $F1 PF32: .byte $F1, $F1, $F1, $2F, $2F, $F1 PF33: .byte $F1, $F1, $F1, $2B, $2D, $F1 PF34: .byte $29, $2B, $F1, $0D, $0F, $27 PF35: .byte $29, $2B, $F1, $09, $0B, $25 PF36: .byte $29, $2B, $F1, $01, $03, $3F PF37: .byte $29, $2B, $F1, $01, $03, $05 PF38: .byte $29, $2B, $F1, $01, $03, $07 PF39: .byte $29, $2B, $F1, $31, $33, $3D PF3A: .byte $29, $2B, $F1, $35, $37, $3D PF3B: .byte $29, $2B, $F1, $39, $3B, $3D PF3C: .byte $29, $2B, $F1, $0D, $1F, $25 PF3D: .byte $29, $2B, $F1, $0D, $2D, $2F PF3E: .byte $F1, $F1, $F1, $05, $07, $F1 PF3F: .byte $F1, $F1, $F1, $01, $03, $F1 PF40: .byte $F1, $F1, $F1, $19, $1B, $F1 PF41: .byte $F1, $F1, $F1, $21, $23, $F1 PF42: .byte $F1, $F1, $F1, $1D, $1F, $F1 PF43: .byte $05, $07, $F1, $A9, $AB, $F1 PF44: .byte $05, $07, $F1, $A9, $AD, $F1 PF45: .byte $29, $2B, $F1, $01, $03, $05 PF46: .byte $F1, $F1, $F1, $25, $27, $F1 PF47: .byte $F1, $F1, $F1, $29, $2B, $F1 PF48: .byte $F1, $F1, $F1, $29, $2F, $F1 PF49: .byte $F1, $F1, $F1, $25, $2D, $F1 PF4A: .byte $F1, $F1, $F1, $09, $0B, $F1 PF4B: .byte $F1, $F1, $F1, $0D, $0D, $F1 PF4C: .byte $F1, $F1, $F1, $31, $33, $F1 PF4D: .byte $F1, $F1, $F1, $35, $37, $F1 PF4E: .byte $F1, $F1, $F1, $0F, $3F, $F1 PF4F: .byte $19, $1B, $F1, $1D, $21, $F1 PF50: .byte $19, $1B, $F1, $1D, $21, $23 ; Selects a VROM page offset per Player_Frame Player_FramePageOff: .byte 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; 00 - 0F .byte 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 ; 10 - 1F .byte 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2 ; 20 - 2F .byte 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ; 30 - 3F .byte 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ; 40 - 4F .byte 3 PRG029_CE88: .byte -8, 10, -8, 18, 8, 10, 8, 18, 1, 9, 0, 8, 2, 10, -2, 6 ; Specified root VROM page for a given power up Player_PUpRootPage: ; Small, Big, Fire, Leaf, Frog, Tanooki, Hammer .byte $50, $54, $54, $00, $50, $40, $44 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Player_Draw ; ; Not literally "draw", but configure the sprites for the Player ; to be drawn! With the given data set of where the screen is ; scrolled, the Player's animation frame, invincibility status, ; etc. all handled by this major subroutine... ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Player_Draw: LDX <Player_Frame LDA Player_FramePageOff,X STA <Temp_Var1 ; Get VROM page offset for this animation frame -> Temp_Var1 LDY <Player_Suit LDA Player_PUpRootPage,Y ; Get VROM root page for this power up ADD <Temp_Var1 ; Add appropriate offset to the VROM base for the animation frame STA PatTable_BankSel+2 ; Set VROM bank switch for sprites 1/4 LDA <Player_X SUB <Horz_Scroll STA <Player_SpriteX ; Player_SpriteX = Player_X - Horz_Scroll LDA <Player_Y SUB Level_VertScroll STA <Player_SpriteY ; Player_SpriteY = Player_Y - Level_VertScroll LDA <Player_YHi SBC Level_VertScrollH STA Player_AboveTop ; Player_Above top calculated if Player is off top of screen LDA Player_FlashInv BEQ PRG029_CED7 ; If Player_FlashInv = 0, jump to PRG029_CED7 DEC Player_FlashInv ; Player_FlashInv-- AND #$02 BEQ PRG029_CED7 ; Every 2 ticks, draw Player JMP PRG029_D094 ; Every other 2 ticks, don't! PRG029_CED7: LDA Player_StarOff BNE PRG029_CEEA ; If Player_StarOff <> 0 (star invincibility wearing off), jump to PRG029_CEEA LDA Player_StarInv BEQ PRG029_CF0B ; If Player_StarInv = 0 (not star invincible), jump to PRG029_CF0B LDA <Counter_1 AND #$01 BEQ PRG029_CEEA ; Every other tick, jump to PRG029_CEEA DEC Player_StarInv ; Player_StarInv-- PRG029_CEEA: LDA <Counter_1 AND #$0f ; A = 0-15 ticks LDY Player_StarOff BNE PRG029_CF07 ; If Player_StarOff <> 0 (star invincibility wearing off), jump to PRG029_CF07 LDY Player_StarInv CPY #32 BNE PRG029_CF05 ; If Player_StarInv <> 32, jump to PRG029_CF05 ; At precisely star invincibility tick 32... LDY Level_PSwitchCnt BNE PRG029_CF05 ; If P-Switch is active, jump to PRG029_CF05 ; Otherwise, restore level BGM music now that invincibility is wearing off LDY Level_MusicQueueRestore STY Sound_QMusic2 PRG029_CF05: BCS PRG029_CF09 ; If we're NOT doing the "wearing off" star invincibility, jump to PRG029_CF09 PRG029_CF07: ; These shifts are used to produce the "slower" color cycle ; when the star invincibility is wearing off... LSR A LSR A PRG029_CF09: AND #$03 ; Cap it 0-3 in any case (select one of the four sprite palettes, basically) PRG029_CF0B: STA <Temp_Var1 ; Store cycle tick into Temp_Var1 (0 if not invincible, sprite palette 0) LDA Level_PipeMove LDA Player_Behind ORA Player_SandSink BEQ PRG029_CF1E ; If Player is behind the scenes, jump to PRG029_CF1E ; Set priority over background (normal most game sprite behavior) LDA #$20 ORA <Temp_Var1 STA <Temp_Var1 PRG029_CF1E: LDA #LOW(SPPF_Table-4) STA <Player_SprWorkL LDA #HIGH(SPPF_Table-4) STA <Player_SprWorkH ; X = Player_Frame LDA SPPF_Offsets,X ; Get offset value to sprite's pattern set ASL A TAY ; Needs to be shifted up to be correct (stored shifted right 1) BCC PRG029_CF2F ; If carry is NOT set (a >= $80 value indicate "second page"), jump to PRG029_CF2F INC <Player_SprWorkH ; Go to second page PRG029_CF2F: LDX Player_SprOff ; X = Root offset where Player sprite should begin ; Store pattern in this Player sprite and go to next byte LDA [Player_SprWorkL],Y STA Sprite_RAM+$0D,X INY ; Store pattern in this Player sprite and go to next byte LDA [Player_SprWorkL],Y STA Sprite_RAM+$11,X INY ; Store pattern in this Player sprite and go to next byte LDA [Player_SprWorkL],Y STA Sprite_RAM+$15,X INY ; Store pattern in this Player sprite and go to next byte LDA [Player_SprWorkL],Y STA Sprite_RAM+$01,X INY ; Store pattern in this Player sprite and go to next byte LDA [Player_SprWorkL],Y STA Sprite_RAM+$05,X INY ; Store pattern in this Player sprite and go to next byte LDA [Player_SprWorkL],Y STA Sprite_RAM+$09,X LDA <Player_FlipBits AND #$c0 ORA <Temp_Var1 ; Merge with possible other attributes (the star invincibility palette cycle) ; Store attributes to all Player sprites STA Sprite_RAM+$02,X STA Sprite_RAM+$06,X STA Sprite_RAM+$0A,X STA Sprite_RAM+$0E,X STA Sprite_RAM+$12,X STA Sprite_RAM+$16,X LDA Sprite_RAM+$01,X CMP Sprite_RAM+$05,X BNE PRG029_CF88 ; If the patterns to the first two sprites are not the same, jump to PRG029_CF88 ; If they ARE the same, this is a mirrored sprite (like Mario "looking towards screen" etc.) ; So the "right half" sprites must mirror the "left half" LDA Sprite_RAM+$0E,X AND #~SPR_HFLIP ; Keep all attributes EXCEPT horizontal flip STA Sprite_RAM+$02,X STA Sprite_RAM+$0E,X ORA #SPR_HFLIP ; Force horizontal flip STA Sprite_RAM+$06,X STA Sprite_RAM+$12,X PRG029_CF88: ; First row sprites LDA <Player_SpriteY STA Sprite_RAM+$0C,X STA Sprite_RAM+$10,X STA Sprite_RAM+$14,X ; Second row sprites ADD #16 STA Sprite_RAM+$00,X STA Sprite_RAM+$04,X STA Sprite_RAM+$08,X ; Left column LDA <Player_SpriteX STA Sprite_RAM+$03,X STA Sprite_RAM+$0F,X ; Middle column ADD #8 STA Sprite_RAM+$07,X STA Sprite_RAM+$13,X ; Right column ADD #8 STA Sprite_RAM+$0B,X STA Sprite_RAM+$17,X LDA <Player_FlipBits AND #SPR_HFLIP BEQ PRG029_D010 ; If Player sprite is NOT horizontally flipped, jump to PRG029_D010 ; Reverse these patterns LDA Sprite_RAM+$01,X PHA LDA Sprite_RAM+$05,X STA Sprite_RAM+$01,X PLA STA Sprite_RAM+$05,X ; Reverse these X values LDA Sprite_RAM+$0B,X ADD #-24 STA Sprite_RAM+$0B,X STA Sprite_RAM+$17,X ; Reverse these patterns LDA Sprite_RAM+$0D,X PHA LDA Sprite_RAM+$11,X STA Sprite_RAM+$0D,X PLA STA Sprite_RAM+$11,X LDA Player_Flip BEQ PRG029_D010 ; If Player is not somersaulting, jump to PRG029_D010 ; Otherwise all of the sprites are pushed to the right by 8 LDA Sprite_RAM+$03,X ADD #8 STA Sprite_RAM+$03,X STA Sprite_RAM+$0F,X LDA Sprite_RAM+$07,X ADD #8 STA Sprite_RAM+$07,X STA Sprite_RAM+$13,X LDA Sprite_RAM+$0B,X ADD #8 STA Sprite_RAM+$0B,X STA Sprite_RAM+$17,X PRG029_D010: LDA Player_Kuribo BEQ PRG029_D050 ; If Player is not in a Kuribo's shoe, jump to PRG029_D050 ; In short, if Player is small, use Temp_Var1 = 6, otherwise Temp_Var1 = 0 (sprite vertical offset in shoe) LDY #$00 LDA <Player_Suit BNE PRG029_D01D LDY #$06 PRG029_D01D: STY <Temp_Var1 LDA <Player_InAir BEQ PRG029_D036 ; If Player is not mid-air, jump to PRG029_D036 LDA <Player_YVel BPL PRG029_D029 ; If Player is falling, jump to PRG029_D029 EOR #$ff ; Otherwise negate it (sort of) PRG029_D029: LSR A LSR A LSR A LSR A SUB #$03 ; The "whole" part of the Y Velocity, minus 3 EOR #$ff ; Negate that (sort of) BPL PRG029_D036 ; If the result is positive, jump to PRG029_D036 LDA #$00 ; Otherwise if it slipped below zero, just use zero PRG029_D036: ADD <Temp_Var1 ; Add that to the initial offset ADD <Player_SpriteY ; And add in the Player's sprite Y position ; Store that as the new Y position on the "first row" sprites STA Sprite_RAM+$0C,X STA Sprite_RAM+$10,X STA Sprite_RAM+$14,X ; The "second row" sprites (the shoe part in this case) use a different palette LDA Sprite_RAM+$02,X ORA #$02 STA Sprite_RAM+$02,X STA Sprite_RAM+$06,X PRG029_D050: LDA <Player_Frame CMP #PF_KICK_BIG BNE PRG029_D076 ; If Player_Frame <> PF_KICK_BIG (kicking shell, etc. when not small), jump to PRG029_D076 ; Otherwise the third "first row" sprite is pulled down to "second row" ; This becomes the foot involved in the kick! LDA Sprite_RAM+$00,X STA Sprite_RAM+$14,X ; If Player is not horizontally flipped, A = -8, otherwise A = 16 LDA #-8 LDY <Player_FlipBits BEQ PRG029_D064 LDA #16 PRG029_D064: ; The aforementioned foot sprite is offset into proper X position ADD Sprite_RAM+$0F,X STA Sprite_RAM+$17,X LDA #$1b STA Sprite_RAM+$15,X ; The foot sprite is forced to pattern $1B LDA Sprite_RAM+$0E,X STA Sprite_RAM+$16,X ; Attributes are copied (is this necessary?) PRG029_D076: LDA <Player_FlipBits AND #$80 BEQ PRG029_D094 ; If Player is vertically flipped, all sprite Y values must be reversed too! LDA Sprite_RAM+$00,X STA Sprite_RAM+$0C,X STA Sprite_RAM+$10,X STA Sprite_RAM+$14,X ADD #-16 STA Sprite_RAM+$00,X STA Sprite_RAM+$04,X STA Sprite_RAM+$08,X PRG029_D094: LDA #$00 STA Player_OffScreen ; Player_OffScreen = 0 (not off screen until we decide so!) LDY #$ff LDA Player_AboveTop BPL PRG029_D0AE ; If Player is not above top of screen, jump to PRG029_D0AE LDA <Player_SpriteY ADD #16 LDA #$00 ADC Player_AboveTop BNE PRG029_D0BC ; If Player is completely off the top of screen, jump to PRG029_D0BC BEQ PRG029_D0D3 ; If Player is not at all off the top of screen, jump to PRG029_D0D3 PRG029_D0AE: BNE PRG029_D0BC ; Jump reserved for when Player is already known as off screen, so jump (technically always) to PRG029_D0BC LDA <Player_SpriteY CMP #$c0 BGE PRG029_D0BC ; If Player_SpriteY >= $C0, he's below the status bar, so jump to PRG029_D0BC CMP #$b0 BGE PRG029_D0C9 ; If Player_SpriteY >= $B0, he's halway below the status bar, so jump to PRG029_D0C9 BLT PRG029_D0D3 ; Otherwise, Player is totally visible, jump to PRG029_D0D3 PRG029_D0BC: INC Player_OffScreen ; Player is off screen ; Prevent "second row" sprites from being displayed TYA ; A = $FF STA Sprite_RAM+$0C,X STA Sprite_RAM+$10,X STA Sprite_RAM+$14,X PRG029_D0C9: ; Prevent "first row" sprites from being displayed TYA ; A = $FF STA Sprite_RAM+$00,X STA Sprite_RAM+$04,X STA Sprite_RAM+$08,X PRG029_D0D3: ; $F1 is a magic value reserved as a "don't display this sprite" flag ; So let's check if any sprite is using that value right now... LDY #$05 ; Y = 5 (looping through all six Player sprites) PRG029_D0D5: LDA Sprite_RAM+$01,X CMP #$f1 BNE PRG029_D0E1 ; If this sprite is NOT using pattern $F1, PRG029_D0E1 ; Pattern $F1 is the "don't use" pattern, so set this sprite's Y to $F8 (make invisible) LDA #$f8 STA Sprite_RAM+$00,X PRG029_D0E1: INX INX INX INX ; X -= 4 (previous sprite) DEY ; Y-- BPL PRG029_D0D5 ; While Y >= 0, loop! LDA Level_PipeMove BEQ PRG029_D13A ; If Level_PipeMove = 0, jump to PRG029_D13A (RTS) ; When Player is going through pipe, a special "cover sprite" is used ; at the pipe entrance which masks the Player... ; Mask sprite X LDA <Pipe_PlayerX SUB <Horz_Scroll STA Sprite_RAM+$03 STA Sprite_RAM+$07 ADD #$08 STA Sprite_RAM+$0B STA Sprite_RAM+$0F ; Mask sprite Y LDA <Pipe_PlayerY SUB Level_VertScroll PHA CMP #$f0 BLT PRG029_D10E LDA #$00 PRG029_D10E: STA Sprite_RAM+$00 STA Sprite_RAM+$08 PLA ADD #16 STA Sprite_RAM+$04 STA Sprite_RAM+$0C ; The pattern doesn't really matter so long as it is opaque ; since the masking sprite is not intended to be visible ; (not that certain glitches or ill behavior don't reveal ; it once in a while) ; Uses pattern $77 ("metal block" from used up [?], should be completely opaque) LDA #$77 STA Sprite_RAM+$01 STA Sprite_RAM+$05 STA Sprite_RAM+$09 STA Sprite_RAM+$0D ; Must appear behind tiles LDA #SPR_BEHINDBG STA Sprite_RAM+$02 STA Sprite_RAM+$06 STA Sprite_RAM+$0A STA Sprite_RAM+$0E PRG029_D13A: RTS ; Return ToadHouse_Item2Inventory: .byte $0C, $08, $04, $05, $06, $04, $05, $06, $01, $02, $03, $04, $02, $03, $05 ; Toad House items: ; 0 = Warp Whistle ; 1 = P-Wing ; 2 = Frog Suit ; 3 = Tanooki ; 4 = Hammer ; 5 = Frog ; 6 = Tanooki ; 7 = Hammer ; 8 = Mushroom ; 9 = Fire Flower ; 10 = Leaf ; Item offsets per Toad House type ToadHouse_ItemOff: ; 0 1 2 3 4 5 6 .byte $02, 03, $0A, $0A, $0A, $05, $08 .byte $0B, $0E, $11 ; SB: This is a large set and could have the same effect ; with just four items, so I wonder if there was a thought ; of having additional items at some point? ToadHouse_RandomItem: ; Where 0 = Super Mushroom, 1 = Fire Flower, 2 = Super Leaf ; OR 0 = Frog, 1 = Tanooki, 2 = Hammer ; Super Mushroom / Frog has the best chance in this lottery by 1... .byte $00, $01, $02, $00, $01, $02, $00, $01, $02, $00, $01, $02, $00, $01, $02, $00 ; X values of three treasure boxes, specifically the tile that must change when opened ToadHouse_Box_X: .byte $40, $70, $A0 ; Routine to open a chest if Player is standing in front of it ; (Already checked for him pressing 'B'!) ToadHouse_ChestPressB: LDA #TILE7_CHEST_LR SUB Level_Tile_Head CMP #$04 BGE PRG029_D1B7 ; If Player is NOT touching one of the treasure boxes, jump to PRG029_D1B7 ; Touching a treasure box... determine which one LDY #$00 ; Y = 0 (first box) LDA <Player_X CMP #$60 BLT PRG029_D17F ; If Player_X < $60, jump to PRG029_D17F INY ; Y = 1 (second box) CMP #$90 BLT PRG029_D17F ; If Player_X < $90, jump to PRG029_D17F INY ; Y = 2 (third box) PRG029_D17F: ; Block change is always same height regardless of which box... LDA #$80 STA Level_BlockChgYLo LDA #$01 STA Level_BlockChgYHi LSR A ; A = 0, effectively STA Level_BlockChgXHi ; Always zero LDA ToadHouse_Box_X,Y ; Get proper X for the selected box STA Level_BlockChgXLo ; Store as low X of tile change LDA #CHNGTILE_TOADBOXOPEN STA Level_SkipStatusBarUpd ; Set Level_SkipStatusBarUpd (skip status bar for a frame, priority update!) STA Level_ChgTileEvent ; Toad House tile change event! ; THouse_Treasure = 7 is standard random basic item (mushroom, flower, leaf) LDX THouse_Treasure DEX ; X = THouse_Treasure - 1 CPX #$05 BLS PRG029_D1B1 ; If X < 5, jump to PRG029_D1B1 ; X = 5 if random super suit (frog, tanooki, hammer) ; X = 6 if standard random basic item LDA RandomN AND #$0f TAY ; Y = Random number 0 - 15 LDA ToadHouse_RandomItem,Y ; Pick a random item ADD ToadHouse_ItemOff,X ; Add appropriate offset TAX ; -> 'X' PRG029_D1B1: LDA ToadHouse_Item2Inventory,X ; Load Toad House item code -> Player Inventory index TAX ; -> 'X' INX ; X++ (because 0 is "no box opened") RTS ; Return PRG029_D1B7: LDX #$00 ; X = 0 RTS ; Return ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Player_DrawAndDoActions ; ; Have to give this one its props; this function does an entire ; mess of routines, from adjusting the Player during autoscroll, ; going to coin heaven, the airship intro, going through pipes, ; changing power ups... all the things that happen to the Player ; object, though none of the instigation code is here! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Player_DrawAndDoActions: LDA Player_HaltTick BEQ PRG029_D1CE ; If Player_HaltTick = 0 (not halted), jump to PRG029_D1CE ; This code is only executed if the Player is halted DEC Player_HaltTick ; Player_HaltTick-- JSR Player_Draw ; Draw Player's sprite! LDA Level_AScrlConfig BEQ PRG029_D1CD ; If Level_AScrlConfig = 0 (no auto scroll going on), jump to PRG029_D1CD JSR AutoScroll_CalcPlayerY ; Adjust Player_Y and Player_YHi for auto scroll PRG029_D1CD: RTS ; Return PRG029_D1CE: LDA <Player_IsDying BEQ PRG029_D1D5 ; If Player is not dying, jump to PRG029_D1D5 JMP PRG029_D6BC ; Jump to PRG029_D6BC (the Player's death routine) PRG029_D1D5: LDA Level_CoinHeav BPL PRG029_D205 ; If Level_CoinHeav >= 0, jump to PRG029_D205 ; Note that by above logic, Level_CoinHeav must be <= -1... ; Technically, it is set to $80 (-128) at start! ; Release holding anything and stop horizontal movement LDA #$00 STA Player_IsHolding STA <Player_XVel ; Produces an initial burst of upward Y velocity which slows down INC Level_CoinHeav ; Level_CoinHeav++ LDA Level_CoinHeav STA <Player_YVel BNE PRG029_D1EE ; If Level_CoinHeav <> 0, jump to PRG029_D1EE INC Level_CoinHeav ; Level_CoinHeav++ PRG029_D1EE: LDA <Player_YHi BPL PRG029_D205 ; If Player hasn't gone above top of screen yet, jump to PRG029_D205 ; Once Player crosses top of screen, he is then placed at halfway ; above the status bar (16 pixels above the death point!) LDA #$01 STA <Player_YHi ; Player_YHi = 1 (really low) LDA #$b0 STA <Player_Y ; Player_Y = $B0 (near the bottom) LDA #$d0 STA Level_CoinHeav ; Change to coin heaven (technically, this is the "general" level junction) LDA #$03 STA Level_JctCtl ; Level_JctCtl = 3 RTS ; Return PRG029_D205: LDA Player_SuitLost BEQ PRG029_D20E ; If Player_SuitLost = 0, jump to PRG029_D20E JSR Player_SuitLost_DoPoof ; Do the suit lost poof RTS ; Return PRG029_D20E: LDA Player_StarOff BEQ PRG029_D224 ; If Player_StarOff = 0 (invincibility is not wearing off), jump to PRG029_D224 CMP #31 BNE PRG029_D21D ; If Player_StarOff <> 31, jump to PRG029_D21D DEC Player_StarOff ; Player_StarOff-- JMP PRG029_D224 ; Jump to PRG029_D224 PRG029_D21D: JSR Player_Draw ; Draw Player DEC Player_StarOff ; Player_StarOff-- RTS ; Return PRG029_D224: LDA Player_Grow BEQ PRG029_D257 ; If Player is not transforming into "Super", jump to PRG029_D257 LSR A LSR A TAX ; X = Player_Grow >> 2 LDY <Player_Suit ; Y = Player_Suit BNE PRG029_D238 ; If Y <> 0 (small), jump to PRG029_D238 STX <Temp_Var1 LDA #$0b SUB <Temp_Var1 TAX ; Otherwise, X = $0B - (Player_Grow >> 2) PRG029_D238: AND #$01 PHP ; Save result LDA Player_GrowFrames,X ; Get this grow frame STA <Player_Frame ; Set as current frame JSR Player_Draw ; Draw Player ; Changes the Sprite 1/4 VROM bank as appropriate LDA PatTable_BankSel+2 AND #$03 ORA #$54 PLP ; Restore result BEQ PRG029_D250 SUB #$10 PRG029_D250: STA PatTable_BankSel+2 DEC Player_Grow ; Player_Grow-- RTS ; Return PRG029_D257: LDA Player_EndLevel BEQ PRG029_D279 ; If we're not doing the end of level run, jump to PRG029_D279 LDA Player_Kuribo BEQ PRG029_D26B ; If Player was not in a Kuribo's shoe, jump to PRG029_D26B ; If Player was in Kuribo's shoe at the end goal, "poof" it away! LDA #$00 STA Player_Kuribo LDA #$18 STA Player_SuitLost ; Player_SuitLost = $18 PRG029_D26B: LDA <Player_InAir BNE PRG029_D279 ; If Player is mid-air, jump to PRG029_D279 DEC Player_EndLevel ; Player_EndLevel-- LDA #$14 STA <Player_XVel ; Player_XVel = $14 JMP PRG029_D457 ; Jump to PRG029_D457 PRG029_D279: LDA Level_AirshipCtl BNE PRG029_D281 ; If Level_AirshipCtl <> 0, jump to PRG029_D281 JMP PRG029_D33E ; Otherwise, jump to PRG029_D33E PRG029_D281: ; Level_AirshipCtl <> 0... PHA ; Save Level_AirshipCtl LDA #$00 STA <Scroll_LastDir ; Force screen to have "last moved right" INC <Horz_Scroll ; Screen scrolls to the right BNE PRG029_D28C ; If it hasn't rolled over, jump to PRG029_D28C INC <Horz_Scroll_Hi ; Otherwise, apply carry PRG029_D28C: LDA <Horz_Scroll_Hi BNE PRG029_D296 ; If Horz_Scroll_Hi <> 0, jump to PRG029_D296 LDA <Horz_Scroll CMP #$60 BLT PRG029_D2AF ; If Horz_Scroll < $60, jump to PRG029_D2AF PRG029_D296: INC Level_AirshipH ; Level_AirshipH++ LDA Level_AirshipH ADD Counter_Wiggly ; Increase height of the airship in a bit of a wobbly way BCC PRG029_D2AF ; If it hasn't overflowed, jump to PRG029_D2AF INC <Vert_Scroll LDA <Objects_Y+4 SUB #$01 STA <Objects_Y+4 ; Anchor's Y minus 1 BCS PRG029_D2AF DEC <Objects_YHi+4 ; If overflow occurred, propogate the carry PRG029_D2AF: PLA ; Restore Level_AirshipCtl JSR DynJump ; Dynamic jump based on Level_AirshipCtl... ; THESE MUST FOLLOW DynJump FOR THE DYNAMIC JUMP TO WORK!! .word AirshipCtl_DoNothing ; 0 - Do nothing (not used) .word AirshipCtl_RunAndJump ; 1 - Run and jump (when horizontal scroll hits $80) .word AirshipCtl_Catch ; 2 - Catch anchor .word AirshipCtl_HoldAnchor ; 3 - Hold onto anchor .word AirshipCtl_LandOnDeck ; 4 - Land Player on deck AirshipCtl_DoNothing: RTS ; Return AirshipCtl_RunAndJump: LDA #$ef STA Level_VertScroll ; Level_VertScroll = $EF LDA <Horz_Scroll CMP #$80 BLT PRG029_D2D0 ; If Horz_Scroll < $80, jump to PRG029_D2D0 ; Player makes the jump! LDA #-$60 STA <Player_YVel ; Player_YVel = -$60 INC Level_AirshipCtl ; Next Level_AirshipCtl! PRG029_D2D0: LDA #$01 STA <Player_FlipBits ; Player_FlipBits = 1 LDA #$20 STA <Player_XVel ; Player_XVel = $20 JMP PRG029_D457 ; $D2D8 AirshipCtl_Catch: LDA <Player_X CMP #$36 BLT PRG029_D2FF ; If Player_X < $36, jump to PRG029_D2FF ; Apply Player's velocities JSR Player_ApplyYVelocity JSR Player_ApplyXVelocity LDA <Player_YVel ADD #$04 STA <Player_YVel ; Player_YVel += 4 CMP #$0f BLS PRG029_D2F5 ; If Player_YVel < $0F, jump to PRG029_D2F5 INC Level_AirshipCtl ; Otherwise, next Level_AirshipCtl! PRG029_D2F5: ; Set mid-air jump frame as appropriate by suit and draw Player... LDY <Player_Suit LDA Airship_JumpFrameByPup,Y STA <Player_Frame JMP Player_Draw PRG029_D2FF: JMP PRG029_D457 ; Jump to PRG029_D457 AirshipCtl_HoldAnchor: LDA #$02 STA <Player_FlipBits ; Player_FlipBits = 2 (use "caught anchor" frame) LDA #-$14 STA <Player_YVel ; Player_YVel = -$14 JSR PRG029_D457 ; Continue using the "run" code LDA <Vert_Scroll CMP #$70 BLT PRG029_D31B ; If Vert_Scroll < $70, jump to PRG029_D31B (RTS) LDA #$03 STA Level_JctCtl ; Level_JctCtl = 3 (general purpose junction) INC Level_AirshipCtl ; Next Level_AirshipCtl! PRG029_D31B: RTS ; Return AirshipCtl_LandOnDeck: LDA Level_AScrlConfig BEQ PRG029_D33D ; If autoscroll not enabled, jump to PRG029_D33D JSR Player_ApplyYVelocity ; Apply Player's Y velocity LDA <Player_YVel BMI PRG029_D330 ; If Player's Y velocity is negative (still rising), jump to PRG029_D330 LDA #$00 STA Level_AirshipCtl ; Level_AirshipCtl = 0 (airship sequence complete) STA Level_TimerEn ; Level_TimerEn = 0 (level timer enabled!) PRG029_D330: LDA <Player_YVel ADD #$04 STA <Player_YVel ; Player_YVel += 4 (Player falling to airship) JSR Player_DoScrolling ; Update scrolling at Player's position JSR PRG029_D2F5 ; Mid-air frame as appropriate PRG029_D33D: RTS ; Return PRG029_D33E: LDA Level_GetWandState CMP #$03 BLS PRG029_D361 ; If Level_GetWandState < 3 (wand grabbed), jump to PRG029_D361 CMP #$07 BLS PRG029_D354 ; If Level_GetWandState < 7, jump to PRG029_D354 ; Player's slow decent... LDA <Player_Y ADD #$02 STA <Player_Y ; Player_Y += 2 BCC PRG029_D354 ; If no carry, jump to PRG029_D354 INC <Player_YHi ; Otherwise, apply carry PRG029_D354: ; Player holding wand! LDY <Player_Suit ; Y = Player_Suit LDA Airship_JumpFrameByPup,Y STA <Player_Frame ; Use proper "mid-air" frame JSR Player_Draw ; Draw Player JMP Wand_Offset_BySuit ; Jump to Wand_Offset_BySuit PRG029_D361: ; Level_PipeMove is set to $8x when we are EXITING from ; a pipe OR moving through it (in-level transit style), ; but NOT when a non-transit pipe is entered; just being ; clear, the "BPL" is for jumping when Level_PipeMove is ; NOT holding an $8x value (and it might be zero, but ; that check is coming up next...) LDA Level_PipeMove BPL PRG029_D369 ; If not transiting or exiting, jump to PRG029_D369 JMP Level_PipeTransitOrExit ; Otherwise jump to Level_PipeTransitOrExit PRG029_D369: BNE Level_PipeEnter ; If Level_PipeMove is not zero (and not in the $8x range), jump to Level_PipeEnter JMP PRG029_D3EC ; Otherwise, jump to PRG029_D3EC Level_PipeEnter: ; For when you've just entered a pipe of any sort... LDA Event_Countdown BNE PRG029_D3A0 ; If Event_Countdown <> 0, jump to PRG029_D3A0 ; Init... LDA Level_PipeMove AND #%00011100 ; Examine just bits 2-4 (determines what the pipe will do) CMP #%00010100 BNE PRG029_D384 ; If this is NOT an in-level transit pipe, jump to PRG029_D384 LDA #$05 STA Level_PipeExitDir ; Otherwise, Level_PipeExitDir = 5 (in-level transit flag) JMP PRG029_D395 ; Jump to PRG029_D395 PRG029_D384: ; Non in-level transit pipe... LSR A LSR A ; Shift down twice so the pipe behavior value is index based STA Level_JctCtl ; Push it right into Level_JctCtl! CMP #$01 ; Although Level_JctCtl = 1 is not valid, this is used as "return to map"... BNE PRG029_D395 ; If Level_JctCtl <> 1, jump to PRG029_D395 INC <Level_ExitToMap ; Level_ExitToMap = 1 (return to map) LDA #$00 STA Map_ReturnStatus ; Map_ReturnStatus = 0 (completed level, i.e. did not die) RTS ; Return PRG029_D395: ; Entered into an in-level transit pipe... ; Level_PipeMove will hold the direction and bit 7, which flags the in-level transit pipe LDA Level_PipeMove AND #$03 ORA #$80 STA Level_PipeMove RTS ; Return PRG029_D3A0: ; While traveling in a pipe (but not an in-level transit style) LDA Level_PipeMove AND #%00000011 ; Just keep the lower 2 bits (direction) CMP #$02 BGS PRG029_D3CB ; If direction is down/up, jump to PRG029_D3CB ; Left/right pipe LDA Event_Countdown CMP #16 BLS PRG029_D3CA ; If Event_Countdown < 16, jump to PRG029_D3CA (RTS) PHA ; Save Event_Countdown JSR PipeMove_LeftRight ; Move through pipe horizontally PLA ; Restore Event_Countdown CMP #36 BGS PRG029_D3CA ; If Event_Countdown >= 36, jump to PRG029_D3CA ; Remove Player's edge sprites as he vanishes into pipe LDX Player_SprOff LDA #$f8 STA Sprite_RAM+$00,X STA Sprite_RAM+$04,X STA Sprite_RAM+$0C,X STA Sprite_RAM+$10,X PRG029_D3CA: RTS ; Return PRG029_D3CB: ; Up/down pipe JSR PipeMove_UpDown ; Move through pipe vertically LDA Event_Countdown CMP #16 BGE PRG029_D3EB ; If Event_Countdown >= 16, jump to PRG029_D3EB (RTS) LDA Player_SprOff LDX <Player_YVel BPL PRG029_D3DF ; If Player_YVel >= 0 (going down), jump to PRG029_D3DF ADD #$0c ; Remove other half of Player ; Gets rid of appropriate half of Player sprites as he disappears into pipe PRG029_D3DF: TAX ; X = Player_SprOff LDA #$f8 STA Sprite_RAM+$00,X STA Sprite_RAM+$04,X STA Sprite_RAM+$08,X PRG029_D3EB: RTS ; Return PRG029_D3EC: ; Nothing to do with pipes... JMP PRG008_A224 ; Jump to PRG008_A224 ; When Player has grabbed wand, offset from Player X/Y by suit / power-up Wand_XOff_BySuitL: .byte -5, -5, -5, -5, -7, -5, -5 Wand_XOff_BySuitR: .byte 6, 6, 6, 6, 8, 6, 6 Wand_YOff_BySuit: .byte 1, -9, -9, -9, 3, -9, -9 Wand_Offset_BySuit: LDY Object_SprRAM+5 ; Y = 5th index object Sprite RAM offset LDX <Player_Suit ; X = Player's suit LDA <Player_FlipBits PHP ; Save Player flip bits LDA Wand_XOff_BySuitR,X ; Wand offset, held right PLP ; Restore Player flip bits BNE PRG029_D415 ; If Player is not flipped, jump to PRG029_D415 LDA Wand_XOff_BySuitL,X ; Wand offset, held left PRG029_D415: ADD <Player_SpriteX ; Add offset to Player sprite X STA Sprite_RAM+$03,Y ; -> Sprite X ADD #$08 ; +8 STA Sprite_RAM+$07,Y ; -> Sprite X ; Temp_Var1 = Player_YHi LDA <Player_YHi STA <Temp_Var1 LDA Wand_YOff_BySuit,X BPL PRG029_D42C ; If Y offset is positive, jump to PRG029_D42C DEC <Temp_Var1 ; Otherwise, Temp_Var1-- PRG029_D42C: ADD <Player_SpriteY ; Add offset to Player Y BCC PRG029_D433 ; If no carry, jump to PRG029_D433 INC <Temp_Var1 ; Otherwise, apply carry PRG029_D433: LDX <Temp_Var1 ; X = Temp_Var1 CPX #$01 BPL PRG029_D454 ; If off-screen, jump to PRG029_D454 ; Store Wand Sprites Y STA Sprite_RAM+$00,Y STA Sprite_RAM+$04,Y ; Store Wand Sprite Patterns LDA #$99 STA Sprite_RAM+$01,Y STA Sprite_RAM+$05,Y ; Palette cycling of wand LDA <Counter_1 AND #$06 LSR A STA Sprite_RAM+$02,Y ; Mirrored half ORA #SPR_HFLIP STA Sprite_RAM+$06,Y PRG029_D454: RTS ; Return Level_EndFlipBits: .byte $00, $40 PRG029_D457: ; The "run forward" bit at the end of a level... ; OR the run & jump for the airship! LDA <Player_FlipBits AND #$02 BEQ PRG029_D468 ; If (Player_FlipBits & 2) = 0, jump to PRG029_D468 JSR Player_ApplyYVelocity ; Apply Y velocity ; Used by airship only (the "caught anchor" frames) LDY <Player_Suit LDA Player_ClimbFrame,Y ; Get "caught anchor" frame JMP PRG029_D49B ; Jump to PRG029_D49B PRG029_D468: LDA <Player_FlipBits AND #$01 TAY ; Y = Player_FlipBits & 1 LDA Level_EndFlipBits,Y ; Get proper flip bit ORA <Player_FlipBits STA <Player_FlipBits ; Level_EndFlipBits |= Level_EndFlipBits[Y] JSR Player_ApplyXVelocity ; Apply X Velocity LDA <Counter_1 AND #$06 LSR A STA <Temp_Var1 ; Temp_Var1 = (Counter_1 & 6) >> 1 (0-3) PRG029_D47E: ; Jump point for horizontal pipe-walking LDY Player_Kuribo BEQ PRG029_D491 ; If Player is NOT wearing Kuribo's shoe, jump to PRG029_D491 ; Wearing Kuribo's shoe (NOTE: This CAN'T happen because the ; shoe was forcefully removed before we got here; dead code?) AND #$01 LDY <Player_Suit BEQ PRG029_D48B ; If Player_Suit = 0 (small), jump to PRG029_D48B LDY #$01 ; Y = 1 (small / big same) PRG029_D48B: ADD Player_KuriboFrame,Y BNE PRG029_D49B ; If result is not zero, jump to PRG029_D49B PRG029_D491: LDA <Player_Suit ASL A ASL A ORA <Temp_Var1 TAY ; Y = (Player_Suit << 2) | Temp_Var1 (0 to 3) LDA Player_WalkFramesByPUp,Y ; Get appropriate frame PRG029_D49B: STA <Player_Frame ; Whatever the result, store as Player frame! JSR Player_Draw ; Draw Player RTS ; Return Pipe_Move_JumpTable: .word Player_Die_NotDying ; 0 - Not used .word Pipe_Move_Up ; 1 - Moving Up .word Pipe_Move_Down ; 2 - Down .word Pipe_Move_Right ; 3 - Right .word Pipe_Move_Left ; 4 - Left .word Pipe_Transit ; 5 - In-level transit ; For horizontal pipe movement, X velocity right and left, respectively PipeMove_XVel: .byte 8, -8 ; For vertical pipe movement, Y velocity down and up, respectively PipeMove_YVel: .byte 8, -8 ; This sets the Scroll_LastDir variable based on travel direction (right and left, respectively) PipeMove_LR_Dir: .byte 0, 1 ; This adds to Horz_Scroll based on travel direction (right and left, respectively) PipeMove_LR: .byte 1, -1 ; High byte sign extension to values in table immediately above PipeMove_LRH: .byte $00, $FF Level_PipeTransitOrExit: ; Jump here when Level_PipeExitDir is one of the $8x varities ; indicating that we're moving through the pipe (in-level ; transit or simply exiting out one end of it) ; Splash_DisTimer = 8 (halt Player splashing in water when in-pipe) LDA #$08 STA Splash_DisTimer LDA Level_PipeExitDir ASL A TAY ; Dynamic jump based on Level_PipeExitDir index into Pipe_Move_JumpTable table LDA Pipe_Move_JumpTable,Y STA <Temp_Var1 LDA Pipe_Move_JumpTable+1,Y STA <Temp_Var2 JMP [Temp_Var1] Player_Die_NotDying: RTS ; Return Pipe_Move_Up: ; Level_PipeMove = $83 (indicates Player is moving up through pipe, no additional action to be taken) LDA #$83 STA Level_PipeMove JSR PipeMove_UpDown ; Do pipe movement and draw Player LDA Event_Countdown BNE PRG029_D4DF ; If Event_Countdown <> 0, jump to PRG029_D4DF JMP Player_StopMovement ; Jump to Player_StopMovement PRG029_D4DF: CMP #32 LDA Player_SprOff BLT PRG029_D4E9 ; If Event_Countdown < 32, jump to PRG029_D4E9 (RTS) JMP PRG029_D3DF ; Jump to PRG029_D3DF PRG029_D4E9: RTS ; Return Pipe_Move_Down: ; Level_PipeMove = $82 (indicates Player is moving down through pipe, no additional action to be taken) LDA #$82 STA Level_PipeMove STA <Player_InAir ; Flag Player as being mid-air (going to fall out the bottom) LDA #$30 STA <Player_YVel ; Player_YVel = $30 JSR Player_ApplyYVelocity ; Apply Player's Y velocity JSR PipeMove_UpDown ; Move through pipe vertically LDA Event_Countdown BNE PRG029_D50E ; If Event_Countdown <> 0, jump to PRG029_D50E LDA #$00 STA Player_IsDucking ; Clear ducking flag (since Player pressed down on a pipe, it's incorrectly set) STA Level_PipeMove ; Not moving through a pipe anymore STA <Player_XVel ; Not horizontally moving, period LDA #$38 STA <Player_YVel ; Player_IsDucking = $38 (fall out the bottom) PRG029_D50E: RTS ; Return Pipe_Move_Right: ; Level_PipeMove = $80 (indicates Player is moving right through pipe, no additional action to be taken) LDA #$80 STA Level_PipeMove LDA #$40 STA <Player_FlipBits ; Player_FlipBits = $40 (facing right) LDY #$00 ; Y = 0 (moving right) PRG029_D51A: LDA <Counter_1 LSR A BCC PRG029_D53B ; Basically, every other tick, jump to PRG029_D53B ; And on the other ticks... LDA PipeMove_LR_Dir,Y STA <Scroll_LastDir LDA <Horz_Scroll LDX <Horz_Scroll_Hi BNE PRG029_D52E ; If Horz_Scroll_Hi = 0, jump to PRG029_D52E ; Horz_Scroll_Hi <> 0... CMP #$80 BLT PRG029_D53B ; If Horz_Scroll < $80, jump to PRG029_D53B PRG029_D52E: ADD PipeMove_LR,Y STA <Horz_Scroll ; Horz_Scroll += PipeMove_LR[Y] ; Add matching sign extension and any carry LDA PipeMove_LRH,Y ADC <Horz_Scroll_Hi STA <Horz_Scroll_Hi PRG029_D53B: JSR PipeMove_LeftRight ; Move through pipe horizontally LDX Player_SprOff ; X = Player's root sprite position ; Remove one of the masking sprites?? LDA #$f8 STA Sprite_RAM+$08,X LDA Event_Countdown BNE PRG029_D54E ; If Event_Countdown <> 0, jump to PRG029_D54E (RTS) JSR Player_StopMovement ; Stop movement exiting pipe! PRG029_D54E: RTS ; Return Pipe_Move_Left: ; Level_PipeMove = $81 (indicates Player is moving left through pipe, no additional action to be taken) LDA #$81 STA Level_PipeMove LDA #$00 STA <Player_FlipBits ; Player_FlipBits = $00 (facing left) LDY #$01 ; Y = 1 (moving left) JMP PRG029_D51A ; Jump to PRG029_D51A ; Y Offset based on direction (down and up respectively) PipeTransit_YOff: .byte 31, 0 Pipe_Transit: LDA Level_7Vertical BNE PRG029_D5DC ; If level is a vertical pipe maze type level, jump to PRG029_D5DC ; Pipe transit for non-vertical levels ; ; This version is functionally limited in non-vertical levels ; such that only vertical runs of in-level transit pipes are ; supported; none of the bends and such of a pipe maze level. ; ; But there is no Level_Tileset in the non-vertical realm that ; has the graphics to support the bends and whatnot anyway, so ; they clearly weren't planning on it... ; ; Further these pipes intend to bring you from the lowest scroll ; point to the uppermost scroll point and visually act strangely ; if you try to go somewhere short of that at either end. LDA #-2 ; A = -2 (scroll upward) LDX #$01 ; X = 1 LDY <Player_YVel ; Y = Player_YVel BMI PRG029_D56F ; If Player_YVel < 0, jump to PRG029_D56F ; If Player_Vel >= 0... LDA #$02 ; A = 2 (scroll downward) DEX ; X = 0 PRG029_D56F: STA Pipe_TransYDelta ; Pipe_TransYDelta = -2 (going up) or 2 (going down) ADD <Vert_Scroll STA <Vert_Scroll ; Vert_Scroll += A STA Level_VertScroll ; Level_VertScroll += A LDY <Player_YVel ; Y = Player_YVel BPL PRG029_D584 ; If Player_YVel >= 0, jump to PRG029_D584 BCS PRG029_D59B ; If carry occurred from addition to Vert_Scroll, jump to PRG029_D59B ; Otherwise... ; Inter-level vertical pipes stop moving upward when scroll reaches $00 LDA #$00 ; A = 0 BEQ PRG029_D58A ; Jump (technically always) to PRG029_D58A PRG029_D584: CMP #$ef BLT PRG029_D59B ; If Vert_Scroll < $EF, jump to PRG029_D59B ; Inter-level vertical pipes stop moving downward when scroll reaches $EF LDA #$ef ; Otherwise, A = $EF (bottom scroll) PRG029_D58A: ; Common termination point when exiting inter-level vertical pipe STA <Vert_Scroll ; Update Vert_Scroll LDA #$01 STA Level_PipeExitDir ; Level_PipeExitDir = 1 (exiting up) LDY <Player_YVel BMI PRG029_D598 ; If Player_YVel < 0, jump to PRG029_D598 INC Level_PipeExitDir ; Otherwise, Level_PipeExitDir = 2 (exiting down) PRG029_D598: JMP PRG008_A38E ; Jump to PRG008_A38E (Player exits pipe) PRG029_D59B: ; X = 0 (going down) or 1 (going up) LDA PipeTransit_YOff,X STA <Temp_Var10 ; Temp_Var10 = PipeTransit_YOff[X] (appropriate Y offset) LDA #$08 STA <Temp_Var11 ; Temp_Var11 = 8 JSR Player_GetTileAndSlope ; Get tile SUB #TILE1_PIPETB4_L CMP #$02 BLT PRG029_D5C3 ; If tile is one of the transit pipe top/bottom tiles, jump to PRG029_D5C3 (RTS) LDA #16 ; A = 16 CPX #$00 BEQ PRG029_D5B8 ; If Player was going down, jump to PRG029_D5B8 ; Player was going up DEC <Player_YHi ; Player_YHi-- LDA #-16 ; A = 16 PRG029_D5B8: ADD <Player_Y AND #$f0 STA <Player_Y ; Player_Y = (Player_Y + A) & $F0 (tile-aligned move) BCC PRG029_D5C3 ; If no carry, jump to PRG029_D5C3 INC <Player_YHi ; Otherwise, apply carry PRG029_D5C3: RTS ; Return ; Defines Y and X offset pairs, for two different rotation possibilities ; when Player hits an elbow (does he go from up to right, or up to left? etc.) ; Indexed per lower 2 bits of Level_PipeMove, shifted up by 2 PipeTransit_XYOffsets: ; YO1 XO1 YO2 XO2 .byte 30, 18, 2, 18 ; Moving right .byte 30, 2, 2, 2 ; Moving left .byte 30, 14, 30, 2 ; Moving up .byte 2, 14, 2, 2 ; Moving down ; This is actually access as a contiguous array, but might as well be clear PipeTransit_YDelta: .byte 2, -2 ; Y Deltas while moving through pipes (down and up) PipeTransit_XDelta: .byte 2, -2 ; X Deltas while moving through pipes (right and left) ; Sets Level_PipeExitDir appropriately based on direction Level_PipeExitDirTable: .byte $03, $04, $02, $01 PRG029_D5DC: ; Pipe transit in vertical levels LDA Level_PipeMove AND #$03 ; Just the lower 2 bits of Level_PipeMove (the direction) PHA ; Save it TAY ; Y = the direction of Level_PipeMove LDX #$00 ; Index Player's X CPY #$02 BLS PRG029_D605 ; If direction is right or left, jump to PRG029_D605 ; Direction is down or up LDX #(Player_Y - Player_X) ; Index Player's Y instead LDA PipeTransit_YDelta,Y ; Get delta BPL PRG029_D5FD ; If it's not negative, jump to PRG029_D5FD LDA <Player_SpriteY CMP #$68 LDA #$00 BLT PRG029_D608 ; If Player_SpriteY < $68, jump to PRG029_D608 DEC <Player_XHi,X ; Decrement approprate Player Hi JMP PRG029_D605 ; Jump to PRG029_D605 PRG029_D5FD: LDA <Player_SpriteY CMP #$38 LDA #$00 BGE PRG029_D608 ; If Player_SpriteY >= $38, jump to PRG029_D608 PRG029_D605: LDA PipeTransit_YDelta,Y ; Get delta PRG029_D608: ADD <Player_X,X ; Apply delta to Player X or Y (as appropriate) AND #$fe ; Align to nearest 2 pixels STA <Player_X,X ; Store it BCC PRG029_D613 ; If no carry, jump to PRG029_D613 INC <Player_XHi,X ; Otherwise, apply carry PRG029_D613: AND #$0f ; Lower 4 bits of Player's X or Y TAX ; -> 'X' CPY #$02 BLS PRG029_D651 ; If direction is right or left, jump to PRG029_D651 ; Down or up LDA <Player_X AND #$f0 ORA #$08 STA <Player_X ; Player_X = (Player_X & $F0) | 8 (nearest column, centered) LDA #$01 STA <Scroll_LastDir ; Scroll_LastDir = 1 (down) LDA PipeTransit_YDelta,Y ; Get delta BPL PRG029_D630 ; If delta is not negative, jump to PRG029_D630 ; Negative delta means up, so... DEC <Scroll_LastDir ; Scroll_LastDir = 0 (up) DEC Level_VertScrollH ; Level_VertScrollH-- PRG029_D630: STA Pipe_TransYDelta ; Store into Pipe_TransYDelta ADD Level_VertScroll STA Level_VertScroll ; Level_VertScroll += Pipe_TransYDelta BCC PRG029_D63F ; If no carry, jump to PRG029_D63F INC Level_VertScrollH ; Otherwise, apply carry PRG029_D63F: LDY Level_VertScrollH ; Y = Level_VertScrollH JSR LevelJct_GetVScreenH ; Adjust coordinates for vertical ; Update scrolls STA <Vert_Scroll STY <Vert_Scroll_Hi LDA <Player_Y SUB Level_VertScroll STA <Player_SpriteY ; Player_SpriteY = relative Y position PRG029_D651: PLA ; Restore the lower 2 bits of Level_PipeMove (the direction) ; 'X' was last left as lower 4 bits of Player's X or Y position ; (i.e. distance across cell horizontally or vertically; a value ; of zero indicates Player has just aligned with a new tile) CPX #$00 BNE PRG029_D69B ; If Player has not reached a new tile, jump to PRG029_D69B ; Player has reached a new tile... ASL A ASL A ; direction of pipe move, shifted left 2 LDX #$01 ; X = 1 TAY ; Y = the direction of the pipe move, shifted left 2 (0, 4, 8, 12) PRG029_D65B: LDA PipeTransit_XYOffsets,Y STA <Temp_Var10 ; Temp_Var10 = Y offset LDA PipeTransit_XYOffsets+1,Y STA <Temp_Var11 ; Temp_Var11 = X offset JSR Player_GetTileAndSlope ; Get tile STA <Temp_Var1 ; Store into Temp_Var1 SUB #TILE8_SCENPIPE_ENDVR CMP #$02 BGE PRG029_D674 ; If tile is NOT a vertical scenery pipe's left or right end, jump to PRG029_D674 JMP PRG029_D69C ; Otherwise, jump to PRG029_D69C PRG029_D674: LDA <Temp_Var1 CMP #TILE8_SCENPIPE_ENDH1B BNE PRG029_D67D ; If tile is NOT a horizontal scenery pipe's bottom tile, jump to PRG029_D67D JMP PRG029_D69C ; Otherwise, jump to PRG029_D69C PRG029_D67D: LDA <Temp_Var1 SUB #TILE8_PIPEELBOW_CUL CMP #$04 BGE PRG029_D696 ; If tile is NOT a pipe elbow corner tile, jump to PRG029_D696 ; Otherwise... STX <Temp_Var1 ; Temp_Var1 = 1 OR 0 (depending which iteration, which will change which way it rotates) LDA Level_PipeMove AND #%10000010 ; Keep only the up/down vs left/right bit and the "in-transit" bit EOR #%00000010 ; Turn corner ORA <Temp_Var1 ; -> Temp_Var1 STA Level_PipeMove ; Update Level_PipeMove LDX #$00 ; X = 0 PRG029_D696: INY ; Y++ INY ; Y++ (next Y/X offset pair) DEX ; X-- (if Player turned corner, this will result in a negative) BPL PRG029_D65B ; If X >= 0, loop! PRG029_D69B: RTS ; Return PRG029_D69C: ; In-transit pipe, hit an end LDA Level_PipeMove AND #%00000011 TAY ; Y = lower 2 bits of Level_PipeMove (the direction) BNE PRG029_D6AB ; If direction is not rightward, jump to PRG029_D6AB ; Otherwise, add 16 to Player_X LDA <Player_X ADD #16 STA <Player_X PRG029_D6AB: ; Set Level_PipeExitDir appropriately LDA Level_PipeExitDirTable,Y STA Level_PipeExitDir JMP PRG008_A38E ; Jump to PRG008_A38E Player_Die_JumpTable: .word Player_Die_NotDying ; 0 - Player isn't dying! Do nothing .word Player_Die_Dying ; 1 - Dying normal .word Player_Die_FellOff ; 2 - Dying by having fallen off screen .word Player_Die_TimeUp ; 3 - Dying due to time up PRG029_D6BC: ; Player is dying! LDA <Player_IsDying ASL A TAY ; Y = Player_IsDying << 1 LDA Player_Die_JumpTable,Y STA <Temp_Var1 LDA Player_Die_JumpTable+1,Y STA <Temp_Var2 JMP [Temp_Var1] ; Jump to appropriate "Player is dying" routine... Player_Die_Dying: LDA Player_AboveTop BNE PRG029_D6DA ; If Player is above top of screen, jump to PRG029_D6DA LDA <Player_SpriteY AND #$f0 CMP #$b0 BEQ PRG029_D6E5 ; If Player_SpriteY >= $B0 && Player_SpriteY <= $BF (Player is halfway below status bar), jump to PRG029_D6E5 PRG029_D6DA: LDA Event_Countdown BNE PRG029_D6E2 ; If Event_Countdown <> 0 (time until drop to map), jump to PRG029_D6E2 JMP PRG029_D768 ; Otherwise, jump to PRG029_D6E2 PRG029_D6E2: JMP PRG029_D771 ; Jump to PRG029_D771 if Event_Countdown <> 0 PRG029_D6E5: LDA Event_Countdown BNE PRG029_D6EF ; If Event_Countdown > 0 (time until drop to map), jump to PRG029_D6EF ; Reload Event_Countdown LDA #64 STA Event_Countdown ; Event_Countdown = 64 PRG029_D6EF: CMP #$01 BNE PRG029_D6F5 ; If Event_Countdown <> 1, jump to PRG029_D6F5 (RTS) BEQ PRG029_D6FB ; If Event_Countdown = 1, jump to PRG029_D6FB PRG029_D6F5: RTS ; Return Player_Die_FellOff: LDA Event_Countdown BNE PRG029_D702 ; If Event_Countdown <> 0, jump to PRG029_D702 (RTS) PRG029_D6FB: INC <Level_ExitToMap ; Level_ExitToMap = 1 LDA #$01 STA Map_ReturnStatus ; Map_ReturnStatus = 1 (Player died, level is not clear) PRG029_D702: RTS ; Return ; Patterns for TIME-UP TIMEUP_Sprites: .byte $21 ; T .byte $23 ; I .byte $25 ; M .byte $27 ; E .byte $29 ; - .byte $1D ; U .byte $1F ; P ; X positions for each letter in TIME-UP TIMEUP_SpriteXs: .byte $60, $68, $70, $78, $80, $88, $90 Player_Die_TimeUp: LDA Player_AboveTop BNE PRG029_D71E ; If Player is off top of screen, jump to PRG029_D71E LDA <Player_SpriteY AND #$f0 CMP #$b0 BEQ PRG029_D729 ; If Player_SpriteY >= $B0 && Player_SpriteY <= $BF (Player is halfway below status bar), jump to PRG029_D729 PRG029_D71E: LDA Event_Countdown BNE PRG029_D726 ; If Event_Countdown <> 0, jump to PRG029_D726 JMP PRG029_D768 ; Jump to PRG029_D768 PRG029_D726: JMP PRG029_D771 ; Jump to PRG029_D768 if Event_Countdown <> 0 PRG029_D729: DEC <Pipe_PlayerY ; Pipe_PlayerY-- LDA <Pipe_PlayerX CMP #$60 BLT PRG029_D73B ; If Pipe_PlayerX < $60, jump to PRG029_D73B ADD <Pipe_PlayerY STA <Pipe_PlayerX ; Pipe_PlayerX += Pipe_PlayerY LDA #112 STA Event_Countdown ; Event_Countdown = 112 PRG029_D73B: LDA Event_Countdown BEQ PRG029_D6FB ; If Event_Countdown = 0, jump to PRG029_D6FB LDA #$32 STA PatTable_BankSel+2 ; Set sprites 1/4 VROM page for the TIME UP sprites LDY #$06 ; Y = 6 (seven sprites for T I M E - U P) LDX Player_SprOff ; Starting from Player's sprite offset PRG029_D74A: LDA <Pipe_PlayerX STA Sprite_RAM+$00,X LDA TIMEUP_Sprites,Y STA Sprite_RAM+$01,X LDA #$01 STA Sprite_RAM+$02,X LDA TIMEUP_SpriteXs,Y STA Sprite_RAM+$03,X INX INX INX INX DEY ; Y-- BPL PRG029_D74A ; While Y >= 0, loop RTS ; Return PRG029_D768: ; Player gravity while dying INC <Player_YVel INC <Player_YVel ; Player_YVel += 2 LDX #$00 ; X = 0 (?) JSR Player_ApplyYVelocity ; Applies Player's Y velocity PRG029_D771: LDA #PF_DIE STA <Player_Frame ; Player_Frame = PF_DIE JSR Player_Draw ; Draw Player RTS ; Return ; Move Player left/right within pipe PipeMove_LeftRight: LDA Level_PipeMove AND #$01 ; Just determining left or right (see def for Level_PipeMove) TAY ; Y = 0 (right) or 1 (left) LDA PipeMove_XVel,Y ; Get appropriate X velocity STA <Player_XVel ; Set it! JSR Player_ApplyXVelocity ; Apply Player's X velocity ; A little "step up" into the pipe DEC <Player_Y DEC <Player_Y ; Player_Y -= 2 LDA <Counter_1 AND #$0c LSR A LSR A STA <Temp_Var1 ; Temp_Var1 = (Counter_1 & $C) >> 2 (0 to 3, walking animation) JSR PRG029_D47E ; Do walking animation and draw Player ; Undo "step up" INC <Player_Y INC <Player_Y ; Player_Y += 2 RTS ; Return ; Move Player up/down within pipe PipeMove_UpDown: LDA Level_PipeMove AND #$01 ; Just determining up or down (see def for Level_PipeMove) TAY ; Y = 0 (down) or 1 (up) LDA PipeMove_YVel,Y ; Get appropriate Y velocity STA <Player_YVel ; Set it! JSR Player_ApplyYVelocity ; Apply Player's Y velocity JSR PipeMove_SetPlayerFrame ; Set appropriate frame for pipe traversal JMP Player_Draw ; Jump to draw Player! Player_StopMovement: LDA #$00 STA Level_PipeMove ; Not moving through a pipe STA <Player_XVel ; Player stopped horizontall STA <Player_YVel ; Player stopped vertically STA <Player_InAir ; Not mid-air RTS ; Return SuitLost_Poof_Patterns: .byte $47, $45, $43, $41 Player_SuitLost_DoPoof: DEC Player_SuitLost ; Player_SuitLost-- AND #$0c LSR A LSR A TAY ; Y = 0-3, changing every 4 ticks LDA SuitLost_Poof_Patterns,Y ; Get poof pattern STA <Temp_Var2 ; Store into Temp_Var2 LDY Player_SprOff ; Y = Player_SprOff (Player sprite beginning offset) LDA #%11000001 ; Flipped horizontal and vertical, and palette 1 STA <Temp_Var1 ; -> Temp_Var1 PRG029_D7D3: ; Sprite Y LDA <Player_SpriteY ADD #$08 ; Start at 8 pixels below Player sprite Y pos STA Sprite_RAM+$00,Y ; Store into sprite Y ; Poof pattern LDA <Temp_Var2 STA Sprite_RAM+$01,Y ; Attribute LDA <Temp_Var1 STA Sprite_RAM+$02,Y ; Sprite X LDA <Player_X SUB <Horz_Scroll STA Sprite_RAM+$03,Y LDA <Temp_Var1 AND #$f0 BEQ PRG029_D7FC ; If we're the unflipped one, jump to PRG029_D7FC ; Otherwise, put it to the right of the first one LDA Sprite_RAM+$03,Y ADD #$08 STA Sprite_RAM+$03,Y PRG029_D7FC: INY INY INY INY ; Y += 4 ; Other sprite is not H/V flipped LDA <Temp_Var1 SUB #%11000000 STA <Temp_Var1 BCS PRG029_D7D3 ; Loop if not the second sprite RTS ; Return ;; BEGIN HUGE UNUSED SPACE .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D80A - $D819 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D81A - $D829 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D82A - $D839 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D83A - $D849 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D84A - $D859 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D85A - $D869 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D86A - $D879 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D87A - $D889 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D88A - $D899 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D89A - $D8A9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D8AA - $D8B9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D8BA - $D8C9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D8CA - $D8D9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D8DA - $D8E9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D8EA - $D8F9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D8FA - $D909 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D90A - $D919 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D91A - $D929 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D92A - $D939 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D93A - $D949 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D94A - $D959 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D95A - $D969 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D96A - $D979 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D97A - $D989 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D98A - $D999 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D99A - $D9A9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D9AA - $D9B9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D9BA - $D9C9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D9CA - $D9D9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D9DA - $D9E9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D9EA - $D9F9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $D9FA - $DA09 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA0A - $DA19 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA1A - $DA29 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA2A - $DA39 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA3A - $DA49 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA4A - $DA59 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA5A - $DA69 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA6A - $DA79 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA7A - $DA89 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA8A - $DA99 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DA9A - $DAA9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DAAA - $DAB9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DABA - $DAC9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DACA - $DAD9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DADA - $DAE9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DAEA - $DAF9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DAFA - $DB09 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB0A - $DB19 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB1A - $DB29 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB2A - $DB39 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB3A - $DB49 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB4A - $DB59 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB5A - $DB69 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB6A - $DB79 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB7A - $DB89 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB8A - $DB99 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DB9A - $DBA9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DBAA - $DBB9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DBBA - $DBC9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DBCA - $DBD9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DBDA - $DBE9 .byte $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; $DBEA - $DBF9 .byte $FF, $FF, $FF, $FF, $FF, $FF ; $DBFA - $DBFF ;; END HUGE UNUSED SPACE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; BlockChange_Do ; ; Performs a Block Change command, if one is needed ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; BlockChange_Do: LDA Level_7Vertical BEQ PRG029_DC36 ; If level is not vertical, jump to PRG029_DC36 ; Vertical level only... ; Fix Block Change Y coordinates for vertical world LDA Level_BlockChgYLo LDY Level_BlockChgYHi JSR LevelJct_GetVScreenH STA Level_BlockChgYLo STY Level_BlockChgYHi ; Get tile here LDA Tile_Mem_AddrVL,Y STA <Map_Tile_AddrL LDA Tile_Mem_AddrVH,Y STA <Map_Tile_AddrH ; Temp_Var6 = block change screen Y aligned to grid LDA Level_BlockChgYLo AND #$f0 STA <Temp_Var6 ; Build row/column offset value -> Temp_Var5 LDA Level_BlockChgXLo LSR A LSR A LSR A LSR A ORA <Temp_Var6 STA <Temp_Var5 ; Temp_Var7 = 0 LDA #$00 STA <Temp_Var7 BEQ PRG029_DC7C ; Jump (technically always) to PRG029_DC7C PRG029_DC36: ; Non-vertical level only... LDA Level_BlockChgXHi ASL A ; Multiply by 2 (2 byte index per Tile_Mem_Addr) TAX ; -> 'X' ; Set address in tile memory to Map_Tile_AddrL/H LDA Tile_Mem_Addr,X STA <Map_Tile_AddrL LDA Tile_Mem_Addr+1,X STA <Map_Tile_AddrH ; Temp_Var7 = 0 LDA #$00 STA <Temp_Var7 LDA Level_BlockChgYHi BEQ PRG029_DC50 ; If block change is not on the lower part of the screen, jump to PRG029_DC50 INC <Map_Tile_AddrH ; Otherwise, jump to lower screen address PRG029_DC50: ; Construct a row/column offset -> Temp_Var5 LDA Level_BlockChgYLo AND #$f0 STA <Temp_Var6 LDA Level_BlockChgXLo LSR A LSR A LSR A LSR A ORA <Temp_Var6 STA <Temp_Var5 LDA Level_BlockChgYHi BNE PRG029_DC70 ; If Level_BlockChgYHi <> 0 (block change is down low on the lower screen space), jump to PRG029_DC70 ; Block change is on upper screen space... LDA Level_BlockChgYLo AND #$f0 ; Align to grid CMP #$f0 BNE PRG029_DC7C ; If not TOO low, jump to PRG029_DC7C PRG029_DC70: ; Block is on upper part of screen but at the 240 line ; This logic calculates an alternate address because the code that actually ; applies the tile change needs to have a 32 byte jump to the next line, ; and use $F0 would overflow back to $10 and misalign the tile change!! ; Temp_Var6 = 0-ish LDA Level_BlockChgYLo ADD #$10 STA <Temp_Var6 ; Temp_Var7 = 1 (carry) LDA #$01 STA <Temp_Var7 PRG029_DC7C: LDA Level_ChgTileEvent BNE PRG029_DC82 ; If Level_ChgTileEvent <> 0, jump to PRG029_DC82 ; Otherwise, do nothing... seems like they should've checked for ; this BEFORE bothering with all those calculations! :) RTS ; Return PRG029_DC82: JSR DynJump ; THESE MUST FOLLOW DynJump FOR THE DYNAMIC JUMP TO WORK!! .word TileChng_DoNothing ; $00 - NOT USED (Level_ChgTileEvent = 0 not valid) .word TileChng_OneTile ; $01 - CHNGTILE_DELETECOIN .word TileChng_OneTile ; $02 - CHNGTILE_DELETETOBG .word TileChng_OneTile ; $03 - CHNGTILE_TOGNOTEBLOCK .word TileChng_OneTile ; $04 - CHNGTILE_TOBOUNCEWOOD .word TileChng_OneTile ; $05 - CHNGTILE_TONOTEBLOCK .word TileChng_OneTile ; $06 - CHNGTILE_COINHEAVEN .word TileChng_OneTile ; $07 - CHNGTILE_TOBRICK .word TileChng_OneTile ; $08 - CHNGTILE_TOMETALPLATE .word TileChng_OneTile ; $09 - CHNGTILE_PSWITCHSTOMP .word TileChng_OneTile ; $0A (Change to Fortress light cable??) .word TileChng_OneTile ; $0B - CHNGTILE_TOBRICKCOIN .word TileChng_OneTile ; $0C - CHNGTILE_DELETETOBGALT (not sure about this one) .word TileChng_OneTile ; $0D - not different from $02?? .word TileChng_OneTile ; $0E (Spikes??) .word TileChng_OneTile ; $0F - CHNGTILE_DELETEDONUT .word TileChng_OneTile ; $10 - CHNGTILE_FROZENMUNCHER .word TileChng_OneTile ; $11 - CHNGTILE_FROZENCOIN .word TileChng_OneTile ; $12 - CHNGTILE_PSWITCHAPPEAR .word TileChng_DoorAppear ; $13 - CHNGTILE_DOORAPPEAR .word TileChng_ToadBoxOpen ; $14 - CHNGTILE_TOADBOXOPEN .word ChngTile_32x32 ; $15 - CHNGTILE_4WAYCANNON .word ChngTile_32x32 ; $16 - GiantBlock_BrickBust .word ChngTile_32x32 ; $17 - GiantBlock_BlockHit .word ChngTile_32x32 ; $18 - GiantBlock_BrickRestore ; Tile to "change to"; just for updating the level grid ; NOTES: ; TILE2_HANGGLOBE_CABLE -- only tile that made visual sense as a standalone ?? ; TILE9_PIPEWORKS_CRACK -- not sure about this one ; TILE2_SPIKEUP -- only tile that made visual sense as a standalone ?? OneTile_ChangeToTile: .byte TILEA_COINREMOVED, TILE1_SKY, TILEA_GNOTE, TILEA_WOODBLOCKBOUNCE .byte TILEA_NOTE, TILEA_HNOTE, TILEA_BRICK, TILEA_BLOCKEMPTY .byte TILEA_PSWITCH_PRESSED, TILE2_HANGGLOBE_CABLE, TILEA_BRICKCOIN, TILE9_PIPEWORKS_CRACK .byte TILE1_SKY, TILE2_SPIKEUP, TILE2_DONUTLIFT, TILE4_MUNCHER, TILEA_COIN, TILEA_PSWITCH ; Defines each of the four 8x8 patterns that make up the tile ; Too bad Nintendo couldn't keep things like this in one spot :) OneTile_ChangeToPatterns: .byte $05, $07, $06, $08 ; $01 - CHNGTILE_DELETECOIN .byte $05, $07, $06, $08 ; $02 - CHNGTILE_DELETETOBG .byte $B8, $BA, $B9, $BB ; $03 - CHNGTILE_TOGNOTEBLOCK .byte $C0, $C2, $C1, $C3 ; $04 - CHNGTILE_TOBOUNCEWOOD .byte $B8, $BA, $B9, $BB ; $05 - CHNGTILE_TONOTEBLOCK .byte $B8, $BA, $B9, $BB ; $06 - CHNGTILE_COINHEAVEN .byte $B4, $B6, $B5, $B7 ; $07 - CHNGTILE_TOBRICK .byte $D8, $DA, $D9, $DB ; $08 - CHNGTILE_TOMETALPLATE .byte $FF, $FF, $E6, $E7 ; $09 - CHNGTILE_PSWITCHSTOMP .byte $60, $61, $6D, $6F ; $0A .byte $B4, $B6, $B5, $B7 ; $0B - CHNGTILE_TOBRICKCOIN .byte $52, $50, $62, $60 ; $0C - CHNGTILE_DELETETOBGALT .byte $05, $07, $06, $08 ; $0D .byte $18, $1A, $19, $1B ; $0E .byte $5C, $5E, $5D, $5F ; $0F - CHNGTILE_DELETEDONUT .byte $92, $CA, $93, $CB ; $10 - CHNGTILE_FROZENMUNCHER .byte $DC, $DE, $DD, $DF ; $11 - CHNGTILE_FROZENCOIN .byte $E0, $E2, $E1, $E3 ; $12 - CHNGTILE_PSWITCHAPPEAR TileChng_OneTile: LDX Level_ChgTileEvent DEX ; X = Level_ChgTileEvent - 1 (because zero is no-action) LDY <Temp_Var5 ; Y = Temp_Var5 (row/column offset value) ; Change the tile to the proper target tile LDA OneTile_ChangeToTile,X STA [Map_Tile_AddrL],Y ; X *= 4 (index into OneTile_ChangeToPatterns) TXA ASL A ASL A TAX LDY #$00 ; Y = 0 PRG029_DD22: LDA OneTile_ChangeToPatterns,X ; Get pattern STA TileChng_Pats,Y ; Copy into TileChng_Pats INX ; X++ (next pattern) INY ; Y++ (count of patterns) CPY #$04 BNE PRG029_DD22 ; While Y < 4, loop! LDA <Temp_Var6 ; Get tile Y (aligned to grid, so bits 0-3 are zero) ASL A ; Bit 7 -> carry ADC #$00 ; Set as bit 0 ASL A ; Bit 7 -> carry ADC #$00 ; Set as bit 0 (result: Former bit 6-7 are now bit 0-1) PHA ; Save this value AND #%00001111 ; Only keep lower 4 bits (bits 2 and 3 are still zero) ORA #$20 ; Set high part of video address LDY <Temp_Var7 BEQ PRG029_DD41 ; If Temp_Var7 not set (set if tile was on the fringe between upper and lower screen space), jump to PRG029_DD41 ORA #$08 ; Set $28 high address PRG029_DD41: STA TileChng_VRAM_H ; Store the high byte of the tile change base address PLA ; Restore value from before AND #%11110000 ; Keep the upper 4 bits STA <Temp_Var2 ; -> Temp_Var2 LDA Level_BlockChgXLo LSR A LSR A LSR A ; A = Level_BlockChgXLo / 8 ORA <Temp_Var2 STA TileChng_VRAM_L ; Store the low byte of the tile change base address ; Level_ChgTileEvent = 0 (we handled it) LDA #$00 STA Level_ChgTileEvent TileChng_DoNothing: RTS ; Return TileChng_DoorBufCmds: ; First two bytes for both are to-be-determined VRAM addres .byte $00, $00, VU_VERT | VU_REPEAT | 4, $FC ; Left 4 patterns of door .byte $00, $00, VU_VERT | VU_REPEAT | 4, $FC ; Right 4 patterns of door .byte $00 ; Terminator TileChng_DoorBufCmds_End TileChng_DoorAppear: ; Level_ChgTileEvent = 0 (we're handling it) LDA #$00 STA Level_ChgTileEvent LDY <Temp_Var5 ; Y = Temp_Var5 (row/column offset value) ; Set upper tile of door LDA #TILEA_DOOR1 STA [Map_Tile_AddrL],Y ; +16 (next row of tiles) TYA ADD #16 TAY BCC PRG029_DD77 ; If no carry, jump to PRG029_DD77 INC <Map_Tile_AddrH ; Apply carry PRG029_DD77: ; Set lower tile of door LDA #TILEA_DOOR1 STA [Map_Tile_AddrL],Y LDY #$00 ; Y = 0 LDX Graphics_BufCnt ; X = Graphics_BufCnt PRG029_DD80: LDA TileChng_DoorBufCmds,Y ; Get next command byte STA Graphics_Buffer,X ; Store into graphics buffer INX ; X++ (one more byte in the graphics buffer) INY ; Y++ (next command byte) CPY #(TileChng_DoorBufCmds_End - TileChng_DoorBufCmds) BNE PRG029_DD80 ; While more to commit, loop! LDX Graphics_BufCnt ; X = Graphics_BufCnt LDA <Temp_Var6 ; Get tile Y (aligned to grid, so bits 0-3 are zero) ASL A ; Bit 7 -> carry ADC #$00 ; Set as bit 0 ASL A ; Bit 7 -> carry ADC #$00 ; Set as bit 0 (result: Former bit 6-7 are now bit 0-1) PHA ; Save this value AND #%00001111 ; Only keep lower 4 bits (bits 2 and 3 are still zero) ORA #$20 ; Set high part of video address LDY <Temp_Var7 BEQ PRG029_DDA2 ; If Temp_Var7 not set (set if tile was on the fringe between upper and lower screen space), jump to PRG029_DDA2 ORA #$08 ; Set $28 high address PRG029_DDA2: ; Commit high addresses to graphics buffer STA Graphics_Buffer,X STA Graphics_Buffer+$04,X PLA ; Restore value from before AND #%11110000 ; Keep the upper 4 bits STA <Temp_Var2 ; -> Temp_Var2 LDA Level_BlockChgXLo LSR A LSR A LSR A ; A = Level_BlockChgXLo / 8 ORA <Temp_Var2 ; Set low address for left column of patterns of door STA Graphics_Buffer+$01,X ADD #$01 ; Next column of door ; Set low address for right column of patterns of door STA Graphics_Buffer+$05,X ; Add array size -1 to graphics buffer count LDA Graphics_BufCnt ADD #(TileChng_DoorBufCmds_End - TileChng_DoorBufCmds - 1) STA Graphics_BufCnt RTS ; Return TileChng_ToadBoxBufCmds: ; First two bytes for both are to-be-determined VRAM addres .byte $00, $00, $04, $50, $51, $52, $53 ; Chest top patterns .byte $00, $00, $04, $54, $55, $56, $57 ; Chest bottom patterns .byte $00 ; Terminator TileChng_ToadBoxBufCmds_End TileChng_ToadBoxOpen: ; Level_ChgTileEvent = 0 (we're handling it) LDA #$00 STA Level_ChgTileEvent LDY <Temp_Var5 ; Y = Temp_Var5 (row/column offset value) ; Chest open tile upper left LDA #TILE7_CHEST_OPEN_UL STA [Map_Tile_AddrL],Y INY ; Y++ ; Chest open tile upper right LDA #TILE7_CHEST_OPEN_UR STA [Map_Tile_AddrL],Y LDY #$00 ; Y = 0 LDX Graphics_BufCnt ; X = Graphics_BufCnt PRG029_DDEC: LDA TileChng_ToadBoxBufCmds,Y ; Get next command byte STA Graphics_Buffer,X ; Store into graphics buffer INX ; X++ (one more byte in the graphics buffer) INY ; Y++ (next command byte) CPY #(TileChng_ToadBoxBufCmds_End - TileChng_ToadBoxBufCmds) BNE PRG029_DDEC ; While more to commit, loop! LDX Graphics_BufCnt ; X = Graphics_BufCnt LDA <Temp_Var6 ; Get tile Y (aligned to grid, so bits 0-3 are zero) ASL A ; Bit 7 -> carry ADC #$00 ; Set as bit 0 ASL A ; Bit 7 -> carry ADC #$00 ; Set as bit 0 (result: Former bit 6-7 are now bit 0-1) PHA ; Save this value AND #%00001111 ; Only keep lower 4 bits (bits 2 and 3 are still zero) ORA #$20 ; Set high part of video address LDY <Temp_Var7 BEQ PRG029_DE0E ; If Temp_Var7 not set (set if tile was on the fringe between upper and lower screen space), jump to PRG029_DE0E ORA #$08 ; Set $28 high address PRG029_DE0E: ; Commit high addresses to graphics buffer STA Graphics_Buffer,X STA Graphics_Buffer+$07,X PLA ; Restore value from before AND #%11110000 ; Keep the upper 4 bits STA <Temp_Var2 ; -> Temp_Var2 LDA Level_BlockChgXLo LSR A LSR A LSR A ; A = Level_BlockChgXLo / 8 ORA <Temp_Var2 ; Set low address for first row of open chest patterns STA Graphics_Buffer+$01,X ADD #32 ; +32 to next row ; Set low address for second row of open chest patterns STA Graphics_Buffer+$08,X ; Add array size -1 to graphics buffer count LDA Graphics_BufCnt ADD #(TileChng_ToadBoxBufCmds_End - TileChng_ToadBoxBufCmds - 1) STA Graphics_BufCnt RTS ; Return ; Change Big Buffer Command offset CBIG_BCOff .func \1 - Chng4Way_90Degrees ; Get initial offset to proper set of commands to be used CBig_Offsets: .byte CBIG_BCOff(Chng4Way_90Degrees) ; 4-way cannon at 90 degrees .byte CBIG_BCOff(Chng4Way_45Degrees) ; 4-way cannon at 45 degrees .byte CBIG_BCOff(CBig_GiantBlock_BrickBust) ; GiantBlock_BrickBust .byte CBIG_BCOff(CBig_GiantBlock_BlockHit) ; GiantBlock_BlockHit .byte CBIG_BCOff(CBig_GiantBlock_BrickRestore) ; GiantBlock_BrickRestore Chng4Way_90Degrees: .byte $00, $00, $04, $FF, $A6, $A7, $FF .byte $00, $00, $04, $8D, $B2, $BC, $8D .byte $00, $00, $04, $9D, $B3, $BD, $9D .byte $00, $00, $04, $FF, $AE, $AF, $FF .byte $00 Chng4Way_45Degrees: .byte $00, $00, $04, $09, $28, $36, $49 .byte $00, $00, $04, $EC, $ED, $EE, $EF .byte $00, $00, $04, $E8, $E9, $EA, $EB .byte $00, $00, $04, $F8, $F9, $FA, $FB .byte $00 CBig_GiantBlock_BrickBust: .byte $00, $00, $04, $05, $07, $05, $07 .byte $00, $00, $04, $06, $08, $06, $08 .byte $00, $00, $04, $05, $07, $05, $07 .byte $00, $00, $04, $06, $08, $06, $08 .byte $00 CBig_GiantBlock_BlockHit: .byte $00, $00, $04, $04, $0D, $0D, $0E .byte $00, $00, $04, $24, $FE, $FE, $27 .byte $00, $00, $04, $24, $FE, $FE, $27 .byte $00, $00, $04, $34, $48, $48, $37 .byte $00 CBig_GiantBlock_BrickRestore: .byte $00, $00, $04, $00, $01, $02, $03 .byte $00, $00, $04, $10, $11, $12, $10 .byte $00, $00, $04, $20, $21, $22, $23 .byte $00, $00, $04, $30, $31, $32, $33 .byte $00 CBIG_BCSize = Chng4Way_45Degrees - Chng4Way_90Degrees PRG029_DECA: .byte $96, $92 CBig_ChngTiles: .byte TILE10_4WAYCANNON_90_UL, TILE10_4WAYCANNON_90_UR, TILE10_4WAYCANNON_90_LL, TILE10_4WAYCANNON_90_LR ; 4-way cannon 90 degrees .byte TILE10_4WAYCANNON_45_UL, TILE10_4WAYCANNON_45_UR, TILE10_4WAYCANNON_45_LL, TILE10_4WAYCANNON_45_LR ; 4-way cannon 45 degrees .byte TILE11_SKY, TILE11_SKY, TILE11_SKY, TILE11_SKY ; Giant World brick bust tile clear .byte TILE11_METAL_UL, TILE11_METAL_UR, TILE11_METAL_LL, TILE11_METAL_LR ; Giant World [?] block hit .byte TILE11_BRICK_UL, TILE11_BRICK_UR, TILE11_BRICK_LL, TILE11_BRICK_LR ; Giant World brick bump ChngTile_32x32: LDX #$00 ; X = 0 LDA Level_ChgTileEvent CMP #CHNGTILE_4WAYCANNON BNE PRG029_DEF3 ; If this is not the 4-way cannon change, jump to PRG029_DEF3 ; 4-way cannon change only... LDY <Temp_Var5 ; Y = Temp_Var5 (row/column offset value) LDA [Map_Tile_AddrL],Y ; Get tile currently here CMP #TILE10_4WAYCANNON_45_UL BEQ PRG029_DEF9 ; If cannon is at 45 degree position, jump to PRG029_DEF9 BNE PRG029_DEF8 ; Otherwise, jump to PRG029_DEF8 PRG029_DEF3: ; Not the 4-way cannon... SUB #CHNGTILE_GIANTBRICKBUST ; Make relative TAX ; -> 'X' INX ; X++ PRG029_DEF8: INX ; X++ (X = 1 for 4-way cannon, 2+ for the others) PRG029_DEF9: LDY CBig_Offsets,X ; Y = initial command offset STX <Temp_Var11 ; Temp_Var11 = X (index into CBig_Offsets) LDX Graphics_BufCnt ; X = graphics buffer count ; Temp_Var1 = total number of bytes we're going to copy (CBIG_BCSize) LDA #CBIG_BCSize STA <Temp_Var1 PRG029_DF05: LDA Chng4Way_90Degrees,Y ; Get next command byte STA Graphics_Buffer,X ; Store into graphics buffer INX ; X++ (one more byte in the graphics buffer) INY ; Y++ (next command byte) DEC <Temp_Var1 ; Temp_Var1-- BNE PRG029_DF05 ; While Temp_Var1 > 0, loop! ; Temp_Var11 (index into CBig_Offsets) multiplied by 4 LDA <Temp_Var11 ASL A ASL A STA <Temp_Var11 ; Temp_Var3 = 0 LDA #$00 STA <Temp_Var3 PRG029_DF1B: LDA <Temp_Var5 ; A = Temp_Var5 (row/column offset value) AND #$f0 ; Just keep the row part LDY <Temp_Var7 ; Y = Temp_Var7 BEQ PRG029_DF26 ; If Temp_Var7 not set (set if tile was on the fringe between upper and lower screen space), jump to PRG029_DF26 ADD #$10 ; Next row PRG029_DF26: STA <Temp_Var6 ; -> Temp_Var6 LDA <Temp_Var5 ; A = Temp_Var5 (row/column offset value) AND #$0f ; Just keep the column part ASL A ; Multiply by 2 STA <Temp_Var8 ; -> Temp_Var8 LDA <Temp_Var6 ; Get tile Y (aligned to grid, so bits 0-3 are zero) ASL A ; Bit 7 -> carry ADC #$00 ; Set as bit 0 ASL A ; Bit 7 -> carry ADC #$00 ; Set as bit 0 (result: Former bit 6-7 are now bit 0-1) PHA ; Save this value AND #%00000011 ; Only keep lower 2 bits ORA #$20 ; Set high part of video address LDY <Temp_Var7 ; Y = Temp_Var7 BEQ PRG029_DF42 ; If Temp_Var7 not set (set if tile was on the fringe between upper and lower screen space), jump to PRG029_DF42 ORA #$08 ; Set $28 high address PRG029_DF42: STA <Temp_Var9 ; -> Temp_Var9 LDX #$00 ; X = 0 LDA <Temp_Var3 BEQ PRG029_DF4C ; If Temp_Var3 = 0 (loop first pass), jump to PRG029_DF4C LDX #$0e ; Otherwise, X = $0E PRG029_DF4C: ; X += current graphics buffer count TXA ADD Graphics_BufCnt TAX ; Commit high addresses to graphics buffer LDA <Temp_Var9 STA Graphics_Buffer,X STA Graphics_Buffer+$07,X PLA ; Restore value from before AND #%11110000 ; Keep the upper 4 bits ORA <Temp_Var8 ; The column value STA <Temp_Var4 ; -> Temp_Var4 ; Set low address in graphics buffer STA Graphics_Buffer+$01,X ADD #32 ; +32 is next row ; Set low address in graphics buffer STA Graphics_Buffer+$08,X LDY <Temp_Var5 ; Y = Temp_Var5 LDX <Temp_Var11 ; X = Temp_Var11 LDA CBig_ChngTiles,X ; Get tile STA [Map_Tile_AddrL],Y ; Set tile INY ; Next column LDA CBig_ChngTiles+1,X ; Get tile STA [Map_Tile_AddrL],Y ; Set tile ; Temp_Var5 += 16 (next tile row) LDA <Temp_Var5 ADD #16 STA <Temp_Var5 ; Apply carry if needed LDA <Map_Tile_AddrH ADC #$00 STA <Map_Tile_AddrH ; Temp_Var11 += 2 INC <Temp_Var11 INC <Temp_Var11 INC <Temp_Var3 ; Temp_Var3++ LDA <Temp_Var3 CMP #$02 BNE PRG029_DF1B ; While Temp_Var3 < 2, loop! ; Add array size -1 to graphics buffer count LDA Graphics_BufCnt ADD #(CBIG_BCSize - 1) STA Graphics_BufCnt ; Level_ChgTileEvent = 0 (redundant!) LDA #$00 STA Level_ChgTileEvent INC Level_SkipStatusBarUpd ; Set Level_SkipStatusBarUpd (skip status bar for a frame, priority update!) RTS ; Return ; Palette data for the "glowing coin" effect PRG029_DFA4: .byte $3C, $0F, $36, $27 ; 0 .byte $3C, $0F, $36, $17 ; 4 .byte $3C, $0F, $36, $07 ; 8 .byte $3C, $0F, $36, $0F ; 12 ; FIXME: Anybody want to claim this?? ; Appears to be coin palette cycling routine ; $DFB4 LDA <Counter_1 AND #$07 BNE PRG029_DFEB ; 1:8 ticks continue, otherwise jump to PRG029_DFEB (RTS) LDA <Counter_1 AND #$18 LSR A TAX ; X = 0, 4, 8, 12 ; Copies current coin palette into buffer LDY Graphics_BufCnt LDA #$3f STA Graphics_Buffer,Y LDA #$04 STA Graphics_Buffer+$01,Y STA Graphics_Buffer+$02,Y PRG029_DFD0: LDA PRG029_DFA4,X STA Graphics_Buffer+$03,Y INY ; Y++ INX ; X++ TXA AND #$03 ; X = 0 to 3 BNE PRG029_DFD0 ; While X <> 0, loop! ; Terminator LDA #$00 STA Graphics_Buffer+$03,Y ; Graphics_BufCnt += 7 LDA Graphics_BufCnt ADD #$07 STA Graphics_BufCnt PRG029_DFEB: RTS ; Return ; Rest of ROM bank was empty
; A036586: Ternary Thue-Morse sequence: closed under a->abc, b->ac, c->b. ; 2,0,1,2,1,0,2,0,1,0,2,1,2,0,1,2,1,0,2,1,2,0,1,0,2,0,1,2,1,0,2,0,1,0,2,1,2,0,1,0,2,0,1,2,1,0,2,1,2,0,1,2,1,0,2,0,1,0,2,1,2,0,1,2,1,0,2,1,2,0,1,0,2,0,1,2,1,0,2,1,2,0,1,2,1,0,2,0,1,0,2,1,2,0,1,0,2,0,1 seq $0,36579 ; Ternary Thue-Morse sequence: closed under a->abc, b->ac, c->b. add $0,10 mod $0,3
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <wallet/fees.h> #include <policy/policy.h> #include <txmempool.h> #include <util/system.h> #include <validation.h> #include <wallet/coincontrol.h> #include <wallet/wallet.h> CAmount GetRequiredFee(const CWallet& wallet, unsigned int nTxBytes) { return GetRequiredFeeRate(wallet).GetFee(nTxBytes); } CAmount GetMinimumFee(const CAmount &txValue, unsigned int nTxBytes, const CWallet& wallet) { CAmount feeNeeded = (txValue / nTxFeeValueMultiplier) * std::max(nTxBytes / nTxFeeSizeMultiplier, 1u); // back to a hard-coded fee if (feeNeeded == 0) feeNeeded = wallet.m_min_fee.GetFee(nTxBytes); // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee auto minRelayTxFeeAmount = minRelayTxFee.GetFee(nTxBytes); if (feeNeeded < minRelayTxFeeAmount) feeNeeded = minRelayTxFeeAmount; // But always obey the maximum if (feeNeeded > maxTxFee) feeNeeded = maxTxFee; return feeNeeded; } CAmount GetMinimumFee(const CWallet& wallet, unsigned int nTxBytes, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation* feeCalc) { CAmount fee_needed = GetMinimumFeeRate(wallet, coin_control, pool, estimator, feeCalc).GetFee(nTxBytes); // Always obey the maximum if (fee_needed > maxTxFee) { fee_needed = maxTxFee; if (feeCalc) feeCalc->reason = FeeReason::MAXTXFEE; } return fee_needed; } CFeeRate GetRequiredFeeRate(const CWallet& wallet) { return std::max(wallet.m_min_fee, ::minRelayTxFee); } CFeeRate GetMinimumFeeRate(const CWallet& wallet, const CCoinControl& coin_control, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, FeeCalculation* feeCalc) { /* User control of how to calculate fee uses the following parameter precedence: 1. coin_control.m_feerate 2. coin_control.m_confirm_target 3. m_pay_tx_fee (user-set member variable of wallet) 4. m_confirm_target (user-set member variable of wallet) The first parameter that is set is used. */ CFeeRate feerate_needed; if (coin_control.m_feerate) { // 1. feerate_needed = *(coin_control.m_feerate); if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE; // Allow to override automatic min/max check over coin control instance if (coin_control.fOverrideFeeRate) return feerate_needed; } else if (!coin_control.m_confirm_target && wallet.m_pay_tx_fee != CFeeRate(0)) { // 3. TODO: remove magic value of 0 for wallet member m_pay_tx_fee feerate_needed = wallet.m_pay_tx_fee; if (feeCalc) feeCalc->reason = FeeReason::PAYTXFEE; } else { // 2. or 4. // We will use smart fee estimation unsigned int target = coin_control.m_confirm_target ? *coin_control.m_confirm_target : wallet.m_confirm_target; // By default estimates are economical iff we are signaling opt-in-RBF bool conservative_estimate = !coin_control.m_signal_bip125_rbf.get_value_or(wallet.m_signal_rbf); // Allow to override the default fee estimate mode over the CoinControl instance if (coin_control.m_fee_mode == FeeEstimateMode::CONSERVATIVE) conservative_estimate = true; else if (coin_control.m_fee_mode == FeeEstimateMode::ECONOMICAL) conservative_estimate = false; feerate_needed = estimator.estimateSmartFee(target, feeCalc, conservative_estimate); if (feerate_needed == CFeeRate(0)) { // if we don't have enough data for estimateSmartFee, then use fallback fee feerate_needed = wallet.m_fallback_fee; if (feeCalc) feeCalc->reason = FeeReason::FALLBACK; // directly return if fallback fee is disabled (feerate 0 == disabled) if (wallet.m_fallback_fee == CFeeRate(0)) return feerate_needed; } // Obey mempool min fee when using smart fee estimation CFeeRate min_mempool_feerate = pool.GetMinFee(gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000); if (feerate_needed < min_mempool_feerate) { feerate_needed = min_mempool_feerate; if (feeCalc) feeCalc->reason = FeeReason::MEMPOOL_MIN; } } // prevent user from paying a fee below the required fee rate CFeeRate required_feerate = GetRequiredFeeRate(wallet); if (required_feerate > feerate_needed) { feerate_needed = required_feerate; if (feeCalc) feeCalc->reason = FeeReason::REQUIRED; } return feerate_needed; } CFeeRate GetDiscardRate(const CWallet& wallet, const CBlockPolicyEstimator& estimator) { unsigned int highest_target = estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE); CFeeRate discard_rate = estimator.estimateSmartFee(highest_target, nullptr /* FeeCalculation */, false /* conservative */); // Don't let discard_rate be greater than longest possible fee estimate if we get a valid fee estimate discard_rate = (discard_rate == CFeeRate(0)) ? wallet.m_discard_rate : std::min(discard_rate, wallet.m_discard_rate); // Discard rate must be at least dustRelayFee discard_rate = std::max(discard_rate, ::dustRelayFee); return discard_rate; }
;generated automatically via makeasms.bat include gfxlib.i CGROUP group code code segment dword 'CODE' assume cs:CGROUP,ds:CGROUP GFXLIB_JUMP pj_zoomblit gfxl_zoomblit code ends end
; ; S-OS specific routines ; by Stefano Bodrato, 2013 ; ;; void lptoff() ; ; $Id: lptoff.asm,v 1.3 2015/01/19 01:33:07 pauloscustodio Exp $ ; PUBLIC lptoff lptoff: jp $1fd6
db 0 ; species ID placeholder db 69, 69, 69, 69, 69, 69 ; hp atk def spd sat sdf db NORMAL, NORMAL ; type db 45 ; catch rate db 64 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F0 ; gender ratio db 20 ; step cycles to hatch INCBIN "gfx/pokemon/drakarve/front.dimensions" db GROWTH_MEDIUM_SLOW ; growth rate dn EGG_MONSTER, EGG_PLANT ; egg groups db 70 ; happiness ; tm/hm learnset tmhm ; end
#include <ctime> #include "consoleui.h" using namespace std; //Default Constructor ConsoleUI::ConsoleUI() { } // The Function used in the main() function. // Displays the main menu, and takes you to the // respective function depending on the choice. void ConsoleUI::run() { bool run = true; if (serve.list().size() == 0) { cout << "\nCould not load from file or file was empty\n" << endl; } while (run) { cout << " ================================" << endl; cout << " Press 1 to list the scientists" << endl; cout << " Press 2 to sort the scientists" << endl; cout << " Press 3 to add a scientist" << endl; cout << " Press 4 to search the list" << endl; cout << " Press 5 to remove a scientist" << endl; cout << " Press 6 to save to a custom file" << endl; cout << " Press 7 to exit" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; onlyTakeOneInput(); // Takes only one letter and flushes the rest. int choice = input - '0'; switch (choice) { case 1: { listData(); break; } case 2: { sortData(); break; } case 3: { addData(); break; } case 4: { searchData(); break; } case 5: { deleteData(); break; } case 6: saveToCustomFile(); break; case 7: { run = false; break; } default: { cout << "Error! Invalid input" << endl; } } } } // lists all the data from the vector. //uses the printLine() function, which gives us a nice header. void ConsoleUI::listData() { cout << endl; printLine(); for(size_t i = 0; i < serve.list().size(); i++) { cout << serve.list()[i]; } cout << "_____________________________________________________" << endl; } //Here we get to pick the parameter by which we want to sort our data. void ConsoleUI::sortData() { char input = '0'; int choice = 0; bool error = false; do { cout << "How would you like to sort the list?" << endl; cout << " ================================" << endl; cout << " Press 1 to sort by name" << endl; cout << " Press 2 to sort by gender" << endl; cout << " Press 3 to sort by birth year " << endl; cout << " Press 4 to sort by death year" << endl; cout << " Press 5 to Cancel" << endl; cout << " ================================" << endl; cin >> input; onlyTakeOneInput(); choice = input - '0'; input = '1'; switch (choice) { case 1: { sortByName(input, error); break; } case 2: { sortByGender(input, error); break; } case 3: { sortByBirthYear(input, error); break; } case 4: { sortByDeathYear(input, error); break; } case 5: { error = false; break; } default: { cout << "Error! Invalid input!" << endl; error = true; } } } while (error); if (choice != 5) //if you press cancel, you don't want to see the list, do you? { listData(); } } //We sort by name, and want to know whether you want to sort reversed or not. void ConsoleUI::sortByName(char input, bool& error) { int order = 0; do { cout << "Regular or Reversed sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 for regular sorting" << endl; cout << "Press 2 for reversed sorting" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; onlyTakeOneInput(); if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } } while (input != '1' && input != '2' && input != '3'); order = input - '0'; if (order == 1 || order == 2) { serve.sortByName(order); error = false; } else { error = true; } } //Do you want to see all the ladies first? Or maybe the men? //Then this function is for you!! void ConsoleUI::sortByGender(char input, bool& error) { int order = 0; do { cout << "Sort by Males or Females?" << endl; cout << " ================================" << endl; cout << "Press 1 to sort by females first" << endl; cout << "Press 2 to sort by males first" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; onlyTakeOneInput(); if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } } while (input != '1' && input != '2' && input != '3'); order = input - '0'; if (order == 1 || order == 2) { serve.sortByGender(order); error = false; } else { error = true; } } //We sort by birthyear, and want to know whether we want to sort reversed or not. void ConsoleUI::sortByBirthYear(char input, bool& error) { int order = 0; do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Ascending or Descending sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 to sort by ascending order" << endl; cout << "Press 2 to sort by descending order" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; onlyTakeOneInput(); } while (input != '1' && input != '2' && input != '3'); order = input - '0'; if (order == 1 || order == 2) { serve.sortByBirthYear(order); error = false; } else { error = true; } } //We sort by death year, and want to know whether we want to sort reversed or not. //Alive people will be listed last (or first for reversed). void ConsoleUI::sortByDeathYear(char input, bool& error) { int order = 0; do { if (input != '1' && input != '2' && input != '3') { cout << "Error! Invalid input" << endl; } cout << "Ascending or Descending sorting?" << endl; cout << " ================================" << endl; cout << "Press 1 to sort by ascending order" << endl; cout << "Press 2 to sort by descending order" << endl; cout << "Press 3 to cancel" << endl; cout << " ================================" << endl; cin >> input; onlyTakeOneInput(); } while (input != '1' && input != '2' && input != '3'); order = input - '0'; if (order == 1 || order == 2) { serve.sortByDeathYear(order); error = false; } else { error = true; } } // Asks you to enter whether you want to add data manually or from a file. void ConsoleUI::addData() { bool error = false; do { cout << " ================================" << endl; cout << " Press 1 to add manually" << endl; cout << " Press 2 to add from file" << endl; cout << " Press 3 to cancel" << endl; cout << " ================================" << endl; char input = '0'; cin >> input; onlyTakeOneInput(); int choice = input - '0'; switch (choice) { case 1: { addPersonManually(); error = false; break; } case 2: { addPeopleFromFile(); error = false; break; } case 3: { error = false; break; } default: { cout << "Error! Invalid input" << endl; error = true; break; } } } while (error); } //We add a person through the console. //If user does not enter a string with names he gets an error message. //The first letter becomes uppercase. //there are error checks for birth Year and death Year. //If no invalid information is entered, the person is added to the file. void ConsoleUI::addPersonManually() { string name, year; char gender; int birthYear; int deathYear; cout << "Enter name: "; cin >> ws; getline(cin,name); while(!validName(name)) { cout << "Wrong input for name!" << endl; cout << "Enter name: "; cin >> ws; getline(cin,name); } if(!isupper(name[0])) { name[0] = toupper(name[0]); } cout << "Enter gender (M/F): "; cin >> gender; onlyTakeOneInput(); while(!genderCheck(gender)) { cout << "Wrong input for gender!" << endl; cout << "Enter gender (M/F): "; cin >> gender; onlyTakeOneInput(); } while(!validYear(year, birthYear) || birthYear == 0) { cout << "Enter birth year: "; cin >> year; onlyTakeOneInput(); if (!validYear(year, birthYear) || birthYear == 0) { cout << "Invalid input!\n"; } } year = " "; while(!validYear(year, deathYear)) { cout << "Enter death year (0 for living person): "; cin >> year; onlyTakeOneInput(); if(!validYear(year, deathYear)) { cout << "Invalid input!\n"; } } if(!birthChecks(birthYear, deathYear)) { check(); // Checks if you want to try to input again. } else { Persons newPerson(name, gender, birthYear, deathYear); int a = 0; for (unsigned int i = 0; i < serve.list().size(); i++) { if (newPerson == serve.list()[i]) { cout << "Scientist already on list!\n"; a++; break; } } if (a == 0) { serve.add(newPerson); cout << "Scientist added\n"; } } } // Asks user to enter path to file. This WILL overwrite the default file. void ConsoleUI::addPeopleFromFile() { string fileName = ""; bool fileOpen = false; do { cout << "Enter the full path of the file, or the name of the file, if the file is in the same directory: " << endl; cin >> fileName; if(serve.addFromFile(fileName)) { cout << "Success!" << endl; fileOpen = false; } else { cout << "Error! Failed to open file" << endl; char continuel; bool cont = true; while (cont) { cout << "Do you want to try again? (Y for yes and N for no) " ; cin >> continuel; if(continuel == 'Y' || continuel == 'y') { fileOpen = true; cont = false; } else if (continuel == 'N' || continuel == 'n') { fileOpen = false; cont = false; } else { cout << "Error! Invalid input" << endl; cont = true; } } } } while (fileOpen); } // Shows the table for search options. void ConsoleUI::searchData() { bool error = false; do { cout << "How would you like to search the data?" << endl; cout << " =====================================" << endl; cout << " Press 1 to search by name" << endl; cout << " Press 2 to search by gender" << endl; cout << " Press 3 to search by birth year" << endl; cout << " Press 4 to search by birth year range" << endl; cout << " Press 5 to cancel" << endl; cout << " ======================================" << endl; char input = '0'; cin >> input; onlyTakeOneInput(); int choice = input - '0'; switch(choice) { case 1: { searchByName(); error = false; break; } case 2: { searchByGender(); error = false; break; } case 3: { searchByBirthYear(); break; } case 4: { searchByYearRange(); break; } case 5: { error = false; break; } default: { cout << "Error! Invalid input" << endl; error = true; } } } while (error); } //searches the vector for the string which the user enters //and displays every result. void ConsoleUI::searchByName() { string n = " "; cout << "Enter name: "; cin >> ws; getline(cin, n); if(!isupper(n[0])) { n[0] = toupper(n[0]); } vector<int> vN = serve.searchByName(n); if (vN.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < vN.size(); i++) { cout << serve.list()[vN[i]]; } } } //We can search by gender. Yay. void ConsoleUI::searchByGender() { string gender = " "; cout << "Enter gender (M/F): "; cin >> gender; if (gender.length() == 1) { char g = gender.at(0); if (!genderCheck(g)) { cout << "Invalid gender input!" << endl; searchByGender(); } else { vector<int> vG = serve.searchByGender(g); if (vG.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < vG.size(); i++) { cout << serve.list()[vG[i]]; } } } } else { cout << "Invalid input" << endl; searchByGender(); } } //We search for people born in a certain year. void ConsoleUI::searchByBirthYear() { int y = 0; string s = " "; while (!validYear(s, y) || y == 0) { cout << "Enter year: "; cin >> s; if(!validYear(s, y) || y == 0) { cout << "Invalid input!\n"; } } vector<int> vY = serve.searchByYear(y); if (vY.size() == 0) { cout << "No results found\n"; } else { printLine(); for (unsigned int i = 0; i < vY.size(); i++) { cout << serve.list()[vY[i]]; } } } //We get a whole range of years, both included. //Note that this is only for birthyear. void ConsoleUI::searchByYearRange() { int f = 0, l = 0; string s = " "; while(!validYear(s, f)) { cout << "Enter first year in range: "; cin >> s; if (!validYear(s, f)) { cout << "Invalid input!\n"; } } s = " "; while(!validYear(s, l) || l < f) { cout << "Enter last year in range: "; cin >> s; if(!validYear(s, l) || l < f) { cout << "Invalid input!\n"; } } vector<int> vR = serve.searchByRange(f,l); if (vR.size() == 0) { cout << "No results found" << endl; } else { printLine(); for (unsigned int i = 0; i < vR.size(); i++) { cout << serve.list()[vR[i]]; } } } //This deletes a scientist. RIP. He/she probably didn't belong on the list anyway. void ConsoleUI::deleteData() { cout << "Enter name of scientist(s) you would like to delete: "; string n = " "; cin >> ws; getline(cin, n); if(!isupper(n[0])) { n[0] = toupper(n[0]); } vector<int> v = serve.searchByName(n); int s = v.size(); if (s > 0) { bool d = false; while (!d) { cout << endl; cout << "Are you sure you would like to delete the following scientist(s)? (y/n)\n" << endl; printLine(); for (int i = 0; i < s; i++) { cout << serve.list()[v[i]]; } char a = ' '; cin >> a; if (a == 'y' || a == 'Y') { for (int i = s-1; i >= 0; i--) { serve.deletePerson(v[i]); } cout << "Scientist(s) deleted\n"; d = true; } else if (a == 'n' || a == 'N') { cout << "Delete cancelled\n"; d = true; } else { cout << "Invalid input!\n"; } } } else { cout << "No match for " << n << endl; } } //Here, the user puts in a string, where it will be attempted to save the list to. void ConsoleUI::saveToCustomFile() { bool fileOpen = false; string fileName; do { cout << "WARNING: This will overwrite everything in the file selected!" << endl; cout << "If the File Doesn't exist, it will create a new file." << endl << endl; cout << "Enter the full path of the file, or the name of the file, if the file is in the same directory: " << endl; cin >> fileName; if(serve.saveToOtherFile(fileName)) { cout << "Success!" << endl; fileOpen = false; } else { cout << "Error! Failed to open file" << endl; char continuel; bool cont = true; while (cont) { cout << "Do you want to try again? (Y for yes and N for no) " ; cin >> continuel; if(continuel == 'Y' && continuel == 'y') { fileOpen = true; cont = false; } else if (continuel == 'N' && continuel == 'n') { fileOpen = false; cont = false; } else { cout << "Error! Invalid input" << endl; cont = true; } } } } while (fileOpen); } //a function which checks whether a certain entered string is a year. //And whether it's a valid year (AKA not in the future). bool ConsoleUI::validYear(const string& s, int& year) { string::const_iterator it = s.begin(); //Checks if the string 's' is a number while (it != s.end() && isdigit(*it)) { it++; } if (s.empty() || it != s.end()) { return false; } //Checks if 'year' is positive and lower than current year year = atoi(s.c_str()); time_t t = time(NULL); tm* TimePtr = localtime(&t); int currentYear = TimePtr->tm_year + 1900; return year >= 0 && year <= currentYear; } //we check whether a name entered by the user is valid // i.e. that it's not empty, no numbers. bool ConsoleUI::validName(const string& s) { //Checks if 's' is empty or contains characters other than letters and spaces string::const_iterator it = s.begin(); while (it != s.end() && (isalpha(*it) || *it == ' ')) { it++; } return !s.empty() && it == s.end(); } //Errorchecks for whether certain years entered by the user are valid. //sadly, it can't be a 300 year old dude. No vampires. bool ConsoleUI::birthChecks(int birthYear, int deathYear) { time_t t = time(NULL); tm* TimePtr = localtime(&t); int currentYear = TimePtr->tm_year + 1900; if(deathYear < birthYear && deathYear != 0) { cout << "The scientist cannot die before they are born!" << endl; return false; } if((deathYear - birthYear) > 122) { cout << "That is too old, the oldest woman was 122 years old!" << endl; return false; } if ((currentYear - birthYear) > 122 && deathYear == 0) { cout << "That is too old, the oldest woman was 122 years old!" << endl; return false; } return true; } //in the addData() function, errors will call upon this function. //it then loops back into said function if you want. bool ConsoleUI::check() { char continuel; cout << "Do you want to try again? (Y for yes and N for no) " ; cin >> continuel; if(continuel == 'Y' || continuel == 'y') { addData(); return true; } else { return false; } } //Errorcheck for whether the entered char is a recognised gender. bool ConsoleUI::genderCheck(char& gender) { if (gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') { if(gender == 'm') { gender = 'M'; } if(gender == 'f') { gender = 'F'; } return true; } else { return false; } } //If the user entered too many commands, the rest will just be flushed. Fun stuff. void ConsoleUI::onlyTakeOneInput() { cin.clear(); fflush(stdin); } //The header used when we list scientists. void ConsoleUI::printLine() { cout.width(26); cout << left << "Name"; cout << "\tGender\tBorn\tDied" << endl; cout << "_____________________________________________________" << endl; }
// Copyright (c) 2021 Johannes Delport // This code is licensed under MIT license (see LICENSE for details) #include "JoSIM/Errors.hpp" #include <iostream> using namespace JoSIM; void Errors::cli_errors(CLIErrors errorCode, string_o message) { std::string formattedMessage = "Command Line Interface\n"; switch (errorCode) { case CLIErrors::NO_OUTPUT: formattedMessage += "No output file name specified. Using default (output.csv).\n"; formattedMessage += "This file will be stored in the current working directory."; warning_message(formattedMessage); break; case CLIErrors::NO_INPUT: formattedMessage += "No input file was specified.\n"; formattedMessage += "Continuing by reading from standard input."; warning_message(formattedMessage); break; case CLIErrors::UNKNOWN_SWITCH: formattedMessage += "Unknown option '" + message.value_or("") + "' specified. Please refer to the help menu."; warning_message(formattedMessage); break; case CLIErrors::UNKNOWN_OUTPUT_TYPE: formattedMessage += "Unknown output type " + message.value_or("") + " specified. CSV will be used instead."; warning_message(formattedMessage); break; case CLIErrors::TOO_FEW_ARGUMENTS: formattedMessage += "Missing input arguments\n"; formattedMessage += "Usage: josim [options] input_netlist\n\n"; formattedMessage += "For further help use the -h switch"; throw std::runtime_error(formattedMessage); case CLIErrors::INVALID_ANALYSIS: formattedMessage += "Invalid analysis type specified. 0 - Voltage, 1 - Phase.\n"; formattedMessage += "Usage: josim [options] input_netlist\n\n"; formattedMessage += "For further help use the -h switch"; throw std::runtime_error(formattedMessage); case CLIErrors::INVALID_SOLVER: formattedMessage += "Invalid solver type specified. 0 - KLU, 1 - SLU.\n"; formattedMessage += "Usage: josim [options] input_netlist\n\n"; formattedMessage += "For further help use the -h switch"; throw std::runtime_error(formattedMessage); case CLIErrors::INVALID_INTEGRATION: formattedMessage += "Invalid integration method specified. 0 - Trapezoidal, 1 - Gear.\n"; formattedMessage += "Usage: josim [options] input_netlist\n\n"; formattedMessage += "For further help use the -h switch"; throw std::runtime_error(formattedMessage); case CLIErrors::NO_ANALYSIS: formattedMessage += "No analysis was specified. Reverting to default (0 - Voltage).\n"; formattedMessage += "Please refer to the help menu (-h) or manual for further information."; warning_message(formattedMessage); break; case CLIErrors::NO_SOLVER: formattedMessage += "No solver was specified. Reverting to default (0 - KLU).\n"; formattedMessage += "Please refer to the help menu (-h) or manual for further information."; warning_message(formattedMessage); break; case CLIErrors::NO_INTEGRATION: formattedMessage += "No integration method specified\n."; formattedMessage += "Reverting to default (0 - Trapezoidal).\n"; formattedMessage += "Please refer to the help menu (-h) or manual for further information."; warning_message(formattedMessage); break; case CLIErrors::INVALID_CONVENTION: formattedMessage += "Invalid subcircuit convention specified. 0 - JSIM, 1 - WRspice.\n"; formattedMessage += "Usage: josim [options] input_netlist\n\n"; formattedMessage += "For further help use the -h switch"; throw std::runtime_error(formattedMessage); case CLIErrors::INPUT_SAME_OUTPUT: formattedMessage += "Output file name is the same as input file name.\n"; formattedMessage += "This will cause irreversible changes to input file.\n"; formattedMessage += "Please choose a different output file name."; throw std::runtime_error(formattedMessage); case CLIErrors::NO_CONVENTION: formattedMessage += "No convention was specified. Reverting to default (0 - JSIM).\n"; formattedMessage += "Please refer to the help menu (-h) or manual for further information."; warning_message(formattedMessage); break; case CLIErrors::INVALID_MINIMAL: formattedMessage += "Invalid minimal output specified. 0 - Off, 1 - On.\n"; formattedMessage += "Usage: josim [options] input_netlist\n\n"; formattedMessage += "For further help use the -h switch"; throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown handling error.\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } void Errors::input_errors(InputErrors errorCode, string_o message) { std::string formattedMessage = "Input\n"; switch (errorCode) { case InputErrors::CANNOT_OPEN_FILE: formattedMessage += "Input file " + message.value_or("") + " cannot be found or opened.\n"; formattedMessage += "Please ensure that the file exists and can be opened.\n\n"; formattedMessage += "For further help use the -h switch"; throw std::runtime_error(formattedMessage); case InputErrors::CYCLIC_INCLUDE: formattedMessage += "Attempting to include file " + message.value_or("") + ".\n"; formattedMessage += "This is the same file as input file.\n\n"; formattedMessage += "Preventing cyclic includes."; throw std::runtime_error(formattedMessage); case InputErrors::MISSING_SUBCKT_IO: formattedMessage += "Missing subcircuit io.\n"; formattedMessage += "Please recheck the netlist and try again."; throw std::runtime_error(formattedMessage); case InputErrors::MISSING_SUBCKT_NAME: formattedMessage += "Missing subcircuit name.\n"; formattedMessage += "Please recheck the netlist and try again."; throw std::runtime_error(formattedMessage); case InputErrors::SUBCKT_CONTROLS: formattedMessage += "Subcircuit " + message.value_or("") + " contains controls.\n"; formattedMessage += "Controls are reserved for the main design.\n"; formattedMessage += "These controls will be ignored."; warning_message(formattedMessage); break; case InputErrors::MISSING_MAIN: formattedMessage += "Missing main design in netlist.\n"; formattedMessage += "This design will not simulate without a main design."; throw std::runtime_error(formattedMessage); case InputErrors::UNKNOWN_SUBCKT: formattedMessage += "The subcircuit in the following line was not found:\n"; formattedMessage += message.value() + "\n"; formattedMessage += "Please ensure all subcircuits exist and are correctly named."; throw std::runtime_error(formattedMessage); case InputErrors::EMPTY_FILE: formattedMessage += "The file \"" + message.value_or("") + "\" contains no lines.\n"; formattedMessage += "Please check the input file and ensure that the file is not empty."; throw std::runtime_error(formattedMessage); case InputErrors::IO_MISMATCH: formattedMessage += "The IO of line \"" + message.value_or("") + "\" does not " "match the subcircuit IO.\n"; formattedMessage += "Please check the line and ensure correct IO and " "that parameters do not contain spaces."; throw std::runtime_error(formattedMessage); case InputErrors::UNKNOWN_CONTROL: formattedMessage += "The control \"" + message.value_or("") + "\" is not known.\n"; formattedMessage += "Please consult the syntax guide for a list of available controls."; throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown input error.\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } void Errors::invalid_component_errors(ComponentErrors errorCode, string_o message) { std::string formattedMessage = "Components\n"; switch (errorCode) { case ComponentErrors::INVALID_COMPONENT_DECLARATION: formattedMessage += "Invalid component declaration detected.\n"; formattedMessage += "Infringing line: " + message.value_or("") + "\n"; formattedMessage += "Please refer to the documentation for the correct notation."; throw std::runtime_error(formattedMessage); case ComponentErrors::BOTH_GROUND: formattedMessage += "Both nodes are grounded for the following component.\n"; formattedMessage += "Component: " + message.value_or(""); warning_message(formattedMessage); break; case ComponentErrors::GROUNDED_VOLTAGE_SOURCE: formattedMessage += "Both nodes are grounded for the following source.\n"; formattedMessage += "Component: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::RES_ERROR: formattedMessage += "Resistor value error\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::CAP_ERROR: formattedMessage += "Capacitor value error\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::IND_ERROR: formattedMessage += "Inductor value error\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::LABEL_ERROR: formattedMessage += "Invalid component label: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::MISSING_LABEL: formattedMessage += "No component label. This should not happen.\n"; formattedMessage += "Infringing line: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer as this is possibly a bug."; throw std::runtime_error(formattedMessage); case ComponentErrors::MISSING_PNODE: formattedMessage += "No positive node. This should not happen.\n"; formattedMessage += "Infringing line: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer as this is possibly a bug."; throw std::runtime_error(formattedMessage); case ComponentErrors::MISSING_NNODE: formattedMessage += "No negative node. This should not happen.\n"; formattedMessage += "Infringing line: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer as this is possibly a bug."; throw std::runtime_error(formattedMessage); case ComponentErrors::MISSING_JJMODEL: formattedMessage += "No junction model is specified for junction " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::MODEL_NOT_DEFINED: formattedMessage += "The specified model is not defined.\n"; formattedMessage += "Missing model: " + message.value_or("") + "\n"; formattedMessage += "Using default model as specified in the manual."; warning_message(formattedMessage); break; case ComponentErrors::MODEL_AREA_NOT_GIVEN: formattedMessage += "No area specified for junction " + message.value_or("") + "\n"; formattedMessage += "Using default: AREA=1.0"; warning_message(formattedMessage); break; case ComponentErrors::DUPLICATE_LABEL: formattedMessage += "Duplicate label " + message.value_or("") + " detected.\n"; formattedMessage += "The program will now terminate. Please recheck the netlist."; throw std::runtime_error(formattedMessage); case ComponentErrors::INVALID_SUBCIRCUIT_NODES: formattedMessage += "The nodes of " + message.value_or("") + " do not match the subcicuit nodes.\n"; formattedMessage += "Please recheck the nodes required by the subcircuit and try again."; throw std::runtime_error(formattedMessage); case ComponentErrors::TIME_ERROR: formattedMessage += "Time delay value error\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::MISSING_SUBCIRCUIT_NAME: formattedMessage += "The subcircuit for " + message.value_or("") + " was not found in the file.\n"; formattedMessage += "Please recheck the subcircuit name and try again."; throw std::runtime_error(formattedMessage); case ComponentErrors::MUT_ERROR: formattedMessage += "Invalid mutual coupling definition found.\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::INVALID_EXPR: formattedMessage += "Invalid expression statement found.\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::INVALID_TX_DEFINED: formattedMessage += "Invalid definition for transmission line found.\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::INVALID_TX_RESOLUTION: formattedMessage += "Time delay for transmission line is less than simulation timestep.\n"; formattedMessage += "Please reduce timestep to less than any transmission line delay.\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ComponentErrors::MISSING_INDUCTOR: formattedMessage += "Invalid mutual coupling defined."; formattedMessage += "Missing inductor " + message.value_or("") + "\n"; formattedMessage += "Please ensure that " + message.value_or("") + " exists."; throw std::runtime_error(formattedMessage); case ComponentErrors::UNKNOWN_DEVICE_TYPE: formattedMessage += "Unkown device type " + message.value_or("") + "\n"; formattedMessage += "Please refer to the syntax guide for a list of device types."; throw std::runtime_error(formattedMessage); case ComponentErrors::SPECIAL_CHARS: formattedMessage += "Label " + message.value_or("") + " contains special characters.\n"; formattedMessage += "The use of special characters in label names is not advised.\n"; formattedMessage += "This might produce unexpected results.\n"; formattedMessage += "Continuing operation."; warning_message(formattedMessage); break; default: formattedMessage += "Unknown invalid component error.\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } void Errors::control_errors(ControlErrors errorCode, string_o message) { std::string formattedMessage = "Controls\n"; switch (errorCode) { case ControlErrors::TRANS_ERROR: formattedMessage += "Invalid transient analysis specified. " + message.value_or("") + "\n"; formattedMessage += "Substituting default parameters.\n"; formattedMessage += "Defaults: TSTEP=1PS TSTOP=1000PS prstart=0PS PRSTEP=1PS"; warning_message(formattedMessage); break; case ControlErrors::PRINT_TOO_MANY_ARGS: formattedMessage += "Print request for device current has too many arguments.\n"; formattedMessage += "Line: " + message.value_or("") + "\n"; formattedMessage += "Ignoring the extra argument."; warning_message(formattedMessage); break; case ControlErrors::PRINT_ERROR: throw std::runtime_error(formattedMessage); case ControlErrors::PLOT_ERROR: throw std::runtime_error(formattedMessage); case ControlErrors::INV_CONTROL: throw std::runtime_error(formattedMessage); case ControlErrors::DC_ERROR: throw std::runtime_error(formattedMessage); case ControlErrors::AC_ERROR: throw std::runtime_error(formattedMessage); case ControlErrors::PHASE_ERROR: throw std::runtime_error(formattedMessage); case ControlErrors::NO_SIM: formattedMessage += "No simulation type specified. Nothing will be simulated."; throw std::runtime_error(formattedMessage); case ControlErrors::UNKNOWN_DEVICE: formattedMessage += "Unknown device/node " + message.value_or("") + "\n"; formattedMessage += "Cannot store results for this device/node.\n"; formattedMessage += "Ignoring this store request."; warning_message(formattedMessage); break; case ControlErrors::CURRENT_THROUGH_VOLT: formattedMessage += "Requesting current through a voltage source.\n"; formattedMessage += "Line: " + message.value_or("") + "\n"; formattedMessage += "This is invalid and the request will be ignored."; warning_message(formattedMessage); break; case ControlErrors::VOLT_WHEN_PHASE: formattedMessage += "Request to store voltage for device " + message.value_or("") + "\n"; formattedMessage += "Phase mode simulation performed.\n"; formattedMessage += "Storing device phase instead."; warning_message(formattedMessage); break; case ControlErrors::VOLT_ACROSS_CURRENT: formattedMessage += "Requesting voltage across a current source.\n"; formattedMessage += "Line: " + message.value_or("") + "\n"; formattedMessage += "This is invalid and the request will be ignored."; warning_message(formattedMessage); break; case ControlErrors::NODEVOLT_WHEN_PHASE: formattedMessage += "Request to store nodal voltage for " + message.value_or("") + "\n"; formattedMessage += "Phase mode simulation performed.\n"; formattedMessage += "Storing nodal phase instead."; warning_message(formattedMessage); break; case ControlErrors::NODECURRENT: formattedMessage += "Request for current of " + message.value_or("") + " is invalid.\n"; formattedMessage += "Cannot find device or cannot store current of a node."; warning_message(formattedMessage); break; case ControlErrors::UNKNOWN_NODE: formattedMessage += "Node " + message.value_or("") + " was not found in the circuit.\n"; formattedMessage += "This request for store will be ignored."; warning_message(formattedMessage); break; case ControlErrors::NODEPHASE_WHEN_VOLT: formattedMessage += "Request to store nodal phase for " + message.value_or("") + "\n"; formattedMessage += "Voltage mode simulation performed.\n"; formattedMessage += "Storing nodal voltage instead."; warning_message(formattedMessage); break; case ControlErrors::INVALID_NODEV: formattedMessage += "Invalid node voltage request found.\n"; formattedMessage += "Line: " + message.value_or("") + "\n"; formattedMessage += "This request for store will be ignored."; warning_message(formattedMessage); break; case ControlErrors::INVALID_NODEP: formattedMessage += "Invalid node phase request found.\n"; formattedMessage += "Line: " + message.value_or("") + "\n"; formattedMessage += "This request for store will be ignored."; warning_message(formattedMessage); break; case ControlErrors::PHASE_WHEN_VOLT: formattedMessage += "Requesting phase in a voltage simulation.\n"; formattedMessage += "Line: " + message.value_or("") + "\n"; formattedMessage += "This request will be ignored."; warning_message(formattedMessage); break; case ControlErrors::PHASE_OF_VOLT: formattedMessage += "Requesting phase of a voltage source.\n"; formattedMessage += "Line: " + message.value_or("") + "\n"; formattedMessage += "This is invalid and the request will be ignored."; warning_message(formattedMessage); break; case ControlErrors::PHASE_OF_CURRENT: formattedMessage += "Requesting phase of a current source.\n"; formattedMessage += "Line: " + message.value_or("") + "\n"; formattedMessage += "This is invalid and the request will be ignored."; warning_message(formattedMessage); break; case ControlErrors::INVALID_CURRENT: formattedMessage += "Invalid request to plot current.\n"; formattedMessage += "Infringing line: " + message.value_or(""); warning_message(formattedMessage); break; case ControlErrors::MATHOPS: formattedMessage += "Mathematical operations on output vectors are not yet supported.\n"; formattedMessage += "Ignoring plotting of " + message.value_or(""); warning_message(formattedMessage); break; case ControlErrors::UNKNOWN_PLOT: formattedMessage += "Unknown plot type " + message.value_or("") + "\n"; formattedMessage += "Ignoring request to plot."; warning_message(formattedMessage); break; case ControlErrors::INVALID_OUTPUT_COMMAND: formattedMessage += "Invalid request for output found.\n"; formattedMessage += message.value_or("") + "\n"; formattedMessage += "Ignoring request and continuing."; warning_message(formattedMessage); break; case ControlErrors::INVALID_FILE_COMMAND: formattedMessage += "Invalid request for file output found.\n"; formattedMessage += message.value_or("") + "\n"; formattedMessage += "Ignoring request and continuing."; warning_message(formattedMessage); break; case ControlErrors::INVALID_IV_COMMAND: formattedMessage += "Invalid request for IV curve generation found.\n"; formattedMessage += message.value_or("") + "\n"; formattedMessage += "Please refer to the manual for proper syntax.\n"; formattedMessage += "Ignoring request and continuing."; warning_message(formattedMessage); break; case ControlErrors::IV_MODEL_NOT_FOUND: formattedMessage += "The requested model was not found.\n"; formattedMessage += message.value_or("") + "\n"; formattedMessage += "Please ensure the model exists in the netlist.\n"; error_message(formattedMessage); default: formattedMessage += "Unknown control error: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } void Errors::model_errors(ModelErrors errorCode, string_o message) { std::string formattedMessage = "Model\n"; switch (errorCode) { case ModelErrors::PARAM_TYPE_ERROR: formattedMessage += "Unknown model parameter specified.\n"; formattedMessage += "Model line: " + message.value_or("") + "\n"; formattedMessage += "Continuing with default model parameters.\n" "Please consult the syntax guide for more information."; warning_message(formattedMessage); break; case ModelErrors::UNKNOWN_MODEL_TYPE: formattedMessage += "Unknown model type specified.\n"; formattedMessage += "Model line: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ModelErrors::BAD_MODEL_DEFINITION: formattedMessage += "Bad model definition found.\n"; formattedMessage += "Infringing line: " + message.value_or(""); throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown model error: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } [[noreturn]] void Errors::matrix_errors(MatrixErrors errorCode, string_o message) { std::string formattedMessage = "Matrix\n"; switch (errorCode) { case MatrixErrors::NON_SQUARE: formattedMessage += "Matrix is not square. Dimensions are " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer as this is potentially a bug."; throw std::runtime_error(formattedMessage); case MatrixErrors::SANITY_ERROR: formattedMessage += "Component " + message.value_or("") + " created a value in the non-zero" " matrix that is either 0, inf or NaN.\n"; formattedMessage += "This is an internal error and the developer should be contacted."; throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown matrix error: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } [[noreturn]] void Errors::misc_errors(MiscErrors errorCode, string_o message) { std::string formattedMessage = "Miscellaneous\n"; switch (errorCode) { case MiscErrors::STOD_ERROR: formattedMessage += "Cannot convert string to double: " + message.value_or(""); throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown misc error: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } void Errors::function_errors(FunctionErrors errorCode, string_o message) { std::string formattedMessage = "Function\n"; switch (errorCode) { case FunctionErrors::INITIAL_VALUES: formattedMessage += "Invalid PWL definition found.\n"; formattedMessage += "The value of " + message.value_or("") + " is expected to be 0\n"; formattedMessage += "Please refer to the PWL definition:\n"; formattedMessage += "PWL(0 V0 T1 V1 T2 V2 ... Tn Vn)"; warning_message(formattedMessage); break; case FunctionErrors::TOO_FEW_TIMESTEPS: formattedMessage += "Total timesteps specified do not match the values specified.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the PWL definition:\n"; formattedMessage += "PWL(0 0 T1 V1 T2 V2 ... Tn Vn)"; throw std::runtime_error(formattedMessage); case FunctionErrors::TOO_FEW_VALUES: formattedMessage += "Total values specified do not match the timesteps specified.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the PWL definition:\n"; formattedMessage += "PWL(0 0 T1 V1 T2 V2 ... Tn Vn)"; throw std::runtime_error(formattedMessage); case FunctionErrors::INITIAL_PULSE_VALUE: formattedMessage += "Invalid PULSE definition found.\n"; formattedMessage += "The value of " + message.value_or("") + " is expected to be 0\n"; formattedMessage += "Please refer to the PULSE definition:\n"; formattedMessage += "PULSE(0 V2 TD TR TF PW PER)"; throw std::runtime_error(formattedMessage); case FunctionErrors::PULSE_TOO_FEW_ARGUMENTS: formattedMessage += "Total arguments specified do not match the required for PULSE.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the PULSE definition:\n"; formattedMessage += "PULSE(0 V2 TD TR TF PW PER)"; throw std::runtime_error(formattedMessage); case FunctionErrors::PULSE_VPEAK_ZERO: formattedMessage += "PULSE peak voltage is 0.0, this renders the function redundant.\n"; formattedMessage += "Program will continue but PULSE command is redundant."; warning_message(formattedMessage); break; case FunctionErrors::PULSE_WIDTH_ZERO: formattedMessage += "PULSE width is 0.0, this renders the function redundant.\n"; formattedMessage += "Program will continue but PULSE command is redundant."; warning_message(formattedMessage); break; case FunctionErrors::PULSE_REPEAT: formattedMessage += "PULSE repeat rate is 0.0, this is effectively a DC source.\n"; formattedMessage += "Program will continue, but this is most likely unwanted."; warning_message(formattedMessage); break; case FunctionErrors::SIN_TOO_FEW_ARGUMENTS: formattedMessage += "Total arguments specified do not match the required for SIN.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the SIN definition:\n"; formattedMessage += "SIN(VO VA FREQ TD THETA)"; throw std::runtime_error(formattedMessage); case FunctionErrors::SIN_TOO_MANY_ARGUMENTS: formattedMessage += "Total arguments specified do not match the required for SIN.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the SIN definition:\n"; formattedMessage += "SIN(VO VA FREQ TD THETA)"; throw std::runtime_error(formattedMessage); case FunctionErrors::SIN_VA_ZERO: formattedMessage += "SIN amplitude is 0.0, this renders the function redundant.\n"; formattedMessage += "Program will continue but SIN command is redundant."; warning_message(formattedMessage); break; case FunctionErrors::CUS_TOO_FEW_ARGUMENTS: formattedMessage += "Total arguments specified do not match the required for CUS.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the CUS definition:\n"; formattedMessage += "CUS(WaveFile.dat TS SF IM <TD PER>)"; warning_message(formattedMessage); break; case FunctionErrors::CUS_TOO_MANY_ARGUMENTS: formattedMessage += "Total arguments specified do not match the required for CUS.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the CUS definition:\n"; formattedMessage += "CUS(WaveFile.dat TS SF IM <TD PER>)"; warning_message(formattedMessage); break; case FunctionErrors::CUS_SF_ZERO: formattedMessage += "CUS scale factor is 0.0, this renders the function redundant.\n"; formattedMessage += "Program will continue but SIN command is redundant."; warning_message(formattedMessage); break; case FunctionErrors::CUS_WF_NOT_FOUND: formattedMessage += "CUS waveform file was not found.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Program will terminate."; throw std::runtime_error(formattedMessage); case FunctionErrors::NOISE_TOO_FEW_ARGUMENTS: formattedMessage += "Total arguments specified do not match the required for NOISE.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the NOISE definition:\n"; formattedMessage += "NOISE(0 VA TSTEP TD)"; throw std::runtime_error(formattedMessage); case FunctionErrors::NOISE_TOO_MANY_ARGUMENTS: formattedMessage += "Total arguments specified do not match the required for NOISE.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the NOISE definition:\n"; formattedMessage += "NOISE(0 VA TSTEP TD)"; throw std::runtime_error(formattedMessage); case FunctionErrors::NOISE_VO_ZERO: formattedMessage += "NOISE initial value is not 0.0, this needs to be zero.\n"; formattedMessage += "Program will continue but NOISE command is redundant."; warning_message(formattedMessage); break; case FunctionErrors::NOISE_VA_ZERO: formattedMessage += "NOISE amplitude is 0.0, this renders the function redundant.\n"; formattedMessage += "Program will continue but NOISE command is redundant."; warning_message(formattedMessage); break; case FunctionErrors::EXP_TOO_FEW_ARGUMENTS: formattedMessage += "Total arguments specified do not match the required for NOISE.\n"; formattedMessage += message.value_or("") + " specified.\n"; formattedMessage += "Please refer to the NOISE definition:\n"; formattedMessage += "EXP(V1 V2 TD1[0.0] TAU1[TSTEP] TD2[TD1+TSTEP] TAU2[TSTEP])"; throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown function error: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } [[noreturn]] void Errors::simulation_errors(SimulationErrors errorCode, string_o message) { std::string formattedMessage = "Simulation\n"; switch (errorCode) { case SimulationErrors::JJCAP_NOT_FOUND: formattedMessage += "Capacitance for " + message.value_or("") + " could not be found.\n"; formattedMessage += "This is a bug and the developer should be contacted.\n"; formattedMessage += "The program will abort."; throw std::runtime_error(formattedMessage); case SimulationErrors::JJICRIT_NOT_FOUND: formattedMessage += "Critical current value for " + message.value_or("") + " could not be found.\n"; formattedMessage += "This is a bug and the developer should be contacted.\n"; formattedMessage += "The program will abort."; throw std::runtime_error(formattedMessage); case SimulationErrors::JJPHASE_NODE_NOT_FOUND: formattedMessage += "Junction phase node not found for " + message.value_or("") + ".\n"; formattedMessage += "This is a bug and the developer should be contacted.\n"; formattedMessage += "The program will abort."; throw std::runtime_error(formattedMessage); case SimulationErrors::INDUCTOR_CURRENT_NOT_FOUND: formattedMessage += "Inductor current not defined for " + message.value_or("") + ".\n"; formattedMessage += "Matrix will have no solution.\n"; formattedMessage += "This is a bug and the developer should be contacted.\n"; formattedMessage += "The program will abort."; throw std::runtime_error(formattedMessage); case SimulationErrors::MATRIX_SINGULAR: formattedMessage += "Matrix is singular. Matrix will have no solution.\n"; formattedMessage += "Please check the components in the netlist.\n"; formattedMessage += "The program will abort."; throw std::runtime_error(formattedMessage); case SimulationErrors::PHASEGUESS_TOO_LARGE: formattedMessage += "Junction " + message.value_or("") + " has gone too far.\n"; formattedMessage += "This is a result of integration error.\n"; formattedMessage += "Please reduce the timestep and try again."; throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown simulation error: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } void Errors::parsing_errors(ParsingErrors errorCode, string_o message) { std::string formattedMessage = "Parsing\n"; switch (errorCode) { case ParsingErrors::EXPRESSION_ARLEADY_DEFINED: formattedMessage += "Expression duplication: " + message.value_or("") + "\n"; formattedMessage += "Replacing."; warning_message(formattedMessage); break; case ParsingErrors::UNIDENTIFIED_PART: formattedMessage += "The following variables were not found/defined.\n"; formattedMessage += "Please ensure that these variables exist within the netlist.\n"; formattedMessage += "Variables: \n" + message.value_or(""); throw std::runtime_error(formattedMessage); case ParsingErrors::MISMATCHED_PARENTHESIS: formattedMessage += "Mismatched parenthesis in expression: " + message.value_or("") + "\n"; formattedMessage += "Please correct the expression before trying again."; throw std::runtime_error(formattedMessage); case ParsingErrors::INVALID_RPN: formattedMessage += "Invalid RPN detected.\n"; formattedMessage += "This might be an algorithm fault or an incorrect expression parse.\n"; formattedMessage += "The expression in question: " + message.value_or(""); throw std::runtime_error(formattedMessage); case ParsingErrors::INVALID_DECLARATION: formattedMessage += "Missing parameter declaration in: " + message.value_or("") + "\n"; formattedMessage += "Please ensure that a valid .PARAM definition is declared."; throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown parsing error: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } [[noreturn]] void Errors::netlist_errors(NetlistErrors errorCode, string_o message) { std::string formattedMessage = "Netlist\n"; switch (errorCode) { case NetlistErrors::NO_SUCH_NODE: formattedMessage += "Node \"" + message.value_or("") + "\" was not found in the netlist\n"; formattedMessage += "Please check for any disconnections in the netlist"; throw std::runtime_error(formattedMessage); case NetlistErrors::MISSING_IO: formattedMessage += "Missing I/O nodes for subcircuit:\n"; formattedMessage += message.value_or("") + "\n"; formattedMessage += "Please check for any disconnections in the netlist"; throw std::runtime_error(formattedMessage); default: formattedMessage += "Unknown netlist error: " + message.value_or("") + "\n"; formattedMessage += "Please contact the developer."; throw std::runtime_error(formattedMessage); } } void Errors::output_errors(OutputErrors errorCode, string_o message) { std::string formattedMessage = "Output\n"; switch (errorCode) { case OutputErrors::CANNOT_OPEN_FILE: formattedMessage += "Cannot open the requested file for output.\n"; formattedMessage += "Please ensure write permission for the file: " + message.value_or(""); throw std::runtime_error(formattedMessage); case OutputErrors::NOTHING_SPECIFIED: formattedMessage += "Nothing specified to output.\n"; formattedMessage += "Cannot create empty RAW file."; warning_message(formattedMessage); break; } } void Errors::verbosity_errors(VerbosityErrors errorCode, string_o message) { std::string formattedMessage = "Verbosity\n"; switch (errorCode) { case VerbosityErrors::NO_SUCH_LEVEL: formattedMessage += "No such verbosity level: " + message.value_or("") + "\n"; formattedMessage += "Continuing with maximum verbosity."; warning_message(formattedMessage); break; case VerbosityErrors::INVALID_VERBOSITY_LEVEL: formattedMessage += "Invalid verbosity specified: " + message.value_or("") + "\n"; formattedMessage += "Please specify a valid level. Levels are 0, 1, 2, 3.\n"; throw std::runtime_error(formattedMessage); } } [[noreturn]] void Errors::oor() { std::cerr << "\nE: Out of range error. This is a bug." << std::endl; std::cerr << "E: Please contact the developer." << std::endl; std::cerr << std::endl; exit(-1); } [[noreturn]] void Errors::error_message(const std::string& formattedMessage) { std::cerr << "\nE: " << formattedMessage << std::endl; std::cerr << std::endl; exit(-1); } void Errors::warning_message(const std::string& formattedMessage) { std::cerr << "\nW: " << formattedMessage << std::endl; std::cerr << std::endl; }
LongLong: .long 0x0001e240,0x00000000 .type LongLong,@object .size LongLong,8 .align 4 .globl Int Int: .long 123 .type Int,@object .size Int,4 .align 2 .globl Short Short: .word 4660 .type Short,@object .size Short,2 .align 1 .globl Char Char: .byte -128 .type Char,@object .size Char,1 .data
; A294013: Sum of the differences of the larger and smaller parts in the partitions of 2n into two parts with the smaller part prime. ; 0,0,2,6,10,16,22,30,38,46,54,64,74,86,98,110,122,136,150,166,182,198,214,232,250,268,286,304,322,342,362,384,406,428,450,472,494,518,542,566,590,616,642,670,698,726,754,784,814,844,874,904,934,966,998,1030,1062,1094,1126,1160,1194,1230,1266,1302,1338,1374,1410,1448,1486,1524,1562,1602,1642,1684,1726,1768,1810,1852,1894,1938,1982,2026,2070,2116,2162,2208,2254,2300,2346,2394,2442,2490,2538,2586,2634,2682,2730,2780,2830,2880 trn $0,1 seq $0,46992 ; a(n) = Sum_{k=1..n} pi(k) (cf. A000720). mul $0,2
#ifndef INCLUDED_ALI_LUA_EXT_QUEUE #define INCLUDED_ALI_LUA_EXT_QUEUE #include <aliLuaCore.hpp> #include <aliSystem.hpp> #include <deque> #include <memory> #include <mutex> #include <string> #include <ostream> struct lua_State; namespace aliLuaExt { /// @brief The Queue class defines a queue of Lua MakeFn values that /// can be used to asynronously queue data for a Lua interpreter /// or a set of Lua interpreters to process. /// /// Since Lua is fundamentally a single threaded API, so using an /// interpreter to execute work is often challenged by the desire /// to allow the c++ code that would generally call the Lua to run /// without being blocked. In order to separate this interaction, /// this class provides a mechanism for c++ code to queue work. /// One could use a aliLuaCore::Future to retrieve processing results /// alternatively one might have their own custom call back mechanism. /// In general, when Lua calls to C++, it is often quite easy to enable /// synchronize those calls with other C++ threads. In cases where /// the is no need for a call back, interactions between C++ and Lua are /// simply that much simpler. If data needs to be queued to C++, and /// the call from Lua will not directly syncronize with the C++ data sink /// one might extract a aliLuaCore::MakeFn from the Lua interpreter in /// the call back. Then in a "decoupling" Lua interpreter, that data can /// be re-constructed and read directly from the C++ code needing the /// data. struct Queue { using Ptr = std::shared_ptr<Queue>; ///< shared pointer using WPtr = std::weak_ptr<Queue>; ///< weak pointer using MVec = std::deque<aliLuaCore::MakeFn>; ///< MakeFn queue using Listeners = aliSystem::Listeners<const WPtr &>; ///< listener container using Listener = aliSystem::Listener<const WPtr &>; ///< listener using OBJ = aliLuaCore::StaticObject<Queue>; ///< utility StaticObject using LOBJ = aliLuaCore::StaticObject<Listener>; ///< utility StaticObject /// @brief Initialize Queue module /// @param cr is a component registry to which any initialzation /// and finalization logic should be registered. /// @note This function should only be called from aliLuaExt::RegisterInitFini static void RegisterInitFini(aliSystem::ComponentRegistry &cr); /// @brief Create a queue. /// @param name the name of the queue /// @return A queueu static Ptr Create(const std::string &name); /// @brief Destructor. ~Queue(); /// @brief Name retrieves the name of the queue /// @return the name const std::string &Name() const; /// @brief GetPtr retrieves a shared pointer to the queue /// @return "self" pointer Ptr GetPtr() const; /// @brief PushNext will extract an item from the queue and push /// it onto the given interpreter's stack. /// @param L the interpreter to receive the queue item /// @return the number of items pushed onto the stack /// @note If there are no items in the queue, nothing will be /// pushed. int PushNext(lua_State *L); /// @brief Append will add the given item to the end of the queue. /// @param item MakeFn representing the "item to add" /// @note The 'item' may represent more than one stack value. /// One might consider pushing tables into a queue, which /// makes it easy to consistently received the items from a /// queue. One's strategy in this regard is arbitrary. void Append(const aliLuaCore::MakeFn &item); /// @brief Append will add the given item to the end of the queue. /// @param item MakeFn representing the "item to add" /// @note The 'item' may represent more than one stack value. /// One might consider pushing tables into a queue, which /// makes it easy to consistently received the items from a /// queue. One's strategy in this regard is arbitrary. void Insert(const aliLuaCore::MakeFn &item); /// @brief Empty checks to see if the queue is empty. /// @brief empty status bool Empty(); /// @brief Size returns the number of items in the queue, which /// may be zero. /// @return number of items in the queue. size_t Size(); /// @brief Onfirst will return a listering container that will /// be notified when the first item is entered into the /// queue whenever it was empty before the addition. /// @return listener container. const Listeners::Ptr &OnFirst () const; /// @brief OnInsert will return a listering container that will /// be notified whenever an item is added to the /// queue. /// @return listener container. const Listeners::Ptr &OnInsert() const; /// @brief serialization function for a Queue. /// @param out is the stream to which the queue should be serialized /// @param o is the queue object to serialize /// @return the stream passed as out friend std::ostream &operator<<(std::ostream &out, const Queue &o); private: /// @brief Constructor Queue(); /// @brief Notify is an internal function that is used to trigger /// listeners whenever items are added to the queue. /// @param sz should be the size of the queue before the item /// trigger the call was added. /// @note This call is made within the queue's lock. Because /// of this listeners should not makes calls to the queue /// that would trigger a lock. void Notify(size_t sz); WPtr THIS; ///< weak pointer to self std::mutex lock; ///< lock to guard the manipulation of items std::string name; ///< name of the queue MVec items; ///< items in the queue Listeners::Ptr onFirst; ///< listener container Listeners::Ptr onInsert; ///< listener container }; } #endif
; A235332: a(n) = n*(9*n + 25)/2 + 6. ; 6,23,49,84,128,181,243,314,394,483,581,688,804,929,1063,1206,1358,1519,1689,1868,2056,2253,2459,2674,2898,3131,3373,3624,3884,4153,4431,4718,5014,5319,5633,5956,6288,6629,6979,7338,7706,8083,8469,8864,9268,9681,10103,10534,10974,11423,11881,12348,12824,13309,13803,14306,14818,15339,15869,16408,16956,17513,18079,18654,19238,19831,20433,21044,21664,22293,22931,23578,24234,24899,25573,26256,26948,27649,28359,29078,29806,30543,31289,32044,32808,33581,34363,35154,35954,36763,37581,38408,39244,40089 mov $1,9 mul $1,$0 add $1,25 mul $1,$0 div $1,2 add $1,6 mov $0,$1
#include "precomp.hxx" #include "lkrcust.h" LKR_CUST_EXTN* FindLkrCustExtn( LPCSTR cmdName, VOID* lkrAddress, DWORD& rdwSig) { extern LKR_CUST_EXTN g_alce[]; struct LKRheader { DWORD m_dwSignature; CHAR m_szName[NAME_SIZE]; }; LKRheader lkrh; rdwSig = 0; if (!ReadMemory((ULONG_PTR)lkrAddress, &lkrh, sizeof(lkrh), NULL) ) { dprintf(DBGEXT ".%s: cannot read memory @ %p\n", cmdName, (PVOID) lkrAddress); return NULL; } rdwSig = lkrh.m_dwSignature; lkrh.m_szName[NAME_SIZE-1] = '\0'; const INT cch = strlen(lkrh.m_szName); for (LKR_CUST_EXTN* plce = g_alce + 1; // skip Dummys plce->m_pszTableName != NULL; ++plce) { if (strncmp(plce->m_pszTableName, lkrh.m_szName, min(cch, plce->m_cchTableName)) == 0) { return plce; } } return &g_alce[0]; // Dummy methods } BOOL WINAPI Dummy_LKHT_Dump( IN LKRHASH_NS::CLKRHashTable* pht, IN INT nVerbose) { return TRUE; } BOOL WINAPI Dummy_LKLH_Dump( IN LKRHASH_NS::CLKRLinearHashTable* plht, IN INT nVerbose) { return TRUE; } BOOL WINAPI Dummy_Record_Dump( IN const void* pvRecord, IN DWORD dwSignature, IN INT nVerbose) { dprintf("Record=%p (HashSig=%08x)\n", pvRecord, dwSignature); return TRUE; }
/*********************************************************************************/ /********** THIS FILE IS GENERATED BY TOUCHGFX DESIGNER, DO NOT MODIFY ***********/ /*********************************************************************************/ #ifndef SCREEN2VIEWBASE_HPP #define SCREEN2VIEWBASE_HPP #include <gui/common/FrontendApplication.hpp> #include <mvp/View.hpp> #include <gui/screen2_screen/Screen2Presenter.hpp> #include <touchgfx/widgets/Box.hpp> #include <touchgfx/widgets/TextArea.hpp> #include <touchgfx/widgets/ButtonWithLabel.hpp> class Screen2ViewBase : public touchgfx::View<Screen2Presenter> { public: Screen2ViewBase(); virtual ~Screen2ViewBase() {} virtual void setupScreen(); protected: FrontendApplication& application() { return *static_cast<FrontendApplication*>(touchgfx::Application::getInstance()); } /* * Member Declarations */ touchgfx::Box __background; touchgfx::Box box1; touchgfx::TextArea textArea1; touchgfx::ButtonWithLabel buttonWithLabel1; private: /* * Callback Declarations */ touchgfx::Callback<Screen2ViewBase, const touchgfx::AbstractButton&> buttonCallback; /* * Callback Handler Declarations */ void buttonCallbackHandler(const touchgfx::AbstractButton& src); }; #endif // SCREEN2VIEWBASE_HPP
MODULE __printf_number SECTION code_clib PUBLIC __printf_number EXTERN __printf_print_to_buf EXTERN __printf_print_the_buffer EXTERN l_int2long_s EXTERN l_long_neg EXTERN l_long_div_u EXTERN get_16bit_ap_parameter defc handlelong = 1 ; Print a number ; Entry: hl = fmt (character after format) ; de = ap ; c = 1 = signed, 0 = unsigned __printf_number: push hl ;save fmt bit 6,(ix-4) jr z,printf_number16 bit 0,(ix+6) ;sccz80 flag jr nz,pickuplong_sccz80 ; Picking up a long sdcc style ex de,hl ;hl=where tp pick up from ld e,(hl) ;LSW inc hl ld d,(hl) inc hl ld a,(hl) inc hl ld b,(hl) inc hl push hl ; save ap ld h,b ld l,a ex de,hl ;dehl=long, c: 1=signed, 0=unsigned printlong: ld a,c jp miniprintn pickuplong_sccz80: ex de,hl ld e,(hl) ;MSW inc hl ld d,(hl) dec hl dec hl ld b,(hl) ;LSW dec hl ld a,(hl) dec hl dec hl push hl ;Save ap for next time ld h,b ld l,a jr printlong printf_number16: call get_16bit_ap_parameter ;de = new ap, hl = number to print push de ; save ap ld de,0 ;make it a long ld a,c ;signed? and a call nz,l_int2long_s ;extend it out jr printlong ; Entry: a = flag (0=unsigned, 1 = signed) ; dehl = number miniprintn: ld b,a IF handlelong ld a,d ELSE ld a,h ENDIF rlca and 1 and b jr z,noneg IF handlelong call l_long_neg ELSE call l_neg ENDIF ld a,'-' printsign: call __printf_print_to_buf jr miniprintn_start_process noneg: ld a,' ' bit 3,(ix-4) jr nz,printsign ld a,'+' bit 1,(ix-4) ;do we force a + jr nz,printsign bit 4,(ix-4) ;# indicator jr z,miniprintn_start_process ld a,(ix-9) ;get base cp 10 jr z,miniprintn_start_process ex af,af ld a,'0' call __printf_print_to_buf ex af,af cp 16 jr nz,miniprintn_start_process ld a,'x' add (ix-3) call __printf_print_to_buf miniprintn_start_process: xor a push af ; set terminator .divloop IF handlelong push de ; number MSW push hl ; number LSW ld l,(ix-9) ;base ld h,0 ld d,h ld e,h call l_long_div_u exx ld a,l cp 255 ; force flag to non-zero push af ; save reminder as a digit in stack exx ELSE ld e,(ix-9) ;base ld d,0 ex de,hl call l_div_u ;hl=de/hl de=de%hl ld a,e cp 255 ; force flag to non-zero push af ; save reminder as a digit in stack ENDIF ld a,h IF handlelong or d or e ENDIF or l ; is integer part of last division zero ? jr nz,divloop ; not still ?.. loop ; now recurse for the single digit ; pick all from stack until you get the terminator ; .printloop pop af jp z,__printf_print_the_buffer add '0' ; We only print hex at level 2 cp '9'+1 jr c,printloop1 add 'a' - '9' -1 add (ix-3) printloop1: call __printf_print_to_buf jr printloop
// Copyright (c) Team CharLS. // SPDX-License-Identifier: BSD-3-Clause #include "jpeg_stream_reader.h" #include "constants.h" #include "decoder_strategy.h" #include "jls_codec_factory.h" #include "jpeg_marker_code.h" #include "jpegls_preset_parameters_type.h" #include "util.h" #include <algorithm> #include <memory> namespace charls { using impl::throw_jpegls_error; using std::find; using std::unique_ptr; using std::vector; jpeg_stream_reader::jpeg_stream_reader(const byte_span source) noexcept : source_{source} { } void jpeg_stream_reader::read(byte_span source, size_t stride) { ASSERT(state_ == state::bit_stream_section); check_parameter_coherent(); if (rect_.Width <= 0) { rect_.Width = static_cast<int32_t>(frame_info_.width); rect_.Height = static_cast<int32_t>(frame_info_.height); } if (stride == 0) { const uint32_t width{rect_.Width != 0 ? static_cast<uint32_t>(rect_.Width) : frame_info_.width}; const uint32_t component_count{ parameters_.interleave_mode == interleave_mode::none ? 1U : static_cast<uint32_t>(frame_info_.component_count)}; stride = static_cast<size_t>(component_count) * width * ((static_cast<size_t>(frame_info_.bits_per_sample) + 7U) / 8U); } const int64_t bytes_per_plane{static_cast<int64_t>(rect_.Width) * rect_.Height * bit_to_byte_count(frame_info_.bits_per_sample)}; if (static_cast<int64_t>(source.size) < bytes_per_plane * frame_info_.component_count) throw_jpegls_error(jpegls_errc::destination_buffer_too_small); int component_index{}; while (component_index < frame_info_.component_count) { if (state_ == state::scan_section) { read_next_start_of_scan(); } unique_ptr<decoder_strategy> codec{ jls_codec_factory<decoder_strategy>().create_codec(frame_info_, parameters_, preset_coding_parameters_)}; unique_ptr<process_line> process_line(codec->create_process_line(source, stride)); codec->decode_scan(move(process_line), rect_, source_); skip_bytes(source, static_cast<size_t>(bytes_per_plane)); state_ = state::scan_section; if (parameters_.interleave_mode != interleave_mode::none) return; component_index++; } } void jpeg_stream_reader::read_bytes(std::vector<char>& destination, const int byte_count) { for (int i{}; i < byte_count; ++i) { destination.push_back(static_cast<char>(read_byte())); } } void jpeg_stream_reader::read_header(spiff_header* header, bool* spiff_header_found) { ASSERT(state_ != state::scan_section); if (state_ == state::before_start_of_image) { if (read_next_marker_code() != jpeg_marker_code::start_of_image) throw_jpegls_error(jpegls_errc::start_of_image_marker_not_found); state_ = state::header_section; } for (;;) { const jpeg_marker_code marker_code = read_next_marker_code(); validate_marker_code(marker_code); if (marker_code == jpeg_marker_code::start_of_scan) { if (!is_maximum_sample_value_valid()) throw_jpegls_error(jpegls_errc::invalid_parameter_jpegls_pc_parameters); state_ = state::scan_section; return; } const int32_t segment_size{read_segment_size()}; int bytes_read; switch (state_) { case state::spiff_header_section: bytes_read = read_spiff_directory_entry(marker_code, segment_size - 2) + 2; break; default: bytes_read = read_marker_segment(marker_code, segment_size - 2, header, spiff_header_found) + 2; break; } const int padding_to_read{segment_size - bytes_read}; if (padding_to_read < 0) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); for (int i{}; i < padding_to_read; ++i) { read_byte(); } if (state_ == state::header_section && spiff_header_found && *spiff_header_found) { state_ = state::spiff_header_section; return; } } } void jpeg_stream_reader::read_next_start_of_scan() { ASSERT(state_ == state::scan_section); for (;;) { const jpeg_marker_code marker_code{read_next_marker_code()}; validate_marker_code(marker_code); if (marker_code == jpeg_marker_code::start_of_scan) { read_start_of_scan(); return; } const int32_t segment_size{read_segment_size()}; const int bytes_read{read_marker_segment(marker_code, segment_size - 2) + 2}; const int padding_to_read{segment_size - bytes_read}; if (padding_to_read < 0) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); for (int i{}; i < padding_to_read; ++i) { read_byte(); } } } jpeg_marker_code jpeg_stream_reader::read_next_marker_code() { auto byte{read_byte()}; if (byte != jpeg_marker_start_byte) throw_jpegls_error(jpegls_errc::jpeg_marker_start_byte_not_found); // Read all preceding 0xFF fill values until a non 0xFF value has been found. (see T.81, B.1.1.2) do { byte = read_byte(); } while (byte == jpeg_marker_start_byte); return static_cast<jpeg_marker_code>(byte); } void jpeg_stream_reader::validate_marker_code(const jpeg_marker_code marker_code) const { // ISO/IEC 14495-1, C.1.1. defines the following markers as valid for a JPEG-LS byte stream: // SOF55, LSE, SOI, EOI, SOS, DNL, DRI, RSTm, APPn and COM. // All other markers shall not be present. switch (marker_code) { case jpeg_marker_code::start_of_scan: if (state_ != state::scan_section) throw_jpegls_error(jpegls_errc::unexpected_marker_found); return; case jpeg_marker_code::start_of_frame_jpegls: if (state_ == state::scan_section) throw_jpegls_error(jpegls_errc::duplicate_start_of_frame_marker); return; case jpeg_marker_code::jpegls_preset_parameters: case jpeg_marker_code::comment: case jpeg_marker_code::application_data0: case jpeg_marker_code::application_data1: case jpeg_marker_code::application_data2: case jpeg_marker_code::application_data3: case jpeg_marker_code::application_data4: case jpeg_marker_code::application_data5: case jpeg_marker_code::application_data6: case jpeg_marker_code::application_data7: case jpeg_marker_code::application_data8: case jpeg_marker_code::application_data9: case jpeg_marker_code::application_data10: case jpeg_marker_code::application_data11: case jpeg_marker_code::application_data12: case jpeg_marker_code::application_data13: case jpeg_marker_code::application_data14: case jpeg_marker_code::application_data15: return; // Check explicit for one of the other common JPEG encodings. case jpeg_marker_code::start_of_frame_baseline_jpeg: case jpeg_marker_code::start_of_frame_extended_sequential: case jpeg_marker_code::start_of_frame_progressive: case jpeg_marker_code::start_of_frame_lossless: case jpeg_marker_code::start_of_frame_differential_sequential: case jpeg_marker_code::start_of_frame_differential_progressive: case jpeg_marker_code::start_of_frame_differential_lossless: case jpeg_marker_code::start_of_frame_extended_arithmetic: case jpeg_marker_code::start_of_frame_progressive_arithmetic: case jpeg_marker_code::start_of_frame_lossless_arithmetic: case jpeg_marker_code::start_of_frame_jpegls_extended: throw_jpegls_error(jpegls_errc::encoding_not_supported); case jpeg_marker_code::start_of_image: throw_jpegls_error(jpegls_errc::duplicate_start_of_image_marker); case jpeg_marker_code::end_of_image: throw_jpegls_error(jpegls_errc::unexpected_end_of_image_marker); } throw_jpegls_error(jpegls_errc::unknown_jpeg_marker_found); } int jpeg_stream_reader::read_marker_segment(const jpeg_marker_code marker_code, const int32_t segment_size, spiff_header* header, bool* spiff_header_found) { switch (marker_code) { case jpeg_marker_code::start_of_frame_jpegls: return read_start_of_frame_segment(segment_size); case jpeg_marker_code::comment: return read_comment(); case jpeg_marker_code::jpegls_preset_parameters: return read_preset_parameters_segment(segment_size); case jpeg_marker_code::application_data0: case jpeg_marker_code::application_data1: case jpeg_marker_code::application_data2: case jpeg_marker_code::application_data3: case jpeg_marker_code::application_data4: case jpeg_marker_code::application_data5: case jpeg_marker_code::application_data6: case jpeg_marker_code::application_data7: case jpeg_marker_code::application_data9: case jpeg_marker_code::application_data10: case jpeg_marker_code::application_data11: case jpeg_marker_code::application_data12: case jpeg_marker_code::application_data13: case jpeg_marker_code::application_data14: case jpeg_marker_code::application_data15: return 0; case jpeg_marker_code::application_data8: return try_read_application_data8_segment(segment_size, header, spiff_header_found); // Other tags not supported (among which DNL DRI) default: ASSERT(false); return 0; } } int jpeg_stream_reader::read_spiff_directory_entry(const jpeg_marker_code marker_code, const int32_t segment_size) { if (marker_code != jpeg_marker_code::application_data8) throw_jpegls_error(jpegls_errc::missing_end_of_spiff_directory); if (segment_size < 4) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); const uint32_t spiff_directory_type{read_uint32()}; if (spiff_directory_type == spiff_end_of_directory_entry_type) { state_ = state::image_section; } return 4; } int jpeg_stream_reader::read_start_of_frame_segment(const int32_t segment_size) { // A JPEG-LS Start of Frame (SOF) segment is documented in ISO/IEC 14495-1, C.2.2 // This section references ISO/IEC 10918-1, B.2.2, which defines the normal JPEG SOF, // with some modifications. if (segment_size < 6) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); frame_info_.bits_per_sample = read_byte(); if (frame_info_.bits_per_sample < minimum_bits_per_sample || frame_info_.bits_per_sample > maximum_bits_per_sample) throw_jpegls_error(jpegls_errc::invalid_parameter_bits_per_sample); frame_info_.height = read_uint16(); if (frame_info_.height < 1) throw_jpegls_error(jpegls_errc::parameter_value_not_supported); frame_info_.width = read_uint16(); if (frame_info_.width < 1) throw_jpegls_error(jpegls_errc::parameter_value_not_supported); frame_info_.component_count = read_byte(); if (frame_info_.component_count < 1) throw_jpegls_error(jpegls_errc::invalid_parameter_component_count); if (segment_size != 6 + (frame_info_.component_count * 3)) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); for (int32_t i{}; i < frame_info_.component_count; ++i) { // Component specification parameters add_component(read_byte()); // Ci = Component identifier const uint8_t horizontal_vertical_sampling_factor{ read_byte()}; // Hi + Vi = Horizontal sampling factor + Vertical sampling factor if (horizontal_vertical_sampling_factor != 0x11) throw_jpegls_error(jpegls_errc::parameter_value_not_supported); skip_byte(); // Tqi = Quantization table destination selector (reserved for JPEG-LS, should be set to 0) } state_ = state::scan_section; return segment_size; } int jpeg_stream_reader::read_comment() noexcept { return 0; } int jpeg_stream_reader::read_preset_parameters_segment(const int32_t segment_size) { if (segment_size < 1) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); const auto type{static_cast<jpegls_preset_parameters_type>(read_byte())}; switch (type) { case jpegls_preset_parameters_type::preset_coding_parameters: { constexpr int32_t coding_parameter_segment_size = 11; if (segment_size != coding_parameter_segment_size) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); preset_coding_parameters_.maximum_sample_value = read_uint16(); preset_coding_parameters_.threshold1 = read_uint16(); preset_coding_parameters_.threshold2 = read_uint16(); preset_coding_parameters_.threshold3 = read_uint16(); preset_coding_parameters_.reset_value = read_uint16(); return coding_parameter_segment_size; } case jpegls_preset_parameters_type::mapping_table_specification: case jpegls_preset_parameters_type::mapping_table_continuation: case jpegls_preset_parameters_type::extended_width_and_height: throw_jpegls_error(jpegls_errc::parameter_value_not_supported); case jpegls_preset_parameters_type::coding_method_specification: case jpegls_preset_parameters_type::near_lossless_error_re_specification: case jpegls_preset_parameters_type::visually_oriented_quantization_specification: case jpegls_preset_parameters_type::extended_prediction_specification: case jpegls_preset_parameters_type::start_of_fixed_length_coding: case jpegls_preset_parameters_type::end_of_fixed_length_coding: case jpegls_preset_parameters_type::extended_preset_coding_parameters: case jpegls_preset_parameters_type::inverse_color_transform_specification: throw_jpegls_error(jpegls_errc::jpegls_preset_extended_parameter_type_not_supported); } throw_jpegls_error(jpegls_errc::invalid_jpegls_preset_parameter_type); } void jpeg_stream_reader::read_start_of_scan() { const int32_t segment_size{read_segment_size()}; if (segment_size < 3) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); const int component_count_in_scan{read_byte()}; if (component_count_in_scan != 1 && component_count_in_scan != frame_info_.component_count) throw_jpegls_error(jpegls_errc::parameter_value_not_supported); if (segment_size != 6 + (2 * component_count_in_scan)) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); for (int i{}; i < component_count_in_scan; ++i) { read_byte(); // Read Scan component selector const uint8_t mapping_table_selector{read_byte()}; if (mapping_table_selector != 0) throw_jpegls_error(jpegls_errc::parameter_value_not_supported); } parameters_.near_lossless = read_byte(); // Read NEAR parameter if (parameters_.near_lossless > compute_maximum_near_lossless(static_cast<int>(maximum_sample_value()))) throw_jpegls_error(jpegls_errc::invalid_parameter_near_lossless); const auto mode{static_cast<interleave_mode>(read_byte())}; // Read ILV parameter if (!(mode == interleave_mode::none || mode == interleave_mode::line || mode == interleave_mode::sample)) throw_jpegls_error(jpegls_errc::invalid_parameter_interleave_mode); parameters_.interleave_mode = mode; if ((read_byte() & 0xFU) != 0) // Read Ah (no meaning) and Al (point transform). throw_jpegls_error(jpegls_errc::parameter_value_not_supported); state_ = state::bit_stream_section; } uint8_t jpeg_stream_reader::read_byte() { if (source_.size == 0) throw_jpegls_error(jpegls_errc::source_buffer_too_small); const uint8_t value{source_.data[0]}; skip_bytes(source_, 1); return value; } void jpeg_stream_reader::skip_byte() { static_cast<void>(read_byte()); } uint16_t jpeg_stream_reader::read_uint16() { const uint16_t value = read_byte() * 256U; return static_cast<uint16_t>(value + read_byte()); } uint32_t jpeg_stream_reader::read_uint32() { uint32_t value{read_uint16()}; value = value << 16U; value += read_uint16(); return value; } int32_t jpeg_stream_reader::read_segment_size() { const int32_t segment_size{read_uint16()}; if (segment_size < 2) throw_jpegls_error(jpegls_errc::invalid_marker_segment_size); return segment_size; } int jpeg_stream_reader::try_read_application_data8_segment(const int32_t segment_size, spiff_header* header, bool* spiff_header_found) { if (spiff_header_found) { ASSERT(header); *spiff_header_found = false; } if (segment_size == 5) return try_read_hp_color_transform_segment(); if (header && spiff_header_found && segment_size >= 30) return try_read_spiff_header_segment(*header, *spiff_header_found); return 0; } int jpeg_stream_reader::try_read_hp_color_transform_segment() { vector<char> source_tag; read_bytes(source_tag, 4); if (strncmp(source_tag.data(), "mrfx", 4) != 0) // mrfx = xfrm (in big endian) = colorXFoRM return 4; const auto transformation{read_byte()}; switch (transformation) { case static_cast<uint8_t>(color_transformation::none): case static_cast<uint8_t>(color_transformation::hp1): case static_cast<uint8_t>(color_transformation::hp2): case static_cast<uint8_t>(color_transformation::hp3): parameters_.transformation = static_cast<color_transformation>(transformation); return 5; case 4: // RgbAsYuvLossy (The standard lossy RGB to YCbCr transform used in JPEG.) case 5: // Matrix (transformation is controlled using a matrix that is also stored in the segment. throw_jpegls_error(jpegls_errc::color_transform_not_supported); default: throw_jpegls_error(jpegls_errc::invalid_encoded_data); } } template<typename EnumType, EnumType Low, EnumType High> EnumType enum_cast(uint8_t value) { if (value < static_cast<uint8_t>(Low)) throw_jpegls_error(jpegls_errc::invalid_encoded_data); if (value > static_cast<uint8_t>(High)) throw_jpegls_error(jpegls_errc::invalid_encoded_data); return static_cast<EnumType>(value); } int jpeg_stream_reader::try_read_spiff_header_segment(OUT_ spiff_header& header, OUT_ bool& spiff_header_found) { vector<char> source_tag; read_bytes(source_tag, 6); if (strncmp(source_tag.data(), "SPIFF\0", 6) != 0) { header = {}; spiff_header_found = false; return 6; } const auto high_version{read_byte()}; if (high_version > spiff_major_revision_number) { header = {}; spiff_header_found = false; return 7; // Treat unknown versions as if the SPIFF header doesn't exists. } skip_byte(); // low version header.profile_id = static_cast<spiff_profile_id>(read_byte()); header.component_count = read_byte(); header.height = read_uint32(); header.width = read_uint32(); header.color_space = static_cast<spiff_color_space>(read_byte()); header.bits_per_sample = read_byte(); header.compression_type = static_cast<spiff_compression_type>(read_byte()); header.resolution_units = static_cast<spiff_resolution_units>(read_byte()); header.vertical_resolution = read_uint32(); header.horizontal_resolution = read_uint32(); spiff_header_found = true; return 30; } void jpeg_stream_reader::add_component(const uint8_t component_id) { if (find(component_ids_.cbegin(), component_ids_.cend(), component_id) != component_ids_.cend()) throw_jpegls_error(jpegls_errc::duplicate_component_id_in_sof_segment); component_ids_.push_back(component_id); } void jpeg_stream_reader::check_parameter_coherent() const { switch (frame_info_.component_count) { case 4: case 3: break; default: if (parameters_.interleave_mode != interleave_mode::none) throw_jpegls_error(jpegls_errc::parameter_value_not_supported); break; } } bool jpeg_stream_reader::is_maximum_sample_value_valid() const noexcept { return preset_coding_parameters_.maximum_sample_value == 0 || static_cast<uint32_t>(preset_coding_parameters_.maximum_sample_value) <= calculate_maximum_sample_value(frame_info_.bits_per_sample); } uint32_t jpeg_stream_reader::maximum_sample_value() const noexcept { ASSERT(is_maximum_sample_value_valid()); if (preset_coding_parameters_.maximum_sample_value != 0) return static_cast<uint32_t>(preset_coding_parameters_.maximum_sample_value); return calculate_maximum_sample_value(frame_info_.bits_per_sample); } } // namespace charls
; Emulate 'rl bc' instruction, only carry is affected ; CPU Min T Max T ; 8080 90 90 ; 8085 88 88 ; gbz80 16 16 ; r2ka 8 8 ; z180 14 14 ; z80 16 16 ; z80n 16 16 SECTION code_l_sccz80 PUBLIC __z80asm__rl_bc __z80asm__rl_bc: IF __CPU_INTEL__ push af ld a, c rla ld c, a ld a, b rla ld b, a jr nc, carry0 pop af scf ret carry0: pop af and a ret ELSE rl c rl b ret ENDIF
/*========================================================================= * * Copyright NumFOCUS * * 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 itkWatershedSegmentTable_hxx #define itkWatershedSegmentTable_hxx #include "itkWatershedSegmentTable.h" namespace itk { namespace watershed { template <typename TScalar> void SegmentTable<TScalar>::PruneEdgeLists(ScalarType maximum_saliency) { Iterator it; typename edge_list_t::iterator e; for (it = this->Begin(); it != this->End(); ++it) { for (e = (*it).second.edge_list.begin(); e != (*it).second.edge_list.end(); e++) { if ((e->height - (*it).second.min) > maximum_saliency) { // dump the rest of the list, assumes list is sorted e++; (*it).second.edge_list.erase(e, (*it).second.edge_list.end()); break; // through with this segment } } } } template <typename TScalar> void SegmentTable<TScalar>::SortEdgeLists() { Iterator it; for (it = this->Begin(); it != this->End(); ++it) { (*it).second.edge_list.sort(); } } template <typename TScalar> bool SegmentTable<TScalar>::Add(IdentifierType a, const segment_t & t) { std::pair<Iterator, bool> result; result = m_HashMap.insert(ValueType(a, t)); if (result.second == false) { return false; } else { return true; } } } // end namespace watershed } // end namespace itk #endif
; A257594: Consider the hexagonal lattice packing of circles; a(n) is the maximal number of circles that can be enclosed by a closed chain of n circles. ; 0,0,0,0,0,0,1,1,2,3,4,5,7,8,10 lpb $0,1 sub $0,5 add $2,1 add $3,$0 mov $1,$3 sub $0,1 add $1,2 lpe sub $1,1 sub $1,$2
; A155650: 7^n - 6^n + 1. ; 1,2,14,128,1106,9032,70994,543608,4085186,30275912,222009074,1614529688,11664504866,83828316392,599858908754,4277376525368,30411820662146,215703854542472,1526853641242034,10789535445362648 mov $1,7 pow $1,$0 mov $2,6 pow $2,$0 add $2,7 mov $3,$2 sub $3,8 sub $1,$3
/*************************************************************************** * Copyright (C) by GFZ Potsdam * * * * You can redistribute and/or modify this program under the * * terms of the SeisComP Public License. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * SeisComP Public License for more details. * ***************************************************************************/ #define SEISCOMP_COMPONENT OriginLocatorView #include <seiscomp3/logging/log.h> #include <seiscomp3/gui/core/application.h> #include "mainframe.h" using namespace Seiscomp::Gui; class OLVApp : public Kicker<MainFrame> { public: OLVApp(int& argc, char** argv, int flags = DEFAULT) : Kicker<MainFrame>(argc, argv, flags) { setLoadRegionsEnabled(true); _preloadDays = 1; } protected: bool initConfiguration() { if ( !Kicker<MainFrame>::initConfiguration() ) return false; try { _preloadDays = configGetDouble("loadEventDB"); } catch ( ... ) {} return true; } void createCommandLineDescription() { Kicker<MainFrame>::createCommandLineDescription(); commandline().addGroup("Options"); commandline().addOption("Options", "origin,O", "Preload origin", &_originID); commandline().addOption("Options", "event,E", "Preload event", &_eventID); commandline().addOption("Options", "offline", "Switch to offline mode"); commandline().addOption("Options", "load-event-db", "Number of days to load from database", &_preloadDays); } bool validateParameters() { if ( !Kicker<MainFrame>::validateParameters() ) return false; if ( commandline().hasOption("offline") ) { setMessagingEnabled(false); if ( !isInventoryDatabaseEnabled() ) setDatabaseEnabled(false, false); } return true; } void setupUi(MainFrame* w) { if ( commandline().hasOption("offline") ) w->setOffline(true); else if ( !_eventID.empty() ) w->setEventID(_eventID); else if ( !_originID.empty() ) w->setOriginID(_originID); else w->loadEvents(_preloadDays); } private: std::string _originID; std::string _eventID; float _preloadDays; }; int main(int argc, char** argv) { int retCode; { OLVApp app(argc, argv, Application::DEFAULT | Application::LOAD_INVENTORY | Application::LOAD_CONFIGMODULE); app.setPrimaryMessagingGroup("LOCATION"); app.addMessagingSubscription("EVENT"); app.addMessagingSubscription("LOCATION"); app.addMessagingSubscription("FOCMECH"); app.addMessagingSubscription("MAGNITUDE"); app.addMessagingSubscription("PICK"); app.addMessagingSubscription("CONFIG"); app.addMessagingSubscription("GUI"); retCode = app(); SEISCOMP_DEBUG("Number of remaining objects before destroying application: %d", Seiscomp::Core::BaseObject::ObjectCount()); } SEISCOMP_DEBUG("Number of remaining objects after destroying application: %d", Seiscomp::Core::BaseObject::ObjectCount()); return retCode; }
%include "const.inc" %include "config.inc" org 0x90000 [bits 16] align 16 entry: mov ax, cs mov ds, ax mov ss, ax mov sp, 0 mov ax, 0xb800 mov es, ax ;show 'LOADER' mov byte [es:160+0],'L' mov byte [es:160+1],0x07 mov byte [es:160+2],'O' mov byte [es:160+3],0x07 mov byte [es:160+4],'A' mov byte [es:160+5],0x07 mov byte [es:160+6],'D' mov byte [es:160+7],0x07 mov byte [es:160+8],'E' mov byte [es:160+9],0x07 mov byte [es:160+10],'R' mov byte [es:160+11],0x07 call load_setup_file call load_kernel_file %ifdef CONFIG_BOOT_FLOPPY call stop_floppy_motor %endif call get_memory_info %ifdef KERN_VBE_MODE call get_vbe_info %endif jmp set_protect_mode ;保护模式设置的步骤为 ;1.关闭中断,防止中间发生中断,因为保护模式中断和实模式中断的方式不一样 ;2.加载gdt,保护模式进行内存访问需要用到gdt里面定义的数据结构 ;3.打开A20总线,使得可以访问1MB以上的内存空间 ;4.设置cr0的最低1位位1,就是切换成保护模式 ;5.执行一个远跳转,清空cpu流水线 set_protect_mode: cli ;close the interruption lgdt [gdt_reg] ;enable A20 line in al,0x92 or al,2 out 0x92,al ; enable protect mode mov eax,cr0 or eax,1 mov cr0,eax ;far jump:to clean the flush line jmp dword 0x08:flush load_setup_file: mov ax, SETUP_SEG mov dx, 0 mov si, SETUP_OFF mov cx, SETUP_CNTS xor bx, bx call read_sectors ret load_kernel_file: mov ax, KERNEL_SEG mov si, KERNEL_OFF mov dx, 0 mov cx, DISK_BLOCK_SIZE xor bx, bx mov di, 16 ; 内核占用512kb,每次加载64扇区(32kb),因此需要加载16次 .replay: call read_sectors add ax, 0x800 add si, DISK_BLOCK_SIZE dec di cmp di, 0 ja .replay ret %ifdef CONFIG_BOOT_FLOPPY ; function: read a sector data from floppy ; @input: ; es: dx -> buffer seg: off ; si -> lba floppy_read_sector: push ax push cx push dx push bx mov ax, si xor dx, dx mov bx, 18 div bx inc dx mov cl, dl xor dx, dx mov bx, 2 div bx mov dh, dl xor dl, dl mov ch, al pop bx .1: mov al, 0x01 mov ah, 0x02 int 0x13 jc .1 pop dx pop cx pop ax ret %endif %ifdef CONFIG_BOOT_HARDDISK align 4 DAP: ; disk address packet db 0x10 ; [0]: packet size in bytes db 0 ; [1]: reserved, must be 0 db 0 ; [2]: nr of blocks to transfer (0~127) db 0 ; [3]: reserved, must be 0 dw 0 ; [4]: buf addr(offset) dw 0 ; [6]: buf addr(seg) dd 0 ; [8]: lba. low 32-bit dd 0 ; [12]: lba. high 32-bit ; function: read a sector data from harddisk ; @input: ; ax: dx -> buffer seg: off ; si -> lba low 32 bits harddisk_read_sector: push ax push bx push cx push dx push si mov word [DAP + 2], 1 ; count mov word [DAP + 4], dx ; offset mov word [DAP + 6], ax ; segment mov word [DAP + 8], si ; lba low 32 bits mov dword [DAP + 12], 0 ; lba high 32 bits xor bx, bx mov ah, 0x42 mov dl, 0x80 mov si, DAP int 0x13 pop si pop dx pop cx pop bx pop ax ret %endif read_sectors: push ax push bx push cx push dx push si push di push es .reply: %ifdef CONFIG_BOOT_HARDDISK call harddisk_read_sector add ax, 0x20 ; next buffer %endif %ifdef CONFIG_BOOT_FLOPPY mov es, ax call floppy_read_sector add bx, 512 ; next buffer %endif inc si ; next lba loop .reply pop es pop di pop si pop dx pop cx pop bx pop ax ret %ifdef CONFIG_BOOT_FLOPPY stop_floppy_motor: push dx mov dx, 03F2h mov al, 0 out dx, al pop dx ret %endif get_memory_info: mov ax, ARDS_SEG mov es, ax mov ebx, 0 ; ebx = 后续值, 开始时需为 0 mov di, 4 ; es:di 指向一个地址范围描述符结构(Address Range Descriptor Structure) .mem_loop: mov eax, 0E820h ; eax = 0000E820h mov ecx, 20 ; ecx = 地址范围描述符结构的大小 mov edx, 0534D4150h ; edx = 'SMAP' int 15h jc .mem_failed add di, 20 inc dword [es:0] cmp ebx, 0 jne .mem_loop jmp .mem_ok .mem_failed: mov dword [es:0], 0 .mem_ok: ret %ifdef KERN_VBE_MODE ; 使用的分辨率 ;VBE_MODE EQU VMODE_800_600_32 ;VBE_MODE EQU VMODE_1920_1080_16 VBE_MODE EQU VMODE_1024_768_16 ;VBE_MODE EQU VMODE_800_600_32 get_vbe_info: push ds ;获取VBE信息块 ; Input: AX=4F00H ; ES:DI=储存信息块的缓冲区 ; Output: AX=VBE return status mov ax, VBE_INFO_SEG mov es, ax mov di, 0 mov ax, VBE_CMD_VBEINFO ;检查VBE存在功能,指定ax=0x4f00 int 0x10 ;ax=0x004f 获取成功 cmp ax, 0x004f jne .vbe_error ;检查VBE版本,必须是VBE 2.0及其以上 mov ax, [es:di + 4] cmp ax, 0x0200 ; VBE2.0的BCD码是0x200 jb .vbe_error ; if (ax < 0x0200) goto screen_default ;获取画面信息, 256字节 ;cx=输入检查的模式 ; 获取VBE模式 ; Input: AX=4F01H ; CX=模式号 ; ES:DI=储存模式块的缓冲区 ; Output: AX=VBE return status mov ax, VBE_MODE_SEG mov es, ax mov cx, VBE_MODE ;cx=模式号 mov ax, 0x4f01 ;获取画面模式功能,指定ax=0x4f01 int 0x10 cmp ax, 0x004f ;ax=0x004f 指定的这种模式可以使用 jne .vbe_error %ifdef KERN_VBE_MODE ;切换到指定的模式 mov bx, VBE_MODE + 0x4000 ;bx=模式号和属性 mov ax, 0x4f02 ;切换模式模式功能,指定ax=0x4f01 int 0x10 %endif ;由于初始化图形模式改变了ds的值,这里设置和cs一样 mov ax, cs mov ds, ax jmp .finish .vbe_error: mov ax, 0xb800 mov es, ax ; 第3排显示 error mov byte [es:160*24+0],'N' mov byte [es:160*24+1],0x04 mov byte [es:160*24+2],'O' mov byte [es:160*24+3],0x04 mov byte [es:160*24+4],' ' mov byte [es:160*24+5],0x04 mov byte [es:160*24+6],'V' mov byte [es:160*24+7],0x04 mov byte [es:160*24+8],'B' mov byte [es:160*24+9],0x04 mov byte [es:160*24+10],'E' mov byte [es:160*24+11],0x04 hlt jmp $ .finish: pop ds ret %endif ;Global Descriptor Table(GDT) gdt_table: dd 0x00000000 dd 0x00000000 dd 0x0000ffff dd 0x00cf9A00 dd 0x0000ffff dd 0x00cf9200 gdt_length equ $ - gdt_table gdt_reg: dw (gdt_length-1) dd gdt_table [bits 32] align 32 flush: mov ax, 0x10 ;the data selector mov ds, ax mov es, ax mov fs, ax mov gs, ax mov ss, ax mov esp, LOADER_STACK_TOP jmp 0x08: SETUP_ADDR ;pad loader to 4kb times (4096-($-$$)) db 0
/** * Autogenerated by Thrift for src/module.thrift * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ #pragma once #include "thrift/compiler/test/fixtures/templated-deserialize/gen-cpp2/module_types.h" #include <thrift/lib/cpp2/gen/module_types_tcc.h> namespace cpp2 { } // cpp2 namespace std { } // std namespace apache { namespace thrift { namespace detail { template <> struct TccStructTraits<::cpp2::SmallStruct> { static void translateFieldName( folly::StringPiece _fname, int16_t& fid, apache::thrift::protocol::TType& _ftype) noexcept; }; template <> struct TccStructTraits<::cpp2::containerStruct> { static void translateFieldName( folly::StringPiece _fname, int16_t& fid, apache::thrift::protocol::TType& _ftype) noexcept; }; } // namespace detail } // namespace thrift } // namespace apache namespace cpp2 { template <class Protocol_> void SmallStruct::readNoXfer(Protocol_* iprot) { apache::thrift::detail::ProtocolReaderStructReadState<Protocol_> _readState; _readState.readStructBegin(iprot); using apache::thrift::TProtocolException; if (UNLIKELY(!_readState.advanceToNextField( iprot, 0, 1, apache::thrift::protocol::T_BOOL))) { goto _loop; } _readField_small_A: { ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::readWithContext(*iprot, this->small_A, _readState); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.small_A = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 1, 2, apache::thrift::protocol::T_I32))) { goto _loop; } _readField_small_B: { ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int32_t>::readWithContext(*iprot, this->small_B, _readState); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.small_B = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 2, 0, apache::thrift::protocol::T_STOP))) { goto _loop; } _end: _readState.readStructEnd(iprot); return; _loop: _readState.afterAdvanceFailure(iprot); if (_readState.atStop()) { goto _end; } if (iprot->kUsesFieldNames()) { _readState.template fillFieldTraitsFromName<apache::thrift::detail::TccStructTraits<SmallStruct>>(); } switch (_readState.fieldId) { case 1: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_BOOL))) { goto _readField_small_A; } else { goto _skip; } } case 2: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_I32))) { goto _readField_small_B; } else { goto _skip; } } default: { _skip: _readState.skip(iprot); _readState.readFieldEnd(iprot); _readState.readFieldBeginNoInline(iprot); goto _loop; } } } template <class Protocol_> uint32_t SmallStruct::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedFieldSize("small_A", apache::thrift::protocol::T_BOOL, 1); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::serializedSize<false>(*prot_, this->small_A); xfer += prot_->serializedFieldSize("small_B", apache::thrift::protocol::T_I32, 2); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int32_t>::serializedSize<false>(*prot_, this->small_B); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t SmallStruct::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedFieldSize("small_A", apache::thrift::protocol::T_BOOL, 1); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::serializedSize<false>(*prot_, this->small_A); xfer += prot_->serializedFieldSize("small_B", apache::thrift::protocol::T_I32, 2); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int32_t>::serializedSize<false>(*prot_, this->small_B); xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t SmallStruct::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("SmallStruct"); xfer += prot_->writeFieldBegin("small_A", apache::thrift::protocol::T_BOOL, 1); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::write(*prot_, this->small_A); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("small_B", apache::thrift::protocol::T_I32, 2); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, ::std::int32_t>::write(*prot_, this->small_B); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } extern template void SmallStruct::readNoXfer<>(apache::thrift::BinaryProtocolReader*); extern template uint32_t SmallStruct::write<>(apache::thrift::BinaryProtocolWriter*) const; extern template uint32_t SmallStruct::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; extern template uint32_t SmallStruct::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; extern template void SmallStruct::readNoXfer<>(apache::thrift::CompactProtocolReader*); extern template uint32_t SmallStruct::write<>(apache::thrift::CompactProtocolWriter*) const; extern template uint32_t SmallStruct::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; extern template uint32_t SmallStruct::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; } // cpp2 namespace cpp2 { template <class Protocol_> void containerStruct::readNoXfer(Protocol_* iprot) { apache::thrift::detail::ProtocolReaderStructReadState<Protocol_> _readState; _readState.readStructBegin(iprot); using apache::thrift::TProtocolException; if (UNLIKELY(!_readState.advanceToNextField( iprot, 0, 1, apache::thrift::protocol::T_BOOL))) { goto _loop; } _readField_fieldA: { ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::readWithContext(*iprot, this->fieldA, _readState); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldA = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 1, 2, apache::thrift::protocol::T_MAP))) { goto _loop; } _readField_fieldB: { _readState.beforeSubobject(iprot); this->fieldB = ::std::map<::std::string, bool>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, bool>>::readWithContext(*iprot, this->fieldB, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldB = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 2, 3, apache::thrift::protocol::T_SET))) { goto _loop; } _readField_fieldC: { _readState.beforeSubobject(iprot); this->fieldC = ::std::set<::std::int32_t>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>, ::std::set<::std::int32_t>>::readWithContext(*iprot, this->fieldC, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldC = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 3, 4, apache::thrift::protocol::T_STRING))) { goto _loop; } _readField_fieldD: { ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->fieldD, _readState); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldD = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 4, 5, apache::thrift::protocol::T_STRING))) { goto _loop; } _readField_fieldE: { ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::readWithContext(*iprot, this->fieldE, _readState); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldE = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 5, 6, apache::thrift::protocol::T_LIST))) { goto _loop; } _readField_fieldF: { _readState.beforeSubobject(iprot); this->fieldF = ::std::vector<::std::vector<::std::vector<::std::int32_t>>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>, ::std::vector<::std::vector<::std::vector<::std::int32_t>>>>::readWithContext(*iprot, this->fieldF, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldF = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 6, 7, apache::thrift::protocol::T_MAP))) { goto _loop; } _readField_fieldG: { _readState.beforeSubobject(iprot); this->fieldG = ::std::map<::std::string, ::std::map<::std::string, ::std::map<::std::string, ::std::int32_t>>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>>>, ::std::map<::std::string, ::std::map<::std::string, ::std::map<::std::string, ::std::int32_t>>>>::readWithContext(*iprot, this->fieldG, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldG = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 7, 8, apache::thrift::protocol::T_LIST))) { goto _loop; } _readField_fieldH: { _readState.beforeSubobject(iprot); this->fieldH = ::std::vector<::std::set<::std::int32_t>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>>, ::std::vector<::std::set<::std::int32_t>>>::readWithContext(*iprot, this->fieldH, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldH = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 8, 9, apache::thrift::protocol::T_BOOL))) { goto _loop; } _readField_fieldI: { ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::readWithContext(*iprot, this->fieldI, _readState); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldI = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 9, 10, apache::thrift::protocol::T_MAP))) { goto _loop; } _readField_fieldJ: { _readState.beforeSubobject(iprot); this->fieldJ = ::std::map<::std::string, ::std::vector<::std::int32_t>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::std::map<::std::string, ::std::vector<::std::int32_t>>>::readWithContext(*iprot, this->fieldJ, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldJ = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 10, 11, apache::thrift::protocol::T_LIST))) { goto _loop; } _readField_fieldK: { _readState.beforeSubobject(iprot); this->fieldK = ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>>, ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>>::readWithContext(*iprot, this->fieldK, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldK = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 11, 12, apache::thrift::protocol::T_SET))) { goto _loop; } _readField_fieldL: { _readState.beforeSubobject(iprot); this->fieldL = ::std::set<::std::set<::std::set<bool>>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::set<::apache::thrift::type_class::set<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>>>, ::std::set<::std::set<::std::set<bool>>>>::readWithContext(*iprot, this->fieldL, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldL = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 12, 13, apache::thrift::protocol::T_MAP))) { goto _loop; } _readField_fieldM: { _readState.beforeSubobject(iprot); this->fieldM = ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::set<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::apache::thrift::type_class::map<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::string>>, ::apache::thrift::type_class::string>>, ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>>::readWithContext(*iprot, this->fieldM, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldM = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 13, 14, apache::thrift::protocol::T_LIST))) { goto _loop; } _readField_fieldN: { _readState.beforeSubobject(iprot); this->fieldN = ::std::vector<::cpp2::IndirectionA>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::integral, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionA>>::readWithContext(*iprot, this->fieldN, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldN = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 14, 15, apache::thrift::protocol::T_LIST))) { goto _loop; } _readField_fieldO: { _readState.beforeSubobject(iprot); this->fieldO = ::std::vector<::cpp2::IndirectionB>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::floating_point, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionB>>::readWithContext(*iprot, this->fieldO, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldO = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 15, 16, apache::thrift::protocol::T_LIST))) { goto _loop; } _readField_fieldP: { _readState.beforeSubobject(iprot); this->fieldP = ::std::vector<::cpp2::IndirectionC>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::integral, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionC>>::readWithContext(*iprot, this->fieldP, _readState); _readState.afterSubobject(iprot); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldP = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 16, 17, apache::thrift::protocol::T_I32))) { goto _loop; } _readField_fieldQ: { ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::enumeration, ::cpp2::MyEnumA>::readWithContext(*iprot, this->fieldQ, _readState); THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN this->__isset.fieldQ = true; THRIFT_IGNORE_ISSET_USE_WARNING_END } if (UNLIKELY(!_readState.advanceToNextField( iprot, 17, 18, apache::thrift::protocol::T_MAP))) { goto _loop; } _readField_fieldR: { _readState.beforeSubobject(iprot); auto ptr = ::apache::thrift::detail::make_mutable_smart_ptr<::std::unique_ptr<::std::map<::std::string, bool>>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, bool>>::readWithContext(*iprot, *ptr, _readState); this->fieldR = std::move(ptr); _readState.afterSubobject(iprot); } if (UNLIKELY(!_readState.advanceToNextField( iprot, 18, 19, apache::thrift::protocol::T_STRUCT))) { goto _loop; } _readField_fieldS: { _readState.beforeSubobject(iprot); auto ptr = ::apache::thrift::detail::make_mutable_smart_ptr<::std::unique_ptr<::cpp2::SmallStruct>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::readWithContext(*iprot, *ptr, _readState); this->fieldS = std::move(ptr); _readState.afterSubobject(iprot); } if (UNLIKELY(!_readState.advanceToNextField( iprot, 19, 20, apache::thrift::protocol::T_STRUCT))) { goto _loop; } _readField_fieldT: { _readState.beforeSubobject(iprot); auto ptr = ::apache::thrift::detail::make_mutable_smart_ptr<::std::shared_ptr<::cpp2::SmallStruct>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::readWithContext(*iprot, *ptr, _readState); this->fieldT = std::move(ptr); _readState.afterSubobject(iprot); } if (UNLIKELY(!_readState.advanceToNextField( iprot, 20, 21, apache::thrift::protocol::T_STRUCT))) { goto _loop; } _readField_fieldU: { _readState.beforeSubobject(iprot); auto ptr = ::apache::thrift::detail::make_mutable_smart_ptr<::std::shared_ptr<const ::cpp2::SmallStruct>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::readWithContext(*iprot, *ptr, _readState); this->fieldU = std::move(ptr); _readState.afterSubobject(iprot); } if (UNLIKELY(!_readState.advanceToNextField( iprot, 21, 23, apache::thrift::protocol::T_STRUCT))) { goto _loop; } _readField_fieldX: { _readState.beforeSubobject(iprot); auto ptr = ::apache::thrift::detail::make_mutable_smart_ptr<::std::unique_ptr<::cpp2::SmallStruct>>(); ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::readWithContext(*iprot, *ptr, _readState); this->fieldX = std::move(ptr); _readState.afterSubobject(iprot); } if (UNLIKELY(!_readState.advanceToNextField( iprot, 23, 0, apache::thrift::protocol::T_STOP))) { goto _loop; } _end: _readState.readStructEnd(iprot); return; _loop: _readState.afterAdvanceFailure(iprot); if (_readState.atStop()) { goto _end; } if (iprot->kUsesFieldNames()) { _readState.template fillFieldTraitsFromName<apache::thrift::detail::TccStructTraits<containerStruct>>(); } switch (_readState.fieldId) { case 1: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_BOOL))) { goto _readField_fieldA; } else { goto _skip; } } case 2: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_MAP))) { goto _readField_fieldB; } else { goto _skip; } } case 3: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_SET))) { goto _readField_fieldC; } else { goto _skip; } } case 4: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) { goto _readField_fieldD; } else { goto _skip; } } case 5: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRING))) { goto _readField_fieldE; } else { goto _skip; } } case 6: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_LIST))) { goto _readField_fieldF; } else { goto _skip; } } case 7: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_MAP))) { goto _readField_fieldG; } else { goto _skip; } } case 8: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_LIST))) { goto _readField_fieldH; } else { goto _skip; } } case 9: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_BOOL))) { goto _readField_fieldI; } else { goto _skip; } } case 10: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_MAP))) { goto _readField_fieldJ; } else { goto _skip; } } case 11: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_LIST))) { goto _readField_fieldK; } else { goto _skip; } } case 12: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_SET))) { goto _readField_fieldL; } else { goto _skip; } } case 13: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_MAP))) { goto _readField_fieldM; } else { goto _skip; } } case 14: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_LIST))) { goto _readField_fieldN; } else { goto _skip; } } case 15: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_LIST))) { goto _readField_fieldO; } else { goto _skip; } } case 16: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_LIST))) { goto _readField_fieldP; } else { goto _skip; } } case 17: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_I32))) { goto _readField_fieldQ; } else { goto _skip; } } case 18: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_MAP))) { goto _readField_fieldR; } else { goto _skip; } } case 19: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRUCT))) { goto _readField_fieldS; } else { goto _skip; } } case 20: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRUCT))) { goto _readField_fieldT; } else { goto _skip; } } case 21: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRUCT))) { goto _readField_fieldU; } else { goto _skip; } } case 23: { if (LIKELY(_readState.isCompatibleWithType(iprot, apache::thrift::protocol::T_STRUCT))) { goto _readField_fieldX; } else { goto _skip; } } default: { _skip: _readState.skip(iprot); _readState.readFieldEnd(iprot); _readState.readFieldBeginNoInline(iprot); goto _loop; } } } template <class Protocol_> uint32_t containerStruct::serializedSize(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("containerStruct"); xfer += prot_->serializedFieldSize("fieldA", apache::thrift::protocol::T_BOOL, 1); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::serializedSize<false>(*prot_, this->fieldA); xfer += prot_->serializedFieldSize("fieldB", apache::thrift::protocol::T_MAP, 2); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, bool>>::serializedSize<false>(*prot_, this->fieldB); xfer += prot_->serializedFieldSize("fieldC", apache::thrift::protocol::T_SET, 3); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>, ::std::set<::std::int32_t>>::serializedSize<false>(*prot_, this->fieldC); xfer += prot_->serializedFieldSize("fieldD", apache::thrift::protocol::T_STRING, 4); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->fieldD); xfer += prot_->serializedFieldSize("fieldE", apache::thrift::protocol::T_STRING, 5); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->fieldE); xfer += prot_->serializedFieldSize("fieldF", apache::thrift::protocol::T_LIST, 6); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>, ::std::vector<::std::vector<::std::vector<::std::int32_t>>>>::serializedSize<false>(*prot_, this->fieldF); xfer += prot_->serializedFieldSize("fieldG", apache::thrift::protocol::T_MAP, 7); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>>>, ::std::map<::std::string, ::std::map<::std::string, ::std::map<::std::string, ::std::int32_t>>>>::serializedSize<false>(*prot_, this->fieldG); xfer += prot_->serializedFieldSize("fieldH", apache::thrift::protocol::T_LIST, 8); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>>, ::std::vector<::std::set<::std::int32_t>>>::serializedSize<false>(*prot_, this->fieldH); xfer += prot_->serializedFieldSize("fieldI", apache::thrift::protocol::T_BOOL, 9); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::serializedSize<false>(*prot_, this->fieldI); xfer += prot_->serializedFieldSize("fieldJ", apache::thrift::protocol::T_MAP, 10); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::std::map<::std::string, ::std::vector<::std::int32_t>>>::serializedSize<false>(*prot_, this->fieldJ); xfer += prot_->serializedFieldSize("fieldK", apache::thrift::protocol::T_LIST, 11); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>>, ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>>::serializedSize<false>(*prot_, this->fieldK); xfer += prot_->serializedFieldSize("fieldL", apache::thrift::protocol::T_SET, 12); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::set<::apache::thrift::type_class::set<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>>>, ::std::set<::std::set<::std::set<bool>>>>::serializedSize<false>(*prot_, this->fieldL); xfer += prot_->serializedFieldSize("fieldM", apache::thrift::protocol::T_MAP, 13); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::set<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::apache::thrift::type_class::map<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::string>>, ::apache::thrift::type_class::string>>, ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>>::serializedSize<false>(*prot_, this->fieldM); xfer += prot_->serializedFieldSize("fieldN", apache::thrift::protocol::T_LIST, 14); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::integral, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionA>>::serializedSize<false>(*prot_, this->fieldN); xfer += prot_->serializedFieldSize("fieldO", apache::thrift::protocol::T_LIST, 15); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::floating_point, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionB>>::serializedSize<false>(*prot_, this->fieldO); xfer += prot_->serializedFieldSize("fieldP", apache::thrift::protocol::T_LIST, 16); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::integral, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionC>>::serializedSize<false>(*prot_, this->fieldP); xfer += prot_->serializedFieldSize("fieldQ", apache::thrift::protocol::T_I32, 17); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::enumeration, ::cpp2::MyEnumA>::serializedSize<false>(*prot_, this->fieldQ); xfer += prot_->serializedFieldSize("fieldR", apache::thrift::protocol::T_MAP, 18); if (this->fieldR) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, bool>>::serializedSize<false>(*prot_, *this->fieldR); } else { xfer += prot_->serializedSizeMapBegin(apache::thrift::protocol::T_STRING, apache::thrift::protocol::T_BOOL, 0); xfer += prot_->serializedSizeMapEnd(); } xfer += prot_->serializedFieldSize("fieldS", apache::thrift::protocol::T_STRUCT, 19); if (this->fieldS) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::serializedSize<false>(*prot_, *this->fieldS); } else { xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedSizeStop(); } xfer += prot_->serializedFieldSize("fieldT", apache::thrift::protocol::T_STRUCT, 20); if (this->fieldT) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::serializedSize<false>(*prot_, *this->fieldT); } else { xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedSizeStop(); } xfer += prot_->serializedFieldSize("fieldU", apache::thrift::protocol::T_STRUCT, 21); if (this->fieldU) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::serializedSize<false>(*prot_, *this->fieldU); } else { xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedSizeStop(); } xfer += prot_->serializedFieldSize("fieldX", apache::thrift::protocol::T_STRUCT, 23); if (this->fieldX) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::serializedSize<false>(*prot_, *this->fieldX); } else { xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedSizeStop(); } xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t containerStruct::serializedSizeZC(Protocol_ const* prot_) const { uint32_t xfer = 0; xfer += prot_->serializedStructSize("containerStruct"); xfer += prot_->serializedFieldSize("fieldA", apache::thrift::protocol::T_BOOL, 1); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::serializedSize<false>(*prot_, this->fieldA); xfer += prot_->serializedFieldSize("fieldB", apache::thrift::protocol::T_MAP, 2); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, bool>>::serializedSize<false>(*prot_, this->fieldB); xfer += prot_->serializedFieldSize("fieldC", apache::thrift::protocol::T_SET, 3); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>, ::std::set<::std::int32_t>>::serializedSize<false>(*prot_, this->fieldC); xfer += prot_->serializedFieldSize("fieldD", apache::thrift::protocol::T_STRING, 4); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->fieldD); xfer += prot_->serializedFieldSize("fieldE", apache::thrift::protocol::T_STRING, 5); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::serializedSize<false>(*prot_, this->fieldE); xfer += prot_->serializedFieldSize("fieldF", apache::thrift::protocol::T_LIST, 6); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>, ::std::vector<::std::vector<::std::vector<::std::int32_t>>>>::serializedSize<false>(*prot_, this->fieldF); xfer += prot_->serializedFieldSize("fieldG", apache::thrift::protocol::T_MAP, 7); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>>>, ::std::map<::std::string, ::std::map<::std::string, ::std::map<::std::string, ::std::int32_t>>>>::serializedSize<false>(*prot_, this->fieldG); xfer += prot_->serializedFieldSize("fieldH", apache::thrift::protocol::T_LIST, 8); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>>, ::std::vector<::std::set<::std::int32_t>>>::serializedSize<false>(*prot_, this->fieldH); xfer += prot_->serializedFieldSize("fieldI", apache::thrift::protocol::T_BOOL, 9); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::serializedSize<false>(*prot_, this->fieldI); xfer += prot_->serializedFieldSize("fieldJ", apache::thrift::protocol::T_MAP, 10); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::std::map<::std::string, ::std::vector<::std::int32_t>>>::serializedSize<false>(*prot_, this->fieldJ); xfer += prot_->serializedFieldSize("fieldK", apache::thrift::protocol::T_LIST, 11); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>>, ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>>::serializedSize<false>(*prot_, this->fieldK); xfer += prot_->serializedFieldSize("fieldL", apache::thrift::protocol::T_SET, 12); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::set<::apache::thrift::type_class::set<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>>>, ::std::set<::std::set<::std::set<bool>>>>::serializedSize<false>(*prot_, this->fieldL); xfer += prot_->serializedFieldSize("fieldM", apache::thrift::protocol::T_MAP, 13); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::set<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::apache::thrift::type_class::map<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::string>>, ::apache::thrift::type_class::string>>, ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>>::serializedSize<false>(*prot_, this->fieldM); xfer += prot_->serializedFieldSize("fieldN", apache::thrift::protocol::T_LIST, 14); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::integral, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionA>>::serializedSize<false>(*prot_, this->fieldN); xfer += prot_->serializedFieldSize("fieldO", apache::thrift::protocol::T_LIST, 15); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::floating_point, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionB>>::serializedSize<false>(*prot_, this->fieldO); xfer += prot_->serializedFieldSize("fieldP", apache::thrift::protocol::T_LIST, 16); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::integral, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionC>>::serializedSize<false>(*prot_, this->fieldP); xfer += prot_->serializedFieldSize("fieldQ", apache::thrift::protocol::T_I32, 17); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::enumeration, ::cpp2::MyEnumA>::serializedSize<false>(*prot_, this->fieldQ); xfer += prot_->serializedFieldSize("fieldR", apache::thrift::protocol::T_MAP, 18); if (this->fieldR) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, bool>>::serializedSize<false>(*prot_, *this->fieldR); } else { xfer += prot_->serializedSizeMapBegin(apache::thrift::protocol::T_STRING, apache::thrift::protocol::T_BOOL, 0); xfer += prot_->serializedSizeMapEnd(); } xfer += prot_->serializedFieldSize("fieldS", apache::thrift::protocol::T_STRUCT, 19); if (this->fieldS) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::serializedSize<true>(*prot_, *this->fieldS); } else { xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedSizeStop(); } xfer += prot_->serializedFieldSize("fieldT", apache::thrift::protocol::T_STRUCT, 20); if (this->fieldT) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::serializedSize<true>(*prot_, *this->fieldT); } else { xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedSizeStop(); } xfer += prot_->serializedFieldSize("fieldU", apache::thrift::protocol::T_STRUCT, 21); if (this->fieldU) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::serializedSize<true>(*prot_, *this->fieldU); } else { xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedSizeStop(); } xfer += prot_->serializedFieldSize("fieldX", apache::thrift::protocol::T_STRUCT, 23); if (this->fieldX) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::serializedSize<true>(*prot_, *this->fieldX); } else { xfer += prot_->serializedStructSize("SmallStruct"); xfer += prot_->serializedSizeStop(); } xfer += prot_->serializedSizeStop(); return xfer; } template <class Protocol_> uint32_t containerStruct::write(Protocol_* prot_) const { uint32_t xfer = 0; xfer += prot_->writeStructBegin("containerStruct"); xfer += prot_->writeFieldBegin("fieldA", apache::thrift::protocol::T_BOOL, 1); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::write(*prot_, this->fieldA); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldB", apache::thrift::protocol::T_MAP, 2); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, bool>>::write(*prot_, this->fieldB); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldC", apache::thrift::protocol::T_SET, 3); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>, ::std::set<::std::int32_t>>::write(*prot_, this->fieldC); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldD", apache::thrift::protocol::T_STRING, 4); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->fieldD); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldE", apache::thrift::protocol::T_STRING, 5); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::string, ::std::string>::write(*prot_, this->fieldE); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldF", apache::thrift::protocol::T_LIST, 6); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>, ::std::vector<::std::vector<::std::vector<::std::int32_t>>>>::write(*prot_, this->fieldF); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldG", apache::thrift::protocol::T_MAP, 7); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>>>, ::std::map<::std::string, ::std::map<::std::string, ::std::map<::std::string, ::std::int32_t>>>>::write(*prot_, this->fieldG); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldH", apache::thrift::protocol::T_LIST, 8); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>>, ::std::vector<::std::set<::std::int32_t>>>::write(*prot_, this->fieldH); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldI", apache::thrift::protocol::T_BOOL, 9); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::integral, bool>::write(*prot_, this->fieldI); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldJ", apache::thrift::protocol::T_MAP, 10); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::std::map<::std::string, ::std::vector<::std::int32_t>>>::write(*prot_, this->fieldJ); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldK", apache::thrift::protocol::T_LIST, 11); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>>>, ::std::vector<::std::vector<::std::vector<::std::vector<::std::int32_t>>>>>::write(*prot_, this->fieldK); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldL", apache::thrift::protocol::T_SET, 12); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::set<::apache::thrift::type_class::set<::apache::thrift::type_class::set<::apache::thrift::type_class::integral>>>, ::std::set<::std::set<::std::set<bool>>>>::write(*prot_, this->fieldL); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldM", apache::thrift::protocol::T_MAP, 13); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::set<::apache::thrift::type_class::list<::apache::thrift::type_class::integral>>, ::apache::thrift::type_class::map<::apache::thrift::type_class::list<::apache::thrift::type_class::set<::apache::thrift::type_class::string>>, ::apache::thrift::type_class::string>>, ::std::map<::std::set<::std::vector<::std::int32_t>>, ::std::map<::std::vector<::std::set<::std::string>>, ::std::string>>>::write(*prot_, this->fieldM); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldN", apache::thrift::protocol::T_LIST, 14); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::integral, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionA>>::write(*prot_, this->fieldN); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldO", apache::thrift::protocol::T_LIST, 15); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::floating_point, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionB>>::write(*prot_, this->fieldO); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldP", apache::thrift::protocol::T_LIST, 16); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::list<::apache::thrift::detail::indirection_tag<::apache::thrift::type_class::integral, ::apache::thrift::detail::apply_indirection_fn>>, ::std::vector<::cpp2::IndirectionC>>::write(*prot_, this->fieldP); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldQ", apache::thrift::protocol::T_I32, 17); xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::enumeration, ::cpp2::MyEnumA>::write(*prot_, this->fieldQ); xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldR", apache::thrift::protocol::T_MAP, 18); if (this->fieldR) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::map<::apache::thrift::type_class::string, ::apache::thrift::type_class::integral>, ::std::map<::std::string, bool>>::write(*prot_, *this->fieldR); } else { xfer += prot_->writeMapBegin(apache::thrift::protocol::T_STRING, apache::thrift::protocol::T_BOOL, 0); xfer += prot_->writeMapEnd(); } xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldS", apache::thrift::protocol::T_STRUCT, 19); if (this->fieldS) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::write(*prot_, *this->fieldS); } else { xfer += prot_->writeStructBegin("SmallStruct"); xfer += prot_->writeStructEnd(); xfer += prot_->writeFieldStop(); } xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldT", apache::thrift::protocol::T_STRUCT, 20); if (this->fieldT) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::write(*prot_, *this->fieldT); } else { xfer += prot_->writeStructBegin("SmallStruct"); xfer += prot_->writeStructEnd(); xfer += prot_->writeFieldStop(); } xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldU", apache::thrift::protocol::T_STRUCT, 21); if (this->fieldU) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::write(*prot_, *this->fieldU); } else { xfer += prot_->writeStructBegin("SmallStruct"); xfer += prot_->writeStructEnd(); xfer += prot_->writeFieldStop(); } xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldBegin("fieldX", apache::thrift::protocol::T_STRUCT, 23); if (this->fieldX) { xfer += ::apache::thrift::detail::pm::protocol_methods<::apache::thrift::type_class::structure, ::cpp2::SmallStruct>::write(*prot_, *this->fieldX); } else { xfer += prot_->writeStructBegin("SmallStruct"); xfer += prot_->writeStructEnd(); xfer += prot_->writeFieldStop(); } xfer += prot_->writeFieldEnd(); xfer += prot_->writeFieldStop(); xfer += prot_->writeStructEnd(); return xfer; } extern template void containerStruct::readNoXfer<>(apache::thrift::BinaryProtocolReader*); extern template uint32_t containerStruct::write<>(apache::thrift::BinaryProtocolWriter*) const; extern template uint32_t containerStruct::serializedSize<>(apache::thrift::BinaryProtocolWriter const*) const; extern template uint32_t containerStruct::serializedSizeZC<>(apache::thrift::BinaryProtocolWriter const*) const; extern template void containerStruct::readNoXfer<>(apache::thrift::CompactProtocolReader*); extern template uint32_t containerStruct::write<>(apache::thrift::CompactProtocolWriter*) const; extern template uint32_t containerStruct::serializedSize<>(apache::thrift::CompactProtocolWriter const*) const; extern template uint32_t containerStruct::serializedSizeZC<>(apache::thrift::CompactProtocolWriter const*) const; } // cpp2
; build a new map on diskette newmap newmpv jsr clnbam ldy #0 lda #18 ; set link to 18.1 sta (bmpnt),y iny tya sta (bmpnt),y iny iny iny ; .y=4 nm10 lda #0 ; clear track map sta t0 sta t1 sta t2 tya ; 4=>1 lsr a lsr a ; .a=track # jsr maxsec ; store blks free byte away sta (bmpnt),y iny tax nm20 sec ; set map bits rol t0 ; t0 t1 t2 rol t1 ; 76543210 111111 xxx21111 rol t2 ; 54321098 09876 dex ; 11111111 11111111 11111 bne nm20 nm30 ; .x=0 lda t0,x sta (bmpnt),y ; write out bit map iny inx cpx #3 bcc nm30 cpy #$90 ; end of bam, 4-143 bcc nm10 jmp nfcalc ; calc # free sectors ; write out the bit map to ; the drive in lstjob(active) mapout jsr getact tax lda lstjob,x mo10 and #1 sta drvnum ; check bam before writing ; write bam according to drvnum scrbam ldy drvnum lda mdirty,y bne sb10 rts ; not dirty sb10 lda #0 ; set to clean bam sta mdirty,y jsr setbpt ; set bit map ptr lda drvnum asl a pha ;put memory images to bam jsr putbam pla clc adc #1 jsr putbam ; verify the bam block count ; matches the bits lda track pha ; save track var lda #1 sta track sb20 asl a asl a sta bmpnt jsr avck ; check available blocks inc track lda track cmp trknum bcc sb20 pla ; restore track var sta track jmp dowrit ; write it out ; set bit map ptr, read in bam if nec. setbpt jsr bam2a tax jsr redbam ; read bam if not in ldx jobnum lda bufind,x ; set the ptr sta bmpnt+1 lda #0 sta bmpnt rts ; calc the number of free blocks on drvnum numfre ldx drvnum lda ndbl,x sta nbtemp lda ndbh,x sta nbtemp+1 rts
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r12 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x7a95, %rdx nop nop nop cmp $2458, %r10 mov $0x6162636465666768, %r11 movq %r11, %xmm2 movups %xmm2, (%rdx) nop nop nop lfence lea addresses_A_ht+0x2f55, %rdi xor %r10, %r10 mov (%rdi), %ax nop xor $32274, %rdx lea addresses_normal_ht+0x6195, %rsi lea addresses_WT_ht+0xa80b, %rdi clflush (%rdi) nop nop nop sub $34127, %r12 mov $94, %rcx rep movsq nop nop xor $35324, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r12 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r14 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi // REPMOV lea addresses_RW+0xd895, %rsi lea addresses_WC+0x9109, %rdi nop nop and %rax, %rax mov $6, %rcx rep movsw nop nop nop cmp %r14, %r14 // Store lea addresses_normal+0xa721, %rcx nop nop nop xor %rbp, %rbp mov $0x5152535455565758, %rbx movq %rbx, (%rcx) nop nop nop nop nop and %r14, %r14 // Load lea addresses_US+0x12695, %rdi xor $57008, %rcx mov (%rdi), %r14w nop cmp $52968, %rax // Faulty Load lea addresses_A+0x2a95, %rdi nop nop nop nop nop xor $15625, %rcx mov (%rdi), %ebp lea oracles, %rbx and $0xff, %rbp shlq $12, %rbp mov (%rbx,%rbp,1), %rbp pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r14 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_RW', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WC', 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}} {'00': 1} 00 */
; A060354: The n-th n-gonal number: a(n) = n*(n^2-3*n+4)/2. ; 0,1,2,6,16,35,66,112,176,261,370,506,672,871,1106,1380,1696,2057,2466,2926,3440,4011,4642,5336,6096,6925,7826,8802,9856,10991,12210,13516,14912,16401,17986,19670,21456,23347,25346,27456,29680,32021,34482,37066,39776,42615,45586,48692,51936,55321,58850,62526,66352,70331,74466,78760,83216,87837,92626,97586,102720,108031,113522,119196,125056,131105,137346,143782,150416,157251,164290,171536,178992,186661,194546,202650,210976,219527,228306,237316,246560,256041,265762,275726,285936,296395,307106,318072,329296,340781,352530,364546,376832,389391,402226,415340,428736,442417,456386,470646 mov $2,$0 bin $2,3 mul $2,3 add $0,$2
; A169675: Lexicographically earliest de Bruijn sequence for n = 3 and k = 2. ; 0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,1,1,0,0,0 mod $0,8 lpb $0 gcd $0,4 add $1,1 lpe mov $0,$1
// Copyright 1996-2021 Cyberbotics Ltd. // // 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 "WbPositionViewer.hpp" #include "WbGuiRefreshOracle.hpp" #include "WbSolid.hpp" #include "WbTransform.hpp" #include <QtWidgets/QComboBox> #include <QtWidgets/QLabel> #include <QtWidgets/QVBoxLayout> WbPositionViewer::WbPositionViewer(QWidget *parent) : QWidget(parent), mTransform(NULL), mIsSelected(false), mRelativeToComboBox(new QComboBox(this)) { QVBoxLayout *vBoxLayout = new QVBoxLayout(this); // Relative to combo box mRelativeToComboBox->setMinimumHeight(mRelativeToComboBox->sizeHint().height()); mRelativeToComboBox->setToolTip(tr("Select relatively to which solid the position should be measured")); vBoxLayout->addWidget(mRelativeToComboBox); connect(mRelativeToComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &WbPositionViewer::updateRelativeTo); // Labels QGridLayout *labelLayout = new QGridLayout(); labelLayout->addWidget(new QLabel(tr("Position:")), 0, 0); labelLayout->addWidget(new QLabel(tr("Rotation:")), 1, 0); mPositionLabels.resize(3); for (int i = 0; i < mPositionLabels.size(); ++i) { mPositionLabels[i] = new QLabel(this); mPositionLabels[i]->setTextInteractionFlags(Qt::TextSelectableByMouse); labelLayout->addWidget(mPositionLabels[i], 0, i + 1, Qt::AlignVCenter | Qt::AlignLeft); } mRotationLabels.resize(4); for (int i = 0; i < mRotationLabels.size(); ++i) { mRotationLabels[i] = new QLabel(this); mRotationLabels[i]->setTextInteractionFlags(Qt::TextSelectableByMouse); labelLayout->addWidget(mRotationLabels[i], 1, i + 1, Qt::AlignVCenter | Qt::AlignLeft); } vBoxLayout->addLayout(labelLayout); } WbPositionViewer::~WbPositionViewer() { mTransform = NULL; } void WbPositionViewer::clean() { if (mTransform) disconnect(mTransform, &WbTransform::destroyed, this, &WbPositionViewer::clean); mTransform = NULL; } void WbPositionViewer::stopUpdating() { if (mTransform) { disconnect(mTransform->translationFieldValue(), &WbSFVector3::changed, this, &WbPositionViewer::update); disconnect(mTransform->rotationFieldValue(), &WbSFRotation::changed, this, &WbPositionViewer::update); disconnect(WbGuiRefreshOracle::instance(), &WbGuiRefreshOracle::canRefreshUpdated, this, &WbPositionViewer::requestUpdate); } } void WbPositionViewer::show(WbTransform *transform) { if (mTransform) disconnect(mTransform, &WbTransform::destroyed, this, &WbPositionViewer::clean); mTransform = transform; updateRelativeToComboBox(); if (mTransform) { connect(mTransform, &WbTransform::destroyed, this, &WbPositionViewer::clean, Qt::UniqueConnection); if (mIsSelected) { connect(mTransform->translationFieldValue(), &WbSFVector3::changed, this, &WbPositionViewer::update, Qt::UniqueConnection); connect(mTransform->rotationFieldValue(), &WbSFRotation::changed, this, &WbPositionViewer::update, Qt::UniqueConnection); connect(WbGuiRefreshOracle::instance(), &WbGuiRefreshOracle::canRefreshUpdated, this, &WbPositionViewer::requestUpdate, Qt::UniqueConnection); } } } void WbPositionViewer::requestUpdate() { if (WbGuiRefreshOracle::instance()->canRefreshNow()) update(); } void WbPositionViewer::update() { if (mIsSelected && mTransform) { WbVector3 position(0, 0, 0); WbRotation rotation(0, 0, 0, 0); if (mRelativeToComboBox->currentIndex() == 0) { position = mTransform->position(); rotation = WbRotation(mTransform->rotationMatrix()); rotation.normalize(); } else { WbTransform *transform = mTransform; for (int i = 0; i < mRelativeToComboBox->currentIndex(); ++i) transform = transform->upperTransform(); position = mTransform->position() - transform->position(); position = position * WbMatrix3(transform->rotation().toQuaternion()); WbRotation currentRotation = WbRotation(mTransform->rotationMatrix()); WbRotation referenceRotation = WbRotation(transform->rotationMatrix()); currentRotation.normalize(); referenceRotation.normalize(); if (currentRotation == referenceRotation) // if there is no orientation difference, return 0 1 0 0 rotation = WbRotation(0, 1, 0, 0); else rotation = WbRotation(currentRotation.toQuaternion() * referenceRotation.toQuaternion().conjugated()); } for (int i = 0; i < mPositionLabels.size(); ++i) mPositionLabels[i]->setText(WbPrecision::doubleToString(position[i], WbPrecision::GUI_MEDIUM)); for (int i = 0; i < mRotationLabels.size(); ++i) mRotationLabels[i]->setText(WbPrecision::doubleToString(rotation[i], WbPrecision::GUI_MEDIUM)); return; } for (int i = 0; i < mPositionLabels.size(); ++i) mPositionLabels[i]->clear(); for (int i = 0; i < mRotationLabels.size(); ++i) mRotationLabels[i]->clear(); } void WbPositionViewer::updateRelativeTo(int index) { update(); } void WbPositionViewer::setSelected(bool selected) { mIsSelected = selected; triggerPhysicsUpdates(); } void WbPositionViewer::triggerPhysicsUpdates() { if (mTransform == NULL) return; if (mIsSelected) { connect(mTransform->translationFieldValue(), &WbSFVector3::changed, this, &WbPositionViewer::update, Qt::UniqueConnection); connect(mTransform->rotationFieldValue(), &WbSFRotation::changed, this, &WbPositionViewer::update, Qt::UniqueConnection); connect(WbGuiRefreshOracle::instance(), &WbGuiRefreshOracle::canRefreshUpdated, this, &WbPositionViewer::requestUpdate, Qt::UniqueConnection); update(); } else { disconnect(mTransform->translationFieldValue(), &WbSFVector3::changed, this, &WbPositionViewer::update); disconnect(mTransform->rotationFieldValue(), &WbSFRotation::changed, this, &WbPositionViewer::update); disconnect(WbGuiRefreshOracle::instance(), &WbGuiRefreshOracle::canRefreshUpdated, this, &WbPositionViewer::requestUpdate); } } void WbPositionViewer::updateRelativeToComboBox() { mRelativeToComboBox->clear(); if (mTransform) { mRelativeToComboBox->insertItem(0, tr("Absolute")); int i = 0; WbTransform *transform = mTransform->upperTransform(); while (transform) { ++i; if (transform->nodeModelName() == transform->fullName()) mRelativeToComboBox->insertItem(i, tr("Relative to %1 (depth level %2)").arg(transform->fullName()).arg(i)); else mRelativeToComboBox->insertItem(i, tr("Relative to %1").arg(transform->fullName())); transform = transform->upperTransform(); } } }
// Copyright (C) 2021 Intel Corporation // #include <vector> #include <string> #include <iostream> #include "infer_torch_entity.hpp" extern "C" void CreatInferenceEntity(std::shared_ptr<IInfer_entity>& entity) { entity = std::make_shared<infer_torch_entity>(); std::string entity_name = entity->get_entity_name(); std::cout << "entity name is:" << entity_name << std::endl; return; }
############################################################################### # Copyright 2018 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # 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. ############################################################################### .text .p2align 5, 0x90 .globl _h9_DecryptECB_RIJ128pipe_AES_NI _h9_DecryptECB_RIJ128pipe_AES_NI: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (20)(%ebp), %ecx movl (24)(%ebp), %edx movl (16)(%ebp), %eax sub $(64), %edx jl .Lshort_inputgas_1 lea (,%eax,4), %ebx lea (%ecx,%ebx,4), %ecx .Lblks_loopgas_1: movdqa (%ecx), %xmm4 lea (-16)(%ecx), %ebx movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu (32)(%esi), %xmm2 movdqu (48)(%esi), %xmm3 add $(64), %esi pxor %xmm4, %xmm0 pxor %xmm4, %xmm1 pxor %xmm4, %xmm2 pxor %xmm4, %xmm3 movdqa (%ebx), %xmm4 sub $(16), %ebx movl (16)(%ebp), %eax sub $(1), %eax .Lcipher_loopgas_1: aesdec %xmm4, %xmm0 aesdec %xmm4, %xmm1 aesdec %xmm4, %xmm2 aesdec %xmm4, %xmm3 movdqa (%ebx), %xmm4 sub $(16), %ebx dec %eax jnz .Lcipher_loopgas_1 aesdeclast %xmm4, %xmm0 movdqu %xmm0, (%edi) aesdeclast %xmm4, %xmm1 movdqu %xmm1, (16)(%edi) aesdeclast %xmm4, %xmm2 movdqu %xmm2, (32)(%edi) aesdeclast %xmm4, %xmm3 movdqu %xmm3, (48)(%edi) add $(64), %edi sub $(64), %edx jge .Lblks_loopgas_1 .Lshort_inputgas_1: add $(64), %edx jz .Lquitgas_1 movl (16)(%ebp), %eax movl (20)(%ebp), %ecx lea (,%eax,4), %ebx lea (%ecx,%ebx,4), %ebx .Lsingle_blk_loopgas_1: movdqu (%esi), %xmm0 add $(16), %esi pxor (%ebx), %xmm0 cmp $(12), %eax jl .Lkey_128_sgas_1 jz .Lkey_192_sgas_1 .Lkey_256_sgas_1: aesdec (208)(%ecx), %xmm0 aesdec (192)(%ecx), %xmm0 .Lkey_192_sgas_1: aesdec (176)(%ecx), %xmm0 aesdec (160)(%ecx), %xmm0 .Lkey_128_sgas_1: aesdec (144)(%ecx), %xmm0 aesdec (128)(%ecx), %xmm0 aesdec (112)(%ecx), %xmm0 aesdec (96)(%ecx), %xmm0 aesdec (80)(%ecx), %xmm0 aesdec (64)(%ecx), %xmm0 aesdec (48)(%ecx), %xmm0 aesdec (32)(%ecx), %xmm0 aesdec (16)(%ecx), %xmm0 aesdeclast (%ecx), %xmm0 movdqu %xmm0, (%edi) add $(16), %edi sub $(16), %edx jnz .Lsingle_blk_loopgas_1 .Lquitgas_1: pop %edi pop %esi pop %ebx pop %ebp ret
; A291660: a(n) = 2*a(n-1) - a(n-2) + a(n-4) for n>3, a(0)=2, a(1)=3, a(2)=5, a(3)=7, a sequence related to Lucas numbers. ; Submitted by Christian Krause ; 2,3,5,7,11,18,30,49,79,127,205,332,538,871,1409,2279,3687,5966,9654,15621,25275,40895,66169,107064,173234,280299,453533,733831,1187363,1921194,3108558,5029753,8138311,13168063,21306373,34474436,55780810,90255247,146036057,236291303 mov $1,2 mov $5,1 lpb $0 sub $0,1 sub $3,$4 mov $4,$2 mov $2,$3 add $2,$1 add $1,$3 add $1,1 sub $2,$3 add $5,$4 mov $3,$5 lpe mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r15 push %r8 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0xa283, %rdx sub $46907, %r11 vmovups (%rdx), %ymm1 vextracti128 $1, %ymm1, %xmm1 vpextrq $1, %xmm1, %r8 nop nop cmp %r8, %r8 lea addresses_A_ht+0x14303, %r13 clflush (%r13) nop nop nop dec %r11 movb (%r13), %r15b nop cmp %r13, %r13 lea addresses_WT_ht+0x12a03, %rdi nop nop nop nop nop xor $51739, %rbp movups (%rdi), %xmm0 vpextrq $1, %xmm0, %r8 nop nop nop nop nop add %r15, %r15 lea addresses_D_ht+0xb283, %rdx clflush (%rdx) nop nop nop cmp $24867, %r13 mov (%rdx), %r8 nop nop nop nop nop cmp %r13, %r13 lea addresses_UC_ht+0x6603, %r11 nop nop nop cmp %rdx, %rdx movb $0x61, (%r11) nop nop cmp $6370, %r11 lea addresses_UC_ht+0x5363, %r13 nop nop nop nop and %r11, %r11 mov (%r13), %r15d nop add %rdi, %rdi lea addresses_WC_ht+0x1ddab, %rsi lea addresses_WC_ht+0x15a43, %rdi nop nop cmp $12844, %rdx mov $24, %rcx rep movsq inc %rbp lea addresses_WT_ht+0x51e5, %rdi clflush (%rdi) xor $57242, %r11 mov $0x6162636465666768, %r8 movq %r8, (%rdi) nop nop nop and %rcx, %rcx lea addresses_WC_ht+0x14da3, %rsi lea addresses_A_ht+0x18849, %rdi nop nop nop nop dec %rdx mov $46, %rcx rep movsq nop nop nop inc %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r8 pop %r15 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r9 push %rdi push %rdx // Store lea addresses_RW+0x1ee43, %rdi nop nop nop nop xor %r12, %r12 mov $0x5152535455565758, %rdx movq %rdx, %xmm2 vmovups %ymm2, (%rdi) nop nop nop nop nop add %rdx, %rdx // Faulty Load lea addresses_PSE+0x1b083, %r12 nop nop nop nop nop sub %r10, %r10 vmovups (%r12), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $1, %xmm2, %r9 lea oracles, %r10 and $0xff, %r9 shlq $12, %r9 mov (%r10,%r9,1), %r9 pop %rdx pop %rdi pop %r9 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_RW'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 8, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 6, 'AVXalign': False, 'same': True, 'size': 1, 'NT': True, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': True, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 2, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 6, 'same': True, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_A_ht'}} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
; A050533: Thickened pyramidal numbers: a(n) = sum(4*i*(i-1)+1, i=1..n) + 2*(n+1)*n. ; 0,5,22,59,124,225,370,567,824,1149,1550,2035,2612,3289,4074,4975,6000,7157,8454,9899,11500,13265,15202,17319,19624,22125,24830,27747,30884,34249,37850,41695,45792,50149,54774,59675,64860,70337,76114,82199,88600,95325,102382,109779,117524,125625,134090,142927,152144,161749,171750,182155,192972,204209,215874,227975,240520,253517,266974,280899,295300,310185,325562,341439,357824,374725,392150,410107,428604,447649,467250,487415,508152,529469,551374,573875,596980,620697,645034,669999,695600,721845,748742,776299,804524,833425,863010,893287,924264,955949,988350,1021475,1055332,1089929,1125274,1161375,1198240,1235877,1274294,1313499,1353500,1394305,1435922,1478359,1521624,1565725,1610670,1656467,1703124,1750649,1799050,1848335,1898512,1949589,2001574,2054475,2108300,2163057,2218754,2275399,2333000,2391565,2451102,2511619,2573124,2635625,2699130,2763647,2829184,2895749,2963350,3031995,3101692,3172449,3244274,3317175,3391160,3466237,3542414,3619699,3698100,3777625,3858282,3940079,4023024,4107125,4192390,4278827,4366444,4455249,4545250,4636455,4728872,4822509,4917374,5013475,5110820,5209417,5309274,5410399,5512800,5616485,5721462,5827739,5935324,6044225,6154450,6266007,6378904,6493149,6608750,6725715,6844052,6963769,7084874,7207375,7331280,7456597,7583334,7711499,7841100,7972145,8104642,8238599,8374024,8510925,8649310,8789187,8930564,9073449,9217850,9363775,9511232,9660229,9810774,9962875,10116540,10271777,10428594,10586999,10747000,10908605,11071822,11236659,11403124,11571225,11740970,11912367,12085424,12260149,12436550,12614635,12794412,12975889,13159074,13343975,13530600,13718957,13909054,14100899,14294500,14489865,14687002,14885919,15086624,15289125,15493430,15699547,15907484,16117249,16328850,16542295,16757592,16974749,17193774,17414675,17637460,17862137,18088714,18317199,18547600,18779925,19014182,19250379,19488524,19728625,19970690,20214727,20460744,20708749 mov $1,-2 mul $1,$0 bin $1,3 sub $0,$1 mov $1,$0
// Copyright (c) 2013 Austin T. Clements. All rights reserved. // Use of this source code is governed by an MIT license // that can be found in the LICENSE file. #include "internal.hh" #include <cinttypes> using namespace std; DWARFPP_BEGIN_NAMESPACE die::die(const unit *cu) : cu(cu), abbrev(nullptr) { } const unit & die::get_unit() const { return *cu; } section_offset die::get_section_offset() const { return cu->get_section_offset() + offset; } void die::read(std::shared_ptr<section> cudata, section_offset off) { cursor cur(cudata, off); position = off; offset = off; acode = cur.uleb128(); if (acode > 1024) { printf("Weird acode %" PRIu64 "\n", acode); exit(-1); } if (acode == 0) { abbrev = nullptr; next = cur.get_section_offset(); return; } abbrev = &cu->get_abbrev(acode); tag = abbrev->tag; // XXX We can pre-compute almost all of this work in the // abbrev_entry. attrs.clear(); attrs.reserve(abbrev->attributes.size()); for (auto &attr : abbrev->attributes) { attrs.push_back(cur.get_section_offset()); cur.skip_form(attr.form); } next = cur.get_section_offset(); } void die::read(section_offset off) { cursor cur(cu->data(), off); position = off; offset = off; acode = cur.uleb128(); if (acode > 1024) { printf("Weird acode %" PRIu64 "\n", acode); exit(-1); } if (acode == 0) { abbrev = nullptr; next = cur.get_section_offset(); return; } abbrev = &cu->get_abbrev(acode); tag = abbrev->tag; // XXX We can pre-compute almost all of this work in the // abbrev_entry. attrs.clear(); attrs.reserve(abbrev->attributes.size()); for (auto &attr : abbrev->attributes) { attrs.push_back(cur.get_section_offset()); cur.skip_form(attr.form); } next = cur.get_section_offset(); } bool die::has(DW_AT attr) const { if (!abbrev) return false; // XXX Totally lame for (auto &a : abbrev->attributes) if (a.name == attr) return true; return false; } value die::operator[](DW_AT attr) const { // XXX We can pre-compute almost all of this work in the // abbrev_entry. if (abbrev) { int i = 0; for (auto &a : abbrev->attributes) { if (a.name == attr) return value(cu, a.name, a.form, a.type, attrs[i]); i++; } } throw out_of_range("DIE does not have attribute " + to_string(attr)); } value die::resolve(DW_AT attr) const { // DWARF4 section 2.13, DWARF4 section 3.3.8 // DWARF4 is unclear about what to do when there's both a // DW_AT::specification and a DW_AT::abstract_origin. // Conceptually, though, a concrete inlined instance cannot // itself complete an external function that wasn't first // completed by its abstract instance, so we first try to // resolve abstract_origin, then we resolve specification. // XXX This traverses the abbrevs at least twice and // potentially several more times if (has(attr)) return (*this)[attr]; if (has(DW_AT::abstract_origin)) { die ao = (*this)[DW_AT::abstract_origin].as_reference(); if (ao.has(attr)) return ao[attr]; if (ao.has(DW_AT::specification)) { die s = ao[DW_AT::specification].as_reference(); if (s.has(attr)) return s[attr]; } } else if (has(DW_AT::specification)) { die s = (*this)[DW_AT::specification].as_reference(); if (s.has(attr)) return s[attr]; } return value(); } die::iterator die::begin() const { if (acode > 1024) printf("ACODE is too big, fixme %" PRIu64 "\n", acode); if (acode > 1024 || !abbrev || !abbrev->children) return end(); return iterator(cu, next); } die::iterator::iterator(const unit *cu, section_offset off) : d(cu) { d.read(off); } die::iterator & die::iterator::operator++() { if (!d.abbrev) return *this; if (!d.abbrev->children) { // The DIE has no children, so its successor follows // immediately d.read(d.next); } else if (d.has(DW_AT::sibling)) { // They made it easy on us. Follow the sibling // pointer. XXX Probably worth optimizing d = d[DW_AT::sibling].as_reference(); } else { // It's a hard-knock life. We have to iterate through // the children to find the next DIE. // XXX Particularly unfortunate if the user is doing a // DFS, since this will result in N^2 behavior. Maybe // a small cache of terminator locations in the CU? iterator sub(d.cu, d.next); while (sub->abbrev) ++sub; d.read(sub->next); } return *this; } const vector<pair<DW_AT, value> > die::attributes() const { vector<pair<DW_AT, value> > res; if (!abbrev) return res; // XXX Quite slow, especially when using this to traverse an // entire DIE tree since each DIE will produce a new vector // (whereas other vectors get reused). Might be worth a // custom iterator. int i = 0; for (auto &a : abbrev->attributes) { res.push_back(make_pair(a.name, value(cu, a.name, a.form, a.type, attrs[i]))); i++; } return res; } bool die::operator==(const die &o) const { return cu == o.cu && offset == o.offset; } bool die::operator!=(const die &o) const { return !(*this == o); } bool die::contains_section_offset(section_offset off) const { auto contains_off = [off] (const die& d) { return off >= d.get_section_offset() && off < d.next; }; if (contains_off(*this)) return true; for (const auto& child : *this) { if (contains_off(child)) return true; } return false; } DWARFPP_END_NAMESPACE size_t std::hash<dwarf::die>::operator()(const dwarf::die &a) const { return hash<decltype(a.cu)>()(a.cu) ^ hash<decltype(a.get_unit_offset())>()(a.get_unit_offset()); }
; 1024 bytes of scratch memory before the program at address 0x5e24 PUBLIC _TEMPMEM defc _TEMPMEM = 0x5e24 SECTION code_user ; Sp1 will call asm_malloc and asm_free as needed to deal with memory when creating and deleting sprites. ; Hijack the library's malloc and free and provide our own that uses the block memory allocator instead. ; To do that you must look up the library API for these functions: ; (malloc) https://github.com/z88dk/z88dk/tree/master/libsrc/_DEVELOPMENT/alloc/malloc/z80 ; (balloc) https://github.com/z88dk/z88dk/tree/master/libsrc/_DEVELOPMENT/alloc/balloc/z80 PUBLIC asm_malloc EXTERN asm_balloc_alloc asm_malloc: ; LIBRARY REQUIREMENT: ; Allocate memory from the thread's default heap ; ; enter : hl = size ; ; exit : success ; ; hl = address of allocated memory, 0 if size == 0 ; carry reset ; ; fail on insufficient memory ; ; hl = 0 ; carry set, errno = ENOMEM ; ; fail on lock acquisition ; ; hl = 0 ; carry set, errno = ENOLCK ; ; uses : af, bc, de, hl ; we have only one queue with one size so that's what we use ld hl,0 ; queue #0 jp asm_balloc_alloc ; agrees with the library's requirements above PUBLIC asm_free EXTERN asm_balloc_free asm_free: ; LIBRARY REQUIREMENT: ; Return the memory block to the thread's default heap ; ; enter : hl = void *p ; ; exit : success ; ; carry reset ; ; fail on lock acquisition ; ; de = void *p ; carry set, errno = ENOLCK ; ; uses : af, de, hl push bc call asm_balloc_free ; agrees with lib req but the lib does not allow bc to change pop bc ret
-- 7 Billion Humans (2053) -- -- 32: Creative Writhing -- -- Author: soerface -- Size: 19 -- Speed: 37 a: b: step s pickup c write 99 drop if s == datacube: jump a endif if e == datacube: step e else: if w == datacube: step w endif endif pickup c write 99 drop step s pickup c write 99 drop jump b
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft import six %> <%docstring>modify_ldt(func, ptr, bytecount) -> str Invokes the syscall modify_ldt. See 'man 2 modify_ldt' for more information. Arguments: func(int): func ptr(void*): ptr bytecount(unsigned): bytecount Returns: int </%docstring> <%page args="func=0, ptr=0, bytecount=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = ['ptr'] can_pushstr_array = [] argument_names = ['func', 'ptr', 'bytecount'] argument_values = [func, ptr, bytecount] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)): if isinstance(arg, six.text_type): arg = arg.encode('utf-8') string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_modify_ldt']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* modify_ldt(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
; 编译链接方法 ; [root@XXX XXX]# nasm -f elf kernel.asm -o kernel.o ; [root@XXX XXX]# ld -s -Ttext 0x30400 -o kernel.bin kernel.o ; [root@XXX XXX]# [section .text] ; 代码在此 global _start ; 导出 _start _start: ; 跳到这里来的时候,我们假设 gs 指向显存 mov ah, 0Fh ; 0000: 黑底 1111: 白字 mov al, 'K' mov [gs:((80 * 1 + 39) * 2)], ax ; 屏幕第 1 行, 第 39 列。 jmp $
; ; DZ80 V3.4.1 8080 Disassembly of VT100.bin ; Initial disassembly: 2021-12-03 08:56 ; Last updated: 2022-02-28 21:27 ; ; Comments by Paul Flo Williams <paul@frixxon.co.uk>, ; released under Creative Commons Attribution 4.0 International licence. ; ; Documentation random things: ; 1. Sequences not mentioned in User Guide: ; a) DECHCP and its VT52 equivalent ESC ]; ; b) DECGON/DECGOFF, ; c) SS2 and SS3. ; DECHCP and DECGON are dependent on GPO anyway, but SS2/SS3 work for unexpanded VT100. ; DECHCP is mentioned in TM p.A-21 ; ; Comments on notation in comments: ; A <- x means "A becomes/is set to x", which frees up "=" to be the straightforward mathematical "is equal to" ; HL <- x means HL becomes x, mostly implying that HL is now a pointer to something at location x. ; ; References to TM here are all to EK-VT100-TM-003, "VT100 Series Video Terminal Technical Manual" ; ; TM Table 4-2-3, p.4-18, explains the RST interrupt handling. ; ; Table 4-2-3 Interrupt Addresses ; ; 00H Power-up (Not hardware driven) ; 08H Keyboard ; 10H Receiver ; 18H Receiver and keyboard ; 20H Vertical frequency ; 28H Vertical frequency and keyboard ; 30H Vertical frequency and receiver ; 38H Vertical frequency, receiver and keyboard ; org 00h start: di lxi sp,stack_top jmp post ; restart1: org 08h call keyboard_int ei ret ; restart2: org 10h call receiver_int ei ret ; restart3: org 18h call receiver_int call keyboard_int ei ret ; restart4: org 20h call vertical_int ret ; restart5: org 28h call vertical_int ret ; org 30h restart6: call receiver_int call vertical_int ei ret ; restart7: org 38h jmp restart6 ; ; post ; self_test ; The only difference between "proper" POST and the Self Test invoked by DECTST is making sure that POST ; doesn't repeat indefinitely. As register E is a mask of requested tests and repeat indication, POST sets ; the mask just as if DECTST had been invoked with "just self-test, no repeats." ; ; TM §4.2.8, "Power-Up and Self-Test", p. 4-19, describes POST. ; post: mvi e,1 ; Pretend this is DECTST and we requested POST without repeats ; ; Self-test starts by checksumming ROMs, which is a rotate-and-XOR operation across all four 2K ROMs ; individually. The checksum is expected to produce a zero result, which is ensured by including a ; byte somewhere in each ROM that can mix-in to make zero. Checksum bytes are marked in this listing ; where they have been identified. ; self_test: di mvi a,0fh out iow_nvr_latch ; "standby" to NVR latch (see port definition for details) cma ; A <- 0xf0 out iow_brightness ; set mid brightness xra a mov d,a mov l,a mov h,a ; HL <- 0, starting address of ROMs ; Checksumming ROMS 1 to 4 next_rom: inr a mov b,a out iow_keyboard ; Place ROM number on LEDs mvi c,8 ; Each ROM is 8 x 256 = 2K bytes next_byte: rlc ; checksum is rotate and XOR xra m inr l jnz next_byte inr h dcr c jnz next_byte ora a ; A spare byte in each ROM is programmmed to ensure the correct hang_rom: jnz hang_rom ; checksum is always zero. Failed? Hang with ROM number on keyboard. mov a,b cpi 4 jnz next_rom ; Loop for all four ROMs ; inr a out iow_keyboard ; RAM test next; failure leaves "5" on the LEDs mvi c,0aah ; C is test pattern mvi b,HIGH ram_top+1 in ior_flags ani iob_flags_avo ; Test for presence of AVO jnz next_pattern ; jump if absent mvi b,HIGH avo_ram_top+1 next_pattern: mov h,b ; Start at top of RAM (L zero either from ROM test, or from last loop) dcx h zero_ram: mvi m,0 dcx h mov a,h cpi HIGH ram_start - 1 jnz zero_ram ; Now work back up through RAM, applying pattern inx h patt_loop: mov a,m ; A <- current contents, which should be zero ora a jz zero_good ani 0fh ; A <- low 4 bits of memory value mov a,h ; jnz ram_fail ; if low 4 bits are not zero, we've failed cpi HIGH avo_ram_start jc ram_fail ; Don't fail RAM if we're looking at AVO, because its RAM is 4 bits wide zero_good: mov m,c ; Now place pattern mov a,m ; and read back xra c ; should be identical (i.e. XOR to zero) jz patt_good ani 0fh ; Again, AVO RAM is only 4 bits wide mov a,h jnz ram_fail cpi HIGH avo_ram_start jnc patt_good ; so don't fail RAM for 4 high bit being wrong, in AVO space ram_fail: mvi d,1 ; D <- accumulates test failures cpi HIGH ram_top+1 hang_ram: jc hang_ram ; Hang for baseboard RAM, not AVO patt_good: xra a inx h ora l jnz patt_loop ora h cmp b jnz patt_loop mov a,c ; A <- pattern rlc ; 1st time: 0xaa -> 0x55 set carry; 2nd time: 0x55 -> 0xaa, reset carry mov c,a ; C <- new pattern jc next_pattern push d call clear_scratch call init_terminal call recall_nvr pop d jz recall_ok mov a,d ori 2 ; add "nvr failed" to test results mov d,a recall_ok: mvi a,2fh ; c111 d1 = "standby" (inv) sta vint_nvr out iow_nvr_latch ; Keyboard test lxi b,0fffh ; good long loop ei ; We rely on keyboard_int going off to detect end-of-scan beep_loop: mvi a,8 ; If we entered POST from DECTST, and we requested repeating tests, ana e mvi a,7fh ; clear the "SPKR. CLICK" bit in the byte we send to the keyboard, jnz skip_click mvi a,0ffh ; If we're not repeating test, go wild, beep-boy! skip_click: out iow_keyboard dcx b mov a,b ora c jnz beep_loop out iow_keyboard ; quieten keyboard again lda key_flags ; Check key_flags that have been maintained by keyboard_int ora a jm seen_eos ; We should have seen an end of scan after that loop mov a,d ori 4 ; add "keyboard failed" to test results mov d,a seen_eos: push d call init_devices pop d jmp continue_tests ; ; The keyboard interrupt detects modifier keys and "end of scan" and places them into a ; flags location, and places other keys into what the Technical Manual calls the SILO, ; here called key_silo. ; ; The TM describes the SETUP key going into key_flags but it doesn't; its key code of 7bh ; falls just under the cut-off established here and it goes into the SILO. ; ; Interpretation of keys happens in _see_ process_keys. ; keyboard_int: push psw in ior_keyboard push h push b mov b,a ; B <- key row/column sui 7ch ; 07ch and up are the modifier keys: CTRL, SHIFT and CAPS LOCK jm into_key_buf ; normal keys will go into SILO mov h,a ; H <- key code - 7ch inr h ; H <- 1 = CTRL, 2 = SHIFT, 3 = CAPS, 4 = EOS mvi a,10h ; Not at all sure why A could not have been initialised to rrc ; 08h at this point, and we could lose the RRC instruction. shift_key: rlc dcr h jnz shift_key lxi h,key_flags ora m mov m,a jmp kexit ; Done for this key, exit interrupt ; into_key_buf: lxi h,key_flags mvi a,7 ana m cpi 4 ; Number of keys waiting to be processed? jp kexit ; No room if already got 4 inr m ; Increment number of keys waiting lxi h,key_silo call add_a_to_hl mov m,b ; Add this key to queue kexit: pop b pop h pop psw ret ; ; proc_func_key ; ; Having placed keyboard scan codes through the switch array, we now have a key code that identifies ; a non-ASCII, or "function" key. ; ; BREAK is 081h, NO SCROLL is 082h (although it has already been acted upon, and doesn't get here) ; Numeric keypad keys all have their ASCII codes with the high bit set, i.e. KP COMMA is 0ach, and ; the digits 0 to 9 have codes 0b0h to 0b9h. ; Arrow keys are codes 0c1h to 0c4h (bit 7 plus 41h to 44h, i.e. 'A' to 'D') ; PF1 to PF4 are 0d0h to 0d3h (bit 7 plus 50h to 053h, i.e 'p' to 's') proc_func_key: ani 7fh ; All keys entering here at the bit 7 set, so remove it mov c,a ; C <- adjusted key code lda in_setup ora a jnz setup_cursor mov a,c cpi 1 ; BREAK was 081h, adjusted to 01h jz break_pressed lda setup_b2 ani sb2_ansi jnz ansi_keys ; jump to ANSI mode processing lda keypad_mode ora a jnz vt52_app_mode mov a,c ; A <- adjusted key code cpi 'A' ; If it isn't a cursor key, it's a number from the numeric jm send_c ; keypad and they are sent just as '0' to '9' on VT52 mvi a,C0_ESC ; otherwise it's a cursor key and they have leading ESC call send_key_byte send_c: mov a,c jmp send_key_end ; vt52_app_mode: mvi a,C0_ESC call send_key_byte mov a,c ; A <- adjusted key code cpi 'A' ; Is it an arrow key? jp send_c ; we've sent ESC already, so just send 'A' to 'D' now mvi a,'?' ; else numeric keypad keys are KP0 -> ESC ? p send_plus_col4: call send_key_byte mov a,c ; A <- adjusted key code adi 40h ; '0' -> 'p' jmp send_key_end ; ansi_keys: lda keypad_mode ora a jnz ansi_app_mode mov a,c ; A <- adjusted key code cpi 'A' ; If it isn't a cursor key (and here we're in numeric keypad mode), jm send_c ; send the plain digit cpi 'P' ; PF1 to PF4? jm ansi_app_mode ; No, deal with arrow keys esc_o_last: mvi a,C0_ESC ; PF1 to PF4 are the same in numeric and application modes, call send_key_byte ; sending ESC O P to ESC O S mvi a,'O' send_ac: call send_key_byte jmp send_c ; esc_brack_last: mvi a,C0_ESC call send_key_byte mvi a,'[' jmp send_ac ; ansi_app_mode: lda mode_ckm ; Responses may also depend on DECCKM (cursor key mode) ora a jz decckm_reset ; CKM is reset mov a,c ; A <- adjusted key code cpi 'A' ; Cursor keys? jp esc_o_last ; Yes, in ANSI + CKM mode, these are ESC O A to ESC O D ansi_digits: mvi a,C0_ESC call send_key_byte mvi a,'O' jmp send_plus_col4 ; decckm_reset: mov a,c ; A <- adjusted key code cpi 'A' ; Is this a digit key? jm ansi_digits ; ANSI-mode digits are same with CKM set or reset cpi 'P' ; PF1 to PF4? jm esc_brack_last ; ANSI-mode arrows are ESC [ A to ESC [ D jmp esc_o_last ; ANSI + CKM reset PF1 to PF4 are ESC O P to ESC O S ; ; ; ; break_pressed: lxi h,pk_noclick ; Return to a "tidy keyboard processing" point push h lda local_mode ; BREAK has no function in local mode ora a rnz call make_keyclick lxi b,020eh ; B <- "not DTR" for PUSART; C <- 14 vert. frames =~ 0.2333 s lxi h,key_flags mov a,m ani key_flag_ctrl ; CTRL + BREAK sends answerback message jnz c0_answerback mov a,m ; A <- key flags ani key_flag_shift ; SHIFT + BREAK is a longer break jz not_shift ; but if we're not doing that, keep counter short lxi b,00d2h ; Long break C <- 210 vertical frames =~ 3.5 s not_shift: mvi a,25h ; A <- base command: "not RTS, rx enable, tx enable" ori 8 ; A <- mix in "send break character" ora b ; A <- possibly mix in disconnect (dropping DTR) for SHIFT+BREAK out iow_pusart_cmd ; send PUSART command lda frame_count ; get current vertical frame count add c ; add number we want mov c,a ; C <- end number of frames wait_break: push b call update_kbd pop b lda frame_count cmp c ; are we there yet? jnz wait_break jmp ready_comms ; setup_cursor: lxi h,pk_click ; Push a return address that will tidy up keyboard push h xra a sta csi_params sta csi_private lxi h,brightness mov a,c sui 'A' mov b,a ; B <- adjusted cursor key mov a,m ; Get current brightness jz brighter ; up arrow - screen brighter dcr b jz dim_screen ; down arrow - screen more dim dcr b jz cuf_action ; right arrow - normal cursor movement dcr b jz cub_action ; left arrow - normal cursor movement ret ; brighter: dcr a rm ; limit at 0 mov m,a ; write new brightness ret ; dim_screen: inr a cpi 20h ; limit at 1fh rz mov m,a ; write new brightness ret ; no_scroll_key: lda setup_b2 cma ; complement sense of switches ani 10h ; A <- 10h if autoxon is OFF lxi h,local_mode ora m jnz clear_keyboard ; Can't send XOFF if autoxon is OFF or we're in local mode lda why_xoff lxi b,2<<8|C0_XON ana b ; NZ if we had previously sent XOFF, in which case jnz send_xany ; we'll send an XON mvi c,C0_XOFF send_xany: mov a,c sui C0_XON ; If we've sent XON, A = 0, XOFF -> A = 2 sta noscroll call send_xonoff jmp pk_click ; after_tests: di lxi sp,stack_top lxi h,ram_start ; Just done tests, so this is the where failures are recorded push h mov a,m ; A <- test results rar ; Set carry if AVO failed tests jc no_avo in ior_flags ani iob_flags_avo jz have_avo ; AVO is an "absence" flag no_avo: inr a sta avo_missing have_avo: call init_devices lda screen_cols dcr a sta right_margin pop h mov a,m ; A <- test results mvi m,7fh ; Write line terminator over test results, at start of screen layout ora a ; Did any fail? jz done_results ; no, don't bother displaying jp no_cycle_bit ; jump if we aren't cycling through results lxi h,test_field ; To show that tests are being repeated and failing, the entire screen mvi m,0ah ; is toggled between normal and reverse field, so initialise this. ani 7fh ; Remove cycle bit when storing results no_cycle_bit: sta test_results adi '0' ; convert to printable range lhld cursor_address mov m,a ; Display results at cursor position cpi '4' ; was it just modem test that failed? jz done_results ; OK, don't go into local mode just for that mvi a,20h ; sta local_mode ; any other failures, go into local done_results: call set_charsets lxi b,C0_XON call send_xonoff jmp idle_loop ; clear_scratch: lxi h,stack_top lxi d,avo_ram_start - stack_top mvi b,0 call memset ; Clear all of scratch RAM above stack cma ; A <- 0ffh (because memset always zeroes A) sta saved_rend ; saved character rendering lxi h,line1_dma shld UNREAD_X2052 lxi h,main_video ; (home address) shld cursor_address ret ; ; init_video_ram ; init_video_ram: call to_ground ; initialise character processing routine lxi h,ram_start ; HL <- start of screen RAM lxi d,screen_layout mvi b,12h call memcopy ; initial video RAM layout lxi h,avo_ram_start lxi d,avo_ram_top - avo_ram_start + 1 mvi b,0ffh jmp memset ; attribute RAM blank (default rendition) ; ; This is the initial configuration of screen RAM. TM §4.6 explains the ; screen refresh and three termination bytes on each line. ; This layout almost matches TM Figure 4-7-3, p.4-89, except that that figure seems to have ; a typo (repeated 7F 70 06 line, when second should be 7F 70 0C) - other figures in that ; chapter get this right. ; screen_layout: db 07fh,70h,03h db 07fh,0f2h,0d0h db 07fh,70h,06h db 07fh,70h,0ch db 07fh,70h,0fh db 07fh,70h,03h ; ; init_terminal ; Initialise a bunch of terminal settings: timers, scroll, cursor and receiver buffer ; init_terminal: lxi h,0212h ; long, visible, cursor timer shld cursor_timer mvi a,35h sta blink_timer mvi a,1 sta scroll_dir sta tparm_solicited ; By default reports cannot be sent unsolicited lxi h,07ffh ; Never used shld UNREAD_X2149 ; Never used mvi a,2 sta key_rpt_pause mvi a,0f7h ; All attributes off, normal character set sta char_rend in ior_flags ani iob_flags_gpo mvi a,1 jnz no_gpo ; AVO and GPO flags are both "absence" flags sta gpo_flags no_gpo: mvi a,0ffh sta saved_curs_row ; invalidate cursor row sta cursor_visible mvi h,80h mov l,h shld rx_head ; Initialise rx_head and rx_tail of receive buffer ret ; reset_pusart: mvi a,40h ; Reset PUSART so we can write a mode byte again out iow_pusart_cmd lda tx_rx_speed out iow_baud_rate lda pusart_mode out iow_pusart_cmd call ready_comms mvi a,10h sta vint_nvr out iow_nvr_latch ret ; ; update_dc011 ; ; This is the only routine that writes to I/O port 0c2h, which drives DC011, the circuit ; that provides most of the timing signals to the Video Processor. Because setting ; columns or refresh rate always sets or resets interlaced mode, we may need to write ; the column mode twice. ; ; See TM §4.6.2, p. 4-55 ; update_dc011: lda columns_132 ora a jz is80 mvi a,10h is80: mov b,a ; B <- 0 for 80 columns, 10h for 132 columns out iow_dc011 ; this write also sets interlaced mode lda refresh_rate out iow_dc011 ; also sets non-interlaced mode cpi refresh_60Hz lxi h,0970h ; 50Hz fill, per TM Figure 4-7-3, p. 4-89 jnz fill_req lxi h,0370h ; 60Hz fill fill_req: shld line0_dma lda setup_b3 ani sb3_interlace rz mov a,b ; A <- 0 for 80 columns, 10h for 132 columns out iow_dc011 ; write columns again, so we get interlaced mode ret ; ; update_dc012 ; DC012 is the video controller chip, and here we update the field colour (reverse/normal field) and ; whether the basic attribute (important in the absence of the AVO) is underline or reverse video. ; update_dc012: lda setup_b1 ani sb1_lightback jnz is_light mvi a,1 is_light: ori 0ah ; A <- 0ah/0bh = "set reverse field on/off", respectively out iow_dc012 lda basic_rev_video ; 0 = underline, 1 = reverse video ori 0ch ; "set basic attribute" command out iow_dc012 ret ; clear_display: lda columns_132 ora a jz init_80col jmp init_132col ; ; memcopy - copy B bytes from (DE) to (HL) memcopy: ldax d mov m,a inx h inx d dcr b jnz memcopy ret ; ready_comms: lda local_mode ora a mvi a,1 ; "RTS" jnz skip_dtr ; don't set DTR if we're in local mode mvi a,5 ; "RTS" and "DTR" skip_dtr: jmp modem_signals ; ; ; Initialise display, PUSART, and the video devices DC011 and DC012 ; init_devices: call clear_display call program_pusart call update_dc012 jmp update_dc011 ; idle_loop: call keyboard_tick call receiver_tick lxi h,pending_setup mov a,m ora a mvi m,0 cnz in_out_setup lda local_mode ora a jz idle_loop xra a sta keyboard_locked jmp idle_loop ; receiver_int: push psw push b push h in ior_pusart_data ani 7fh jz exit_rx_int ; quick exit for received NULs mov c,a ; C <- character received lda local_mode ora a jnz exit_rx_int ; if we're in local mode, reject received characters too in ior_pusart_cmd ; read PUSART status ani 38h ; do we have framing, overrun or parity errors? jz no_rx_errors ; no, phew mvi c,C0_SUB ; Rx errors are treated as SUB, shown as checkboard on screen mvi a,27h ; PUSART command enables RTS*, DTR*, transmit and receive ori 10h ; mix-in "error reset" out iow_pusart_cmd no_rx_errors: mov a,c ; A <- received character (or SUB) cpi 7fh ; Is this DEL? jz pass_on lda setup_b2 ani sb2_autoxon ; test XON mov a,c ; A <- received character jz no_autoxon ; jump if we don't do auto XON/XOFF lxi h,received_xoff cpi C0_XON ; have we received XON? jz rx_xon cpi C0_XOFF ; have we received XOFF? jz rx_xoff no_autoxon: lxi h,rx_head mov c,m ; Get pointer mov b,h ; as 16-bits stax b ; Place in buffer mov a,c ; A <- rx_head pointer inr a ; move along ani 0bfh ; And wrapping, so location after 20bf is 2080 mov m,a ; Write rx_head back mov b,a ; B <- rx_head lda rx_tail ; A <- rx_tail sub b ; A <- rx_tail - rx_head (= space in buffer) jnz not_caught mov m,c ; Put old head back, so we lose newest character mov a,b ; A <- new rx_head inr a ; move along ani 0bfh ; and wrap mov l,a ; make a pointer mvi m,C0_SUB ; place SUB in buffer to mark lost character jmp do_xoff ; not_caught: jp nowrap ; If rx_head > rx_tail adi 40h ; space is "over the wrap" nowrap: cpi 32 ; Have we got half a buffer full? jnz pass_on do_xoff: lxi b,1<<8|C0_XOFF ; Half buffer full, so sent XOFF call send_xonoff pass_on: call try_tx2 exit_rx_int: pop h pop b pop psw ret ; rx_xon: mvi a,0feh ; Clear bit 0 of received_xoff ana m jmp track_xon_xoff ; rx_xoff: mvi a,1 ; Set bit 0 of received_xoff ora m track_xon_xoff: mov m,a ; Update received_xoff jmp pass_on ; ; ; Map from an unshifted key to the symbol it has when shifted. This table has no terminator, ; so it is exhaustive, i.e. every code other than the letter keys that passes through here ; must be found somewhere. Taking the table as ending at the byte of key_scan_map, every ; ASCII code from 20h to 7fh is here, either as the unshifted code or the shifted one. ; key_shift_map: db '0', ')' db '1', '!' db '2', '@' db '3', '#' db '4', '$' db '5', '%' db '6', '^' db '7', '&' db '8', '*' db '9', '(' db '-', '_' db '=', '+' db '`', '~' db '[', '{' db ']', '}' db 03bh, ':' ; 03bh is semicolon, which asm8080 hates in quotes :-) db '/', '?' db 027h, 022h ; 027h is single quote, 022h is double quote db ',', '<' db '.', '>' db '\', '|' db 20h,20h db 7fh,7fh ; ; Key map. Keys are received from the keyboard in a column/row form, shown in TM Figure 4-4-4, ; "Keyboard Switch Array". This table is arranged in natural order, by columns as ; labelled in that figure, except there are just 11 rows for each column (most of the remaining ; key codes being either absent or corresponding to key modifier functions like SHIFT, which ; were weeded out by the keyboard interrupt. ; ; Because the first three keys of column 0 (rows 0 to 2) are absent from the array (i.e. these ; scan codes are never sent by the keyboard), this table is overlapped by three bytes with ; key_shift_map, hence the equate below. So, at first glance, each column should have 11 rows, ; but column 0 appears to have 8. ; ; Numeric keypad entries have their "normal" ASCII code with the top bit set, so that KP9 is ; '9'|80h, i.e. 0b9h. However, asm8080 won't let me write '9'|80h in a DB directive without ; parenthesizing, so I'm just leaving hex values here. Whinge over. ; ; For stability, because of its big reversed "L" shape, the RETURN key has two switches, ; with scan codes 04h and 64h. This table converts 04h to 0 and 64h to 13 (i.e. C0_CR) so ; that it only counts once. ; key_scan_map equ $-3 ; Column 0 - this starts with row 3 (see comments above). db 07fh, 0, 'p', 'o', 'y', 't', 'w', 'q' ; Column 1 - c3 is arrow right key_scan_col1: db 0c3h, 0, 0, 0, ']', '[', 'i', 'u', 'r', 'e', '1' ; Column 2 - c4 is arrow left, c2 is arrow down, 81 is break key_scan_col2: db 0c4h, 0, 0c2h, 81h, '`', '-', '9', '7', '4', '3',C0_ESC ; Column 3 - c1 is arrow up, d2 is PF3, d0 is PF1, backspace and ; tab have their natural codes key_scan_col3: db 0c1h, 0d2h, 0d0h,C0_BS, '=', '0', '8', '6', '5', '2',C0_HT ; Column 4 - b7 is num7, d3 is PF4, d1 is PF2 key_scan_col4: db 0b7h, 0d3h, 0d1h, 0b0h,C0_LF, '\', 'l', 'k', 'g', 'f', 'a' ; Column 5 - bx is numeric keypad, key_scan_col5: db 0b8h, 08dh, 0b2h, 0b1h, 0, 27h, 3bh, 'j', 'h', 'd', 's' ; Column 6 key_scan_col6: db 0aeh, 0ach, 0b5h, 0b4h,C0_CR, '.', ',', 'n', 'b', 'x', 082h ; Column 7 key_scan_col7: db 0b9h, 0b3h, 0b6h, 0adh, 0, '/', 'm', 20h, 'v', 'c', 'z' ; This is the checksum byte for ROM 1 (0000-07FF) db 0ffh ; CHECKSUM ; vertical_int: push psw push h push d call shuffle ; think this is line shuffle push b mvi a,9 ; "clear vertical frequency interrupt" out iow_dc012 ei lda smooth_scroll ora a jnz update_scroll lxi h,scroll_pending ora m jz check_bell ; (not been asked to scroll, so skip to next job) mvi a,1 ; Now start a smooth scroll, so mark it as in progress sta smooth_scroll ora m ; reading scroll_pending (direction) setting flags too mvi m,0 ; scroll_pending <- 0 mvi a,1 ; scrolling up if sta scroll_dir lda bottom_margin jp connectx ; scroll direction is positive mvi a,99h ; else we're scrolling down (BCD 99h = -1) sta scroll_dir lda top_margin dcr a connectx: call connect_extra ; sta shuffle_ready ; A is not zero here update_scroll: lxi b,scroll_dir ldax b ; A <- scroll direction (-1 or 1) lxi h,scroll_scan add m ; A <- scan line ± 1 daa ; keep arithmetic decimal, as there are 10 scan lines ani 0fh ; A <- scan line (single BCD digit) mov m,a ; update scroll_scan mov d,a ; D <- scroll latch ani 3 ; Update scroll latch in DC012, two low bits first out iow_dc012 mov a,d ; A <- scroll latch rar ; ana a ; rar ; shift right two bits ori 4 ; mark this as "high bits of scroll latch" out iow_dc012 ; Update scroll latch in DC012, two high bits mov a,d ; A <- scroll latch ora a ; done? jnz check_bell ; still scrolling, so skip the termination stuff sta smooth_scroll ; now we've finished that scroll ldax b ; A <- scroll direction ora a lda bottom_margin jm do_shuf ; A is -1 if screen is scrolling down lda top_margin ; no, we're going up dcr a do_shuf: call calc_shuf1 sta shuffle_ready ; A is not zero here check_bell: lxi h,bell_duration mov a,m ora a jz nobell dcr m ; decrease remaining duration ani 4 ; and flip speaker click bit every 8 cycles rrc ; bit 2 -> bit 1 rrc ; bit 1 -> bit 0 rrc ; bit 0 -> bit 7 (speaker click) sta kbd_online_mask nobell: lxi h,blink_timer mov a,m dcr a jnz no_blink mvi m,35h ; reset blink timer if it's expired, then do blink mvi a,8 out iow_dc012 ; DC012 <- "toggle blink flip flop" lxi h,test_field mov a,m ; If tests are repeatedly failing, the screen toggles between ora a ; normal and reverse field at the blink rate jz out_ports out iow_dc012 xri 1 no_blink: mov m,a ; update blink_timer or test_field, as necessary out_ports: mvi a,iow_kbd_scan ; Keyboard scan is started by vertical refresh sta kbd_scan_mask ; When this mask is sent to the keyboard, it gets cleared lxi h,frame_count ; increment frame count, used for timing purposes inr m lda brightness out iow_brightness lda tx_rx_speed out iow_baud_rate lda vint_nvr out iow_nvr_latch pop b pop d pop h pop psw ret ; receiver_tick: lda local_mode ; Do nothing in local mode lxi h,in_setup ; or if we are in SET-UP ora m rnz call test_rx_q rz ; No characters waiting reflect_char: mov b,a ; B <- received char lda in_setup ora a mov a,b ; A <- received char jnz no_exec lda gpo_flags rlc ; Test if we are currently passing characters to GPO mov a,b ; A <- received char jc no_exec ; and if we are, don't interpret control characters cpi 20h jc exec_c0 no_exec: lhld char_action pchl ; ; Once DECGON has been received, all characters are passed through to the graphics ; port until DECGOFF, ESC 2, is detected. This requires two states, an escape detector, ; installed first, and a "2" detector. If detect ESC and then the next character isn't ; "2", these routines will pass through the ESC and other character, and then head back ; to escape detector. ; gfx_det_esc: cpi C0_ESC jnz gfx_send_char lxi h,gfx_det_final jmp install_action ; ; This state detects the final character of DECGOFF: '2'. Any other character will ; need to be forwarded to the graphics port, after catching up by sending the preceding ; ESC. ; ; Detecting DECGOFF will transition to ground state. ; gfx_det_final: cpi '2' jnz gfx_send_esc mvi a,1 ; mark as present (bit 0) but not using (bit 7) sta gpo_flags jmp to_ground ; gfx_send_esc: mov b,a ; Save the character that we weren't looking for mvi a,C0_ESC ; while we send through the ESC we previously detected call gfx_tx_char mov a,b gfx_send_char: call gfx_tx_char jmp gfx_set_state ; back to detecting ESC ; gfx_tx_char: mov c,a wait_gpo_rdy: push b call keyboard_tick pop b in ior_flags ; TM §6.4.1 "When data is passed, the GRAPHICS FLAG goes ani iob_flags_gpo ; high and stays high until the data is stored in [RAM]" jnz wait_gpo_rdy mov a,c out iow_graphics ret ; ; This early entry point (fall through) for print_char is only called from one place, when ; we insert a control character in an answerback string, and at that point this point is ; called with A = 1, in order to represent the control character onscreen as a diamond shape, ; which is ROM glyph 1. It would be important at that point to ensure that the mappings ; didn't disrupt the display, and calling single_shift would do that for ASCII range, but ; codes 00h to 01fh pass straight through print_char anyway and produce Special Graphics codes, ; without any mappings getting in the way. In fact, that is exactly what happens when CAN ; and SUB are used to cancel an escape/control sequence and a checkboard character is printed; ; the print_char entry point is used. Am I missing something? ; print_nomap: call single_shift ; fall through ; ; There is a bug with character set mapping at the line marked [* BUG *] below. ; ; To find out which character should be printed, the number in gl_invocation (normally 0 or 1), ; is added to the address g0_charset, which is 20fdh, and the encoding designated into that set ; will be used to print a character. If a single shift is in effect, the number in gl_invocation ; will have been increased by 2, so G0 invoked into GL will have become G2 invoked into GL for ; a single character. If SHIFT OUT (^N) was already in effect, such that G1 was invoked into GL, ; and then a single shift is applied, G3 will be invoked into GL. ; ; At this point, the address of g0_charset (20fdh), in HL, has 3 added to it to find the mapping, ; except that the addition only affects the L register, making HL now point to 2000h, when it ; should be pointing to 2100h. ; ; Because 2000h always contains the value 7fh, as the start of the video DMA stream, this bug ; will make it appear as if the United Kingdom character set had been invoked, regardless of the ; SET-UP condition. ; ; To demonstrate this, the following three sequences should produce a string of three '#' (hash) ; characters, but the third one will produce two '#' and a '£' (pound). ; ; ; a) SI # SO # SI # (designations being G0, G1, G0) ; b) SI # ESC N # # ( " " G0, G2, G0) ; c) SI # SO # ESC N # ( " " G0, G1, G3) ; print_char: push psw cpi 7fh ; Discard DEL jz delete_exit push h push d push b mov c,a ; C <- character to be printed lxi h,gl_invocation ; Now perform character set mapping mov d,m ; D <- character set (0 = G0, 1 = G1) invoked inx h ; HL <- g0_charset mov a,d ; A <- charset add l ; advance to invoked charset mov l,a ; HL <- mapped charset [* BUG *] mov a,d ; A <- charset sui 2 ; Speculatively remove single shift jp charset_range ; detect whether this worked mov a,d ; A <- charset, which was fine anyway charset_range: sta gl_invocation ; Unshifted, ready for next character mov d,m ; D <- character map (_see_ charset_list) lda char_rend ora d mov b,a ; B <- mixed map + rendition mov a,d ; A <- character map rlc ; Set carry flag for Special Graphics or Alternate ROM Graphics mov a,c ; A <- character jnc normal_mapping ; jump for "normal" sets sui 5fh ; Special graphics are encoded from 05fh, but are in ROM from glyph 0 cpi 20h ; ... but there are only 20h of them, so may unmap for rest of range jnc normal_mapping mov c,a ; Preserve our adjusted mapping for graphics only normal_mapping: mov a,d ; A <- character map ani 40h ; Only United Kingdom will be non-zero here mov a,c ; A <- character jz not_uk_enc cpi 23h ; Only difference between UK and ASCII is '#', 023h jnz not_uk_enc ; So leave everything else untouched mvi c,1eh ; '#' becomes '£', at ROM glyph 01eh (TM Table 4-6-18, p.4-78) not_uk_enc: lda char_rvid ; A <- 0 = normal video, 80h = reverse video ora c mov c,a ; C <- ROM glyph + normal/reverse video bit lda pending_wrap ora a jz skip_wrap lxi h,curs_col lda right_margin ; test for cursor at right-hand edge cmp m jnz skip_wrap mvi m,0 ; wrap to next line push b call index_down ; and move cursor down pop b skip_wrap: lhld cursor_address ; HL <- cursor address in screen RAM mov m,c ; display it mov a,h ; Now adjust address to point at attributes adi 10h mov h,a mov m,b ; Apply rendition (and mapping) mov a,b sta rend_und_curs ; Record this rendition and mapping lxi h,char_und_curs mov m,c ; Store character under cursor lxi h,curs_col lda right_margin cmp m jnz no_wrap_needed mov a,c ; A <- glyph + normal/reverse sta char_und_curs lda setup_b3 ani sb3_autowrap jmp may_need_wrap ; no_wrap_needed: inr m ; move cursor right call move_updates xra a may_need_wrap: sta pending_wrap pop b pop d pop h delete_exit: pop psw ret ; ; test_rx_q ; See if there are any received characters waiting to be processed, ; provided the user hasn't pressed NO SCROLL. ; Returns NZ if there is a character available; character in A. ; Returns Z if no scroll in operation or no characters waiting. ; test_rx_q: lda noscroll ora a jnz no_test_q lxi h,rx_head mov a,m ; A <- rx_head inx h ; HL <- rx_tail sub m ; A <- rx_head - rx_tail jnz rx_not_empty ; jump if characters received no_test_q: xra a ret ; rx_not_empty: mov l,m ; L <- rx_tail mvi h,20h ; Make HL pointer to character mov d,m ; D <- first character in buffer lxi h,rx_tail mov a,m inr a ; advance rx_tail pointer ani 0bfh ; with wrap ori 80h mov m,a ; write new rx_tail dcx h ; HL <- rx_head sub m ; A <- tail - head jp nowrap2 adi 40h ; space is "over the wrap" nowrap2: cpi 30h ; Is the buffer three-quarters empty? jnz not_empty_yet lxi b,1<<8|C0_XON call send_xonoff not_empty_yet: mov a,d ; A <- first character in buffer ora a ret ; process_keys: lda key_flags mov e,a ani key_flag_eos ; Don't bother processing anything until end of scan, rz ; so exit immediately lxi h,clear_keyboard push h ; always exit by clearing down keyboard flags and silo mov a,e ; A <- key_flags ani 7 ; isolate count cpi 4 jm process_silo ; if fewer than 4 keys waiting, process them xra a ; else we've overflowed sta new_key_scan ; there are no new keys ret ; throw away flags and silo on way out ; process_silo: mov d,a ; D <- number of keys in silo mvi c,0 ; C <- 0, number of keys in silo matching history mvi b,4 ; loop through (up to) 4 history entries lxi h,key_history next_history: mov a,m ; grab next key from history ora a jz zero_history ; if there wasn't a key here, skip search push h push b ; Having grabbed a key from the key history, we try to find it in the silo. Finding ; it still down confirms it as something other than a bounce, and we'll leave it for ; processing. If we don't find it, we'll zero out the entry in the history. ; This loop employs a neat trick of distinguishing between a silo match and ; exhausting the the search. If we find a match, we'll jump out of the comparison ; loop with Z flag set. The normal way of running a count would also leave us ; looping from a number down to zero though, meaning the Z flag would be set in ; either case. So here, the loop is run from one count less and B is decremented ; and loops while it is still positive. So, exhausting the silo leaves us with ; Z flag *unset*. mvi b,3 lxi h,key_silo compare_silo: cmp m ; Does old key exist in silo? jz silo_match ; yes, process inx h ; next location in silo dcr b jp compare_silo silo_match: pop b pop h jz found_in_silo ; If we found key in silo (result of cmp), add to history mvi m,0 ; zero out the key from history dcr c ; Reduce the number of matching keys, to overcome next instruction found_in_silo: inr c ; Increase the number of matching keys zero_history: inx h ; next history entry dcr b jnz next_history ; mov a,e ; A <- key flags ani 8 ; According to TM, this bit was intended for SETUP, but this rnz ; must be out of date; can't see a way of setting this bit now. ora d ; Include the number of keys in silo jnz keys_avail mvi a,-31 ; When there are no keys down, reset the key repeat timer sta key_rpt_timer ret ; keys_avail: lxi h,check_history ; next stage push h lda key_rpt_timer inr a jz rpt_expired sta key_rpt_timer rpt_expired: lda setup_b1 ani sb1_autorep ; If we're not auto-repeating, timer expiry is irrelevant rz mov a,e ; A <- key flags ani 10h ; CTRL pressed? rnz ; A key with control cannot repeat (TM §4.4.9.5) lda latest_key_scan lxi h,nonrepeat ; Five keys are not allowed to auto-repeat mvi b,5 chk_nonrep: cmp m ; If this is one of them, reject it (return early) rz inx h dcr b jnz chk_nonrep lxi h,key_rpt_pause ; Pause before repeating begins (about half a second) dcr m rnz mvi m,2 ; Two counts per repeat (30 per second) lda key_rpt_timer cpi 0ffh rnz mov a,c ; A <- number of matching keys (in history) cpi 1 ; Only one key can repeat at a time rnz mvi b,4 ; The key could be in any of the history slots lxi h,key_history check_rpt_slot: mov a,m ora a jnz got_repeater inx h dcr b jnz check_rpt_slot ret ; We should have found one, but failed! ; got_repeater: pop h ; Pop the return address we stacked earlier jmp set_latest ; check_history: mov a,c ; A <- number of matching keys in history cpi 4 ; Still got false keys down? rp ; if so, exit lxi b,key_silo comp_silo_hist: lxi h,key_history try_next_hist: mov a,m ; A <- key from history ora a jz next_hist_key ldax b ; Is this key in silo same as this history key? cmp m jz next_silo_key ; OK, found it next_hist_key: inx h ; try next key in history mov a,l ; cpi LOW key_history + 4 jnz try_next_hist ; try again, unless at end of history buffer ldax b ; A <- key from silo jmp found_new_key ; next_silo_key: inx b ; point to next silo entry dcr d ; decrease number of keys in silo jnz comp_silo_hist ret ; found_new_key: mov b,a ; B <- scan code lda new_key_scan cmp b mov a,b ; A <- scan code sta new_key_scan rnz set_latest: pop h sta latest_key_scan cpi 7bh ; is SETUP pressed? jz setup_pressed ; yes, mark as pending cpi 6ah ; is NO SCROLL pressed? jz no_scroll_key mov b,e ; B <- key flags mov e,a ; E <- scan code lda keyboard_locked ; Don't process while keyboard locked - clear SILO ora a jnz clear_keyboard ; ; Each column of the key switch array contains 11 entries, so need to take a column ; number in the top four bits of E, divide by 16, and then multiply by 11. ; mov a,e ; A <- scan code ani 0f0h ; A <- 16 * column (because shifted) rrc rrc mov d,a ; D <- 4 * column rrc rrc ; A <- column add d ; A <- 5 * column mov d,a ; D <- 5 * column mov a,e ; A <- scan code = 16 * column + row sub d ; A <- 11 * column + row lxi h,key_scan_map mov e,a mvi d,0 ; DE <- A (offset) dad d ; HL <- offset into array for this scan code mov c,m ; C <- key code mov a,c ; A <- key code ora a ; jm proc_func_key ; jump to deal with function keys cpi 20h jc done_modifiers ; unmapped, ESC, BS, TAB, LF, RETURN mov a,b ; A <- key flags ani 70h ; any modifiers pressed? jz done_modifiers ; no, simple path ; Given that some modifiers have been pressed, work out a candidate shift code mov a,c ; A <- key code cpi 7bh ; candidates for table shift jnc use_shift_map cpi 61h ; also shift these by table jc use_shift_map ; Otherwise, we are just left with lowercase letter range (61h to 07ah), ; and they are shifted to uppercase by a simple logical and. ani 0dfh ; make uppercase from lowercase mov c,a ; C <- shifted key code jmp exam_key_mods ; use_shift_map: mov a,b ; A <- key flags ani 30h ; are CTRL or SHIFT pressed? jz exam_key_mods ; no, skip shift table lxi h,key_shift_map ; HL <- start of shift table next_shift: mov a,m ; get unshifted code from table cmp c ; compare with ours jz pick_shift ; match, go and pick up shift code inx h ; go past shifted code inx h ; to next key jmp next_shift ; round again ; pick_shift: inx h ; advance to shift code mov c,m ; C <- shifted key code exam_key_mods: mov a,b ; A <- key flags ani 10h ; mask with CTRL jz done_modifiers ; not CTRL, straight out, we've got final code mov a,c ; A <- shifted key code cpi 'A' jc below_alpha cpi '[' ; (the real '[' has already been shifted to '{') jc apply_ctrl ; apply to 'A' to 'Z' below_alpha: cpi '?' jz apply_ctrl ; '?' 3fh => 1fh (US) cpi 20h ; jz apply_ctrl ; SP 20h => 00h (NUL) cpi 7bh jc clear_keyboard cpi 7fh jnc clear_keyboard ; Codes 07bh to 07eh drop through here, allowing us to ; produce control codes from 1bh (ESC) to 1eh (RS) apply_ctrl: ani 9fh ; e.g. 'A' 01000001 & 10011111 -> 00000001 mov c,a ; C <- final code done_modifiers: ora c push psw lda setup_b2 ani sb2_marginbell jz mbell_disabled sta margin_bell ; Typing a key could potentially trigger a margin bell mbell_disabled: pop psw send_key_end: ori 80h ; Set high bit to mark as last character we're sending call send_key_byte ; pk_click: call make_keyclick ; ; Now we've identified the latest key, place it in a zeroed location in the key history, ; if it isn't already there. ; pk_noclick: lda latest_key_scan mvi d,4 lxi h,key_history next_hist: cmp m jz clear_keyboard inx h dcr d jnz next_hist mvi d,4 lxi h,key_history next_hist2: mov a,m ora a jz got_hist_place inx h dcr d jnz next_hist2 jmp clear_keyboard ; got_hist_place: lda latest_key_scan mov m,a ; place key in history mvi a,-31 ; reset key repeat timer sta key_rpt_timer ; ; clear_keyboard ; At the end of keyboard processing, clear key_flags and the keyboard silo. ; clear_keyboard: xra a lxi h,key_flags mov d,m ; D <- key_flags mov m,a ; zero key_flags inx h ; HL <- last_key_flags mov m,d ; last_key_flags <- key_flags inx h ; HL <- key_silo mvi d,4 ; 4 locations to clear clear_silo: mov m,a ; zero silo location inx h ; next location dcr d jnz clear_silo ret ; make_keyclick: lda setup_b2 ani sb2_keyclick rz ; exit if keyclick is not enabled mvi a,iow_kbd_click sta kbd_click_mask ; When this mask is sent to the keyboard, it gets cleared ret ; ; Table of keys that are not allowed to auto-repeat (TM §4.4.9.5) ; These are: SETUP, ESC, NO SCROLL, TAB, RETURN ; nonrepeat: db 7bh, 2ah, 6ah, 3ah, 64h ; Entry point for DECTST, which has form ESC [ 2 ; Ps y tst_action: lda csi_p1 ; The first parameter to DECTST sui 2 ; must be the value 2 rnz ; else quit early! mov d,a ; D <- 0 lda csi_p2 ; Now grab the test(s) we'd like to perform mov e,a ; E <- test values (each bit set is a test) rep_tests: mvi a,1 ; Test mask 0x01 - power up self test ana e ; if POST is requested, jnz self_test ; do it. (POST knows to return here.) continue_tests: mov a,d ; A <- cumulative test results ora a cnz note_failure push d ; preserve current results on stack ... call print_wait ; "Wait", we could be here a while pop d ; ... and restore mvi a,2 ; Test mask 0x02 - data loop back test ana e cnz data_loop_test mvi a,8 ; A <- display mask for failing tests cc note_failure mvi a,4 ; Test mask 0x04 - modem control test ana e cnz modem_test mvi a,10h ; A <- display mask for failing tests cc note_failure mov a,d ; Have we failed any tests? ora a jnz skip_repeat ; if so, don't go round again mvi a,8 ; Test mask 0x08 ana e ; means repeat selected tests indefinitely until jnz rep_tests ; failure or power off skip_repeat: mov a,d ; Get test results sta ram_start ; squirrel away (_see_ after_tests) jmp after_tests ; ; Add bits to D register as tests fail. Current mask to add to failure is in A register. ; This corresponds directly to the characters displayed on screen for test failure, ; except bit 7. The displayed characters are shown in TM Table 5-6. ; Pulling this into ASCII range is done in _see_ after_tests. ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; D: |cycle| | |modem| data| kbd | RAM | AVO | ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; note_failure: ora d ; A <- new failure mask | previous failures mov d,a ; D <- new failure tally mvi a,8 ; 8 is a request to cycle tests ana e ; E is tests requested rz mvi a,80h ; Mark "cycle tests" in failure mask ora d mov d,a ret ; exec_c0: cpi C0_ESC jz c0_escape ; start extended processing cpi C0_DLE ; Are we in column 0 or column 1? jc process_col0 ; Column 0 controls go through a jump table mov e,a ; E <- character sui 18h ani 0fdh ; Z if A was 018h (CAN) or 01ah (SUB) rnz ; No? No action for anything else in this column mov a,e ; A <- character cpi C0_SUB jz cancel_seq cpi C0_CAN rnz cancel_seq: call to_ground mvi a,2 ; ROM glyph 2 is checkerboard (error indicator) jmp print_char ; ret ; UNREACHABLE ; ; It happens that the only C0 controls that the VT100 "processes" are those from column 0, ; i.e. with codes 00h to 0fh, and they are looked up here. Codes from column 1 are either ; dealt with earlier for communication control (XON and XOFF), invoke extended processing ; (ESC) or just cancel that extended processing (CAN and SUB). ; process_col0: sui 5 ; Codes 00h to 04h are ignored (actually, NUL never got here) rm lxi h,c0_actions add a ; Addresses are two bytes long, so double up our code, mov e,a ; use DE to hold a 16-bit offset mvi d,0 dad d ; and add to the table base address mov e,m ; extract action routine inx h ; address mov d,m ; DE <- action routine xchg ; HL <-> DE (can't jump to DE) xra a ; convenience clear - used for SHIFT IN/OUT pchl ; Jump to action routine, so its return will continue ; other processing ; JUMP TABLE c0_actions: dw c0_answerback ; 05 ENQ (answerback) dw do_nothing_ack ; 06 ACK (acknowledge) - does nothing dw c0_bell ; 07 BEL (bell) dw c0_backspace ; 08 BS (backspace) dw c0_horiz_tab ; 09 HT (horizontal tab) dw index_down ; 0a LF (line feed) dw index_down ; 0b VT (vertical tab) dw index_down ; 0c FF (form feed) dw c0_return ; 0d CR (carriage return) dw c0_shift_out ; 0e SO (shift out) dw c0_shift_in ; 0f SI (shift in) c0_shift_out: inr a c0_shift_in: sta gl_invocation ret ; c0_answerback: lda local_mode ; Can't send answerback in local mode ora a rnz lhld aback_buffer mov a,h ; If the first two characters of the answerback buffer cmp l ; are the same, they are two delimiters and the message rz ; is empty, so exit lxi h,pending_report mvi a,pend_aback ora m mov m,a ret ; ; aback_report ; Produce the answerback report by dumping the buffer from aback_buffer, raw, to the serial stream. ; There can be up to 20 characters in this buffer, but may be fewer, as determined by the first ; byte, the delimiter. ; aback_report: lxi h,pending_report mov a,m ani ~pend_aback mov m,a lxi h,aback_buffer mov b,m ; B <- delimiter inx h ; next character mvi c,20 ; we're going to send 20 characters at most lxi d,report_buffer more_aback: mov a,m ; grab next character cmp b ; if it is the delimiter, exit jz aback_repend stax d ; add character to report inx d ; next report location inx h ; next answerback location dcr c jnz more_aback aback_repend: dcx d ; go back one character ldax d ; grab the last character ori 80h ; mark it as the end of string, by setting bit 7 stax d ; put it back jmp send_report ; c0_bell: lxi h,bell_duration mov a,m adi 8 rc mov m,a ret ; c0_backspace: lxi h,curs_col mov a,m ora a rz ; Can't backspace beyond the start of the line dcr m ; Move cursor one column left jmp move_updates ; ; c0_return - move the cursor to the start of the line, the CR action c0_return: xra a sta curs_col ; Column zero jmp move_updates ; nextline: call c0_return ; ; C0 codes LF, VT and FF, as well as escape sequence IND, are all processed the same way index_down: lda setup_b3 ; Check newline (LNM) mode, to see if moving down also ani sb3_newline ; implies moving to the start of the (next) line. cnz c0_return lxi h,curs_row mov d,m lda bottom_margin cmp d jz at_margin_b call last_row ; B <- last row number mov a,b cmp d rz inr d ; Not at bottom of screen, so just increment row number mov m,d jmp move_updates ; at_margin_b: lda setup_b1 ani sb1_smooth jz jump_scroll_up mvi c,1 call wait_scroll mvi a,0ffh sta row_clearing inr m ; scroll_pending <- 1 call move_lines_up wait_clear1: lda row_clearing ora a jnz wait_clear1 sta char_und_curs ; blank under cursor (00h) dcr a sta rend_und_curs ; and default rendition (0ffh) ; ; This return instruction is used as a handy jump point for the C0 ACK control, ; which the terminal ignores. do_nothing_ack: ret ; jump_scroll_up: call start_jump_up jmp inv_saved_row ; ; The routine that kicks off all escape and control sequence processing in the terminal. ; c0_escape: xra a sta inter_chars sta csi_private lxi h,recog_esc jmp install_action ; recog_esc: cpi '0' ; all characters >= '0' are finals jnc esc_final lxi h,inter_chars ; so this is an intermediate character that we will mov c,a ; store for later mov a,m ora a ; check that we haven't already had an intermediate jz store_inter mvi c,0ffh ; invalidate the intermediate if so store_inter: mov m,c ; store valid or invalid intermediate ret ; esc_final: sta final_char lxi h,to_ground ; Setup a return address for after the escape sequence's action push h lda inter_chars ; Is there an intermediate character? (Or one we invalidated ora a ; earlier by storing 0ffh?) jnz esc_inter lda setup_b2 ; Given that there are no intermediates, we are now dealing ani sb2_ansi ; with a simple ESC Final sequence, which we will now lookup lxi h,ansiesct ; in either the ANSI (VT100) table, or VT52 table. jnz do_esc_find lxi h,vt52esct do_esc_find: jmp find_action ; esc_inter: mov b,a ; B <- intermediate lda setup_b2 ; Check if we're in ANSI mode ani sb2_ansi ; and if not, exit immediately because mov a,b ; there are no VT52 escape sequences with rz ; intermediate characters cpi '(' ; SCS sequence - designate to G0 lxi d,g0_charset ; DE <- location of G0 mapping, for when we've looked up charset jz scs_g0 cpi ')' ; SCS sequence - designate to G1 jz scs_g1 cpi '#' ; ESC # Final are the presentation sequences (DECDWL, etc.) lxi h,esc_hash_table rnz ; If the intermediate was something else, or invalid (0ffh), do nothing ; drop through to find an action for the final character of the ESC # sequence ; find_action is used to search a table for a final character and extract the address of the ; appropriate action routine. A secondary entry point, ; find_action_a is used to select an action when a Ps parameter value is already in register A ;(_see_ sgr_action for an example.) ; find_action will jump to the found action routine, which means a normal return from that routine ; will return to find_action's caller. In some cases we see someone jumping to this routine, having ; stowed another return address on the stack in advance. ; As well as calling an action routine, record the found entry in found_action, which allows the ; caller to try several tables in sequence, if needed (i.e. CSI execution.) ; This routine preserves B, as it is used to store the selective parameter to be ; passed to the action routine. ; find_action: lxi d,found_action ; we'll record success here xra a stax d ; but initally say "nothing found" lda final_char find_action_a: mov c,a next_action: xra a add m ; A <- next comparison value rz ; return if reached end of table inx h ; increment to action routine low byte cmp c ; is this the value we want? jz exec_action ; found value/character we were looking for inx h ; else increment over the action routine address inx h ; to the next comparison value jmp next_action ; and try again ; exec_action: stax d ; record entry that matched mov a,m ; A <- low byte of action address inx h ; hop to high byte mov h,m ; H <- high byte of action address mov l,a ; L <- low byte of action address xra a pchl ; jump to action routine ; ; pop_to_ground is only jumped to if initialisation for DECGON fails, in _see_ gfx_init. We now pop the ; original return address before returning to ground state. Because gfx_init was reached through either ; the ANSI or VT52 escape jump tables, and the stack had already been primed with the address to_ground, ; gfx_init could have just returned instead of jumping to this point, which pops the stack and then ; falls through to the original destination anyway. _test_ t/decgon-init.txt ; pop_to_ground: pop h ; throw away a return address if DECGON fails ; ; This address gets stored on the stack before find_action is jumped to, for escape sequences to_ground: lxi h,print_char install_action: shld char_action ret ; ; VT52 escape sequence action table (0a1c - 0a4f) ; Each entry is three bytes: character after ESC has been ; recognised, and then a word of an action routine. ; JUMP TABLE vt52esct: ; Cursor movement db 'A' dw vt52curmove db 'B' dw vt52curmove db 'C' dw vt52curmove db 'D' dw vt52curmove ; "Graphics" mode - selects special character set db 'F' dw vt52gfxenter db 'G' dw vt52gfxexit db 'H' dw vt52curhome db 'I' dw reverse_index ; Erase to end of screen db 'J' dw vt52curmove db 'K' dw vt52curmove db 'Y' dw vt52_det_cup db 'Z' dw identify db '=' dw app_keypad db '>' dw num_keypad db '1' ; DECGON - graphics mode dw gfx_init db '<' dw ansi_mode db ']' dw print_screen db 0 ; end of table ; ; Same as above but for ANSI (VT100) mode ; JUMP TABLE ansiesct: db 'c' ; RIS - reset to initial state dw start db 'E' ; NEL - next line dw nextline db 'M' ; RI - reverse index dw reverse_index db '1' ; DECGON - graphics mode dw gfx_init db '[' ; CSI - control sequence introducer dw recog_csi db 'H' ; Set tab at current column dw set_tab_here db 'D' ; IND - index (move down without changing column) dw index_down db '7' ; DECSC - save cursor and attributes dw save_cursor db '8' dw restore_cursor ; DECRC - restore cursor and attributes db '=' dw app_keypad db '>' dw num_keypad db 'Z' dw identify db 'N' ; SS2 - mentioned in TM p.D-3, but not UG dw single_shift db 'O' ; SS3 - mentioned in TM p.D-3 but not UG dw single_shift db 0 ; end of table ; ; JUMP TABLE esc_hash_table: ; Triple byte entries again, with final character followed by address of routine db '3' ; DECDHL - double height line, top half dw dhl_top_action db '4' ; DECDHL - double height line, bottom half dw dhl_bot_action db '5' ; DECSWL - single-width line dw line_attr_swl db '6' ; DECDWL - double-width line dw line_attr_dwl db '7' ; DECHCP - hard copy dw print_screen db '8' ; DECALN - screen alignment display dw align_pattern db 0 ; end of table ; ; Received ESC [ (CSI), so set up processing for next character recog_csi: lxi h,start_csi shld char_action pop h ret ; vt52curhome: mvi a,'H' ; setup to pretend this is ANSI sequence sta final_char vt52curmove: lxi h,0 shld csi_params pop h ; execute_seq: lxi h,to_ground ; we are always going to transition to ground state next push h ; pushing so we can just return from this routine lda inter_chars ; Did we get any intermediate characters? ora a ; If so, quit early, as no VT100 sequences allow them rnz lxi h,fixed_param_t ; search the table of fixed parameter sequences first call find_action lda found_action ; and if any of those matched (and just got executed), ora a ; we can stop looking rnz lxi h,csi_params ; HL <- start of parameter list. We'll iterate through this lda num_params ora a ; if there weren't any parameters, we'll treat the sequence mov e,a ; as if there was a single, defaulted, parameter jnz loop_params inr e ; pretend we have one parameter loop_params: mov a,m ; retrieve this parameter push h ; preserve param list pointer push d ; preserve param count lxi h,sel_param_t ; search the selective parameters table mov b,a ; B <- selective parameter for action routine call find_action pop d ; restore param count pop h ; and list lda found_action ; If we couldn't find an action at all, no point iterating ... ora a rz ; ... so quit early inx h ; point to next parameter dcr e jnz loop_params ; and go round again ret ; ; Table of sequences that have a fixed number of parameters, whether defaulted or not. ; All other sequences have "Ps" selective parameters, in the next table. ; JUMP TABLE fixed_param_t: db 'D' ; CUB - cursor left n columns dw cub_action db 'B' ; CUD - cursor down n rows dw cud_action db 'C' ; CUF - cursor forward n columns dw cuf_action db 'H' ; CUP - cursor position dw curpos_action db 'A' ; CUU - cursor up n rows dw cuu_action db 'r' ; DECSTBM - set top and bottom margins dw stbm_action db 'f' ; HVP - horizontal and vertical position dw curpos_action ; (same routine as CUP) db 'x' ; DECREQTPARM - request terminal parameters dw tparm_action db 'y' ; DECTST - invoke confidence test dw tst_action db 0 ; end of table ; Table of sequences with selective parameters. There action routines will be called ; multiple times, with a single parameter each time. This way, conflicts between parameters ; get resolved naturally, by having later parameters override earlier ones. ; JUMP TABLE sel_param_t: db 'c' ; DA - device attributes dw da_action db 'q' ; DECLL - load LEDs dw decll_action db 'n' ; DSR - device status report dw dsr_action db 'J' ; ED - erase in display dw ed_action db 'K' ; EL - erase in line dw el_action db 'l' ; RM - reset mode dw rm_action db 'm' ; SGR - select graphic rendition dw sgr_action db 'h' ; SM - set mode dw sm_action db 'g' ; TBC - tabulation clear dw tbc_action db 0 ; end of table ; ; In VT52 mode, recognised ESC Y, which now needs two more characters, row and column. ; vt52_det_cup: lxi h,vt52_get_coord shld char_action pop h ret ; ; vt52_get_coord ; Two characters after ESC Y should be row and column. This state gathers them both, using a flag ; to record whether we've seen the row already. ; ; NOTE: This routine shows that the VT100 will execute C0 controls when coordinates are expected ; for this sequence, making ESC Y BEL SP SP identical in effect to ESC Y SP SP BEL. ; Would be interesting to check this against later terminals' behaviour and VSRM. ; ; There is a "sub-state" flag here, called got_vt52_row. It is not initialised when ESC Y is ; recognised and is only cleared when a column has been received, which means that not only will ; single-character C0 controls be executed in the middle of a sequence, but that a second ESC Y ; received after the row character will not stop the very next printable character being ; interpreted as a column coordinate and terminating the sequence. ; ; For example: ; a) ESC Y ESC Y 0 0 executes as ESC Y 0 0 ; b) ESC Y 0 ESC Y 0 also executes as ESC Y 0 0 ; vt52_get_coord: mov b,a cpi 20h ; Do we have a C0 control? Pointless test as these are processed jc exec_c0 ; before other characters are passed to action routines, like this. cpi C0_ESC ; Similarly, ESC cannot reach here. lxi h,got_vt52_row ; HL <- flag location, kind of sub-state jnz store_coord ; this character wasn't ESC, so treat as coordinate lxi h,recog_esc ; UNREACHABLE shld char_action ; UNREACHABLE ret ; UNREACHABLE ; store_coord: mov a,m ; Check whether we've had a coord already ora a jnz vt52_move ; if we have, perform the move mvi m,1 ; got_vt52_row <- 1 "had a row, now need column" mov a,b ; grab raw character sui 20h ; turn it into a zero-based row number sta vt52_row_coord ; keep it for later lxi h,vt52_get_coord shld char_action ; keep the same action, really ret ; vt52_move: mvi m,0 ; got_vt52_row <- 0 -- clear the "had a row" flag mov a,b ; grab raw character sui 20h ; turn it into a zero-based column number cpi 50h ; which can only take us up to column 80! jnc skip_col_upd ; Could end up only moving the cursor row, if the column is invalid sta curs_col ; in range, so update skip_col_upd: call last_row ; B <- last row number lda vt52_row_coord inr b cmp b jnc skip_row_upd sta curs_row skip_row_upd: call to_ground jmp move_updates ; ; init_80col ; Create an 80 column display, which involves clearing the 132-column flag and setting up the ; screen RAM with terminators at the righ places. Margins, cursor position and DC011 updates ; are shared with the 132-column initialisation, below. ; init_80col: xra a sta columns_132 call init_screen mvi c,80 call make_screen call make_line_t mvi c,80 jmp col_common ; ; init_132col ; Create a 132 column display, in the same manner as described above. ; init_132col: mvi a,1 sta columns_132 call init_screen mvi c,132 call make_screen call make_line_t mvi c,132 col_common: xra a sta top_margin ; Reset top margin again (make_line_t just did this) call last_row ; B <- last row number mov a,b sta bottom_margin ; Deja margin mov a,c ; A <- screen columns sta screen_cols call update_dc011 call cursor_home mvi a,1 jmp wait_n_frames ; reverse_index: lxi h,curs_row ; Move cursor up one row, in the same column lda top_margin mov b,a ; B <- top margin mov a,m ; A <- cursor row cmp b jz at_margin_t ; Need to scroll up if we are at the top margin ora a rz lxi h,curs_row ; Just move the cursor up one row dcr m jmp move_updates ; at_margin_t: lda setup_b1 ani sb1_smooth jz jump_scroll_dn mvi c,1 call wait_scroll mvi a,0ffh sta row_clearing dcr m ; scroll_pending <- -1 call move_lines_dn wait_clear2: lda row_clearing ora a jnz wait_clear2 sta char_und_curs ret ; jump_scroll_dn: call start_jump_dn jmp inv_saved_row ; app_keypad: lxi h,keypad_mode mvi m,1 ret ; num_keypad: lxi h,keypad_mode mvi m,0 ret ; ansi_mode: lxi h,setup_b2 mov a,m ori sb2_ansi mov m,a ; set_charsets: lda setup_b3 ani sb3_uk mvi h,8 ; H <- ASCII Set jz not_uk mvi h,48h ; H <- United Kingdom Set not_uk: mov l,h ; L <- same set as H shld g0_charset ; Place in all four designators shld g2_charset xra a sta gl_invocation ; Invoke G0 into GL ret ; vt52gfxenter: mvi h,88h ; H <- Special Graphics Character Set jmp vt52gfx1 ; vt52gfxexit: mvi h,8 ; H <- ASCII Set vt52gfx1: mov l,h ; L <- same set as h shld g0_charset ; Map G0 and G1 in a single operation ret ; ; decll_action ; ; DECLL - ESC [ Ps q [* BUG *] ; ; Single Ps parameter: ; 0 - clears all LEDs ; 1 - lights L1 ; 2 - lights L2 ; 3 - lights L3 ; 4 - lights L4 ; ; This routine either masks four lowest bits to zero for Ps = 0, ; on constructs a single-bit-on mask that it can OR with the existing ; LED state value. No writing of the LED state to the keyboard is done ; here, so presumably that's a periodic thing elsewhere. ; ; However, this routine has a bug. It checks for a zero parameter, and then ; subtracts 5 from any non-zero parameter, bombs out for a positive result, ; and then attempts to make a LED mask with the result (Ps - 5). However, ; values of Ps between 133 and 255 will still be negative when 5 is subtracted, ; meaning that some of them will make masks to affect bits 4 - 7, and these will ; be sent to the keyboard without further censoring. The keyboard byte itself ; is described in TM Figure 4-4-2 (_see_ iow_keyboard) ; ; This bug accounts for the strange behaviour documented by John 'Sloppy' Millington ; in his "VT100 Oddities" document: https://vt100.net/dec/vt100/oddities ; ; To find out which bit will be set by this routine, calculate (260 - Ps) % 9. ; Result Effect ; 0 - 3 lights one of the LEDs L1 to L4 in the normal fashion ; 4 lights the keyboard locked LED such that it cannot be unlit ; 5 lights the online/local LED such that it cannot be unlit ; 6 sets "start scan", which will result in a mad repeat rate ; 7 sets "speaker click", which will make the terminal beep continuously ; 8 leaves a 1 in the carry flags, so it is completely harmless ; decll_action: lxi h,led_state mov a,b ; On entry to action routines, B is always the selection value ora a ; zero is special case (all off) jnz make_led_mask mov a,m ; A <- current LED state ani 0f0h ; mask all LEDs to zero mov m,a ; place back ret ; make_led_mask: sui 5 rp ; maximum allowed parameter value is 4 mov b,a ; Because LEDs register are reversed in order from the number of xra a ; the selection parameter, b will count up to zero to find bit stc ; start with a "1" bit for our mask rot_m: ral ; shift mask bit left through register inr b jnz rot_m ora m ; A <- new mask mov m,a ; led_state <- old value | new mask ret ; ; SCS - select character set ; On entry, de is 20fdh (G0), and the earlier entry point, scs_g1, increments ; it so that G1 is affected. ; scs_g1: inx d scs_g0: lda final_char mov b,a ; B <- charset name lxi h,charset_list-2 nxtmap: inx h inx h mov a,m ora a rz ; end of table without finding a match? cmp b ; is this the charset we're looking for? jnz nxtmap inx h ; yes, so grab internal charset number mov a,m stax d ; and store it in either G0 or G1 ret ; ; single_shift ; This routine is used to implement an action for SS2 and SS3, neither of which are ; documented as being supported in the VT100 User Guide, though they are mentioned ; the Technical Manual as being supported by the "VT100 Family." ; ; SS2 (ESC N) is supposed to invoke G2 into GL for a single printable character, ; after which the terminal reverts to the previous invocation, G0 or G1. SS3 (ESC O) ; is supposed to do the same with G3. ; ; What they actually do on the VT100 is to act identically, in increasing the current ; invocation by two sets, so that they will both invoke G2 into GL if G0 was previously ; there, or invoke G3 into GL if SHIFT OUT was previously in effect. After a single ; displayed character, the invocation drops by two sets, leaving the terminal as before. ; ; This behaviour is cheaper to implement than the correct one, and doesn't make any ; difference because both G2 and G3 have the default character set (ASCII or UK) ; designated at start-up, and there is no way to designate anything else. ; ; In fact, the only way you can tell the difference between the VT100 ignoring these ; controls completely and implementing them is by designating the Special Graphics Set ; into G0, invoking it to GL and then using SS2 and sending a character that would be ; different between the two sets. For example: ; ; ESC ( 0 a ESC N a a ; ; On a terminal that didn't support this sequence at all, the above sequence would ; display three lowercase "a" characters. On the VT100, this will display a checkerboard, ; a lowercase "a", and another checkerboard. ; single_shift: lxi h,gl_invocation inr m inr m ret ; charset_list: db 'A',48h ; United Kingdom Set db 'B',08h ; ASCII Set db '0',88h ; Special Graphics db '1',0 ; Alternate Character ROM Standard Character Set db '2',80h ; Alternate Character ROM Special Graphics db 0 ; end of table gfx_init: lxi h,gpo_flags mov a,m ora a jz pop_to_ground mvi m,81h pop h gfx_set_state: lxi h,gfx_det_esc jmp install_action ; save_cursor: lxi h,gfx_saved lxi d,gfx_state jmp copy_state ; restore_cursor: lxi h,gfx_state lxi d,gfx_saved copy_state: mvi b,0bh call memcopy jmp move_updates ; ; SGR - select graphics rendition sgr_action: lxi h,sgr_ps_table ; we're looking for rendition value in this table mov a,b ; this is the selective parameter we're finding ora a jz sgr_off ; zero (all attributes off) is special jmp find_action_a ; employing tail recursion to take us back to execute_seq ; ; JUMP TABLE sgr_ps_table: db 1 ; bold dw sgr_bold db 4 ; underscore dw sgr_underscore db 5 ; blink dw sgr_blink db 7 ; negative (reverse) image dw sgr_reverse db 0 ; end of table sgr_off: sta char_rvid ; A is zero on entry, so clear reverse video lxi h,char_rend mov a,m ori 0f7h ; and set all the normal rendition bits mov m,a ret ; sgr_bold: mvi a,rend_bold jmp sgr_mask ; ; If we don't have AVO, then we are limited to the "base attribute", bit 7 of each character in ; screen RAM, which will render as underscore if the cursor is underline, or reverse video if the ; cursor is a block. ; sgr_underscore: lda avo_missing ora a jnz set_base_attr mvi a,rend_under jmp sgr_mask ; sgr_blink: mvi a,rend_blink sgr_mask: lxi h,char_rend ana m mov m,a ret ; ; Reverse attribute is available without AVO, if the cursor is a block. All the same, in that case, ; it is the only attribute available, and sgr_underscore will also set the base attribute. ; ; If you have AVO, the reverse is one of four attributes available. ; ; (Two names for the same entry point, just to clarify the above, and why sgr_underscore is jumping here.) ; sgr_reverse: set_base_attr: mvi a,80h sta char_rvid ret ; ANSI entry point - ESC [ c da_action: lda csi_p1 ora a ; This sequence only allows no parameter or a parameter of 0 rnz ; ANSI/VT52 entry point - ESC Z identify: lxi h,pending_report mov a,m ori pend_ident mov m,a ret ; ident_report: mvi a,~pend_ident call prepare_report lda setup_b2 ani sb2_ansi ; Are we in ANSI mode? jnz ansi_identity ; now producing VT52 report, which is just ESC / Z. As we're at the character ; after the prepared template of "ESC [", we'll write the terminating 'Z' first ; (with bit 7 set), and then move backwards to overwrite the '[' with '/'. mvi m,'Z'|80h ; in reverse order, ladies and gentlemen dcx h mvi m,'/' jmp send_report ; ; Going to produce the sequence ESC [ ? 1 ; <n> c ; where <n> is produced from the installed options. ansi_identity: mvi m,'?' ; add the fixed part of response inx h ; to the buffer mvi a,'1' call rep_char_semi in ior_flags mov b,a ; B <- flags byte cma ; complement because the AVO and GPO flags ani 6 ; are "missing" flags, not "present" flags mov c,a ; C <- AVO and GPO presence flags mov a,b ; A <- flags byte ani iob_flags_stp ; check STP jz stp_not_found ; not present, skip inr c ; STP adds 1 to the result stp_not_found: mov a,c ; A <- final answer ori '0' ; ASCII-ify this digit mov m,a ; into buffer inx h mvi m,'c'|80h ; terminate with 'c' + high bit jmp send_report ; dsr_action: lda csi_private ; This sequence doesn't accept any private characters ora a rnz ; so quit early if supplied mov a,b ; B is the selection parameter lxi h,pending_report cpi 6 ; is it "please report active position"? jz get_active_pos cpi 5 ; is it "please report status"? rnz ; if not, quit mov a,m ori pend_devstat mov m,a ret ; devstat_report: mvi a,~pend_devstat call prepare_report mvi b,3 ; Assume the worst, which is a report of '3' lda test_results ora a mov a,b jnz devr2 ; If any tests failed, we were right xra a ; Didn't find any errors, so report '0' devr2: ori '0' ; Convert our value to ASCII digiit mov m,a ; add it to the report buffer inx h mvi m,'n'|80h ; 'n' makes this a DSR sequence jmp send_report ; get_active_pos: mov a,m ori pend_curpos ; Received DSR triggers a cursor position report mov m,a ret ; curpos_report: mvi a,~pend_curpos call prepare_report lda curs_row mov b,a lda origin_mode ora a jz skip_tm ; Not in origin mode, so don't need to add margin lda top_margin ; In origin mode, so get cursor row relative to start of area skip_tm: mov c,a ; C <- margin (or 0) mov a,b ; A <- cursor row (absolute) sub c ; A <- cursor row (relative to top of scrolling area) inr a ; Reports call the top row 1, not 0, to match CUP/HVP call ascii_decimal call report_semi lda curs_col inr a ; Left column is 1, to match CUP/HVP call ascii_decimal mvi m,'R'|80h ; 'R' makes this a CPR sequence jmp send_report ; ; print_screen ; ; Triggered in VT52 mode by ESC ], and in VT100 mode by ESC # 7, though that is not mentioned in the ; User Guide. All of the work is done by the GPO, which is explained in the block diagrams in the TM. ; The VT100 main terminal board just commands the print and waits for the GPO to become ready again. ; print_screen: in ior_flags ani iob_flags_gpo rnz ; Exit if we don't have the graphics processor option mvi c,81h call wait_scroll mvi a,0ffh out iow_graphics nop wait_gpo_rdy2: call keyboard_tick in ior_flags ani iob_flags_gpo jnz wait_gpo_rdy2 ret ; ; ascii_decimal ; Convert the unsigned number in A to an ASCII decimal string, loading it ; into the buffer pointed to by HL. ; ascii_decimal: mov e,a mvi d,'0' ; digit to suppress mvi c,100 ; try hundreds first call ascii_digit ; produce an ASCII hundreds digit jz tens ; suppress leading zero mov m,a ; store hundreds digit inx h ; next place in buffer dcr d ; if we've had a hundreds digit, then can't suppress tens! tens: mvi c,10 ; now try tens call ascii_digit ; produce an ASCII tens digit jz units ; suppress leading zero (if possible!) dcr d ; again, can't suppress next digit (but we don't try) mov m,a ; store tens digit inx h units: mov a,e ; get the remaining single-digit number ori '0' ; And make it ASCII mov m,a ; add to buffer inx h ; and increment buffer pointer ret ; ; ascii_digit ; Convert value in E to an ASCII digit for the decimal places given by C, which will probably ; start at 100 and be reduced to 10 on the next call. Returns ASCII digit in A and will ; return with Z flag set if that digit matches D (which is set to '0' before entry). The Z ; flag enables skipping of leading zeroes on reported numbers. Look at routine above for the ; cute trick to not suppress tens digits if we've produced a hundreds digit already. ; ascii_digit: mov a,e mvi b,'0' ; lowest digit we could return repeat_sub: inr b ; assume subtraction will succeed sub c ; before attempting (because of flag states) jp repeat_sub ; and if it worked (no overflow), keep going add c ; last subtraction failed, so restore original minuend dcr b ; and reduce the ASCII digit too mov e,a ; E <- remaining number mov a,b ; A <- ASCII digit for this place cmp d ; Is it zero? (for leading digit suppression) ret ; align_pattern: mvi a,'E' sta cls_char call clear_display mvi a,'E' sta char_und_curs xra a sta cls_char ; Back to normal clear screen ret ; ; rep_char_semi ; Add the character in A to the buffer pointed to by HL, and increment ; pointer. Follow it up with a semi-colon. rep_char_semi: mov m,a inx h report_semi: mvi m,3bh ; Semi-colon, which asm8080 will not allow in quotes, boo. inx h ret ; ; prepare_report ; Setup a scratch buffer at 215ch with the start of an control sequence, ; ESC [, ready to be appended to, and return the address of the next ; character in HL. On entry, A contains the inverse bit mask of the report ; that we are preparing, so it can be removed from the pending pile. ; prepare_report: lxi h,pending_report ana m mov m,a ; this report won't be processed again lxi h,report_buffer mvi m,C0_ESC inx h mvi m,'[' inx h ret ; db 42h ; CHECKSUM ; TBC - tabulation clear tbc_action: mov a,b ; A <- which tabs to clear (0 = here, 3 = all) ora a jnz check_tbc_opt call clear_this_tab ret ; check_tbc_opt: cpi 3 ; If the parameter is not zero or defaulted, rnz ; it must be 3. call clear_all_tabs ret ; set_tab_here: call tab_offs_curs ora m ; set the appropriate tab bit mov m,a ret ; clear_this_tab: call tab_offs_curs cma ; complement the tab bit mask because we're clearing ana m mov m,a ret ; ; clear_all_tabs ; ; Zeroes the entire 17-byte tab_settings area. Can be invoked either from SET-UP or by control sequence. ; clear_all_tabs: lxi h,tab_settings clrnxt: xra a mov m,a inx h mov a,l cpi LOW tab_settings + tablen jnz clrnxt ret ; ; c0_horiz_tab ; Move the cursor to the next horizontal tab. Movement off the end of the tab array is checked for, ; column by column, but movement beyond the 80th column will be caught by a margin check at the end. ; c0_horiz_tab: call tab_offs_curs next_tab_col: inr c ; increment cursor column ora a ; clear carry rar ; rotate tab mask, so carry will mean next column's tab mask will jc next_tab_loc ; be in next location try_tab_loc: mov d,a ; D <- tab mask ana m ; Is there a tab set here? mov a,d ; A <- tab mask jz next_tab_col ; no, try next column jmp chk_rmargin ; yes tab, check we don't stray beyond right margin before setting ; next_tab_loc: inx h ; tab mask for next column is in next tab setting entry mov a,l cpi LOW tab_settings + tablen ; have we gone off end of array? mvi a,80h ; set up a fresh tab mask for new location jnz try_tab_loc ; not off end, try again dcr c ; off end, so column number is before our prospective increment, above chk_rmargin: lda right_margin cmp c jc stop_at_margin mov a,c ; We found a tab, not beyond right margin, all good stop_at_margin: sta curs_col jmp move_updates ; ; tab_offs_curs ; Grab the cursor column and return HL with a pointer to correct location in tab settings, ; and A with a single-bit mask that addresses that location, so we can determine whether ; there is a tab set (or use the mask to change it). ; Returns cursor column in C (as a bonus for the single caller that needs it.) ; tab_offs_curs: lda curs_col mov c,a ; tab_offs ; Alternate entry point used for SET-UP A, where we are iterating over every column in ; order to determine whether to print a 'T' or not. Register A contains column number. ; tab_offs: mov d,a ; D <- cursor column, while we destroy A lxi h,tab_settings ; col_in_bits ; Third entry point (value for money, this one), where A is the number of a bit offset ; into a table pointed to by HL. For this entry point, D must be equal to A on entry. ; On return, HL is advanced to the appropriate location and A is the bit mask ; ; (It strikes me that the two preceding instructions could have been reversed, and this ; entry point made one byte earlier, to grab the "mov d,a" instruction.) ; col_in_bits: rrc ; divide cursor position by 8, in order to get byte offset rrc rrc ani 1fh ; range is really 0 to 16 for 132-column display add l ; offset to HL, assuming HL is aligned to allow single-byte add mov l,a ; HL is now byte containing tab bit mov a,d ; A <- cursor column again ani 7 ; divided by 8 before, now just want remainder mov d,a ; which we will use as a count for a bit shift mvi a,80h ; Bit 7 is tab at column 0, bit 6 is column 1, etc. t_shft: dcr d ; rm ; if count's gone negative, A contains correct mask rrc ; rotate right for next column jmp t_shft ; ; ; try_tx_byte ; Returns with B containing local OR setup ; try_tx_byte: lda local_mode ; Do nothing in local mode lxi h,in_setup ; or setup. ora m mov b,a rnz try_tx2: in ior_flags ani iob_flags_xmit ; Can't send to PUSART until XMIT high rz lxi h,tx_xo_flag ; Is there an XON/XOFF to transmit? mov a,m ora a mvi m,0 dcx h ; HL <- tx_xo_char rz ; No, return mov a,m ; A <- XON/XOFF out iow_pusart_data ret ; try_report: di call try_tx_byte ei mov a,b ; local mode OR setup ora a jnz X0e6d_ ; jump if local mode or setup in ior_flags ani iob_flags_xmit ; Can't send to PUSART until XMIT high rz lda received_xoff ; Have we received XOFF? ora a rnz ; We have, so can't transmit X0e6d_: lxi h,sending_report mov a,m ora a jz pick_report ; If we aren't sending a report already, pick the next one lhld report_action ; otherwise, continue doing the current one pchl ; pick_report: lda pending_report ; Do we have any reports that need sending? ora a rz ; No, return mvi e,0 ; Turn one bit into a report table offset next_report: rar jc find_report inr e inr e ; 16-bit offsets jmp next_report ; find_report: mvi d,0 ; Ready for 16-bit add lxi h,report_table dad d ; Get to report routine mov a,m ; A <- low byte of report routine inx h mov h,m ; H <- high byte of report routine mov l,a ; L <- low byte of report routine pchl ; jump to it! ; ; Address of routines that will produce reports that have ; been asked for. In the ROM, they generally live very close to the ; that set the "pending report" bit :-) ; JUMP TABLE report_table: dw curpos_report ; DSR 6 dw tparm_report ; DECREQTPARM dw ident_report ; DECID/DA dw devstat_report ; DSR 5 dw aback_report ; Response to answerback request (C0 ENQ) dw key_report ; Sending a cursor key sequence ; ; key_report ; ; Responsible for transmitting both single key presses and more multi-key presses, such ; as cursor and other function keys. These are all handled as reports so that they can't ; reports aren't interleaved with key presses or vice versa. ; ; When a key report is being prepared, sending CR will also add LF if newline mode is ; enabled, and both of those controls will enter the queue with high bits set. This routine ; will clear "sending report" as soon as it encounters a character with high bit set. Does ; this have any material impact on the sending of the following LF? Not sure how to test this. ; key_report: lxi h,curkey_queue mov b,m ; B <- first character mov d,h mov e,l ; DE <- HL inx d ; DE points to second character mvi c,8 shift_queue: ldax d ; move all bytes up one place mov m,a ; in queue, because we've removed the first inx h inx d dcr c jnz shift_queue lxi h,curkey_qcount dcr m ; mark that we've popped a byte mov a,m mov c,a ; C <- remaining count jnz q_not_empty lxi h,pending_report mov a,m ani ~pend_key ; If we emptied the queue, we're done with this report mov m,a q_not_empty: lda local_mode ; If we're in local mode, keyboard is locked ora a jnz upd_kbd_locked mov a,c ; A <- remaining count cpi 5 jnc key_tx ; If got less than half a queue to transmit, can clear keyboard xra a ; else, clear it upd_kbd_locked: sta keyboard_locked key_tx: mov a,b ; A <- first character ani 80h ; isolate the high bit ral ; rotate it into carry cmc ; complement rar ; and back again sta sending_report ; say that we're sending a report if character didn't have high bit set lxi h,key_report ; Further characters in the queue will come through here shld report_action ; Fall through. Now send the character we've just retrieved from the queue ; ; report_char ; ; The routine that is responsible for either transmitted reports (including key presses) ; to the host or, if we are in LOCAL or SETUP mode, reflecting them internally to cause ; actions on the screen (so that cursor keys work, we can type normal characters, etc.) ; report_char: mov a,b ani 7fh ; This may be last character, so mask off top bit mov b,a lda local_mode ; Are we in local mode lxi h,in_setup ora m ; or setup? mov a,b ; A <- character to send jnz reflect_char ; jump if in local mode or setup -- denied! out iow_pusart_data ; got a report character out of the door ret ; this routine is jumped to when a report has been prepared send_report: lxi h,cont_report shld report_action xra a sta rep_send_offset inr a sta sending_report cont_report: lxi h,rep_send_offset mov a,m ; A <- offset into report buffer inr m ; increment offset to next character lxi h,report_buffer add l ; add offset to report buffer start mov l,a ; point to character to send mov b,m ; B <- next character of report mov a,b ora a jp report_char ; jump if not last character xra a sta sending_report jmp report_char ; ; send_key_byte ; Cursor keys and other function keys send multiple bytes, so they are gathered before transmission ; like any other report. ; Individual bytes of the sequence are sent through here, with the final byte of the sequence having ; the high bit set. ; send_key_byte: push h push d mov d,a ; D <- byte to store lda setup_b2 ani sb2_autoxon jz noautox ; Auto XON/XOFF is OFF mov a,d sui 91h ani 0fdh jz xhigh ; Jump if this is XON or XOFF with high bit set noautox: lxi h,pending_report mov a,m ori pend_key ; mark the cursor key report as in progress mov m,a add_a_key: lxi h,curkey_qcount mov a,m ; A <- count (= offset) inr m lxi h,curkey_queue ; HL <- buffer address mov e,a ; E <- offset add l mov l,a ; Get to free location mov m,d ; Store key byte mvi a,8dh ; cmp d ; Is this CR with high bit? jnz key_not_cr lda setup_b3 ani sb3_newline mvi d,8ah ; Newline mode implies LF after CR jnz add_a_key ; so go round again. key_not_cr: lda local_mode ; If we are in local mode ora a jnz apply_lock ; Lock keyboard mvi a,5 ; cmp e ; Set carry if offset is greater than 5 mvi a,0 rar ; Rotate that carry into high bit of A, which will lock keyboard apply_lock: sta keyboard_locked popret: pop d pop h ret ; ; Found XON or XOFF with high bit set, in send_key_byte ; xhigh: mov a,d ani 7fh ; bring back to C0 range mov d,a lxi h,tx_xo_flag mov a,m ; Is there an XON/XOFF to transmit? ora a ; jnz sendx ; Yes dcx h ; HL <- tx_xo_char mov a,m ; A <- last XON/XOFF transmitted cmp d ; is it the same as this one? jnz sendx ; No inx h ; HL <- tx_xo_flag mov m,d ; Flag this one to go sendx: mov c,d ; C <- XON/XOFF mvi b,2 call send_xonoff jmp popret ; ; send_xonoff ; On entry: ; C is the character we went to sent, XON or XOFF ; B is the reason we're sending: ; 1 = receive buffer exhaustion [XOFF] or space available [XON]) ; 2 = user-initiated (pressing NO SCROLL) ; send_xonoff: lda setup_b2 ; If we aren't configured for ani sb2_autoxon ; auto XON/XOFF, rz ; exit lda local_mode ; Similarly, if we're in local mode ora a ; then there is no point rnz ; in sending XOFF mov a,c lxi h,why_xoff cpi C0_XOFF mov a,b ; A <- mask for why we're XON/XOFF-ing jz is_xoff cma ; If we're sending asking for XON, be aware that there is more ana m ; than one reason for the XOFF, so only release the mask for mov m,a ; this reason. push psw ani 2 ; If we're released NO SCROLL, mark that sta noscroll pop psw rnz is_xoff: ora m ; Add this XOFF reason to why_xoff mov m,a mov a,c lxi h,tx_xo_char ; If this Xany isn't the same as the last one, cmp m ; then we'll send it rz ; else quit mov m,a ; write to tx_xo_char inx h ; HL <- tx_xo_flag mov m,a ; flag so that tx_xo_char gets sent ret ; ; wait_n_frames ; Only ever called to wait one frame, when screens are (re)initialised and we want the DMA ; to catch up. ; wait_n_frames: lxi h,frame_count add m test_frames: cmp m rz push h push psw lda in_setup ora a cz keyboard_tick pop psw pop h jmp test_frames ; ; Change the extra line's attributes so it becomes part of the scrolling region and is normal width. ; reset_extra: lhld line_25_addr mov a,h ori 0f0h mov h,a shld line_25_addr ; ; clear_row ; On entry: HL is a pointer to start of line in screen RAM. ; clear_row: lda screen_cols ; ; clear_part_row ; On entry: HL is a pointer to screen RAM. A is number of positions to clear (forward) ; clear_part_row: mov b,a ; B <- number of columns to clear mov a,h ; Make sure that HL is proper pointer (no attributes) ani 0fh ori 20h mov h,a adi 10h ; Now make an attribute RAM pointer, for DE mov d,a mov e,l mvi a,0ffh ; A <- default rendition clr_next_col: mvi m,0 ; clear screen RAM stax d ; and attribute RAM inx d ; next column inx h ; ... in both dcr b jnz clr_next_col inr a ; zero A (was 0ffh throughout loop) sta row_clearing ; done clearing of row ret ; ; for scrolling up move_lines_up: mvi b,0ffh jmp move_lines ; ; for scrolling down move_lines_dn: mvi b,1 ; ; at this point, B is either -1 or +1, for the direction of movement ; move_lines: lxi h,top_margin mov d,m ; D <- top margin inx h ; HL ^ bottom_margin mov e,m ; E <- bottom margin mov a,b ; A <- direction ora a mov a,d ; A <- top margin jp grab_phys ; jump if scrolling down (i.e. at top margin) mov a,e ; A <- bottom margin (because scrolling up grab_phys: call phl_num ; A <- physical line number of this row (HL points to entry in LATOFS) mov a,e sub d ; A <- bottom margin - top margin mov c,a ; C <- no. lines to scroll - 1 lda latofs_last ; physical line number of "25th line" shuffle_latofs: mov d,m ; D <- physical line number of old row (margin row, initially) mov m,a ; replace this with row in A (initially, 25th row, because that will come into view) mov a,b ; A <- direction add l ; next logical line (one line nearer beginning when scrolling up) mov l,a dcr c ; decrement number of lines to shift mov a,d ; A <- previous row (one we just overwrote) jp shuffle_latofs ani 7fh ; remove any line attributes from line about to disappear sta latofs_last ; and this becomes the new "25th row" ; fall through ; ; Other routines that perform major reorganisation of the screen, including changing the ; size of a line, jump here so that they can invalidate cursor row before do all the normal ; post cursor move actions. That way, we get a full recalculation of the cursor position, ; because we're claiming it was previously on row -1, which can't be the same as the current row. ; inv_saved_row: mvi a,0ffh sta saved_curs_row jmp move_updates ; ; ; start a jump scroll up start_jump_up: call wait_for_x lda bottom_margin call connect_extra ; Clear extra line and connect it to screen list call move_lines_up ; Move logical lines lda top_margin dcr a jmp scroll_common ; ; start a jump scroll down start_jump_dn: call wait_for_x lda top_margin dcr a call connect_extra call move_lines_dn lda bottom_margin dcr a scroll_common: call calc_shuf1 ei sta shuffle_ready ; A is not zero here lxi h,bottom_margin mov a,m dcx h sub m cpi 17h ; Even jump scrolls can only be completed in one go rnz ; if they apply to full screen, else they must be ; delayed until frame refresh. (TM §4.7.5) ; ; shuffle ; ; This performs a test-and-clear on the shuffle_ready semaphore and then moves the lines pointers ; around as described on TM p.4-92. The connecting of the extra line has ; been done in advance, and the working out of the other connections for shuffle data 1 and 2. ; Now all that remains is for the pointers to be updated. ; shuffle: lxi h,shuffle_ready mov a,m mvi m,0 ora a rz lhld shufdt2 xchg lhld shufad2 ; Place the DMA address in shufdt2 into shufad2 mov m,d inx h mov m,e lhld shufdt1 xchg lhld shufad1 ; Place the DMA address in shufdt1 into shufad1 mov m,d inx h mov m,e reset_shuffle: lxi h,shufdt2 shld shufad2 shld shufad1 ret ; ; curs_line_addr ; Returns pointer to current line in screen RAM ; ; On entry: -- ; On exit: HL is address of first location of line in screen RAM ; curs_line_addr: call curs_phl_num ani 80h ; Grab double-width marker sta curr_line_dbl ; and store it call curs_phl_addr ; HL <- start of cursor line in screen RAM shld start_line_addr ; and store it ret ; ; memset - set DE bytes from (HL) to B memset: mov m,b inx h dcx d mov a,d ora e jnz memset ret ; ; wait_scroll ; ; Certain actions wait for a quiet screen, i.e. scrolling to finish, before they ; take place. The TM says that entering SET-UP mode is one of those. Examination of the ; code shows three other actions that will wait: ; 1. Changing the top and bottom margins ; 2. Scrolling up or down the display (RI or LF), because there is only one extra line, ; and scrolling needs to have finished using it before we can connect is again ; 3. Print screen, which waits before telling GPO to go ; ; oddity - this routine uses C, but no one ever jumps to the line below, which ; sets C to 0. This routine feels like C=0 could be legitimate, but worthwhile finding ; out why it's never called like that. So the line below is UNUSED but is not ; this ROM's checksum address. ; ; C is a combination of two flags, in bit 0 and bit 7 (for ease of testing with rotate ; and carry testing). ; C = 01h allows keyboard processing to take place while waiting ; C = 80h makes routine exit through wait_for_x (still needs bottoming out) ; ; When using for scrolling, i.e. processing index or reverse_index, this routine is called ; with C=1, and that results in it exiting with HL pointing to scroll_pending. The callers ; then change scroll_pending through this pointer, which was quite hard to find! ; mvi c,0 ; UNUSED wait_scroll: lxi h,scroll_pending di lda smooth_scroll ; in smooth scroll? ora m ; or scroll pending? ei jz scroll_done mov a,c rar push b ; save our wait flags cc keyboard_tick call update_kbd pop b ; restore wait flags jmp wait_scroll ; scroll_done: mov a,c ral ; Test bit 7 rnc jmp wait_for_x ; init_screen: lxi h,0670h ; DMA address (2006h) shld line1_dma ; blank screen by pointing direct to fill lines xra a ; A <- 0 sta scroll_pending ; there is no scroll pending sta smooth_scroll ; we are not smooth scrolling now sta scroll_scan out iow_dc012 ; DC012 <- "low order scroll latch = 00" mvi a,4 out iow_dc012 ; DC012 <- "high order scroll latch = 00" call reset_shuffle ; feels like cleaning up shuffle ei mvi a,1 call wait_n_frames ; allow DMA to blank screen lxi h,main_video ; (first byte of screen definition) mov a,h adi 10h ; Attribute RAM is Screen RAM + 1000h mov d,a mov e,l ; DE <- start of attribute RAM for default display lxi b,0d2fh ; 22d0h + 0d2fh = 2fffh ; ; clear screen, including AVO's additional 1K of screen RAM ; cls: lda cls_char mov m,a ; "clear" screen RAM (maybe to 'E', for alignment display) inx h mvi a,0ffh stax d ; Normal attributes inx d dcx b mov a,b ora c jnz cls ; lda cls_char sta char_und_curs xra a sta curs_row sta curs_col mvi a,0ffh sta rend_und_curs ret ; ; make_screen ; Write all the line terminators for a screen of a given width in normal screen RAM. ; Writes pointers only; makes no attempt to zero the display. ; ; On entry: C is number of columns on screen ; make_screen: xra a ; A <- 0 sta scroll_pending ; there is no scroll pending wait_smooth: lda smooth_scroll ; are we in middle of smooth scroll? ora a jnz wait_smooth lxi h,main_video ; HL <- start of screen RAM mvi b,0 ; BC <- number of columns dad b ; advance to end of first line call last_row ; B <- last row number (23 or 13) inr c ; C <- number of columns + 1 (oddity in make_lines) call make_lines push h mvi b,1 ; Need a 24th line call make_lines pop h mvi m,7fh ; Terminate 23rd line (already done this?) inx h ; HL <- 24th line DMA address (big endian) shld UNREAD_X2054 ; Store this mvi m,70h ; Make DMA address for 24th line 7006h (i.e. fill lines) inx h mvi m,6 mov a,c ; A <- number of columns + 1 call add_a_to_hl ; Get to end of 24th line mvi m,7fh ; Write terminator (first time!) dcr c ; C <- number of columns mvi a,3 ; Point initial screen DMA to line 1 (2003h) sta line0_dma + 1 lxi h,main_video_be ; byte-swapped video address shld line1_dma ; Point to our new screen ret ; ; Given a pointer HL, to end of a line, make another B lines of (C - 1) columns wide ; (create a full screen display) ; HL isn't advanced after writing low byte of screen address, so C is passed in ; with number of columns + 1 (small oddity) ; make_lines: mvi m,7fh ; write terminator inx h ; advance to point at high byte (DMA order) mov d,h ; DE <- HL mov e,l inx d ; In DMA terms, DE is byte-swapped, so advance 2 locations inx d mov a,d ; And add normal line attributes ori 0f0h mov m,a ; Write high byte + attrs first inx h mov m,e ; Then low byte mov a,c ; A <- columns + 1 (didn't increment HL already) call add_a_to_hl ; advance to next line dcr b jnz make_lines ret ; ; make_line_t ; ; Create the physical line address and logical offset tables for screen rows. ; The logical offset table is what the TM calls LATOFS. ; ; On entry, C is number of columns ; make_line_t: lxi h,pline_addr ; Start of table of physical line addresses inr c ; Each line is columns + 3 terminators bytes long inr c inr c lxi d,main_video mvi b,0 ; Make BC <- columns + 3 (for 16-bit additions) mvi a,25 store_physline: mov m,e ; Store address of physical line in table inx h mov m,d inx h xchg ; HL <- screen RAM address dad b ; get to next line, past terminators too xchg ; DE <- next line screen RAM address dcr a ; Do all 24 lines jnz store_physline sta top_margin ; new screen, reset top margin call last_row ; B <- last row number mov a,b sta bottom_margin ; and bottom margin inr a ; row number of one line beyond bottom margin, sta latofs_last ; as last place in latofs lhld pline_extra ; Now grab screen address of 0-based row 24 mvi a,23 cmp b jz ok24 ; unless this is a 14-row screen, in which case lhld pline_addr+(14*2) ; use 0-based row 14 (20deh) ok24: mov a,h ori 0f0h mov h,a shld line_25_addr ; extra line attributes to single width lxi h,latofs ; Now write LATOFS, with all logical lines pointing xra a ; to the same physical lines, so just 0 to 23. next_lof: mov m,a inr l ; [* fragile *] LATOFS can't go just anywhere inr a dcr b jp next_lof ret ; wait_for_x: di lda shuffle_ready ora a jz no_shuffle do_tick: ei call keyboard_tick jmp wait_for_x ; no_shuffle: lda smooth_scroll ; are we in middle of smooth scroll? ora a jnz next_scan lda scroll_pending ora a ei rz ; no scroll pending, so exit jmp do_tick ; next_scan: lda scroll_dir lxi h,scroll_scan add m daa ani 0fh jz do_tick ei ret ; ; last_row ; Returns with B set to last row number, i.e. 13 or 23 ; last_row: push h mvi b,23 ; assume we have 24 lines lda columns_132 ; unless we're in 132-column mode lxi h,avo_missing ana m ; AND we DON'T have AVO pop h rz mvi b,13 ; in which case, we only have 14 lines ret ; ; calc_shuf1 ; Work out which line will be the new top line and take the line that will disappear and store it as ; the new extra line. ; ; On entry: A is the top or bottom margin - 1 (i.e. RI at top of full screen will enter here with A = 23) ; calc_shuf1: ora a jp pos_margin lxi h,line1_dma ; HL <- address of video line (big-endian) push h mov a,m ; A <- high byte the video address inx h ; HL points to low byte mov l,m ; L <- low byte of video address ori 0f0h ; Change attributes of high byte to be scrolling region, normal size mov h,a ; H <- high byte of video address shld line_25_addr ; stow it as new extra line address call next_line_addr ; DE <- DMA address of next line pop h ; HL <- address that will need changing to point to line 2 (new top line) mov b,d mov c,e ; BC <- DMA address of line 2 jmp store_shufad1 ; pos_margin: call to_line_n call next_line_addr ; DE <- DMA address of line we're losing from bottom push h push d xchg ; HL <- DMA address of losing line call next_line_addr ; DE <- address of line after (fill address) mov b,d mov c,e ; BC <- fill address pop d ; DE <- losing line address, again mov a,d ori 0f0h ; Restore its line attributes mov h,a mov l,e ; HL <- (corrected) losing line address shld line_25_addr ; which now becomes available as the extra line pop h ; HL <- new bottom line address mov a,h ori 9fh ; testing for double-width attributes inr a jnz not_sinwid1 ; If line isn't single-width, there are two pointers to next line call eoline_addr store_shufad1: di ; Make shufad1 & shufdt1 consistent before vertical refresh shld shufad1 ; Now store the address of the terminating info to be updated jmp store_shufdt1 ; not_sinwid1: call real_addr lda screen_cols rrc ; Need to get to halfway terminator because line is double-width mov d,a ; D <- half screen width call add_a_to_hl inx h ; HL <- next DMA address di shld shufad1 ; This is the address we'll write to during shuffle mov a,d ; A <- half screen width call add_a_to_hl ; Get to the address we aren't using at the moment mov m,b ; and make it consistent with the one we'll update during shuffle inx h mov m,c store_shufdt1: mov h,b mov l,c shld shufdt1 ei ret ; ; connect_extra ; In advance of the shuffle happening, connect the extra line to the screen lines. ; If we are indexing down, the extra line will be connected to the first line ; (within margins). If we are reverse indexing then we are shifting all the lines ; down and the extra line connection will be made to the second line. At the same ; time, we write shufad2 and shufdt2, per TM Figure 4-7-9, so that one of the ; existing lines will get a join to the extra line when the shuffle gets performed. ; ; On entry: A is the row number of the bottom margin, or the top margin - 1 (so may be negative) ; connect_extra: push psw call reset_extra ; make the cursor line scrollable pop psw ora a lxi h,line1_dma ; set HL in case we're at the top and jm at_top ; the extra line will be connected after the fill line call to_line_n ; otherwise work out which line will be connected to extra mov a,h ; A <- high byte of screen RAM address with attrs ori 9fh inr a jnz not_sinwid2 ; jump if line attrs were not single width call eoline_addr ; HL <- next line DMA address at_top: di shld shufad2 ; points to line DMA address mov b,m inx h mov c,m ; BC <- line DMA address + attrs jmp conn_shuf2 ; not_sinwid2: call real_addr lda screen_cols ; As the line we're connecting to extra isn't single rrc ; width, work out where the terminator is (i.e. half way) mov b,a call add_a_to_hl inx h ; HL <- next DMA address di shld shufad2 ; This is the address we'll write to during shuffle mov a,b ; A <- half width mov b,m ; Grab the current DMA address inx h mov c,m call add_a_to_hl ; move to full width (HL points one byte too far, to DMA low byte) xchg ; DE <- DMA low byte lhld line_25_addr xchg mov m,e ; Place LOW byte of extra line address dcx h ; Move back to high byte mov m,d ; Place HIGH byte of extra line address ; Mid-line address (the active one) will be updated during shuffle conn_shuf2: lhld line_25_addr ; Line 24 will have its end pointer updated shld shufdt2 ; to point to the extra line during shuffle call eoline_addr mov m,b ; Update extra line's next DMA address now inx h mov m,c ei ret ; ; to_line_n ; On entry: ; A is the row number of physical screen to get to (0 gets to address line1_dma points to) ; On exit: ; HL points to first character of screen RAM of line ; to_line_n: inr a mov b,a lxi h,line1_dma adv_line: mov a,m ; A <- high byte of screen DMA address (and attrs) inx h mov l,m ; L <-low byte mov h,a ; H <- high byte dcr b rz call eoline_addr ; advance to next DMA address jmp adv_line ; ; Given start of line address in HL, returns DE with address of next line ; next_line_addr: push h call eoline_addr mov d,m ; D <- high byte (incl. attrs) inx h mov e,m ; E <- low byte pop h ret ; ; Given start of line address in HL, add screen width to get end of line eoline_addr: call add_cols_to_hl inx h ; real_addr ; ; On entry, HL is an address in screen RAM with the line attribute and scrolling region bits ; in the top four bits. Mask out these attributes and add the 2000h offset to get a real address. ; real_addr: mov a,h ani 0fh ori 20h mov h,a ret ; line_attr_dwl: call double_line db 50h ; dhl_top_action: call double_line db 30h ; dhl_bot_action: call double_line db 10h ; ; double_line ; ; The single byte at the return address is the line attributes to be applied to the current line. ; We are not going to go back there, so no attempt is made to restore the stacked address. ; As these are all double-width line attributes, the right margin must be adjusted, and the cursor ; pulled back onto screen if necessary. ; double_line: call wait_for_x lxi h,latofs ; Find current physical line number in LATOFS ` lda curs_row ; | duplicates add l ; > curs_phl_num mov l,a ; | mov a,m ; , ori 80h ; Mark the current row in LATOFS as double width mov m,a ; We've now set bit 7 of the physical line number in LATOFS, but this doesn't affect ; the next routine, even though it again looks up a physical line number in LATOFS, ; as the (corrupted) line number it receives will be doubled in order to extract an ; address from the table at pline_addr. ; call curs_phl_addr ; HL <- address of cursor line in screen RAM? call halve_line pop h ; Grab return address (which we will discard) mov a,m ; A <- line attributes to be applied call add_line_attrs lda right_margin lxi h,curs_col ora a ; clear carry because RAR brings it into bit 7 (why not use RRC?) rar ; A <- right margin / 2 cmp m jnc inv_saved_row ; jump if right margin / 2 is still greater than current cursor column ; ; The next two lines look odd because they aren't storing a screen RAM address in ; cursor_address, as you'd expect. However, we're about to go into move_updates, ; which is going to attempt to restore the old character under the cursor and the ; old rendition in attribute RAM. If we allowed that to happen with the cursor just ; beyond the margin, this restoration could wreck the new terminators, so by ; storing the address of these locations in the cursor address, move_updates ; will place the character under the cursor in char_und_curs, a cunning no-op. ; lxi h,char_und_curs shld cursor_address jmp inv_saved_row ; ; Process DECREQTPARM - ESC [ <sol> x tparm_action: lda csi_p1 cpi 2 ; request parameter can only be 0 or 1 rnc sta tparm_solicited ; If they are allowed, exiting SET-UP will send a TPARM report setup_tparm: lxi h,pending_report mov a,m ori pend_tparm mov m,a ret ; ; tparm_report ; ; Produce a DECREPTPARM sequence: ; ESC [ <sol>; <par>; <nbits>; <xspeed>; <rspeed>; <clkmul>; <flags> x ; tparm_report: mvi a,~pend_tparm call prepare_report lda tparm_solicited ; A <- solicited flag (0 or 1) ori '2' ; convert to ASCII digit '2' or '3' call rep_char_semi ; <sol> lda setup_b4 ; A <- comms + power settings push psw ; save for later, when we'd like bits/char ani 0c0h ; keep just parity bits ori 18h ; mix in half an ASCII '0' add a ; shift even/odd into carry inr a ; and convert "no parity" into '1' jp skip_odd_even ; skip to display if parity is off (new bit 7) rar ; bring carry back into bit 7 rlc ; and rotate it into bit 0 ori 4 ; making odd parity '4' and even '5'|80h ani 7fh ; clean up that high bit skip_odd_even: call rep_char_semi ; <par> mvi b,'1' ; prepare "8 bits" answer pop psw ; A <- comms + power settings again ani 20h ; bit 5 is zero for "7 bits" jnz skip_bit_adj ; display if we've got right answer already inr b ; change to '2' for "7 bits" skip_bit_adj: mov a,b call rep_char_semi ; <nbits> lda tx_spd rrc call ascii_decimal ; <xspeed> call report_semi lda rx_spd rrc call ascii_decimal ; <rspeed> call report_semi mvi a,'1' ; <clkmul> is a constant call rep_char_semi lda setup_b5 ; report STP switch values ani 0f0h ; as with all other setup blocks, only top 4 bits rrc rrc rrc rrc ; which we shift down to report as number 0 to 15 call ascii_decimal mvi m,'x'|80h ; 'x' for DECREPTPARM sequence final jmp send_report ; ; DECSWL - single-width-line line_attr_swl: lxi h,curr_line_dbl mov a,m ora a rz ; Nothing to do if current line is already single width call wait_for_x lxi h,latofs lda curs_row ; Retrieve logical line number entry add l mov l,a mov a,m ani 7fh ; Zero bit 7, the double width indicator mov m,a ; place back call curs_phl_addr ; HL <- screen address of cursor row lda screen_cols rrc mov b,a ; B <- half number of columns call add_a_to_hl ; Move halfway across line, to where the "half" terminator is xra a zap_2nd_half: mov m,a ; Remove terminator, DMA address and all following characters inx h dcr b jnz zap_2nd_half mvi a,0f0h sta saved_curs_row call add_line_attrs xra a sta curr_line_dbl jmp move_updates ; ; curs_phl_loc curs_phl_loc: lda curs_row call phl_num ; phl_loc ; Given a physical line number in A, look up the address of this line ; in an address table (doubling and adding, so we're returning a proper ; address in HL). phl_loc: lxi h,pline_addr add a add l ; [* fragile *] pline_addr table must not go over 8-bit boundary mov l,a ret ; ; curs_phl_addr ; ; Get the address of the physical line in screen RAM of the cursor row ; Returns this in HL. ; curs_phl_addr: call curs_phl_loc ld_hl_from_hl: mov a,m inx h mov h,m mov l,a ret ; ; add_line_attrs ; ; Apply the line attributes in A to the current (cursor) row. This involves finding the start address ; of the previous line and marching across to its terminating bytes, because they determine the attributes ; for this line, as well as the address. Two wrinkles: ; ; 1) If this is the first line, then we have to modify the attributes as stored in the initial ; screen layout (at address line1_dma) ; 2) LATOFS stores the physical line number with bit 7 high if that line (the previous one, in our case) ; is double-wdith. In that case, the terminators have been placed half across the line, instead of ; screen width columns across. ; add_line_attrs: ani 70h ; Censor attributes (don't affect scrolling region, for example) mov b,a lda curs_row ; It's the terminating bytes for the previous line that decides dcr a ; the attributes (and address) for this one lxi h,line1_dma ; Set up for initial line address if we were at row 0 anyway jm set_attrs ; yep, we were call phl_num ; As we weren't at beginning, grab physical line number from LATOFS mov d,a ; D <- physical line number ani 7fh ; Get rid of any double line marker call phl_loc ; HL <- address in physical line table call ld_hl_from_hl ; HL <- start of line in screen RAM lda screen_cols rrc ; A <- screen width / 2 mov e,a ; E <- screen width / 2 inx h ; inr d ; dcr d ; set flags for phys line number from LATOFS (i.e. was it doubled?) mvi d,0 ; Set up DE to be offset of half-way across line dad d cm set_attrs ; If this line was double-width, do middle first (CALL) dad d ; and then (or just) the end of line set_attrs: mov a,m ; A <- first (high) byte of DMA address + attrs ani 8fh ; Remove line attrs, keeping scroll flags + address ora b ; Place new line attributes mov m,a ; Store new high byte of DMA address ret ; ; On entry (from double_line at least), HL is the screen address of start of current line ; This routine halves the length of the line by moving this line's terminator and next screen address to half way. halve_line: lda screen_cols rrc ; A <- screen width / 2 mov d,h ; mov e,l ; DE <- start of current line call add_a_to_hl ; HL is half way across line xchg ; DE <- half way, HL <- start call add_cols_to_hl ; HL <- addr of right margin + 1 (terminator) mvi b,3 end_byte_loop: mov a,m ; get post-EOL bytes (terminator first, then two screen addresses) stax d ; place half way inx d inx h dcr b jnz end_byte_loop ret ; add_cols_to_hl: lda screen_cols add_a_to_hl: add l mov l,a rnc inr h ret ; ; curs_phl_num ; Return physical line number of cursor row in A ; phl_num ; Return physical line number of logical row A, in A ; curs_phl_num: lda curs_row ; phl_num: lxi h,latofs add l mov l,a mov a,m ret ; ; RM - reset modes rm_action: mvi c,0 jmp do_modes ; ; SM - set modes sm_action: mvi c,0ffh ; ; At this point, we are either setting (C = 0ffh) or resetting (C = 0) modes. The mode number is in B. do_modes: lda csi_private ora a lxi h,ansi_mode_t ; We're dealing with ANSI modes jz mode_lookup ; if there isn't a private character cpi '?' ; But if the private character isn't '?', quit rnz lxi h,dec_mode_t ; Look up DEC private modes mode_lookup: mov a,b ; A <- mode number mov b,c ; B <- set/reset call find_action_a ret ; JUMP TABLE dec_mode_t: db 1 ; DECCKM - cursor key dw decckm_mode db 2 ; DECANM - ANSI/VT52 dw decanm_mode db 3 ; DECCOLM - column dw deccolm_mode db 4 ; DECSCLM - scrolling dw decsclm_mode db 5 ; DECSCNM - screen dw decscnm_mode db 6 ; DECOM - origin dw decom_mode db 7 ; DECAWM - auto wrap dw decawm_mode db 8 ; DECARM - auto repeating dw decarm_mode db 9 ; DECINLM - interlace dw decinlm_mode db 0 ; end of table ; ; Only a single ANSI mode can be set/reset: LNM - line feed new line mode ansi_mode_t: db 20 dw lnm_mode db 0 ; end of table decckm_mode: lxi h,mode_ckm mov m,b ret ; decanm_mode: call apply_mask_sp dw setup_b2 db sb2_ansi jmp set_charsets lnm_mode: call apply_mask_sp dw setup_b3 db sb3_newline ret ; decom_mode [* BUG *] ; This routine changes origin mode and sends the cursor to the home position. ; However, this routine contains a bug because it calls cursor_home, and that routine ; clears the first two CSI parameters before dropping into the general cursor positioning routine. ; ; That means that, if DECOM is the first mode in an RM or SM sequence, the second mode will be ; cleared by cursor_home and won't be executed. This can be shown by using a highly visible change ; for the second parameter, such as DECSCNM (screen mode - light or dark). ; ; For example: ; 1. Go into reverse screen mode: ESC [ ? 5 h ; 2. Go into normal screen mode: ESC [ ? 5 l ; 3. Set origin mode and reverse screen mode: ESC [ ? 6 ; 5 h ; ; The third sequence will completely ignore DECSCNM (private mode 5). However, third and ; subsequent modes will still be processed, so this works: ; ; 4. Set origin mode and reverse screen mode: ESC [ ? 6 ; ; 5 h ; decom_mode: lxi h,origin_mode mov m,b call cursor_home ; *BUG* (_see_ cursor_home) ret ; decsclm_mode: call apply_mask_sp dw setup_b1 db sb1_smooth ret decscnm_mode: call apply_mask_sp dw setup_b1 db sb1_lightback jmp update_dc012 deccolm_mode: lxi h,columns_132 mov m,b call clear_display ret ; decarm_mode: call apply_mask_sp dw setup_b1 db sb1_autorep ret decawm_mode: call apply_mask_sp dw setup_b3 db sb3_autowrap ret decinlm_mode: call apply_mask_sp dw setup_b3 db sb3_interlace jmp update_dc011 ; apply_mask_sp ; The stacked return address is the address of a setup switch block and the following byte ; is a bit mask that must either be set (B = 0ffh) or reset (B = 0). ; apply_mask_sp: pop h ; HL <- return address mov e,m ; E <- byte after inx h ; mov d,m ; D <- byte after that inx h ; mov a,m ; A <- mask value inx h ; increment hl again, to make new return address xchg ; DE <--> HL (DE is now return address) mov c,a ; C <- mask value cma ; A <- all the other bits set ana m ; clear our bit in location mov m,a ; and write it back mov a,b ; get all ones if we'd like to set, or all zeros to reset ana c ; either mask for set, or zero for reset ora m ; (we already reset the mode, so now possibly set it) mov m,a ; apply to location xchg ; HL <- return address again pchl ; return ; keyboard_tick: call update_kbd ani 10h ; Probably intended to prevent processing when keyboard locked, cz process_keys ; but see notes below. jmp try_report ; ; If the keyboard is ready to receive and isn't locked, make up the status byte to transmit ; to it. Then do the cursor timer housekeeping. ; Return value: ; If keyboard is not ready to receive, A is 0 ; If UNWRIT_X2077 had a purpose, that value would be returned in A ; If smooth scrolling or pending scroll, A will be 1 or -1 (direction of scroll) ; Otherwise it will be the OR of the high and low bytes of the cursor timer. ; ; Because the keyboard locked flag in the keyboard status is 10h, it feels as if this routine ; was originally intended to return when the keyboard was locked, which would naturally mean ; that there was point calling process_keys. ; update_kbd: in ior_flags ani iob_flags_kbd rz ; Keyboard not ready to receive lxi h,keyboard_locked mov a,m ora a jz kbd_not_locked mvi a,iow_kbd_locked kbd_not_locked: lxi h,local_mode ora m ; Local mode is 20h, to set LOCAL LED lxi h,led_state ; Make up a keyboard command from all status bytes ora m inx h ; HL <- kbd_online_mask (can also affect click if bell is sounding) ora m inx h ; HL <- kbd_click_mask ora m mvi m,0 ; zero "click" after use: kbd_click_mask <- 0 inx h ; HL <- kbd_scan_mask ora m mvi m,0 ; zero "start scan" after use: kbd_scan_mask <- 0 out iow_keyboard lxi h,num_kbd_updates inr m lda UNWRIT_X2077 ora a rnz lda smooth_scroll ; are we in middle of smooth scroll? lxi h,scroll_pending; or are we about to start one? ora m rnz ; exit if either scroll condition is true lhld cursor_timer ; Maintain cursor timer dcx h mov a,h ora l jz curs_timer_up shld cursor_timer ret ; ; Cursor time has counted down to zero curs_timer_up: lda cursor_visible ; toggle cursor visibility xri 0ffh sta cursor_visible lxi h,0212h ; Cursor will be on for about 2/3 second jnz curs_was_off lxi h,0109h ; Cursor will be off for about 1/3 second curs_was_off: shld cursor_timer ; Set new timer lhld cursor_address mov b,m ; B <- current char at cursor position lda curs_char_rend ; A <- 0x80 or 0, depending on whether we're using base rendition xra b ; Flip bit, if bit fit to flip mov m,a ; Place back on screen lxi d,1000h ; Make an address in attribute RAM dad d lda curs_attr_rend ; Again, flip cursor rendition xra m mov m,a ; and replace ret ; db 74h ; CHECKSUM ; el_action: mov a,b ; A <- selective parameter ora a jz el_to_end ; default is "erase from cursor to end of line" dcr a jz el_to_start ; Ps = 1 means "beginning of line to cursor" dcr a rnz ; No options beyond Ps = 2 call el_to_end ; Ps = 2 means "erase whole line" el_to_start: lda curs_col mov b,a inr b ; number of locations is cursor column (0-based) + 1 lhld start_line_addr ; from the start of the line jmp blank_chars ; el_to_end: lda curs_col mov b,a lda curr_line_dbl ora a ; NZ flag if current line is double width lda screen_cols jz not_double rrc ; divide columns by 2, on double width line not_double: sub b mov b,a ; B <- screen columns - cursor column lhld cursor_address ; ; blank the number of characters in B, from the screen RAM position in HL ; blank_chars: mov a,h ; Convert screen address in HL adi 10h ; to attribute RAM address in DE mov d,a mov e,l mvi a,0ffh ; default rendition blank_loop: stax d ; blank attributes mvi m,0 ; blank screen inx h ; next addresses in screen RAM inx d ; and attribute RAM dcr b jnz blank_loop sta rend_und_curs ; default rendition is 0ffh xra a sta char_und_curs ; and character under cursor is blank, 00h ret ; ; ed_action ; ; Implements the ED (erase in display) control sequence, which has a single selective parameter ; ; Lines that are wholly erased are made single width. The cursor line's width attribute is only ; changed if the cursor is in column 0 when "erase to end of screen" is invoked, or the entire ; display is erased. ; ed_action: mov a,b ; A <- selective parameter ora a jz ed_to_end ; Ps = null/0 is "erase from cursor to end of display" dcr a jz ed_to_start ; Ps = 1 is "erase from start of screen to cursor" dcr a rnz ; No options beyond Ps = 2, which is "erase entire display" call ed_to_start call ed_to_end jmp line_attr_swl ; ; ed_to_start: lxi h,curs_row mov a,m ; A <- cursor row push psw mov b,a ; B <- cursor row xra a ; mov m,a ; zero cursor row, for the sake of erase_n_lines mvi c,-1 ; Pretend cursor row is -1 call erase_n_lines pop psw mov m,a ; Now restore proper cursor row call curs_line_addr ; HL <- start of cursor line in screen RAM jmp el_to_start ; this line does not have line attributes changed ; ed_to_end: lda curs_col ora a ; If the cursor is at the start of the line, the line is made cz line_attr_swl ; single width, otherwise not call el_to_end lxi h,curs_row mov a,m ; A <- cursor row (for restoration later) push psw mov c,a ; C <- cursor row mvi a,23 sub c ; A <- number of complete lines to be erased mov b,a call erase_n_lines pop psw mov m,a ; restore original cursor row jmp curs_line_addr ; correct relevant pointers ; ; erase_n_lines ; On entry: HL points to curs_row ; B is number of lines to erase (this may be zero) ; C is one less than the row number of the first line to be *wholly* erased erase_n_lines: dcr b rm ; done erasing whole lines inr c ; increment row number mov m,c ; write cursor row push b push h call curs_phl_num ; A <- physical line number of cursor row, HL <- LATOFS entry ani 7fh ; ignore any double-width marker mov m,a ; Erased lines become single width mvi a,70h ; single width line attributes call add_line_attrs call curs_line_addr ; HL <- start of line in screen RAM lda screen_cols mov b,a call blank_chars pop h pop b jmp erase_n_lines ; ; Set top and bottom margins stbm_action: mvi c,81h call wait_scroll call last_row ; B <- last row number lda csi_p1 ; A <- first parameter (top margin) ora a jz p1_def ; If the first parameter is not zero (or zero by default) dcr a ; reduce by one for internal numbering p1_def: mov d,a ; D <- top margin lda csi_p2 ; A <- second parameter (bottom margin) ora a ; Is the bottom margin defaulted, or zero? jnz supp_b ; No, use it mov a,b ; else make it the bottom of the screen inr a supp_b: dcr a mov e,a ; E <- bottom margin mov a,b ; A <- last row cmp e ; If last row < bottom margin rc ; don't do anything mov a,d ; A <- top margin cmp e ; If top margin > bottom margin rnc ; don't do anything lxi h,top_margin mov m,d ; store top margin inx h mov m,e ; store bottom margin mov c,e ; C <- bottom margin mov b,d ; B <- top margin mov a,c sub b inr a ; A <- bottom - top + 1 mov e,a ; E <- lines in scrolling region lxi h,line1_dma mov a,b ; A <- top margin ora a jz n_scroll_reg ; jump if top margin is top row mov d,b ; D <- top margin top_mar_loop: mov a,m ; A <- high byte of DMA address ani 7fh ; remove scroll region flag mov m,a ; put back call advance_line dcr d jnz top_mar_loop ; follow line links until we're at first line of new scroll region n_scroll_reg: mov a,m ; A <- high byte of DMA address ori 80h ; add scroll region flag mov m,a ; put back call advance_line dcr e jnz n_scroll_reg mvi a,23 sub c ; A <- number of non-scrollable lines at bottom jz done_lines mov d,a ; D <- line count bot_mar_loop: mov a,m ; A <- high byte of DMA address ani 7fh ; remove scroll region flag mov m,a ; put back call advance_line dcr d jnz bot_mar_loop done_lines: mov a,b ; A <- top margin sta top_margin ; store mov a,c ; A <- bottom margin sta bottom_margin ; store lxi h,latofs ; Now work our way through the logical address offset table, mvi c,24 ; halving each line again, if appropriate. This way, we grab ; the terminating line attributes at the full length of each line, ; which we've just modified, to re-copy them into the middle of each ; double-width line. half_line_loop: mov a,m ; Grab physical number of logical line ora a ; jp skip_single ; if it isn't double width, skip it push h call phl_loc ; HL <- addresss of pline_addr entry for this line mov a,m inx h mov h,m mov l,a ; HL <- start of screen RAM for line call halve_line pop h skip_single: inx h dcr c jnz half_line_loop jmp cursor_home ; ; advance_line ; On entry: HL points to high byte of DMA address, A contains that byte ; On exit: HL points to high byte of next DMA address ; advance_line: inx h ; HL points to low byte of DMA address mov l,m ; L <- low byte ani 0fh ; A <- high byte already, which ori 20h ; we convert into proper address (i.e. discard line attributes) mov h,a ; HL <- points to first character of next line inx h ; and increment jmp add_cols_to_hl ; so on return HL <- high byte of next DMA address ; ; move_updates ; This routine is called any time that cursor row or column have been updated. This has a lot of work to do: ; 1. Place the old character and rendition where the cursor was ; 2. Possibly adjusting cursor position if we've moved to a double-width line ; 3. Triggering margin bell if this movement was caused by receiving printable characters ; 4. Saving the character and rendition of the new cursor position. ; move_updates: lxi h,0dh ; set a tiny cursor timer shld cursor_timer xra a ; and record cursor visibility as off sta cursor_visible ; so it will come back quickly after movement lhld cursor_address lda char_und_curs mov b,a ; B <- char under cursor mov m,a ; place char back on screen mov a,h ; move HL to point to attribute RAM adi 10h mov h,a lda rend_und_curs mov m,a ; place old rendition lda screen_cols dcr a mov e,a ; E <- last column number lda in_setup ora a jnz skip_half_col ; In setup, can't have double-width cursor line lda curs_row lxi h,saved_curs_row cmp m jz same_row mov m,a ; save the new row call curs_line_addr xra a ; We didn't get here by typing, so clear the flag sta margin_bell ; that allows the margin bell to be triggered by movement lxi h,curr_line_dbl ; Is current line double width? mov a,m ora a jz skip_half_col ; No, so last column number is correct mov a,e ; Double-width, so halve last column number (e.g. 79 -> 39) dcr a ora a ; clear carry for the rotate rar mov e,a skip_half_col: mov a,e ; A <- last column number (adjusted, if necessary, for double width) sta right_margin same_row: lxi h,right_margin ; test if cursor has moved beyond right margin lxi d,curs_col ldax d ; A <- cursor column cmp m jc less_rmargin ; jump if less than margin mov a,m ; otherwise place margin stax d ; into current column less_rmargin: lda last_curs_col adi 8 ; Margin bell is triggered exactly 8 columns from right edge sub m jnz no_margin_bell inx h ; HL <- margin_bell ora m ; A was zero, so now NZ if we want a margin bell jz no_margin_bell call c0_bell xra a ; now don't permit another margin bell until typed char sta margin_bell ; sets this flag again (_see_ process_keys) no_margin_bell: lda curs_col sta last_curs_col lhld start_line_addr call add_a_to_hl shld cursor_address ; Make new cursor address mov a,m ; Grab character "under" cursor sta char_und_curs ; store it until cursor moves mov b,a ; B <- new character under cursor mov a,h ; move HL to point to attribute RAM adi 10h mov h,a mov a,m ; A <- rendition "under" cursor sta rend_und_curs ; store it until cursor moves lhld cursor_address ; HL <- new cursor address mov m,b ; place new/old character back ret ; ; Entry point for CSI state, initialising parameters, private flag, intermediate ; and final characters start_csi: mov b,a ; B <- received char while we initialise state lxi h,gather_params ; private flag and params are first part of control sequence shld char_action ; set up processing for next character xra a sta param_value ; zero out csi_param state sta num_params sta inter_chars ; zero out the params array lxi h,csi_params mvi c,0fh xra a zero_csi: mov m,a ; zero this parameter inx h dcr c jnz zero_csi ; lxi h,csi_private ; mvi m,0 ; mark that we haven't seen a private character mov a,b ; A <- received char cpi '@' ; is it a final character? jnc gather2 ; yes cpi '<' ; less than flag character range? jc gather2 ; yes, start building parameter value mov m,a ; store flag character ret ; ; This is the entry point for all subsequent characters while we're in this state. ; ; This section has to deal with parameter values, which are sequences of ASCII digits '0' to '9', ; separated with ';' and recognising intermediate and final characters. Intermediates are from ; SP (20h) to '/' (2fh), Finals are from '@' (40h) to '~' (7eh) and most other characters will ; invalidate the sequence. Because the VT100 doesn't support any sequences with intermediates, ; it gathers them, along with other invalid characters, and only disposes of them when a Final ; character has been found and the sequence is executed. ; ; This section has a bug at the marked line. Any character other than a digit is supposed to be ; passed through to finish_param, which puts aside the current character while the gathered current ; numeric parameter (param_value) is placed at the end of the list (csi_params). Then, the current ; character is restored from the stack and we drop through to detect_i_f, to determine what to do ; with the current character. Characters above the digit range, like the semicolon or final characters, ; will be dealt with correctly here, but characters below digit range (intermediates) have already ; been corrupted by having 30h subtracted from their value, leaving them in the range 0f0h to 0ffh, ; and detect_i_f will incorrectly treat them as final characters, leading to immediate execution of ; the sequence, with a final character in this high range, which fails to match any of the tables. ; ; A valid but unsupported sequence like: ESC [ 9 ! p ; will be executed by the VT100 on reaching the '!', leaving the parser in "ground" state, which ; means that the final character "p" will be displayed on the screen. ; ; With this bug, the bytes from the label not_final to the next "ret" (17 bytes) are all unreachable. ; ; If the buggy line is replaced by: ; ; cmp '0' ; ; then all the rest works as intended. ; gather_params: mov b,a gather2: mov a,b cpi '9'+1 ; above digit range? jnc finish_param ; then we've finished with this parameter (at least) sui '0' ; convert to actual digit value [* BUG *] jm finish_param ; might have hit an intermediate, or something invalid mov c,a ; C <- value of this digit lxi h,param_value mov a,m ; A <- current param value cpi 1ah ; if the current param value >= 26, multiplying by ; 10 would send us out of range, jnc par_range ; so limit it to 255 ; otherwise, multiply current value by 10 rlc ; A <- param * 2 mov b,a ; B <- param * 2 rlc ; A <- param * 4 rlc ; A <- param * 8 add b ; A <- param * 8 + param * 2 (= param * 10) jc par_range ; don't think this could be OOR now? add c ; A <- param + current digit value jnc par_store ; but this could be OOR (e.g. 259) par_range: mvi a,0ffh ; out of range parameters are limited at 255 par_store: mov m,a ; store new param_value ret ; ; We've now collected a CSI parameter value in param_value (212fh) ; and we want to store it in the list of parameters for this sequence. ; We do this regardless of what we're going to do next, which might be to ; start a new parameter, invalidate the sequence, or execute it. ; finish_param: lxi d,csi_params ; base of csi_params array push psw ; push the character we're working on lxi h,num_params mov c,m ; retrieve offset into array mvi b,0 xchg ; HL <- base of array, DE <- num_params dad b ; HL <- addr of next param to store lxi b,param_value ldax b ; A <- new param value mov m,a ; store in array xra a stax b ; now we've stowed parameter, zero current value ldax d ; A <- num params (array offset) cpi 0fh ; Limit ourselves to storing 16 params jz no_more_params ; Have we just stored the 16th parameter? inr a ; Still OK stax d no_more_params: pop psw ; A <- character we're working on ; ; This is a control sequence state where we're only collecting intermediates and ; finals. This state also allows ';' parameter separators to appear, which would be ; illegal after intermediate characters. However, the VT100 doesn't support any ; sequences with intermediates, so this state can harmlessly use the next few lines ; as part of two different states. ; detect_i_f: mov b,a ; B <- copy of original character cpi 03bh ; if it's a ';' separator, we're done for now rz ani 0c0h ; Control sequence finals are 040h to 07fh mov a,b jz not_final ; not a final character sta final_char jmp execute_seq ; ; At this stage, we know the current character didn't form part of a parameter value ; so, having tidied away the last parameter value, we now know that we're not ; dealing with a parameter separator or a final character. This could only be an ; intermediate or an illegal character (e.g. ':') or a character out of place, such ; as another private flag. We'll untangle these later but for now we'll add them ; into the intermediate store and change the action to collect the rest of the ; sequence until a final arrives, without storing further numeric parameters. ; not_final: lxi h,inter_chars ; Mix this character into the intermediate store, and we'll add m ; untangle invalidity here when it's time to execute the sequence. jnc inter_range_ok ; Mindful that we wouldn't want to wrap addition round to where mvi a,0ffh ; we appear to have a legal intermediate again. inter_range_ok: mov m,a ; Store our intermediate (or illegal mix) lxi h,detect_i_f ; Only collect "intermediates" and detect finals from now on. shld char_action ret ; ; store_nvr ; Store current settings back in NVR. The opposite of _see_ recall_nvr. ; store_nvr: mvi d,0 ; direction is write mvi b,1 ; try once jmp settings_nvr ; recall_nvr: call init_video_ram mvi b,10 ; try 10 times mvi d,1 ; direction is read ; settings_nvr: push b push d call print_wait ; "Wait" pop d di ; all NVR access is done with interrupts disabled lxi h,aback_buffer mvi e,33h ; Number of bytes in NVR, including checksum mvi c,1 ; C <- initial checksum xra a rw_byte_loop: sta nvr_addr mov a,c sta nvr_checksum push d push h mov a,d ; A <- direction flag ora a ; Flag Z if storing settings mov a,m ; A <- settings byte sta nvr_data ; stow copy for working on cz write_nvr_byte call read_nvr_byte pop h pop d lda nvr_data ; A <- read back settings byte dcr e jz finished_rw mov m,a ; place settings byte in scratch RAM lda nvr_checksum ; get checksum rlc ; rotate and exclusive-or this byte into it xra m mov c,a ; C <- checksum inx h ; point to next settings byte lda nvr_addr ; increase NVR address inr a jmp rw_byte_loop ; finished_rw: cmp m ; compare final byte (A) with checksum pop b mvi c,0 ; return result jz nvrchk_ok dcr b ; checksum wrong, so try again (on recall only) jnz settings_nvr call init_scratch ; Otherwise give up and put reasonable defaults in scratch nvrchk_ok: mov a,c ora a ; This routine returns Z flag for "ok, read NVR and checksum matched" push psw mvi c,iob_flags_lba7 mvi a,99 ; last address in NVR call set_nvr_addr_a lxi h,main_video_be ; To match screen address main_video shld line1_dma ; Put normal screen back pop psw ret ; ; A tiny area of scratch RAM is used for the tiny screen definition used when ; NVR is being accessed and "Wait" is displayed. ; print_wait: lxi d,wait_display mvi b,7 lxi h,wait_addr ; Copy "Wait" to video RAM, with terminators call memcopy ; that point to fill lines. lxi h,wait_addr_be shld line1_dma ret ; ; init_scratch ; Initialise all scratch locations from the answerback buffer up to rx_spd, inclusive ; Returns C = 1, for the benefit of recall_nvr, which wants to return non-zero ; if NVR couldn't be read (or checksum didn't match.) (_see_ recall_nvr) ; init_scratch: lxi h,aback_buffer mvi b,27h ; Answerback buffer + tab settings scribble_loop: mvi m,80h ; scribble (80h is "end of string" for answerback and tab-every-8) inx h dcr b jnz scribble_loop ; HL finishes pointing to columns_132 lxi d,scratch_defs mvi b,11 ; 11 locations to initialise call memcopy mvi c,1 ; C <- 1 is for the benefit of recall_nvr mvi a,30h sta bell_duration ; going to sound bell ret ; ; "Wait" is followed by terminator and address that leads back to the fill lines. ; wait_display: db 'Wait',7fh,70h,06h ; Initialisation values for scratch area from columns_132 to rx_spd, inclusive ; Note that failure of NVR leaves the terminal in VT52 mode rather than ANSI mode! ; scratch_defs: db 0 ; columns_132 <- 80 columns db 8 ; brightness <- three quarters brightness db 6eh ; pusart_mode <- 1 stop bit, no parity, 8 bits, 16x clock db 20h ; local_mode <- "local" db 0d0h ; setup_b1 <- smooth scroll, autorepeat, dark background, block cursor db 50h ; setup_b2 <- no margin bell, keyclick on, VT52 mode, auto xon/off db 0 ; setup_b3 <- ASCII, no autowrap, no newline, no interlace db 20h ; setup_b4 <- no parity, 8 bits, power 60 Hz db 0 ; setup_b5 <- (don't care) db 0e0h ; tx_spd <- 9600 baud db 0e0h ; rx_spd <- 9600 baud ; ; CUU - cursor up n rows cuu_action: lda top_margin lxi b,00ffh ; B <- limit of movement (row 0), C <- direction (-1 = up) jmp row_mv ; ; CUD - cursor down n rows cud_action: call last_row ; B <- last row number (i.e. 13, or 23 with AVO) lda bottom_margin mvi c,1 ; C <- direction of movement (+1 = down) ; ; row_mv ; On entry, B is limit of movement, which is 0 or last row (cursor movement can't cause scrolling) ; C is direction of movement, -1 for up, or +1 for down ; row_mv: lxi h,curs_row ; HL <- coordinate location we're affecting (row) jmp cur_mv ; ; CUF - cursor forward n columns cuf_action: lda right_margin lxi b,0ff01h ; B <- limit of movement (column 255!), c is direction of movement (+1) jmp col_mv ; shared code with CUB ; ; CUB - cursor backward (left) n columns cub_action: xra a lxi b,00ffh ; B <- limit of movement (column 0), c is direction of movement (-1) col_mv: lxi h,curs_col ; Row movement can also be processed here, by having HL initialised to the curs_row address and ; appropriate limits set cur_mv: mov d,a ; D <- appropriate margin, to limit movement lda csi_private ; Check that we haven't got any private characters ora a ; because there is no private meaning for any of the jnz to_ground ; cursor movement sequences lda csi_p1 ; Defaulting the first parameter: if the parameter ora a ; hasn't been supplied, or is supplied as zero, jnz got_p1 inr a ; then treat it as one got_p1: mov e,a ; E <- number of times to move mov a,m ; A <- current column repeat_move: cmp d ; check against margin jz stop_move cmp b jz stop_move add c dcr e ; Do this movement until limited (conditions above) jnz repeat_move ; or until we've exhaused the count stop_move: mov m,a ; store final column address jmp move_updates ; ; cursor_home ; ; Because this routine clears the first two CSI parameter locations in order to act like a CUP ; or HVP sequence with defaulted row and column positions, it provokes a bug in DECOM. ; _See_ decom_mode for details. ; cursor_home: lxi h,0 shld csi_params mvi a,0ffh sta saved_curs_row ; ; curpos_action ; ; The sequences CUP (CSI H) and HVP (CSI f) both come here, as they have identifical effects on all ; models of DEC VTs. ; ; This routine has a bug in that it starts off by storing the origin mode flag in the C register, ; but can lose track of that and use C for a row number instead, but then make a further decision ; as if it still contained the flag. ; ; The fault path is triggered if we are not in origin mode, which means the code validates the ; row parameter against the last row of the screen, not the bottom margin. At this point, C is ; changed from storing the origin mode flag to storing the requested new row. Next, the column ; number is validated by checking the column number against either the right margin (origin mode) ; or the last column on the screen (non origin mode). If we are in origin mode, the test proceeds ; as intended, but if we were not in origin mode, using the right margin or last column depends ; on whether the new internal row number is 0 or not. If it is non-zero, we check the right margin ; (i.e. acting like origin mode) instead of last column. ; ; This bug constrains the cursor column update to the right margin even if origin mode is not in ; effect. However, the VT100 doesn't have settable left and right margins, and the right margin is ; only ever different from last column number on double width lines. So there is no case in which ; this code will allow the setting of a column number beyond the right margin, which means the ; corruption of the middle-of-line terminators on double width lines cannot occur. (In any case, all ; cursor moves are then re-validated by _see_ move_updates.) ; ; The effect of the bug is that cursor moves from a line that is double-width to a line that is ; single width are constrained by the right margin of the current line, provided the new row ; is anything other than row 1, which is incorrect. ; ; This is demonstrated by test t/margin-bug.txt. [* BUG *] ; curpos_action: lda origin_mode mov c,a lxi h,csi_p1 mov a,m ; Pn1 is row ora a ; default/0 will be top row jz def_row dcr a ; Otherwise, our internal rows are 0-based, not 1-based def_row: mov b,a ; B <- row mov a,c ; A <- origin mode flag ora a jz add_top ; jump if not in origin mode lda top_margin ; In origin mode, move within margins add_top: add b mov b,a ; B <- adjusted row mov a,c ; A <- origin mode flag ora a lda bottom_margin ; A <- bottom margin jnz chk_bot_limit ; jump if origin mode mov c,b ; C <- new row call last_row ; B <- last row on screen mov a,b ; A <- last row mov b,c ; B <- new row chk_bot_limit: cmp b ; comparing new row against either bottom margin or last row jc skip_row ; if last row < new row, go store last row mov a,b ; else new row is ok skip_row: sta curs_row ; store row inx h ; HL points to csi_p2 mov a,m ; A <- Pn2 (column) ora a ; default/0 will be left column jz def_col dcr a ; Otherwise, our internal cols are 0-based, not 1-based def_col: mov b,a ; B <- col mov a,c ; A <- 1 if origin mode flag had been set, new row if unset ora a ; jnz use_rmargin ; jump if origin mode lda screen_cols dcr a ; A <- last column number jmp chk_rlimit ; use_rmargin: lda right_margin chk_rlimit: cmp b jc nolim_rm ; if right margin < requested column, store margin mov a,b ; else A <- request column nolim_rm: sta curs_col ; store jmp move_updates ; ; read_nvr_byte ; read_nvr_byte: mvi c,iob_flags_lba7 call set_nvr_addr call read_nvr_data jmp nvr_idle ; ; write_nvr_byte ; ; Writing a byte to the NVR involves addressing the location and an erase cycle first, ; which involves commanding the erase operation and waiting; there is no positive ; acknowledgement of completion. ; write_nvr_byte: mvi c,iob_flags_lba7 call set_nvr_addr call erase_nvr ; includes 20 ms delay call nvr_accept call write_nvr ; includes 20 ms delay nvr_idle: mvi a,30h ; c000 d0 = "accept data" (inv) out iow_nvr_latch ret ; read_nvr_data: w1h: in ior_flags ; ER1400 shows command acceptance on rising ana c ; edge of clock. Wait for high, low, jz w1h ; command, then wait for high again. w1l: in ior_flags ana c jnz w1l mvi a,2dh ; c110 d1 = "read" (inv) out iow_nvr_latch w2h: in ior_flags ana c jz w2h w2l: in ior_flags ana c jnz w2l mvi a,2fh ; c111 d1 = "standby" (inv) out iow_nvr_latch lxi h,nvr_bits mvi b,14 ; shifting 14 bits out of NVR w3h: in ior_flags ana c jz w3h w3l: in ior_flags ana c jnz w3l mvi a,25h ; c010 d1 = "shift data out" (inv) out iow_nvr_latch w4h: in ior_flags ; \ ana c ; | jz w4h ; | in ior_flags ; | mov m,a ; | - squirrel away raw flags buffer value inx h ; > 14 bits w4l: in ior_flags ; | ana c ; | jnz w4l ; | dcr b ; | jnz w4h ; / mvi a,2fh ; c111 d1 = "standby" (inv) out iow_nvr_latch ; lxi d,nvr_bits mvi b,14 ; 14 bits again lxi h,0 accum_bits: dad h ; shift HL left, clearing bit 0 of L ldax d ; grab next bit, which is raw flags buffer read ani iob_flags_nvr ; isolate bit 5 rlc ; data is bit 6 rlc ; data is bit 7 rlc ; data is bit 0 ora l ; Add to HL mov l,a inx d ; next raw read dcr b ; for all 14 bits jnz accum_bits shld nvr_data ; stow all 14 bits ret ; ; used for both read and write operations ; only routine that uses nvr_addr ; ; Addresses are represented by 20 bits are split into a tens and units part, each represented by ten ; bits. Addresses are clocked into the ER1400 with all address bits held high except for the single ; bit of the digit that represents your tens or units. ; ; In order to get the timing right, this routine pre-calculates all 20 bits of the address in memory, ; in the nvr_bits array, including the complete C1, C2, C3 for each NVR latch byte. ; set_nvr_addr: lda nvr_addr set_nvr_addr_a: mvi b,-1 ; The address is broken up into tens and units addr_tens: inr b sui 0ah jp addr_tens adi 0ah ; Now B is tens, A is units lxi h,nvr_bits mvi e,23h ; c001 d1 "accept address" (inv) mvi d,20 ; 20 address bits addr_const: mov m,e ; some kind of constant lead-in? inx h dcr d jnz addr_const mvi m,2fh ; c111 d1 "standby" (inv) lxi h,nvr_bits mov e,a ; mvi d,0 ; DE <- units address dad d ; Advance HL by units address mvi m,22h ; c001 d0 "accept address" (inv) lxi h,nvr_bits mvi a,0ah add b ; A = address tens + 10 mov e,a ; dad d ; Advance HL by 10 + tens address mvi m,22h ; c001 d0 "accept address" (inv) wa1l: in ior_flags ana c jnz wa1l lxi h,nvr_bits ; Back to beginning of bits, ready for latching on clock lows mvi b,21 ; must be complete in 21 clock periods (including high after last bit) wa1h: in ior_flags ana c jz wa1h dcr b rm ; limited cycles for entire write wa2l: in ior_flags ana c jnz wa2l mov a,m out iow_nvr_latch inx h jmp wa1h ; nvr_accept: lhld nvr_data ; grab 14 bits of data dad h ; shift the bits 2 places left so that the dad h ; next add will start forcing data into carry lxi d,nvr_bits mvi b,14 ; going to process 14 bits next_split: mvi a,20h ; c000 d0 = "accept data" (inv) dad h ; shift top by of HL into carry flag ral ; and pull it into bit 0 of A stax d ; place in nvr_bits buffer inx d dcr b jnz next_split mvi a,2fh ; c111 d1 = "standby" (inv) stax d lxi h,nvr_bits mvi b,15 ; 14 data bits + standby terminator wd1h: in ior_flags ana c jz wd1h wd1l: in ior_flags ana c jnz wd1l mov a,m out iow_nvr_latch inx h dcr b jnz wd1h ret ; erase_nvr: wl1h: in ior_flags ana c jz wl1h wl1l: in ior_flags ana c jnz wl1l mvi a,2bh ; c101 d1 = "erase" (inv) out iow_nvr_latch call wait_nvr mvi a,2fh ; c111 d1 = "standby" (inv) out iow_nvr_latch ret ; ; If we're expected to clock data out of NVR and we don't want it, ; we just wait out a number of clocks. ; wait_nvr: lxi h,315 ; 315 x LBA 7 cycles at 63.5 µs per cycle = 20 ms w20h: in ior_flags ana c jz w20h w20l: in ior_flags ana c jnz w20l dcx h mov a,h ora l jnz w20h ret ; ; After an "accept data" operation, command the NVR to write the data. Then wait. ; The datasheet says that the ER1400 will finish in a maximum of 24 ms. write_nvr: wwwh: in ior_flags ana c jz wwwh wwwl: in ior_flags ana c jnz wwwl mvi a,29h ; c100 d1 = "write" (inv) out iow_nvr_latch call wait_nvr mvi a,2fh ; c111 d1 = "standby (inv) out iow_nvr_latch ret ; ; Processing next "received" character for SET-UP, which means handling a keypress, as we're now in ; LOCAL mode, and keypresses aren't going to the host, but being reflected internally. For the ; mechanism here, _see_ report_char. ; ; On entry, A and B both contain the received character (_see_ reflect_char) ; setup_action: cpi 20h ; If SPACE is pressed, mvi c,43h ; it is treated the same as RIGHT ARROW, jz setup_cursor ; so perform cursor movement lxi h,setup_ready push h ; Push return address on stack cpi C0_CR jz c0_return cpi C0_HT jz c0_horiz_tab cpi '9'+1 ; Keys above numeric range are handled separately jnc setup_keys sui '0' ; Numeric keys are handled through a jump table, rm ; bring down into range and reject any keys lower than '0' add a ; double up code because addresses are two bytes lxi h,setup_key_t ; HL <- base of key table call add_a_to_hl ; call ld_hl_from_hl mov a,b ; A <- received char lxi d,rx_spd ; DE <- rx_spd, which is convenient for toggle speed keys, at least pchl ; jump to action routine ; ; Keyboard processing has detected SETUP key, which either takes us into or out of SET-UP setup_pressed: sta pending_setup jmp pk_click ; ; Pressing "SET UP" will mark a SET-UP action as pending, and then this routine will be called ; to either enter or exit. ; in_out_setup: lda in_setup xri 0ffh ; Toggle in/out of SET-UP sta in_setup jz exit_setup ; ; TM says that, on entering SET-UP, it waits for scrolls to finish. ; enter_setup: mvi c,80h call wait_scroll lhld char_action ; We're going to redirect all key actions shld saved_action ; so save previous state lxi h,setup_action ; and register the SET-UP action shld char_action lxi h,0 shld curkey_qcount ; keyboard_locked <- 0 too shld pending_report ; sending_report <- 0 too setup_addrs: lhld line1_dma shld saved_line1_dma lhld curs_col ; HL <- curs_row and curs_col shld saved_curs_col ; save them call extra_addr shld start_line_addr xra a sta curs_col call setup_display jmp move_updates ; exit_setup: lhld saved_action ; Restore character processing state (we could have been in the middle shld char_action ; of receiving a control sequence when SET-UP was pressed.) call extra_addr ; HL <- extra line screen RAM lxi d,1000h dad d ; HL <- start of cursor line attribute RAM lda screen_cols ; Default attributes for entire line restore_attr: mvi m,0ffh inx h dcr a jnz restore_attr lxi h,saved_curs_col mov a,m ; A <- saved cursor column sta curs_col mvi a,0ffh ; A <- 0ffh inx h ; HL points to saved_curs_row mov m,a ; destroy it call move_updates lhld saved_line1_dma shld line1_dma xra a sta noscroll sta received_xoff in ior_flags ; Exiting SET-UP will trigger DECREPTPARM if we are ani iob_flags_stp ; allowed to send them unsolicited, and if we don't have STP. jz skip_tparm lda tparm_solicited ora a cz setup_tparm skip_tparm: ret ; ; Jump table for digit keys pressed in either SET-UP mode ; setup_key_t: dw restart ; Key 0 - reset dw do_nothing_key ; Key 1 - has no function in SET-UP dw toggle_tab ; Key 2 - set or clear tab (SET-UP A only) dw setup_clr_tabs ; Key 3 - clear all tabs (SET-UP A only) dw toggle_online ; Key 4 - line/local dw toggle_a_b ; Key 5 - SET-UP A/B dw toggle_bit ; Key 6 - Toggle 1/0 (SET-UP B only) dw cycle_tx_speed ; Key 7 - Transmit speed dw cycle_rx_speed ; Key 8 - Receive speed dw switch_columns ; Key 9 - 80/132 columns ; switch_columns: call setup_a_only xra a sta saved_curs_row sta saved_curs_col lda columns_132 ora a push psw cz init_132col pop psw cnz init_80col jmp setup_addrs ; same address-setting code as entering SET-UP ; restart: rst 0 ; toggle_tab: call setup_a_only ; lda curs_col ora a ; Can't have a tab at first column on line rz ; so quit early call tab_offs_curs xra m ; flip tab state mov m,a ; and write back call tab_offs_curs ana m mvi b,'T' ; Assume there'll be a tab stop jnz is_tab no_tab: mvi b,0 ; B <- blank is_tab: mov a,b ; A <- 'T'/blank sta char_und_curs lda curs_col jmp disp_char_col ; setup_clr_tabs: call setup_a_only call clear_all_tabs call clear_extra jmp no_tab ; ; SET-UP key 4 toggles line/local toggle_online: lxi h,local_mode mov a,m xri 20h ; Toggle local mode mov m,a xra a sta keyboard_locked ; this is just a convenient "ret" for a key that does nothing in SET-UP do_nothing_key: ret ; toggle_a_b: call c0_return lxi h,setup_video+7 ; Screen location of final character of "SET-UP A" (or "B") mov a,m ; A <- character xri 3 ; A <- "A" ^ "B" mov m,a ; Write it back sta setup_video+12h ; And same thing on bottom line, because it's double height ani 1 ; And the low bit of the ASCII "A" conveniently matches sta in_setup_a ; our flag for which screen we're on jz draw_setup_b jmp draw_setup_a ; ; toggle_bit allows any of the SET-UP B configuration blocks to be updated, with ; addressing made easy by a cunning screen layout; The screen looks like this: ; ; 1 1101 2 1111 3 0100 4 0010 5 0000 <- (optional block 5) ; ; As each setup block is only 4 bits in the top half of each setup byte, the ; placement of the bit blocks 4 columns apart, allows the col_in_bits ; routine to directly address the correct bit (after the starting column offset ; has been removed.) ; toggle_bit: call setup_b_only lxi h,setup_b1 ; First block on screen (lowest in memory) lda curs_col sui 2 ; Ignore the "1 " at the start of line cpi 28h ; To accommodate possible block 5 rnc ; Return if out of range nop ; Feels like last-minute code removal here nop nop nop mov d,a ; D <- A because col_in_bits uses both call col_in_bits xra m ; toggle the appropriate bit mov m,a ; and write back call program_pusart jmp draw_setup_b ; ; cycle_tx_speed ; cycle_rx_speed ; ; SET-UP initialises DE to point to rx_spd before jumping to action routines, so cycle_tx_speed ; just adjusts this location before dropping through to the generic routine. ; SET-UP B ONLY ; cycle_tx_speed: dcx d ; DE <- tx_spd cycle_rx_speed: xchg ; HL <-> DE, so HL points at speed location call setup_b_only ; A is 0 on exit! sta curs_col mov a,m ; Read current speed adi 10h ; add to the value in top 4 bits mov m,a ; Store new value call program_pusart jmp draw_setup_b ; ; setup_a_only ; setup_b_only ; These guard routines are called by functions that should only work in one of the two ; SET-UP modes, because key dispatching happens through the same table for both screens. ; These routines are called by action routines and they will just return if the correct ; SET-UP screen is in use. Otherwise, they'll pop the stack, to quit the action routine ; early and return to the action routine's caller. ; setup_a_only: lda in_setup_a ora a rnz ; Correct screen; return to caller pop h ret ; else discard the action routine ; setup_b_only: lda in_setup_a ora a rz ; Correct screen; return to caller pop h ret ; else discard the action routine ; ; In SET-UP mode, deal with keys other than digits (which are handled through a table) ; setup_keys: lda last_key_flags ; All other keys will need SHIFT to be pressed ani key_flag_shift rz ; so if it isn't, exit mov a,b cpi 'S' ; SHIFT S stores settings in NVR jnz try_recall call store_nvr jmp post_nvr ; try_recall: cpi 'R' ; SHIFT R recalls settings from NVR jnz try_answerback call recall_nvr ei call init_devices call enter_setup post_nvr: ei call setup_display ret ; try_answerback: cpi 'A' rnz call setup_b_only call c0_return mvi a,'A' ; extra line is initialised with "A= " and then you type a call print_char ; delimiter, rest of message and another delimiter to finish. mvi a,'=' call print_char mvi a,' ' call print_char lxi h,aback_entry shld char_action pop h ret ; ; These 10 bytes are all valid 8080 instructions but are unreachable. The first byte is a little out of ; place, hence my assumption that it's the checksum for ROM 4 (1800h - 1fffh), as there are no unused ; non-zero bytes elsewhere in this ROM. The other 9 bytes would result in a lowercase character in the ; A register being made uppercase, returning all others unchanged. As this is very far from the keyboard ; routines, perhaps this is the remnants of some VT50 compatibility code. Who knows? ; sbb b ; = 98h. Probably CHECKSUM (first byte of unused code) cpi 61h ; UNREACHABLE (see note above) rm cpi 7bh rp ani 0dfh ret ; ; Gets us ready for next setup action. Used as a handy return point by being pushed on the stack. ; setup_ready: call ready_comms lxi h,setup_action shld char_action ret ; ; extra_addr ; Returns with HL containing address of the extra line in screen RAM. ; This is the line that gets used as the cursor line in SET-UP mode, so in SET-UP A, it ; shows all the tab stops; in SET-UP B the cursor moves along it to select a switch to be ; changed, and the answerback message gets entered here. ; extra_addr: lhld line_25_addr jmp real_addr2 ; wait_screen: lxi h,wait_addr ; fall through, pointlessly, as HL is already in screen range ; local copy of real_addr real_addr2: mov a,h ani 0fh ori 20h mov h,a ret ; ; finish_setup ; ; The final part of drawing the setup screen is connecting the cursor line (23rd line = row 22), to the ; "Wait" line that we're using as 24th line (row 23). ; finish_setup: call extra_addr ; HL <- extra line in screen RAM call clear_row push h ; HL points to where terminator should be/is mvi m,7fh ; OK, put terminator there inx h ; point to where screen DMA address will be xchg ; Stow it in DE call wait_screen ; HL <- wait screen line mov a,h ; Add line attributes for use as DMA high byte ani 0fh ori 70h stax d ; Next line address is "Wait" line inx d mov a,l stax d pop h ; HL <- back to terminator address ; ; Now write a line containing a 'T' at every tab stop position. ; Other columns aren't written, so they remain blank. ; lda screen_cols mov e,a ; E <- column number mvi b,'T' ; B <- character drawn at tab stops tloop: mov a,e call tab_offs ana m ; If the bit in A is not set in (HL), jz tnotab ; then there is no tab set here. mov a,e ; Otherwise, draw a 'T' at this column call disp_char_col tnotab: dcr e ; Loop for all columns jnz tloop ret ; setup_display: lxi b,setup_a_string lxi h,setup_video mvi a,0fah ; "SET-UP x" is bold and blinking call display_zstr mvi c,1 ; terminate 1 line mvi b,10h ; line attributes *for next line*: bottom half, double height call term_line lxi b,setup_a_string mvi a,0fah ; still bold and blinking call display_zstr mvi c,1 mvi b,50h ; line attributes for next line: double width call term_line ; "To exit..." is underlined lxi b,to_exit_string mvi a,rend_under call display_zstr mvi c,13h ; terminate 19 lines call term_line1 ; use entry point that sets single width line attributes ; Now the 3 top lines and 18 middle blank lines have been written, ; we're about to terminate the 22nd line and point to the current ; cursor line for the 23rd line of the setup screen, which is where ; the cursor will be movign, and also where answerback can be entered. ; This cursor line is the 25th line of the main screen, which is ; known to have nothing needing preserving on it, as scrolling has been ; completed. mvi m,7fh ; Terminate the last blank line, so that's 22 lines terminated. inx h ; HL now points to where we're going to the write DMA addres xchg ; Pop this into DE temporarily call extra_addr ; HL <- extra line address (25th line of main screen, i.e. mov a,h ; main_video + (ncols + 3 ) * 24 = 2a98h (80) or 2f78h (132) ori 70h ; Add line attributes stax d ; Write high byte inx d ; advance to low byte of DMA address mov a,l ; A <- low byte of cursor line address stax d ; Write low byte ; draw_setup_a: call wait_screen ; HL <- wait screen ; ; The final line of the screen, which for SET-UP is the column numbers, ; will go in the same place the "Wait" display is created. ; Now draw the column numbers at the bottom. We start with '1' and increment the ; number, discarding tens. Every tenth position we change between normal video ; and reverse video. lda screen_cols mov b,a mvi a,'1' n_col: mov m,a ; write current digit inx h mov c,a ; preserve number + rendition ani 0fh ; just consider units column mov a,c ; restore number jnz noflip ; If we've just written a '0', we'll xri 80h ; flip between normal and reverse video noflip: inr a ; next column digit daa ; staying decimal jnc normok ; carry from daa if we are in reverse video ori 80h ; so restore the reverse video bit normok: ani 8fh ; remove tens digit ori '0' ; and ASCII-ify it dcr b jnz n_col ; call end_screen call finish_setup mvi a,1 ; 1 = "SET-UP A" ; ; Now we've drawn the SET-UP screen, switch the Video DMA to point to it. ; display_setup: sta in_setup_a lxi h,setup_video ; Our address, 2253h, will be sent to Video RAM as 3000h+(2)253h mov a,h mov h,l ; Video RAM address are big-endian, so swap bytes ani 0fh ori 30h ; Force top bits to say: not scrolling region, double-height top half mov l,a shld line1_dma ret ; ; display_zstr ; Display the zero-terminated string pointed to by BC, at the screen address given by HL, ; with character attributes in A. ; Returns screen address in DE, attribute address in HL ; display_zstr: push h ; Given a pointer to character memory, lxi d,1000h ; Attributes are 1000h further on (somewhere beyond 3000h) dad d pop d ; swap so that HL <- attribute memory, DE <- character memory n_ch: push psw ; push rendition while we grab character ldax b ; Grab next character ora a jz z_term ; Zero byte to finish stax d ; Place in character memory pop psw ; A <- rendition mov m,a ; Place rendition in attribute memory inx h ; inc. attr ptr inx d ; inc. char ptr inx b ; inc. string ptr jmp n_ch ; z_term: pop psw ; clean the last rendition push ret ; ; term_line1 ; term_line ; ; This routine (with two entry points) helds construct SET-UP displays by providing a fast way ; of terminating lines and writing video DMA addresses, with line attributes. ; ; DE points to just beyond the last character of the line ; B holds the upper four bits of the video address, while is scroll region flag and line attributes (size); ; term_line1 is a convenient second entry point to say "single height, single width" ; C is the number of lines to terminate, effective performing line feeds, which is used to make the blank ; space in the middle of the SET-UP screen. ; term_line1: mvi b,70h term_line: xchg ; DE <-> HL ; term_loop: mvi m,7fh ; (HL) <- line terminator inx h mov d,h ; The characters for the next line will start two bytes mov e,l ; further on, so get DE pointing to where they'll be inx d inx d mov a,d ; Now make up a DMA address high byte for DE ani 0fh ; Mask off high nybble, '2', as that's a given ora b ; and put in scrolling region and line attributes instead mov m,a ; Write DMA high byte inx h ; Point to DMA low byte mov m,e ; ... and that's our real address low byte inx h ; Move on, so that HL points to next character dcr c ; If C is non-zero here, the next line is empty and jnz term_loop ; we'll just terminate again (line feed operation) ret ; ; Write the terminator to mark this line as finished, and then write the next DMA address ; to point back to this terminator, to produce fill lines. ; end_screen: mvi m,7fh ; write terminator mov d,h ; DE <- address of terminator, so we write back to here mov e,l inx h ; Point to high byte of DMA address mov a,d ; A <- high byte of terminator address ani 0fh ori 70h ; Write not scrolling, normal lines attributes, 2000h mov m,a ; Write modified high byte inx h ; Point to low byte mov m,e ; Point low byte back to terminator too ret ; setup_a_string: db 'SET-UP A',0 to_exit_string: db 'TO EXIT PRESS ',22h,'SET-UP',22h,0 ; asm8080 doesn't like nested quotes ; ; clear_extra ; Clear the extra line ; clear_extra: call extra_addr jmp clear_row ; ; SET-UP B screen initialisation ; ; Every change made to setup fields causes this line to be redrawn. ; draw_setup_b: call clear_extra call wait_screen ; HL <- start of screen line push h mvi a,4eh ; Clear 78 positions call clear_part_row ; on current line to blanks and default rendition pop h ; HL <- start of screen line push h inx h ; Leave first two locations blank for now, inx h ; as we'll draw switch block numbers later. mvi e,0 ; E <- switch number (starting from high bit in setup_b1) mvi b,4 ; assume 4 setup blocks in ior_flags ; read flag buffer ani iob_flags_stp ; check for STP push psw jz next_block inr b ; If we have STP, add another switch block ; must be drawing the setup blocks loop next_block: mvi c,4 ; C <- switches per block nx_sw: call bit_from_setup ; A <- 1 or 0 of switch bit E ori 0b0h ; ASCII-ify in reverse video mov m,a ; place on screen inr e ; next switch bit inx h ; next column on screen dcr c jnz nx_sw ; ; Gaps of four blanks between switch blocks (we fill in the switch block numbers later) mvi c,4 blank4: mvi m,0 ; write blank to screen inr e ; next switch bit inx h ; next column on screen dcr c jnz blank4 dcr b ; next switch block jnz next_block ; ; Now draw the blanks between the last switch block and the baud rate fields mvi c,4 ; At least 4 blanks pop psw push psw jnz draw_blanks ; We pushed the "test for STP" result, above mov a,c ; Without an STP switch block, adi 8 ; we need another 8 blanks mov c,a draw_blanks: mvi m,0 ; write blank to screen inx h ; next column on screen dcr c jnz draw_blanks ; ; Baud rate fields lxi d,t_speed_string lda tx_spd call copy_baud_str ; lxi d,r_speed_string lda rx_spd call copy_baud_str ; call end_screen ; ; Finally, draw the numbers on the switch blocks lxi d,8 ; 8 characters between switch block numbers mvi c,4 ; Again, 4 blocks by default pop psw ; Flags NZ means "got STP" jz no_block_5 inr c ; Add that fifth block for STP no_block_5: mvi a,'1' ; Switch block number one coming up pop h ; HL <- start of screen line next_block2: mov m,a inr a ; next block number dad d ; skip past block bits we drew earlier dcr c jnz next_block2 xra a ; A <- 0 means "in SET-UP B" jmp display_setup ; t_speed_string: db ' T SPEED ' r_speed_string: db ' R SPEED ' ; copy_baud_str ; Comms speeds are encoded internally as values 0 to 15 in the upper 4 bits ; of the locations tx_spd and rx_spd. ; The baud strings are 5 characters long, stored sequentially in the table ; below this routine, without terminators, so this routine copies the ; appropriate string to the buffer pointed to by HL. ; ; The placement of these values in the upper 4 bits of a byte is the same as the ; switch block settings that are also on the SET-UP B screen. It feels as if they ; might originally have been planned as switch block settings. ; copy_baud_str: mov c,a ; C <- speed value (memcopy corrupts A) mvi b,11 ; speed strings above are 11 characters long call memcopy ; place in buffer mov a,c ; A <- speed value, in upper 4 bits rrc ; To avoid shifting this value down 4 bits and rrc ; multiplying by 5 (x * 4 + x * 1), we combine mov c,a ; the shift and multiply by calculating rrc ; x / 4 + x / 16. Same result but shorter by rrc ; four instructions. add c ; mov c,a ; mvi b,0 ; BC <- offset of string from baud_strings lxi d,baud_strings xchg ; Swap HL <-> DE because can only add BC to HL dad b ; HL <- string location xchg ; HL <-> DE because DE is "copy from" pointer mvi b,5 ; 5 chars to copy jmp memcopy ; copy and return ; ; These strings aren't delimited because they are all five characters long baud_strings: db ' 50' db ' 75' db ' 110' db ' 134' db ' 150' db ' 200' db ' 300' db ' 600' db ' 1200' db ' 1800' db ' 2000' db ' 2400' db ' 3600' db ' 4800' db ' 9600' db '19200' ; bit_from_setup ; Retrieve bit E from setup blocks 1 to 5, numbered with bit 0 being bit 7 ; of setup block 1. ; Returns 1 or 0 in A for bit state (don't need a mask from this routine, ; as we're just going to print the result.) ; bit_from_setup: push h lxi h,setup_b1 mov d,e ; It's a quirk of col_in_bits that the bit number mov a,e ; must be provided in A and D call col_in_bits ana m pop h rz mvi a,1 ret ; ; Combine rx_spd and tx_spd configuration locations into a single byte, which the ; Technical Manual says allows both speeds to be altered by a single write to the PUSART. ; program_pusart: lda rx_spd ; A <- receive speed, in bits 7-4 ani 0f0h ; mask and shift down to low 4 bits rrc rrc rrc rrc mov b,a lda tx_spd ; A <- transmit speed, in bits 7-4 ani 0f0h ; mask and combine with receive speed ora b sta tx_rx_speed ; store combined speed byte ani 0f0h ; Now look at just transmit speed cpi 20h ; Is it 110 baud? lda pusart_mode jz two_stop ; jump if 110 baud ani 3fh ori 80h ; Set 1½ stop bits (according to TM Figure 4-3-3 and 8251A datasheet) jmp stow_m ; Why not one stop bit? ; two_stop: ani 3fh ; Set two stop bits for transmit at low speed (TM §1.1) ori 0c0h stow_m: sta pusart_mode in ior_flags ani iob_flags_stp jz add_parity lxi h,setup_b2 mov a,m ori sb2_autoxon ; If we have STP, force Auto XON mov m,a mvi a,6eh ; And set serial to 1 stop bit, no parity, 8 data bits jmp stow_m2 ; ; Make another PUSART mode by combining parity information and other bits add_parity: lda setup_b4 ani sb4_paritybits mov b,a ; B <- |pe|p1| | | | | | | lda setup_b4 ani sb4_8bits ; A <- | | |8b| | | | | | rrc ; A <- | | | |8b| | | | | ori 20h ora b ; A <- |pe|p1| 1|8b| | | | | rrc rrc mov b,a ; B <- | | |pe|p1| 1|8b| | | lda pusart_mode ; grab existing mode ani 0c3h ; and preserve opposite bits from B ora b ; combine stow_m2: sta pusart_mode ; place back lda setup_b4 ani sb4_50Hz jz is_60 mvi a,10h is_60: adi 20h ; A <- 20h for 60Hz, 30h for 50Hz sta refresh_rate ; Ends up in DC011 video processor lda setup_b1 ani sb1_curblock jz is_und mvi a,1 is_und: call cursor_type ; A <- 1 for block cursor, 0 for underline call reset_pusart lda curs_col cpi 15h cz update_dc011 ; Update DC011 for interlace setting cpi 1dh cz update_dc011 ; Update DC011 for power hertz cpi 0ch ; cz set_charsets ; Update charsets on ANSI/VT52 change. There is no difference ; between charset designation in ANSI/VT52 mode, but this ; action merely mirrors the SM/RM ANSI sequence action ; (_see_ ansi_mode) cpi 12h cz set_charsets ; Update charsets on ASCII/UK change call move_updates ret ; ; cursor_type ; ; Called with A = 0 for underline cursor, 1 = block cursor. ; Sets whether the basic character attribute has to match the cursor selection (not required if AVO ; is present), and flags the cursor selection to video processor through basic_rev_video (which gets ; sent to DC012.) ; cursor_type: ora a ; NZ if block cursor jz und_cursor sta basic_rev_video ; block cursor selection will set basic attribute to reverse video xra a jmp set_curs_rend ; und_cursor: in ior_flags ani iob_flags_avo jnz und_curs_base sta curs_char_rend ; no character attribute (bit 7) change for cursor (because AVO present) mvi a,1 sta basic_rev_video mvi a,2 sta curs_attr_rend jmp update_dc012 ; ; Without AVO, picking a cursor type will also set the basic attribute for characters ; und_curs_base: xra a sta basic_rev_video set_curs_rend: sta curs_attr_rend mvi a,80h ; Set up character attribute use for cursor sta curs_char_rend jmp update_dc012 ; ; The first character of an answerback message comes here, in order to store it as the answerback ; delimiters. The action then changes to answer_action for all the rest, up to a matching delimiter. ; aback_entry: call answer_print lxi h,aback_buffer mov m,a ; First character becomes the delimiter inx h shld answerback_ptr mov b,a ; B <- delimiter lxi d,20 call memset ; Fill the answerback buffer with the delimiter lxi h,answer_action ; Switch to the "rest of the message" handler shld char_action ret ; ; answer_action ; ; This routine handles keys that are pressed while we're entering an answerback message. ; answer_action: call answer_print lhld answerback_ptr mov b,a ; B <- character pressed lda aback_buffer ; A <- delimiter mov c,a ; C <- delimiter cmp b ; Have we had the delimiter again? jz delim_found mov a,l cpi LOW aback_bufend ; have we exhausted the buffer? jz delim_found mov m,b ; add character to buffer inx h shld answerback_ptr ret ; delim_found: mov m,c ; delimit the buffer call clear_extra call c0_return jmp setup_ready ; ; answer_print: ; ; Going to print_char, but making sure that control characters are shown as a diamond. ; answer_print: push psw cpi 20h jnc skip_ctrl_sub mvi a,1 ; A <- diamond glyph to represent control characters skip_ctrl_sub: call print_nomap pop psw ret ; ; disp_char_col ; Display the character in register B at the column in register ; A on the current line. ; disp_char_col: push h lxi h,line_25_addr mov c,a ; C <- column lda columns_132 ora a jnz c132 mov a,c ; A <- column cpi 80 jp col_oor ; column >= 80 in 80-column mode? Exit c132: mov a,m ; A <- low byte of addr \ inx h ; HL <- point to high byte | load_hl_from_hl, unrolled mov h,m ; H <- high byte of addr | mov l,a ; L <- low byte / mov a,h ; \ ani 0fh ; | screen_addr, unrolled ori 20h ; | mov h,a ; / mov a,c ; A <- column add l ; \ mov l,a ; | add A to HL jnc no_h_inc ; | inr h ; / no_h_inc: mov m,b ; Place character on screen mov a,b ; A <- character col_oor: pop h ret ; ; Called from DECTST data_loop_test: push d xra a sta local_mode mvi b,0 ; Start with lowest speed test_next_spd: mov a,b sta tx_rx_speed ; Storing same speed as both transmit and receive out iow_baud_rate mvi c,1 ; Going to send 01h, 02h, 04h, 08h, 10h, 20h, 40h test_tx_ch: mov a,c out iow_pusart_data ; send a character lxi h,0c000h ; a long counter test_wait_ch: push b push h call test_rx_q ; Set NZ for characters available pop h pop b jnz test_got_ch inx h mov a,h ora l jnz test_wait_ch data_failed: mvi a,5 ; command byte: rx enable, tx enable out iow_pusart_cmd lda tx_rx_speed out iow_baud_rate mvi a,25h ; Into local mode and (briefly) light LEDs L2 and L4 sta local_mode ; (these are cleared during _see_ after_tests) xra a stc ; set "test failed" pop d ret ; test_got_ch: ani 7fh ; Ignore parity cmp c ; check received character is the same jnz data_failed mov a,c rlc ; rotate set bit to next higher position cpi 80h mov c,a jnz test_tx_ch mov a,b ; A <- speed adi 11h ; advance tx and rx speed together mov b,a cpi 10h ; Last speed is 0ffh (+ 11h = 10h) jnz test_next_spd xra a ; clear carry - "test passed" pop d ret ; ; modem_test ; For this test, try commanding 7 combinations of three modem signals (except for all off) ; and read back the resultant signals that should come from a modem or, in this case, ; an appropriate loopback connector. ; modem_test: push d mvi d,7 ; D <- signal combination modem_loop: mov a,d call modem_signals ; command signals through PUSART and NVR latch call read_modem ; and read the response cmp d ; which should be identical jnz data_failed dcr d jnz modem_loop mvi a,5 ; command byte: rx enable, tx enable out iow_pusart_cmd ; PUSART back to normal xra a pop d ret ; ; modem_signals ; ; Register A is a modem signal enable mask: ; 01h - RTS (ready to send) ; 02h - SPDS (speed select) ; 04h - DTR (data terminal ready) ; ; RTS and DTR are controlled by sending a PUSART command word. ; SPDS is an output from the NVR latch. ; ; NVR latch bit 5 drives BV2 /SPDS, which goes to the EIA pin 11, "speed select" ; modem_signals: mov b,a ani 2 ; A <- bit 1 rrc ; A <- bit 0 rrc ; A <- bit 7 rrc ; A <- bit 6 rrc ; A <- bit 5 (20h / 00h) ori 10h ; A <- bit 5 + bit 4 (30h / 10h) sta vint_nvr out iow_nvr_latch mvi c,5 ; command byte: rx enable, tx enable mov a,b ani 1 jz no_rts mvi c,25h ; command byte: RTS (request to send), rx enable, tx enable no_rts: mov a,b ani 4 jz no_dtr mov a,c ori 2 ; mix in DTR (data terminal ready) mov c,a no_dtr: mov a,c out iow_pusart_cmd ret ; ; read_modem ; ; Reads modem buffer (read only I/O port 22h) ; Not documented in TM ; Looking at print set MP-00633-00 sheet 3 of 6, Modem Buffer is E41, an 81LS97 addressed ; by signal BV2 MODEM RD L ; DB 07 H is /CTS ; DB 06 H is /SPDI ; DB 05 H is /RI -- ignored here ; DB 04 H is /CD ; ; This is designed to return a mask that matches the number passed to modem_signals, i.e. ; 01h will indicate that RTS (ready to send) worked, ; because the modem returns CTS (clear to send) and CD (carrier detect) ; 02h will indicate that SPDS (speed select) worked, ; because the modem returns SPDI (speed indicator) ; 04h will indicate that DTR (data terminal ready) worked ; because the PUSART status indicates DSR (data set ready) ; read_modem: in ior_modem mov b,a ; B <- modem signals mvi c,1 ; Assume RTS worked mov a,b ani 90h ; mask /CTS and /CD jz test_spdi cpi 90h ; expecting both signals in same state mvi a,0ffh rnz ; return with failure if not mvi c,0 ; if CTS and CD are not enabled, mark 0 so far test_spdi: mov a,b ; A <- modem signals ani 40h ; mask /SPDI jz test_ri ; not enabled mov a,c ori 2 ; mix in "SPDS worked" to result mov c,a test_ri: in ior_pusart_cmd ; read PUSART status byte rrc ; Looking for DSR (bit 7) and we want it to be low rrc ; to 5, cma ; invert ani 20h ; and mask xra b ; xor with /RI from modem signals ani 20h ; and mask again (making the first mask pointless) mvi a,0ffh ; failure if they weren't in the same state rnz mov a,b ; A <- modem signals ani 20h ; if /RI not found, skip marking DTR jnz modem_result mov a,c ori 4 ; mix in "DTR worked" to result mov c,a modem_result: ora a mov a,c ret ; ; Zeroes till end of ROM ... ; org 1fffh db 0 ; C0 Codes C0_BS equ 08h C0_HT equ 09h C0_LF equ 0ah C0_CR equ 0dh C0_DLE equ 10h C0_XON equ 11h C0_XOFF equ 13h C0_CAN equ 18h C0_SUB equ 1ah C0_ESC equ 1bh ; I/O Ports ; From TM Table 4-2-2 "List of Hex I/O Addresses", p.4-17 ; ior_pusart_data equ 0 iow_pusart_data equ 0 ior_pusart_cmd equ 1 iow_pusart_cmd equ 1 iow_baud_rate equ 2 ior_modem equ 22h ; This is the flags buffer. This defined in the VT100 Print Set, MP-00633-00, ; VT100 Basic Video (Sheet 6 of 6). It is an 81LS97 chip, buffering the signal ; names (and active H/L) shown in the comments ; TM §4.6.2.7 says that LBA 7 is used for clocking the NVR, and the print set shows this ior_flags equ 42h iob_flags_xmit equ 01h ; BV3 XMIT FLAG H iob_flags_avo equ 02h ; BV1 ADVANCED VIDEO L iob_flags_gpo equ 04h ; BV1 GRAPHICS FLAG L iob_flags_stp equ 08h ; BV3 OPTION PRESENT H iob_flags_unk4 equ 10h ; BV4 EVEN FIELD L iob_flags_nvr equ 20h ; BV2 NVR DATA H iob_flags_lba7 equ 40h ; LBA 7 H iob_flags_kbd equ 80h ; BV6 KBD TBMT H ; On Print Set MP-00633-00, this appears to drive the D/A latch E49, a 74LS174 device, ; with five bits of data and a sixth "init" value. ; POST sends 0f0h and the other writes are from a scratch location that goes from ; 0 (brightest) to 1fh (dimmest), making it look as if the POST write says "mid-brightness, init" ; iow_brightness equ 42h ; iow_nvr_latch ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | |/SPDS| --- | C3 | C2 | C1 |data | ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; ; Not defined in TM - this from print set MP-00633-00. ; Bit 4 is not connected. TM §4.2.7 says it was intended to disable receiver interrupts, ; though it isn't used. ; Bit 5 drives BV2 /SPDS (active low), which goes to the EIA connector as "speed select" ; Other modem signals are driven by PUSART command words. ; ; The NVR latch is often driven (early initialisation and modem test, for instance) with ; the command bits C3, C2 and C1 set to 0, the ER1400 "accept data" which the Technical ; Manual explains as a handy idle command because the all zeroes protects the NVR from ; spontaneous writes during power down. iow_nvr_latch equ 62h ior_keyboard equ 82h ; iow_keyboard ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | | |L1 on|L2 on|L3 on|L4 on| ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | `-- keyboard locked LED ; | | `-- online/local LED ; | `-- start scan ; `-- speaker click iow_keyboard equ 82h iow_kbd_led4 equ 01h iow_kbd_led3 equ 02h iow_kbd_led2 equ 04h iow_kbd_led1 equ 08h iow_kbd_locked equ 10h iow_kbd_local equ 20h iow_kbd_scan equ 40h iow_kbd_click equ 80h ; Detailed in TM p.4-70 iow_dc012 equ 0a2h iow_dc011 equ 0c2h iow_graphics equ 0e2h ; ; Equates for RAM locations, 2000h - 2bffh (3 KiB) ; ; The Video Processor is hard-wired to DMA from this region, always starting a frame at 2000h. ; ; Memory layout rom_top equ 1fffh ; ram_start equ 2000h ; The VT100 without AVO has 3K of RAM, from 2000h to 2bffh ram_top equ 2bffh avo_ram_start equ 3000h avo_ram_top equ 3fffh ; AVO adds another 4K of RAM line0_dma equ 2001h line1_dma equ 2004h ; There are two names for this location because, although it is stack_top, ; the stack always decrements before a push, so 204eh itself is available for some other ; purpose, and we'd like a name for that. stack_top equ 204eh ; ; Extra line address, i.e. the line that is available to be scrolled onto the screen. ; From soon after reset, set to FA98, which is address of 25th (spare) line. ; If we go to bottom of screen, and execute LF, it becomes F2D0, i.e. the old 1st line. ; line_25_addr equ 204eh ; screen_cols is either 80 or 132 screen_cols equ 2050h ; ; zeroed on width change. read in vertint ; When processing index_down, when smooth scrolling is enabled and we reach the bottom margin, ; this gets set to 1 and when processing reverse index and the top margin is reached, it'll get ; set to -1, to indicate the direction of the pending scroll. ; Pending scrolls are acted upon during vertical interrupts, as they will then cause single scan line ; changes until the extra line has fully scrolled into view (over 10 scans). scroll_pending equ 2051h ; stores pointer to screen DMA address (can only see a single write, and no reads) ; this name will have _dma on the end UNREAD_X2052 equ 2052h ; Pointer to 25th line DMA address in screen RAM. Never read; confirmed by tests. UNREAD_X2054 equ 2054h ; stores a line address for shuffle shufdt2 equ 2056h ; stores a line address for shuffle shufad2 equ 2058h ; Scan line of current scroll (to DC012 scroll latch). Zeroed on width change scroll_scan equ 205ah ; scroll direction, as initialised to 01h but could be 99h (=-1 daa) scroll_dir equ 205bh ; Buffer where cursor and function keys are prepared for sending to host ; offset into buffer is curkey_qcount curkey_queue equ 205ch ; 10 locs ; updated in vertical int, non-zero seems to hold up width change (fast loop, so must be waiting ; on vertical int to update it) Perhaps scroll to finish? smooth_scroll equ 2065h UNUSED_X2066 equ 2066h ; scan code of the latest new key seen in silo new_key_scan equ 2067h ; key_flags low 3 bits are number of keys waiting to be processed, which ; can only be up to 4. ; Bits 4-7 are the "shift" key flags, which get processed by the interrupt ; routine instead of being buffered. ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; |EOS |CAPS |SHIFT|CTRL | | OVR key count | ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; key_flags equ 2068h key_flag_ctrl equ 10h key_flag_shift equ 20h key_flag_caps equ 40h key_flag_eos equ 80h ; last_key_flags are updated at the end of the keyboard processing last_key_flags equ 2069h ; Space for 4 keys pending processing 206ah to 206dh. TM says "SILO" throughout key_silo equ 206ah ; 4 locs ; Buffer for previous keys which we'll attempt to match with silo key_history equ 206eh ; 4 locs key_rpt_timer equ 2072h ; used while processing keys - initialised to 2 and decremented key_rpt_pause equ 2073h ; incremented every time we send byte to keyboard num_kbd_updates equ 2074h ; storing a line address, possibly also to do with shuffle shufad1 equ 2075h ; Confirmed unwritten by tests. Reading non-zero causes premature exit from update_kbd UNWRIT_X2077 equ 2077h ; C0 BEL and margin bell add to this location, and it is processed in vertical interrupt with other keyboard bits bell_duration equ 2078h ; ; At start-up, GPO presence is read from the I/O flags buffer and sets bit 0 of these flags. ; Bit 7 is set if we are currently passing characters to the GPO, between DECGON and DECGOFF. ; No other bits are used. gpo_flags equ 2079h ; tested and cleared during vert. int. ; shuffle cannot happen until this is nonzero. made nonzero when extra line is connected shuffle_ready equ 207ah ; checked in proc_func_key ; 0ffh = in setup, 0 = not in setup in_setup equ 207bh ; refresh_rate is 20h for 60Hz, 30h for 50Hz refresh_rate equ 207ch refresh_60Hz equ 20h refresh_50Hz equ 30h inter_chars equ 207dh ; intermediate chars are added together in this byte final_char equ 207eh ; final character of ESC or CSI sequence ; Count of vertical interrupts, at 60 Hz, used for timing BREAK and synchronising switch to SET-UP screen frame_count equ 207fh ; Received characters go into this buffer, at the location 2000h + rx_head, ; and they are pulled out from 2000h + rx_tail. Both rx_head and rx_tail are ; initialised to 80h, and when they increment past 0bfh, that's where they ; wrap back to, so the buffer is 64 characters long. rx_buffer equ 2080h ; initialised to 80h, seems to be where next received character is placed, ; and will run up to 0bfh, then wrap back to 80h ; Receiver int rx_head equ 20c0h rx_tail equ 20c1h ; 20c2 is a table of 25 (including pline_extra) addresses of physical lines in the screen RAM. ; X20de is because it is the address of row 14 (0-based), so for a 14 line ; display it is the line beyond the last on the screen. Looking at the code ; around X117e, pline_extra seems to have a similar function. pline_addr equ 20c2h ; 28 locs ; address of last line in screen ram? pline_extra equ 20f2h ; move_updates seems to place this where cursor *was* char_und_curs equ 20f4h rend_und_curs equ 20f5h ; Must be cursor address in screen RAM cursor_address equ 20f6h ; The graphics state that DECSC saves, and DECRC restores, is stored from 20f8h to 2101h. ; Not all of these bytes have been decoded yet. gfx_state equ 20f8h ; live graphics state (cursor position, SGR, etc.) curs_col equ 20f8h ; first location of state seems to be X (column) curs_row equ 20f9h ; this is absolute cursor row (regardless of origin mode) ; Default rendition is 0f7h (_see_ sgr_off) ; blink masks with 0feh (11111110b) ; underscore masks with 0fdh (11111101b) ; bold masks with 0fbh (11111011b) char_rend equ 20fah rend_blink equ 0feh rend_under equ 0fdh rend_bold equ 0fbh ; reverse video is treated differently, with normal video being ; 0 and reverse video setting this to 80h. char_rvid equ 20fbh gl_invocation equ 20fch ; 0 or 1, depending on whether G0 or G1 is invoked into GL g0_charset equ 20fdh g1_charset equ 20feh g2_charset equ 20ffh ; can't designate a charset into G2 or G3 but they are initialised g3_charset equ 2100h ; with the same defaults as G0 and G1 ; origin mode DECOM 1/0 origin_mode equ 2101h gfx_saved equ 2102h ; saved graphics state saved_rend equ 2104h ; saved char_rend ; enter_setup stores curs_col and curs_row here saved_curs_col equ 210dh ; initialised to 0ffh at startup. Something to do with margins, but looks more like a flag than value ; Seems to be very commonly invalidated by storing 0ffh (many places) and 0f0h (one place) saved_curs_row equ 210eh UNUSED_X210f equ 210fh UNUSED_X2110 equ 2110h ; When we enter SET-UP, the previous action for received characters, char_action, is ; saved here. saved_action equ 2111h ; ; Detailed in TM §4.7.3.2, p. 4-92 ; Each entry in this array contains the number of a line on the physical screen. What the TM ; doesn't say is that bit 7 might be set on the physical line number; this means that the line ; is double width, which in turn means that a second set of terminating bytes have been placed ; half-way across the line. ; ; LATOFS runs from 2113h (row 0) to 212a (row 23). I don't yet know whether X212b is related, ; as perhaps being the physical number of the 25th line. latofs equ 2113h ; Bottom row number + 1 is written in latofs_last, even for 14-line screens latofs_last equ 212bh ; Counts down from 35h, toggles blink flip-flop every time it reaches zero blink_timer equ 212ch ; 16-bit counts down in update_kbd and then flips cursor visibility cursor_timer equ 212dh param_value equ 212fh ; current CSI parameter value we're collecting ; TWO names for same location here. csi_params is used to refer to the array, when the ; code is going to iterate over params and the name csi_p1 is used when we're explicitly ; looking for the first parameter. csi_params equ 2130h ; list of 16 params for CSI sequence csi_p1 equ 2130h ; parameter p1 is start of array csi_p2 equ 2131h ; None of these names for further parameters are used in the source because there are no ; sequences on a VT100 with more than two fixed parameters. All other sequences have ; selection parameters, and they are addressed by iterating over the array as a whole. ; Nevertheless, the presence of names in the symbol table aids debugging. csi_p3 equ 2132h csi_p4 equ 2133h csi_p5 equ 2134h csi_p6 equ 2135h csi_p7 equ 2136h csi_p8 equ 2137h csi_p9 equ 2138h csi_p10 equ 2139h csi_p11 equ 213ah csi_p12 equ 213bh csi_p13 equ 213ch csi_p14 equ 213dh csi_p15 equ 213eh ; The 16th numeric parameter is here for convenience of processing. It can be written ; to, but it is never used during execution of a control sequence. csi_p16 equ 213fh ; char_action equ 2140h ; address of routine used to process next incoming character ; If we write to location on right-hand edge of screen and auto-wrap is on, ; need for a wrap on the next write is recorded here. Always cleared after ; a non-edge character is written. pending_wrap equ 2142h ; used in send_key_byte to hold offset into curkey_queue curkey_qcount equ 2143h keyboard_locked equ 2144h ; Supposed to be a mask for four bits (0-3, here) that are masked with other ; bytes to form an instruction for the keyword. However, a bug (_see_ decll_action) ; means that this byte can have bits 4-7 set, causing interference with the ; keyboard, and they cannot be then unset without resetting the terminal. ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | | |L1 on|L2 on|L3 on|L4 on| ; +-----+-----+-----+-----+-----+-----+-----+-----+ led_state equ 2145h ; online/local mask for keyboard (directly ORed with led_state) kbd_online_mask equ 2146h ; spkr./click mask (directly ORed with led_state) kbd_click_mask equ 2147h kbd_scan_mask equ 2148h ; Never see this being read, or jumped through but looks like address location ; I believe this always contains 07ffh. Confirmed by tests. UNREAD_X2149 equ 2149h UNREAD_X214a equ 214ah num_params equ 214bh ; offset into params array of the current param UNUSED_X214c equ 214ch UNUSED_X214d equ 214dh ; ; Start of the cursor line in video RAM start_line_addr equ 214eh ; a key scan code - checked when processing auto repeat latest_key_scan equ 2150h ; This flag is only cleared when a column has been received, rather than when ESC Y has been ; recognised, which means that intervening C0 controls won't affect the very next printable ; characters from being recognised as a row or column. got_vt52_row equ 2151h vt52_row_coord equ 2152h ; ; Internal column number of right margin of the current line. ; This will be 79 or 131 for single-width lines. One of the jobs of _see_ move_updates ; is to halve this for double-width lines. ; right_margin equ 2153h ; ; Set up if a margin bell is required. Stealth read at 1696h. margin_bell equ 2154h top_margin equ 2155h bottom_margin equ 2156h ; Gets 80h double-width marker if appropriate, or 0 for single line curr_line_dbl equ 2157h ; This tx_spd and rx_spd combined to make a single byte, sent to iow_baud_rate tx_rx_speed equ 2158h ; ; Next two locations control how the cursor is going to work, either by changing the ; base attribute in the video RAM for each character, which is what must happen without ; AVO present, or by changing attribute RAM, when AVO is present. Cursor setup records ; both options in these locations, which get XORed with video RAM and attribute RAM, ; respectively. ; ; without AVO, this is 80h, so toggles between normal and reverse video (or underline) curs_char_rend equ 2159h ; 0 for underline cursor, 2 for block curs_attr_rend equ 215ah ; 0 = basic attribute is underline, 1 = basic attribute is reverse video basic_rev_video equ 215bh ; Reports to be sent out from the terminal are built in this buffer. ; Longest report is DECREPTPARM, which can reach 21 characters, making ; this buffer extend from 215ch to 2170h. ; DECREPTPARM: ESC [ 2 ; 1 ; 1 ; 120 ; 120 ; 1 ; 15 c report_buffer equ 215ch ; Offset into report_buffer of the character to be sent next rep_send_offset equ 2171h ; When a sequence is received that requires a response, the need for a response is placed in ; location pending_report, and then dealt with later, as part of the periodic keyboard ; tick routine. ; ; pend_<x> are the individual bit flags to say what needs reporting pending_report equ 2172h pend_curpos equ 01h ; DSR 6 (cursor position) has been requested pend_tparm equ 02h ; DECREQTPARM has been received pend_ident equ 04h ; DECID has been received pend_devstat equ 08h ; DSR 5 (device status) has been requested pend_aback equ 10h ; Answerback has been triggered pend_key equ 20h ; Keys to host (single or multi-byte) ; When a report has been prepared and send_report has been called, this goes to 1, ; then back to zero when last character of report has been grabbed from buffer sending_report equ 2173h ; ; Used to hold the address of a routine that will produce a report, then holds ; the address of the routine that pumps them out, which is cont_report for all ; reports other than cursor keys, because they are prepared in advance, one at ; a time, but several cursor key reports can be buffered. report_action equ 2174h ; Flag whether DECREPTPARM can be sent unsolicited (i.e. whenever SET-UP is exited), ; or only on request. This is controlled by the parameter sent with DECREQTPARM, ; so this flag will be 0 = unsolicited reports allowed, 1 = solicited only ; Status on reset will be 1, i.e. no unsolicited reports tparm_solicited equ 2176h ; When SETUP is detected in keyboard processing, this flag is set to indicate that ; SET-UP should be entered. pending_setup equ 2177h ; keypad_mode: 0 = numeric, 1 = application keypad_mode equ 2178h ; For line shuffling shufdt1 equ 2179h ; TM §4.7.11 details SET-UP scratch RAM (saying it is subject to change.) ; It confirms that the first area here is the answerback message, 22 bytes, with 20 characters and 2 delimiters. aback_buffer equ 217bh aback_bufend equ 2190h ; 132/8 = 16.5 bytes, so tab buffer is 17 bytes, 2191h to 21a1h tab_settings equ 2191h tablen equ 17 ; bytes in tab settings area ; 1 = 132 columns, 0 = 80 columns columns_132 equ 21a2h ; brightest = 0, dimmest = 1fh brightness equ 21a3h ; pusart_mode, based on TM §4.7.11 pusart_mode equ 21a4h ; ; local_mode flag is ORed into the keyboard byte in order to set the Local LED, ; so the value 20h is used as "local". Data loopback test will indicate failure ; by placing 25h, in order to briefly light LEDs L2 and L4 - these then get removed ; by after_tests. local_mode equ 21a5h ; 21a6: SET-UP B block 1 ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | | | | | | | ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | `-- 1 = cursor block, 0 = cursor underline ; | | `-- 1 = light background, 0 = dark background ; | `-- 1 = autorepeat on, 0 = autorepeat off ; `-- 1 = smooth scroll, 0 = jump scroll ; setup_b1 equ 21a6h sb1_curblock equ 10h sb1_lightback equ 20h sb1_autorep equ 40h sb1_smooth equ 80h ; ; 21a7: SET-UP B block 2 ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | | | | | | | ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | `-- 1 = auto xon/xoff, 0 = no auto xon/off ; | | `-- 1 = ANSI mode, 0 = VT52 (_see_ ansi_mode) ; | `-- 1 = keyclick on, 0 = keyclick off ; `-- 1 = margin bell on, 0 = margin bell off ; setup_b2 equ 21a7h sb2_autoxon equ 10h sb2_ansi equ 20h sb2_keyclick equ 40h sb2_marginbell equ 80h ; 21a8: SET-UP B block 3 ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | | | | | | | ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | `-- 1 = interlace on, 0 = interlace off (_see_ decinlm_mode) ; | | `-- 1 = ?, 0 = ? ; | `-- 1 = autowrap, 0 = no autowrap (_see_ decawm_mode) ; `-- 1 = UK, 0 = ASCII setup_b3 equ 21a8h sb3_interlace equ 10h sb3_newline equ 20h sb3_autowrap equ 40h sb3_uk equ 80h ; 21a9: SET-UP B block 4 ; ; 7 6 5 4 3 2 1 0 ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | | | | | | | ; +-----+-----+-----+-----+-----+-----+-----+-----+ ; | | | `-- 1 - power 50 Hz, 0 = power 60 Hz ; | | `-- bits/char: 1 = 8 bits, 0 = 7 bits ; | `-- 1 = parity on, 0 = parity off ; `-- 1 = even parity, 0 = odd parity setup_b4 equ 21a9h sb4_50Hz equ 10h sb4_8bits equ 20h sb4_parityon equ 40h sb4_evenparity equ 80h sb4_paritybits equ (sb4_parityon|sb4_evenparity) ; setup_b5 equ 21aah ; only visible with STP option installed tx_spd equ 21abh ; encoded transmit speed in high 4 bits rx_spd equ 21ach ; encoded receive speed in high 4 bits nvr_checksum equ 21adh ; nvr_addr equ 21aeh nvr_data equ 21afh ; 2 locs UNUSED_X21b1 equ 21b1h UNUSED_X21b2 equ 21b2h UNUSED_X21b3 equ 21b3h answerback_ptr equ 21b4h UNUSED_X21b6 equ 21b6h UNUSED_X21b7 equ 21b7h csi_private equ 21b8h ; CSI sequence private character is stored here found_action equ 21b9h ; initialised to 0ffh at startup cursor_visible equ 21bah ; updated post cursor move, used for margin bell calculations because it matters whether ; we got to the current column by typing or cursor positioning sequences. last_curs_col equ 21bbh mode_ckm equ 21bch ; POST results go here test_results equ 21bdh ; in_setup_a is 1 for SET-UP A, 0 for SET-UP B. in_setup_a equ 21beh ; ; If the host is allowed to send characters (receive buffer has enough space, ; user has pressed Ctrl/Q, we've come out of SETUP, etc.) then this will be zero, ; and an XON will probably have been sent. Otherwise, this records why the host has ; been told to stop, as a bit mask. 01h means the receive buffer is getting full, ; and 02h means the user has pressed NO SCROLL or Ctrl/S. ; 03h means the receive buffer was already getting full, and the user also panicked ; and hit NO SCROLL! ; why_xoff equ 21bfh ; XON/XOFF character to transmit is pulled from here, as long as 21c1h is not zero tx_xo_char equ 21c0h tx_xo_flag equ 21c1h ; Contents of this ANDed with 0feh if we've received XON, ORed with 1 if we've received XOFF received_xoff equ 21c2h ; gets zeroed by clear_part_row ; flag marked when smooth scroll and need to clear extra line, so non-interrupt path ; sets this flag and then waits until the clearance happens in vertical interrupt and ; the flag gets zeroed. row_clearing equ 21c3h ; no_scroll_key stores 2 (sent XOFF) or 0 (sent XON) here noscroll equ 21c4h ; When we enter SET-UP mode, we save the previous video pointer here saved_line1_dma equ 21c5h ; This is zero, except for alignment display, which makes it 'E' (and then zeroes again) cls_char equ 21c7h ; Recorded early in start-up. Non zero if no AVO found avo_missing equ 21c8h ; gets sent to iow_nvr_latch during vertical int ; Vertical interrupt outputs to the NVR latch, so any code that is writing to the latch while ; interrupts are still enabled also stores the value here, so it persists. vint_nvr equ 21c9h UNUSED_X21ca equ 21cah ; updated when blink timer goes off in vertical interrupt ; repeat test field ; If DECTST has requested some tests to be repeatedly executed and they fail, the screen field ; is toggled between normal and reverse on each cycle. This can be seen by sending the sequence ; ESC [ 2 ; 10 y (data loopback with repeat). Data loopback will always fail in the absence of ; a loopback connector, so the screen will show "8" for failure in the first character position, ; and the entire screen will blink between normal and reverse field. ; test_field equ 21cbh ; This area holds the mini screen definition for "Wait", with terminators that ; point back to the fill lines. The entire screen definition is just 7 bytes long. wait_addr equ 21cch ; wait screen address in DMA (big-endian) form, with normal line attributes wait_addr_be equ 0cc71h nvr_bits equ 21d3h ; must be at least 14 locations ; setup_video is where the SET-UP characters are drawn, and then the Video DMA is switched ; to point to here while we are in this mode. setup_video equ 2253h ; ; Normal screen display starts here in scratch RAM, and line1_dma gets initialised to point to it. ; screen_layout (the initial 18 bytes of definition) point here literally, and any other time ; we want to get back to this location, main_video_be will be loaded into HL and then ; written to line1_dma. This establishes the first line as part of the scrolling region, ; with normal lines attributes. ; main_video equ 22d0h main_video_be equ 0d0f2h ; end ; ; vim: set ts=8 noet :
; A166118: Fixed points of the mapping f(x) = (x + 2^x) mod (17 + x). ; 15,47,111,239,495,1007,2031,4079,8175,16367,32751,65519,131055,262127,524271,1048559,2097135,4194287,8388591,16777199,33554415,67108847,134217711,268435439,536870895,1073741807,2147483631,4294967279,8589934575,17179869167,34359738351,68719476719,137438953455,274877906927,549755813871,1099511627759,2199023255535,4398046511087,8796093022191,17592186044399,35184372088815,70368744177647,140737488355311,281474976710639,562949953421295,1125899906842607,2251799813685231,4503599627370479,9007199254740975 add $0,5 mov $1,2 pow $1,$0 sub $1,17
include aasyslib.i CGROUP group code code segment dword 'CODE' assume cs:CGROUP,ds:CGROUP SYSLIB_JUMP pj_rexlib_init sysl_pj_rexlib_init code ends end
//===- Win64EHDumper.cpp - Win64 EH Printer ---------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Win64EHDumper.h" #include "llvm-readobj.h" #include "llvm/Object/COFF.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" using namespace llvm; using namespace llvm::object; using namespace llvm::Win64EH; static const EnumEntry<unsigned> UnwindFlags[] = { { "ExceptionHandler", UNW_ExceptionHandler }, { "TerminateHandler", UNW_TerminateHandler }, { "ChainInfo" , UNW_ChainInfo } }; static const EnumEntry<unsigned> UnwindOpInfo[] = { { "RAX", 0 }, { "RCX", 1 }, { "RDX", 2 }, { "RBX", 3 }, { "RSP", 4 }, { "RBP", 5 }, { "RSI", 6 }, { "RDI", 7 }, { "R8", 8 }, { "R9", 9 }, { "R10", 10 }, { "R11", 11 }, { "R12", 12 }, { "R13", 13 }, { "R14", 14 }, { "R15", 15 } }; static uint64_t getOffsetOfLSDA(const UnwindInfo& UI) { return static_cast<const char*>(UI.getLanguageSpecificData()) - reinterpret_cast<const char*>(&UI); } static uint32_t getLargeSlotValue(ArrayRef<UnwindCode> UC) { if (UC.size() < 3) return 0; return UC[1].FrameOffset + (static_cast<uint32_t>(UC[2].FrameOffset) << 16); } // Returns the name of the unwind code. static StringRef getUnwindCodeTypeName(uint8_t Code) { switch (Code) { default: llvm_unreachable("Invalid unwind code"); case UOP_PushNonVol: return "PUSH_NONVOL"; case UOP_AllocLarge: return "ALLOC_LARGE"; case UOP_AllocSmall: return "ALLOC_SMALL"; case UOP_SetFPReg: return "SET_FPREG"; case UOP_SaveNonVol: return "SAVE_NONVOL"; case UOP_SaveNonVolBig: return "SAVE_NONVOL_FAR"; case UOP_SaveXMM128: return "SAVE_XMM128"; case UOP_SaveXMM128Big: return "SAVE_XMM128_FAR"; case UOP_PushMachFrame: return "PUSH_MACHFRAME"; } } // Returns the name of a referenced register. static StringRef getUnwindRegisterName(uint8_t Reg) { switch (Reg) { default: llvm_unreachable("Invalid register"); case 0: return "RAX"; case 1: return "RCX"; case 2: return "RDX"; case 3: return "RBX"; case 4: return "RSP"; case 5: return "RBP"; case 6: return "RSI"; case 7: return "RDI"; case 8: return "R8"; case 9: return "R9"; case 10: return "R10"; case 11: return "R11"; case 12: return "R12"; case 13: return "R13"; case 14: return "R14"; case 15: return "R15"; } } // Calculates the number of array slots required for the unwind code. static unsigned getNumUsedSlots(const UnwindCode &UnwindCode) { switch (UnwindCode.getUnwindOp()) { default: llvm_unreachable("Invalid unwind code"); case UOP_PushNonVol: case UOP_AllocSmall: case UOP_SetFPReg: case UOP_PushMachFrame: return 1; case UOP_SaveNonVol: case UOP_SaveXMM128: return 2; case UOP_SaveNonVolBig: case UOP_SaveXMM128Big: return 3; case UOP_AllocLarge: return (UnwindCode.getOpInfo() == 0) ? 2 : 3; } } static std::string formatSymbol(const Dumper::Context &Ctx, const coff_section *Section, uint64_t Offset, uint32_t Displacement) { std::string Buffer; raw_string_ostream OS(Buffer); SymbolRef Symbol; if (!Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData)) { if (ErrorOr<StringRef> Name = Symbol.getName()) { OS << *Name; if (Displacement > 0) OS << format(" +0x%X (0x%" PRIX64 ")", Displacement, Offset); else OS << format(" (0x%" PRIX64 ")", Offset); return OS.str(); } } OS << format(" (0x%" PRIX64 ")", Offset); return OS.str(); } static std::error_code resolveRelocation(const Dumper::Context &Ctx, const coff_section *Section, uint64_t Offset, const coff_section *&ResolvedSection, uint64_t &ResolvedAddress) { SymbolRef Symbol; if (std::error_code EC = Ctx.ResolveSymbol(Section, Offset, Symbol, Ctx.UserData)) return EC; ErrorOr<uint64_t> ResolvedAddressOrErr = Symbol.getAddress(); if (std::error_code EC = ResolvedAddressOrErr.getError()) return EC; ResolvedAddress = *ResolvedAddressOrErr; ErrorOr<section_iterator> SI = Symbol.getSection(); ResolvedSection = Ctx.COFF.getCOFFSection(**SI); return std::error_code(); } namespace llvm { namespace Win64EH { void Dumper::printRuntimeFunctionEntry(const Context &Ctx, const coff_section *Section, uint64_t Offset, const RuntimeFunction &RF) { SW.printString("StartAddress", formatSymbol(Ctx, Section, Offset + 0, RF.StartAddress)); SW.printString("EndAddress", formatSymbol(Ctx, Section, Offset + 4, RF.EndAddress)); SW.printString("UnwindInfoAddress", formatSymbol(Ctx, Section, Offset + 8, RF.UnwindInfoOffset)); } // Prints one unwind code. Because an unwind code can occupy up to 3 slots in // the unwind codes array, this function requires that the correct number of // slots is provided. void Dumper::printUnwindCode(const UnwindInfo& UI, ArrayRef<UnwindCode> UC) { assert(UC.size() >= getNumUsedSlots(UC[0])); SW.startLine() << format("0x%02X: ", unsigned(UC[0].u.CodeOffset)) << getUnwindCodeTypeName(UC[0].getUnwindOp()); switch (UC[0].getUnwindOp()) { case UOP_PushNonVol: OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo()); break; case UOP_AllocLarge: OS << " size=" << ((UC[0].getOpInfo() == 0) ? UC[1].FrameOffset * 8 : getLargeSlotValue(UC)); break; case UOP_AllocSmall: OS << " size=" << (UC[0].getOpInfo() + 1) * 8; break; case UOP_SetFPReg: if (UI.getFrameRegister() == 0) OS << " reg=<invalid>"; else OS << " reg=" << getUnwindRegisterName(UI.getFrameRegister()) << format(", offset=0x%X", UI.getFrameOffset() * 16); break; case UOP_SaveNonVol: OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo()) << format(", offset=0x%X", UC[1].FrameOffset * 8); break; case UOP_SaveNonVolBig: OS << " reg=" << getUnwindRegisterName(UC[0].getOpInfo()) << format(", offset=0x%X", getLargeSlotValue(UC)); break; case UOP_SaveXMM128: OS << " reg=XMM" << static_cast<uint32_t>(UC[0].getOpInfo()) << format(", offset=0x%X", UC[1].FrameOffset * 16); break; case UOP_SaveXMM128Big: OS << " reg=XMM" << static_cast<uint32_t>(UC[0].getOpInfo()) << format(", offset=0x%X", getLargeSlotValue(UC)); break; case UOP_PushMachFrame: OS << " errcode=" << (UC[0].getOpInfo() == 0 ? "no" : "yes"); break; } OS << "\n"; } void Dumper::printUnwindInfo(const Context &Ctx, const coff_section *Section, off_t Offset, const UnwindInfo &UI) { DictScope UIS(SW, "UnwindInfo"); SW.printNumber("Version", UI.getVersion()); SW.printFlags("Flags", UI.getFlags(), makeArrayRef(UnwindFlags)); SW.printNumber("PrologSize", UI.PrologSize); if (UI.getFrameRegister()) { SW.printEnum("FrameRegister", UI.getFrameRegister(), makeArrayRef(UnwindOpInfo)); SW.printHex("FrameOffset", UI.getFrameOffset()); } else { SW.printString("FrameRegister", StringRef("-")); SW.printString("FrameOffset", StringRef("-")); } SW.printNumber("UnwindCodeCount", UI.NumCodes); { ListScope UCS(SW, "UnwindCodes"); ArrayRef<UnwindCode> UC(&UI.UnwindCodes[0], UI.NumCodes); for (const UnwindCode *UCI = UC.begin(), *UCE = UC.end(); UCI < UCE; ++UCI) { unsigned UsedSlots = getNumUsedSlots(*UCI); if (UsedSlots > UC.size()) { errs() << "corrupt unwind data"; return; } printUnwindCode(UI, ArrayRef<UnwindCode>(UCI, UCE)); UCI = UCI + UsedSlots - 1; } } uint64_t LSDAOffset = Offset + getOffsetOfLSDA(UI); if (UI.getFlags() & (UNW_ExceptionHandler | UNW_TerminateHandler)) { SW.printString("Handler", formatSymbol(Ctx, Section, LSDAOffset, UI.getLanguageSpecificHandlerOffset())); } else if (UI.getFlags() & UNW_ChainInfo) { if (const RuntimeFunction *Chained = UI.getChainedFunctionEntry()) { DictScope CS(SW, "Chained"); printRuntimeFunctionEntry(Ctx, Section, LSDAOffset, *Chained); } } } void Dumper::printRuntimeFunction(const Context &Ctx, const coff_section *Section, uint64_t SectionOffset, const RuntimeFunction &RF) { DictScope RFS(SW, "RuntimeFunction"); printRuntimeFunctionEntry(Ctx, Section, SectionOffset, RF); const coff_section *XData; uint64_t Offset; resolveRelocation(Ctx, Section, SectionOffset + 8, XData, Offset); ArrayRef<uint8_t> Contents; error(Ctx.COFF.getSectionContents(XData, Contents)); if (Contents.empty()) return; Offset = Offset + RF.UnwindInfoOffset; if (Offset > Contents.size()) return; const auto UI = reinterpret_cast<const UnwindInfo*>(Contents.data() + Offset); printUnwindInfo(Ctx, XData, Offset, *UI); } void Dumper::printData(const Context &Ctx) { for (const auto &Section : Ctx.COFF.sections()) { StringRef Name; Section.getName(Name); if (Name != ".pdata" && !Name.startswith(".pdata$")) continue; const coff_section *PData = Ctx.COFF.getCOFFSection(Section); ArrayRef<uint8_t> Contents; error(Ctx.COFF.getSectionContents(PData, Contents)); if (Contents.empty()) continue; const RuntimeFunction *Entries = reinterpret_cast<const RuntimeFunction *>(Contents.data()); const size_t Count = Contents.size() / sizeof(RuntimeFunction); ArrayRef<RuntimeFunction> RuntimeFunctions(Entries, Count); size_t Index = 0; for (const auto &RF : RuntimeFunctions) { printRuntimeFunction(Ctx, Ctx.COFF.getCOFFSection(Section), Index * sizeof(RuntimeFunction), RF); ++Index; } } } } }
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. All rights reserved. ParaView is a free software; you can redistribute it and/or modify it under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting Kitware Inc. 28 Corporate Drive Clifton Park, NY 12065 USA THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "pqScalarsToColors.h" #include "vtkCommand.h" #include "vtkEventQtSlotConnect.h" #include "vtkSMDoubleVectorProperty.h" #include "vtkSMProxy.h" #include <QPointer> #include <QList> #include <QtDebug> #include "pqApplicationCore.h" #include "pqPipelineRepresentation.h" #include "pqRenderViewBase.h" #include "pqScalarBarRepresentation.h" #include "pqServerManagerModel.h" #include "pqSMAdaptor.h" #include "vtkSMProperty.h" //----------------------------------------------------------------------------- class pqScalarsToColorsInternal { public: QList<QPointer<pqScalarBarRepresentation> > ScalarBars; vtkEventQtSlotConnect* VTKConnect; pqScalarsToColorsInternal() { this->VTKConnect = vtkEventQtSlotConnect::New(); } ~pqScalarsToColorsInternal() { this->VTKConnect->Delete(); } }; //----------------------------------------------------------------------------- pqScalarsToColors::pqScalarsToColors(const QString& group, const QString& name, vtkSMProxy* proxy, pqServer* server, QObject* _parent/*=NULL*/) : pqProxy(group, name, proxy, server, _parent) { this->Internal = new pqScalarsToColorsInternal; this->Internal->VTKConnect->Connect(proxy->GetProperty("RGBPoints"), vtkCommand::ModifiedEvent, this, SLOT(checkRange())); this->Internal->VTKConnect->Connect(proxy->GetProperty("UseLogScale"), vtkCommand::ModifiedEvent, this, SLOT(checkRange())); } //----------------------------------------------------------------------------- pqScalarsToColors::~pqScalarsToColors() { delete this->Internal; } //----------------------------------------------------------------------------- void pqScalarsToColors::addScalarBar(pqScalarBarRepresentation* sb) { if (this->Internal->ScalarBars.indexOf(sb) == -1) { this->Internal->ScalarBars.push_back(sb); emit this->scalarBarsChanged(); } } //----------------------------------------------------------------------------- void pqScalarsToColors::removeScalarBar(pqScalarBarRepresentation* sb) { if (this->Internal->ScalarBars.removeAll(sb) > 0) { emit this->scalarBarsChanged(); } } //----------------------------------------------------------------------------- pqScalarBarRepresentation* pqScalarsToColors::getScalarBar(pqRenderViewBase* ren) const { foreach(pqScalarBarRepresentation* sb, this->Internal->ScalarBars) { if (sb && (sb->getView() == ren)) { return sb; } } return 0; } //----------------------------------------------------------------------------- void pqScalarsToColors::setScalarRangeLock(bool lock) { vtkSMProperty* prop = this->getProxy()->GetProperty("LockScalarRange"); if (prop) { pqSMAdaptor::setElementProperty(prop, (lock? 1: 0)); } this->getProxy()->UpdateVTKObjects(); } //----------------------------------------------------------------------------- bool pqScalarsToColors::getScalarRangeLock() const { vtkSMProperty* prop = this->getProxy()->GetProperty("LockScalarRange"); if (prop && pqSMAdaptor::getElementProperty(prop).toInt() != 0) { return true; } // we may keep some GUI only state for vtkLookupTable proxies. return false; } //----------------------------------------------------------------------------- void pqScalarsToColors::hideUnusedScalarBars() { pqApplicationCore* core = pqApplicationCore::instance(); pqServerManagerModel* smmodel = core->getServerManagerModel(); QList<pqPipelineRepresentation*> displays = smmodel->findItems<pqPipelineRepresentation*>(this->getServer()); bool used_at_all = false; foreach(pqPipelineRepresentation* display, displays) { if (display->isVisible() && display->getColorField(true) != pqPipelineRepresentation::solidColor() && display->getLookupTableProxy() == this->getProxy()) { used_at_all = true; break; } } if (!used_at_all) { foreach(pqScalarBarRepresentation* sb, this->Internal->ScalarBars) { sb->setVisible(false); sb->renderViewEventually(); } } } //----------------------------------------------------------------------------- void pqScalarsToColors::setScalarRange(double min, double max) { if (min > max) { double t = min; min = max; max = t; } pqSMAdaptor::setElementProperty( this->getProxy()->GetProperty("ScalarRangeInitialized"), 1); QPair <double, double> current_range = this->getScalarRange(); if (current_range.first == min && current_range.second == max) { // Nothing to do. return; } // Adjust vtkColorTransferFunction points to the new range. double dold = (current_range.second - current_range.first); dold = (dold > 0) ? dold : 1; double dnew = (max -min); dnew = (dnew > 0) ? dnew : 1; double scale = dnew/dold; vtkSMDoubleVectorProperty* dvp = vtkSMDoubleVectorProperty::SafeDownCast( this->getProxy()->GetProperty("RGBPoints")); QList<QVariant> controlPoints = pqSMAdaptor::getMultipleElementProperty(dvp); int num_elems_per_command = dvp->GetNumberOfElementsPerCommand(); for (int cc=0; cc < controlPoints.size(); cc += num_elems_per_command) { // These checks ensure that the first and last control points match the // min and max values exactly. if (cc==0) { controlPoints[cc] = min; } else if ((cc+num_elems_per_command) >= controlPoints.size()) { controlPoints[cc] = max; } else { controlPoints[cc] = scale * (controlPoints[cc].toDouble()-current_range.first) + min; } } pqSMAdaptor::setMultipleElementProperty(dvp, controlPoints); this->getProxy()->UpdateVTKObjects(); } //----------------------------------------------------------------------------- QPair<double, double> pqScalarsToColors::getScalarRange() const { vtkSMDoubleVectorProperty* dvp = vtkSMDoubleVectorProperty::SafeDownCast( this->getProxy()->GetProperty("RGBPoints")); QList<QVariant> controlPoints = pqSMAdaptor::getMultipleElementProperty(dvp); if (controlPoints.size() == 0) { return QPair<double, double>(0, 0); } int max_index = dvp->GetNumberOfElementsPerCommand() * ( (controlPoints.size()-1)/ dvp->GetNumberOfElementsPerCommand()); return QPair<double, double>(controlPoints[0].toDouble(), controlPoints[max_index].toDouble()); } //----------------------------------------------------------------------------- void pqScalarsToColors::setWholeScalarRange(double min, double max) { if (this->getScalarRangeLock()) { return; } if (pqSMAdaptor::getElementProperty( this->getProxy()->GetProperty("ScalarRangeInitialized")).toBool()) { QPair<double, double> curRange = this->getScalarRange(); min = (min < curRange.first)? min : curRange.first; max = (max > curRange.second)? max : curRange.second; } this->setScalarRange(min, max); } //----------------------------------------------------------------------------- bool pqScalarsToColors::getUseLogScale() const { vtkSMProxy *proxy = this->getProxy(); vtkSMProperty *prop = proxy->GetProperty("UseLogScale"); return (pqSMAdaptor::getElementProperty(prop).toInt() != 0); } //----------------------------------------------------------------------------- void pqScalarsToColors::checkRange() { // Only need to adjust range if using log scale. if (!this->getUseLogScale()) return; QPair<double, double> range = this->getScalarRange(); if (range.first > 0.0) return; // If we are here, we need to adjust the range to be all positive. QPair<double, double> newRange; if (range.second > 1.0) { newRange.first = 1.0; newRange.second = range.second; } else if (range.second > 0.0) { newRange.first = range.second/10.0; newRange.second = range.second; } else { range.first = 1.0; range.second = 10.0; } qWarning("Warning: Range [%g,%g] invalid for log scaling. Changing to [%g,%g].", range.first, range.second, newRange.first, newRange.second); this->setScalarRange(newRange.first, newRange.second); } //----------------------------------------------------------------------------- void pqScalarsToColors::setVectorMode(Mode mode, int comp) { vtkSMProxy* proxy = this->getProxy(); pqSMAdaptor::setEnumerationProperty(proxy->GetProperty("VectorMode"), (mode == MAGNITUDE)? "Magnitude" : "Component"); pqSMAdaptor::setElementProperty(proxy->GetProperty("VectorComponent"), (mode == COMPONENT)? comp: 0); proxy->UpdateVTKObjects(); } //----------------------------------------------------------------------------- void pqScalarsToColors::updateScalarBarTitles(const QString& component) { foreach(pqScalarBarRepresentation* sb, this->Internal->ScalarBars) { sb->setTitle(sb->getTitle().first, component); } } //----------------------------------------------------------------------------- pqScalarsToColors::Mode pqScalarsToColors::getVectorMode() const { if (pqSMAdaptor::getEnumerationProperty( this->getProxy()->GetProperty("VectorMode")) == "Magnitude") { return MAGNITUDE; } return COMPONENT; } //----------------------------------------------------------------------------- int pqScalarsToColors::getVectorComponent() const { return pqSMAdaptor::getElementProperty( this->getProxy()->GetProperty("VectorComponent")).toInt(); } //----------------------------------------------------------------------------- void pqScalarsToColors::build() { this->getProxy()->InvokeCommand("Build"); }
;------------------------------------------------------------------------------ ; ; 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: ; ; CpuPause.Asm ; ; Abstract: ; ; CpuPause function ; ; Notes: ; ;------------------------------------------------------------------------------ DEFAULT REL SECTION .text ;------------------------------------------------------------------------------ ; VOID ; EFIAPI ; CpuPause ( ; VOID ; ); ;------------------------------------------------------------------------------ global ASM_PFX(CpuPause) ASM_PFX(CpuPause): pause ret
; A004259: a(n) = floor(10*log_2(n)). ; 0,10,15,20,23,25,28,30,31,33,34,35,37,38,39,40,40,41,42,43,43,44,45,45,46,47,47,48,48,49,49,50,50,50,51,51,52,52,52,53,53,53,54,54,54,55,55,55,56,56,56,57,57,57,57,58,58,58,58,59,59,59,59,60,60,60,60,60,61,61,61,61,61,62,62,62,62,62,63,63,63,63,63,63,64,64,64,64,64,64,65,65,65,65,65,65,65,66,66,66 mov $2,-2 bin $2,$0 pow $2,10 lpb $2 div $2,2 add $3,1 lpe mov $0,$3 sub $0,1
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; Compute the line coordinates and put into a vector ; Basic concept by Rafael de Oliveira Jannone (calculate_side) ; ; Internal function to update the area object's vectors ; ; Stefano Bodrato - 13/3/2009 ; ; ; $Id: stencil_add_pixel.asm,v 1.6 2016-07-02 09:01:35 dom Exp $ ; ; registers changed after return: ; ..bc..../ixiy same ; af..dehl/.... different INCLUDE "graphics/grafix.inc" SECTION code_clib PUBLIC stencil_add_pixel PUBLIC _stencil_add_pixel PUBLIC stencil_ptr EXTERN __gfx_coords .stencil_add_pixel ._stencil_add_pixel ld (__gfx_coords),hl ; update plot coordinates ld d,0 ld e,l ld a,h ; current X coordinate ld hl,(stencil_ptr) ; right side vector add hl,de cp (hl) jr nc,lo_higher ld (hl),a .lo_higher ld de,maxy add hl,de cp (hl) ret c ; hi_lower ld (hl),a ret SECTION bss_clib .stencil_ptr defw 0
; A232984: The Gauss factorial n_10!. ; Submitted by Jon Maiga ; 1,1,1,3,3,3,3,21,21,189,189,2079,2079,27027,27027,27027,27027,459459,459459,8729721,8729721,183324141,183324141,4216455243,4216455243,4216455243,4216455243,113844291561,113844291561,3301484455269,3301484455269,102346018113339,102346018113339,3377418597740187 sub $0,1 mov $1,1 mov $2,1 lpb $0 mov $3,$2 lpb $3 sub $0,1 add $2,1 mov $4,10 gcd $4,$2 cmp $4,1 cmp $4,0 sub $3,$4 lpe sub $0,1 add $2,1 mul $1,$2 lpe mov $0,$1
// Copyright (c) 2018 The DSC developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode-budget.h" #include "tinyformat.h" #include "utilmoneystr.h" #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(budget_tests) void CheckBudgetValue(int nHeight, std::string strNetwork, CAmount nExpectedValue) { CBudgetManager budget; CAmount nBudget = budget.GetTotalBudget(nHeight); std::string strError = strprintf("Budget is not as expected for %s. Result: %s, Expected: %s", strNetwork, FormatMoney(nBudget), FormatMoney(nExpectedValue)); BOOST_CHECK_MESSAGE(nBudget == nExpectedValue, strError); } BOOST_AUTO_TEST_CASE(budget_value) { SelectParams(CBaseChainParams::TESTNET); int nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "testnet", 7300*COIN); SelectParams(CBaseChainParams::MAIN); nHeightTest = Params().Zerocoin_Block_V2_Start() + 1; CheckBudgetValue(nHeightTest, "mainnet", 43200*COIN); } BOOST_AUTO_TEST_SUITE_END()
; A011903: a(n) = floor(n*(n-1)*(n-2)/21). ; 0,0,0,0,1,2,5,10,16,24,34,47,62,81,104,130,160,194,233,276,325,380,440,506,578,657,742,835,936,1044,1160,1284,1417,1558,1709,1870,2040,2220,2410,2611,2822,3045,3280,3526,3784,4054,4337,4632,4941,5264,5600,5950,6314,6693,7086,7495,7920,8360,8816,9288,9777,10282,10805,11346,11904,12480,13074,13687,14318,14969,15640,16330,17040,17770,18521,19292,20085,20900,21736,22594,23474,24377,25302,26251,27224,28220,29240,30284,31353,32446,33565,34710,35880,37076,38298,39547,40822,42125,43456,44814 bin $0,3 mul $0,2 div $0,7
; A295859: a(n) = a(n-1) + 3*a(n-2) -2*a(n-3) - 2*a(n-4), where a(0) = -2, a(1) = 0, a(2) = 1, a(3) = 1. ; Submitted by Jon Maiga ; -2,0,1,1,8,9,29,38,91,129,268,397,761,1158,2111,3269,5764,9033,15565,24598,41699,66297,111068,177365,294577,471942,778807,1250749,2054132,3304881,5408165,8713046,14219515,22932561,37348684,60281245,98023145,158304390,257113967,415418357,674105188,1089523545,1766774461,2856298006,4629363923,7485661929,12127608764,19613270693,31766045281,51379315974,83195692903,134575008877,217871365076,352446373953,570519065621,922965439574,1493887158379,2416852597953,3911545062700,6328397660653,10241553336089 mov $4,-2 lpb $0 sub $0,1 sub $2,$1 add $1,$3 add $3,1 sub $4,3 mul $4,2 sub $4,$5 add $4,1 add $4,$2 mov $5,$4 mov $4,$2 mov $2,$3 add $4,$1 add $5,2 add $5,$4 mov $3,$5 lpe sub $4,$3 sub $4,$1 add $5,$4 mov $0,$5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Copyright (c) 2013 Manolis Agkopian ; ;See the file LICENCE for copying permission. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PROCESSOR '16F72A' INCLUDE <P16F72.inc> __CONFIG _XT_OSC & _WDT_OFF & _PWRTE_OFF & _CP_OFF & _BODEN_OFF LED EQU 0 CBLOCK 0x20 CNT0 CNT1 CNT2 ENDC ORG 0x00 INIT: BSF STATUS, RP0 ;SELECT BANK 01 BCF TRISB, LED ;PB0 IS AN OUTPUT BCF STATUS, RP0 ;SELECT BANK 00 BCF PORTB, LED MAIN: BSF PORTB, LED ;SET PB0 HIGH CALL DELAY BCF PORTB, LED ;SET PB1 LOW CALL DELAY GOTO MAIN DELAY: MOVLW 0xA0 MOVWF CNT2 D2: MOVLW 0xFA MOVWF CNT1 D1: MOVLW 0xFA MOVWF CNT0 D0: DECFSZ CNT0 GOTO D0 DECFSZ CNT1 GOTO D1 DECFSZ CNT2 GOTO D2 RETURN END
// index_catalog.cpp /** * Copyright (C) 2013-2014 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kIndex #include "mongo/platform/basic.h" #include "mongo/db/catalog/index_catalog.h" #include <vector> #include "mongo/bson/simple_bsonelement_comparator.h" #include "mongo/bson/simple_bsonobj_comparator.h" #include "mongo/db/audit.h" #include "mongo/db/background.h" #include "mongo/db/catalog/collection.h" #include "mongo/db/catalog/collection_catalog_entry.h" #include "mongo/db/catalog/database_catalog_entry.h" #include "mongo/db/catalog/index_create.h" #include "mongo/db/catalog/index_key_validate.h" #include "mongo/db/client.h" #include "mongo/db/clientcursor.h" #include "mongo/db/curop.h" #include "mongo/db/field_ref.h" #include "mongo/db/index/index_access_method.h" #include "mongo/db/index/index_descriptor.h" #include "mongo/db/index_legacy.h" #include "mongo/db/index_names.h" #include "mongo/db/jsobj.h" #include "mongo/db/keypattern.h" #include "mongo/db/matcher/expression.h" #include "mongo/db/matcher/extensions_callback_disallow_extensions.h" #include "mongo/db/operation_context.h" #include "mongo/db/ops/delete.h" #include "mongo/db/query/collation/collation_spec.h" #include "mongo/db/query/collation/collator_factory_interface.h" #include "mongo/db/query/internal_plans.h" #include "mongo/db/repl/replication_coordinator_global.h" #include "mongo/db/server_options.h" #include "mongo/db/service_context.h" #include "mongo/util/assert_util.h" #include "mongo/util/log.h" #include "mongo/util/mongoutils/str.h" #include "mongo/util/represent_as.h" namespace mongo { using std::unique_ptr; using std::endl; using std::string; using std::vector; using IndexVersion = IndexDescriptor::IndexVersion; static const int INDEX_CATALOG_INIT = 283711; static const int INDEX_CATALOG_UNINIT = 654321; const BSONObj IndexCatalog::_idObj = BSON("_id" << 1); // ------------- IndexCatalog::IndexCatalog(Collection* collection) : _magic(INDEX_CATALOG_UNINIT), _collection(collection), _maxNumIndexesAllowed(_collection->getCatalogEntry()->getMaxAllowedIndexes()) {} IndexCatalog::~IndexCatalog() { if (_magic != INDEX_CATALOG_UNINIT) { // only do this check if we haven't been initialized _checkMagic(); } _magic = 123456; } Status IndexCatalog::init(OperationContext* txn) { vector<string> indexNames; _collection->getCatalogEntry()->getAllIndexes(txn, &indexNames); for (size_t i = 0; i < indexNames.size(); i++) { const string& indexName = indexNames[i]; BSONObj spec = _collection->getCatalogEntry()->getIndexSpec(txn, indexName).getOwned(); if (!_collection->getCatalogEntry()->isIndexReady(txn, indexName)) { _unfinishedIndexes.push_back(spec); continue; } BSONObj keyPattern = spec.getObjectField("key"); IndexDescriptor* descriptor = new IndexDescriptor(_collection, _getAccessMethodName(txn, keyPattern), spec); const bool initFromDisk = true; IndexCatalogEntry* entry = _setupInMemoryStructures(txn, descriptor, initFromDisk); fassert(17340, entry->isReady(txn)); } if (_unfinishedIndexes.size()) { // if there are left over indexes, we don't let anyone add/drop indexes // until someone goes and fixes them log() << "found " << _unfinishedIndexes.size() << " index(es) that wasn't finished before shutdown"; } _magic = INDEX_CATALOG_INIT; return Status::OK(); } IndexCatalogEntry* IndexCatalog::_setupInMemoryStructures(OperationContext* txn, IndexDescriptor* descriptor, bool initFromDisk) { unique_ptr<IndexDescriptor> descriptorCleanup(descriptor); Status status = _isSpecOk(txn, descriptor->infoObj()); if (!status.isOK() && status != ErrorCodes::IndexAlreadyExists) { severe() << "Found an invalid index " << descriptor->infoObj() << " on the " << _collection->ns().ns() << " collection: " << redact(status); fassertFailedNoTrace(28782); } auto entry = stdx::make_unique<IndexCatalogEntry>(txn, _collection->ns().ns(), _collection->getCatalogEntry(), descriptorCleanup.release(), _collection->infoCache()); std::unique_ptr<IndexAccessMethod> accessMethod( _collection->_dbce->getIndex(txn, _collection->getCatalogEntry(), entry.get())); entry->init(std::move(accessMethod)); IndexCatalogEntry* save = entry.get(); _entries.add(entry.release()); if (!initFromDisk) { txn->recoveryUnit()->onRollback([this, txn, descriptor] { // Need to preserve indexName as descriptor no longer exists after remove(). const std::string indexName = descriptor->indexName(); _entries.remove(descriptor); _collection->infoCache()->droppedIndex(txn, indexName); }); } invariant(save == _entries.find(descriptor)); invariant(save == _entries.find(descriptor->indexName())); return save; } bool IndexCatalog::ok() const { return (_magic == INDEX_CATALOG_INIT); } void IndexCatalog::_checkMagic() const { if (ok()) { return; } log() << "IndexCatalog::_magic wrong, is : " << _magic; fassertFailed(17198); } Status IndexCatalog::checkUnfinished() const { if (_unfinishedIndexes.size() == 0) return Status::OK(); return Status(ErrorCodes::InternalError, str::stream() << "IndexCatalog has left over indexes that must be cleared" << " ns: " << _collection->ns().ns()); } bool IndexCatalog::_shouldOverridePlugin(OperationContext* txn, const BSONObj& keyPattern) const { string pluginName = IndexNames::findPluginName(keyPattern); bool known = IndexNames::isKnownName(pluginName); if (!_collection->_dbce->isOlderThan24(txn)) { // RulesFor24+ // This assert will be triggered when downgrading from a future version that // supports an index plugin unsupported by this version. uassert(17197, str::stream() << "Invalid index type '" << pluginName << "' " << "in index " << keyPattern, known); return false; } // RulesFor22 if (!known) { log() << "warning: can't find plugin [" << pluginName << "]"; return true; } if (!IndexNames::existedBefore24(pluginName)) { warning() << "Treating index " << keyPattern << " as ascending since " << "it was created before 2.4 and '" << pluginName << "' " << "was not a valid type at that time."; return true; } return false; } string IndexCatalog::_getAccessMethodName(OperationContext* txn, const BSONObj& keyPattern) const { if (_shouldOverridePlugin(txn, keyPattern)) { return ""; } return IndexNames::findPluginName(keyPattern); } // --------------------------- Status IndexCatalog::_upgradeDatabaseMinorVersionIfNeeded(OperationContext* txn, const string& newPluginName) { // first check if requested index requires pdfile minor version to be bumped if (IndexNames::existedBefore24(newPluginName)) { return Status::OK(); } DatabaseCatalogEntry* dbce = _collection->_dbce; if (!dbce->isOlderThan24(txn)) { return Status::OK(); // these checks have already been done } // Everything below is MMAPv1 specific since it was the only storage engine that existed // before 2.4. We look at all indexes in this database to make sure that none of them use // plugins that didn't exist before 2.4. If that holds, we mark the database as "2.4-clean" // which allows creation of indexes using new plugins. RecordStore* indexes = dbce->getRecordStore(dbce->name() + ".system.indexes"); auto cursor = indexes->getCursor(txn); while (auto record = cursor->next()) { const BSONObj index = record->data.releaseToBson(); const BSONObj key = index.getObjectField("key"); const string plugin = IndexNames::findPluginName(key); if (IndexNames::existedBefore24(plugin)) continue; const string errmsg = str::stream() << "Found pre-existing index " << index << " with invalid type '" << plugin << "'. " << "Disallowing creation of new index type '" << newPluginName << "'. See " << "http://dochub.mongodb.org/core/index-type-changes"; return Status(ErrorCodes::CannotCreateIndex, errmsg); } dbce->markIndexSafe24AndUp(txn); return Status::OK(); } StatusWith<BSONObj> IndexCatalog::prepareSpecForCreate(OperationContext* txn, const BSONObj& original) const { Status status = _isSpecOk(txn, original); if (!status.isOK()) return StatusWith<BSONObj>(status); auto fixed = _fixIndexSpec(txn, _collection, original); if (!fixed.isOK()) { return fixed; } // we double check with new index spec status = _isSpecOk(txn, fixed.getValue()); if (!status.isOK()) return StatusWith<BSONObj>(status); status = _doesSpecConflictWithExisting(txn, fixed.getValue()); if (!status.isOK()) return StatusWith<BSONObj>(status); return fixed; } StatusWith<BSONObj> IndexCatalog::createIndexOnEmptyCollection(OperationContext* txn, BSONObj spec) { invariant(txn->lockState()->isCollectionLockedForMode(_collection->ns().toString(), MODE_X)); invariant(_collection->numRecords(txn) == 0); _checkMagic(); Status status = checkUnfinished(); if (!status.isOK()) return status; StatusWith<BSONObj> statusWithSpec = prepareSpecForCreate(txn, spec); status = statusWithSpec.getStatus(); if (!status.isOK()) return status; spec = statusWithSpec.getValue(); string pluginName = IndexNames::findPluginName(spec["key"].Obj()); if (pluginName.size()) { Status s = _upgradeDatabaseMinorVersionIfNeeded(txn, pluginName); if (!s.isOK()) return s; } // now going to touch disk IndexBuildBlock indexBuildBlock(txn, _collection, spec); status = indexBuildBlock.init(); if (!status.isOK()) return status; // sanity checks, etc... IndexCatalogEntry* entry = indexBuildBlock.getEntry(); invariant(entry); IndexDescriptor* descriptor = entry->descriptor(); invariant(descriptor); invariant(entry == _entries.find(descriptor)); status = entry->accessMethod()->initializeAsEmpty(txn); if (!status.isOK()) return status; indexBuildBlock.success(); // sanity check invariant(_collection->getCatalogEntry()->isIndexReady(txn, descriptor->indexName())); return spec; } IndexCatalog::IndexBuildBlock::IndexBuildBlock(OperationContext* txn, Collection* collection, const BSONObj& spec) : _collection(collection), _catalog(collection->getIndexCatalog()), _ns(_catalog->_collection->ns().ns()), _spec(spec.getOwned()), _entry(NULL), _txn(txn) { invariant(collection); } Status IndexCatalog::IndexBuildBlock::init() { // need this first for names, etc... BSONObj keyPattern = _spec.getObjectField("key"); IndexDescriptor* descriptor = new IndexDescriptor(_collection, IndexNames::findPluginName(keyPattern), _spec); unique_ptr<IndexDescriptor> descriptorCleaner(descriptor); _indexName = descriptor->indexName(); _indexNamespace = descriptor->indexNamespace(); /// ---------- setup on disk structures ---------------- Status status = _collection->getCatalogEntry()->prepareForIndexBuild(_txn, descriptor); if (!status.isOK()) return status; /// ---------- setup in memory structures ---------------- const bool initFromDisk = false; _entry = _catalog->_setupInMemoryStructures(_txn, descriptorCleaner.release(), initFromDisk); // Register this index with the CollectionInfoCache to regenerate the cache. This way, updates // occurring while an index is being build in the background will be aware of whether or not // they need to modify any indexes. _collection->infoCache()->addedIndex(_txn, descriptor); return Status::OK(); } IndexCatalog::IndexBuildBlock::~IndexBuildBlock() { // Don't need to call fail() here, as rollback will clean everything up for us. } void IndexCatalog::IndexBuildBlock::fail() { fassert(17204, _catalog->_collection->ok()); // defensive IndexCatalogEntry* entry = _catalog->_entries.find(_indexName); invariant(entry == _entry); if (entry) { _catalog->_dropIndex(_txn, entry); } else { _catalog->_deleteIndexFromDisk(_txn, _indexName, _indexNamespace); } } void IndexCatalog::IndexBuildBlock::success() { Collection* collection = _catalog->_collection; fassert(17207, collection->ok()); NamespaceString ns(_indexNamespace); invariant(_txn->lockState()->isDbLockedForMode(ns.db(), MODE_X)); collection->getCatalogEntry()->indexBuildSuccess(_txn, _indexName); IndexDescriptor* desc = _catalog->findIndexByName(_txn, _indexName, true); fassert(17330, desc); IndexCatalogEntry* entry = _catalog->_entries.find(desc); fassert(17331, entry && entry == _entry); OperationContext* txn = _txn; LOG(2) << "marking index " << _indexName << " as ready in snapshot id " << txn->recoveryUnit()->getSnapshotId(); _txn->recoveryUnit()->onCommit([txn, entry, collection] { // Note: this runs after the WUOW commits but before we release our X lock on the // collection. This means that any snapshot created after this must include the full index, // and no one can try to read this index before we set the visibility. auto replCoord = repl::ReplicationCoordinator::get(txn); auto snapshotName = replCoord->reserveSnapshotName(txn); replCoord->forceSnapshotCreation(); // Ensures a newer snapshot gets created even if idle. entry->setMinimumVisibleSnapshot(snapshotName); // TODO remove this once SERVER-20439 is implemented. It is a stopgap solution for // SERVER-20260 to make sure that reads with majority readConcern level can see indexes that // are created with w:majority by making the readers block. collection->setMinimumVisibleSnapshot(snapshotName); }); entry->setIsReady(true); } namespace { // While technically recursive, only current possible with 2 levels. Status _checkValidFilterExpressions(MatchExpression* expression, int level = 0) { if (!expression) return Status::OK(); switch (expression->matchType()) { case MatchExpression::AND: if (level > 0) return Status(ErrorCodes::CannotCreateIndex, "$and only supported in partialFilterExpression at top level"); for (size_t i = 0; i < expression->numChildren(); i++) { Status status = _checkValidFilterExpressions(expression->getChild(i), level + 1); if (!status.isOK()) return status; } return Status::OK(); case MatchExpression::EQ: case MatchExpression::LT: case MatchExpression::LTE: case MatchExpression::GT: case MatchExpression::GTE: case MatchExpression::EXISTS: case MatchExpression::TYPE_OPERATOR: return Status::OK(); default: return Status(ErrorCodes::CannotCreateIndex, str::stream() << "unsupported expression in partial index: " << expression->toString()); } } } Status IndexCatalog::_isSpecOk(OperationContext* txn, const BSONObj& spec) const { const NamespaceString& nss = _collection->ns(); BSONElement vElt = spec["v"]; if (!vElt) { return {ErrorCodes::InternalError, str::stream() << "An internal operation failed to specify the 'v' field, which is a required " "property of an index specification: " << spec}; } if (!vElt.isNumber()) { return Status(ErrorCodes::CannotCreateIndex, str::stream() << "non-numeric value for \"v\" field: " << vElt); } auto vEltAsInt = representAs<int>(vElt.number()); if (!vEltAsInt) { return {ErrorCodes::CannotCreateIndex, str::stream() << "Index version must be representable as a 32-bit integer, but got " << vElt.toString(false, false)}; } auto indexVersion = static_cast<IndexVersion>(*vEltAsInt); if (indexVersion >= IndexVersion::kV2) { auto status = index_key_validate::validateIndexSpecFieldNames(spec); if (!status.isOK()) { return status; } } // SERVER-16893 Forbid use of v0 indexes with non-mmapv1 engines if (indexVersion == IndexVersion::kV0 && !txn->getServiceContext()->getGlobalStorageEngine()->isMmapV1()) { return Status(ErrorCodes::CannotCreateIndex, str::stream() << "use of v0 indexes is only allowed with the " << "mmapv1 storage engine"); } if (!IndexDescriptor::isIndexVersionSupported(indexVersion)) { return Status(ErrorCodes::CannotCreateIndex, str::stream() << "this version of mongod cannot build new indexes " << "of version number " << static_cast<int>(indexVersion)); } if (nss.isSystemDotIndexes()) return Status(ErrorCodes::CannotCreateIndex, "cannot have an index on the system.indexes collection"); if (nss.isOplog()) return Status(ErrorCodes::CannotCreateIndex, "cannot have an index on the oplog"); if (nss.coll() == "$freelist") { // this isn't really proper, but we never want it and its not an error per se return Status(ErrorCodes::IndexAlreadyExists, "cannot index freelist"); } const BSONElement specNamespace = spec["ns"]; if (specNamespace.type() != String) return Status(ErrorCodes::CannotCreateIndex, "the index spec is missing a \"ns\" string field"); if (nss.ns() != specNamespace.valueStringData()) return Status(ErrorCodes::CannotCreateIndex, str::stream() << "the \"ns\" field of the index spec '" << specNamespace.valueStringData() << "' does not match the collection name '" << nss.ns() << "'"); // logical name of the index const BSONElement nameElem = spec["name"]; if (nameElem.type() != String) return Status(ErrorCodes::CannotCreateIndex, "index name must be specified as a string"); const StringData name = nameElem.valueStringData(); if (name.find('\0') != std::string::npos) return Status(ErrorCodes::CannotCreateIndex, "index name cannot contain NUL bytes"); if (name.empty()) return Status(ErrorCodes::CannotCreateIndex, "index name cannot be empty"); const std::string indexNamespace = IndexDescriptor::makeIndexNamespace(nss.ns(), name); if (indexNamespace.length() > NamespaceString::MaxNsLen) return Status(ErrorCodes::CannotCreateIndex, str::stream() << "namespace name generated from index name \"" << indexNamespace << "\" is too long (127 byte max)"); const BSONObj key = spec.getObjectField("key"); const Status keyStatus = index_key_validate::validateKeyPattern(key, indexVersion); if (!keyStatus.isOK()) { return Status(ErrorCodes::CannotCreateIndex, str::stream() << "bad index key pattern " << key << ": " << keyStatus.reason()); } std::unique_ptr<CollatorInterface> collator; BSONElement collationElement = spec.getField("collation"); if (collationElement) { if (collationElement.type() != BSONType::Object) { return Status(ErrorCodes::CannotCreateIndex, "\"collation\" for an index must be a document"); } auto statusWithCollator = CollatorFactoryInterface::get(txn->getServiceContext()) ->makeFromBSON(collationElement.Obj()); if (!statusWithCollator.isOK()) { return statusWithCollator.getStatus(); } collator = std::move(statusWithCollator.getValue()); if (!collator) { return {ErrorCodes::InternalError, str::stream() << "An internal operation specified the collation " << CollationSpec::kSimpleSpec << " explicitly, which should instead be implied by omitting the " "'collation' field from the index specification"}; } if (static_cast<IndexVersion>(vElt.numberInt()) < IndexVersion::kV2) { return {ErrorCodes::CannotCreateIndex, str::stream() << "Index version " << vElt.fieldNameStringData() << "=" << vElt.numberInt() << " does not support the '" << collationElement.fieldNameStringData() << "' option"}; } string pluginName = IndexNames::findPluginName(key); if ((pluginName != IndexNames::BTREE) && (pluginName != IndexNames::GEO_2DSPHERE) && (pluginName != IndexNames::HASHED)) { return Status(ErrorCodes::CannotCreateIndex, str::stream() << "Index type '" << pluginName << "' does not support collation: " << collator->getSpec().toBSON()); } } const bool isSparse = spec["sparse"].trueValue(); // Ensure if there is a filter, its valid. BSONElement filterElement = spec.getField("partialFilterExpression"); if (filterElement) { if (isSparse) { return Status(ErrorCodes::CannotCreateIndex, "cannot mix \"partialFilterExpression\" and \"sparse\" options"); } if (filterElement.type() != Object) { return Status(ErrorCodes::CannotCreateIndex, "\"partialFilterExpression\" for an index must be a document"); } // The collator must outlive the constructed MatchExpression. StatusWithMatchExpression statusWithMatcher = MatchExpressionParser::parse( filterElement.Obj(), ExtensionsCallbackDisallowExtensions(), collator.get()); if (!statusWithMatcher.isOK()) { return statusWithMatcher.getStatus(); } const std::unique_ptr<MatchExpression> filterExpr = std::move(statusWithMatcher.getValue()); Status status = _checkValidFilterExpressions(filterExpr.get()); if (!status.isOK()) { return status; } } if (IndexDescriptor::isIdIndexPattern(key)) { BSONElement uniqueElt = spec["unique"]; if (uniqueElt && !uniqueElt.trueValue()) { return Status(ErrorCodes::CannotCreateIndex, "_id index cannot be non-unique"); } if (filterElement) { return Status(ErrorCodes::CannotCreateIndex, "_id index cannot be a partial index"); } if (isSparse) { return Status(ErrorCodes::CannotCreateIndex, "_id index cannot be sparse"); } if (collationElement && !CollatorInterface::collatorsMatch(collator.get(), _collection->getDefaultCollator())) { return Status(ErrorCodes::CannotCreateIndex, "_id index must have the collection default collation"); } } else { // for non _id indexes, we check to see if replication has turned off all indexes // we _always_ created _id index if (!repl::getGlobalReplicationCoordinator()->buildsIndexes()) { // this is not exactly the right error code, but I think will make the most sense return Status(ErrorCodes::IndexAlreadyExists, "no indexes per repl"); } } // --- only storage engine checks allowed below this ---- BSONElement storageEngineElement = spec.getField("storageEngine"); if (storageEngineElement.eoo()) { return Status::OK(); } if (storageEngineElement.type() != mongo::Object) { return Status(ErrorCodes::CannotCreateIndex, "\"storageEngine\" options must be a document if present"); } BSONObj storageEngineOptions = storageEngineElement.Obj(); if (storageEngineOptions.isEmpty()) { return Status(ErrorCodes::CannotCreateIndex, "Empty \"storageEngine\" options are invalid. " "Please remove the field or include valid options."); } Status storageEngineStatus = validateStorageOptions(storageEngineOptions, stdx::bind(&StorageEngine::Factory::validateIndexStorageOptions, stdx::placeholders::_1, stdx::placeholders::_2)); if (!storageEngineStatus.isOK()) { return storageEngineStatus; } return Status::OK(); } Status IndexCatalog::_doesSpecConflictWithExisting(OperationContext* txn, const BSONObj& spec) const { const char* name = spec.getStringField("name"); invariant(name[0]); const BSONObj key = spec.getObjectField("key"); const BSONObj collation = spec.getObjectField("collation"); { // Check both existing and in-progress indexes (2nd param = true) const IndexDescriptor* desc = findIndexByName(txn, name, true); if (desc) { // index already exists with same name if (SimpleBSONObjComparator::kInstance.evaluate(desc->keyPattern() == key) && SimpleBSONObjComparator::kInstance.evaluate( desc->infoObj().getObjectField("collation") != collation)) { // key patterns are equal but collations differ. return Status(ErrorCodes::IndexOptionsConflict, str::stream() << "An index with the same key pattern, but a different " << "collation already exists with the same name. Try again with " << "a unique name. " << "Existing index: " << desc->infoObj() << " Requested index: " << spec); } if (SimpleBSONObjComparator::kInstance.evaluate(desc->keyPattern() != key) || SimpleBSONObjComparator::kInstance.evaluate( desc->infoObj().getObjectField("collation") != collation)) { return Status(ErrorCodes::IndexKeySpecsConflict, str::stream() << "Index must have unique name." << "The existing index: " << desc->infoObj() << " has the same name as the requested index: " << spec); } IndexDescriptor temp(_collection, _getAccessMethodName(txn, key), spec); if (!desc->areIndexOptionsEquivalent(&temp)) return Status(ErrorCodes::IndexOptionsConflict, str::stream() << "Index with name: " << name << " already exists with different options"); // Index already exists with the same options, so no need to build a new // one (not an error). Most likely requested by a client using ensureIndex. return Status(ErrorCodes::IndexAlreadyExists, str::stream() << "Identical index already exists: " << name); } } { // Check both existing and in-progress indexes. const bool findInProgressIndexes = true; const IndexDescriptor* desc = findIndexByKeyPatternAndCollationSpec(txn, key, collation, findInProgressIndexes); if (desc) { LOG(2) << "index already exists with diff name " << name << " pattern: " << key << " collation: " << collation; IndexDescriptor temp(_collection, _getAccessMethodName(txn, key), spec); if (!desc->areIndexOptionsEquivalent(&temp)) return Status(ErrorCodes::IndexOptionsConflict, str::stream() << "Index: " << spec << " already exists with different options: " << desc->infoObj()); return Status(ErrorCodes::IndexAlreadyExists, str::stream() << "index already exists with different name: " << name); } } if (numIndexesTotal(txn) >= _maxNumIndexesAllowed) { string s = str::stream() << "add index fails, too many indexes for " << _collection->ns().ns() << " key:" << key; log() << s; return Status(ErrorCodes::CannotCreateIndex, s); } // Refuse to build text index if another text index exists or is in progress. // Collections should only have one text index. string pluginName = IndexNames::findPluginName(key); if (pluginName == IndexNames::TEXT) { vector<IndexDescriptor*> textIndexes; const bool includeUnfinishedIndexes = true; findIndexByType(txn, IndexNames::TEXT, textIndexes, includeUnfinishedIndexes); if (textIndexes.size() > 0) { return Status(ErrorCodes::CannotCreateIndex, str::stream() << "only one text index per collection allowed, " << "found existing text index \"" << textIndexes[0]->indexName() << "\""); } } return Status::OK(); } BSONObj IndexCatalog::getDefaultIdIndexSpec( ServerGlobalParams::FeatureCompatibility::Version featureCompatibilityVersion) const { dassert(_idObj["_id"].type() == NumberInt); const auto indexVersion = IndexDescriptor::getDefaultIndexVersion(featureCompatibilityVersion); BSONObjBuilder b; b.append("v", static_cast<int>(indexVersion)); b.append("name", "_id_"); b.append("ns", _collection->ns().ns()); b.append("key", _idObj); if (_collection->getDefaultCollator() && indexVersion >= IndexVersion::kV2) { // Creating an index with the "collation" option requires a v=2 index. b.append("collation", _collection->getDefaultCollator()->getSpec().toBSON()); } return b.obj(); } Status IndexCatalog::dropAllIndexes(OperationContext* txn, bool includingIdIndex) { invariant(txn->lockState()->isCollectionLockedForMode(_collection->ns().toString(), MODE_X)); BackgroundOperation::assertNoBgOpInProgForNs(_collection->ns().ns()); // there may be pointers pointing at keys in the btree(s). kill them. // TODO: can this can only clear cursors on this index? _collection->getCursorManager()->invalidateAll(false, "all indexes on collection dropped"); // make sure nothing in progress massert(17348, "cannot dropAllIndexes when index builds in progress", numIndexesTotal(txn) == numIndexesReady(txn)); bool haveIdIndex = false; vector<string> indexNamesToDrop; { int seen = 0; IndexIterator ii = getIndexIterator(txn, true); while (ii.more()) { seen++; IndexDescriptor* desc = ii.next(); if (desc->isIdIndex() && includingIdIndex == false) { haveIdIndex = true; continue; } indexNamesToDrop.push_back(desc->indexName()); } invariant(seen == numIndexesTotal(txn)); } for (size_t i = 0; i < indexNamesToDrop.size(); i++) { string indexName = indexNamesToDrop[i]; IndexDescriptor* desc = findIndexByName(txn, indexName, true); invariant(desc); LOG(1) << "\t dropAllIndexes dropping: " << desc->toString(); IndexCatalogEntry* entry = _entries.find(desc); invariant(entry); _dropIndex(txn, entry); } // verify state is sane post cleaning long long numIndexesInCollectionCatalogEntry = _collection->getCatalogEntry()->getTotalIndexCount(txn); if (haveIdIndex) { fassert(17324, numIndexesTotal(txn) == 1); fassert(17325, numIndexesReady(txn) == 1); fassert(17326, numIndexesInCollectionCatalogEntry == 1); fassert(17336, _entries.size() == 1); } else { if (numIndexesTotal(txn) || numIndexesInCollectionCatalogEntry || _entries.size()) { error() << "About to fassert - " << " numIndexesTotal(): " << numIndexesTotal(txn) << " numSystemIndexesEntries: " << numIndexesInCollectionCatalogEntry << " _entries.size(): " << _entries.size() << " indexNamesToDrop: " << indexNamesToDrop.size() << " haveIdIndex: " << haveIdIndex; } fassert(17327, numIndexesTotal(txn) == 0); fassert(17328, numIndexesInCollectionCatalogEntry == 0); fassert(17337, _entries.size() == 0); } return Status::OK(); } Status IndexCatalog::dropIndex(OperationContext* txn, IndexDescriptor* desc) { invariant(txn->lockState()->isCollectionLockedForMode(_collection->ns().toString(), MODE_X)); IndexCatalogEntry* entry = _entries.find(desc); if (!entry) return Status(ErrorCodes::InternalError, "cannot find index to delete"); if (!entry->isReady(txn)) return Status(ErrorCodes::InternalError, "cannot delete not ready index"); BackgroundOperation::assertNoBgOpInProgForNs(_collection->ns().ns()); return _dropIndex(txn, entry); } namespace { class IndexRemoveChange final : public RecoveryUnit::Change { public: IndexRemoveChange(OperationContext* txn, Collection* collection, IndexCatalogEntryContainer* entries, IndexCatalogEntry* entry) : _txn(txn), _collection(collection), _entries(entries), _entry(entry) {} void commit() final { // Ban reading from this collection on committed reads on snapshots before now. auto replCoord = repl::ReplicationCoordinator::get(_txn); auto snapshotName = replCoord->reserveSnapshotName(_txn); replCoord->forceSnapshotCreation(); // Ensures a newer snapshot gets created even if idle. _collection->setMinimumVisibleSnapshot(snapshotName); delete _entry; } void rollback() final { _entries->add(_entry); _collection->infoCache()->addedIndex(_txn, _entry->descriptor()); } private: OperationContext* _txn; Collection* _collection; IndexCatalogEntryContainer* _entries; IndexCatalogEntry* _entry; }; } // namespace Status IndexCatalog::_dropIndex(OperationContext* txn, IndexCatalogEntry* entry) { /** * IndexState in order * <db>.system.indexes * NamespaceDetails * <db>.system.ns */ // ----- SANITY CHECKS ------------- if (!entry) return Status(ErrorCodes::BadValue, "IndexCatalog::_dropIndex passed NULL"); _checkMagic(); Status status = checkUnfinished(); if (!status.isOK()) return status; // Pulling indexName/indexNamespace out as they are needed post descriptor release. string indexName = entry->descriptor()->indexName(); string indexNamespace = entry->descriptor()->indexNamespace(); // If any cursors could be using this index, invalidate them. Note that we do not use indexes // until they are ready, so we do not need to invalidate anything if the index fails while it is // being built. // TODO only kill cursors that are actually using the index rather than everything on this // collection. if (entry->isReady(txn)) { _collection->getCursorManager()->invalidateAll( false, str::stream() << "index '" << indexName << "' dropped"); } // --------- START REAL WORK ---------- audit::logDropIndex(&cc(), indexName, _collection->ns().ns()); invariant(_entries.release(entry->descriptor()) == entry); txn->recoveryUnit()->registerChange(new IndexRemoveChange(txn, _collection, &_entries, entry)); entry = NULL; _deleteIndexFromDisk(txn, indexName, indexNamespace); _checkMagic(); _collection->infoCache()->droppedIndex(txn, indexName); return Status::OK(); } void IndexCatalog::_deleteIndexFromDisk(OperationContext* txn, const string& indexName, const string& indexNamespace) { Status status = _collection->getCatalogEntry()->removeIndex(txn, indexName); if (status.code() == ErrorCodes::NamespaceNotFound) { // this is ok, as we may be partially through index creation } else if (!status.isOK()) { warning() << "couldn't drop index " << indexName << " on collection: " << _collection->ns() << " because of " << redact(status); } } vector<BSONObj> IndexCatalog::getAndClearUnfinishedIndexes(OperationContext* txn) { vector<BSONObj> toReturn = _unfinishedIndexes; _unfinishedIndexes.clear(); for (size_t i = 0; i < toReturn.size(); i++) { BSONObj spec = toReturn[i]; BSONObj keyPattern = spec.getObjectField("key"); IndexDescriptor desc(_collection, _getAccessMethodName(txn, keyPattern), spec); _deleteIndexFromDisk(txn, desc.indexName(), desc.indexNamespace()); } return toReturn; } bool IndexCatalog::isMultikey(OperationContext* txn, const IndexDescriptor* idx) { IndexCatalogEntry* entry = _entries.find(idx); invariant(entry); return entry->isMultikey(); } MultikeyPaths IndexCatalog::getMultikeyPaths(OperationContext* txn, const IndexDescriptor* idx) { IndexCatalogEntry* entry = _entries.find(idx); invariant(entry); return entry->getMultikeyPaths(txn); } // --------------------------- bool IndexCatalog::haveAnyIndexes() const { return _entries.size() != 0; } int IndexCatalog::numIndexesTotal(OperationContext* txn) const { int count = _entries.size() + _unfinishedIndexes.size(); dassert(_collection->getCatalogEntry()->getTotalIndexCount(txn) == count); return count; } int IndexCatalog::numIndexesReady(OperationContext* txn) const { int count = 0; IndexIterator ii = getIndexIterator(txn, /*includeUnfinished*/ false); while (ii.more()) { ii.next(); count++; } dassert(_collection->getCatalogEntry()->getCompletedIndexCount(txn) == count); return count; } bool IndexCatalog::haveIdIndex(OperationContext* txn) const { return findIdIndex(txn) != NULL; } IndexCatalog::IndexIterator::IndexIterator(OperationContext* txn, const IndexCatalog* cat, bool includeUnfinishedIndexes) : _includeUnfinishedIndexes(includeUnfinishedIndexes), _txn(txn), _catalog(cat), _iterator(cat->_entries.begin()), _start(true), _prev(NULL), _next(NULL) {} bool IndexCatalog::IndexIterator::more() { if (_start) { _advance(); _start = false; } return _next != NULL; } IndexDescriptor* IndexCatalog::IndexIterator::next() { if (!more()) return NULL; _prev = _next; _advance(); return _prev->descriptor(); } IndexAccessMethod* IndexCatalog::IndexIterator::accessMethod(const IndexDescriptor* desc) { invariant(desc == _prev->descriptor()); return _prev->accessMethod(); } IndexCatalogEntry* IndexCatalog::IndexIterator::catalogEntry(const IndexDescriptor* desc) { invariant(desc == _prev->descriptor()); return _prev; } void IndexCatalog::IndexIterator::_advance() { _next = NULL; while (_iterator != _catalog->_entries.end()) { IndexCatalogEntry* entry = *_iterator; ++_iterator; if (!_includeUnfinishedIndexes) { if (auto minSnapshot = entry->getMinimumVisibleSnapshot()) { if (auto mySnapshot = _txn->recoveryUnit()->getMajorityCommittedSnapshot()) { if (mySnapshot < minSnapshot) { // This index isn't finished in my snapshot. continue; } } } if (!entry->isReady(_txn)) continue; } _next = entry; return; } } IndexDescriptor* IndexCatalog::findIdIndex(OperationContext* txn) const { IndexIterator ii = getIndexIterator(txn, false); while (ii.more()) { IndexDescriptor* desc = ii.next(); if (desc->isIdIndex()) return desc; } return NULL; } IndexDescriptor* IndexCatalog::findIndexByName(OperationContext* txn, StringData name, bool includeUnfinishedIndexes) const { IndexIterator ii = getIndexIterator(txn, includeUnfinishedIndexes); while (ii.more()) { IndexDescriptor* desc = ii.next(); if (desc->indexName() == name) return desc; } return NULL; } IndexDescriptor* IndexCatalog::findIndexByKeyPatternAndCollationSpec( OperationContext* txn, const BSONObj& key, const BSONObj& collationSpec, bool includeUnfinishedIndexes) const { IndexIterator ii = getIndexIterator(txn, includeUnfinishedIndexes); while (ii.more()) { IndexDescriptor* desc = ii.next(); if (SimpleBSONObjComparator::kInstance.evaluate(desc->keyPattern() == key) && SimpleBSONObjComparator::kInstance.evaluate( desc->infoObj().getObjectField("collation") == collationSpec)) { return desc; } } return NULL; } void IndexCatalog::findIndexesByKeyPattern(OperationContext* txn, const BSONObj& key, bool includeUnfinishedIndexes, std::vector<IndexDescriptor*>* matches) const { invariant(matches); IndexIterator ii = getIndexIterator(txn, includeUnfinishedIndexes); while (ii.more()) { IndexDescriptor* desc = ii.next(); if (SimpleBSONObjComparator::kInstance.evaluate(desc->keyPattern() == key)) { matches->push_back(desc); } } } IndexDescriptor* IndexCatalog::findShardKeyPrefixedIndex(OperationContext* txn, const BSONObj& shardKey, bool requireSingleKey) const { IndexDescriptor* best = NULL; IndexIterator ii = getIndexIterator(txn, false); while (ii.more()) { IndexDescriptor* desc = ii.next(); bool hasSimpleCollation = desc->infoObj().getObjectField("collation").isEmpty(); if (desc->isPartial()) continue; if (!shardKey.isPrefixOf(desc->keyPattern(), SimpleBSONElementComparator::kInstance)) continue; if (!desc->isMultikey(txn) && hasSimpleCollation) return desc; if (!requireSingleKey && hasSimpleCollation) best = desc; } return best; } void IndexCatalog::findIndexByType(OperationContext* txn, const string& type, vector<IndexDescriptor*>& matches, bool includeUnfinishedIndexes) const { IndexIterator ii = getIndexIterator(txn, includeUnfinishedIndexes); while (ii.more()) { IndexDescriptor* desc = ii.next(); if (IndexNames::findPluginName(desc->keyPattern()) == type) { matches.push_back(desc); } } } IndexAccessMethod* IndexCatalog::getIndex(const IndexDescriptor* desc) { IndexCatalogEntry* entry = _entries.find(desc); massert(17334, "cannot find index entry", entry); return entry->accessMethod(); } const IndexAccessMethod* IndexCatalog::getIndex(const IndexDescriptor* desc) const { return getEntry(desc)->accessMethod(); } const IndexCatalogEntry* IndexCatalog::getEntry(const IndexDescriptor* desc) const { const IndexCatalogEntry* entry = _entries.find(desc); massert(17357, "cannot find index entry", entry); return entry; } const IndexDescriptor* IndexCatalog::refreshEntry(OperationContext* txn, const IndexDescriptor* oldDesc) { invariant(txn->lockState()->isCollectionLockedForMode(_collection->ns().ns(), MODE_X)); invariant(!BackgroundOperation::inProgForNs(_collection->ns())); const std::string indexName = oldDesc->indexName(); invariant(_collection->getCatalogEntry()->isIndexReady(txn, indexName)); // Notify other users of the IndexCatalog that we're about to invalidate 'oldDesc'. const bool collectionGoingAway = false; _collection->getCursorManager()->invalidateAll( collectionGoingAway, str::stream() << "definition of index '" << indexName << "' changed"); // Delete the IndexCatalogEntry that owns this descriptor. After deletion, 'oldDesc' is // invalid and should not be dereferenced. IndexCatalogEntry* oldEntry = _entries.release(oldDesc); txn->recoveryUnit()->registerChange( new IndexRemoveChange(txn, _collection, &_entries, oldEntry)); // Ask the CollectionCatalogEntry for the new index spec. BSONObj spec = _collection->getCatalogEntry()->getIndexSpec(txn, indexName).getOwned(); BSONObj keyPattern = spec.getObjectField("key"); // Re-register this index in the index catalog with the new spec. IndexDescriptor* newDesc = new IndexDescriptor(_collection, _getAccessMethodName(txn, keyPattern), spec); const bool initFromDisk = false; const IndexCatalogEntry* newEntry = _setupInMemoryStructures(txn, newDesc, initFromDisk); invariant(newEntry->isReady(txn)); // Return the new descriptor. return newEntry->descriptor(); } // --------------------------- Status IndexCatalog::_indexFilteredRecords(OperationContext* txn, IndexCatalogEntry* index, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut) { InsertDeleteOptions options; prepareInsertDeleteOptions(txn, index->descriptor(), &options); for (auto bsonRecord : bsonRecords) { int64_t inserted; invariant(bsonRecord.id != RecordId()); Status status = index->accessMethod()->insert( txn, *bsonRecord.docPtr, bsonRecord.id, options, &inserted); if (!status.isOK()) return status; if (keysInsertedOut) { *keysInsertedOut += inserted; } } return Status::OK(); } Status IndexCatalog::_indexRecords(OperationContext* txn, IndexCatalogEntry* index, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut) { const MatchExpression* filter = index->getFilterExpression(); if (!filter) return _indexFilteredRecords(txn, index, bsonRecords, keysInsertedOut); std::vector<BsonRecord> filteredBsonRecords; for (auto bsonRecord : bsonRecords) { if (filter->matchesBSON(*(bsonRecord.docPtr))) filteredBsonRecords.push_back(bsonRecord); } return _indexFilteredRecords(txn, index, filteredBsonRecords, keysInsertedOut); } Status IndexCatalog::_unindexRecord(OperationContext* txn, IndexCatalogEntry* index, const BSONObj& obj, const RecordId& loc, bool logIfError, int64_t* keysDeletedOut) { InsertDeleteOptions options; prepareInsertDeleteOptions(txn, index->descriptor(), &options); options.logIfError = logIfError; // For unindex operations, dupsAllowed=false really means that it is safe to delete anything // that matches the key, without checking the RecordID, since dups are impossible. We need // to disable this behavior for in-progress indexes. See SERVER-17487 for more details. options.dupsAllowed = options.dupsAllowed || !index->isReady(txn); int64_t removed; Status status = index->accessMethod()->remove(txn, obj, loc, options, &removed); if (!status.isOK()) { log() << "Couldn't unindex record " << redact(obj) << " from collection " << _collection->ns() << ". Status: " << redact(status); } if (keysDeletedOut) { *keysDeletedOut += removed; } return Status::OK(); } Status IndexCatalog::indexRecords(OperationContext* txn, const std::vector<BsonRecord>& bsonRecords, int64_t* keysInsertedOut) { if (keysInsertedOut) { *keysInsertedOut = 0; } for (IndexCatalogEntryContainer::const_iterator i = _entries.begin(); i != _entries.end(); ++i) { Status s = _indexRecords(txn, *i, bsonRecords, keysInsertedOut); if (!s.isOK()) return s; } return Status::OK(); } void IndexCatalog::unindexRecord(OperationContext* txn, const BSONObj& obj, const RecordId& loc, bool noWarn, int64_t* keysDeletedOut) { if (keysDeletedOut) { *keysDeletedOut = 0; } for (IndexCatalogEntryContainer::const_iterator i = _entries.begin(); i != _entries.end(); ++i) { IndexCatalogEntry* entry = *i; // If it's a background index, we DO NOT want to log anything. bool logIfError = entry->isReady(txn) ? !noWarn : false; _unindexRecord(txn, entry, obj, loc, logIfError, keysDeletedOut); } } BSONObj IndexCatalog::fixIndexKey(const BSONObj& key) { if (IndexDescriptor::isIdIndexPattern(key)) { return _idObj; } if (key["_id"].type() == Bool && key.nFields() == 1) { return _idObj; } return key; } void IndexCatalog::prepareInsertDeleteOptions(OperationContext* txn, const IndexDescriptor* desc, InsertDeleteOptions* options) { auto replCoord = repl::ReplicationCoordinator::get(txn); if (replCoord->shouldRelaxIndexConstraints(NamespaceString(desc->parentNS()))) { options->getKeysMode = IndexAccessMethod::GetKeysMode::kRelaxConstraints; } else { options->getKeysMode = IndexAccessMethod::GetKeysMode::kEnforceConstraints; } // Don't allow dups for Id key. Allow dups for non-unique keys or when constraints relaxed. if (KeyPattern::isIdKeyPattern(desc->keyPattern())) { options->dupsAllowed = false; } else { options->dupsAllowed = !desc->unique() || options->getKeysMode == IndexAccessMethod::GetKeysMode::kRelaxConstraints; } } StatusWith<BSONObj> IndexCatalog::_fixIndexSpec(OperationContext* txn, Collection* collection, const BSONObj& spec) { auto statusWithSpec = IndexLegacy::adjustIndexSpecObject(spec); if (!statusWithSpec.isOK()) { return statusWithSpec; } BSONObj o = statusWithSpec.getValue(); BSONObjBuilder b; // We've already verified in IndexCatalog::_isSpecOk() that the index version is present and // that it is representable as a 32-bit integer. auto vElt = o["v"]; invariant(vElt); b.append("v", vElt.numberInt()); if (o["unique"].trueValue()) b.appendBool("unique", true); // normalize to bool true in case was int 1 or something... BSONObj key = fixIndexKey(o["key"].Obj()); b.append("key", key); string name = o["name"].String(); if (IndexDescriptor::isIdIndexPattern(key)) { name = "_id_"; } b.append("name", name); { BSONObjIterator i(o); while (i.more()) { BSONElement e = i.next(); string s = e.fieldName(); if (s == "_id") { // skip } else if (s == "dropDups") { // dropDups is silently ignored and removed from the spec as of SERVER-14710. } else if (s == "v" || s == "unique" || s == "key" || s == "name") { // covered above } else { b.append(e); } } } return b.obj(); } }
/* * Copyright (C) 2008 The Android Open Source Project * * 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. */ /* * dalvik.system.Zygote */ #include "Dalvik.h" #include "native/InternalNativePriv.h" #include <selinux/android.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <grp.h> #include <errno.h> #include <paths.h> #include <fcntl.h> #include <unistd.h> #include <sys/personality.h> #include <sys/stat.h> #include <sys/mount.h> #include <linux/fs.h> #include <cutils/fs.h> #include <cutils/sched_policy.h> #include <cutils/multiuser.h> #include <sched.h> #include <sys/utsname.h> #include <sys/capability.h> #if defined(HAVE_PRCTL) # include <sys/prctl.h> #endif #define ZYGOTE_LOG_TAG "Zygote" /* must match values in dalvik.system.Zygote */ enum { DEBUG_ENABLE_DEBUGGER = 1, DEBUG_ENABLE_CHECKJNI = 1 << 1, DEBUG_ENABLE_ASSERT = 1 << 2, DEBUG_ENABLE_SAFEMODE = 1 << 3, DEBUG_ENABLE_JNI_LOGGING = 1 << 4, }; /* must match values in dalvik.system.Zygote */ enum { MOUNT_EXTERNAL_NONE = 0, MOUNT_EXTERNAL_SINGLEUSER = 1, MOUNT_EXTERNAL_MULTIUSER = 2, MOUNT_EXTERNAL_MULTIUSER_ALL = 3, }; /* * This signal handler is for zygote mode, since the zygote * must reap its children */ static void sigchldHandler(int s) { pid_t pid; int status; while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { /* Log process-death status that we care about. In general it is not safe to call ALOG(...) from a signal handler because of possible reentrancy. However, we know a priori that the current implementation of ALOG() is safe to call from a SIGCHLD handler in the zygote process. If the ALOG() implementation changes its locking strategy or its use of syscalls within the lazy-init critical section, its use here may become unsafe. */ if (WIFEXITED(status)) { if (WEXITSTATUS(status)) { ALOG(LOG_DEBUG, ZYGOTE_LOG_TAG, "Process %d exited cleanly (%d)", (int) pid, WEXITSTATUS(status)); } else { IF_ALOGV(/*should use ZYGOTE_LOG_TAG*/) { ALOG(LOG_VERBOSE, ZYGOTE_LOG_TAG, "Process %d exited cleanly (%d)", (int) pid, WEXITSTATUS(status)); } } } else if (WIFSIGNALED(status)) { if (WTERMSIG(status) != SIGKILL) { ALOG(LOG_DEBUG, ZYGOTE_LOG_TAG, "Process %d terminated by signal (%d)", (int) pid, WTERMSIG(status)); } else { IF_ALOGV(/*should use ZYGOTE_LOG_TAG*/) { ALOG(LOG_VERBOSE, ZYGOTE_LOG_TAG, "Process %d terminated by signal (%d)", (int) pid, WTERMSIG(status)); } } #ifdef WCOREDUMP if (WCOREDUMP(status)) { ALOG(LOG_INFO, ZYGOTE_LOG_TAG, "Process %d dumped core", (int) pid); } #endif /* ifdef WCOREDUMP */ } /* * If the just-crashed process is the system_server, bring down zygote * so that it is restarted by init and system server will be restarted * from there. */ if (pid == gDvm.systemServerPid) { ALOG(LOG_INFO, ZYGOTE_LOG_TAG, "Exit zygote because system server (%d) has terminated", (int) pid); kill(getpid(), SIGKILL); } } if (pid < 0) { ALOG(LOG_WARN, ZYGOTE_LOG_TAG, "Zygote SIGCHLD error in waitpid: %s",strerror(errno)); } } /* * configure sigchld handler for the zygote process * This is configured very late, because earlier in the dalvik lifecycle * we can fork() and exec() for the verifier/optimizer, and we * want to waitpid() for those rather than have them be harvested immediately. * * This ends up being called repeatedly before each fork(), but there's * no real harm in that. */ static void setSignalHandler() { int err; struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = sigchldHandler; err = sigaction (SIGCHLD, &sa, NULL); if (err < 0) { ALOGW("Error setting SIGCHLD handler: %s", strerror(errno)); } } /* * Set the SIGCHLD handler back to default behavior in zygote children */ static void unsetSignalHandler() { int err; struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_DFL; err = sigaction (SIGCHLD, &sa, NULL); if (err < 0) { ALOGW("Error unsetting SIGCHLD handler: %s", strerror(errno)); } } /* * Calls POSIX setgroups() using the int[] object as an argument. * A NULL argument is tolerated. */ static int setgroupsIntarray(ArrayObject* gidArray) { gid_t *gids; u4 i; s4 *contents; if (gidArray == NULL) { return 0; } /* just in case gid_t and u4 are different... */ gids = (gid_t *)alloca(sizeof(gid_t) * gidArray->length); contents = (s4 *)(void *)gidArray->contents; for (i = 0 ; i < gidArray->length ; i++) { gids[i] = (gid_t) contents[i]; } return setgroups((size_t) gidArray->length, gids); } /* * Sets the resource limits via setrlimit(2) for the values in the * two-dimensional array of integers that's passed in. The second dimension * contains a tuple of length 3: (resource, rlim_cur, rlim_max). NULL is * treated as an empty array. * * -1 is returned on error. */ static int setrlimitsFromArray(ArrayObject* rlimits) { u4 i; struct rlimit rlim; if (rlimits == NULL) { return 0; } memset (&rlim, 0, sizeof(rlim)); ArrayObject** tuples = (ArrayObject **)(void *)rlimits->contents; for (i = 0; i < rlimits->length; i++) { ArrayObject * rlimit_tuple = tuples[i]; s4* contents = (s4 *)(void *)rlimit_tuple->contents; int err; if (rlimit_tuple->length != 3) { ALOGE("rlimits array must have a second dimension of size 3"); return -1; } rlim.rlim_cur = contents[1]; rlim.rlim_max = contents[2]; err = setrlimit(contents[0], &rlim); if (err < 0) { return -1; } } return 0; } /* * Create a private mount namespace and bind mount appropriate emulated * storage for the given user. */ static int mountEmulatedStorage(uid_t uid, u4 mountMode) { // See storage config details at http://source.android.com/tech/storage/ userid_t userid = multiuser_get_user_id(uid); // Create a second private mount namespace for our process if (unshare(CLONE_NEWNS) == -1) { ALOGE("Failed to unshare(): %s", strerror(errno)); return -1; } // Create bind mounts to expose external storage if (mountMode == MOUNT_EXTERNAL_MULTIUSER || mountMode == MOUNT_EXTERNAL_MULTIUSER_ALL) { // These paths must already be created by init.rc const char* source = getenv("EMULATED_STORAGE_SOURCE"); const char* target = getenv("EMULATED_STORAGE_TARGET"); const char* legacy = getenv("EXTERNAL_STORAGE"); if (source == NULL || target == NULL || legacy == NULL) { ALOGE("Storage environment undefined; unable to provide external storage"); return -1; } // Prepare source paths char source_user[PATH_MAX]; char target_user[PATH_MAX]; // /mnt/shell/emulated/0 snprintf(source_user, PATH_MAX, "%s/%d", source, userid); // /storage/emulated/0 snprintf(target_user, PATH_MAX, "%s/%d", target, userid); if (fs_prepare_dir(source_user, 0000, 0, 0) == -1 || fs_prepare_dir(target_user, 0000, 0, 0) == -1) { return -1; } if (mountMode == MOUNT_EXTERNAL_MULTIUSER_ALL) { // Mount entire external storage tree for all users if (mount(source, target, NULL, MS_BIND, NULL) == -1) { ALOGE("Failed to mount %s to %s: %s", source, target, strerror(errno)); return -1; } } else { // Only mount user-specific external storage if (mount(source_user, target_user, NULL, MS_BIND, NULL) == -1) { ALOGE("Failed to mount %s to %s: %s", source_user, target_user, strerror(errno)); return -1; } } if (fs_prepare_dir(legacy, 0000, 0, 0) == -1) { return -1; } // Finally, mount user-specific path into place for legacy users if (mount(target_user, legacy, NULL, MS_BIND | MS_REC, NULL) == -1) { ALOGE("Failed to mount %s to %s: %s", target_user, legacy, strerror(errno)); return -1; } } else { ALOGE("Mount mode %d unsupported", mountMode); return -1; } return 0; } /* native public static int fork(); */ static void Dalvik_dalvik_system_Zygote_fork(const u4* args, JValue* pResult) { pid_t pid; if (!gDvm.zygote) { dvmThrowIllegalStateException( "VM instance not started with -Xzygote"); RETURN_VOID(); } if (!dvmGcPreZygoteFork()) { ALOGE("pre-fork heap failed"); dvmAbort(); } setSignalHandler(); dvmDumpLoaderStats("zygote"); pid = fork(); #ifdef HAVE_ANDROID_OS if (pid == 0) { /* child process */ extern int gMallocLeakZygoteChild; gMallocLeakZygoteChild = 1; } #endif RETURN_INT(pid); } /* * Enable/disable debug features requested by the caller. * * debugger * If set, enable debugging; if not set, disable debugging. This is * easy to handle, because the JDWP thread isn't started until we call * dvmInitAfterZygote(). * checkjni * If set, make sure "check JNI" is enabled. * assert * If set, make sure assertions are enabled. This gets fairly weird, * because it affects the result of a method called by class initializers, * and hence can't affect pre-loaded/initialized classes. * safemode * If set, operates the VM in the safe mode. The definition of "safe mode" is * implementation dependent and currently only the JIT compiler is disabled. * This is easy to handle because the compiler thread and associated resources * are not requested until we call dvmInitAfterZygote(). */ static void enableDebugFeatures(u4 debugFlags) { ALOGV("debugFlags is 0x%02x", debugFlags); gDvm.jdwpAllowed = ((debugFlags & DEBUG_ENABLE_DEBUGGER) != 0); if ((debugFlags & DEBUG_ENABLE_CHECKJNI) != 0) { /* turn it on if it's not already enabled */ dvmLateEnableCheckedJni(); } if ((debugFlags & DEBUG_ENABLE_JNI_LOGGING) != 0) { gDvmJni.logThirdPartyJni = true; } if ((debugFlags & DEBUG_ENABLE_ASSERT) != 0) { /* turn it on if it's not already enabled */ dvmLateEnableAssertions(); } if ((debugFlags & DEBUG_ENABLE_SAFEMODE) != 0) { #if defined(WITH_JIT) /* turn off the jit if it is explicitly requested by the app */ if (gDvm.executionMode == kExecutionModeJit) gDvm.executionMode = kExecutionModeInterpFast; #endif } #ifdef HAVE_ANDROID_OS if ((debugFlags & DEBUG_ENABLE_DEBUGGER) != 0) { /* To let a non-privileged gdbserver attach to this * process, we must set its dumpable bit flag. However * we are not interested in generating a coredump in * case of a crash, so also set the coredump size to 0 * to disable that */ if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) < 0) { ALOGE("could not set dumpable bit flag for pid %d: %s", getpid(), strerror(errno)); } else { struct rlimit rl; rl.rlim_cur = 0; rl.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &rl) < 0) { ALOGE("could not disable core file generation for pid %d: %s", getpid(), strerror(errno)); } } } #endif } /* * Set Linux capability flags. * * Returns 0 on success, errno on failure. */ static int setCapabilities(int64_t permitted, int64_t effective) { #ifdef HAVE_ANDROID_OS struct __user_cap_header_struct capheader; struct __user_cap_data_struct capdata; memset(&capheader, 0, sizeof(capheader)); memset(&capdata, 0, sizeof(capdata)); capheader.version = _LINUX_CAPABILITY_VERSION; capheader.pid = 0; capdata.effective = effective; capdata.permitted = permitted; ALOGV("CAPSET perm=%llx eff=%llx", permitted, effective); if (capset(&capheader, &capdata) != 0) return errno; #endif /*HAVE_ANDROID_OS*/ return 0; } /* * Set SELinux security context. * * Returns 0 on success, -1 on failure. */ static int setSELinuxContext(uid_t uid, bool isSystemServer, const char *seInfo, const char *niceName) { #ifdef HAVE_ANDROID_OS return selinux_android_setcontext(uid, isSystemServer, seInfo, niceName); #else return 0; #endif } static bool needsNoRandomizeWorkaround() { #if !defined(__arm__) return false; #else int major; int minor; struct utsname uts; if (uname(&uts) == -1) { return false; } if (sscanf(uts.release, "%d.%d", &major, &minor) != 2) { return false; } // Kernels before 3.4.* need the workaround. return (major < 3) || ((major == 3) && (minor < 4)); #endif } #ifdef HAVE_ANDROID_OS // Utility to close down the Zygote socket file descriptors while // the child is still running as root with Zygote's privileges. Each // descriptor (if any) is closed via dup2(), replacing it with a valid // (open) descriptor to /dev/null. static void detachDescriptors(ArrayObject* fdsToClose) { if (!fdsToClose) { return; } size_t count = fdsToClose->length; int *ar = (int *) (void *) fdsToClose->contents; if (!ar) { ALOG(LOG_ERROR, ZYGOTE_LOG_TAG, "Bad fd array"); dvmAbort(); } size_t i; int devnull; for (i = 0; i < count; i++) { if (ar[1] < 0) { continue; } devnull = open("/dev/null", O_RDWR); if (devnull < 0) { ALOG(LOG_ERROR, ZYGOTE_LOG_TAG, "Failed to open /dev/null"); dvmAbort(); } ALOG(LOG_VERBOSE, ZYGOTE_LOG_TAG, "Switching descriptor %d to /dev/null", ar[i]); if (dup2(devnull, ar[i]) < 0) { ALOG(LOG_ERROR, ZYGOTE_LOG_TAG, "Failed dup2() on descriptor %d", ar[i]); dvmAbort(); } close(devnull); } } #endif /* * Utility routine to fork zygote and specialize the child process. */ static pid_t forkAndSpecializeCommon(const u4* args, bool isSystemServer, bool legacyFork) { pid_t pid; uid_t uid = (uid_t) args[0]; gid_t gid = (gid_t) args[1]; ArrayObject* gids = (ArrayObject *)args[2]; u4 debugFlags = args[3]; ArrayObject *rlimits = (ArrayObject *)args[4]; ArrayObject *fdsToClose = NULL; u4 mountMode = MOUNT_EXTERNAL_NONE; int64_t permittedCapabilities, effectiveCapabilities; char *seInfo = NULL; char *niceName = NULL; if (isSystemServer) { /* * Don't use GET_ARG_LONG here for now. gcc is generating code * that uses register d8 as a temporary, and that's coming out * scrambled in the child process. b/3138621 */ //permittedCapabilities = GET_ARG_LONG(args, 5); //effectiveCapabilities = GET_ARG_LONG(args, 7); permittedCapabilities = args[5] | (int64_t) args[6] << 32; effectiveCapabilities = args[7] | (int64_t) args[8] << 32; } else { mountMode = args[5]; permittedCapabilities = effectiveCapabilities = 0; StringObject* seInfoObj = (StringObject*)args[6]; if (seInfoObj) { seInfo = dvmCreateCstrFromString(seInfoObj); if (!seInfo) { ALOGE("seInfo dvmCreateCstrFromString failed"); dvmAbort(); } } StringObject* niceNameObj = (StringObject*)args[7]; if (niceNameObj) { niceName = dvmCreateCstrFromString(niceNameObj); if (!niceName) { ALOGE("niceName dvmCreateCstrFromString failed"); dvmAbort(); } } if (!legacyFork) { fdsToClose = (ArrayObject *)args[8]; } } if (!gDvm.zygote) { dvmThrowIllegalStateException( "VM instance not started with -Xzygote"); return -1; } if (!dvmGcPreZygoteFork()) { ALOGE("pre-fork heap failed"); dvmAbort(); } setSignalHandler(); dvmDumpLoaderStats("zygote"); pid = fork(); if (pid == 0) { int err; /* The child process */ #ifdef HAVE_ANDROID_OS extern int gMallocLeakZygoteChild; gMallocLeakZygoteChild = 1; // Unhook from the Zygote sockets immediately detachDescriptors(fdsToClose); /* keep caps across UID change, unless we're staying root */ if (uid != 0) { err = prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0); if (err < 0) { ALOGE("cannot PR_SET_KEEPCAPS: %s", strerror(errno)); dvmAbort(); } } for (int i = 0; prctl(PR_CAPBSET_READ, i, 0, 0, 0) >= 0; i++) { err = prctl(PR_CAPBSET_DROP, i, 0, 0, 0); if (err < 0) { if (errno == EINVAL) { ALOGW("PR_CAPBSET_DROP %d failed: %s. " "Please make sure your kernel is compiled with " "file capabilities support enabled.", i, strerror(errno)); } else { ALOGE("PR_CAPBSET_DROP %d failed: %s.", i, strerror(errno)); dvmAbort(); } } } #endif /* HAVE_ANDROID_OS */ if (mountMode != MOUNT_EXTERNAL_NONE) { err = mountEmulatedStorage(uid, mountMode); if (err < 0) { ALOGE("cannot mountExternalStorage(): %s", strerror(errno)); if (errno == ENOTCONN || errno == EROFS) { // When device is actively encrypting, we get ENOTCONN here // since FUSE was mounted before the framework restarted. // When encrypted device is booting, we get EROFS since // FUSE hasn't been created yet by init. // In either case, continue without external storage. } else { dvmAbort(); } } } err = setgroupsIntarray(gids); if (err < 0) { ALOGE("cannot setgroups(): %s", strerror(errno)); dvmAbort(); } err = setrlimitsFromArray(rlimits); if (err < 0) { ALOGE("cannot setrlimit(): %s", strerror(errno)); dvmAbort(); } err = setresgid(gid, gid, gid); if (err < 0) { ALOGE("cannot setresgid(%d): %s", gid, strerror(errno)); dvmAbort(); } err = setresuid(uid, uid, uid); if (err < 0) { ALOGE("cannot setresuid(%d): %s", uid, strerror(errno)); dvmAbort(); } if (needsNoRandomizeWorkaround()) { int current = personality(0xffffFFFF); int success = personality((ADDR_NO_RANDOMIZE | current)); if (success == -1) { ALOGW("Personality switch failed. current=%d error=%d\n", current, errno); } } err = setCapabilities(permittedCapabilities, effectiveCapabilities); if (err != 0) { ALOGE("cannot set capabilities (%llx,%llx): %s", permittedCapabilities, effectiveCapabilities, strerror(err)); dvmAbort(); } err = set_sched_policy(0, SP_DEFAULT); if (err < 0) { ALOGE("cannot set_sched_policy(0, SP_DEFAULT): %s", strerror(-err)); dvmAbort(); } err = setSELinuxContext(uid, isSystemServer, seInfo, niceName); if (err < 0) { ALOGE("cannot set SELinux context: %s\n", strerror(errno)); dvmAbort(); } // These free(3) calls are safe because we know we're only ever forking // a single-threaded process, so we know no other thread held the heap // lock when we forked. free(seInfo); free(niceName); /* * Our system thread ID has changed. Get the new one. */ Thread* thread = dvmThreadSelf(); thread->systemTid = dvmGetSysThreadId(); /* configure additional debug options */ enableDebugFeatures(debugFlags); unsetSignalHandler(); gDvm.zygote = false; if (!dvmInitAfterZygote()) { ALOGE("error in post-zygote initialization"); dvmAbort(); } } else if (pid > 0) { /* the parent process */ free(seInfo); free(niceName); } return pid; } /* * We must expose both flavors of the native forking code for a while, * as this Dalvik change must be reviewed and checked in before the * libcore and frameworks changes. The legacy fork API function and * registration can be removed later. */ /* * native public static int nativeForkAndSpecialize(int uid, int gid, * int[] gids, int debugFlags, int[][] rlimits, int mountExternal, * String seInfo, String niceName, int[] fdsToClose); */ static void Dalvik_dalvik_system_Zygote_forkAndSpecialize(const u4* args, JValue* pResult) { pid_t pid; pid = forkAndSpecializeCommon(args, false, false); RETURN_INT(pid); } /* * native public static int nativeForkSystemServer(int uid, int gid, * int[] gids, int debugFlags, int[][] rlimits, * long permittedCapabilities, long effectiveCapabilities); */ static void Dalvik_dalvik_system_Zygote_forkSystemServer( const u4* args, JValue* pResult) { pid_t pid; pid = forkAndSpecializeCommon(args, true, true); /* The zygote process checks whether the child process has died or not. */ if (pid > 0) { int status; ALOGI("System server process %d has been created", pid); gDvm.systemServerPid = pid; /* There is a slight window that the system server process has crashed * but it went unnoticed because we haven't published its pid yet. So * we recheck here just to make sure that all is well. */ if (waitpid(pid, &status, WNOHANG) == pid) { ALOGE("System server process %d has died. Restarting Zygote!", pid); kill(getpid(), SIGKILL); } } RETURN_INT(pid); } const DalvikNativeMethod dvm_dalvik_system_Zygote[] = { { "nativeFork", "()I", Dalvik_dalvik_system_Zygote_fork }, { "nativeForkAndSpecialize", "(II[II[[IILjava/lang/String;Ljava/lang/String;[I)I", Dalvik_dalvik_system_Zygote_forkAndSpecialize }, { "nativeForkSystemServer", "(II[II[[IJJ)I", Dalvik_dalvik_system_Zygote_forkSystemServer }, { NULL, NULL, NULL }, };
; ; Copyright (c) 2015 Digi International Inc. ; ; This Source Code Form is subject to the terms of the Mozilla Public ; License, v. 2.0. If a copy of the MPL was not distributed with this ; file, You can obtain one at http://mozilla.org/MPL/2.0/. ; ; feilipu, 2019 April ; adapted for z80, z180, and z80n ; ;------------------------------------------------------------------------- ; m32_fsadd - z80, z180, z80n floating point add ; m32_fssub - z80, z180, z80n floating point subtract ;------------------------------------------------------------------------- ; ; 1) first section: unpack from F_add: to sort: ; one unpacked number in hldebc the other in hl'de'bc' ; unpacked format: h==0; mantissa= lde, sign in b, exponent in c ; in addition af' holds b xor b' used to test if add or sub needed ; ; 2) second section: sort from sort to align, sets up smaller number in hldebc and larger in hl'de'bc' ; This section sorts out the special cases: ; to alignzero - if no alignment (right) shift needed ; alignzero has properties: up to 23 normalize shifts needed if signs differ ; not know which mantissa is larger for different signs until sub performed ; no alignment shifts needed ; to alignone - if one alignment shift needed ; alignone has properties: up to 23 normalize shifts needed if signs differ ; mantissa aligned is always smaller than other mantissa ; one alignment shift needed ; to align - 2 to 23 alignment shifts needed ; numbers aligned 2-23 have properties: max of 1 normalize shift needed ; mantissa aligned always smaller ; 2-23 alignment shifts needed ; number too small to add, return larger number (to doadd1) ; ; 3) third section alignment - aligns smaller number mantissa with larger mantissa ; This section does the right shift. Lost bits shifted off, are tested. Up to 8 lost bits ; are used for the test. If any are non-zero a one is or'ed into remaining mantissa bit 0. ; align 2-23 - worst case right shift by 7 with lost bits ; ; 4) 4th section add or subtract ; ; 5) 5th section normalize in separate file d32_fsnormalize.asm ; ; 6) 6th section pack up in separate file d32_fsnormalize.asm ; ;------------------------------------------------------------------------- ; FIXME clocks ;------------------------------------------------------------------------- SECTION code_clib SECTION code_fp_math32 EXTERN m32_fsnormalize PUBLIC m32_fssub, m32_fssub_callee PUBLIC m32_fsadd, m32_fsadd_callee ; enter here for floating subtract, x-y x on stack, y in dehl .m32_fssub ld a,d ; toggle the sign bit for subtraction xor 080h ld d,a ; enter here for floating add, x+y, x on stack, y in dehl, result in dehl .m32_fsadd ex de,hl ; DEHL -> HLDE ld b,h ; place op1.s in b[7] add hl,hl ; unpack op1 ld c,h ; save op1.e in c ld a,h or a jr Z,faunp1 ; add implicit bit if op1.e!=0 scf .faunp1 rr l ; rotate in op1.m's implicit bit ld a,b ; place op1.s in a[7] exx ld hl,002h ; get second operand off of the stack add hl,sp ld e,(hl) inc hl ld d,(hl) inc hl ld c,(hl) inc hl ld h,(hl) ld l,c ; hlde = seeeeeee emmmmmmm mmmmmmmm mmmmmmmm jp farejoin ; enter here for floating subtract callee, x-y x on stack, y in dehl .m32_fssub_callee ld a,d ; toggle the sign bit for subtraction xor 080h ld d,a ; enter here for floating add callee, x+y, x on stack, y in bcde, result in bcde .m32_fsadd_callee ex de,hl ; DEHL -> HLDE ld b,h ; place op1.s in b[7] add hl,hl ; unpack op1 ld c,h ; save op1.e in c ld a,h or a jr Z,faunp1_callee ; add implicit bit if op1.e!=0 scf .faunp1_callee rr l ; rotate in op1.m's implicit bit ld a,b ; place op1.s in a[7] exx pop bc ; pop return address pop de ; get second operand off of the stack pop hl ; hlde = seeeeeee emmmmmmm mmmmmmmm mmmmmmmm push bc ; return address on stack .farejoin ld b,h ; save op2.s in b[7] add hl,hl ; unpack op2 ld c,h ; save op2.e in c xor b ; check if op1.s==op2.s ex af,af ; save results sign in f' (C clear in af') ld a,h or a jr Z,faunp2 ; add implicit bit if op2.e!=0 scf .faunp2 rr l ; rotate in op2.m's implicit bit xor a ld h,a ; op2 mantissa: h = 00000000, lde = 1mmmmmmm mmmmmmmm mmmmmmmm exx ld h,a ; op1 mantissa: h = 00000000, lde = 1mmmmmmm mmmmmmmm mmmmmmmm ; sort larger from smaller and compute exponent difference ld a,c exx cp a,c ; nc if a>=c jp Z,alignzero ; no alignment needed, mantissas equal jr NC,sort ; if a larger than c ld a,c exx .sort sub a,c ; positive difference in a cp a,1 ; if one difference, special case jp Z,alignone ; smaller mantissa on top cp a,24 ; check for too many shifts jr C,align ; if 23 or fewer shifts ; use other side, adding small quantity that can be ignored exx jp doadd1 ; pack result ; align begin align count zero .align srl a ; clear carry flag jr NC,al_2 srl h rr l rr d rr e .al_2 rra ; 1st lost bit to a jr NC,al_3 srl h rr l rr d rr e rr h rr l rr d rr e .al_3 rra ; 2nd lost bit to a jr NC,al_4 srl h rr l rr d rr e rr h rr l rr d rr e rr h rr l rr d rr e rr h rr l rr d rr e ; check for 8 bit right shift .al_4 rra ; 3rd lost bit to a check shift by 8, jr NC,al_5 ; shift by 8 right, no 16 possible ld a,e ; lost bits, keep only 8 or a ; test lost bits ld e,d ld d,l ld hl,0 ; upper zero jr Z,aldone set 0,e ; lost bits jr aldone ; here possible 16 .al_5 rra ; shift in a zero, lost bits in 6,5,4 jr NC,al_6 ; no shift by 16 ; here shift by 16 ; toss lost bits in a which are remote for 16 shift ; consider only lost bits in d and h ld a,d ; lost bits or a,h ; test lost bits ld e,l ld d,0 ld h,d ; hl zero ld l,d jr Z,aldone set 0,e ; lost bits jr aldone ; here no 8 or 16 shift, lost bits in a-reg bits 6,5,4, other bits zero's .al_6 or a,h ; test lost bits ld h,0 jr Z,aldone set 0,e ; aldone here .aldone ex af,af ; carry clear jp P,doadd ; here for subtract, smaller shifted right at least 2, so no more than ; one step of normalize push hl exx ex de,hl ex (sp),hl ex de,hl exx pop hl ; subtract the mantissas sbc hl,de exx sbc hl,de push de exx ex (sp),hl exx pop de ; difference larger-smaller in hlde ; exponent of result in c sign of result in b bit 7,l ; check for norm jr NZ,doadd1 ; no normalize step, pack it up sla e rl d adc hl,hl dec c jr doadd1 ; pack ; here for do add c has exponent of result (larger) b or b' has sign .doadd push hl exx ex de,hl ex (sp),hl ex de,hl exx pop hl ; add the mantissas add hl,de exx adc hl,de push de exx ex (sp),hl exx pop de ; get least of sum xor a or a,h ; see if overflow to h jr Z,doadd1 rr h rr l rr d rr e jr NC,doadd0 set 0,e .doadd0 inc c jr Z,foverflow .doadd1 ; now pack result add hl,hl ld h,c ; exp rl b rr h rr l ex de,hl ; return DEHL ret .foverflow ld a,b and 080h or 07fh ld d,a ld e,0ffh ld hl,0ffffh ; max number scf ; error ret ; here one alignment needed .alignone ; from fadd srl h rr l rr d rr e jr NC,alignone_a set 0,e .alignone_a ex af,af jp M,fasub jr doadd .alignzero ex af,af jp P,doadd ; here do subtract ; enter with aligned, smaller in hlde, exp of result in c' ; sign of result in b' ; larger number in hl'de' ; c is clear .fasub push hl exx ex de,hl ex (sp),hl ex de,hl exx pop hl ; subtract the mantissas sbc hl,de exx sbc hl,de jr NC,noneg ; *** what if zero ; fix up and subtract in reverse direction exx ld a,b ; get reversed sign add hl,de ; reverse sub exx adc hl,de ; reverse sub exx ex de,hl or a sbc hl,de exx ex de,hl sbc hl,de ld b,a ; get proper sign to result .noneg push de exx ex (sp),hl exx pop de ; get least part of result ; sub zero alignment from fadd ; difference larger-smaller in hlde ; exponent of result in c sign of result in b ; now do normalize scf ex af,af ; if no C an alternate exit is taken jp m32_fsnormalize ; now begin to normalize
Name: zel_char2.asm Type: file Size: 14984 Last-Modified: '2016-05-13T04:36:32Z' SHA-1: B3B11D4313F71ED960660EA11FED21FD68FC07B4 Description: null
; float _fmax (float left, float right) SECTION code_clib SECTION code_fp_math32 PUBLIC cm32_sdcc_fmax EXTERN cm32_sdcc_fsread1, cm32_sdcc_fsreadr, m32_compare ; maximum of two sdcc floats ; ; enter : stack = sdcc_float right, sdcc_float left, ret ; ; exit : stack = sdcc_float right, sdcc_float left, ret ; DEHL = sdcc_float ; ; uses : af, bc, de, hl, af', bc', de', hl' .cm32_sdcc_fmax call m32_compare ; compare two floats on the stack jp C,cm32_sdcc_fsreadr jp cm32_sdcc_fsread1 ; enter stack = sdcc_float right, sdcc_float left, ret ; return stack = sdcc_float right, sdcc_float left ; DEHL = sdcc_float max
; A008553: Numbers that contain the letter `y'. ; 20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85 add $0,20 mov $1,$0