text stringlengths 1 1.05M |
|---|
_SafariZoneRestHouse2Text1::
text "Tossing ROCKs at"
line "#MON might"
cont "make them run,"
cont "but they'll be"
cont "easier to catch."
done
_SafariZoneRestHouse2Text2::
text "Using BAIT will"
line "make #MON"
cont "easier to catch."
done
_SafariZoneRestHouse2Text3::
text "I hiked a lot, but"
line "I didn't see any"
cont "#MON I wanted."
done
|
;
; Jupiter ACE pseudo graphics routines
; Version for the 2x3 graphics symbols (UDG redefined)
;
; Stefano Bodrato 2014
;
;
; XOR pixel at (x,y) coordinate.
;
;
; $Id: xorpixl.asm,v 1.9 2016/07/02 09:01:35 dom Exp $
;
INCLUDE "graphics/grafix.inc"
SECTION code_clib
PUBLIC xorpixel
EXTERN div3
EXTERN __gfx_coords
EXTERN base_graphics
.xorpixel
ld a,h
cp maxx
ret nc
ld a,l
cp maxy
ret nc ; y0 out of range
dec a
dec a
ld (__gfx_coords),hl
push bc
ld c,a ; y
ld b,h ; x
push bc
ld hl,div3
ld d,0
ld e,c
inc e
add hl,de
ld a,(hl)
ld c,a ; y/3
srl b ; x/2
ld a,c
ld c,b ; !!
;--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
ld hl,(base_graphics)
ld b,a ; keep y/3
and a
jr z,r_zero
ld de,32
.r_loop
add hl,de
dec a
jr nz,r_loop
.r_zero ld d,0
ld e,c
add hl,de
;--- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
ld a,(hl) ; get current symbol from screen
sub 128
ld e,a ; ..and its copy
ex (sp),hl ; save char address <=> restore x,y (y=h, x=l)
ld a,l
inc a
inc a
sub b
sub b
sub b ; we get the remainder of y/3
ld l,a
ld a,1 ; the pixel we want to draw
jr z,iszero
bit 0,l
jr nz,is1
add a,a
add a,a
.is1
add a,a
add a,a
.iszero
bit 0,h
jr nz,evenrow
add a,a ; move down the bit
.evenrow
xor e
add 128
pop hl
ld (hl),a
pop bc
ret
|
#include "../../flame32.asm"
; Tests LDM
ldm A, TEST_VALUE
TEST_VALUE:
#d32 0x12345678
|
pxor xmm0, xmm1
aesdec xmm0, xmm2
aesdec xmm0, xmm3
aesdec xmm0, xmm4
aesdec xmm0, xmm5
aesdec xmm0, xmm6
aesdec xmm0, xmm7
aesdec xmm0, xmm8
aesdec xmm0, xmm9
aesdec xmm0, xmm10
aesdec xmm0, xmm11
aesdec xmm0, xmm12
aesdeclast xmm0, xmm13 |
// Copyright (c) 2017-2018 SECI developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternodeman.h"
#include "masternode.h"
#include "activemasternode.h"
#include "signhelper_mn.h"
#include "sync.h"
#include "validation.h"
#include "consensus/validation.h"
#include "util.h"
#include "addrman.h"
#include "net_processing.h"
#include "txmempool.h"
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
CCriticalSection cs_process_message;
/** Masternode manager */
CMasternodeMan mnodeman;
CMNSignHelper darkSendPool;
struct CompareValueOnly
{
bool operator()(const pair<int64_t, CTxIn>& t1,
const pair<int64_t, CTxIn>& t2) const
{
return t1.first < t2.first;
}
};
struct CompareValueOnlyMN
{
bool operator()(const pair<int64_t, CMasternode>& t1,
const pair<int64_t, CMasternode>& t2) const
{
return t1.first < t2.first;
}
};
//
// CMasternodeDB
//
CMasternodeDB::CMasternodeDB()
{
pathMN = GetDataDir() / "mncache.dat";
strMagicMessage = "MasternodeCache";
}
bool CMasternodeDB::Write(const CMasternodeMan& mnodemanToSave)
{
int64_t nStart = GetTimeMillis();
// serialize, checksum data up to that point, then append checksum
CDataStream ssMasternodes(SER_DISK, CLIENT_VERSION);
ssMasternodes << strMagicMessage; // masternode cache file specific magic message
ssMasternodes << FLATDATA(Params().MessageStart()); // network specific magic number
ssMasternodes << mnodemanToSave;
uint256 hash = Hash(ssMasternodes.begin(), ssMasternodes.end());
ssMasternodes << hash;
// open output file, and associate with CAutoFile
FILE *file = fopen(pathMN.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathMN.string());
// Write and commit header, data
try {
fileout << ssMasternodes;
}
catch (std::exception &e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
//FileCommit(fileout);
fileout.fclose();
LogPrintf("Written info to mncache.dat %dms\n", GetTimeMillis() - nStart);
LogPrintf(" %s\n", mnodemanToSave.ToString());
return true;
}
CMasternodeDB::ReadResult CMasternodeDB::Read(CMasternodeMan& mnodemanToLoad)
{
int64_t nStart = GetTimeMillis();
// open input file, and associate with CAutoFile
FILE *file = fopen(pathMN.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
{
error("%s : Failed to open file %s", __func__, pathMN.string());
return FileError;
}
// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathMN);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char *)&vchData[0], dataSize);
filein >> hashIn;
}
catch (std::exception &e) {
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return HashReadError;
}
filein.fclose();
CDataStream ssMasternodes(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssMasternodes.begin(), ssMasternodes.end());
if (hashIn != hashTmp)
{
error("%s : Checksum mismatch, data corrupted", __func__);
return IncorrectHash;
}
unsigned char pchMsgTmp[4];
std::string strMagicMessageTmp;
try {
// de-serialize file header (masternode cache file specific magic message) and ..
ssMasternodes >> strMagicMessageTmp;
// ... verify the message matches predefined one
if (strMagicMessage != strMagicMessageTmp)
{
error("%s : Invalid masternode cache magic message", __func__);
return IncorrectMagicMessage;
}
// de-serialize file header (network specific magic number) and ..
ssMasternodes >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
{
error("%s : Invalid network magic number", __func__);
return IncorrectMagicNumber;
}
// de-serialize data into CMasternodeMan object
ssMasternodes >> mnodemanToLoad;
}
catch (std::exception &e) {
mnodemanToLoad.Clear();
error("%s : Deserialize or I/O error - %s", __func__, e.what());
return IncorrectFormat;
}
mnodemanToLoad.CheckAndRemove(); // clean out expired
LogPrintf("Loaded info from mncache.dat %dms\n", GetTimeMillis() - nStart);
LogPrintf(" %s\n", mnodemanToLoad.ToString());
return Ok;
}
void DumpMasternodes()
{
int64_t nStart = GetTimeMillis();
CMasternodeDB mndb;
CMasternodeMan tempMnodeman;
LogPrintf("Verifying mncache.dat format...\n");
CMasternodeDB::ReadResult readResult = mndb.Read(tempMnodeman);
// there was an error and it was not an error on file openning => do not proceed
if (readResult == CMasternodeDB::FileError)
LogPrintf("Missing masternode cache file - mncache.dat, will try to recreate\n");
else if (readResult != CMasternodeDB::Ok)
{
LogPrintf("Error reading mncache.dat: ");
if(readResult == CMasternodeDB::IncorrectFormat)
LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
else
{
LogPrintf("file format is unknown or invalid, please fix it manually\n");
return;
}
}
LogPrintf("Writting info to mncache.dat...\n");
mndb.Write(mnodeman);
LogPrintf("Masternode dump finished %dms\n", GetTimeMillis() - nStart);
}
CMasternodeMan::CMasternodeMan() {
nDsqCount = 0;
}
bool CMasternodeMan::Add(CMasternode &mn)
{
LOCK(cs);
if (!mn.IsEnabled())
return false;
LogPrintf("CMasternodeMan: Attempting to locate and add new Masternode %s - %i now\n", mn.addr.ToString().c_str(), size() + 1);
CMasternode *pmn = Find(mn.vin);
if (pmn == NULL)
{
if(fDebug) LogPrintf("CMasternodeMan: Adding new Masternode %s - %i now\n", mn.addr.ToString().c_str(), size() + 1);
vMasternodes.push_back(mn);
return true;
}
return false;
}
void CMasternodeMan::Check()
{
LOCK(cs);
BOOST_FOREACH(CMasternode& mn, vMasternodes)
mn.Check();
}
void CMasternodeMan::CheckAndRemove()
{
LOCK(cs);
Check();
//remove inactive
vector<CMasternode>::iterator it = vMasternodes.begin();
while(it != vMasternodes.end()){
if((*it).activeState == CMasternode::MASTERNODE_REMOVE || (*it).activeState == CMasternode::MASTERNODE_VIN_SPENT){
if(fDebug) LogPrintf("CMasternodeMan: Removing inactive Masternode %s - %i now\n", (*it).addr.ToString().c_str(), size() - 1);
it = vMasternodes.erase(it);
} else {
++it;
}
}
// check who's asked for the Masternode list
map<CNetAddr, int64_t>::iterator it1 = mAskedUsForMasternodeList.begin();
while(it1 != mAskedUsForMasternodeList.end()){
if((*it1).second < GetTime()) {
mAskedUsForMasternodeList.erase(it1++);
} else {
++it1;
}
}
// check who we asked for the Masternode list
it1 = mWeAskedForMasternodeList.begin();
while(it1 != mWeAskedForMasternodeList.end()){
if((*it1).second < GetTime()){
mWeAskedForMasternodeList.erase(it1++);
} else {
++it1;
}
}
// check which Masternodes we've asked for
map<COutPoint, int64_t>::iterator it2 = mWeAskedForMasternodeListEntry.begin();
while(it2 != mWeAskedForMasternodeListEntry.end()){
if((*it2).second < GetTime()){
mWeAskedForMasternodeListEntry.erase(it2++);
} else {
++it2;
}
}
}
void CMasternodeMan::Clear()
{
LOCK(cs);
vMasternodes.clear();
mAskedUsForMasternodeList.clear();
mWeAskedForMasternodeList.clear();
mWeAskedForMasternodeListEntry.clear();
nDsqCount = 0;
}
int CMasternodeMan::CountEnabled()
{
int i = 0;
BOOST_FOREACH(CMasternode& mn, vMasternodes) {
mn.Check();
if(mn.IsEnabled()) i++;
}
return i;
}
int CMasternodeMan::CountMasternodesAboveProtocol(int protocolVersion)
{
int i = 0;
BOOST_FOREACH(CMasternode& mn, vMasternodes) {
mn.Check();
if(mn.protocolVersion < protocolVersion || !mn.IsEnabled()) continue;
i++;
}
return i;
}
void CMasternodeMan::DsegUpdate(CNode* pnode)
{
LOCK(cs);
std::map<CNetAddr, int64_t>::iterator it = mWeAskedForMasternodeList.find(pnode->addr);
if (it != mWeAskedForMasternodeList.end())
{
if (GetTime() < (*it).second) {
LogPrintf("dseg - we already asked %s for the list; skipping...\n", pnode->addr.ToString());
return;
}
}
//pnode->PushMessage("dseg", CTxIn());
g_connman->PushMessage(pnode, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "dseg", CTxIn()));
int64_t askAgain = GetTime() + MASTERNODES_DSEG_SECONDS;
mWeAskedForMasternodeList[pnode->addr] = askAgain;
}
CMasternode *CMasternodeMan::Find(const CTxIn &vin)
{
LOCK(cs);
BOOST_FOREACH(CMasternode& mn, vMasternodes)
{
if(mn.vin.prevout == vin.prevout)
return &mn;
}
return NULL;
}
CMasternode *CMasternodeMan::Find(const CPubKey &pubKeyMasternode)
{
LOCK(cs);
BOOST_FOREACH(CMasternode& mn, vMasternodes)
{
if(mn.pubkey2 == pubKeyMasternode)
return &mn;
}
return NULL;
}
CMasternode* CMasternodeMan::FindOldestNotInVec(const std::vector<CTxIn> &vVins, int nMinimumAge, int nMinimumActiveSeconds)
{
LOCK(cs);
CMasternode *pOldestMasternode = NULL;
BOOST_FOREACH(CMasternode &mn, vMasternodes)
{
mn.Check();
if(!mn.IsEnabled()) continue;
if(mn.GetMasternodeInputAge() < nMinimumAge || mn.lastTimeSeen - mn.sigTime < nMinimumActiveSeconds) continue;
bool found = false;
BOOST_FOREACH(const CTxIn& vin, vVins)
if(mn.vin.prevout == vin.prevout)
{
found = true;
break;
}
if(found) continue;
if(pOldestMasternode == NULL || pOldestMasternode->GetMasternodeInputAge() < mn.GetMasternodeInputAge()){
pOldestMasternode = &mn;
}
}
return pOldestMasternode;
}
CMasternode *CMasternodeMan::FindRandom()
{
LOCK(cs);
if(size() == 0) return NULL;
return &vMasternodes[GetRandInt(vMasternodes.size())];
}
CMasternode* CMasternodeMan::GetCurrentMasterNode(int mod, int64_t nBlockHeight, int minProtocol)
{
unsigned int score = 0;
CMasternode* winner = NULL;
// scan for winner
BOOST_FOREACH(CMasternode& mn, vMasternodes) {
mn.Check();
if(mn.protocolVersion < minProtocol || !mn.IsEnabled()) continue;
// calculate the score for each Masternode
uint256 n = mn.CalculateScore(mod, nBlockHeight);
unsigned int n2 = 0;
memcpy(&n2, &n, sizeof(n2));
// determine the winner
if(n2 > score){
score = n2;
winner = &mn;
}
}
return winner;
}
int CMasternodeMan::GetMasternodeRank(const CTxIn& vin, int64_t nBlockHeight, int minProtocol, bool fOnlyActive)
{
std::vector<pair<unsigned int, CTxIn> > vecMasternodeScores;
//make sure we know about this block
uint256 hash = uint256();
if(!GetBlockHash(hash, nBlockHeight)) return -1;
// scan for winner
BOOST_FOREACH(CMasternode& mn, vMasternodes) {
if(mn.protocolVersion < minProtocol) continue;
if(fOnlyActive) {
mn.Check();
if(!mn.IsEnabled()) continue;
}
uint256 n = mn.CalculateScore(1, nBlockHeight);
unsigned int n2 = 0;
memcpy(&n2, &n, sizeof(n2));
vecMasternodeScores.push_back(make_pair(n2, mn.vin));
}
sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnly());
int rank = 0;
BOOST_FOREACH (PAIRTYPE(unsigned int, CTxIn)& s, vecMasternodeScores){
rank++;
if(s.second == vin) {
return rank;
}
}
return -1;
}
std::vector<pair<int, CMasternode> > CMasternodeMan::GetMasternodeRanks(int64_t nBlockHeight, int minProtocol)
{
std::vector<pair<unsigned int, CMasternode> > vecMasternodeScores;
std::vector<pair<int, CMasternode> > vecMasternodeRanks;
//make sure we know about this block
uint256 hash = uint256();
if(!GetBlockHash(hash, nBlockHeight)) return vecMasternodeRanks;
// scan for winner
BOOST_FOREACH(CMasternode& mn, vMasternodes) {
mn.Check();
if(mn.protocolVersion < minProtocol) continue;
if(!mn.IsEnabled()) {
continue;
}
uint256 n = mn.CalculateScore(1, nBlockHeight);
unsigned int n2 = 0;
memcpy(&n2, &n, sizeof(n2));
vecMasternodeScores.push_back(make_pair(n2, mn));
}
sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnlyMN());
int rank = 0;
BOOST_FOREACH (PAIRTYPE(unsigned int, CMasternode)& s, vecMasternodeScores){
rank++;
vecMasternodeRanks.push_back(make_pair(rank, s.second));
}
return vecMasternodeRanks;
}
CMasternode* CMasternodeMan::GetMasternodeByRank(int nRank, int64_t nBlockHeight, int minProtocol, bool fOnlyActive)
{
std::vector<pair<unsigned int, CTxIn> > vecMasternodeScores;
// scan for winner
BOOST_FOREACH(CMasternode& mn, vMasternodes) {
if(mn.protocolVersion < minProtocol) continue;
if(fOnlyActive) {
mn.Check();
if(!mn.IsEnabled()) continue;
}
uint256 n = mn.CalculateScore(1, nBlockHeight);
unsigned int n2 = 0;
memcpy(&n2, &n, sizeof(n2));
vecMasternodeScores.push_back(make_pair(n2, mn.vin));
}
sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnly());
int rank = 0;
BOOST_FOREACH (PAIRTYPE(unsigned int, CTxIn)& s, vecMasternodeScores){
rank++;
if(rank == nRank) {
return Find(s.second);
}
}
return NULL;
}
void CMasternodeMan::ProcessMasternodeConnections()
{
//we don't care about this for regtest
//if(RegTest()) return;
// LOCK(cs_vNodes);
//if(!darkSendPool.pSubmittedToMasternode) return;
/*BOOST_FOREACH(CNode* pnode, vNodes)
{
if(darkSendPool.pSubmittedToMasternode->addr == pnode->addr) continue;
if(pnode->fDarkSendMaster){
LogPrintf("Closing Masternode connection %s \n", pnode->addr.ToString().c_str());
pnode->CloseSocketDisconnect();
}
}*///todo ++ add must
}
void CMasternodeMan::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
if(fProUserModeDarksendInstantX2) return; //disable all Darksend/Masternode related functionality
if(IsInitialBlockDownload()) return;
LOCK(cs_process_message);
if (strCommand == "dsee") { //DarkSend Election Entry
CTxIn vin;
CService addr;
CPubKey pubkey;
CPubKey pubkey2;
vector<unsigned char> vchSig;
int64_t sigTime;
int count;
int current;
int64_t lastUpdated;
int protocolVersion;
CScript donationAddress;
int donationPercentage;
std::string strMessage;
// 70047 and greater
vRecv >> vin >> addr >> vchSig >> sigTime >> pubkey >> pubkey2 >> count >> current >> lastUpdated >> protocolVersion >> *(CScriptBase*)(&donationAddress) >> donationPercentage;
// make sure signature isn't in the future (past is OK)
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrintf("dsee - Signature rejected, too far into the future %s\n", vin.ToString().c_str());
return;
}
bool isLocal = addr.IsRFC1918() || addr.IsLocal();
//if(RegTest()) isLocal = false;
std::string vchPubKey(pubkey.begin(), pubkey.end());
std::string vchPubKey2(pubkey2.begin(), pubkey2.end());
strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion) + donationAddress.ToString() + boost::lexical_cast<std::string>(donationPercentage);
if(donationPercentage < 0 || donationPercentage > 100){
LogPrintf("dsee - donation percentage out of range %d\n", donationPercentage);
return;
}
if(protocolVersion < MIN_PEER_PROTO_VERSION) {
LogPrintf("dsee - ignoring outdated Masternode %s protocol version %d\n", vin.ToString().c_str(), protocolVersion);
return;
}
CScript pubkeyScript;
pubkeyScript = GetScriptForDestination(pubkey.GetID());
if(pubkeyScript.size() != 25) {
LogPrintf("dsee - pubkey the wrong size\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
CScript pubkeyScript2;
pubkeyScript2 = GetScriptForDestination(pubkey2.GetID());
if(pubkeyScript2.size() != 25) {
LogPrintf("dsee - pubkey2 the wrong size\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
if(!vin.scriptSig.empty()) {
LogPrintf("dsee - Ignore Not Empty ScriptSig %s\n",vin.ToString().c_str());
return;
}
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(pubkey, vchSig, strMessage, errorMessage)){
LogPrintf("dsee - Got bad Masternode address signature\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
if(addr.GetPort() != 9819 && Params().NetworkIDString() == CBaseChainParams::MAIN) {
LogPrintf("dsee - Got bad mainnet Masternode port: Actual:%d => Expected:%d\n", addr.GetPort(), 9819);
return;
}
else if(addr.GetPort() != 9829 && Params().NetworkIDString() == CBaseChainParams::TESTNET) {
LogPrintf("dsee - Got bad testnet Masternode port: Actual:%d => Expected:%d\n", addr.GetPort(), 9829);
return;
}
//search existing Masternode list, this is where we update existing Masternodes with new dsee broadcasts
CMasternode* pmn = this->Find(vin);
// if we are masternode but with undefined vin and this dsee is ours (matches our Masternode privkey) then just skip this part
if(pmn != NULL && !(fMasterNode && activeMasternode.vin == CTxIn() && pubkey2 == activeMasternode.pubKeyMasternode))
{
// count == -1 when it's a new entry
// e.g. We don't want the entry relayed/time updated when we're syncing the list
// mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below,
// after that they just need to match
if(count == -1 && pmn->pubkey == pubkey && !pmn->UpdatedWithin(MASTERNODE_MIN_DSEE_SECONDS)){
pmn->UpdateLastSeen();
if(pmn->sigTime < sigTime){ //take the newest entry
LogPrintf("dsee - Got updated entry for %s\n", addr.ToString().c_str());
pmn->pubkey2 = pubkey2;
pmn->sigTime = sigTime;
pmn->sig = vchSig;
pmn->protocolVersion = protocolVersion;
pmn->addr = addr;
pmn->donationAddress = donationAddress;
pmn->donationPercentage = donationPercentage;
pmn->Check();
if(pmn->IsEnabled())
mnodeman.RelayMasternodeEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, donationAddress, donationPercentage, connman);
}
}
return;
}
// make sure the vout that was signed is related to the transaction that spawned the Masternode
// - this is expensive, so it's only done once per Masternode
if(!darkSendSigner.IsVinAssociatedWithPubkey(vin, pubkey)) {
LogPrintf("dsee - Got mismatched pubkey and vin Fehler1\n");
Misbehaving(pfrom->GetId(), 100);
return;
}
if(fDebug) LogPrintf("dsee - Got NEW Masternode entry %s\n", addr.ToString().c_str());
// make sure it's still unspent
// - this is checked later by .check() in many places and by ThreadCheckDarkSendPool()
CValidationState state;
//LogPrintf("after CValidationState state\n");
CMutableTransaction mtx;
CTxOut vout = CTxOut(MASTERNODEAMOUNT * COIN, darkSendSigner.collateralPubKey);
mtx.vin.push_back(vin);
mtx.vout.push_back(vout);
if(AcceptableInputs(mempool, state, MakeTransactionRef(mtx))){
//LogPrintf(" after passing AcceptToMemoryPool\n");
CTransactionRef txref(MakeTransactionRef(std::move(mtx)));
if(fDebug) LogPrintf("dsee - Accepted Masternode entry %i %i\n", count, current);
if(GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS){
LogPrintf("dsee - Input must have least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS);
Misbehaving(pfrom->GetId(), 20);
return;
}
// verify that sig time is legit in past
// should be at least not earlier than block when 1000 SECI tx got MASTERNODE_MIN_CONFIRMATIONS
uint256 hashBlock = uint256();
GetTransaction(vin.prevout.hash, txref,Params().GetConsensus(), hashBlock, true);
//vin.prevout.hash, txVin, Params().GetConsensus(),hash, true
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pMNIndex = (*mi).second; // block for 5000 SECI tx -> 1 confirmation
CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + MASTERNODE_MIN_CONFIRMATIONS - 1]; // block where tx got MASTERNODE_MIN_CONFIRMATIONS
if(pConfIndex->GetBlockTime() > sigTime)
{
LogPrintf("dsee - Bad sigTime %d for Masternode %20s %105s (%i conf block is at %d)\n",
sigTime, addr.ToString(), vin.ToString(), MASTERNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime());
return;
}
}
// use this as a peer
//const CAddress addr2 = CAddress(addr);
std::vector<CAddress> vAddr;
//vAddr = CAddress(addr);
vAddr.push_back(CAddress(addr));
connman.AddNewAddresses(vAddr, pfrom->addr, 2*60*60);
//doesn't support multisig addresses
if(donationAddress.IsPayToScriptHash()){
donationAddress = CScript();
donationPercentage = 0;
}
// add our Masternode
CMasternode mn(addr, vin, pubkey, vchSig, sigTime, pubkey2, protocolVersion, donationAddress, donationPercentage);
mn.UpdateLastSeen(lastUpdated);
this->Add(mn);
// if it matches our Masternode privkey, then we've been remotely activated
if(pubkey2 == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION){
activeMasternode.EnableHotColdMasterNode(vin, addr);
}
if(count == -1 && !isLocal)
mnodeman.RelayMasternodeEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, donationAddress, donationPercentage, connman);
} else {
LogPrintf("dsee - Rejected Masternode entry %s\n", addr.ToString().c_str());
int nDoS = 0;
if (state.IsInvalid(nDoS))
{
LogPrintf("dsee - %s from %s %s was not accepted into the memory pool\n", mtx.GetHash().ToString().c_str(),
pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str());
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
}
}
}
else if (strCommand == "dseep") { //DarkSend Election Entry Ping
CTxIn vin;
vector<unsigned char> vchSig;
int64_t sigTime;
bool stop;
vRecv >> vin >> vchSig >> sigTime >> stop;
//LogPrintf("dseep - Received: vin: %s sigTime: %lld stop: %s\n", vin.ToString().c_str(), sigTime, stop ? "true" : "false");
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrintf("dseep - Signature rejected, too far into the future %s\n", vin.ToString().c_str());
return;
}
if (sigTime <= GetAdjustedTime() - 60 * 60) {
LogPrintf("dseep - Signature rejected, too far into the past %s - %d %d \n", vin.ToString().c_str(), sigTime, GetAdjustedTime());
return;
}
// see if we have this Masternode
CMasternode* pmn = this->Find(vin);
if(pmn != NULL && pmn->protocolVersion >= MIN_PEER_PROTO_VERSION)
{
//LogPrintf("dseep - Found corresponding mn for vin: %s\n", vin.ToString().c_str());
// take this only if it's newer
if(pmn->lastDseep < sigTime)
{
std::string strMessage = pmn->addr.ToString() + boost::lexical_cast<std::string>(sigTime) + boost::lexical_cast<std::string>(stop);
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(pmn->pubkey2, vchSig, strMessage, errorMessage))
{
LogPrintf("dseep - Got bad Masternode address signature %s \n", vin.ToString().c_str());
//Misbehaving(pfrom->GetId(), 100);
return;
}
pmn->lastDseep = sigTime;
if(!pmn->UpdatedWithin(MASTERNODE_MIN_DSEEP_SECONDS))
{
if(stop) pmn->Disable();
else
{
pmn->UpdateLastSeen();
pmn->Check();
if(!pmn->IsEnabled()) return;
}
mnodeman.RelayMasternodeEntryPing(vin, vchSig, sigTime, stop, connman);
}
}
return;
}
if(fDebug) LogPrintf("dseep - Couldn't find Masternode entry %s\n", vin.ToString().c_str());
std::map<COutPoint, int64_t>::iterator i = mWeAskedForMasternodeListEntry.find(vin.prevout);
if (i != mWeAskedForMasternodeListEntry.end())
{
int64_t t = (*i).second;
if (GetTime() < t) return; // we've asked recently
}
// ask for the dsee info once from the node that sent dseep
LogPrintf("dseep - Asking source node for missing entry %s\n", vin.ToString().c_str());
//pfrom->PushMessage("dseg", vin);
connman.PushMessage(pfrom, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "dseg", vin));
int64_t askAgain = GetTime() + MASTERNODE_MIN_DSEEP_SECONDS;
mWeAskedForMasternodeListEntry[vin.prevout] = askAgain;
} else if (strCommand == "mvote") { //Masternode Vote
CTxIn vin;
vector<unsigned char> vchSig;
int nVote;
vRecv >> vin >> vchSig >> nVote;
// see if we have this Masternode
CMasternode* pmn = this->Find(vin);
if(pmn != NULL)
{
if((GetAdjustedTime() - pmn->lastVote) > (60*60))
{
std::string strMessage = vin.ToString() + boost::lexical_cast<std::string>(nVote);
std::string errorMessage = "";
if(!darkSendSigner.VerifyMessage(pmn->pubkey2, vchSig, strMessage, errorMessage))
{
LogPrintf("mvote - Got bad Masternode address signature %s \n", vin.ToString().c_str());
return;
}
pmn->nVote = nVote;
pmn->lastVote = GetAdjustedTime();
//send to all peers
/*LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
pnode->PushMessage("mvote", vin, vchSig, nVote);*/
connman.ForEachNode([&connman, &vin, &vchSig, &nVote](CNode* pnode)
{
connman.PushMessage(pnode, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "mvote", vin, vchSig, nVote));
});
}
return;
}
} else if (strCommand == "dseg") { //Get Masternode list or specific entry
CTxIn vin;
vRecv >> vin;
if(vin == CTxIn()) { //only should ask for this once
//local network
if(!pfrom->addr.IsRFC1918())
{
std::map<CNetAddr, int64_t>::iterator i = mAskedUsForMasternodeList.find(pfrom->addr);
if (i != mAskedUsForMasternodeList.end())
{
int64_t t = (*i).second;
if (GetTime() < t) {
Misbehaving(pfrom->GetId(), 34);
LogPrintf("dseg - peer already asked me for the list\n");
return;
}
}
int64_t askAgain = GetTime() + MASTERNODES_DSEG_SECONDS;
mAskedUsForMasternodeList[pfrom->addr] = askAgain;
}
} //else, asking for a specific node which is ok
int count = this->size();
int i = 0;
BOOST_FOREACH(CMasternode& mn, vMasternodes) {
if(mn.addr.IsRFC1918()) continue; //local network
if(mn.IsEnabled())
{
if(fDebug) LogPrintf("dseg - Sending Masternode entry - %s \n", mn.addr.ToString().c_str());
if(vin == CTxIn()){
//pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.sigTime, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion, mn.donationAddress, mn.donationPercentage);
connman.PushMessage(pfrom, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "dsee", mn.vin, mn.addr, mn.sig, mn.sigTime, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion, *(CScriptBase*)(&mn.donationAddress), mn.donationPercentage));
} else if (vin == mn.vin) {
//pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.sigTime, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion, mn.donationAddress, mn.donationPercentage);
connman.PushMessage(pfrom, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "dsee", mn.vin, mn.addr, mn.sig, mn.sigTime, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion, *(CScriptBase*)(&mn.donationAddress), mn.donationPercentage));
LogPrintf("dseg - Sent 1 Masternode entries to %s\n", pfrom->addr.ToString().c_str());
return;
}
i++;
}
}
LogPrintf("dseg - Sent %d Masternode entries to %s\n", i, pfrom->addr.ToString().c_str());
}
}
void CMasternodeMan::RelayMasternodeEntry(const CTxIn vin, const CService addr, const std::vector<unsigned char> vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion, CScript donationAddress, int donationPercentage, CConnman& connman)
{
/*LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
pnode->PushMessage("dsee", vin, addr, vchSig, nNow, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, donationAddress, donationPercentage);
*/
connman.ForEachNode([&connman, &vin, &addr, &vchSig, &nNow, &pubkey, &pubkey2, &count, ¤t, &lastUpdated, &protocolVersion, &donationAddress, &donationPercentage](CNode* pnode)
{
connman.PushMessage(pnode, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "dsee", vin, addr, vchSig, nNow, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, *(CScriptBase*)(&donationAddress), donationPercentage));
});
}
void CMasternodeMan::RelayMasternodeEntryPing(const CTxIn vin, const std::vector<unsigned char> vchSig, const int64_t nNow, const bool stop, CConnman& connman)
{
/*LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
pnode->PushMessage("dseep", vin, vchSig, nNow, stop);*/
connman.ForEachNode([&connman, &vin, &vchSig, &nNow, &stop](CNode* pnode)
{
connman.PushMessage(pnode, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "dseep", vin, vchSig, nNow, stop));
});
}
void CMasternodeMan::RelayNormalMasternodeEntry(const CTxIn vin, const CService addr, const std::vector<unsigned char> vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion, CScript donationAddress, int donationPercentage)
{
/*LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
pnode->PushMessage("dsee", vin, addr, vchSig, nNow, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, donationAddress, donationPercentage);
*/
g_connman->ForEachNode([&vin, &addr, &vchSig, &nNow, &pubkey, &pubkey2, &count, ¤t, &lastUpdated, &protocolVersion, &donationAddress, &donationPercentage](CNode* pnode)
{
g_connman->PushMessage(pnode, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "dsee", vin, addr, vchSig, nNow, pubkey, pubkey2, count, current, lastUpdated, protocolVersion, *(CScriptBase*)(&donationAddress), donationPercentage));
});
}
void CMasternodeMan::RelayNormalMasternodeEntryPing(const CTxIn vin, const std::vector<unsigned char> vchSig, const int64_t nNow, const bool stop)
{
/*LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
pnode->PushMessage("dseep", vin, vchSig, nNow, stop);*/
g_connman->ForEachNode([&vin, &vchSig, &nNow, &stop](CNode* pnode)
{
g_connman->PushMessage(pnode, CNetMsgMaker(PROTOCOL_VERSION).Make(SERIALIZE_TRANSACTION_NO_WITNESS, "dseep", vin, vchSig, nNow, stop));
});
}
void CMasternodeMan::Remove(CTxIn vin)
{
LOCK(cs);//todo++ define own LOCK
vector<CMasternode>::iterator it = vMasternodes.begin();
while(it != vMasternodes.end()){
if((*it).vin == vin){
if(fDebug) LogPrintf("CMasternodeMan: Removing Masternode %s - %i now\n", (*it).addr.ToString().c_str(), size() - 1);
vMasternodes.erase(it);
break;
}
++it;
}
}
std::string CMasternodeMan::ToString() const
{
std::ostringstream info;
info << "Masternodes: " << (int)vMasternodes.size() <<
", peers who asked us for Masternode list: " << (int)mAskedUsForMasternodeList.size() <<
", peers we asked for Masternode list: " << (int)mWeAskedForMasternodeList.size() <<
", entries in Masternode list we asked for: " << (int)mWeAskedForMasternodeListEntry.size() <<
", nDsqCount: " << (int)nDsqCount;
return info.str();
}
|
.thumb
.macro blh to,reg=r4
push {\reg}
ldr \reg,=\to
mov r14,\reg
pop {\reg}
.short 0xF800
.endm
.macro SET_FUNC name, value
.global \name
.type \name, function
.set \name, \value
.endm
.macro SET_DATA name, value
.global \name
.type \name, object
.set \name, \value
.endm
SET_DATA gBattleHitIterator, 0x203A608
.global BattleGenerateHitFix
.type BattleGenerateHitFix, function
@ ORG $2B884
BattleGenerateHitFix:
push {r0-r3, lr}
blh isCombatArt
cmp r0, #1
bne .L1_Nope
.L0_CombatArt:
@ gBattleHitIterator->info |= BATTLE_HIT_ATTR_SURESHOT
ldr r3, =gBattleHitIterator
ldr r3,[r3]
ldr r0,[r3]
ldr r1, =0x4000
orr r0, r1, r0
str r0,[r3]
.L1_Nope:
pop {r0-r3}
pop {r0}
mov lr, r0
@ Vanilla 2BB84
mov r0, #0x13
ldsb r0,[r4, r0]
cmp r0, #0
bne .L2
ldr r1, =0x802B893
bx r1
.L2:
ldsb r0,[r5, r0]
ldr r1, =0x802B88F
bx r1
.align
.ltorg
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r13
push %r15
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x15d03, %r10
nop
nop
add %r13, %r13
mov $0x6162636465666768, %r15
movq %r15, (%r10)
nop
nop
nop
lfence
lea addresses_normal_ht+0xa5d9, %r8
nop
nop
nop
nop
nop
add $33175, %r11
vmovups (%r8), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $1, %xmm6, %r10
nop
nop
nop
xor $20455, %r11
lea addresses_D_ht+0x79d9, %rax
nop
nop
nop
xor %rbx, %rbx
mov (%rax), %r13d
nop
nop
nop
cmp %r11, %r11
lea addresses_UC_ht+0xc9d9, %r13
nop
nop
nop
nop
xor %r11, %r11
movb (%r13), %r10b
add $23319, %r13
lea addresses_UC_ht+0x28d9, %rsi
lea addresses_D_ht+0xeffd, %rdi
nop
nop
nop
nop
cmp $13233, %rax
mov $10, %rcx
rep movsb
inc %r15
lea addresses_WC_ht+0xe235, %r11
nop
cmp %rdi, %rdi
movb $0x61, (%r11)
nop
nop
cmp $8267, %rsi
lea addresses_WC_ht+0xbdd5, %r13
nop
add %r11, %r11
movl $0x61626364, (%r13)
sub %r8, %r8
lea addresses_UC_ht+0x18c83, %rsi
nop
sub $36531, %rbx
and $0xffffffffffffffc0, %rsi
movntdqa (%rsi), %xmm0
vpextrq $1, %xmm0, %rcx
nop
nop
dec %rdi
lea addresses_D_ht+0x1b859, %rsi
lea addresses_WT_ht+0x16bd9, %rdi
clflush (%rdi)
nop
nop
nop
nop
xor $41466, %r8
mov $1, %rcx
rep movsq
nop
add $13338, %r10
lea addresses_WC_ht+0x10d15, %r11
nop
nop
nop
nop
dec %r8
movb (%r11), %bl
nop
nop
nop
dec %r11
lea addresses_UC_ht+0xf161, %r15
nop
nop
nop
nop
nop
xor $65355, %rax
mov (%r15), %rdi
nop
nop
nop
nop
cmp $21121, %rdi
lea addresses_A_ht+0x8fb7, %r8
clflush (%r8)
nop
nop
sub $14189, %r15
mov $0x6162636465666768, %rcx
movq %rcx, %xmm3
vmovups %ymm3, (%r8)
nop
nop
nop
nop
nop
cmp %rdi, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r15
pop %r13
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r9
push %rcx
push %rsi
// Faulty Load
lea addresses_A+0x39d9, %r13
nop
nop
nop
nop
lfence
movb (%r13), %r11b
lea oracles, %r13
and $0xff, %r11
shlq $12, %r11
mov (%r13,%r11,1), %r11
pop %rsi
pop %rcx
pop %r9
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 8}}
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 10}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_UC_ht'}, 'dst': {'same': True, 'congruent': 2, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 2}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 0}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
{'35': 21829}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
;
; Page the graphics bank in/out - used by all gfx functions
; Doesn't really page on the MSX.
;
;
; $Id: swapgfxbk.asm,v 1.5 2015/01/19 01:32:49 pauloscustodio Exp $
;
PUBLIC swapgfxbk
EXTERN pixeladdress
PUBLIC swapgfxbk1
.swapgfxbk
di
ret
.swapgfxbk1
ei
ret
|
54_Header:
sHeaderInit ; Z80 offset is $C59D
sHeaderPatch 54_Patches
sHeaderTick $01
sHeaderCh $02
sHeaderSFX $80, $02, 54_FM3, $00, $00
sHeaderSFX $80, $04, 54_FM4, $02, $00
54_FM4:
ssDetune $90
54_FM3:
sPatFM $00
dc.b nEb1, $7F, sHold
sJump 54_FM3
dc.b $F2 ; Unused
54_Patches:
; Patch $00
; $2F
; $32, $04, $02, $34, $08, $08, $08, $08
; $00, $00, $00, $00, $00, $00, $00, $00
; $0F, $0F, $0F, $0F, $80, $80, $80, $80
spAlgorithm $07
spFeedback $05
spDetune $03, $00, $00, $03
spMultiple $02, $02, $04, $04
spRateScale $00, $00, $00, $00
spAttackRt $08, $08, $08, $08
spAmpMod $00, $00, $00, $00
spSustainRt $00, $00, $00, $00
spSustainLv $00, $00, $00, $00
spDecayRt $00, $00, $00, $00
spReleaseRt $0F, $0F, $0F, $0F
spTotalLv $00, $00, $00, $00
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/basics/Log.h>
#include <ripple/basics/StringUtilities.h>
#include <ripple/protocol/jss.h>
#include <peersafe/protocol/STMap256.h>
namespace ripple {
//STMap256::STMap256(SerialIter& sit, SField const& name)
// : STBase(name)
//{
// Blob data = sit.getVL();
// auto const count = data.size() / (256 / 8) / 2;
// Blob::iterator begin = data.begin();
// unsigned int uStart = 0;
// for (unsigned int i = 0; i != count; i++)
// {
// unsigned int uKeyEnd = uStart + (256 / 8);
// unsigned int uValueEnd = uStart + (256 / 8) * 2;
// // This next line could be optimized to construct a default
// // uint256 in the map and then copy into it
// mValue.insert(std::make_pair(uint256(Blob(begin + uStart, begin + uKeyEnd)),
// uint256(Blob(begin + uKeyEnd, begin + uValueEnd))));
// uStart = uValueEnd;
// }
//}
//void
// STMap256::add(Serializer& s) const
//{
// assert(fName->isBinary());
// assert(fName->fieldType == STI_MAP256);
// for (auto iter = mValue.begin(); iter != mValue.end(); iter++)
// {
// s.add256(iter->first);
// s.add256(iter->second);
// }
//}
//bool
// STMap256::isEquivalent(const STBase& t) const
//{
// const STMap256* v = dynamic_cast<const STMap256*> (&t);
// return v && (mValue == v->mValue);
//}
//Json::Value
// STMap256::getJson(int) const
//{
// Json::Value ret(Json::objectValue);
// for (auto iter = mValue.begin(); iter != mValue.end(); iter++)
// {
// ret[to_string(iter->first)] = to_string(iter->second);
// }
// return ret;
//}
} // ripple
|
#ifndef CAFFE_LIBDNN_LIBDNN_CONV_HPP_
#define CAFFE_LIBDNN_LIBDNN_CONV_HPP_
#ifdef USE_LIBDNN
#include "caffe/definitions.hpp"
#include "caffe/common.hpp"
#include "caffe/quantizer.hpp"
#include "caffe/libdnn/libdnn.hpp"
#include "caffe/libdnn/libdnn_tuner.hpp"
namespace caffe {
typedef enum {
// Stack the batch update into one GEMM block
// (deterministic, 1 kernel call)
// Serializes the batch and may therefore under use
// the GPUs compute units.
LIBDNN_CONVOLUTION_WG_ALGO_DIRECT = 0,
// Use multiple GEMM blocks in parallel and update weights atomically
// (non deterministic, 1 kernel call, not supported on all devices)
// Parallelizes the batch and has therefore higher GPU usage.
LIBDNN_CONVOLUTION_WG_ALGO_ATOMIC = 1,
// Use multiple GEMM blocks and an intermediate buffer
// to reduce weight updates
// (deterministic, >= 2 kernel calls)
// Parallelizes the batch and has therefore higher GPU usage.
// NOT IMPLEMENTED YET
LIBDNN_CONVOLUTION_WG_ALGO_REDUCTION = 2
} libdnnConvolutionWeightAlgo_t;
typedef enum {
// Transform data before GEMM (load, im2col, gemm, store)
// This method is suitable for convolutions with similar
// spatial input == output sizes, but can become inefficient
// if input >> output (with large strides and kernels).
LIBDNN_CONVOLUTION_BW_ALGO_IM2COL = 0,
// Transform data after GEMM (load, gemm, col2im, store)
// Sometimes faster than im2col method, but uses
// atomic operations and is not deterministic.
LIBDNN_CONVOLUTION_BW_ALGO_COL2IM_ATOMIC = 1
} libdnnConvolutionBackwardAlgo_t;
struct LibDNNConvConfig {
LibDNNConvConfig() :
in_shape(3, 1),
out_shape(3, 1),
kernel(1, 1),
pad(0, 0),
stride(1, 1),
dilation(1, 1)
{}
Device* dev_ptr = nullptr;
vector<int_tp> in_shape;
vector<int_tp> out_shape;
vector<int_tp> kernel;
vector<int_tp> pad;
vector<int_tp> stride;
vector<int_tp> dilation;
int_tp group = 1;
bool bias_term = false;
bool fast_unsafe_math = false;
bool weights_backward = true;
bool bias_backward = true;
bool phase_test = false;
libdnnConvolutionWeightAlgo_t wgalgo =
LIBDNN_CONVOLUTION_WG_ALGO_ATOMIC;
libdnnConvolutionBackwardAlgo_t bwalgo =
LIBDNN_CONVOLUTION_BW_ALGO_COL2IM_ATOMIC;
};
template<typename MItype, typename MOtype>
class LibDNNConv : public LibDNN<MItype, MOtype> {
public:
explicit LibDNNConv(LibDNNConvConfig config);
void Forward(vptr<const MItype> bottom_data, vptr<const MItype> weight,
const MItype bias_mult, vptr<const MItype> bias, vptr<MOtype> top_data,
int_tp batch_size,
const QuantizerValues* const bottom_quant = nullptr,
const QuantizerValues* const weight_quant = nullptr,
const QuantizerValues* const bias_mult_quant = nullptr,
const QuantizerValues* const bias_quant = nullptr,
const QuantizerValues* const top_quant = nullptr);
void Backward(bool prop_down_data, bool prop_down_weights,
vptr<const MOtype> top_data, vptr<const MOtype> top_diff,
vptr<const MItype> weight, vptr<MItype> weight_diff,
const MItype bias_mult, vptr<const MItype> bias,
vptr<MItype> bias_diff, vptr<const MItype> bottom_data,
vptr<MItype> bottom_diff, int_tp batch_size);
void BackwardDropout(bool prop_down_data, bool prop_down_weights,
vptr<const MOtype> top_data, vptr<const MOtype> top_diff,
vptr<const MItype> weight, vptr<MItype> weight_diff,
const MItype bias_mult, vptr<const MItype> bias,
vptr<MItype> bias_diff, vptr<const MItype> bottom_data,
vptr<MItype> bottom_diff, int_tp batch_size,
vptr<const uint_tp> mask, const uint_tp uint_thres, const float scale);
void Tune(vptr<MOtype> top_data, vptr<MOtype> top_diff,
vptr<MItype> weight, vptr<MItype> weight_diff,
const MItype bias_mult, vptr<MItype> bias, vptr<MItype> bias_diff,
vptr<MItype> bottom_data, vptr<MItype> bottom_diff,
int_tp batch_size);
const LibDNNConvConfig get_config();
protected:
explicit LibDNNConv(Device* dev_ptr);
virtual void GenerateKernels();
virtual bool CompileKernels();
string string_identifier();
string generate_fw_defs();
string generate_bw_defs();
string generate_wg_defs();
string generate_fw_kernels(string name);
string generate_bw_kernels(string name);
string generate_bw_dropout_kernels(string name);
string generate_wg_kernels(string name);
// Autotuners
shared_ptr<LibDNNTuner> fw_tuner_;
shared_ptr<LibDNNTuner> bw_tuner_;
shared_ptr<LibDNNTuner> wg_tuner_;
// Forward GEMM sizes
int_tp M_FW_;
int_tp MG_FW_;
int_tp N_FW_;
int_tp K_FW_;
int_tp KG_FW_;
// Backward GEMM sizes
int_tp M_BW_;
int_tp MG_BW_;
int_tp N_BW_;
int_tp K_BW_;
int_tp KG_BW_;
// Weight GEMM sizes
int_tp M_WG_;
int_tp MG_WG_;
int_tp N_WG_;
int_tp NG_WG_;
int_tp K_WG_;
// Convolution parameters
int_tp num_axes_;
int_tp fmaps_in_;
int_tp fmaps_out_;
int_tp group_;
vector<int_tp> pad_;
vector<int_tp> stride_;
vector<int_tp> dilation_;
vector<int_tp> kernel_shape_;
vector<int_tp> im_in_shape_;
vector<int_tp> im_out_shape_;
// Compile and method flags
bool weights_backward_;
bool bias_backward_;
bool bias_term_;
bool skip_range_check_;
libdnnConvolutionWeightAlgo_t wgalgo_;
libdnnConvolutionBackwardAlgo_t bwalgo_;
private:
LibDNNConvConfig config_;
};
struct LibDNNDeconvConfig {
LibDNNDeconvConfig() :
in_shape(3, 1),
out_shape(3, 1),
kernel(1, 1),
pad(0, 0),
stride(1, 1),
dilation(1, 1)
{}
Device* dev_ptr = nullptr;
vector<int_tp> in_shape;
vector<int_tp> out_shape;
vector<int_tp> kernel;
vector<int_tp> pad;
vector<int_tp> stride;
vector<int_tp> dilation;
int_tp group = 1;
bool bias_term = false;
bool fast_unsafe_math = false;
bool weights_backward = true;
bool bias_backward = true;
libdnnConvolutionWeightAlgo_t wgalgo =
LIBDNN_CONVOLUTION_WG_ALGO_ATOMIC;
libdnnConvolutionBackwardAlgo_t bwalgo =
LIBDNN_CONVOLUTION_BW_ALGO_COL2IM_ATOMIC;
};
template<typename MItype, typename MOtype>
class LibDNNDeconv : public LibDNNConv<MItype, MOtype> {
public:
explicit LibDNNDeconv(LibDNNDeconvConfig config);
void Forward(vptr<const MItype> bottom_data, vptr<const MItype> weight,
const MItype bias_mult, vptr<const MItype> bias,
vptr<MOtype> top_data, int_tp batch_size);
void Backward(bool prop_down_data, bool prop_down_weights,
vptr<const MOtype> top_data, vptr<const MOtype> top_diff,
vptr<const MItype> weight, vptr<MItype> weight_diff,
const MItype bias_mult, vptr<const MItype> bias,
vptr<MItype> bias_diff, vptr<const MItype> bottom_data,
vptr<MItype> bottom_diff, int_tp batch_size);
void Tune(vptr<MOtype> top_data, vptr<MOtype> top_diff,
vptr<MItype> weight, vptr<MItype> weight_diff,
const MItype bias_mult,
vptr<MItype> bias, vptr<MItype> bias_diff,
vptr<MItype> bottom_data, vptr<MItype> bottom_diff,
int_tp batch_size);
const LibDNNDeconvConfig get_config();
protected:
virtual void GenerateKernels();
virtual bool CompileKernels();
string string_identifier();
string generate_fw_defs();
string generate_bw_defs();
string generate_wg_defs();
string generate_fw_kernels(string name);
string generate_bw_kernels(string name);
string generate_wg_kernels(string name);
// Bias GEMV sizes
int_tp M_BG_;
int_tp MG_BG_;
int_tp N_BG_;
int_tp NG_BG_;
int_tp K_BG_;
private:
LibDNNDeconvConfig config_;
};
#ifdef USE_INTEL_SPATIAL
template<typename MItype, typename MOtype>
class LibDNNConvSpatial : public LibDNNConv<MItype, MOtype> {
public:
explicit LibDNNConvSpatial(LibDNNConvConfig config);
void Forward(vptr<const MItype> bottom_data, vptr<const MItype> weight,
vptr<const MItype> bias,
vptr<MOtype> top_data, int_tp batch_size);
void ForwardBenchmark(vptr<const MItype> bottom_data, vptr<const MItype> weight,
vptr<const MItype> bias,
vptr<MOtype> top_data, int_tp batch_size);
void Backward(bool prop_down_data, bool prop_down_weights,
vptr<const MOtype> top_data, const vptr<MOtype> top_diff,
vptr<const MItype> weight, MItype* weight_diff,
vptr<const MItype> bias, vptr<MItype> bias_diff,
vptr<const MItype> bottom_data, vptr<MItype> bottom_diff,
int_tp batch_size);
void Tune(vptr<MOtype> top_data, vptr<MOtype> top_diff,
vptr<const MItype> weight, MItype* weight_diff,
vptr<const MItype> bias, vptr<MItype> bias_diff,
vptr<const MItype> bottom_data, vptr<MItype> bottom_diff,
int_tp batch_size);
protected:
void GenerateKernels();
string string_identifier();
string generate_fw_defs();
string generate_fw_kernels(int_tp kernelType,
int_tp blockM,
int_tp blockK,
int_tp blockN);
private:
struct kernelConfig {
string kernelName;
float executionTime;
size_t local_work_size[3];
size_t global_work_size[3];
int_tp workItem_output[3];
bool verified;
bool autoTune;
bool tested;
bool swizzle_weights;
bool use_null_local;
int_tp kernelType;
kernelConfig() {
}
kernelConfig(string name, size_t* global_size, size_t* local_size,
int_tp* workItem,
bool tune, bool swizzle, bool null_local,
int_tp type = 0) {
kernelName = name;
for (int_tp X = 0; X < 3; X++) {
local_work_size[X] = local_size[X];
global_work_size[X] = global_size[X];
workItem_output[X] = workItem[X];
}
autoTune = tune;
swizzle_weights = swizzle;
use_null_local = null_local;
verified = false;
tested = false;
kernelType = type;
}
};
void GenerateHelperKernels();
viennacl::ocl::program compile_fw_kernel();
void calculate_verify_data(const MItype* bottom,
const MItype* w,
vptr<const MItype> bias,
MItype* verify_data);
virtual void setup_convolution(const MItype *bottom,
const MItype *top,
const MItype *verify_blob);
virtual void create_convolution_kernel(const MItype *bottom,
const MItype *top,
int_tp kernelType,
int_tp blockWidth,
int_tp blockHeight,
int_tp blockDepth);
virtual bool setup_IDLF(const MItype *bottom,
const MItype *top, int_tp blockWidth,
int_tp blockHeight,
int_tp blockDepth);
virtual bool create_basic_kernel(const MItype *bottom,
const MItype *top,
int_tp blockWidth,
int_tp blockHeight,
int_tp blockDepth);
virtual bool create_gemm_like_conv_kernel(const MItype *bottom,
const MItype *top,
int_tp blockWidth,
int_tp blockHeight,
int_tp blockDepth);
virtual cl_int convolve(const MItype *bottom,
const MItype *top, int_tp index,
int_tp numImages,
kernelConfig* config);
virtual float timed_convolve(const MItype *bottom,
const MItype *top, int_tp index,
int_tp numImages,
kernelConfig* config);
virtual bool verify_result(const MItype *bottom,
const MItype *top, int_tp index,
int_tp numImages, const MItype *verify_blob,
kernelConfig* config);
virtual bool tune_local_size(const MItype *bottom,
const MItype *top, kernelConfig*);
virtual void swizzleWeights(const MItype *bottom,
const MItype *top,
int_tp swizzle_factor,
bool interleave = false);
virtual void generate_key();
virtual string generate_specific_key(int_tp type, int_tp blockWidth,
int_tp blockHeight,
int_tp blockDepth);
virtual void calculate_global_size(int_tp batch, int_tp* workItemOutput,
size_t* localSizes, size_t* globalSizes);
void load_cached_kernels(const MItype *bottom,
const MItype *top);
void SetUp(const MItype *bottom,
const MItype *top, caffe::Backend backend);
void setBufferKernelArg(const MItype *bottom,
const MItype *top,
viennacl::ocl::kernel *cl_kernel,
const cl_uint &argIdx,
viennacl::ocl::context *ctx,
cl_mem buffer, size_t offset,
size_t size, bool readOnly,
bool preserved);
void cleanTmpSubBuffers(const MItype *bottom,
const MItype *top);
std::map<std::tuple<cl_mem, size_t, size_t>, cl_mem> subBufferMap;
vector<cl_mem> tmpSubBuffers;
vptr<const MItype> bottom_data_;
vptr<MOtype> top_data_;
vptr<MItype> col_data_;
vptr<const MItype> weight_;
uint64_t prev_weight_seq_id_;
vptr<MItype> swizzled_weights;
int_tp weight_offset;
int_tp col_offset;
int_tp top_offset;
int_tp output_h_, output_w_;
int_tp padded_height_, padded_width_;
vptr<const MItype> bias_;
int_tp bias_offset_;
int_tp bottom_index_;
int_tp height_;
int_tp width_;
/// M_ is the channel dimension of the output for a single group, which is the
/// leading dimension of the filter matrix.
/// K_ is the dimension of an unrolled input for a single group, which is the
/// leading dimension of the data matrix.
/// N_ is the spatial dimension of the output, the H X W, which are the last
/// dimensions of the data and filter matrices.
bool tuned_;
bool try_cache_;
// if need_padding_ is true, we need to pad the input image,
// otherwise, we don't need to pad it then the convolution kernel
// need to handle it.
bool need_padding_;
string key_;
string short_key_;
string kernel_name_;
stringstream cache_path_;
MItype *swizzled_weights_;
int_tp kernel_index_;
int_tp kernel_uid_;
vector<kernelConfig*> kernelQueue;
kernelConfig* bestKernelConfig;
// derived from BaseConvolutionLayer
int_tp bottom_dim_;
int_tp top_dim_;
int_tp num_;
int_tp out_spatial_dim_;
bool is_1x1_;
int_tp kernel_dim_;
int_tp in_spatial_dim_;
int_tp kernelType_;
int_tp blockM_;
int_tp blockK_;
int_tp blockN_;
string options_;
LibDNNConvConfig config_;
shared_ptr<LibDNNConv<MItype, MOtype> > libdnn_conv_;
};
#endif
} // namespace caffe
#endif // USE_LIBDNN
#endif // INCLUDE_CAFFE_LIBDNN_LIBDNN_CONV_HPP_
|
; A178205: a(n) = a(n-1) + 10*a(n-3) for n > 2; a(0) = a(1) = a(2) = 1.
; Submitted by Jon Maiga
; 1,1,1,11,21,31,141,351,661,2071,5581,12191,32901,88711,210621,539631,1426741,3532951,8929261,23196671,58526181,147818791,379785501,965047311,2443235221,6241090231,15891563341,40323915551,102734817861,261650451271,664889606781,1692237785391,4308742298101,10957638365911,27880016219821,70967439200831,180543822859941,459343985058151,1169018377066461,2974456605665871,7567896456247381,19258080226911991,49002646283570701,124681610846044511,317262413115164421,807288875950871431,2054104984411316541
lpb $0
sub $0,1
mul $1,2
mov $3,$1
mov $1,$4
mul $3,5
add $2,$3
mov $4,$2
sub $4,$3
add $4,1
lpe
mov $0,$2
add $0,1
|
// Copyright (c) 2017 Valve Corporation
// Copyright (c) 2017 LunarG Inc.
//
// 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 <memory>
#include <string>
#include <vector>
#include "test/opt/pass_fixture.h"
#include "test/opt/pass_utils.h"
namespace spvtools {
namespace opt {
namespace {
using InlineTest = PassTest<::testing::Test>;
TEST_F(InlineTest, Simple) {
// #version 140
//
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// return bar.x + bar.y;
// }
//
// void main()
// {
// vec4 color = vec4(foo(BaseColor));
// gl_FragColor = color;
// }
const std::vector<const char*> predefs = {
// clang-format off
"OpCapability Shader",
"%1 = OpExtInstImport \"GLSL.std.450\"",
"OpMemoryModel Logical GLSL450",
"OpEntryPoint Fragment %main \"main\" %BaseColor %gl_FragColor",
"OpExecutionMode %main OriginUpperLeft",
"OpSource GLSL 140",
"OpName %main \"main\"",
"OpName %foo_vf4_ \"foo(vf4;\"",
"OpName %bar \"bar\"",
"OpName %color \"color\"",
"OpName %BaseColor \"BaseColor\"",
"OpName %param \"param\"",
"OpName %gl_FragColor \"gl_FragColor\"",
"%void = OpTypeVoid",
"%10 = OpTypeFunction %void",
"%float = OpTypeFloat 32",
"%v4float = OpTypeVector %float 4",
"%_ptr_Function_v4float = OpTypePointer Function %v4float",
"%14 = OpTypeFunction %float %_ptr_Function_v4float",
"%uint = OpTypeInt 32 0",
"%uint_0 = OpConstant %uint 0",
"%_ptr_Function_float = OpTypePointer Function %float",
"%uint_1 = OpConstant %uint 1",
"%_ptr_Input_v4float = OpTypePointer Input %v4float",
"%BaseColor = OpVariable %_ptr_Input_v4float Input",
"%_ptr_Output_v4float = OpTypePointer Output %v4float",
"%gl_FragColor = OpVariable %_ptr_Output_v4float Output",
// clang-format on
};
const std::vector<const char*> nonEntryFuncs = {
// clang-format off
"%foo_vf4_ = OpFunction %float None %14",
"%bar = OpFunctionParameter %_ptr_Function_v4float",
"%26 = OpLabel",
"%27 = OpAccessChain %_ptr_Function_float %bar %uint_0",
"%28 = OpLoad %float %27",
"%29 = OpAccessChain %_ptr_Function_float %bar %uint_1",
"%30 = OpLoad %float %29",
"%31 = OpFAdd %float %28 %30",
"OpReturnValue %31",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> before = {
// clang-format off
"%main = OpFunction %void None %10",
"%21 = OpLabel",
"%color = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%22 = OpLoad %v4float %BaseColor",
"OpStore %param %22",
"%23 = OpFunctionCall %float %foo_vf4_ %param",
"%24 = OpCompositeConstruct %v4float %23 %23 %23 %23",
"OpStore %color %24",
"%25 = OpLoad %v4float %color",
"OpStore %gl_FragColor %25",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> after = {
// clang-format off
"%main = OpFunction %void None %10",
"%21 = OpLabel",
"%32 = OpVariable %_ptr_Function_float Function",
"%color = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%22 = OpLoad %v4float %BaseColor",
"OpStore %param %22",
"%34 = OpAccessChain %_ptr_Function_float %param %uint_0",
"%35 = OpLoad %float %34",
"%36 = OpAccessChain %_ptr_Function_float %param %uint_1",
"%37 = OpLoad %float %36",
"%38 = OpFAdd %float %35 %37",
"OpStore %32 %38",
"%23 = OpLoad %float %32",
"%24 = OpCompositeConstruct %v4float %23 %23 %23 %23",
"OpStore %color %24",
"%25 = OpLoad %v4float %color",
"OpStore %gl_FragColor %25",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
SinglePassRunAndCheck<InlineExhaustivePass>(
JoinAllInsts(Concat(Concat(predefs, before), nonEntryFuncs)),
JoinAllInsts(Concat(Concat(predefs, after), nonEntryFuncs)),
/* skip_nop = */ false, /* do_validate = */ true);
}
TEST_F(InlineTest, Nested) {
// #version 140
//
// in vec4 BaseColor;
//
// float foo2(float f, float f2)
// {
// return f * f2;
// }
//
// float foo(vec4 bar)
// {
// return foo2(bar.x + bar.y, bar.z);
// }
//
// void main()
// {
// vec4 color = vec4(foo(BaseColor));
// gl_FragColor = color;
// }
const std::vector<const char*> predefs = {
// clang-format off
"OpCapability Shader",
"%1 = OpExtInstImport \"GLSL.std.450\"",
"OpMemoryModel Logical GLSL450",
"OpEntryPoint Fragment %main \"main\" %BaseColor %gl_FragColor",
"OpExecutionMode %main OriginUpperLeft",
"OpSource GLSL 140",
"OpName %main \"main\"",
"OpName %foo2_f1_f1_ \"foo2(f1;f1;\"",
"OpName %f \"f\"",
"OpName %f2 \"f2\"",
"OpName %foo_vf4_ \"foo(vf4;\"",
"OpName %bar \"bar\"",
"OpName %param \"param\"",
"OpName %param_0 \"param\"",
"OpName %color \"color\"",
"OpName %BaseColor \"BaseColor\"",
"OpName %param_1 \"param\"",
"OpName %gl_FragColor \"gl_FragColor\"",
"%void = OpTypeVoid",
"%15 = OpTypeFunction %void",
"%float = OpTypeFloat 32",
"%_ptr_Function_float = OpTypePointer Function %float",
"%18 = OpTypeFunction %float %_ptr_Function_float %_ptr_Function_float",
"%v4float = OpTypeVector %float 4",
"%_ptr_Function_v4float = OpTypePointer Function %v4float",
"%21 = OpTypeFunction %float %_ptr_Function_v4float",
"%uint = OpTypeInt 32 0",
"%uint_0 = OpConstant %uint 0",
"%uint_1 = OpConstant %uint 1",
"%uint_2 = OpConstant %uint 2",
"%_ptr_Input_v4float = OpTypePointer Input %v4float",
"%BaseColor = OpVariable %_ptr_Input_v4float Input",
"%_ptr_Output_v4float = OpTypePointer Output %v4float",
"%gl_FragColor = OpVariable %_ptr_Output_v4float Output",
// clang-format on
};
const std::vector<const char*> nonEntryFuncs = {
// clang-format off
"%foo2_f1_f1_ = OpFunction %float None %18",
"%f = OpFunctionParameter %_ptr_Function_float",
"%f2 = OpFunctionParameter %_ptr_Function_float",
"%33 = OpLabel",
"%34 = OpLoad %float %f",
"%35 = OpLoad %float %f2",
"%36 = OpFMul %float %34 %35",
"OpReturnValue %36",
"OpFunctionEnd",
"%foo_vf4_ = OpFunction %float None %21",
"%bar = OpFunctionParameter %_ptr_Function_v4float",
"%37 = OpLabel",
"%param = OpVariable %_ptr_Function_float Function",
"%param_0 = OpVariable %_ptr_Function_float Function",
"%38 = OpAccessChain %_ptr_Function_float %bar %uint_0",
"%39 = OpLoad %float %38",
"%40 = OpAccessChain %_ptr_Function_float %bar %uint_1",
"%41 = OpLoad %float %40",
"%42 = OpFAdd %float %39 %41",
"OpStore %param %42",
"%43 = OpAccessChain %_ptr_Function_float %bar %uint_2",
"%44 = OpLoad %float %43",
"OpStore %param_0 %44",
"%45 = OpFunctionCall %float %foo2_f1_f1_ %param %param_0",
"OpReturnValue %45",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> before = {
// clang-format off
"%main = OpFunction %void None %15",
"%28 = OpLabel",
"%color = OpVariable %_ptr_Function_v4float Function",
"%param_1 = OpVariable %_ptr_Function_v4float Function",
"%29 = OpLoad %v4float %BaseColor",
"OpStore %param_1 %29",
"%30 = OpFunctionCall %float %foo_vf4_ %param_1",
"%31 = OpCompositeConstruct %v4float %30 %30 %30 %30",
"OpStore %color %31",
"%32 = OpLoad %v4float %color",
"OpStore %gl_FragColor %32",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> after = {
// clang-format off
"%main = OpFunction %void None %15",
"%28 = OpLabel",
"%58 = OpVariable %_ptr_Function_float Function",
"%46 = OpVariable %_ptr_Function_float Function",
"%47 = OpVariable %_ptr_Function_float Function",
"%48 = OpVariable %_ptr_Function_float Function",
"%color = OpVariable %_ptr_Function_v4float Function",
"%param_1 = OpVariable %_ptr_Function_v4float Function",
"%29 = OpLoad %v4float %BaseColor",
"OpStore %param_1 %29",
"%50 = OpAccessChain %_ptr_Function_float %param_1 %uint_0",
"%51 = OpLoad %float %50",
"%52 = OpAccessChain %_ptr_Function_float %param_1 %uint_1",
"%53 = OpLoad %float %52",
"%54 = OpFAdd %float %51 %53",
"OpStore %46 %54",
"%55 = OpAccessChain %_ptr_Function_float %param_1 %uint_2",
"%56 = OpLoad %float %55",
"OpStore %47 %56",
"%60 = OpLoad %float %46",
"%61 = OpLoad %float %47",
"%62 = OpFMul %float %60 %61",
"OpStore %58 %62",
"%57 = OpLoad %float %58",
"OpStore %48 %57",
"%30 = OpLoad %float %48",
"%31 = OpCompositeConstruct %v4float %30 %30 %30 %30",
"OpStore %color %31",
"%32 = OpLoad %v4float %color",
"OpStore %gl_FragColor %32",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
SinglePassRunAndCheck<InlineExhaustivePass>(
JoinAllInsts(Concat(Concat(predefs, before), nonEntryFuncs)),
JoinAllInsts(Concat(Concat(predefs, after), nonEntryFuncs)),
/* skip_nop = */ false, /* do_validate = */ true);
}
TEST_F(InlineTest, InOutParameter) {
// #version 400
//
// in vec4 Basecolor;
//
// void foo(inout vec4 bar)
// {
// bar.z = bar.x + bar.y;
// }
//
// void main()
// {
// vec4 b = Basecolor;
// foo(b);
// vec4 color = vec4(b.z);
// gl_FragColor = color;
// }
const std::vector<const char*> predefs = {
// clang-format off
"OpCapability Shader",
"%1 = OpExtInstImport \"GLSL.std.450\"",
"OpMemoryModel Logical GLSL450",
"OpEntryPoint Fragment %main \"main\" %Basecolor %gl_FragColor",
"OpExecutionMode %main OriginUpperLeft",
"OpSource GLSL 400",
"OpName %main \"main\"",
"OpName %foo_vf4_ \"foo(vf4;\"",
"OpName %bar \"bar\"",
"OpName %b \"b\"",
"OpName %Basecolor \"Basecolor\"",
"OpName %param \"param\"",
"OpName %color \"color\"",
"OpName %gl_FragColor \"gl_FragColor\"",
"%void = OpTypeVoid",
"%11 = OpTypeFunction %void",
"%float = OpTypeFloat 32",
"%v4float = OpTypeVector %float 4",
"%_ptr_Function_v4float = OpTypePointer Function %v4float",
"%15 = OpTypeFunction %void %_ptr_Function_v4float",
"%uint = OpTypeInt 32 0",
"%uint_0 = OpConstant %uint 0",
"%_ptr_Function_float = OpTypePointer Function %float",
"%uint_1 = OpConstant %uint 1",
"%uint_2 = OpConstant %uint 2",
"%_ptr_Input_v4float = OpTypePointer Input %v4float",
"%Basecolor = OpVariable %_ptr_Input_v4float Input",
"%_ptr_Output_v4float = OpTypePointer Output %v4float",
"%gl_FragColor = OpVariable %_ptr_Output_v4float Output",
// clang-format on
};
const std::vector<const char*> nonEntryFuncs = {
// clang-format off
"%foo_vf4_ = OpFunction %void None %15",
"%bar = OpFunctionParameter %_ptr_Function_v4float",
"%32 = OpLabel",
"%33 = OpAccessChain %_ptr_Function_float %bar %uint_0",
"%34 = OpLoad %float %33",
"%35 = OpAccessChain %_ptr_Function_float %bar %uint_1",
"%36 = OpLoad %float %35",
"%37 = OpFAdd %float %34 %36",
"%38 = OpAccessChain %_ptr_Function_float %bar %uint_2",
"OpStore %38 %37",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> before = {
// clang-format off
"%main = OpFunction %void None %11",
"%23 = OpLabel",
"%b = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%color = OpVariable %_ptr_Function_v4float Function",
"%24 = OpLoad %v4float %Basecolor",
"OpStore %b %24",
"%25 = OpLoad %v4float %b",
"OpStore %param %25",
"%26 = OpFunctionCall %void %foo_vf4_ %param",
"%27 = OpLoad %v4float %param",
"OpStore %b %27",
"%28 = OpAccessChain %_ptr_Function_float %b %uint_2",
"%29 = OpLoad %float %28",
"%30 = OpCompositeConstruct %v4float %29 %29 %29 %29",
"OpStore %color %30",
"%31 = OpLoad %v4float %color",
"OpStore %gl_FragColor %31",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> after = {
// clang-format off
"%main = OpFunction %void None %11",
"%23 = OpLabel",
"%b = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%color = OpVariable %_ptr_Function_v4float Function",
"%24 = OpLoad %v4float %Basecolor",
"OpStore %b %24",
"%25 = OpLoad %v4float %b",
"OpStore %param %25",
"%40 = OpAccessChain %_ptr_Function_float %param %uint_0",
"%41 = OpLoad %float %40",
"%42 = OpAccessChain %_ptr_Function_float %param %uint_1",
"%43 = OpLoad %float %42",
"%44 = OpFAdd %float %41 %43",
"%45 = OpAccessChain %_ptr_Function_float %param %uint_2",
"OpStore %45 %44",
"%27 = OpLoad %v4float %param",
"OpStore %b %27",
"%28 = OpAccessChain %_ptr_Function_float %b %uint_2",
"%29 = OpLoad %float %28",
"%30 = OpCompositeConstruct %v4float %29 %29 %29 %29",
"OpStore %color %30",
"%31 = OpLoad %v4float %color",
"OpStore %gl_FragColor %31",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
SinglePassRunAndCheck<InlineExhaustivePass>(
JoinAllInsts(Concat(Concat(predefs, before), nonEntryFuncs)),
JoinAllInsts(Concat(Concat(predefs, after), nonEntryFuncs)),
/* skip_nop = */ false, /* do_validate = */ true);
}
TEST_F(InlineTest, BranchInCallee) {
// #version 140
//
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// float r = bar.x;
// if (r < 0.0)
// r = -r;
// return r;
// }
//
// void main()
// {
// vec4 color = vec4(foo(BaseColor));
//
// gl_FragColor = color;
// }
const std::vector<const char*> predefs = {
// clang-format off
"OpCapability Shader",
"%1 = OpExtInstImport \"GLSL.std.450\"",
"OpMemoryModel Logical GLSL450",
"OpEntryPoint Fragment %main \"main\" %BaseColor %gl_FragColor",
"OpExecutionMode %main OriginUpperLeft",
"OpSource GLSL 140",
"OpName %main \"main\"",
"OpName %foo_vf4_ \"foo(vf4;\"",
"OpName %bar \"bar\"",
"OpName %r \"r\"",
"OpName %color \"color\"",
"OpName %BaseColor \"BaseColor\"",
"OpName %param \"param\"",
"OpName %gl_FragColor \"gl_FragColor\"",
"%void = OpTypeVoid",
"%11 = OpTypeFunction %void",
"%float = OpTypeFloat 32",
"%v4float = OpTypeVector %float 4",
"%_ptr_Function_v4float = OpTypePointer Function %v4float",
"%15 = OpTypeFunction %float %_ptr_Function_v4float",
"%_ptr_Function_float = OpTypePointer Function %float",
"%uint = OpTypeInt 32 0",
"%uint_0 = OpConstant %uint 0",
"%float_0 = OpConstant %float 0",
"%bool = OpTypeBool",
"%_ptr_Input_v4float = OpTypePointer Input %v4float",
"%BaseColor = OpVariable %_ptr_Input_v4float Input",
"%_ptr_Output_v4float = OpTypePointer Output %v4float",
"%gl_FragColor = OpVariable %_ptr_Output_v4float Output",
// clang-format on
};
const std::vector<const char*> nonEntryFuncs = {
// clang-format off
"%foo_vf4_ = OpFunction %float None %15",
"%bar = OpFunctionParameter %_ptr_Function_v4float",
"%28 = OpLabel",
"%r = OpVariable %_ptr_Function_float Function",
"%29 = OpAccessChain %_ptr_Function_float %bar %uint_0",
"%30 = OpLoad %float %29",
"OpStore %r %30",
"%31 = OpLoad %float %r",
"%32 = OpFOrdLessThan %bool %31 %float_0",
"OpSelectionMerge %33 None",
"OpBranchConditional %32 %34 %33",
"%34 = OpLabel",
"%35 = OpLoad %float %r",
"%36 = OpFNegate %float %35",
"OpStore %r %36",
"OpBranch %33",
"%33 = OpLabel",
"%37 = OpLoad %float %r",
"OpReturnValue %37",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> before = {
// clang-format off
"%main = OpFunction %void None %11",
"%23 = OpLabel",
"%color = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%24 = OpLoad %v4float %BaseColor",
"OpStore %param %24",
"%25 = OpFunctionCall %float %foo_vf4_ %param",
"%26 = OpCompositeConstruct %v4float %25 %25 %25 %25",
"OpStore %color %26",
"%27 = OpLoad %v4float %color",
"OpStore %gl_FragColor %27",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> after = {
// clang-format off
"%main = OpFunction %void None %11",
"%23 = OpLabel",
"%38 = OpVariable %_ptr_Function_float Function",
"%39 = OpVariable %_ptr_Function_float Function",
"%color = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%24 = OpLoad %v4float %BaseColor",
"OpStore %param %24",
"%41 = OpAccessChain %_ptr_Function_float %param %uint_0",
"%42 = OpLoad %float %41",
"OpStore %38 %42",
"%43 = OpLoad %float %38",
"%44 = OpFOrdLessThan %bool %43 %float_0",
"OpSelectionMerge %48 None",
"OpBranchConditional %44 %45 %48",
"%45 = OpLabel",
"%46 = OpLoad %float %38",
"%47 = OpFNegate %float %46",
"OpStore %38 %47",
"OpBranch %48",
"%48 = OpLabel",
"%49 = OpLoad %float %38",
"OpStore %39 %49",
"%25 = OpLoad %float %39",
"%26 = OpCompositeConstruct %v4float %25 %25 %25 %25",
"OpStore %color %26",
"%27 = OpLoad %v4float %color",
"OpStore %gl_FragColor %27",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
SinglePassRunAndCheck<InlineExhaustivePass>(
JoinAllInsts(Concat(Concat(predefs, before), nonEntryFuncs)),
JoinAllInsts(Concat(Concat(predefs, after), nonEntryFuncs)),
/* skip_nop = */ false, /* do_validate = */ true);
}
TEST_F(InlineTest, PhiAfterCall) {
// #version 140
//
// in vec4 BaseColor;
//
// float foo(float bar)
// {
// float r = bar;
// if (r < 0.0)
// r = -r;
// return r;
// }
//
// void main()
// {
// vec4 color = BaseColor;
// if (foo(color.x) > 2.0 && foo(color.y) > 2.0)
// color = vec4(0.0);
// gl_FragColor = color;
// }
const std::vector<const char*> predefs = {
// clang-format off
"OpCapability Shader",
"%1 = OpExtInstImport \"GLSL.std.450\"",
"OpMemoryModel Logical GLSL450",
"OpEntryPoint Fragment %main \"main\" %BaseColor %gl_FragColor",
"OpExecutionMode %main OriginUpperLeft",
"OpSource GLSL 140",
"OpName %main \"main\"",
"OpName %foo_f1_ \"foo(f1;\"",
"OpName %bar \"bar\"",
"OpName %r \"r\"",
"OpName %color \"color\"",
"OpName %BaseColor \"BaseColor\"",
"OpName %param \"param\"",
"OpName %param_0 \"param\"",
"OpName %gl_FragColor \"gl_FragColor\"",
"%void = OpTypeVoid",
"%12 = OpTypeFunction %void",
"%float = OpTypeFloat 32",
"%_ptr_Function_float = OpTypePointer Function %float",
"%15 = OpTypeFunction %float %_ptr_Function_float",
"%float_0 = OpConstant %float 0",
"%bool = OpTypeBool",
"%v4float = OpTypeVector %float 4",
"%_ptr_Function_v4float = OpTypePointer Function %v4float",
"%_ptr_Input_v4float = OpTypePointer Input %v4float",
"%BaseColor = OpVariable %_ptr_Input_v4float Input",
"%uint = OpTypeInt 32 0",
"%uint_0 = OpConstant %uint 0",
"%float_2 = OpConstant %float 2",
"%uint_1 = OpConstant %uint 1",
"%25 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0",
"%_ptr_Output_v4float = OpTypePointer Output %v4float",
"%gl_FragColor = OpVariable %_ptr_Output_v4float Output",
// clang-format on
};
const std::vector<const char*> nonEntryFuncs = {
// clang-format off
"%foo_f1_ = OpFunction %float None %15",
"%bar = OpFunctionParameter %_ptr_Function_float",
"%43 = OpLabel",
"%r = OpVariable %_ptr_Function_float Function",
"%44 = OpLoad %float %bar",
"OpStore %r %44",
"%45 = OpLoad %float %r",
"%46 = OpFOrdLessThan %bool %45 %float_0",
"OpSelectionMerge %47 None",
"OpBranchConditional %46 %48 %47",
"%48 = OpLabel",
"%49 = OpLoad %float %r",
"%50 = OpFNegate %float %49",
"OpStore %r %50",
"OpBranch %47",
"%47 = OpLabel",
"%51 = OpLoad %float %r",
"OpReturnValue %51",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> before = {
// clang-format off
"%main = OpFunction %void None %12",
"%27 = OpLabel",
"%color = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_float Function",
"%param_0 = OpVariable %_ptr_Function_float Function",
"%28 = OpLoad %v4float %BaseColor",
"OpStore %color %28",
"%29 = OpAccessChain %_ptr_Function_float %color %uint_0",
"%30 = OpLoad %float %29",
"OpStore %param %30",
"%31 = OpFunctionCall %float %foo_f1_ %param",
"%32 = OpFOrdGreaterThan %bool %31 %float_2",
"OpSelectionMerge %33 None",
"OpBranchConditional %32 %34 %33",
"%34 = OpLabel",
"%35 = OpAccessChain %_ptr_Function_float %color %uint_1",
"%36 = OpLoad %float %35",
"OpStore %param_0 %36",
"%37 = OpFunctionCall %float %foo_f1_ %param_0",
"%38 = OpFOrdGreaterThan %bool %37 %float_2",
"OpBranch %33",
"%33 = OpLabel",
"%39 = OpPhi %bool %32 %27 %38 %34",
"OpSelectionMerge %40 None",
"OpBranchConditional %39 %41 %40",
"%41 = OpLabel",
"OpStore %color %25",
"OpBranch %40",
"%40 = OpLabel",
"%42 = OpLoad %v4float %color",
"OpStore %gl_FragColor %42",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> after = {
// clang-format off
"%main = OpFunction %void None %12",
"%27 = OpLabel",
"%63 = OpVariable %_ptr_Function_float Function",
"%64 = OpVariable %_ptr_Function_float Function",
"%52 = OpVariable %_ptr_Function_float Function",
"%53 = OpVariable %_ptr_Function_float Function",
"%color = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_float Function",
"%param_0 = OpVariable %_ptr_Function_float Function",
"%28 = OpLoad %v4float %BaseColor",
"OpStore %color %28",
"%29 = OpAccessChain %_ptr_Function_float %color %uint_0",
"%30 = OpLoad %float %29",
"OpStore %param %30",
"%55 = OpLoad %float %param",
"OpStore %52 %55",
"%56 = OpLoad %float %52",
"%57 = OpFOrdLessThan %bool %56 %float_0",
"OpSelectionMerge %61 None",
"OpBranchConditional %57 %58 %61",
"%58 = OpLabel",
"%59 = OpLoad %float %52",
"%60 = OpFNegate %float %59",
"OpStore %52 %60",
"OpBranch %61",
"%61 = OpLabel",
"%62 = OpLoad %float %52",
"OpStore %53 %62",
"%31 = OpLoad %float %53",
"%32 = OpFOrdGreaterThan %bool %31 %float_2",
"OpSelectionMerge %33 None",
"OpBranchConditional %32 %34 %33",
"%34 = OpLabel",
"%35 = OpAccessChain %_ptr_Function_float %color %uint_1",
"%36 = OpLoad %float %35",
"OpStore %param_0 %36",
"%66 = OpLoad %float %param_0",
"OpStore %63 %66",
"%67 = OpLoad %float %63",
"%68 = OpFOrdLessThan %bool %67 %float_0",
"OpSelectionMerge %72 None",
"OpBranchConditional %68 %69 %72",
"%69 = OpLabel",
"%70 = OpLoad %float %63",
"%71 = OpFNegate %float %70",
"OpStore %63 %71",
"OpBranch %72",
"%72 = OpLabel",
"%73 = OpLoad %float %63",
"OpStore %64 %73",
"%37 = OpLoad %float %64",
"%38 = OpFOrdGreaterThan %bool %37 %float_2",
"OpBranch %33",
"%33 = OpLabel",
"%39 = OpPhi %bool %32 %61 %38 %72",
"OpSelectionMerge %40 None",
"OpBranchConditional %39 %41 %40",
"%41 = OpLabel",
"OpStore %color %25",
"OpBranch %40",
"%40 = OpLabel",
"%42 = OpLoad %v4float %color",
"OpStore %gl_FragColor %42",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
SinglePassRunAndCheck<InlineExhaustivePass>(
JoinAllInsts(Concat(Concat(predefs, before), nonEntryFuncs)),
JoinAllInsts(Concat(Concat(predefs, after), nonEntryFuncs)),
/* skip_nop = */ false, /* do_validate = */ true);
}
TEST_F(InlineTest, OpSampledImageOutOfBlock) {
// #version 450
//
// uniform texture2D t2D;
// uniform sampler samp;
// out vec4 FragColor;
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// float r = bar.x;
// if (r < 0.0)
// r = -r;
// return r;
// }
//
// void main()
// {
// vec4 color1 = texture(sampler2D(t2D, samp), vec2(1.0));
// vec4 color2 = vec4(foo(BaseColor));
// vec4 color3 = texture(sampler2D(t2D, samp), vec2(0.5));
// FragColor = (color1 + color2 + color3)/3;
// }
//
// Note: the before SPIR-V will need to be edited to create a use of
// the OpSampledImage across the function call.
const std::vector<const char*> predefs = {
// clang-format off
"OpCapability Shader",
"%1 = OpExtInstImport \"GLSL.std.450\"",
"OpMemoryModel Logical GLSL450",
"OpEntryPoint Fragment %main \"main\" %BaseColor %FragColor",
"OpExecutionMode %main OriginUpperLeft",
"OpSource GLSL 450",
"OpName %main \"main\"",
"OpName %foo_vf4_ \"foo(vf4;\"",
"OpName %bar \"bar\"",
"OpName %r \"r\"",
"OpName %color1 \"color1\"",
"OpName %t2D \"t2D\"",
"OpName %samp \"samp\"",
"OpName %color2 \"color2\"",
"OpName %BaseColor \"BaseColor\"",
"OpName %param \"param\"",
"OpName %color3 \"color3\"",
"OpName %FragColor \"FragColor\"",
"OpDecorate %t2D DescriptorSet 0",
"OpDecorate %samp DescriptorSet 0",
"%void = OpTypeVoid",
"%15 = OpTypeFunction %void",
"%float = OpTypeFloat 32",
"%v4float = OpTypeVector %float 4",
"%_ptr_Function_v4float = OpTypePointer Function %v4float",
"%19 = OpTypeFunction %float %_ptr_Function_v4float",
"%_ptr_Function_float = OpTypePointer Function %float",
"%uint = OpTypeInt 32 0",
"%uint_0 = OpConstant %uint 0",
"%float_0 = OpConstant %float 0",
"%bool = OpTypeBool",
"%25 = OpTypeImage %float 2D 0 0 0 1 Unknown",
"%_ptr_UniformConstant_25 = OpTypePointer UniformConstant %25",
"%t2D = OpVariable %_ptr_UniformConstant_25 UniformConstant",
"%27 = OpTypeSampler",
"%_ptr_UniformConstant_27 = OpTypePointer UniformConstant %27",
"%samp = OpVariable %_ptr_UniformConstant_27 UniformConstant",
"%29 = OpTypeSampledImage %25",
"%v2float = OpTypeVector %float 2",
"%float_1 = OpConstant %float 1",
"%32 = OpConstantComposite %v2float %float_1 %float_1",
"%_ptr_Input_v4float = OpTypePointer Input %v4float",
"%BaseColor = OpVariable %_ptr_Input_v4float Input",
"%float_0_5 = OpConstant %float 0.5",
"%35 = OpConstantComposite %v2float %float_0_5 %float_0_5",
"%_ptr_Output_v4float = OpTypePointer Output %v4float",
"%FragColor = OpVariable %_ptr_Output_v4float Output",
"%float_3 = OpConstant %float 3",
// clang-format on
};
const std::vector<const char*> nonEntryFuncs = {
// clang-format off
"%foo_vf4_ = OpFunction %float None %19",
"%bar = OpFunctionParameter %_ptr_Function_v4float",
"%56 = OpLabel",
"%r = OpVariable %_ptr_Function_float Function",
"%57 = OpAccessChain %_ptr_Function_float %bar %uint_0",
"%58 = OpLoad %float %57",
"OpStore %r %58",
"%59 = OpLoad %float %r",
"%60 = OpFOrdLessThan %bool %59 %float_0",
"OpSelectionMerge %61 None",
"OpBranchConditional %60 %62 %61",
"%62 = OpLabel",
"%63 = OpLoad %float %r",
"%64 = OpFNegate %float %63",
"OpStore %r %64",
"OpBranch %61",
"%61 = OpLabel",
"%65 = OpLoad %float %r",
"OpReturnValue %65",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> before = {
// clang-format off
"%main = OpFunction %void None %15",
"%38 = OpLabel",
"%color1 = OpVariable %_ptr_Function_v4float Function",
"%color2 = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%color3 = OpVariable %_ptr_Function_v4float Function",
"%39 = OpLoad %25 %t2D",
"%40 = OpLoad %27 %samp",
"%41 = OpSampledImage %29 %39 %40",
"%42 = OpImageSampleImplicitLod %v4float %41 %32",
"OpStore %color1 %42",
"%43 = OpLoad %v4float %BaseColor",
"OpStore %param %43",
"%44 = OpFunctionCall %float %foo_vf4_ %param",
"%45 = OpCompositeConstruct %v4float %44 %44 %44 %44",
"OpStore %color2 %45",
"%46 = OpLoad %25 %t2D",
"%47 = OpLoad %27 %samp",
"%48 = OpImageSampleImplicitLod %v4float %41 %35",
"OpStore %color3 %48",
"%49 = OpLoad %v4float %color1",
"%50 = OpLoad %v4float %color2",
"%51 = OpFAdd %v4float %49 %50",
"%52 = OpLoad %v4float %color3",
"%53 = OpFAdd %v4float %51 %52",
"%54 = OpCompositeConstruct %v4float %float_3 %float_3 %float_3 %float_3",
"%55 = OpFDiv %v4float %53 %54",
"OpStore %FragColor %55",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> after = {
// clang-format off
"%main = OpFunction %void None %15",
"%38 = OpLabel",
"%66 = OpVariable %_ptr_Function_float Function",
"%67 = OpVariable %_ptr_Function_float Function",
"%color1 = OpVariable %_ptr_Function_v4float Function",
"%color2 = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%color3 = OpVariable %_ptr_Function_v4float Function",
"%39 = OpLoad %25 %t2D",
"%40 = OpLoad %27 %samp",
"%41 = OpSampledImage %29 %39 %40",
"%42 = OpImageSampleImplicitLod %v4float %41 %32",
"OpStore %color1 %42",
"%43 = OpLoad %v4float %BaseColor",
"OpStore %param %43",
"%69 = OpAccessChain %_ptr_Function_float %param %uint_0",
"%70 = OpLoad %float %69",
"OpStore %66 %70",
"%71 = OpLoad %float %66",
"%72 = OpFOrdLessThan %bool %71 %float_0",
"OpSelectionMerge %76 None",
"OpBranchConditional %72 %73 %76",
"%73 = OpLabel",
"%74 = OpLoad %float %66",
"%75 = OpFNegate %float %74",
"OpStore %66 %75",
"OpBranch %76",
"%76 = OpLabel",
"%77 = OpLoad %float %66",
"OpStore %67 %77",
"%44 = OpLoad %float %67",
"%45 = OpCompositeConstruct %v4float %44 %44 %44 %44",
"OpStore %color2 %45",
"%46 = OpLoad %25 %t2D",
"%47 = OpLoad %27 %samp",
"%78 = OpSampledImage %29 %39 %40",
"%48 = OpImageSampleImplicitLod %v4float %78 %35",
"OpStore %color3 %48",
"%49 = OpLoad %v4float %color1",
"%50 = OpLoad %v4float %color2",
"%51 = OpFAdd %v4float %49 %50",
"%52 = OpLoad %v4float %color3",
"%53 = OpFAdd %v4float %51 %52",
"%54 = OpCompositeConstruct %v4float %float_3 %float_3 %float_3 %float_3",
"%55 = OpFDiv %v4float %53 %54",
"OpStore %FragColor %55",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
SinglePassRunAndCheck<InlineExhaustivePass>(
JoinAllInsts(Concat(Concat(predefs, before), nonEntryFuncs)),
JoinAllInsts(Concat(Concat(predefs, after), nonEntryFuncs)),
/* skip_nop = */ false, /* do_validate = */ true);
}
TEST_F(InlineTest, OpImageOutOfBlock) {
// #version 450
//
// uniform texture2D t2D;
// uniform sampler samp;
// uniform sampler samp2;
//
// out vec4 FragColor;
//
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// float r = bar.x;
// if (r < 0.0)
// r = -r;
// return r;
// }
//
// void main()
// {
// vec4 color1 = texture(sampler2D(t2D, samp), vec2(1.0));
// vec4 color2 = vec4(foo(BaseColor));
// vec4 color3 = texture(sampler2D(t2D, samp2), vec2(0.5));
// FragColor = (color1 + color2 + color3)/3;
// }
// Note: the before SPIR-V will need to be edited to create an OpImage
// from the first OpSampledImage, place it before the call and use it
// in the second OpSampledImage following the call.
const std::vector<const char*> predefs = {
// clang-format off
"OpCapability Shader",
"%1 = OpExtInstImport \"GLSL.std.450\"",
"OpMemoryModel Logical GLSL450",
"OpEntryPoint Fragment %main \"main\" %BaseColor %FragColor",
"OpExecutionMode %main OriginUpperLeft",
"OpSource GLSL 450",
"OpName %main \"main\"",
"OpName %foo_vf4_ \"foo(vf4;\"",
"OpName %bar \"bar\"",
"OpName %r \"r\"",
"OpName %color1 \"color1\"",
"OpName %t2D \"t2D\"",
"OpName %samp \"samp\"",
"OpName %color2 \"color2\"",
"OpName %BaseColor \"BaseColor\"",
"OpName %param \"param\"",
"OpName %color3 \"color3\"",
"OpName %samp2 \"samp2\"",
"OpName %FragColor \"FragColor\"",
"OpDecorate %t2D DescriptorSet 0",
"OpDecorate %samp DescriptorSet 0",
"OpDecorate %samp2 DescriptorSet 0",
"%void = OpTypeVoid",
"%16 = OpTypeFunction %void",
"%float = OpTypeFloat 32",
"%v4float = OpTypeVector %float 4",
"%_ptr_Function_v4float = OpTypePointer Function %v4float",
"%20 = OpTypeFunction %float %_ptr_Function_v4float",
"%_ptr_Function_float = OpTypePointer Function %float",
"%uint = OpTypeInt 32 0",
"%uint_0 = OpConstant %uint 0",
"%float_0 = OpConstant %float 0",
"%bool = OpTypeBool",
"%26 = OpTypeImage %float 2D 0 0 0 1 Unknown",
"%_ptr_UniformConstant_26 = OpTypePointer UniformConstant %26",
"%t2D = OpVariable %_ptr_UniformConstant_26 UniformConstant",
"%28 = OpTypeSampler",
"%_ptr_UniformConstant_28 = OpTypePointer UniformConstant %28",
"%samp = OpVariable %_ptr_UniformConstant_28 UniformConstant",
"%30 = OpTypeSampledImage %26",
"%v2float = OpTypeVector %float 2",
"%float_1 = OpConstant %float 1",
"%33 = OpConstantComposite %v2float %float_1 %float_1",
"%_ptr_Input_v4float = OpTypePointer Input %v4float",
"%BaseColor = OpVariable %_ptr_Input_v4float Input",
"%samp2 = OpVariable %_ptr_UniformConstant_28 UniformConstant",
"%float_0_5 = OpConstant %float 0.5",
"%36 = OpConstantComposite %v2float %float_0_5 %float_0_5",
"%_ptr_Output_v4float = OpTypePointer Output %v4float",
"%FragColor = OpVariable %_ptr_Output_v4float Output",
"%float_3 = OpConstant %float 3",
// clang-format on
};
const std::vector<const char*> nonEntryFuncs = {
// clang-format off
"%foo_vf4_ = OpFunction %float None %20",
"%bar = OpFunctionParameter %_ptr_Function_v4float",
"%58 = OpLabel",
"%r = OpVariable %_ptr_Function_float Function",
"%59 = OpAccessChain %_ptr_Function_float %bar %uint_0",
"%60 = OpLoad %float %59",
"OpStore %r %60",
"%61 = OpLoad %float %r",
"%62 = OpFOrdLessThan %bool %61 %float_0",
"OpSelectionMerge %63 None",
"OpBranchConditional %62 %64 %63",
"%64 = OpLabel",
"%65 = OpLoad %float %r",
"%66 = OpFNegate %float %65",
"OpStore %r %66",
"OpBranch %63",
"%63 = OpLabel",
"%67 = OpLoad %float %r",
"OpReturnValue %67",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> before = {
// clang-format off
"%main = OpFunction %void None %16",
"%39 = OpLabel",
"%color1 = OpVariable %_ptr_Function_v4float Function",
"%color2 = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%color3 = OpVariable %_ptr_Function_v4float Function",
"%40 = OpLoad %26 %t2D",
"%41 = OpLoad %28 %samp",
"%42 = OpSampledImage %30 %40 %41",
"%43 = OpImageSampleImplicitLod %v4float %42 %33",
"%44 = OpImage %26 %42",
"%45 = OpLoad %28 %samp2",
"OpStore %color1 %43",
"%46 = OpLoad %v4float %BaseColor",
"OpStore %param %46",
"%47 = OpFunctionCall %float %foo_vf4_ %param",
"%48 = OpCompositeConstruct %v4float %47 %47 %47 %47",
"OpStore %color2 %48",
"%49 = OpSampledImage %30 %44 %45",
"%50 = OpImageSampleImplicitLod %v4float %49 %36",
"OpStore %color3 %50",
"%51 = OpLoad %v4float %color1",
"%52 = OpLoad %v4float %color2",
"%53 = OpFAdd %v4float %51 %52",
"%54 = OpLoad %v4float %color3",
"%55 = OpFAdd %v4float %53 %54",
"%56 = OpCompositeConstruct %v4float %float_3 %float_3 %float_3 %float_3",
"%57 = OpFDiv %v4float %55 %56",
"OpStore %FragColor %57",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> after = {
// clang-format off
"%main = OpFunction %void None %16",
"%39 = OpLabel",
"%68 = OpVariable %_ptr_Function_float Function",
"%69 = OpVariable %_ptr_Function_float Function",
"%color1 = OpVariable %_ptr_Function_v4float Function",
"%color2 = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%color3 = OpVariable %_ptr_Function_v4float Function",
"%40 = OpLoad %26 %t2D",
"%41 = OpLoad %28 %samp",
"%42 = OpSampledImage %30 %40 %41",
"%43 = OpImageSampleImplicitLod %v4float %42 %33",
"%44 = OpImage %26 %42",
"%45 = OpLoad %28 %samp2",
"OpStore %color1 %43",
"%46 = OpLoad %v4float %BaseColor",
"OpStore %param %46",
"%71 = OpAccessChain %_ptr_Function_float %param %uint_0",
"%72 = OpLoad %float %71",
"OpStore %68 %72",
"%73 = OpLoad %float %68",
"%74 = OpFOrdLessThan %bool %73 %float_0",
"OpSelectionMerge %78 None",
"OpBranchConditional %74 %75 %78",
"%75 = OpLabel",
"%76 = OpLoad %float %68",
"%77 = OpFNegate %float %76",
"OpStore %68 %77",
"OpBranch %78",
"%78 = OpLabel",
"%79 = OpLoad %float %68",
"OpStore %69 %79",
"%47 = OpLoad %float %69",
"%48 = OpCompositeConstruct %v4float %47 %47 %47 %47",
"OpStore %color2 %48",
"%80 = OpSampledImage %30 %40 %41",
"%81 = OpImage %26 %80",
"%49 = OpSampledImage %30 %81 %45",
"%50 = OpImageSampleImplicitLod %v4float %49 %36",
"OpStore %color3 %50",
"%51 = OpLoad %v4float %color1",
"%52 = OpLoad %v4float %color2",
"%53 = OpFAdd %v4float %51 %52",
"%54 = OpLoad %v4float %color3",
"%55 = OpFAdd %v4float %53 %54",
"%56 = OpCompositeConstruct %v4float %float_3 %float_3 %float_3 %float_3",
"%57 = OpFDiv %v4float %55 %56",
"OpStore %FragColor %57",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
SinglePassRunAndCheck<InlineExhaustivePass>(
JoinAllInsts(Concat(Concat(predefs, before), nonEntryFuncs)),
JoinAllInsts(Concat(Concat(predefs, after), nonEntryFuncs)),
/* skip_nop = */ false, /* do_validate = */ true);
}
TEST_F(InlineTest, OpImageAndOpSampledImageOutOfBlock) {
// #version 450
//
// uniform texture2D t2D;
// uniform sampler samp;
// uniform sampler samp2;
//
// out vec4 FragColor;
//
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// float r = bar.x;
// if (r < 0.0)
// r = -r;
// return r;
// }
//
// void main()
// {
// vec4 color1 = texture(sampler2D(t2D, samp), vec2(1.0));
// vec4 color2 = vec4(foo(BaseColor));
// vec4 color3 = texture(sampler2D(t2D, samp2), vec2(0.5));
// FragColor = (color1 + color2 + color3)/3;
// }
// Note: the before SPIR-V will need to be edited to create an OpImage
// and subsequent OpSampledImage that is used across the function call.
const std::vector<const char*> predefs = {
// clang-format off
"OpCapability Shader",
"%1 = OpExtInstImport \"GLSL.std.450\"",
"OpMemoryModel Logical GLSL450",
"OpEntryPoint Fragment %main \"main\" %BaseColor %FragColor",
"OpExecutionMode %main OriginUpperLeft",
"OpSource GLSL 450",
"OpName %main \"main\"",
"OpName %foo_vf4_ \"foo(vf4;\"",
"OpName %bar \"bar\"",
"OpName %r \"r\"",
"OpName %color1 \"color1\"",
"OpName %t2D \"t2D\"",
"OpName %samp \"samp\"",
"OpName %color2 \"color2\"",
"OpName %BaseColor \"BaseColor\"",
"OpName %param \"param\"",
"OpName %color3 \"color3\"",
"OpName %samp2 \"samp2\"",
"OpName %FragColor \"FragColor\"",
"OpDecorate %t2D DescriptorSet 0",
"OpDecorate %samp DescriptorSet 0",
"OpDecorate %samp2 DescriptorSet 0",
"%void = OpTypeVoid",
"%16 = OpTypeFunction %void",
"%float = OpTypeFloat 32",
"%v4float = OpTypeVector %float 4",
"%_ptr_Function_v4float = OpTypePointer Function %v4float",
"%20 = OpTypeFunction %float %_ptr_Function_v4float",
"%_ptr_Function_float = OpTypePointer Function %float",
"%uint = OpTypeInt 32 0",
"%uint_0 = OpConstant %uint 0",
"%float_0 = OpConstant %float 0",
"%bool = OpTypeBool",
"%26 = OpTypeImage %float 2D 0 0 0 1 Unknown",
"%_ptr_UniformConstant_26 = OpTypePointer UniformConstant %26",
"%t2D = OpVariable %_ptr_UniformConstant_26 UniformConstant",
"%28 = OpTypeSampler",
"%_ptr_UniformConstant_28 = OpTypePointer UniformConstant %28",
"%samp = OpVariable %_ptr_UniformConstant_28 UniformConstant",
"%30 = OpTypeSampledImage %26",
"%v2float = OpTypeVector %float 2",
"%float_1 = OpConstant %float 1",
"%33 = OpConstantComposite %v2float %float_1 %float_1",
"%_ptr_Input_v4float = OpTypePointer Input %v4float",
"%BaseColor = OpVariable %_ptr_Input_v4float Input",
"%samp2 = OpVariable %_ptr_UniformConstant_28 UniformConstant",
"%float_0_5 = OpConstant %float 0.5",
"%36 = OpConstantComposite %v2float %float_0_5 %float_0_5",
"%_ptr_Output_v4float = OpTypePointer Output %v4float",
"%FragColor = OpVariable %_ptr_Output_v4float Output",
"%float_3 = OpConstant %float 3",
// clang-format on
};
const std::vector<const char*> nonEntryFuncs = {
// clang-format off
"%foo_vf4_ = OpFunction %float None %20",
"%bar = OpFunctionParameter %_ptr_Function_v4float",
"%58 = OpLabel",
"%r = OpVariable %_ptr_Function_float Function",
"%59 = OpAccessChain %_ptr_Function_float %bar %uint_0",
"%60 = OpLoad %float %59",
"OpStore %r %60",
"%61 = OpLoad %float %r",
"%62 = OpFOrdLessThan %bool %61 %float_0",
"OpSelectionMerge %63 None",
"OpBranchConditional %62 %64 %63",
"%64 = OpLabel",
"%65 = OpLoad %float %r",
"%66 = OpFNegate %float %65",
"OpStore %r %66",
"OpBranch %63",
"%63 = OpLabel",
"%67 = OpLoad %float %r",
"OpReturnValue %67",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> before = {
// clang-format off
"%main = OpFunction %void None %16",
"%39 = OpLabel",
"%color1 = OpVariable %_ptr_Function_v4float Function",
"%color2 = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%color3 = OpVariable %_ptr_Function_v4float Function",
"%40 = OpLoad %26 %t2D",
"%41 = OpLoad %28 %samp",
"%42 = OpSampledImage %30 %40 %41",
"%43 = OpImageSampleImplicitLod %v4float %42 %33",
"%44 = OpImage %26 %42",
"%45 = OpLoad %28 %samp2",
"%46 = OpSampledImage %30 %44 %45",
"OpStore %color1 %43",
"%47 = OpLoad %v4float %BaseColor",
"OpStore %param %47",
"%48 = OpFunctionCall %float %foo_vf4_ %param",
"%49 = OpCompositeConstruct %v4float %48 %48 %48 %48",
"OpStore %color2 %49",
"%50 = OpImageSampleImplicitLod %v4float %46 %36",
"OpStore %color3 %50",
"%51 = OpLoad %v4float %color1",
"%52 = OpLoad %v4float %color2",
"%53 = OpFAdd %v4float %51 %52",
"%54 = OpLoad %v4float %color3",
"%55 = OpFAdd %v4float %53 %54",
"%56 = OpCompositeConstruct %v4float %float_3 %float_3 %float_3 %float_3",
"%57 = OpFDiv %v4float %55 %56",
"OpStore %FragColor %57",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
const std::vector<const char*> after = {
// clang-format off
"%main = OpFunction %void None %16",
"%39 = OpLabel",
"%68 = OpVariable %_ptr_Function_float Function",
"%69 = OpVariable %_ptr_Function_float Function",
"%color1 = OpVariable %_ptr_Function_v4float Function",
"%color2 = OpVariable %_ptr_Function_v4float Function",
"%param = OpVariable %_ptr_Function_v4float Function",
"%color3 = OpVariable %_ptr_Function_v4float Function",
"%40 = OpLoad %26 %t2D",
"%41 = OpLoad %28 %samp",
"%42 = OpSampledImage %30 %40 %41",
"%43 = OpImageSampleImplicitLod %v4float %42 %33",
"%44 = OpImage %26 %42",
"%45 = OpLoad %28 %samp2",
"%46 = OpSampledImage %30 %44 %45",
"OpStore %color1 %43",
"%47 = OpLoad %v4float %BaseColor",
"OpStore %param %47",
"%71 = OpAccessChain %_ptr_Function_float %param %uint_0",
"%72 = OpLoad %float %71",
"OpStore %68 %72",
"%73 = OpLoad %float %68",
"%74 = OpFOrdLessThan %bool %73 %float_0",
"OpSelectionMerge %78 None",
"OpBranchConditional %74 %75 %78",
"%75 = OpLabel",
"%76 = OpLoad %float %68",
"%77 = OpFNegate %float %76",
"OpStore %68 %77",
"OpBranch %78",
"%78 = OpLabel",
"%79 = OpLoad %float %68",
"OpStore %69 %79",
"%48 = OpLoad %float %69",
"%49 = OpCompositeConstruct %v4float %48 %48 %48 %48",
"OpStore %color2 %49",
"%80 = OpSampledImage %30 %40 %41",
"%81 = OpImage %26 %80",
"%82 = OpSampledImage %30 %81 %45",
"%50 = OpImageSampleImplicitLod %v4float %82 %36",
"OpStore %color3 %50",
"%51 = OpLoad %v4float %color1",
"%52 = OpLoad %v4float %color2",
"%53 = OpFAdd %v4float %51 %52",
"%54 = OpLoad %v4float %color3",
"%55 = OpFAdd %v4float %53 %54",
"%56 = OpCompositeConstruct %v4float %float_3 %float_3 %float_3 %float_3",
"%57 = OpFDiv %v4float %55 %56",
"OpStore %FragColor %57",
"OpReturn",
"OpFunctionEnd",
// clang-format on
};
SinglePassRunAndCheck<InlineExhaustivePass>(
JoinAllInsts(Concat(Concat(predefs, before), nonEntryFuncs)),
JoinAllInsts(Concat(Concat(predefs, after), nonEntryFuncs)),
/* skip_nop = */ false, /* do_validate = */ true);
}
TEST_F(InlineTest, EarlyReturnInLoopIsNotInlined) {
// #version 140
//
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// while (true) {
// if (bar.x < 0.0)
// return 0.0;
// return bar.x;
// }
// }
//
// void main()
// {
// vec4 color = vec4(foo(BaseColor));
// gl_FragColor = color;
// }
const std::string assembly =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %BaseColor %gl_FragColor
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 140
OpName %main "main"
OpName %foo_vf4_ "foo(vf4;"
OpName %bar "bar"
OpName %color "color"
OpName %BaseColor "BaseColor"
OpName %param "param"
OpName %gl_FragColor "gl_FragColor"
%void = OpTypeVoid
%10 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Function_v4float = OpTypePointer Function %v4float
%14 = OpTypeFunction %float %_ptr_Function_v4float
%bool = OpTypeBool
%true = OpConstantTrue %bool
%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%_ptr_Function_float = OpTypePointer Function %float
%float_0 = OpConstant %float 0
%_ptr_Input_v4float = OpTypePointer Input %v4float
%BaseColor = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_FragColor = OpVariable %_ptr_Output_v4float Output
%main = OpFunction %void None %10
%23 = OpLabel
%color = OpVariable %_ptr_Function_v4float Function
%param = OpVariable %_ptr_Function_v4float Function
%24 = OpLoad %v4float %BaseColor
OpStore %param %24
%25 = OpFunctionCall %float %foo_vf4_ %param
%26 = OpCompositeConstruct %v4float %25 %25 %25 %25
OpStore %color %26
%27 = OpLoad %v4float %color
OpStore %gl_FragColor %27
OpReturn
OpFunctionEnd
%foo_vf4_ = OpFunction %float None %14
%bar = OpFunctionParameter %_ptr_Function_v4float
%28 = OpLabel
OpBranch %29
%29 = OpLabel
OpLoopMerge %30 %31 None
OpBranch %32
%32 = OpLabel
OpBranchConditional %true %33 %30
%33 = OpLabel
%34 = OpAccessChain %_ptr_Function_float %bar %uint_0
%35 = OpLoad %float %34
%36 = OpFOrdLessThan %bool %35 %float_0
OpSelectionMerge %37 None
OpBranchConditional %36 %38 %37
%38 = OpLabel
OpReturnValue %float_0
%37 = OpLabel
%39 = OpAccessChain %_ptr_Function_float %bar %uint_0
%40 = OpLoad %float %39
OpReturnValue %40
%31 = OpLabel
OpBranch %29
%30 = OpLabel
%41 = OpUndef %float
OpReturnValue %41
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(assembly, assembly, false, true);
}
TEST_F(InlineTest, ExternalFunctionIsNotInlined) {
// In particular, don't crash.
// See report https://github.com/KhronosGroup/SPIRV-Tools/issues/605
const std::string assembly =
R"(OpCapability Addresses
OpCapability Kernel
OpCapability Linkage
OpMemoryModel Physical32 OpenCL
OpEntryPoint Kernel %1 "entry_pt"
OpDecorate %2 LinkageAttributes "external" Import
%void = OpTypeVoid
%4 = OpTypeFunction %void
%2 = OpFunction %void None %4
OpFunctionEnd
%1 = OpFunction %void None %4
%5 = OpLabel
%6 = OpFunctionCall %void %2
OpReturn
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(assembly, assembly, false, true);
}
TEST_F(InlineTest, SingleBlockLoopCallsMultiBlockCallee) {
// Example from https://github.com/KhronosGroup/SPIRV-Tools/issues/787
//
// CFG structure is:
// foo:
// fooentry -> fooexit
//
// main:
// entry -> loop
// loop -> loop, merge
// loop calls foo()
// merge
//
// Since the callee has multiple blocks, it will split the calling block
// into at least two, resulting in a new "back-half" block that contains
// the instructions after the inlined function call. If the calling block
// has an OpLoopMerge that points back to the calling block itself, then
// the OpLoopMerge can't remain in the back-half block, but must be
// moved to the end of the original calling block, and it continue target
// operand updated to point to the back-half block.
const std::string predefs =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %1 "main"
OpSource OpenCL_C 120
%bool = OpTypeBool
%true = OpConstantTrue %bool
%void = OpTypeVoid
)";
const std::string nonEntryFuncs =
R"(%5 = OpTypeFunction %void
%6 = OpFunction %void None %5
%7 = OpLabel
OpBranch %8
%8 = OpLabel
OpReturn
OpFunctionEnd
)";
const std::string before =
R"(%1 = OpFunction %void None %5
%9 = OpLabel
OpBranch %10
%10 = OpLabel
%11 = OpFunctionCall %void %6
OpLoopMerge %12 %10 None
OpBranchConditional %true %10 %12
%12 = OpLabel
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(%1 = OpFunction %void None %5
%9 = OpLabel
OpBranch %10
%10 = OpLabel
OpLoopMerge %12 %10 None
OpBranch %14
%14 = OpLabel
OpBranchConditional %true %10 %12
%12 = OpLabel
OpReturn
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(predefs + nonEntryFuncs + before,
predefs + nonEntryFuncs + after,
false, true);
}
TEST_F(InlineTest, MultiBlockLoopHeaderCallsMultiBlockCallee) {
// Like SingleBlockLoopCallsMultiBlockCallee but the loop has several
// blocks, but the function call still occurs in the loop header.
// Example from https://github.com/KhronosGroup/SPIRV-Tools/issues/800
const std::string predefs =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %1 "main"
OpSource OpenCL_C 120
%bool = OpTypeBool
%true = OpConstantTrue %bool
%int = OpTypeInt 32 1
%int_1 = OpConstant %int 1
%int_2 = OpConstant %int 2
%int_3 = OpConstant %int 3
%int_4 = OpConstant %int 4
%int_5 = OpConstant %int 5
%void = OpTypeVoid
%11 = OpTypeFunction %void
)";
const std::string nonEntryFuncs =
R"(%12 = OpFunction %void None %11
%13 = OpLabel
%14 = OpCopyObject %int %int_1
OpBranch %15
%15 = OpLabel
%16 = OpCopyObject %int %int_2
OpReturn
OpFunctionEnd
)";
const std::string before =
R"(%1 = OpFunction %void None %11
%17 = OpLabel
OpBranch %18
%18 = OpLabel
%19 = OpCopyObject %int %int_3
%20 = OpFunctionCall %void %12
%21 = OpCopyObject %int %int_4
OpLoopMerge %22 %23 None
OpBranchConditional %true %23 %22
%23 = OpLabel
%24 = OpCopyObject %int %int_5
OpBranchConditional %true %18 %22
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(%1 = OpFunction %void None %11
%17 = OpLabel
OpBranch %18
%18 = OpLabel
%19 = OpCopyObject %int %int_3
%26 = OpCopyObject %int %int_1
OpLoopMerge %22 %23 None
OpBranch %27
%27 = OpLabel
%28 = OpCopyObject %int %int_2
%21 = OpCopyObject %int %int_4
OpBranchConditional %true %23 %22
%23 = OpLabel
%24 = OpCopyObject %int %int_5
OpBranchConditional %true %18 %22
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(predefs + nonEntryFuncs + before,
predefs + nonEntryFuncs + after,
false, true);
}
TEST_F(InlineTest, SingleBlockLoopCallsMultiBlockCalleeHavingSelectionMerge) {
// This is similar to SingleBlockLoopCallsMultiBlockCallee except
// that calleee block also has a merge instruction in its first block.
// That merge instruction must be an OpSelectionMerge (because the entry
// block of a function can't be the header of a loop since the entry
// block can't be the target of a branch).
//
// In this case the OpLoopMerge can't be placed in the same block as
// the OpSelectionMerge, so inlining must create a new block to contain
// the callee contents.
//
// Additionally, we have two dummy OpCopyObject instructions to prove that
// the OpLoopMerge is moved to the right location.
//
// Also ensure that OpPhis within the cloned callee code are valid.
// We need to test that the predecessor blocks are remapped correctly so that
// dominance rules are satisfied
const std::string predefs =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %1 "main"
OpSource OpenCL_C 120
%bool = OpTypeBool
%true = OpConstantTrue %bool
%false = OpConstantFalse %bool
%void = OpTypeVoid
%6 = OpTypeFunction %void
)";
// This callee has multiple blocks, and an OpPhi in the last block
// that references a value from the first block. This tests that
// cloned block IDs are remapped appropriately. The OpPhi dominance
// requires that the remapped %9 must be in a block that dominates
// the remapped %8.
const std::string nonEntryFuncs =
R"(%7 = OpFunction %void None %6
%8 = OpLabel
%9 = OpCopyObject %bool %true
OpSelectionMerge %10 None
OpBranchConditional %true %10 %10
%10 = OpLabel
%11 = OpPhi %bool %9 %8
OpReturn
OpFunctionEnd
)";
const std::string before =
R"(%1 = OpFunction %void None %6
%12 = OpLabel
OpBranch %13
%13 = OpLabel
%14 = OpCopyObject %bool %false
%15 = OpFunctionCall %void %7
OpLoopMerge %16 %13 None
OpBranchConditional %true %13 %16
%16 = OpLabel
OpReturn
OpFunctionEnd
)";
// Note the remapped Phi uses %17 as the parent instead
// of %13, demonstrating that the parent block has been remapped
// correctly.
const std::string after =
R"(%1 = OpFunction %void None %6
%12 = OpLabel
OpBranch %13
%13 = OpLabel
%14 = OpCopyObject %bool %false
OpLoopMerge %16 %13 None
OpBranch %17
%17 = OpLabel
%19 = OpCopyObject %bool %true
OpSelectionMerge %20 None
OpBranchConditional %true %20 %20
%20 = OpLabel
%21 = OpPhi %bool %19 %17
OpBranchConditional %true %13 %16
%16 = OpLabel
OpReturn
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(predefs + nonEntryFuncs + before,
predefs + nonEntryFuncs + after,
false, true);
}
TEST_F(InlineTest,
MultiBlockLoopHeaderCallsFromToMultiBlockCalleeHavingSelectionMerge) {
// This is similar to SingleBlockLoopCallsMultiBlockCalleeHavingSelectionMerge
// but the call is in the header block of a multi block loop.
const std::string predefs =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint GLCompute %1 "main"
OpSource OpenCL_C 120
%bool = OpTypeBool
%true = OpConstantTrue %bool
%int = OpTypeInt 32 1
%int_1 = OpConstant %int 1
%int_2 = OpConstant %int 2
%int_3 = OpConstant %int 3
%int_4 = OpConstant %int 4
%int_5 = OpConstant %int 5
%void = OpTypeVoid
%11 = OpTypeFunction %void
)";
const std::string nonEntryFuncs =
R"(%12 = OpFunction %void None %11
%13 = OpLabel
%14 = OpCopyObject %int %int_1
OpSelectionMerge %15 None
OpBranchConditional %true %15 %15
%15 = OpLabel
%16 = OpCopyObject %int %int_2
OpReturn
OpFunctionEnd
)";
const std::string before =
R"(%1 = OpFunction %void None %11
%17 = OpLabel
OpBranch %18
%18 = OpLabel
%19 = OpCopyObject %int %int_3
%20 = OpFunctionCall %void %12
%21 = OpCopyObject %int %int_4
OpLoopMerge %22 %23 None
OpBranchConditional %true %23 %22
%23 = OpLabel
%24 = OpCopyObject %int %int_5
OpBranchConditional %true %18 %22
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(%1 = OpFunction %void None %11
%17 = OpLabel
OpBranch %18
%18 = OpLabel
%19 = OpCopyObject %int %int_3
OpLoopMerge %22 %23 None
OpBranch %25
%25 = OpLabel
%27 = OpCopyObject %int %int_1
OpSelectionMerge %28 None
OpBranchConditional %true %28 %28
%28 = OpLabel
%29 = OpCopyObject %int %int_2
%21 = OpCopyObject %int %int_4
OpBranchConditional %true %23 %22
%23 = OpLabel
%24 = OpCopyObject %int %int_5
OpBranchConditional %true %18 %22
%22 = OpLabel
OpReturn
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(predefs + nonEntryFuncs + before,
predefs + nonEntryFuncs + after,
false, true);
}
TEST_F(InlineTest, NonInlinableCalleeWithSingleReturn) {
// The case from https://github.com/KhronosGroup/SPIRV-Tools/issues/2018
//
// The callee has a single return, but cannot be inlined because the
// return is inside a loop.
const std::string predefs =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %_GLF_color
OpExecutionMode %main OriginUpperLeft
OpSource ESSL 310
OpName %main "main"
OpName %f_ "f("
OpName %i "i"
OpName %_GLF_color "_GLF_color"
OpDecorate %_GLF_color Location 0
%void = OpTypeVoid
%7 = OpTypeFunction %void
%float = OpTypeFloat 32
%9 = OpTypeFunction %float
%float_1 = OpConstant %float 1
%bool = OpTypeBool
%false = OpConstantFalse %bool
%int = OpTypeInt 32 1
%_ptr_Function_int = OpTypePointer Function %int
%int_0 = OpConstant %int 0
%int_1 = OpConstant %int 1
%v4float = OpTypeVector %float 4
%_ptr_Output_v4float = OpTypePointer Output %v4float
%_GLF_color = OpVariable %_ptr_Output_v4float Output
%float_0 = OpConstant %float 0
%20 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0
%21 = OpConstantComposite %v4float %float_0 %float_1 %float_0 %float_1
)";
const std::string caller =
R"(%main = OpFunction %void None %7
%22 = OpLabel
%i = OpVariable %_ptr_Function_int Function
OpStore %i %int_0
OpBranch %23
%23 = OpLabel
OpLoopMerge %24 %25 None
OpBranch %26
%26 = OpLabel
%27 = OpLoad %int %i
%28 = OpSLessThan %bool %27 %int_1
OpBranchConditional %28 %29 %24
%29 = OpLabel
OpStore %_GLF_color %20
%30 = OpFunctionCall %float %f_
OpBranch %25
%25 = OpLabel
%31 = OpLoad %int %i
%32 = OpIAdd %int %31 %int_1
OpStore %i %32
OpBranch %23
%24 = OpLabel
OpStore %_GLF_color %21
OpReturn
OpFunctionEnd
)";
const std::string callee =
R"(%f_ = OpFunction %float None %9
%33 = OpLabel
OpBranch %34
%34 = OpLabel
OpLoopMerge %35 %36 None
OpBranch %37
%37 = OpLabel
OpReturnValue %float_1
%36 = OpLabel
OpBranch %34
%35 = OpLabel
OpUnreachable
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(
predefs + caller + callee, predefs + caller + callee, false, true);
}
TEST_F(InlineTest, Decorated1) {
// Same test as Simple with the difference
// that OpFAdd in the outlined function is
// decorated with RelaxedPrecision
// Expected result is an equal decoration
// of the corresponding inlined instruction
//
// #version 140
//
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// return bar.x + bar.y;
// }
//
// void main()
// {
// vec4 color = vec4(foo(BaseColor));
// gl_FragColor = color;
// }
const std::string predefs =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %BaseColor %gl_FragColor
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 140
OpName %main "main"
OpName %foo_vf4_ "foo(vf4;"
OpName %bar "bar"
OpName %color "color"
OpName %BaseColor "BaseColor"
OpName %param "param"
OpName %gl_FragColor "gl_FragColor"
OpDecorate %9 RelaxedPrecision
)";
const std::string before =
R"(%void = OpTypeVoid
%11 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Function_v4float = OpTypePointer Function %v4float
%15 = OpTypeFunction %float %_ptr_Function_v4float
%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%_ptr_Function_float = OpTypePointer Function %float
%uint_1 = OpConstant %uint 1
%_ptr_Input_v4float = OpTypePointer Input %v4float
%BaseColor = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_FragColor = OpVariable %_ptr_Output_v4float Output
%main = OpFunction %void None %11
%22 = OpLabel
%color = OpVariable %_ptr_Function_v4float Function
%param = OpVariable %_ptr_Function_v4float Function
%23 = OpLoad %v4float %BaseColor
OpStore %param %23
%24 = OpFunctionCall %float %foo_vf4_ %param
%25 = OpCompositeConstruct %v4float %24 %24 %24 %24
OpStore %color %25
%26 = OpLoad %v4float %color
OpStore %gl_FragColor %26
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(OpDecorate %38 RelaxedPrecision
%void = OpTypeVoid
%11 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Function_v4float = OpTypePointer Function %v4float
%15 = OpTypeFunction %float %_ptr_Function_v4float
%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%_ptr_Function_float = OpTypePointer Function %float
%uint_1 = OpConstant %uint 1
%_ptr_Input_v4float = OpTypePointer Input %v4float
%BaseColor = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_FragColor = OpVariable %_ptr_Output_v4float Output
%main = OpFunction %void None %11
%22 = OpLabel
%32 = OpVariable %_ptr_Function_float Function
%color = OpVariable %_ptr_Function_v4float Function
%param = OpVariable %_ptr_Function_v4float Function
%23 = OpLoad %v4float %BaseColor
OpStore %param %23
%34 = OpAccessChain %_ptr_Function_float %param %uint_0
%35 = OpLoad %float %34
%36 = OpAccessChain %_ptr_Function_float %param %uint_1
%37 = OpLoad %float %36
%38 = OpFAdd %float %35 %37
OpStore %32 %38
%24 = OpLoad %float %32
%25 = OpCompositeConstruct %v4float %24 %24 %24 %24
OpStore %color %25
%26 = OpLoad %v4float %color
OpStore %gl_FragColor %26
OpReturn
OpFunctionEnd
)";
const std::string nonEntryFuncs =
R"(%foo_vf4_ = OpFunction %float None %15
%bar = OpFunctionParameter %_ptr_Function_v4float
%27 = OpLabel
%28 = OpAccessChain %_ptr_Function_float %bar %uint_0
%29 = OpLoad %float %28
%30 = OpAccessChain %_ptr_Function_float %bar %uint_1
%31 = OpLoad %float %30
%9 = OpFAdd %float %29 %31
OpReturnValue %9
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(predefs + before + nonEntryFuncs,
predefs + after + nonEntryFuncs,
false, true);
}
TEST_F(InlineTest, Decorated2) {
// Same test as Simple with the difference
// that the Result <id> of the outlined OpFunction
// is decorated with RelaxedPrecision
// Expected result is an equal decoration
// of the created return variable
//
// #version 140
//
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// return bar.x + bar.y;
// }
//
// void main()
// {
// vec4 color = vec4(foo(BaseColor));
// gl_FragColor = color;
// }
const std::string predefs =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %BaseColor %gl_FragColor
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 140
OpName %main "main"
OpName %foo_vf4_ "foo(vf4;"
OpName %bar "bar"
OpName %color "color"
OpName %BaseColor "BaseColor"
OpName %param "param"
OpName %gl_FragColor "gl_FragColor"
OpDecorate %foo_vf4_ RelaxedPrecision
)";
const std::string before =
R"(%void = OpTypeVoid
%10 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Function_v4float = OpTypePointer Function %v4float
%14 = OpTypeFunction %float %_ptr_Function_v4float
%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%_ptr_Function_float = OpTypePointer Function %float
%uint_1 = OpConstant %uint 1
%_ptr_Input_v4float = OpTypePointer Input %v4float
%BaseColor = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_FragColor = OpVariable %_ptr_Output_v4float Output
%main = OpFunction %void None %10
%21 = OpLabel
%color = OpVariable %_ptr_Function_v4float Function
%param = OpVariable %_ptr_Function_v4float Function
%22 = OpLoad %v4float %BaseColor
OpStore %param %22
%23 = OpFunctionCall %float %foo_vf4_ %param
%24 = OpCompositeConstruct %v4float %23 %23 %23 %23
OpStore %color %24
%25 = OpLoad %v4float %color
OpStore %gl_FragColor %25
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(OpDecorate %32 RelaxedPrecision
%void = OpTypeVoid
%10 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Function_v4float = OpTypePointer Function %v4float
%14 = OpTypeFunction %float %_ptr_Function_v4float
%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%_ptr_Function_float = OpTypePointer Function %float
%uint_1 = OpConstant %uint 1
%_ptr_Input_v4float = OpTypePointer Input %v4float
%BaseColor = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_FragColor = OpVariable %_ptr_Output_v4float Output
%main = OpFunction %void None %10
%21 = OpLabel
%32 = OpVariable %_ptr_Function_float Function
%color = OpVariable %_ptr_Function_v4float Function
%param = OpVariable %_ptr_Function_v4float Function
%22 = OpLoad %v4float %BaseColor
OpStore %param %22
%34 = OpAccessChain %_ptr_Function_float %param %uint_0
%35 = OpLoad %float %34
%36 = OpAccessChain %_ptr_Function_float %param %uint_1
%37 = OpLoad %float %36
%38 = OpFAdd %float %35 %37
OpStore %32 %38
%23 = OpLoad %float %32
%24 = OpCompositeConstruct %v4float %23 %23 %23 %23
OpStore %color %24
%25 = OpLoad %v4float %color
OpStore %gl_FragColor %25
OpReturn
OpFunctionEnd
)";
const std::string nonEntryFuncs =
R"(%foo_vf4_ = OpFunction %float None %14
%bar = OpFunctionParameter %_ptr_Function_v4float
%26 = OpLabel
%27 = OpAccessChain %_ptr_Function_float %bar %uint_0
%28 = OpLoad %float %27
%29 = OpAccessChain %_ptr_Function_float %bar %uint_1
%30 = OpLoad %float %29
%31 = OpFAdd %float %28 %30
OpReturnValue %31
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(predefs + before + nonEntryFuncs,
predefs + after + nonEntryFuncs,
false, true);
}
TEST_F(InlineTest, DeleteName) {
// Test that the name of the result id of the call is deleted.
const std::string before =
R"(
OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %main "main"
OpName %main "main"
OpName %main_entry "main_entry"
OpName %foo_result "foo_result"
OpName %void_fn "void_fn"
OpName %foo "foo"
OpName %foo_entry "foo_entry"
%void = OpTypeVoid
%void_fn = OpTypeFunction %void
%foo = OpFunction %void None %void_fn
%foo_entry = OpLabel
OpReturn
OpFunctionEnd
%main = OpFunction %void None %void_fn
%main_entry = OpLabel
%foo_result = OpFunctionCall %void %foo
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %main "main"
OpName %main "main"
OpName %main_entry "main_entry"
OpName %void_fn "void_fn"
OpName %foo "foo"
OpName %foo_entry "foo_entry"
%void = OpTypeVoid
%void_fn = OpTypeFunction %void
%foo = OpFunction %void None %void_fn
%foo_entry = OpLabel
OpReturn
OpFunctionEnd
%main = OpFunction %void None %void_fn
%main_entry = OpLabel
OpReturn
OpFunctionEnd
)";
SinglePassRunAndCheck<InlineExhaustivePass>(before, after, false, true);
}
TEST_F(InlineTest, SetParent) {
// Test that after inlining all basic blocks have the correct parent.
const std::string text =
R"(
OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %main "main"
OpName %main "main"
OpName %main_entry "main_entry"
OpName %foo_result "foo_result"
OpName %void_fn "void_fn"
OpName %foo "foo"
OpName %foo_entry "foo_entry"
%void = OpTypeVoid
%void_fn = OpTypeFunction %void
%foo = OpFunction %void None %void_fn
%foo_entry = OpLabel
OpReturn
OpFunctionEnd
%main = OpFunction %void None %void_fn
%main_entry = OpLabel
%foo_result = OpFunctionCall %void %foo
OpReturn
OpFunctionEnd
)";
std::unique_ptr<IRContext> context =
BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
InlineExhaustivePass pass;
pass.Run(context.get());
for (Function& func : *context->module()) {
for (BasicBlock& bb : func) {
EXPECT_TRUE(bb.GetParent() == &func);
}
}
}
TEST_F(InlineTest, OpVariableWithInit) {
// Check that there is a store that corresponds to the initializer. This
// test makes sure that is a store to the variable in the loop and before any
// load.
const std::string text = R"(
; CHECK: OpFunction
; CHECK-NOT: OpFunctionEnd
; CHECK: [[var:%\w+]] = OpVariable %_ptr_Function_float Function %float_0
; CHECK: OpLoopMerge [[outer_merge:%\w+]]
; CHECK-NOT: OpLoad %float [[var]]
; CHECK: OpStore [[var]] %float_0
; CHECK: OpFunctionEnd
OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %o
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 450
OpDecorate %o Location 0
%void = OpTypeVoid
%3 = OpTypeFunction %void
%float = OpTypeFloat 32
%7 = OpTypeFunction %float
%_ptr_Function_float = OpTypePointer Function %float
%float_0 = OpConstant %float 0
%bool = OpTypeBool
%float_1 = OpConstant %float 1
%_ptr_Output_float = OpTypePointer Output %float
%o = OpVariable %_ptr_Output_float Output
%int = OpTypeInt 32 1
%_ptr_Function_int = OpTypePointer Function %int
%_ptr_Input_int = OpTypePointer Input %int
%int_0 = OpConstant %int 0
%int_1 = OpConstant %int 1
%int_2 = OpConstant %int 2
%main = OpFunction %void None %3
%5 = OpLabel
OpStore %o %float_0
OpBranch %34
%34 = OpLabel
%39 = OpPhi %int %int_0 %5 %47 %37
OpLoopMerge %36 %37 None
OpBranch %38
%38 = OpLabel
%41 = OpSLessThan %bool %39 %int_2
OpBranchConditional %41 %35 %36
%35 = OpLabel
%42 = OpFunctionCall %float %foo_
%43 = OpLoad %float %o
%44 = OpFAdd %float %43 %42
OpStore %o %44
OpBranch %37
%37 = OpLabel
%47 = OpIAdd %int %39 %int_1
OpBranch %34
%36 = OpLabel
OpReturn
OpFunctionEnd
%foo_ = OpFunction %float None %7
%9 = OpLabel
%n = OpVariable %_ptr_Function_float Function %float_0
%13 = OpLoad %float %n
%15 = OpFOrdEqual %bool %13 %float_0
OpSelectionMerge %17 None
OpBranchConditional %15 %16 %17
%16 = OpLabel
%19 = OpLoad %float %n
%20 = OpFAdd %float %19 %float_1
OpStore %n %20
OpBranch %17
%17 = OpLabel
%21 = OpLoad %float %n
OpReturnValue %21
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
TEST_F(InlineTest, DontInlineDirectlyRecursiveFunc) {
// Test that the name of the result id of the call is deleted.
const std::string test =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %1 "main"
OpExecutionMode %1 OriginUpperLeft
OpDecorate %2 DescriptorSet 439418829
%void = OpTypeVoid
%4 = OpTypeFunction %void
%float = OpTypeFloat 32
%_struct_6 = OpTypeStruct %float %float
%15 = OpConstantNull %_struct_6
%7 = OpTypeFunction %_struct_6
%1 = OpFunction %void Pure|Const %4
%8 = OpLabel
%2 = OpFunctionCall %_struct_6 %9
OpKill
OpFunctionEnd
%9 = OpFunction %_struct_6 None %7
%10 = OpLabel
%11 = OpFunctionCall %_struct_6 %9
OpReturnValue %15
OpFunctionEnd
)";
SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
SinglePassRunAndCheck<InlineExhaustivePass>(test, test, false, true);
}
TEST_F(InlineTest, DontInlineInDirectlyRecursiveFunc) {
// Test that the name of the result id of the call is deleted.
const std::string test =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %1 "main"
OpExecutionMode %1 OriginUpperLeft
OpDecorate %2 DescriptorSet 439418829
%void = OpTypeVoid
%4 = OpTypeFunction %void
%float = OpTypeFloat 32
%_struct_6 = OpTypeStruct %float %float
%15 = OpConstantNull %_struct_6
%7 = OpTypeFunction %_struct_6
%1 = OpFunction %void Pure|Const %4
%8 = OpLabel
%2 = OpFunctionCall %_struct_6 %9
OpKill
OpFunctionEnd
%9 = OpFunction %_struct_6 None %7
%10 = OpLabel
%11 = OpFunctionCall %_struct_6 %12
OpReturnValue %15
OpFunctionEnd
%12 = OpFunction %_struct_6 None %7
%13 = OpLabel
%14 = OpFunctionCall %_struct_6 %9
OpReturnValue %15
OpFunctionEnd
)";
SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
SinglePassRunAndCheck<InlineExhaustivePass>(test, test, false, true);
}
TEST_F(InlineTest, DontInlineFuncWithOpKillInContinue) {
const std::string test =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main"
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 330
OpName %main "main"
OpName %kill_ "kill("
%void = OpTypeVoid
%3 = OpTypeFunction %void
%bool = OpTypeBool
%true = OpConstantTrue %bool
%main = OpFunction %void None %3
%5 = OpLabel
OpBranch %9
%9 = OpLabel
OpLoopMerge %11 %12 None
OpBranch %13
%13 = OpLabel
OpBranchConditional %true %10 %11
%10 = OpLabel
OpBranch %12
%12 = OpLabel
%16 = OpFunctionCall %void %kill_
OpBranch %9
%11 = OpLabel
OpReturn
OpFunctionEnd
%kill_ = OpFunction %void None %3
%7 = OpLabel
OpKill
OpFunctionEnd
)";
SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
SinglePassRunAndCheck<InlineExhaustivePass>(test, test, false, true);
}
TEST_F(InlineTest, InlineFuncWithOpKillNotInContinue) {
const std::string before =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main"
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 330
OpName %main "main"
OpName %kill_ "kill("
%void = OpTypeVoid
%3 = OpTypeFunction %void
%bool = OpTypeBool
%true = OpConstantTrue %bool
%main = OpFunction %void None %3
%5 = OpLabel
%16 = OpFunctionCall %void %kill_
OpReturn
OpFunctionEnd
%kill_ = OpFunction %void None %3
%7 = OpLabel
OpKill
OpFunctionEnd
)";
const std::string after =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main"
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 330
OpName %main "main"
OpName %kill_ "kill("
%void = OpTypeVoid
%3 = OpTypeFunction %void
%bool = OpTypeBool
%true = OpConstantTrue %bool
%main = OpFunction %void None %3
%5 = OpLabel
OpKill
%18 = OpLabel
OpReturn
OpFunctionEnd
%kill_ = OpFunction %void None %3
%7 = OpLabel
OpKill
OpFunctionEnd
)";
SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
SinglePassRunAndCheck<InlineExhaustivePass>(before, after, false, true);
}
TEST_F(InlineTest, DontInlineFuncWithOpTerminateInvocationInContinue) {
const std::string test =
R"(OpCapability Shader
OpExtension "SPV_KHR_terminate_invocation"
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main"
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 330
OpName %main "main"
OpName %kill_ "kill("
%void = OpTypeVoid
%3 = OpTypeFunction %void
%bool = OpTypeBool
%true = OpConstantTrue %bool
%main = OpFunction %void None %3
%5 = OpLabel
OpBranch %9
%9 = OpLabel
OpLoopMerge %11 %12 None
OpBranch %13
%13 = OpLabel
OpBranchConditional %true %10 %11
%10 = OpLabel
OpBranch %12
%12 = OpLabel
%16 = OpFunctionCall %void %kill_
OpBranch %9
%11 = OpLabel
OpReturn
OpFunctionEnd
%kill_ = OpFunction %void None %3
%7 = OpLabel
OpTerminateInvocation
OpFunctionEnd
)";
SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
SinglePassRunAndCheck<InlineExhaustivePass>(test, test, false, true);
}
TEST_F(InlineTest, InlineFuncWithOpTerminateInvocationNotInContinue) {
const std::string before =
R"(OpCapability Shader
OpExtension "SPV_KHR_terminate_invocation"
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main"
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 330
OpName %main "main"
OpName %kill_ "kill("
%void = OpTypeVoid
%3 = OpTypeFunction %void
%bool = OpTypeBool
%true = OpConstantTrue %bool
%main = OpFunction %void None %3
%5 = OpLabel
%16 = OpFunctionCall %void %kill_
OpReturn
OpFunctionEnd
%kill_ = OpFunction %void None %3
%7 = OpLabel
OpTerminateInvocation
OpFunctionEnd
)";
const std::string after =
R"(OpCapability Shader
OpExtension "SPV_KHR_terminate_invocation"
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main"
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 330
OpName %main "main"
OpName %kill_ "kill("
%void = OpTypeVoid
%3 = OpTypeFunction %void
%bool = OpTypeBool
%true = OpConstantTrue %bool
%main = OpFunction %void None %3
%5 = OpLabel
OpTerminateInvocation
%18 = OpLabel
OpReturn
OpFunctionEnd
%kill_ = OpFunction %void None %3
%7 = OpLabel
OpTerminateInvocation
OpFunctionEnd
)";
SetAssembleOptions(SPV_TEXT_TO_BINARY_OPTION_PRESERVE_NUMERIC_IDS);
SinglePassRunAndCheck<InlineExhaustivePass>(before, after, false, true);
}
TEST_F(InlineTest, EarlyReturnFunctionInlined) {
// #version 140
//
// in vec4 BaseColor;
//
// float foo(vec4 bar)
// {
// if (bar.x < 0.0)
// return 0.0;
// return bar.x;
// }
//
// void main()
// {
// vec4 color = vec4(foo(BaseColor));
// gl_FragColor = color;
// }
const std::string predefs =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %BaseColor %gl_FragColor
OpExecutionMode %main OriginUpperLeft
OpSource GLSL 140
OpName %main "main"
OpName %foo_vf4_ "foo(vf4;"
OpName %bar "bar"
OpName %color "color"
OpName %BaseColor "BaseColor"
OpName %param "param"
OpName %gl_FragColor "gl_FragColor"
%void = OpTypeVoid
%10 = OpTypeFunction %void
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Function_v4float = OpTypePointer Function %v4float
%14 = OpTypeFunction %float %_ptr_Function_v4float
%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%_ptr_Function_float = OpTypePointer Function %float
%float_0 = OpConstant %float 0
%bool = OpTypeBool
%_ptr_Input_v4float = OpTypePointer Input %v4float
%BaseColor = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_FragColor = OpVariable %_ptr_Output_v4float Output
)";
const std::string foo =
R"(%foo_vf4_ = OpFunction %float None %14
%bar = OpFunctionParameter %_ptr_Function_v4float
%27 = OpLabel
%28 = OpAccessChain %_ptr_Function_float %bar %uint_0
%29 = OpLoad %float %28
%30 = OpFOrdLessThan %bool %29 %float_0
OpSelectionMerge %31 None
OpBranchConditional %30 %32 %31
%32 = OpLabel
OpReturnValue %float_0
%31 = OpLabel
%33 = OpAccessChain %_ptr_Function_float %bar %uint_0
%34 = OpLoad %float %33
OpReturnValue %34
OpFunctionEnd
)";
const std::string fooMergeReturn =
R"(%foo_vf4_ = OpFunction %float None %14
%bar = OpFunctionParameter %_ptr_Function_v4float
%27 = OpLabel
%41 = OpVariable %_ptr_Function_bool Function %false
%36 = OpVariable %_ptr_Function_float Function
OpSelectionMerge %35 None
OpSwitch %uint_0 %38
%38 = OpLabel
%28 = OpAccessChain %_ptr_Function_float %bar %uint_0
%29 = OpLoad %float %28
%30 = OpFOrdLessThan %bool %29 %float_0
OpSelectionMerge %31 None
OpBranchConditional %30 %32 %31
%32 = OpLabel
OpStore %41 %true
OpStore %36 %float_0
OpBranch %35
%31 = OpLabel
%33 = OpAccessChain %_ptr_Function_float %bar %uint_0
%34 = OpLoad %float %33
OpStore %41 %true
OpStore %36 %34
OpBranch %35
%35 = OpLabel
%37 = OpLoad %float %36
OpReturnValue %37
OpFunctionEnd
)";
const std::string before =
R"(%main = OpFunction %void None %10
%22 = OpLabel
%color = OpVariable %_ptr_Function_v4float Function
%param = OpVariable %_ptr_Function_v4float Function
%23 = OpLoad %v4float %BaseColor
OpStore %param %23
%24 = OpFunctionCall %float %foo_vf4_ %param
%25 = OpCompositeConstruct %v4float %24 %24 %24 %24
OpStore %color %25
%26 = OpLoad %v4float %color
OpStore %gl_FragColor %26
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(%false = OpConstantFalse %bool
%_ptr_Function_bool = OpTypePointer Function %bool
%true = OpConstantTrue %bool
%main = OpFunction %void None %10
%22 = OpLabel
%43 = OpVariable %_ptr_Function_bool Function %false
%44 = OpVariable %_ptr_Function_float Function
%45 = OpVariable %_ptr_Function_float Function
%color = OpVariable %_ptr_Function_v4float Function
%param = OpVariable %_ptr_Function_v4float Function
%23 = OpLoad %v4float %BaseColor
OpStore %param %23
OpStore %43 %false
OpSelectionMerge %55 None
OpSwitch %uint_0 %47
%47 = OpLabel
%48 = OpAccessChain %_ptr_Function_float %param %uint_0
%49 = OpLoad %float %48
%50 = OpFOrdLessThan %bool %49 %float_0
OpSelectionMerge %52 None
OpBranchConditional %50 %51 %52
%51 = OpLabel
OpStore %43 %true
OpStore %44 %float_0
OpBranch %55
%52 = OpLabel
%53 = OpAccessChain %_ptr_Function_float %param %uint_0
%54 = OpLoad %float %53
OpStore %43 %true
OpStore %44 %54
OpBranch %55
%55 = OpLabel
%56 = OpLoad %float %44
OpStore %45 %56
%24 = OpLoad %float %45
%25 = OpCompositeConstruct %v4float %24 %24 %24 %24
OpStore %color %25
%26 = OpLoad %v4float %color
OpStore %gl_FragColor %26
OpReturn
OpFunctionEnd
)";
// The early return case must be handled by merge-return first.
AddPass<MergeReturnPass>();
AddPass<InlineExhaustivePass>();
RunAndCheck(predefs + before + foo, predefs + after + fooMergeReturn);
}
TEST_F(InlineTest, EarlyReturnNotAppearingLastInFunctionInlined) {
// Example from https://github.com/KhronosGroup/SPIRV-Tools/issues/755
//
// Original example is derived from:
//
// #version 450
//
// float foo() {
// if (true) {
// }
// }
//
// void main() { foo(); }
//
// But the order of basic blocks in foo is changed so that the return
// block is listed second-last. There is only one return in the callee
// but it does not appear last.
const std::string predefs =
R"(OpCapability Shader
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %main "main"
OpSource GLSL 450
OpName %main "main"
OpName %foo_ "foo("
%void = OpTypeVoid
%4 = OpTypeFunction %void
%bool = OpTypeBool
%true = OpConstantTrue %bool
)";
const std::string foo =
R"(%foo_ = OpFunction %void None %4
%7 = OpLabel
OpSelectionMerge %8 None
OpBranchConditional %true %9 %8
%8 = OpLabel
OpReturn
%9 = OpLabel
OpBranch %8
OpFunctionEnd
)";
const std::string fooMergeReturn =
R"(%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%false = OpConstantFalse %bool
%_ptr_Function_bool = OpTypePointer Function %bool
%foo_ = OpFunction %void None %4
%7 = OpLabel
%18 = OpVariable %_ptr_Function_bool Function %false
OpSelectionMerge %12 None
OpSwitch %uint_0 %13
%13 = OpLabel
OpSelectionMerge %8 None
OpBranchConditional %true %9 %8
%8 = OpLabel
OpStore %18 %true
OpBranch %12
%9 = OpLabel
OpBranch %8
%12 = OpLabel
OpReturn
OpFunctionEnd
)";
const std::string before =
R"(%main = OpFunction %void None %4
%10 = OpLabel
%11 = OpFunctionCall %void %foo_
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(%main = OpFunction %void None %4
%10 = OpLabel
%19 = OpVariable %_ptr_Function_bool Function %false
OpStore %19 %false
OpSelectionMerge %24 None
OpSwitch %uint_0 %21
%21 = OpLabel
OpSelectionMerge %22 None
OpBranchConditional %true %23 %22
%22 = OpLabel
OpStore %19 %true
OpBranch %24
%23 = OpLabel
OpBranch %22
%24 = OpLabel
OpReturn
OpFunctionEnd
)";
// The early return case must be handled by merge-return first.
AddPass<MergeReturnPass>();
AddPass<InlineExhaustivePass>();
RunAndCheck(predefs + foo + before, predefs + fooMergeReturn + after);
}
TEST_F(InlineTest, CalleeWithSingleReturnNeedsSingleTripLoopWrapper) {
// The case from https://github.com/KhronosGroup/SPIRV-Tools/issues/2018
//
// The callee has a single return, but needs single-trip loop wrapper
// to be inlined because the return is in a selection structure.
const std::string predefs =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %_GLF_color
OpExecutionMode %main OriginUpperLeft
OpSource ESSL 310
OpName %main "main"
OpName %f_ "f("
OpName %i "i"
OpName %_GLF_color "_GLF_color"
OpDecorate %_GLF_color Location 0
%void = OpTypeVoid
%7 = OpTypeFunction %void
%float = OpTypeFloat 32
%9 = OpTypeFunction %float
%float_1 = OpConstant %float 1
%bool = OpTypeBool
%false = OpConstantFalse %bool
%true = OpConstantTrue %bool
%int = OpTypeInt 32 1
%_ptr_Function_int = OpTypePointer Function %int
%int_0 = OpConstant %int 0
%int_1 = OpConstant %int 1
%v4float = OpTypeVector %float 4
%_ptr_Output_v4float = OpTypePointer Output %v4float
%_GLF_color = OpVariable %_ptr_Output_v4float Output
%float_0 = OpConstant %float 0
%21 = OpConstantComposite %v4float %float_0 %float_0 %float_0 %float_0
%22 = OpConstantComposite %v4float %float_0 %float_1 %float_0 %float_1
)";
const std::string new_predefs =
R"(%_ptr_Function_float = OpTypePointer Function %float
%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%_ptr_Function_bool = OpTypePointer Function %bool
)";
const std::string main_before =
R"(%main = OpFunction %void None %7
%23 = OpLabel
%i = OpVariable %_ptr_Function_int Function
OpStore %i %int_0
OpBranch %24
%24 = OpLabel
OpLoopMerge %25 %26 None
OpBranch %27
%27 = OpLabel
%28 = OpLoad %int %i
%29 = OpSLessThan %bool %28 %int_1
OpBranchConditional %29 %30 %25
%30 = OpLabel
OpStore %_GLF_color %21
%31 = OpFunctionCall %float %f_
OpBranch %26
%26 = OpLabel
%32 = OpLoad %int %i
%33 = OpIAdd %int %32 %int_1
OpStore %i %33
OpBranch %24
%25 = OpLabel
OpStore %_GLF_color %22
OpReturn
OpFunctionEnd
)";
const std::string main_after =
R"(%main = OpFunction %void None %7
%23 = OpLabel
%46 = OpVariable %_ptr_Function_bool Function %false
%47 = OpVariable %_ptr_Function_float Function
%48 = OpVariable %_ptr_Function_float Function
%i = OpVariable %_ptr_Function_int Function
OpStore %i %int_0
OpBranch %24
%24 = OpLabel
OpLoopMerge %25 %26 None
OpBranch %27
%27 = OpLabel
%28 = OpLoad %int %i
%29 = OpSLessThan %bool %28 %int_1
OpBranchConditional %29 %30 %25
%30 = OpLabel
OpStore %_GLF_color %21
OpStore %46 %false
OpSelectionMerge %53 None
OpSwitch %uint_0 %50
%50 = OpLabel
OpSelectionMerge %52 None
OpBranchConditional %true %51 %52
%51 = OpLabel
OpStore %46 %true
OpStore %47 %float_1
OpBranch %53
%52 = OpLabel
OpStore %46 %true
OpStore %47 %float_1
OpBranch %53
%53 = OpLabel
%54 = OpLoad %float %47
OpStore %48 %54
%31 = OpLoad %float %48
OpBranch %26
%26 = OpLabel
%32 = OpLoad %int %i
%33 = OpIAdd %int %32 %int_1
OpStore %i %33
OpBranch %24
%25 = OpLabel
OpStore %_GLF_color %22
OpReturn
OpFunctionEnd
)";
const std::string callee =
R"(%f_ = OpFunction %float None %9
%34 = OpLabel
OpSelectionMerge %35 None
OpBranchConditional %true %36 %35
%36 = OpLabel
OpReturnValue %float_1
%35 = OpLabel
OpReturnValue %float_1
OpFunctionEnd
)";
const std::string calleeMergeReturn =
R"(%f_ = OpFunction %float None %9
%34 = OpLabel
%45 = OpVariable %_ptr_Function_bool Function %false
%39 = OpVariable %_ptr_Function_float Function
OpSelectionMerge %37 None
OpSwitch %uint_0 %41
%41 = OpLabel
OpSelectionMerge %35 None
OpBranchConditional %true %36 %35
%36 = OpLabel
OpStore %45 %true
OpStore %39 %float_1
OpBranch %37
%35 = OpLabel
OpStore %45 %true
OpStore %39 %float_1
OpBranch %37
%37 = OpLabel
%40 = OpLoad %float %39
OpReturnValue %40
OpFunctionEnd
)";
// The early return case must be handled by merge-return first.
AddPass<MergeReturnPass>();
AddPass<InlineExhaustivePass>();
RunAndCheck(predefs + main_before + callee,
predefs + new_predefs + main_after + calleeMergeReturn);
}
TEST_F(InlineTest, ForwardReferencesInPhiInlined) {
// The basic structure of the test case is like this:
//
// int foo() {
// int result = 1;
// if (true) {
// result = 1;
// }
// return result;
// }
//
// void main() {
// int x = foo();
// }
//
// but with modifications: Using Phi instead of load/store, and the
// return block in foo appears before the "then" block.
const std::string predefs =
R"(OpCapability Shader
%1 = OpExtInstImport "GLSL.std.450"
OpMemoryModel Logical GLSL450
OpEntryPoint Vertex %main "main"
OpSource GLSL 450
OpName %main "main"
OpName %foo_ "foo("
OpName %x "x"
%void = OpTypeVoid
%6 = OpTypeFunction %void
%int = OpTypeInt 32 1
%8 = OpTypeFunction %int
%bool = OpTypeBool
%true = OpConstantTrue %bool
%int_0 = OpConstant %int 0
%_ptr_Function_int = OpTypePointer Function %int
)";
const std::string callee =
R"(%foo_ = OpFunction %int None %8
%13 = OpLabel
%14 = OpCopyObject %int %int_0
OpSelectionMerge %15 None
OpBranchConditional %true %16 %15
%15 = OpLabel
%17 = OpPhi %int %14 %13 %18 %16
OpReturnValue %17
%16 = OpLabel
%18 = OpCopyObject %int %int_0
OpBranch %15
OpFunctionEnd
)";
const std::string calleeMergeReturn =
R"(%uint = OpTypeInt 32 0
%uint_0 = OpConstant %uint 0
%false = OpConstantFalse %bool
%_ptr_Function_bool = OpTypePointer Function %bool
%foo_ = OpFunction %int None %8
%13 = OpLabel
%29 = OpVariable %_ptr_Function_bool Function %false
%22 = OpVariable %_ptr_Function_int Function
OpSelectionMerge %21 None
OpSwitch %uint_0 %24
%24 = OpLabel
%14 = OpCopyObject %int %int_0
OpSelectionMerge %15 None
OpBranchConditional %true %16 %15
%15 = OpLabel
%17 = OpPhi %int %14 %24 %18 %16
OpStore %29 %true
OpStore %22 %17
OpBranch %21
%16 = OpLabel
%18 = OpCopyObject %int %int_0
OpBranch %15
%21 = OpLabel
%23 = OpLoad %int %22
OpReturnValue %23
OpFunctionEnd
)";
const std::string before =
R"(%main = OpFunction %void None %6
%19 = OpLabel
%x = OpVariable %_ptr_Function_int Function
%20 = OpFunctionCall %int %foo_
OpStore %x %20
OpReturn
OpFunctionEnd
)";
const std::string after =
R"(%main = OpFunction %void None %6
%19 = OpLabel
%30 = OpVariable %_ptr_Function_bool Function %false
%31 = OpVariable %_ptr_Function_int Function
%32 = OpVariable %_ptr_Function_int Function
%x = OpVariable %_ptr_Function_int Function
OpStore %30 %false
OpSelectionMerge %40 None
OpSwitch %uint_0 %34
%34 = OpLabel
%35 = OpCopyObject %int %int_0
OpSelectionMerge %36 None
OpBranchConditional %true %38 %36
%36 = OpLabel
%37 = OpPhi %int %35 %34 %39 %38
OpStore %30 %true
OpStore %31 %37
OpBranch %40
%38 = OpLabel
%39 = OpCopyObject %int %int_0
OpBranch %36
%40 = OpLabel
%41 = OpLoad %int %31
OpStore %32 %41
%20 = OpLoad %int %32
OpStore %x %20
OpReturn
OpFunctionEnd
)";
AddPass<MergeReturnPass>();
AddPass<InlineExhaustivePass>();
RunAndCheck(predefs + callee + before, predefs + calleeMergeReturn + after);
}
TEST_F(InlineTest, DebugSimple) {
// Check that it correctly generates DebugInlinedAt and maps it to DebugScope
// for the inlined function foo().
const std::string text = R"(
; CHECK: [[main_name:%\d+]] = OpString "main"
; CHECK: [[foo_name:%\d+]] = OpString "foo"
; CHECK: [[dbg_main:%\d+]] = OpExtInst %void {{%\d+}} DebugFunction [[main_name]] {{%\d+}} {{%\d+}} 4 1 {{%\d+}} [[main_name]] FlagIsProtected|FlagIsPrivate 4 [[main:%\d+]]
; CHECK: [[dbg_foo:%\d+]] = OpExtInst %void {{%\d+}} DebugFunction [[foo_name]] {{%\d+}} {{%\d+}} 1 1 {{%\d+}} [[foo_name]] FlagIsProtected|FlagIsPrivate 1 [[foo:%\d+]]
; CHECK: [[foo_bb:%\d+]] = OpExtInst %void {{%\d+}} DebugLexicalBlock {{%\d+}} 1 14 [[dbg_foo]]
; CHECK: [[inlined_at:%\d+]] = OpExtInst %void {{%\d+}} DebugInlinedAt 4 [[dbg_main]]
; CHECK: [[main]] = OpFunction %void None
; CHECK: {{%\d+}} = OpExtInst %void {{%\d+}} DebugScope [[foo_bb]] [[inlined_at]]
; CHECK: [[foo]] = OpFunction %v4float None
OpCapability Shader
%1 = OpExtInstImport "OpenCL.DebugInfo.100"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %3 %4
OpExecutionMode %main OriginUpperLeft
%5 = OpString "ps.hlsl"
OpSource HLSL 600 %5
%6 = OpString "float"
%main_name = OpString "main"
%foo_name = OpString "foo"
OpDecorate %3 Location 0
OpDecorate %4 Location 0
%uint = OpTypeInt 32 0
%uint_32 = OpConstant %uint 32
%float = OpTypeFloat 32
%float_1 = OpConstant %float 1
%v4float = OpTypeVector %float 4
%14 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%void = OpTypeVoid
%18 = OpTypeFunction %void
%19 = OpTypeFunction %v4float
%3 = OpVariable %_ptr_Input_v4float Input
%4 = OpVariable %_ptr_Output_v4float Output
%20 = OpExtInst %void %1 DebugSource %5
%21 = OpExtInst %void %1 DebugCompilationUnit 1 4 %20 HLSL
%22 = OpExtInst %void %1 DebugTypeBasic %6 %uint_32 Float
%23 = OpExtInst %void %1 DebugTypeVector %22 4
%24 = OpExtInst %void %1 DebugTypeFunction FlagIsProtected|FlagIsPrivate %23 %23
%25 = OpExtInst %void %1 DebugTypeFunction FlagIsProtected|FlagIsPrivate %23
%dbg_main = OpExtInst %void %1 DebugFunction %main_name %24 %20 4 1 %21 %main_name FlagIsProtected|FlagIsPrivate 4 %main
%dbg_foo = OpExtInst %void %1 DebugFunction %foo_name %25 %20 1 1 %21 %foo_name FlagIsProtected|FlagIsPrivate 1 %foo
%29 = OpExtInst %void %1 DebugLexicalBlock %20 1 14 %dbg_foo
%main = OpFunction %void None %18
%30 = OpLabel
%31 = OpExtInst %void %1 DebugScope %dbg_main
%32 = OpFunctionCall %v4float %foo
%33 = OpLoad %v4float %3
%34 = OpFAdd %v4float %32 %33
OpStore %4 %34
OpReturn
OpFunctionEnd
%foo = OpFunction %v4float None %19
%35 = OpExtInst %void %1 DebugScope %dbg_foo
%36 = OpLabel
%37 = OpExtInst %void %1 DebugScope %29
OpReturnValue %14
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
TEST_F(InlineTest, DebugNested) {
// When function main() calls function zoo() and function zoo() calls
// function bar() and function bar() calls function foo(), check that
// the inline pass correctly generates DebugInlinedAt instructions
// for the nested function calls.
const std::string text = R"(
; CHECK: [[v4f1:%\d+]] = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
; CHECK: [[v4f2:%\d+]] = OpConstantComposite %v4float %float_2 %float_2 %float_2 %float_2
; CHECK: [[v4f3:%\d+]] = OpConstantComposite %v4float %float_3 %float_3 %float_3 %float_3
; CHECK: [[color:%\d+]] = OpVariable %_ptr_Input_v4float Input
; CHECK: [[dbg_main:%\d+]] = OpExtInst %void [[ext:%\d+]] DebugFunction {{%\d+}} {{%\d+}} {{%\d+}} 10 1 {{%\d+}} {{%\d+}} FlagIsProtected|FlagIsPrivate 10 [[main:%\d+]]
; CHECK: [[dbg_foo:%\d+]] = OpExtInst %void [[ext]] DebugFunction {{%\d+}} {{%\d+}} {{%\d+}} 1 1 {{%\d+}} {{%\d+}} FlagIsProtected|FlagIsPrivate 1 [[foo:%\d+]]
; CHECK: [[dbg_bar:%\d+]] = OpExtInst %void [[ext]] DebugFunction {{%\d+}} {{%\d+}} {{%\d+}} 4 1 {{%\d+}} {{%\d+}} FlagIsProtected|FlagIsPrivate 4 [[bar:%\d+]]
; CHECK: [[dbg_zoo:%\d+]] = OpExtInst %void [[ext]] DebugFunction {{%\d+}} {{%\d+}} {{%\d+}} 7 1 {{%\d+}} {{%\d+}} FlagIsProtected|FlagIsPrivate 7 [[zoo:%\d+]]
; CHECK: [[inlined_to_main:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 600 [[dbg_main]]
; CHECK: [[inlined_to_zoo:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 700 [[dbg_zoo]] [[inlined_to_main]]
; CHECK: [[inlined_to_bar:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 300 [[dbg_bar]] [[inlined_to_zoo]]
; CHECK: [[main]] = OpFunction %void None
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_foo]] [[inlined_to_bar]]
; CHECK-NEXT: OpLine {{%\d+}} 100 0
; CHECK-NEXT: OpStore {{%\d+}} [[v4f1]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_bar]] [[inlined_to_zoo]]
; CHECK-NEXT: OpLine {{%\d+}} 300 0
; CHECK-NEXT: [[foo_ret:%\d+]] = OpLoad %v4float
; CHECK-NEXT: OpLine {{%\d+}} 400 0
; CHECK-NEXT: {{%\d+}} = OpFAdd %v4float [[foo_ret]] [[v4f2]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_zoo]] [[inlined_to_main]]
; CHECK-NEXT: OpLine {{%\d+}} 700 0
; CHECK-NEXT: [[bar_ret:%\d+]] = OpLoad %v4float
; CHECK-NEXT: {{%\d+}} = OpFAdd %v4float [[bar_ret]] [[v4f3]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_main]]
; CHECK-NEXT: OpLine {{%\d+}} 600 0
; CHECK-NEXT: [[zoo_ret:%\d+]] = OpLoad %v4float
; CHECK-NEXT: [[color_val:%\d+]] = OpLoad %v4float [[color]]
; CHECK-NEXT: {{%\d+}} = OpFAdd %v4float [[zoo_ret]] [[color_val]]
; CHECK: [[foo]] = OpFunction %v4float None
; CHECK: [[bar]] = OpFunction %v4float None
; CHECK: [[zoo]] = OpFunction %v4float None
OpCapability Shader
%1 = OpExtInstImport "OpenCL.DebugInfo.100"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %3 %4
OpExecutionMode %main OriginUpperLeft
%5 = OpString "ps.hlsl"
OpSource HLSL 600 %5
%6 = OpString "float"
%7 = OpString "main"
%8 = OpString "foo"
%9 = OpString "bar"
%10 = OpString "zoo"
OpDecorate %3 Location 0
OpDecorate %4 Location 0
%uint = OpTypeInt 32 0
%uint_32 = OpConstant %uint 32
%float = OpTypeFloat 32
%float_1 = OpConstant %float 1
%float_2 = OpConstant %float 2
%float_3 = OpConstant %float 3
%v4float = OpTypeVector %float 4
%18 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
%19 = OpConstantComposite %v4float %float_2 %float_2 %float_2 %float_2
%20 = OpConstantComposite %v4float %float_3 %float_3 %float_3 %float_3
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%void = OpTypeVoid
%24 = OpTypeFunction %void
%25 = OpTypeFunction %v4float
%3 = OpVariable %_ptr_Input_v4float Input
%4 = OpVariable %_ptr_Output_v4float Output
%26 = OpExtInst %void %1 DebugSource %5
%27 = OpExtInst %void %1 DebugCompilationUnit 1 4 %26 HLSL
%28 = OpExtInst %void %1 DebugTypeBasic %6 %uint_32 Float
%29 = OpExtInst %void %1 DebugTypeVector %28 4
%30 = OpExtInst %void %1 DebugTypeFunction FlagIsProtected|FlagIsPrivate %29 %29
%31 = OpExtInst %void %1 DebugTypeFunction FlagIsProtected|FlagIsPrivate %29
%32 = OpExtInst %void %1 DebugFunction %7 %30 %26 10 1 %27 %7 FlagIsProtected|FlagIsPrivate 10 %main
%33 = OpExtInst %void %1 DebugFunction %8 %31 %26 1 1 %27 %8 FlagIsProtected|FlagIsPrivate 1 %foo
%35 = OpExtInst %void %1 DebugFunction %9 %31 %26 4 1 %27 %9 FlagIsProtected|FlagIsPrivate 4 %bar
%37 = OpExtInst %void %1 DebugFunction %10 %31 %26 7 1 %27 %10 FlagIsProtected|FlagIsPrivate 7 %zoo
%main = OpFunction %void None %24
%39 = OpLabel
%40 = OpExtInst %void %1 DebugScope %32
OpLine %5 600 0
%41 = OpFunctionCall %v4float %zoo
%42 = OpLoad %v4float %3
%43 = OpFAdd %v4float %41 %42
OpStore %4 %43
OpReturn
OpFunctionEnd
%foo = OpFunction %v4float None %25
%44 = OpExtInst %void %1 DebugScope %33
%45 = OpLabel
OpLine %5 100 0
OpReturnValue %18
OpFunctionEnd
OpLine %5 200 0
%bar = OpFunction %v4float None %25
%46 = OpExtInst %void %1 DebugScope %35
%47 = OpLabel
OpLine %5 300 0
%48 = OpFunctionCall %v4float %foo
OpLine %5 400 0
%49 = OpFAdd %v4float %48 %19
OpLine %5 500 0
OpReturnValue %49
OpFunctionEnd
%zoo = OpFunction %v4float None %25
%50 = OpExtInst %void %1 DebugScope %37
%51 = OpLabel
OpLine %5 700 0
%52 = OpFunctionCall %v4float %bar
%53 = OpFAdd %v4float %52 %20
OpReturnValue %53
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
TEST_F(InlineTest, DebugSimpleHLSLPixelShader) {
const std::string text = R"(
; CHECK: [[dbg_main:%\d+]] = OpExtInst %void [[ext:%\d+]] DebugFunction {{%\d+}} {{%\d+}} {{%\d+}} 1 1 {{%\d+}} {{%\d+}} FlagIsProtected|FlagIsPrivate 1 %src_main
; CHECK: [[lex_blk:%\d+]] = OpExtInst %void [[ext]] DebugLexicalBlock {{%\d+}} 1 47 [[dbg_main]]
; CHECK: %main = OpFunction %void None
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_main]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugDeclare {{%\d+}} %param_var_color
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[lex_blk]]
; CHECK: OpLine {{%\d+}} 2 10
; CHECK: {{%\d+}} = OpLoad %v4float %param_var_color
; CHECK: OpLine {{%\d+}} 2 3
; CHECK: OpFunctionEnd
; CHECK: %src_main = OpFunction %v4float None
OpCapability Shader
%1 = OpExtInstImport "OpenCL.DebugInfo.100"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %in_var_COLOR %out_var_SV_TARGET
OpExecutionMode %main OriginUpperLeft
%5 = OpString "ps.hlsl"
OpSource HLSL 600 %5
%14 = OpString "#line 1 \"ps.hlsl\"
float4 main(float4 color : COLOR) : SV_TARGET {
return color;
}
"
%17 = OpString "float"
%21 = OpString "src.main"
%24 = OpString "color"
OpName %in_var_COLOR "in.var.COLOR"
OpName %out_var_SV_TARGET "out.var.SV_TARGET"
OpName %main "main"
OpName %param_var_color "param.var.color"
OpName %src_main "src.main"
OpName %color "color"
OpName %bb_entry "bb.entry"
OpDecorate %in_var_COLOR Location 0
OpDecorate %out_var_SV_TARGET Location 0
%uint = OpTypeInt 32 0
%uint_32 = OpConstant %uint 32
%float = OpTypeFloat 32
%v4float = OpTypeVector %float 4
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%void = OpTypeVoid
%27 = OpTypeFunction %void
%_ptr_Function_v4float = OpTypePointer Function %v4float
%33 = OpTypeFunction %v4float %_ptr_Function_v4float
%in_var_COLOR = OpVariable %_ptr_Input_v4float Input
%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output
%13 = OpExtInst %void %1 DebugExpression
%15 = OpExtInst %void %1 DebugSource %5 %14
%16 = OpExtInst %void %1 DebugCompilationUnit 1 4 %15 HLSL
%18 = OpExtInst %void %1 DebugTypeBasic %17 %uint_32 Float
%19 = OpExtInst %void %1 DebugTypeVector %18 4
%20 = OpExtInst %void %1 DebugTypeFunction FlagIsProtected|FlagIsPrivate %19 %19
%22 = OpExtInst %void %1 DebugFunction %21 %20 %15 1 1 %16 %21 FlagIsProtected|FlagIsPrivate 1 %src_main
%25 = OpExtInst %void %1 DebugLocalVariable %24 %19 %15 1 20 %22 FlagIsLocal 0
%26 = OpExtInst %void %1 DebugLexicalBlock %15 1 47 %22
%main = OpFunction %void None %27
%28 = OpLabel
%param_var_color = OpVariable %_ptr_Function_v4float Function
%31 = OpLoad %v4float %in_var_COLOR
OpStore %param_var_color %31
%32 = OpFunctionCall %v4float %src_main %param_var_color
OpStore %out_var_SV_TARGET %32
OpReturn
OpFunctionEnd
OpLine %5 1 1
%src_main = OpFunction %v4float None %33
%34 = OpExtInst %void %1 DebugScope %22
%color = OpFunctionParameter %_ptr_Function_v4float
%36 = OpExtInst %void %1 DebugDeclare %25 %color %13
%bb_entry = OpLabel
%38 = OpExtInst %void %1 DebugScope %26
OpLine %5 2 10
%39 = OpLoad %v4float %color
OpLine %5 2 3
OpReturnValue %39
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
TEST_F(InlineTest, DebugDeclareForCalleeFunctionParam) {
// Check that InlinePass correctly generates DebugDeclare instructions
// for callee function's parameters and maps them to corresponding
// local variables of caller function.
const std::string text = R"(
; CHECK: [[add:%\d+]] = OpString "add"
; CHECK: [[a:%\d+]] = OpString "a"
; CHECK: [[b:%\d+]] = OpString "b"
; CHECK: [[dbg_add:%\d+]] = OpExtInst %void [[ext:%\d+]] DebugFunction [[add]]
; CHECK: [[dbg_a:%\d+]] = OpExtInst %void [[ext]] DebugLocalVariable [[a]]
; CHECK: [[dbg_b:%\d+]] = OpExtInst %void [[ext]] DebugLocalVariable [[b]]
; CHECK: [[inlinedat:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 5
; CHECK: OpStore [[param_a:%\d+]]
; CHECK: OpStore [[param_b:%\d+]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_add]] [[inlinedat]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugDeclare [[dbg_a]] [[param_a]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugDeclare [[dbg_b]] [[param_b]]
OpCapability Shader
%ext = OpExtInstImport "OpenCL.DebugInfo.100"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %in_var_COLOR %out_var_SV_TARGET
OpExecutionMode %main OriginUpperLeft
%file_name = OpString "ps.hlsl"
OpSource HLSL 600 %file_name
%float_name = OpString "float"
%main_name = OpString "main"
%add_name = OpString "add"
%a_name = OpString "a"
%b_name = OpString "b"
OpDecorate %in_var_COLOR Location 0
OpDecorate %out_var_SV_TARGET Location 0
%uint = OpTypeInt 32 0
%uint_32 = OpConstant %uint 32
%float = OpTypeFloat 32
%float_1 = OpConstant %float 1
%float_2 = OpConstant %float 2
%v4float = OpTypeVector %float 4
%v4f1 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
%v4f2 = OpConstantComposite %v4float %float_2 %float_2 %float_2 %float_2
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%_ptr_Function_v4float = OpTypePointer Function %v4float
%add_fn_type = OpTypeFunction %v4float %_ptr_Function_v4float %_ptr_Function_v4float
%void = OpTypeVoid
%void_fn_type = OpTypeFunction %void
%v4f_fn_type = OpTypeFunction %v4float
%in_var_COLOR = OpVariable %_ptr_Input_v4float Input
%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output
%null_expr = OpExtInst %void %ext DebugExpression
%src = OpExtInst %void %ext DebugSource %file_name
%cu = OpExtInst %void %ext DebugCompilationUnit 1 4 %src HLSL
%dbg_f = OpExtInst %void %ext DebugTypeBasic %float_name %uint_32 Float
%dbg_v4f = OpExtInst %void %ext DebugTypeVector %dbg_f 4
%main_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f
%add_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f %dbg_v4f
%dbg_main = OpExtInst %void %ext DebugFunction %main_name %main_ty %src 5 1 %cu %main_name FlagIsProtected|FlagIsPrivate 10 %main
%dbg_add = OpExtInst %void %ext DebugFunction %add_name %add_ty %src 1 1 %cu %add_name FlagIsProtected|FlagIsPrivate 1 %add
%dbg_a = OpExtInst %void %ext DebugLocalVariable %a_name %dbg_v4f %src 1 13 %dbg_add FlagIsLocal 0
%dbg_b = OpExtInst %void %ext DebugLocalVariable %b_name %dbg_v4f %src 1 20 %dbg_add FlagIsLocal 1
%add_lb = OpExtInst %void %ext DebugLexicalBlock %src 1 23 %dbg_add
%main = OpFunction %void None %void_fn_type
%main_bb = OpLabel
%param_a = OpVariable %_ptr_Function_v4float Function
%param_b = OpVariable %_ptr_Function_v4float Function
%scope0 = OpExtInst %void %ext DebugScope %dbg_main
OpStore %param_a %v4f1
OpStore %param_b %v4f2
%result = OpFunctionCall %v4float %add %param_a %param_b
OpStore %out_var_SV_TARGET %result
OpReturn
OpFunctionEnd
%add = OpFunction %v4float None %add_fn_type
%scope1 = OpExtInst %void %ext DebugScope %dbg_add
%a = OpFunctionParameter %_ptr_Function_v4float
%b = OpFunctionParameter %_ptr_Function_v4float
%decl0 = OpExtInst %void %ext DebugDeclare %dbg_a %a %null_expr
%decl1 = OpExtInst %void %ext DebugDeclare %dbg_b %b %null_expr
%add_bb = OpLabel
%scope2 = OpExtInst %void %ext DebugScope %add_lb
%a_val = OpLoad %v4float %a
%b_val = OpLoad %v4float %b
%res = OpFAdd %v4float %a_val %b_val
OpReturnValue %res
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
TEST_F(InlineTest, DebugDeclareForCalleeLocalVar) {
// Check that InlinePass correctly generates DebugDeclare instructions
// for callee function's local variables and maps them to corresponding
// local variables of caller function.
const std::string text = R"(
; CHECK: [[add:%\d+]] = OpString "add"
; CHECK: [[foo:%\d+]] = OpString "foo"
; CHECK: [[dbg_add:%\d+]] = OpExtInst %void [[ext:%\d+]] DebugFunction [[add]]
; CHECK: [[dbg_foo:%\d+]] = OpExtInst %void [[ext]] DebugLocalVariable [[foo]] {{%\d+}} {{%\d+}} 2 2 [[dbg_add]]
; CHECK: [[inlinedat:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 5
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_add]] [[inlinedat]]
; CHECK: [[new_foo:%\d+]] = OpVariable %_ptr_Function_v4float Function
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_add]] [[inlinedat]]
; CHECK: [[a_val:%\d+]] = OpLoad %v4float
; CHECK: [[b_val:%\d+]] = OpLoad %v4float
; CHECK: [[res:%\d+]] = OpFAdd %v4float [[a_val]] [[b_val]]
; CHECK: OpStore [[new_foo]] [[res]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugDeclare [[dbg_foo]] [[new_foo]]
OpCapability Shader
%ext = OpExtInstImport "OpenCL.DebugInfo.100"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %in_var_COLOR %out_var_SV_TARGET
OpExecutionMode %main OriginUpperLeft
%file_name = OpString "ps.hlsl"
OpSource HLSL 600 %file_name
%float_name = OpString "float"
%main_name = OpString "main"
%add_name = OpString "add"
%foo_name = OpString "foo"
OpDecorate %in_var_COLOR Location 0
OpDecorate %out_var_SV_TARGET Location 0
%uint = OpTypeInt 32 0
%uint_32 = OpConstant %uint 32
%float = OpTypeFloat 32
%float_1 = OpConstant %float 1
%float_2 = OpConstant %float 2
%v4float = OpTypeVector %float 4
%v4f1 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
%v4f2 = OpConstantComposite %v4float %float_2 %float_2 %float_2 %float_2
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%_ptr_Function_v4float = OpTypePointer Function %v4float
%add_fn_type = OpTypeFunction %v4float %_ptr_Function_v4float %_ptr_Function_v4float
%void = OpTypeVoid
%void_fn_type = OpTypeFunction %void
%v4f_fn_type = OpTypeFunction %v4float
%in_var_COLOR = OpVariable %_ptr_Input_v4float Input
%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output
%null_expr = OpExtInst %void %ext DebugExpression
%src = OpExtInst %void %ext DebugSource %file_name
%cu = OpExtInst %void %ext DebugCompilationUnit 1 4 %src HLSL
%dbg_f = OpExtInst %void %ext DebugTypeBasic %float_name %uint_32 Float
%dbg_v4f = OpExtInst %void %ext DebugTypeVector %dbg_f 4
%main_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f
%add_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f %dbg_v4f
%dbg_main = OpExtInst %void %ext DebugFunction %main_name %main_ty %src 5 1 %cu %main_name FlagIsProtected|FlagIsPrivate 10 %main
%dbg_add = OpExtInst %void %ext DebugFunction %add_name %add_ty %src 1 1 %cu %add_name FlagIsProtected|FlagIsPrivate 1 %add
%dbg_foo = OpExtInst %void %ext DebugLocalVariable %foo_name %dbg_v4f %src 2 2 %dbg_add FlagIsLocal
%main = OpFunction %void None %void_fn_type
%main_bb = OpLabel
%param_a = OpVariable %_ptr_Function_v4float Function
%param_b = OpVariable %_ptr_Function_v4float Function
%scope0 = OpExtInst %void %ext DebugScope %dbg_main
OpStore %param_a %v4f1
OpStore %param_b %v4f2
%result = OpFunctionCall %v4float %add %param_a %param_b
OpStore %out_var_SV_TARGET %result
OpReturn
OpFunctionEnd
%add = OpFunction %v4float None %add_fn_type
%scope1 = OpExtInst %void %ext DebugScope %dbg_add
%a = OpFunctionParameter %_ptr_Function_v4float
%b = OpFunctionParameter %_ptr_Function_v4float
%add_bb = OpLabel
%foo = OpVariable %_ptr_Function_v4float Function
%a_val = OpLoad %v4float %a
%b_val = OpLoad %v4float %b
%res = OpFAdd %v4float %a_val %b_val
OpStore %foo %res
%decl = OpExtInst %void %ext DebugDeclare %dbg_foo %foo %null_expr
%foo_val = OpLoad %v4float %foo
OpReturnValue %foo_val
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
TEST_F(InlineTest, DebugDeclareMultiple) {
// Check that InlinePass correctly generates DebugDeclare instructions
// for callee function's parameters and maps them to corresponding
// local variables of caller function.
const std::string text = R"(
; CHECK: [[add:%\d+]] = OpString "add"
; CHECK: [[a:%\d+]] = OpString "a"
; CHECK: [[b:%\d+]] = OpString "b"
; CHECK: [[dbg_add:%\d+]] = OpExtInst %void [[ext:%\d+]] DebugFunction [[add]]
; CHECK: [[dbg_a:%\d+]] = OpExtInst %void [[ext]] DebugLocalVariable [[a]]
; CHECK: [[dbg_b:%\d+]] = OpExtInst %void [[ext]] DebugLocalVariable [[b]]
; CHECK: OpFunction
; CHECK-NOT: OpFunctionEnd
; CHECK: OpStore [[param_a:%\d+]]
; CHECK: OpStore [[param_b:%\d+]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_add]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugDeclare [[dbg_a]] [[param_a]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugDeclare [[dbg_b]] [[param_b]]
; CHECK: [[a_val:%\d+]] = OpLoad %v4float [[param_a]]
; CHECK: OpStore [[foo:%\d+]] [[a_val]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugValue [[dbg_a]] [[foo]]
OpCapability Shader
%ext = OpExtInstImport "OpenCL.DebugInfo.100"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %in_var_COLOR %out_var_SV_TARGET
OpExecutionMode %main OriginUpperLeft
%file_name = OpString "ps.hlsl"
OpSource HLSL 600 %file_name
%float_name = OpString "float"
%main_name = OpString "main"
%add_name = OpString "add"
%a_name = OpString "a"
%b_name = OpString "b"
OpDecorate %in_var_COLOR Location 0
OpDecorate %out_var_SV_TARGET Location 0
%uint = OpTypeInt 32 0
%uint_32 = OpConstant %uint 32
%float = OpTypeFloat 32
%float_1 = OpConstant %float 1
%float_2 = OpConstant %float 2
%v4float = OpTypeVector %float 4
%v4f1 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
%v4f2 = OpConstantComposite %v4float %float_2 %float_2 %float_2 %float_2
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%_ptr_Function_v4float = OpTypePointer Function %v4float
%add_fn_type = OpTypeFunction %v4float %_ptr_Function_v4float %_ptr_Function_v4float
%void = OpTypeVoid
%void_fn_type = OpTypeFunction %void
%v4f_fn_type = OpTypeFunction %v4float
%in_var_COLOR = OpVariable %_ptr_Input_v4float Input
%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output
%null_expr = OpExtInst %void %ext DebugExpression
%src = OpExtInst %void %ext DebugSource %file_name
%cu = OpExtInst %void %ext DebugCompilationUnit 1 4 %src HLSL
%dbg_f = OpExtInst %void %ext DebugTypeBasic %float_name %uint_32 Float
%dbg_v4f = OpExtInst %void %ext DebugTypeVector %dbg_f 4
%main_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f
%add_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f %dbg_v4f
%dbg_main = OpExtInst %void %ext DebugFunction %main_name %main_ty %src 5 1 %cu %main_name FlagIsProtected|FlagIsPrivate 10 %main
%dbg_add = OpExtInst %void %ext DebugFunction %add_name %add_ty %src 1 1 %cu %add_name FlagIsProtected|FlagIsPrivate 1 %add
%dbg_a = OpExtInst %void %ext DebugLocalVariable %a_name %dbg_v4f %src 1 13 %dbg_add FlagIsLocal 0
%dbg_b = OpExtInst %void %ext DebugLocalVariable %b_name %dbg_v4f %src 1 20 %dbg_add FlagIsLocal 1
%main = OpFunction %void None %void_fn_type
%main_bb = OpLabel
%param_a = OpVariable %_ptr_Function_v4float Function
%param_b = OpVariable %_ptr_Function_v4float Function
%scope0 = OpExtInst %void %ext DebugScope %dbg_main
OpStore %param_a %v4f1
OpStore %param_b %v4f2
%result = OpFunctionCall %v4float %add %param_a %param_b
OpStore %out_var_SV_TARGET %result
OpReturn
OpFunctionEnd
%add = OpFunction %v4float None %add_fn_type
%scope1 = OpExtInst %void %ext DebugScope %dbg_add
%a = OpFunctionParameter %_ptr_Function_v4float
%b = OpFunctionParameter %_ptr_Function_v4float
%decl0 = OpExtInst %void %ext DebugDeclare %dbg_a %a %null_expr
%add_bb = OpLabel
%decl1 = OpExtInst %void %ext DebugDeclare %dbg_b %b %null_expr
%foo = OpVariable %_ptr_Function_v4float Function
%a_val = OpLoad %v4float %a
OpStore %foo %a_val
%dbg_val = OpExtInst %void %ext DebugValue %dbg_a %foo %null_expr
%b_val = OpLoad %v4float %b
%res = OpFAdd %v4float %a_val %b_val
OpReturnValue %res
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
TEST_F(InlineTest, DebugValueForFunctionCallReturn) {
// Check that InlinePass correctly generates DebugValue instruction
// for function call's return value and maps it to a corresponding
// value in the caller function.
const std::string text = R"(
; CHECK: [[main:%\d+]] = OpString "main"
; CHECK: [[add:%\d+]] = OpString "add"
; CHECK: [[result:%\d+]] = OpString "result"
; CHECK: [[dbg_main:%\d+]] = OpExtInst %void [[ext:%\d+]] DebugFunction [[main]]
; CHECK: [[dbg_add:%\d+]] = OpExtInst %void [[ext:%\d+]] DebugFunction [[add]]
; CHECK: [[dbg_result:%\d+]] = OpExtInst %void [[ext]] DebugLocalVariable [[result]] {{%\d+}} {{%\d+}} 6 2 [[dbg_main]]
; CHECK: [[inlinedat:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 5
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_add]] [[inlinedat]]
; CHECK: [[a_val:%\d+]] = OpLoad %v4float
; CHECK: [[b_val:%\d+]] = OpLoad %v4float
; CHECK: [[res:%\d+]] = OpFAdd %v4float [[a_val]] [[b_val]]
; CHECK: OpStore [[new_result:%\d+]] [[res]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_main]]
; CHECK: [[result_val:%\d+]] = OpLoad %v4float [[new_result]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugValue [[dbg_result]] [[result_val]]
OpCapability Shader
%ext = OpExtInstImport "OpenCL.DebugInfo.100"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %in_var_COLOR %out_var_SV_TARGET
OpExecutionMode %main OriginUpperLeft
%file_name = OpString "ps.hlsl"
OpSource HLSL 600 %file_name
%float_name = OpString "float"
%main_name = OpString "main"
%add_name = OpString "add"
%result_name = OpString "result"
OpDecorate %in_var_COLOR Location 0
OpDecorate %out_var_SV_TARGET Location 0
%uint = OpTypeInt 32 0
%uint_32 = OpConstant %uint 32
%float = OpTypeFloat 32
%float_1 = OpConstant %float 1
%float_2 = OpConstant %float 2
%v4float = OpTypeVector %float 4
%v4f1 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
%v4f2 = OpConstantComposite %v4float %float_2 %float_2 %float_2 %float_2
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%_ptr_Function_v4float = OpTypePointer Function %v4float
%add_fn_type = OpTypeFunction %v4float %_ptr_Function_v4float %_ptr_Function_v4float
%void = OpTypeVoid
%void_fn_type = OpTypeFunction %void
%v4f_fn_type = OpTypeFunction %v4float
%in_var_COLOR = OpVariable %_ptr_Input_v4float Input
%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output
%null_expr = OpExtInst %void %ext DebugExpression
%src = OpExtInst %void %ext DebugSource %file_name
%cu = OpExtInst %void %ext DebugCompilationUnit 1 4 %src HLSL
%dbg_f = OpExtInst %void %ext DebugTypeBasic %float_name %uint_32 Float
%dbg_v4f = OpExtInst %void %ext DebugTypeVector %dbg_f 4
%main_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f
%add_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f %dbg_v4f
%dbg_main = OpExtInst %void %ext DebugFunction %main_name %main_ty %src 5 1 %cu %main_name FlagIsProtected|FlagIsPrivate 10 %main
%dbg_add = OpExtInst %void %ext DebugFunction %add_name %add_ty %src 1 1 %cu %add_name FlagIsProtected|FlagIsPrivate 1 %add
%dbg_result = OpExtInst %void %ext DebugLocalVariable %result_name %dbg_v4f %src 6 2 %dbg_main FlagIsLocal
%main = OpFunction %void None %void_fn_type
%main_bb = OpLabel
%param_a = OpVariable %_ptr_Function_v4float Function
%param_b = OpVariable %_ptr_Function_v4float Function
%scope0 = OpExtInst %void %ext DebugScope %dbg_main
OpStore %param_a %v4f1
OpStore %param_b %v4f2
%result = OpFunctionCall %v4float %add %param_a %param_b
%value = OpExtInst %void %ext DebugValue %dbg_result %result %null_expr
OpStore %out_var_SV_TARGET %result
OpReturn
OpFunctionEnd
%add = OpFunction %v4float None %add_fn_type
%scope1 = OpExtInst %void %ext DebugScope %dbg_add
%a = OpFunctionParameter %_ptr_Function_v4float
%b = OpFunctionParameter %_ptr_Function_v4float
%add_bb = OpLabel
%a_val = OpLoad %v4float %a
%b_val = OpLoad %v4float %b
%res = OpFAdd %v4float %a_val %b_val
OpReturnValue %res
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
TEST_F(InlineTest, NestedWithAnExistingDebugInlinedAt) {
// When a DebugScope instruction in a callee function already has a
// DebugInlinedAt information, we have to create a recursive
// DebugInlinedAt chain. See inlined_to_zoo and inlined_to_bar in
// the following code.
const std::string text = R"(
; CHECK: [[main:%\d+]] = OpString "main"
; CHECK: [[foo:%\d+]] = OpString "foo"
; CHECK: [[bar:%\d+]] = OpString "bar"
; CHECK: [[zoo:%\d+]] = OpString "zoo"
; CHECK: [[v4f1:%\d+]] = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
; CHECK: [[v4f2:%\d+]] = OpConstantComposite %v4float %float_2 %float_2 %float_2 %float_2
; CHECK: [[v4f3:%\d+]] = OpConstantComposite %v4float %float_3 %float_3 %float_3 %float_3
; CHECK: [[dbg_main:%\d+]] = OpExtInst %void [[ext:%\d+]] DebugFunction [[main]]
; CHECK: [[dbg_foo:%\d+]] = OpExtInst %void [[ext]] DebugFunction [[foo]]
; CHECK: [[dbg_bar:%\d+]] = OpExtInst %void [[ext]] DebugFunction [[bar]]
; CHECK: [[dbg_zoo:%\d+]] = OpExtInst %void [[ext]] DebugFunction [[zoo]]
; CHECK: [[inlined_to_main:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 10 [[dbg_main]]
; CHECK: [[inlined_to_zoo:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 7 [[dbg_zoo]] [[inlined_to_main]]
; CHECK: [[inlined_to_main:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 10 [[dbg_main]]
; CHECK: [[inlined_to_bar:%\d+]] = OpExtInst %void [[ext]] DebugInlinedAt 4 [[dbg_bar]] [[inlined_to_zoo]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_foo]] [[inlined_to_bar]]
; CHECK: OpStore [[foo_ret:%\d+]] [[v4f1]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_bar]] [[inlined_to_zoo]]
; CHECK: [[foo_ret_val:%\d+]] = OpLoad %v4float [[foo_ret]]
; CHECK: [[bar_ret:%\d+]] = OpFAdd %v4float [[foo_ret_val]] [[v4f2]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_zoo]] [[inlined_to_main]]
; CHECK: [[zoo_result:%\d+]] = OpFAdd %v4float [[bar_ret]] [[v4f3]]
; CHECK: OpStore [[zoo_ret:%\d+]] [[zoo_result]]
; CHECK: {{%\d+}} = OpExtInst %void [[ext]] DebugScope [[dbg_main]]
; CHECK: [[zoo_ret_val:%\d+]] = OpLoad %v4float [[zoo_ret]]
; CHECK: {{%\d+}} = OpFAdd %v4float [[zoo_ret_val]] {{%\d+}}
OpCapability Shader
%ext = OpExtInstImport "OpenCL.DebugInfo.100"
OpMemoryModel Logical GLSL450
OpEntryPoint Fragment %main "main" %in_var_COLOR %out_var_SV_TARGET
OpExecutionMode %main OriginUpperLeft
%file_name = OpString "ps.hlsl"
OpSource HLSL 600 %file_name
%float_name = OpString "float"
%main_name = OpString "main"
%foo_name = OpString "foo"
%bar_name = OpString "bar"
%zoo_name = OpString "zoo"
OpDecorate %in_var_COLOR Location 0
OpDecorate %out_var_SV_TARGET Location 0
%uint = OpTypeInt 32 0
%uint_32 = OpConstant %uint 32
%float = OpTypeFloat 32
%float_1 = OpConstant %float 1
%float_2 = OpConstant %float 2
%float_3 = OpConstant %float 3
%v4float = OpTypeVector %float 4
%v4f1 = OpConstantComposite %v4float %float_1 %float_1 %float_1 %float_1
%v4f2 = OpConstantComposite %v4float %float_2 %float_2 %float_2 %float_2
%v4f3 = OpConstantComposite %v4float %float_3 %float_3 %float_3 %float_3
%_ptr_Input_v4float = OpTypePointer Input %v4float
%_ptr_Output_v4float = OpTypePointer Output %v4float
%void = OpTypeVoid
%void_fn_type = OpTypeFunction %void
%v4f_fn_type = OpTypeFunction %v4float
%in_var_COLOR = OpVariable %_ptr_Input_v4float Input
%out_var_SV_TARGET = OpVariable %_ptr_Output_v4float Output
%src = OpExtInst %void %ext DebugSource %file_name
%cu = OpExtInst %void %ext DebugCompilationUnit 1 4 %src HLSL
%dbg_f = OpExtInst %void %ext DebugTypeBasic %float_name %uint_32 Float
%dbg_v4f = OpExtInst %void %ext DebugTypeVector %dbg_f 4
%main_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f %dbg_v4f
%foo_ty = OpExtInst %void %ext DebugTypeFunction FlagIsProtected|FlagIsPrivate %dbg_v4f
%dbg_main = OpExtInst %void %ext DebugFunction %main_name %main_ty %src 10 1 %cu %main_name FlagIsProtected|FlagIsPrivate 10 %main
%dbg_foo = OpExtInst %void %ext DebugFunction %foo_name %foo_ty %src 1 1 %cu %foo_name FlagIsProtected|FlagIsPrivate 1 %foo
%dbg_bar = OpExtInst %void %ext DebugFunction %bar_name %foo_ty %src 4 1 %cu %bar_name FlagIsProtected|FlagIsPrivate 4 %bar
%dbg_zoo = OpExtInst %void %ext DebugFunction %zoo_name %foo_ty %src 7 1 %cu %zoo_name FlagIsProtected|FlagIsPrivate 7 %zoo
%inlined_to_zoo = OpExtInst %void %ext DebugInlinedAt 7 %dbg_zoo
%main = OpFunction %void None %void_fn_type
%main_bb = OpLabel
%scope0 = OpExtInst %void %ext DebugScope %dbg_main
%zoo_val = OpFunctionCall %v4float %zoo
%color = OpLoad %v4float %in_var_COLOR
%result = OpFAdd %v4float %zoo_val %color
OpStore %out_var_SV_TARGET %result
OpReturn
OpFunctionEnd
%foo = OpFunction %v4float None %v4f_fn_type
%scope1 = OpExtInst %void %ext DebugScope %dbg_foo
%foo_bb = OpLabel
OpReturnValue %v4f1
OpFunctionEnd
%zoo = OpFunction %v4float None %v4f_fn_type
%scope3 = OpExtInst %void %ext DebugScope %dbg_zoo
%zoo_bb = OpLabel
%scope2 = OpExtInst %void %ext DebugScope %dbg_bar %inlined_to_zoo
%foo_val = OpFunctionCall %v4float %foo
%bar_val = OpFAdd %v4float %foo_val %v4f2
%scope4 = OpExtInst %void %ext DebugScope %dbg_zoo
%zoo_ret = OpFAdd %v4float %bar_val %v4f3
OpReturnValue %zoo_ret
OpFunctionEnd
%bar = OpFunction %v4float None %v4f_fn_type
%scope5 = OpExtInst %void %ext DebugScope %dbg_bar
%bar_bb = OpLabel
%foo_val0 = OpFunctionCall %v4float %foo
%bar_ret = OpFAdd %v4float %foo_val0 %v4f2
OpReturnValue %bar_ret
OpFunctionEnd
)";
SinglePassRunAndMatch<InlineExhaustivePass>(text, true);
}
// TODO(greg-lunarg): Add tests to verify handling of these cases:
//
// Empty modules
// Modules without function definitions
// Modules in which all functions do not call other functions
// Caller and callee both accessing the same global variable
// Functions with OpLine & OpNoLine
// Others?
// TODO(dneto): Test suggestions from code review
// https://github.com/KhronosGroup/SPIRV-Tools/pull/534
//
// Callee function returns a value generated outside the callee,
// e.g. a constant value. This might exercise some logic not yet
// exercised by the current tests: the false branch in the "if"
// inside the SpvOpReturnValue case in InlinePass::GenInlineCode?
// SampledImage before function call, but callee is only single block.
// Then the SampledImage instruction is not cloned. Documents existing
// behaviour.
// SampledImage after function call. It is not cloned or changed.
} // namespace
} // namespace opt
} // namespace spvtools
|
IDD_DLGVERSION equ 1700
IDC_EDTVERFILE equ 2903
IDC_EDTVERPROD equ 2904
IDC_CBOVEROS equ 2905
IDC_CBOVERTYPE equ 2906
IDC_CBOVERLANG equ 2907
IDC_CBOVERCHAR equ 2908
IDC_LSTVER equ 2909
IDC_EDTVER equ 2910
IDC_EDTVERTPE equ 2911
IDC_BTNVERADD equ 2912
.const
szVerOS dd 00000004h
db 'WINDOWS32',0
dd 00000000h
db 'UNKNOWN',0
dd 00010000h
db 'DOS',0
dd 00020000h
db 'OS216',0
dd 00030000h
db 'OS232',0
dd 00040000h
db 'NT',0
dd 00000000h
db 'BASE',0
dd 00000001h
db 'WINDOWS16',0
dd 00000002h
db 'PM16',0
dd 00000003h
db 'PM32',0
dd 00010001h
db 'DOS_WINDOWS16',0
dd 00010004h
db 'DOS_WINDOWS32',0
dd 00020002h
db 'OS216_PM16',0
dd 00030003h
db 'OS232_PM32',0
dd 00040004h
db 'NT_WINDOWS32',0
dd 0,0
szVerFT dd 00000000h
db 'UNKNOWN',0
dd 00000001h
db 'APP',0
dd 00000002h
db 'DLL',0
dd 00000003h
db 'DRV',0
dd 00000004h
db 'FONT',0
dd 00000005h
db 'VXD',0
dd 00000007h
db 'STATIC_LIB',0
dd 0,0
szVerLNG dd 0409h
db 'U.S. English',0
dd 0401h
db 'Arabic',0
dd 0402h
db 'Bulgarian',0
dd 0403h
db 'Catalan',0
dd 0404h
db 'Traditional Chinese',0
dd 0405h
db 'Czech',0
dd 0406h
db 'Danish',0
dd 0407h
db 'German',0
dd 0408h
db 'Greek',0
dd 040Ah
db 'Castilian Spanish',0
dd 040Bh
db 'Finnish',0
dd 040Ch
db 'French',0
dd 040Dh
db 'Hebrew',0
dd 040Eh
db 'Hungarian',0
dd 040Fh
db 'Icelandic',0
dd 0410h
db 'Italian',0
dd 0411h
db 'Japanese',0
dd 0412h
db 'Korean',0
dd 0413h
db 'Dutch',0
dd 0414h
db 'Norwegian - Bokml',0
dd 0415h
db 'Polish',0
dd 0416h
db 'Brazilian Portuguese',0
dd 0417h
db 'Rhaeto-Romanic',0
dd 0417h
db 'Rhaeto-Romanic',0
dd 0418h
db 'Romanian',0
dd 0419h
db 'Russian',0
dd 041Ah
db 'Croato-Serbian (Latin)',0
dd 041Bh
db 'Slovak',0
dd 041Ch
db 'Albanian',0
dd 041Dh
db 'Swedish',0
dd 041Eh
db 'Thai',0
dd 041Fh
db 'Turkish',0
dd 0420h
db 'Urdu',0
dd 0421h
db 'Bahasa',0
dd 0804h
db 'Simplified Chinese',0
dd 0807h
db 'Swiss German',0
dd 0809h
db 'U.K. English',0
dd 080Ah
db 'Mexican Spanish',0
dd 080Ch
db 'Belgian French',0
dd 0810h
db 'Swiss Italian',0
dd 0813h
db 'Belgian Dutch',0
dd 0814h
db 'Norwegian - Nynorsk',0
dd 0816h
db 'Portuguese',0
dd 081Ah
db 'Serbo-Croatian (Cyrillic)',0
dd 0C0Ch
db 'Canadian French',0
dd 100Ch
db 'Swiss French',0
dd 0,0
szVerCHS dd 1200
db 'Unicode',0
dd 0
db '7-bit ASCII',0
dd 932
db 'Japan (Shift - JIS X-0208)',0
dd 949
db 'Korea (Shift - KSC 5601)',0
dd 950
db 'Taiwan (GB5)',0
dd 1250
db 'Latin-2 (Eastern European)',0
dd 1251
db 'Cyrillic',0
dd 1252
db 'Multilingual',0
dd 1253
db 'Greek',0
dd 1254
db 'Turkish',0
dd 1255
db 'Hebrew',0
dd 1256
db 'Arabic',0
dd 0,0
szVerTpe db 'CompanyName',0
db 'FileVersion',0
db 'FileDescription',0
db 'InternalName',0
db 'LegalCopyright',0
db 'LegalTrademarks',0
db 'OriginalFilename',0
db 'ProductName',0
db 'ProductVersion',0
db 0
szStringFileInfo db 'StringFileInfo',0
szVarFileInfo db 'VarFileInfo',0
szTranslation db 'Translation',0
.data
szVersionName db 'IDR_VERSION',0
defver VERSIONMEM <,1,1,0,0,0,1,0,0,0,4,0,409h,4B0h>
VERSIONITEM <"FileVersion","1.0.0.0">
VERSIONITEM <"ProductVersion","1.0.0.0">
VERSIONITEM 30 dup(<>)
.data?
szVersionTxt db 32*256 dup(?)
lpOldEditProc dd ?
hVerDlg dd ?
.code
IncrementVersion proc lpProMem:DWORD
mov eax,hDialog
.if eax && eax==hVerDlg
invoke CloseDialog
.endif
RADbg 0,2097726,0
RADbg 0,1181728,0
invoke GetTypeMem,lpProMem,TPE_VERSION
.if eax
mov edx,[eax].PROJECT.hmem
inc [edx].VERSIONMEM.fv3
inc [edx].VERSIONMEM.pv3
mov [eax].PROJECT.changed,TRUE
.endif
ret
IncrementVersion endp
ExportVersionNames proc uses esi edi,hMem:DWORD
invoke xGlobalAlloc,GMEM_FIXED or GMEM_ZEROINIT,1024*16
mov edi,eax
invoke GlobalLock,edi
push edi
mov esi,hMem
;#define
.if [esi].VERSIONMEM.szname && [esi].VERSIONMEM.value
invoke ExportName,addr [esi].VERSIONMEM.szname,[esi].VERSIONMEM.value,edi
lea edi,[edi+eax]
.endif
pop eax
ret
ExportVersionNames endp
ExportVersion proc uses esi edi,hMem:DWORD
invoke xGlobalAlloc,GMEM_FIXED or GMEM_ZEROINIT,1024*16
mov edi,eax
invoke GlobalLock,edi
push edi
mov esi,hMem
;Name or ID
.if [esi].VERSIONMEM.szname
invoke strcpy,edi,addr [esi].VERSIONMEM.szname
.else
invoke ResEdBinToDec,[esi].VERSIONMEM.value,edi
.endif
invoke strlen,edi
add edi,eax
mov al,' '
stosb
invoke SaveStr,edi,addr szVERSIONINFO
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
;File version
invoke SaveStr,edi,addr szFILEVERSION
add edi,eax
mov al,' '
stosb
push esi
lea esi,[esi].VERSIONMEM.fv
call SaveVer
pop esi
;Product version
invoke SaveStr,edi,addr szPRODUCTVERSION
add edi,eax
mov al,' '
stosb
push esi
lea esi,[esi].VERSIONMEM.pv
call SaveVer
pop esi
;File OS
invoke SaveStr,edi,addr szFILEOS
add edi,eax
mov al,' '
stosb
mov eax,[esi].VERSIONMEM.os
call SaveHex
;File type
invoke SaveStr,edi,addr szFILETYPE
add edi,eax
mov al,' '
stosb
mov eax,[esi].VERSIONMEM.ft
call SaveHex
invoke SaveStr,edi,addr szBEGIN
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
invoke SaveStr,edi,addr szBLOCK
add edi,eax
mov al,' '
stosb
mov al,22h
stosb
invoke SaveStr,edi,addr szStringFileInfo
add edi,eax
mov al,22h
stosb
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
invoke SaveStr,edi,addr szBEGIN
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
stosb
stosb
invoke SaveStr,edi,addr szBLOCK
add edi,eax
mov al,' '
stosb
mov al,22h
stosb
mov eax,[esi].VERSIONMEM.lng
invoke hexEax
invoke strcpy,edi,offset strHex+4
add edi,4
mov eax,[esi].VERSIONMEM.chs
invoke hexEax
invoke strcpy,edi,offset strHex+4
add edi,4
mov al,22h
stosb
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
stosb
stosb
invoke SaveStr,edi,addr szBEGIN
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
push esi
lea esi,[esi+sizeof VERSIONMEM]
.while TRUE
.break .if ![esi].VERSIONITEM.szname
.if [esi].VERSIONITEM.szvalue
mov al,' '
stosb
stosb
stosb
stosb
stosb
stosb
invoke SaveStr,edi,addr szVALUE
add edi,eax
mov al,' '
stosb
mov al,22h
stosb
invoke SaveStr,edi,addr [esi].VERSIONITEM.szname
add edi,eax
mov al,22h
stosb
mov al,','
stosb
mov al,' '
stosb
mov al,22h
stosb
invoke SaveStr,edi,addr [esi].VERSIONITEM.szvalue
add edi,eax
mov al,'\'
stosb
mov al,'0'
stosb
mov al,22h
stosb
mov al,0Dh
stosb
mov al,0Ah
stosb
.endif
lea esi,[esi+sizeof VERSIONITEM]
.endw
pop esi
mov al,' '
stosb
stosb
stosb
stosb
invoke SaveStr,edi,addr szEND
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
invoke SaveStr,edi,addr szEND
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
invoke SaveStr,edi,addr szBLOCK
add edi,eax
mov al,' '
stosb
mov al,22h
stosb
invoke SaveStr,edi,addr szVarFileInfo
add edi,eax
mov al,22h
stosb
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
invoke SaveStr,edi,addr szBEGIN
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
stosb
stosb
invoke SaveStr,edi,addr szVALUE
add edi,eax
mov al,' '
stosb
mov al,22h
stosb
invoke SaveStr,edi,addr szTranslation
add edi,eax
mov al,22h
stosb
mov al,','
stosb
mov al,' '
stosb
mov al,'0'
stosb
mov al,'x'
stosb
mov eax,[esi].VERSIONMEM.lng
invoke hexEax
invoke strcpy,edi,offset strHex+4
add edi,4
mov al,','
stosb
mov al,' '
stosb
mov al,'0'
stosb
mov al,'x'
stosb
mov eax,[esi].VERSIONMEM.chs
invoke hexEax
invoke strcpy,edi,offset strHex+4
add edi,4
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,' '
stosb
stosb
invoke SaveStr,edi,addr szEND
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
invoke SaveStr,edi,addr szEND
add edi,eax
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,0Dh
stosb
mov al,0Ah
stosb
mov al,0
stosb
pop eax
ret
SaveVer:
mov eax,[esi]
call SaveVerItem
mov eax,[esi+4]
call SaveVerItem
mov eax,[esi+8]
call SaveVerItem
mov eax,[esi+12]
call SaveVerItem
dec edi
mov al,0Dh
stosb
mov al,0Ah
stosb
retn
SaveVerItem:
invoke ResEdBinToDec,eax,edi
invoke strlen,edi
lea edi,[edi+eax]
mov al,','
stosb
retn
SaveHex:
mov word ptr [edi],'x0'
add edi,2
invoke hexEax
invoke strcpy,edi,offset strHex
add edi,8
mov al,0Dh
stosb
mov al,0Ah
stosb
retn
ExportVersion endp
SaveVersionEdit proc uses ebx esi edi,hWin:HWND
LOCAL nInx:DWORD
LOCAL buffer[512]:BYTE
invoke GetWindowLong,hWin,GWL_USERDATA
.if !eax
invoke SendMessage,hRes,PRO_ADDITEM,TPE_VERSION,FALSE
push eax
invoke RtlMoveMemory,[eax].PROJECT.hmem,offset defver,sizeof VERSIONMEM+sizeof VERSIONITEM*32
pop eax
.endif
mov ebx,eax
push ebx
mov esi,[ebx].PROJECT.hmem
invoke GetProjectItemName,ebx,addr buffer
invoke SetProjectItemName,ebx,addr buffer
invoke GetDlgItemText,hWin,IDC_EDTVERFILE,addr buffer,16
push esi
lea esi,[esi].VERSIONMEM.fv
call GetVerNum
pop esi
invoke GetDlgItemText,hWin,IDC_EDTVERPROD,addr buffer,16
push esi
lea esi,[esi].VERSIONMEM.pv
call GetVerNum
pop esi
invoke SendDlgItemMessage,hWin,IDC_CBOVEROS,CB_GETCURSEL,0,0
invoke SendDlgItemMessage,hWin,IDC_CBOVEROS,CB_GETITEMDATA,eax,0
mov [esi].VERSIONMEM.os,eax
invoke SendDlgItemMessage,hWin,IDC_CBOVERTYPE,CB_GETCURSEL,0,0
invoke SendDlgItemMessage,hWin,IDC_CBOVERTYPE,CB_GETITEMDATA,eax,0
mov [esi].VERSIONMEM.ft,eax
invoke SendDlgItemMessage,hWin,IDC_CBOVERLANG,CB_GETCURSEL,0,0
invoke SendDlgItemMessage,hWin,IDC_CBOVERLANG,CB_GETITEMDATA,eax,0
mov [esi].VERSIONMEM.lng,eax
invoke SendDlgItemMessage,hWin,IDC_CBOVERCHAR,CB_GETCURSEL,0,0
invoke SendDlgItemMessage,hWin,IDC_CBOVERCHAR,CB_GETITEMDATA,eax,0
mov [esi].VERSIONMEM.chs,eax
lea esi,[esi+sizeof VERSIONMEM]
mov nInx,0
.while TRUE
mov [esi].VERSIONITEM.szname,0
mov [esi].VERSIONITEM.szvalue,0
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_GETTEXT,nInx,addr [esi].VERSIONITEM.szname
.break .if eax==LB_ERR
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_GETITEMDATA,nInx,0
invoke strcpy,addr [esi].VERSIONITEM.szvalue,eax
lea esi,[esi+sizeof VERSIONITEM]
inc nInx
.endw
pop eax
ret
GetVerNum:
lea edi,buffer
call GetVerNumItem
mov [esi],eax
call GetVerNumItem
mov [esi+4],eax
call GetVerNumItem
mov [esi+8],eax
call GetVerNumItem
mov [esi+12],eax
retn
GetVerNumItem:
invoke ResEdDecToBin,edi
.while byte ptr [edi]!='.' && byte ptr [edi]
inc edi
.endw
.if byte ptr [edi]=='.'
inc edi
.endif
retn
SaveVersionEdit endp
VersionSetCbo proc uses esi,hWin:HWND,nID:DWORD,lpKey:DWORD,nVal:DWORD
LOCAL nInx:DWORD
mov esi,lpKey
.while byte ptr [esi+4]
push [esi]
add esi,4
invoke SendDlgItemMessage,hWin,nID,CB_ADDSTRING,0,esi
pop edx
invoke SendDlgItemMessage,hWin,nID,CB_SETITEMDATA,eax,edx
invoke strlen,esi
lea esi,[esi+eax+1]
.endw
mov nInx,0
.while TRUE
invoke SendDlgItemMessage,hWin,nID,CB_GETITEMDATA,nInx,0
.break .if eax==CB_ERR
.if eax==nVal
invoke SendDlgItemMessage,hWin,nID,CB_SETCURSEL,nInx,0
.break
.endif
inc nInx
.endw
ret
VersionSetCbo endp
EditProc proc hWin:HWND,uMsg:UINT,wParam:WPARAM,lParam:LPARAM
.if uMsg==WM_CHAR
.if wParam==VK_RETURN
invoke GetParent,hWin
invoke PostMessage,eax,WM_COMMAND,IDC_BTNVERADD,hWin
xor eax,eax
ret
.endif
.endif
invoke CallWindowProc,lpOldEditProc,hWin,uMsg,wParam,lParam
ret
EditProc endp
VersionEditProc proc uses esi edi,hWin:HWND,uMsg:UINT,wParam:WPARAM,lParam:LPARAM
LOCAL nInx:DWORD
LOCAL buffer[512]:BYTE
LOCAL rect:RECT
LOCAL fChanged:DWORD
mov eax,uMsg
.if eax==WM_INITDIALOG
mov eax,hWin
mov hVerDlg,eax
mov fChanged,FALSE
mov esi,lParam
invoke SetWindowLong,hWin,GWL_USERDATA,esi
.if esi
mov esi,[esi].PROJECT.hmem
.else
invoke GetFreeProjectitemID,TPE_VERSION
mov esi,offset defver
mov [esi].VERSIONMEM.value,eax
invoke strcpy,addr [esi].VERSIONMEM.szname,addr szVersionName
invoke GetUnikeName,addr [esi].VERSIONMEM.szname
mov fChanged,TRUE
.endif
invoke RtlZeroMemory,offset szVersionTxt,sizeof szVersionTxt
mov lpResType,offset szVERSIONINFO
lea eax,[esi].VERSIONMEM.szname
mov lpResName,eax
lea eax,[esi].VERSIONMEM.value
mov lpResID,eax
invoke SendDlgItemMessage,hWin,IDC_EDTVERFILE,EM_LIMITTEXT,16,0
push esi
lea esi,[esi].VERSIONMEM.fv
call ConvVer
pop esi
invoke SetDlgItemText,hWin,IDC_EDTVERFILE,addr buffer
invoke SendDlgItemMessage,hWin,IDC_EDTVERPROD,EM_LIMITTEXT,16,0
push esi
lea esi,[esi].VERSIONMEM.pv
call ConvVer
pop esi
invoke SetDlgItemText,hWin,IDC_EDTVERPROD,addr buffer
invoke VersionSetCbo,hWin,IDC_CBOVEROS,offset szVerOS,[esi].VERSIONMEM.os
invoke VersionSetCbo,hWin,IDC_CBOVERTYPE,offset szVerFT,[esi].VERSIONMEM.ft
invoke VersionSetCbo,hWin,IDC_CBOVERLANG,addr szVerLNG,[esi].VERSIONMEM.lng
invoke VersionSetCbo,hWin,IDC_CBOVERCHAR,addr szVerCHS,[esi].VERSIONMEM.chs
lea esi,[esi+sizeof VERSIONMEM]
mov edi,offset szVerTpe
.while byte ptr [edi]
call AddTpe
invoke strlen,edi
lea edi,[edi+eax+1]
.endw
mov edi,offset szVersionTxt
.while [esi].VERSIONITEM.szname
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_ADDSTRING,0,addr [esi].VERSIONITEM.szname
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_SETITEMDATA,eax,edi
invoke strcpy,edi,addr [esi].VERSIONITEM.szvalue
add edi,256
lea esi,[esi+sizeof VERSIONITEM]
.endw
invoke SendDlgItemMessage,hWin,IDC_EDTVER,EM_LIMITTEXT,255,0
invoke SendDlgItemMessage,hWin,IDC_EDTVERTPE,EM_LIMITTEXT,63,0
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_SETCURSEL,0,0
invoke SendMessage,hWin,WM_COMMAND,(LBN_SELCHANGE shl 16) or IDC_LSTVER,0
invoke GetDlgItem,hWin,IDC_EDTVERTPE
mov edx,eax
invoke SetWindowLong,edx,GWL_WNDPROC,addr EditProc
mov lpOldEditProc,eax
invoke GetWindowLong,hWin,GWL_USERDATA
.if !eax
invoke SaveVersionEdit,hWin
invoke SetWindowLong,hWin,GWL_USERDATA,eax
.endif
invoke PropertyList,-2
mov fNoScroll,TRUE
invoke ShowScrollBar,hDEd,SB_BOTH,FALSE
invoke SendMessage,hWin,WM_SIZE,0,0
mov eax,fChanged
mov fDialogChanged,eax
.elseif eax==WM_COMMAND
mov eax,wParam
mov edx,eax
shr edx,16
and eax,0FFFFh
.if edx==BN_CLICKED
.if eax==IDOK
invoke SaveVersionEdit,hWin
.if fDialogChanged
invoke SendMessage,hRes,PRO_SETMODIFY,TRUE,0
mov fDialogChanged,FALSE
.endif
.elseif eax==IDCANCEL
invoke SendMessage,hWin,WM_CLOSE,NULL,NULL
invoke PropertyList,0
.elseif eax==IDC_BTNVERADD
invoke SendDlgItemMessage,hWin,IDC_EDTVERTPE,WM_GETTEXT,sizeof buffer,addr buffer
.if eax
lea edi,buffer
invoke GetWindowLong,hWin,GWL_USERDATA
.if eax
mov esi,[eax].PROJECT.hmem
.else
mov esi,offset defver
.endif
lea esi,[esi+sizeof VERSIONMEM]
call AddTpe
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_RESETCONTENT,0,0
mov edi,offset szVersionTxt
mov nInx,-1
.while [esi].VERSIONITEM.szname
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_ADDSTRING,0,addr [esi].VERSIONITEM.szname
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_SETITEMDATA,eax,edi
invoke strcpy,edi,addr [esi].VERSIONITEM.szvalue
inc nInx
add edi,256
lea esi,[esi+sizeof VERSIONITEM]
.endw
mov buffer,0
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_SETCURSEL,nInx,0
invoke SendDlgItemMessage,hWin,IDC_EDTVERTPE,WM_SETTEXT,0,addr buffer
invoke SendMessage,hWin,WM_COMMAND,(LBN_SELCHANGE shl 16) or IDC_LSTVER,0
invoke GetDlgItem,hWin,IDC_BTNVERADD
invoke EnableWindow,eax,FALSE
.endif
.endif
.elseif edx==EN_CHANGE
.if eax==IDC_EDTVER
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_GETCURSEL,0,0
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_GETITEMDATA,eax,0
invoke SendDlgItemMessage,hWin,IDC_EDTVER,WM_GETTEXT,256,eax
.elseif eax==IDC_EDTVERTPE
invoke GetDlgItem,hWin,IDC_BTNVERADD
push eax
invoke SendDlgItemMessage,hWin,IDC_EDTVERTPE,WM_GETTEXTLENGTH,0,0
pop edx
invoke EnableWindow,edx,eax
.endif
mov fDialogChanged,TRUE
invoke NotifyParent
.elseif edx==LBN_SELCHANGE
.if eax==IDC_LSTVER
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_GETCURSEL,0,0
.if eax!=LB_ERR
invoke SendDlgItemMessage,hWin,IDC_LSTVER,LB_GETITEMDATA,eax,0
invoke SendDlgItemMessage,hWin,IDC_EDTVER,WM_SETTEXT,0,eax
.endif
.endif
mov fDialogChanged,TRUE
invoke NotifyParent
.endif
.elseif eax==WM_CLOSE
mov fNoScroll,FALSE
invoke ShowScrollBar,hDEd,SB_BOTH,TRUE
invoke DestroyWindow,hWin
mov hVerDlg,0
.elseif eax==WM_SIZE
invoke SendMessage,hDEd,WM_VSCROLL,SB_THUMBTRACK,0
invoke SendMessage,hDEd,WM_HSCROLL,SB_THUMBTRACK,0
invoke GetClientRect,hDEd,addr rect
mov rect.left,3
mov rect.top,3
sub rect.right,6
sub rect.bottom,6
invoke MoveWindow,hWin,rect.left,rect.top,rect.right,rect.bottom,TRUE
.else
mov eax,FALSE
ret
.endif
mov eax,TRUE
ret
ConvVer:
lea edi,buffer
invoke ResEdBinToDec,[esi],edi
invoke strlen,edi
lea edi,[edi+eax]
mov al,'.'
stosb
invoke ResEdBinToDec,[esi+4],edi
invoke strlen,edi
lea edi,[edi+eax]
mov al,'.'
stosb
invoke ResEdBinToDec,[esi+8],edi
invoke strlen,edi
lea edi,[edi+eax]
mov al,'.'
stosb
invoke ResEdBinToDec,[esi+12],edi
retn
AddTpe:
push esi
.while [esi].VERSIONITEM.szname
invoke strcmpi,addr [esi].VERSIONITEM.szname,edi
.break .if !eax
lea esi,[esi+sizeof VERSIONITEM]
.endw
invoke strcpy,addr [esi].VERSIONITEM.szname,edi
pop esi
retn
VersionEditProc endp
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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 "tensorflow/compiler/xla/service/convolution_feature_group_converter.h"
#include <memory>
#include <vector>
#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
namespace {
// ConvolutionVisitor traverses the HLO computation and rewrites Convolution
// operations with feature_group_count > 1 into convolutions with
// feature_group_count = 1.
class ConvolutionVisitor : public DfsHloVisitorWithDefault {
public:
// Default visitor action is to do nothing and return OK.
Status DefaultAction(HloInstruction* /*hlo_instruction*/) override {
return Status::OK();
}
Status HandleConvolution(HloInstruction* convolution) override;
// Runs the visitor on a computation.
static bool Run(HloComputation* computation);
// Returns whether any convolution ops were rewritten.
const bool changed() const { return changed_; }
~ConvolutionVisitor() override = default;
private:
explicit ConvolutionVisitor(HloComputation* computation)
: computation_(computation) {}
// Current HloComputation instance the ConvolutionVisitor is traversing.
HloComputation* computation_;
// Whether rewrite has occurred.
bool changed_ = false;
};
bool ConvolutionVisitor::Run(HloComputation* computation) {
ConvolutionVisitor visitor(computation);
TF_CHECK_OK(computation->Accept(&visitor));
return visitor.changed_;
}
Shape ExpandedFilterShape(const Shape& shape, int64 group_count,
int64 input_feature_dim) {
int64 num_dims = shape.dimensions_size();
CHECK_GE(num_dims, 2);
Shape expanded_shape = shape;
expanded_shape.set_dimensions(
input_feature_dim, shape.dimensions(input_feature_dim) * group_count);
return expanded_shape;
}
// Returns a vector with 'group_count' many groups, where the i-th group
// consists of 'group_size' times the value i.
std::vector<int32> GetMaskIds(int64 group_size, int64 group_count) {
std::vector<int32> values;
for (int i = 0; i < group_count; ++i) {
for (int j = 0; j < group_size; ++j) {
values.push_back(i);
}
}
return values;
}
// Create a mask for grouped convolution that will make a normal convolution
// produce the same results as a grouped convolution. For a [2, 1, 6]
// filter this returns a [2, 3, 6] mask
// 1 1 0 0 0 0
// 0 0 1 1 0 0
// 0 0 0 0 1 1
//
// 1 1 0 0 0 0
// 0 0 1 1 0 0
// 0 0 0 0 1 1
//
// The first step is to create a rank 1 constant:
// 0 1 2
//
// This is broadcasted to
// 0 0 0 0 0 0
// 1 1 1 1 1 1
// 2 2 2 2 2 2
//
// 0 0 0 0 0 0
// 1 1 1 1 1 1
// 2 2 2 2 2 2
//
// Then we create another rank 1 constant
// 0 0 1 1 2 2
//
// This is broadcasted to
// 0 0 1 1 2 2
// 0 0 1 1 2 2
// 0 0 1 1 2 2
//
// 0 0 1 1 2 2
// 0 0 1 1 2 2
// 0 0 1 1 2 2
//
// Finally we use the Eq op of these two broadcasted constants and get the
// desired mask.
HloInstruction* GetExpandedFilterMask(
const Shape& filter_shape, int64 input_feature_dim,
int64 output_feature_dim, int64 group_count,
const std::function<HloInstruction*(std::unique_ptr<HloInstruction>)>&
add_instruction) {
Shape expanded_filter_shape =
ExpandedFilterShape(filter_shape, group_count, input_feature_dim);
Shape mask_shape = ShapeUtil::MakeShape(
S32, AsInt64Slice(expanded_filter_shape.dimensions()));
int64 output_feature = filter_shape.dimensions(output_feature_dim);
int64 group_size = filter_shape.dimensions(input_feature_dim);
// Create a 'input_feature' sized linspace and 'output_feature' sized linspace
// that will be broadcasted into perpendicular dimensions and compared.
const std::vector<int32> input_feature_filter_mask =
GetMaskIds(group_size, group_count);
const std::vector<int32> output_feature_filter_mask =
GetMaskIds(output_feature / group_count, group_count);
auto mask1 = add_instruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR1<int32>(input_feature_filter_mask)));
auto broadcasted_mask1 = add_instruction(
HloInstruction::CreateBroadcast(mask_shape, mask1, {input_feature_dim}));
auto mask2 = add_instruction(HloInstruction::CreateConstant(
LiteralUtil::CreateR1<int32>(output_feature_filter_mask)));
auto broadcasted_mask2 = add_instruction(
HloInstruction::CreateBroadcast(mask_shape, mask2, {output_feature_dim}));
// Compare the broadcasted output feature linspace to the input feature
// linspace to create a diagonal predicate.
Shape predicate_shape = ShapeUtil::MakeShape(
PRED, AsInt64Slice(expanded_filter_shape.dimensions()));
return add_instruction(HloInstruction::CreateBinary(
predicate_shape, HloOpcode::kEq, broadcasted_mask1, broadcasted_mask2));
}
Status ConvolutionVisitor::HandleConvolution(HloInstruction* convolution) {
int64 group_count = convolution->feature_group_count();
if (group_count == 1) {
return Status::OK();
}
auto filter = convolution->mutable_operand(1);
changed_ = true;
auto add = [&](std::unique_ptr<HloInstruction> inst) {
return computation_->AddInstruction(std::move(inst));
};
auto dim_numbers = convolution->convolution_dimension_numbers();
int64 input_feature_dim = dim_numbers.kernel_input_feature_dimension();
int64 group_size = filter->shape().dimensions(input_feature_dim);
int64 output_feature_dim = dim_numbers.kernel_output_feature_dimension();
auto expanded_filter_shape =
ExpandedFilterShape(filter->shape(), group_count, input_feature_dim);
HloInstruction* filter_mask = GetExpandedFilterMask(
filter->shape(), input_feature_dim, output_feature_dim, group_count, add);
HloInstruction* expanded_filter;
// We want to repeat 'filter' in the 'input_feature_dim' dimension
// 'group_count' times.
if (group_size == 1) {
Shape reshaped_filter_shape =
ShapeUtil::DeleteDimension(input_feature_dim, filter->shape());
auto reshaped_filter =
add(HloInstruction::CreateReshape(reshaped_filter_shape, filter));
std::vector<int64> broadcast_dims;
for (int64 i = 0; i < filter->shape().dimensions_size(); ++i) {
if (i == input_feature_dim) {
continue;
}
broadcast_dims.push_back(i);
}
expanded_filter = add(HloInstruction::CreateBroadcast(
expanded_filter_shape, reshaped_filter, broadcast_dims));
} else {
// We could possibly also use reshape, broadcast, reshape instead of concat
// here, but it would require more complex code, and for depthwise
// convolution we would never end up in this branch.
std::vector<HloInstruction*> concat_operands(group_count, filter);
expanded_filter = add(HloInstruction::CreateConcatenate(
expanded_filter_shape, concat_operands, input_feature_dim));
}
auto zero = add(HloInstruction::CreateConstant(absl::make_unique<Literal>(
LiteralUtil::Zero(expanded_filter_shape.element_type()))));
auto zero_filter =
add(HloInstruction::CreateBroadcast(expanded_filter_shape, zero, {}));
auto new_filter = add(
HloInstruction::CreateTernary(expanded_filter_shape, HloOpcode::kSelect,
filter_mask, expanded_filter, zero_filter));
auto new_convolution = HloInstruction::CreateConvolve(
convolution->shape(), convolution->mutable_operand(0), new_filter,
/*feature_group_count=*/1, convolution->window(), dim_numbers,
convolution->precision_config());
TF_RETURN_IF_ERROR(computation_->ReplaceWithNewInstruction(
convolution, std::move(new_convolution)));
return Status::OK();
}
} // namespace
StatusOr<bool> ConvolutionFeatureGroupConverter::Run(HloModule* module) {
XLA_VLOG_LINES(2, "ConvolutionFeatureGroupConverter::Run(), before:\n" +
module->ToString());
bool changed = false;
for (auto* comp : module->MakeNonfusionComputations()) {
if (ConvolutionVisitor::Run(comp)) {
changed = true;
}
}
XLA_VLOG_LINES(2, "ConvolutionFeatureGroupConverter::Run(), after:\n" +
module->ToString());
return changed;
}
} // namespace xla
|
//=- WebAssemblyInstPrinter.cpp - WebAssembly assembly instruction printing -=//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Print MCInst instructions to wasm format.
///
//===----------------------------------------------------------------------===//
#include "MCTargetDesc/WebAssemblyInstPrinter.h"
#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "WebAssembly.h"
#include "WebAssemblyMachineFunctionInfo.h"
#include "WebAssemblyUtilities.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/FormattedStream.h"
using namespace llvm;
#define DEBUG_TYPE "asm-printer"
#include "WebAssemblyGenAsmWriter.inc"
WebAssemblyInstPrinter::WebAssemblyInstPrinter(const MCAsmInfo &MAI,
const MCInstrInfo &MII,
const MCRegisterInfo &MRI)
: MCInstPrinter(MAI, MII, MRI) {}
void WebAssemblyInstPrinter::printRegName(raw_ostream &OS,
unsigned RegNo) const {
assert(RegNo != WebAssemblyFunctionInfo::UnusedReg);
// Note that there's an implicit local.get/local.set here!
OS << "$" << RegNo;
}
void WebAssemblyInstPrinter::printInst(const MCInst *MI, uint64_t Address,
StringRef Annot,
const MCSubtargetInfo &STI,
raw_ostream &OS) {
// Print the instruction (this uses the AsmStrings from the .td files).
printInstruction(MI, Address, OS);
// Print any additional variadic operands.
const MCInstrDesc &Desc = MII.get(MI->getOpcode());
if (Desc.isVariadic()) {
if ((Desc.getNumOperands() == 0 && MI->getNumOperands() > 0) ||
Desc.variadicOpsAreDefs())
OS << "\t";
unsigned Start = Desc.getNumOperands();
unsigned NumVariadicDefs = 0;
if (Desc.variadicOpsAreDefs()) {
// The number of variadic defs is encoded in an immediate by MCInstLower
NumVariadicDefs = MI->getOperand(0).getImm();
Start = 1;
}
bool NeedsComma = Desc.getNumOperands() > 0 && !Desc.variadicOpsAreDefs();
for (auto I = Start, E = MI->getNumOperands(); I < E; ++I) {
if (MI->getOpcode() == WebAssembly::CALL_INDIRECT &&
I - Start == NumVariadicDefs) {
// Skip type and flags arguments when printing for tests
++I;
continue;
}
if (NeedsComma)
OS << ", ";
printOperand(MI, I, OS, I - Start < NumVariadicDefs);
NeedsComma = true;
}
}
// Print any added annotation.
printAnnotation(OS, Annot);
if (CommentStream) {
// Observe any effects on the control flow stack, for use in annotating
// control flow label references.
unsigned Opc = MI->getOpcode();
switch (Opc) {
default:
break;
case WebAssembly::LOOP:
case WebAssembly::LOOP_S:
printAnnotation(OS, "label" + utostr(ControlFlowCounter) + ':');
ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, true));
break;
case WebAssembly::BLOCK:
case WebAssembly::BLOCK_S:
ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
break;
case WebAssembly::TRY:
case WebAssembly::TRY_S:
ControlFlowStack.push_back(std::make_pair(ControlFlowCounter++, false));
EHPadStack.push_back(EHPadStackCounter++);
LastSeenEHInst = TRY;
break;
case WebAssembly::END_LOOP:
case WebAssembly::END_LOOP_S:
if (ControlFlowStack.empty()) {
printAnnotation(OS, "End marker mismatch!");
} else {
ControlFlowStack.pop_back();
}
break;
case WebAssembly::END_BLOCK:
case WebAssembly::END_BLOCK_S:
if (ControlFlowStack.empty()) {
printAnnotation(OS, "End marker mismatch!");
} else {
printAnnotation(
OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
}
break;
case WebAssembly::END_TRY:
case WebAssembly::END_TRY_S:
if (ControlFlowStack.empty()) {
printAnnotation(OS, "End marker mismatch!");
} else {
printAnnotation(
OS, "label" + utostr(ControlFlowStack.pop_back_val().first) + ':');
LastSeenEHInst = END_TRY;
}
break;
case WebAssembly::CATCH:
case WebAssembly::CATCH_S:
if (EHPadStack.empty()) {
printAnnotation(OS, "try-catch mismatch!");
} else {
printAnnotation(OS, "catch" + utostr(EHPadStack.pop_back_val()) + ':');
}
break;
}
// Annotate any control flow label references.
// rethrow instruction does not take any depth argument and rethrows to the
// nearest enclosing catch scope, if any. If there's no enclosing catch
// scope, it throws up to the caller.
if (Opc == WebAssembly::RETHROW || Opc == WebAssembly::RETHROW_S) {
if (EHPadStack.empty()) {
printAnnotation(OS, "to caller");
} else {
printAnnotation(OS, "down to catch" + utostr(EHPadStack.back()));
}
} else {
unsigned NumFixedOperands = Desc.NumOperands;
SmallSet<uint64_t, 8> Printed;
for (unsigned I = 0, E = MI->getNumOperands(); I < E; ++I) {
// See if this operand denotes a basic block target.
if (I < NumFixedOperands) {
// A non-variable_ops operand, check its type.
if (Desc.OpInfo[I].OperandType != WebAssembly::OPERAND_BASIC_BLOCK)
continue;
} else {
// A variable_ops operand, which currently can be immediates (used in
// br_table) which are basic block targets, or for call instructions
// when using -wasm-keep-registers (in which case they are registers,
// and should not be processed).
if (!MI->getOperand(I).isImm())
continue;
}
uint64_t Depth = MI->getOperand(I).getImm();
if (!Printed.insert(Depth).second)
continue;
if (Depth >= ControlFlowStack.size()) {
printAnnotation(OS, "Invalid depth argument!");
} else {
const auto &Pair = ControlFlowStack.rbegin()[Depth];
printAnnotation(OS, utostr(Depth) + ": " +
(Pair.second ? "up" : "down") + " to label" +
utostr(Pair.first));
}
}
}
}
}
static std::string toString(const APFloat &FP) {
// Print NaNs with custom payloads specially.
if (FP.isNaN() && !FP.bitwiseIsEqual(APFloat::getQNaN(FP.getSemantics())) &&
!FP.bitwiseIsEqual(
APFloat::getQNaN(FP.getSemantics(), /*Negative=*/true))) {
APInt AI = FP.bitcastToAPInt();
return std::string(AI.isNegative() ? "-" : "") + "nan:0x" +
utohexstr(AI.getZExtValue() &
(AI.getBitWidth() == 32 ? INT64_C(0x007fffff)
: INT64_C(0x000fffffffffffff)),
/*LowerCase=*/true);
}
// Use C99's hexadecimal floating-point representation.
static const size_t BufBytes = 128;
char Buf[BufBytes];
auto Written = FP.convertToHexString(
Buf, /*HexDigits=*/0, /*UpperCase=*/false, APFloat::rmNearestTiesToEven);
(void)Written;
assert(Written != 0);
assert(Written < BufBytes);
return Buf;
}
void WebAssemblyInstPrinter::printOperand(const MCInst *MI, unsigned OpNo,
raw_ostream &O, bool IsVariadicDef) {
const MCOperand &Op = MI->getOperand(OpNo);
if (Op.isReg()) {
const MCInstrDesc &Desc = MII.get(MI->getOpcode());
unsigned WAReg = Op.getReg();
if (int(WAReg) >= 0)
printRegName(O, WAReg);
else if (OpNo >= Desc.getNumDefs() && !IsVariadicDef)
O << "$pop" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
else if (WAReg != WebAssemblyFunctionInfo::UnusedReg)
O << "$push" << WebAssemblyFunctionInfo::getWARegStackId(WAReg);
else
O << "$drop";
// Add a '=' suffix if this is a def.
if (OpNo < MII.get(MI->getOpcode()).getNumDefs() || IsVariadicDef)
O << '=';
} else if (Op.isImm()) {
O << Op.getImm();
} else if (Op.isFPImm()) {
const MCInstrDesc &Desc = MII.get(MI->getOpcode());
const MCOperandInfo &Info = Desc.OpInfo[OpNo];
if (Info.OperandType == WebAssembly::OPERAND_F32IMM) {
// TODO: MC converts all floating point immediate operands to double.
// This is fine for numeric values, but may cause NaNs to change bits.
O << ::toString(APFloat(float(Op.getFPImm())));
} else {
assert(Info.OperandType == WebAssembly::OPERAND_F64IMM);
O << ::toString(APFloat(Op.getFPImm()));
}
} else {
assert(Op.isExpr() && "unknown operand kind in printOperand");
// call_indirect instructions have a TYPEINDEX operand that we print
// as a signature here, such that the assembler can recover this
// information.
auto SRE = static_cast<const MCSymbolRefExpr *>(Op.getExpr());
if (SRE->getKind() == MCSymbolRefExpr::VK_WASM_TYPEINDEX) {
auto &Sym = static_cast<const MCSymbolWasm &>(SRE->getSymbol());
O << WebAssembly::signatureToString(Sym.getSignature());
} else {
Op.getExpr()->print(O, &MAI);
}
}
}
void WebAssemblyInstPrinter::printBrList(const MCInst *MI, unsigned OpNo,
raw_ostream &O) {
O << "{";
for (unsigned I = OpNo, E = MI->getNumOperands(); I != E; ++I) {
if (I != OpNo)
O << ", ";
O << MI->getOperand(I).getImm();
}
O << "}";
}
void WebAssemblyInstPrinter::printWebAssemblyP2AlignOperand(const MCInst *MI,
unsigned OpNo,
raw_ostream &O) {
int64_t Imm = MI->getOperand(OpNo).getImm();
if (Imm == WebAssembly::GetDefaultP2Align(MI->getOpcode()))
return;
O << ":p2align=" << Imm;
}
void WebAssemblyInstPrinter::printWebAssemblySignatureOperand(const MCInst *MI,
unsigned OpNo,
raw_ostream &O) {
const MCOperand &Op = MI->getOperand(OpNo);
if (Op.isImm()) {
auto Imm = static_cast<unsigned>(Op.getImm());
if (Imm != wasm::WASM_TYPE_NORESULT)
O << WebAssembly::anyTypeToString(Imm);
} else {
auto Expr = cast<MCSymbolRefExpr>(Op.getExpr());
auto *Sym = cast<MCSymbolWasm>(&Expr->getSymbol());
if (Sym->getSignature()) {
O << WebAssembly::signatureToString(Sym->getSignature());
} else {
// Disassembler does not currently produce a signature
O << "unknown_type";
}
}
}
void WebAssemblyInstPrinter::printWebAssemblyHeapTypeOperand(const MCInst *MI,
unsigned OpNo,
raw_ostream &O) {
const MCOperand &Op = MI->getOperand(OpNo);
if (Op.isImm()) {
switch (Op.getImm()) {
case long(wasm::ValType::EXTERNREF):
O << "extern";
break;
case long(wasm::ValType::FUNCREF):
O << "func";
break;
default:
O << "unsupported_heap_type_value";
break;
}
} else {
// Typed function references and other subtypes of funcref and externref
// currently unimplemented.
O << "unsupported_heap_type_operand";
}
}
// We have various enums representing a subset of these types, use this
// function to convert any of them to text.
const char *WebAssembly::anyTypeToString(unsigned Ty) {
switch (Ty) {
case wasm::WASM_TYPE_I32:
return "i32";
case wasm::WASM_TYPE_I64:
return "i64";
case wasm::WASM_TYPE_F32:
return "f32";
case wasm::WASM_TYPE_F64:
return "f64";
case wasm::WASM_TYPE_V128:
return "v128";
case wasm::WASM_TYPE_FUNCREF:
return "funcref";
case wasm::WASM_TYPE_EXTERNREF:
return "externref";
case wasm::WASM_TYPE_FUNC:
return "func";
case wasm::WASM_TYPE_EXNREF:
return "exnref";
case wasm::WASM_TYPE_NORESULT:
return "void";
default:
return "invalid_type";
}
}
const char *WebAssembly::typeToString(wasm::ValType Ty) {
return anyTypeToString(static_cast<unsigned>(Ty));
}
std::string WebAssembly::typeListToString(ArrayRef<wasm::ValType> List) {
std::string S;
for (auto &Ty : List) {
if (&Ty != &List[0]) S += ", ";
S += WebAssembly::typeToString(Ty);
}
return S;
}
std::string WebAssembly::signatureToString(const wasm::WasmSignature *Sig) {
std::string S("(");
S += typeListToString(Sig->Params);
S += ") -> (";
S += typeListToString(Sig->Returns);
S += ")";
return S;
}
|
; A141418: Triangle read by rows: T(n,k) = k * (2*n - k - 1) / 2, 1 <= k <= n.
; Submitted by Jamie Morken(s4)
; 0,1,1,2,3,3,3,5,6,6,4,7,9,10,10,5,9,12,14,15,15,6,11,15,18,20,21,21,7,13,18,22,25,27,28,28,8,15,21,26,30,33,35,36,36,9,17,24,30,35,39,42,44,45,45,10,19,27,34,40,45,49,52,54,55,55,11,21,30,38,45,51,56,60,63,65,66,66,12,23,33,42,50,57,63,68,72,75,77,78,78,13,25,36,46,55,63,70,76,81
lpb $0
add $1,1
sub $0,$1
lpe
mul $1,2
sub $1,$0
add $0,1
mul $0,$1
div $0,2
|
; A010795: n! (n+6)! / 6!.
; Submitted by Jon Maiga
; 1,7,112,3024,120960,6652800,479001600,43589145600,4881984307200,659067881472000,105450861035520000,19719311013642240000,4259371178946723840000,1052064681199840788480000
mov $1,1
mov $2,6
lpb $0
mul $1,$0
sub $0,1
add $2,1
mul $1,$2
lpe
mov $0,$1
|
%include "vesa.inc"
SECTION .text
USE16
vesa:
.getcardinfo:
mov ax, 0x4F00
mov di, VBECardInfo
int 0x10
cmp ax, 0x4F
je .findmode
mov eax, 1
ret
.resetlist:
;if needed, reset mins/maxes/stuff
xor cx, cx
mov [.minx], cx
mov [.miny], cx
mov [config.xres], cx
mov [config.yres], cx
.findmode:
mov si, [VBECardInfo.videomodeptr]
mov ax, [VBECardInfo.videomodeptr+2]
mov fs, ax
sub si, 2
.searchmodes:
add si, 2
mov cx, [fs:si]
cmp cx, 0xFFFF
jne .getmodeinfo
cmp word [.goodmode], 0
je .resetlist
jmp .findmode
.getmodeinfo:
push esi
mov [.currentmode], cx
mov ax, 0x4F01
mov di, VBEModeInfo
int 0x10
pop esi
cmp ax, 0x4F
je .foundmode
mov eax, 1
ret
.foundmode:
;check minimum values, really not minimums from an OS perspective but ugly for users
cmp byte [VBEModeInfo.bitsperpixel], 32
jb .searchmodes
.testx:
mov cx, [VBEModeInfo.xresolution]
cmp word [config.xres], 0
je .notrequiredx
cmp cx, [config.xres]
je .testy
jmp .searchmodes
.notrequiredx:
cmp cx, [.minx]
jb .searchmodes
.testy:
mov cx, [VBEModeInfo.yresolution]
cmp word [config.yres], 0
je .notrequiredy
cmp cx, [config.yres]
jne .searchmodes ;as if there weren't enough warnings, USE WITH CAUTION
cmp word [config.xres], 0
jnz .setmode
jmp .testgood
.notrequiredy:
cmp cx, [.miny]
jb .searchmodes
.testgood:
mov cx, [.currentmode]
mov [.goodmode], cx
push esi
; call decshowrm
; mov al, ':'
; call charrm
mov cx, [VBEModeInfo.xresolution]
call decshowrm
mov al, 'x'
call charrm
mov cx, [VBEModeInfo.yresolution]
call decshowrm
mov al, '@'
call charrm
xor ch, ch
mov cl, [VBEModeInfo.bitsperpixel]
call decshowrm
mov si, .modeok
call printrm
xor ax, ax
int 0x16
pop esi
cmp al, 'y'
je .setmode
cmp al, 's'
je .savemode
jmp .searchmodes
.savemode:
mov cx, [VBEModeInfo.xresolution]
mov [config.xres], cx
mov cx, [VBEModeInfo.yresolution]
mov [config.yres], cx
call save_config
.setmode:
mov bx, [.currentmode]
cmp bx, 0
je .nomode
or bx, 0x4000
mov ax, 0x4F02
int 0x10
.nomode:
cmp ax, 0x4F
je .returngood
mov eax, 1
ret
.returngood:
xor eax, eax
ret
.minx dw 640
.miny dw 480
.modeok db ": Is this OK? (s)ave/(y)es/(n)o",10,13,0
.goodmode dw 0
.currentmode dw 0
;useful functions
decshowrm:
mov si, .number
.clear:
mov al, "0"
mov [si], al
inc si
cmp si, .numberend
jb .clear
dec si
call convertrm
mov si, .number
.lp:
lodsb
cmp si, .numberend
jae .end
cmp al, "0"
jbe .lp
.end:
dec si
call printrm
ret
.number times 7 db 0
.numberend db 0
convertrm:
dec si
mov bx, si ;place to convert into must be in si, number to convert must be in cx
.cnvrt:
mov si, bx
sub si, 4
.ten4: inc si
cmp cx, 10000
jb .ten3
sub cx, 10000
inc byte [si]
jmp .cnvrt
.ten3: inc si
cmp cx, 1000
jb .ten2
sub cx, 1000
inc byte [si]
jmp .cnvrt
.ten2: inc si
cmp cx, 100
jb .ten1
sub cx, 100
inc byte [si]
jmp .cnvrt
.ten1: inc si
cmp cx, 10
jb .ten0
sub cx, 10
inc byte [si]
jmp .cnvrt
.ten0: inc si
cmp cx, 1
jb .return
sub cx, 1
inc byte [si]
jmp .cnvrt
.return:
ret
printrm:
mov al, [si]
test al, al
jz .return
call charrm
inc si
jmp printrm
.return:
ret
charrm: ;char must be in al
mov bx, 7
mov ah, 0xE
int 10h
ret
|
;
; Z88 Graphics Functions - Small C+ stubs
;
; Written around the Interlogic Standard Library
;
; Stubs Written by D Morris - 30/9/98
;
;
; $Id: clg.asm,v 1.6 2016-04-13 21:09:09 dom Exp $
;
SECTION code_clib
PUBLIC clg
PUBLIC _clg
EXTERN swapgfxbk
EXTERN __graphics_end
EXTERN cleargraphics
.clg
._clg
push ix
call swapgfxbk
call cleargraphics
jp __graphics_end
|
;
;
SECTION code_clib
PUBLIC generic_console_cls
PUBLIC generic_console_vpeek
PUBLIC generic_console_scrollup
PUBLIC generic_console_printc
PUBLIC generic_console_ioctl
PUBLIC generic_console_set_ink
PUBLIC generic_console_set_paper
PUBLIC generic_console_set_attribute
EXTERN CONSOLE_COLUMNS
EXTERN CONSOLE_ROWS
defc DISPLAY = $F800
PUBLIC CLIB_GENCON_CAPS
defc CLIB_GENCON_CAPS = 0
generic_console_ioctl:
scf
generic_console_set_attribute:
ret
generic_console_set_ink:
generic_console_set_paper:
ret
generic_console_cls:
ld hl, DISPLAY
ld de, DISPLAY +1
ld bc, +(CONSOLE_COLUMNS * CONSOLE_ROWS) - 1
ld (hl),32
ldir
ret
; c = x
; b = y
; a = character to print
; e = raw
generic_console_printc:
call xypos
ld (hl),a
ret
;Entry: c = x,
; b = y
;Exit: nc = success
; a = character,
; c = failure
generic_console_vpeek:
call xypos
ld a,(hl)
and a
ret
xypos:
ld hl,DISPLAY - CONSOLE_COLUMNS
ld de,CONSOLE_COLUMNS
inc b
generic_console_printc_1:
add hl,de
djnz generic_console_printc_1
generic_console_printc_3:
add hl,bc ;hl now points to address in display
ret
generic_console_scrollup:
push de
push bc
ld hl, DISPLAY + CONSOLE_COLUMNS
ld de, DISPLAY
ld bc,+ ((CONSOLE_COLUMNS) * (CONSOLE_ROWS-1))
ldir
ex de,hl
ld b,CONSOLE_COLUMNS
generic_console_scrollup_3:
ld (hl),32
inc hl
djnz generic_console_scrollup_3
pop bc
pop de
ret
SECTION code_crt_init
defc DSPLC = $01 ; DISPLAY CONTROL
defc DSPLD = $00 ; DISPLAY DATA
; Disable the cursor (push off screen)
ld a,$80
out (DSPLC),a
ld a,255
out (DSPLD),a ;X
out (DSPLD),a ;Y
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r8
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x1be0a, %rsi
lea addresses_A_ht+0x10f80, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
add %r11, %r11
mov $43, %rcx
rep movsb
xor $55658, %rdx
lea addresses_D_ht+0x10aea, %rdi
nop
sub %r8, %r8
and $0xffffffffffffffc0, %rdi
vmovaps (%rdi), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $1, %xmm3, %rsi
nop
sub $3034, %rcx
lea addresses_A_ht+0xc146, %rsi
lea addresses_WC_ht+0x2722, %rdi
sub $26538, %r10
mov $82, %rcx
rep movsw
nop
nop
nop
xor $57485, %rdi
lea addresses_D_ht+0x7aea, %rsi
lea addresses_UC_ht+0x4c6a, %rdi
nop
nop
nop
nop
nop
xor %r11, %r11
mov $77, %rcx
rep movsb
nop
nop
nop
nop
nop
and $63679, %rdx
lea addresses_WC_ht+0x12b42, %rdx
clflush (%rdx)
nop
nop
sub %r11, %r11
and $0xffffffffffffffc0, %rdx
vmovaps (%rdx), %ymm1
vextracti128 $1, %ymm1, %xmm1
vpextrq $1, %xmm1, %rsi
nop
nop
nop
xor $39025, %r11
lea addresses_A_ht+0xd8a, %r8
nop
nop
nop
nop
nop
sub $15923, %rdi
movb (%r8), %r10b
nop
nop
and $30233, %rdi
lea addresses_WT_ht+0x8ca5, %rsi
lea addresses_normal_ht+0x1850a, %rdi
nop
nop
nop
nop
sub %rax, %rax
mov $92, %rcx
rep movsq
nop
nop
nop
nop
nop
dec %rax
lea addresses_WT_ht+0x15aea, %rcx
nop
nop
nop
nop
and $29528, %rdi
mov (%rcx), %rdx
nop
nop
nop
cmp %rdi, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r15
push %r8
push %rbx
// Store
lea addresses_UC+0x1336a, %r13
nop
nop
nop
cmp %rbx, %rbx
movl $0x51525354, (%r13)
add %r15, %r15
// Faulty Load
lea addresses_D+0x1c2ea, %r15
nop
nop
cmp %r8, %r8
mov (%r15), %r11d
lea oracles, %r15
and $0xff, %r11
shlq $12, %r11
mov (%r15,%r11,1), %r11
pop %rbx
pop %r8
pop %r15
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_D', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_UC', 'size': 4, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_D', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}}
{'src': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}}
{'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': True}}
{'src': {'same': True, 'congruent': 2, 'NT': False, 'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_A_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}}
{'src': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False}, '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
*/
|
[BITS 32]
section .asm
global print:function
global smollos_getkey: function
global smollos_malloc: function
global smollos_free: function
global smollos_putchar:function
global smollos_process_load_start: function
global smollos_process_get_arguments: function
global smollos_system:function
global smollos_exit: function
global user_putchar: function
global smollos_fopen: function
global smollos_fread: function
global smollos_fclose: function
global smollos_mkdir: function
global smollos_fwrite: function
global smollos_fstat: function
global smollos_opendir: function
global smollos_closedir: function
global smollos_freaddir: function
global smollos_funlink: function
global smollos_frename: function
global smollos_spawnp: function
extern _fini
; void print(const char* filename)
print:
push ebp
mov ebp, esp
push dword[ebp+8]
mov eax, 1 ; Command print
int 0x80
add esp, 4
pop ebp
ret
; int smollos_getkey()
smollos_getkey:
push ebp
mov ebp, esp
mov eax, 2 ; Command getkey
int 0x80
pop ebp
ret
; void smollos_putchar(char c)
smollos_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* smollos_malloc(size_t size)
smollos_malloc:
push ebp
mov ebp, esp
mov eax, 4 ; Command malloc (Allocates memory for the process)
push dword[ebp+8] ; Variable "size"
int 0x80
add esp, 4
pop ebp
ret
; void smollos_free(void* ptr)
smollos_free:
push ebp
mov ebp, esp
mov eax, 5 ; Command 5 free (Frees the allocated memory for this process)
push dword[ebp+8] ; Variable "ptr"
int 0x80
add esp, 4
pop ebp
ret
; void smollos_process_load_start(const char* filename)
smollos_process_load_start:
push ebp
mov ebp, esp
mov eax, 6 ; Command 6 process load start ( stars a process )
push dword[ebp+8] ; Variable "filename"
int 0x80
add esp, 4
pop ebp
ret
; int smollos_system(struct command_argument* arguments)
smollos_system:
push ebp
mov ebp, esp
mov eax, 7 ; Command 7 process_system ( runs a system command based on the arguments)
push dword[ebp+8] ; Variable "arguments"
int 0x80
add esp, 4
pop ebp
ret
; void smollos_process_get_arguments(struct process_arguments* arguments)
smollos_process_get_arguments:
push ebp
mov ebp, esp
mov eax, 8 ; Command 8 Gets the process arguments
push dword[ebp+8] ; Variable arguments
int 0x80
add esp, 4
pop ebp
ret
; void smollos_exit()
smollos_exit:
push ebp
mov ebp, esp
mov eax, 9 ; Command 9 process exit
int 0x80
call _fini ;before exit?
pop ebp
ret
;int user_putchar(uint16_t x, uint16_t y, uint16_t c);
user_putchar:
push ebp
mov ebp,esp
mov eax,10
push dword[ebp+16]
push dword[ebp+12]
push dword[ebp+8]
int 0x80
add esp,12
pop ebp
ret
;int smollos_fopen(const char* path,const int mode)
smollos_fopen:
push ebp
mov ebp,esp
mov eax,11
push dword[ebp+12]
push dword[ebp + 8]
int 0x80
add esp,8
pop ebp
ret
;smollos_fread(void* ptr, uint32_t size, uint32_t nmemb, int fd)
smollos_fread:
push ebp
mov ebp,esp
mov eax,12
push dword[ebp+20]
push dword[ebp+16]
push dword[ebp+12]
push dword[ebp+8]
int 0x80
add esp,16
pop ebp
ret
;void fclose(int fd)
smollos_fclose:
push ebp
mov ebp,esp
mov eax,13
push dword[ebp+8]
int 0x80
add esp,4
pop ebp
ret
;void mkdir(const char* path)
smollos_mkdir:
push ebp
mov ebp,esp
mov eax,14
push dword[ebp+8]
int 0x80
add esp,4
pop ebp
ret
;void smollos_fwrite(int fd,const char* buff,uint32_t amount,uint32_t* nmemb);
smollos_fwrite:
push ebp
mov ebp,esp
mov eax,15
push dword[ebp+20]
push dword[ebp+16]
push dword[ebp+12]
push dword[ebp+8]
int 0x80
add esp,16
pop ebp
ret
;void smollos_fstat(const char* path,FILINFO* info);
smollos_fstat:
push ebp
mov ebp,esp
mov eax,16
push dword[ebp + 12]
push dword[ebp+8]
int 0x80
add esp,8
pop ebp
ret
;void smollos_opendir(char* path)
smollos_opendir:
push ebp
mov ebp,esp
mov eax,17
push dword[ebp + 12]
push dword[ebp+8]
int 0x80
add esp,8
pop ebp
ret
;void smollos_closedir(DIR* dir)
smollos_closedir:
push ebp
mov ebp,esp
mov eax,18
push dword[ebp + 8]
int 0x80
add esp,4
pop ebp
ret
;FRESULT f_readdir (DIR* dp, FILINFO* fno);
smollos_freaddir:
push ebp
mov ebp,esp
mov eax,19
push dword[ebp+12]
push dword[ebp+8]
int 0x80
add esp,8
pop ebp
ret
;FRESULT f_unlink (const char* path);
smollos_funlink:
push ebp
mov ebp,esp
mov eax,20
push dword[ebp+8]
int 0x80
add esp,4
pop ebp
ret
;int frename (const TCHAR* path_old, const TCHAR* path_new);
smollos_frename:
push ebp
mov ebp,esp
push dword[ebp+12]
push dword[ebp+8]
mov eax,21
int 0x80
add esp,8
pop ebp
ret
;int smollos_spawnp(const char* filename)
smollos_spawnp:
push ebp
mov ebp,esp
push dword[ebp+8]
mov eax,22
int 0x80
add esp,4
pop ebp
ret |
; A073784: Number of primes between successive composite numbers.
; 1,1,0,0,1,1,0,0,1,1,0,0,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,1,0,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1,0,0,1,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0
seq $0,72668 ; Numbers one less than composite numbers.
seq $0,34693 ; Smallest k such that k*n+1 is prime.
mov $2,$0
mul $0,2
sub $0,1
sub $0,$2
cmp $1,$0
mov $0,$1
|
%ifdef CONFIG
{
"RegData": {
"RAX": ["0xbff0000000000000"]
},
"Env": { "FEX_X87REDUCEDPRECISION" : "1" }
}
%endif
mov rdx, 0xe0000000
mov rax, 0x3ff0000000000000 ; 1.0
mov [rdx + 8 * 0], rax
mov ax, 2
mov [rdx + 8 * 1], ax
fld qword [rdx + 8 * 0]
fisub word [rdx + 8 * 1]
fst qword [rdx]
mov rax, [rdx]
hlt
|
.ORIG x0200
START
; LD R0, S1
; ST R0, S2
ADD R0, R0, #0
BRp APPLE
BRnz BANANA
BR ORANGE
APPLE ADD R1, R2, R3
BANANA ADD R4, R5, R6
ORANGE ADD R0, R1, R4
DONE BR DONE
S1 .STRINGZ "XYZ"
S2 .STRINGZ "123"
.END |
// https://github.com/mrdoob/three.js/tree/r129/src/core/Clock.js
#ifndef THREEPP_CLOCK_HPP
#define THREEPP_CLOCK_HPP
#include <chrono>
namespace threepp {
class Clock {
public:
explicit Clock(bool autoStart = true) : autoStart_(autoStart) {}
void start() {
startTime_ = std::chrono::system_clock::now();
oldTime_ = startTime_;
elapsedTime_ = 0;
running_ = true;
}
void stop() {
getElapsedTime();
running_ = false;
autoStart_ = false;
}
float getElapsedTime() {
getDelta();
return elapsedTime_;
}
float getDelta() {
float diff = 0;
if (autoStart_ && !running_) {
start();
return 0;
}
if (running_) {
const auto newTime = std::chrono::system_clock::now();
diff = std::chrono::duration_cast<std::chrono::microseconds>(newTime - oldTime_).count() / 1000000.0f;
oldTime_ = newTime;
elapsedTime_ += diff;
}
return diff;
}
private:
bool autoStart_;
bool running_ = false;
float elapsedTime_ = 0;
std::chrono::time_point<std::chrono::system_clock> startTime_;
std::chrono::time_point<std::chrono::system_clock> oldTime_;
};
}// namespace threepp
#endif//THREEPP_CLOCK_HPP
|
// Copyright (c) 2015-2017, RAPtor Developer Team
// License: Simplified BSD, http://opensource.org/licenses/BSD-2-Clause
#include "core/comm_pkg.hpp"
#include "core/par_matrix.hpp"
using namespace raptor;
// Forward Declarations
// Helper Methods
template <typename T> aligned_vector<T>& create_mat(int n, int m, int b_n, int b_m,
CSRMatrix** mat_ptr);
template <typename T> CSRMatrix* communication_helper(const int* rowptr,
const int* col_indices, const T& values,
CommData* send_comm, CommData* recv_comm, int key, MPI_Comm mpi_comm,
const int b_rows, const int b_cols, const bool has_vals = true);
template <typename T> void init_comm_helper(char* send_buffer,
const int* rowptr, const int* col_indices, const T& values,
CommData* send_comm, int key, MPI_Comm mpi_comm, const int b_rows,
const int b_cols);
CSRMatrix* complete_comm_helper(CommData* send_comm,
CommData* recv_comm, int key, MPI_Comm mpi_comm, const int b_rows,
const int b_cols, const bool has_vals = true);
template <typename T> CSRMatrix* transpose_recv(CSRMatrix* recv_mat_T,
aligned_vector<T>& T_vals, NonContigData* send_data, int n);
template <typename T> CSRMatrix* combine_recvs(CSRMatrix* L_mat, CSRMatrix* R_mat,
aligned_vector<T>& L_vals, aligned_vector<T>& R_vals, const int b_rows,
const int b_cols, NonContigData* local_L_recv, NonContigData* local_R_recv,
aligned_vector<int>& row_sizes);
template <typename T> CSRMatrix* combine_recvs_T(CSRMatrix* L_mat,
CSRMatrix* final_mat, NonContigData* local_L_send, NonContigData* final_send,
aligned_vector<T>& L_vals, aligned_vector<T>& final_vals, int n,
int b_rows, int b_cols);
// Main Methods
CSRMatrix* CommPkg::communicate(ParCSRMatrix* A, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_par_mat_comm(A, send_buffer, has_vals);
return complete_mat_comm(A->on_proc->b_rows, A->on_proc->b_cols,
has_vals);
}
CSRMatrix* CommPkg::communicate(ParBSRMatrix* A, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_par_mat_comm(A, send_buffer, has_vals);
return complete_mat_comm(A->on_proc->b_rows, A->on_proc->b_cols,
has_vals);
}
void CommPkg::init_par_mat_comm(ParCSRMatrix* A, aligned_vector<char>& send_buffer,
const bool has_vals)
{
int start, end;
int ctr, idx;
int global_col;
int nnz = A->on_proc->nnz + A->off_proc->nnz;
aligned_vector<int> rowptr(A->local_num_rows + 1);
aligned_vector<int> col_indices;
aligned_vector<double> values;
if (nnz)
{
col_indices.resize(nnz);
if (has_vals)
values.resize(nnz);
}
ctr = 0;
rowptr[0] = ctr;
for (int i = 0; i < A->local_num_rows; i++)
{
start = A->on_proc->idx1[i];
end = A->on_proc->idx1[i+1];
for (int j = start; j < end; j++)
{
global_col = A->on_proc_column_map[A->on_proc->idx2[j]];
if (has_vals) values[ctr] = A->on_proc->vals[j];
col_indices[ctr++] = global_col;
}
start = A->off_proc->idx1[i];
end = A->off_proc->idx1[i+1];
for (int j = start; j < end; j++)
{
global_col = A->off_proc_column_map[A->off_proc->idx2[j]];
if (has_vals) values[ctr] = A->off_proc->vals[j];
col_indices[ctr++] = global_col;
}
rowptr[i+1] = ctr;
}
return init_mat_comm(send_buffer, rowptr, col_indices, values,
A->on_proc->b_rows, A->on_proc->b_cols, has_vals);
}
void CommPkg::init_par_mat_comm(ParBSRMatrix* A, aligned_vector<char>& send_buffer,
const bool has_vals)
{
int start, end;
int ctr, idx;
int global_col;
int nnz = A->on_proc->nnz + A->off_proc->nnz;
aligned_vector<int> rowptr(A->local_num_rows + 1);
aligned_vector<int> col_indices;
aligned_vector<double*> values;
if (nnz)
{
col_indices.resize(nnz);
if (has_vals)
values.resize(nnz);
}
BSRMatrix* A_on = (BSRMatrix*) A->on_proc;
BSRMatrix* A_off = (BSRMatrix*) A->off_proc;
ctr = 0;
rowptr[0] = ctr;
for (int i = 0; i < A->local_num_rows; i++)
{
start = A->on_proc->idx1[i];
end = A->on_proc->idx1[i+1];
for (int j = start; j < end; j++)
{
global_col = A->on_proc_column_map[A->on_proc->idx2[j]];
if (has_vals) values[ctr] = A->on_proc->copy_val(A_on->block_vals[j]);
col_indices[ctr++] = global_col;
}
start = A->off_proc->idx1[i];
end = A->off_proc->idx1[i+1];
for (int j = start; j < end; j++)
{
global_col = A->off_proc_column_map[A->off_proc->idx2[j]];
if (has_vals) values[ctr] = A->off_proc->copy_val(A_off->block_vals[j]);
col_indices[ctr++] = global_col;
}
rowptr[i+1] = ctr;
}
return init_mat_comm(send_buffer, rowptr, col_indices, values,
A->on_proc->b_rows, A->on_proc->b_cols, has_vals);
}
CSRMatrix* ParComm::communicate(const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_mat_comm(send_buffer, rowptr, col_indices, values, b_rows, b_cols, has_vals);
return complete_mat_comm(b_rows, b_cols, has_vals);
}
CSRMatrix* ParComm::communicate(const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double*>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_mat_comm(send_buffer, rowptr, col_indices, values, b_rows, b_cols, has_vals);
return complete_mat_comm(b_rows, b_cols, has_vals);
}
void ParComm::init_mat_comm(aligned_vector<char>& send_buffer,
const aligned_vector<int>& rowptr, const aligned_vector<int>& col_indices,
const aligned_vector<double>& values, const int b_rows, const int b_cols,
const bool has_vals)
{
int s = send_data->get_msg_size(rowptr.data(), values.data(), mpi_comm, b_rows * b_cols);
send_buffer.resize(s);
init_comm_helper(send_buffer.data(), rowptr.data(), col_indices.data(), values.data(),
send_data, key, mpi_comm, b_rows, b_cols);
}
void ParComm::init_mat_comm(aligned_vector<char>& send_buffer,
const aligned_vector<int>& rowptr, const aligned_vector<int>& col_indices,
const aligned_vector<double*>& values, const int b_rows, const int b_cols,
const bool has_vals)
{
int s = send_data->get_msg_size(rowptr.data(), values.data(), mpi_comm, b_rows * b_cols);
send_buffer.resize(s);
init_comm_helper(send_buffer.data(), rowptr.data(), col_indices.data(), values.data(),
send_data, key, mpi_comm, b_rows, b_cols);
}
CSRMatrix* ParComm::complete_mat_comm(const int b_rows, const int b_cols,
const bool has_vals)
{
CSRMatrix* recv_mat = complete_comm_helper(send_data, recv_data, key, mpi_comm,
b_rows, b_cols, has_vals);
key++;
return recv_mat;
}
CSRMatrix* ParComm::communicate_T(const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double>& values,
const int n_result_rows, const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_mat_comm_T(send_buffer, rowptr, col_indices, values, b_rows, b_cols, has_vals);
return complete_mat_comm_T(n_result_rows, b_rows, b_cols, has_vals);
}
CSRMatrix* ParComm::communicate_T(const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double*>& values,
const int n_result_rows, const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_mat_comm_T(send_buffer, rowptr, col_indices, values, b_rows, b_cols, has_vals);
return complete_mat_comm_T(n_result_rows, b_rows, b_cols, has_vals);
}
void ParComm::init_mat_comm_T(aligned_vector<char>& send_buffer, const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
int s = recv_data->get_msg_size(rowptr.data(), values.data(), mpi_comm, b_rows * b_cols);
send_buffer.resize(s);
init_comm_helper(send_buffer.data(), rowptr.data(), col_indices.data(), values.data(),
recv_data, key, mpi_comm, b_rows, b_cols);
}
void ParComm::init_mat_comm_T(aligned_vector<char>& send_buffer, const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double*>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
int s = recv_data->get_msg_size(rowptr.data(), values.data(), mpi_comm, b_rows * b_cols);
send_buffer.resize(s);
init_comm_helper(send_buffer.data(), rowptr.data(), col_indices.data(), values.data(),
recv_data, key, mpi_comm, b_rows, b_cols);
}
CSRMatrix* ParComm::complete_mat_comm_T(const int n_result_rows, const int b_rows, const int b_cols, const bool has_vals)
{
CSRMatrix* recv_mat_T = complete_comm_helper(recv_data, send_data, key, mpi_comm,
b_rows, b_cols, has_vals);
CSRMatrix* recv_mat;
if (b_rows > 1 || b_cols > 1)
{
BSRMatrix* recv_mat_T_bsr = (BSRMatrix*) recv_mat_T;
recv_mat = transpose_recv(recv_mat_T_bsr, recv_mat_T_bsr->block_vals,
send_data, n_result_rows);
}
else
{
recv_mat = transpose_recv(recv_mat_T, recv_mat_T->vals,
send_data, n_result_rows);
}
delete recv_mat_T;
return recv_mat;
}
CSRMatrix* TAPComm::communicate(const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_mat_comm(send_buffer, rowptr, col_indices, values, b_rows, b_cols, has_vals);
return complete_mat_comm(b_rows, b_cols, has_vals);
}
CSRMatrix* TAPComm::communicate(const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double*>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_mat_comm(send_buffer, rowptr, col_indices, values, b_rows, b_cols, has_vals);
return complete_mat_comm(b_rows, b_cols, has_vals);
}
void TAPComm::init_mat_comm(aligned_vector<char>& send_buffer, const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
int block_size = b_rows * b_cols;
int l_bytes = local_L_par_comm->send_data->get_msg_size(rowptr.data(),
values.data(), local_L_par_comm->mpi_comm, block_size);
int g_bytes;
if (local_S_par_comm)
{
CSRMatrix* S_mat = local_S_par_comm->communicate(rowptr, col_indices, values,
b_rows, b_cols, has_vals);
g_bytes = global_par_comm->send_data->get_msg_size(S_mat->idx1.data(),
S_mat->vals.data(), global_par_comm->mpi_comm, block_size);
send_buffer.resize(l_bytes + g_bytes);
init_comm_helper(&(send_buffer[0]), S_mat->idx1.data(),
S_mat->idx2.data(), S_mat->vals.data(), global_par_comm->send_data,
global_par_comm->key, global_par_comm->mpi_comm, b_rows, b_cols);
delete S_mat;
}
else
{
g_bytes = global_par_comm->send_data->get_msg_size(rowptr.data(),
values.data(), global_par_comm->mpi_comm, block_size);
send_buffer.resize(l_bytes + g_bytes);
init_comm_helper(&(send_buffer[0]), rowptr.data(), col_indices.data(),
values.data(), global_par_comm->send_data, global_par_comm->key,
global_par_comm->mpi_comm, b_rows, b_cols);
}
init_comm_helper(&(send_buffer[g_bytes]), rowptr.data(), col_indices.data(),
values.data(), local_L_par_comm->send_data, local_L_par_comm->key,
local_L_par_comm->mpi_comm, b_rows, b_cols);
}
void TAPComm::init_mat_comm(aligned_vector<char>& send_buffer, const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double*>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
int block_size = b_rows * b_cols;
int l_bytes = local_L_par_comm->send_data->get_msg_size(rowptr.data(),
values.data(), local_L_par_comm->mpi_comm, block_size);
int g_bytes;
if (local_S_par_comm)
{
BSRMatrix* S_mat = (BSRMatrix*) local_S_par_comm->communicate(rowptr, col_indices, values,
b_rows, b_cols, has_vals);
g_bytes = global_par_comm->send_data->get_msg_size(S_mat->idx1.data(),
S_mat->block_vals.data(), global_par_comm->mpi_comm, block_size);
send_buffer.resize(l_bytes + g_bytes);
init_comm_helper(&(send_buffer[0]), S_mat->idx1.data(),
S_mat->idx2.data(), S_mat->vals.data(), global_par_comm->send_data,
global_par_comm->key, global_par_comm->mpi_comm, b_rows, b_cols);
delete S_mat;
}
else
{
g_bytes = global_par_comm->send_data->get_msg_size(rowptr.data(),
values.data(), global_par_comm->mpi_comm, block_size);
send_buffer.resize(l_bytes + g_bytes);
init_comm_helper(&(send_buffer[0]), rowptr.data(), col_indices.data(),
values.data(), global_par_comm->send_data, global_par_comm->key,
global_par_comm->mpi_comm, b_rows, b_cols);
}
init_comm_helper(&(send_buffer[g_bytes]), rowptr.data(), col_indices.data(),
values.data(), local_L_par_comm->send_data, local_L_par_comm->key,
local_L_par_comm->mpi_comm, b_rows, b_cols);
}
CSRMatrix* TAPComm::complete_mat_comm(const int b_rows, const int b_cols, const bool has_vals)
{
int block_size = b_rows * b_cols;
CSRMatrix* G_mat = global_par_comm->complete_mat_comm(b_rows, b_cols, has_vals);
CSRMatrix* L_mat = local_L_par_comm->complete_mat_comm(b_rows, b_cols, has_vals);
CSRMatrix* R_mat;
CSRMatrix* recv_mat;
if (b_rows > 1 || b_cols > 1)
{
BSRMatrix* G_mat_bsr = (BSRMatrix*) G_mat;
R_mat = local_R_par_comm->communicate(G_mat_bsr->idx1, G_mat_bsr->idx2,
G_mat_bsr->block_vals, b_rows, b_cols, has_vals);
BSRMatrix* R_mat_bsr = (BSRMatrix*) R_mat;
BSRMatrix* L_mat_bsr = (BSRMatrix*) L_mat;
// Create recv_mat (combination of L_mat and R_mat)
recv_mat = combine_recvs(L_mat_bsr, R_mat_bsr,
L_mat_bsr->block_vals, R_mat_bsr->block_vals, b_rows, b_cols,
(NonContigData*) local_L_par_comm->recv_data,
(NonContigData*) local_R_par_comm->recv_data,
get_buffer<int>());
}
else
{
R_mat = local_R_par_comm->communicate(G_mat->idx1, G_mat->idx2,
G_mat->vals, b_rows, b_cols, has_vals);
// Create recv_mat (combination of L_mat and R_mat)
recv_mat = combine_recvs(L_mat, R_mat,
L_mat->vals, R_mat->vals, b_rows, b_cols,
(NonContigData*) local_L_par_comm->recv_data,
(NonContigData*) local_R_par_comm->recv_data,
get_buffer<int>());
}
delete G_mat;
delete R_mat;
delete L_mat;
return recv_mat;
}
CSRMatrix* TAPComm::communicate_T(const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double>& values,
const int n_result_rows, const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_mat_comm_T(send_buffer, rowptr, col_indices, values, b_rows, b_cols, has_vals);
return complete_mat_comm_T(n_result_rows, b_rows, b_cols, has_vals);
}
CSRMatrix* TAPComm::communicate_T(const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double*>& values,
const int n_result_rows, const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
init_mat_comm_T(send_buffer, rowptr, col_indices, values, b_rows, b_cols, has_vals);
return complete_mat_comm_T(n_result_rows, b_rows, b_cols, has_vals);
}
void TAPComm::init_mat_comm_T(aligned_vector<char>& send_buffer, const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
int block_size = b_rows * b_cols;
// Transpose communication with local_R_par_comm
CSRMatrix* R_mat = communication_helper(rowptr.data(), col_indices.data(),
values.data(), local_R_par_comm->recv_data,
local_R_par_comm->send_data, local_R_par_comm->key,
local_R_par_comm->mpi_comm, b_rows, b_cols, has_vals);
local_R_par_comm->key++;
// Calculate size of send_buffer for global and local_L
int l_bytes = local_L_par_comm->recv_data->get_msg_size(rowptr.data(),
values.data(), local_L_par_comm->mpi_comm, block_size);
int g_bytes = global_par_comm->recv_data->get_msg_size(R_mat->idx1.data(),
R_mat->vals.data(), global_par_comm->mpi_comm, block_size);
send_buffer.resize(l_bytes + g_bytes);
// Initialize global_par_comm
init_comm_helper(&(send_buffer[0]), R_mat->idx1.data(), R_mat->idx2.data(),
R_mat->vals.data(), global_par_comm->recv_data, global_par_comm->key,
global_par_comm->mpi_comm, b_rows, b_cols);
delete R_mat;
// Initialize local_L_par_comm
init_comm_helper(&(send_buffer[g_bytes]), rowptr.data(), col_indices.data(),
values.data(), local_L_par_comm->recv_data,
local_L_par_comm->key, local_L_par_comm->mpi_comm,
b_rows, b_cols);
}
void TAPComm::init_mat_comm_T(aligned_vector<char>& send_buffer, const aligned_vector<int>& rowptr,
const aligned_vector<int>& col_indices, const aligned_vector<double*>& values,
const int b_rows, const int b_cols, const bool has_vals)
{
int block_size = b_rows * b_cols;
// Transpose communication with local_R_par_comm
BSRMatrix* R_mat = (BSRMatrix*) communication_helper(rowptr.data(), col_indices.data(),
values.data(), local_R_par_comm->recv_data,
local_R_par_comm->send_data, local_R_par_comm->key,
local_R_par_comm->mpi_comm, b_rows, b_cols, has_vals);
local_R_par_comm->key++;
// Calculate size of send_buffer for global and local_L
int l_bytes = local_L_par_comm->recv_data->get_msg_size(rowptr.data(),
values.data(), local_L_par_comm->mpi_comm, block_size);
int g_bytes = global_par_comm->recv_data->get_msg_size(R_mat->idx1.data(),
R_mat->block_vals.data(), global_par_comm->mpi_comm, block_size);
send_buffer.resize(l_bytes + g_bytes);
// Initialize global_par_comm
init_comm_helper(&(send_buffer[0]), R_mat->idx1.data(), R_mat->idx2.data(),
R_mat->block_vals.data(), global_par_comm->recv_data, global_par_comm->key,
global_par_comm->mpi_comm, b_rows, b_cols);
delete R_mat;
// Initialize local_L_par_comm
init_comm_helper(&(send_buffer[g_bytes]), rowptr.data(), col_indices.data(),
values.data(), local_L_par_comm->recv_data,
local_L_par_comm->key, local_L_par_comm->mpi_comm,
b_rows, b_cols);
}
CSRMatrix* TAPComm::complete_mat_comm_T(const int n_result_rows, const int b_rows, const int b_cols, const bool has_vals)
{
CSRMatrix* G_mat = complete_comm_helper(global_par_comm->recv_data,
global_par_comm->send_data, global_par_comm->key,
global_par_comm->mpi_comm, b_rows, b_cols, has_vals);
global_par_comm->key++;
CSRMatrix* L_mat = complete_comm_helper(local_L_par_comm->recv_data,
local_L_par_comm->send_data, local_L_par_comm->key,
local_L_par_comm->mpi_comm, b_rows, b_cols, has_vals);
local_L_par_comm->key++;
CSRMatrix* final_mat;
CSRMatrix* recv_mat;
ParComm* final_comm;
if (b_rows > 1 || b_cols > 1)
{
BSRMatrix* L_mat_bsr = (BSRMatrix*) L_mat;
if (local_S_par_comm)
{
BSRMatrix* G_mat_bsr = (BSRMatrix*) G_mat;
final_mat = communication_helper(G_mat_bsr->idx1.data(), G_mat_bsr->idx2.data(),
G_mat_bsr->block_vals.data(), local_S_par_comm->recv_data,
local_S_par_comm->send_data, local_S_par_comm->key,
local_S_par_comm->mpi_comm, b_rows, b_cols, has_vals);
local_S_par_comm->key++;
delete G_mat;
final_comm = local_S_par_comm;
}
else
{
final_mat = G_mat;
final_comm = global_par_comm;
}
BSRMatrix* final_mat_bsr = (BSRMatrix*) final_mat;
recv_mat = combine_recvs_T(L_mat_bsr, final_mat_bsr,
local_L_par_comm->send_data, final_comm->send_data,
L_mat_bsr->vals, final_mat_bsr->vals, n_result_rows, b_rows, b_cols);
}
else
{
if (local_S_par_comm)
{
final_mat = communication_helper(G_mat->idx1.data(), G_mat->idx2.data(),
G_mat->vals.data(), local_S_par_comm->recv_data, local_S_par_comm->send_data,
local_S_par_comm->key, local_S_par_comm->mpi_comm, b_rows, b_cols, has_vals);
local_S_par_comm->key++;
delete G_mat;
final_comm = local_S_par_comm;
}
else
{
final_mat = G_mat;
final_comm = global_par_comm;
}
recv_mat = combine_recvs_T(L_mat, final_mat,
local_L_par_comm->send_data, final_comm->send_data,
L_mat->vals, final_mat->vals, n_result_rows, b_rows, b_cols);
}
delete L_mat;
delete final_mat;
return recv_mat;
}
// Helper Methods
// Create matrix (either CSR or BSR)
template<> aligned_vector<double>& create_mat<double>(int n, int m, int b_n, int b_m,
CSRMatrix** mat_ptr)
{
CSRMatrix* recv_mat = new CSRMatrix(n, m);
*mat_ptr = recv_mat;
return recv_mat->vals;
}
template<> aligned_vector<double*>& create_mat<double*>(int n, int m, int b_n, int b_m,
CSRMatrix** mat_ptr)
{
BSRMatrix* recv_mat = new BSRMatrix(n, m, b_n, b_m);
*mat_ptr = recv_mat;
return recv_mat->block_vals;
}
template <typename T> // double* or double**
CSRMatrix* communication_helper(const int* rowptr,
const int* col_indices, const T& values,
CommData* send_comm, CommData* recv_comm, int key, MPI_Comm mpi_comm,
const int b_rows, const int b_cols, const bool has_vals)
{
aligned_vector<char> send_buffer;
int s = send_comm->get_msg_size(rowptr, values, mpi_comm, b_rows * b_cols);
send_buffer.resize(s);
init_comm_helper(send_buffer.data(), rowptr, col_indices, values, send_comm,
key, mpi_comm, b_rows, b_cols);
return complete_comm_helper(send_comm, recv_comm, key, mpi_comm,
b_rows, b_cols, has_vals);
}
template <typename T> // double* or double**
void init_comm_helper(char* send_buffer, const int* rowptr,
const int* col_indices, const T& values,
CommData* send_comm, int key, MPI_Comm mpi_comm,
const int b_rows, const int b_cols)
{
int block_size = b_rows * b_cols;
send_comm->send(send_buffer, rowptr, col_indices, values,
key, mpi_comm, block_size);
}
CSRMatrix* complete_comm_helper(CommData* send_comm, CommData* recv_comm, int key,
MPI_Comm mpi_comm, const int b_rows, const int b_cols, const bool has_vals)
{
CSRMatrix* recv_mat;
// Form recv_mat
int block_size = b_rows * b_cols;
if (b_rows > 1 || b_cols > 1)
recv_mat = new BSRMatrix(recv_comm->size_msgs, -1, b_rows, b_cols);
else
recv_mat = new CSRMatrix(recv_comm->size_msgs, -1);
// Recv contents of recv_mat
recv_comm->recv(recv_mat, key, mpi_comm, block_size, has_vals);
if (send_comm->num_msgs)
MPI_Waitall(send_comm->num_msgs, send_comm->requests.data(),
MPI_STATUSES_IGNORE);
return recv_mat;
}
template <typename T>
CSRMatrix* transpose_recv(CSRMatrix* recv_mat_T, aligned_vector<T>& T_vals,
NonContigData* send_data, int n)
{
int idx, ptr;
int start, end;
CSRMatrix* recv_mat;
aligned_vector<T>& vals = create_mat<T>(n, -1, recv_mat_T->b_rows,
recv_mat_T->b_cols, &recv_mat);
if (n == 0) return recv_mat;
aligned_vector<int> row_sizes(n, 0);
for (int i = 0; i < send_data->size_msgs; i++)
{
idx = send_data->indices[i];
start = recv_mat_T->idx1[i];
end = recv_mat_T->idx1[i+1];
row_sizes[idx] += end - start;
}
recv_mat->idx1[0] = 0;
for (int i = 0; i < n; i++)
{
recv_mat->idx1[i+1] = recv_mat->idx1[i] + row_sizes[i];
row_sizes[i] = 0;
}
recv_mat->nnz = recv_mat->idx1[n];
if (recv_mat->nnz)
{
recv_mat->idx2.resize(recv_mat->nnz);
if (T_vals.size())
vals.resize(recv_mat->nnz);
}
for (int i = 0; i < send_data->size_msgs; i++)
{
idx = send_data->indices[i];
start = recv_mat_T->idx1[i];
end = recv_mat_T->idx1[i+1];
for (int j = start; j < end; j++)
{
ptr = recv_mat->idx1[idx] + row_sizes[idx]++;
recv_mat->idx2[ptr] = recv_mat_T->idx2[j];
if (recv_mat_T->vals.size())
vals[ptr] = T_vals[j];
}
}
return recv_mat;
}
template <typename T>
CSRMatrix* combine_recvs(CSRMatrix* L_mat, CSRMatrix* R_mat,
aligned_vector<T>& L_vals, aligned_vector<T>& R_vals,
const int b_rows, const int b_cols,
NonContigData* local_L_recv, NonContigData* local_R_recv,
aligned_vector<int>& row_sizes)
{
int ctr, idx, row;
int start, end;
CSRMatrix* recv_mat;
aligned_vector<T>& vals = create_mat<T>(L_mat->n_rows + R_mat->n_rows, -1, b_rows, b_cols,
&recv_mat);
recv_mat->nnz = L_mat->nnz + R_mat->nnz;
int ptr;
if (recv_mat->nnz)
{
recv_mat->idx2.resize(recv_mat->nnz);
if (L_vals.size() || R_vals.size())
vals.resize(recv_mat->nnz);
}
for (int i = 0; i < R_mat->n_rows; i++)
{
start = R_mat->idx1[i];
end = R_mat->idx1[i+1];
row = local_R_recv->indices[i];
row_sizes[row] = end - start;
}
for (int i = 0; i < L_mat->n_rows; i++)
{
start = L_mat->idx1[i];
end = L_mat->idx1[i+1];
row = local_L_recv->indices[i];
row_sizes[row] = end - start;
}
recv_mat->idx1[0] = 0;
for (int i = 0; i < recv_mat->n_rows; i++)
{
recv_mat->idx1[i+1] = recv_mat->idx1[i] + row_sizes[i];
row_sizes[i] = 0;
}
for (int i = 0; i < R_mat->n_rows; i++)
{
start = R_mat->idx1[i];
end = R_mat->idx1[i+1];
row = local_R_recv->indices[i];
for (int j = start; j < end; j++)
{
ptr = recv_mat->idx1[row] + row_sizes[row]++;
recv_mat->idx2[ptr] = R_mat->idx2[j];
if (vals.size())
vals[ptr] = R_mat->copy_val(R_vals[j]);
}
}
for (int i = 0; i < L_mat->n_rows; i++)
{
start = L_mat->idx1[i];
end = L_mat->idx1[i+1];
row = local_L_recv->indices[i];
for (int j = start; j < end; j++)
{
ptr = recv_mat->idx1[row] + row_sizes[row]++;
recv_mat->idx2[ptr] = L_mat->idx2[j];
if (vals.size())
vals[ptr] = L_mat->copy_val(L_vals[j]);
}
}
return recv_mat;
}
template <typename T>
CSRMatrix* combine_recvs_T(CSRMatrix* L_mat, CSRMatrix* final_mat,
NonContigData* local_L_send, NonContigData* final_send,
aligned_vector<T>& L_vals, aligned_vector<T>& final_vals,
int n, int b_rows, int b_cols)
{
int row_start, row_end, row_size;
int row, idx;
CSRMatrix* recv_mat;
aligned_vector<T>& vals = create_mat<T>(n, -1, b_rows, b_cols,
&recv_mat);
aligned_vector<int> row_sizes(n, 0);
int nnz = L_mat->nnz + final_mat->nnz;
if (nnz)
{
recv_mat->idx2.resize(nnz);
if (L_vals.size() || final_vals.size())
vals.resize(nnz);
}
for (int i = 0; i < final_send->size_msgs; i++)
{
row = final_send->indices[i];
row_size = final_mat->idx1[i+1] - final_mat->idx1[i];
row_sizes[row] += row_size;
}
for (int i = 0; i < local_L_send->size_msgs; i++)
{
row = local_L_send->indices[i];
row_size = L_mat->idx1[i+1] - L_mat->idx1[i];
row_sizes[row] += row_size;
}
recv_mat->idx1[0] = 0;
for (int i = 0; i < n; i++)
{
recv_mat->idx1[i+1] = recv_mat->idx1[i] + row_sizes[i];
row_sizes[i] = 0;
}
for (int i = 0; i < final_send->size_msgs; i++)
{
row = final_send->indices[i];
row_start = final_mat->idx1[i];
row_end = final_mat->idx1[i+1];
for (int j = row_start; j < row_end; j++)
{
idx = recv_mat->idx1[row] + row_sizes[row]++;
recv_mat->idx2[idx] = final_mat->idx2[j];
if (final_vals.size())
vals[idx] = final_vals[j];
}
}
for (int i = 0; i < local_L_send->size_msgs; i++)
{
row = local_L_send->indices[i];
row_start = L_mat->idx1[i];
row_end = L_mat->idx1[i+1];
for (int j = row_start; j < row_end; j++)
{
idx = recv_mat->idx1[row] + row_sizes[row]++;
recv_mat->idx2[idx] = L_mat->idx2[j];
if (L_vals.size())
vals[idx] = L_vals[j];
}
}
recv_mat->nnz = recv_mat->idx2.size();
recv_mat->sort();
return recv_mat;
}
|
; (c) Dossytronics 2017
; test harness ROM for VHDL testbench for MEMC mk2
; makes a 4k ROM
.setcpu "6502X"
.include "common.inc"
.include "hw.inc"
.include "aeris.inc"
vec_nmi := $D00
.ZEROPAGE
ZP_PTR: .RES 2
.CODE
mostbl_chardefs:
.byte $00,$00,$00,$00,$00,$00,$00,$00
.byte $18,$18,$18,$18,$18,$00,$18,$00
.byte $6C,$6C,$6C,$00,$00,$00,$00,$00
.byte $36,$36,$7F,$36,$7F,$36,$36,$00
.byte $0C,$3F,$68,$3E,$0B,$7E,$18,$00
.byte $60,$66,$0C,$18,$30,$66,$06,$00
.byte $38,$6C,$6C,$38,$6D,$66,$3B,$00
.byte $0C,$18,$30,$00,$00,$00,$00,$00
.byte $0C,$18,$30,$30,$30,$18,$0C,$00
.byte $30,$18,$0C,$0C,$0C,$18,$30,$00
.byte $00,$18,$7E,$3C,$7E,$18,$00,$00
.byte $00,$18,$18,$7E,$18,$18,$00,$00
.byte $00,$00,$00,$00,$00,$18,$18,$30
.byte $00,$00,$00,$7E,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$18,$18,$00
.byte $00,$06,$0C,$18,$30,$60,$00,$00
.byte $3C,$66,$6E,$7E,$76,$66,$3C,$00
.byte $18,$38,$18,$18,$18,$18,$7E,$00
.byte $3C,$66,$06,$0C,$18,$30,$7E,$00
.byte $3C,$66,$06,$1C,$06,$66,$3C,$00
.byte $0C,$1C,$3C,$6C,$7E,$0C,$0C,$00
.byte $7E,$60,$7C,$06,$06,$66,$3C,$00
.byte $1C,$30,$60,$7C,$66,$66,$3C,$00
.byte $7E,$06,$0C,$18,$30,$30,$30,$00
.byte $3C,$66,$66,$3C,$66,$66,$3C,$00
.byte $3C,$66,$66,$3E,$06,$0C,$38,$00
.byte $00,$00,$18,$18,$00,$18,$18,$00
.byte $00,$00,$18,$18,$00,$18,$18,$30
.byte $0C,$18,$30,$60,$30,$18,$0C,$00
.byte $00,$00,$7E,$00,$7E,$00,$00,$00
.byte $30,$18,$0C,$06,$0C,$18,$30,$00
.byte $3C,$66,$0C,$18,$18,$00,$18,$00
.byte $3C,$66,$6E,$6A,$6E,$60,$3C,$00
.byte $3C,$66,$66,$7E,$66,$66,$66,$00
.byte $7C,$66,$66,$7C,$66,$66,$7C,$00
.byte $3C,$66,$60,$60,$60,$66,$3C,$00
.byte $78,$6C,$66,$66,$66,$6C,$78,$00
.byte $7E,$60,$60,$7C,$60,$60,$7E,$00
.byte $7E,$60,$60,$7C,$60,$60,$60,$00
.byte $3C,$66,$60,$6E,$66,$66,$3C,$00
.byte $66,$66,$66,$7E,$66,$66,$66,$00
.byte $7E,$18,$18,$18,$18,$18,$7E,$00
.byte $3E,$0C,$0C,$0C,$0C,$6C,$38,$00
.byte $66,$6C,$78,$70,$78,$6C,$66,$00
.byte $60,$60,$60,$60,$60,$60,$7E,$00
.byte $63,$77,$7F,$6B,$6B,$63,$63,$00
.byte $66,$66,$76,$7E,$6E,$66,$66,$00
.byte $3C,$66,$66,$66,$66,$66,$3C,$00
.byte $7C,$66,$66,$7C,$60,$60,$60,$00
.byte $3C,$66,$66,$66,$6A,$6C,$36,$00
.byte $7C,$66,$66,$7C,$6C,$66,$66,$00
.byte $3C,$66,$60,$3C,$06,$66,$3C,$00
.byte $7E,$18,$18,$18,$18,$18,$18,$00
.byte $66,$66,$66,$66,$66,$66,$3C,$00
.byte $66,$66,$66,$66,$66,$3C,$18,$00
.byte $63,$63,$6B,$6B,$7F,$77,$63,$00
.byte $66,$66,$3C,$18,$3C,$66,$66,$00
.byte $66,$66,$66,$3C,$18,$18,$18,$00
.byte $7E,$06,$0C,$18,$30,$60,$7E,$00
.byte $7C,$60,$60,$60,$60,$60,$7C,$00
.byte $00,$60,$30,$18,$0C,$06,$00,$00
.byte $3E,$06,$06,$06,$06,$06,$3E,$00
.byte $18,$3C,$66,$42,$00,$00,$00,$00
.byte $00,$00,$00,$00,$00,$00,$00,$FF
.byte $1C,$36,$30,$7C,$30,$30,$7E,$00
.byte $00,$00,$3C,$06,$3E,$66,$3E,$00
.byte $60,$60,$7C,$66,$66,$66,$7C,$00
.byte $00,$00,$3C,$66,$60,$66,$3C,$00
.byte $06,$06,$3E,$66,$66,$66,$3E,$00
.byte $00,$00,$3C,$66,$7E,$60,$3C,$00
.byte $1C,$30,$30,$7C,$30,$30,$30,$00
.byte $00,$00,$3E,$66,$66,$3E,$06,$3C
.byte $60,$60,$7C,$66,$66,$66,$66,$00
.byte $18,$00,$38,$18,$18,$18,$3C,$00
.byte $18,$00,$38,$18,$18,$18,$18,$70
.byte $60,$60,$66,$6C,$78,$6C,$66,$00
.byte $38,$18,$18,$18,$18,$18,$3C,$00
.byte $00,$00,$36,$7F,$6B,$6B,$63,$00
.byte $00,$00,$7C,$66,$66,$66,$66,$00
.byte $00,$00,$3C,$66,$66,$66,$3C,$00
.byte $00,$00,$7C,$66,$66,$7C,$60,$60
.byte $00,$00,$3E,$66,$66,$3E,$06,$07
.byte $00,$00,$6C,$76,$60,$60,$60,$00
.byte $00,$00,$3E,$60,$3C,$06,$7C,$00
.byte $30,$30,$7C,$30,$30,$30,$1C,$00
.byte $00,$00,$66,$66,$66,$66,$3E,$00
.byte $00,$00,$66,$66,$66,$3C,$18,$00
.byte $00,$00,$63,$6B,$6B,$7F,$36,$00
.byte $00,$00,$66,$3C,$18,$3C,$66,$00
.byte $00,$00,$66,$66,$66,$3E,$06,$3C
.byte $00,$00,$7E,$0C,$18,$30,$7E,$00
.byte $0C,$18,$18,$70,$18,$18,$0C,$00
.byte $18,$18,$18,$00,$18,$18,$18,$00
.byte $30,$18,$18,$0E,$18,$18,$30,$00
.byte $31,$6B,$46,$00,$00,$00,$00,$00
.byte $FF,$FF,$FF,$FF,$FF,$FF,$FF,$FF
_ULA_SETTINGS: .byte $9c ; 10011100
.byte $d8 ; 11011000
.byte $f4 ; 11110100
.byte $9c ; 10011100
.byte $88 ; 10001000
.byte $c4 ; 11000100
.byte $88 ; 10001000
.byte $4b ; 01001011
;************* 6845 REGISTERS 0-11 FOR SCREEN TYPE 0 - MODES 0-2 *********
_CRTC_REG_TAB: .byte $7f ; 0 Horizontal Total =128
.byte $50 ; 1 Horizontal Displayed =80
.byte $62 ; 2 Horizontal Sync =&62
.byte $28 ; 3 HSync Width+VSync =&28 VSync=2, HSync Width=8
.byte $26 ; 4 Vertical Total =38
.byte $00 ; 5 Vertial Adjust =0
.byte $20 ; 6 Vertical Displayed =32
.byte $22 ; 7 VSync Position =&22
.byte $01 ; 8 Interlace+Cursor =&01 Cursor=0, Display=0, Interlace=Sync
.byte $07 ; 9 Scan Lines/Character =8
.byte $67 ; 10 Cursor Start Line =&67 Blink=On, Speed=1/32, Line=7
.byte $08 ; 11 Cursor End Line =8
;************* 6845 REGISTERS 0-11 FOR SCREEN TYPE 1 - MODE 3 ************
.byte $7f ; 0 Horizontal Total =128
.byte $50 ; 1 Horizontal Displayed =80
.byte $62 ; 2 Horizontal Sync =&62
.byte $28 ; 3 HSync Width+VSync =&28 VSync=2, HSync=8
.byte $1e ; 4 Vertical Total =30
.byte $02 ; 5 Vertical Adjust =2
.byte $19 ; 6 Vertical Displayed =25
.byte $1b ; 7 VSync Position =&1B
.byte $01 ; 8 Interlace+Cursor =&01 Cursor=0, Display=0, Interlace=Sync
.byte $09 ; 9 Scan Lines/Character =10
.byte $67 ; 10 Cursor Start Line =&67 Blink=On, Speed=1/32, Line=7
.byte $09 ; 11 Cursor End Line =9
;************ 6845 REGISTERS 0-11 FOR SCREEN TYPE 2 - MODES 4-5 **********
.byte $3f ; 0 Horizontal Total =64
.byte $28 ; 1 Horizontal Displayed =40
.byte $31 ; 2 Horizontal Sync =&31
.byte $24 ; 3 HSync Width+VSync =&24 VSync=2, HSync=4
.byte $26 ; 4 Vertical Total =38
.byte $00 ; 5 Vertical Adjust =0
.byte $20 ; 6 Vertical Displayed =32
.byte $22 ; 7 VSync Position =&22
.byte $01 ; 8 Interlace+Cursor =&01 Cursor=0, Display=0, Interlace=Sync
.byte $07 ; 9 Scan Lines/Character =8
.byte $67 ; 10 Cursor Start Line =&67 Blink=On, Speed=1/32, Line=7
.byte $08 ; 11 Cursor End Line =8
;********** 6845 REGISTERS 0-11 FOR SCREEN TYPE 3 - MODE 6 ***************
.byte $3f ; 0 Horizontal Total =64
.byte $28 ; 1 Horizontal Displayed =40
.byte $31 ; 2 Horizontal Sync =&31
.byte $24 ; 3 HSync Width+VSync =&24 VSync=2, HSync=4
.byte $1e ; 4 Vertical Total =30
.byte $02 ; 5 Vertical Adjust =0
.byte $19 ; 6 Vertical Displayed =25
.byte $1b ; 7 VSync Position =&1B
.byte $01 ; 8 Interlace+Cursor =&01 Cursor=0, Display=0, Interlace=Sync
.byte $09 ; 9 Scan Lines/Character =10
.byte $67 ; 10 Cursor Start Line =&67 Blink=On, Speed=1/32, Line=7
.byte $09 ; 11 Cursor End Line =9
;********* 6845 REGISTERS 0-11 FOR SCREEN TYPE 4 - MODE 7 ****************
.byte $3f ; 0 Horizontal Total =64
.byte $28 ; 1 Horizontal Displayed =40
.byte $33 ; 2 Horizontal Sync =&33 Note: &31 is a better value
.byte $24 ; 3 HSync Width+VSync =&24 VSync=2, HSync=4
.byte $1e ; 4 Vertical Total =30
.byte $02 ; 5 Vertical Adjust =2
.byte $19 ; 6 Vertical Displayed =25
.byte $1b ; 7 VSync Position =&1B
.byte $93 ; 8 Interlace+Cursor =&93 Cursor=2, Display=1, Interlace=Sync+Video
.byte $12 ; 9 Scan Lines/Character =19
.byte $72 ; 10 Cursor Start Line =&72 Blink=On, Speed=1/32, Line=18
.byte $13 ; 11 Cursor End Line =19
sprite:
.INCBIN "SPRIT2"
aeris_test2:
AE_BRA aeris_test2
aeris_test2_end:
aeris_test:
AE_MOVEC 0, 3
ae_lp:
AE_MOVECC 1, 0
ae_lp2:
AE_BRA *+3
AE_BRA *+3
AE_BRA *+3
AE_BRA *+3
AE_BRA *+3
AE_DSZ 1
AE_BRA ae_lp2
AE_SYNC
AE_MOVE16 $2, $20, $ABCD
AE_UNSYNC
AE_DSZ 0
AE_BRA ae_lp
AE_BRA aeris_test
AE_SYNC
AE_MOVE16 $2, $40, $BEEF
AE_UNSYNC
AE_SYNC
AE_MOVE16 $2, $40, $DEAD
AE_UNSYNC
AE_SYNC
AE_MOVE16 $2, $40, $1234
AE_UNSYNC
AE_SYNC
AE_WAITH
AE_MOVE16 $2, $40, $FEDC
AE_MOVE16 $2, $40, $BA98
AE_MOVE16 $2, $40, $7654
AE_MOVE16 $2, $40, $3210
AE_UNSYNC
AE_BRA aeris_test
; AE_MOVEC 0, 10
; AE_MOVEP 0, aeris_rainbow
;
; ;;AE_WAIT $1FF, $00, 30, 0
;
;aeris_lp1: AE_MOVECC 1, 0
; AE_MOVEPP 1, 0
;
; AE_MOVEC 2, 9
;
;aeris_lp2: AE_PLAY16 1, 1
;
;aeris_lp3: AE_WAITH
; AE_DSZ 0
; AE_BRA aeris_lp3
;
; AE_DSZ 2
; AE_BRA aeris_lp2
;
; AE_SKIP $1FF, $00, 200, 0
; AE_BRA aeris_lp1
;
; AE_WAIT $1FF, $00, $1FF, 0
aeris_rainbow:
AE_MOVE16 $2, $23, $0000 ; black
AE_MOVE16 $2, $23, $0F00 ; red
AE_MOVE16 $2, $23, $0F80 ; orange
AE_MOVE16 $2, $23, $0FF0 ; yellow
AE_MOVE16 $2, $23, $0FF0 ; green
AE_MOVE16 $2, $23, $000F ; blue
AE_MOVE16 $2, $23, $0408 ; indigo
AE_MOVE16 $2, $23, $0F8F ; violet
AE_MOVE16 $2, $23, $0000 ; black
;; AE_MOVEC 3, 4
;;aeris_lp: AE_DSZ 3
;; AE_BRA aeris_lp
;; AE_WAITH
;;
;; AE_WAIT $1FF, $FF, 0, 5
;; AE_BRAL 7, aeris_sub
;; AE_SKIP $1FF, 0, 1, 0
;; AE_BRA aeris_test
;; AE_MOVE $2, $21, $04
;; AE_MOVE $2, $21, $14
;; AE_MOVE $2, $21, $44
;; AE_MOVE $2, $21, $54
;; AE_MOVEP 5, aeris_data
;; AE_PLAY 5, 2
;; AE_PLAY16 5, 2
AE_WAIT $1FF, $FF, $1FF, $FF ;; wait forever
;;
;;aeris_sub: AE_MOVE $2, $23, $10
;; AE_MOVE16 $2, $00, $1234
;; AE_MOVE16I $2, $02, $5678
;; AE_RET 7
;;
;;aeris_data: AE_MOVE $2, $21, $00
;; AE_MOVE $2, $21, $02
;;aeris_data16:
;; AE_MOVE16 $2, $23, $ABCD
;; AE_MOVE16 $2, $23, $DCBA
aeris_test_end:
sprite_blit_addr_mask := $050000
sprite_blit_addr_sprit := $050000 + $40
sprite2_size := 320
sample_test1:
.INCBIN "A.SAMP"
sample_len := *-sample_test1
test_data:
.byte 1,2,3,4,5,6,7,8,9
sprite2blit_ctl:
.word sprite
.byte $FF
.word sprite_blit_addr_mask & $FFFF
.byte sprite_blit_addr_mask >> 16
.word sprite2_size
sample_to_blit:
.byte $8A ; act, lin, mo.0, execD, execB 0 BLTCON
.byte $CC ; copy B to D, ignore A, C 0 FUNCGEN
WORDBE (32-1) ; 0 WIDTH
.byte 0 ; 0 HEIGHT
.byte 0 ; 0 SHIFT
.byte 0 ; 0 MASK_FIRST
.byte 0 ; 0 MASK_LAST
.byte $AA ; 0 DATA_A
.byte 0 ; 0 ADDR_A_BANK
WORDBE 0 ; 0 ADDR_A
.byte $55 ; 0 DATA_B
.byte $FF ; 0 ADDR_B_BANK
WORDBE sample_test1 ; 0 ADDR_B
.byte $5A ; 0 DATA_C
.byte 0 ; 0 ADDR_C_BANK
WORDBE 0 ; 0 ADDR_C
.byte 0 ; 0 INTCON
.byte $08 ; 0 ADDR_D_BANK
WORDBE $0000 ; 0 ADDR_D
WORDBE 256 ; 0 STRIDE_A
WORDBE 256 ; 0 STRIDE_B
WORDBE 256 ; 0 STRIDE_C
WORDBE 256 ; 0 STRIDE_D
dollar_copy_to_SRAM_settings:
.byte BLITCON_EXEC_B + BLITCON_EXEC_D ;0
.byte $CC ; copy B to D, ignore A, C FUNCGEN ;1
.byte 0 ; WIDTH ;2
.byte 255 ; HEIGHT ;3
.byte 0 ; SHIFT ;4
.byte 0 ; MASK_FIRST ;5
.byte 0 ; MASK_LAST ;6
.byte $AA ; DATA_A ;7
.byte 0 ; ADDR_A_BANK ;8
WORDBE 0 ; ADDR_A ;9
.byte $55 ; DATA_B ;B
.byte $FF ; ADDR_B_BANK ;C
WORDBE (mostbl_chardefs+8*('$'-' ')); ADDR_B ;D
.byte 0 ; ADDR_C_BANK ;F
WORDBE 0 ; ADDR_C ;10
.byte $00 ; ADDR_D_BANK ;12
WORDBE $0 ; ADDR_D ;13
.byte $00 ; ADDR_E_BANK ;15
WORDBE $0 ; ADDR_E ;16
WORDBE 1 ; STRIDE_A ;18
WORDBE 1 ; STRIDE_B ;1A
WORDBE 1 ; STRIDE_C ;1C
WORDBE 1 ; STRIDE_D ;1E
.byte BLITCON_ACT_ACT + BLITCON_ACT_MODE_1BBP ;BLTCON ACT ;0
dollar_copy_from_SRAM_settings:
.byte BLITCON_EXEC_B + BLITCON_EXEC_D
.byte $CC ; copy B to D, ignore A, C FUNCGEN
.byte 0 ; WIDTH
.byte 7 ; HEIGHT
.byte 0 ; SHIFT
.byte 0 ; MASK_FIRST
.byte 0 ; MASK_LAST
.byte $AA ; DATA_A
.byte 0 ; ADDR_A_BANK
WORDBE 0 ; ADDR_A
.byte $55 ; DATA_B
.byte $00 ; ADDR_B_BANK
WORDBE $0000 ; ADDR_B
.byte 0 ; ADDR_C_BANK
WORDBE 0 ; ADDR_C
.byte $FF ; ADDR_D_BANK
WORDBE $4000 ; ADDR_D
.byte $FF ; ADDR_E_BANK
WORDBE $4000 ; ADDR_E
WORDBE 1 ; STRIDE_A
WORDBE 1 ; STRIDE_B
WORDBE 1 ; STRIDE_C
WORDBE 1 ; STRIDE_D
dollar_copy_from_SRAM_settings_ACT := BLITCON_ACT_ACT + BLITCON_ACT_MODE_1BBP
.byte dollar_copy_from_SRAM_settings_ACT
sprite_test_settings:
.byte $EF ; act, cell, 4bpp, execD,C,B,A BLTCON
.byte $CA ; copy B to D, mask A, C FUNCGEN
WORDBE (8 - 1) ; WIDTH
.byte 32-1 ; HEIGHT
.byte 0 ; SHIFT
.byte 0 ; MASK_FIRST
.byte 0 ; MASK_LAST
.byte $AA ; DATA_A
.byte sprite_blit_addr_mask >> 16 ; ADDR_A_BANK
WORDBE sprite_blit_addr_mask & $FFFF ; ADDR_A
.byte $55 ; DATA_B
.byte sprite_blit_addr_sprit >> 16 ; ADDR_B_BANK
WORDBE sprite_blit_addr_sprit & $FFFF ; ADDR_B
.byte $5A ; DATA_C
.byte $FF ; ADDR_C_BANK
WORDBE $300C ; ADDR_C
.byte 0 ; INTCON
.byte $FF ; ADDR_D_BANK
WORDBE $300C ; ADDR_D
WORDBE 2 ; STRIDE_A
WORDBE 8 ; STRIDE_B
WORDBE 640 ; STRIDE_C
WORDBE 640 ; STRIDE_D
blitcol_test_data:
.byte $03, $80
testrts:
stx $4000
inx
stx $4001
ldx $4000
ldx $4001
rts
testrtsend:
zp_shift := $80
zp_maskf := $81
blitcolres := $100
I2C_TEST_ADDR := $A2
i2cwait:
bit jim_I2C_STAT
bmi i2cwait
rts
mos_handle_res:
; tricky test rom prolg
sei
cld
ldx #$FF
txs
; IORB block checker
sta $FE4F
sta $FE4F
sta $FE4F
; test VPA/VDA/cycles on 816
php
plp
; quick ROM E test
lda #$E
sta $FE30
lda $8000
lda #$D1
sta fred_JIM_DEVNO
; test HDMI RAM access
lda #$FA
sta fred_JIM_PAGE_HI
lda #0
sta fred_JIM_PAGE_LO
lda #$AA
sta JIM
lda JIM
lda #$55
sta JIM+1
lda JIM+1
lda JIM
HDMI_PAGE_REGS := $FBFE
HDMI_ADDR_VIDPROC_CTL := $FD20
HDMI_ADDR_VIDPROC_PAL := $FD21
HDMI_ADDR_CRTC_IX := $FD00
HDMI_ADDR_CRTC_DAT := $FD01
; set up HDMI for mode 2
lda #>HDMI_PAGE_REGS
sta fred_JIM_PAGE_HI
lda #<HDMI_PAGE_REGS
sta fred_JIM_PAGE_LO
lda _ULA_SETTINGS+2
sta HDMI_ADDR_VIDPROC_CTL
ldy #$0b ; Y=11
ldx #$0b
_BCBB0: lda _CRTC_REG_TAB,X ; get end of 6845 registers 0-11 table
sty HDMI_ADDR_CRTC_IX
sta HDMI_ADDR_CRTC_DAT
dex ; reduce pointers
dey ;
bpl _BCBB0 ; and if still >0 do it again
; palette
lda #$00
ldx #15
clc
pplp: sta HDMI_ADDR_VIDPROC_PAL
adc #$11
dex
bne pplp
; test i2c interface
lda #$D1
sta fred_JIM_DEVNO
jsr jimDMACPAGE
; send address with RnW=0
lda #I2C_TEST_ADDR
sta jim_I2C_DATA
lda #I2C_BUSY|I2C_START
sta jim_I2C_STAT
jsr i2cwait
lda #1
sta jim_I2C_DATA
lda #I2C_BUSY
sta jim_I2C_STAT
jsr i2cwait
lda #2
sta jim_I2C_DATA
lda #I2C_BUSY
sta jim_I2C_STAT
jsr i2cwait
lda #3
sta jim_I2C_DATA
lda #I2C_BUSY|I2C_STOP
sta jim_I2C_STAT
; send address with RnW=1
lda #I2C_TEST_ADDR|I2C_RNW
sta jim_I2C_DATA
lda #I2C_BUSY|I2C_START
sta jim_I2C_STAT
jsr i2cwait
lda #I2C_BUSY|I2C_RNW
sta jim_I2C_STAT
jsr i2cwait
lda jim_I2C_DATA
lda #I2C_BUSY|I2C_RNW|I2C_NACK|I2C_STOP
sta jim_I2C_STAT
jsr i2cwait
lda jim_I2C_DATA
; test BB RAM (if enabled)
lda #$D1
sta fred_JIM_DEVNO
lda #$70
sta fred_JIM_PAGE_HI
sta fred_JIM_PAGE_LO
lda #$AA
sta $FD00
lda $FD00
; test Chipram
lda #$00
sta fred_JIM_PAGE_HI
sta fred_JIM_PAGE_LO
lda #$AA
sta $FD00
lda $FD00
; test Flash
lda #$90
sta fred_JIM_PAGE_HI
sta fred_JIM_PAGE_LO
lda $FD00
lda $FD00
lda $FD00
; test throttle
lda #$80
sta $FE36
lda #$D1
sta fred_JIM_DEVNO
nop
nop
lda fred_JIM_DEVNO
lda #0
sta fred_JIM_DEVNO
lda #0
sta $FE36
lda #$D1
sta fred_JIM_DEVNO
; test RAM0 access
lda #$01
sta fred_JIM_PAGE_HI
sta fred_JIM_PAGE_LO
sta JIM
lda JIM
; test BBC slow bus bodge
sta sheila_SYSVIA_orb
lda sheila_SYSVIA_ora
sta sheila_SYSVIA_orb
sta sheila_SYSVIA_orb
; enable jim
lda #JIM_DEVNO_BLITTER
sta fred_JIM_DEVNO
lda fred_JIM_DEVNO
; quick BLTURBO test
lda #$80
sta $FE37
ldx #23
stx $7F0F
ldx $7F0F
; quick version test
lda #$FC
sta $FCFD
lda $FD00
lda $FD00
; test contention of resources - set off a dma transfer
; from ChipRAM to SYS run program from memory at same
; time copying to/from SYS
; initialise DMAC channel 0
jsr jimDMACPAGE
ldx #0
stx jim_DMAC_DMA_SEL
; source is Base of MOS in ChipRAM (80 0000)
ldx #$80
stx jim_DMAC_DMA_SRC_ADDR
ldx #0
stx jim_DMAC_DMA_SRC_ADDR+1
stx jim_DMAC_DMA_SRC_ADDR+2
; dest is Screen RAM at FF 7000
ldx #$FF
stx jim_DMAC_DMA_DEST_ADDR
ldx #$70
stx jim_DMAC_DMA_DEST_ADDR+1
ldx #0
stx jim_DMAC_DMA_DEST_ADDR+2
ldx #$00
stx jim_DMAC_DMA_COUNT
ldx #$40
stx jim_DMAC_DMA_COUNT+1
ldx #DMACTL_ACT | DMACTL_STEP_DEST_UP | DMACTL_STEP_SRC_UP
stx jim_DMAC_DMA_CTL
; loop copying from SYS RAM at FF 1000 to Chip RAM at 00 01000
@lpDMA: jsr jimChipRAMPAGE
lda $1000,X
sta JIM,X
inx
jsr jimDMACPAGE
lda jim_DMAC_DMA_CTL
bmi @lpDMA
lda #20
sta 0
@lp0: dec 0
bne @lp0
lda $FC00
lda $FC00
jmp @sksk
@sksk: lda $FC00
lda $FC00
lda #$A5
eor $FC00
; sound select test
jsr jimDMACPAGE
ldx #3
@l1_1: stx jim_DMAC_SND_SEL
txa
asl A
asl A
asl A
asl A
sta jim_DMAC_SND_ADDR+1
dex
bpl @l1_1
ldx #3
@l1_2: stx jim_DMAC_SND_SEL
lda jim_DMAC_SND_ADDR+1
dex
bpl @l1_2
lda #0
sta fred_JIM_PAGE_HI
sta fred_JIM_PAGE_LO
; test run from RAM
ldx #testrtsend-testrts
@lprts: lda testrts,X
sta $FD00,X
dex
bpl @lprts
jsr $FD00
jsr testDMAC_simple
;; jsr illegalops
jsr AERTEST
ldx #0
@lp: stx $FE40
stx $FE40
stx $FE40
stx $FE40
stx $FE40
stx $FE40
stx $FE40
inx
jmp @lp
; blturbo on page 0, 1
lda #$03
sta sheila_MEM_LOMEMTURBO
jsr testrts
; check clock lock
lda $FC00
lda $FC00
lda $FC00
lda $FC00
bne @s1
@s1: lda $FC00
lda $FC00
lda $FC00
lda $FC00
jsr SOUNDTEST
jsr AERTEST
HERE: jmp HERE
; test blitter collision detection
lda #0
sta zp_shift
lda #$FF
sta zp_maskf
ldx #$FF
stx jim_DMAC_ADDR_A
stx jim_DMAC_ADDR_B
stx jim_DMAC_MASK_LAST
ldx #0
stx jim_DMAC_HEIGHT
inx
stx jim_DMAC_WIDTH
ldx #$C0
stx jim_DMAC_FUNCGEN
ldx #BLITCON_EXEC_A+BLITCON_EXEC_B
stx jim_DMAC_BLITCON
@loop: ldx #>blitcol_test_data
stx jim_DMAC_ADDR_A+1
stx jim_DMAC_ADDR_B+1
ldx #<blitcol_test_data
stx jim_DMAC_ADDR_A+2
stx jim_DMAC_ADDR_B+2
ldx zp_shift
stx jim_DMAC_SHIFT
ldx zp_maskf
stx jim_DMAC_MASK_FIRST
ldx #BLITCON_ACT_MODE_1BBP+BLITCON_ACT_ACT+BLITCON_ACT_COLLISION
stx jim_DMAC_BLITCON
ldx zp_shift
lda jim_DMAC_BLITCON
sta blitcolres, X
; next
inc zp_shift
lsr zp_maskf
bne @loop
ldx #0
@loop2: lda blitcolres, X
inx
cpx #8
bne @loop2
; test lo memory blturbo
lda #0
sta fred_JIM_PAGE_HI
lda #02
sta fred_JIM_PAGE_LO
ldx #testrtsend-testrts-1
@lp: lda testrts,X
sta $FD00,X
dex
bpl @lp
lda #01
sta sheila_MEM_LOMEMTURBO
jsr $200
lda #$03
sta $FE37 ; make pages 00-2F shadow
sta $4000
sta $4001
lda #$10
sta fred_JIM_PAGE_HI
sta fred_JIM_PAGE_LO
ldx #testrtsend-testrts
@l1: lda testrts,X
sta jim_base,X
dex
bpl @l1
jsr jim_base
lda #0
sta $FE37
jsr jim_base
jsr SOUNDTEST
ldx #0
@l2: stx $FE30
lda $8000
inx
cpx #10
bne @l2
; test DMAC pause
LDA #$FF
STA jim_DMAC_DMA_SRC_ADDR
STA jim_DMAC_DMA_DEST_ADDR
LDA #>(sample_to_blit + 31)
STA jim_DMAC_DMA_SRC_ADDR + 1
LDA #<(sample_to_blit + 31)
STA jim_DMAC_DMA_SRC_ADDR + 2
LDA #>$FC5C
STA jim_DMAC_DMA_DEST_ADDR + 1
LDA #<$FC5C
STA jim_DMAC_DMA_DEST_ADDR + 2
LDA #0
STA jim_DMAC_DMA_COUNT
LDA #$5
STA jim_DMAC_DMA_COUNT+1
LDA #$01
STA jim_DMAC_DMA_CTL2 ; pause!
LDA #5
STA jim_DMAC_DMA_PAUSE_VAL
LDA #$BA ; act, dest, src down, halt, extend
STA jim_DMAC_DMA_CTL
; test sound register writes / reads
lda #0
sta jim_DMAC_SND_SEL
lda #0
sta jim_DMAC_SND_DATA
lda #255
sta jim_DMAC_SND_DATA
lda #3
sta jim_DMAC_SND_SEL
lda #0
sta jim_DMAC_SND_DATA
lda #128
sta jim_DMAC_SND_DATA
lda #0
sta jim_DMAC_SND_SEL
lda jim_DMAC_SND_DATA
; test DMAC
LDA #$FF
STA jim_DMAC_DMA_SRC_ADDR
STA jim_DMAC_DMA_DEST_ADDR
LDA #>(sample_to_blit + 31)
STA jim_DMAC_DMA_SRC_ADDR + 1
LDA #<(sample_to_blit + 31)
STA jim_DMAC_DMA_SRC_ADDR + 2
LDA #>(jim_DMAC + 31)
STA jim_DMAC_DMA_DEST_ADDR + 1
LDA #<(jim_DMAC + 31)
STA jim_DMAC_DMA_DEST_ADDR + 2
LDA #0
STA jim_DMAC_DMA_COUNT
LDA #$1F
STA jim_DMAC_DMA_COUNT+1
LDA #$01
STA jim_DMAC_DMA_CTL2 ; pause!
LDA #3
STA jim_DMAC_DMA_PAUSE_VAL
LDA #$BA ; act, dest, src down, halt, extend
STA jim_DMAC_DMA_CTL
skipahead:
testDMAC_simple:
; test DMAC simple 16 bits
jsr jimDMACPAGE
LDA #$FF
STA jim_DMAC_DMA_SEL
STA jim_DMAC_DMA_SRC_ADDR
STA jim_DMAC_DMA_DEST_ADDR
LDA #>test_data
STA jim_DMAC_DMA_SRC_ADDR + 1
LDA #<test_data
STA jim_DMAC_DMA_SRC_ADDR + 2
LDA #>$4000
STA jim_DMAC_DMA_DEST_ADDR + 1
LDA #<$4000
STA jim_DMAC_DMA_DEST_ADDR + 2
LDA #>$10
STA jim_DMAC_DMA_COUNT
LDA #<$10
STA jim_DMAC_DMA_COUNT+1
LDA #$04 ; word, no swap
STA jim_DMAC_DMA_CTL2 ; no pause!
LDA #0
STA jim_DMAC_DMA_PAUSE_VAL
LDA #$A5 ; act, dest, src up, NOT halt, extend
STA jim_DMAC_DMA_CTL
LDA $FE60
STX $FE60
INX
JMP @jj
@jj: LDA $FE60
STX $FE60
INX
@w: BIT jim_DMAC_DMA_CTL
BMI @w
; test count =0 restart - should do a single iteration back to 4000
LDA #0
STA jim_DMAC_DMA_DEST_ADDR+2
LDA #$A5 ; act, dest, src up, NOT halt, extend
STA jim_DMAC_DMA_CTL
@w2: BIT jim_DMAC_DMA_CTL
BMI @w2
rts
jimDMACPAGE:
pha
lda #<jim_page_DMAC
sta fred_JIM_PAGE_LO
lda #>jim_page_DMAC
sta fred_JIM_PAGE_HI
pla
rts
jimChipRAMPAGE:
pha
lda #0
sta fred_JIM_PAGE_LO
sta fred_JIM_PAGE_HI
pla
rts
SOUNDTEST:
jsr jimDMACPAGE
; sound read test
lda #3
sta jim_DMAC_SND_SEL
lda #$ff
sta jim_DMAC_SND_SEL
lda jim_DMAC_SND_SEL
; set up sound sample
lda #1
sta fred_JIM_PAGE_HI
sta fred_JIM_PAGE_LO
ldx #31
@lll1: txa
sta $FD00,X
dex
bpl @lll1
jsr jimDMACPAGE
ldy #0
sl: sty jim_DMAC_SND_SEL
; play samples
ldx #1
stx jim_DMAC_SND_ADDR
ldx #1
stx jim_DMAC_SND_ADDR + 1
ldx #0
stx jim_DMAC_SND_ADDR + 2
ldx #0
stx jim_DMAC_SND_PERIOD
stx jim_DMAC_SND_LEN
tya
asl a
asl a
adc #20
sta jim_DMAC_SND_PERIOD + 1
ldx #31
stx jim_DMAC_SND_LEN + 1
ldx #$81
stx jim_DMAC_SND_STATUS
iny
cpy #4
bne sl
rts
AERTEST:
jsr jimDMACPAGE
; test dma
lda #0
sta jim_DMAC_DMA_SEL
; source address from ROM at FFCxxx
lda #$FF
sta jim_DMAC_DMA_SRC_ADDR
lda #>aeris_test
sta jim_DMAC_DMA_SRC_ADDR+1
lda #<aeris_test
sta jim_DMAC_DMA_SRC_ADDR+2
lda #$00
sta jim_DMAC_DMA_DEST_ADDR
lda #$10
sta jim_DMAC_DMA_DEST_ADDR+1
lda #$00
sta jim_DMAC_DMA_DEST_ADDR+2
lda #>(aeris_test_end-aeris_test-1)
sta jim_DMAC_DMA_COUNT
lda #<(aeris_test_end-aeris_test-1)
sta jim_DMAC_DMA_COUNT+1
lda #DMACTL_ACT+DMACTL_HALT+DMACTL_STEP_SRC_UP+DMACTL_STEP_DEST_UP
sta jim_DMAC_DMA_CTL
;aeris setup at $00 1000
; lda #0
; sta fred_JIM_PAGE_HI
; lda #$10
; sta fred_JIM_PAGE_LO
;
; ; copy data to chip ram
; ldx #aeris_test_end-aeris_test-1
;aecpylp:lda aeris_test,X
; sta JIM,X
; dex
; bpl aecpylp
;
; jsr jimDMACPAGE
lda #$00
sta jim_DMAC_AERIS_PROGBASE
lda #$10
sta jim_DMAC_AERIS_PROGBASE+1
lda #$00
sta jim_DMAC_AERIS_PROGBASE+2
lda #$80
sta jim_DMAC_AERIS_CTL
rts
AERTEST2:
jsr jimDMACPAGE
; test dma
lda #0
sta jim_DMAC_DMA_SEL
; source address from ROM at FFCxxx
lda #$FF
sta jim_DMAC_DMA_SRC_ADDR
lda #>aeris_test2
sta jim_DMAC_DMA_SRC_ADDR+1
lda #<aeris_test2
sta jim_DMAC_DMA_SRC_ADDR+2
lda #$00
sta jim_DMAC_DMA_DEST_ADDR
lda #$10
sta jim_DMAC_DMA_DEST_ADDR+1
lda #$00
sta jim_DMAC_DMA_DEST_ADDR+2
lda #>(aeris_test2_end-aeris_test2-1)
sta jim_DMAC_DMA_COUNT
lda #<(aeris_test2_end-aeris_test2-1)
sta jim_DMAC_DMA_COUNT+1
lda #DMACTL_ACT+DMACTL_HALT+DMACTL_STEP_SRC_UP+DMACTL_STEP_DEST_UP
sta jim_DMAC_DMA_CTL
lda #$00
sta jim_DMAC_AERIS_PROGBASE
lda #$10
sta jim_DMAC_AERIS_PROGBASE+1
lda #$00
sta jim_DMAC_AERIS_PROGBASE+2
lda #$80
sta jim_DMAC_AERIS_CTL
rts
; ; wait until blit done
;1 LDA jim_DMAC_BLITCON
; BMI 1B
RTS
; test some illegal operations
illegalops:
ldx #$55 ; mask
lda #%10011100 ; data
sax 0 ; should store 00010100 to 0
alr #$AA ; A should be 01000100
slo 0 ; 0 should go to 00101000 and A to 01101100
sta 0
rts
mos_handle_irq:
rti
.SEGMENT "VECTORS"
hanmi: .addr vec_nmi ; FFFA 00 0D ..
hares: .addr mos_handle_res ; FFFC CD D9 ..
hairq: .addr mos_handle_irq ; FFFE 1C DC ..
.END
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/elasticmapreduce/model/InstanceGroupStateChangeReason.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace EMR
{
namespace Model
{
InstanceGroupStateChangeReason::InstanceGroupStateChangeReason() :
m_code(InstanceGroupStateChangeReasonCode::NOT_SET),
m_codeHasBeenSet(false),
m_messageHasBeenSet(false)
{
}
InstanceGroupStateChangeReason::InstanceGroupStateChangeReason(const JsonValue& jsonValue) :
m_code(InstanceGroupStateChangeReasonCode::NOT_SET),
m_codeHasBeenSet(false),
m_messageHasBeenSet(false)
{
*this = jsonValue;
}
InstanceGroupStateChangeReason& InstanceGroupStateChangeReason::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("Code"))
{
m_code = InstanceGroupStateChangeReasonCodeMapper::GetInstanceGroupStateChangeReasonCodeForName(jsonValue.GetString("Code"));
m_codeHasBeenSet = true;
}
if(jsonValue.ValueExists("Message"))
{
m_message = jsonValue.GetString("Message");
m_messageHasBeenSet = true;
}
return *this;
}
JsonValue InstanceGroupStateChangeReason::Jsonize() const
{
JsonValue payload;
if(m_codeHasBeenSet)
{
payload.WithString("Code", InstanceGroupStateChangeReasonCodeMapper::GetNameForInstanceGroupStateChangeReasonCode(m_code));
}
if(m_messageHasBeenSet)
{
payload.WithString("Message", m_message);
}
return payload;
}
} // namespace Model
} // namespace EMR
} // namespace Aws |
/* **********************************************************
* Copyright (c) 2008-2009 VMware, Inc. All rights reserved.
* ********************************************************** */
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of VMware, Inc. nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* 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 VMWARE, INC. 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.
*/
#ifndef _ASM_DEFINES_ASM_
#define _ASM_DEFINES_ASM_ 1
/* Preprocessor macro definitions shared among all .asm files.
* Since cpp macros can't generate newlines we have a later
* script replace @N@ for us.
*/
#include "configure.h"
/****************************************************/
#if defined(ASSEMBLE_WITH_GAS)
# define START_FILE .text
# define END_FILE /* nothing */
# define DECLARE_FUNC(symbol) \
.align 0 @N@\
.global symbol @N@\
.hidden symbol @N@\
.type symbol, %function
# define DECLARE_EXPORTED_FUNC(symbol) \
.align 0 @N@\
.global symbol @N@\
.type symbol, %function
# define END_FUNC(symbol) /* nothing */
# define DECLARE_GLOBAL(symbol) \
.global symbol @N@\
.hidden symbol
# define GLOBAL_LABEL(label) label
# define ADDRTAKEN_LABEL(label) label
# define WORD word ptr
# define DWORD dword ptr
# define QWORD qword ptr
# ifdef X64
/* w/o the rip, gas won't use rip-rel and adds relocs that ld trips over */
# define SYMREF(sym) [rip + sym]
# else
# define SYMREF(sym) [sym]
# endif
# define HEX(n) 0x##n
# define SEGMEM(seg,mem) [seg:mem]
# define DECL_EXTERN(symbol) /* nothing */
/* include newline so we can put multiple on one line */
# define RAW(n) .byte HEX(n) @N@
# define DECLARE_FUNC_SEH(symbol) DECLARE_FUNC(symbol)
# define PUSH_SEH(reg) push reg
# define PUSH_NONCALLEE_SEH(reg) push reg
# define END_PROLOG /* nothing */
/* PR 212290: avoid text relocations.
* @GOT returns the address and is for extern vars; @GOTOFF gets the value.
* Note that using ## to paste =>
* "error: pasting "initstack_mutex" and "@" does not give a valid preprocessing token"
* but whitespace separation seems fine.
*/
# define ADDR_VIA_GOT(base, sym) [sym @GOT + base]
# define VAR_VIA_GOT(base, sym) [sym @GOTOFF + base]
/****************************************************/
#elif defined(ASSEMBLE_WITH_MASM)
# ifdef X64
# define START_FILE .CODE
# else
# define START_FILE \
.686 /* default is 8086! need 686 for sysenter */ @N@\
.XMM /* needed for fnclex and fxrstor */ @N@\
.MODEL flat, c @N@\
ASSUME fs:_DATA @N@\
.CODE
# endif
# define END_FILE END
/* we don't seem to need EXTERNDEF or GLOBAL */
# define DECLARE_FUNC(symbol) symbol PROC
# define DECLARE_EXPORTED_FUNC(symbol) symbol PROC
# define END_FUNC(symbol) symbol ENDP
# define DECLARE_GLOBAL(symbol)
# define GLOBAL_LABEL(label)
# define ADDRTAKEN_LABEL(label) label
# define WORD word ptr
# define DWORD dword ptr
# define QWORD qword ptr
/* ml64 uses rip-rel automatically */
# define SYMREF(sym) [sym]
# define HEX(n) 0##n##h
# define SEGMEM(seg,mem) seg:[mem]
# define DECL_EXTERN(symbol) EXTERN symbol:PROC
/* include newline so we can put multiple on one line */
# define RAW(n) DB HEX(n) @N@
# ifdef X64
/* 64-bit SEH directives */
/* Declare non-leaf function (adjusts stack; makes calls; saves non-volatile regs): */
# define DECLARE_FUNC_SEH(symbol) symbol PROC FRAME
/* Push a non-volatile register in prolog: */
# define PUSH_SEH(reg) push reg @N@ .pushreg reg
/* Push a volatile register or an immed in prolog: */
# define PUSH_NONCALLEE_SEH(reg) push reg @N@ .allocstack 8
# define END_PROLOG .endprolog
# else
# define DECLARE_FUNC_SEH(symbol) DECLARE_FUNC(symbol)
# define PUSH_SEH(reg) push reg
# define PUSH_NONCALLEE_SEH(reg) push reg
# define END_PROLOG /* nothing */
# endif
/****************************************************/
#elif defined(ASSEMBLE_WITH_NASM)
# define START_FILE SECTION .text
# define END_FILE /* nothing */
# define DECLARE_FUNC(symbol) global symbol
# define DECLARE_EXPORTED_FUNC(symbol) global symbol
# define END_FUNC(symbol) /* nothing */
# define DECLARE_GLOBAL(symbol) global symbol
# define GLOBAL_LABEL(label) label
# define WORD word
# define DWORD dword
# define QWORD qword
# define SYMREF(sym) [sym]
# define HEX(n) 0x##n
# define SEGMEM(seg,mem) [seg:mem]
# define DECL_EXTERN(symbol) EXTERN symbol
# define RAW(n) error_not_implemented
# define DECLARE_FUNC_SEH(symbol) DECLARE_FUNC(symbol)
# define PUSH_SEH(reg) push reg
# define PUSH_NONCALLEE_SEH(reg) push reg
# define END_PROLOG /* nothing */
/****************************************************/
#else
# error Unknown assembler
#endif
/****************************************************/
/* Macros for writing cross-platform 64-bit + 32-bit code */
#ifdef X64
# define REG_XAX rax
# define REG_XBX rbx
# define REG_XCX rcx
# define REG_XDX rdx
# define REG_XSI rsi
# define REG_XDI rdi
# define REG_XBP rbp
# define REG_XSP rsp
# define SEG_TLS gs /* keep in sync w/ {linux,win32}/os_exports.h defines */
# ifdef WINDOWS
/* Arguments are passed in: rcx, rdx, r8, r9, then on stack right-to-left, but
* leaving space on stack for the 1st 4.
*/
# define ARG1 rcx
# define ARG2 rdx
# define ARG3 r8
# define ARG4 r9
# define ARG5 QWORD [40 + esp] /* includes ret addr */
# define ARG6 QWORD [48 + esp]
# define ARG5_NORETADDR QWORD [32 + esp]
# else
/* Arguments are passed in: rdi, rsi, rdx, rcx, r8, r9, then on stack right-to-left,
* without leaving any space on stack for the 1st 6.
*/
# define ARG1 rdi
# define ARG2 rsi
# define ARG3 rdx
# define ARG4 rcx
# define ARG5 r8
# define ARG5_NORETADDR ARG5
# define ARG6 r9
# endif
# define ARG_SZ 8
# define PTRSZ QWORD
#else /* x86 */
# define REG_XAX eax
# define REG_XBX ebx
# define REG_XCX ecx
# define REG_XDX edx
# define REG_XSI esi
# define REG_XDI edi
# define REG_XBP ebp
# define REG_XSP esp
# define SEG_TLS fs /* keep in sync w/ {linux,win32}/os_exports.h defines */
# define ARG_SZ 4
# define PTRSZ DWORD
/* Arguments are passed on stack right-to-left. */
# define ARG1 DWORD [4 + esp] /* includes ret addr */
# define ARG2 DWORD [8 + esp]
# define ARG3 DWORD [12 + esp]
# define ARG4 DWORD [16 + esp]
# define ARG5 DWORD [20 + esp]
# define ARG6 DWORD [24 + esp]
#endif
#ifdef X64
# define PUSHF pushfq
# define POPF popfq
# ifdef WINDOWS
# define STACK_PAD(tot, gt4) \
lea REG_XSP, [-32 - ARG_SZ*gt4 + REG_XSP]
# define STACK_UNPAD(tot, gt4) \
lea REG_XSP, [32 + ARG_SZ*gt4 + REG_XSP]
/* we split these out just to avoid nop lea for x64 linux */
# define STACK_PAD_LE4 STACK_PAD(0/*doesn't matter*/, 0)
# define STACK_UNPAD_LE4(tot) STACK_UNPAD(tot, 0)
# else
# define STACK_PAD(tot, gt4) \
lea REG_XSP, [-ARG_SZ*gt4 + REG_XSP]
# define STACK_UNPAD(tot, gt4) \
lea REG_XSP, [ARG_SZ*gt4 + REG_XSP]
# define STACK_PAD_LE4 /* nothing */
# define STACK_UNPAD_LE4(tot) /* nothing */
# endif
# define SETARG(argreg, p) \
mov argreg, p
#else
# define PUSHF pushfd
# define POPF popfd
# define STACK_PAD(tot, gt4) /* nothing */
# define STACK_UNPAD(tot, gt4) \
lea REG_XSP, [ARG_SZ*tot + REG_XSP]
# define STACK_PAD_LE4 /* nothing */
# define STACK_UNPAD_LE4(tot) STACK_UNPAD(tot, 0)
/* SETARG usage is order-dependent on 32-bit. we could avoid that
* by having STACK_PAD allocate the stack space and do a mov here.
*/
# define SETARG(argreg, p) \
push p
#endif
/* CALLC* are for C calling convention callees only.
* Caller must ensure that if params are passed in regs there are no conflicts.
* Caller can rely on us storing each parameter in reverse order.
* For x64, caller must arrange for 16-byte alignment at end of arg setup.
*/
#define CALLC0(callee) \
STACK_PAD_LE4 @N@\
call callee @N@\
STACK_UNPAD_LE4(0)
#define CALLC1(callee, p1) \
STACK_PAD_LE4 @N@\
SETARG(ARG1, p1) @N@\
call callee @N@\
STACK_UNPAD_LE4(1)
#define CALLC2(callee, p1, p2) \
STACK_PAD_LE4 @N@\
SETARG(ARG2, p2) @N@\
SETARG(ARG1, p1) @N@\
call callee @N@\
STACK_UNPAD_LE4(2)
#define CALLC3(callee, p1, p2, p3) \
STACK_PAD_LE4 @N@\
SETARG(ARG3, p3) @N@\
SETARG(ARG2, p2) @N@\
SETARG(ARG1, p1) @N@\
call callee @N@\
STACK_UNPAD_LE4(3)
#define CALLC4(callee, p1, p2, p3, p4) \
STACK_PAD_LE4 @N@\
SETARG(ARG4, p4) @N@\
SETARG(ARG3, p3) @N@\
SETARG(ARG2, p2) @N@\
SETARG(ARG1, p1) @N@\
call callee @N@\
STACK_UNPAD_LE4(4)
#define CALLC5(callee, p1, p2, p3, p4, p5) \
STACK_PAD(5, 1) @N@\
SETARG(ARG5_NORETADDR, p5) @N@\
SETARG(ARG4, p4) @N@\
SETARG(ARG3, p3) @N@\
SETARG(ARG2, p2) @N@\
SETARG(ARG1, p1) @N@\
call callee @N@\
STACK_UNPAD(5, 1)
/* For stdcall callees */
#ifdef X64
# define CALLWIN0 CALLC0
# define CALLWIN1 CALLC1
# define CALLWIN2 CALLC2
#else
# define CALLWIN0(callee) \
STACK_PAD_LE4 @N@\
call callee
# define CALLWIN1(callee, p1) \
STACK_PAD_LE4 @N@\
SETARG(ARG1, p1) @N@\
call callee
# define CALLWIN2(callee, p1, p2) \
STACK_PAD_LE4 @N@\
SETARG(ARG2, p2) @N@\
SETARG(ARG1, p1) @N@\
call callee
#endif
#endif /* _ASM_DEFINES_ASM_ */
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>timerfd_settime64(vararg_0, vararg_1, vararg_2, vararg_3, vararg_4) -> str
Invokes the syscall timerfd_settime64.
See 'man 2 timerfd_settime64' for more information.
Arguments:
vararg(int): vararg
Returns:
long
</%docstring>
<%page args="vararg_0=None, vararg_1=None, vararg_2=None, vararg_3=None, vararg_4=None"/>
<%
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 = ['vararg_0', 'vararg_1', 'vararg_2', 'vararg_3', 'vararg_4']
argument_values = [vararg_0, vararg_1, vararg_2, vararg_3, vararg_4]
# 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=%s' % (name, pwnlib.shellcraft.pretty(arg, False)))
# 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_timerfd_settime64']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* timerfd_settime64(${', '.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)}
|
; play some animated gifs
.start_fx_playgifs
PLAYGIFS_shadow_addr = MODE7_VRAM_SHADOW+40
PLAYGIFS_num = 4
PLAYGIFS_time = 25 * 8
PLAYGIFS_BIRD = 0
PLAYGIFS_WEATHER = 1
PLAYGIFS_DANCER = 2
PLAYGIFS_BLUEBLOB = 3
.fx_playgifs_data
{
EQUW animated_gif_bird
EQUW animated_gif_weather
EQUW animated_gif_dancer
EQUW animated_gif_blueblob
}
.fx_playgifs_speed
{
EQUB 1
EQUB 2
EQUB 3
EQUB 4
}
.fx_playgifs_length
{
EQUB 25 * 4
EQUB 255
EQUB 25 * 6
EQUB 25 * 3
}
\ ******************************************************************
\ * Play GIFs FX
\ ******************************************************************
.fx_playgifs_num
EQUB 0
.fx_playgifs_timer
EQUB 0
; A contains animation to play
.fx_playgifs_init
{
\\ Get GIF data
ASL A
TAX
LDA fx_playgifs_data, X
LDY fx_playgifs_data+1, X
TAX
JSR mode7_gif_anim_set_data
\\ Initialise GIF player
LDX fx_playgifs_num
LDA fx_playgifs_speed, X
LDX #LO(PLAYGIFS_shadow_addr)
LDY #HI(PLAYGIFS_shadow_addr)
JSR mode7_gif_anim_init
\\ Reset our timer
LDX fx_playgifs_num
LDA fx_playgifs_length, X
STA fx_playgifs_timer
RTS
}
.fx_playgifs_update
{
\\ Decrement our timer
DEC fx_playgifs_timer
BEQ play_next_gif
\\ Update GIF player
JSR mode7_gif_anim_update
RTS
\\ Next GIF
.play_next_gif
LDA fx_playgifs_num
CLC
ADC #1
CMP #PLAYGIFS_num
BCC init_next_gif
JSR fx_buffer_clear
LDA #0
.init_next_gif
STA fx_playgifs_num
JSR fx_playgifs_init
.return
RTS
}
.fx_playgifs_playanim
{
cmp sequence
beq sameanim
sta fx_playgifs_num
sta sequence
JSR fx_buffer_clear
lda fx_playgifs_num
JSR fx_playgifs_init
.sameanim
\\ Update GIF player
JSR mode7_gif_anim_update
rts
.sequence EQUB 255
}
.animated_gif_bird
INCBIN "data\gifs\bird_beeb.bin"
.animated_gif_weather
INCBIN "data\gifs\weather_beeb.bin"
.animated_gif_dancer
INCBIN "data\gifs\dancer_beeb.bin"
.animated_gif_blueblob
INCBIN "data\gifs\blueblob_beeb.bin"
.end_fx_playgifs |
/**
* GeoDa TM, Copyright (C) 2011-2015 by Luc Anselin - all rights reserved
*
* This file is part of GeoDa.
*
* GeoDa is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GeoDa 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ShapeFileHdr.h"
#include "../GdaConst.h"
#include "../GenUtils.h"
#ifndef GDA_SWAP
#define GDA_SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))
#endif
ShapeFileHdr::ShapeFileHdr(const ShapeFileTypes::ShapeType FileShape)
: FileCode(kFileCode), Version(kVersion),
FileLength(GdaConst::ShpHeaderSize), fShape(FileShape)
{
}
ShapeFileHdr::ShapeFileHdr(const char* s)
{
//MMM: very dangerous. This is where the problems begin
// on 64 bit builds!
HdrRecord *hr= (HdrRecord *) s;
#ifdef WORDS_BIGENDIAN
FileCode = hr->f[0];
#else
FileCode = GenUtils::Reverse(hr->f[0]);
#endif
#ifdef WORDS_BIGENDIAN
FileLength = hr->f[6];
#else
FileLength = GenUtils::Reverse(hr->f[6]);
HdrRecord64 *hr64=(HdrRecord64 *) s;
wxInt32 x = GenUtils::ReverseInt(hr64->f[6]);
#endif
#ifdef WORDS_BIGENDIAN
Version = GenUtils::Reverse(hr->f[7]);
#else
Version = hr->f[7];
#endif
#ifdef WORDS_BIGENDIAN
fShape = GenUtils::Reverse(hr->f[8]);
#else
fShape = hr->f[8];
#endif
#ifdef WORDS_BIGENDIAN
char r[32], t;
memcpy(&r[0], &s[36], sizeof(double) * 4);
double m1, m2, n1, n2;
GDA_SWAP(r[0], r[31], t);
GDA_SWAP(r[1], r[30], t);
GDA_SWAP(r[2], r[29], t);
GDA_SWAP(r[3], r[28], t);
GDA_SWAP(r[4], r[27], t);
GDA_SWAP(r[5], r[26], t);
GDA_SWAP(r[6], r[25], t);
GDA_SWAP(r[7], r[24], t);
GDA_SWAP(r[8], r[23], t);
GDA_SWAP(r[9], r[22], t);
GDA_SWAP(r[10], r[21], t);
GDA_SWAP(r[11], r[20], t);
GDA_SWAP(r[12], r[19], t);
GDA_SWAP(r[13], r[18], t);
GDA_SWAP(r[14], r[17], t);
GDA_SWAP(r[15], r[16], t);
memcpy(&m1, &r[24], sizeof(double));
memcpy(&m2, &r[16], sizeof(double));
memcpy(&n1, &r[8], sizeof(double));
memcpy(&n2, &r[0], sizeof(double));
BasePoint p1 = BasePoint(m1, m2);
BasePoint p2 = BasePoint(n1, n2);
FileBox = Box(p1, p2);
hr->b = FileBox;
#else
memcpy(&FileBox, &s[36], sizeof(double)*4);
hr->b = FileBox;
#endif
}
void ShapeFileHdr::SetFileBox(const Box& fBox)
{
//LOG_MSG("Entering ShapeFileHdr::SetFileBox");
FileBox = fBox;
//LOG(FileBox.Bmin.x);
//LOG(FileBox.Bmin.y);
//LOG(FileBox.Bmax.x);
//LOG(FileBox.Bmax.y);
//LOG_MSG("Exiting ShapeFileHdr::SetFileBox");
}
void ShapeFileHdr::SetFileLength(wxInt32 fl)
{
FileLength = fl;
}
void ShapeFileHdr::MakeBuffer(char* s) const
{
HdrRecord * hr= (HdrRecord *) s;
wxInt32 *ptr= (wxInt32 *) s;
int cp;
for (cp= 0; cp < GdaConst::ShpHeaderSize/2; ++cp) ptr[cp]= 0;
#ifdef WORDS_BIGENDIAN
hr->f[0] = FileCode;
hr->f[6] = FileLength;
hr->f[7] = GenUtils::Reverse(Version);
hr->f[8] = GenUtils::Reverse(fShape);
hr->b = FileBox;
char r[32], t;
// MMM: This can't be correct. Verify this!
GDA_SWAP(r[0], r[31], t);
GDA_SWAP(r[1], r[30], t);
GDA_SWAP(r[2], r[29], t);
GDA_SWAP(r[3], r[28], t);
GDA_SWAP(r[4], r[27], t);
GDA_SWAP(r[5], r[26], t);
GDA_SWAP(r[6], r[25], t);
GDA_SWAP(r[7], r[24], t);
GDA_SWAP(r[8], r[23], t);
GDA_SWAP(r[9], r[22], t);
GDA_SWAP(r[10], r[21], t);
GDA_SWAP(r[11], r[20], t);
GDA_SWAP(r[12], r[19], t);
GDA_SWAP(r[13], r[18], t);
GDA_SWAP(r[14], r[17], t);
GDA_SWAP(r[15], r[16], t);
memcpy(&r[0], &s[36], sizeof(double) * 4);
#else
hr->f[0]= GenUtils::Reverse(FileCode);
hr->f[6]= GenUtils::Reverse(FileLength);
hr->f[7]= Version;
hr->f[8]= fShape;
hr->b = FileBox;
memcpy(&s[36], &hr->b, sizeof(double)*4);
#endif
}
void ShapeFileHdr::Replace (const wxString& fname, const wxInt32& recs)
{
// may have problems when writing
HdrRecord buf;
MakeBuffer((char *) &buf);
// update *.shp file
FILE *shp = fopen(
GenUtils::swapExtension(fname, "shp"), "rb+");
fseek(shp, 0, SEEK_SET);
fwrite((char*)&buf, sizeof(char), GdaConst::ShpHeaderSize * 2, shp);
fclose(shp);
// update *.shx file
FILE *shx = fopen(
GenUtils::swapExtension(fname, "shx"), "rb+");
#ifdef WORDS_BIGENDIAN
buf.f[6] = GdaConst::ShpHeaderSize + 4 * recs;
#else
buf.f[6]= GenUtils::Reverse(GdaConst::ShpHeaderSize + 4 * recs);
#endif
fseek(shx, 0, SEEK_SET);
fwrite((char*)&buf, sizeof(char), GdaConst::ShpHeaderSize * 2, shx);
fclose(shx);
// update *.dbf file
FILE *dbf = fopen(
GenUtils::swapExtension(fname, "dbf"), "rb+");
wxInt32 nrec;
fseek(dbf, 4, SEEK_SET);
#ifdef WORDS_BIGENDIAN
nrec = GenUtils::Reverse(recs);
#else
nrec = recs;
#endif
fwrite(&nrec, sizeof(wxInt32), 1, dbf);
#ifdef WORDS_BIGENDIAN
nrec = GenUtils::Reverse(recs);
#endif
fclose(dbf);
}
ShapeFileHdr& operator<<(ShapeFileHdr& hd, const AbstractShape& s)
{
Box bo;
bo = hd.BoundingBox();
if (hd.Length() == GdaConst::ShpHeaderSize) {
hd.SetFileBox(s.ShapeBox());
} else {
bo += s.ShapeBox();
hd.SetFileBox(bo);
}
wxInt32 fl = hd.Length();
fl += 4 + s.ContentsLength();
hd.SetFileLength(fl);
return hd;
}
oShapeFile& operator<<(oShapeFile& s, const ShapeFileHdr& hd)
{
char buf[GdaConst::ShpHeaderSize*2];
hd.MakeBuffer(buf);
s.write(buf, 2*GdaConst::ShpHeaderSize);
return s;
}
|
.text
lui $2,0x0001
addi $1,$0,1
nop
nop
nop
sw $1,1($2)
sw $1,2($2)
et: beq $0,$0,et
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>readlinkat(fd, path, buf, length) -> str
Invokes the syscall readlinkat.
See 'man 2 readlinkat' for more information.
Arguments:
fd(int): fd
path(char*): path
buf(char*): buf
length(size_t): length
Returns:
ssize_t
</%docstring>
<%page args="fd=0, path=0, buf=0, length=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['path', 'buf']
can_pushstr_array = []
argument_names = ['fd', 'path', 'buf', 'length']
argument_values = [fd, path, buf, length]
# 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=%s' % (name, pwnlib.shellcraft.pretty(arg, False)))
# 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_readlinkat']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* readlinkat(${', '.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)}
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 <deque>
#include <string>
#include <mesos/type_utils.hpp>
#include <mesos/state/state.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/future.hpp>
#include <process/help.hpp>
#include <process/http.hpp>
#include <process/id.hpp>
#include <process/owned.hpp>
#include <process/process.hpp>
#include <process/metrics/gauge.hpp>
#include <process/metrics/metrics.hpp>
#include <process/metrics/timer.hpp>
#include <stout/lambda.hpp>
#include <stout/none.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/protobuf.hpp>
#include <stout/stopwatch.hpp>
#include "master/registrar.hpp"
#include "master/registry.hpp"
using mesos::state::State;
using mesos::state::Variable;
using process::dispatch;
using process::spawn;
using process::terminate;
using process::wait; // Necessary on some OS's to disambiguate.
using process::AUTHENTICATION;
using process::DESCRIPTION;
using process::Failure;
using process::Future;
using process::HELP;
using process::Owned;
using process::PID;
using process::Process;
using process::Promise;
using process::TLDR;
using process::http::OK;
using process::http::authentication::Principal;
using process::metrics::Gauge;
using process::metrics::Timer;
using std::deque;
using std::string;
namespace mesos {
namespace internal {
namespace master {
using process::http::Response;
using process::http::Request;
class RegistrarProcess : public Process<RegistrarProcess>
{
public:
using State = mesos::state::State; // `ProcessBase::State` conflicts here.
RegistrarProcess(
const Flags& _flags,
State* _state,
const Option<string>& _authenticationRealm)
: ProcessBase(process::ID::generate("registrar")),
metrics(*this),
state(_state),
updating(false),
flags(_flags),
authenticationRealm(_authenticationRealm) {}
virtual ~RegistrarProcess() {}
// Registrar implementation.
Future<Registry> recover(const MasterInfo& info);
Future<bool> apply(Owned<RegistryOperation> operation);
protected:
virtual void initialize()
{
if (authenticationRealm.isSome()) {
route(
"/registry",
authenticationRealm.get(),
registryHelp(),
&RegistrarProcess::getRegistry);
} else {
route(
"/registry",
registryHelp(),
lambda::bind(
&RegistrarProcess::getRegistry, this, lambda::_1, None()));
}
}
private:
// HTTP handlers.
// /registrar(N)/registry
Future<Response> getRegistry(
const Request& request,
const Option<Principal>&);
static string registryHelp();
// The 'Recover' operation adds the latest MasterInfo.
class Recover : public RegistryOperation
{
public:
explicit Recover(const MasterInfo& _info) : info(_info) {}
protected:
virtual Try<bool> perform(Registry* registry, hashset<SlaveID>* slaveIDs)
{
registry->mutable_master()->mutable_info()->CopyFrom(info);
return true; // Mutation.
}
private:
const MasterInfo info;
};
// Metrics.
struct Metrics
{
explicit Metrics(const RegistrarProcess& process)
: queued_operations(
"registrar/queued_operations",
defer(process, &RegistrarProcess::_queued_operations)),
registry_size_bytes(
"registrar/registry_size_bytes",
defer(process, &RegistrarProcess::_registry_size_bytes)),
state_fetch("registrar/state_fetch"),
state_store("registrar/state_store", Days(1))
{
process::metrics::add(queued_operations);
process::metrics::add(registry_size_bytes);
process::metrics::add(state_fetch);
process::metrics::add(state_store);
}
~Metrics()
{
process::metrics::remove(queued_operations);
process::metrics::remove(registry_size_bytes);
process::metrics::remove(state_fetch);
process::metrics::remove(state_store);
}
Gauge queued_operations;
Gauge registry_size_bytes;
Timer<Milliseconds> state_fetch;
Timer<Milliseconds> state_store;
} metrics;
// Gauge handlers.
double _queued_operations()
{
return operations.size();
}
Future<double> _registry_size_bytes()
{
if (registry.isSome()) {
return registry->ByteSize();
}
return Failure("Not recovered yet");
}
// Continuations.
void _recover(
const MasterInfo& info,
const Future<Variable>& recovery);
void __recover(const Future<bool>& recover);
Future<bool> _apply(Owned<RegistryOperation> operation);
// Helper for updating state (performing store).
void update();
void _update(
const Future<Option<Variable>>& store,
const Owned<Registry>& updatedRegistry,
deque<Owned<RegistryOperation>> operations);
// Fails all pending operations and transitions the Registrar
// into an error state in which all subsequent operations will fail.
// This ensures we don't attempt to re-acquire log leadership by
// performing more State storage operations.
void abort(const string& message);
// TODO(ipronin): We use the "untyped" `State` class here and perform
// the protobuf (de)serialization manually within the Registrar, because
// the use of `protobuf::State` incurs a dramatic peformance cost from
// protobuf copying. We should explore using `protobuf::State`, which will
// require move support and other copy elimination to maintain the
// performance of the current approach.
State* state;
// Per the TODO above, we store both serialized and deserialized versions
// of the `Registry` protobuf. If we're able to move to `protobuf::State`,
// we could just store a single `protobuf::state::Variable<Registry>`.
Option<Variable> variable;
Option<Registry> registry;
deque<Owned<RegistryOperation>> operations;
bool updating; // Used to signify fetching (recovering) or storing.
const Flags flags;
// Used to compose our operations with recovery.
Option<Owned<Promise<Registry>>> recovered;
// When an error is encountered from abort(), we'll fail all
// subsequent operations.
Option<Error> error;
// The authentication realm, if any, into which this process'
// endpoints will be installed.
Option<string> authenticationRealm;
};
// Helper for treating State operations that timeout as failures.
template <typename T>
Future<T> timeout(
const string& operation,
const Duration& duration,
Future<T> future)
{
future.discard();
return Failure(
"Failed to perform " + operation + " within " + stringify(duration));
}
// Helper for failing a deque of operations.
void fail(deque<Owned<RegistryOperation>>* operations, const string& message)
{
while (!operations->empty()) {
operations->front()->fail(message);
operations->pop_front();
}
}
Future<Response> RegistrarProcess::getRegistry(
const Request& request,
const Option<Principal>&)
{
JSON::Object result;
if (registry.isSome()) {
result = JSON::protobuf(registry.get());
}
return OK(result, request.url.query.get("jsonp"));
}
string RegistrarProcess::registryHelp()
{
return HELP(
TLDR(
"Returns the current contents of the Registry in JSON."),
DESCRIPTION(
"Example:",
"",
"```",
"{",
" \"master\":",
" {",
" \"info\":",
" {",
" \"hostname\": \"localhost\",",
" \"id\": \"20140325-235542-1740121354-5050-33357\",",
" \"ip\": 2130706433,",
" \"pid\": \"master@127.0.0.1:5050\",",
" \"port\": 5050",
" }",
" },",
"",
" \"slaves\":",
" {",
" \"slaves\":",
" [",
" {",
" \"info\":",
" {",
" \"checkpoint\": true,",
" \"hostname\": \"localhost\",",
" \"id\":",
" {",
" \"value\": \"20140325-234618-1740121354-5050-29065-0\"",
" },",
" \"port\": 5051,",
" \"resources\":",
" [",
" {",
" \"name\": \"cpus\",",
" \"role\": \"*\",",
" \"scalar\": { \"value\": 24 },",
" \"type\": \"SCALAR\"",
" }",
" ],",
" }",
" }",
" ]",
" }",
"}",
"```"),
AUTHENTICATION(true));
}
Future<Registry> RegistrarProcess::recover(const MasterInfo& info)
{
if (recovered.isNone()) {
VLOG(1) << "Recovering registrar";
metrics.state_fetch.start();
state->fetch("registry")
.after(flags.registry_fetch_timeout,
lambda::bind(
&timeout<Variable>,
"fetch",
flags.registry_fetch_timeout,
lambda::_1))
.onAny(defer(self(), &Self::_recover, info, lambda::_1));
updating = true;
recovered = Owned<Promise<Registry>>(new Promise<Registry>());
}
return recovered.get()->future();
}
void RegistrarProcess::_recover(
const MasterInfo& info,
const Future<Variable>& recovery)
{
updating = false;
CHECK(!recovery.isPending());
if (!recovery.isReady()) {
recovered.get()->fail("Failed to recover registrar: " +
(recovery.isFailed() ? recovery.failure() : "discarded"));
return;
}
// Deserialize the registry.
Try<Registry> deserialized =
::protobuf::deserialize<Registry>(recovery->value());
if (deserialized.isError()) {
recovered.get()->fail("Failed to recover registrar: " +
deserialized.error());
return;
}
Duration elapsed = metrics.state_fetch.stop();
LOG(INFO) << "Successfully fetched the registry"
<< " (" << Bytes(deserialized->ByteSize()) << ")"
<< " in " << elapsed;
// Save the registry.
variable = recovery.get();
// Workaround for immovable protobuf messages.
registry = Option<Registry>(Registry());
registry->Swap(&deserialized.get());
// Perform the Recover operation to add the new MasterInfo.
Owned<RegistryOperation> operation(new Recover(info));
operations.push_back(operation);
operation->future()
.onAny(defer(self(), &Self::__recover, lambda::_1));
update();
}
void RegistrarProcess::__recover(const Future<bool>& recover)
{
CHECK(!recover.isPending());
if (!recover.isReady()) {
recovered.get()->fail("Failed to recover registrar: "
"Failed to persist MasterInfo: " +
(recover.isFailed() ? recover.failure() : "discarded"));
} else if (!recover.get()) {
recovered.get()->fail("Failed to recover registrar: "
"Failed to persist MasterInfo: version mismatch");
} else {
LOG(INFO) << "Successfully recovered registrar";
// At this point _update() has updated 'variable' to contain
// the Registry with the latest MasterInfo.
// Set the promise and un-gate any pending operations.
CHECK_SOME(variable);
CHECK_SOME(registry);
recovered.get()->set(registry.get());
}
}
Future<bool> RegistrarProcess::apply(Owned<RegistryOperation> operation)
{
if (recovered.isNone()) {
return Failure("Attempted to apply the operation before recovering");
}
return recovered.get()->future()
.then(defer(self(), &Self::_apply, operation));
}
Future<bool> RegistrarProcess::_apply(Owned<RegistryOperation> operation)
{
if (error.isSome()) {
return Failure(error.get());
}
CHECK_SOME(variable);
operations.push_back(operation);
Future<bool> future = operation->future();
if (!updating) {
update();
}
return future;
}
void RegistrarProcess::update()
{
if (operations.empty()) {
return; // No-op.
}
CHECK(!updating);
CHECK_NONE(error);
CHECK_SOME(variable);
// Time how long it takes to apply the operations.
Stopwatch stopwatch;
stopwatch.start();
updating = true;
// Create a snapshot of the current registry. We use an `Owned` here
// to avoid copying, since protobuf doesn't suppport move construction.
auto updatedRegistry = Owned<Registry>(new Registry(registry.get()));
// Create the 'slaveIDs' accumulator.
hashset<SlaveID> slaveIDs;
foreach (const Registry::Slave& slave, updatedRegistry->slaves().slaves()) {
slaveIDs.insert(slave.info().id());
}
foreach (Owned<RegistryOperation>& operation, operations) {
// No need to process the result of the operation.
(*operation)(updatedRegistry.get(), &slaveIDs);
}
LOG(INFO) << "Applied " << operations.size() << " operations in "
<< stopwatch.elapsed() << "; attempting to update the registry";
// Perform the store, and time the operation.
metrics.state_store.start();
// Serialize updated registry.
Try<string> serialized = ::protobuf::serialize(*updatedRegistry);
if (serialized.isError()) {
string message = "Failed to update registry: " + serialized.error();
fail(&operations, message);
abort(message);
return;
}
state->store(variable->mutate(serialized.get()))
.after(flags.registry_store_timeout,
lambda::bind(
&timeout<Option<Variable>>,
"store",
flags.registry_store_timeout,
lambda::_1))
.onAny(defer(
self(), &Self::_update, lambda::_1, updatedRegistry, operations));
// Clear the operations, _update will transition the Promises!
operations.clear();
}
void RegistrarProcess::_update(
const Future<Option<Variable>>& store,
const Owned<Registry>& updatedRegistry,
deque<Owned<RegistryOperation>> applied)
{
updating = false;
// Abort if the storage operation did not succeed.
if (!store.isReady() || store.get().isNone()) {
string message = "Failed to update registry: ";
if (store.isFailed()) {
message += store.failure();
} else if (store.isDiscarded()) {
message += "discarded";
} else {
message += "version mismatch";
}
fail(&applied, message);
abort(message);
return;
}
Duration elapsed = metrics.state_store.stop();
LOG(INFO) << "Successfully updated the registry in " << elapsed;
variable = store.get().get();
registry->Swap(updatedRegistry.get());
// Remove the operations.
while (!applied.empty()) {
Owned<RegistryOperation> operation = applied.front();
applied.pop_front();
operation->set();
}
if (!operations.empty()) {
update();
}
}
void RegistrarProcess::abort(const string& message)
{
error = Error(message);
LOG(ERROR) << "Registrar aborting: " << message;
fail(&operations, message);
}
Registrar::Registrar(
const Flags& flags,
State* state,
const Option<string>& authenticationRealm)
{
process = new RegistrarProcess(flags, state, authenticationRealm);
spawn(process);
}
Registrar::~Registrar()
{
terminate(process);
wait(process);
delete process;
}
Future<Registry> Registrar::recover(const MasterInfo& info)
{
return dispatch(process, &RegistrarProcess::recover, info);
}
Future<bool> Registrar::apply(Owned<RegistryOperation> operation)
{
return dispatch(process, &RegistrarProcess::apply, operation);
}
PID<RegistrarProcess> Registrar::pid() const
{
return process->self();
}
} // namespace master {
} // namespace internal {
} // namespace mesos {
|
;/** @file
;
; IDT vector entry.
;
; Copyright (c) 2007 - 2016, Intel Corporation. All rights reserved.<BR>
; SPDX-License-Identifier: BSD-2-Clause-Patent
;
;**/
SECTION .text
;
;------------------------------------------------------------------------------
; Generic IDT Vector Handlers for the Host.
;
;------------------------------------------------------------------------------
ALIGN 8
global ASM_PFX(AsmGetVectorTemplatInfo)
global ASM_PFX(AsmVectorFixup)
@VectorTemplateBase:
push eax
db 0x6a ; push #VectorNumber
@VectorNum:
db 0
mov eax, CommonInterruptEntry
jmp eax
@VectorTemplateEnd:
global ASM_PFX(AsmGetVectorTemplatInfo)
ASM_PFX(AsmGetVectorTemplatInfo):
mov ecx, [esp + 4]
mov dword [ecx], @VectorTemplateBase
mov eax, (@VectorTemplateEnd - @VectorTemplateBase)
ret
global ASM_PFX(AsmVectorFixup)
ASM_PFX(AsmVectorFixup):
mov eax, dword [esp + 8]
mov ecx, [esp + 4]
mov [ecx + (@VectorNum - @VectorTemplateBase)], al
ret
;---------------------------------------;
; CommonInterruptEntry ;
;---------------------------------------;
; The follow algorithm is used for the common interrupt routine.
;
; +---------------------+ <-- 16-byte aligned ensured by processor
; + Old SS +
; +---------------------+
; + Old RSP +
; +---------------------+
; + RFlags +
; +---------------------+
; + CS +
; +---------------------+
; + RIP +
; +---------------------+
; + Error Code +
; +---------------------+
; + Vector Number +
; +---------------------+
CommonInterruptEntry:
cli
jmp $
|
; SMSQ Hardware table handling V2.10 1999 Tony Tebby
section hwt
xdef hwt_create ; create empty hardware table
xdef hwt_iserve ; install interrupt servers in hwt
xref gu_achpp
xref gu_rchp
include 'dev8_keys_hwt'
include 'dev8_smsq_smsq_base_keys'
include 'dev8_mac_assert'
;+++
; Hardware table setup - create empty hardware table
;
; d0 cr number of entries in empty table
;
; status return standard
;---
hwt_create
hwtc.reg reg d1/a0/a5
movem.l hwtc.reg,-(sp)
addq.w #hwt_table/hwt.table,d0
assert hwt.table,$10
lsl.l #4,d0
move.l d0,d1
jsr gu_achpp
bne.s hwtc_exit
bsr.s hwtc_settab
add.l a0,d1
move.l d1,(a0) ; set top
add.w #hwt_table,a0
move.l a0,hwt_ptr-hwt_table(a0) ; set pointer
hwtc_exit
movem.l (sp)+,hwtc.reg
rts
hwtc_settab
lea sms.hwtab,a5 ; set table pointer
move.l a0,d0
swap d0
bsr.s hwtc_setw
swap d0
hwtc_setw
jmp sms.wbase
;+++
; Hardware table setup - install interrupt servers
;
; d0 r offset of first entry in hardware table for this driver
; d1 c p byte, logicl port number
; a3 c p linkage block
; a4 c p base address of hardware
; a5 c u pointer to vector table in driver definition table
; status return arbirary
;---
hwt_iserve
hwti.reg reg d0/d2/d3/d4/a0/a1/a2
clr.l d0 ; return nothing
movem.l hwti.reg,-(sp)
move.l a5,a1
move.w (a5)+,d0 ; get pointer to table and move on
beq.s hwti_exit ; no table
add.w d0,a1
move.l sms.hwtab,a0 ; hardware table
move.l hwt_ptr(a0),a2 ; table pointer
move.l a2,d0
sub.l a0,d0
move.l d0,(sp) ; set offset
hwti_loop
move.w (a1)+,d4 ; next vector to set
beq.s hwti_exit ; no (more) vectors
cmp.l hwt_top(a0),a2 ; off top yet?
blo.s hwti_set ; ... no
move.l a2,d3
sub.l a0,d3 ; old size
moveq #hwt.table*7,d2 ; make room for 7 more entries
add.l d3,d2 ; new size
move.l a0,a4 ; keep old base
move.l d2,d0
jsr gu_achpp ; allocate
bne.s hwti_exit ; should not happen
move.l d3,d0
move.l a4,a2
hwti_copy
move.l (a2)+,(a0)+
subq.w #4,d0
bgt.s hwti_copy
move.l a0,a2 ; new pointer
sub.l d3,a0 ; new base
add.l a0,d2 ; new top
move.l d2,hwt_top(a0)
move.l a2,hwt_ptr(a0)
bsr.s hwtc_settab ; save table
exg a0,a4
jsr gu_rchp ; return old bit
exg a0,a4
hwti_set
move.l a3,(a2)+ ; set linkage
pea -2(a1,d4.w)
move.l (sp)+,(a2)+ ; set server
clr.l (a2)+ ; spare
move.w (a1)+,(a2)+ ; interrupt level and priority
move.w (a1)+,d0 ; type / spare
move.b d1,d0
move.w d0,(a2)+ ; type / port number
move.l a2,hwt_ptr(a0)
bra.s hwti_loop
hwti_exit
movem.l (sp)+,hwti.reg
rts
end
|
! crt1.s for sparc & sparcv9 (SunOS 5)
! Copyright (C) 1992 Free Software Foundation, Inc.
! Written By David Vinayak Henkel-Wallace, June 1992
!
! This file is free software; you can redistribute it and/or modify it
! under the terms of the GNU General Public License as published by the
! Free Software Foundation; either version 2, or (at your option) any
! later version.
!
! In addition to the permissions in the GNU General Public License, the
! Free Software Foundation gives you unlimited permission to link the
! compiled version of this file with other programs, and to distribute
! those programs without any restriction coming from the use of this
! file. (The General Public License restrictions do apply in other
! respects; for example, they cover modification of the file, and
! distribution when not linked into another program.)
!
! This file 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
! General Public License for more details.
!
! You should have received a copy of the GNU General Public License
! along with this program; see the file COPYING. If not, write to
! the Free Software Foundation, 51 Franklin Street, Fifth Floor,
! Boston, MA 02110-1301, USA.
!
! As a special exception, if you link this library with files
! compiled with GCC to produce an executable, this does not cause
! the resulting executable to be covered by the GNU General Public License.
! This exception does not however invalidate any other reasons why
! the executable file might be covered by the GNU General Public License.
!
! This file takes control of the process from the kernel, as specified
! in section 3 of the SVr4 ABI.
! This file is the first thing linked into any executable.
#ifdef __sparcv9
#define CPTRSIZE 8
#define CPTRSHIFT 3
#define STACK_BIAS 2047
#define ldn ldx
#define stn stx
#define setn(s, scratch, dst) setx s, scratch, dst
#else
#define CPTRSIZE 4
#define CPTRSHIFT 2
#define STACK_BIAS 0
#define ldn ld
#define stn st
#define setn(s, scratch, dst) set s, dst
#endif
.section ".text"
.proc 022
.global _start
_start:
mov 0, %fp ! Mark bottom frame pointer
ldn [%sp + (16 * CPTRSIZE) + STACK_BIAS], %l0 ! argc
add %sp, (17 * CPTRSIZE) + STACK_BIAS, %l1 ! argv
! Leave some room for a call. Sun leaves 32 octets (to sit on
! a cache line?) so we do too.
#ifdef __sparcv9
sub %sp, 48, %sp
#else
sub %sp, 32, %sp
#endif
! %g1 may contain a function to be registered w/atexit
orcc %g0, %g1, %g0
#ifdef __sparcv9
be %xcc, .nope
#else
be .nope
#endif
mov %g1, %o0
call atexit
nop
.nope:
! Now make sure constructors and destructors are handled.
setn(_fini, %o1, %o0)
call atexit, 1
nop
call _init, 0
nop
! We ignore the auxiliary vector; there is no defined way to
! access those data anyway. Instead, go straight to main:
mov %l0, %o0 ! argc
mov %l1, %o1 ! argv
#ifdef GCRT1
setn(___Argv, %o4, %o3)
stn %o1, [%o3] ! *___Argv
#endif
! Skip argc words past argv, to env:
sll %l0, CPTRSHIFT, %o2
add %o2, CPTRSIZE, %o2
add %l1, %o2, %o2 ! env
setn(_environ, %o4, %o3)
stn %o2, [%o3] ! *_environ
call main, 4
nop
call exit, 0
nop
call _exit, 0
nop
! We should never get here.
.type _start,#function
.size _start,.-_start
|
//JUC r6 start_menu ///calls start_game.
start_Game:
JAL r6 initlevel
JAL r6 INIT_PACMAN
JAL r6 INIT_GreenGhost
mainGameLoop:
JAL r6 PACMAN_UPDATE_STATE
JAL r6 GreenGhost_UPDATE_STATE
JAL r6 GreenGhost_Draw_GLYPH
JAL r6 PACMAN_DRAW_GLYPH
JUC r6 mainGameLoop
//:::::::::::::BEGIN PACMAN STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::BEGIN PACMAN STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::BEGIN PACMAN STATE MACHINE::::::::::::::::::::::::::
//register usage: r14 used to save return address of this function.
//registers r0, r1 destroyed as general purpose, r4 used to store state address
// STATES:
// For the '0' states, the state feild will evaluate to 0 if masked with 0x0F (15).
// the ZERO ('0') states are where pacman is centered on a tile.
// In the 0 state pacman will continue MOVIng forward unless the player inputs a direction
// if pacman reaches any state0 and a ghost position is this tile, nextstate is dead1.
//
// 0x10: pacmanUP0 (16) --centered on tile, facing up. nextstate will be up1, unless player input
// 0x20: pacmanDOWN0 (32) --centered on tile, facing down. nextstate is player input direction, else down1
// 0x30: pacmanLEFT0 (48) --centered on tile, facing left. nextstate is player input direction, else left1
// 0x40: pacmanRIGHT0 (64) --centered on tile, facing right. nextstate is player input direction, else right1
// The rest of the states are defined with the following pattern
// the number in parenthesis is the decimal value.
//
// 0x11 pacmanUP1 (17) //nextstate up2, if player inputs down then nextstate down0
// 0x12 pacmanUP2 (18) //nextstate up3, if player pushes down then nextstate down3
// 0x13 pacmanUP3 (19) //nextstate up0, if player pushes down then nextstate down2
//
// 0x21 pacmanDOWN1 (33) //nextstate down2, if player inputs up then nextstate up0
// 0x22 pacmanDOWN2 (34) //nextstate down3, if player inputs up then nextstate up3
// 0x23 pacmanDOWN3 (35) //nextstate down0, if player inputs up then nextstate up2
//
// 0x31 pacmanLEFT1 (49) //nextstate left2, if player inputs right then nextstate right0
// 0x32 pacmanLEFT2 (50) //nextstate left3, if player inputs right then nextstate right3
// 0x33 pacmanLEFT3 (51) //nextstate left0, if player inputs right then nextstate right2
//
// 0x41 pacmanRIGHT1 (65) //nextstate right2, if player inputs right then nextstate left0
// 0x42 pacmanRIGHT2 (66) //nextstate right3, if player inputs right then nextstate left3
// 0x43 pacmanRIGHT3 (67) //nextstate right0, if player inputs right then nextstate left2
//
// 0x01 pacmanDEAD1 (1) //nextstate dead2
// 0x02 pacmanDEAD2 (2) //nextstate dead3
// 0x03 pacmanDEAD3 (3) //nextstate dead4
// 0x04 pacmanDEAD4 (4) //nextstate pacleft0, reset position, do magic to clear his board tile.
/////THIS FUNCTION UPDATES PACMAN STATEMACHINE BY ONE STEP.
//
// The first thing it does is check the timer. If the timer is not active, it immediately leaves.
// Otherwise:
// check what state pacman is in
// check controller input accordingly,
// update state & position variables
// reset timer
//
PACMAN_UPDATE_STATE:
MOV r15 r14 //store old return adress
LUI 255 r0 //check timer by making address
ORI 242 r0
LOAD r0 r0 //then loading its value and cmp to 1
CMPI 1 r0
JNE r6 endPacmanStateUpdate //if timer was not active, do not update state.
// //else, continue on to update pacman state:
//
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::GET CURRENT STATE ADDRESS::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CURRENT STATE state address 13201, store address in r4
LUI 51 r4
ORI 145 r4 //store address in r4
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::ZERO STATES::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// If in a ZERO state:
// check if on a ghost, if so die.
// otherwise, check player input in all directions and start MOVIng.
// if player has made no input selections, keep going in current direction.
// CHECK IF PACMAN HIT GHOST: (Any ghost position is on pacmans square)
// if hit, set nextstate to dead,
// jump to reset timer to progress to next state.
//
// if position = AnyGhostPosition
// nextstate = pacmanDEAD1
// JUC endPacmanState_SetTimer
//Check if in a '0' state:
LOAD r1 r4 //read current state, address in r4
MOV r1 r0 //copy STATE into temp register.
ANDI 15 r0 //mask it by ANDing it with 0xF (15)
CMPI 0 r0 //if masked value is not zero, check if it is in another state
JNE r6 UpStates //by branching to the next comparison, to check if it is an upstate
//check if up/down controls are pushed:
state0_updown:
JAL r6 CheckUP //CheckUP is a function that checks if controller up button is pushed
MOV r0 r1 //store the result of checkup in r1
JAL r6 CheckDOWN //CheckDOWN is a function that checks if controller down button is pushed
CMP r0 r1 //compare the results of both checkup and checkdown, by comparing r1 and r0
BEQ state0_leftright //if controller UP/DOWN are pushed together, input could be left or right
CMPI 1 r0 //Else, check if down was pushed. r0 will be 1 if down was pushed
BEQ pacmanTryMoveDOWN
BUC pacmanTryMoveUP
//check if left/right controls are pushed:
state0_leftright:
JAL r6 CheckRIGHT //CheckLEFT is a function that checks if controller up button is pushed
MOV r0 r1 //store the result of checkLEFT in r1
JAL r6 CheckLEFT //CheckRIGHT is a function that checks if controller right button is pushed
CMP r0 r1 //compare the results of both checkup and checkdown, by comparing r1 and r0
BEQ state0_NoInput //if controller LEFT/RIGHT are pushed together and up/down was not processed exclusively, entire dpad pushed
CMPI 1 r0 //Else, check if RIGHT was pushed. r0 will be 1 if right was pushed
BEQ pacmanTryMoveLEFT
BUC pacmanTryMoveRIGHT
state0_NoInput:
LOAD r1 r4 //load state
CMPI 16 r1 //check if in up0 state.
BEQ pacmanMoveUP //if not in up0 state, check if in down0 state
CMPI 32 r1 //check if in down0 state.
BEQ pacmanMoveDOWN //if not in down0 state, check if in left0 state, else:
CMPI 48 r1 //check if in left0 state.
BEQ pacmanMoveLEFT
CMPI 64 r1 //check if in right0 state.
BEQ pacmanMoveRIGHT //if not in right0 state, do not update state.
JUC r6 endPacmanState_SetTimer
pacmanMoveUP:
JAL r6 pacman_isWallUP
CMPI 1 r0 //check if wall is above
JEQ r6 endPacmanState_SetTimer //if there is wall, do not update state, reset timer. else:
MOV r4 r0 // move state address to r0 to prepare for setStateUP call
JAL r6 setStateUP1 // set pacman state to up1
JUC r6 endPacmanState_SetTimer
pacmanMoveDOWN:
JAL r6 pacman_isWallDOWN
CMPI 1 r0 //check if wall is below
JEQ r6 endPacmanState_SetTimer //if there is wall, do not update state, reset timer. else:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN1 // set pacman state
JUC r6 endPacmanState_SetTimer
pacmanMoveLEFT:
JAL r6 pacman_isWallLEFT
CMPI 1 r0 //check if wall is left
JEQ r6 endPacmanState_SetTimer //if there is wall, do not update state, reset timer. else:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT1 // set pacman state to left1
JUC r6 endPacmanState_SetTimer
pacmanMoveRIGHT:
JAL r6 pacman_isWallRIGHT
CMPI 1 r0 //check if wall is right
JEQ r6 endPacmanState_SetTimer //if there is wall, do not update state, reset timer. else:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT1 // set pacman state
JUC r6 endPacmanState_SetTimer
pacmanTryMoveUP:
JAL r6 pacman_isWallUP
CMPI 1 r0 //check if wall is above
JEQ r6 state0_NoInput
MOV r4 r0 // move state address to r0 to prepare for setStateUP call
JAL r6 setStateUP1 // set pacman state to up1
JUC r6 endPacmanState_SetTimer
pacmanTryMoveDOWN:
JAL r6 pacman_isWallDOWN
CMPI 1 r0 //check if wall is below
JEQ r6 state0_NoInput
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN1 // set pacman state
JUC r6 endPacmanState_SetTimer
pacmanTryMoveLEFT:
JAL r6 pacman_isWallLEFT
CMPI 1 r0 //check if wall is left
JEQ r6 state0_NoInput
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT1 // set pacman state to left1
JUC r6 endPacmanState_SetTimer
pacmanTryMoveRIGHT:
JAL r6 pacman_isWallRIGHT
CMPI 1 r0 //check if wall is right
JEQ r6 state0_NoInput
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT1 // set pacman state
JUC r6 endPacmanState_SetTimer
////:::::::::::::::::::::::End Zero States::::::::::::::::::::::::::
UpStates:
//if we are traveling up and not centered on a tile, we will
//continue to travel up, thus only the down button must be checked.
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanUP1:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanUP1:
LOAD r1 r4 //read current state, address in r4
CMPI 17 r1 //if state is pacmanUP1
BNE pacmanUP2
JAL r6 CheckDOWN //check if down control is pushed
CMPI 1 r0
BNE UP1Cont
UP1Rev:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN0 // set pacman state
JUC r6 endPacmanState_SetTimer
UP1Cont:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP2 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanUP2:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanUP2:
LOAD r1 r4 //read current state, address in r4
CMPI 18 r1 //if state is pacmanUP2
BNE pacmanUP3
JAL r6 CheckDOWN //check if down control is pushed
CMPI 1 r0
BNE UP2Cont
//if button isnt pushed, skip to up2cont otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN3 // set pacman state
JUC r6 endPacmanState_SetTimer
UP2Cont:
LUI 51 r0 //update pacman position by making position address in r0
ORI 144 r0
LOAD r1 r0 //then getting it in r1
ADDI 53 r1 //adding one
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP3 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanUP3:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanUP3:
LOAD r1 r4 //read current state, address in r4
CMPI 19 r1 //if state is pacmanUP3
BNE pacmanDOWN1
//set spot in FBCPY to a blank glyph.
LUI 51 r1 //make address 13200 where pacman location is stored
ORI 144 r1
LOAD r1 r1
JAL r6 FBpos_2_CPpos
MOVI 0 r0
STOR r0 r1
JAL r6 CheckDOWN //check if down control is pushed
CMPI 1 r0
BNE UP3Cont
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN2 // set pacman state
JUC r6 endPacmanState_SetTimer
UP3Cont:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP0 // set pacman state
JUC r6 endPacmanState_SetTimer
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
DownStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanDOWN1:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanDOWN1:
LOAD r1 r4 //read current state, address in r4
CMPI 33 r1 //if state is pacmanDOWN1
BNE pacmanDOWN2
JAL r6 CheckUP //check if control is pushed
CMPI 1 r0
BNE D1C
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP0 // set pacman state
JUC r6 endPacmanState_SetTimer
D1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN2 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanDOWN2:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanDOWN2:
LOAD r1 r4 //read current state, address in r4
CMPI 34 r1 //if state is pacmanDOWN2
BNE pacmanDOWN3
JAL r6 CheckUP //check if control is pushed
CMPI 1 r0
BNE D2C
//if button isnt pushed, skip down 9 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP3 // set pacman state //and storing back to position address in r0
JUC r6 endPacmanState_SetTimer
D2C:
LUI 51 r0 //update pacman position by making position address in r0
ORI 144 r0
LOAD r1 r0 //then getting it in r1
ADDI -53 r1 //adding one
STOR r1 r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN3 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanDOWN3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanDOWN3:
LOAD r1 r4 //read current state, address in r4
CMPI 35 r1 //check state
BNE pacmanLEFT1 //
//set spot in FBCPY to a blank glyph.
LUI 51 r1 //make address 13200 where pacman location is stored
ORI 144 r1
LOAD r1 r1
JAL r6 FBpos_2_CPpos
MOVI 0 r0
STOR r0 r1
JAL r6 CheckUP //check if down control is pushed
CMPI 1 r0
BNE D3C
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP2 // set pacman state
JUC r6 endPacmanState_SetTimer
D3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN0 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
LeftStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanLEFT1:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanLEFT1:
LOAD r1 r4 //read current state, address in r4
CMPI 49 r1 //check state
BNE pacmanLEFT2
JAL r6 CheckRIGHT //check if control is pushed
CMPI 1 r0
BNE L1C //if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT0 // set pacman state
JUC r6 endPacmanState_SetTimer
L1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT2 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanLEFT2:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanLEFT2:
LOAD r1 r4 //read current state, address in r4
CMPI 50 r1 //check state
BNE pacmanLEFT3
JAL r6 CheckRIGHT //check if control is pushed
CMPI 1 r0
BNE L2C
//if button isnt pushed, skip down 9 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT3 // set pacman state
JUC r6 endPacmanState_SetTimer
L2C:
LUI 51 r0 //update pacman position by making position address in r0
ORI 144 r0
LOAD r1 r0 //then getting it in r1
ADDI 1 r1 //adding one
JAL r6 SetPosition_WarpLeftSide //setting it to either its position or the 'warp' position.
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT3 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanLEFT3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanLEFT3:
LOAD r1 r4 //read current state, address in r4
CMPI 51 r1 //check state
BNE pacmanRIGHT1 //
//set spot in FBCPY to a blank glyph.
LUI 51 r1 //make address 13200 where pacman location is stored
ORI 144 r1
LOAD r1 r1
JAL r6 FBpos_2_CPpos
MOVI 0 r0
STOR r0 r1
JAL r6 CheckRIGHT //check if down control is pushed
CMPI 1 r0
BNE L3C
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT2 // set pacman state
JUC r6 endPacmanState_SetTimer
L3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT0 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
RightStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanRIGHT1:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanRIGHT1:
LOAD r1 r4 //read current state, address in r4
CMPI 65 r1 //check state
BNE pacmanRIGHT2
JAL r6 CheckLEFT //check if control is pushed
CMPI 1 r0
BNE R1C //if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT0 // set pacman state
JUC r6 endPacmanState_SetTimer
R1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT2 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanRIGHT2::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanRIGHT2:
LOAD r1 r4 //read current state, address in r4
CMPI 66 r1 //check state
BNE pacmanRIGHT3
JAL r6 CheckLEFT //check if control is pushed
CMPI 1 r0
BNE R2C //if button isnt pushed, skip down 9 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT3 // set pacman state
JUC r6 endPacmanState_SetTimer
R2C:
LUI 51 r0 //update pacman position by making position address in r0
ORI 144 r0
LOAD r1 r0 //then getting it in r1
ADDI -1 r1 //adding one
JAL r6 SetPosition_WarpRightSide //set position to warped side or current position.
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT3 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::pacmanRIGHT3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
pacmanRIGHT3:
LOAD r1 r4 //read current state, address in r4
CMPI 67 r1 //check state
BNE pacmanDEAD1 //
//set spot in FBCPY to blank the glyph.
LUI 51 r1 //make address 13200 where pacman location is stored
ORI 144 r1
LOAD r1 r1
JAL r6 FBpos_2_CPpos
MOVI 0 r0
STOR r0 r1
JAL r6 CheckLEFT //check if LEFT control is pushed
CMPI 1 r0
BNE R3C
//if button isnt pushed, skip down 4 lines, otherwise do the following:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT2 // set pacman state
JUC r6 endPacmanState_SetTimer
R3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT0 // set pacman state
JUC r6 endPacmanState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
DeadStates:
pacmanDEAD1:
LOAD r1 r4 //read current state, address in r4
CMPI 1 r1 //if state is pacmanDEAD1
BNE pacmanDEAD2 //
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDEAD2 // set pacman state
JUC r6 endPacmanState_SetTimer
pacmanDEAD2:
LOAD r1 r4 //read current state, address in r4
CMPI 1 r1 //if state is pacmanDEAD1
BNE pacmanDEAD3 //
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDEAD3 // set pacman state
JUC r6 endPacmanState_SetTimer
pacmanDEAD3:
LOAD r1 r4 //read current state, address in r4
CMPI 1 r1 //if state is pacmanDEAD1
BNE pacmanDEAD4 //
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDEAD4 // set pacman state
JUC r6 endPacmanState_SetTimer
pacmanDEAD4:
MOV r4 r0 // //default case, move state address to r0 to prepare for setState call
JAL r6 setStateLEFT0 // set pacman state
JUC r6 endPacmanState_SetTimer
LUI 51 r0 //update pacman position by making position address in r0
ORI 144 r0
LOAD r1 r0 //then getting it in r1
ADDI 1 r1 //adding one
STOR r1 r0 //and storing back to position address in r0
endPacmanState_SetTimer:
LUI 255 r0 //make timer reset address
ORI 243 r0
MOVI 55 r1 //set 512+256 miliseconds on timer //TIMER SET
STOR r1 r0
endPacmanStateUpdate:
MOV r14 r15 //restore old return adress
RETX //return
PACMAN_DRAW_GLYPH:
//pacman's draw glyph
//
// if opentimer == 1
// load open timer
// open timer in 65510
//make of timer address in r1
LUI 255 r1
ORI 230 r1
LOAD r1 r1 //store result back in r1
//r2 has the mouth condition address
LUI 51 r2
ORI 146 r2
LOAD r4 r2
//check to see if timer is 1
CMPI 1 r1
//check condition code
BNE AFTER_MOUTH_TOGGLE
//if timer is 1, invert the mouth condition
//get the value of the mouth condition
XORI 1 r4 //MOUTH POSITION IN r4
//store back in memory
STOR r4 r2
//after toggling, reset timer to toggle again next time it activates: //added mouth toggle timer reset~!
LUI 255 r1
ORI 231 r1
LUI 1 r2
STOR r2 r1 //store 250 ms on timer. //TIMER SET MOUTH
AFTER_MOUTH_TOGGLE:
//MOUTH POSITION IN r4 //cleaned up register usage a bit
//MAKE PACMAN LOCATION ADDRESS IN r2
LUI 51 r2
ORI 144 r2
//MAKE PACMAN STATE ADDRESS IN r3
LUI 51 r3
ORI 145 r3
//load location of pacman INTO r0
LOAD r0 r2
//CHECK IF STATE UP0
drawUP0:
load r5 r3
CMPI 16 r5
BNE drawUP1 //else check if in state UP1
//check the condition of the mouth
//if open
CMPI 1 R4
BNE CLOSED_STATE_UP0
MOV r0 r1
LUI 1 r0 //load PACMAN_OPEN_UP_0
ORI 8 r0
STOR r0 r1
ADDI -53 r1 //get location below pacman
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
CLOSED_STATE_UP0:
MOV r0 r1
LUI 0 r0 //load PACMAN_CLOSED_UP_0
ORI 212 r0
STOR r0 r1
ADDI -53 r1 //get location below pacman
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//CHECK IF STATE UP1
drawUP1:
LOAD R5 R3
CMPI 17 r5
BNE drawUP2 //else check if in state UP2
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_UP1
//GET PACMAN_OPEN_6...GLYPH NUM 270
MOV r0 r1
MOVI 255 r0
ADDI 15 R0 //R1 SHOULD BE 270 NOW
STOR R0 R1 //LOAD GLYPH INTO POSITION
ADDI 53 R1 // GET POSITION ABOVE PACMAN
//NOW NEED TO LOAD PACMAN_OPEN_UP5
//IT IS GLPYH NUM 269
MOVI 255 R0
ADDI 14 R0
STOR r0 r1 //STORE POSITION ABOVE PACMAN
RETX
CLOSED_STATE_UP1:
//LOAD PACMAN_CLOSED_UP6
//IT'S GLYPH 218
MOVI 218 R1
STOR R1 R0 //LOAD INTO POSITION
ADDI 53 R0 // GET POSITION ABOVE PACMAN //fixed this, was negative, needed positive
//NOW NEED TO LOAD PMANCLOSED_UP_5
//IT'S GLYPH 217
MOVI 217 R1
STOR R1 R0 //LOAD INTO POSITION
RETX
//CHECK IF STATE UP2
drawUP2:
LOAD R5 R3
CMPI 18 r5
BNE drawUP3 //else check if in state UP3
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_UP2
//GET PMANOPEN_UP_4
//THIS IS GLYPH 268
MOVI 255 r1
ADDI 13 R1 //R1 SHOULD BE 268 NOW
STOR R1 R0 //LOAD INTO POSITION
ADDI 53 R0 // GET POSITION ABOVE PACMAN
//NOW NEED TO LOAD PMANOPEN_Up_3
//ITS IN LOCATION 267
MOVI 255 R1
ADDI 12 R1
STOR r1 r0 //STORE POSITION ABOVE PACMAN
RETX
CLOSED_STATE_UP2:
//LOAD PMANCLOSED_Up_4 //are these right?
//IT'S GLYPH 216
MOVI 216 R1
STOR R1 R0 //LOAD INTO POSITION
ADDI 53 R0 // GET POSITION ABOVE PACMAN
//NOW NEED TO LOAD PMANCLOSED_Up_3
//IT'S GLYPH 215
MOVI 215 R1 ///wait what?
STOR R1 R0 //LOAD INTO POSITION
RETX
//CHECK IF STATE UP3
drawUP3:
LOAD R5 R3
CMPI 19 r5
BNE drawDOWN0 //else check if in state drawDOWN0
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_UP3
//GET PMANOPEN_Up_1
//THIS IS GLYPH 265
MOVI 255 r1
ADDI 10 R1 //R1 SHOULD BE 265 NOW
STOR R1 R0 //LOAD POSITION
ADDI -53 R0 // GET POSITION BELOW PACMAN
//NOW NEED TO PMANOPEN_Up_2
//ITS IN LOCATION 266
MOVI 255 R1
ADDI 11 R1 //R1 SHOULD BE 266
STOR r1 r0 //STORE POSITION BELOW PACMAN
RETX
CLOSED_STATE_UP3:
//LOAD PMANCLOSED_Up_1
//IT'S GLYPH 213
MOVI 213 R1 //wait what?
STOR R1 R0 //LOAD INTO POSITION
ADDI -53 R0 // GET POSITION BELOW PACMAN
//NOW NEED TO LOAD PMANCLOSED_Up_2
//IT'S GLYPH 266
MOVI 255 r1
ADDI 11 r1 //R1 should be 266
STOR r1 r0 //STORE POSITION BELOW PACMAN
RETX
//COPY AND PASTING FROM STATE 1
//CHECK IF STATE DOWN0
drawDOWN0:
LOAD R5 R3
CMPI 32 r5
BNE drawDOWN1 //else check if in state UP1
//check the condition of the mouth
//if open
CMPI 1 R4
BNE CLOSED_STATE_DOWN0
//load PMANOPEN_DOWN_0
MOV r0 r1
//GLYPH 219
MOVI 219 R0
STOR r0 r1
ADDI 53 r1 //get location ABOVE pacman
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
CLOSED_STATE_DOWN0:
MOV r0 r1
LUI 0 r0 //load PMANCLOSED_DOWN_0
// GLYPH 179
MOVI 179 R0
STOR r0 r1
ADDI 53 r1 //get location ABOVE pacman
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//CHECK IF STATE DOWN1
drawDOWN1:
LOAD R5 R3
CMPI 33 r5
BNE drawDOWN2 //else check if in state DOWN2
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_DOWN1
//GET PMANOPEN_Down_1...in GLYPH 220
MOVI 220 r1
STOR R1 R0 //LOAD POSITION
ADDI -53 R0 // GET POSITION BELOW PACMAN
//NOW NEED TO LOAD PMANOPEN_Down_2
//ITS IN LOCATION 221
MOVI 221 R1
STOR r1 r0 //STORE POSITION BELOW PACMAN
RETX
CLOSED_STATE_DOWN1:
//LOAD PMANCLOSED_Down_1
//IT'S GLYPH 180
MOVI 180 R1
STOR R1 R0 //LOAD INTO POSITION
ADDI -53 R0 // GET POSITION BELOW PACMAN
//NOW NEED TO LOAD PMANCLOSED_Down_2
//IT'S GLYPH 181
MOVI 181 R1
STOR R1 R0 //LOAD INTO POSITION
RETX
//CHECK IF STATE DOWN2
drawDOWN2:
LOAD R5 R3
CMPI 34 r5
BNE drawDOWN3 //else check if in state DOWN2
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_DOWN2
//GET PMANOPEN_DOWN_3
//THIS IS GLYPH 222
MOVI 222 r1
STOR R1 R0 //LOAD POSITION
ADDI -53 R0 // GET POSITION BELOW PACMAN
//NOW NEED TO LOAD PMANOPEN_Down_4
//ITS IN LOCATION 223
MOVI 223 R1
STOR r1 r0 //STORE POSITION ABOVE PACMAN
RETX
CLOSED_STATE_DOWN2:
//LOAD PMANCLOSED_DOWN_3
//IT'S GLYPH 182
MOVI 182 R1
STOR R1 R0 //LOAD INTO POSITION
ADDI -53 R0 // GET POSITION BELOW PACMAN
//NOW NEED TO LOAD PMANCLOSE_Down_4
//IT'S GLYPH 183
MOVI 183 R1
STOR R1 R0 //LOAD INTO POSITION
RETX
//CHECK IF STATE DOWN3
drawDOWN3:
LOAD R5 R3
CMPI 35 r5
BNE drawLEFT0 //else check if in state drawDOWN0
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_DOWN3
//GET PMANOPEN_Down_6
//THIS IS GLYPH 225
MOVI 225 r1
STOR R1 R0 //LOAD POSITION
ADDI 53 R0 // GET POSITION ABOVE PACMAN
//NOW NEED TO PMANOPEN_Down_5
//ITS IN LOCATION 224
MOVI 224 R1
STOR r1 r0 //STORE POSITION ABOVE PACMAN
RETX
CLOSED_STATE_DOWN3:
//LOAD PMANCLOSED_Down_6
//IT'S GLYPH 185
MOVI 185 R1
STOR R1 R0 //LOAD INTO POSITION
ADDI 53 R0 // GET POSITION ABOVE PACMAN
//NOW NEED TO LOAD PMANOPEN_Down_5 (SAME AS PMANCLOSED)
//IT'S GLYPH 224
MOVI 224 R1 //is this right? i guess its same as pmanclosed?
STOR r1 r0 //STORE POSITION ABOVE PACMAN
RETX
// COPY AND PASTED FROM DOWN STATES
//CHECK IF STATE LEFT0
drawLEFT0:
LOAD R5 R3
CMPI 48 r5
BNE drawLEFT1 //else check if in state LEFT1
//check the condition of the mouth
//if open
CMPI 1 R4
BNE CLOSED_STATE_LEFT0
//load PMANOPEN_LEFT_0
//GLYPH 226
MOV r0 r1
MOVI 226 R0
STOR r0 r1
ADDI -1 r1 //get location TO THE RIGHT
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
CLOSED_STATE_LEFT0:
MOV r0 r1
LUI 0 r0 //load PMANCLOSED_LEFT_0
// GLYPH 186
MOVI 186 R0
STOR r0 r1
ADDI -1 r1 //get location TO THE RIGHT
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//CHECK IF STATE LEFT1
drawLEFT1:
LOAD R5 R3
CMPI 49 r5
BNE drawLEFT2 //else check if in state LEFT2
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_LEFT1
//GET PMANOPEN_Left_6...in GLYPH 232
MOV r0 r1
MOVI 232 r0
STOR R0 R1 //LOAD POSITION
ADDI 1 R1 //GET POSITION TO THE LEFT OF PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
//NOW NEED TO PMANOPEN_Left_5
//ITS IN LOCATION 231
MOVI 231 R0
STOR r0 r1 //STORE POSITION BELOW PACMAN
RETX
CLOSED_STATE_LEFT1:
//LOAD PMANCLOSED_Left_6
//IT'S GLYPH 192
MOV r0 r1
MOVI 192 R0
STOR R0 R1 //LOAD INTO POSITION
ADDI 1 R1 // GET POSITION TO THE LEFT OF PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
//NOW NEED TO LOAD PMANCLOSED_Left_5
//IT'S GLYPH 191
MOVI 191 R0
STOR R0 R1 //LOAD INTO POSITION
RETX
//CHECK IF STATE LEFT2
drawLEFT2:
LOAD R5 R3
CMPI 50 r5
BNE drawLEFT3 //else check if in state LEFT2
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_LEFT2
//GET PMANOPEN_Left_4
//THIS IS GLYPH 230
MOV R0 R1
MOVI 230 r0
STOR R0 R1 //LOAD POSITION
ADDI 1 R1 // GET POSITION TO THE LEFT OF PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
//NOW NEED TO LOAD PMANOPEN_Left_3
//ITS IN LOCATION 229
MOVI 229 R0
STOR r0 r1 //STORE POSITION ABOVE PACMAN
RETX
CLOSED_STATE_LEFT2:
//LOAD PMANCLOSED_Left_4
//IT'S GLYPH 190
MOV R0 R1
MOVI 190 R0
STOR R0 R1 //LOAD INTO POSITION
ADDI 1 R1 // GET POSITION BELOW PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
//NOW NEED TO LOAD PMANCLOSED_Left_3
//IT'S GLYPH 189
MOVI 189 R0
STOR R0 R1 //LOAD INTO POSITION
RETX
//CHECK IF STATE LEFT3
drawLEFT3:
LOAD R5 R3
CMPI 51 r5
BNE drawRIGHT0 //else check if in state drawRIGHT0
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_LEFT3
//GET PMANOPEN_Left_1
//THIS IS GLYPH 227
MOV r0 r1
MOVI 227 r0
STOR R0 R1 //LOAD POSITION
ADDI -1 R1 // GET POSITION TO THE RIGHT OF PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
//NOW NEED TO PMANOPEN_Left_2
//ITS IN LOCATION 228
MOVI 228 R0
STOR r0 r1 //STORE POSITION ABOVE PACMAN
RETX
CLOSED_STATE_LEFT3:
//LOAD PMANCLOSED_Left_1
//IT'S GLYPH 187
MOV r0 r1
MOVI 187 R0
STOR R0 R1 //LOAD INTO POSITION
ADDI -1 R1 // GET POSITION TO THE RIGHT PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
//NOW NEED TO LOAD PMANCLOSED_Left_2 (SAME AS PMANCLOSED)
//IT'S GLYPH 188
MOVI 188 R0
STOR r0 r1 //STORE POSITION ABOVE PACMAN
RETX
// COPY AND PASTE FROM LEFT
//CHECK IF STATE RIGHT0
drawRIGHT0:
LOAD R5 R3
CMPI 64 r5
BNE drawRIGHT1 //else check if in state RIGHT1
//check the condition of the mouth
//if open
CMPI 1 R4
BNE CLOSED_STATE_RIGHT0
//load PMANOPEN_RIGHT_0
//GLYPH 245
MOV R0 R1
MOVI 245 R0
STOR r0 r1
ADDI 1 r1 //get location TO THE LEFT
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
CLOSED_STATE_RIGHT0:
MOV R0 R1
LUI 0 r0 //load PMANCLOSED_RIGHT_0
// GLYPH 205
MOVI 205 R0
STOR r0 r1
ADDI 1 r1 //get location TO THE LEFT
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//CHECK IF STATE RIGHT1
drawRIGHT1:
LOAD R5 R3
CMPI 65 r5
BNE drawRIGHT2 //else check if in state RIGHT2
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_RIGHT1
//GET PMANOPEN_Right_1...in GLYPH 246
MOV r0 r1
MOVI 246 r0
STOR R0 R1 //LOAD POSITION
ADDI -1 R1 // GET POSITION TO THE RIGHT OF PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
//NOW NEED TO PMANOPEN_Right_2
//ITS IN LOCATION 247
MOVI 247 R0
STOR r0 r1 //STORE POSITION BELOW PACMAN
RETX
CLOSED_STATE_RIGHT1:
//LOAD PMANCLOSED_Right_1
//IT'S GLYPH 206
MOV r0 r1
MOVI 206 R0
STOR R0 R1 //LOAD INTO POSITION
ADDI -1 R1 // GET POSITION TO THE RIGHT OF PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
//NOW NEED TO LOAD PMANCLOSED_Right_2
//IT'S GLYPH 207
MOVI 207 R0
STOR R0 R1 //LOAD INTO POSITION
RETX
//CHECK IF STATE RIGHT2
drawRIGHT2:
LOAD R5 R3
CMPI 66 r5
BNE drawRIGHT3 //else check if in state RIGHT2
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_RIGHT2
//GET PMANOPEN_Right_3
//THIS IS GLYPH 248
MOV R0 R1
MOVI 248 r0
STOR R0 R1 //LOAD POSITION
ADDI -1 R1 // GET POSITION TO THE RIGHT OF PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
//NOW NEED TO LOAD PMANOPEN_Right_4
//ITS IN LOCATION 249
MOVI 249 R0
STOR R0 R1 //STORE POSITION ABOVE PACMAN
RETX
CLOSED_STATE_RIGHT2:
//LOAD PMANCLOSED_Right_3
//IT'S GLYPH 208
MOV R0 R1 //swap registers so function to setposition_warpright call will work...... I hope....
MOVI 208 R0
STOR R0 R1 //LOAD INTO POSITION
ADDI -1 R1 // GET POSITION TO THE RIGHT PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
//NOW NEED TO LOAD PMANCLOSED_Right_4
//IT'S GLYPH 209
MOVI 209 R0
STOR R0 R1 //LOAD INTO POSITION
RETX
//CHECK IF STATE RIGHT3
drawRIGHT3:
LOAD R5 R3
CMPI 67 r5
BNE drawDEAD1 //else check if in state drawRIGHT0
//CHECK CONDITION OF MOUTH
//IF OPEN
CMPI 1 R4
BNE CLOSED_STATE_RIGHT3
//GET PMANOPEN_Right_6
//THIS IS GLYPH 251
MOV r0 r1
MOVI 251 r0
STOR R0 R1 //LOAD POSITION
ADDI 1 R1 // GET POSITION TO THE LEFT OF PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
//NOW NEED TO PMANOPEN_Right_5
//ITS IN LOCATION 250
MOVI 250 R0
STOR r0 r1 //STORE POSITION ABOVE PACMAN
RETX
CLOSED_STATE_RIGHT3:
//LOAD PMANCLOSED_Right_6
//IT'S GLYPH 211
MOV r0 r1
MOVI 211 R0
STOR R0 R1 //LOAD INTO POSITION
ADDI 1 R1 // GET POSITION TO THE LEFT PACMAN
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
//NOW NEED TO LOAD PMANCLOSED_Right_5 (SAME AS PMANCLOSED)
//IT'S GLYPH 210
MOVI 210 R0
STOR r0 r1 //STORE POSITION ABOVE PACMAN
RETX
drawDEAD1:
ADD r0 r0
RETX
INIT_PACMAN:
LUI 255 r0 //make timer reset address
ORI 243 r0
LUI 4 r1 //set 512+256 miliseconds on timer //TIMER SET
STOR r1 r0
//set pacman state to left0
LUI 51 r4
ORI 145 r4
MOVI 48 r1
STOR r1 r4
//set pacman initial mouth toggle to 1
LUI 51 r4
ORI 146 r4
MOVI 1 r1
STOR r1 r4
//set pacman mouth toggle timer
LUI 255 r1
ORI 231 r1
MOVI 250 r2
STOR r2 r1 //store 250 ms on timer. //TIMER SET
//put pacman on initial spot in map
LUI 51 r4
ORI 144 r4 //store address in r4
LUI 63 r1 # make address for top corner in frame buffer
ORI 255 r1
MOVI 53 r8
MULI -28 r8
ADD r8 r1 # Offset by rows
ADDI -26 r1 # Offset by columns
STOR R1 r4
//initialize lives left
LUI 51 r4 //lives left addr
ORI 244 r4 //lives left addr
MOVI 4 r0
STOR r0 r4
MOV r15 r14
JAL r6 drawLivesLeft
MOV r14 r15
RETX
pacman_isWallUP:
LUI 51 r0 //make address 13200 where pacman location is stored
ORI 144 r0
LOAD r0 r0 //save result back into r0
ADDI 53 r0 //increment r0 to get location of square above pacman (53 adress spaces higher in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
pacman_isWallDOWN:
LUI 51 r0 //make address 13200 where pacman location is stored
ORI 144 r0
LOAD r0 r0 //save result back into r0
ADDI -53 r0 //increment r0 to get location of square below pacman (53 adress spaces lower in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
pacman_isWallLEFT:
LUI 51 r0 //make address 13200 where pacman location is stored
ORI 144 r0
LOAD r0 r0 //save result back into r0
ADDI 1 r0 //increment r0 to get location of square left of pacman (1 space higher in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
pacman_isWallRIGHT:
LUI 51 r0 //make address 13200 where pacman location is stored
ORI 144 r0
LOAD r0 r0 //save result back into r0
ADDI -1 r0 //increment r0 to get location of square right of pacman (1 space lower in memory)
LOAD r0 r0
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
//:::::::::::::END PACMAN STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::END PACMAN STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::END PACMAN STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::BEGIN GreenGhost STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::BEGIN GreenGhost STATE MACHINE::::::::::::::::::::::::::
//:::::::::::::BEGIN GreenGhost STATE MACHINE::::::::::::::::::::::::::
/////THIS FUNCTION UPDATES STATEMACHINE BY ONE STEP.
//
// The first thing it does is check the timer. If the timer is not active, it immediately leaves.
// Otherwise:
// check what state GreenGhost is in
// check controller input accordingly,
// update state & position variables
// reset timer
//
GreenGhost_UPDATE_STATE:
MOV r15 r14 //store old return adress
LUI 255 r0 //check timer by making address
ORI 240 r0
LOAD r0 r0 //then loading its value and cmp to 1
CMPI 1 r0
JNE r6 endGreenGhostStateUpdate //if timer was not active, do not update state.
// //else, continue on to update GreenGhost state:
//
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::GET CURRENT STATE ADDRESS::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CURRENT STATE state address 12801, store address in r4
LUI 50 r4
ORI 1 r4 //store address in r4
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::ZERO STATES::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// If in a ZERO state:
// check if on a ghost, if so die.
// otherwise, check player input in all directions and start MOVIng.
// if player has made no input selections, keep going in current direction.
// CHECK IF GreenGhost HIT GHOST: (Any ghost position is on GreenGhosts square)
// if hit, set nextstate to dead,
// jump to reset timer to progress to next state.
//
// if position = AnyGhostPosition
// nextstate = GreenGhostDEAD1
// JUC endGreenGhostState_SetTimer
//Check if in a '0' state:
LOAD r1 r4 //read current state, address in r4
MOV r1 r0 //copy STATE into temp register.
ANDI 15 r0 //mask it by ANDing it with 0xF (15)
CMPI 0 r0 //if masked value is not zero, check if it is in another state
JNE r6 GGUpStates //by branching to the next comparison, to check if it is an upstate
//IN A ZERO STATE:
LUI 50 r1
ORI 10 r1
MOVI 0 r2
STOR r2 r1 //zero up
ADDI 1 r1
STOR r2 r1 //zero down
ADDI 1 r1
STOR r2 r1 //zero left
ADDI 1 r1
STOR r2 r1 //zero right
LUI 50 r1
ORI 20 r1
STOR r2 r1 //zero vert heur
ADDI 1 r1
STOR r2 r1 //zero horiz heur
LOAD r1 r4 //load state into r1
CMPI 16 r1 //check if in up0 state.
BEQ GG_StateUP0 //if not in up0 state, check if in down0 state
CMPI 32 r1 //check if in down0 state.
BEQ GG_StateDOWN0 //if not in down0 state, check if in left0 state, else:
CMPI 48 r1 //check if in left0 state.
BEQ GG_StateLEFT0
CMPI 64 r1 //check if in right0 state.
BEQ GG_StateRIGHT0 //if not in right0 state, do not update state.
GG_StateUP0:
LUI 50 r1
ORI 10 r1
MOVI 150 r2 //save UP heur as 150
STOR r2 r1
BUC GG_WallCheckUP
GG_StateDOWN0:
LUI 50 r1
ORI 11 r1
MOVI 150 r2 //save DOWN heur as 150
STOR r2 r1
BUC GG_WallCheckUP
GG_StateLEFT0:
LUI 50 r1
ORI 12 r1
MOVI 150 r2 //save LEFT heur as 150
STOR r2 r1
BUC GG_WallCheckUP
GG_StateRIGHT0:
LUI 50 r1
ORI 13 r1
MOVI 150 r2 //save RIGHT heur as 150
STOR r2 r1
GG_WallCheckUP:
JAL r6 GreenGhost_isWallUP
CMPI 1 r0
BNE GG_WallCheckDOWN
LUI 50 r1
ORI 10 r1
MOVI 200 r0 //SAVE UP HEUR AS 200
STOR r0 r1
GG_WallCheckDOWN:
JAL r6 GreenGhost_isWallDOWN
CMPI 1 r0
BNE GG_WallCheckLEFT
LUI 50 r1
ORI 11 r1
MOVI 200 r0 //SAVE down HEUR AS 200
STOR r0 r1
GG_WallCheckLEFT:
JAL r6 GreenGhost_isWallLEFT
CMPI 1 r0
BNE GG_WallCheckRIGHT
LUI 50 r1
ORI 12 r1
MOVI 200 r0 //SAVE left HEUR AS 200
STOR r0 r1
GG_WallCheckRIGHT:
JAL r6 GreenGhost_isWallRIGHT
CMPI 1 r0
BNE GreenGhost_findTarget
LUI 50 r1
ORI 13 r1
MOVI 200 r0 //SAVE right HEUR AS 200
STOR r0 r1
GreenGhost_findTarget:
LUI 51 r10 //load pman position
ORI 144 r10
LOAD r10 r10
ADDI 2 r10 //target location is 2 behind pman
LUI 50 r11 //load ghost position
LOAD r11 r11
SUB r10 r11 //r11 = r11 - r10
CMPI 0 r11
BLT GG_pman_is_ABOVEorLEFT
BGT GG_pman_is_BELOWorRIGHT
JUC r6 endGreenGhostState_SetTimer
GG_pman_is_ABOVEorLEFT:
MOVI 0 r9 //ROWS = r9
GG_loop1:
CMPI 0 r11
BGE GG_endLoop1
ADDI 53 r11
ADDI 1 r9
BUC GG_loop1
GG_endLoop1:
MOV r11 r8 //COLS = r8
BUC GG_CompareDistances
GG_pman_is_BELOWorRIGHT:
MOVI 0 r9
GG_loop2:
CMPI 0 r11
BLE GG_endLoop2
ADDI -53 r11
ADDI 1 r9
BUC GG_loop2
GG_endLoop2:
MULI -1 r11
MOV r11 r8
GG_CompareDistances:
CMP r8 r9
BGE GG_LR
LUI 50 r1
ORI 12 r1
LOAD r0 r1
ADDI 50 r0
STOR r0 r1
ADDI 1 r1
LOAD r0 r1
ADDI 50 r0
STOR r0 r1
BUC GG_findDirection
GG_LR:
LUI 50 r1
ORI 10 r1
LOAD r0 r1
ADDI 50 r0
STOR r0 r1
ADDI 1 r1
LOAD r0 r1
ADDI 50 r0
STOR r0 r1
GG_findDirection:
//load heuristics
LUI 50 r0
ORI 10 r0
LOAD r1 r0 //r1 = up heur
ADDI 1 r0
LOAD r2 r0 //r2 = down heur
ADDI 1 r0
LOAD r3 r0 //r3 = left heur
ADDI 1 r0
LOAD r4 r0 //r4 = right heur
MOVI 0 r5 //r5 = winner of up/down (1 means down was less)
MOVI 0 r6 //r6 = winner of left/right (1 means right was less)
CMP r1 r2
BGE GG_checkLR //if up <= down // DOWN GREATER OR EQUAL TO UP:
MOV r2 r1 //if up > down // DOWN LESS THAN UP
MOVI 1 r5 //1 means down was less
GG_checkLR:
CMP r3 r4
BGE GG_findWinner //if left <= right // RIGHT GREATER OR EQUAL TO LEFT:
MOV r4 r3 //if left > right // RIGHT LESS THAN UP
MOVI 1 r6 //1 means right eas less
GG_findWinner:
CMP r1 r3
BLE GG_GetHorizDirection //r3 is less than r1... HORIZ less than VERT
GG_GetVertDirection:
CMPI 0 r5
BEQ GG_GoUP
LUI 50 r0
ORI 1 r0
JAL r6 setStateDOWN1
JUC r6 endGreenGhostState_SetTimer
GG_GoUP:
LUI 50 r0
ORI 1 r0
JAL r6 setStateUP1
JUC r6 endGreenGhostState_SetTimer
GG_GetHorizDirection:
CMPI 0 r6
BEQ GG_GoLEFT
LUI 50 r0
ORI 1 r0
JAL r6 setStateRIGHT1
JUC r6 endGreenGhostState_SetTimer
GG_GoLEFT:
LUI 50 r0
ORI 1 r0
JAL r6 setStateLEFT1
JUC r6 endGreenGhostState_SetTimer
////:::::::::::::::::::::::End Zero States::::::::::::::::::::::::::
GGUpStates:
//if we are traveling up and not centered on a tile, we will
//continue to travel up, thus only the down button must be checked.
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostUP1:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostUP1:
LOAD r1 r4 //read current state, address in r4
CMPI 17 r1 //if state is GreenGhostUP1
BNE GreenGhostUP2
//JAL r6 CheckDOWN //check if down control is pushed
//CMPI 1 r0
//BNE GGUP1Cont
//UP1Rev:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateDOWN0 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGUP1Cont:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostUP2:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostUP2:
LOAD r1 r4 //read current state, address in r4
CMPI 18 r1 //if state is GreenGhostUP2
BNE GreenGhostUP3
//JAL r6 CheckDOWN //check if down control is pushed
//CMPI 1 r0
//BNE GGUP2Cont
////if button isnt pushed, skip to up2cont otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateDOWN3 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGUP2Cont:
LUI 50 r0 //update GreenGhost position by making position address in r0
LOAD r1 r0 //then getting it in r1
ADDI 53 r1 //adding one
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostUP3:::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostUP3:
LOAD r1 r4 //read current state, address in r4
CMPI 19 r1 //if state is GreenGhostUP3
BNE GreenGhostDOWN1
//JAL r6 CheckDOWN //check if down control is pushed
//CMPI 1 r0
//BNE GGUP3Cont
////if button isnt pushed, skip down 4 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateDOWN2 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGUP3Cont:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateUP0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GGDownStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostDOWN1:::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostDOWN1:
LOAD r1 r4 //read current state, address in r4
CMPI 33 r1 //if state is GreenGhostDOWN1
BNE GreenGhostDOWN2
//JAL r6 CheckUP //check if control is pushed
//CMPI 1 r0
//BNE GGD1C
////if button isnt pushed, skip down 4 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateUP0 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGD1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostDOWN2:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostDOWN2:
LOAD r1 r4 //read current state, address in r4
CMPI 34 r1 //if state is GreenGhostDOWN2
BNE GreenGhostDOWN3
//JAL r6 CheckUP //check if control is pushed
//CMPI 1 r0
//BNE GGD2C
////if button isnt pushed, skip down 9 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateUP3 // set GreenGhost state //and storing back to position address in r0
//JUC r6 endGreenGhostState_SetTimer
GGD2C:
LUI 50 r0 //update GreenGhost position by making position address in r0
LOAD r1 r0 //then getting it in r1
ADDI -53 r1 //adding one
STOR r1 r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostDOWN3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostDOWN3:
LOAD r1 r4 //read current state, address in r4
CMPI 35 r1 //check state
BNE GreenGhostLEFT1 //
//JAL r6 CheckUP //check if down control is pushed
//CMPI 1 r0
//BNE GGD3C
////if button isnt pushed, skip down 4 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateUP2 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGD3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateDOWN0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GGLeftStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostLEFT1:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostLEFT1:
LOAD r1 r4 //read current state, address in r4
CMPI 49 r1 //check state
BNE GreenGhostLEFT2
//JAL r6 CheckRIGHT //check if control is pushed
//CMPI 1 r0
//BNE GGL1C //if button isnt pushed, skip down 4 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateRIGHT0 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGL1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostLEFT2:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostLEFT2:
LOAD r1 r4 //read current state, address in r4
CMPI 50 r1 //check state
BNE GreenGhostLEFT3
//JAL r6 CheckRIGHT //check if control is pushed
//CMPI 1 r0
//BNE GGL2C
////if button isnt pushed, skip down 9 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateRIGHT3 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGL2C:
LUI 50 r0 //update GreenGhost position by making position address in r0
LOAD r1 r0 //then getting it in r1
ADDI 1 r1 //adding one
JAL r6 SetPosition_WarpLeftSide //setting it to either its position or the 'warp' position.
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostLEFT3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostLEFT3:
LOAD r1 r4 //read current state, address in r4
CMPI 51 r1 //check state
BNE GreenGhostRIGHT1 //
//JAL r6 CheckRIGHT //check if down control is pushed
//CMPI 1 r0
//BNE GGL3C
////if button isnt pushed, skip down 4 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateRIGHT2 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGL3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateLEFT0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GGRightStates:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostRIGHT1:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostRIGHT1:
LOAD r1 r4 //read current state, address in r4
CMPI 65 r1 //check state
BNE GreenGhostRIGHT2
//JAL r6 CheckLEFT //check if control is pushed
//CMPI 1 r0
//BNE GGR1C //if button isnt pushed, skip down 4 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateLEFT0 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGR1C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT2 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostRIGHT2::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostRIGHT2:
LOAD r1 r4 //read current state, address in r4
CMPI 66 r1 //check state
BNE GreenGhostRIGHT3
//JAL r6 CheckLEFT //check if control is pushed
//CMPI 1 r0
//BNE GGR2C //if button isnt pushed, skip down 9 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateLEFT3 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGR2C:
LUI 50 r0 //update GreenGhost position by making position address in r0
LOAD r1 r0 //then getting it in r1
ADDI -1 r1 //adding one
JAL r6 SetPosition_WarpRightSide //set position to warped side or current position.
STOR r1 r0 //and storing back to position address in r0
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT3 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::GreenGhostRIGHT3:::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhostRIGHT3:
LOAD r1 r4 //read current state, address in r4
CMPI 67 r1 //check state
BNE endGreenGhostState_SetTimer //
//JAL r6 CheckLEFT //check if LEFT control is pushed
//CMPI 1 r0
//BNE GGR3C
////if button isnt pushed, skip down 4 lines, otherwise do the following:
//MOV r4 r0 // move state address to r0 to prepare for setState call
//JAL r6 setStateLEFT2 // set GreenGhost state
//JUC r6 endGreenGhostState_SetTimer
GGR3C:
MOV r4 r0 // move state address to r0 to prepare for setState call
JAL r6 setStateRIGHT0 // set GreenGhost state
JUC r6 endGreenGhostState_SetTimer
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
endGreenGhostState_SetTimer:
LUI 255 r0 //make timer reset address
ORI 241 r0
MOVI 80 r1 //set 512+256 miliseconds on timer //TIMER SET
STOR r1 r0
endGreenGhostStateUpdate:
MOV r14 r15 //restore old return adress
RETX //return
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::GreenGhostDraw GLYPH:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
GreenGhost_Draw_GLYPH:
//GreenGhost's GreenGhostDraw glyph
//check if not edible
// if not edible GreenGhostDraw normal
// if edible check flash state:
// if blue: GreenGhostDraw blue ghost
// if lblue: GreenGhostDraw lblue ghost
//MAKE GreenGhost LOCATION ADDRESS IN r2
LUI 50 r2
//MAKE GreenGhost STATE ADDRESS IN r3
LUI 50 r3
ORI 1 r3
//load location of GreenGhost INTO r0
LOAD r0 r2
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE UP 0:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE UP0
GreenGhostDrawUP0:
load r5 r3
CMPI 16 r5
BNE GreenGhostDrawUP1 //else check if in state UP1
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_UP0
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_UP0
BUC GG_Eat1_UP0
GG_Normal_UP0:
MOV r0 r1
MOVI 107 r0 //GGHOST_UP_0
STOR r0 r1
ADDI -53 r1 //get location below GreenGhost
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
GG_Eat0_UP0:
MOV r0 r1
MOVI 51 r0 //E1GHOST_UP_0
STOR r0 r1
ADDI -53 r1 //get location below
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
GG_Eat1_UP0:
MOV r0 r1
MOVI 79 r0 //E2GHOST_UP0
STOR r0 r1
ADDI -53 r1 //get location below
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE UP 1:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE UP1
GreenGhostDrawUP1:
LOAD R5 R3
CMPI 17 r5
BNE GreenGhostDrawUP2 //else check if in state UP2
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_UP1
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_UP1
BUC GG_Eat1_UP1
GG_Normal_UP1:
MOV r0 r1
MOVI 113 r0 //GHOST_UP_6
STOR R0 R1
ADDI 53 R1 //get location above
MOVI 112 r0 //GHOST_UP_5
STOR r0 r1
RETX
GG_Eat0_Up1:
MOVI 57 R1 //E1GHOST_UP_6
STOR R1 R0
ADDI 53 R0
MOVI 56 R1 //E1GHOST_UP_5
STOR R1 R0
RETX
GG_Eat1_Up1:
MOVI 85 R1 //E2GHOST_UP6
STOR R1 R0
ADDI 53 R0
MOVI 84 R1 //E2GHOST_UP5
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE UP 2:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE UP2
GreenGhostDrawUP2:
LOAD R5 R3
CMPI 18 r5
BNE GreenGhostDrawUP3 //else check if in state UP3
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_UP2
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_UP2
BUC GG_Eat1_UP2
GG_Normal_UP2:
MOV r0 r1
MOVI 111 r0 //GHOST_UP_4
STOR R0 R1
ADDI 53 R1 //get location above
MOVI 110 r0 //GHOST_UP_3
STOR r0 r1
RETX
GG_Eat0_Up2:
MOVI 55 R1 //E1GHOST_UP_4
STOR R1 R0
ADDI 53 R0
MOVI 54 R1 //E1GHOST_UP_3
STOR R1 R0
RETX
GG_Eat1_Up2:
MOVI 83 R1 //E2GHOST_UP_4
STOR R1 R0
ADDI 53 R0
MOVI 82 R1 //E2GHOST_UP_3
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE UP 3:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE UP3
GreenGhostDrawUP3:
LOAD R5 R3
CMPI 19 r5
BNE GreenGhostDrawDOWN0 //else check if in state GreenGhostDrawDOWN0
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_UP3
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_UP3
BUC GG_Eat1_UP3
GG_Normal_UP3:
MOV r0 r1
MOVI 108 r0 //GHOST_UP_1
STOR R0 R1
ADDI -53 R1 //get location below
MOVI 109 r0 //GHOST_UP_2
STOR r0 r1
RETX
GG_Eat0_Up3:
MOVI 52 R1 //E1GHOST_UP_1
STOR R1 R0
ADDI -53 R0
MOVI 53 R1 //E1GHOST_UP_2
STOR R1 R0
RETX
GG_Eat1_Up3:
MOVI 80 R1 //E2GHOST_UP_1
STOR R1 R0
ADDI -53 R0
MOVI 81 R1 //E2GHOST_UP_2
STOR R1 R0 //LOAD INTO POSITION
RETX
//COPY AND PASTE FROM UP STATES!!
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE DOWN 0:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE DOWN0
GreenGhostDrawDOWN0:
load r5 r3
CMPI 32 r5
BNE GreenGhostDrawDOWN1 //else check if in state DOWN1
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_DOWN0
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_DOWN0
BUC GG_Eat1_DOWN0
GG_Normal_DOWN0:
MOV r0 r1
MOVI 86 r0 //GGHOST_DOWN_0
STOR r0 r1
ADDI 53 r1 //get location above GreenGhost
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
GG_Eat0_DOWN0:
MOV r0 r1
MOVI 30 r0 //E1GHOST_DOWN_0
STOR r0 r1
ADDI 53 r1 //get location above
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
GG_Eat1_DOWN0:
MOV r0 r1
MOVI 58 r0 //E2GHOST_DOWN_0
STOR r0 r1
ADDI 53 r1 //get location above
MOV r15 r14
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE DOWN 1:::::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE DOWN1
GreenGhostDrawDOWN1:
LOAD R5 R3
CMPI 33 r5
BNE GreenGhostDrawDOWN2 //else check if in state DOWN2
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_DOWN1
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_DOWN1
BUC GG_Eat1_DOWN1
GG_Normal_DOWN1:
MOV r0 r1
MOVI 87 r0 //GHOST_DOWN_1
STOR R0 R1
ADDI -53 R1 //get location below
MOVI 88 r0 //GHOST_DOWN_2
STOR r0 r1
RETX
GG_Eat0_DOWN1:
MOVI 31 R1 //E1GHOST_DOWN_1
STOR R1 R0
ADDI -53 R0
MOVI 32 R1 //E1GHOST_DOWN_2
STOR R1 R0
RETX
GG_Eat1_DOWN1:
MOVI 59 R1 //E2GHOST_DOWN_1
STOR R1 R0
ADDI -53 R0
MOVI 60 R1 //E2GHOST_DOWN_2
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE DOWN 2:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE DOWN2
GreenGhostDrawDOWN2:
LOAD R5 R3
CMPI 34 r5
BNE GreenGhostDrawDOWN3 //else check if in state DOWN3
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_DOWN2
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_DOWN2
BUC GG_Eat1_DOWN2
GG_Normal_DOWN2:
MOV r0 r1
MOVI 89 r0 //GHOST_DOWN_3
STOR R0 R1
ADDI -53 R1 //get location below
MOVI 90 r0 //GHOST_DOWN_4
STOR r0 r1
RETX
GG_Eat0_DOWN2:
MOVI 33 R1 //E1GHOST_DOWN_3
STOR R1 R0
ADDI -53 R0
MOVI 34 R1 //E1GHOST_DOWN_4
STOR R1 R0
RETX
GG_Eat1_DOWN2:
MOVI 61 R1 //E2GHOST_DOWN_3
STOR R1 R0
ADDI -53 R0
MOVI 62 R1 //E2GHOST_DOWN_4
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE DOWN 3:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE DOWN3
GreenGhostDrawDOWN3:
LOAD R5 R3
CMPI 35 r5
BNE GreenGhostDrawLEFT0 //else check if in state GreenGhostDrawDOWN0
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_DOWN3
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_DOWN3
BUC GG_Eat1_DOWN3
GG_Normal_DOWN3:
MOV r0 r1
MOVI 92 r0 //GHOST_DOWN_6
STOR R0 R1
ADDI 53 R1 //get location above
MOVI 91 r0 //GHOST_DOWN_5
STOR r0 r1
RETX
GG_Eat0_DOWN3:
MOVI 64 R1 //E1GHOST_DOWN_6
STOR R1 R0
ADDI 53 R0
MOVI 63 R1 //E1GHOST_DOWN_5
STOR R1 R0
RETX
GG_Eat1_DOWN3:
MOVI 81 R1 //E2GHOST_DOWN_6
STOR R1 R0
ADDI 53 R0
MOVI 80 R1 //E2GHOST_DOWN_5
STOR R1 R0 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE LEFT 0:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE LEFT0
GreenGhostDrawLEFT0:
load r5 r3
CMPI 48 r5
BNE GreenGhostDrawLEFT1 //else check if in state LEFT1
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_LEFT0
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_LEFT0
BUC GG_Eat1_LEFT0
GG_Normal_LEFT0:
MOV r0 r1
MOVI 93 r0 //GGHOST_LEFT_0
STOR r0 r1
ADDI -1 r1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
GG_Eat0_LEFT0:
MOV r0 r1
MOVI 37 r0 //E1GHOST_LEFT_0
STOR r0 r1
ADDI -1 r1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
GG_Eat1_LEFT0:
MOV r0 r1
MOVI 65 r0 //E2GHOST_LEFT0
STOR r0 r1
ADDI -1 r1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE LEFT 1:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE LEFT1
GreenGhostDrawLEFT1:
LOAD R5 R3
CMPI 49 r5
BNE GreenGhostDrawLEFT2 //else check if in state LEFT2
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_LEFT1
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_LEFT1
BUC GG_Eat1_LEFT1
GG_Normal_LEFT1:
MOV r0 r1
MOVI 99 r0 //GHOST_LEFT_6
STOR R0 R1
ADDI 1 R1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 98 r0 //GHOST_LEFT_5
STOR r0 r1
RETX
GG_Eat0_LEFT1:
MOV r0 r1
MOVI 43 R0 //E1GHOST_LEFT_6
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 42 R0 //E1GHOST_LEFT_5
STOR R0 R1
RETX
GG_Eat1_LEFT1:
MOV r0 r1
MOVI 71 R0 //E2GHOST_LEFT_6
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 70 R0 //E2GHOST_LEFT_5
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE LEFT 2:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE LEFT2
GreenGhostDrawLEFT2:
LOAD R5 R3
CMPI 50 r5
BNE GreenGhostDrawLEFT3 //else check if in state LEFT3
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_LEFT2
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_LEFT2
BUC GG_Eat1_LEFT2
GG_Normal_LEFT2:
MOV r0 r1
MOVI 97 r0 //GHOST_LEFT_4
STOR R0 R1
ADDI 1 R1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 96 r0 //GHOST_LEFT_3
STOR r0 r1
RETX
GG_Eat0_LEFT2:
MOV r0 r1
MOVI 41 R0 //E1GHOST_LEFT_4
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 40 R0 //E1GHOST_LEFT_3
STOR R0 R1
RETX
GG_Eat1_LEFT2:
MOV r0 r1
MOVI 69 R0 //E2GHOST_LEFT_4
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 68 R0 //E2GHOST_LEFT_3
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE LEFT 3:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE LEFT3
GreenGhostDrawLEFT3:
LOAD R5 R3
CMPI 51 r5
BNE GreenGhostDrawRIGHT0 //else check if in state GreenGhostDrawDOWN0
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_LEFT3
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_LEFT3
BUC GG_Eat1_LEFT3
GG_Normal_LEFT3:
MOV r0 r1
MOVI 94 r0 //GHOST_LEFT_1
STOR R0 R1
ADDI -1 R1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 95 r0 //GHOST_LEFT_2
STOR r0 r1
RETX
GG_Eat0_LEFT3:
MOV r0 r1
MOVI 38 R0 //E1GHOST_LEFT_1
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 39 R0 //E1GHOST_LEFT_2
STOR R0 R1
RETX
GG_Eat1_LEFT3:
MOV r0 r1
MOVI 66 R0 //E2GHOST_LEFT_1
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 67 R0 //E2GHOST_LEFT_2
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE RIGHT 0:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE RIGHT0
GreenGhostDrawRIGHT0:
load r5 r3
CMPI 64 r5
BNE GreenGhostDrawRIGHT1 //else check if in state RIGHT1
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_RIGHT0
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_RIGHT0
BUC GG_Eat1_RIGHT0
GG_Normal_RIGHT0:
MOV r0 r1
MOVI 100 r0 //GGHOST_RIGHT_0
STOR r0 r1
ADDI 1 r1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1 //store the glyph back in.
RETX
GG_Eat0_RIGHT0:
MOV r0 r1
MOVI 44 r0 //E1GHOST_RIGHT_0
STOR r0 r1
ADDI 1 r1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
GG_Eat1_RIGHT0:
MOV r0 r1
MOVI 72 r0 //E2GHOST_RIGHT_0
STOR r0 r1
ADDI 1 r1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
JAL r6 FBpos_2_CPpos //get the position in frame buffer copy
LOAD r0 r1 //load the glyph in frame buffer copy
JAL r6 CPpos_2_FBpos //get the position in the frame buffer
MOV r14 r15
STOR r0 r1
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE RIGHT 1:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE RIGHT1
GreenGhostDrawRIGHT1:
LOAD R5 R3
CMPI 65 r5
BNE GreenGhostDrawRIGHT2 //else check if in state RIGHT2
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_RIGHT1
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_RIGHT1
BUC GG_Eat1_RIGHT1
GG_Normal_RIGHT1:
MOV r0 r1
MOVI 101 r0 //GHOST_RIGHT_1
STOR R0 R1
ADDI -1 R1 //get location left
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 102 r0 //GHOST_RIGHT_2
STOR r0 r1
RETX
GG_Eat0_RIGHT1:
MOV r0 r1
MOVI 45 R0 //E1GHOST_RIGHT_1
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 46 R0 //E1GHOST_RIGHT_2
STOR R0 R1
RETX
GG_Eat1_RIGHT1:
MOV r0 r1
MOVI 73 R0 //E2GHOST_RIGHT_1
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 74 R0 //E2GHOST_RIGHT_2
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE RIGHT 2:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE RIGHT2
GreenGhostDrawRIGHT2:
LOAD R5 R3
CMPI 66 r5
BNE GreenGhostDrawRIGHT3 //else check if in state RIGHT3
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_RIGHT2
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_RIGHT2
BUC GG_Eat1_RIGHT2
GG_Normal_RIGHT2:
MOV r0 r1
MOVI 103 r0 //GHOST_RIGHT_3
STOR R0 R1
ADDI -1 R1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 104 r0 //GHOST_RIGHT_4
STOR r0 r1
RETX
GG_Eat0_RIGHT2:
MOV r0 r1
MOVI 47 R0 //E1GHOST_RIGHT_3
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 48 R0 //E1GHOST_RIGHT_4
STOR R0 R1
RETX
GG_Eat1_RIGHT2:
MOV r0 r1
MOVI 75 R0 //E2GHOST_RIGHT_3
STOR R0 R1
ADDI -1 R1
MOV r15 r14
JAL r6 SetPosition_WarpRightSide
MOV r14 r15
MOVI 76 R0 //E2GHOST_RIGHT_4
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::STATE RIGHT 3:::::::::::::::::::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//CHECK IF STATE RIGHT3
GreenGhostDrawRIGHT3:
LOAD R5 R3
CMPI 67 r5
BEQ GG_Right3 //else return if not in a state...
RETX
GG_Right3:
//check edible state:
LUI 51 r1
ORI 255 r1
LOAD r1 r1
CMPI 0 r1
BEQ GG_Normal_RIGHT3
LUI 52 r1
LOAD r1 r1
CMPI 1 r1
BEQ GG_Eat0_RIGHT3
BUC GG_Eat1_RIGHT3
GG_Normal_RIGHT3:
MOV r0 r1
MOVI 106 r0 //GHOST_RIGHT_6
STOR R0 R1
ADDI 1 R1 //get location right
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 105 r0 //GHOST_RIGHT_5
STOR r0 r1
RETX
GG_Eat0_RIGHT3:
MOV r0 r1
MOVI 50 R0 //E1GHOST_RIGHT_6
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 49 R0 //E1GHOST_RIGHT_5
STOR R0 R1
RETX
GG_Eat1_RIGHT3:
MOV r0 r1
MOVI 78 R0 //E2GHOST_RIGHT_6
STOR R0 R1
ADDI 1 R1
MOV r15 r14
JAL r6 SetPosition_WarpLeftSide
MOV r14 r15
MOVI 77 R0 //E2GHOST_RIGHT_5
STOR R0 R1 //LOAD INTO POSITION
RETX
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::END GreenGhostDraw GLYPH:::::::::::::::::::
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
INIT_GreenGhost:
LUI 255 r0 //make timer reset address
ORI 241 r0
LUI 4 r1 //set 512+256 miliseconds on timer //TIMER SET
STOR r1 r0
//set GreenGhost state to left0
LUI 50 r4
ORI 1 r4
MOVI 48 r1
STOR r1 r4
//put GreenGhost on initial spot in map
LUI 50 r4
LUI 63 r1 # make address for top corner in frame buffer
ORI 255 r1
MOVI 53 r8
MULI -19 r8
ADD r8 r1 # Offset by rows
ADDI -26 r1 # Offset by columns
STOR R1 r4
RETX
GreenGhost_isWallUP:
LUI 50 r0 //make address 12800 where GreenGhost location is stored
LOAD r0 r0 //save result back into r0
ADDI 53 r0 //increment r0 to get location of square above GreenGhost (53 adress spaces higher in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
GreenGhost_isWallDOWN:
LUI 50 r0 //green ghost location
LOAD r0 r0 //save result back into r0
ADDI -53 r0 //increment r0 to get location of square below GreenGhost (53 adress spaces lower in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
GreenGhost_isWallLEFT:
LUI 50 r0 //make address 12800 where GreenGhost location is stored
LOAD r0 r0 //save result back into r0
ADDI 1 r0 //increment r0 to get location of square left of GreenGhost (1 space higher in memory)
LOAD r0 r0 // LOAD glyph number
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
GreenGhost_isWallRIGHT:
LUI 50 r0 //make address 12800 where GreenGhost location is stored
LOAD r0 r0 //save result back into r0
ADDI -1 r0 //increment r0 to get location of square right of GreenGhost (1 space lower in memory)
LOAD r0 r0
MOVI 100 r9
MULI 8 r9
CMP r0 r9
SGE r0 // use Scond instruction to set r0 to 1 if r0 is greater or equal to 800, else 0 if not.
RETX // return to calling function
///::::::::::::::::::END GreenGhost STATE MACHINE::::::::::::::::::::::
///::::::::::::::::::END GreenGhost STATE MACHINE::::::::::::::::::::::
///::::::::::::::::::END GreenGhost STATE MACHINE::::::::::::::::::::::
///::::::::::::::::::STATE MACHINE HELPERS FOR ALL MACHINES::::::::::::::::
///check the position passed in r1, sets r1 to equal r1 if not on warp,
///otherwise sets r1 to warped position.
SetPosition_WarpLeftSide:
LUI 63 r7 # make address for checking location
ORI 255 r7
MOVI 53 r9
MULI -19 r9
ADD r9 r7 # Offset by rows
ADDI -12 r7 # Offset by columns
CMP r1 r7
BNE endWarpLeftSide
ADDI -28 r7
MOV r7 r1
endWarpLeftSide:
RETX
SetPosition_WarpRightSide:
LUI 63 r7 # make address for checking location
ORI 255 r7
MOVI 53 r9
MULI -19 r9
ADD r9 r7 # Offset by rows
ADDI -12 r7
ADDI -29 r7 # Offset by columns
CMP r1 r7
BNE endWarpRightSide
ADDI 28 r7
MOV r7 r1
endWarpRightSide:
RETX
FBpos_2_CPpos:
LUI 14 r7
MULI -1 r7
ADD r7 r1
RETX
CPpos_2_FBpos:
LUI 14 r7
ADD r7 r1
RETX
// The following functions assume 'state address' has been moved to r0
//**actorUP**
setStateUP0:
MOVI 16 r1
STOR r1 r0
RETX
setStateUP1:
MOVI 17 r1
STOR r1 r0
RETX
setStateUP2:
MOVI 18 r1
STOR r1 r0
RETX
setStateUP3:
MOVI 19 r1
STOR r1 r0
RETX
//**actorDOWN**
setStateDOWN0:
MOVI 32 r1
STOR r1 r0
RETX
setStateDOWN1:
MOVI 33 r1
STOR r1 r0
RETX
setStateDOWN2:
MOVI 34 r1
STOR r1 r0
RETX
setStateDOWN3:
MOVI 35 r1
STOR r1 r0
RETX
//**actorLEFT**
setStateLEFT0:
MOVI 48 r1
STOR r1 r0
RETX
setStateLEFT1:
MOVI 49 r1
STOR r1 r0
RETX
setStateLEFT2:
MOVI 50 r1
STOR r1 r0
RETX
setStateLEFT3:
MOVI 51 r1
STOR r1 r0
RETX
//**actorRIGHT**
setStateRIGHT0:
MOVI 64 r1
STOR r1 r0
RETX
setStateRIGHT1:
MOVI 65 r1
STOR r1 r0
RETX
setStateRIGHT2:
MOVI 66 r1
STOR r1 r0
RETX
setStateRIGHT3:
MOVI 67 r1
STOR r1 r0
RETX
//**pacmanDEAD**
setStateDEAD1:
MOVI 1 r1
STOR r1 r0
RETX
setStateDEAD2:
MOVI 2 r1
STOR r1 r0
RETX
setStateDEAD3:
MOVI 3 r1
STOR r1 r0
RETX
setStateDEAD4:
MOVI 4 r1
STOR r1 r0
RETX
/////:::::::::::END ALL STATE MACHINE LOGIC:::::::::::::::::://////
//CHECK_DIRECTION functions. Use only register r0 and ra for safety. This way when calling these functions,
//only the r0 and ra registers must be preserved first if they are important.
CheckRIGHT:
LUI 255 r0 //make right address in r0
ORI 248 r0
LOAD r0 r0 //save result back into r0
RETX
CheckLEFT:
LUI 255 r0 //make address in r0
ORI 249 r0
LOAD r0 r0 //save result back into r0
RETX //return
CheckUP:
LUI 255 r0
ORI 251 r0
LOAD r0 r0
RETX
CheckDOWN:
LUI 255 r0
ORI 250 r0
LOAD r0 r0
RETX
/////HELPER FUNCTIONS FOR MAIN GAME LOGIC ////
drawLivesLeft:
LUI 63 r1 # make address for writting location in frame buffer
ORI 255 r1
MOVI 53 r8
MULI -37 r8
ADD r8 r1 # Offset by rows
ADDI -14 r1 # Offset by columns
//zero out space where lives drawn
MOVI 0 r0 // number of lives drawn
MOVI 0 r2 // blank glyph
livesClearLoop:
CMPI 5 r0
BEQ endlivesClearLoop
STOR r2 r1
ADDI -1 r1
ADDI 1 r0
BUC livesClearLoop
endlivesClearLoop:
ADDI 5 r1 //reset address
LUI 51 r8 //lives left addr
ORI 244 r8 //lives left addr
LOAD r8 r8
MOVI 0 r0
MOVI 226 r2 //pman glyph
livesLoop:
CMP r0 r8
BEQ endlivesLoop
STOR r2 r1
ADDI -1 r1
ADDI 1 r0
BUC livesLoop
endlivesLoop:
RETX
initlevel:
//Initialize pill remaining counter in gamestate by MOVIng 244 Pills left on board to addr 13301
LUI 51 r4
ORI 245 r4
MOVI 244 r0
STOR r0 r4
//initialize map in fb only.
LUI 55 r0 // Make the address for where init function starts
ORI 182 r0 //
MOV r0 r3 // r3 current address of where we are reading from memory
LUI 63 r1 # make address for writting location in frame buffer
ORI 255 r1
MOVI 53 r8
MULI -5 r8
ADD r8 r1 # Offset by rows
ADDI -13 r1 # Offset by columns
MOVI 0 r6
loopi:
CMPI 31 r6
BEQ endloopi #this should support labels, jump endloopi
MOVI 0 r7
loopj:
CMPI 28 r7
BEQ endloopj #jump to endloopj
MOV r6 r4
MULI 53 r4
ADD r7 r4
MULI -1 r4
ADD r1 r4
LOAD r5 r3
STOR r5 r4
SUBI 1 r3
ADDI 1 r7
BUC loopj
endloopj:
ADDI 1 r6
BUC loopi
endloopi:
//make the copy of the map in memory in fbcp
LUI 55 r0 // Make the address for where init function starts
ORI 182 r0 //
MOV r0 r3 // r3 current address of where we are reading from memory
LUI 49 r1 # make address for writting location in frame buffer copy
ORI 255 r1
MOVI 53 r8
MULI -5 r8
ADD r8 r1 # Offset by rows
ADDI -13 r1 # Offset by columns
MOVI 0 r6
loopi2:
CMPI 31 r6
BEQ endloopi2 #this should support labels, jump endloopi
MOVI 0 r7
loopj2:
CMPI 28 r7
BEQ endloopj2 #jump to endloopj
MOV r6 r4
MULI 53 r4
ADD r7 r4
MULI -1 r4
ADD r1 r4
LOAD r5 r3
STOR r5 r4
SUBI 1 r3
ADDI 1 r7
BUC loopj2
endloopj2:
ADDI 1 r6
BUC loopi2
endloopi2:
RETX
//***************************************
//************Start Menu*****************
//***************************************
// A(114) - Z(139)
// !(140)
// 0(169) - 9(178)
start_menu:
// zero out map
MOV r15 r14
JAL r9 clear_screen
MOV r14 r15
MOVI 0 r8 // zero out r8 for toggle return address
LUI 63 r0 // top left most glyph address
ORI 255 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0 // offset rows by 4 down
ADDI -22 r0 // and 22 columns
MOVI 129 r1 // Store 'P'
STOR r1 r0
ADDI -1 r0
MOVI 114 r1 // Store 'A'
STOR r1 r0
ADDI -1 r0
MOV r0 r10 // save this location to draw closed mouth too
MOVI 245 r1 // Store 'pacman0'
STOR r1 r0
ADDI -1 r0
MOVI 126 r1 // Store 'M'
STOR r1 r0
ADDI -1 r0
MOVI 114 r1 // Store 'A'
STOR r1 r0
ADDI -1 r0
MOVI 127 r1 // Store 'N'
STOR r1 r0
ADDI -1 r0
MOVI 0 r1 // Store ' '
STOR r1 r0
ADDI -1 r0
MOVI 171 r1 // Store '2'
STOR r1 r0
ADDI -1 r0
LUI 1 r1 // Store 'pill'
ORI 15 r1
STOR r1 r0
ADDI -1 r0
MOVI 169 r1 // Store '0'
STOR r1 r0
ADDI 6 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0 // offset rows by 4 down
MOVI 129 r1 // Store 'P'
STOR r1 r0
ADDI -1 r0
MOVI 131 r1 // Store 'R'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 132 r1 // Store 'S'
STOR r1 r0
ADDI -1 r0
MOVI 132 r1 // Store 'S'
STOR r1 r0
ADDI 6 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
MOVI 133 r1 // Store 'T'
STOR r1 r0
ADDI -1 r0
MOVI 128 r1 // Store 'O'
STOR r1 r0
ADDI -1 r0
MOVI 0 r1 // Store ' '
STOR r1 r0
ADDI -1 r0
MOVI 115 r1 // Store 'B'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 120 r1 // Store 'G'
STOR r1 r0
ADDI -1 r0
MOVI 122 r1 // Store 'I'
STOR r1 r0
ADDI -1 r0
MOVI 127 r1 // Store 'N'
STOR r1 r0
ADDI 5 r0
ADDI 106 r0
ADDI 106 r0
LUI 255 r4 // start timer
ORI 231 r4
MOVI 250 r5 // .5 seconds (500 milliseconds)
ADDI 125 r5
ADDI 125 r5
STOR r5 r4
BUC flash_start
dead_menu:
// zero out map
MOV r15 r14
JAL r9 clear_screen
MOV r14 r15
MOVI 0 r8 // zero out r8 for toggle return address
LUI 63 r0 // top left most glyph address
ORI 255 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0 // offset rows by 4 down
ADDI -22 r0 // and 22 columns
MOVI 120 r1 // Store 'G'
STOR r1 r0
ADDI -1 r0
MOVI 114 r1 // Store 'A'
STOR r1 r0
ADDI -1 r0
MOV r0 r10 // save this location to draw closed mouth too
MOVI 126 r1 // Store 'M'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 0 r1 // Store ' '
STOR r1 r0
ADDI -1 r0
MOV r0 r10 // save this location to draw closed mouth too
MOVI 245 r1 // Store 'pacman0'
STOR r1 r0
ADDI -1 r0
MOVI 135 r1 // Store 'V'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 131 r1 // Store 'R'
STOR r1 r0
ADDI -1 r0
MOVI 140 r1 // Store '!'
STOR r1 r0
ADDI 6 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0 // offset rows by 4 down
MOVI 129 r1 // Store 'P'
STOR r1 r0
ADDI -1 r0
MOVI 131 r1 // Store 'R'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 132 r1 // Store 'S'
STOR r1 r0
ADDI -1 r0
MOVI 132 r1 // Store 'S'
STOR r1 r0
ADDI 6 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
ADDI -106 r0
MOVI 133 r1 // Store 'T'
STOR r1 r0
ADDI -1 r0
MOVI 128 r1 // Store 'O'
STOR r1 r0
ADDI -1 r0
MOVI 0 r1 // Store ' '
STOR r1 r0
ADDI -1 r0
MOVI 115 r1 // Store 'B'
STOR r1 r0
ADDI -1 r0
MOVI 118 r1 // Store 'E'
STOR r1 r0
ADDI -1 r0
MOVI 120 r1 // Store 'G'
STOR r1 r0
ADDI -1 r0
MOVI 122 r1 // Store 'I'
STOR r1 r0
ADDI -1 r0
MOVI 127 r1 // Store 'N'
STOR r1 r0
ADDI 5 r0
ADDI 106 r0
ADDI 106 r0
LUI 255 r4 // start timer
ORI 231 r4
MOVI 250 r5 // .5 seconds (500 milliseconds)
ADDI 125 r5
ADDI 125 r5
STOR r5 r4
BUC flash_start
flash_start:
MOV r0 r7
//check if start button has been pressed on NES controller
MOV r15 r14
JAL r9 Homescreencheckstart
MOV r14 r15
LUI 255 r3 // calculate timer return value address
ORI 230 r3
LOAD r3 r3 // load timer rv into r3
CMPI 1 r3
BNE choose_draw
MOV r15 r14
JAL r9 toggle
MOV r14 r15
choose_draw: // choose whether to draw 'start' or 'blank'
CMPI 1 r8
BNE draw_blank
draw_start:
MOVI 205 r1 // Draw closed pacmanRIGHT0
STOR r1 r10
MOVI 132 r1 // Store 'S'
STOR r1 r7
ADDI -1 r7
MOVI 133 r1 // Store 'T'
STOR r1 r7
ADDI -1 r7
MOVI 114 r1 // Store 'A'
STOR r1 r7
ADDI -1 r7
MOVI 131 r1 // Store 'R'
STOR r1 r7
ADDI -1 r7
MOVI 133 r1 // Store 'T'
STOR r1 r7
JUC r9 flash_start
draw_blank:
MOVI 245 r1
STOR r1 r10
MOVI 0 r1 // otherwise draw nothing
STOR r1 r7
ADDI -1 r7
MOVI 0 r1
STOR r1 r7
ADDI -1 r7
MOVI 0 r1
STOR r1 r7
ADDI -1 r7
MOVI 0 r1
STOR r1 r7
ADDI -1 r7
MOVI 0 r1
STOR r1 r7
JUC r9 flash_start
toggle:
XORI 1 r8 // toggle rv
LUI 255 r4 // reset timer
ORI 231 r4
LUI 2 r5 // really close to 500, maybe 512
STOR r5 r4
RETX
Homescreencheckstart:
MOVI 0 r2 // Check 'START'
LUI 255 r2
ORI 252 r2
LOAD r2 r2
CMPI 1 r2
JEQ r9 start_Game // if start asserted, start game
RETX
clear_screen:
MOV r2 r10 //save this register
MOV r3 r11 // save this register
MOVI 0 r0 // zero-out temp
LUI 63 r2 // create glyph address
ORI 255 r2
LUI 8 r3 // create counter constraint of 2120 (# of glyphs)
ORI 72 r3
MOVI 0 r1 // glyph 0 to be drawn
clearscreenloop:
STOR r1 r2 // draw glyph
ADDI -1 r2 // decrement address pointer
ADDI 1 r0 // increment counter
CMP r0 r3 // check counter <= 2120
BLT clearscreenloop
MOV r10 r2 // else restore the reg's
MOV r11 r3
RETX
//*** end start menu**///
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "op/quantize_linear.hpp"
#include <cstdint>
#include <memory>
#include <numeric>
#include <tuple>
#include "default_opset.hpp"
#include "exceptions.hpp"
#include "ngraph/axis_set.hpp"
#include "ngraph/builder/reshape.hpp"
#include "ngraph/shape.hpp"
#include "ngraph/type/element_type.hpp"
#include "ngraph/validation_util.hpp"
#include "utils/reshape.hpp"
namespace ngraph {
namespace onnx_import {
namespace op {
namespace detail {
namespace {
Output<ngraph::Node> get_zero_point(const OutputVector& inputs) {
if (inputs.size() > 2) {
return inputs.at(2);
} else {
return std::make_shared<default_opset::Constant>(element::u8, Shape{1}, std::uint8_t(0));
}
}
void validate_zero_point_type(const Node& onnx_node, const Output<ngraph::Node>& y_zero_point) {
const auto& y_zero_point_et = y_zero_point.get_element_type();
CHECK_VALID_NODE(onnx_node,
y_zero_point_et.is_static() && (y_zero_point_et == element::u8 || y_zero_point_et == element::i8),
"\"y_zero_point\" input data type must be static and of 8-bit "
"integer type.");
}
Output<ngraph::Node> validate_scale(const Node& onnx_node, const Output<ngraph::Node>& y_scale) {
const auto& y_scale_et = y_scale.get_element_type();
CHECK_VALID_NODE(onnx_node, y_scale_et.is_static(), "\"y_scale\" input data type must be static.");
if (y_scale_et != element::f32) {
return std::make_shared<default_opset::Convert>(y_scale, element::f32);
}
return y_scale;
}
Output<ngraph::Node> validate_data(const Node& onnx_node, const Output<ngraph::Node>& data) {
const auto& data_et = data.get_element_type();
CHECK_VALID_NODE(onnx_node, data_et.is_static(), "\"x\" input data type must be static.");
if (data_et != element::f32) {
return std::make_shared<default_opset::Convert>(data, element::f32);
}
return data;
}
std::tuple<std::shared_ptr<ngraph::Node>, std::shared_ptr<ngraph::Node>> get_output_bands(
const element::Type& destination_type,
const element::Type& data_type) {
std::shared_ptr<ngraph::Node> output_low;
std::shared_ptr<ngraph::Node> output_high;
if (destination_type == element::i8) {
output_low = std::make_shared<default_opset::Constant>(data_type, Shape{1}, -128);
output_high = std::make_shared<default_opset::Constant>(data_type, Shape{1}, 127);
} else {
output_low = std::make_shared<default_opset::Constant>(data_type, Shape{1}, 0);
output_high = std::make_shared<default_opset::Constant>(data_type, Shape{1}, 255);
}
return std::make_tuple(output_low, output_high);
}
std::tuple<std::shared_ptr<ngraph::Node>, std::shared_ptr<ngraph::Node>> get_input_bands(
const Output<ngraph::Node>& y_scale,
const Output<ngraph::Node>& y_zero_point,
const std::shared_ptr<ngraph::Node>& output_low,
const std::shared_ptr<ngraph::Node>& output_high,
const element::Type& data_type) {
std::shared_ptr<ngraph::Node> input_low;
std::shared_ptr<ngraph::Node> input_high;
const auto& zero_point = std::make_shared<default_opset::Convert>(y_zero_point, data_type);
input_low =
std::make_shared<default_opset::Multiply>(y_scale,
std::make_shared<default_opset::Subtract>(output_low, zero_point));
if (auto constant = get_constant_from_source(input_low))
input_low = constant;
input_high =
std::make_shared<default_opset::Multiply>(y_scale,
std::make_shared<default_opset::Subtract>(output_high, zero_point));
if (auto constant = get_constant_from_source(input_high))
input_high = constant;
return std::make_tuple(input_low, input_high);
}
} // namespace
std::shared_ptr<ngraph::Node> make_fake_quantize(const Output<ngraph::Node>& y_scale,
const Output<ngraph::Node>& y_zero_point,
const Output<ngraph::Node>& data) {
const element::Type& destination_type = y_zero_point.get_element_type();
const element::Type& data_type = data.get_element_type();
std::shared_ptr<ngraph::Node> output_low;
std::shared_ptr<ngraph::Node> output_high;
std::tie(output_low, output_high) = detail::get_output_bands(destination_type, data_type);
std::shared_ptr<ngraph::Node> input_low;
std::shared_ptr<ngraph::Node> input_high;
std::tie(input_low, input_high) =
detail::get_input_bands(y_scale, y_zero_point, output_low, output_high, data_type);
const std::size_t levels = 1 << destination_type.bitwidth();
return std::make_shared<default_opset::Convert>(
std::make_shared<default_opset::FakeQuantize>(data, input_low, input_high, output_low, output_high, levels),
destination_type);
}
} // namespace detail
namespace set_1 {
OutputVector quantize_linear(const Node& node) {
OutputVector inputs{node.get_ng_inputs()};
auto x = inputs.at(0);
auto y_scale = inputs.at(1);
auto y_zero_point = detail::get_zero_point(inputs);
x = detail::validate_data(node, x);
detail::validate_zero_point_type(node, y_zero_point);
y_scale = detail::validate_scale(node, y_scale);
return {detail::make_fake_quantize(y_scale, y_zero_point, x)};
}
} // namespace set_1
namespace set_13 {
namespace {
OutputVector quantize_linear(Output<ngraph::Node> x,
Output<ngraph::Node> y_scale,
Output<ngraph::Node> y_zero_point,
int64_t axis,
Node node) {
namespace detail = ngraph::onnx_import::op::detail;
x = detail::validate_data(node, x);
detail::validate_zero_point_type(node, y_zero_point);
y_scale = detail::validate_scale(node, y_scale);
const auto& x_shape = x.get_partial_shape();
axis = normalize_axis(node.get_description(), axis, x_shape.rank());
const auto& y_scale_shape = y_scale.get_partial_shape();
const auto& y_zero_point_shape = y_zero_point.get_partial_shape();
if (y_scale_shape.rank().is_static() && y_scale_shape.rank().get_length() == 1 && x_shape.rank().is_static() &&
x_shape[axis].is_static()) {
CHECK_VALID_NODE(node,
y_scale_shape[0].same_scheme(x_shape[axis]),
"The number of quantization scale elements ",
y_scale_shape[0],
" must match the number of respective input data axis size: ",
x_shape[axis]);
Shape target_shape(x_shape.rank().get_length(), 1);
target_shape[axis] = static_cast<size_t>(x_shape[axis].get_length());
y_scale = builder::opset1::reshape(y_scale, target_shape);
}
if (y_zero_point_shape.rank().is_static() && y_zero_point_shape.rank().get_length() == 1 &&
x_shape.rank().is_static() && x_shape[axis].is_static()) {
CHECK_VALID_NODE(node,
y_zero_point_shape[0].same_scheme(x_shape[axis]),
"The number of quantization zero point elements ",
y_zero_point_shape[0],
" must match the number of respective input data axis size: ",
x_shape[axis]);
Shape target_shape(x_shape.rank().get_length(), 1);
target_shape[axis] = static_cast<size_t>(x_shape[axis].get_length());
y_zero_point = builder::opset1::reshape(y_zero_point, target_shape);
}
return {detail::make_fake_quantize(y_scale, y_zero_point, x)};
}
} // namespace
OutputVector quantize_linear(const Node& node) {
const OutputVector inputs{node.get_ng_inputs()};
NGRAPH_CHECK(2 <= inputs.size() && inputs.size() <= 3,
"The QuantizeLinear op expects 2 required and one optional "
"input. Got: ",
inputs.size());
const auto x = inputs[0];
auto scale = inputs[1];
auto zero_point = op::detail::get_zero_point(inputs);
return quantize_linear(x, scale, zero_point, node.get_attribute_value<int64_t>("axis", 1), node);
}
} // namespace set_13
} // namespace op
} // namespace onnx_import
} // namespace ngraph
|
; A025445: Expansion of 1/((1-2x)(1-3x)(1-4x)(1-7x)).
; Submitted by Christian Krause
; 1,16,167,1454,11529,86772,633739,4547818,32300477,228024368,1604029791,11260172742,78950652145,553177103404,3874344193523,27128870214626,189936063951333,1329688724613480,9308367341848135
mov $1,1
mov $2,$0
mov $3,$0
lpb $2
mov $0,$3
mul $1,2
sub $2,1
sub $0,$2
seq $0,16801 ; Expansion of 1/((1-3x)(1-4x)(1-7x)).
sub $0,$1
mul $1,2
add $1,$0
lpe
mov $0,$1
|
%ifdef CONFIG
{
"RegData": {
"XMM1": ["0xee65166050ac19a0", "0xfe1eb34a32b1a0b2"],
"XMM2": ["0x28a18cdd2d20fb20", "0x1d6fa69c44caed04"],
"XMM3": ["0xf514cf89a88edcde", "0x01e3dc4237becfcf"],
"XMM4": ["0x0004b0350897f35a", "0x03cd750e809c18d0"],
"XMM5": ["0x066a5fa4ad5148c8", "0x00bca2da387e55a2"],
"XMM6": ["0x1e0f03011112ed90", "0x18c90f3ec0d58440"],
"XMM7": ["0xee94b334b2358df2", "0x1b82409d7ae7fa28"],
"XMM8": ["0xed12f34e8fb5e098", "0xd83d0ba0ff8632db"]
}
}
%endif
lea rdx, [rel .data]
movaps xmm1, [rdx + 16 * 0]
movaps xmm2, [rdx + 16 * 1]
movaps xmm3, [rdx + 16 * 2]
movaps xmm4, [rdx + 16 * 3]
movaps xmm5, [rdx + 16 * 4]
movaps xmm6, [rdx + 16 * 5]
movaps xmm7, [rdx + 16 * 6]
movaps xmm8, [rdx + 16 * 7]
pmuldq xmm1, [rdx + 16 * 8]
pmuldq xmm2, [rdx + 16 * 9]
pmuldq xmm3, [rdx + 16 * 10]
pmuldq xmm4, [rdx + 16 * 11]
pmuldq xmm5, [rdx + 16 * 12]
pmuldq xmm6, [rdx + 16 * 13]
pmuldq xmm7, [rdx + 16 * 14]
pmuldq xmm8, [rdx + 16 * 15]
hlt
align 16
; 256bytes of random data
.data:
db 0xe0, 0xfc, 0x2b, 0xa1, 0x06, 0x4f, 0x6c, 0xa7, 0x0f, 0x06, 0x6a, 0x1e, 0x7f, 0x76, 0x80, 0x9b
db 0xe0, 0x56, 0xed, 0xaa, 0xf3, 0xc3, 0x68, 0x68, 0xde, 0xe6, 0xe6, 0x94, 0xe2, 0xe9, 0xfc, 0xf0
db 0x6e, 0x35, 0xa8, 0x54, 0xd7, 0xab, 0x8b, 0x6c, 0x77, 0x5f, 0x92, 0xca, 0x25, 0xa6, 0x7e, 0x27
db 0xc7, 0xcd, 0x73, 0xec, 0x95, 0xd6, 0x6f, 0x6a, 0xbb, 0xae, 0xf2, 0xbb, 0x27, 0xb9, 0xa1, 0xdd
db 0x73, 0x4d, 0xd1, 0xc7, 0xd5, 0x2c, 0x31, 0x88, 0xfe, 0xe7, 0xdb, 0xfd, 0x1e, 0x1e, 0x09, 0x7f
db 0x14, 0xfa, 0x4e, 0x95, 0xef, 0xe6, 0x9a, 0xf2, 0xa0, 0x42, 0x62, 0x9a, 0xa4, 0xa8, 0x73, 0x82
db 0x0e, 0x0f, 0x16, 0x82, 0x38, 0x07, 0x12, 0x32, 0x07, 0x35, 0x92, 0xc1, 0x63, 0x07, 0x78, 0xb3
db 0xcb, 0x46, 0x19, 0x57, 0x2b, 0x37, 0x2a, 0x46, 0x1f, 0x04, 0x0e, 0x79, 0x3d, 0xcd, 0x8d, 0xa3
db 0x2b, 0xf3, 0x86, 0x2f, 0xab, 0xba, 0x57, 0x30, 0x2e, 0xd6, 0x2c, 0xf0, 0x46, 0x4f, 0x3f, 0xef
db 0xef, 0xd1, 0xbb, 0x85, 0x34, 0x4b, 0x3c, 0xde, 0x9e, 0x48, 0xa3, 0xb9, 0x8d, 0x71, 0xe3, 0x9d
db 0x09, 0x72, 0xfb, 0xde, 0x8a, 0x32, 0x50, 0x9d, 0x69, 0x98, 0xf1, 0xf6, 0x52, 0xeb, 0xf7, 0xee
db 0xd6, 0x99, 0xc2, 0xff, 0x30, 0x1c, 0x02, 0xce, 0x70, 0x05, 0xb2, 0xf1, 0x56, 0x9c, 0x0e, 0xa6
db 0x18, 0x62, 0xc4, 0xe2, 0x86, 0x38, 0x76, 0x30, 0x2f, 0xa1, 0xe4, 0xa7, 0x0e, 0x5d, 0x53, 0xeb
db 0x14, 0x45, 0xe0, 0xb7, 0xe1, 0xe8, 0x02, 0x68, 0x1a, 0xfe, 0x8e, 0xc1, 0x8f, 0xf2, 0xeb, 0x46
db 0x7f, 0x5d, 0x6a, 0x23, 0x46, 0x97, 0x2e, 0x03, 0x98, 0x12, 0x32, 0x8f, 0x54, 0x76, 0x59, 0xac
db 0xc8, 0x76, 0x5f, 0xc8, 0x71, 0x0c, 0xd3, 0xb6, 0xc5, 0x19, 0xea, 0xab, 0xa6, 0x2c, 0x1d, 0x88
|
%define ARCH_ARM 0
%define ARCH_MIPS 0
%define ARCH_X86 1
%define ARCH_X86_64 0
%define ARCH_PPC 0
%define HAVE_NEON 0
%define HAVE_NEON_ASM 0
%define HAVE_MIPS32 0
%define HAVE_DSPR2 0
%define HAVE_MSA 0
%define HAVE_MIPS64 0
%define HAVE_MMX 1
%define HAVE_SSE 1
%define HAVE_SSE2 1
%define HAVE_SSE3 1
%define HAVE_SSSE3 1
%define HAVE_SSE4_1 1
%define HAVE_AVX 1
%define HAVE_AVX2 1
%define HAVE_AVX512 0
%define HAVE_VSX 0
%define HAVE_MMI 0
%define HAVE_VPX_PORTS 1
%define HAVE_PTHREAD_H 0
%define HAVE_UNISTD_H 0
%define CONFIG_DEPENDENCY_TRACKING 1
%define CONFIG_EXTERNAL_BUILD 1
%define CONFIG_INSTALL_DOCS 0
%define CONFIG_INSTALL_BINS 1
%define CONFIG_INSTALL_LIBS 1
%define CONFIG_INSTALL_SRCS 0
%define CONFIG_DEBUG 0
%define CONFIG_GPROF 0
%define CONFIG_GCOV 0
%define CONFIG_RVCT 0
%define CONFIG_GCC 0
%define CONFIG_MSVS 1
%define CONFIG_PIC 1
%define CONFIG_BIG_ENDIAN 0
%define CONFIG_CODEC_SRCS 0
%define CONFIG_DEBUG_LIBS 0
%define CONFIG_DEQUANT_TOKENS 0
%define CONFIG_DC_RECON 0
%define CONFIG_RUNTIME_CPU_DETECT 1
%define CONFIG_POSTPROC 1
%define CONFIG_VP9_POSTPROC 1
%define CONFIG_MULTITHREAD 1
%define CONFIG_INTERNAL_STATS 0
%define CONFIG_VP8_ENCODER 1
%define CONFIG_VP8_DECODER 1
%define CONFIG_VP9_ENCODER 1
%define CONFIG_VP9_DECODER 1
%define CONFIG_VP8 1
%define CONFIG_VP9 1
%define CONFIG_ENCODERS 1
%define CONFIG_DECODERS 1
%define CONFIG_STATIC_MSVCRT 0
%define CONFIG_SPATIAL_RESAMPLING 1
%define CONFIG_REALTIME_ONLY 1
%define CONFIG_ONTHEFLY_BITPACKING 0
%define CONFIG_ERROR_CONCEALMENT 0
%define CONFIG_SHARED 0
%define CONFIG_STATIC 1
%define CONFIG_SMALL 0
%define CONFIG_POSTPROC_VISUALIZER 0
%define CONFIG_OS_SUPPORT 1
%define CONFIG_UNIT_TESTS 1
%define CONFIG_WEBM_IO 1
%define CONFIG_LIBYUV 1
%define CONFIG_DECODE_PERF_TESTS 0
%define CONFIG_ENCODE_PERF_TESTS 0
%define CONFIG_MULTI_RES_ENCODING 1
%define CONFIG_TEMPORAL_DENOISING 1
%define CONFIG_VP9_TEMPORAL_DENOISING 1
%define CONFIG_CONSISTENT_RECODE 0
%define CONFIG_COEFFICIENT_RANGE_CHECKING 0
%define CONFIG_VP9_HIGHBITDEPTH 1
%define CONFIG_BETTER_HW_COMPATIBILITY 0
%define CONFIG_EXPERIMENTAL 0
%define CONFIG_SIZE_LIMIT 1
%define CONFIG_ALWAYS_ADJUST_BPM 0
%define CONFIG_FP_MB_STATS 0
%define CONFIG_EMULATE_HARDWARE 0
%define CONFIG_NON_GREEDY_MV 0
%define CONFIG_ML_VAR_PARTITION 0
%define DECODE_WIDTH_LIMIT 16384
%define DECODE_HEIGHT_LIMIT 16384
|
; A060758: a(n) = 5^(n^2).
; Submitted by Christian Krause
; 1,5,625,1953125,152587890625,298023223876953125,14551915228366851806640625,17763568394002504646778106689453125,542101086242752217003726400434970855712890625,413590306276513837435704346034981426782906055450439453125,7888609052210118054117285652827862296732064351090230047702789306640625,3761581922631320025499956919111186169019729781670680068828005460090935230255126953125,44841550858394146269559346665277316200968382140048504696226185084473314645947539247572422027587890625
pow $0,2
mov $1,5
pow $1,$0
mov $0,$1
|
;*****************************************************************************
;* dct-32.asm: x86_32 transform and zigzag
;*****************************************************************************
;* Copyright (C) 2003-2015 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;* Holger Lubitz <holger@lubitz.org>
;* Laurent Aimar <fenrir@via.ecp.fr>
;* Min Chen <chenm001.163.com>
;* Christian Heine <sennindemokrit@gmx.net>
;*
;* This program is free software; you can redistribute it and/or modify
;* it under the terms of the GNU General Public License as published by
;* the Free Software Foundation; either version 2 of the License, or
;* (at your option) any later version.
;*
;* 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 General Public License for more details.
;*
;* You should have received a copy of the GNU General Public License
;* along with this program; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
;*
;* This program is also available under a commercial proprietary license.
;* For more information, contact us at licensing@x264.com.
;*****************************************************************************
%include "x86inc.asm"
%include "x86util.asm"
SECTION .text
cextern pd_32
cextern pw_pixel_max
cextern pw_2
cextern pw_m2
cextern pw_32
cextern hsub_mul
%macro SPILL_SHUFFLE 3-* ; ptr, list of regs, list of memory offsets
%xdefine %%base %1
%rep %0/2
%xdefine %%tmp m%2
%rotate %0/2
mova [%%base + %2*16], %%tmp
%rotate 1-%0/2
%endrep
%endmacro
%macro UNSPILL_SHUFFLE 3-*
%xdefine %%base %1
%rep %0/2
%xdefine %%tmp m%2
%rotate %0/2
mova %%tmp, [%%base + %2*16]
%rotate 1-%0/2
%endrep
%endmacro
%macro SPILL 2+ ; assume offsets are the same as reg numbers
SPILL_SHUFFLE %1, %2, %2
%endmacro
%macro UNSPILL 2+
UNSPILL_SHUFFLE %1, %2, %2
%endmacro
; in: size, m0..m7
; out: 0,4,6 in memory at %10,%11,%12, rest in regs
%macro DCT8_1D 12
SUMSUB_BA %1, %9, %2 ; %9 = s07, %2 = d07
SUMSUB_BA %1, %8, %3 ; %8 = s16, %3 = d16
SUMSUB_BA %1, %7, %4 ; %7 = s25, %4 = d25
SUMSUB_BA %1, %6, %5 ; %6 = s34, %5 = d34
SUMSUB_BA %1, %6, %9 ; %6 = a0, %9 = a2
SUMSUB_BA %1, %7, %8 ; %7 = a1, %8 = a3
SUMSUB_BA %1, %7, %6 ; %7 = dst0, %6 = dst4
mova %10, m%7
mova %11, m%6
psra%1 m%7, m%8, 1 ; a3>>1
padd%1 m%7, m%9 ; a2 + (a3>>1)
psra%1 m%9, 1 ; a2>>1
psub%1 m%9, m%8 ; (a2>>1) - a3
mova %12, m%9
psra%1 m%6, m%4, 1
padd%1 m%6, m%4 ; d25+(d25>>1)
psub%1 m%8, m%2, m%5 ; a5 = d07-d34-(d25+(d25>>1))
psub%1 m%8, m%6
psra%1 m%6, m%3, 1
padd%1 m%6, m%3 ; d16+(d16>>1)
padd%1 m%9, m%2, m%5
psub%1 m%9, m%6 ; a6 = d07+d34-(d16+(d16>>1))
psra%1 m%6, m%2, 1
padd%1 m%6, m%2 ; d07+(d07>>1)
padd%1 m%6, m%3
padd%1 m%6, m%4 ; a4 = d16+d25+(d07+(d07>>1))
psra%1 m%2, m%5, 1
padd%1 m%2, m%5 ; d34+(d34>>1)
padd%1 m%2, m%3
psub%1 m%2, m%4 ; a7 = d16-d25+(d34+(d34>>1))
psra%1 m%5, m%2, 2
padd%1 m%5, m%6 ; a4 + (a7>>2)
psra%1 m%4, m%9, 2
padd%1 m%4, m%8 ; a5 + (a6>>2)
psra%1 m%6, 2
psra%1 m%8, 2
psub%1 m%6, m%2 ; (a4>>2) - a7
psub%1 m%9, m%8 ; a6 - (a5>>2)
SWAP %3, %5, %4, %7, %9, %6
%endmacro
; in: size, m[1,2,3,5,6,7], 0,4 in mem at %10,%11
; out: m0..m7
%macro IDCT8_1D 11
psra%1 m%2, m%4, 1
psra%1 m%6, m%8, 1
psub%1 m%2, m%8
padd%1 m%6, m%4
psra%1 m%8, m%3, 1
padd%1 m%8, m%3
padd%1 m%8, m%5
padd%1 m%8, m%7
psra%1 m%4, m%7, 1
padd%1 m%4, m%7
padd%1 m%4, m%9
psub%1 m%4, m%3
psub%1 m%3, m%5
psub%1 m%7, m%5
padd%1 m%3, m%9
psub%1 m%7, m%9
psra%1 m%5, 1
psra%1 m%9, 1
psub%1 m%3, m%5
psub%1 m%7, m%9
psra%1 m%5, m%8, 2
psra%1 m%9, m%4, 2
padd%1 m%5, m%7
padd%1 m%9, m%3
psra%1 m%7, 2
psra%1 m%3, 2
psub%1 m%8, m%7
psub%1 m%3, m%4
mova m%4, %10
mova m%7, %11
SUMSUB_BA %1, %7, %4
SUMSUB_BA %1, %6, %7
SUMSUB_BA %1, %2, %4
SUMSUB_BA %1, %8, %6
SUMSUB_BA %1, %3, %2
SUMSUB_BA %1, %9, %4
SUMSUB_BA %1, %5, %7
SWAP %2, %4
SWAP %6, %8
SWAP %2, %6, %7
SWAP %4, %9, %8
%endmacro
%if HIGH_BIT_DEPTH
%macro SUB8x8_DCT8 0
cglobal sub8x8_dct8, 3,3,8
global current_function %+ .skip_prologue
.skip_prologue:
LOAD_DIFF8x4 0,1,2,3, none,none, r1, r2
LOAD_DIFF8x4 4,5,6,7, none,none, r1, r2
DCT8_1D w, 0,1,2,3,4,5,6,7, [r0],[r0+0x10],[r0+0x50]
mova m0, [r0]
mova [r0+0x30], m5
mova [r0+0x70], m7
TRANSPOSE4x4W 0,1,2,3,4
WIDEN_SXWD 0,4
WIDEN_SXWD 1,5
WIDEN_SXWD 2,6
WIDEN_SXWD 3,7
DCT8_1D d, 0,4,1,5,2,6,3,7, [r0],[r0+0x80],[r0+0xC0]
mova [r0+0x20], m4
mova [r0+0x40], m1
mova [r0+0x60], m5
mova [r0+0xA0], m6
mova [r0+0xE0], m7
mova m4, [r0+0x10]
mova m5, [r0+0x30]
mova m6, [r0+0x50]
mova m7, [r0+0x70]
TRANSPOSE4x4W 4,5,6,7,0
WIDEN_SXWD 4,0
WIDEN_SXWD 5,1
WIDEN_SXWD 6,2
WIDEN_SXWD 7,3
DCT8_1D d,4,0,5,1,6,2,7,3, [r0+0x10],[r0+0x90],[r0+0xD0]
mova [r0+0x30], m0
mova [r0+0x50], m5
mova [r0+0x70], m1
mova [r0+0xB0], m2
mova [r0+0xF0], m3
ret
%endmacro ; SUB8x8_DCT8
INIT_XMM sse2
SUB8x8_DCT8
INIT_XMM sse4
SUB8x8_DCT8
INIT_XMM avx
SUB8x8_DCT8
%macro ADD8x8_IDCT8 0
cglobal add8x8_idct8, 2,2
add r1, 128
global current_function %+ .skip_prologue
.skip_prologue:
UNSPILL_SHUFFLE r1, 1,2,3,5,6,7, -6,-4,-2,2,4,6
IDCT8_1D d,0,1,2,3,4,5,6,7,[r1-128],[r1+0]
mova [r1+0], m4
TRANSPOSE4x4D 0,1,2,3,4
paddd m0, [pd_32]
mova m4, [r1+0]
SPILL_SHUFFLE r1, 0,1,2,3, -8,-6,-4,-2
TRANSPOSE4x4D 4,5,6,7,3
paddd m4, [pd_32]
SPILL_SHUFFLE r1, 4,5,6,7, 0,2,4,6
UNSPILL_SHUFFLE r1, 1,2,3,5,6,7, -5,-3,-1,3,5,7
IDCT8_1D d,0,1,2,3,4,5,6,7,[r1-112],[r1+16]
mova [r1+16], m4
TRANSPOSE4x4D 0,1,2,3,4
mova m4, [r1+16]
mova [r1-112], m0
TRANSPOSE4x4D 4,5,6,7,0
SPILL_SHUFFLE r1, 4,5,6,7, 1,3,5,7
UNSPILL_SHUFFLE r1, 5,6,7, -6,-4,-2
IDCT8_1D d,4,5,6,7,0,1,2,3,[r1-128],[r1-112]
SPILL_SHUFFLE r1, 4,5,6,7,0,1,2,3, -8,-7,-6,-5,-4,-3,-2,-1
UNSPILL_SHUFFLE r1, 1,2,3,5,6,7, 2,4,6,3,5,7
IDCT8_1D d,0,1,2,3,4,5,6,7,[r1+0],[r1+16]
SPILL_SHUFFLE r1, 7,6,5, 7,6,5
mova m7, [pw_pixel_max]
pxor m6, m6
mova m5, [r1-128]
STORE_DIFF m5, m0, m6, m7, [r0+0*FDEC_STRIDEB]
mova m0, [r1-112]
STORE_DIFF m0, m1, m6, m7, [r0+1*FDEC_STRIDEB]
mova m0, [r1-96]
STORE_DIFF m0, m2, m6, m7, [r0+2*FDEC_STRIDEB]
mova m0, [r1-80]
STORE_DIFF m0, m3, m6, m7, [r0+3*FDEC_STRIDEB]
mova m0, [r1-64]
STORE_DIFF m0, m4, m6, m7, [r0+4*FDEC_STRIDEB]
mova m0, [r1-48]
mova m1, [r1+80]
STORE_DIFF m0, m1, m6, m7, [r0+5*FDEC_STRIDEB]
mova m0, [r1-32]
mova m1, [r1+96]
STORE_DIFF m0, m1, m6, m7, [r0+6*FDEC_STRIDEB]
mova m0, [r1-16]
mova m1, [r1+112]
STORE_DIFF m0, m1, m6, m7, [r0+7*FDEC_STRIDEB]
RET
%endmacro ; ADD8x8_IDCT8
INIT_XMM sse2
ADD8x8_IDCT8
INIT_XMM avx
ADD8x8_IDCT8
%else ; !HIGH_BIT_DEPTH
INIT_MMX
ALIGN 16
load_diff_4x8_mmx:
LOAD_DIFF m0, m7, none, [r1+0*FENC_STRIDE], [r2+0*FDEC_STRIDE]
LOAD_DIFF m1, m7, none, [r1+1*FENC_STRIDE], [r2+1*FDEC_STRIDE]
LOAD_DIFF m2, m7, none, [r1+2*FENC_STRIDE], [r2+2*FDEC_STRIDE]
LOAD_DIFF m3, m7, none, [r1+3*FENC_STRIDE], [r2+3*FDEC_STRIDE]
LOAD_DIFF m4, m7, none, [r1+4*FENC_STRIDE], [r2+4*FDEC_STRIDE]
LOAD_DIFF m5, m7, none, [r1+5*FENC_STRIDE], [r2+5*FDEC_STRIDE]
movq [r0], m0
LOAD_DIFF m6, m7, none, [r1+6*FENC_STRIDE], [r2+6*FDEC_STRIDE]
LOAD_DIFF m7, m0, none, [r1+7*FENC_STRIDE], [r2+7*FDEC_STRIDE]
movq m0, [r0]
ret
cglobal dct8_mmx
DCT8_1D w,0,1,2,3,4,5,6,7,[r0],[r0+0x40],[r0+0x60]
SAVE_MM_PERMUTATION
ret
;-----------------------------------------------------------------------------
; void sub8x8_dct8( int16_t dct[8][8], uint8_t *pix1, uint8_t *pix2 )
;-----------------------------------------------------------------------------
cglobal sub8x8_dct8_mmx, 3,3
global sub8x8_dct8_mmx.skip_prologue
.skip_prologue:
RESET_MM_PERMUTATION
call load_diff_4x8_mmx
call dct8_mmx
UNSPILL r0, 0
TRANSPOSE4x4W 0,1,2,3,4
SPILL r0, 0,1,2,3
UNSPILL r0, 4,6
TRANSPOSE4x4W 4,5,6,7,0
SPILL r0, 4,5,6,7
RESET_MM_PERMUTATION
add r1, 4
add r2, 4
add r0, 8
call load_diff_4x8_mmx
sub r1, 4
sub r2, 4
call dct8_mmx
sub r0, 8
UNSPILL r0+8, 4,6
TRANSPOSE4x4W 4,5,6,7,0
SPILL r0+8, 4,5,6,7
UNSPILL r0+8, 0
TRANSPOSE4x4W 0,1,2,3,5
UNSPILL r0, 4,5,6,7
SPILL_SHUFFLE r0, 0,1,2,3, 4,5,6,7
movq mm4, m6 ; depends on the permutation to not produce conflicts
movq mm0, m4
movq mm1, m5
movq mm2, mm4
movq mm3, m7
RESET_MM_PERMUTATION
UNSPILL r0+8, 4,5,6,7
add r0, 8
call dct8_mmx
sub r0, 8
SPILL r0+8, 1,2,3,5,7
RESET_MM_PERMUTATION
UNSPILL r0, 0,1,2,3,4,5,6,7
call dct8_mmx
SPILL r0, 1,2,3,5,7
ret
cglobal idct8_mmx
IDCT8_1D w,0,1,2,3,4,5,6,7,[r1+0],[r1+64]
SAVE_MM_PERMUTATION
ret
%macro ADD_STORE_ROW 3
movq m1, [r0+%1*FDEC_STRIDE]
punpckhbw m2, m1, m0
punpcklbw m1, m0
paddw m1, %2
paddw m2, %3
packuswb m1, m2
movq [r0+%1*FDEC_STRIDE], m1
%endmacro
;-----------------------------------------------------------------------------
; void add8x8_idct8( uint8_t *dst, int16_t dct[8][8] )
;-----------------------------------------------------------------------------
cglobal add8x8_idct8_mmx, 2,2
global add8x8_idct8_mmx.skip_prologue
.skip_prologue:
INIT_MMX
add word [r1], 32
UNSPILL r1, 1,2,3,5,6,7
call idct8_mmx
SPILL r1, 7
TRANSPOSE4x4W 0,1,2,3,7
SPILL r1, 0,1,2,3
UNSPILL r1, 7
TRANSPOSE4x4W 4,5,6,7,0
SPILL r1, 4,5,6,7
INIT_MMX
UNSPILL r1+8, 1,2,3,5,6,7
add r1, 8
call idct8_mmx
sub r1, 8
SPILL r1+8, 7
TRANSPOSE4x4W 0,1,2,3,7
SPILL r1+8, 0,1,2,3
UNSPILL r1+8, 7
TRANSPOSE4x4W 4,5,6,7,0
SPILL r1+8, 4,5,6,7
INIT_MMX
movq m3, [r1+0x08]
movq m0, [r1+0x40]
movq [r1+0x40], m3
movq [r1+0x08], m0
; memory layout at this time:
; A0------ A1------
; B0------ F0------
; C0------ G0------
; D0------ H0------
; E0------ E1------
; B1------ F1------
; C1------ G1------
; D1------ H1------
UNSPILL_SHUFFLE r1, 1,2,3, 5,6,7
UNSPILL r1+8, 5,6,7
add r1, 8
call idct8_mmx
sub r1, 8
psraw m0, 6
psraw m1, 6
psraw m2, 6
psraw m3, 6
psraw m4, 6
psraw m5, 6
psraw m6, 6
psraw m7, 6
movq [r1+0x08], m0 ; mm4
movq [r1+0x48], m4 ; mm5
movq [r1+0x58], m5 ; mm0
movq [r1+0x68], m6 ; mm2
movq [r1+0x78], m7 ; mm6
movq mm5, [r1+0x18]
movq mm6, [r1+0x28]
movq [r1+0x18], m1 ; mm1
movq [r1+0x28], m2 ; mm7
movq mm7, [r1+0x38]
movq [r1+0x38], m3 ; mm3
movq mm1, [r1+0x10]
movq mm2, [r1+0x20]
movq mm3, [r1+0x30]
call idct8_mmx
psraw m0, 6
psraw m1, 6
psraw m2, 6
psraw m3, 6
psraw m4, 6
psraw m5, 6
psraw m6, 6
psraw m7, 6
SPILL r1, 0,1,2
pxor m0, m0
ADD_STORE_ROW 0, [r1+0x00], [r1+0x08]
ADD_STORE_ROW 1, [r1+0x10], [r1+0x18]
ADD_STORE_ROW 2, [r1+0x20], [r1+0x28]
ADD_STORE_ROW 3, m3, [r1+0x38]
ADD_STORE_ROW 4, m4, [r1+0x48]
ADD_STORE_ROW 5, m5, [r1+0x58]
ADD_STORE_ROW 6, m6, [r1+0x68]
ADD_STORE_ROW 7, m7, [r1+0x78]
ret
%macro DCT_SUB8 0
cglobal sub8x8_dct, 3,3
add r2, 4*FDEC_STRIDE
global current_function %+ .skip_prologue
.skip_prologue:
%if cpuflag(ssse3)
mova m7, [hsub_mul]
%endif
LOAD_DIFF8x4 0, 1, 2, 3, 6, 7, r1, r2-4*FDEC_STRIDE
SPILL r0, 1,2
SWAP 2, 7
LOAD_DIFF8x4 4, 5, 6, 7, 1, 2, r1, r2-4*FDEC_STRIDE
UNSPILL r0, 1
SPILL r0, 7
SWAP 2, 7
UNSPILL r0, 2
DCT4_1D 0, 1, 2, 3, 7
TRANSPOSE2x4x4W 0, 1, 2, 3, 7
UNSPILL r0, 7
SPILL r0, 2
DCT4_1D 4, 5, 6, 7, 2
TRANSPOSE2x4x4W 4, 5, 6, 7, 2
UNSPILL r0, 2
SPILL r0, 6
DCT4_1D 0, 1, 2, 3, 6
UNSPILL r0, 6
STORE_DCT 0, 1, 2, 3, r0, 0
DCT4_1D 4, 5, 6, 7, 3
STORE_DCT 4, 5, 6, 7, r0, 64
ret
;-----------------------------------------------------------------------------
; void sub8x8_dct8( int16_t dct[8][8], uint8_t *pix1, uint8_t *pix2 )
;-----------------------------------------------------------------------------
cglobal sub8x8_dct8, 3,3
add r2, 4*FDEC_STRIDE
global current_function %+ .skip_prologue
.skip_prologue:
%if cpuflag(ssse3)
mova m7, [hsub_mul]
LOAD_DIFF8x4 0, 1, 2, 3, 4, 7, r1, r2-4*FDEC_STRIDE
SPILL r0, 0,1
SWAP 1, 7
LOAD_DIFF8x4 4, 5, 6, 7, 0, 1, r1, r2-4*FDEC_STRIDE
UNSPILL r0, 0,1
%else
LOAD_DIFF m0, m7, none, [r1+0*FENC_STRIDE], [r2-4*FDEC_STRIDE]
LOAD_DIFF m1, m7, none, [r1+1*FENC_STRIDE], [r2-3*FDEC_STRIDE]
LOAD_DIFF m2, m7, none, [r1+2*FENC_STRIDE], [r2-2*FDEC_STRIDE]
LOAD_DIFF m3, m7, none, [r1+3*FENC_STRIDE], [r2-1*FDEC_STRIDE]
LOAD_DIFF m4, m7, none, [r1+4*FENC_STRIDE], [r2+0*FDEC_STRIDE]
LOAD_DIFF m5, m7, none, [r1+5*FENC_STRIDE], [r2+1*FDEC_STRIDE]
SPILL r0, 0
LOAD_DIFF m6, m7, none, [r1+6*FENC_STRIDE], [r2+2*FDEC_STRIDE]
LOAD_DIFF m7, m0, none, [r1+7*FENC_STRIDE], [r2+3*FDEC_STRIDE]
UNSPILL r0, 0
%endif
DCT8_1D w,0,1,2,3,4,5,6,7,[r0],[r0+0x40],[r0+0x60]
UNSPILL r0, 0,4
TRANSPOSE8x8W 0,1,2,3,4,5,6,7,[r0+0x60],[r0+0x40],1
UNSPILL r0, 4
DCT8_1D w,0,1,2,3,4,5,6,7,[r0],[r0+0x40],[r0+0x60]
SPILL r0, 1,2,3,5,7
ret
%endmacro
INIT_XMM sse2
%define movdqa movaps
%define punpcklqdq movlhps
DCT_SUB8
%undef movdqa
%undef punpcklqdq
INIT_XMM ssse3
DCT_SUB8
INIT_XMM avx
DCT_SUB8
INIT_XMM xop
DCT_SUB8
;-----------------------------------------------------------------------------
; void add8x8_idct( uint8_t *pix, int16_t dct[4][4][4] )
;-----------------------------------------------------------------------------
%macro ADD8x8 0
cglobal add8x8_idct, 2,2
add r0, 4*FDEC_STRIDE
global current_function %+ .skip_prologue
.skip_prologue:
UNSPILL_SHUFFLE r1, 0,2,1,3, 0,1,2,3
SBUTTERFLY qdq, 0, 1, 4
SBUTTERFLY qdq, 2, 3, 4
UNSPILL_SHUFFLE r1, 4,6,5,7, 4,5,6,7
SPILL r1, 0
SBUTTERFLY qdq, 4, 5, 0
SBUTTERFLY qdq, 6, 7, 0
UNSPILL r1,0
IDCT4_1D w,0,1,2,3,r1
SPILL r1, 4
TRANSPOSE2x4x4W 0,1,2,3,4
UNSPILL r1, 4
IDCT4_1D w,4,5,6,7,r1
SPILL r1, 0
TRANSPOSE2x4x4W 4,5,6,7,0
UNSPILL r1, 0
paddw m0, [pw_32]
IDCT4_1D w,0,1,2,3,r1
paddw m4, [pw_32]
IDCT4_1D w,4,5,6,7,r1
SPILL r1, 6,7
pxor m7, m7
DIFFx2 m0, m1, m6, m7, [r0-4*FDEC_STRIDE], [r0-3*FDEC_STRIDE]; m5
DIFFx2 m2, m3, m6, m7, [r0-2*FDEC_STRIDE], [r0-1*FDEC_STRIDE]; m5
UNSPILL_SHUFFLE r1, 0,2, 6,7
DIFFx2 m4, m5, m6, m7, [r0+0*FDEC_STRIDE], [r0+1*FDEC_STRIDE]; m5
DIFFx2 m0, m2, m6, m7, [r0+2*FDEC_STRIDE], [r0+3*FDEC_STRIDE]; m5
STORE_IDCT m1, m3, m5, m2
ret
%endmacro ; ADD8x8
INIT_XMM sse2
ADD8x8
INIT_XMM avx
ADD8x8
;-----------------------------------------------------------------------------
; void add8x8_idct8( uint8_t *p_dst, int16_t dct[8][8] )
;-----------------------------------------------------------------------------
%macro ADD8x8_IDCT8 0
cglobal add8x8_idct8, 2,2
add r0, 4*FDEC_STRIDE
global current_function %+ .skip_prologue
.skip_prologue:
UNSPILL r1, 1,2,3,5,6,7
IDCT8_1D w,0,1,2,3,4,5,6,7,[r1+0],[r1+64]
SPILL r1, 6
TRANSPOSE8x8W 0,1,2,3,4,5,6,7,[r1+0x60],[r1+0x40],1
paddw m0, [pw_32]
SPILL r1, 0
IDCT8_1D w,0,1,2,3,4,5,6,7,[r1+0],[r1+64]
SPILL r1, 6,7
pxor m7, m7
DIFFx2 m0, m1, m6, m7, [r0-4*FDEC_STRIDE], [r0-3*FDEC_STRIDE]; m5
DIFFx2 m2, m3, m6, m7, [r0-2*FDEC_STRIDE], [r0-1*FDEC_STRIDE]; m5
UNSPILL_SHUFFLE r1, 0,2, 6,7
DIFFx2 m4, m5, m6, m7, [r0+0*FDEC_STRIDE], [r0+1*FDEC_STRIDE]; m5
DIFFx2 m0, m2, m6, m7, [r0+2*FDEC_STRIDE], [r0+3*FDEC_STRIDE]; m5
STORE_IDCT m1, m3, m5, m2
ret
%endmacro ; ADD8x8_IDCT8
INIT_XMM sse2
ADD8x8_IDCT8
INIT_XMM avx
ADD8x8_IDCT8
%endif ; !HIGH_BIT_DEPTH
|
build/machineCsr.elf: file format elf32-littleriscv
Disassembly of section .crt_section:
80000000 <trap_entry-0x20>:
80000000: 0940006f j 80000094 <_start>
80000004: 00000013 nop
80000008: 00000013 nop
8000000c: 00000013 nop
80000010: 00000013 nop
80000014: 00000013 nop
80000018: 00000013 nop
8000001c: 00000013 nop
80000020 <trap_entry>:
80000020: 34202e73 csrr t3,mcause
80000024: 000e1e63 bnez t3,80000040 <notICmdAlignementException>
80000028: ffc00f13 li t5,-4
8000002c: 34102ef3 csrr t4,mepc
80000030: 01eefeb3 and t4,t4,t5
80000034: 004e8e93 addi t4,t4,4
80000038: 341e9073 csrw mepc,t4
8000003c: 01c0006f j 80000058 <mepcFixed>
80000040 <notICmdAlignementException>:
80000040: 80000eb7 lui t4,0x80000
80000044: 01de7f33 and t5,t3,t4
80000048: 000f1863 bnez t5,80000058 <mepcFixed>
8000004c: 34102ef3 csrr t4,mepc
80000050: 004e8e93 addi t4,t4,4 # 80000004 <unalignedPcA+0xfffffe60>
80000054: 341e9073 csrw mepc,t4
80000058 <mepcFixed>:
80000058: 80000eb7 lui t4,0x80000
8000005c: 003e8e93 addi t4,t4,3 # 80000003 <unalignedPcA+0xfffffe5f>
80000060: 01ce9863 bne t4,t3,80000070 <noSoftwareInterrupt>
80000064: f0013c37 lui s8,0xf0013
80000068: 00000c93 li s9,0
8000006c: 019c2023 sw s9,0(s8) # f0013000 <unalignedPcA+0x70012e5c>
80000070 <noSoftwareInterrupt>:
80000070: 80000eb7 lui t4,0x80000
80000074: 007e8e93 addi t4,t4,7 # 80000007 <unalignedPcA+0xfffffe63>
80000078: 01ce9463 bne t4,t3,80000080 <noTimerInterrupt>
8000007c: 30405073 csrwi mie,0
80000080 <noTimerInterrupt>:
80000080: 80000eb7 lui t4,0x80000
80000084: 00be8e93 addi t4,t4,11 # 8000000b <unalignedPcA+0xfffffe67>
80000088: 01ce9463 bne t4,t3,80000090 <noExernalInterrupt>
8000008c: 30405073 csrwi mie,0
80000090 <noExernalInterrupt>:
80000090: 30200073 mret
80000094 <_start>:
80000094: 00100e13 li t3,1
80000098: 00000073 ecall
8000009c: 00200e13 li t3,2
800000a0: 00800293 li t0,8
800000a4: 3002a073 csrs mstatus,t0
800000a8: 00800293 li t0,8
800000ac: 30429073 csrw mie,t0
800000b0: f0013c37 lui s8,0xf0013
800000b4: 00100c93 li s9,1
800000b8: 019c2023 sw s9,0(s8) # f0013000 <unalignedPcA+0x70012e5c>
800000bc: 00000013 nop
800000c0: 00000013 nop
800000c4: 00000013 nop
800000c8: 00000013 nop
800000cc: 00000013 nop
800000d0: 00000013 nop
800000d4: 00000013 nop
800000d8: 00000013 nop
800000dc: 00000013 nop
800000e0: 00000013 nop
800000e4: 00000013 nop
800000e8: 00000013 nop
800000ec: 00300e13 li t3,3
800000f0: 08000293 li t0,128
800000f4: 30429073 csrw mie,t0
800000f8: 00000013 nop
800000fc: 00000013 nop
80000100: 00000013 nop
80000104: 00000013 nop
80000108: 00000013 nop
8000010c: 00000013 nop
80000110: 00000013 nop
80000114: 00400e13 li t3,4
80000118: 000012b7 lui t0,0x1
8000011c: 80028293 addi t0,t0,-2048 # 800 <trap_entry-0x7ffff820>
80000120: 30429073 csrw mie,t0
80000124: 00000013 nop
80000128: 00000013 nop
8000012c: 00000013 nop
80000130: 00000013 nop
80000134: 00000013 nop
80000138: 00000013 nop
8000013c: 00000013 nop
80000140: 00500e13 li t3,5
80000144: f01001b7 lui gp,0xf0100
80000148: f4018193 addi gp,gp,-192 # f00fff40 <unalignedPcA+0x700ffd9c>
8000014c: 0001a203 lw tp,0(gp)
80000150: 0041a283 lw t0,4(gp)
80000154: 3ff20213 addi tp,tp,1023 # 3ff <trap_entry-0x7ffffc21>
80000158: 0041a423 sw tp,8(gp)
8000015c: 0051a623 sw t0,12(gp)
80000160: 00600e13 li t3,6
80000164: 08000213 li tp,128
80000168: 30421073 csrw mie,tp
8000016c: 00700e13 li t3,7
80000170: 10500073 wfi
80000174: 00800e13 li t3,8
80000178: 00100193 li gp,1
8000017c: 0041a023 sw tp,0(gp)
80000180: 00900e13 li t3,9
80000184: 00419023 sh tp,0(gp)
80000188: 00a00e13 li t3,10
8000018c: 0001a203 lw tp,0(gp)
80000190: 00b00e13 li t3,11
80000194: 00019203 lh tp,0(gp)
80000198: 00c00e13 li t3,12
8000019c: 00d00e13 li t3,13
800001a0: 00002083 lw ra,0(zero) # 0 <trap_entry-0x80000020>
800001a4 <unalignedPcA>:
800001a4: 0020006f j 800001a6 <unalignedPcA+0x2>
800001a8: 00002083 lw ra,0(zero) # 0 <trap_entry-0x80000020>
800001ac: 00e00e13 li t3,14
800001b0: 20200073 hret
800001b4: 00f00e13 li t3,15
800001b8: f01000b7 lui ra,0xf0100
800001bc: f6008093 addi ra,ra,-160 # f00fff60 <unalignedPcA+0x700ffdbc>
800001c0: 0000a103 lw sp,0(ra)
800001c4: 01000e13 li t3,16
800001c8: 0020a023 sw sp,0(ra)
800001cc: 01100e13 li t3,17
800001d0: 00008067 ret
...
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; SPDX-License-Identifier: BSD-2-Clause-Patent
;
; Module Name:
;
; SetMem16.nasm
;
; Abstract:
;
; SetMem16 function
;
; Notes:
;
;------------------------------------------------------------------------------
DEFAULT REL
SECTION .text
;------------------------------------------------------------------------------
; VOID *
; InternalMemSetMem16 (
; IN VOID *Buffer,
; IN UINTN Count,
; IN UINT16 Value
; )
;------------------------------------------------------------------------------
global ASM_PFX(InternalMemSetMem16)
ASM_PFX(InternalMemSetMem16):
push rdi
mov rdi, rcx
mov r9, rdi
xor rcx, rcx
sub rcx, rdi
and rcx, 63
mov rax, r8
jz .0
shr rcx, 1
cmp rcx, rdx
cmova rcx, rdx
sub rdx, rcx
rep stosw
.0:
mov rcx, rdx
and edx, 31
shr rcx, 5
jz @SetWords
movd xmm0, eax
pshuflw xmm0, xmm0, 0
movlhps xmm0, xmm0
.1:
movntdq [rdi], xmm0
movntdq [rdi + 16], xmm0
movntdq [rdi + 32], xmm0
movntdq [rdi + 48], xmm0
add rdi, 64
loop .1
mfence
@SetWords:
mov ecx, edx
rep stosw
mov rax, r9
pop rdi
ret
|
;
; Copyright (C) 2019 Assured Information Security, Inc.
;
; Permission is hereby granted, free of charge, to any person obtaining a copy
; of this software and associated documentation files (the "Software"), to deal
; in the Software without restriction, including without limitation the rights
; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
; copies of the Software, and to permit persons to whom the Software is
; furnished to do so, subject to the following conditions:
;
; The above copyright notice and this permission notice shall be included in all
; copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
; SOFTWARE.
bits 64
default rel
%define VMCS_GUEST_RSP 0x0000681C
%define VMCS_GUEST_RIP 0x0000681E
extern handle_exit
global exit_handler_entry:function
section .text
; Exit Handler Entry Point
;
; With respect to VT-x, when an exit occurs, the CPU keeps the state of the
; registers from the guest intact, and gives the state of the registers prior
; to vmresume, back to the guest. The only exception to this is RSP and RIP as
; these two registers are specific to the VMM (RIP is exit_handler_entry,
; and RSP is the exit_handler_stack). So the only job that this entry point
; has is to preserve the state of the guest
;
exit_handler_entry:
mov [gs:0x000], rax
mov [gs:0x008], rbx
mov [gs:0x010], rcx
mov [gs:0x018], rdx
mov [gs:0x020], rbp
mov [gs:0x028], rsi
mov [gs:0x030], rdi
mov [gs:0x038], r8
mov [gs:0x040], r9
mov [gs:0x048], r10
mov [gs:0x050], r11
mov [gs:0x058], r12
mov [gs:0x060], r13
mov [gs:0x068], r14
mov [gs:0x070], r15
movdqa [gs:0x0C0], xmm0
movdqa [gs:0x0E0], xmm1
movdqa [gs:0x100], xmm2
movdqa [gs:0x120], xmm3
movdqa [gs:0x140], xmm4
movdqa [gs:0x160], xmm5
movdqa [gs:0x180], xmm6
movdqa [gs:0x1A0], xmm7
mov rdi, VMCS_GUEST_RIP
vmread [gs:0x078], rdi
mov rdi, VMCS_GUEST_RSP
vmread [gs:0x080], rdi
mov rdi, [gs:0x0098]
mov rsi, [gs:0x00A0]
call handle_exit wrt ..plt
; The code should never get this far as the exit handler should resume back
; into the guest using the VMCS's resume function. If we get this far,
; something really bad has happened as we also halt in exit_handler if the
; resume doesn't happen.
hlt
|
; ---------------------------------------------------------------------------
; Animation script - prison capsule
; ---------------------------------------------------------------------------
dc.w byte_1AD70-Ani_obj3E
dc.w byte_1AD70-Ani_obj3E
byte_1AD70: dc.b 2, 1, 3, $FF
even |
#include <bits/stdc++.h>
#define le 10004
using namespace std;
vector<int> v;
int main(){
//freopen("input.txt", "r", stdin);
int a;
while(scanf("%d", &a) != EOF) v.push_back(a);
sort(v.begin(), v.end());
for(int i = v.size() - 1, j = 0; i >= 0 && j < 3; i--, j++) cout << v[i] << endl;
return 0;
}
|
; A059831: Determinant of Wilkinson's eigenvalue test matrix of order 2n+1.
; Submitted by Jon Maiga
; 0,-2,-4,-20,-252,-5610,-187944,-8760272,-540315160,-42535905530,-4158250120140,-493938370048692,-70043599065844404,-11684931733886455730,-2264985487707963662992,-504752888883221450120000,-128137017404994234514023024
mov $2,1
mov $3,1
lpb $0
sub $0,1
mov $1,$3
mul $1,$0
sub $1,$3
add $2,$1
add $3,$2
lpe
mul $1,$3
mov $0,$1
mul $0,2
|
assume cs:code, ds:data, ss:stack
stack segment
db 100 dup(0)
stack ends
data segment
a dw 0
db 100 dup(0)
string db 'Hello!$'
data ends
code segment
start:
mov ax, data
mov ds, ax
mov ax, stack
mov ss, ax
call mathFunc3
mov bx, ax
mov ax, 4c00h
int 21h
; 返回值放寄存器
mathFunc3:
mov ax, 2
add ax, ax
add ax, ax
ret
; 返回值放数据段
mathFunc2:
mov ax, 2
add ax, ax
add ax, ax
mov a, ax
ret
mathFunc1:
mov ax, 2
add ax, ax
add ax, ax
mov [0], ax
ret
code ends
end start |
lbu $3,15($0)
subu $3,$4,$3
slti $6,$3,22413
sllv $6,$2,$3
srav $4,$0,$3
ori $3,$3,29131
and $1,$3,$3
addiu $3,$3,23286
lw $4,0($0)
xori $3,$3,62860
slti $5,$1,-14026
lh $0,14($0)
xor $3,$3,$3
addu $4,$5,$3
srav $1,$3,$3
lhu $4,16($0)
sra $5,$1,17
sltu $3,$3,$3
srlv $3,$3,$3
lw $3,16($0)
slt $4,$0,$3
slti $4,$5,-18192
lhu $1,12($0)
addiu $6,$1,10604
addu $5,$5,$3
lbu $0,6($0)
sltiu $3,$4,20965
addu $1,$6,$3
addu $3,$3,$3
addu $3,$3,$3
xori $4,$5,33584
lb $3,6($0)
andi $3,$4,4918
lb $6,7($0)
sra $3,$4,26
andi $3,$1,63154
addiu $5,$5,-7184
sll $6,$0,15
sw $5,8($0)
sll $3,$3,12
nor $3,$3,$3
sra $3,$4,6
slti $1,$3,-31280
addu $4,$0,$3
lhu $3,10($0)
xori $1,$0,21347
ori $4,$5,35553
sh $5,8($0)
addiu $5,$4,2610
sra $5,$3,28
lbu $3,5($0)
addu $3,$4,$3
ori $4,$0,35845
sw $3,8($0)
xori $5,$3,52309
lbu $1,1($0)
sltu $0,$0,$3
slt $3,$4,$3
sw $5,8($0)
subu $3,$3,$3
andi $3,$5,56746
sll $4,$5,29
sll $6,$4,19
sllv $6,$0,$3
lh $4,16($0)
xor $4,$4,$3
nor $4,$1,$3
srav $4,$4,$3
or $1,$1,$3
lhu $3,16($0)
sh $5,2($0)
lb $1,6($0)
lb $3,15($0)
srl $5,$1,1
srav $3,$4,$3
addiu $3,$4,19304
ori $3,$3,11866
subu $3,$4,$3
lb $3,10($0)
sltu $0,$4,$3
or $1,$3,$3
sltiu $5,$5,9648
sllv $0,$3,$3
sh $3,4($0)
xor $3,$3,$3
xori $5,$5,59256
xori $1,$1,14278
addu $4,$1,$3
sw $0,16($0)
lh $5,0($0)
slt $3,$3,$3
srl $3,$5,19
sllv $3,$3,$3
sllv $0,$3,$3
lh $3,14($0)
slti $5,$1,-1763
lb $4,13($0)
ori $0,$0,62215
lhu $6,12($0)
lbu $5,14($0)
sltu $3,$3,$3
sw $3,8($0)
addu $3,$3,$3
srlv $3,$4,$3
slti $3,$6,-1914
lhu $4,8($0)
srav $4,$1,$3
subu $4,$4,$3
addu $5,$4,$3
lh $3,14($0)
addu $3,$5,$3
addu $0,$0,$3
andi $6,$0,17541
sh $3,10($0)
sh $1,10($0)
nor $3,$4,$3
sh $4,0($0)
subu $1,$1,$3
and $0,$6,$3
srl $3,$3,14
sltiu $1,$0,-29468
sh $5,6($0)
nor $3,$3,$3
lw $3,12($0)
sra $6,$4,3
nor $1,$6,$3
srl $4,$4,7
sh $1,16($0)
subu $3,$5,$3
lhu $0,12($0)
addiu $3,$3,-32318
addiu $3,$0,19062
lbu $3,11($0)
or $3,$1,$3
sll $4,$5,15
lw $1,16($0)
addiu $3,$3,10004
lb $4,2($0)
sh $1,8($0)
ori $3,$1,393
lh $5,10($0)
subu $5,$3,$3
srav $6,$1,$3
slti $3,$2,17569
lbu $5,0($0)
addiu $4,$3,-5173
subu $6,$4,$3
addu $3,$3,$3
addiu $4,$4,-27884
sltiu $3,$3,16206
andi $3,$1,47663
or $4,$3,$3
sltiu $3,$1,-12386
nor $4,$4,$3
ori $5,$5,1563
lhu $5,0($0)
slti $5,$2,23074
nor $4,$1,$3
sh $4,4($0)
xori $4,$5,59624
lw $3,4($0)
sra $5,$5,19
subu $3,$3,$3
addiu $3,$3,-14283
lb $4,1($0)
srav $3,$3,$3
or $3,$3,$3
andi $3,$4,21675
lw $3,4($0)
sll $3,$4,31
sllv $3,$0,$3
or $5,$5,$3
sh $1,2($0)
lw $3,12($0)
xori $3,$6,44448
sw $3,0($0)
and $4,$6,$3
sltu $3,$5,$3
nor $3,$3,$3
sll $1,$1,6
lbu $1,5($0)
sb $1,0($0)
sltiu $6,$4,-21646
lw $0,8($0)
sll $3,$3,6
lbu $3,3($0)
sltu $3,$3,$3
addiu $5,$1,-19920
xor $3,$1,$3
sb $5,4($0)
slt $4,$1,$3
andi $0,$3,35703
addu $3,$6,$3
sra $5,$5,15
xori $5,$5,42574
sra $1,$1,7
srl $3,$1,27
addiu $3,$0,6427
xor $3,$3,$3
lhu $5,10($0)
xori $4,$5,62104
srav $4,$4,$3
xori $4,$3,31154
sw $0,0($0)
sltu $5,$3,$3
lw $0,0($0)
lw $0,8($0)
and $3,$6,$3
nor $3,$4,$3
nor $3,$4,$3
sw $5,16($0)
addu $1,$1,$3
sltu $4,$0,$3
nor $3,$2,$3
xori $1,$1,4200
xor $4,$5,$3
lh $5,12($0)
addiu $4,$5,-29581
or $0,$1,$3
sb $3,3($0)
subu $5,$5,$3
sra $3,$6,7
slt $5,$4,$3
subu $3,$4,$3
subu $1,$1,$3
addiu $0,$3,-28780
addiu $3,$3,14180
or $3,$5,$3
sb $3,7($0)
lw $3,4($0)
slt $5,$3,$3
ori $4,$3,32205
addu $4,$3,$3
or $6,$5,$3
sh $1,8($0)
addiu $3,$5,22532
sltu $3,$4,$3
subu $4,$5,$3
addiu $3,$6,-9633
srl $0,$3,20
slt $3,$5,$3
srav $4,$4,$3
lhu $4,6($0)
andi $0,$0,51586
addiu $3,$0,-17949
sltu $1,$3,$3
addiu $5,$0,9130
addu $0,$3,$3
subu $2,$2,$3
srl $3,$6,23
sb $3,4($0)
sh $0,16($0)
sb $3,8($0)
addu $4,$5,$3
srl $5,$5,6
ori $3,$3,4378
sb $4,12($0)
subu $5,$4,$3
lbu $6,16($0)
addu $3,$3,$3
lhu $3,4($0)
srav $4,$3,$3
srl $3,$4,5
sw $4,12($0)
sllv $0,$3,$3
lbu $3,12($0)
lw $4,4($0)
sh $0,8($0)
sh $3,16($0)
subu $1,$1,$3
lhu $1,10($0)
sltiu $4,$6,15391
nor $4,$0,$3
addu $4,$4,$3
subu $3,$3,$3
or $3,$3,$3
lh $4,4($0)
lw $5,12($0)
sltiu $3,$3,5671
sw $6,16($0)
addu $4,$4,$3
sb $5,2($0)
sll $3,$3,7
sltiu $3,$3,-28308
lh $3,16($0)
sh $6,0($0)
or $4,$4,$3
srlv $3,$3,$3
sltiu $3,$1,5720
sw $3,16($0)
subu $4,$5,$3
sb $1,7($0)
lhu $3,0($0)
sltiu $3,$4,30302
sb $4,13($0)
sltu $0,$1,$3
sh $6,10($0)
or $4,$4,$3
sltu $0,$3,$3
lbu $4,7($0)
sltiu $4,$0,6349
xor $4,$6,$3
addu $1,$3,$3
sllv $4,$4,$3
sh $4,6($0)
sra $4,$3,11
slt $1,$3,$3
sll $5,$3,7
sb $5,10($0)
sllv $6,$6,$3
srlv $5,$0,$3
sll $0,$4,8
addiu $5,$5,-24445
xori $3,$3,24155
slt $4,$3,$3
xor $1,$5,$3
sw $4,16($0)
subu $5,$5,$3
sw $4,8($0)
lb $3,0($0)
lbu $3,2($0)
andi $3,$5,25987
lw $4,8($0)
sllv $6,$6,$3
sltiu $1,$1,-3125
addu $3,$3,$3
addu $6,$6,$3
srlv $4,$4,$3
sll $4,$4,14
lb $4,13($0)
lw $4,12($0)
andi $6,$3,52452
sllv $4,$4,$3
srl $3,$3,5
nor $3,$1,$3
sb $3,4($0)
addiu $3,$2,28289
lhu $0,16($0)
sltiu $4,$4,-31610
ori $4,$6,28307
addu $3,$4,$3
sllv $3,$3,$3
or $3,$3,$3
sll $3,$0,13
sltu $5,$0,$3
andi $3,$3,46296
lh $5,12($0)
nor $3,$3,$3
lw $3,8($0)
addiu $0,$0,6304
lhu $0,8($0)
nor $0,$1,$3
or $3,$6,$3
lbu $3,11($0)
slt $4,$6,$3
lhu $3,2($0)
sra $4,$5,0
xori $3,$1,55833
addu $3,$0,$3
lhu $4,14($0)
srl $5,$5,6
lw $6,16($0)
andi $3,$0,55962
nor $3,$3,$3
srav $3,$3,$3
xori $3,$3,61042
xori $4,$1,31316
lw $4,4($0)
sll $4,$0,13
subu $3,$5,$3
nor $5,$6,$3
sw $4,16($0)
or $4,$4,$3
xor $6,$3,$3
lhu $6,12($0)
srl $5,$3,11
sh $3,8($0)
addu $0,$3,$3
srl $3,$3,16
slt $4,$3,$3
xor $5,$5,$3
andi $4,$0,62263
sh $0,16($0)
subu $4,$4,$3
sll $4,$4,5
lw $0,12($0)
subu $3,$3,$3
sra $3,$4,23
subu $5,$5,$3
xor $5,$3,$3
addu $5,$5,$3
ori $3,$3,49539
slti $3,$2,5760
sltu $6,$1,$3
lhu $3,2($0)
sb $3,7($0)
sllv $5,$4,$3
sltu $6,$3,$3
sllv $3,$3,$3
sltu $1,$1,$3
subu $0,$3,$3
slti $1,$2,20137
lw $3,8($0)
sltiu $3,$0,1596
xori $3,$4,2695
lw $4,0($0)
sltiu $0,$4,-27703
subu $3,$3,$3
sllv $4,$1,$3
xor $5,$5,$3
or $4,$4,$3
sltiu $5,$3,-24991
ori $0,$0,57955
lh $0,12($0)
sltu $6,$1,$3
sh $4,0($0)
sra $4,$4,6
lbu $0,3($0)
slt $4,$4,$3
xori $4,$5,50871
lw $3,16($0)
addu $3,$3,$3
srl $5,$5,12
slti $3,$3,-20103
sltu $5,$5,$3
sltiu $4,$1,-28171
slti $1,$4,-12254
and $5,$3,$3
slti $1,$5,-5247
subu $4,$4,$3
lbu $3,11($0)
lw $4,0($0)
slti $1,$4,-6782
subu $3,$4,$3
addiu $3,$3,26867
subu $5,$6,$3
sra $3,$4,10
sllv $3,$3,$3
addu $5,$1,$3
sb $3,13($0)
sw $1,8($0)
subu $1,$3,$3
ori $3,$1,2184
or $3,$4,$3
nor $3,$4,$3
sllv $3,$3,$3
lhu $3,16($0)
sltu $3,$3,$3
srlv $1,$3,$3
addiu $5,$1,-18795
and $3,$5,$3
sltu $4,$1,$3
xori $1,$0,12090
srl $0,$0,7
sb $4,2($0)
lhu $6,0($0)
sltiu $2,$2,32076
srlv $3,$4,$3
slt $5,$3,$3
and $3,$0,$3
srlv $1,$3,$3
and $3,$6,$3
addiu $2,$2,-11417
lh $1,12($0)
andi $5,$5,61693
lb $3,0($0)
lbu $3,12($0)
sllv $1,$1,$3
addiu $4,$6,27017
lb $2,6($0)
xor $3,$3,$3
lbu $0,7($0)
andi $3,$3,858
slti $6,$6,-30077
lbu $3,8($0)
slti $3,$0,3605
sll $4,$0,28
slti $4,$4,22942
or $3,$3,$3
srl $5,$5,21
lbu $1,15($0)
sltu $5,$4,$3
sb $0,9($0)
sb $5,5($0)
srl $3,$1,23
ori $4,$4,47878
andi $3,$0,8841
subu $4,$3,$3
lh $4,4($0)
addu $3,$5,$3
sll $4,$4,24
nor $0,$3,$3
lh $1,14($0)
subu $4,$6,$3
sra $5,$1,3
sltu $4,$6,$3
addiu $3,$5,21480
slt $4,$3,$3
addiu $3,$4,-7715
or $4,$5,$3
xori $5,$1,37212
sh $4,12($0)
addu $3,$3,$3
sb $4,12($0)
sra $1,$5,31
sllv $3,$4,$3
sllv $3,$3,$3
sh $5,0($0)
sb $4,9($0)
sll $3,$6,12
sh $3,16($0)
lbu $1,4($0)
slt $5,$5,$3
lw $4,8($0)
lbu $3,14($0)
addiu $3,$0,14245
lw $1,16($0)
xori $3,$1,1494
lh $4,4($0)
sltiu $4,$0,9784
sllv $4,$4,$3
xor $5,$1,$3
slt $3,$3,$3
addu $3,$3,$3
sll $4,$6,16
addiu $3,$6,3454
or $3,$3,$3
slt $4,$4,$3
sllv $6,$3,$3
slti $5,$3,16036
sb $5,11($0)
addu $6,$1,$3
sltu $5,$3,$3
sh $3,14($0)
lhu $5,16($0)
and $3,$4,$3
addu $1,$1,$3
addiu $0,$6,-15486
lbu $1,14($0)
sb $6,11($0)
lh $5,16($0)
ori $4,$4,24304
lhu $3,12($0)
sh $6,6($0)
addu $3,$3,$3
xori $1,$6,32956
lh $3,0($0)
subu $0,$5,$3
subu $4,$3,$3
ori $4,$3,42197
xor $3,$3,$3
lh $3,0($0)
andi $3,$3,9616
subu $5,$5,$3
and $3,$0,$3
sb $3,9($0)
slti $6,$3,10329
sltiu $1,$2,-7550
xori $3,$0,25259
lb $0,5($0)
andi $6,$3,34988
nor $4,$5,$3
sllv $4,$5,$3
ori $3,$3,19403
sw $3,0($0)
srl $3,$1,18
sltiu $0,$4,26550
sw $3,16($0)
sh $4,8($0)
slti $3,$3,-1262
addu $5,$5,$3
lw $5,16($0)
srav $4,$4,$3
lhu $6,2($0)
sb $1,15($0)
nor $3,$3,$3
and $0,$0,$3
lbu $1,4($0)
and $1,$3,$3
lb $3,5($0)
addu $3,$3,$3
addu $1,$5,$3
addiu $1,$1,14861
lh $6,0($0)
subu $4,$4,$3
sll $0,$3,6
xor $4,$5,$3
sh $4,14($0)
lb $3,9($0)
srlv $4,$4,$3
andi $3,$4,5807
addu $4,$0,$3
addu $6,$3,$3
addiu $5,$1,6125
sw $3,8($0)
andi $5,$4,45480
subu $6,$1,$3
addiu $3,$3,8501
sb $4,5($0)
addu $5,$3,$3
andi $4,$4,15767
xori $3,$3,48638
lb $3,8($0)
sll $3,$3,12
slti $1,$3,-6893
xor $4,$3,$3
xori $5,$3,29532
andi $4,$3,59134
sra $4,$4,1
lhu $0,4($0)
sllv $4,$3,$3
addiu $3,$1,-27758
slti $4,$4,-12256
subu $3,$3,$3
or $3,$3,$3
addiu $3,$3,-4112
sll $4,$4,25
slti $4,$2,8504
sw $4,0($0)
xor $1,$5,$3
lbu $4,3($0)
slt $4,$3,$3
ori $4,$0,13520
srlv $3,$1,$3
addu $3,$5,$3
slt $3,$3,$3
slti $3,$5,-11809
srl $6,$1,11
ori $1,$4,62518
subu $5,$4,$3
addu $1,$2,$3
addu $1,$3,$3
lw $5,12($0)
lhu $6,12($0)
sw $0,4($0)
addiu $5,$5,21207
subu $3,$6,$3
sltu $1,$4,$3
lb $1,3($0)
addu $5,$5,$3
nor $3,$5,$3
sll $3,$3,29
lh $3,6($0)
xori $4,$1,4951
nor $3,$6,$3
subu $3,$4,$3
nor $0,$3,$3
addiu $6,$6,11999
sltiu $3,$1,9761
or $3,$3,$3
sltu $4,$4,$3
sw $1,16($0)
srlv $3,$3,$3
slti $5,$0,21592
sltiu $1,$1,9279
sltiu $3,$4,-15586
addiu $1,$4,-30808
xor $1,$3,$3
lhu $5,0($0)
addiu $5,$5,9868
addiu $1,$4,23471
lh $1,0($0)
sb $4,6($0)
sltiu $5,$3,29055
lh $3,6($0)
sra $4,$5,1
lbu $4,0($0)
sra $1,$5,7
nor $5,$5,$3
addiu $1,$1,18728
subu $1,$3,$3
sllv $4,$5,$3
sltu $3,$3,$3
sllv $4,$6,$3
sllv $1,$1,$3
and $6,$1,$3
and $3,$3,$3
lhu $3,2($0)
subu $3,$3,$3
xori $1,$4,16243
subu $3,$3,$3
lb $5,2($0)
sltu $5,$4,$3
sw $3,4($0)
lb $4,14($0)
sw $4,12($0)
sb $4,10($0)
srav $3,$5,$3
sltu $4,$6,$3
addiu $4,$4,23994
sltu $3,$5,$3
srav $1,$3,$3
addu $5,$6,$3
addu $3,$4,$3
sltiu $3,$4,21629
nor $5,$4,$3
sra $1,$1,3
slti $6,$3,-15521
subu $6,$3,$3
subu $4,$3,$3
lb $3,3($0)
ori $6,$1,54172
addiu $1,$1,2675
srav $5,$3,$3
addiu $3,$0,4600
nor $3,$3,$3
sltu $3,$5,$3
lhu $3,12($0)
sh $0,8($0)
sltiu $4,$6,-725
xor $3,$3,$3
andi $1,$6,45048
sllv $5,$5,$3
xori $1,$1,15618
addiu $3,$4,-30267
sllv $3,$0,$3
lbu $4,12($0)
lhu $3,16($0)
sllv $3,$3,$3
sh $4,6($0)
subu $3,$6,$3
or $4,$3,$3
xori $4,$5,40836
sra $3,$3,3
subu $3,$3,$3
addu $3,$4,$3
or $4,$4,$3
addiu $3,$3,-20236
andi $3,$3,25411
sltu $3,$3,$3
nor $1,$3,$3
addu $4,$4,$3
ori $4,$3,15703
srl $5,$6,6
sb $1,0($0)
xori $4,$6,62244
srav $5,$4,$3
lhu $1,16($0)
sra $5,$1,31
or $3,$3,$3
slti $1,$5,29512
sb $0,15($0)
srl $1,$3,16
sra $4,$3,27
lbu $3,5($0)
subu $1,$3,$3
slt $0,$3,$3
lh $4,6($0)
nor $1,$5,$3
slti $4,$1,-1043
andi $3,$3,44960
and $5,$3,$3
and $5,$4,$3
srlv $5,$3,$3
slti $1,$4,-27233
sll $5,$4,13
sh $3,4($0)
xor $1,$4,$3
lb $4,9($0)
lb $3,12($0)
xori $6,$4,41209
nor $3,$0,$3
sb $3,12($0)
sltiu $3,$3,353
or $4,$4,$3
slti $3,$4,-26145
slti $3,$3,16984
sltiu $3,$6,10517
sh $3,10($0)
srl $5,$5,21
and $3,$3,$3
sh $5,4($0)
srl $0,$0,28
slti $5,$5,26680
slt $1,$1,$3
sb $6,1($0)
srav $3,$3,$3
xor $3,$4,$3
slt $1,$4,$3
or $3,$4,$3
lhu $4,8($0)
lw $3,0($0)
addu $4,$4,$3
subu $3,$0,$3
lb $3,6($0)
slt $5,$4,$3
sltu $4,$6,$3
srlv $5,$5,$3
subu $3,$4,$3
lw $3,0($0)
or $1,$0,$3
subu $1,$3,$3
xor $5,$6,$3
sltiu $3,$4,19837
addiu $4,$0,28517
addu $3,$5,$3
or $3,$3,$3
lhu $3,12($0)
slti $6,$0,-31658
lbu $4,2($0)
andi $6,$0,49106
sll $4,$4,29
subu $3,$4,$3
slti $4,$3,-25423
addiu $1,$0,-23657
sll $0,$0,0
srav $1,$1,$3
subu $1,$6,$3
addiu $4,$4,8874
slt $3,$4,$3
addu $3,$3,$3
addu $3,$3,$3
sllv $4,$5,$3
xor $6,$3,$3
andi $4,$4,31051
andi $0,$4,34184
sb $1,9($0)
lw $6,8($0)
and $4,$4,$3
srlv $1,$5,$3
nor $5,$5,$3
lh $3,4($0)
sltu $0,$4,$3
xori $4,$3,21727
sh $5,16($0)
addu $4,$3,$3
xor $1,$1,$3
or $3,$4,$3
sll $5,$5,9
xor $3,$6,$3
lw $6,16($0)
srlv $5,$2,$3
lh $5,6($0)
sw $3,4($0)
sllv $5,$5,$3
slti $0,$0,12208
addu $1,$0,$3
andi $1,$1,25831
addiu $1,$1,-18286
lb $5,7($0)
subu $1,$3,$3
sw $5,16($0)
sw $5,0($0)
subu $4,$3,$3
srav $3,$3,$3
lb $4,6($0)
srlv $4,$3,$3
subu $6,$0,$3
ori $0,$0,22661
slt $5,$3,$3
sltu $0,$1,$3
lb $4,8($0)
lh $1,0($0)
lb $4,2($0)
sh $3,0($0)
nor $3,$3,$3
ori $3,$5,39860
sllv $3,$1,$3
ori $3,$3,22208
ori $5,$0,41809
subu $3,$6,$3
addu $3,$0,$3
xori $5,$4,51236
sra $1,$1,6
srl $0,$0,22
lbu $4,6($0)
sll $3,$5,2
sll $3,$0,28
nor $5,$5,$3
sll $0,$3,30
xori $4,$1,34465
sllv $1,$3,$3
addiu $3,$3,13060
lw $4,12($0)
nor $3,$3,$3
addiu $3,$6,-170
addu $4,$6,$3
lb $5,16($0)
slt $6,$4,$3
sltiu $3,$4,8686
addu $3,$0,$3
sb $1,10($0)
sh $3,12($0)
slt $1,$3,$3
or $4,$4,$3
srlv $3,$6,$3
sh $5,16($0)
nor $4,$3,$3
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r14
push %r9
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0xefc3, %rax
nop
nop
nop
nop
nop
inc %rbp
movl $0x61626364, (%rax)
add $58532, %r14
lea addresses_WC_ht+0x8697, %r12
nop
nop
nop
nop
nop
xor %rax, %rax
movb $0x61, (%r12)
nop
nop
sub %r13, %r13
lea addresses_A_ht+0xb443, %r13
inc %rcx
and $0xffffffffffffffc0, %r13
vmovaps (%r13), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $1, %xmm5, %rbp
nop
sub $3059, %r9
lea addresses_normal_ht+0x18cf3, %r14
nop
cmp %r13, %r13
movups (%r14), %xmm2
vpextrq $1, %xmm2, %rbp
nop
sub %rbp, %rbp
lea addresses_D_ht+0x17240, %r9
nop
nop
nop
nop
add $2533, %r13
movups (%r9), %xmm1
vpextrq $0, %xmm1, %r14
nop
xor $51405, %rcx
lea addresses_WC_ht+0xd443, %rax
nop
nop
nop
nop
nop
sub $47220, %r12
mov $0x6162636465666768, %r13
movq %r13, (%rax)
nop
add %rcx, %rcx
lea addresses_WT_ht+0xd7c3, %r13
nop
nop
nop
and $39654, %rax
movl $0x61626364, (%r13)
nop
nop
sub $3902, %r12
lea addresses_UC_ht+0xa1c3, %rbp
dec %rax
mov (%rbp), %r13w
nop
nop
add $32498, %rbp
lea addresses_WC_ht+0x1b7c3, %rsi
lea addresses_UC_ht+0xf7c3, %rdi
nop
nop
inc %rbp
mov $15, %rcx
rep movsw
nop
nop
nop
nop
inc %r9
lea addresses_A_ht+0x1a0ab, %r13
cmp $13212, %rsi
vmovups (%r13), %ymm1
vextracti128 $1, %ymm1, %xmm1
vpextrq $0, %xmm1, %rbp
nop
nop
nop
xor %rdi, %rdi
lea addresses_UC_ht+0x1282f, %rdi
nop
nop
nop
nop
xor %r12, %r12
movb $0x61, (%rdi)
nop
nop
nop
nop
nop
sub $9314, %rax
lea addresses_A_ht+0xfc3, %rsi
nop
cmp $52885, %rbp
mov (%rsi), %ecx
add %r13, %r13
lea addresses_WC_ht+0xa5a3, %rsi
lea addresses_D_ht+0x19843, %rdi
nop
dec %rbp
mov $116, %rcx
rep movsl
nop
nop
nop
nop
add %rcx, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r9
pop %r14
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r14
push %rbx
push %rcx
push %rdi
push %rsi
// Store
lea addresses_WC+0xdfc3, %r14
nop
nop
nop
nop
dec %rsi
mov $0x5152535455565758, %rcx
movq %rcx, (%r14)
nop
nop
nop
cmp %rsi, %rsi
// Store
lea addresses_A+0xa7a3, %rbx
nop
inc %r14
mov $0x5152535455565758, %rdi
movq %rdi, %xmm1
movups %xmm1, (%rbx)
nop
nop
nop
nop
nop
xor %rbx, %rbx
// Store
lea addresses_UC+0x2e83, %rdi
nop
add $58698, %rbx
mov $0x5152535455565758, %r14
movq %r14, (%rdi)
nop
nop
cmp $12833, %r14
// Store
lea addresses_normal+0x180c3, %rsi
nop
nop
cmp $41818, %r14
mov $0x5152535455565758, %rdi
movq %rdi, (%rsi)
nop
nop
mfence
// Store
lea addresses_PSE+0x81c3, %r14
nop
nop
nop
cmp %rbx, %rbx
movb $0x51, (%r14)
nop
xor $14173, %rsi
// Store
lea addresses_A+0xfb43, %rcx
cmp %rbx, %rbx
mov $0x5152535455565758, %r14
movq %r14, %xmm1
vmovntdq %ymm1, (%rcx)
nop
cmp %rdi, %rdi
// Store
lea addresses_WT+0x1703, %r14
add $52711, %r13
mov $0x5152535455565758, %r12
movq %r12, (%r14)
nop
inc %r12
// Store
lea addresses_PSE+0x126c3, %rcx
nop
xor %rbx, %rbx
movl $0x51525354, (%rcx)
nop
nop
nop
nop
cmp %rdi, %rdi
// Store
lea addresses_WT+0x1ffc3, %r12
xor $47996, %rdi
mov $0x5152535455565758, %rbx
movq %rbx, %xmm4
movups %xmm4, (%r12)
nop
nop
dec %rbx
// Faulty Load
lea addresses_RW+0x1b7c3, %r14
nop
nop
cmp %rsi, %rsi
vmovntdqa (%r14), %ymm7
vextracti128 $1, %ymm7, %xmm7
vpextrq $0, %xmm7, %rbx
lea oracles, %r13
and $0xff, %rbx
shlq $12, %rbx
mov (%r13,%rbx,1), %rbx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r14
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_RW', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WC', 'congruent': 11}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A', 'congruent': 5}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_UC', 'congruent': 6}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal', 'congruent': 8}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_PSE', 'congruent': 9}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 32, 'type': 'addresses_A', 'congruent': 6}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WT', 'congruent': 4}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_PSE', 'congruent': 8}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WT', 'congruent': 8}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': True, 'AVXalign': False, 'size': 32, 'type': 'addresses_RW', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_D_ht', 'congruent': 10}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 1, 'type': 'addresses_WC_ht', 'congruent': 2}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': True, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 7}}
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal_ht', 'congruent': 3}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 0}}
{'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 8, 'type': 'addresses_WC_ht', 'congruent': 5}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WT_ht', 'congruent': 10}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_UC_ht', 'congruent': 9}}
{'dst': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_WC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 2}}
{'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 1, 'type': 'addresses_UC_ht', 'congruent': 2}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_A_ht', 'congruent': 11}}
{'dst': {'same': False, 'congruent': 7, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_WC_ht'}}
{'48': 4, '00': 1}
00 48 48 48 48
*/
|
; A047484: Numbers that are congruent to {3, 5, 7} mod 8.
; Submitted by Christian Krause
; 3,5,7,11,13,15,19,21,23,27,29,31,35,37,39,43,45,47,51,53,55,59,61,63,67,69,71,75,77,79,83,85,87,91,93,95,99,101,103,107,109,111,115,117,119,123,125,127,131,133,135,139,141,143,147,149,151,155,157,159,163,165,167,171,173,175,179,181,183,187,189,191,195,197,199,203,205,207,211,213,215,219,221,223,227,229,231,235,237,239,243,245,247,251,253,255,259,261,263,267
mul $0,36
div $0,27
mul $0,2
add $0,3
|
; int __FASTCALL__ putchar(int c)
; 06.2008 aralbrec
PUBLIC putchar
EXTERN fputc_callee
EXTERN ASMDISP_FPUTC_CALLEE, _stdout
.putchar
ld ix,(_stdout)
jp fputc_callee + ASMDISP_FPUTC_CALLEE
|
; A212764: Number of (w,x,y,z) with all terms in {0,...,n}, w, x and y odd, and z odd.
; 0,1,8,16,54,81,192,256,500,625,1080,1296,2058,2401,3584,4096,5832,6561,9000,10000,13310,14641,19008,20736,26364,28561,35672,38416,47250,50625,61440,65536,78608,83521,99144,104976,123462,130321
add $0,1
mov $1,1
add $1,$0
div $1,2
pow $1,3
mov $2,$0
div $2,2
mul $2,2
lpb $0
sub $0,1
mul $1,$2
mov $2,1
lpe
div $1,2
mov $0,$1
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Berkeley Softworks 1990 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: laserjet print driver
FILE: textInitFontPCL4.asm
AUTHOR: Dave Durran
ROUTINES:
Name Description
---- -----------
PrInitFont Set default font to courier 10 pitch
PrintSetURWMono12 Set text mode font to URW Mono 12 pt
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 1/22/92 Initial revision from laserdwnText.asm
DESCRIPTION:
This file contains most of the code to implement the PCL 4
print driver ascii text support
$Id: textInitFontPCL4.asm,v 1.1 97/04/18 11:50:01 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrInitFont
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS:
CALLED BY:
PrintStartJob
PASS:
es - Segment of PSTATE
RETURN:
nothing
DESTROYED:
ax, bx, cx, si, di, es, ds
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 02/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrInitFont proc near
call PrintSetURWMono12 ;set the font.
call FontInit ;init the font manager.
ret
PrInitFont endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrintSetURWMono12
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set font for text mode to URW Mono 12 pt which is the same as
courier 10 pitch
CALLED BY: GLOBAL
PASS: es - Segment of PSTATE
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 02/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrintSetURWMono12 proc near
mov es:PS_curFont.FE_fontID,FID_DTC_URW_MONO ;set mono
mov es:PS_curFont.FE_size,12 ;12 point font.
mov {word} es:PS_curOptFont.OFE_trackKern,0 ;+
ret
PrintSetURWMono12 endp
|
; pgrm.asm
; Search an array to see if it contains a known value.
; Assumptions:
; R4 initially contains the start address of the array.
; R5 initially contains the number of elements in the array.
; R3 initially contains the “value of interest”.
; If the “value of interest” is in the array, then at the end of execution, R6
; will contain the index of the element that contains the “value of interest”.
; If the “value of interest” is not in the array, then at the end of execution,
; R6 will contain –1.
; Equivalent C-like pseudo-code:
; r6 = -1 // Initially, the value has not yet been.
; for(r7 = 0, r7 < r5, r7++) // r5 == array size
; {
; if(array[r7] == r3) // Found!
; {
; r6 = r7; // Save index.
; break; // Exit loop.
; }
; }
mov r5, #20 ; # Elements in array.
mov r4, #0x1234 ; Start address
mov r3, #'a' ; Value of interest.
str r3, [r4, #4] ; Store value of interest at array[2].
mvn r6, #0 ; r6 = -1
mov r7, #0 ; Initialize loop r7 = 0.
b TestForDone ; Test for done at end of loop!
DoFor ldr r8, [r4, r7] ; Get element array[r7]
cmp r8, r3 ; Element == value of interest.
bne IncR7 ; No - Continue loop.
mov r6, r7 ; Yes - Save index.
b DoneFor ; - Break.
IncR7 add r7, r7, #1 ; r7++
TestForDone cmp r7, r5 ; r7 < r5
blt DoFor ; Yes - Do loop body again.
DoneFor ; Continue.
|
//===-- ArchSpec.cpp --------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Core/ArchSpec.h"
#include <stdio.h>
#include <errno.h>
#include <string>
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/ELF.h"
#include "llvm/Support/Host.h"
#include "lldb/Core/RegularExpression.h"
#include "lldb/Core/StringList.h"
#include "lldb/Host/Endian.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Target/Platform.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/NameMatches.h"
#include "lldb/Utility/SafeMachO.h"
#include "Plugins/Process/Utility/ARMDefines.h"
#include "Plugins/Process/Utility/InstructionUtils.h"
using namespace lldb;
using namespace lldb_private;
#define ARCH_SPEC_SEPARATOR_CHAR '-'
static bool cores_match (const ArchSpec::Core core1, const ArchSpec::Core core2, bool try_inverse, bool enforce_exact_match);
namespace lldb_private {
struct CoreDefinition
{
ByteOrder default_byte_order;
uint32_t addr_byte_size;
uint32_t min_opcode_byte_size;
uint32_t max_opcode_byte_size;
llvm::Triple::ArchType machine;
ArchSpec::Core core;
const char * const name;
};
}
// This core information can be looked using the ArchSpec::Core as the index
static const CoreDefinition g_core_definitions[] =
{
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_generic , "arm" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv4 , "armv4" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv4t , "armv4t" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv5 , "armv5" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv5e , "armv5e" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv5t , "armv5t" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv6 , "armv6" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv6m , "armv6m" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7 , "armv7" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7f , "armv7f" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7s , "armv7s" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7k , "armv7k" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7m , "armv7m" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_armv7em , "armv7em" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::arm , ArchSpec::eCore_arm_xscale , "xscale" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumb , "thumb" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv4t , "thumbv4t" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv5 , "thumbv5" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv5e , "thumbv5e" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv6 , "thumbv6" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv6m , "thumbv6m" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7 , "thumbv7" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7f , "thumbv7f" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7s , "thumbv7s" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7k , "thumbv7k" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7m , "thumbv7m" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::thumb , ArchSpec::eCore_thumbv7em , "thumbv7em" },
{ eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, ArchSpec::eCore_arm_arm64 , "arm64" },
{ eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, ArchSpec::eCore_arm_armv8 , "armv8" },
{ eByteOrderLittle, 8, 4, 4, llvm::Triple::aarch64, ArchSpec::eCore_arm_aarch64 , "aarch64" },
// mips32, mips32r2, mips32r3, mips32r5, mips32r6
{ eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32 , "mips" },
{ eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32r2 , "mipsr2" },
{ eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32r3 , "mipsr3" },
{ eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32r5 , "mipsr5" },
{ eByteOrderBig , 4, 2, 4, llvm::Triple::mips , ArchSpec::eCore_mips32r6 , "mipsr6" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32el , "mipsel" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32r2el , "mipsr2el" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32r3el , "mipsr3el" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32r5el , "mipsr5el" },
{ eByteOrderLittle, 4, 2, 4, llvm::Triple::mipsel, ArchSpec::eCore_mips32r6el , "mipsr6el" },
// mips64, mips64r2, mips64r3, mips64r5, mips64r6
{ eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64 , "mips64" },
{ eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64r2 , "mips64r2" },
{ eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64r3 , "mips64r3" },
{ eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64r5 , "mips64r5" },
{ eByteOrderBig , 8, 2, 4, llvm::Triple::mips64 , ArchSpec::eCore_mips64r6 , "mips64r6" },
{ eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64el , "mips64el" },
{ eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64r2el , "mips64r2el" },
{ eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64r3el , "mips64r3el" },
{ eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64r5el , "mips64r5el" },
{ eByteOrderLittle, 8, 2, 4, llvm::Triple::mips64el, ArchSpec::eCore_mips64r6el , "mips64r6el" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_generic , "powerpc" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc601 , "ppc601" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc602 , "ppc602" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc603 , "ppc603" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc603e , "ppc603e" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc603ev , "ppc603ev" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc604 , "ppc604" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc604e , "ppc604e" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc620 , "ppc620" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc750 , "ppc750" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc7400 , "ppc7400" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc7450 , "ppc7450" },
{ eByteOrderBig , 4, 4, 4, llvm::Triple::ppc , ArchSpec::eCore_ppc_ppc970 , "ppc970" },
{ eByteOrderBig , 8, 4, 4, llvm::Triple::ppc64 , ArchSpec::eCore_ppc64_generic , "powerpc64" },
{ eByteOrderBig , 8, 4, 4, llvm::Triple::ppc64 , ArchSpec::eCore_ppc64_ppc970_64 , "ppc970-64" },
{ eByteOrderLittle, 4, 4, 4, llvm::Triple::sparc , ArchSpec::eCore_sparc_generic , "sparc" },
{ eByteOrderLittle, 8, 4, 4, llvm::Triple::sparcv9, ArchSpec::eCore_sparc9_generic , "sparcv9" },
{ eByteOrderLittle, 4, 1, 15, llvm::Triple::x86 , ArchSpec::eCore_x86_32_i386 , "i386" },
{ eByteOrderLittle, 4, 1, 15, llvm::Triple::x86 , ArchSpec::eCore_x86_32_i486 , "i486" },
{ eByteOrderLittle, 4, 1, 15, llvm::Triple::x86 , ArchSpec::eCore_x86_32_i486sx , "i486sx" },
{ eByteOrderLittle, 4, 1, 15, llvm::Triple::x86 , ArchSpec::eCore_x86_32_i686 , "i686" },
{ eByteOrderLittle, 8, 1, 15, llvm::Triple::x86_64 , ArchSpec::eCore_x86_64_x86_64 , "x86_64" },
{ eByteOrderLittle, 8, 1, 15, llvm::Triple::x86_64 , ArchSpec::eCore_x86_64_x86_64h , "x86_64h" },
{ eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon , ArchSpec::eCore_hexagon_generic, "hexagon" },
{ eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon , ArchSpec::eCore_hexagon_hexagonv4, "hexagonv4" },
{ eByteOrderLittle, 4, 4, 4, llvm::Triple::hexagon , ArchSpec::eCore_hexagon_hexagonv5, "hexagonv5" },
{ eByteOrderLittle, 4, 4, 4 , llvm::Triple::UnknownArch , ArchSpec::eCore_uknownMach32 , "unknown-mach-32" },
{ eByteOrderLittle, 8, 4, 4 , llvm::Triple::UnknownArch , ArchSpec::eCore_uknownMach64 , "unknown-mach-64" },
{ eByteOrderBig , 4, 1, 1 , llvm::Triple::kalimba , ArchSpec::eCore_kalimba3 , "kalimba3" },
{ eByteOrderLittle, 4, 1, 1 , llvm::Triple::kalimba , ArchSpec::eCore_kalimba4 , "kalimba4" },
{ eByteOrderLittle, 4, 1, 1 , llvm::Triple::kalimba , ArchSpec::eCore_kalimba5 , "kalimba5" }
};
// Ensure that we have an entry in the g_core_definitions for each core. If you comment out an entry above,
// you will need to comment out the corresponding ArchSpec::Core enumeration.
static_assert(sizeof(g_core_definitions) / sizeof(CoreDefinition) == ArchSpec::kNumCores, "make sure we have one core definition for each core");
struct ArchDefinitionEntry
{
ArchSpec::Core core;
uint32_t cpu;
uint32_t sub;
uint32_t cpu_mask;
uint32_t sub_mask;
};
struct ArchDefinition
{
ArchitectureType type;
size_t num_entries;
const ArchDefinitionEntry *entries;
const char *name;
};
size_t
ArchSpec::AutoComplete (const char *name, StringList &matches)
{
uint32_t i;
if (name && name[0])
{
for (i = 0; i < llvm::array_lengthof(g_core_definitions); ++i)
{
if (NameMatches(g_core_definitions[i].name, eNameMatchStartsWith, name))
matches.AppendString (g_core_definitions[i].name);
}
}
else
{
for (i = 0; i < llvm::array_lengthof(g_core_definitions); ++i)
matches.AppendString (g_core_definitions[i].name);
}
return matches.GetSize();
}
#define CPU_ANY (UINT32_MAX)
//===----------------------------------------------------------------------===//
// A table that gets searched linearly for matches. This table is used to
// convert cpu type and subtypes to architecture names, and to convert
// architecture names to cpu types and subtypes. The ordering is important and
// allows the precedence to be set when the table is built.
#define SUBTYPE_MASK 0x00FFFFFFu
static const ArchDefinitionEntry g_macho_arch_entries[] =
{
{ ArchSpec::eCore_arm_generic , llvm::MachO::CPU_TYPE_ARM , CPU_ANY, UINT32_MAX , UINT32_MAX },
{ ArchSpec::eCore_arm_generic , llvm::MachO::CPU_TYPE_ARM , 0 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv4 , llvm::MachO::CPU_TYPE_ARM , 5 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv4t , llvm::MachO::CPU_TYPE_ARM , 5 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv6 , llvm::MachO::CPU_TYPE_ARM , 6 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv6m , llvm::MachO::CPU_TYPE_ARM , 14 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv5 , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv5e , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv5t , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_xscale , llvm::MachO::CPU_TYPE_ARM , 8 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv7 , llvm::MachO::CPU_TYPE_ARM , 9 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv7f , llvm::MachO::CPU_TYPE_ARM , 10 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv7s , llvm::MachO::CPU_TYPE_ARM , 11 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv7k , llvm::MachO::CPU_TYPE_ARM , 12 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv7m , llvm::MachO::CPU_TYPE_ARM , 15 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_armv7em , llvm::MachO::CPU_TYPE_ARM , 16 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_arm64 , llvm::MachO::CPU_TYPE_ARM64 , 1 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_arm64 , llvm::MachO::CPU_TYPE_ARM64 , 0 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_arm64 , llvm::MachO::CPU_TYPE_ARM64 , 13 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_arm_arm64 , llvm::MachO::CPU_TYPE_ARM64 , CPU_ANY, UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumb , llvm::MachO::CPU_TYPE_ARM , 0 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv4t , llvm::MachO::CPU_TYPE_ARM , 5 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv5 , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv5e , llvm::MachO::CPU_TYPE_ARM , 7 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv6 , llvm::MachO::CPU_TYPE_ARM , 6 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv6m , llvm::MachO::CPU_TYPE_ARM , 14 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv7 , llvm::MachO::CPU_TYPE_ARM , 9 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv7f , llvm::MachO::CPU_TYPE_ARM , 10 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv7s , llvm::MachO::CPU_TYPE_ARM , 11 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv7k , llvm::MachO::CPU_TYPE_ARM , 12 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv7m , llvm::MachO::CPU_TYPE_ARM , 15 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_thumbv7em , llvm::MachO::CPU_TYPE_ARM , 16 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_generic , llvm::MachO::CPU_TYPE_POWERPC , CPU_ANY, UINT32_MAX , UINT32_MAX },
{ ArchSpec::eCore_ppc_generic , llvm::MachO::CPU_TYPE_POWERPC , 0 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc601 , llvm::MachO::CPU_TYPE_POWERPC , 1 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc602 , llvm::MachO::CPU_TYPE_POWERPC , 2 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc603 , llvm::MachO::CPU_TYPE_POWERPC , 3 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc603e , llvm::MachO::CPU_TYPE_POWERPC , 4 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc603ev , llvm::MachO::CPU_TYPE_POWERPC , 5 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc604 , llvm::MachO::CPU_TYPE_POWERPC , 6 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc604e , llvm::MachO::CPU_TYPE_POWERPC , 7 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc620 , llvm::MachO::CPU_TYPE_POWERPC , 8 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc750 , llvm::MachO::CPU_TYPE_POWERPC , 9 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc7400 , llvm::MachO::CPU_TYPE_POWERPC , 10 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc7450 , llvm::MachO::CPU_TYPE_POWERPC , 11 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc_ppc970 , llvm::MachO::CPU_TYPE_POWERPC , 100 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc64_generic , llvm::MachO::CPU_TYPE_POWERPC64 , 0 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_ppc64_ppc970_64 , llvm::MachO::CPU_TYPE_POWERPC64 , 100 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_x86_32_i386 , llvm::MachO::CPU_TYPE_I386 , 3 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_x86_32_i486 , llvm::MachO::CPU_TYPE_I386 , 4 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_x86_32_i486sx , llvm::MachO::CPU_TYPE_I386 , 0x84 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_x86_32_i386 , llvm::MachO::CPU_TYPE_I386 , CPU_ANY, UINT32_MAX , UINT32_MAX },
{ ArchSpec::eCore_x86_64_x86_64 , llvm::MachO::CPU_TYPE_X86_64 , 3 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_x86_64_x86_64 , llvm::MachO::CPU_TYPE_X86_64 , 4 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_x86_64_x86_64h , llvm::MachO::CPU_TYPE_X86_64 , 8 , UINT32_MAX , SUBTYPE_MASK },
{ ArchSpec::eCore_x86_64_x86_64 , llvm::MachO::CPU_TYPE_X86_64 , CPU_ANY, UINT32_MAX , UINT32_MAX },
// Catch any unknown mach architectures so we can always use the object and symbol mach-o files
{ ArchSpec::eCore_uknownMach32 , 0 , 0 , 0xFF000000u, 0x00000000u },
{ ArchSpec::eCore_uknownMach64 , llvm::MachO::CPU_ARCH_ABI64 , 0 , 0xFF000000u, 0x00000000u }
};
static const ArchDefinition g_macho_arch_def = {
eArchTypeMachO,
llvm::array_lengthof(g_macho_arch_entries),
g_macho_arch_entries,
"mach-o"
};
//===----------------------------------------------------------------------===//
// A table that gets searched linearly for matches. This table is used to
// convert cpu type and subtypes to architecture names, and to convert
// architecture names to cpu types and subtypes. The ordering is important and
// allows the precedence to be set when the table is built.
static const ArchDefinitionEntry g_elf_arch_entries[] =
{
{ ArchSpec::eCore_sparc_generic , llvm::ELF::EM_SPARC , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // Sparc
{ ArchSpec::eCore_x86_32_i386 , llvm::ELF::EM_386 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // Intel 80386
{ ArchSpec::eCore_x86_32_i486 , llvm::ELF::EM_IAMCU , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // Intel MCU // FIXME: is this correct?
{ ArchSpec::eCore_ppc_generic , llvm::ELF::EM_PPC , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // PowerPC
{ ArchSpec::eCore_ppc64_generic , llvm::ELF::EM_PPC64 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // PowerPC64
{ ArchSpec::eCore_arm_generic , llvm::ELF::EM_ARM , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARM
{ ArchSpec::eCore_arm_aarch64 , llvm::ELF::EM_AARCH64, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARM64
{ ArchSpec::eCore_sparc9_generic , llvm::ELF::EM_SPARCV9, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // SPARC V9
{ ArchSpec::eCore_x86_64_x86_64 , llvm::ELF::EM_X86_64 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // AMD64
{ ArchSpec::eCore_mips32 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32
{ ArchSpec::eCore_mips32r2 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32r2, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32r2
{ ArchSpec::eCore_mips32r6 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32r6, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32r6
{ ArchSpec::eCore_mips32el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32el
{ ArchSpec::eCore_mips32r2el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32r2el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32r2el
{ ArchSpec::eCore_mips32r6el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips32r6el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips32r6el
{ ArchSpec::eCore_mips64 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64
{ ArchSpec::eCore_mips64r2 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64r2, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64r2
{ ArchSpec::eCore_mips64r6 , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64r6, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64r6
{ ArchSpec::eCore_mips64el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64el
{ ArchSpec::eCore_mips64r2el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64r2el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64r2el
{ ArchSpec::eCore_mips64r6el , llvm::ELF::EM_MIPS , ArchSpec::eMIPSSubType_mips64r6el, 0xFFFFFFFFu, 0xFFFFFFFFu }, // mips64r6el
{ ArchSpec::eCore_hexagon_generic , llvm::ELF::EM_HEXAGON, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // HEXAGON
{ ArchSpec::eCore_kalimba3 , llvm::ELF::EM_CSR_KALIMBA, llvm::Triple::KalimbaSubArch_v3, 0xFFFFFFFFu, 0xFFFFFFFFu }, // KALIMBA
{ ArchSpec::eCore_kalimba4 , llvm::ELF::EM_CSR_KALIMBA, llvm::Triple::KalimbaSubArch_v4, 0xFFFFFFFFu, 0xFFFFFFFFu }, // KALIMBA
{ ArchSpec::eCore_kalimba5 , llvm::ELF::EM_CSR_KALIMBA, llvm::Triple::KalimbaSubArch_v5, 0xFFFFFFFFu, 0xFFFFFFFFu } // KALIMBA
};
static const ArchDefinition g_elf_arch_def = {
eArchTypeELF,
llvm::array_lengthof(g_elf_arch_entries),
g_elf_arch_entries,
"elf",
};
static const ArchDefinitionEntry g_coff_arch_entries[] =
{
{ ArchSpec::eCore_x86_32_i386 , llvm::COFF::IMAGE_FILE_MACHINE_I386 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // Intel 80x86
{ ArchSpec::eCore_ppc_generic , llvm::COFF::IMAGE_FILE_MACHINE_POWERPC , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // PowerPC
{ ArchSpec::eCore_ppc_generic , llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP, LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // PowerPC (with FPU)
{ ArchSpec::eCore_arm_generic , llvm::COFF::IMAGE_FILE_MACHINE_ARM , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARM
{ ArchSpec::eCore_arm_armv7 , llvm::COFF::IMAGE_FILE_MACHINE_ARMNT , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARMv7
{ ArchSpec::eCore_thumb , llvm::COFF::IMAGE_FILE_MACHINE_THUMB , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu }, // ARMv7
{ ArchSpec::eCore_x86_64_x86_64, llvm::COFF::IMAGE_FILE_MACHINE_AMD64 , LLDB_INVALID_CPUTYPE, 0xFFFFFFFFu, 0xFFFFFFFFu } // AMD64
};
static const ArchDefinition g_coff_arch_def = {
eArchTypeCOFF,
llvm::array_lengthof(g_coff_arch_entries),
g_coff_arch_entries,
"pe-coff",
};
//===----------------------------------------------------------------------===//
// Table of all ArchDefinitions
static const ArchDefinition *g_arch_definitions[] = {
&g_macho_arch_def,
&g_elf_arch_def,
&g_coff_arch_def
};
static const size_t k_num_arch_definitions = llvm::array_lengthof(g_arch_definitions);
//===----------------------------------------------------------------------===//
// Static helper functions.
// Get the architecture definition for a given object type.
static const ArchDefinition *
FindArchDefinition (ArchitectureType arch_type)
{
for (unsigned int i = 0; i < k_num_arch_definitions; ++i)
{
const ArchDefinition *def = g_arch_definitions[i];
if (def->type == arch_type)
return def;
}
return NULL;
}
// Get an architecture definition by name.
static const CoreDefinition *
FindCoreDefinition (llvm::StringRef name)
{
for (unsigned int i = 0; i < llvm::array_lengthof(g_core_definitions); ++i)
{
if (name.equals_lower(g_core_definitions[i].name))
return &g_core_definitions[i];
}
return NULL;
}
static inline const CoreDefinition *
FindCoreDefinition (ArchSpec::Core core)
{
if (core >= 0 && core < llvm::array_lengthof(g_core_definitions))
return &g_core_definitions[core];
return NULL;
}
// Get a definition entry by cpu type and subtype.
static const ArchDefinitionEntry *
FindArchDefinitionEntry (const ArchDefinition *def, uint32_t cpu, uint32_t sub)
{
if (def == NULL)
return NULL;
const ArchDefinitionEntry *entries = def->entries;
for (size_t i = 0; i < def->num_entries; ++i)
{
if (entries[i].cpu == (cpu & entries[i].cpu_mask))
if (entries[i].sub == (sub & entries[i].sub_mask))
return &entries[i];
}
return NULL;
}
static const ArchDefinitionEntry *
FindArchDefinitionEntry (const ArchDefinition *def, ArchSpec::Core core)
{
if (def == NULL)
return NULL;
const ArchDefinitionEntry *entries = def->entries;
for (size_t i = 0; i < def->num_entries; ++i)
{
if (entries[i].core == core)
return &entries[i];
}
return NULL;
}
//===----------------------------------------------------------------------===//
// Constructors and destructors.
ArchSpec::ArchSpec() :
m_triple (),
m_core (kCore_invalid),
m_byte_order (eByteOrderInvalid),
m_flags (0),
m_distribution_id ()
{
}
ArchSpec::ArchSpec (const char *triple_cstr, Platform *platform) :
m_triple (),
m_core (kCore_invalid),
m_byte_order (eByteOrderInvalid),
m_flags (0),
m_distribution_id ()
{
if (triple_cstr)
SetTriple(triple_cstr, platform);
}
ArchSpec::ArchSpec (const char *triple_cstr) :
m_triple (),
m_core (kCore_invalid),
m_byte_order (eByteOrderInvalid),
m_flags (0),
m_distribution_id ()
{
if (triple_cstr)
SetTriple(triple_cstr);
}
ArchSpec::ArchSpec(const llvm::Triple &triple) :
m_triple (),
m_core (kCore_invalid),
m_byte_order (eByteOrderInvalid),
m_flags (0),
m_distribution_id ()
{
SetTriple(triple);
}
ArchSpec::ArchSpec (ArchitectureType arch_type, uint32_t cpu, uint32_t subtype) :
m_triple (),
m_core (kCore_invalid),
m_byte_order (eByteOrderInvalid),
m_flags (0),
m_distribution_id ()
{
SetArchitecture (arch_type, cpu, subtype);
}
ArchSpec::~ArchSpec()
{
}
//===----------------------------------------------------------------------===//
// Assignment and initialization.
const ArchSpec&
ArchSpec::operator= (const ArchSpec& rhs)
{
if (this != &rhs)
{
m_triple = rhs.m_triple;
m_core = rhs.m_core;
m_byte_order = rhs.m_byte_order;
m_distribution_id = rhs.m_distribution_id;
m_flags = rhs.m_flags;
}
return *this;
}
void
ArchSpec::Clear()
{
m_triple = llvm::Triple();
m_core = kCore_invalid;
m_byte_order = eByteOrderInvalid;
m_distribution_id.Clear ();
m_flags = 0;
}
//===----------------------------------------------------------------------===//
// Predicates.
const char *
ArchSpec::GetArchitectureName () const
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
return core_def->name;
return "unknown";
}
uint32_t
ArchSpec::GetMachOCPUType () const
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
{
const ArchDefinitionEntry *arch_def = FindArchDefinitionEntry (&g_macho_arch_def, core_def->core);
if (arch_def)
{
return arch_def->cpu;
}
}
return LLDB_INVALID_CPUTYPE;
}
uint32_t
ArchSpec::GetMachOCPUSubType () const
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
{
const ArchDefinitionEntry *arch_def = FindArchDefinitionEntry (&g_macho_arch_def, core_def->core);
if (arch_def)
{
return arch_def->sub;
}
}
return LLDB_INVALID_CPUTYPE;
}
uint32_t
ArchSpec::GetDataByteSize () const
{
switch (m_core)
{
case eCore_kalimba3:
return 4;
case eCore_kalimba4:
return 1;
case eCore_kalimba5:
return 4;
default:
return 1;
}
return 1;
}
uint32_t
ArchSpec::GetCodeByteSize () const
{
switch (m_core)
{
case eCore_kalimba3:
return 4;
case eCore_kalimba4:
return 1;
case eCore_kalimba5:
return 1;
default:
return 1;
}
return 1;
}
llvm::Triple::ArchType
ArchSpec::GetMachine () const
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
return core_def->machine;
return llvm::Triple::UnknownArch;
}
const ConstString&
ArchSpec::GetDistributionId () const
{
return m_distribution_id;
}
void
ArchSpec::SetDistributionId (const char* distribution_id)
{
m_distribution_id.SetCString (distribution_id);
}
uint32_t
ArchSpec::GetAddressByteSize() const
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
{
if (core_def->machine == llvm::Triple::mips64 || core_def->machine == llvm::Triple::mips64el)
{
// For N32/O32 applications Address size is 4 bytes.
if (m_flags & (eMIPSABI_N32 | eMIPSABI_O32))
return 4;
}
return core_def->addr_byte_size;
}
return 0;
}
ByteOrder
ArchSpec::GetDefaultEndian () const
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
return core_def->default_byte_order;
return eByteOrderInvalid;
}
bool
ArchSpec::CharIsSignedByDefault () const
{
switch (m_triple.getArch()) {
default:
return true;
case llvm::Triple::aarch64:
case llvm::Triple::aarch64_be:
case llvm::Triple::arm:
case llvm::Triple::armeb:
case llvm::Triple::thumb:
case llvm::Triple::thumbeb:
return m_triple.isOSDarwin() || m_triple.isOSWindows();
case llvm::Triple::ppc:
case llvm::Triple::ppc64:
return m_triple.isOSDarwin();
case llvm::Triple::ppc64le:
case llvm::Triple::systemz:
case llvm::Triple::xcore:
return false;
}
}
lldb::ByteOrder
ArchSpec::GetByteOrder () const
{
if (m_byte_order == eByteOrderInvalid)
return GetDefaultEndian();
return m_byte_order;
}
//===----------------------------------------------------------------------===//
// Mutators.
bool
ArchSpec::SetTriple (const llvm::Triple &triple)
{
m_triple = triple;
llvm::StringRef arch_name (m_triple.getArchName());
const CoreDefinition *core_def = FindCoreDefinition (arch_name);
if (core_def)
{
m_core = core_def->core;
// Set the byte order to the default byte order for an architecture.
// This can be modified if needed for cases when cores handle both
// big and little endian
m_byte_order = core_def->default_byte_order;
}
else
{
Clear();
}
return IsValid();
}
static bool
ParseMachCPUDashSubtypeTriple (const char *triple_cstr, ArchSpec &arch)
{
// Accept "12-10" or "12.10" as cpu type/subtype
if (isdigit(triple_cstr[0]))
{
char *end = NULL;
errno = 0;
uint32_t cpu = (uint32_t)::strtoul (triple_cstr, &end, 0);
if (errno == 0 && cpu != 0 && end && ((*end == '-') || (*end == '.')))
{
errno = 0;
uint32_t sub = (uint32_t)::strtoul (end + 1, &end, 0);
if (errno == 0 && end && ((*end == '-') || (*end == '.') || (*end == '\0')))
{
if (arch.SetArchitecture (eArchTypeMachO, cpu, sub))
{
if (*end == '-')
{
llvm::StringRef vendor_os (end + 1);
size_t dash_pos = vendor_os.find('-');
if (dash_pos != llvm::StringRef::npos)
{
llvm::StringRef vendor_str(vendor_os.substr(0, dash_pos));
arch.GetTriple().setVendorName(vendor_str);
const size_t vendor_start_pos = dash_pos+1;
dash_pos = vendor_os.find('-', vendor_start_pos);
if (dash_pos == llvm::StringRef::npos)
{
if (vendor_start_pos < vendor_os.size())
arch.GetTriple().setOSName(vendor_os.substr(vendor_start_pos));
}
else
{
arch.GetTriple().setOSName(vendor_os.substr(vendor_start_pos, dash_pos - vendor_start_pos));
}
}
}
return true;
}
}
}
}
return false;
}
bool
ArchSpec::SetTriple (const char *triple_cstr)
{
if (triple_cstr && triple_cstr[0])
{
if (ParseMachCPUDashSubtypeTriple (triple_cstr, *this))
return true;
llvm::StringRef triple_stref (triple_cstr);
if (triple_stref.startswith (LLDB_ARCH_DEFAULT))
{
// Special case for the current host default architectures...
if (triple_stref.equals (LLDB_ARCH_DEFAULT_32BIT))
*this = HostInfo::GetArchitecture(HostInfo::eArchKind32);
else if (triple_stref.equals (LLDB_ARCH_DEFAULT_64BIT))
*this = HostInfo::GetArchitecture(HostInfo::eArchKind64);
else if (triple_stref.equals (LLDB_ARCH_DEFAULT))
*this = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
}
else
{
std::string normalized_triple_sstr (llvm::Triple::normalize(triple_stref));
triple_stref = normalized_triple_sstr;
SetTriple (llvm::Triple (triple_stref));
}
}
else
Clear();
return IsValid();
}
bool
ArchSpec::SetTriple (const char *triple_cstr, Platform *platform)
{
if (triple_cstr && triple_cstr[0])
{
if (ParseMachCPUDashSubtypeTriple (triple_cstr, *this))
return true;
llvm::StringRef triple_stref (triple_cstr);
if (triple_stref.startswith (LLDB_ARCH_DEFAULT))
{
// Special case for the current host default architectures...
if (triple_stref.equals (LLDB_ARCH_DEFAULT_32BIT))
*this = HostInfo::GetArchitecture(HostInfo::eArchKind32);
else if (triple_stref.equals (LLDB_ARCH_DEFAULT_64BIT))
*this = HostInfo::GetArchitecture(HostInfo::eArchKind64);
else if (triple_stref.equals (LLDB_ARCH_DEFAULT))
*this = HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
}
else
{
ArchSpec raw_arch (triple_cstr);
std::string normalized_triple_sstr (llvm::Triple::normalize(triple_stref));
triple_stref = normalized_triple_sstr;
llvm::Triple normalized_triple (triple_stref);
const bool os_specified = normalized_triple.getOSName().size() > 0;
const bool vendor_specified = normalized_triple.getVendorName().size() > 0;
const bool env_specified = normalized_triple.getEnvironmentName().size() > 0;
// If we got an arch only, then default the vendor, os, environment
// to match the platform if one is supplied
if (!(os_specified || vendor_specified || env_specified))
{
if (platform)
{
// If we were given a platform, use the platform's system
// architecture. If this is not available (might not be
// connected) use the first supported architecture.
ArchSpec compatible_arch;
if (platform->IsCompatibleArchitecture (raw_arch, false, &compatible_arch))
{
if (compatible_arch.IsValid())
{
const llvm::Triple &compatible_triple = compatible_arch.GetTriple();
if (!vendor_specified)
normalized_triple.setVendor(compatible_triple.getVendor());
if (!os_specified)
normalized_triple.setOS(compatible_triple.getOS());
if (!env_specified && compatible_triple.getEnvironmentName().size())
normalized_triple.setEnvironment(compatible_triple.getEnvironment());
}
}
else
{
*this = raw_arch;
return IsValid();
}
}
else
{
// No platform specified, fall back to the host system for
// the default vendor, os, and environment.
llvm::Triple host_triple(llvm::sys::getDefaultTargetTriple());
if (!vendor_specified)
normalized_triple.setVendor(host_triple.getVendor());
if (!vendor_specified)
normalized_triple.setOS(host_triple.getOS());
if (!env_specified && host_triple.getEnvironmentName().size())
normalized_triple.setEnvironment(host_triple.getEnvironment());
}
}
SetTriple (normalized_triple);
}
}
else
Clear();
return IsValid();
}
void
ArchSpec::MergeFrom(const ArchSpec &other)
{
if (TripleVendorIsUnspecifiedUnknown() && !other.TripleVendorIsUnspecifiedUnknown())
GetTriple().setVendor(other.GetTriple().getVendor());
if (TripleOSIsUnspecifiedUnknown() && !other.TripleOSIsUnspecifiedUnknown())
GetTriple().setOS(other.GetTriple().getOS());
if (GetTriple().getArch() == llvm::Triple::UnknownArch)
GetTriple().setArch(other.GetTriple().getArch());
if (GetTriple().getEnvironment() == llvm::Triple::UnknownEnvironment && !TripleVendorWasSpecified())
{
if (other.TripleVendorWasSpecified())
GetTriple().setEnvironment(other.GetTriple().getEnvironment());
}
}
bool
ArchSpec::SetArchitecture (ArchitectureType arch_type, uint32_t cpu, uint32_t sub, uint32_t os)
{
m_core = kCore_invalid;
bool update_triple = true;
const ArchDefinition *arch_def = FindArchDefinition(arch_type);
if (arch_def)
{
const ArchDefinitionEntry *arch_def_entry = FindArchDefinitionEntry (arch_def, cpu, sub);
if (arch_def_entry)
{
const CoreDefinition *core_def = FindCoreDefinition (arch_def_entry->core);
if (core_def)
{
m_core = core_def->core;
update_triple = false;
// Always use the architecture name because it might be more descriptive
// than the architecture enum ("armv7" -> llvm::Triple::arm).
m_triple.setArchName(llvm::StringRef(core_def->name));
if (arch_type == eArchTypeMachO)
{
m_triple.setVendor (llvm::Triple::Apple);
// Don't set the OS. It could be simulator, macosx, ios, watchos, tvos. We could
// get close with the cpu type - but we can't get it right all of the time. Better
// to leave this unset so other sections of code will set it when they have more
// information.
// NB: don't call m_triple.setOS (llvm::Triple::UnknownOS). That sets the OSName to
// "unknown" and the ArchSpec::TripleVendorWasSpecified() method says that any
// OSName setting means it was specified.
}
else if (arch_type == eArchTypeELF)
{
switch (os)
{
case llvm::ELF::ELFOSABI_AIX: m_triple.setOS (llvm::Triple::OSType::AIX); break;
case llvm::ELF::ELFOSABI_FREEBSD: m_triple.setOS (llvm::Triple::OSType::FreeBSD); break;
case llvm::ELF::ELFOSABI_GNU: m_triple.setOS (llvm::Triple::OSType::Linux); break;
case llvm::ELF::ELFOSABI_NETBSD: m_triple.setOS (llvm::Triple::OSType::NetBSD); break;
case llvm::ELF::ELFOSABI_OPENBSD: m_triple.setOS (llvm::Triple::OSType::OpenBSD); break;
case llvm::ELF::ELFOSABI_SOLARIS: m_triple.setOS (llvm::Triple::OSType::Solaris); break;
}
}
else
{
m_triple.setVendor (llvm::Triple::UnknownVendor);
m_triple.setOS (llvm::Triple::UnknownOS);
}
// Fall back onto setting the machine type if the arch by name failed...
if (m_triple.getArch () == llvm::Triple::UnknownArch)
m_triple.setArch (core_def->machine);
}
}
}
CoreUpdated(update_triple);
return IsValid();
}
uint32_t
ArchSpec::GetMinimumOpcodeByteSize() const
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
return core_def->min_opcode_byte_size;
return 0;
}
uint32_t
ArchSpec::GetMaximumOpcodeByteSize() const
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
return core_def->max_opcode_byte_size;
return 0;
}
bool
ArchSpec::IsExactMatch (const ArchSpec& rhs) const
{
return IsEqualTo (rhs, true);
}
bool
ArchSpec::IsCompatibleMatch (const ArchSpec& rhs) const
{
return IsEqualTo (rhs, false);
}
bool
ArchSpec::IsEqualTo (const ArchSpec& rhs, bool exact_match) const
{
// explicitly ignoring m_distribution_id in this method.
if (GetByteOrder() != rhs.GetByteOrder())
return false;
const ArchSpec::Core lhs_core = GetCore ();
const ArchSpec::Core rhs_core = rhs.GetCore ();
const bool core_match = cores_match (lhs_core, rhs_core, true, exact_match);
if (core_match)
{
const llvm::Triple &lhs_triple = GetTriple();
const llvm::Triple &rhs_triple = rhs.GetTriple();
const llvm::Triple::VendorType lhs_triple_vendor = lhs_triple.getVendor();
const llvm::Triple::VendorType rhs_triple_vendor = rhs_triple.getVendor();
if (lhs_triple_vendor != rhs_triple_vendor)
{
const bool rhs_vendor_specified = rhs.TripleVendorWasSpecified();
const bool lhs_vendor_specified = TripleVendorWasSpecified();
// Both architectures had the vendor specified, so if they aren't
// equal then we return false
if (rhs_vendor_specified && lhs_vendor_specified)
return false;
// Only fail if both vendor types are not unknown
if (lhs_triple_vendor != llvm::Triple::UnknownVendor &&
rhs_triple_vendor != llvm::Triple::UnknownVendor)
return false;
}
const llvm::Triple::OSType lhs_triple_os = lhs_triple.getOS();
const llvm::Triple::OSType rhs_triple_os = rhs_triple.getOS();
if (lhs_triple_os != rhs_triple_os)
{
const bool rhs_os_specified = rhs.TripleOSWasSpecified();
const bool lhs_os_specified = TripleOSWasSpecified();
// Both architectures had the OS specified, so if they aren't
// equal then we return false
if (rhs_os_specified && lhs_os_specified)
return false;
// Only fail if both os types are not unknown
if (lhs_triple_os != llvm::Triple::UnknownOS &&
rhs_triple_os != llvm::Triple::UnknownOS)
return false;
}
const llvm::Triple::EnvironmentType lhs_triple_env = lhs_triple.getEnvironment();
const llvm::Triple::EnvironmentType rhs_triple_env = rhs_triple.getEnvironment();
if (lhs_triple_env != rhs_triple_env)
{
// Only fail if both environment types are not unknown
if (lhs_triple_env != llvm::Triple::UnknownEnvironment &&
rhs_triple_env != llvm::Triple::UnknownEnvironment)
return false;
}
return true;
}
return false;
}
//===----------------------------------------------------------------------===//
// Helper methods.
void
ArchSpec::CoreUpdated (bool update_triple)
{
const CoreDefinition *core_def = FindCoreDefinition (m_core);
if (core_def)
{
if (update_triple)
m_triple = llvm::Triple(core_def->name, "unknown", "unknown");
m_byte_order = core_def->default_byte_order;
}
else
{
if (update_triple)
m_triple = llvm::Triple();
m_byte_order = eByteOrderInvalid;
}
}
//===----------------------------------------------------------------------===//
// Operators.
static bool
cores_match (const ArchSpec::Core core1, const ArchSpec::Core core2, bool try_inverse, bool enforce_exact_match)
{
if (core1 == core2)
return true;
switch (core1)
{
case ArchSpec::kCore_any:
return true;
case ArchSpec::eCore_arm_generic:
if (enforce_exact_match)
break;
// Fall through to case below
case ArchSpec::kCore_arm_any:
if (core2 >= ArchSpec::kCore_arm_first && core2 <= ArchSpec::kCore_arm_last)
return true;
if (core2 >= ArchSpec::kCore_thumb_first && core2 <= ArchSpec::kCore_thumb_last)
return true;
if (core2 == ArchSpec::kCore_arm_any)
return true;
break;
case ArchSpec::kCore_x86_32_any:
if ((core2 >= ArchSpec::kCore_x86_32_first && core2 <= ArchSpec::kCore_x86_32_last) || (core2 == ArchSpec::kCore_x86_32_any))
return true;
break;
case ArchSpec::kCore_x86_64_any:
if ((core2 >= ArchSpec::kCore_x86_64_first && core2 <= ArchSpec::kCore_x86_64_last) || (core2 == ArchSpec::kCore_x86_64_any))
return true;
break;
case ArchSpec::kCore_ppc_any:
if ((core2 >= ArchSpec::kCore_ppc_first && core2 <= ArchSpec::kCore_ppc_last) || (core2 == ArchSpec::kCore_ppc_any))
return true;
break;
case ArchSpec::kCore_ppc64_any:
if ((core2 >= ArchSpec::kCore_ppc64_first && core2 <= ArchSpec::kCore_ppc64_last) || (core2 == ArchSpec::kCore_ppc64_any))
return true;
break;
case ArchSpec::eCore_arm_armv6m:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_arm_generic)
return true;
try_inverse = false;
if (core2 == ArchSpec::eCore_arm_armv7)
return true;
if (core2 == ArchSpec::eCore_arm_armv6m)
return true;
}
break;
case ArchSpec::kCore_hexagon_any:
if ((core2 >= ArchSpec::kCore_hexagon_first && core2 <= ArchSpec::kCore_hexagon_last) || (core2 == ArchSpec::kCore_hexagon_any))
return true;
break;
// v. https://en.wikipedia.org/wiki/ARM_Cortex-M#Silicon_customization
// Cortex-M0 - ARMv6-M - armv6m
// Cortex-M3 - ARMv7-M - armv7m
// Cortex-M4 - ARMv7E-M - armv7em
case ArchSpec::eCore_arm_armv7em:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_arm_generic)
return true;
if (core2 == ArchSpec::eCore_arm_armv7m)
return true;
if (core2 == ArchSpec::eCore_arm_armv6m)
return true;
if (core2 == ArchSpec::eCore_arm_armv7)
return true;
try_inverse = true;
}
break;
// v. https://en.wikipedia.org/wiki/ARM_Cortex-M#Silicon_customization
// Cortex-M0 - ARMv6-M - armv6m
// Cortex-M3 - ARMv7-M - armv7m
// Cortex-M4 - ARMv7E-M - armv7em
case ArchSpec::eCore_arm_armv7m:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_arm_generic)
return true;
if (core2 == ArchSpec::eCore_arm_armv6m)
return true;
if (core2 == ArchSpec::eCore_arm_armv7)
return true;
if (core2 == ArchSpec::eCore_arm_armv7em)
return true;
try_inverse = true;
}
break;
case ArchSpec::eCore_arm_armv7f:
case ArchSpec::eCore_arm_armv7k:
case ArchSpec::eCore_arm_armv7s:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_arm_generic)
return true;
if (core2 == ArchSpec::eCore_arm_armv7)
return true;
try_inverse = false;
}
break;
case ArchSpec::eCore_x86_64_x86_64h:
if (!enforce_exact_match)
{
try_inverse = false;
if (core2 == ArchSpec::eCore_x86_64_x86_64)
return true;
}
break;
case ArchSpec::eCore_arm_armv8:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_arm_arm64)
return true;
if (core2 == ArchSpec::eCore_arm_aarch64)
return true;
try_inverse = false;
}
break;
case ArchSpec::eCore_arm_aarch64:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_arm_arm64)
return true;
if (core2 == ArchSpec::eCore_arm_armv8)
return true;
try_inverse = false;
}
break;
case ArchSpec::eCore_arm_arm64:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_arm_aarch64)
return true;
if (core2 == ArchSpec::eCore_arm_armv8)
return true;
try_inverse = false;
}
break;
case ArchSpec::eCore_mips32:
if (!enforce_exact_match)
{
if (core2 >= ArchSpec::kCore_mips32_first && core2 <= ArchSpec::kCore_mips32_last)
return true;
try_inverse = false;
}
break;
case ArchSpec::eCore_mips32el:
if (!enforce_exact_match)
{
if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= ArchSpec::kCore_mips32el_last)
return true;
try_inverse = false;
}
case ArchSpec::eCore_mips64:
if (!enforce_exact_match)
{
if (core2 >= ArchSpec::kCore_mips32_first && core2 <= ArchSpec::kCore_mips32_last)
return true;
if (core2 >= ArchSpec::kCore_mips64_first && core2 <= ArchSpec::kCore_mips64_last)
return true;
try_inverse = false;
}
case ArchSpec::eCore_mips64el:
if (!enforce_exact_match)
{
if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= ArchSpec::kCore_mips32el_last)
return true;
if (core2 >= ArchSpec::kCore_mips64el_first && core2 <= ArchSpec::kCore_mips64el_last)
return true;
try_inverse = false;
}
case ArchSpec::eCore_mips64r2:
case ArchSpec::eCore_mips64r3:
case ArchSpec::eCore_mips64r5:
if (!enforce_exact_match)
{
if (core2 >= ArchSpec::kCore_mips32_first && core2 <= (core1 - 10))
return true;
if (core2 >= ArchSpec::kCore_mips64_first && core2 <= (core1 - 1))
return true;
try_inverse = false;
}
break;
case ArchSpec::eCore_mips64r2el:
case ArchSpec::eCore_mips64r3el:
case ArchSpec::eCore_mips64r5el:
if (!enforce_exact_match)
{
if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= (core1 - 10))
return true;
if (core2 >= ArchSpec::kCore_mips64el_first && core2 <= (core1 - 1))
return true;
try_inverse = false;
}
break;
case ArchSpec::eCore_mips32r2:
case ArchSpec::eCore_mips32r3:
case ArchSpec::eCore_mips32r5:
if (!enforce_exact_match)
{
if (core2 >= ArchSpec::kCore_mips32_first && core2 <= core1)
return true;
}
break;
case ArchSpec::eCore_mips32r2el:
case ArchSpec::eCore_mips32r3el:
case ArchSpec::eCore_mips32r5el:
if (!enforce_exact_match)
{
if (core2 >= ArchSpec::kCore_mips32el_first && core2 <= core1)
return true;
}
break;
case ArchSpec::eCore_mips32r6:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_mips32 || core2 == ArchSpec::eCore_mips32r6)
return true;
}
break;
case ArchSpec::eCore_mips32r6el:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_mips32el || core2 == ArchSpec::eCore_mips32r6el)
return true;
return true;
}
break;
case ArchSpec::eCore_mips64r6:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_mips32 || core2 == ArchSpec::eCore_mips32r6)
return true;
if (core2 == ArchSpec::eCore_mips64 || core2 == ArchSpec::eCore_mips64r6)
return true;
}
break;
case ArchSpec::eCore_mips64r6el:
if (!enforce_exact_match)
{
if (core2 == ArchSpec::eCore_mips32el || core2 == ArchSpec::eCore_mips32r6el)
return true;
if (core2 == ArchSpec::eCore_mips64el || core2 == ArchSpec::eCore_mips64r6el)
return true;
}
break;
default:
break;
}
if (try_inverse)
return cores_match (core2, core1, false, enforce_exact_match);
return false;
}
bool
lldb_private::operator<(const ArchSpec& lhs, const ArchSpec& rhs)
{
const ArchSpec::Core lhs_core = lhs.GetCore ();
const ArchSpec::Core rhs_core = rhs.GetCore ();
return lhs_core < rhs_core;
}
static void
StopInfoOverrideCallbackTypeARM(lldb_private::Thread &thread)
{
// We need to check if we are stopped in Thumb mode in a IT instruction
// and detect if the condition doesn't pass. If this is the case it means
// we won't actually execute this instruction. If this happens we need to
// clear the stop reason to no thread plans think we are stopped for a
// reason and the plans should keep going.
//
// We do this because when single stepping many ARM processes, debuggers
// often use the BVR/BCR registers that says "stop when the PC is not
// equal to its current value". This method of stepping means we can end
// up stopping on instructions inside an if/then block that wouldn't get
// executed. By fixing this we can stop the debugger from seeming like
// you stepped through both the "if" _and_ the "else" clause when source
// level stepping because the debugger stops regardless due to the BVR/BCR
// triggering a stop.
//
// It also means we can set breakpoints on instructions inside an an
// if/then block and correctly skip them if we use the BKPT instruction.
// The ARM and Thumb BKPT instructions are unconditional even when executed
// in a Thumb IT block.
//
// If your debugger inserts software traps in ARM/Thumb code, it will
// need to use 16 and 32 bit instruction for 16 and 32 bit thumb
// instructions respectively. If your debugger inserts a 16 bit thumb
// trap on top of a 32 bit thumb instruction for an opcode that is inside
// an if/then, it will change the it/then to conditionally execute your
// 16 bit trap and then cause your program to crash if it executes the
// trailing 16 bits (the second half of the 32 bit thumb instruction you
// partially overwrote).
RegisterContextSP reg_ctx_sp (thread.GetRegisterContext());
if (reg_ctx_sp)
{
const uint32_t cpsr = reg_ctx_sp->GetFlags(0);
if (cpsr != 0)
{
// Read the J and T bits to get the ISETSTATE
const uint32_t J = Bit32(cpsr, 24);
const uint32_t T = Bit32(cpsr, 5);
const uint32_t ISETSTATE = J << 1 | T;
if (ISETSTATE == 0)
{
// NOTE: I am pretty sure we want to enable the code below
// that detects when we stop on an instruction in ARM mode
// that is conditional and the condition doesn't pass. This
// can happen if you set a breakpoint on an instruction that
// is conditional. We currently will _always_ stop on the
// instruction which is bad. You can also run into this while
// single stepping and you could appear to run code in the "if"
// and in the "else" clause because it would stop at all of the
// conditional instructions in both.
// In such cases, we really don't want to stop at this location.
// I will check with the lldb-dev list first before I enable this.
#if 0
// ARM mode: check for condition on intsruction
const addr_t pc = reg_ctx_sp->GetPC();
Error error;
// If we fail to read the opcode we will get UINT64_MAX as the
// result in "opcode" which we can use to detect if we read a
// valid opcode.
const uint64_t opcode = thread.GetProcess()->ReadUnsignedIntegerFromMemory(pc, 4, UINT64_MAX, error);
if (opcode <= UINT32_MAX)
{
const uint32_t condition = Bits32((uint32_t)opcode, 31, 28);
if (ARMConditionPassed(condition, cpsr) == false)
{
// We ARE stopped on an ARM instruction whose condition doesn't
// pass so this instruction won't get executed.
// Regardless of why it stopped, we need to clear the stop info
thread.SetStopInfo (StopInfoSP());
}
}
#endif
}
else if (ISETSTATE == 1)
{
// Thumb mode
const uint32_t ITSTATE = Bits32 (cpsr, 15, 10) << 2 | Bits32 (cpsr, 26, 25);
if (ITSTATE != 0)
{
const uint32_t condition = Bits32(ITSTATE, 7, 4);
if (ARMConditionPassed(condition, cpsr) == false)
{
// We ARE stopped in a Thumb IT instruction on an instruction whose
// condition doesn't pass so this instruction won't get executed.
// Regardless of why it stopped, we need to clear the stop info
thread.SetStopInfo (StopInfoSP());
}
}
}
}
}
}
ArchSpec::StopInfoOverrideCallbackType
ArchSpec::GetStopInfoOverrideCallback () const
{
const llvm::Triple::ArchType machine = GetMachine();
if (machine == llvm::Triple::arm)
return StopInfoOverrideCallbackTypeARM;
return NULL;
}
bool
ArchSpec::IsFullySpecifiedTriple () const
{
const auto& user_specified_triple = GetTriple();
bool user_triple_fully_specified = false;
if ((user_specified_triple.getOS() != llvm::Triple::UnknownOS) || TripleOSWasSpecified())
{
if ((user_specified_triple.getVendor() != llvm::Triple::UnknownVendor) || TripleVendorWasSpecified())
{
const unsigned unspecified = 0;
if (user_specified_triple.getOSMajorVersion() != unspecified)
{
user_triple_fully_specified = true;
}
}
}
return user_triple_fully_specified;
}
void
ArchSpec::PiecewiseTripleCompare (const ArchSpec &other,
bool &arch_different,
bool &vendor_different,
bool &os_different,
bool &os_version_different,
bool &env_different)
{
const llvm::Triple &me(GetTriple());
const llvm::Triple &them(other.GetTriple());
arch_different = (me.getArch() != them.getArch());
vendor_different = (me.getVendor() != them.getVendor());
os_different = (me.getOS() != them.getOS());
os_version_different = (me.getOSMajorVersion() != them.getOSMajorVersion());
env_different = (me.getEnvironment() != them.getEnvironment());
}
void
ArchSpec::DumpTriple(Stream &s) const
{
const llvm::Triple &triple = GetTriple();
llvm::StringRef arch_str = triple.getArchName();
llvm::StringRef vendor_str = triple.getVendorName();
llvm::StringRef os_str = triple.getOSName();
s.Printf("%s-%s-%s",
arch_str.empty() ? "*" : arch_str.str().c_str(),
vendor_str.empty() ? "*" : vendor_str.str().c_str(),
os_str.empty() ? "*" : os_str.str().c_str()
);
}
|
; A140429: a(n) = floor(3^(n-1)).
; 0,1,3,9,27,81,243,729,2187,6561,19683,59049,177147,531441,1594323,4782969,14348907,43046721,129140163,387420489,1162261467,3486784401,10460353203,31381059609,94143178827,282429536481,847288609443
mov $1,3
pow $1,$0
div $1,3
|
;;kernel.asm
%define MEMORY_MAP 0x1
%define PAGE_ALIGN 0x2
%define VBE_ENABLE 0x4
;nasm directive - 32 bit
bits 32
section .multiboot
;multiboot1
align 4
dd 0x1BADB002 ;magic
dd MEMORY_MAP|PAGE_ALIGN|VBE_ENABLE ;flags (bit 1 set for memory map, bit 0 set for page aligning)
dd - (0x1BADB002 + (MEMORY_MAP|PAGE_ALIGN|VBE_ENABLE)) ;checksum. m+f+c should be zero
addrinfo_ignored:
dd 0
dd 0
dd 0
dd 0
dd 0
videomode:
dd 0
dd 1280 ; VBE width
dd 720 ; VBE height
dd 32 ; VBE pixel depth
; ; multiboot2 (qemu doesn't support yet!)
; header_start:
; dd 0xe85250d6 ; magic number
; dd 0 ; protected mode code
; dd header_end - header_start ; header length
; dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start)) ; checksum
; ; required end tag
; dw 0 ; type
; dw 0 ; flags
; dd 8 ; size
; header_end:
section .text
global start
extern main ;kmain is defined in the c file
start:
cli ;block interrupts
mov esp, stack_space ;set stack pointer
sub esp, 8 ; so we can align the arguments
push eax ; push magic number
push ebx ; push multiboot info
call main
hlt ;halt the CPU
section .bss
resb 8192 ;8KB for stack
global stack_space
stack_space:
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2022, Intel Corporation. All rights reserved.<BR>
; SPDX-License-Identifier: BSD-2-Clause-Patent
;
; Module Name:
;
; PeiCoreEntry.nasm
;
; Abstract:
;
; Find and call SecStartup
;
;------------------------------------------------------------------------------
SECTION .text
%include "PushPopRegsNasm.inc"
extern ASM_PFX(SecStartup)
extern ASM_PFX(PlatformInit)
;
; args 1:XMM, 2:REG, 3:IDX
;
%macro LXMMN 3
pextrq %2, %1, (%3 & 3)
%endmacro
;
; args 1:YMM, 2:XMM, 3:IDX (0 - lower 128bits, 1 - upper 128bits)
;
%macro LYMMN 3
vextractf128 %2, %1, %3
%endmacro
%macro LOAD_TS 1
LYMMN ymm6, xmm5, 1
LXMMN xmm5, %1, 1
%endmacro
global ASM_PFX(CallPeiCoreEntryPoint)
ASM_PFX(CallPeiCoreEntryPoint):
;
; Per X64 calling convention, make sure RSP is 16-byte aligned.
;
mov rax, rsp
and rax, 0fh
sub rsp, rax
;
; Platform init
;
PUSHA_64
sub rsp, 20h
call ASM_PFX(PlatformInit)
add rsp, 20h
POPA_64
;
; Set stack top pointer
;
mov rsp, r8
;
; Push the hob list pointer
;
push rcx
;
; RBP holds start of BFV passed from Vtf0. Save it to r10.
;
mov r10, rbp
;
; Save the value
; RDX: start of range
; r8: end of range
;
mov rbp, rsp
push rdx
push r8
mov r14, rdx
mov r15, r8
;
; Push processor count to stack first, then BIST status (AP then BSP)
;
mov eax, 1
cpuid
shr ebx, 16
and ebx, 0000000FFh
cmp bl, 1
jae PushProcessorCount
;
; Some processors report 0 logical processors. Effectively 0 = 1.
; So we fix up the processor count
;
inc ebx
PushProcessorCount:
sub rsp, 4
mov rdi, rsp
mov DWORD [rdi], ebx
;
; We need to implement a long-term solution for BIST capture. For now, we just copy BSP BIST
; for all processor threads
;
xor ecx, ecx
mov cl, bl
PushBist:
sub rsp, 4
mov rdi, rsp
movd eax, mm0
mov DWORD [rdi], eax
loop PushBist
; Save Time-Stamp Counter
LOAD_TS rax
push rax
;
; Pass entry point of the PEI core
;
mov rdi, 0FFFFFFE0h
mov edi, DWORD [rdi]
mov r9, rdi
;
; Pass BFV into the PEI Core
;
mov r8, r10
;
; Pass stack size into the PEI Core
;
mov rcx, r15 ; Start of TempRam
mov rdx, r14 ; End of TempRam
sub rcx, rdx ; Size of TempRam
;
; Pass Control into the PEI Core
;
sub rsp, 20h
call ASM_PFX(SecStartup)
|
###############################################################################
# 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.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 4, 0x90
CONST_TABLE:
u128_str:
.byte 15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0
.p2align 4, 0x90
.globl p8_EncryptCTR_RIJ128pipe_AES_NI
.type p8_EncryptCTR_RIJ128pipe_AES_NI, @function
p8_EncryptCTR_RIJ128pipe_AES_NI:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
movl (32)(%ebp), %esi
movl (28)(%ebp), %edi
movdqu (%esi), %xmm6
movdqu (%edi), %xmm1
movdqu %xmm6, %xmm5
pandn %xmm1, %xmm6
sub $(16), %esp
lea CONST_TABLE, %eax
movdqa ((u128_str-CONST_TABLE))(%eax), %xmm4
movl (%edi), %edx
movl (4)(%edi), %ecx
movl (8)(%edi), %ebx
movl (12)(%edi), %eax
bswap %edx
bswap %ecx
bswap %ebx
bswap %eax
movl %eax, (%esp)
movl %ebx, (4)(%esp)
movl %ecx, (8)(%esp)
movl %edx, (12)(%esp)
movl (8)(%ebp), %esi
movl (12)(%ebp), %edi
subl $(64), (24)(%ebp)
jl .Lshort_inputgas_1
.Lblks_loopgas_1:
movl (%esp), %eax
movl (4)(%esp), %ebx
movl (8)(%esp), %ecx
movl (12)(%esp), %edx
pinsrd $(0), %eax, %xmm0
pinsrd $(1), %ebx, %xmm0
pinsrd $(2), %ecx, %xmm0
pinsrd $(3), %edx, %xmm0
pshufb %xmm4, %xmm0
pand %xmm5, %xmm0
por %xmm6, %xmm0
add $(1), %eax
adc $(0), %ebx
adc $(0), %ecx
adc $(0), %edx
pinsrd $(0), %eax, %xmm1
pinsrd $(1), %ebx, %xmm1
pinsrd $(2), %ecx, %xmm1
pinsrd $(3), %edx, %xmm1
pshufb %xmm4, %xmm1
pand %xmm5, %xmm1
por %xmm6, %xmm1
add $(1), %eax
adc $(0), %ebx
adc $(0), %ecx
adc $(0), %edx
pinsrd $(0), %eax, %xmm2
pinsrd $(1), %ebx, %xmm2
pinsrd $(2), %ecx, %xmm2
pinsrd $(3), %edx, %xmm2
pshufb %xmm4, %xmm2
pand %xmm5, %xmm2
por %xmm6, %xmm2
add $(1), %eax
adc $(0), %ebx
adc $(0), %ecx
adc $(0), %edx
pinsrd $(0), %eax, %xmm3
pinsrd $(1), %ebx, %xmm3
pinsrd $(2), %ecx, %xmm3
pinsrd $(3), %edx, %xmm3
pshufb %xmm4, %xmm3
pand %xmm5, %xmm3
por %xmm6, %xmm3
add $(1), %eax
adc $(0), %ebx
adc $(0), %ecx
adc $(0), %edx
movl %eax, (%esp)
movl %ebx, (4)(%esp)
movl %ecx, (8)(%esp)
movl %edx, (12)(%esp)
movl (20)(%ebp), %ecx
movdqa (%ecx), %xmm7
lea (16)(%ecx), %ebx
pxor %xmm7, %xmm0
pxor %xmm7, %xmm1
pxor %xmm7, %xmm2
pxor %xmm7, %xmm3
movdqa (%ebx), %xmm7
add $(16), %ebx
movl (16)(%ebp), %eax
sub $(1), %eax
.Lcipher_loopgas_1:
aesenc %xmm7, %xmm0
aesenc %xmm7, %xmm1
aesenc %xmm7, %xmm2
aesenc %xmm7, %xmm3
movdqa (%ebx), %xmm7
add $(16), %ebx
dec %eax
jnz .Lcipher_loopgas_1
aesenclast %xmm7, %xmm0
aesenclast %xmm7, %xmm1
aesenclast %xmm7, %xmm2
aesenclast %xmm7, %xmm3
movdqu (%esi), %xmm7
pxor %xmm7, %xmm0
movdqu %xmm0, (%edi)
movdqu (16)(%esi), %xmm7
pxor %xmm7, %xmm1
movdqu %xmm1, (16)(%edi)
movdqu (32)(%esi), %xmm7
pxor %xmm7, %xmm2
movdqu %xmm2, (32)(%edi)
movdqu (48)(%esi), %xmm7
pxor %xmm7, %xmm3
movdqu %xmm3, (48)(%edi)
add $(64), %esi
add $(64), %edi
subl $(64), (24)(%ebp)
jge .Lblks_loopgas_1
.Lshort_inputgas_1:
addl $(64), (24)(%ebp)
jz .Lquitgas_1
movl (20)(%ebp), %ecx
movl (16)(%ebp), %eax
lea (,%eax,4), %ebx
lea (-144)(%ecx,%ebx,4), %ebx
.Lsingle_blk_loopgas_1:
movdqu (%esp), %xmm0
pshufb %xmm4, %xmm0
pand %xmm5, %xmm0
por %xmm6, %xmm0
pxor (%ecx), %xmm0
cmp $(12), %eax
jl .Lkey_128_sgas_1
jz .Lkey_192_sgas_1
.Lkey_256_sgas_1:
aesenc (-64)(%ebx), %xmm0
aesenc (-48)(%ebx), %xmm0
.Lkey_192_sgas_1:
aesenc (-32)(%ebx), %xmm0
aesenc (-16)(%ebx), %xmm0
.Lkey_128_sgas_1:
aesenc (%ebx), %xmm0
aesenc (16)(%ebx), %xmm0
aesenc (32)(%ebx), %xmm0
aesenc (48)(%ebx), %xmm0
aesenc (64)(%ebx), %xmm0
aesenc (80)(%ebx), %xmm0
aesenc (96)(%ebx), %xmm0
aesenc (112)(%ebx), %xmm0
aesenc (128)(%ebx), %xmm0
aesenclast (144)(%ebx), %xmm0
addl $(1), (%esp)
adcl $(0), (4)(%esp)
adcl $(0), (8)(%esp)
adcl $(0), (12)(%esp)
subl $(16), (24)(%ebp)
jl .Lpartial_blockgas_1
movdqu (%esi), %xmm1
add $(16), %esi
pxor %xmm1, %xmm0
movdqu %xmm0, (%edi)
add $(16), %edi
cmpl $(0), (24)(%ebp)
jz .Lquitgas_1
jmp .Lsingle_blk_loopgas_1
.Lpartial_blockgas_1:
addl $(16), (24)(%ebp)
.Lpartial_block_loopgas_1:
pextrb $(0), %xmm0, %eax
psrldq $(1), %xmm0
movzbl (%esi), %ebx
xor %ebx, %eax
movb %al, (%edi)
inc %esi
inc %edi
decl (24)(%ebp)
jnz .Lpartial_block_loopgas_1
.Lquitgas_1:
movl (28)(%ebp), %eax
movdqu (%esp), %xmm0
pshufb %xmm4, %xmm0
pand %xmm5, %xmm0
por %xmm6, %xmm0
movdqu %xmm0, (%eax)
add $(16), %esp
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.Lfe1:
.size p8_EncryptCTR_RIJ128pipe_AES_NI, .Lfe1-(p8_EncryptCTR_RIJ128pipe_AES_NI)
|
;;
;; Copyright (c) 2009-2019, Intel Corporation
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; * Neither the name of Intel Corporation nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; 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 COPYRIGHT OWNER 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 "include/os.asm"
%include "include/reg_sizes.asm"
%include "include/zuc_sbox.inc"
section .data
default rel
EK_d:
dw 0x44D7, 0x26BC, 0x626B, 0x135E, 0x5789, 0x35E2, 0x7135, 0x09AF,
dw 0x4D78, 0x2F13, 0x6BC4, 0x1AF1, 0x5E26, 0x3C4D, 0x789A, 0x47AC
mask31:
dd 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF, 0x7FFFFFFF
align 16
bit_reverse_table_l:
db 0x00, 0x08, 0x04, 0x0c, 0x02, 0x0a, 0x06, 0x0e, 0x01, 0x09, 0x05, 0x0d, 0x03, 0x0b, 0x07, 0x0f
align 16
bit_reverse_table_h:
db 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0
align 16
bit_reverse_and_table:
db 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f
align 16
data_mask_64bits:
dd 0xffffffff, 0xffffffff, 0x00000000, 0x00000000
bit_mask_table:
db 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe
align 16
swap_mask:
db 0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04
db 0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c
align 16
S1_S0_shuf:
db 0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E, 0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F
align 16
S0_S1_shuf:
db 0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F, 0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E
align 16
rev_S1_S0_shuf:
db 0x00, 0x08, 0x01, 0x09, 0x02, 0x0A, 0x03, 0x0B, 0x04, 0x0C, 0x05, 0x0D, 0x06, 0x0E, 0x07, 0x0F
align 16
rev_S0_S1_shuf:
db 0x08, 0x00, 0x09, 0x01, 0x0A, 0x02, 0x0B, 0x03, 0x0C, 0x04, 0x0D, 0x05, 0x0E, 0x06, 0x0F, 0x07
section .text
%define MASK31 xmm12
%define OFS_R1 (16*(4*4))
%define OFS_R2 (OFS_R1 + (4*4))
%define OFS_X0 (OFS_R2 + (4*4))
%define OFS_X1 (OFS_X0 + (4*4))
%define OFS_X2 (OFS_X1 + (4*4))
%define OFS_X3 (OFS_X2 + (4*4))
%ifidn __OUTPUT_FORMAT__, win64
%define XMM_STORAGE 16*10
%define GP_STORAGE 8*8
%else
%define XMM_STORAGE 0
%define GP_STORAGE 6*8
%endif
%define VARIABLE_OFFSET XMM_STORAGE + GP_STORAGE
%define GP_OFFSET XMM_STORAGE
%macro FUNC_SAVE 0
mov r11, rsp
sub rsp, VARIABLE_OFFSET
and rsp, ~15
%ifidn __OUTPUT_FORMAT__, win64
; xmm6:xmm15 need to be maintained for Windows
movdqa [rsp + 0*16], xmm6
movdqa [rsp + 1*16], xmm7
movdqa [rsp + 2*16], xmm8
movdqa [rsp + 3*16], xmm9
movdqa [rsp + 4*16], xmm10
movdqa [rsp + 5*16], xmm11
movdqa [rsp + 6*16], xmm12
movdqa [rsp + 7*16], xmm13
movdqa [rsp + 8*16], xmm14
movdqa [rsp + 9*16], xmm15
mov [rsp + GP_OFFSET + 48], rdi
mov [rsp + GP_OFFSET + 56], rsi
%endif
mov [rsp + GP_OFFSET], r12
mov [rsp + GP_OFFSET + 8], r13
mov [rsp + GP_OFFSET + 16], r14
mov [rsp + GP_OFFSET + 24], r15
mov [rsp + GP_OFFSET + 32], rbx
mov [rsp + GP_OFFSET + 40], r11 ;; rsp pointer
%endmacro
%macro FUNC_RESTORE 0
%ifidn __OUTPUT_FORMAT__, win64
movdqa xmm6, [rsp + 0*16]
movdqa xmm7, [rsp + 1*16]
movdqa xmm8, [rsp + 2*16]
movdqa xmm9, [rsp + 3*16]
movdqa xmm10, [rsp + 4*16]
movdqa xmm11, [rsp + 5*16]
movdqa xmm12, [rsp + 6*16]
movdqa xmm13, [rsp + 7*16]
movdqa xmm14, [rsp + 8*16]
movdqa xmm15, [rsp + 9*16]
mov rdi, [rsp + GP_OFFSET + 48]
mov rsi, [rsp + GP_OFFSET + 56]
%endif
mov r12, [rsp + GP_OFFSET]
mov r13, [rsp + GP_OFFSET + 8]
mov r14, [rsp + GP_OFFSET + 16]
mov r15, [rsp + GP_OFFSET + 24]
mov rbx, [rsp + GP_OFFSET + 32]
mov rsp, [rsp + GP_OFFSET + 40]
%endmacro
;
; make_u31()
;
%macro make_u31 4
%define %%Rt %1
%define %%Ke %2
%define %%Ek %3
%define %%Iv %4
xor %%Rt, %%Rt
shrd %%Rt, %%Iv, 8
shrd %%Rt, %%Ek, 15
shrd %%Rt, %%Ke, 9
%endmacro
;
; bits_reorg4()
;
; params
; %1 - round number
; rax - LFSR pointer
; uses
;
; return
;
%macro bits_reorg4 1
;
; xmm15 = LFSR_S15
; xmm14 = LFSR_S14
; xmm11 = LFSR_S11
; xmm9 = LFSR_S9
; xmm7 = LFSR_S7
; xmm5 = LFSR_S5
; xmm2 = LFSR_S2
; xmm0 = LFSR_S0
;
movdqa xmm15, [rax + ((15 + %1) % 16)*16]
movdqa xmm14, [rax + ((14 + %1) % 16)*16]
movdqa xmm11, [rax + ((11 + %1) % 16)*16]
movdqa xmm9, [rax + (( 9 + %1) % 16)*16]
movdqa xmm7, [rax + (( 7 + %1) % 16)*16]
movdqa xmm5, [rax + (( 5 + %1) % 16)*16]
movdqa xmm2, [rax + (( 2 + %1) % 16)*16]
movdqa xmm0, [rax + (( 0 + %1) % 16)*16]
pxor xmm1, xmm1
pslld xmm15, 1
movdqa xmm3, xmm14
pblendw xmm3, xmm1, 0xAA
pblendw xmm15, xmm3, 0x55
movdqa [rax + OFS_X0], xmm15 ; BRC_X0
pslld xmm11, 16
psrld xmm9, 15
por xmm11, xmm9
movdqa [rax + OFS_X1], xmm11 ; BRC_X1
pslld xmm7, 16
psrld xmm5, 15
por xmm7, xmm5
movdqa [rax + OFS_X2], xmm7 ; BRC_X2
pslld xmm2, 16
psrld xmm0, 15
por xmm2, xmm0
movdqa [rax + OFS_X3], xmm2 ; BRC_X3
%endmacro
;
; rot_mod32()
;
; uses xmm7
;
%macro rot_mod32 3
movdqa %1, %2
pslld %1, %3
movdqa xmm7, %2
psrld xmm7, (32 - %3)
por %1, xmm7
%endmacro
;
; nonlin_fun4()
;
; params
; %1 == 1, then calculate W
; uses
;
; return
; xmm0 = W value, updates F_R1[] / F_R2[]
;
%macro nonlin_fun4 1
%if (%1 == 1)
movdqa xmm0, [rax + OFS_X0]
pxor xmm0, [rax + OFS_R1]
paddd xmm0, [rax + OFS_R2] ; W = (BRC_X0 ^ F_R1) + F_R2
%endif
movdqa xmm1, [rax + OFS_R1]
movdqa xmm2, [rax + OFS_R2]
paddd xmm1, [rax + OFS_X1] ; W1 = F_R1 + BRC_X1
pxor xmm2, [rax + OFS_X2] ; W2 = F_R2 ^ BRC_X2
movdqa xmm3, xmm1
movdqa xmm4, xmm1
movdqa xmm5, xmm2
movdqa xmm6, xmm2
pslld xmm3, 16
psrld xmm4, 16
pslld xmm5, 16
psrld xmm6, 16
movdqa xmm1, xmm3
movdqa xmm2, xmm4
por xmm1, xmm6
por xmm2, xmm5
rot_mod32 xmm3, xmm1, 2
rot_mod32 xmm4, xmm1, 10
rot_mod32 xmm5, xmm1, 18
rot_mod32 xmm6, xmm1, 24
pxor xmm1, xmm3
pxor xmm1, xmm4
pxor xmm1, xmm5
pxor xmm1, xmm6 ; XMM1 = U = L1(P)
rot_mod32 xmm3, xmm2, 8
rot_mod32 xmm4, xmm2, 14
rot_mod32 xmm5, xmm2, 22
rot_mod32 xmm6, xmm2, 30
pxor xmm2, xmm3
pxor xmm2, xmm4
pxor xmm2, xmm5
pxor xmm2, xmm6 ; XMM2 = V = L2(Q)
; Shuffle U and V to have all S0 lookups in XMM1 and all S1 lookups in XMM2
; Compress all S0 and S1 input values in each register
pshufb xmm1, [rel S0_S1_shuf] ; S0: Bytes 0-7, S1: Bytes 8-15
pshufb xmm2, [rel S1_S0_shuf] ; S1: Bytes 0-7, S0: Bytes 8-15
movdqa xmm3, xmm1
shufpd xmm1, xmm2, 0x2 ; All S0 input values
shufpd xmm2, xmm3, 0x2 ; All S1 input values
; Compute S0 and S1 values
S0_comput_SSE xmm1, xmm3, xmm4
S1_comput_SSE xmm2, xmm3, xmm4, xmm5
; Need to shuffle back xmm1 & xmm2 before storing output
; (revert what was done before S0 and S1 computations)
movdqa xmm3, xmm1
shufpd xmm1, xmm2, 0x2 ; All S0 input values
shufpd xmm2, xmm3, 0x2 ; All S1 input values
pshufb xmm1, [rel rev_S0_S1_shuf]
pshufb xmm2, [rel rev_S1_S0_shuf]
movdqa [rax + OFS_R1], xmm1
movdqa [rax + OFS_R2], xmm2
%endmacro
;
; store_kstr4()
;
; params
;
; uses
; xmm0 as input
; return
;
%macro store_kstr4 0
pxor xmm0, [rax + OFS_X3]
mov rcx, [rsp]
mov rdx, [rsp + 8]
mov r8, [rsp + 16]
mov r9, [rsp + 24]
pextrd r15d, xmm0, 3
pextrd r14d, xmm0, 2
pextrd r13d, xmm0, 1
pextrd r12d, xmm0, 0
mov [r9], r15d
mov [r8], r14d
mov [rdx], r13d
mov [rcx], r12d
add rcx, 4
add rdx, 4
add r8, 4
add r9, 4
mov [rsp], rcx
mov [rsp + 8], rdx
mov [rsp + 16], r8
mov [rsp + 24], r9
%endmacro
;
; add_mod31()
; add two 32-bit args and reduce mod (2^31-1)
; params
; %1 - arg1/res
; %2 - arg2
; uses
; xmm2
; return
; %1
%macro add_mod31 2
paddd %1, %2
movdqa xmm2, %1
psrld xmm2, 31
pand %1, MASK31
paddd %1, xmm2
%endmacro
;
; rot_mod31()
; rotate (mult by pow of 2) 32-bit arg and reduce mod (2^31-1)
; params
; %1 - arg
; %2 - # of bits
; uses
; xmm2
; return
; %1
%macro rot_mod31 2
movdqa xmm2, %1
pslld xmm2, %2
psrld %1, (31 - %2)
por %1, xmm2
pand %1, MASK31
%endmacro
;
; lfsr_updt4()
;
; params
; %1 - round number
; uses
; xmm0 as input (ZERO or W)
; return
;
%macro lfsr_updt4 1
;
; xmm1 = LFSR_S0
; xmm4 = LFSR_S4
; xmm10 = LFSR_S10
; xmm13 = LFSR_S13
; xmm15 = LFSR_S15
;
pxor xmm3, xmm3
movdqa xmm1, [rax + (( 0 + %1) % 16)*16]
movdqa xmm4, [rax + (( 4 + %1) % 16)*16]
movdqa xmm10, [rax + ((10 + %1) % 16)*16]
movdqa xmm13, [rax + ((13 + %1) % 16)*16]
movdqa xmm15, [rax + ((15 + %1) % 16)*16]
; Calculate LFSR feedback
add_mod31 xmm0, xmm1
rot_mod31 xmm1, 8
add_mod31 xmm0, xmm1
rot_mod31 xmm4, 20
add_mod31 xmm0, xmm4
rot_mod31 xmm10, 21
add_mod31 xmm0, xmm10
rot_mod31 xmm13, 17
add_mod31 xmm0, xmm13
rot_mod31 xmm15, 15
add_mod31 xmm0, xmm15
movdqa [rax + (( 0 + %1) % 16)*16], xmm0
; LFSR_S16 = (LFSR_S15++) = eax
%endmacro
;
; key_expand_4()
;
%macro key_expand_4 2
movzx r8d, byte [rdi + (%1 + 0)]
movzx r9d, word [rbx + ((%1 + 0)*2)]
movzx r10d, byte [rsi + (%1 + 0)]
make_u31 r11d, r8d, r9d, r10d
mov [rax + (((%1 + 0)*16)+(%2*4))], r11d
movzx r12d, byte [rdi + (%1 + 1)]
movzx r13d, word [rbx + ((%1 + 1)*2)]
movzx r14d, byte [rsi + (%1 + 1)]
make_u31 r15d, r12d, r13d, r14d
mov [rax + (((%1 + 1)*16)+(%2*4))], r15d
%endmacro
MKGLOBAL(asm_ZucInitialization_4_sse,function,internal)
asm_ZucInitialization_4_sse:
%ifdef LINUX
%define pKe rdi
%define pIv rsi
%define pState rdx
%else
%define pKe rcx
%define pIv rdx
%define pState r8
%endif
FUNC_SAVE
lea rax, [pState] ; load pointer to LFSR
push pState ; Save LFSR Pointer to stack
; setup the key pointer for first buffer key expand
mov rbx, [pKe] ; load the pointer to the array of keys into rbx
push pKe ; save rdi (key pointer) to the stack
lea rdi, [rbx] ; load the pointer to the first key into rdi
; setup the IV pointer for first buffer key expand
mov rcx, [pIv] ; load the pointer to the array of IV's
push pIv ; save the IV pointer to the stack
lea rsi, [rcx] ; load the first IV pointer
lea rbx, [EK_d] ; load D variables
; Expand key packet 1
key_expand_4 0, 0
key_expand_4 2, 0
key_expand_4 4, 0
key_expand_4 6, 0
key_expand_4 8, 0
key_expand_4 10, 0
key_expand_4 12, 0
key_expand_4 14, 0
;second packet key expand here - reset pointers
pop rdx ; get IV array pointer from Stack
mov rcx, [rdx+8] ; load offset to IV 2 in array
lea rsi, [rcx] ; load pointer to IV2
pop rbx ; get Key array pointer from Stack
mov rcx, [rbx+8] ; load offset to key 2 in array
lea rdi, [rcx] ; load pointer to Key 2
push rbx ; save Key pointer
push rdx ; save IV pointer
lea rbx, [EK_d]
; Expand key packet 2
key_expand_4 0, 1
key_expand_4 2, 1
key_expand_4 4, 1
key_expand_4 6, 1
key_expand_4 8, 1
key_expand_4 10, 1
key_expand_4 12, 1
key_expand_4 14, 1
;Third packet key expand here - reset pointers
pop rdx ; get IV array pointer from Stack
mov rcx, [rdx+16] ; load offset to IV 3 in array
lea rsi, [rcx] ; load pointer to IV3
pop rbx ; get Key array pointer from Stack
mov rcx, [rbx+16] ; load offset to key 3 in array
lea rdi, [rcx] ; load pointer to Key 3
push rbx ; save Key pointer
push rdx ; save IV pointer
lea rbx, [EK_d]
; Expand key packet 3
key_expand_4 0, 2
key_expand_4 2, 2
key_expand_4 4, 2
key_expand_4 6, 2
key_expand_4 8, 2
key_expand_4 10, 2
key_expand_4 12, 2
key_expand_4 14, 2
;fourth packet key expand here - reset pointers
pop rdx ; get IV array pointer from Stack
mov rcx, [rdx+24] ; load offset to IV 4 in array
lea rsi, [rcx] ; load pointer to IV4
pop rbx ; get Key array pointer from Stack
mov rcx, [rbx+24] ; load offset to key 2 in array
lea rdi, [rcx] ; load pointer to Key 2
lea rbx, [EK_d]
; Expand key packet 4
key_expand_4 0, 3
key_expand_4 2, 3
key_expand_4 4, 3
key_expand_4 6, 3
key_expand_4 8, 3
key_expand_4 10, 3
key_expand_4 12, 3
key_expand_4 14, 3
; Load read-only registers
movdqa xmm12, [rel mask31]
; Shift LFSR 32-times, update state variables
%assign N 0
%rep 32
pop rdx
lea rax, [rdx]
push rdx
bits_reorg4 N
nonlin_fun4 1
psrld xmm0,1 ; Shift out LSB of W
pop rdx
lea rax, [rdx]
push rdx
lfsr_updt4 N ; W (xmm0) used in LFSR update - not set to zero
%assign N N+1
%endrep
; And once more, initial round from keygen phase = 33 times
pop rdx
lea rax, [rdx]
push rdx
bits_reorg4 0
nonlin_fun4 0
pop rdx
lea rax, [rdx]
pxor xmm0, xmm0
lfsr_updt4 0
FUNC_RESTORE
ret
;
; Generate N*4 bytes of keystream
; for 4 buffers (where N is number of rounds)
;
%macro KEYGEN_4_SSE 1
%define %%NUM_ROUNDS %1 ; [in] Number of 4-byte rounds
%ifdef LINUX
%define pState rdi
%define pKS1 rsi
%define pKS2 rdx
%define pKS3 rcx
%define pKS4 r8
%else
%define pState rcx
%define pKS1 rdx
%define pKS2 r8
%define pKS3 r9
%define pKS4 rax
%endif
%ifndef LINUX
mov rax, [rsp + 8*5] ; 5th parameter from stack
%endif
FUNC_SAVE
; Store 4 keystream pointers on the stack
sub rsp, 4*8
mov [rsp], pKS1
mov [rsp + 8], pKS2
mov [rsp + 16], pKS3
mov [rsp + 24], pKS4
; Load state pointer in RAX
mov rax, pState
; Load read-only registers
movdqa xmm12, [rel mask31]
; Generate N*4B of keystream in N rounds
%assign N 1
%rep %%NUM_ROUNDS
bits_reorg4 N
nonlin_fun4 1
store_kstr4
pxor xmm0, xmm0
lfsr_updt4 N
%assign N N+1
%endrep
;; Restore rsp pointer to value before pushing keystreams
add rsp, 4*8
FUNC_RESTORE
%endmacro
;;
;; void asm_ZucGenKeystream64B_4_sse(state4_t *pSta, u32* pKeyStr1, u32* pKeyStr2, u32* pKeyStr3, u32* pKeyStr4);
;;
;; WIN64
;; RCX - pSta
;; RDX - pKeyStr1
;; R8 - pKeyStr2
;; R9 - pKeyStr3
;; Stack - pKeyStr4
;;
;; LIN64
;; RDI - pSta
;; RSI - pKeyStr1
;; RDX - pKeyStr2
;; RCX - pKeyStr3
;; R8 - pKeyStr4
;;
MKGLOBAL(asm_ZucGenKeystream64B_4_sse,function,internal)
asm_ZucGenKeystream64B_4_sse:
KEYGEN_4_SSE 16
ret
;;
;; void asm_ZucGenKeystream8B_4_sse(state4_t *pSta, u32* pKeyStr1, u32* pKeyStr2, u32* pKeyStr3, u32* pKeyStr4);
;;
;; WIN64
;; RCX - pSta
;; RDX - pKeyStr1
;; R8 - pKeyStr2
;; R9 - pKeyStr3
;; Stack - pKeyStr4
;;
;; LIN64
;; RDI - pSta
;; RSI - pKeyStr1
;; RDX - pKeyStr2
;; RCX - pKeyStr3
;; R8 - pKeyStr4
;;
MKGLOBAL(asm_ZucGenKeystream8B_4_sse,function,internal)
asm_ZucGenKeystream8B_4_sse:
KEYGEN_4_SSE 2
ret
;;
;; void asm_ZucCipher64B_4_sse(state4_t *pSta, u32 *pKeyStr[4], u64 *pIn[4],
;; u64 *pOut[4], u64 bufOff);
;;
;; WIN64
;; RCX - pSta
;; RDX - pKeyStr
;; R8 - pIn
;; R9 - pOut
;; rsp+40 - bufOff
;;
;; LIN64
;; RDI - pSta
;; RSI - pKeyStr
;; RDX - pIn
;; RCX - pOut
;; R8 - bufOff
;;
MKGLOBAL(asm_ZucCipher64B_4_sse,function,internal)
asm_ZucCipher64B_4_sse:
%ifdef LINUX
%define pState rdi
%define pKS rsi
%define pIn rdx
%define pOut rcx
%define bufOff r8
%else
%define pState rcx
%define pKS rdx
%define pIn r8
%define pOut r9
%define bufOff r10
%endif
%ifndef LINUX
mov bufOff, [rsp + 40]
%endif
FUNC_SAVE
; Store 4 keystream pointers and input registers in the stack
sub rsp, 8*8
mov r12, [pKS]
mov r13, [pKS + 8]
mov r14, [pKS + 16]
mov r15, [pKS + 24]
mov [rsp], r12
mov [rsp + 8], r13
mov [rsp + 16], r14
mov [rsp + 24], r15
mov [rsp + 32], pKS
mov [rsp + 40], pIn
mov [rsp + 48], pOut
mov [rsp + 56], bufOff
; Load state pointer in RAX
mov rax, pState
; Load read-only registers
movdqa xmm12, [rel mask31]
; Generate 64B of keystream in 16 rounds
%assign N 1
%rep 16
bits_reorg4 N
nonlin_fun4 1
store_kstr4
pxor xmm0, xmm0
lfsr_updt4 N
%assign N N+1
%endrep
;; Restore input parameters
mov pKS, [rsp + 32]
mov pIn, [rsp + 40]
mov pOut, [rsp + 48]
mov bufOff, [rsp + 56]
;; Restore rsp pointer to value before pushing keystreams
;; and input parameters
add rsp, 8*8
movdqa xmm15, [rel swap_mask]
%assign off 0
%rep 4
;; XOR Input buffer with keystream in rounds of 16B
mov r12, [pIn]
mov r13, [pIn + 8]
mov r14, [pIn + 16]
mov r15, [pIn + 24]
movdqu xmm0, [r12 + bufOff + off]
movdqu xmm1, [r13 + bufOff + off]
movdqu xmm2, [r14 + bufOff + off]
movdqu xmm3, [r15 + bufOff + off]
mov r12, [pKS]
mov r13, [pKS + 8]
mov r14, [pKS + 16]
mov r15, [pKS + 24]
movdqa xmm4, [r12 + off]
movdqa xmm5, [r13 + off]
movdqa xmm6, [r14 + off]
movdqa xmm7, [r15 + off]
pshufb xmm4, xmm15
pshufb xmm5, xmm15
pshufb xmm6, xmm15
pshufb xmm7, xmm15
pxor xmm4, xmm0
pxor xmm5, xmm1
pxor xmm6, xmm2
pxor xmm7, xmm3
mov r12, [pOut]
mov r13, [pOut + 8]
mov r14, [pOut + 16]
mov r15, [pOut + 24]
movdqu [r12 + bufOff + off], xmm4
movdqu [r13 + bufOff + off], xmm5
movdqu [r14 + bufOff + off], xmm6
movdqu [r15 + bufOff + off], xmm7
%assign off (off + 16)
%endrep
FUNC_RESTORE
ret
;;
;; extern uint32_t Zuc_Eia3_Remainder_sse(const void *ks, const void *data, uint64_t n_bits)
;;
;; Returns authentication update value to be XOR'ed with current authentication tag
;;
;; WIN64
;; RCX - KS (key stream pointer)
;; RDX - DATA (data pointer)
;; R8 - N_BITS (number data bits to process)
;; LIN64
;; RDI - KS (key stream pointer)
;; RSI - DATA (data pointer)
;; RDX - N_BITS (number data bits to process)
;;
align 16
MKGLOBAL(asm_Eia3RemainderSSE,function,internal)
asm_Eia3RemainderSSE:
%ifdef LINUX
%define KS rdi
%define DATA rsi
%define N_BITS rdx
%else
%define KS rcx
%define DATA rdx
%define N_BITS r8
%endif
FUNC_SAVE
movdqa xmm5, [bit_reverse_table_l]
movdqa xmm6, [bit_reverse_table_h]
movdqa xmm7, [bit_reverse_and_table]
movdqa xmm10, [data_mask_64bits]
pxor xmm9, xmm9
%rep 3
cmp N_BITS, 128
jb Eia3RoundsSSE_dq_end
;; read 16 bytes and reverse bits
movdqu xmm0, [DATA]
movdqa xmm1, xmm0
pand xmm1, xmm7
movdqa xmm2, xmm7
pandn xmm2, xmm0
psrld xmm2, 4
movdqa xmm8, xmm6 ; bit reverse low nibbles (use high table)
pshufb xmm8, xmm1
movdqa xmm4, xmm5 ; bit reverse high nibbles (use low table)
pshufb xmm4, xmm2
por xmm8, xmm4
; xmm8 - bit reversed data bytes
;; ZUC authentication part
;; - 4x32 data bits
;; - set up KS
movdqu xmm3, [KS + (0*4)]
movdqu xmm4, [KS + (2*4)]
pshufd xmm0, xmm3, 0x61
pshufd xmm1, xmm4, 0x61
;; - set up DATA
movdqa xmm2, xmm8
pand xmm2, xmm10
pshufd xmm3, xmm2, 0xdc
movdqa xmm4, xmm3
psrldq xmm8, 8
pshufd xmm13, xmm8, 0xdc
movdqa xmm14, xmm13
;; - clmul
;; - xor the results from 4 32-bit words together
pclmulqdq xmm3, xmm0, 0x00
pclmulqdq xmm4, xmm0, 0x11
pclmulqdq xmm13, xmm1, 0x00
pclmulqdq xmm14, xmm1, 0x11
pxor xmm3, xmm4
pxor xmm13, xmm14
pxor xmm9, xmm3
pxor xmm9, xmm13
lea DATA, [DATA + 16]
lea KS, [KS + 16]
sub N_BITS, 128
%endrep
Eia3RoundsSSE_dq_end:
%rep 3
cmp N_BITS, 32
jb Eia3RoundsSSE_dw_end
;; swap dwords in KS
movq xmm1, [KS]
pshufd xmm4, xmm1, 0xf1
;; bit-reverse 4 bytes of data
movdqa xmm2, xmm7
movd xmm0, [DATA]
movdqa xmm1, xmm0
pand xmm1, xmm2
pandn xmm2, xmm0
psrld xmm2, 4
movdqa xmm0, xmm6 ; bit reverse low nibbles (use high table)
pshufb xmm0, xmm1
movdqa xmm3, xmm5 ; bit reverse high nibbles (use low table)
pshufb xmm3, xmm2
por xmm0, xmm3
;; rol & xor
pclmulqdq xmm0, xmm4, 0
pxor xmm9, xmm0
lea DATA, [DATA + 4]
lea KS, [KS + 4]
sub N_BITS, 32
%endrep
Eia3RoundsSSE_dw_end:
movq rax, xmm9
shr rax, 32
or N_BITS, N_BITS
jz Eia3RoundsSSE_byte_loop_end
;; get 64-bit key stream for the last data bits (less than 32)
mov KS, [KS]
; ;; process remaining data bytes and bits
Eia3RoundsSSE_byte_loop:
or N_BITS, N_BITS
jz Eia3RoundsSSE_byte_loop_end
cmp N_BITS, 8
jb Eia3RoundsSSE_byte_partial
movzx r11, byte [DATA]
sub N_BITS, 8
jmp Eia3RoundsSSE_byte_read
Eia3RoundsSSE_byte_partial:
;; process remaining bits (up to 7)
lea r11, [bit_mask_table]
movzx r10, byte [r11 + N_BITS]
movzx r11, byte [DATA]
and r11, r10
xor N_BITS, N_BITS
Eia3RoundsSSE_byte_read:
%assign DATATEST 0x80
%rep 8
xor r10, r10
test r11, DATATEST
cmovne r10, KS
xor rax, r10
rol KS, 1
%assign DATATEST (DATATEST >> 1)
%endrep ; byte boundary
lea DATA, [DATA + 1]
jmp Eia3RoundsSSE_byte_loop
Eia3RoundsSSE_byte_loop_end:
;; eax - holds the return value at this stage
FUNC_RESTORE
ret
;;
;;extern uint32_t Zuc_Eia3_Round64B_sse(uint32_t T, const void *KS, const void *DATA)
;;
;; Updates authentication tag T based on keystream KS and DATA.
;; - it processes 64 bytes of DATA
;; - reads data in 16 byte chunks and bit reverses them
;; - reads and re-arranges KS
;; - employs clmul for the XOR & ROL part
;; - copies top 64 butes of KS to bottom (for the next round)
;;
;; WIN64
;; RCX - T
;; RDX - KS pointer to key stream (2 x 64 bytes)
;;; R8 - DATA pointer to data
;; LIN64
;; RDI - T
;; RSI - KS pointer to key stream (2 x 64 bytes)
;; RDX - DATA pointer to data
;;
align 16
MKGLOBAL(asm_Eia3Round64BSSE,function,internal)
asm_Eia3Round64BSSE:
%ifdef LINUX
%define T edi
%define KS rsi
%define DATA rdx
%else
%define T ecx
%define KS rdx
%define DATA r8
%endif
FUNC_SAVE
movdqa xmm5, [bit_reverse_table_l]
movdqa xmm6, [bit_reverse_table_h]
movdqa xmm7, [bit_reverse_and_table]
movdqa xmm10, [data_mask_64bits]
pxor xmm9, xmm9
%assign I 0
%rep 4
;; read 16 bytes and reverse bits
movdqu xmm0, [DATA + 16*I]
movdqa xmm1, xmm0
pand xmm1, xmm7
movdqa xmm2, xmm7
pandn xmm2, xmm0
psrld xmm2, 4
movdqa xmm8, xmm6 ; bit reverse low nibbles (use high table)
pshufb xmm8, xmm1
movdqa xmm4, xmm5 ; bit reverse high nibbles (use low table)
pshufb xmm4, xmm2
por xmm8, xmm4
; xmm8 - bit reversed data bytes
;; ZUC authentication part
;; - 4x32 data bits
;; - set up KS
%if I != 0
movdqa xmm0, xmm12
movdqu xmm2, [KS + (I*16) + (4*4)]
movdqa xmm12, xmm2
palignr xmm2, xmm0, 8
pshufd xmm1, xmm0, 0x61
pshufd xmm11, xmm2, 0x61
%else
movdqu xmm2, [KS + (I*16) + (0*4)]
movdqu xmm3, [KS + (I*16) + (4*4)]
movdqa xmm12, xmm3
palignr xmm3, xmm2, 8
pshufd xmm1, xmm2, 0x61
pshufd xmm11, xmm3, 0x61
%endif
;; - set up DATA
movdqa xmm0, xmm8
pand xmm0, xmm10
pshufd xmm3, xmm0, 0xdc
movdqa xmm0, xmm3
psrldq xmm8, 8
pshufd xmm13, xmm8, 0xdc
movdqa xmm14, xmm13
;; - clmul
;; - xor the results from 4 32-bit words together
pclmulqdq xmm0, xmm1, 0x00
pclmulqdq xmm3, xmm1, 0x11
pclmulqdq xmm14, xmm11, 0x00
pclmulqdq xmm13, xmm11, 0x11
pxor xmm3, xmm0
pxor xmm13, xmm14
pxor xmm9, xmm3
pxor xmm9, xmm13
%assign I (I + 1)
%endrep
;; - update T
movq rax, xmm9
shr rax, 32
xor eax, T
FUNC_RESTORE
ret
;----------------------------------------------------------------------------------------
;----------------------------------------------------------------------------------------
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
device ZXSPECTRUMNEXT
CSPECTMAP "i4.map"
org $8000
BORDER: defb 0
Start:
;break
jr SetupISR
Update:
ld a,(BORDER)
inc a
and 7
out (254),a
ld (BORDER),a
ret
SetupISR:
; Setup the 128 entry vector table
di
; Setup the I register (the high byte of the table)
ld a, high IM2Table
ld i, a
im 2
ei
ret ; return to BASIC
ORG $FCFC
; ISR (Interrupt Service Routine)
ISR:
push af
push hl
push bc
push de
push ix
push iy
exx
ex af, af'
push af
push hl
push bc
push de
call Update
pop de
pop bc
pop hl
pop af
ex af, af'
exx
pop iy
pop ix
pop de
pop bc
pop hl
pop af
ei
rst $38
; Make sure this is on a 256 byte boundary
ORG $FE00
IM2Table:
defs 257,high ISR
;SAVESNA "i3.sna", Start
SAVENEX OPEN "i4.nex", Start, $ff40
SAVENEX CORE 3, 0, 0 ; core 3.0.0 required
SAVENEX CFG 1 ; blue border (as debug)
SAVENEX AUTO ; dump all modified banks into NEX file |
; A250230: Number of length 3+1 0..n arrays with the sum of the cubes of adjacent differences multiplied by some arrangement of +-1 equal to zero.
; 8,27,52,89,132,187,248,321,400,491,588,697,812,939,1072,1217,1368,1531,1700,1881,2068,2267,2472,2689,2912,3147,3388,3641,3900,4171,4448,4737,5032,5339,5652,5977,6308,6651,7000,7361,7728,8107,8492,8889,9292,9707
mov $1,$0
mov $2,2
add $2,$0
add $2,$0
add $2,4
add $0,$2
mov $3,1
lpb $0
add $1,$3
add $1,$3
add $1,1
mov $3,$0
sub $0,1
trn $0,1
add $1,1
trn $3,4
lpe
sub $1,4
|
#include "stdafx.h"
#include "DMSlopeDetector.h"
#include "SlopeDetector.h"
#include "SlopeDetector.h"
#include "DACVoltage.h"
#include "DMSlopeDetector.h"
#include "TestWrappers.h"
//#define _HACK
/** Test harness
*/
void sd0()
{
#if (_VERBOSE > 0)
printf("sd0\n");
#endif
SlopeDetector sd(20, 1000, Constants::DISTING_SAMPLE_RATE, true);
assert( !sd.getPositiveSlope());
assert( !sd.getNegativeSlope());
assert( !sd.getBothSlope());
}
// POSITIVE
void sd1()
{
#if (_VERBOSE > 0)
printf("sd1\n");
#endif
SlopeDetector sd(20, 1000, Constants::DISTING_SAMPLE_RATE, true); // 20 mv thresh
int input = DACVoltage::xcodeForMV(1000); // huge step
sd.go(input);
assert( sd.getPositiveSlope() );
assert( !sd.getNegativeSlope());
assert( sd.getBothSlope());
}
// below thresh
void sd2()
{
#if (_VERBOSE > 0)
printf("sd2\n");
#endif
SlopeDetector sd(20, 1000, Constants::DISTING_SAMPLE_RATE, true); //210 mv thresh
int input = DACVoltage::xcodeForMV(10); // small step
sd.go(input);
assert( !sd.getPositiveSlope() );
assert( !sd.getNegativeSlope());
assert( !sd.getBothSlope());
}
// neg
void sd3()
{
#if (_VERBOSE > 0)
printf("sd3\n");
#endif
SlopeDetector sd(20, 1000, Constants::DISTING_SAMPLE_RATE, true); // 20 mv thresh
int input = DACVoltage::xcodeForMV(1000); // huge step
sd.go(-input);
assert( !sd.getPositiveSlope() );
assert( sd.getNegativeSlope());
assert( sd.getBothSlope());
}
class Note
{
public:
int midiPitch;
int durationMS;
};
Note chromatic[] = {
{100, 1000 },
{101, 1000 },
{102, 1000 },
{103, 1000 },
{104, 1000 },
{105, 1000 },
{0,0 }
};
Note trill[] = {
{1, 1000 },
#ifndef _HACK
{2, 1000 },
{1, 1000 },
{2, 1000 },
{1, 1000 },
{2, 1000 },
#endif
{0,0 }
};
Note leap[] = {
{20, 1000 },
#ifndef _HACK
{80, 1000 },
{81, 1000 },
{20, 1000 },
{21, 1000 },
{20, 1000 },
#endif
{0,0 }
};
Note leapfast[] = {
{20, 100 },
#ifndef _HACK
{80, 100 },
{81, 100 },
{20, 100 },
{21, 100 },
{20, 100 },
#endif
{0,0 }
};
void testSeq(I_Test& sd, Note * seq, int sampleRate, const char * msg)
{
// validate test inputs
Note * p = seq;
for (bool done=false; !done; ++p)
{
if (p->durationMS == 0)
done=true;
else
{
assert(p->midiPitch >= 0);
assert(p->midiPitch <= 127);
assert(p->durationMS > 0);
assert(p->durationMS < 10000);
}
}
for (int step=0; seq[step].durationMS != 0; ++step)
{
int mv = (1000 * seq[step].midiPitch) / 12;
int input = DACVoltage::xcodeForMV(mv);
#if (_VERBOSE > 1)
printf("top of loop in testSeq step = %d input = %d pitch = %d millis=%d mv=%d sampleRAte = %d\n", step, input, seq[step].midiPitch, seq[step].durationMS, mv, sampleRate);
#endif
// numer of samples in which we must detect
int samples = (seq[step].durationMS * sampleRate) / 1000;
// because of gibbs filter, we may need a few to detect high
int output=false;
for (int i=0; i< Constants::SLOPE_TEST_DELAY; ++i) // was 20
{
output = sd.doIt(input);
if (output)
{
#if (_VERBOSE > 1)
printf("detected change on sample %d\n", i);
#endif
samples -= i; // we used up some, so take tehm into account
break;
}
}
// make sure we detected the change
if (!output)
{
printf("failing due to missed input[%d] %s (after %d iterations)\n", step, msg, Constants::SLOPE_TEST_DELAY);
}
assert(output);
// now make sure the detector clears
for (int i=0; i<samples; ++i)
{
#ifdef _HACK
if (0 == (i % 1000))
{
printf("count = %d\n", i);
sd.print_go(msg, input);
}
else
#endif
//sd.go(input); // keep clocking in the same input
output = sd.doIt(input);
}
if (output)
{
printf("failing becuase detector still firing. step=%d\n", step);
}
assert(!output); // should be recoverd
}
}
void sd4()
{
#if (_VERBOSE > 0)
printf("sd4\n");
#endif
int sampleRate = Constants::DISTING_SAMPLE_RATE;
SlopeDetector _sd(20, 1000, sampleRate, true); // 20 mv thresh
//SlopeDetector _sd(41, 4000, sampleRate, true); // (like the DM version)
SDWrap sd(_sd);
testSeq(sd, chromatic, sampleRate, "chrom, 1");
}
void sdm4()
{
#if (_VERBOSE > 0)
printf("sd4m\n");
#endif
int sampleRate = Constants::DISTING_SAMPLE_RATE;
DMSlopeDetectorDual _sd; // 20 mv thresh
SDMWrap sd(_sd);
//printf("smd4 using wrong stim\n");
//testSeq(sd, leap, sampleRate, "leap, 1");
testSeq(sd, chromatic, sampleRate, "chrom, 1");
}
void sd5()
{
#if (_VERBOSE > 0)
printf("sd5\n");
#endif
int sampleRate = Constants::DISTING_SAMPLE_RATE;
SlopeDetector _sd(20, 1000, sampleRate, true); // 20 mv thresh
SDWrap sd(_sd);
testSeq(sd, trill, sampleRate, "trill 1");
}
void sd6()
{
#if (_VERBOSE > 0)
printf("sd6\n");
#endif
int sampleRate = Constants::DISTING_SAMPLE_RATE;
SlopeDetector _sd(20, 1000, sampleRate, true); // 20 mv thresh
SDWrap sd(_sd);
testSeq(sd, leap, sampleRate, "leap 1");
}
// try when the detector is slower
// trill fails at 650, works 600
void sd7()
{
#if (_VERBOSE > 0)
printf("sd7\n");
#endif
int sampleRate = Constants::DISTING_SAMPLE_RATE;
SlopeDetector _sd(20, 600 * 1000, sampleRate, true); // 20 mv thresh
SDWrap sd(_sd);
testSeq(sd, trill, sampleRate, "trill 159");
}
// try when the detector is slower
// leap fails at 200, works 180
void sd8()
{
#if (_VERBOSE > 0)
printf("sd8\n");
#endif
int sampleRate = Constants::DISTING_SAMPLE_RATE;
SlopeDetector _sd(20, 180 * 1000, sampleRate, true); // 20 mv thresh
SDWrap sd(_sd);
testSeq(sd, leap, sampleRate, "leap 159");
}
// try when the detector is slower
// leap fails at 20 works at 18
// now with fixed point fails at 18
void sd9()
{
#if (_VERBOSE > 0)
printf("sd9\n");
#endif
int sampleRate = Constants::DISTING_SAMPLE_RATE;
SlopeDetector _sd(20, 15 * 1000, sampleRate, true); // 20 mv thresh
SDWrap sd(_sd);
testSeq(sd, leapfast, sampleRate, "leap 159");
//printf("getchar finished sd9\n");
//getchar();
}
void sdm9()
{
#if (_VERBOSE > 0)
printf("sdm9\n");
#endif
int sampleRate = Constants::DISTING_SAMPLE_RATE;
// SlopeDetector _sd(20, 18 * 1000, sampleRate, true); // 20 mv thresh
DMSlopeDetectorDual _sd;
SDMWrap sd(_sd);
testSeq(sd, leapfast, sampleRate, "leap 159 m");
//printf("getchar finished sd9\n");
//getchar();
}
void sdm0()
{
#if (_VERBOSE > 0)
printf("sdm0\n");
#endif
DMSlopeDetectorDual sd;
DModule * dm = &sd;
ZState z(0, true);
int a=-1, b=-1;
dm->go(false, 0, 0, z, a, b);
assert(a == 0 && b == 0);
}
void sdm1()
{
#if (_VERBOSE > 0)
printf("sdm1\n");
#endif
DMSlopeDetectorDual sd;
int a=-1, b=-1;
int v = DACVoltage::xcodeForMV(100); // emough to trigger
int v5 = DACVoltage::xcodeForMV(5 * 1000);
ZState z(0, true);
sd.go(false, 0, 0, z, a, b);
assert(a == 0 && b == 0);
for (int i=0; i< Constants::SLOPE_TEST_DELAY; ++i) // delay for gibbs filter
{
sd.go(false, v, 0, z, a, b);
if (a > v5 && b == 0)
break;
}
//printf("went high, a=%d\n", a);
assert(a > v5 && b == 0);
for (int i=0; i<Constants::SLOPE_TEST_DELAY; ++i) // delay for gibbs filter
{
sd.go(false, v, v, z, a, b);
if (a > v5 && b > v5)
break;
}
assert(a > v5 && b > v5);
}
extern void hack();
void SlopeDetectorTests()
{
printf("slope detect test\n");
sd0();
sd1();
sd2();
sd3();
sd4();
sdm4();
sd5();
sd6();
#ifdef _SLOWTEST
sd7();
sd8();
sd9();
sdm9();
#endif
sdm0();
sdm1();
}
void hack()
{
int sampleRate = Constants::DISTING_SAMPLE_RATE;
SlopeDetector sd1(20, 159*1000, sampleRate, true); // 20 mv thresh
SlopeDetector sd2(20, 159*1000, sampleRate, true); // 20 mv thresh
int mv1 = (1000 * 1) / 12; // midi pitch 1
int input1 = DACVoltage::xcodeForMV(mv1);
int mv2 = (1000 * 100) / 12; // midi pitch 100
int input2 = DACVoltage::xcodeForMV(mv2);
bool done=false;
for( int count=0; !done; ++count )
{
if (0 == count % 1000)
{
printf("count = %d\n", count);
sd1.print_go("sd1", input1);
sd2.print_go("sd2", input2);
}
else
{
sd1.go(input1);
sd2.go(input2);
}
if (!sd1.getBothSlope() && !sd2.getBothSlope())
{
done = true;
printf("Hack finished at count = %d\n", count);
}
}
} |
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "common/base/Base.h"
#include "storage/mutate/UpdateEdgeProcessor.h"
#include "common/utils/NebulaKeyUtils.h"
#include "storage/exec/EdgeNode.h"
#include "storage/exec/FilterNode.h"
#include "storage/exec/UpdateNode.h"
#include "storage/exec/UpdateResultNode.h"
namespace nebula {
namespace storage {
ProcessorCounters kUpdateEdgeCounters;
void UpdateEdgeProcessor::process(const cpp2::UpdateEdgeRequest& req) {
if (executor_ != nullptr) {
executor_->add([req, this] () {
this->doProcess(req);
});
} else {
doProcess(req);
}
}
void UpdateEdgeProcessor::doProcess(const cpp2::UpdateEdgeRequest& req) {
spaceId_ = req.get_space_id();
auto partId = req.get_part_id();
edgeKey_ = req.get_edge_key();
updatedProps_ = req.get_updated_props();
if (req.insertable_ref().has_value()) {
insertable_ = *req.insertable_ref();
}
auto retCode = getSpaceVidLen(spaceId_);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
pushResultCode(retCode, partId);
onFinished();
return;
}
if (!NebulaKeyUtils::isValidVidLen(
spaceVidLen_, edgeKey_.get_src().getStr(), edgeKey_.get_dst().getStr())) {
LOG(ERROR) << "Space " << spaceId_ << ", vertex length invalid, "
<< " space vid len: " << spaceVidLen_
<< ", edge srcVid: " << edgeKey_.get_src()
<< " dstVid: " << edgeKey_.get_dst();
pushResultCode(nebula::cpp2::ErrorCode::E_INVALID_VID, partId);
onFinished();
return;
}
planContext_ = std::make_unique<PlanContext>(env_, spaceId_, spaceVidLen_, isIntId_);
context_ = std::make_unique<RunTimeContext>(planContext_.get());
if (env_->txnMan_ && env_->txnMan_->enableToss(spaceId_)) {
planContext_->defaultEdgeVer_ = 1L;
}
retCode = checkAndBuildContexts(req);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
LOG(ERROR) << "Failure build contexts: " << apache::thrift::util::enumNameSafe(retCode);
pushResultCode(retCode, partId);
onFinished();
return;
}
CHECK_NOTNULL(env_->indexMan_);
auto iRet = env_->indexMan_->getEdgeIndexes(spaceId_);
if (!iRet.ok()) {
LOG(ERROR) << iRet.status();
pushResultCode(nebula::cpp2::ErrorCode::E_SPACE_NOT_FOUND, partId);
onFinished();
return;
}
indexes_ = std::move(iRet).value();
VLOG(3) << "Update edge, spaceId: " << spaceId_ << ", partId: " << partId
<< ", src: " << edgeKey_.get_src() << ", edge_type: " << edgeKey_.get_edge_type()
<< ", dst: " << edgeKey_.get_dst() << ", ranking: " << edgeKey_.get_ranking();
auto plan = buildPlan(&resultDataSet_);
auto ret = plan.go(partId, edgeKey_);
if (ret != nebula::cpp2::ErrorCode::SUCCEEDED) {
handleErrorCode(ret, spaceId_, partId);
if (ret == nebula::cpp2::ErrorCode::E_FILTER_OUT) {
onProcessFinished();
}
} else {
onProcessFinished();
}
onFinished();
return;
}
nebula::cpp2::ErrorCode
UpdateEdgeProcessor::checkAndBuildContexts(const cpp2::UpdateEdgeRequest& req) {
// Build edgeContext_.schemas_
auto retCode = buildEdgeSchema();
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
return retCode;
}
// Build edgeContext_.propContexts_ edgeTypeProps_
retCode = buildEdgeContext(req);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
return retCode;
}
// Build edgeContext_.ttlInfo_
buildEdgeTTLInfo();
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
/*
The storage plan of update(upsert) edge looks like this:
+--------+----------+
| UpdateEdgeResNode |
+--------+----------+
|
+--------+----------+
| UpdateEdgeNode |
+--------+----------+
|
+--------+----------+
| FilterNode |
+--------+----------+
|
+--------+----------+
| FetchEdgeNode |
+-------------------+
*/
StoragePlan<cpp2::EdgeKey> UpdateEdgeProcessor::buildPlan(nebula::DataSet* result) {
StoragePlan<cpp2::EdgeKey> plan;
// because update edgetype is one
auto edgeUpdate = std::make_unique<FetchEdgeNode>(context_.get(),
&edgeContext_,
edgeContext_.propContexts_[0].first,
&(edgeContext_.propContexts_[0].second));
auto filterNode = std::make_unique<FilterNode<cpp2::EdgeKey>>(context_.get(),
edgeUpdate.get(),
expCtx_.get(),
filterExp_);
filterNode->addDependency(edgeUpdate.get());
auto updateNode = std::make_unique<UpdateEdgeNode>(context_.get(),
indexes_,
updatedProps_,
filterNode.get(),
insertable_,
depPropMap_,
expCtx_.get(),
&edgeContext_);
updateNode->addDependency(filterNode.get());
auto resultNode = std::make_unique<UpdateResNode<cpp2::EdgeKey>>(context_.get(),
updateNode.get(),
getReturnPropsExp(),
expCtx_.get(),
result);
resultNode->addDependency(updateNode.get());
plan.addNode(std::move(edgeUpdate));
plan.addNode(std::move(filterNode));
plan.addNode(std::move(updateNode));
plan.addNode(std::move(resultNode));
return plan;
}
// Get all edge schema in spaceID
nebula::cpp2::ErrorCode UpdateEdgeProcessor::buildEdgeSchema() {
auto edges = env_->schemaMan_->getAllVerEdgeSchema(spaceId_);
if (!edges.ok()) {
return nebula::cpp2::ErrorCode::E_SPACE_NOT_FOUND;
}
edgeContext_.schemas_ = std::move(edges).value();
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
// edgeContext.propContexts_ return prop, filter prop, update prop
nebula::cpp2::ErrorCode
UpdateEdgeProcessor::buildEdgeContext(const cpp2::UpdateEdgeRequest& req) {
// Build default edge context
auto edgeNameRet = env_->schemaMan_->toEdgeName(spaceId_, std::abs(edgeKey_.get_edge_type()));
if (!edgeNameRet.ok()) {
VLOG(1) << "Can't find spaceId " << spaceId_ << " edgeType "
<< std::abs(edgeKey_.get_edge_type());
return nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND;
}
auto edgeName = edgeNameRet.value();
std::vector<PropContext> ctxs;
edgeContext_.propContexts_.emplace_back(edgeKey_.get_edge_type(), std::move(ctxs));
edgeContext_.indexMap_.emplace(edgeKey_.get_edge_type(), edgeContext_.propContexts_.size() - 1);
edgeContext_.edgeNames_.emplace(edgeKey_.get_edge_type(), edgeName);
auto pool = context_->objPool();
// Build context of the update edge prop
for (auto& edgeProp : updatedProps_) {
auto edgePropExp = EdgePropertyExpression::make(pool, edgeName, edgeProp.get_name());
auto retCode = checkExp(edgePropExp, false, false);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
VLOG(1) << "Invalid update edge expression!";
return retCode;
}
auto updateExp = Expression::decode(pool, edgeProp.get_value());
if (!updateExp) {
VLOG(1) << "Can't decode the prop's value " << edgeProp.get_value();
return nebula::cpp2::ErrorCode::E_INVALID_UPDATER;
}
valueProps_.clear();
retCode = checkExp(updateExp, false, false, insertable_);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
return retCode;
}
if (insertable_) {
depPropMap_.emplace_back(std::make_pair(edgeProp.get_name(), valueProps_));
}
}
// Return props
if (req.return_props_ref().has_value()) {
for (auto& prop : *req.return_props_ref()) {
auto colExp = Expression::decode(pool, prop);
if (!colExp) {
VLOG(1) << "Can't decode the return expression";
return nebula::cpp2::ErrorCode::E_INVALID_UPDATER;
}
auto retCode = checkExp(colExp, true, false);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
return retCode;
}
returnPropsExp_.emplace_back(std::move(colExp));
}
}
// Condition
if (req.condition_ref().has_value()) {
const auto& filterStr = *req.condition_ref();
if (!filterStr.empty()) {
filterExp_ = Expression::decode(pool, filterStr);
if (!filterExp_) {
VLOG(1) << "Can't decode the filter " << filterStr;
return nebula::cpp2::ErrorCode::E_INVALID_FILTER;
}
auto retCode = checkExp(filterExp_, false, true);
if (retCode != nebula::cpp2::ErrorCode::SUCCEEDED) {
return retCode;
}
}
}
// update edge only handle one edgetype
// maybe no updated prop, filter prop, return prop
auto iter = edgeContext_.edgeNames_.find(edgeKey_.get_edge_type());
if (edgeContext_.edgeNames_.size() != 1 ||
iter == edgeContext_.edgeNames_.end()) {
VLOG(1) << "should only contain one edge in update edge!";
return nebula::cpp2::ErrorCode::E_MUTATE_EDGE_CONFLICT;
}
context_->edgeType_ = edgeKey_.get_edge_type();
context_->edgeName_ = iter->second;
auto schemaMap = edgeContext_.schemas_;
auto iterSchema = schemaMap.find(std::abs(edgeKey_.get_edge_type()));
if (iterSchema != schemaMap.end()) {
auto schemas = iterSchema->second;
auto schema = schemas.back().get();
if (!schema) {
VLOG(1) << "Fail to get schema in edgeType " << edgeKey_.get_edge_type();
return nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND;
}
context_->edgeSchema_ = schema;
} else {
VLOG(1) << "Fail to get schema in edgeType " << edgeKey_.get_edge_type();
return nebula::cpp2::ErrorCode::E_EDGE_NOT_FOUND;
}
if (expCtx_ == nullptr) {
expCtx_ = std::make_unique<StorageExpressionContext>(spaceVidLen_,
isIntId_,
context_->edgeName_,
context_->edgeSchema_,
true);
}
return nebula::cpp2::ErrorCode::SUCCEEDED;
}
void UpdateEdgeProcessor::onProcessFinished() {
resp_.set_props(std::move(resultDataSet_));
}
} // namespace storage
} // namespace nebula
|
#include <iostream>
#include "geo3x3.h"
using namespace std;
int main() {
char buf[30];
Geo3x3_encode(35.65858, 139.745433, 14, buf);
cout << buf << endl;
double res[4];
Geo3x3_decode("E3793653391822", res);
cout << res[0] << " " << res[1] << " " << res[2] << " " << res[3] << endl;
return 0;
}
|
db GOLDEEN ; pokedex id
db 45 ; base hp
db 67 ; base attack
db 60 ; base defense
db 63 ; base speed
db 50 ; base special
db WATER ; species type 1
db WATER ; species type 2
db 225 ; catch rate
db 111 ; base exp yield
INCBIN "pic/gsmon/goldeen.pic",0,1 ; 66, sprite dimensions
dw GoldeenPicFront
dw GoldeenPicBack
; attacks known at lvl 0
db PECK
db 0
db 0
db 0
db 0 ; growth rate
; learnset
tmlearn 6,7
tmlearn 9,10,11,13,14
tmlearn 20
tmlearn 31,32
tmlearn 34,39
tmlearn 44
tmlearn 50,53
db BANK(GoldeenPicFront)
|
/*
* Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h"
#include "CppUTest/TestHarness_c.h"
#include "CppUTestExt/MockSupport_c.h"
#include "TestMockSupport_cCFile.h"
TEST_GROUP(MockSupport_c)
{
};
TEST(MockSupport_c, expectAndActualOneCall)
{
mock_c()->expectOneCall("boo");
mock_c()->actualCall("boo");
mock_c()->checkExpectations();
}
TEST(MockSupport_c, expectAndActualParameters)
{
mock_c()->expectOneCall("boo")->withIntParameters("integer", 1)->withDoubleParameters("doube", 1.0)->
withStringParameters("string", "string")->withPointerParameters("pointer", (void*) 1);
mock_c()->actualCall("boo")->withIntParameters("integer", 1)->withDoubleParameters("doube", 1.0)->
withStringParameters("string", "string")->withPointerParameters("pointer", (void*) 1);
}
static int typeNameIsEqual(void* object1, void* object2)
{
return object1 == object2;
}
static char* typeNameValueToString(void* PUNUSED(object))
{
return (char*) "valueToString";
}
TEST(MockSupport_c, expectAndActualParametersOnObject)
{
mock_c()->installComparator("typeName", typeNameIsEqual, typeNameValueToString);
mock_c()->expectOneCall("boo")->withParameterOfType("typeName", "name", (void*) 1);
mock_c()->actualCall("boo")->withParameterOfType("typeName", "name", (void*) 1);
mock_c()->checkExpectations();
mock_c()->removeAllComparators();
}
TEST(MockSupport_c, returnIntValue)
{
mock_c()->expectOneCall("boo")->andReturnIntValue(10);
LONGS_EQUAL(10, mock_c()->actualCall("boo")->returnValue().value.intValue);
LONGS_EQUAL(MOCKVALUETYPE_INTEGER, mock_c()->returnValue().type);
}
TEST(MockSupport_c, returnDoubleValue)
{
mock_c()->expectOneCall("boo")->andReturnDoubleValue(1.0);
DOUBLES_EQUAL(1.0, mock_c()->actualCall("boo")->returnValue().value.doubleValue, 0.005);
LONGS_EQUAL(MOCKVALUETYPE_DOUBLE, mock_c()->returnValue().type);
}
TEST(MockSupport_c, returnStringValue)
{
mock_c()->expectOneCall("boo")->andReturnStringValue("hello world");
STRCMP_EQUAL("hello world", mock_c()->actualCall("boo")->returnValue().value.stringValue);
LONGS_EQUAL(MOCKVALUETYPE_STRING, mock_c()->returnValue().type);
}
TEST(MockSupport_c, returnPointerValue)
{
mock_c()->expectOneCall("boo")->andReturnPointerValue((void*) 10);
POINTERS_EQUAL((void*) 10, mock_c()->actualCall("boo")->returnValue().value.pointerValue);
LONGS_EQUAL(MOCKVALUETYPE_POINTER, mock_c()->returnValue().type);
}
TEST(MockSupport_c, MockSupportWithScope)
{
mock_scope_c("scope")->expectOneCall("boo");
LONGS_EQUAL(0, mock_scope_c("other")->expectedCallsLeft());
LONGS_EQUAL(1, mock_scope_c("scope")->expectedCallsLeft());
mock_scope_c("scope")->actualCall("boo");
}
TEST(MockSupport_c, MockSupportSetIntData)
{
mock_c()->setIntData("integer", 10);
LONGS_EQUAL(10, mock_c()->getData("integer").value.intValue);
}
TEST(MockSupport_c, MockSupportSetDoubleData)
{
mock_c()->setDoubleData("double", 1.0);
DOUBLES_EQUAL(1.00, mock_c()->getData("double").value.doubleValue, 0.05);
}
TEST(MockSupport_c, MockSupportSetStringData)
{
mock_c()->setStringData("string", "hello world");
STRCMP_EQUAL("hello world", mock_c()->getData("string").value.stringValue);
}
TEST(MockSupport_c, MockSupportSetPointerData)
{
mock_c()->setPointerData("pointer", (void*) 1);
POINTERS_EQUAL((void*) 1, mock_c()->getData("pointer").value.pointerValue);
}
TEST(MockSupport_c, MockSupportSetDataObject)
{
mock_c()->setDataObject("name", "type", (void*) 1);
POINTERS_EQUAL((void*) 1, mock_c()->getData("name").value.objectValue);
}
TEST(MockSupport_c, WorksInCFile)
{
all_mock_support_c_calls();
}
|
copyright zengfr site:http://github.com/zengfr/romhack
002F7C move.w (A0,D0.w), D1 [boss+37, enemy+37]
copyright zengfr site:http://github.com/zengfr/romhack
|
; A292295: Sum of values of vertices of type A at level n of the hyperbolic Pascal pyramid.
; 0,0,6,18,54,174,582,1974,6726,22950,78342,267462,913158,3117702,10644486,36342534,124081158,423639558,1446395910,4938304518,16860426246,57565095942,196539531270,671027933190,2291032670214,7822074814470,26706233917446,91180786040838,311310676328454,1062881133232134,3628903180271622
mov $2,6
lpb $0,1
sub $0,1
add $1,$3
add $2,$1
mul $1,2
sub $2,3
mov $3,$2
lpe
|
; A145812: Odd positive integers a(n) such that for every odd integer m > 1 there exists a unique representation of m as a sum of the form a(l) + 2a(s).
; 1,3,9,11,33,35,41,43,129,131,137,139,161,163,169,171,513,515,521,523,545,547,553,555,641,643,649,651,673,675,681,683,2049,2051,2057,2059,2081,2083,2089,2091,2177,2179,2185,2187,2209,2211,2217,2219,2561,2563,2569,2571,2593,2595,2601,2603,2689,2691,2697,2699,2721,2723,2729,2731,8193,8195,8201,8203,8225,8227,8233,8235,8321,8323,8329,8331,8353,8355,8361,8363,8705,8707,8713,8715,8737,8739,8745,8747,8833,8835,8841,8843,8865,8867,8873,8875,10241,10243,10249,10251,10273,10275,10281,10283,10369,10371,10377,10379,10401,10403,10409,10411,10753,10755,10761,10763,10785,10787,10793,10795,10881,10883,10889,10891,10913,10915,10921,10923,32769,32771,32777,32779,32801,32803,32809,32811,32897,32899,32905,32907,32929,32931,32937,32939,33281,33283,33289,33291,33313,33315,33321,33323,33409,33411,33417,33419,33441,33443,33449,33451,34817,34819,34825,34827,34849,34851,34857,34859,34945,34947,34953,34955,34977,34979,34985,34987,35329,35331,35337,35339,35361,35363,35369,35371,35457,35459,35465,35467,35489,35491,35497,35499,40961,40963,40969,40971,40993,40995,41001,41003,41089,41091,41097,41099,41121,41123,41129,41131,41473,41475,41481,41483,41505,41507,41513,41515,41601,41603,41609,41611,41633,41635,41641,41643,43009,43011,43017,43019,43041,43043,43049,43051,43137,43139,43145,43147,43169,43171,43177,43179,43521,43523,43529,43531,43553,43555,43561,43563,43649,43651
mov $2,$0
add $2,1
mov $6,$0
lpb $2
mov $0,$6
sub $2,1
sub $0,$2
mov $3,1
mov $5,$0
add $5,$0
lpb $0
sub $0,1
mul $3,2
gcd $3,$5
lpe
pow $3,2
mul $3,2
mov $4,$3
div $4,6
add $4,1
add $1,$4
lpe
|
; A345939: a(n) = (n-1) / gcd(n-1, uphi(n)), where uphi is unitary totient (or unitary phi) function, A047994.
; Submitted by Christian Krause
; 0,1,1,1,1,5,1,1,1,9,1,11,1,13,7,1,1,17,1,19,5,21,1,23,1,25,1,3,1,29,1,1,8,33,17,35,1,37,19,39,1,41,1,43,11,45,1,47,1,49,25,17,1,53,27,55,14,57,1,59,1,61,31,1,4,13,1,67,17,23,1,71,1,73,37,25,19,77,1,79,1,81,1,83,21,85,43,87,1,89,5,91,23,93,47,95,1,97,49,11
mov $2,$0
seq $0,47994 ; Unitary totient (or unitary phi) function uphi(n).
mov $1,$0
gcd $1,$2
div $2,$1
mov $0,$2
|
; A162642: Number of odd exponents in the canonical prime factorization of n.
; 0,1,1,0,1,2,1,1,0,2,1,1,1,2,2,0,1,1,1,1,2,2,1,2,0,2,1,1,1,3,1,1,2,2,2,0,1,2,2,2,1,3,1,1,1,2,1,1,0,1,2,1,1,2,2,2,2,2,1,2,1,2,1,0,2,3,1,1,2,3,1,1,1,2,1,1,2,3,1,1,0,2,1,2,2,2,2,2,1,2,2,1,2,2,2,2,1,1,1,0
seq $0,7913 ; Squarefree part of n: a(n) is the smallest positive number m such that n/m is a square.
sub $0,1
seq $0,1222 ; Number of prime divisors of n counted with multiplicity (also called bigomega(n) or Omega(n)).
|
#include <gatb/debruijn/impl/GraphUnitigs.hpp>
#include <bcalm_1.hpp>
using namespace std;
/*
* where did all the code go? now it's mostly in ../gatb-core/gatb-core/src/gatb/bcalm/
*/
/********************************************************************************/
bcalm_1::bcalm_1 () : Tool ("bcalm_1"){
// old options, now using GATB's built-in options for kmer counting and graph creation
// but TODO would be nice to integrate --nb-glue-partitions in gatb someday
/* getParser()->push_back (new OptionOneParam ("-in", "input file", true));
getParser()->push_back (new OptionOneParam ("-out", "output prefix", false, "unitigs"));
getParser()->push_back (new OptionOneParam ("-k", "kmer size", false,"31"));
getParser()->push_back (new OptionOneParam ("-m", "minimizer size", false,"8"));
getParser()->push_back (new OptionOneParam ("-abundance", "abundance threshold", false,"1"));
getParser()->push_back (new OptionOneParam ("-minimizer-type", "use lexicographical minimizers (0) or frequency based (1)", false,"1"));
getParser()->push_back (new OptionOneParam ("-dsk-memory", "max memory for kmer counting (MB)", false, "1500"));
getParser()->push_back (new OptionOneParam ("-dsk-disk", "max disk space for kmer counting (MB)", false, "default"));
// glue options
getParser()->push_front (new OptionNoParam ("--only-uf", "(for debugging only) stop after UF construction", false));
getParser()->push_front (new OptionNoParam ("--uf-stats", "display UF statistics", false));
getParser()->push_back (new OptionOneParam ("--nb-glue-partitions", "number of glue files on disk", false,"200"));
*/
IOptionsParser* graphParser = GraphUnitigsTemplate<32>::getOptionsParser(false);
// hiding options
if (IOptionsParser* p = graphParser->getParser(STR_KMER_ABUNDANCE_MIN_THRESHOLD)) { p->setVisible(false); }
if (IOptionsParser* p = graphParser->getParser(STR_HISTOGRAM_MAX)) { p->setVisible(false); }
if (IOptionsParser* p = graphParser->getParser(STR_SOLIDITY_KIND)) { p->setVisible(false); } // oohh. multi-sample dbg construction someday maybe?
if (IOptionsParser* p = graphParser->getParser(STR_URI_SOLID_KMERS)) { p->setVisible(false); }
// setting defaults
if (Option* p = dynamic_cast<Option*> (graphParser->getParser(STR_REPARTITION_TYPE))) { p->setDefaultValue ("1"); }
if (Option* p = dynamic_cast<Option*> (graphParser->getParser(STR_MINIMIZER_TYPE))) { p->setDefaultValue ("1"); }
getParser()->push_back(graphParser);
}
template <size_t span>
struct Functor { void operator () (bcalm_1 *bcalm)
{
typedef GraphUnitigsTemplate<span> GraphType;
GraphType graph;
if (bcalm->getInput()->get(STR_URI_INPUT) != 0)
{
graph = GraphType::create (bcalm->getInput(), false /* do not load unitigs after*/);
}
else
{
throw OptionFailure (bcalm->getParser(), "Specifiy -in");
}
// delete the .h5 file
bool delete_h5_file = true;
if (delete_h5_file)
{
// copies the h5 naming mechanism in GraphUnitigs.cpp
string input = bcalm->getInput()->getStr(STR_URI_INPUT);
string prefix;
if (bcalm->getInput()->get(STR_URI_OUTPUT))
prefix = bcalm->getInput()->getStr(STR_URI_OUTPUT);
else
prefix = System::file().getBaseName (input) + prefix;
System::file().remove (prefix + ".h5");
}
}
};
void bcalm_1::execute (){
std::cout << "BCALM 2, version " << VERSION;
#ifdef GIT_SHA1
std::cout << ", git commit " << GIT_SHA1;
#endif
std::cout << std::endl;
/** we get the kmer size chosen by the end user. */
size_t kmerSize = getInput()->getInt (STR_KMER_SIZE);
/** We launch Minia with the correct Integer implementation according to the choosen kmer size. */
Integer::apply<Functor,bcalm_1*> (kmerSize, this);
}
|
; A145069: a(n) = n*(n^2 + 3*n + 5)/3.
; 0,3,10,23,44,75,118,175,248,339,450,583,740,923,1134,1375,1648,1955,2298,2679,3100,3563,4070,4623,5224,5875,6578,7335,8148,9019,9950,10943,12000,13123,14314,15575,16908,18315,19798,21359,23000,24723,26530,28423,30404,32475,34638,36895,39248,41699,44250,46903,49660,52523,55494,58575,61768,65075,68498,72039,75700,79483,83390,87423,91584,95875,100298,104855,109548,114379,119350,124463,129720,135123,140674,146375,152228,158235,164398,170719,177200,183843,190650,197623,204764,212075,219558,227215,235048,243059,251250,259623,268180,276923,285854,294975,304288,313795,323498,333399
add $0,1
mov $1,$0
pow $0,2
add $0,2
mul $0,$1
sub $0,1
div $0,3
|
Map_4DA68: dc.w word_4DA6A-Map_4DA68
word_4DA6A: dc.w 3
dc.b $FC, 0, 0, 0, $FF, $D4
dc.b $FC, $C, 0, 1, $FF, $E4
dc.b $FC, $C, 0, 5, 0, $C
|
global uint32_to_ip
section .text
; <--- char *uint32_to_ip(char *ip, uint32_t num) --->
; Converter without using a library function.
uint32_to_ip:
%push mycontext ; store current context
%stacksize flat64 ; address stack frame with rbp
%assign %$localsize 0
BUFFER_SIZE equ 4*4 ; maximal 4 x 4 chars for IP address text
%local b1:QWORD,b2:QWORD ; reserve bytes
%local buffer:BYTE
%local result:QWORD
enter %$localsize, 0 ; allocate stack frame
mov [result], rdi ; store pointer to return buffer
lea rdi, [buffer+BUFFER_SIZE] ; rdi = running pointer in buffer
std ; create address from end
; convert int into IP address text
mov bx, 10 ; base of the decimal numbers
xor al, al
stosb ; end of string
mov rcx, 4 ; 4 numbers in the IP address text
jmp .start_ip_loop ; start converting the least significant byte
.convert_ip_loop:
mov al, '.' ; separate numbers by a dot
stosb
.start_ip_loop:
mov ax, si ; move the last byte into al
and ax, 0xff
shr rsi, 8
; convert byte in ax into decimal number
.convert_byte_loop:
xor dx, dx
div bx
add dl,'0' ; convert value to ASCII decimal digit
mov [rdi], dl ; write digit into buffer
dec rdi ; down in the buffer
test ax, ax
jnz .convert_byte_loop
loop .convert_ip_loop
; copy IP address into output buffer
mov rsi, rdi
inc rsi ; rsi = first char in the buffer
mov rdi, [result] ; rdi = result buffer
cld ; prepare string copy rsi -> rdi
.copy_loop:
lodsb
stosb
test al, al ; check for end of string
jnz .copy_loop
; return
mov rax, [result] ; RAX <- IP address text
leave ; freee stach frame
ret
%pop ; restore old context
; -----> endof uint32_to_ip <-----
|
SECTION code_clib
SECTION code_fp_math48
PUBLIC ___fs2uchar
EXTERN cm48_sdccixp_ds2uchar
defc ___fs2uchar = cm48_sdccixp_ds2uchar
|
// The YukinoDB Unit Test Suite
//
// area_test.cc
//
// Created by Niko Bellic.
//
//
#include "util/area-inl.h"
#include "util/area.h"
#include "gtest/gtest.h"
#include <stdio.h>
namespace yukino {
namespace util {
class AreaTest : public ::testing::Test {
public:
AreaTest ()
: area_(kPageSize) {
}
virtual void SetUp() override {
EXPECT_EQ(0, area_.ApproximateMemoryUsage());
}
virtual void TearDown() override {
area_.Purge();
}
static const size_t kPageSize = 4 * base::kKB;
static const int kBench = 1000000;
Area area_;
};
TEST_F(AreaTest, Sanity) {
EXPECT_EQ(0, area_.ApproximateMemoryUsage());
auto p = area_.Allocate(1);
EXPECT_EQ(area_.page_size(), area_.ApproximateMemoryUsage());
area_.Free(p);
EXPECT_EQ(0, area_.ApproximateMemoryUsage());
EXPECT_EQ(nullptr, area_.Allocate(0));
area_.Free(nullptr);
}
TEST_F(AreaTest, MutilPageAllocation) {
std::vector<const void*> collected;
auto k = area_.page_size() / area_.segment_chunk_size(1);
for (auto i = 0; i < k; ++i) {
auto p = area_.Allocate(1);
EXPECT_NE(nullptr, p);
collected.push_back(p);
}
EXPECT_EQ(area_.page_size() * 2, area_.ApproximateMemoryUsage());
for (auto p : collected) {
area_.Free(p);
}
EXPECT_EQ(0, area_.ApproximateMemoryUsage());
}
TEST_F(AreaTest, LargePageAllocation) {
auto large_size = area_.segment_chunk_size(Area::kNumSegments - 1) * 2;
auto p = area_.Allocate(large_size);
EXPECT_NE(nullptr, p);
EXPECT_LE(large_size, area_.ApproximateMemoryUsage());
area_.Free(p);
EXPECT_EQ(0, area_.ApproximateMemoryUsage());
}
// 303 ms
// 160 ms
TEST_F(AreaTest, AreaBenchmark) {
size_t slots[Area::kNumSegments] = {
area_.segment_chunk_size(Area::kNumSegments - 1) * 2,
area_.segment_chunk_size(1),
area_.segment_chunk_size(2),
area_.segment_chunk_size(3),
area_.segment_chunk_size(4),
area_.segment_chunk_size(5),
};
for (auto size : slots) {
area_.Allocate(size);
}
for (auto i = 0; i < kBench; ++i) {
auto p = area_.Allocate(slots[i % Area::kNumSegments]);
area_.Free(p);
}
}
} // namespace util
} // namespace yukino
|
.inesprg 4 ; 4x 16KB PRG = 128KB PRG
.ineschr 0 ; 0x 8KB CHR
.inesmap 1 ; MMC1 mapper
.inesmir %10
.include "nes_constants.asm"
.include "constants.asm"
.rsset $0000
.include "variables.asm"
.bank 0
.org $8000
.include "maps/map00.asm"
.bank 1
.org $A000
.bank 2
.org $8000
.bank 3
.org $A000
.bank 4
.org $8000
.bank 5
.org $A000
.bank 6
.org $C000
Graphics:
.incbin "graphics/bank.chr"
.bank 7
.org $E000
;; subroutines
.include "init_helper.asm"
.include "engine/readController.asm"
.include "engine/drawsprite.asm"
.include "engine/renderMap.asm"
.include "engine/renderPlayer.asm"
.include "engine/renderEnemies.asm"
;; START
.include "init.asm"
.include "engine/init.asm"
NMI
.include "engine/engine.asm"
RTI
.include "engine/overworld.asm"
palette:
.db $30,$37,$16,$27, $22,$16,$17,$0F, $22,$30,$21,$0F, $22,$27,$17,$0F ;;background palette
.db $30,$1E,$16,$27, $30,$0F,$16,$30, $22,$1C,$15,$14, $22,$02,$38,$3C ;;sprite palette
.include "maps/tileset.asm"
.include "sprites/sprites.asm"
.org $FFFA
.dw NMI
.dw RESET
.dw 0 |
; A279506: Total number of 1's in the binary expansion of A003418.
; Submitted by Jamie Morken(w4)
; 1,1,1,2,2,4,4,4,4,6,6,6,6,12,12,12,12,12,12,12,12,12,12,14,14,21,21,18,18,17,17,22,22,22,22,22,22,28,28,28,28,25,25,32,32,32,32,40,40,40,40,40,40,43,43,43,43,43,43,38,38,44,44,44,44,44,44,47,47,47,47,52,52,56,56,56,56,56,56,53,53,51,51,65,65,65,65,65,65,63,63,63,63,63,63,63,63,67,67,67
seq $0,3418 ; Least common multiple (or LCM) of {1, 2, ..., n} for n >= 1, a(0) = 1.
seq $0,120 ; 1's-counting sequence: number of 1's in binary expansion of n (or the binary weight of n).
|
/* Copyright (c) 2017-2020, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation, nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER 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.
*
*/
#define LOG_TAG "LocSvc_SystemStatus"
#include <inttypes.h>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <pthread.h>
#include <loc_pla.h>
#include <log_util.h>
#include <loc_nmea.h>
#include <DataItemsFactoryProxy.h>
#include <SystemStatus.h>
#include <SystemStatusOsObserver.h>
#include <DataItemConcreteTypesBase.h>
namespace loc_core
{
/******************************************************************************
SystemStatusNmeaBase - base class for all NMEA parsers
******************************************************************************/
class SystemStatusNmeaBase
{
protected:
std::vector<std::string> mField;
SystemStatusNmeaBase(const char *str_in, uint32_t len_in)
{
// check size and talker
if (!loc_nmea_is_debug(str_in, len_in)) {
return;
}
std::string parser(str_in);
std::string::size_type index = 0;
// verify checksum field
index = parser.find("*");
if (index == std::string::npos) {
return;
}
parser[index] = ',';
// tokenize parser
while (1) {
std::string str;
index = parser.find(",");
if (index == std::string::npos) {
break;
}
str = parser.substr(0, index);
parser = parser.substr(index + 1);
mField.push_back(str);
}
}
virtual ~SystemStatusNmeaBase() { }
public:
static const uint32_t NMEA_MINSIZE = DEBUG_NMEA_MINSIZE;
static const uint32_t NMEA_MAXSIZE = DEBUG_NMEA_MAXSIZE;
};
/******************************************************************************
SystemStatusPQWM1
******************************************************************************/
class SystemStatusPQWM1
{
public:
uint16_t mGpsWeek; // x1
uint32_t mGpsTowMs; // x2
uint8_t mTimeValid; // x3
uint8_t mTimeSource; // x4
int32_t mTimeUnc; // x5
int32_t mClockFreqBias; // x6
int32_t mClockFreqBiasUnc; // x7
uint8_t mXoState; // x8
int32_t mPgaGain; // x9
uint32_t mGpsBpAmpI; // xA
uint32_t mGpsBpAmpQ; // xB
uint32_t mAdcI; // xC
uint32_t mAdcQ; // xD
uint32_t mJammerGps; // xE
uint32_t mJammerGlo; // xF
uint32_t mJammerBds; // x10
uint32_t mJammerGal; // x11
uint32_t mRecErrorRecovery; // x12
double mAgcGps; // x13
double mAgcGlo; // x14
double mAgcBds; // x15
double mAgcGal; // x16
int32_t mLeapSeconds;// x17
int32_t mLeapSecUnc; // x18
uint32_t mGloBpAmpI; // x19
uint32_t mGloBpAmpQ; // x1A
uint32_t mBdsBpAmpI; // x1B
uint32_t mBdsBpAmpQ; // x1C
uint32_t mGalBpAmpI; // x1D
uint32_t mGalBpAmpQ; // x1E
uint64_t mTimeUncNs; // x1F
};
// parser
class SystemStatusPQWM1parser : public SystemStatusNmeaBase
{
private:
enum
{
eTalker = 0,
eGpsWeek = 1,
eGpsTowMs = 2,
eTimeValid = 3,
eTimeSource = 4,
eTimeUnc = 5,
eClockFreqBias = 6,
eClockFreqBiasUnc = 7,
eXoState = 8,
ePgaGain = 9,
eGpsBpAmpI = 10,
eGpsBpAmpQ = 11,
eAdcI = 12,
eAdcQ = 13,
eJammerGps = 14,
eJammerGlo = 15,
eJammerBds = 16,
eJammerGal = 17,
eRecErrorRecovery = 18,
eAgcGps = 19,
eAgcGlo = 20,
eAgcBds = 21,
eAgcGal = 22,
eMax0 = eAgcGal,
eLeapSeconds = 23,
eLeapSecUnc = 24,
eGloBpAmpI = 25,
eGloBpAmpQ = 26,
eBdsBpAmpI = 27,
eBdsBpAmpQ = 28,
eGalBpAmpI = 29,
eGalBpAmpQ = 30,
eTimeUncNs = 31,
eMax
};
SystemStatusPQWM1 mM1;
public:
inline uint16_t getGpsWeek() { return mM1.mGpsWeek; }
inline uint32_t getGpsTowMs() { return mM1.mGpsTowMs; }
inline uint8_t getTimeValid() { return mM1.mTimeValid; }
inline uint8_t getTimeSource() { return mM1.mTimeSource; }
inline int32_t getTimeUnc() { return mM1.mTimeUnc; }
inline int32_t getClockFreqBias() { return mM1.mClockFreqBias; }
inline int32_t getClockFreqBiasUnc() { return mM1.mClockFreqBiasUnc; }
inline uint8_t getXoState() { return mM1.mXoState;}
inline int32_t getPgaGain() { return mM1.mPgaGain; }
inline uint32_t getGpsBpAmpI() { return mM1.mGpsBpAmpI; }
inline uint32_t getGpsBpAmpQ() { return mM1.mGpsBpAmpQ; }
inline uint32_t getAdcI() { return mM1.mAdcI; }
inline uint32_t getAdcQ() { return mM1.mAdcQ; }
inline uint32_t getJammerGps() { return mM1.mJammerGps; }
inline uint32_t getJammerGlo() { return mM1.mJammerGlo; }
inline uint32_t getJammerBds() { return mM1.mJammerBds; }
inline uint32_t getJammerGal() { return mM1.mJammerGal; }
inline uint32_t getAgcGps() { return mM1.mAgcGps; }
inline uint32_t getAgcGlo() { return mM1.mAgcGlo; }
inline uint32_t getAgcBds() { return mM1.mAgcBds; }
inline uint32_t getAgcGal() { return mM1.mAgcGal; }
inline uint32_t getRecErrorRecovery() { return mM1.mRecErrorRecovery; }
inline int32_t getLeapSeconds(){ return mM1.mLeapSeconds; }
inline int32_t getLeapSecUnc() { return mM1.mLeapSecUnc; }
inline uint32_t getGloBpAmpI() { return mM1.mGloBpAmpI; }
inline uint32_t getGloBpAmpQ() { return mM1.mGloBpAmpQ; }
inline uint32_t getBdsBpAmpI() { return mM1.mBdsBpAmpI; }
inline uint32_t getBdsBpAmpQ() { return mM1.mBdsBpAmpQ; }
inline uint32_t getGalBpAmpI() { return mM1.mGalBpAmpI; }
inline uint32_t getGalBpAmpQ() { return mM1.mGalBpAmpQ; }
inline uint64_t getTimeUncNs() { return mM1.mTimeUncNs; }
SystemStatusPQWM1parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
memset(&mM1, 0, sizeof(mM1));
if (mField.size() <= eMax0) {
LOC_LOGE("PQWM1parser - invalid size=%zu", mField.size());
mM1.mTimeValid = 0;
return;
}
mM1.mGpsWeek = atoi(mField[eGpsWeek].c_str());
mM1.mGpsTowMs = atoi(mField[eGpsTowMs].c_str());
mM1.mTimeValid = atoi(mField[eTimeValid].c_str());
mM1.mTimeSource = atoi(mField[eTimeSource].c_str());
mM1.mTimeUnc = atoi(mField[eTimeUnc].c_str());
mM1.mClockFreqBias = atoi(mField[eClockFreqBias].c_str());
mM1.mClockFreqBiasUnc = atoi(mField[eClockFreqBiasUnc].c_str());
mM1.mXoState = atoi(mField[eXoState].c_str());
mM1.mPgaGain = atoi(mField[ePgaGain].c_str());
mM1.mGpsBpAmpI = atoi(mField[eGpsBpAmpI].c_str());
mM1.mGpsBpAmpQ = atoi(mField[eGpsBpAmpQ].c_str());
mM1.mAdcI = atoi(mField[eAdcI].c_str());
mM1.mAdcQ = atoi(mField[eAdcQ].c_str());
mM1.mJammerGps = atoi(mField[eJammerGps].c_str());
mM1.mJammerGlo = atoi(mField[eJammerGlo].c_str());
mM1.mJammerBds = atoi(mField[eJammerBds].c_str());
mM1.mJammerGal = atoi(mField[eJammerGal].c_str());
mM1.mRecErrorRecovery = atoi(mField[eRecErrorRecovery].c_str());
mM1.mAgcGps = atof(mField[eAgcGps].c_str());
mM1.mAgcGlo = atof(mField[eAgcGlo].c_str());
mM1.mAgcBds = atof(mField[eAgcBds].c_str());
mM1.mAgcGal = atof(mField[eAgcGal].c_str());
if (mField.size() > eLeapSecUnc) {
mM1.mLeapSeconds = atoi(mField[eLeapSeconds].c_str());
mM1.mLeapSecUnc = atoi(mField[eLeapSecUnc].c_str());
}
if (mField.size() > eGalBpAmpQ) {
mM1.mGloBpAmpI = atoi(mField[eGloBpAmpI].c_str());
mM1.mGloBpAmpQ = atoi(mField[eGloBpAmpQ].c_str());
mM1.mBdsBpAmpI = atoi(mField[eBdsBpAmpI].c_str());
mM1.mBdsBpAmpQ = atoi(mField[eBdsBpAmpQ].c_str());
mM1.mGalBpAmpI = atoi(mField[eGalBpAmpI].c_str());
mM1.mGalBpAmpQ = atoi(mField[eGalBpAmpQ].c_str());
}
if (mField.size() > eTimeUncNs) {
mM1.mTimeUncNs = strtoull(mField[eTimeUncNs].c_str(), nullptr, 10);
}
}
inline SystemStatusPQWM1& get() { return mM1;} //getparser
};
/******************************************************************************
SystemStatusPQWP1
******************************************************************************/
class SystemStatusPQWP1
{
public:
uint8_t mEpiValidity; // x4
float mEpiLat; // x5
float mEpiLon; // x6
float mEpiAlt; // x7
float mEpiHepe; // x8
float mEpiAltUnc; // x9
uint8_t mEpiSrc; // x10
};
class SystemStatusPQWP1parser : public SystemStatusNmeaBase
{
private:
enum
{
eTalker = 0,
eUtcTime = 1,
eEpiValidity = 2,
eEpiLat = 3,
eEpiLon = 4,
eEpiAlt = 5,
eEpiHepe = 6,
eEpiAltUnc = 7,
eEpiSrc = 8,
eMax
};
SystemStatusPQWP1 mP1;
public:
inline uint8_t getEpiValidity() { return mP1.mEpiValidity; }
inline float getEpiLat() { return mP1.mEpiLat; }
inline float getEpiLon() { return mP1.mEpiLon; }
inline float getEpiAlt() { return mP1.mEpiAlt; }
inline float getEpiHepe() { return mP1.mEpiHepe; }
inline float getEpiAltUnc() { return mP1.mEpiAltUnc; }
inline uint8_t getEpiSrc() { return mP1.mEpiSrc; }
SystemStatusPQWP1parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
if (mField.size() < eMax) {
return;
}
memset(&mP1, 0, sizeof(mP1));
mP1.mEpiValidity = strtol(mField[eEpiValidity].c_str(), NULL, 16);
mP1.mEpiLat = atof(mField[eEpiLat].c_str());
mP1.mEpiLon = atof(mField[eEpiLon].c_str());
mP1.mEpiAlt = atof(mField[eEpiAlt].c_str());
mP1.mEpiHepe = atoi(mField[eEpiHepe].c_str());
mP1.mEpiAltUnc = atof(mField[eEpiAltUnc].c_str());
mP1.mEpiSrc = atoi(mField[eEpiSrc].c_str());
}
inline SystemStatusPQWP1& get() { return mP1;}
};
/******************************************************************************
SystemStatusPQWP2
******************************************************************************/
class SystemStatusPQWP2
{
public:
float mBestLat; // x4
float mBestLon; // x5
float mBestAlt; // x6
float mBestHepe; // x7
float mBestAltUnc; // x8
};
class SystemStatusPQWP2parser : public SystemStatusNmeaBase
{
private:
enum
{
eTalker = 0,
eUtcTime = 1,
eBestLat = 2,
eBestLon = 3,
eBestAlt = 4,
eBestHepe = 5,
eBestAltUnc = 6,
eMax
};
SystemStatusPQWP2 mP2;
public:
inline float getBestLat() { return mP2.mBestLat; }
inline float getBestLon() { return mP2.mBestLon; }
inline float getBestAlt() { return mP2.mBestAlt; }
inline float getBestHepe() { return mP2.mBestHepe; }
inline float getBestAltUnc() { return mP2.mBestAltUnc; }
SystemStatusPQWP2parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
if (mField.size() < eMax) {
return;
}
memset(&mP2, 0, sizeof(mP2));
mP2.mBestLat = atof(mField[eBestLat].c_str());
mP2.mBestLon = atof(mField[eBestLon].c_str());
mP2.mBestAlt = atof(mField[eBestAlt].c_str());
mP2.mBestHepe = atof(mField[eBestHepe].c_str());
mP2.mBestAltUnc = atof(mField[eBestAltUnc].c_str());
}
inline SystemStatusPQWP2& get() { return mP2;}
};
/******************************************************************************
SystemStatusPQWP3
******************************************************************************/
class SystemStatusPQWP3
{
public:
uint8_t mXtraValidMask;
uint32_t mGpsXtraAge;
uint32_t mGloXtraAge;
uint32_t mBdsXtraAge;
uint32_t mGalXtraAge;
uint32_t mQzssXtraAge;
uint32_t mNavicXtraAge;
uint32_t mGpsXtraValid;
uint32_t mGloXtraValid;
uint64_t mBdsXtraValid;
uint64_t mGalXtraValid;
uint8_t mQzssXtraValid;
uint32_t mNavicXtraValid;
};
class SystemStatusPQWP3parser : public SystemStatusNmeaBase
{
private:
// todo: update for navic once available
enum
{
eTalker = 0,
eUtcTime = 1,
eXtraValidMask = 2,
eGpsXtraAge = 3,
eGloXtraAge = 4,
eBdsXtraAge = 5,
eGalXtraAge = 6,
eQzssXtraAge = 7,
eGpsXtraValid = 8,
eGloXtraValid = 9,
eBdsXtraValid = 10,
eGalXtraValid = 11,
eQzssXtraValid = 12,
eMax
};
SystemStatusPQWP3 mP3;
public:
inline uint8_t getXtraValid() { return mP3.mXtraValidMask; }
inline uint32_t getGpsXtraAge() { return mP3.mGpsXtraAge; }
inline uint32_t getGloXtraAge() { return mP3.mGloXtraAge; }
inline uint32_t getBdsXtraAge() { return mP3.mBdsXtraAge; }
inline uint32_t getGalXtraAge() { return mP3.mGalXtraAge; }
inline uint32_t getQzssXtraAge() { return mP3.mQzssXtraAge; }
inline uint32_t getNavicXtraAge() { return mP3.mNavicXtraAge; }
inline uint32_t getGpsXtraValid() { return mP3.mGpsXtraValid; }
inline uint32_t getGloXtraValid() { return mP3.mGloXtraValid; }
inline uint64_t getBdsXtraValid() { return mP3.mBdsXtraValid; }
inline uint64_t getGalXtraValid() { return mP3.mGalXtraValid; }
inline uint8_t getQzssXtraValid() { return mP3.mQzssXtraValid; }
inline uint32_t getNavicXtraValid() { return mP3.mNavicXtraValid; }
SystemStatusPQWP3parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
if (mField.size() < eMax) {
return;
}
memset(&mP3, 0, sizeof(mP3));
// todo: update for navic once available
mP3.mXtraValidMask = strtol(mField[eXtraValidMask].c_str(), NULL, 16);
mP3.mGpsXtraAge = atoi(mField[eGpsXtraAge].c_str());
mP3.mGloXtraAge = atoi(mField[eGloXtraAge].c_str());
mP3.mBdsXtraAge = atoi(mField[eBdsXtraAge].c_str());
mP3.mGalXtraAge = atoi(mField[eGalXtraAge].c_str());
mP3.mQzssXtraAge = atoi(mField[eQzssXtraAge].c_str());
mP3.mGpsXtraValid = strtol(mField[eGpsXtraValid].c_str(), NULL, 16);
mP3.mGloXtraValid = strtol(mField[eGloXtraValid].c_str(), NULL, 16);
mP3.mBdsXtraValid = strtol(mField[eBdsXtraValid].c_str(), NULL, 16);
mP3.mGalXtraValid = strtol(mField[eGalXtraValid].c_str(), NULL, 16);
mP3.mQzssXtraValid = strtol(mField[eQzssXtraValid].c_str(), NULL, 16);
}
inline SystemStatusPQWP3& get() { return mP3;}
};
/******************************************************************************
SystemStatusPQWP4
******************************************************************************/
class SystemStatusPQWP4
{
public:
uint32_t mGpsEpheValid;
uint32_t mGloEpheValid;
uint64_t mBdsEpheValid;
uint64_t mGalEpheValid;
uint8_t mQzssEpheValid;
};
class SystemStatusPQWP4parser : public SystemStatusNmeaBase
{
private:
enum
{
eTalker = 0,
eUtcTime = 1,
eGpsEpheValid = 2,
eGloEpheValid = 3,
eBdsEpheValid = 4,
eGalEpheValid = 5,
eQzssEpheValid = 6,
eMax
};
SystemStatusPQWP4 mP4;
public:
inline uint32_t getGpsEpheValid() { return mP4.mGpsEpheValid; }
inline uint32_t getGloEpheValid() { return mP4.mGloEpheValid; }
inline uint64_t getBdsEpheValid() { return mP4.mBdsEpheValid; }
inline uint64_t getGalEpheValid() { return mP4.mGalEpheValid; }
inline uint8_t getQzssEpheValid() { return mP4.mQzssEpheValid; }
SystemStatusPQWP4parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
if (mField.size() < eMax) {
return;
}
memset(&mP4, 0, sizeof(mP4));
mP4.mGpsEpheValid = strtol(mField[eGpsEpheValid].c_str(), NULL, 16);
mP4.mGloEpheValid = strtol(mField[eGloEpheValid].c_str(), NULL, 16);
mP4.mBdsEpheValid = strtol(mField[eBdsEpheValid].c_str(), NULL, 16);
mP4.mGalEpheValid = strtol(mField[eGalEpheValid].c_str(), NULL, 16);
mP4.mQzssEpheValid = strtol(mField[eQzssEpheValid].c_str(), NULL, 16);
}
inline SystemStatusPQWP4& get() { return mP4;}
};
/******************************************************************************
SystemStatusPQWP5
******************************************************************************/
class SystemStatusPQWP5
{
public:
uint32_t mGpsUnknownMask;
uint32_t mGloUnknownMask;
uint64_t mBdsUnknownMask;
uint64_t mGalUnknownMask;
uint8_t mQzssUnknownMask;
uint32_t mNavicUnknownMask;
uint32_t mGpsGoodMask;
uint32_t mGloGoodMask;
uint64_t mBdsGoodMask;
uint64_t mGalGoodMask;
uint8_t mQzssGoodMask;
uint32_t mNavicGoodMask;
uint32_t mGpsBadMask;
uint32_t mGloBadMask;
uint64_t mBdsBadMask;
uint64_t mGalBadMask;
uint8_t mQzssBadMask;
uint32_t mNavicBadMask;
};
class SystemStatusPQWP5parser : public SystemStatusNmeaBase
{
private:
// todo: update for navic once available
enum
{
eTalker = 0,
eUtcTime = 1,
eGpsUnknownMask = 2,
eGloUnknownMask = 3,
eBdsUnknownMask = 4,
eGalUnknownMask = 5,
eQzssUnknownMask = 6,
eGpsGoodMask = 7,
eGloGoodMask = 8,
eBdsGoodMask = 9,
eGalGoodMask = 10,
eQzssGoodMask = 11,
eGpsBadMask = 12,
eGloBadMask = 13,
eBdsBadMask = 14,
eGalBadMask = 15,
eQzssBadMask = 16,
eMax
};
SystemStatusPQWP5 mP5;
public:
inline uint32_t getGpsUnknownMask() { return mP5.mGpsUnknownMask; }
inline uint32_t getGloUnknownMask() { return mP5.mGloUnknownMask; }
inline uint64_t getBdsUnknownMask() { return mP5.mBdsUnknownMask; }
inline uint64_t getGalUnknownMask() { return mP5.mGalUnknownMask; }
inline uint8_t getQzssUnknownMask() { return mP5.mQzssUnknownMask; }
inline uint32_t getNavicUnknownMask() { return mP5.mNavicUnknownMask; }
inline uint32_t getGpsGoodMask() { return mP5.mGpsGoodMask; }
inline uint32_t getGloGoodMask() { return mP5.mGloGoodMask; }
inline uint64_t getBdsGoodMask() { return mP5.mBdsGoodMask; }
inline uint64_t getGalGoodMask() { return mP5.mGalGoodMask; }
inline uint8_t getQzssGoodMask() { return mP5.mQzssGoodMask; }
inline uint32_t getNavicGoodMask() { return mP5.mNavicGoodMask; }
inline uint32_t getGpsBadMask() { return mP5.mGpsBadMask; }
inline uint32_t getGloBadMask() { return mP5.mGloBadMask; }
inline uint64_t getBdsBadMask() { return mP5.mBdsBadMask; }
inline uint64_t getGalBadMask() { return mP5.mGalBadMask; }
inline uint8_t getQzssBadMask() { return mP5.mQzssBadMask; }
inline uint32_t getNavicBadMask() { return mP5.mNavicBadMask; }
SystemStatusPQWP5parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
if (mField.size() < eMax) {
return;
}
memset(&mP5, 0, sizeof(mP5));
// todo: update for navic once available
mP5.mGpsUnknownMask = strtol(mField[eGpsUnknownMask].c_str(), NULL, 16);
mP5.mGloUnknownMask = strtol(mField[eGloUnknownMask].c_str(), NULL, 16);
mP5.mBdsUnknownMask = strtol(mField[eBdsUnknownMask].c_str(), NULL, 16);
mP5.mGalUnknownMask = strtol(mField[eGalUnknownMask].c_str(), NULL, 16);
mP5.mQzssUnknownMask = strtol(mField[eQzssUnknownMask].c_str(), NULL, 16);
mP5.mGpsGoodMask = strtol(mField[eGpsGoodMask].c_str(), NULL, 16);
mP5.mGloGoodMask = strtol(mField[eGloGoodMask].c_str(), NULL, 16);
mP5.mBdsGoodMask = strtol(mField[eBdsGoodMask].c_str(), NULL, 16);
mP5.mGalGoodMask = strtol(mField[eGalGoodMask].c_str(), NULL, 16);
mP5.mQzssGoodMask = strtol(mField[eQzssGoodMask].c_str(), NULL, 16);
mP5.mGpsBadMask = strtol(mField[eGpsBadMask].c_str(), NULL, 16);
mP5.mGloBadMask = strtol(mField[eGloBadMask].c_str(), NULL, 16);
mP5.mBdsBadMask = strtol(mField[eBdsBadMask].c_str(), NULL, 16);
mP5.mGalBadMask = strtol(mField[eGalBadMask].c_str(), NULL, 16);
mP5.mQzssBadMask = strtol(mField[eQzssBadMask].c_str(), NULL, 16);
}
inline SystemStatusPQWP5& get() { return mP5;}
};
/******************************************************************************
SystemStatusPQWP6parser
******************************************************************************/
class SystemStatusPQWP6
{
public:
uint32_t mFixInfoMask;
};
class SystemStatusPQWP6parser : public SystemStatusNmeaBase
{
private:
enum
{
eTalker = 0,
eUtcTime = 1,
eFixInfoMask = 2,
eMax
};
SystemStatusPQWP6 mP6;
public:
inline uint32_t getFixInfoMask() { return mP6.mFixInfoMask; }
SystemStatusPQWP6parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
if (mField.size() < eMax) {
return;
}
memset(&mP6, 0, sizeof(mP6));
mP6.mFixInfoMask = strtol(mField[eFixInfoMask].c_str(), NULL, 16);
}
inline SystemStatusPQWP6& get() { return mP6;}
};
/******************************************************************************
SystemStatusPQWP7parser
******************************************************************************/
class SystemStatusPQWP7
{
public:
SystemStatusNav mNav[SV_ALL_NUM];
};
class SystemStatusPQWP7parser : public SystemStatusNmeaBase
{
private:
enum
{
eTalker = 0,
eUtcTime = 1,
eMin = 2 + SV_ALL_NUM_MIN*3,
eMax = 2 + SV_ALL_NUM*3
};
SystemStatusPQWP7 mP7;
public:
SystemStatusPQWP7parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
uint32_t svLimit = SV_ALL_NUM;
if (mField.size() < eMin) {
LOC_LOGE("PQWP7parser - invalid size=%zu", mField.size());
return;
}
if (mField.size() < eMax) {
// Try reducing limit, accounting for possibly missing NAVIC support
svLimit = SV_ALL_NUM_MIN;
}
memset(mP7.mNav, 0, sizeof(mP7.mNav));
for (uint32_t i=0; i<svLimit; i++) {
mP7.mNav[i].mType = GnssEphemerisType(atoi(mField[i*3+2].c_str()));
mP7.mNav[i].mSource = GnssEphemerisSource(atoi(mField[i*3+3].c_str()));
mP7.mNav[i].mAgeSec = atoi(mField[i*3+4].c_str());
}
}
inline SystemStatusPQWP7& get() { return mP7;}
};
/******************************************************************************
SystemStatusPQWS1parser
******************************************************************************/
class SystemStatusPQWS1
{
public:
uint32_t mFixInfoMask;
uint32_t mHepeLimit;
};
class SystemStatusPQWS1parser : public SystemStatusNmeaBase
{
private:
enum
{
eTalker = 0,
eUtcTime = 1,
eFixInfoMask = 2,
eHepeLimit = 3,
eMax
};
SystemStatusPQWS1 mS1;
public:
inline uint16_t getFixInfoMask() { return mS1.mFixInfoMask; }
inline uint32_t getHepeLimit() { return mS1.mHepeLimit; }
SystemStatusPQWS1parser(const char *str_in, uint32_t len_in)
: SystemStatusNmeaBase(str_in, len_in)
{
if (mField.size() < eMax) {
return;
}
memset(&mS1, 0, sizeof(mS1));
mS1.mFixInfoMask = atoi(mField[eFixInfoMask].c_str());
mS1.mHepeLimit = atoi(mField[eHepeLimit].c_str());
}
inline SystemStatusPQWS1& get() { return mS1;}
};
/******************************************************************************
SystemStatusTimeAndClock
******************************************************************************/
SystemStatusTimeAndClock::SystemStatusTimeAndClock(const SystemStatusPQWM1& nmea) :
mGpsWeek(nmea.mGpsWeek),
mGpsTowMs(nmea.mGpsTowMs),
mTimeValid(nmea.mTimeValid),
mTimeSource(nmea.mTimeSource),
mTimeUnc(nmea.mTimeUnc),
mClockFreqBias(nmea.mClockFreqBias),
mClockFreqBiasUnc(nmea.mClockFreqBiasUnc),
mLeapSeconds(nmea.mLeapSeconds),
mLeapSecUnc(nmea.mLeapSecUnc),
mTimeUncNs(nmea.mTimeUncNs)
{
}
bool SystemStatusTimeAndClock::equals(const SystemStatusTimeAndClock& peer)
{
if ((mGpsWeek != peer.mGpsWeek) ||
(mGpsTowMs != peer.mGpsTowMs) ||
(mTimeValid != peer.mTimeValid) ||
(mTimeSource != peer.mTimeSource) ||
(mTimeUnc != peer.mTimeUnc) ||
(mClockFreqBias != peer.mClockFreqBias) ||
(mClockFreqBiasUnc != peer.mClockFreqBiasUnc) ||
(mLeapSeconds != peer.mLeapSeconds) ||
(mLeapSecUnc != peer.mLeapSecUnc) ||
(mTimeUncNs != peer.mTimeUncNs)) {
return false;
}
return true;
}
void SystemStatusTimeAndClock::dump()
{
LOC_LOGV("TimeAndClock: u=%ld:%ld g=%d:%d v=%d ts=%d tu=%d b=%d bu=%d ls=%d lu=%d un=%" PRIu64,
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mGpsWeek,
mGpsTowMs,
mTimeValid,
mTimeSource,
mTimeUnc,
mClockFreqBias,
mClockFreqBiasUnc,
mLeapSeconds,
mLeapSecUnc,
mTimeUncNs);
return;
}
/******************************************************************************
SystemStatusXoState
******************************************************************************/
SystemStatusXoState::SystemStatusXoState(const SystemStatusPQWM1& nmea) :
mXoState(nmea.mXoState)
{
}
bool SystemStatusXoState::equals(const SystemStatusXoState& peer)
{
if (mXoState != peer.mXoState) {
return false;
}
return true;
}
void SystemStatusXoState::dump()
{
LOC_LOGV("XoState: u=%ld:%ld x=%d",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mXoState);
return;
}
/******************************************************************************
SystemStatusRfAndParams
******************************************************************************/
SystemStatusRfAndParams::SystemStatusRfAndParams(const SystemStatusPQWM1& nmea) :
mPgaGain(nmea.mPgaGain),
mGpsBpAmpI(nmea.mGpsBpAmpI),
mGpsBpAmpQ(nmea.mGpsBpAmpQ),
mAdcI(nmea.mAdcI),
mAdcQ(nmea.mAdcQ),
mJammerGps(nmea.mJammerGps),
mJammerGlo(nmea.mJammerGlo),
mJammerBds(nmea.mJammerBds),
mJammerGal(nmea.mJammerGal),
mAgcGps(nmea.mAgcGps),
mAgcGlo(nmea.mAgcGlo),
mAgcBds(nmea.mAgcBds),
mAgcGal(nmea.mAgcGal),
mGloBpAmpI(nmea.mGloBpAmpI),
mGloBpAmpQ(nmea.mGloBpAmpQ),
mBdsBpAmpI(nmea.mBdsBpAmpI),
mBdsBpAmpQ(nmea.mBdsBpAmpQ),
mGalBpAmpI(nmea.mGalBpAmpI),
mGalBpAmpQ(nmea.mGalBpAmpQ)
{
}
bool SystemStatusRfAndParams::equals(const SystemStatusRfAndParams& peer)
{
if ((mPgaGain != peer.mPgaGain) ||
(mGpsBpAmpI != peer.mGpsBpAmpI) ||
(mGpsBpAmpQ != peer.mGpsBpAmpQ) ||
(mAdcI != peer.mAdcI) ||
(mAdcQ != peer.mAdcQ) ||
(mJammerGps != peer.mJammerGps) ||
(mJammerGlo != peer.mJammerGlo) ||
(mJammerBds != peer.mJammerBds) ||
(mJammerGal != peer.mJammerGal) ||
(mAgcGps != peer.mAgcGps) ||
(mAgcGlo != peer.mAgcGlo) ||
(mAgcBds != peer.mAgcBds) ||
(mAgcGal != peer.mAgcGal) ||
(mGloBpAmpI != peer.mGloBpAmpI) ||
(mGloBpAmpQ != peer.mGloBpAmpQ) ||
(mBdsBpAmpI != peer.mBdsBpAmpI) ||
(mBdsBpAmpQ != peer.mBdsBpAmpQ) ||
(mGalBpAmpI != peer.mGalBpAmpI) ||
(mGalBpAmpQ != peer.mGalBpAmpQ)) {
return false;
}
return true;
}
void SystemStatusRfAndParams::dump()
{
LOC_LOGV("RfAndParams: u=%ld:%ld p=%d bi=%d bq=%d ai=%d aq=%d "
"jgp=%d jgl=%d jbd=%d jga=%d "
"agp=%lf agl=%lf abd=%lf aga=%lf",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mPgaGain,
mGpsBpAmpI,
mGpsBpAmpQ,
mAdcI,
mAdcQ,
mJammerGps,
mJammerGlo,
mJammerBds,
mJammerGal,
mAgcGps,
mAgcGlo,
mAgcBds,
mAgcGal);
return;
}
/******************************************************************************
SystemStatusErrRecovery
******************************************************************************/
SystemStatusErrRecovery::SystemStatusErrRecovery(const SystemStatusPQWM1& nmea) :
mRecErrorRecovery(nmea.mRecErrorRecovery)
{
}
bool SystemStatusErrRecovery::equals(const SystemStatusErrRecovery& peer)
{
if (mRecErrorRecovery != peer.mRecErrorRecovery) {
return false;
}
return true;
}
void SystemStatusErrRecovery::dump()
{
LOC_LOGV("ErrRecovery: u=%ld:%ld e=%d",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mRecErrorRecovery);
return;
}
/******************************************************************************
SystemStatusInjectedPosition
******************************************************************************/
SystemStatusInjectedPosition::SystemStatusInjectedPosition(const SystemStatusPQWP1& nmea) :
mEpiValidity(nmea.mEpiValidity),
mEpiLat(nmea.mEpiLat),
mEpiLon(nmea.mEpiLon),
mEpiAlt(nmea.mEpiAlt),
mEpiHepe(nmea.mEpiHepe),
mEpiAltUnc(nmea.mEpiAltUnc),
mEpiSrc(nmea.mEpiSrc)
{
}
bool SystemStatusInjectedPosition::equals(const SystemStatusInjectedPosition& peer)
{
if ((mEpiValidity != peer.mEpiValidity) ||
(mEpiLat != peer.mEpiLat) ||
(mEpiLon != peer.mEpiLon) ||
(mEpiAlt != peer.mEpiAlt) ||
(mEpiHepe != peer.mEpiHepe) ||
(mEpiAltUnc != peer.mEpiAltUnc) ||
(mEpiSrc != peer.mEpiSrc)) {
return false;
}
return true;
}
void SystemStatusInjectedPosition::dump()
{
LOC_LOGV("InjectedPosition: u=%ld:%ld v=%x la=%f lo=%f al=%f he=%f au=%f es=%d",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mEpiValidity,
mEpiLat,
mEpiLon,
mEpiAlt,
mEpiHepe,
mEpiAltUnc,
mEpiSrc);
return;
}
/******************************************************************************
SystemStatusBestPosition
******************************************************************************/
SystemStatusBestPosition::SystemStatusBestPosition(const SystemStatusPQWP2& nmea) :
mValid(true),
mBestLat(nmea.mBestLat),
mBestLon(nmea.mBestLon),
mBestAlt(nmea.mBestAlt),
mBestHepe(nmea.mBestHepe),
mBestAltUnc(nmea.mBestAltUnc)
{
}
bool SystemStatusBestPosition::equals(const SystemStatusBestPosition& peer)
{
if ((mBestLat != peer.mBestLat) ||
(mBestLon != peer.mBestLon) ||
(mBestAlt != peer.mBestAlt) ||
(mBestHepe != peer.mBestHepe) ||
(mBestAltUnc != peer.mBestAltUnc)) {
return false;
}
return true;
}
void SystemStatusBestPosition::dump()
{
LOC_LOGV("BestPosition: u=%ld:%ld la=%f lo=%f al=%f he=%f au=%f",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mBestLat,
mBestLon,
mBestAlt,
mBestHepe,
mBestAltUnc);
return;
}
/******************************************************************************
SystemStatusXtra
******************************************************************************/
SystemStatusXtra::SystemStatusXtra(const SystemStatusPQWP3& nmea) :
mXtraValidMask(nmea.mXtraValidMask),
mGpsXtraAge(nmea.mGpsXtraAge),
mGloXtraAge(nmea.mGloXtraAge),
mBdsXtraAge(nmea.mBdsXtraAge),
mGalXtraAge(nmea.mGalXtraAge),
mQzssXtraAge(nmea.mQzssXtraAge),
mNavicXtraAge(nmea.mNavicXtraAge),
mGpsXtraValid(nmea.mGpsXtraValid),
mGloXtraValid(nmea.mGloXtraValid),
mBdsXtraValid(nmea.mBdsXtraValid),
mGalXtraValid(nmea.mGalXtraValid),
mQzssXtraValid(nmea.mQzssXtraValid),
mNavicXtraValid(nmea.mNavicXtraValid)
{
}
bool SystemStatusXtra::equals(const SystemStatusXtra& peer)
{
if ((mXtraValidMask != peer.mXtraValidMask) ||
(mGpsXtraAge != peer.mGpsXtraAge) ||
(mGloXtraAge != peer.mGloXtraAge) ||
(mBdsXtraAge != peer.mBdsXtraAge) ||
(mGalXtraAge != peer.mGalXtraAge) ||
(mQzssXtraAge != peer.mQzssXtraAge) ||
(mNavicXtraAge != peer.mNavicXtraAge) ||
(mGpsXtraValid != peer.mGpsXtraValid) ||
(mGloXtraValid != peer.mGloXtraValid) ||
(mBdsXtraValid != peer.mBdsXtraValid) ||
(mGalXtraValid != peer.mGalXtraValid) ||
(mQzssXtraValid != peer.mQzssXtraValid) ||
(mNavicXtraValid != peer.mNavicXtraValid)) {
return false;
}
return true;
}
void SystemStatusXtra::dump()
{
LOC_LOGV("SystemStatusXtra: u=%ld:%ld m=%x a=%d:%d:%d:%d:%d v=%x:%x:%" PRIx64 ":%" PRIx64":%x",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mXtraValidMask,
mGpsXtraAge,
mGloXtraAge,
mBdsXtraAge,
mGalXtraAge,
mQzssXtraAge,
mGpsXtraValid,
mGloXtraValid,
mBdsXtraValid,
mGalXtraValid,
mQzssXtraValid);
return;
}
/******************************************************************************
SystemStatusEphemeris
******************************************************************************/
SystemStatusEphemeris::SystemStatusEphemeris(const SystemStatusPQWP4& nmea) :
mGpsEpheValid(nmea.mGpsEpheValid),
mGloEpheValid(nmea.mGloEpheValid),
mBdsEpheValid(nmea.mBdsEpheValid),
mGalEpheValid(nmea.mGalEpheValid),
mQzssEpheValid(nmea.mQzssEpheValid)
{
}
bool SystemStatusEphemeris::equals(const SystemStatusEphemeris& peer)
{
if ((mGpsEpheValid != peer.mGpsEpheValid) ||
(mGloEpheValid != peer.mGloEpheValid) ||
(mBdsEpheValid != peer.mBdsEpheValid) ||
(mGalEpheValid != peer.mGalEpheValid) ||
(mQzssEpheValid != peer.mQzssEpheValid)) {
return false;
}
return true;
}
void SystemStatusEphemeris::dump()
{
LOC_LOGV("Ephemeris: u=%ld:%ld ev=%x:%x:%" PRIx64 ":%" PRIx64 ":%x",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mGpsEpheValid,
mGloEpheValid,
mBdsEpheValid,
mGalEpheValid,
mQzssEpheValid);
return;
}
/******************************************************************************
SystemStatusSvHealth
******************************************************************************/
SystemStatusSvHealth::SystemStatusSvHealth(const SystemStatusPQWP5& nmea) :
mGpsUnknownMask(nmea.mGpsUnknownMask),
mGloUnknownMask(nmea.mGloUnknownMask),
mBdsUnknownMask(nmea.mBdsUnknownMask),
mGalUnknownMask(nmea.mGalUnknownMask),
mQzssUnknownMask(nmea.mQzssUnknownMask),
mNavicUnknownMask(nmea.mNavicUnknownMask),
mGpsGoodMask(nmea.mGpsGoodMask),
mGloGoodMask(nmea.mGloGoodMask),
mBdsGoodMask(nmea.mBdsGoodMask),
mGalGoodMask(nmea.mGalGoodMask),
mQzssGoodMask(nmea.mQzssGoodMask),
mNavicGoodMask(nmea.mNavicGoodMask),
mGpsBadMask(nmea.mGpsBadMask),
mGloBadMask(nmea.mGloBadMask),
mBdsBadMask(nmea.mBdsBadMask),
mGalBadMask(nmea.mGalBadMask),
mQzssBadMask(nmea.mQzssBadMask),
mNavicBadMask(nmea.mNavicBadMask)
{
}
bool SystemStatusSvHealth::equals(const SystemStatusSvHealth& peer)
{
if ((mGpsUnknownMask != peer.mGpsUnknownMask) ||
(mGloUnknownMask != peer.mGloUnknownMask) ||
(mBdsUnknownMask != peer.mBdsUnknownMask) ||
(mGalUnknownMask != peer.mGalUnknownMask) ||
(mQzssUnknownMask != peer.mQzssUnknownMask) ||
(mGpsGoodMask != peer.mGpsGoodMask) ||
(mGloGoodMask != peer.mGloGoodMask) ||
(mBdsGoodMask != peer.mBdsGoodMask) ||
(mGalGoodMask != peer.mGalGoodMask) ||
(mQzssGoodMask != peer.mQzssGoodMask) ||
(mGpsBadMask != peer.mGpsBadMask) ||
(mGloBadMask != peer.mGloBadMask) ||
(mBdsBadMask != peer.mBdsBadMask) ||
(mGalBadMask != peer.mGalBadMask) ||
(mQzssBadMask != peer.mQzssBadMask)) {
return false;
}
return true;
}
void SystemStatusSvHealth::dump()
{
LOC_LOGV("SvHealth: u=%ld:%ld \
u=%x:%x:%" PRIx64 ":%" PRIx64 ":%x \
g=%x:%x:%" PRIx64 ":%" PRIx64 ":%x \
b=%x:%x:%" PRIx64 ":%" PRIx64 ":%x",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mGpsUnknownMask,
mGloUnknownMask,
mBdsUnknownMask,
mGalUnknownMask,
mQzssUnknownMask,
mGpsGoodMask,
mGloGoodMask,
mBdsGoodMask,
mGalGoodMask,
mQzssGoodMask,
mGpsBadMask,
mGloBadMask,
mBdsBadMask,
mGalBadMask,
mQzssBadMask);
return;
}
/******************************************************************************
SystemStatusPdr
******************************************************************************/
SystemStatusPdr::SystemStatusPdr(const SystemStatusPQWP6& nmea) :
mFixInfoMask(nmea.mFixInfoMask)
{
}
bool SystemStatusPdr::equals(const SystemStatusPdr& peer)
{
if (mFixInfoMask != peer.mFixInfoMask) {
return false;
}
return true;
}
void SystemStatusPdr::dump()
{
LOC_LOGV("Pdr: u=%ld:%ld m=%x",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mFixInfoMask);
return;
}
/******************************************************************************
SystemStatusNavData
******************************************************************************/
SystemStatusNavData::SystemStatusNavData(const SystemStatusPQWP7& nmea)
{
for (uint32_t i=0; i<SV_ALL_NUM; i++) {
mNav[i] = nmea.mNav[i];
}
}
bool SystemStatusNavData::equals(const SystemStatusNavData& peer)
{
for (uint32_t i=0; i<SV_ALL_NUM; i++) {
if ((mNav[i].mType != peer.mNav[i].mType) ||
(mNav[i].mSource != peer.mNav[i].mSource) ||
(mNav[i].mAgeSec != peer.mNav[i].mAgeSec)) {
return false;
}
}
return true;
}
void SystemStatusNavData::dump()
{
LOC_LOGV("NavData: u=%ld:%ld",
mUtcTime.tv_sec, mUtcTime.tv_nsec);
for (uint32_t i=0; i<SV_ALL_NUM; i++) {
LOC_LOGV("i=%d type=%d src=%d age=%d",
i, mNav[i].mType, mNav[i].mSource, mNav[i].mAgeSec);
}
return;
}
/******************************************************************************
SystemStatusPositionFailure
******************************************************************************/
SystemStatusPositionFailure::SystemStatusPositionFailure(const SystemStatusPQWS1& nmea) :
mFixInfoMask(nmea.mFixInfoMask),
mHepeLimit(nmea.mHepeLimit)
{
}
bool SystemStatusPositionFailure::equals(const SystemStatusPositionFailure& peer)
{
if ((mFixInfoMask != peer.mFixInfoMask) ||
(mHepeLimit != peer.mHepeLimit)) {
return false;
}
return true;
}
void SystemStatusPositionFailure::dump()
{
LOC_LOGV("PositionFailure: u=%ld:%ld m=%d h=%d",
mUtcTime.tv_sec, mUtcTime.tv_nsec,
mFixInfoMask,
mHepeLimit);
return;
}
/******************************************************************************
SystemStatusLocation
******************************************************************************/
bool SystemStatusLocation::equals(const SystemStatusLocation& peer)
{
if ((mLocation.gpsLocation.latitude != peer.mLocation.gpsLocation.latitude) ||
(mLocation.gpsLocation.longitude != peer.mLocation.gpsLocation.longitude) ||
(mLocation.gpsLocation.altitude != peer.mLocation.gpsLocation.altitude)) {
return false;
}
return true;
}
void SystemStatusLocation::dump()
{
LOC_LOGV("Location: lat=%f lon=%f alt=%f spd=%f",
mLocation.gpsLocation.latitude,
mLocation.gpsLocation.longitude,
mLocation.gpsLocation.altitude,
mLocation.gpsLocation.speed);
return;
}
/******************************************************************************
SystemStatus
******************************************************************************/
pthread_mutex_t SystemStatus::mMutexSystemStatus = PTHREAD_MUTEX_INITIALIZER;
SystemStatus* SystemStatus::mInstance = NULL;
SystemStatus* SystemStatus::getInstance(const MsgTask* msgTask)
{
pthread_mutex_lock(&mMutexSystemStatus);
if (!mInstance) {
// Instantiating for the first time. msgTask should not be NULL
if (msgTask == NULL) {
LOC_LOGE("SystemStatus: msgTask is NULL!!");
pthread_mutex_unlock(&mMutexSystemStatus);
return NULL;
}
mInstance = new (nothrow) SystemStatus(msgTask);
LOC_LOGD("SystemStatus::getInstance:%p. Msgtask:%p", mInstance, msgTask);
}
pthread_mutex_unlock(&mMutexSystemStatus);
return mInstance;
}
void SystemStatus::destroyInstance()
{
delete mInstance;
mInstance = NULL;
}
IOsObserver* SystemStatus::getOsObserver()
{
return &mSysStatusObsvr;
}
SystemStatus::SystemStatus(const MsgTask* msgTask) :
mSysStatusObsvr(this, msgTask)
{
int result = 0;
ENTRY_LOG ();
mCache.mLocation.clear();
mCache.mTimeAndClock.clear();
mCache.mXoState.clear();
mCache.mRfAndParams.clear();
mCache.mErrRecovery.clear();
mCache.mInjectedPosition.clear();
mCache.mBestPosition.clear();
mCache.mXtra.clear();
mCache.mEphemeris.clear();
mCache.mSvHealth.clear();
mCache.mPdr.clear();
mCache.mNavData.clear();
mCache.mPositionFailure.clear();
mCache.mAirplaneMode.clear();
mCache.mENH.clear();
mCache.mGPSState.clear();
mCache.mNLPStatus.clear();
mCache.mWifiHardwareState.clear();
mCache.mNetworkInfo.clear();
mCache.mRilServiceInfo.clear();
mCache.mRilCellInfo.clear();
mCache.mServiceStatus.clear();
mCache.mModel.clear();
mCache.mManufacturer.clear();
mCache.mAssistedGps.clear();
mCache.mScreenState.clear();
mCache.mPowerConnectState.clear();
mCache.mTimeZoneChange.clear();
mCache.mTimeChange.clear();
mCache.mWifiSupplicantStatus.clear();
mCache.mShutdownState.clear();
mCache.mTac.clear();
mCache.mMccMnc.clear();
mCache.mBtDeviceScanDetail.clear();
mCache.mBtLeDeviceScanDetail.clear();
EXIT_LOG_WITH_ERROR ("%d",result);
}
/******************************************************************************
SystemStatus - storing dataitems
******************************************************************************/
template <typename TYPE_REPORT, typename TYPE_ITEM>
bool SystemStatus::setIteminReport(TYPE_REPORT& report, TYPE_ITEM&& s)
{
if (s.ignore()) {
return false;
}
if (!report.empty() && report.back().equals(static_cast<TYPE_ITEM&>(s.collate(report.back())))) {
// there is no change - just update reported timestamp
report.back().mUtcReported = s.mUtcReported;
return false;
}
// first event or updated
report.push_back(s);
if (report.size() > s.maxItem) {
report.erase(report.begin());
}
return true;
}
template <typename TYPE_REPORT, typename TYPE_ITEM>
void SystemStatus::setDefaultIteminReport(TYPE_REPORT& report, const TYPE_ITEM& s)
{
report.push_back(s);
if (report.size() > s.maxItem) {
report.erase(report.begin());
}
}
template <typename TYPE_REPORT, typename TYPE_ITEM>
void SystemStatus::getIteminReport(TYPE_REPORT& reportout, const TYPE_ITEM& c) const
{
reportout.clear();
if (c.size() >= 1) {
reportout.push_back(c.back());
reportout.back().dump();
}
}
/******************************************************************************
@brief API to set report data into internal buffer
@param[In] data pointer to the NMEA string
@param[In] len length of the NMEA string
@return true when the NMEA is consumed by the method.
******************************************************************************/
bool SystemStatus::setNmeaString(const char *data, uint32_t len)
{
if (!loc_nmea_is_debug(data, len)) {
return false;
}
char buf[SystemStatusNmeaBase::NMEA_MAXSIZE + 1] = { 0 };
strlcpy(buf, data, sizeof(buf));
pthread_mutex_lock(&mMutexSystemStatus);
// parse the received nmea strings here
if (0 == strncmp(data, "$PQWM1", SystemStatusNmeaBase::NMEA_MINSIZE)) {
SystemStatusPQWM1 s = SystemStatusPQWM1parser(buf, len).get();
setIteminReport(mCache.mTimeAndClock, SystemStatusTimeAndClock(s));
setIteminReport(mCache.mXoState, SystemStatusXoState(s));
setIteminReport(mCache.mRfAndParams, SystemStatusRfAndParams(s));
setIteminReport(mCache.mErrRecovery, SystemStatusErrRecovery(s));
}
else if (0 == strncmp(data, "$PQWP1", SystemStatusNmeaBase::NMEA_MINSIZE)) {
setIteminReport(mCache.mInjectedPosition,
SystemStatusInjectedPosition(SystemStatusPQWP1parser(buf, len).get()));
}
else if (0 == strncmp(data, "$PQWP2", SystemStatusNmeaBase::NMEA_MINSIZE)) {
setIteminReport(mCache.mBestPosition,
SystemStatusBestPosition(SystemStatusPQWP2parser(buf, len).get()));
}
else if (0 == strncmp(data, "$PQWP3", SystemStatusNmeaBase::NMEA_MINSIZE)) {
setIteminReport(mCache.mXtra,
SystemStatusXtra(SystemStatusPQWP3parser(buf, len).get()));
}
else if (0 == strncmp(data, "$PQWP4", SystemStatusNmeaBase::NMEA_MINSIZE)) {
setIteminReport(mCache.mEphemeris,
SystemStatusEphemeris(SystemStatusPQWP4parser(buf, len).get()));
}
else if (0 == strncmp(data, "$PQWP5", SystemStatusNmeaBase::NMEA_MINSIZE)) {
setIteminReport(mCache.mSvHealth,
SystemStatusSvHealth(SystemStatusPQWP5parser(buf, len).get()));
}
else if (0 == strncmp(data, "$PQWP6", SystemStatusNmeaBase::NMEA_MINSIZE)) {
setIteminReport(mCache.mPdr,
SystemStatusPdr(SystemStatusPQWP6parser(buf, len).get()));
}
else if (0 == strncmp(data, "$PQWP7", SystemStatusNmeaBase::NMEA_MINSIZE)) {
setIteminReport(mCache.mNavData,
SystemStatusNavData(SystemStatusPQWP7parser(buf, len).get()));
}
else if (0 == strncmp(data, "$PQWS1", SystemStatusNmeaBase::NMEA_MINSIZE)) {
setIteminReport(mCache.mPositionFailure,
SystemStatusPositionFailure(SystemStatusPQWS1parser(buf, len).get()));
}
else {
// do nothing
}
pthread_mutex_unlock(&mMutexSystemStatus);
return true;
}
/******************************************************************************
@brief API to set report position data into internal buffer
@param[In] UlpLocation
@return true when successfully done
******************************************************************************/
bool SystemStatus::eventPosition(const UlpLocation& location,
const GpsLocationExtended& locationEx)
{
bool ret = false;
pthread_mutex_lock(&mMutexSystemStatus);
ret = setIteminReport(mCache.mLocation, SystemStatusLocation(location, locationEx));
LOC_LOGV("eventPosition - lat=%f lon=%f alt=%f speed=%f",
location.gpsLocation.latitude,
location.gpsLocation.longitude,
location.gpsLocation.altitude,
location.gpsLocation.speed);
pthread_mutex_unlock(&mMutexSystemStatus);
return ret;
}
/******************************************************************************
@brief API to set report DataItem event into internal buffer
@param[In] DataItem
@return true when info is updatated
******************************************************************************/
bool SystemStatus::eventDataItemNotify(IDataItemCore* dataitem)
{
bool ret = false;
pthread_mutex_lock(&mMutexSystemStatus);
switch(dataitem->getId())
{
case AIRPLANEMODE_DATA_ITEM_ID:
ret = setIteminReport(mCache.mAirplaneMode,
SystemStatusAirplaneMode(*(static_cast<AirplaneModeDataItemBase*>(dataitem))));
break;
case ENH_DATA_ITEM_ID:
ret = setIteminReport(mCache.mENH,
SystemStatusENH(*(static_cast<ENHDataItemBase*>(dataitem))));
break;
case GPSSTATE_DATA_ITEM_ID:
ret = setIteminReport(mCache.mGPSState,
SystemStatusGpsState(*(static_cast<GPSStateDataItemBase*>(dataitem))));
break;
case NLPSTATUS_DATA_ITEM_ID:
ret = setIteminReport(mCache.mNLPStatus,
SystemStatusNLPStatus(*(static_cast<NLPStatusDataItemBase*>(dataitem))));
break;
case WIFIHARDWARESTATE_DATA_ITEM_ID:
ret = setIteminReport(mCache.mWifiHardwareState,
SystemStatusWifiHardwareState(*(static_cast<WifiHardwareStateDataItemBase*>(dataitem))));
break;
case NETWORKINFO_DATA_ITEM_ID:
ret = setIteminReport(mCache.mNetworkInfo,
SystemStatusNetworkInfo(*(static_cast<NetworkInfoDataItemBase*>(dataitem))));
break;
case RILSERVICEINFO_DATA_ITEM_ID:
ret = setIteminReport(mCache.mRilServiceInfo,
SystemStatusServiceInfo(*(static_cast<RilServiceInfoDataItemBase*>(dataitem))));
break;
case RILCELLINFO_DATA_ITEM_ID:
ret = setIteminReport(mCache.mRilCellInfo,
SystemStatusRilCellInfo(*(static_cast<RilCellInfoDataItemBase*>(dataitem))));
break;
case SERVICESTATUS_DATA_ITEM_ID:
ret = setIteminReport(mCache.mServiceStatus,
SystemStatusServiceStatus(*(static_cast<ServiceStatusDataItemBase*>(dataitem))));
break;
case MODEL_DATA_ITEM_ID:
ret = setIteminReport(mCache.mModel,
SystemStatusModel(*(static_cast<ModelDataItemBase*>(dataitem))));
break;
case MANUFACTURER_DATA_ITEM_ID:
ret = setIteminReport(mCache.mManufacturer,
SystemStatusManufacturer(*(static_cast<ManufacturerDataItemBase*>(dataitem))));
break;
case ASSISTED_GPS_DATA_ITEM_ID:
ret = setIteminReport(mCache.mAssistedGps,
SystemStatusAssistedGps(*(static_cast<AssistedGpsDataItemBase*>(dataitem))));
break;
case SCREEN_STATE_DATA_ITEM_ID:
ret = setIteminReport(mCache.mScreenState,
SystemStatusScreenState(*(static_cast<ScreenStateDataItemBase*>(dataitem))));
break;
case POWER_CONNECTED_STATE_DATA_ITEM_ID:
ret = setIteminReport(mCache.mPowerConnectState,
SystemStatusPowerConnectState(*(static_cast<PowerConnectStateDataItemBase*>(dataitem))));
break;
case TIMEZONE_CHANGE_DATA_ITEM_ID:
ret = setIteminReport(mCache.mTimeZoneChange,
SystemStatusTimeZoneChange(*(static_cast<TimeZoneChangeDataItemBase*>(dataitem))));
break;
case TIME_CHANGE_DATA_ITEM_ID:
ret = setIteminReport(mCache.mTimeChange,
SystemStatusTimeChange(*(static_cast<TimeChangeDataItemBase*>(dataitem))));
break;
case WIFI_SUPPLICANT_STATUS_DATA_ITEM_ID:
ret = setIteminReport(mCache.mWifiSupplicantStatus,
SystemStatusWifiSupplicantStatus(*(static_cast<WifiSupplicantStatusDataItemBase*>(dataitem))));
break;
case SHUTDOWN_STATE_DATA_ITEM_ID:
ret = setIteminReport(mCache.mShutdownState,
SystemStatusShutdownState(*(static_cast<ShutdownStateDataItemBase*>(dataitem))));
break;
case TAC_DATA_ITEM_ID:
ret = setIteminReport(mCache.mTac,
SystemStatusTac(*(static_cast<TacDataItemBase*>(dataitem))));
break;
case MCCMNC_DATA_ITEM_ID:
ret = setIteminReport(mCache.mMccMnc,
SystemStatusMccMnc(*(static_cast<MccmncDataItemBase*>(dataitem))));
break;
case BTLE_SCAN_DATA_ITEM_ID:
ret = setIteminReport(mCache.mBtDeviceScanDetail,
SystemStatusBtDeviceScanDetail(*(static_cast<BtDeviceScanDetailsDataItemBase*>(dataitem))));
break;
case BT_SCAN_DATA_ITEM_ID:
ret = setIteminReport(mCache.mBtLeDeviceScanDetail,
SystemStatusBtleDeviceScanDetail(*(static_cast<BtLeDeviceScanDetailsDataItemBase*>(dataitem))));
break;
default:
break;
}
pthread_mutex_unlock(&mMutexSystemStatus);
return ret;
}
/******************************************************************************
@brief API to get report data into a given buffer
@param[In] reference to report buffer
@param[In] bool flag to identify latest only or entire buffer
@return true when successfully done
******************************************************************************/
bool SystemStatus::getReport(SystemStatusReports& report, bool isLatestOnly) const
{
pthread_mutex_lock(&mMutexSystemStatus);
if (isLatestOnly) {
// push back only the latest report and return it
getIteminReport(report.mLocation, mCache.mLocation);
getIteminReport(report.mTimeAndClock, mCache.mTimeAndClock);
getIteminReport(report.mXoState, mCache.mXoState);
getIteminReport(report.mRfAndParams, mCache.mRfAndParams);
getIteminReport(report.mErrRecovery, mCache.mErrRecovery);
getIteminReport(report.mInjectedPosition, mCache.mInjectedPosition);
getIteminReport(report.mBestPosition, mCache.mBestPosition);
getIteminReport(report.mXtra, mCache.mXtra);
getIteminReport(report.mEphemeris, mCache.mEphemeris);
getIteminReport(report.mSvHealth, mCache.mSvHealth);
getIteminReport(report.mPdr, mCache.mPdr);
getIteminReport(report.mNavData, mCache.mNavData);
getIteminReport(report.mPositionFailure, mCache.mPositionFailure);
getIteminReport(report.mAirplaneMode, mCache.mAirplaneMode);
getIteminReport(report.mENH, mCache.mENH);
getIteminReport(report.mGPSState, mCache.mGPSState);
getIteminReport(report.mNLPStatus, mCache.mNLPStatus);
getIteminReport(report.mWifiHardwareState, mCache.mWifiHardwareState);
getIteminReport(report.mNetworkInfo, mCache.mNetworkInfo);
getIteminReport(report.mRilServiceInfo, mCache.mRilServiceInfo);
getIteminReport(report.mRilCellInfo, mCache.mRilCellInfo);
getIteminReport(report.mServiceStatus, mCache.mServiceStatus);
getIteminReport(report.mModel, mCache.mModel);
getIteminReport(report.mManufacturer, mCache.mManufacturer);
getIteminReport(report.mAssistedGps, mCache.mAssistedGps);
getIteminReport(report.mScreenState, mCache.mScreenState);
getIteminReport(report.mPowerConnectState, mCache.mPowerConnectState);
getIteminReport(report.mTimeZoneChange, mCache.mTimeZoneChange);
getIteminReport(report.mTimeChange, mCache.mTimeChange);
getIteminReport(report.mWifiSupplicantStatus, mCache.mWifiSupplicantStatus);
getIteminReport(report.mShutdownState, mCache.mShutdownState);
getIteminReport(report.mTac, mCache.mTac);
getIteminReport(report.mMccMnc, mCache.mMccMnc);
getIteminReport(report.mBtDeviceScanDetail, mCache.mBtDeviceScanDetail);
getIteminReport(report.mBtLeDeviceScanDetail, mCache.mBtLeDeviceScanDetail);
}
else {
// copy entire reports and return them
report.mLocation.clear();
report.mTimeAndClock.clear();
report.mXoState.clear();
report.mRfAndParams.clear();
report.mErrRecovery.clear();
report.mInjectedPosition.clear();
report.mBestPosition.clear();
report.mXtra.clear();
report.mEphemeris.clear();
report.mSvHealth.clear();
report.mPdr.clear();
report.mNavData.clear();
report.mPositionFailure.clear();
report.mAirplaneMode.clear();
report.mENH.clear();
report.mGPSState.clear();
report.mNLPStatus.clear();
report.mWifiHardwareState.clear();
report.mNetworkInfo.clear();
report.mRilServiceInfo.clear();
report.mRilCellInfo.clear();
report.mServiceStatus.clear();
report.mModel.clear();
report.mManufacturer.clear();
report.mAssistedGps.clear();
report.mScreenState.clear();
report.mPowerConnectState.clear();
report.mTimeZoneChange.clear();
report.mTimeChange.clear();
report.mWifiSupplicantStatus.clear();
report.mShutdownState.clear();
report.mTac.clear();
report.mMccMnc.clear();
report.mBtDeviceScanDetail.clear();
report.mBtLeDeviceScanDetail.clear();
report = mCache;
}
pthread_mutex_unlock(&mMutexSystemStatus);
return true;
}
/******************************************************************************
@brief API to set default report data
@param[In] none
@return true when successfully done
******************************************************************************/
bool SystemStatus::setDefaultGnssEngineStates(void)
{
pthread_mutex_lock(&mMutexSystemStatus);
setDefaultIteminReport(mCache.mLocation, SystemStatusLocation());
setDefaultIteminReport(mCache.mTimeAndClock, SystemStatusTimeAndClock());
setDefaultIteminReport(mCache.mXoState, SystemStatusXoState());
setDefaultIteminReport(mCache.mRfAndParams, SystemStatusRfAndParams());
setDefaultIteminReport(mCache.mErrRecovery, SystemStatusErrRecovery());
setDefaultIteminReport(mCache.mInjectedPosition, SystemStatusInjectedPosition());
setDefaultIteminReport(mCache.mBestPosition, SystemStatusBestPosition());
setDefaultIteminReport(mCache.mXtra, SystemStatusXtra());
setDefaultIteminReport(mCache.mEphemeris, SystemStatusEphemeris());
setDefaultIteminReport(mCache.mSvHealth, SystemStatusSvHealth());
setDefaultIteminReport(mCache.mPdr, SystemStatusPdr());
setDefaultIteminReport(mCache.mNavData, SystemStatusNavData());
setDefaultIteminReport(mCache.mPositionFailure, SystemStatusPositionFailure());
pthread_mutex_unlock(&mMutexSystemStatus);
return true;
}
/******************************************************************************
@brief API to handle connection status update event from GnssRil
@param[In] Connection status
@return true when successfully done
******************************************************************************/
bool SystemStatus::eventConnectionStatus(bool connected, int8_t type,
bool roaming, NetworkHandle networkHandle)
{
// send networkinof dataitem to systemstatus observer clients
SystemStatusNetworkInfo s(type, "", "", connected, roaming,
(uint64_t) networkHandle);
mSysStatusObsvr.notify({&s});
return true;
}
/******************************************************************************
@brief API to update power connect state
@param[In] power connect status
@return true when successfully done
******************************************************************************/
bool SystemStatus::updatePowerConnectState(bool charging)
{
SystemStatusPowerConnectState s(charging);
mSysStatusObsvr.notify({&s});
return true;
}
} // namespace loc_core
|
SFX_Noise_Instrument10_2_Ch8:
noise_note 0, 8, 2, 37
sound_ret
|
; A313533: Coordination sequence Gal.6.131.5 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; 1,5,10,14,19,23,27,31,35,40,44,49,54,59,64,68,73,77,81,85,89,94,98,103,108,113,118,122,127,131,135,139,143,148,152,157,162,167,172,176,181,185,189,193,197,202,206,211,216,221
mov $4,$0
add $4,1
mov $6,$0
lpb $4
mov $0,$6
sub $4,1
sub $0,$4
mov $5,8
lpb $0
sub $0,1
add $2,$5
add $2,1
div $2,3
gcd $2,2
add $2,2
add $5,$0
lpe
mov $3,$2
add $3,1
add $1,$3
lpe
mov $0,$1
|
###############################################################################
# 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 6, 0x90
.globl n0_Encrypt_RIJ128_AES_NI
.type n0_Encrypt_RIJ128_AES_NI, @function
n0_Encrypt_RIJ128_AES_NI:
movdqu (%rdi), %xmm0
pxor (%rcx), %xmm0
lea (,%rdx,4), %rax
lea (-144)(%rcx,%rax,4), %rcx
cmp $(12), %rdx
jl .Lkey_128gas_1
jz .Lkey_192gas_1
.Lkey_256gas_1:
aesenc (-64)(%rcx), %xmm0
aesenc (-48)(%rcx), %xmm0
.Lkey_192gas_1:
aesenc (-32)(%rcx), %xmm0
aesenc (-16)(%rcx), %xmm0
.Lkey_128gas_1:
aesenc (%rcx), %xmm0
aesenc (16)(%rcx), %xmm0
aesenc (32)(%rcx), %xmm0
aesenc (48)(%rcx), %xmm0
aesenc (64)(%rcx), %xmm0
aesenc (80)(%rcx), %xmm0
aesenc (96)(%rcx), %xmm0
aesenc (112)(%rcx), %xmm0
aesenc (128)(%rcx), %xmm0
aesenclast (144)(%rcx), %xmm0
movdqu %xmm0, (%rsi)
ret
.Lfe1:
.size n0_Encrypt_RIJ128_AES_NI, .Lfe1-(n0_Encrypt_RIJ128_AES_NI)
|
; A309397: a(n) = gcd(n^2, A001008(n-1)) for n > 1.
; Submitted by Christian Krause
; 1,3,1,25,1,49,1,1,1,121,1,169,1,1,1,289,1,361,1,1,1,529,1,5,1,1,1,841,1,961,1,1,1,1,1,1369,1,1,1,1681,1,1849,1,1,1,2209,1,7,1,1,1,2809,1,1,1,1,1,3481,1,3721,1,1,1,1,1,4489,1,1,1,5041,1,5329
mov $2,$0
seq $0,175441 ; Denominators of the harmonic means H(n) of the first n positive integers.
mov $1,$0
add $2,2
pow $2,2
gcd $1,$2
mov $0,$1
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Geoworks 1994 -- All Rights Reserved
PROJECT: PC/GEOS
MODULE: Power Drivers
FILE: apmUtil.asm
AUTHOR: Todd Stumpf, Aug 1, 1994
ROUTINES:
Name Description
---- -----------
APMGetStatusACLine Is AC Adapter Connected?
APMGetStatusBattery What is Battery Status?
REVISION HISTORY:
Name Date Description
---- ---- -----------
TS 8/ 1/94 Initial revision
DESCRIPTION:
This file contains the default routines for determining if
the AC adapter is connected to the system, and what the current
battery level is.
$Id: apmUtil.asm,v 1.1 97/04/18 11:48:28 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
Resident segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
APMGetStatusACLine
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Determine if we are hooked up to AC power source
CALLED BY: APMGetStatus
PASS: ds -> dgroup
RETURN: ax <- PowerStatus
bx <- PowerStatus supprted
DESTROYED: nothing
SIDE EFFECTS:
none
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
TS 5/27/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
if USE_DEFAULT_AC_ADAPTER_CODE
APMGetStatusACLine proc far
.enter
mov bx, APMDID_ALL_BIOS_DEVICES
call SysLockBIOS
CallAPM APMSC_GET_POWER_STATUS ; bh <- ACLineStatus
call SysUnlockBIOS
clr ax ; assume it's off or
cmp bh, ACLS_UNKNOWN ; is AC detect supported?
je unsupported
cmp bh, ACLS_ON_LINE ; is AC connected?
jne supported
mov ax, mask PS_AC_ADAPTER_CONNECTED
supported:
mov bx, mask PS_AC_ADAPTER_CONNECTED
clc
done:
.leave
ret
unsupported:
czr ax, bx ; nothing supported
stc
jmp short done
APMGetStatusACLine endp
endif
Resident ends
Movable segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
APMGetStatusBattery
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Determine % of charge remaining in battery
CALLED BY: APMGetStatus
PASS: ds -> dgroup
RETURN: dxax <- % remaining (0-1000)
DESTROYED: nothing
SIDE EFFECTS: none
PSEUDO CODE/STRATEGY:
none
REVISION HISTORY:
Name Date Description
---- ---- -----------
TS 5/27/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
if USE_DEFAULT_BATTERY_LEVEL_CODE
APMGetStatusBattery proc far
uses bx, cx
.enter
mov bx, APMDID_ALL_BIOS_DEVICES
call SysLockBIOS
CallAPM APMSC_GET_POWER_STATUS
call SysUnlockBIOS
EC< ERROR_C -1 ; ah <- error # >
;
; Return the percentage of power remaining in the
; battery as a XXX.X%.
cmp cl, -1 ; returns -1 if unsuported
je done ; => carry clear
clr dx ; dxax <- ax
mov ch, dl ; cx <- 0-100%
shl cx, 1 ; cx <- cx * 2
mov ax, cx ; ax <- cx * 2
shl cx, 1 ; cx <- cx * 4
shl cx, 1 ; cx <- cx * 8
add ax, cx ; ax <- cx * 10
clr dx ; dxax <- 0-1000
stc
done:
cmc
.leave
ret
APMGetStatusBattery endp
endif
Movable ends
Resident segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
APMDisableGPM
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Disable DOS-level (and BIOS-level) global power management.
CALLED BY: APMInit, APMUnsuspend, APMRecoverFromSuspend
PASS: ds = dgroup
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
TS 8/ 2/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
if HAS_DOS_LEVEL_APM
APMDisableGPM proc near
.enter
ifidn HARDWARE_TYPE, <GPC1>
;
; The only DOS-level GPM feature is auto screen blanking by BIOS OEM
; extension, but the function is not tied to the APM BIOS, so we have
; to call the BIOS extension instead of using APM calls to disable it.
;
pusha
mov ax,(BIOS_OEM_EXT_MAJOR_COMMAND shl 8) or BOEF_SET_VIDEO_TIMEOUT
mov bl, 0xff ; OFF
int BIOS_OEM_EXT_INTERRUPT ; CF set if func not supported, which
; can happen on older BIOS versions.
; Just ignore it.
popa
endif ; HARDWARE_TYPE, <GPC1>
.leave
ret
APMDisableGPM endp
endif
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
APMEnableGPM
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Enable DOS-level (and BIOS-level) global power management.
CALLED BY: APMExit, APMSuspend
PASS: ds = dgroup
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
TS 8/ 2/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
if HAS_DOS_LEVEL_APM
APMEnableGPM proc near
.enter
ifidn HARDWARE_TYPE, <GPC1>
;
; The only DOS-level GPM feature is auto screen blanking by BIOS OEM
; extension, but the function is not tied to the APM BIOS, so we have
; to call the BIOS extension instead of using APM calls to enable it.
;
pusha
mov ax,(BIOS_OEM_EXT_MAJOR_COMMAND shl 8) or BOEF_SET_VIDEO_TIMEOUT
.assert DEFAULT_GPM_TIMEOUT * 60 / 16 gt 1 ; 0 and 1 are invalid
.assert DEFAULT_GPM_TIMEOUT * 60 / 16 lt 0xff ; 0xff means OFF
mov bl, DEFAULT_GPM_TIMEOUT * 60 / 16 ; # of 16-sec intervals
int BIOS_OEM_EXT_INTERRUPT ; CF set if func not supported, which
; can happen on older BIOS versions.
; Just ignore it.
popa
endif ; HARDWARE_TYPE, <GPC1>
.leave
ret
APMEnableGPM endp
endif
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
APMLockBIOSNB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Checks the BIOS lock, only grabbing it if available
CALLED BY: GLOBAL
PASS: ds -> dgroup
RETURN: c flag set if bios lock owned
call CheckBiosLock
jc someoneAlreadyHasBiosLock
Interrupts enabled
DESTROYED: nada
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
atw 7/22/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
APMLockBIOSNB proc near
uses ax, si, ds
.enter
EC< mov ax, ds >
EC< cmp ax, segment dgroup >
EC< ERROR_NE -1 >
pushf
INT_OFF
lds si, ds:[biosLockAddress] ; ds:bx <- biosLock
cmp ds:[si].TL_sem.Sem_value, 1
clc ; assume error
jne done ; => return Error
grabIt::
;
; The following butchered code was taken from ThreadLock
; (a macro that exists in the kernel). As this code
; will never be called _unless_ we can get the semaphore,
; it is much simpler than that particular macro.
; It's also probably buggier. :(
lock dec ds:[si].TL_sem.Sem_value
EC< ERROR_S -1 ; bad code, eh todd? >
mov ax, ss:[TPD_threadHandle] ; hey, we're a driver!
; leave us alone...
mov ds:[si].TL_owner, ax
inc ds:[si].TL_nesting
stc ; return success
done:
lahf ; ah <- normal flags
call SafePopf ; restore Ints
sahf ; restore normal flags
cmc
.leave
ret
APMLockBIOSNB endp
SafePopf proc far
iret
SafePopf endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
APMUnlockBIOS
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Because we Lock BIOS in an odd way, we unlock it oddly
CALLED BY:
PASS:
RETURN:
DESTROYED: nothing
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
TS 8/ 3/94 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
APMUnlockBIOS proc near
uses ax, bx, si, ds
.enter
EC< mov ax, ds >
EC< cmp ax, segment dgroup >
EC< ERROR_NE -1 >
lds si, ds:[biosLockAddress] ; ds:bx <- biosLock
EC< mov ax, ss:[TPD_threadHandle] >
EC< cmp ax, ds:[si].TL_owner >
EC< ERROR_NE -1 >
pushf
INT_OFF
dec ds:[si].TL_nesting
jg done
mov ds:[si].TL_owner, -1
lock inc ds:[si].TL_sem.Sem_value
jg done
wakeAThread::
mov ax, ds
lea bx, ds:[si].TL_sem.Sem_queue
call ThreadWakeUpQueue
done:
call SafePopf
.leave
ret
APMUnlockBIOS endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
APMEnforceWorldView
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Make all others believe as we do.
CALLED BY: APMInit, APMUnsuspend, APMRecoverFromSuspend
PASS: ds -> dgroup
RETURN: nothing
DESTROYED: nothing
SIDE EFFECTS:
Sets power states on all devices to last-known values
PSEUDO CODE/STRATEGY:
Go through all of our devices and ensure they are
in the state we have recorded in our dgroup
REVISION HISTORY:
Name Date Description
---- ---- -----------
TS 6/27/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
APMEnforceWorldViewFar proc far
call APMEnforceWorldView
ret
APMEnforceWorldViewFar endp
APMEnforceWorldView proc near
uses ax, bx, cx, dx, si
.enter
if HAS_PARALLEL_PORTS
ifidn HARDWARE_TYPE, <GPC1>
; GPC1 APM BIOS doesn't support parallel port, so don't call it.
else
;
; For each parallel port we have, set the power
; state to the correct value
mov si, offset parallelPowerStatus ; si <- SuspendRestriction
mov bx, APMDID_PARALLEL_PORT_LPT1 ; bx <- LPT's APM Device ID
mov dx, NUM_PARALLEL_PORTS - 1 ; dx <- last valid ID
add dx, bx
call APMSetDeviceCategoryPower ; ax, bx, cx destroyed
endif ; HARDWARE_TYPE, <GPC1>
endif
if HAS_SERIAL_PORTS
ifidn HARDWARE_TYPE, <GPC1>
; GPC1 APM BIOS doesn't support serial ports, so don't call it.
else
;
; Adjust device # and mark serial port as on or off
mov si, offset serialPowerStatus ; si <- SuspendRestriction
mov bx, APMDID_SERIAL_PORT_COM1 ; bx <- APM Device ID #
mov dx, NUM_SERIAL_PORTS - 1 ; dx <- last valid ID
add dx, bx
call APMSetDeviceCategoryPower ; ax, bx, cx destroyed
endif ; HARDWARE_TYPE, <GPC1>
endif
if HAS_DISPLAY_CONTROLS
;
; Adjust the state of the display.
mov si, offset displayPowerStatus ; si <- SuspendRestriction
mov bx, APMDID_DISPLAY ; bx <- APM Device ID #
mov dx, NUM_DISPLAY_CONTROLS - 1 ; dx <- last valid ID
add dx, bx
call APMSetDeviceCategoryPower ; ax, bx, cx destroyed
endif
if HAS_PCMCIA_PORTS
%out TODD - Hmmm. Wonder what we should do here?
endif
.leave
ret
APMEnforceWorldView endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
APMSetDeviceCategoryPower
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set a category of devices to specified power state
CALLED BY:
PASS: ds -> dgroup
bx -> base DEVICE ID
si -> 1st SuspendRestriction for device type
dx -> last valid DEVICE ID
RETURN: nothing
DESTROYED: ax, bx, cx
SIDE EFFECTS:
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
TS 6/27/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
APMSetDeviceCategoryPower proc near
.enter
deviceLoop:
clr cx ; cx <- APMS_READY
test {byte}ds:[si], mask SR_DEVICE_ON ; is it on?
jnz powerOnDevice ; => It is...
mov cx, APMS_OFF ; actually off
powerOnDevice:
call SysLockBIOS
CallAPM APMSC_SET_DEVICE_STATE
EC< ERROR_C -1 ; ah <- APMErrorCode >
call SysUnlockBIOS
inc bx ; next device #
add si, size SuspendRestriction ; next device status
cmp bx, dx
jbe deviceLoop
.leave
ret
APMSetDeviceCategoryPower endp
Resident ends
|
#ifndef BOOST_STATECHART_SIMPLE_STATE_HPP_INCLUDED
#define BOOST_STATECHART_SIMPLE_STATE_HPP_INCLUDED
//////////////////////////////////////////////////////////////////////////////
// Copyright 2002-2010 Andreas Huber Doenni
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//////////////////////////////////////////////////////////////////////////////
#include <boost/statechart/event.hpp>
#include <boost/statechart/detail/leaf_state.hpp>
#include <boost/statechart/detail/node_state.hpp>
#include <boost/statechart/detail/constructor.hpp>
#include <boost/statechart/detail/memory.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/is_sequence.hpp>
#include <boost/mpl/list.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/find_if.hpp>
#include <boost/mpl/contains.hpp>
#include <boost/mpl/distance.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/mpl/clear.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/less.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/plus.hpp>
#include <boost/mpl/max_element.hpp>
#include <boost/mpl/greater.hpp>
#include <boost/get_pointer.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/assert.hpp>
#include <boost/type_traits/is_base_of.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/static_assert.hpp>
#include <boost/cast.hpp> // boost::polymorphic_downcast
#include <cstddef> // std::size_t
namespace boost
{
namespace statechart
{
namespace detail
{
//////////////////////////////////////////////////////////////////////////////
template< class T >
struct make_list : public mpl::eval_if<
mpl::is_sequence< T >,
mpl::identity< T >,
mpl::identity< mpl::list< T > > > {};
//////////////////////////////////////////////////////////////////////////////
template< class MostDerived, class Context, class InnerInitial >
struct simple_state_base_type
{
private:
typedef typename Context::outermost_context_base_type::allocator_type
allocator_type;
typedef typename Context::outermost_context_base_type::rtti_policy_type
rtti_policy_type;
typedef typename detail::make_list< InnerInitial >::type
inner_initial_list;
typedef typename mpl::size< inner_initial_list >::type
inner_initial_list_size;
public:
typedef typename mpl::eval_if<
mpl::empty< inner_initial_list >,
mpl::identity< typename rtti_policy_type::
template rtti_derived_type< MostDerived, leaf_state<
allocator_type,
rtti_policy_type > > >,
mpl::identity< typename rtti_policy_type::
template rtti_derived_type< MostDerived, node_state<
inner_initial_list_size,
allocator_type,
rtti_policy_type > > > >::type type;
};
//////////////////////////////////////////////////////////////////////////////
struct no_transition_function
{
template< class CommonContext >
void operator()( CommonContext & ) const {}
};
template< class TransitionContext, class Event >
class transition_function
{
public:
transition_function(
void ( TransitionContext::*pTransitionAction )( const Event & ),
const Event & evt
) :
pTransitionAction_( pTransitionAction ),
evt_( evt )
{
}
template< class CommonContext >
void operator()( CommonContext & commonContext ) const
{
( commonContext.template context< TransitionContext >()
.*pTransitionAction_ )( evt_ );
}
private:
// avoids C4512 (assignment operator could not be generated)
transition_function & operator=( const transition_function & );
void ( TransitionContext::*pTransitionAction_ )( const Event & );
const Event & evt_;
};
template< bool contextHasInheritedDeepHistory, bool contextHasDeepHistory >
struct deep_history_storer
{
template< class HistorizedState, class LeafState, class Context >
static void store_deep_history( Context & ) {}
};
template<>
struct deep_history_storer< true, false >
{
template< class HistorizedState, class LeafState, class Context >
static void store_deep_history( Context & ctx )
{
ctx.template store_deep_history_impl< LeafState >();
}
};
template<>
struct deep_history_storer< true, true >
{
template< class HistorizedState, class LeafState, class Context >
static void store_deep_history( Context & ctx )
{
ctx.outermost_context_base().template store_deep_history<
HistorizedState, LeafState >();
ctx.template store_deep_history_impl< LeafState >();
}
};
} // namespace detail
//////////////////////////////////////////////////////////////////////////////
enum history_mode
{
has_no_history,
has_shallow_history,
has_deep_history,
has_full_history // shallow & deep
};
//////////////////////////////////////////////////////////////////////////////
template< class MostDerived,
class Context,
class InnerInitial = mpl::list<>,
history_mode historyMode = has_no_history >
class simple_state : public detail::simple_state_base_type< MostDerived,
typename Context::inner_context_type, InnerInitial >::type
{
typedef typename detail::simple_state_base_type<
MostDerived, typename Context::inner_context_type,
InnerInitial >::type base_type;
public:
//////////////////////////////////////////////////////////////////////////
typedef mpl::list<> reactions;
typedef typename Context::inner_context_type context_type;
template< detail::orthogonal_position_type innerOrthogonalPosition >
struct orthogonal
{
typedef mpl::integral_c<
detail::orthogonal_position_type,
innerOrthogonalPosition > inner_orthogonal_position;
typedef MostDerived inner_context_type;
};
typedef typename context_type::outermost_context_type
outermost_context_type;
outermost_context_type & outermost_context()
{
// This assert fails when an attempt is made to access the state machine
// from a constructor of a state that is *not* a subtype of state<>.
// To correct this, derive from state<> instead of simple_state<>.
BOOST_ASSERT( get_pointer( pContext_ ) != 0 );
return pContext_->outermost_context();
}
const outermost_context_type & outermost_context() const
{
// This assert fails when an attempt is made to access the state machine
// from a constructor of a state that is *not* a subtype of state<>.
// To correct this, derive from state<> instead of simple_state<>.
BOOST_ASSERT( get_pointer( pContext_ ) != 0 );
return pContext_->outermost_context();
}
template< class OtherContext >
OtherContext & context()
{
typedef typename mpl::if_<
is_base_of< OtherContext, MostDerived >,
context_impl_this_context,
context_impl_other_context
>::type impl;
return impl::template context_impl< OtherContext >( *this );
}
template< class OtherContext >
const OtherContext & context() const
{
typedef typename mpl::if_<
is_base_of< OtherContext, MostDerived >,
context_impl_this_context,
context_impl_other_context
>::type impl;
return impl::template context_impl< OtherContext >( *this );
}
template< class Target >
Target state_cast() const
{
return outermost_context_base().template state_cast< Target >();
}
template< class Target >
Target state_downcast() const
{
return outermost_context_base().template state_downcast< Target >();
}
typedef typename context_type::state_base_type state_base_type;
typedef typename context_type::state_iterator state_iterator;
state_iterator state_begin() const
{
return outermost_context_base().state_begin();
}
state_iterator state_end() const
{
return outermost_context_base().state_end();
}
typedef typename context_type::event_base_ptr_type event_base_ptr_type;
void post_event( const event_base_ptr_type & pEvent )
{
outermost_context_base().post_event_impl( pEvent );
}
void post_event( const event_base & evt )
{
outermost_context_base().post_event_impl( evt );
}
result discard_event()
{
return detail::result_utility::make_result( detail::do_discard_event );
}
result forward_event()
{
return detail::result_utility::make_result( detail::do_forward_event );
}
result defer_event()
{
this->state_base_type::defer_event();
return detail::result_utility::make_result( detail::do_defer_event );
}
template< class DestinationState >
result transit()
{
return transit_impl< DestinationState, outermost_context_type >(
detail::no_transition_function() );
}
template< class DestinationState, class TransitionContext, class Event >
result transit(
void ( TransitionContext::*pTransitionAction )( const Event & ),
const Event & evt )
{
return transit_impl< DestinationState, TransitionContext >(
detail::transition_function< TransitionContext, Event >(
pTransitionAction, evt ) );
}
result terminate()
{
outermost_context_base().terminate_as_reaction( *this );
return detail::result_utility::make_result( detail::do_discard_event );
}
template<
class HistoryContext,
detail::orthogonal_position_type orthogonalPosition >
void clear_shallow_history()
{
outermost_context_base().template clear_shallow_history<
HistoryContext, orthogonalPosition >();
}
template<
class HistoryContext,
detail::orthogonal_position_type orthogonalPosition >
void clear_deep_history()
{
outermost_context_base().template clear_deep_history<
HistoryContext, orthogonalPosition >();
}
const event_base * triggering_event() const
{
return outermost_context_base().triggering_event();
}
protected:
//////////////////////////////////////////////////////////////////////////
simple_state() : pContext_( 0 ) {}
~simple_state()
{
// As a result of a throwing derived class constructor, this destructor
// can be called before the context is set.
if ( get_pointer( pContext_ ) != 0 )
{
if ( this->deferred_events() )
{
outermost_context_base().release_events();
}
pContext_->remove_inner_state( orthogonal_position::value );
}
}
public:
//////////////////////////////////////////////////////////////////////////
// The following declarations should be private.
// They are only public because many compilers lack template friends.
//////////////////////////////////////////////////////////////////////////
typedef typename Context::inner_orthogonal_position orthogonal_position;
// If you receive a
// "use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'" or similar
// compiler error here then either this state resides in a non-existent
// orthogonal region of the outer state or the outer state does not have
// inner states.
BOOST_STATIC_ASSERT( ( mpl::less<
orthogonal_position,
typename context_type::no_of_orthogonal_regions >::value ) );
typedef MostDerived inner_context_type;
typedef mpl::integral_c< detail::orthogonal_position_type, 0 >
inner_orthogonal_position;
typedef typename context_type::event_base_type event_base_type;
typedef typename context_type::rtti_policy_type rtti_policy_type;
typedef typename context_type::outermost_context_base_type
outermost_context_base_type;
typedef typename context_type::inner_context_ptr_type context_ptr_type;
typedef typename context_type::state_list_type state_list_type;
typedef intrusive_ptr< inner_context_type > inner_context_ptr_type;
typedef typename detail::make_list< InnerInitial >::type
inner_initial_list;
typedef typename mpl::size< inner_initial_list >::type
inner_initial_list_size;
typedef mpl::integral_c<
detail::orthogonal_position_type,
inner_initial_list_size::value > no_of_orthogonal_regions;
typedef typename mpl::push_front<
typename context_type::context_type_list,
context_type >::type context_type_list;
// If you receive a
// "use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'" or similar
// compiler error here then the direct or indirect context of this state
// has deep history _and_ this state has two or more orthogonal regions.
// Boost.Statechart does not currently support deep history in a state whose
// direct or indirect inner states have two or more orthogonal regions.
// Please consult the documentation on how to work around this limitation.
BOOST_STATIC_ASSERT( ( mpl::or_<
mpl::less<
no_of_orthogonal_regions,
mpl::integral_c< detail::orthogonal_position_type, 2 > >,
mpl::not_<
typename context_type::inherited_deep_history > >::value ) );
typedef mpl::bool_< ( historyMode & has_shallow_history ) != 0 >
shallow_history;
typedef typename context_type::shallow_history stores_shallow_history;
typedef mpl::bool_< ( historyMode & has_deep_history ) != 0 >
deep_history;
typedef typename mpl::or_<
deep_history,
typename context_type::inherited_deep_history
>::type inherited_deep_history;
typedef typename mpl::and_<
inherited_deep_history,
mpl::empty< inner_initial_list > >::type stores_deep_history;
void * operator new( std::size_t size )
{
return detail::allocate< MostDerived,
typename outermost_context_type::allocator_type >( size );
}
void operator delete( void * pState )
{
detail::deallocate< MostDerived,
typename outermost_context_type::allocator_type >( pState );
}
outermost_context_base_type & outermost_context_base()
{
// This assert fails when an attempt is made to access the state machine
// from a constructor of a state that is *not* a subtype of state<>.
// To correct this, derive from state<> instead of simple_state<>.
BOOST_ASSERT( get_pointer( pContext_ ) != 0 );
return pContext_->outermost_context_base();
}
const outermost_context_base_type & outermost_context_base() const
{
// This assert fails when an attempt is made to access the state machine
// from a constructor of a state that is *not* a subtype of state<>.
// To correct this, derive from state<> instead of simple_state<>.
BOOST_ASSERT( get_pointer( pContext_ ) != 0 );
return pContext_->outermost_context_base();
}
virtual const state_base_type * outer_state_ptr() const
{
typedef typename mpl::if_<
is_same< outermost_context_type, context_type >,
outer_state_ptr_impl_outermost,
outer_state_ptr_impl_non_outermost
>::type impl;
return impl::outer_state_ptr_impl( *this );
}
virtual detail::reaction_result react_impl(
const event_base_type & evt,
typename rtti_policy_type::id_type eventType )
{
typedef typename detail::make_list<
typename MostDerived::reactions >::type reaction_list;
detail::reaction_result reactionResult =
local_react< reaction_list >( evt, eventType );
// At this point we can only safely access pContext_ if the handler did
// not return do_discard_event!
if ( reactionResult == detail::do_forward_event )
{
// TODO: The following call to react_impl of our outer state should
// be made with a context_type:: prefix to call directly instead of
// virtually. For some reason the compiler complains...
reactionResult = pContext_->react_impl( evt, eventType );
}
return reactionResult;
}
virtual void exit_impl(
typename base_type::direct_state_base_ptr_type & pSelf,
typename state_base_type::node_state_base_ptr_type &
pOutermostUnstableState,
bool performFullExit )
{
inner_context_ptr_type pMostDerivedSelf =
polymorphic_downcast< MostDerived * >( this );
pSelf = 0;
exit_impl( pMostDerivedSelf, pOutermostUnstableState, performFullExit );
}
void exit_impl(
inner_context_ptr_type & pSelf,
typename state_base_type::node_state_base_ptr_type &
pOutermostUnstableState,
bool performFullExit )
{
switch ( this->ref_count() )
{
case 2:
if ( get_pointer( pOutermostUnstableState ) ==
static_cast< state_base_type * >( this ) )
{
pContext_->set_outermost_unstable_state(
pOutermostUnstableState );
BOOST_FALLTHROUGH;
}
else
{
break;
}
case 1:
{
if ( get_pointer( pOutermostUnstableState ) == 0 )
{
pContext_->set_outermost_unstable_state(
pOutermostUnstableState );
}
if ( performFullExit )
{
pSelf->exit();
check_store_shallow_history< stores_shallow_history >();
check_store_deep_history< stores_deep_history >();
}
context_ptr_type pContext = pContext_;
pSelf = 0;
pContext->exit_impl(
pContext, pOutermostUnstableState, performFullExit );
break;
}
default:
break;
}
}
void set_outermost_unstable_state(
typename state_base_type::node_state_base_ptr_type &
pOutermostUnstableState )
{
pOutermostUnstableState = this;
}
template< class OtherContext >
const typename OtherContext::inner_context_ptr_type & context_ptr() const
{
typedef typename mpl::if_<
is_same< OtherContext, context_type >,
context_ptr_impl_my_context,
context_ptr_impl_other_context
>::type impl;
return impl::template context_ptr_impl< OtherContext >( *this );
}
static void initial_deep_construct(
outermost_context_base_type & outermostContextBase )
{
deep_construct( &outermostContextBase, outermostContextBase );
}
static void deep_construct(
const context_ptr_type & pContext,
outermost_context_base_type & outermostContextBase )
{
const inner_context_ptr_type pInnerContext(
shallow_construct( pContext, outermostContextBase ) );
deep_construct_inner< inner_initial_list >(
pInnerContext, outermostContextBase );
}
static inner_context_ptr_type shallow_construct(
const context_ptr_type & pContext,
outermost_context_base_type & outermostContextBase )
{
const inner_context_ptr_type pInnerContext( new MostDerived );
pInnerContext->set_context( pContext );
outermostContextBase.add( pInnerContext );
return pInnerContext;
}
void set_context( const context_ptr_type & pContext )
{
BOOST_ASSERT( get_pointer( pContext ) != 0 );
pContext_ = pContext;
base_type::set_context(
orthogonal_position::value, get_pointer( pContext ) );
}
template< class InnerList >
static void deep_construct_inner(
const inner_context_ptr_type & pInnerContext,
outermost_context_base_type & outermostContextBase )
{
typedef typename mpl::if_<
mpl::empty< InnerList >,
deep_construct_inner_impl_empty,
deep_construct_inner_impl_non_empty
>::type impl;
impl::template deep_construct_inner_impl< InnerList >(
pInnerContext, outermostContextBase );
}
template< class LeafState >
void store_deep_history_impl()
{
detail::deep_history_storer<
context_type::inherited_deep_history::value,
context_type::deep_history::value
>::template store_deep_history< MostDerived, LeafState >(
*pContext_ );
}
private:
//////////////////////////////////////////////////////////////////////////
struct context_ptr_impl_other_context
{
template< class OtherContext, class State >
static const typename OtherContext::inner_context_ptr_type &
context_ptr_impl( const State & stt )
{
// This assert fails when an attempt is made to access an outer
// context from a constructor of a state that is *not* a subtype of
// state<>. To correct this, derive from state<> instead of
// simple_state<>.
BOOST_ASSERT( get_pointer( stt.pContext_ ) != 0 );
return stt.pContext_->template context_ptr< OtherContext >();
}
};
friend struct context_ptr_impl_other_context;
struct context_ptr_impl_my_context
{
template< class OtherContext, class State >
static const typename OtherContext::inner_context_ptr_type &
context_ptr_impl( const State & stt )
{
// This assert fails when an attempt is made to access an outer
// context from a constructor of a state that is *not* a subtype of
// state<>. To correct this, derive from state<> instead of
// simple_state<>.
BOOST_ASSERT( get_pointer( stt.pContext_ ) != 0 );
return stt.pContext_;
}
};
friend struct context_ptr_impl_my_context;
struct context_impl_other_context
{
template< class OtherContext, class State >
static OtherContext & context_impl( State & stt )
{
// This assert fails when an attempt is made to access an outer
// context from a constructor of a state that is *not* a subtype of
// state<>. To correct this, derive from state<> instead of
// simple_state<>.
BOOST_ASSERT( get_pointer( stt.pContext_ ) != 0 );
return stt.pContext_->template context< OtherContext >();
}
};
friend struct context_impl_other_context;
struct context_impl_this_context
{
template< class OtherContext, class State >
static OtherContext & context_impl( State & stt )
{
return *polymorphic_downcast< MostDerived * >( &stt );
}
};
friend struct context_impl_this_context;
template< class DestinationState,
class TransitionContext,
class TransitionAction >
result transit_impl( const TransitionAction & transitionAction )
{
typedef typename mpl::find_if<
context_type_list,
mpl::contains<
typename DestinationState::context_type_list,
mpl::placeholders::_ > >::type common_context_iter;
typedef typename mpl::deref< common_context_iter >::type
common_context_type;
typedef typename mpl::distance<
typename mpl::begin< context_type_list >::type,
common_context_iter >::type termination_state_position;
typedef typename mpl::push_front< context_type_list, MostDerived >::type
possible_transition_contexts;
typedef typename mpl::at<
possible_transition_contexts,
termination_state_position >::type termination_state_type;
termination_state_type & terminationState(
context< termination_state_type >() );
const typename
common_context_type::inner_context_ptr_type pCommonContext(
terminationState.template context_ptr< common_context_type >() );
outermost_context_base_type & outermostContextBase(
pCommonContext->outermost_context_base() );
#ifdef BOOST_STATECHART_RELAX_TRANSITION_CONTEXT
typedef typename mpl::distance<
typename mpl::begin< possible_transition_contexts >::type,
typename mpl::find<
possible_transition_contexts, TransitionContext >::type
>::type proposed_transition_context_position;
typedef typename mpl::plus<
termination_state_position,
mpl::long_< 1 >
>::type uml_transition_context_position;
typedef typename mpl::deref< typename mpl::max_element<
mpl::list<
proposed_transition_context_position,
uml_transition_context_position >,
mpl::greater< mpl::placeholders::_, mpl::placeholders::_ >
>::type >::type real_transition_context_position;
typedef typename mpl::at<
possible_transition_contexts,
real_transition_context_position >::type real_transition_context_type;
#ifdef BOOST_MSVC
# pragma warning( push )
# pragma warning( disable: 4127 ) // conditional expression is constant
#endif
if ( ( proposed_transition_context_position::value == 0 ) &&
( inner_initial_list_size::value == 0 ) )
{
transitionAction( *polymorphic_downcast< MostDerived * >( this ) );
outermostContextBase.terminate_as_part_of_transit( terminationState );
}
else if ( proposed_transition_context_position::value >=
uml_transition_context_position::value )
{
real_transition_context_type & transitionContext =
context< real_transition_context_type >();
outermostContextBase.terminate_as_part_of_transit( terminationState );
transitionAction( transitionContext );
}
else
{
typename real_transition_context_type::inner_context_ptr_type
pTransitionContext = context_ptr< real_transition_context_type >();
outermostContextBase.terminate_as_part_of_transit(
*pTransitionContext );
transitionAction( *pTransitionContext );
pTransitionContext = 0;
outermostContextBase.terminate_as_part_of_transit( terminationState );
}
#ifdef BOOST_MSVC
# pragma warning( pop )
#endif
#else
outermostContextBase.terminate_as_part_of_transit( terminationState );
transitionAction( *pCommonContext );
#endif
typedef typename detail::make_context_list<
common_context_type, DestinationState >::type context_list_type;
// If you receive a
// "use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'" or
// similar compiler error here then you tried to make an invalid
// transition between different orthogonal regions.
BOOST_STATIC_ASSERT( ( mpl::equal_to<
typename termination_state_type::orthogonal_position,
typename mpl::front< context_list_type >::type::orthogonal_position
>::value ) );
detail::constructor<
context_list_type, outermost_context_base_type >::construct(
pCommonContext, outermostContextBase );
return detail::result_utility::make_result( detail::do_discard_event );
}
struct local_react_impl_non_empty
{
template< class ReactionList, class State >
static detail::reaction_result local_react_impl(
State & stt,
const event_base_type & evt,
typename rtti_policy_type::id_type eventType )
{
detail::reaction_result reactionResult =
mpl::front< ReactionList >::type::react(
*polymorphic_downcast< MostDerived * >( &stt ),
evt, eventType );
if ( reactionResult == detail::no_reaction )
{
reactionResult = stt.template local_react<
typename mpl::pop_front< ReactionList >::type >(
evt, eventType );
}
return reactionResult;
}
};
friend struct local_react_impl_non_empty;
struct local_react_impl_empty
{
template< class ReactionList, class State >
static detail::reaction_result local_react_impl(
State &, const event_base_type &, typename rtti_policy_type::id_type )
{
return detail::do_forward_event;
}
};
template< class ReactionList >
detail::reaction_result local_react(
const event_base_type & evt,
typename rtti_policy_type::id_type eventType )
{
typedef typename mpl::if_<
mpl::empty< ReactionList >,
local_react_impl_empty,
local_react_impl_non_empty
>::type impl;
return impl::template local_react_impl< ReactionList >(
*this, evt, eventType );
}
struct outer_state_ptr_impl_non_outermost
{
template< class State >
static const state_base_type * outer_state_ptr_impl( const State & stt )
{
return get_pointer( stt.pContext_ );
}
};
friend struct outer_state_ptr_impl_non_outermost;
struct outer_state_ptr_impl_outermost
{
template< class State >
static const state_base_type * outer_state_ptr_impl( const State & )
{
return 0;
}
};
struct deep_construct_inner_impl_non_empty
{
template< class InnerList >
static void deep_construct_inner_impl(
const inner_context_ptr_type & pInnerContext,
outermost_context_base_type & outermostContextBase )
{
typedef typename mpl::front< InnerList >::type current_inner;
// If you receive a
// "use of undefined type 'boost::STATIC_ASSERTION_FAILURE<x>'" or
// similar compiler error here then there is a mismatch between the
// orthogonal position of a state and its position in the inner
// initial list of its outer state.
BOOST_STATIC_ASSERT( ( is_same<
current_inner,
typename mpl::at<
typename current_inner::context_type::inner_initial_list,
typename current_inner::orthogonal_position >::type >::value ) );
current_inner::deep_construct( pInnerContext, outermostContextBase );
deep_construct_inner< typename mpl::pop_front< InnerList >::type >(
pInnerContext, outermostContextBase );
}
};
struct deep_construct_inner_impl_empty
{
template< class InnerList >
static void deep_construct_inner_impl(
const inner_context_ptr_type &, outermost_context_base_type & ) {}
};
struct check_store_shallow_history_impl_no
{
template< class State >
static void check_store_shallow_history_impl( State & ) {}
};
struct check_store_shallow_history_impl_yes
{
template< class State >
static void check_store_shallow_history_impl( State & stt )
{
stt.outermost_context_base().template store_shallow_history<
MostDerived >();
}
};
friend struct check_store_shallow_history_impl_yes;
template< class StoreShallowHistory >
void check_store_shallow_history()
{
typedef typename mpl::if_<
StoreShallowHistory,
check_store_shallow_history_impl_yes,
check_store_shallow_history_impl_no
>::type impl;
impl::check_store_shallow_history_impl( *this );
}
struct check_store_deep_history_impl_no
{
template< class State >
static void check_store_deep_history_impl( State & ) {}
};
struct check_store_deep_history_impl_yes
{
template< class State >
static void check_store_deep_history_impl( State & stt )
{
stt.template store_deep_history_impl< MostDerived >();
}
};
friend struct check_store_deep_history_impl_yes;
template< class StoreDeepHistory >
void check_store_deep_history()
{
typedef typename mpl::if_<
StoreDeepHistory,
check_store_deep_history_impl_yes,
check_store_deep_history_impl_no
>::type impl;
impl::check_store_deep_history_impl( *this );
}
context_ptr_type pContext_;
};
#ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
} // namespace statechart
#endif
template< class MostDerived, class Context,
class InnerInitial, history_mode historyMode >
inline void intrusive_ptr_release( const ::boost::statechart::simple_state<
MostDerived, Context, InnerInitial, historyMode > * pBase )
{
if ( pBase->release() )
{
// The cast is necessary because the simple_state destructor is non-
// virtual (and inaccessible from this context)
delete polymorphic_downcast< const MostDerived * >( pBase );
}
}
#ifndef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
} // namespace statechart
#endif
} // namespace boost
#endif
|
;
; Initialisation strings for the LCD panel
;
LCD_init_String0:
.DB 0x0C,0x01 ; turn on display, cursor and blink + clear display, return cursor to home position
LCD_init_Msg:
.DB " ", 0x00
;
; LCD Position - set the write poswition in the DRAM
; r24 holds the LCD I2C address
; r25 holds the address (0-127)
; r17 holds the lower 4 bits
;
LCD_Position:
call sendTWI_Start
brne LCD_serror
mov r16,r24 ; use this address
add r16,r16 ; and move over the r/w bit
call sendTWI_SLA
brne LCD_serror
mov r16,r25
ori r16,0x80 ; set DDRAM address command
ldi r17,8 ; backlight
call sendTWI_Byte
rjmp sendTWI_Stop
;
; LCD Clear - Clears the LCD and places the cursor at location 0
; r24 holds the LCD I2C address
; r17 holds the lower 4 bits
;
LCD_Clear:
call sendTWI_Start
brne LCD_serror
mov r16,r24 ; use this address
add r16,r16 ; and move over the r/w bit
call sendTWI_SLA
brne LCD_serror
ldi r16,0x01 ; set DDRAM address command
ldi r17,8 ; backlight
call sendTWI_Byte
rjmp sendTWI_Stop
;
; LCD_Text - send a null terminated string to the LCD for displaying
; Z points to the string,
; r24 is the address of the LCD
LCD_Text:
call sendTWI_Start
brne LCD_serror
mov r16,r24 ; use this address
add r16,r16 ; and move over the r/w bit
call sendTWI_SLA
brne LCD_serror
ldi r17,(1<<3)|(1<<0) ; backlight[3] + data byte[0]
LCD_Text_loop:
lpm r16,Z+
tst r16 ; test for null terminator
breq LCD_Text_done
call sendTWI_Byte
brne LCD_serror
rjmp LCD_Text_loop
LCD_Text_done:
LCD_Number_done:
LCD_serror:
rjmp sendTWI_Stop
LCD_Number:
push r16
push r19
cpi r16, 100
brge LCD_Number_3dig
cpi r16, 10
brge LCD_Number_2dig
push r16
ldi r19, 0
rcall LCD_Digit
pop r16
cpi r16, 0
breq LCD_Number_zero
rjmp LCD_Number_2dig
LCD_Number_3dig:
ldi r16, '-'
rcall LCD_Char
ldi r16, '-'
rcall LCD_Char
rjmp LCD_Number_end
LCD_Number_2dig:
ldi ZL, LOW(BCD_MEM)
ldi ZH, HIGH(BCD_MEM)
clr rBin1H
mov rBin1L, r16
rcall Bin2ToBcd
LCD_Number_loop:
ld r19, Z+
rcall LCD_Digit
dec r0
brne LCD_Number_loop
rjmp LCD_Number_end
LCD_Number_zero:
ldi r19, 0
rcall LCD_Digit
LCD_Number_end:
pop r19
pop r16
ret
LCD_Digit:
; push r16
; push r17
call sendTWI_Start
brne LCD_serror
mov r16,r24 ; use this address
add r16,r16 ; and move over the r/w bit
rcall sendTWI_SLA
brne LCD_serror
ldi r17, 9 ; backlight + data byte
ldi r16, '0'
add r16, r19
rcall sendTWI_Byte
brne LCD_serror
rjmp sendTWI_Stop
; pop r17
; pop r16
ret
LCD_Char:
call sendTWI_Start
brne LCD_serror
mov r16,r24 ; use this address
add r16,r16 ; and move over the r/w bit
rcall sendTWI_SLA
brne LCD_serror
ldi r17, 9 ; backlight + data byte
mov r16, r19
rcall sendTWI_Byte
brne LCD_serror
rjmp sendTWI_Stop
; pop r17
; pop r16
ret
;
; LCDSetup - setup the LCD display connected at I2C port in r16
;
LCD_Setup:
call sendTWI_Start ; send start bit
breq LCD_Setup_0
jmp LCD_Setup_Err
LCD_Setup_0:
mov r16,r24
add r16,r16
call sendTWI_SLA
breq LCD_Setup_1
jmp LCD_Setup_Err
LCD_Setup_1:
clr r18
clr r19
call sendTWI_Nibble
call sendTWI_Stop
ldi r18,LOW(5)
ldi r19,HIGH(5)
; call delay_ms ; wait 5 ms
;
; Send the first of three 0x30 to the display
;
call sendTWI_Start ; send start bit
breq LCD_Setup_2
jmp LCD_Setup_Err
LCD_Setup_2:
mov r16,r24
add r16,r16
call sendTWI_SLA
breq LCD_Setup_3
jmp LCD_Setup_Err
LCD_Setup_3:
ldi r18,0x30
clr r19
call sendTWI_Nibble
call sendTWI_Stop
ldi r18,LOW(5)
ldi r19,HIGH(5)
; call delay_ms ; wait 5 ms
;
; Send the second of three 0x30 to the display
;
call sendTWI_Start ; send start bit
brne LCD_Setup_Err
mov r16,r24
add r16,r16
call sendTWI_SLA
brne LCD_Setup_Err
ldi r18,0x30
clr r19
call sendTWI_Nibble
call sendTWI_Stop
ldi r18,LOW(5)
ldi r19,HIGH(5)
; call delay_ms ; wait 5 ms
;
; Send the third of three 0x30 to the display
;
call sendTWI_Start ; send start bit
brne LCD_Setup_Err
mov r16,r24
add r16,r16
call sendTWI_SLA
brne LCD_Setup_Err
ldi r18,0x30
clr r19
call sendTWI_Nibble
call sendTWI_Stop
;
; Send 0x28 to the display to reset to 4 bit mode
;
call sendTWI_Start ; send start bit
brne LCD_Setup_Err
mov r16,r24
add r16,r16
call sendTWI_SLA
brne LCD_Setup_Err
ldi r18,0x28
clr r19
call sendTWI_Nibble
call sendTWI_Stop
ldi ZL,LOW(LCD_init_String0*2)
ldi ZH,HIGH(LCD_init_String0*2)
ldi r25,2 ; all 2 bytes
ldi r17,8 ; lower 4 bits zero (Backlight on)
call SendTWI_Data
ret
LCD_Setup_Err: |
; A006940: Rows of Pascal's triangle mod 3.
; Submitted by Jon Maiga
; 1,11,121,1001,11011,121121,1002001,11022011,121212121,1000000001,11000000011,121000000121,1001000001001,11011000011011,121121000121121,1002001001002001,11022011011022011,121212121121212121,1000000002000000001,11000000022000000011,121000000212000000121
mov $3,$0
lpb $0
lpb $3
mul $1,10
mov $2,$0
bin $2,$3
mod $2,3
add $1,$2
sub $3,1
lpe
div $0,22
lpe
mov $0,$1
mul $0,10
add $0,1
|
; A095166: Group the natural numbers so that the n-th group contains n(n+1)/2 numbers and obtain the group sum.
; 1,9,45,155,420,966,1974,3690,6435,10615,16731,25389,37310,53340,74460,101796,136629,180405,234745,301455,382536,480194,596850,735150,897975,1088451,1309959,1566145,1860930,2198520,2583416,3020424,3514665
add $0,2
mov $4,-2
mov $5,1
lpb $0,1
mov $1,$5
add $3,1
sub $3,$0
sub $0,1
add $1,1
add $4,$5
mov $5,$3
lpe
mov $2,$4
mul $2,2
mul $4,2
mul $1,$4
sub $1,$2
sub $1,3
div $1,4
add $1,1
|
%ifdef CONFIG
{
"RegData": {
"MM7": ["0x8000000000000000", "0xBFFF"]
},
"Mode": "32BIT"
}
%endif
lea edx, [.data]
fld qword [edx + 8 * 0]
fisub word [edx + 8 * 1]
hlt
.data:
dq 0x3ff0000000000000
dq 2
|
;
; ANSI Video handling for gencon
;
; BEL - chr(7) Beep it out
MODULE __gencon_ansi_BEL
SECTION code_clib
PUBLIC __gencon_ansi_BEL
__gencon_ansi_BEL:
ret
|
; A065737: Largest square <= binomial(n,2).
; 0,1,1,4,9,9,16,25,36,36,49,64,64,81,100,100,121,144,169,169,196,225,225,256,289,324,324,361,400,400,441,484,484,529,576,625,625,676,729,729,784,841,900,900,961,1024,1024,1089,1156,1225,1225,1296,1369,1369,1444,1521,1521,1600,1681,1764,1764,1849,1936,1936,2025,2116,2209,2209,2304,2401,2401,2500,2601,2601,2704,2809,2916,2916,3025,3136,3136,3249,3364,3481,3481,3600,3721,3721,3844,3969,3969,4096,4225,4356,4356,4489,4624,4624,4761,4900
seq $0,1953 ; a(n) = floor((n + 1/2) * sqrt(2)).
div $0,2
pow $0,2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.