text stringlengths 1 1.05M |
|---|
; A131808: Partial sums of A131378.
; 0,0,1,1,1,2,3,3,3,3,3,4,5,5,5,5,5,6,7,7,7,7,7,8,9,10,11,12,13,13,13,14,15,16,17,18,19,19,19,19,19,20,21,21,21,21,21,22,23,24,25,26,27,27,27,27,27,27,27,28,29,29,29,29,29,29,29,30,31,32,33,33,33,34,35,36,37,38
mov $2,$0
mov $3,$0
lpb $2
mov $0,$3
sub $2,1
sub $0,$2
sub $0,1
seq $0,71986 ; Parity of the prime-counting function pi(n).
add $1,$0
lpe
mov $0,$1
|
; size_t p_queue_size_fastcall(p_queue_t *q)
SECTION code_clib
SECTION code_adt_p_queue
PUBLIC _p_queue_size_fastcall
EXTERN asm_p_queue_size
defc _p_queue_size_fastcall = asm_p_queue_size
|
#include <KrisLibrary/Logger.h>
#include "LCP.h"
#include <errors.h>
#include <sstream>
#include <iostream>
using namespace Optimization;
using namespace std;
LemkeLCP::LemkeLCP(const Matrix& M,const Vector& q)
{
verbose = 1;
Assert(M.m == M.n);
Assert(M.m == q.n);
dictionary.resize(M.m,M.n+2);
dictionary.copySubMatrix(0,1,M);
Vector qdic,z0dic;
dictionary.getColRef(0,qdic);
qdic.copy(q);
dictionary.getColRef(M.n+1,z0dic);
z0dic.set(One);
basic.resize(M.m);
nonbasic.resize(M.n+2);
for(int i=0;i<M.m;i++) basic[i]=WToVar(i);
for(int i=0;i<M.m;i++) nonbasic[i+1]=ZToVar(i);
nonbasic[0] = constant;
nonbasic[M.n+1] = z0;
}
string LemkeLCP::VarName(int var) const
{
stringstream ss;
if(IsVarW(var)) ss<<"W"<<VarToW(var)+1;
else if(IsVarZ(var)) ss<<"Z"<<VarToZ(var)+1;
else if(var==z0) ss<<"Z0";
else if(var==constant) ss<<"const";
else ss<<"InvalidVariable!("<<var<<")";
return ss.str();
}
bool LemkeLCP::Solve()
{
if(verbose >= 3) Print(cout);
int z0index = InitialPivot();
if(verbose >= 3) Print(cout);
if(z0index < 0) {
return true;
}
//last column is the swapped-out varialbe
int lastLeftVar = nonbasic[dictionary.n-1];
Assert(lastLeftVar >= 0);
int maxIters = dictionary.m*dictionary.m;
for(int iters=0;iters<maxIters;iters++) {
int newEnterVar = (IsVarW(lastLeftVar) ? WToZ(lastLeftVar) : ZToW(lastLeftVar));
Assert(newEnterVar >= 0);
int newEnterIndex = -1;
for(size_t i=0;i<nonbasic.size();i++)
if(nonbasic[i] == newEnterVar) {
newEnterIndex=(int)i;
break;
}
Assert(newEnterIndex > 0);
int newLeaveIndex = PickPivot(newEnterIndex);
if(newLeaveIndex < 0) {
if(verbose >= 1) LOG4CXX_INFO(KrisLibrary::logger(),"LemkeLCP: couldn't find a valid pivot variable for "<<VarName(nonbasic[newEnterIndex])<<" to enter");
return false;
}
int newLeaveVar = basic[newLeaveIndex];
if(verbose >= 2) LOG4CXX_INFO(KrisLibrary::logger(),"Picked pivot "<<VarName(newLeaveVar));
if(!Pivot(newEnterIndex,newLeaveIndex)) {
if(verbose >= 1) LOG4CXX_INFO(KrisLibrary::logger(),"LemkeLCP: couldn't pivot variables "<<VarName(nonbasic[newEnterIndex])<<" to enter, "<<VarName(basic[newLeaveIndex])<<" to leave");
return false;
}
if(verbose >= 3) Print(cout);
Assert(newLeaveVar != constant);
if(newLeaveVar == z0) {
return true;
}
lastLeftVar = newLeaveVar;
}
if(verbose >= 1) LOG4CXX_ERROR(KrisLibrary::logger(),"LemkeLCP: error, maximum of "<<dictionary.m<<" iterations reached");
return false;
}
void LemkeLCP::GetW(Vector& w) const
{
w.resize(dictionary.m,Zero);
for(int i=0;i<w.n;i++) {
if(IsVarW(basic[i]))
w(VarToW(basic[i])) = dictionary(i,0);
}
}
void LemkeLCP::GetZ(Vector& z) const
{
z.resize(dictionary.m,Zero);
for(int i=0;i<z.n;i++) {
if(IsVarZ(basic[i]))
z(VarToZ(basic[i])) = dictionary(i,0);
}
}
int LemkeLCP::InitialPivot()
{
//add z0 to the basic variables
int imin=-1;
Real min=Inf;
for(int i=0;i<dictionary.m;i++) {
if(dictionary(i,0) < min) {
min = dictionary(i,0);
imin=i;
}
else if(dictionary(i,0) == min) {
if(verbose >= 1) LOG4CXX_ERROR(KrisLibrary::logger(),"LemkeLCP: Warning, degeneracy!");
}
}
if(min > 0) return -1;
//make imin leave, z0 enter
Assert(nonbasic[dictionary.n-1]==z0);
bool res=Pivot(dictionary.n-1,imin);
Assert(res==true);
//must be feasible
for(int i=0;i<dictionary.m;i++)
Assert(dictionary(i,0) >= Zero);
return imin;
}
int LemkeLCP::PickPivot(int E) const
{
Assert(nonbasic[E] != constant);
for(int i=0;i<dictionary.m;i++)
Assert(dictionary(i,0) >= Zero);
//need to pick entering variable (E) such that the constants do not become negative
//
//From below:
//nonbasic[E] = (basic[L]-sum_{j!=E} d[L,j]*nonbasic[j])/d[L,E]
//d'[L,0] = -d[L,0]/d[L,E] > 0 => d[L,E] must be negative (since all constants must remain positive)
//
//d'[i,0] = d[i,0] - d[L,0]*d[i,E]/d[L,E] > 0
//
//from the L that satisfy these conditions, pick the one with the greatest resulting constants?
int maxL = -1;
Real max=-Inf;
Real entry,sum;
for(int L=0;L<dictionary.m;L++) {
if(Abs(dictionary(L,E)) == Zero) continue;
bool valid=true;
double denom = 1.0/dictionary(L,E);
double scale = dictionary(L,0)*denom;
sum=0;
for(int i=0;i<dictionary.m;i++) {
if(i == L)
entry = -scale;
else
entry = dictionary(i,0) - scale*dictionary(i,E);
if(entry < 0) {
valid = false;
break;
}
sum += entry;
}
if(valid) {
if(sum > max) {
max = sum;
maxL = L;
}
else if(sum == max) {
if(verbose >= 1) LOG4CXX_ERROR(KrisLibrary::logger(),"LemkeLCP: Warning, degeneracy");
}
}
}
return maxL;
}
bool LemkeLCP::Pivot(int E,int L)
{
if(verbose >= 2) LOG4CXX_INFO(KrisLibrary::logger(),"LemkeLCP: Pivoting "<<VarName(nonbasic[E])<<", "<<VarName(basic[L]));
Assert(nonbasic[E] != constant);
Assert(basic[L] != constant);
//nonbasic variable indexed by E (enter) gets moved to the
//basic variable indexed by L (leave) (and vice versa)
//
//basic[L] = sum_{j!=E} d[L,j]*nonbasic[j] + d[L,E]*nonbasic[E]
//=>nonbasic[E] = (basic[L]-sum_{j!=E} d[L,j]*nonbasic[j])/d[L,E]
//
//Replacing this in the dictionary, we get
//=>basic[i] = sum_{j!=E} d[i,j]*nonbasic[j] + d[i,E]*nonbasic[E]
// = sum_{j!=E} d[i,j]*nonbasic[j] + d[i,E]/d[L,E]*basic[L]-sum_{j!=E} d[L,j]*d[i,E]/d[L,E]*nonbasic[j]
// = sum_{j!=E} (d[i,j] - d[L,j]*d[i,E]/d[L,E])*nonbasic[j] + d[i,E]/d[L,E]*basic[L]
if(Abs(dictionary(L,E)) == Zero) return false;
if(FuzzyZero(dictionary(L,E))) { LOG4CXX_INFO(KrisLibrary::logger(),"LemkeLCP: pivot element is very small! "<<dictionary(L,E)); }
//replace all rows referencing the Eing variable with the new
double denom=1.0/dictionary(L,E);
for(int i=0;i<dictionary.m;i++) {
if(i != L) {
double scale = dictionary(i,E)*denom;
for(int j=0;j<dictionary.n;j++) {
if(j != E)
dictionary(i,j) -= scale*dictionary(L,j);
else //gets the unit on the old basic variable
dictionary(i,j) = scale;
}
if(!(dictionary(i,0) >= 0)) {
LOG4CXX_ERROR(KrisLibrary::logger(),"LemkeLCP: possible numerical error: "<<dictionary(i,0)<<" < 0");
Assert(FuzzyZero(dictionary(i,0)));
dictionary(i,0) = 0;
}
}
}
//do row L last (it's needed for all other rows)
for(int j=0;j<dictionary.n;j++) {
if(j != E)
dictionary(L,j) = -dictionary(L,j)*denom;
else
dictionary(L,j) = denom;
}
Assert(dictionary(L,0) >= 0);
swap(basic[L],nonbasic[E]);
return true;
}
void LemkeLCP::Print(ostream& out) const
{
out<<" ";
for(size_t i=0;i<nonbasic.size();i++)
out<<VarName(nonbasic[i])<<" ";
out<<endl;
for(int i=0;i<dictionary.m;i++) {
out<<VarName(basic[i])<<" ";
for(int j=0;j<dictionary.n;j++)
out<<dictionary(i,j)<<" ";
out<<endl;
}
}
namespace Optimization {
bool IterativeLCP(const Matrix& M,const Vector& q,Vector& w,Vector& z,int& maxIters,Real tol)
{
Assert(M.m == M.n);
Assert(M.m == q.n);
if(z.empty()) z.resize(M.m,Zero);
if(w.empty()) w.resize(M.m);
for(int i=0;i<M.n;i++)
Assert(M(i,i) != Zero);
//iteratively solve/project components of z onto 0
//w is a temporary
for(int iters=0;iters<maxIters;iters++) {
M.mul(z,w);
w += q;
if(w.minElement() > -tol && Abs(z.dot(w)) < tol) {
maxIters = iters;
return true;
}
//z^t ( Mz+q ) = 0
for(int i=0;i<M.m;i++) {
//w(i) = sum_{j!=i}M(i,j)z(j) + M(i,i)z(i) + q(i)
//=> z(i) = (-q(i) - sum_{j!=i}M(i,j)z(j))/M(i,i)
Real sum = -q(i);
for(int j=0;j<M.n;j++)
if(i != j) sum -= M(i,j)*z(j);
z(i) = Max(sum/M(i,i),Zero);
}
}
return false;
}
} //namespace Optimization
|
; A206351: a(n) = 7*a(n-1) - a(n-2) - 4 with a(1)=1, a(2)=3.
; 1,3,16,105,715,4896,33553,229971,1576240,10803705,74049691,507544128,3478759201,23843770275,163427632720,1120149658761,7677619978603,52623190191456,360684711361585,2472169789339635,16944503814015856,116139356908771353,796030994547383611,5456077604922913920,37396512239913013825,256319508074468182851,1756840044281364266128,12041560801895081680041,82534085568984207494155,565697038180994370779040,3877345181697976387959121,26575719233704840344934803,182152689454235906026584496
lpb $0
sub $0,1
add $1,1
add $1,$2
add $2,$1
add $1,$2
add $2,$1
lpe
add $1,1
mov $0,$1
|
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <utility>
#include "vm/isolate.h"
#include "include/dart_api.h"
#include "include/dart_native_api.h"
#include "platform/assert.h"
#include "platform/atomic.h"
#include "platform/text_buffer.h"
#include "vm/class_finalizer.h"
#include "vm/code_observers.h"
#include "vm/compiler/jit/compiler.h"
#include "vm/dart_api_message.h"
#include "vm/dart_api_state.h"
#include "vm/dart_entry.h"
#include "vm/debugger.h"
#include "vm/deopt_instructions.h"
#include "vm/dispatch_table.h"
#include "vm/flags.h"
#include "vm/heap/heap.h"
#include "vm/heap/pointer_block.h"
#include "vm/heap/safepoint.h"
#include "vm/heap/verifier.h"
#include "vm/image_snapshot.h"
#include "vm/interpreter.h"
#include "vm/isolate_reload.h"
#include "vm/kernel_isolate.h"
#include "vm/lockers.h"
#include "vm/log.h"
#include "vm/message_handler.h"
#include "vm/object.h"
#include "vm/object_id_ring.h"
#include "vm/object_store.h"
#include "vm/os_thread.h"
#include "vm/port.h"
#include "vm/profiler.h"
#include "vm/reusable_handles.h"
#include "vm/reverse_pc_lookup_cache.h"
#include "vm/service.h"
#include "vm/service_event.h"
#include "vm/service_isolate.h"
#include "vm/simulator.h"
#include "vm/stack_frame.h"
#include "vm/stub_code.h"
#include "vm/symbols.h"
#include "vm/tags.h"
#include "vm/thread_interrupter.h"
#include "vm/thread_registry.h"
#include "vm/timeline.h"
#include "vm/timeline_analysis.h"
#include "vm/visitor.h"
#if !defined(DART_PRECOMPILED_RUNTIME)
#include "vm/compiler/assembler/assembler.h"
#include "vm/compiler/stub_code_compiler.h"
#endif
namespace dart {
DECLARE_FLAG(bool, print_metrics);
DECLARE_FLAG(bool, timing);
DECLARE_FLAG(bool, trace_service);
DECLARE_FLAG(bool, warn_on_pause_with_no_debugger);
// Reload flags.
DECLARE_FLAG(int, reload_every);
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
DECLARE_FLAG(bool, check_reloaded);
DECLARE_FLAG(bool, reload_every_back_off);
DECLARE_FLAG(bool, trace_reload);
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
static void DeterministicModeHandler(bool value) {
if (value) {
FLAG_background_compilation = false; // Timing dependent.
FLAG_concurrent_mark = false; // Timing dependent.
FLAG_concurrent_sweep = false; // Timing dependent.
FLAG_random_seed = 0x44617274; // "Dart"
}
}
DEFINE_FLAG_HANDLER(DeterministicModeHandler,
deterministic,
"Enable deterministic mode.");
// Quick access to the locally defined thread() and isolate() methods.
#define T (thread())
#define I (isolate())
#if defined(DEBUG)
// Helper class to ensure that a live origin_id is never reused
// and assigned to an isolate.
class VerifyOriginId : public IsolateVisitor {
public:
explicit VerifyOriginId(Dart_Port id) : id_(id) {}
void VisitIsolate(Isolate* isolate) { ASSERT(isolate->origin_id() != id_); }
private:
Dart_Port id_;
DISALLOW_COPY_AND_ASSIGN(VerifyOriginId);
};
#endif
static std::unique_ptr<Message> SerializeMessage(Dart_Port dest_port,
const Instance& obj) {
if (ApiObjectConverter::CanConvert(obj.raw())) {
return Message::New(dest_port, obj.raw(), Message::kNormalPriority);
} else {
MessageWriter writer(false);
return writer.WriteMessage(obj, dest_port, Message::kNormalPriority);
}
}
static RawInstance* DeserializeMessage(Thread* thread, Message* message) {
if (message == NULL) {
return Instance::null();
}
Zone* zone = thread->zone();
if (message->IsRaw()) {
return Instance::RawCast(message->raw_obj());
} else {
MessageSnapshotReader reader(message, thread);
const Object& obj = Object::Handle(zone, reader.ReadObject());
ASSERT(!obj.IsError());
return Instance::RawCast(obj.raw());
}
}
void IdleTimeHandler::InitializeWithHeap(Heap* heap) {
MutexLocker ml(&mutex_);
ASSERT(heap_ == nullptr && heap != nullptr);
heap_ = heap;
}
bool IdleTimeHandler::ShouldCheckForIdle() {
MutexLocker ml(&mutex_);
return idle_start_time_ > 0 && FLAG_idle_timeout_micros != 0 &&
disabled_counter_ == 0;
}
void IdleTimeHandler::UpdateStartIdleTime() {
MutexLocker ml(&mutex_);
if (disabled_counter_ == 0) {
idle_start_time_ = OS::GetCurrentMonotonicMicros();
}
}
bool IdleTimeHandler::ShouldNotifyIdle(int64_t* expiry) {
const int64_t now = OS::GetCurrentMonotonicMicros();
MutexLocker ml(&mutex_);
if (idle_start_time_ > 0 && disabled_counter_ == 0) {
const int64_t expiry_time = idle_start_time_ + FLAG_idle_timeout_micros;
if (expiry_time < now) {
idle_start_time_ = 0;
return true;
}
}
*expiry = now + FLAG_idle_timeout_micros;
return false;
}
void IdleTimeHandler::NotifyIdle(int64_t deadline) {
MutexLocker ml(&mutex_, /*no_safepoint_scope=*/false);
if (heap_ != nullptr) {
heap_->NotifyIdle(deadline);
}
idle_start_time_ = 0;
}
void IdleTimeHandler::NotifyIdleUsingDefaultDeadline() {
const int64_t now = OS::GetCurrentMonotonicMicros();
NotifyIdle(now + FLAG_idle_timeout_micros);
}
DisableIdleTimerScope::DisableIdleTimerScope(IdleTimeHandler* handler)
: handler_(handler) {
if (handler_ != nullptr) {
MutexLocker ml(&handler_->mutex_);
++handler_->disabled_counter_;
handler_->idle_start_time_ = 0;
}
}
DisableIdleTimerScope::~DisableIdleTimerScope() {
if (handler_ != nullptr) {
MutexLocker ml(&handler_->mutex_);
--handler_->disabled_counter_;
ASSERT(handler_->disabled_counter_ >= 0);
}
}
IsolateGroup::IsolateGroup(std::unique_ptr<IsolateGroupSource> source,
void* embedder_data)
: embedder_data_(embedder_data),
isolates_rwlock_(new RwLock()),
isolates_(),
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
last_reload_timestamp_(OS::GetCurrentTimeMillis()),
#endif
source_(std::move(source)),
thread_registry_(new ThreadRegistry()),
safepoint_handler_(new SafepointHandler(this)) {
}
IsolateGroup::~IsolateGroup() {}
void IsolateGroup::RegisterIsolate(Isolate* isolate) {
WriteRwLocker wl(ThreadState::Current(), isolates_rwlock_.get());
isolates_.Append(isolate);
isolate_count_++;
}
void IsolateGroup::UnregisterIsolate(Isolate* isolate) {
bool is_last_isolate = false;
{
WriteRwLocker wl(ThreadState::Current(), isolates_rwlock_.get());
isolates_.Remove(isolate);
isolate_count_--;
is_last_isolate = isolate_count_ == 0;
}
if (is_last_isolate) {
// If the creation of the isolate group (or the first isolate within the
// isolate group) failed, we do not invoke the cleanup callback (the
// embedder is responsible for handling the creation error).
if (initial_spawn_successful_) {
auto group_shutdown_callback = Isolate::GroupCleanupCallback();
if (group_shutdown_callback != nullptr) {
group_shutdown_callback(embedder_data());
}
}
UnregisterIsolateGroup(this);
delete this;
}
}
Thread* IsolateGroup::ScheduleThreadLocked(MonitorLocker* ml,
Thread* existing_mutator_thread,
bool is_vm_isolate,
bool is_mutator,
bool bypass_safepoint) {
ASSERT(threads_lock()->IsOwnedByCurrentThread());
// Schedule the thread into the isolate group by associating
// a 'Thread' structure with it (this is done while we are holding
// the thread registry lock).
Thread* thread = nullptr;
OSThread* os_thread = OSThread::Current();
if (os_thread != nullptr) {
// If a safepoint operation is in progress wait for it
// to finish before scheduling this thread in.
while (!bypass_safepoint && safepoint_handler()->SafepointInProgress()) {
ml->Wait();
}
if (is_mutator) {
if (existing_mutator_thread == nullptr) {
// Allocate a new [Thread] structure for the mutator thread.
thread = thread_registry()->GetFreeThreadLocked(is_vm_isolate);
} else {
// Reuse the existing cached [Thread] structure for the mutator thread.,
// see comment in 'base_isolate.h'.
thread_registry()->AddToActiveListLocked(existing_mutator_thread);
thread = existing_mutator_thread;
}
} else {
thread = thread_registry()->GetFreeThreadLocked(is_vm_isolate);
}
// Now get a free Thread structure.
ASSERT(thread != nullptr);
thread->ResetHighWatermark();
// Set up other values and set the TLS value.
thread->isolate_ = nullptr;
thread->isolate_group_ = this;
thread->field_table_values_ = nullptr;
thread->set_os_thread(os_thread);
ASSERT(thread->execution_state() == Thread::kThreadInNative);
thread->set_execution_state(Thread::kThreadInVM);
thread->set_safepoint_state(
Thread::SetBypassSafepoints(bypass_safepoint, 0));
thread->set_vm_tag(VMTag::kVMTagId);
ASSERT(thread->no_safepoint_scope_depth() == 0);
os_thread->set_thread(thread);
Thread::SetCurrent(thread);
os_thread->EnableThreadInterrupts();
}
return thread;
}
void IsolateGroup::UnscheduleThreadLocked(MonitorLocker* ml,
Thread* thread,
bool is_mutator,
bool bypass_safepoint) {
// Disassociate the 'Thread' structure and unschedule the thread
// from this isolate group.
if (!is_mutator) {
ASSERT(thread->api_top_scope_ == nullptr);
ASSERT(thread->zone() == nullptr);
ASSERT(thread->sticky_error() == Error::null());
}
if (!bypass_safepoint) {
// Ensure that the thread reports itself as being at a safepoint.
thread->EnterSafepoint();
}
OSThread* os_thread = thread->os_thread();
ASSERT(os_thread != nullptr);
os_thread->DisableThreadInterrupts();
os_thread->set_thread(nullptr);
OSThread::SetCurrent(os_thread);
// Even if we unschedule the mutator thread, e.g. via calling
// `Dart_ExitIsolate()` inside a native, we might still have one or more Dart
// stacks active, which e.g. GC marker threads want to visit. So we don't
// clear out the isolate pointer if we are on the mutator thread.
//
// The [thread] structure for the mutator thread is kept alive in the thread
// registry even if the mutator thread is temporarily unscheduled.
//
// All other threads are not allowed to unschedule themselves and schedule
// again later on.
if (!is_mutator) {
thread->isolate_ = nullptr;
}
thread->heap_ = nullptr;
thread->set_os_thread(nullptr);
thread->set_execution_state(Thread::kThreadInNative);
thread->set_safepoint_state(Thread::SetAtSafepoint(true, 0));
thread->clear_pending_functions();
ASSERT(thread->no_safepoint_scope_depth() == 0);
if (is_mutator) {
// The mutator thread structure stays alive and attached to the isolate as
// long as the isolate lives. So we simply remove the thread from the list
// of scheduled threads.
thread_registry()->RemoveFromActiveListLocked(thread);
} else {
// Return thread structure.
thread_registry()->ReturnThreadLocked(thread);
}
}
Thread* IsolateGroup::ScheduleThread(bool bypass_safepoint) {
// We are about to associate the thread with an isolate group and it would
// not be possible to correctly track no_safepoint_scope_depth for the
// thread in the constructor/destructor of MonitorLocker,
// so we create a MonitorLocker object which does not do any
// no_safepoint_scope_depth increments/decrements.
MonitorLocker ml(threads_lock(), false);
const bool is_vm_isolate = false;
// Schedule the thread into the isolate by associating
// a 'Thread' structure with it (this is done while we are holding
// the thread registry lock).
return ScheduleThreadLocked(&ml, /*existing_mutator_thread=*/nullptr,
is_vm_isolate, /*is_mutator=*/false,
bypass_safepoint);
}
void IsolateGroup::UnscheduleThread(Thread* thread,
bool is_mutator,
bool bypass_safepoint) {
// Disassociate the 'Thread' structure and unschedule the thread
// from this isolate group.
//
// We are disassociating the thread from an isolate and it would
// not be possible to correctly track no_safepoint_scope_depth for the
// thread in the constructor/destructor of MonitorLocker,
// so we create a MonitorLocker object which does not do any
// no_safepoint_scope_depth increments/decrements.
MonitorLocker ml(threads_lock(), false);
UnscheduleThreadLocked(&ml, thread, is_mutator, bypass_safepoint);
}
#ifndef PRODUCT
void IsolateGroup::PrintJSON(JSONStream* stream, bool ref) {
if (!FLAG_support_service) {
return;
}
JSONObject jsobj(stream);
PrintToJSONObject(&jsobj, ref);
}
void IsolateGroup::PrintToJSONObject(JSONObject* jsobj, bool ref) {
if (!FLAG_support_service) {
return;
}
jsobj->AddProperty("type", (ref ? "@IsolateGroup" : "IsolateGroup"));
jsobj->AddServiceId(ISOLATE_GROUP_SERVICE_ID_FORMAT_STRING, id());
jsobj->AddProperty("name", "isolate_group");
jsobj->AddPropertyF("number", "%" Pu64 "", id());
if (ref) {
return;
}
{
JSONArray isolate_array(jsobj, "isolates");
for (auto it = isolates_.Begin(); it != isolates_.End(); ++it) {
Isolate* isolate = *it;
isolate_array.AddValue(isolate, /*ref=*/true);
}
}
}
void IsolateGroup::PrintMemoryUsageJSON(JSONStream* stream) {
if (!FLAG_support_service) {
return;
}
int64_t used = 0;
int64_t capacity = 0;
int64_t external_used = 0;
for (auto it = isolates_.Begin(); it != isolates_.End(); ++it) {
Isolate* isolate = *it;
used += isolate->heap()->TotalUsedInWords();
capacity += isolate->heap()->TotalCapacityInWords();
external_used += isolate->heap()->TotalExternalInWords();
}
JSONObject jsobj(stream);
// This is the same "MemoryUsage" that the isolate-specific "getMemoryUsage"
// rpc method returns.
// TODO(dartbug.com/36097): Once the heap moves from Isolate to IsolateGroup
// this code needs to be adjusted to not double-count memory.
jsobj.AddProperty("type", "MemoryUsage");
jsobj.AddProperty64("heapUsage", used * kWordSize);
jsobj.AddProperty64("heapCapacity", capacity * kWordSize);
jsobj.AddProperty64("externalUsage", external_used * kWordSize);
}
#endif
void IsolateGroup::ForEach(std::function<void(IsolateGroup*)> action) {
ReadRwLocker wl(Thread::Current(), isolate_groups_rwlock_);
for (auto isolate_group : *isolate_groups_) {
action(isolate_group);
}
}
void IsolateGroup::RunWithIsolateGroup(
uint64_t id,
std::function<void(IsolateGroup*)> action,
std::function<void()> not_found) {
ReadRwLocker wl(Thread::Current(), isolate_groups_rwlock_);
for (auto isolate_group : *isolate_groups_) {
if (isolate_group->id() == id) {
action(isolate_group);
return;
}
}
not_found();
}
void IsolateGroup::RegisterIsolateGroup(IsolateGroup* isolate_group) {
WriteRwLocker wl(ThreadState::Current(), isolate_groups_rwlock_);
isolate_groups_->Append(isolate_group);
}
void IsolateGroup::UnregisterIsolateGroup(IsolateGroup* isolate_group) {
WriteRwLocker wl(ThreadState::Current(), isolate_groups_rwlock_);
isolate_groups_->Remove(isolate_group);
}
void IsolateGroup::Init() {
ASSERT(isolate_groups_rwlock_ == nullptr);
isolate_groups_rwlock_ = new RwLock();
ASSERT(isolate_groups_ == nullptr);
isolate_groups_ = new IntrusiveDList<IsolateGroup>();
}
void IsolateGroup::Cleanup() {
delete isolate_groups_rwlock_;
isolate_groups_rwlock_ = nullptr;
ASSERT(isolate_groups_->IsEmpty());
delete isolate_groups_;
isolate_groups_ = nullptr;
}
bool IsolateVisitor::IsVMInternalIsolate(Isolate* isolate) const {
return Isolate::IsVMInternalIsolate(isolate);
}
NoOOBMessageScope::NoOOBMessageScope(Thread* thread)
: ThreadStackResource(thread) {
thread->DeferOOBMessageInterrupts();
}
NoOOBMessageScope::~NoOOBMessageScope() {
thread()->RestoreOOBMessageInterrupts();
}
NoReloadScope::NoReloadScope(Isolate* isolate, Thread* thread)
: ThreadStackResource(thread), isolate_(isolate) {
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
ASSERT(isolate_ != NULL);
isolate_->no_reload_scope_depth_.fetch_add(1);
ASSERT(isolate_->no_reload_scope_depth_ >= 0);
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
}
NoReloadScope::~NoReloadScope() {
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
isolate_->no_reload_scope_depth_.fetch_sub(1);
ASSERT(isolate_->no_reload_scope_depth_ >= 0);
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
}
void Isolate::RegisterClass(const Class& cls) {
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
if (group()->IsReloading()) {
reload_context()->RegisterClass(cls);
return;
}
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
class_table()->Register(cls);
}
#if defined(DEBUG)
void Isolate::ValidateClassTable() {
class_table()->Validate();
}
#endif // DEBUG
void Isolate::RegisterStaticField(const Field& field) {
field_table()->Register(field);
}
void Isolate::RehashConstants() {
Thread* thread = Thread::Current();
StackZone stack_zone(thread);
Zone* zone = stack_zone.GetZone();
thread->heap()->ResetCanonicalHashTable();
Class& cls = Class::Handle(zone);
intptr_t top = class_table()->NumCids();
for (intptr_t cid = kInstanceCid; cid < top; cid++) {
if (!class_table()->IsValidIndex(cid) ||
!class_table()->HasValidClassAt(cid)) {
continue;
}
if ((cid == kTypeArgumentsCid) || RawObject::IsStringClassId(cid)) {
// TypeArguments and Symbols have special tables for canonical objects
// that aren't based on address.
continue;
}
cls = class_table()->At(cid);
cls.RehashConstants(zone);
}
}
#if defined(DEBUG)
void Isolate::ValidateConstants() {
if (FLAG_precompiled_mode) {
// TODO(27003)
return;
}
if (HasAttemptedReload()) {
return;
}
// Verify that all canonical instances are correctly setup in the
// corresponding canonical tables.
BackgroundCompiler::Stop(this);
heap()->CollectAllGarbage();
Thread* thread = Thread::Current();
HeapIterationScope iteration(thread);
VerifyCanonicalVisitor check_canonical(thread);
iteration.IterateObjects(&check_canonical);
}
#endif // DEBUG
void Isolate::SendInternalLibMessage(LibMsgId msg_id, uint64_t capability) {
const Array& msg = Array::Handle(Array::New(3));
Object& element = Object::Handle();
element = Smi::New(Message::kIsolateLibOOBMsg);
msg.SetAt(0, element);
element = Smi::New(msg_id);
msg.SetAt(1, element);
element = Capability::New(capability);
msg.SetAt(2, element);
MessageWriter writer(false);
PortMap::PostMessage(
writer.WriteMessage(msg, main_port(), Message::kOOBPriority));
}
class IsolateMessageHandler : public MessageHandler {
public:
explicit IsolateMessageHandler(Isolate* isolate);
~IsolateMessageHandler();
const char* name() const;
void MessageNotify(Message::Priority priority);
MessageStatus HandleMessage(std::unique_ptr<Message> message);
#ifndef PRODUCT
void NotifyPauseOnStart();
void NotifyPauseOnExit();
#endif // !PRODUCT
#if defined(DEBUG)
// Check that it is safe to access this handler.
void CheckAccess();
#endif
bool IsCurrentIsolate() const;
virtual Isolate* isolate() const { return isolate_; }
private:
// A result of false indicates that the isolate should terminate the
// processing of further events.
RawError* HandleLibMessage(const Array& message);
MessageStatus ProcessUnhandledException(const Error& result);
Isolate* isolate_;
};
IsolateMessageHandler::IsolateMessageHandler(Isolate* isolate)
: isolate_(isolate) {}
IsolateMessageHandler::~IsolateMessageHandler() {}
const char* IsolateMessageHandler::name() const {
return isolate_->name();
}
// Isolate library OOB messages are fixed sized arrays which have the
// following format:
// [ OOB dispatch, Isolate library dispatch, <message specific data> ]
RawError* IsolateMessageHandler::HandleLibMessage(const Array& message) {
if (message.Length() < 2) return Error::null();
Zone* zone = T->zone();
const Object& type = Object::Handle(zone, message.At(1));
if (!type.IsSmi()) return Error::null();
const intptr_t msg_type = Smi::Cast(type).Value();
switch (msg_type) {
case Isolate::kPauseMsg: {
// [ OOB, kPauseMsg, pause capability, resume capability ]
if (message.Length() != 4) return Error::null();
Object& obj = Object::Handle(zone, message.At(2));
if (!I->VerifyPauseCapability(obj)) return Error::null();
obj = message.At(3);
if (!obj.IsCapability()) return Error::null();
if (I->AddResumeCapability(Capability::Cast(obj))) {
increment_paused();
}
break;
}
case Isolate::kResumeMsg: {
// [ OOB, kResumeMsg, pause capability, resume capability ]
if (message.Length() != 4) return Error::null();
Object& obj = Object::Handle(zone, message.At(2));
if (!I->VerifyPauseCapability(obj)) return Error::null();
obj = message.At(3);
if (!obj.IsCapability()) return Error::null();
if (I->RemoveResumeCapability(Capability::Cast(obj))) {
decrement_paused();
}
break;
}
case Isolate::kPingMsg: {
// [ OOB, kPingMsg, responsePort, priority, response ]
if (message.Length() != 5) return Error::null();
const Object& obj2 = Object::Handle(zone, message.At(2));
if (!obj2.IsSendPort()) return Error::null();
const SendPort& send_port = SendPort::Cast(obj2);
const Object& obj3 = Object::Handle(zone, message.At(3));
if (!obj3.IsSmi()) return Error::null();
const intptr_t priority = Smi::Cast(obj3).Value();
const Object& obj4 = Object::Handle(zone, message.At(4));
if (!obj4.IsInstance() && !obj4.IsNull()) return Error::null();
const Instance& response =
obj4.IsNull() ? Instance::null_instance() : Instance::Cast(obj4);
if (priority == Isolate::kImmediateAction) {
PortMap::PostMessage(SerializeMessage(send_port.Id(), response));
} else {
ASSERT((priority == Isolate::kBeforeNextEventAction) ||
(priority == Isolate::kAsEventAction));
// Update the message so that it will be handled immediately when it
// is picked up from the message queue the next time.
message.SetAt(
0, Smi::Handle(zone, Smi::New(Message::kDelayedIsolateLibOOBMsg)));
message.SetAt(3,
Smi::Handle(zone, Smi::New(Isolate::kImmediateAction)));
this->PostMessage(
SerializeMessage(Message::kIllegalPort, message),
priority == Isolate::kBeforeNextEventAction /* at_head */);
}
break;
}
case Isolate::kKillMsg:
case Isolate::kInternalKillMsg: {
// [ OOB, kKillMsg, terminate capability, priority ]
if (message.Length() != 4) return Error::null();
Object& obj = Object::Handle(zone, message.At(3));
if (!obj.IsSmi()) return Error::null();
const intptr_t priority = Smi::Cast(obj).Value();
if (priority == Isolate::kImmediateAction) {
obj = message.At(2);
if (I->VerifyTerminateCapability(obj)) {
// We will kill the current isolate by returning an UnwindError.
if (msg_type == Isolate::kKillMsg) {
const String& msg = String::Handle(
String::New("isolate terminated by Isolate.kill"));
const UnwindError& error =
UnwindError::Handle(UnwindError::New(msg));
error.set_is_user_initiated(true);
return error.raw();
} else if (msg_type == Isolate::kInternalKillMsg) {
const String& msg =
String::Handle(String::New("isolate terminated by vm"));
return UnwindError::New(msg);
} else {
UNREACHABLE();
}
} else {
return Error::null();
}
} else {
ASSERT((priority == Isolate::kBeforeNextEventAction) ||
(priority == Isolate::kAsEventAction));
// Update the message so that it will be handled immediately when it
// is picked up from the message queue the next time.
message.SetAt(
0, Smi::Handle(zone, Smi::New(Message::kDelayedIsolateLibOOBMsg)));
message.SetAt(3,
Smi::Handle(zone, Smi::New(Isolate::kImmediateAction)));
this->PostMessage(
SerializeMessage(Message::kIllegalPort, message),
priority == Isolate::kBeforeNextEventAction /* at_head */);
}
break;
}
case Isolate::kInterruptMsg: {
// [ OOB, kInterruptMsg, pause capability ]
if (message.Length() != 3) return Error::null();
Object& obj = Object::Handle(zone, message.At(2));
if (!I->VerifyPauseCapability(obj)) return Error::null();
#if !defined(PRODUCT)
// If we are already paused, don't pause again.
if (I->debugger()->PauseEvent() == NULL) {
return I->debugger()->PauseInterrupted();
}
#endif
break;
}
case Isolate::kLowMemoryMsg: {
I->heap()->NotifyLowMemory();
break;
}
case Isolate::kDrainServiceExtensionsMsg: {
#ifndef PRODUCT
Object& obj = Object::Handle(zone, message.At(2));
if (!obj.IsSmi()) return Error::null();
const intptr_t priority = Smi::Cast(obj).Value();
if (priority == Isolate::kImmediateAction) {
return I->InvokePendingServiceExtensionCalls();
} else {
ASSERT((priority == Isolate::kBeforeNextEventAction) ||
(priority == Isolate::kAsEventAction));
// Update the message so that it will be handled immediately when it
// is picked up from the message queue the next time.
message.SetAt(
0, Smi::Handle(zone, Smi::New(Message::kDelayedIsolateLibOOBMsg)));
message.SetAt(2,
Smi::Handle(zone, Smi::New(Isolate::kImmediateAction)));
this->PostMessage(
SerializeMessage(Message::kIllegalPort, message),
priority == Isolate::kBeforeNextEventAction /* at_head */);
}
#else
UNREACHABLE();
#endif // !PRODUCT
break;
}
case Isolate::kAddExitMsg:
case Isolate::kDelExitMsg:
case Isolate::kAddErrorMsg:
case Isolate::kDelErrorMsg: {
// [ OOB, msg, listener port ]
if (message.Length() < 3) return Error::null();
const Object& obj = Object::Handle(zone, message.At(2));
if (!obj.IsSendPort()) return Error::null();
const SendPort& listener = SendPort::Cast(obj);
switch (msg_type) {
case Isolate::kAddExitMsg: {
if (message.Length() != 4) return Error::null();
// [ OOB, msg, listener port, response object ]
const Object& response = Object::Handle(zone, message.At(3));
if (!response.IsInstance() && !response.IsNull()) {
return Error::null();
}
I->AddExitListener(listener, response.IsNull()
? Instance::null_instance()
: Instance::Cast(response));
break;
}
case Isolate::kDelExitMsg:
if (message.Length() != 3) return Error::null();
I->RemoveExitListener(listener);
break;
case Isolate::kAddErrorMsg:
if (message.Length() != 3) return Error::null();
I->AddErrorListener(listener);
break;
case Isolate::kDelErrorMsg:
if (message.Length() != 3) return Error::null();
I->RemoveErrorListener(listener);
break;
default:
UNREACHABLE();
}
break;
}
case Isolate::kErrorFatalMsg: {
// [ OOB, kErrorFatalMsg, terminate capability, val ]
if (message.Length() != 4) return Error::null();
// Check that the terminate capability has been passed correctly.
Object& obj = Object::Handle(zone, message.At(2));
if (!I->VerifyTerminateCapability(obj)) return Error::null();
// Get the value to be set.
obj = message.At(3);
if (!obj.IsBool()) return Error::null();
I->SetErrorsFatal(Bool::Cast(obj).value());
break;
}
#if defined(DEBUG)
// Malformed OOB messages are silently ignored in release builds.
default:
FATAL1("Unknown OOB message type: %" Pd "\n", msg_type);
break;
#endif // defined(DEBUG)
}
return Error::null();
}
void IsolateMessageHandler::MessageNotify(Message::Priority priority) {
if (priority >= Message::kOOBPriority) {
// Handle out of band messages even if the mutator thread is busy.
I->ScheduleInterrupts(Thread::kMessageInterrupt);
}
Dart_MessageNotifyCallback callback = I->message_notify_callback();
if (callback != nullptr) {
// Allow the embedder to handle message notification.
(*callback)(Api::CastIsolate(I));
}
}
bool Isolate::HasPendingMessages() {
return message_handler_->HasMessages() || message_handler_->HasOOBMessages();
}
MessageHandler::MessageStatus IsolateMessageHandler::HandleMessage(
std::unique_ptr<Message> message) {
ASSERT(IsCurrentIsolate());
Thread* thread = Thread::Current();
StackZone stack_zone(thread);
Zone* zone = stack_zone.GetZone();
HandleScope handle_scope(thread);
#if defined(SUPPORT_TIMELINE)
TimelineBeginEndScope tbes(
thread, Timeline::GetIsolateStream(),
message->IsOOB() ? "HandleOOBMessage" : "HandleMessage");
tbes.SetNumArguments(1);
tbes.CopyArgument(0, "isolateName", I->name());
#endif
// If the message is in band we lookup the handler to dispatch to. If the
// receive port was closed, we drop the message without deserializing it.
// Illegal port is a special case for artificially enqueued isolate library
// messages which are handled in C++ code below.
Object& msg_handler = Object::Handle(zone);
if (!message->IsOOB() && (message->dest_port() != Message::kIllegalPort)) {
msg_handler = DartLibraryCalls::LookupHandler(message->dest_port());
if (msg_handler.IsError()) {
return ProcessUnhandledException(Error::Cast(msg_handler));
}
if (msg_handler.IsNull()) {
// If the port has been closed then the message will be dropped at this
// point. Make sure to post to the delivery failure port in that case.
if (message->RedirectToDeliveryFailurePort()) {
PortMap::PostMessage(std::move(message));
}
return kOK;
}
}
// Parse the message.
Object& msg_obj = Object::Handle(zone);
if (message->IsRaw()) {
msg_obj = message->raw_obj();
// We should only be sending RawObjects that can be converted to CObjects.
ASSERT(ApiObjectConverter::CanConvert(msg_obj.raw()));
} else {
MessageSnapshotReader reader(message.get(), thread);
msg_obj = reader.ReadObject();
}
if (msg_obj.IsError()) {
// An error occurred while reading the message.
return ProcessUnhandledException(Error::Cast(msg_obj));
}
if (!msg_obj.IsNull() && !msg_obj.IsInstance()) {
// TODO(turnidge): We need to decide what an isolate does with
// malformed messages. If they (eventually) come from a remote
// machine, then it might make sense to drop the message entirely.
// In the case that the message originated locally, which is
// always true for now, then this should never occur.
UNREACHABLE();
}
Instance& msg = Instance::Handle(zone);
msg ^= msg_obj.raw(); // Can't use Instance::Cast because may be null.
MessageStatus status = kOK;
if (message->IsOOB()) {
// OOB messages are expected to be fixed length arrays where the first
// element is a Smi describing the OOB destination. Messages that do not
// confirm to this layout are silently ignored.
if (msg.IsArray()) {
const Array& oob_msg = Array::Cast(msg);
if (oob_msg.Length() > 0) {
const Object& oob_tag = Object::Handle(zone, oob_msg.At(0));
if (oob_tag.IsSmi()) {
switch (Smi::Cast(oob_tag).Value()) {
case Message::kServiceOOBMsg: {
if (FLAG_support_service) {
const Error& error =
Error::Handle(Service::HandleIsolateMessage(I, oob_msg));
if (!error.IsNull()) {
status = ProcessUnhandledException(error);
}
} else {
UNREACHABLE();
}
break;
}
case Message::kIsolateLibOOBMsg: {
const Error& error = Error::Handle(HandleLibMessage(oob_msg));
if (!error.IsNull()) {
status = ProcessUnhandledException(error);
}
break;
}
#if defined(DEBUG)
// Malformed OOB messages are silently ignored in release builds.
default: {
UNREACHABLE();
break;
}
#endif // defined(DEBUG)
}
}
}
}
} else if (message->dest_port() == Message::kIllegalPort) {
// Check whether this is a delayed OOB message which needed handling as
// part of the regular message dispatch. All other messages are dropped on
// the floor.
if (msg.IsArray()) {
const Array& msg_arr = Array::Cast(msg);
if (msg_arr.Length() > 0) {
const Object& oob_tag = Object::Handle(zone, msg_arr.At(0));
if (oob_tag.IsSmi() &&
(Smi::Cast(oob_tag).Value() == Message::kDelayedIsolateLibOOBMsg)) {
const Error& error = Error::Handle(HandleLibMessage(msg_arr));
if (!error.IsNull()) {
status = ProcessUnhandledException(error);
}
}
}
}
} else {
#ifndef PRODUCT
if (!Isolate::IsVMInternalIsolate(I)) {
// Mark all the user isolates as white-listed for the simplified timeline
// page of Observatory. The internal isolates will be filtered out from
// the Timeline due to absence of this argument. We still send them in
// order to maintain the original behavior of the full timeline and allow
// the developer to download complete dump files.
tbes.SetNumArguments(2);
tbes.CopyArgument(1, "mode", "basic");
}
#endif
const Object& result =
Object::Handle(zone, DartLibraryCalls::HandleMessage(msg_handler, msg));
if (result.IsError()) {
status = ProcessUnhandledException(Error::Cast(result));
} else {
ASSERT(result.IsNull());
}
}
return status;
}
#ifndef PRODUCT
void IsolateMessageHandler::NotifyPauseOnStart() {
if (!FLAG_support_service || Isolate::IsVMInternalIsolate(I)) {
return;
}
if (Service::debug_stream.enabled() || FLAG_warn_on_pause_with_no_debugger) {
StartIsolateScope start_isolate(I);
StackZone zone(T);
HandleScope handle_scope(T);
ServiceEvent pause_event(I, ServiceEvent::kPauseStart);
Service::HandleEvent(&pause_event);
} else if (FLAG_trace_service) {
OS::PrintErr("vm-service: Dropping event of type PauseStart (%s)\n",
I->name());
}
}
void IsolateMessageHandler::NotifyPauseOnExit() {
if (!FLAG_support_service || Isolate::IsVMInternalIsolate(I)) {
return;
}
if (Service::debug_stream.enabled() || FLAG_warn_on_pause_with_no_debugger) {
StartIsolateScope start_isolate(I);
StackZone zone(T);
HandleScope handle_scope(T);
ServiceEvent pause_event(I, ServiceEvent::kPauseExit);
Service::HandleEvent(&pause_event);
} else if (FLAG_trace_service) {
OS::PrintErr("vm-service: Dropping event of type PauseExit (%s)\n",
I->name());
}
}
#endif // !PRODUCT
#if defined(DEBUG)
void IsolateMessageHandler::CheckAccess() {
ASSERT(IsCurrentIsolate());
}
#endif
bool IsolateMessageHandler::IsCurrentIsolate() const {
return (I == Isolate::Current());
}
static MessageHandler::MessageStatus StoreError(Thread* thread,
const Error& error) {
thread->set_sticky_error(error);
if (error.IsUnwindError()) {
const UnwindError& unwind = UnwindError::Cast(error);
if (!unwind.is_user_initiated()) {
return MessageHandler::kShutdown;
}
}
return MessageHandler::kError;
}
MessageHandler::MessageStatus IsolateMessageHandler::ProcessUnhandledException(
const Error& result) {
if (FLAG_trace_isolates) {
OS::PrintErr(
"[!] Unhandled exception in %s:\n"
" exception: %s\n",
T->isolate()->name(), result.ToErrorCString());
}
NoReloadScope no_reload_scope(T->isolate(), T);
// Generate the error and stacktrace strings for the error message.
String& exc_str = String::Handle(T->zone());
String& stacktrace_str = String::Handle(T->zone());
if (result.IsUnhandledException()) {
Zone* zone = T->zone();
const UnhandledException& uhe = UnhandledException::Cast(result);
const Instance& exception = Instance::Handle(zone, uhe.exception());
Object& tmp = Object::Handle(zone);
tmp = DartLibraryCalls::ToString(exception);
if (!tmp.IsString()) {
tmp = String::New(exception.ToCString());
}
exc_str ^= tmp.raw();
const Instance& stacktrace = Instance::Handle(zone, uhe.stacktrace());
tmp = DartLibraryCalls::ToString(stacktrace);
if (!tmp.IsString()) {
tmp = String::New(stacktrace.ToCString());
}
stacktrace_str ^= tmp.raw();
} else {
exc_str = String::New(result.ToErrorCString());
}
if (result.IsUnwindError()) {
// When unwinding we don't notify error listeners and we ignore
// whether errors are fatal for the current isolate.
return StoreError(T, result);
} else {
bool has_listener = I->NotifyErrorListeners(exc_str, stacktrace_str);
if (I->ErrorsFatal()) {
if (has_listener) {
T->ClearStickyError();
} else {
T->set_sticky_error(result);
}
#if !defined(PRODUCT)
// Notify the debugger about specific unhandled exceptions which are
// withheld when being thrown. Do this after setting the sticky error
// so the isolate has an error set when paused with the unhandled
// exception.
if (result.IsUnhandledException()) {
const UnhandledException& error = UnhandledException::Cast(result);
RawInstance* exception = error.exception();
if ((exception == I->object_store()->out_of_memory()) ||
(exception == I->object_store()->stack_overflow())) {
// We didn't notify the debugger when the stack was full. Do it now.
I->debugger()->PauseException(Instance::Handle(exception));
}
}
#endif // !defined(PRODUCT)
return kError;
}
}
return kOK;
}
void Isolate::FlagsInitialize(Dart_IsolateFlags* api_flags) {
const bool false_by_default = false;
const bool true_by_default = true;
USE(true_by_default);
USE(false_by_default);
api_flags->version = DART_FLAGS_CURRENT_VERSION;
#define INIT_FROM_FLAG(when, name, bitname, isolate_flag, flag) \
api_flags->isolate_flag = flag;
ISOLATE_FLAG_LIST(INIT_FROM_FLAG)
#undef INIT_FROM_FLAG
api_flags->entry_points = NULL;
api_flags->load_vmservice_library = false;
api_flags->copy_parent_code = false;
}
void Isolate::FlagsCopyTo(Dart_IsolateFlags* api_flags) const {
api_flags->version = DART_FLAGS_CURRENT_VERSION;
#define INIT_FROM_FIELD(when, name, bitname, isolate_flag, flag) \
api_flags->isolate_flag = name();
ISOLATE_FLAG_LIST(INIT_FROM_FIELD)
#undef INIT_FROM_FIELD
api_flags->entry_points = NULL;
api_flags->load_vmservice_library = should_load_vmservice();
api_flags->copy_parent_code = false;
}
void Isolate::FlagsCopyFrom(const Dart_IsolateFlags& api_flags) {
#if defined(DART_PRECOMPILER)
#define FLAG_FOR_PRECOMPILER(action) action
#else
#define FLAG_FOR_PRECOMPILER(action)
#endif
#if !defined(PRODUCT)
#define FLAG_FOR_NONPRODUCT(action) action
#else
#define FLAG_FOR_NONPRODUCT(action)
#endif
#define FLAG_FOR_PRODUCT(action) action
#define SET_FROM_FLAG(when, name, bitname, isolate_flag, flag) \
FLAG_FOR_##when(isolate_flags_ = bitname##Bit::update( \
api_flags.isolate_flag, isolate_flags_));
ISOLATE_FLAG_LIST(SET_FROM_FLAG)
#undef FLAG_FOR_NONPRODUCT
#undef FLAG_FOR_PRECOMPILER
#undef FLAG_FOR_PRODUCT
#undef SET_FROM_FLAG
set_should_load_vmservice(api_flags.load_vmservice_library);
// Copy entry points list.
ASSERT(embedder_entry_points_ == NULL);
if (api_flags.entry_points != NULL) {
intptr_t count = 0;
while (api_flags.entry_points[count].function_name != NULL)
count++;
embedder_entry_points_ = new Dart_QualifiedFunctionName[count + 1];
for (intptr_t i = 0; i < count; i++) {
embedder_entry_points_[i].library_uri =
strdup(api_flags.entry_points[i].library_uri);
embedder_entry_points_[i].class_name =
strdup(api_flags.entry_points[i].class_name);
embedder_entry_points_[i].function_name =
strdup(api_flags.entry_points[i].function_name);
}
memset(&embedder_entry_points_[count], 0,
sizeof(Dart_QualifiedFunctionName));
}
// Leave others at defaults.
}
#if defined(DEBUG)
// static
void BaseIsolate::AssertCurrent(BaseIsolate* isolate) {
ASSERT(isolate == Isolate::Current());
}
void BaseIsolate::AssertCurrentThreadIsMutator() const {
ASSERT(Isolate::Current() == this);
ASSERT(Thread::Current()->IsMutatorThread());
}
#endif // defined(DEBUG)
#if defined(DEBUG)
#define REUSABLE_HANDLE_SCOPE_INIT(object) \
reusable_##object##_handle_scope_active_(false),
#else
#define REUSABLE_HANDLE_SCOPE_INIT(object)
#endif // defined(DEBUG)
#define REUSABLE_HANDLE_INITIALIZERS(object) object##_handle_(nullptr),
// TODO(srdjan): Some Isolate monitors can be shared. Replace their usage with
// that shared monitor.
Isolate::Isolate(IsolateGroup* isolate_group,
const Dart_IsolateFlags& api_flags)
: BaseIsolate(),
current_tag_(UserTag::null()),
default_tag_(UserTag::null()),
ic_miss_code_(Code::null()),
shared_class_table_(new SharedClassTable()),
class_table_(shared_class_table_.get()),
field_table_(new FieldTable()),
store_buffer_(new StoreBuffer()),
#if !defined(DART_PRECOMPILED_RUNTIME)
native_callback_trampolines_(),
#endif
#if !defined(PRODUCT)
last_resume_timestamp_(OS::GetCurrentTimeMillis()),
vm_tag_counters_(),
pending_service_extension_calls_(GrowableObjectArray::null()),
registered_service_extension_handlers_(GrowableObjectArray::null()),
#define ISOLATE_METRIC_CONSTRUCTORS(type, variable, name, unit) \
metric_##variable##_(),
ISOLATE_METRIC_LIST(ISOLATE_METRIC_CONSTRUCTORS)
#undef ISOLATE_METRIC_CONSTRUCTORS
reload_every_n_stack_overflow_checks_(FLAG_reload_every),
#endif // !defined(PRODUCT)
start_time_micros_(OS::GetCurrentMonotonicMicros()),
random_(),
mutex_(NOT_IN_PRODUCT("Isolate::mutex_")),
symbols_mutex_(NOT_IN_PRODUCT("Isolate::symbols_mutex_")),
type_canonicalization_mutex_(
NOT_IN_PRODUCT("Isolate::type_canonicalization_mutex_")),
constant_canonicalization_mutex_(
NOT_IN_PRODUCT("Isolate::constant_canonicalization_mutex_")),
megamorphic_mutex_(NOT_IN_PRODUCT("Isolate::megamorphic_mutex_")),
kernel_data_lib_cache_mutex_(
NOT_IN_PRODUCT("Isolate::kernel_data_lib_cache_mutex_")),
kernel_data_class_cache_mutex_(
NOT_IN_PRODUCT("Isolate::kernel_data_class_cache_mutex_")),
kernel_constants_mutex_(
NOT_IN_PRODUCT("Isolate::kernel_constants_mutex_")),
pending_deopts_(new MallocGrowableArray<PendingLazyDeopt>()),
tag_table_(GrowableObjectArray::null()),
deoptimized_code_array_(GrowableObjectArray::null()),
sticky_error_(Error::null()),
field_list_mutex_(NOT_IN_PRODUCT("Isolate::field_list_mutex_")),
boxed_field_list_(GrowableObjectArray::null()),
spawn_count_monitor_(),
handler_info_cache_(),
catch_entry_moves_cache_() {
FlagsCopyFrom(api_flags);
SetErrorsFatal(true);
set_compilation_allowed(true);
// TODO(asiva): A Thread is not available here, need to figure out
// how the vm_tag (kEmbedderTagId) can be set, these tags need to
// move to the OSThread structure.
set_user_tag(UserTags::kDefaultUserTag);
if (obfuscate()) {
OS::PrintErr(
"Warning: This VM has been configured to obfuscate symbol information "
"which violates the Dart standard.\n"
" See dartbug.com/30524 for more information.\n");
}
if (FLAG_enable_interpreter) {
NOT_IN_PRECOMPILED(background_compiler_ = new BackgroundCompiler(
this, /* optimizing = */ false));
}
NOT_IN_PRECOMPILED(optimizing_background_compiler_ =
new BackgroundCompiler(this, /* optimizing = */ true));
isolate_group->RegisterIsolate(this);
isolate_group_ = isolate_group;
}
#undef REUSABLE_HANDLE_SCOPE_INIT
#undef REUSABLE_HANDLE_INITIALIZERS
Isolate::~Isolate() {
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
// TODO(32796): Re-enable assertion.
// RELEASE_ASSERT(reload_context_ == NULL);
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
delete reverse_pc_lookup_cache_;
reverse_pc_lookup_cache_ = nullptr;
delete dispatch_table_;
dispatch_table_ = nullptr;
if (FLAG_enable_interpreter) {
delete background_compiler_;
background_compiler_ = nullptr;
}
delete optimizing_background_compiler_;
optimizing_background_compiler_ = nullptr;
#if !defined(PRODUCT)
delete debugger_;
debugger_ = nullptr;
if (FLAG_support_service) {
delete object_id_ring_;
}
object_id_ring_ = nullptr;
delete pause_loop_monitor_;
pause_loop_monitor_ = nullptr;
#endif // !defined(PRODUCT)
free(name_);
delete store_buffer_;
delete heap_;
ASSERT(marking_stack_ == nullptr);
delete object_store_;
delete field_table_;
delete api_state_;
#if defined(USING_SIMULATOR)
delete simulator_;
#endif
delete pending_deopts_;
pending_deopts_ = nullptr;
delete message_handler_;
message_handler_ =
nullptr; // Fail fast if we send messages to a dead isolate.
ASSERT(deopt_context_ ==
nullptr); // No deopt in progress when isolate deleted.
ASSERT(spawn_count_ == 0);
// We have cached the mutator thread, delete it.
ASSERT(scheduled_mutator_thread_ == nullptr);
mutator_thread_->isolate_ = nullptr;
delete mutator_thread_;
mutator_thread_ = nullptr;
if (obfuscation_map_ != nullptr) {
for (intptr_t i = 0; obfuscation_map_[i] != nullptr; i++) {
delete[] obfuscation_map_[i];
}
delete[] obfuscation_map_;
}
if (embedder_entry_points_ != nullptr) {
for (intptr_t i = 0; embedder_entry_points_[i].function_name != nullptr;
i++) {
free(const_cast<char*>(embedder_entry_points_[i].library_uri));
free(const_cast<char*>(embedder_entry_points_[i].class_name));
free(const_cast<char*>(embedder_entry_points_[i].function_name));
}
delete[] embedder_entry_points_;
}
// Run isolate group specific cleanup function if the last isolate in an
// isolate group died.
isolate_group_->UnregisterIsolate(this);
isolate_group_ = nullptr;
}
void Isolate::InitVM() {
create_group_callback_ = nullptr;
initialize_callback_ = nullptr;
shutdown_callback_ = nullptr;
cleanup_callback_ = nullptr;
cleanup_group_callback_ = nullptr;
if (isolates_list_monitor_ == nullptr) {
isolates_list_monitor_ = new Monitor();
}
ASSERT(isolates_list_monitor_ != nullptr);
EnableIsolateCreation();
}
Isolate* Isolate::InitIsolate(const char* name_prefix,
IsolateGroup* isolate_group,
const Dart_IsolateFlags& api_flags,
bool is_vm_isolate) {
Isolate* result = new Isolate(isolate_group, api_flags);
ASSERT(result != nullptr);
#if !defined(PRODUCT)
// Initialize metrics.
#define ISOLATE_METRIC_INIT(type, variable, name, unit) \
result->metric_##variable##_.InitInstance(result, name, NULL, Metric::unit);
ISOLATE_METRIC_LIST(ISOLATE_METRIC_INIT);
#undef ISOLATE_METRIC_INIT
#endif // !defined(PRODUCT)
bool is_service_or_kernel_isolate = false;
if (ServiceIsolate::NameEquals(name_prefix)) {
ASSERT(!ServiceIsolate::Exists());
is_service_or_kernel_isolate = true;
}
#if !defined(DART_PRECOMPILED_RUNTIME)
if (KernelIsolate::NameEquals(name_prefix)) {
ASSERT(!KernelIsolate::Exists());
KernelIsolate::SetKernelIsolate(result);
is_service_or_kernel_isolate = true;
}
#endif // !defined(DART_PRECOMPILED_RUNTIME)
Heap::Init(result,
is_vm_isolate
? 0 // New gen size 0; VM isolate should only allocate in old.
: FLAG_new_gen_semi_max_size * MBInWords,
(is_service_or_kernel_isolate ? kDefaultMaxOldGenHeapSize
: FLAG_old_gen_heap_size) *
MBInWords);
// TODO(5411455): For now just set the recently created isolate as
// the current isolate.
if (!Thread::EnterIsolate(result)) {
// We failed to enter the isolate, it is possible the VM is shutting down,
// return back a NULL so that CreateIsolate reports back an error.
if (KernelIsolate::IsKernelIsolate(result)) {
KernelIsolate::SetKernelIsolate(nullptr);
}
if (ServiceIsolate::IsServiceIsolate(result)) {
ServiceIsolate::SetServiceIsolate(nullptr);
}
delete result;
return nullptr;
}
// Setup the isolate message handler.
MessageHandler* handler = new IsolateMessageHandler(result);
ASSERT(handler != nullptr);
result->set_message_handler(handler);
// Setup the Dart API state.
ApiState* state = new ApiState();
ASSERT(state != nullptr);
result->set_api_state(state);
result->set_main_port(PortMap::CreatePort(result->message_handler()));
#if defined(DEBUG)
// Verify that we are never reusing a live origin id.
VerifyOriginId id_verifier(result->main_port());
Isolate::VisitIsolates(&id_verifier);
#endif
result->set_origin_id(result->main_port());
result->set_pause_capability(result->random()->NextUInt64());
result->set_terminate_capability(result->random()->NextUInt64());
result->BuildName(name_prefix);
#if !defined(PRODUCT)
result->debugger_ = new Debugger(result);
#endif
if (FLAG_trace_isolates) {
if (name_prefix == nullptr || strcmp(name_prefix, "vm-isolate") != 0) {
OS::PrintErr(
"[+] Starting isolate:\n"
"\tisolate: %s\n",
result->name());
}
}
#ifndef PRODUCT
if (FLAG_support_service) {
ObjectIdRing::Init(result);
}
#endif // !PRODUCT
// Add to isolate list. Shutdown and delete the isolate on failure.
if (!AddIsolateToList(result)) {
result->LowLevelShutdown();
Thread::ExitIsolate();
if (KernelIsolate::IsKernelIsolate(result)) {
KernelIsolate::SetKernelIsolate(nullptr);
}
if (ServiceIsolate::IsServiceIsolate(result)) {
ServiceIsolate::SetServiceIsolate(nullptr);
}
delete result;
return nullptr;
}
return result;
}
Thread* Isolate::mutator_thread() const {
ASSERT(thread_registry() != nullptr);
return mutator_thread_;
}
RawObject* Isolate::CallTagHandler(Dart_LibraryTag tag,
const Object& arg1,
const Object& arg2) {
Thread* thread = Thread::Current();
Api::Scope api_scope(thread);
Dart_Handle api_arg1 = Api::NewHandle(thread, arg1.raw());
Dart_Handle api_arg2 = Api::NewHandle(thread, arg2.raw());
Dart_Handle api_result;
{
TransitionVMToNative transition(thread);
ASSERT(HasTagHandler());
api_result = group()->library_tag_handler()(tag, api_arg1, api_arg2);
}
return Api::UnwrapHandle(api_result);
}
void Isolate::SetupImagePage(const uint8_t* image_buffer, bool is_executable) {
Image image(image_buffer);
heap_->SetupImagePage(image.object_start(), image.object_size(),
is_executable);
}
void Isolate::ScheduleInterrupts(uword interrupt_bits) {
// We take the threads lock here to ensure that the mutator thread does not
// exit the isolate while we are trying to schedule interrupts on it.
MonitorLocker ml(threads_lock());
Thread* mthread = mutator_thread();
if (mthread != nullptr) {
mthread->ScheduleInterrupts(interrupt_bits);
}
}
void Isolate::set_name(const char* name) {
free(name_);
name_ = strdup(name);
}
int64_t Isolate::UptimeMicros() const {
return OS::GetCurrentMonotonicMicros() - start_time_micros_;
}
bool Isolate::IsPaused() const {
#if defined(PRODUCT)
return false;
#else
return (debugger_ != nullptr) && (debugger_->PauseEvent() != nullptr);
#endif // !defined(PRODUCT)
}
RawError* Isolate::PausePostRequest() {
#if !defined(PRODUCT)
if (debugger_ == nullptr) {
return Error::null();
}
ASSERT(!IsPaused());
const Error& error = Error::Handle(debugger_->PausePostRequest());
if (!error.IsNull()) {
if (Thread::Current()->top_exit_frame_info() == 0) {
return error.raw();
} else {
Exceptions::PropagateError(error);
UNREACHABLE();
}
}
#endif
return Error::null();
}
void Isolate::BuildName(const char* name_prefix) {
ASSERT(name_ == nullptr);
if (name_prefix == nullptr) {
name_ = OS::SCreate(nullptr, "isolate-%" Pd64 "", main_port());
} else {
name_ = strdup(name_prefix);
}
}
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
bool Isolate::CanReload() const {
return !Isolate::IsVMInternalIsolate(this) && is_runnable() &&
!group()->IsReloading() && (no_reload_scope_depth_ == 0) &&
IsolateCreationEnabled() &&
OSThread::Current()->HasStackHeadroom(64 * KB);
}
bool IsolateGroup::ReloadSources(JSONStream* js,
bool force_reload,
const char* root_script_url,
const char* packages_url,
bool dont_delete_reload_context) {
ASSERT(!IsReloading());
// TODO(dartbug.com/36097): Support multiple isolates within an isolate group.
RELEASE_ASSERT(!FLAG_enable_isolate_groups);
RELEASE_ASSERT(isolates_.First() == isolates_.Last());
RELEASE_ASSERT(isolates_.First() == Isolate::Current());
auto shared_class_table = Isolate::Current()->shared_class_table();
std::shared_ptr<IsolateGroupReloadContext> group_reload_context(
new IsolateGroupReloadContext(this, shared_class_table, js));
group_reload_context_ = group_reload_context;
ForEachIsolate([&](Isolate* isolate) {
isolate->SetHasAttemptedReload(true);
isolate->reload_context_ =
new IsolateReloadContext(group_reload_context_, isolate);
});
const bool success =
group_reload_context_->Reload(force_reload, root_script_url, packages_url,
/*kernel_buffer=*/nullptr,
/*kernel_buffer_size=*/0);
if (!dont_delete_reload_context) {
ForEachIsolate([&](Isolate* isolate) { isolate->DeleteReloadContext(); });
DeleteReloadContext();
}
return success;
}
bool IsolateGroup::ReloadKernel(JSONStream* js,
bool force_reload,
const uint8_t* kernel_buffer,
intptr_t kernel_buffer_size,
bool dont_delete_reload_context) {
ASSERT(!IsReloading());
// TODO(dartbug.com/36097): Support multiple isolates within an isolate group.
RELEASE_ASSERT(!FLAG_enable_isolate_groups);
RELEASE_ASSERT(isolates_.First() == isolates_.Last());
RELEASE_ASSERT(isolates_.First() == Isolate::Current());
auto shared_class_table = Isolate::Current()->shared_class_table();
std::shared_ptr<IsolateGroupReloadContext> group_reload_context(
new IsolateGroupReloadContext(this, shared_class_table, js));
group_reload_context_ = group_reload_context;
ForEachIsolate([&](Isolate* isolate) {
isolate->SetHasAttemptedReload(true);
isolate->reload_context_ =
new IsolateReloadContext(group_reload_context_, isolate);
});
const bool success = group_reload_context_->Reload(
force_reload,
/*root_script_url=*/nullptr,
/*packages_url=*/nullptr, kernel_buffer, kernel_buffer_size);
if (!dont_delete_reload_context) {
ForEachIsolate([&](Isolate* isolate) { isolate->DeleteReloadContext(); });
DeleteReloadContext();
}
return success;
}
void IsolateGroup::DeleteReloadContext() {
SafepointOperationScope safepoint_scope(Thread::Current());
group_reload_context_.reset();
}
void Isolate::DeleteReloadContext() {
// Another thread may be in the middle of GetClassForHeapWalkAt.
SafepointOperationScope safepoint_scope(Thread::Current());
delete reload_context_;
reload_context_ = nullptr;
}
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
const char* Isolate::MakeRunnable() {
ASSERT(Isolate::Current() == nullptr);
MutexLocker ml(&mutex_);
// Check if we are in a valid state to make the isolate runnable.
if (is_runnable() == true) {
return "Isolate is already runnable";
}
// Set the isolate as runnable and if we are being spawned schedule
// isolate on thread pool for execution.
ASSERT(object_store()->root_library() != Library::null());
set_is_runnable(true);
#ifndef PRODUCT
if (!Isolate::IsVMInternalIsolate(this)) {
debugger()->OnIsolateRunnable();
if (FLAG_pause_isolates_on_unhandled_exceptions) {
debugger()->SetExceptionPauseInfo(kPauseOnUnhandledExceptions);
}
}
#endif // !PRODUCT
IsolateSpawnState* state = spawn_state();
if (state != nullptr) {
ASSERT(this == state->isolate());
Run();
}
#if defined(SUPPORT_TIMELINE)
TimelineStream* stream = Timeline::GetIsolateStream();
ASSERT(stream != nullptr);
TimelineEvent* event = stream->StartEvent();
if (event != nullptr) {
event->Instant("Runnable");
event->Complete();
}
#endif
#ifndef PRODUCT
if (FLAG_support_service && !Isolate::IsVMInternalIsolate(this) &&
Service::isolate_stream.enabled()) {
ServiceEvent runnableEvent(this, ServiceEvent::kIsolateRunnable);
Service::HandleEvent(&runnableEvent);
}
GetRunnableLatencyMetric()->set_value(UptimeMicros());
if (FLAG_print_benchmarking_metrics) {
{
StartIsolateScope scope(this);
heap()->CollectAllGarbage();
}
int64_t heap_size = (heap()->UsedInWords(Heap::kNew) * kWordSize) +
(heap()->UsedInWords(Heap::kOld) * kWordSize);
GetRunnableHeapSizeMetric()->set_value(heap_size);
}
#endif // !PRODUCT
return nullptr;
}
bool Isolate::VerifyPauseCapability(const Object& capability) const {
return !capability.IsNull() && capability.IsCapability() &&
(pause_capability() == Capability::Cast(capability).Id());
}
bool Isolate::VerifyTerminateCapability(const Object& capability) const {
return !capability.IsNull() && capability.IsCapability() &&
(terminate_capability() == Capability::Cast(capability).Id());
}
bool Isolate::AddResumeCapability(const Capability& capability) {
// Ensure a limit for the number of resume capabilities remembered.
static const intptr_t kMaxResumeCapabilities =
compiler::target::kSmiMax / (6 * kWordSize);
const GrowableObjectArray& caps = GrowableObjectArray::Handle(
current_zone(), object_store()->resume_capabilities());
Capability& current = Capability::Handle(current_zone());
intptr_t insertion_index = -1;
for (intptr_t i = 0; i < caps.Length(); i++) {
current ^= caps.At(i);
if (current.IsNull()) {
if (insertion_index < 0) {
insertion_index = i;
}
} else if (current.Id() == capability.Id()) {
return false;
}
}
if (insertion_index < 0) {
if (caps.Length() >= kMaxResumeCapabilities) {
// Cannot grow the array of resume capabilities beyond its max. Additional
// pause requests are ignored. In practice will never happen as we will
// run out of memory beforehand.
return false;
}
caps.Add(capability);
} else {
caps.SetAt(insertion_index, capability);
}
return true;
}
bool Isolate::RemoveResumeCapability(const Capability& capability) {
const GrowableObjectArray& caps = GrowableObjectArray::Handle(
current_zone(), object_store()->resume_capabilities());
Capability& current = Capability::Handle(current_zone());
for (intptr_t i = 0; i < caps.Length(); i++) {
current ^= caps.At(i);
if (!current.IsNull() && (current.Id() == capability.Id())) {
// Remove the matching capability from the list.
current = Capability::null();
caps.SetAt(i, current);
return true;
}
}
return false;
}
// TODO(iposva): Remove duplicated code and start using some hash based
// structure instead of these linear lookups.
void Isolate::AddExitListener(const SendPort& listener,
const Instance& response) {
// Ensure a limit for the number of listeners remembered.
static const intptr_t kMaxListeners =
compiler::target::kSmiMax / (12 * kWordSize);
const GrowableObjectArray& listeners = GrowableObjectArray::Handle(
current_zone(), object_store()->exit_listeners());
SendPort& current = SendPort::Handle(current_zone());
intptr_t insertion_index = -1;
for (intptr_t i = 0; i < listeners.Length(); i += 2) {
current ^= listeners.At(i);
if (current.IsNull()) {
if (insertion_index < 0) {
insertion_index = i;
}
} else if (current.Id() == listener.Id()) {
listeners.SetAt(i + 1, response);
return;
}
}
if (insertion_index < 0) {
if (listeners.Length() >= kMaxListeners) {
// Cannot grow the array of listeners beyond its max. Additional
// listeners are ignored. In practice will never happen as we will
// run out of memory beforehand.
return;
}
listeners.Add(listener);
listeners.Add(response);
} else {
listeners.SetAt(insertion_index, listener);
listeners.SetAt(insertion_index + 1, response);
}
}
void Isolate::RemoveExitListener(const SendPort& listener) {
const GrowableObjectArray& listeners = GrowableObjectArray::Handle(
current_zone(), object_store()->exit_listeners());
SendPort& current = SendPort::Handle(current_zone());
for (intptr_t i = 0; i < listeners.Length(); i += 2) {
current ^= listeners.At(i);
if (!current.IsNull() && (current.Id() == listener.Id())) {
// Remove the matching listener from the list.
current = SendPort::null();
listeners.SetAt(i, current);
listeners.SetAt(i + 1, Object::null_instance());
return;
}
}
}
void Isolate::NotifyExitListeners() {
const GrowableObjectArray& listeners = GrowableObjectArray::Handle(
current_zone(), this->object_store()->exit_listeners());
if (listeners.IsNull()) return;
SendPort& listener = SendPort::Handle(current_zone());
Instance& response = Instance::Handle(current_zone());
for (intptr_t i = 0; i < listeners.Length(); i += 2) {
listener ^= listeners.At(i);
if (!listener.IsNull()) {
Dart_Port port_id = listener.Id();
response ^= listeners.At(i + 1);
PortMap::PostMessage(SerializeMessage(port_id, response));
}
}
}
void Isolate::AddErrorListener(const SendPort& listener) {
// Ensure a limit for the number of listeners remembered.
static const intptr_t kMaxListeners =
compiler::target::kSmiMax / (6 * kWordSize);
const GrowableObjectArray& listeners = GrowableObjectArray::Handle(
current_zone(), object_store()->error_listeners());
SendPort& current = SendPort::Handle(current_zone());
intptr_t insertion_index = -1;
for (intptr_t i = 0; i < listeners.Length(); i++) {
current ^= listeners.At(i);
if (current.IsNull()) {
if (insertion_index < 0) {
insertion_index = i;
}
} else if (current.Id() == listener.Id()) {
return;
}
}
if (insertion_index < 0) {
if (listeners.Length() >= kMaxListeners) {
// Cannot grow the array of listeners beyond its max. Additional
// listeners are ignored. In practice will never happen as we will
// run out of memory beforehand.
return;
}
listeners.Add(listener);
} else {
listeners.SetAt(insertion_index, listener);
}
}
void Isolate::RemoveErrorListener(const SendPort& listener) {
const GrowableObjectArray& listeners = GrowableObjectArray::Handle(
current_zone(), object_store()->error_listeners());
SendPort& current = SendPort::Handle(current_zone());
for (intptr_t i = 0; i < listeners.Length(); i++) {
current ^= listeners.At(i);
if (!current.IsNull() && (current.Id() == listener.Id())) {
// Remove the matching listener from the list.
current = SendPort::null();
listeners.SetAt(i, current);
return;
}
}
}
bool Isolate::NotifyErrorListeners(const String& msg,
const String& stacktrace) {
const GrowableObjectArray& listeners = GrowableObjectArray::Handle(
current_zone(), this->object_store()->error_listeners());
if (listeners.IsNull()) return false;
const Array& arr = Array::Handle(current_zone(), Array::New(2));
arr.SetAt(0, msg);
arr.SetAt(1, stacktrace);
SendPort& listener = SendPort::Handle(current_zone());
for (intptr_t i = 0; i < listeners.Length(); i++) {
listener ^= listeners.At(i);
if (!listener.IsNull()) {
Dart_Port port_id = listener.Id();
PortMap::PostMessage(SerializeMessage(port_id, arr));
}
}
return listeners.Length() > 0;
}
static MessageHandler::MessageStatus RunIsolate(uword parameter) {
Isolate* isolate = reinterpret_cast<Isolate*>(parameter);
IsolateSpawnState* state = nullptr;
{
// TODO(turnidge): Is this locking required here at all anymore?
MutexLocker ml(isolate->mutex());
state = isolate->spawn_state();
}
{
StartIsolateScope start_scope(isolate);
Thread* thread = Thread::Current();
ASSERT(thread->isolate() == isolate);
StackZone zone(thread);
HandleScope handle_scope(thread);
// If particular values were requested for this newly spawned isolate, then
// they are set here before the isolate starts executing user code.
isolate->SetErrorsFatal(state->errors_are_fatal());
if (state->on_exit_port() != ILLEGAL_PORT) {
const SendPort& listener =
SendPort::Handle(SendPort::New(state->on_exit_port()));
isolate->AddExitListener(listener, Instance::null_instance());
}
if (state->on_error_port() != ILLEGAL_PORT) {
const SendPort& listener =
SendPort::Handle(SendPort::New(state->on_error_port()));
isolate->AddErrorListener(listener);
}
// Switch back to spawning isolate.
if (!ClassFinalizer::ProcessPendingClasses()) {
// Error is in sticky error already.
#if defined(DEBUG)
const Error& error = Error::Handle(thread->sticky_error());
ASSERT(!error.IsUnwindError());
#endif
return MessageHandler::kError;
}
Object& result = Object::Handle();
result = state->ResolveFunction();
bool is_spawn_uri = state->is_spawn_uri();
if (result.IsError()) {
return StoreError(thread, Error::Cast(result));
}
ASSERT(result.IsFunction());
Function& func = Function::Handle(thread->zone());
func ^= result.raw();
func = func.ImplicitClosureFunction();
const Array& capabilities = Array::Handle(Array::New(2));
Capability& capability = Capability::Handle();
capability = Capability::New(isolate->pause_capability());
capabilities.SetAt(0, capability);
// Check whether this isolate should be started in paused state.
if (state->paused()) {
bool added = isolate->AddResumeCapability(capability);
ASSERT(added); // There should be no pending resume capabilities.
isolate->message_handler()->increment_paused();
}
capability = Capability::New(isolate->terminate_capability());
capabilities.SetAt(1, capability);
// Instead of directly invoking the entry point we call '_startIsolate' with
// the entry point as argument.
// Since this function ("RunIsolate") is used for both Isolate.spawn and
// Isolate.spawnUri we also send a boolean flag as argument so that the
// "_startIsolate" function can act corresponding to how the isolate was
// created.
const Array& args = Array::Handle(Array::New(7));
args.SetAt(0, SendPort::Handle(SendPort::New(state->parent_port())));
args.SetAt(1, Instance::Handle(func.ImplicitStaticClosure()));
args.SetAt(2, Instance::Handle(state->BuildArgs(thread)));
args.SetAt(3, Instance::Handle(state->BuildMessage(thread)));
args.SetAt(4, is_spawn_uri ? Bool::True() : Bool::False());
args.SetAt(5, ReceivePort::Handle(ReceivePort::New(
isolate->main_port(), true /* control port */)));
args.SetAt(6, capabilities);
const Library& lib = Library::Handle(Library::IsolateLibrary());
const String& entry_name = String::Handle(String::New("_startIsolate"));
const Function& entry_point =
Function::Handle(lib.LookupLocalFunction(entry_name));
ASSERT(entry_point.IsFunction() && !entry_point.IsNull());
result = DartEntry::InvokeFunction(entry_point, args);
if (result.IsError()) {
return StoreError(thread, Error::Cast(result));
}
}
return MessageHandler::kOK;
}
static void ShutdownIsolate(uword parameter) {
Isolate* isolate = reinterpret_cast<Isolate*>(parameter);
{
// Print the error if there is one. This may execute dart code to
// print the exception object, so we need to use a StartIsolateScope.
StartIsolateScope start_scope(isolate);
Thread* thread = Thread::Current();
ASSERT(thread->isolate() == isolate);
// We must wait for any outstanding spawn calls to complete before
// running the shutdown callback.
isolate->WaitForOutstandingSpawns();
StackZone zone(thread);
HandleScope handle_scope(thread);
#if defined(DEBUG)
isolate->ValidateConstants();
#endif // defined(DEBUG)
Dart::RunShutdownCallback();
}
// Shut the isolate down.
Dart::ShutdownIsolate(isolate);
}
void Isolate::SetStickyError(RawError* sticky_error) {
ASSERT(
((sticky_error_ == Error::null()) || (sticky_error == Error::null())) &&
(sticky_error != sticky_error_));
sticky_error_ = sticky_error;
}
void Isolate::Run() {
message_handler()->Run(Dart::thread_pool(), RunIsolate, ShutdownIsolate,
reinterpret_cast<uword>(this));
}
void Isolate::AddClosureFunction(const Function& function) const {
ASSERT(!Compiler::IsBackgroundCompilation());
GrowableObjectArray& closures =
GrowableObjectArray::Handle(object_store()->closure_functions());
ASSERT(!closures.IsNull());
ASSERT(function.IsNonImplicitClosureFunction());
closures.Add(function, Heap::kOld);
}
// If the linear lookup turns out to be too expensive, the list
// of closures could be maintained in a hash map, with the key
// being the token position of the closure. There are almost no
// collisions with this simple hash value. However, iterating over
// all closure functions becomes more difficult, especially when
// the list/map changes while iterating over it.
RawFunction* Isolate::LookupClosureFunction(const Function& parent,
TokenPosition token_pos) const {
const GrowableObjectArray& closures =
GrowableObjectArray::Handle(object_store()->closure_functions());
ASSERT(!closures.IsNull());
Function& closure = Function::Handle();
intptr_t num_closures = closures.Length();
for (intptr_t i = 0; i < num_closures; i++) {
closure ^= closures.At(i);
if ((closure.token_pos() == token_pos) &&
(closure.parent_function() == parent.raw())) {
return closure.raw();
}
}
return Function::null();
}
intptr_t Isolate::FindClosureIndex(const Function& needle) const {
const GrowableObjectArray& closures_array =
GrowableObjectArray::Handle(object_store()->closure_functions());
intptr_t num_closures = closures_array.Length();
for (intptr_t i = 0; i < num_closures; i++) {
if (closures_array.At(i) == needle.raw()) {
return i;
}
}
return -1;
}
RawFunction* Isolate::ClosureFunctionFromIndex(intptr_t idx) const {
const GrowableObjectArray& closures_array =
GrowableObjectArray::Handle(object_store()->closure_functions());
if ((idx < 0) || (idx >= closures_array.Length())) {
return Function::null();
}
return Function::RawCast(closures_array.At(idx));
}
class FinalizeWeakPersistentHandlesVisitor : public HandleVisitor {
public:
FinalizeWeakPersistentHandlesVisitor() : HandleVisitor(Thread::Current()) {}
void VisitHandle(uword addr) {
FinalizablePersistentHandle* handle =
reinterpret_cast<FinalizablePersistentHandle*>(addr);
handle->UpdateUnreachable(thread()->isolate());
}
private:
DISALLOW_COPY_AND_ASSIGN(FinalizeWeakPersistentHandlesVisitor);
};
// static
void Isolate::NotifyLowMemory() {
Isolate::KillAllIsolates(Isolate::kLowMemoryMsg);
}
void Isolate::LowLevelShutdown() {
// Ensure we have a zone and handle scope so that we can call VM functions,
// but we no longer allocate new heap objects.
Thread* thread = Thread::Current();
StackZone stack_zone(thread);
HandleScope handle_scope(thread);
NoSafepointScope no_safepoint_scope;
// Notify exit listeners that this isolate is shutting down.
if (object_store() != nullptr) {
const Error& error = Error::Handle(thread->sticky_error());
if (error.IsNull() || !error.IsUnwindError() ||
UnwindError::Cast(error).is_user_initiated()) {
NotifyExitListeners();
}
}
// Close all the ports owned by this isolate.
PortMap::ClosePorts(message_handler());
// Fail fast if anybody tries to post any more messages to this isolate.
delete message_handler();
set_message_handler(nullptr);
#if defined(SUPPORT_TIMELINE)
// Before analyzing the isolate's timeline blocks- reclaim all cached
// blocks.
Timeline::ReclaimCachedBlocksFromThreads();
#endif
// Dump all timing data for the isolate.
#if defined(SUPPORT_TIMELINE) && !defined(PRODUCT)
if (FLAG_timing) {
TimelinePauseTrace tpt;
tpt.Print();
}
#endif // !PRODUCT
// Finalize any weak persistent handles with a non-null referent.
FinalizeWeakPersistentHandlesVisitor visitor;
api_state()->weak_persistent_handles().VisitHandles(&visitor);
#if !defined(PRODUCT)
if (FLAG_dump_megamorphic_stats) {
MegamorphicCacheTable::PrintSizes(this);
}
if (FLAG_dump_symbol_stats) {
Symbols::DumpStats(this);
}
if (FLAG_trace_isolates) {
heap()->PrintSizes();
OS::PrintErr(
"[-] Stopping isolate:\n"
"\tisolate: %s\n",
name());
}
if (FLAG_print_metrics || FLAG_print_benchmarking_metrics) {
LogBlock lb;
OS::PrintErr("Printing metrics for %s\n", name());
#define ISOLATE_METRIC_PRINT(type, variable, name, unit) \
OS::PrintErr("%s\n", metric_##variable##_.ToString());
ISOLATE_METRIC_LIST(ISOLATE_METRIC_PRINT)
#undef ISOLATE_METRIC_PRINT
OS::PrintErr("\n");
}
#endif // !defined(PRODUCT)
}
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
void Isolate::MaybeIncreaseReloadEveryNStackOverflowChecks() {
if (FLAG_reload_every_back_off) {
if (reload_every_n_stack_overflow_checks_ < 5000) {
reload_every_n_stack_overflow_checks_ += 99;
} else {
reload_every_n_stack_overflow_checks_ *= 2;
}
// Cap the value.
if (reload_every_n_stack_overflow_checks_ > 1000000) {
reload_every_n_stack_overflow_checks_ = 1000000;
}
}
}
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
void Isolate::set_forward_table_new(WeakTable* table) {
std::unique_ptr<WeakTable> value(table);
forward_table_new_ = std::move(value);
}
void Isolate::set_forward_table_old(WeakTable* table) {
std::unique_ptr<WeakTable> value(table);
forward_table_old_ = std::move(value);
}
void Isolate::Shutdown() {
ASSERT(this == Isolate::Current());
BackgroundCompiler::Stop(this);
if (FLAG_enable_interpreter) {
delete background_compiler_;
background_compiler_ = nullptr;
}
delete optimizing_background_compiler_;
optimizing_background_compiler_ = nullptr;
Thread* thread = Thread::Current();
// Don't allow anymore dart code to execution on this isolate.
thread->ClearStackLimit();
// Remove this isolate from the list *before* we start tearing it down, to
// avoid exposing it in a state of decay.
RemoveIsolateFromList(this);
{
// After removal from isolate list. Before tearing down the heap.
StackZone zone(thread);
HandleScope handle_scope(thread);
ServiceIsolate::SendIsolateShutdownMessage();
KernelIsolate::NotifyAboutIsolateShutdown(this);
#if !defined(PRODUCT)
debugger()->Shutdown();
#endif
}
if (heap_ != nullptr) {
// Wait for any concurrent GC tasks to finish before shutting down.
// TODO(rmacnak): Interrupt tasks for faster shutdown.
PageSpace* old_space = heap_->old_space();
MonitorLocker ml(old_space->tasks_lock());
while (old_space->tasks() > 0) {
ml.Wait();
}
// Needs to happen before ~PageSpace so TLS and the thread registery are
// still valid.
old_space->AbandonMarkingForShutdown();
}
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
if (FLAG_check_reloaded && is_runnable() &&
!Isolate::IsVMInternalIsolate(this)) {
if (!HasAttemptedReload()) {
FATAL(
"Isolate did not reload before exiting and "
"--check-reloaded is enabled.\n");
}
}
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
// Then, proceed with low-level teardown.
LowLevelShutdown();
#if defined(DEBUG)
// No concurrent sweeper tasks should be running at this point.
if (heap_ != nullptr) {
PageSpace* old_space = heap_->old_space();
MonitorLocker ml(old_space->tasks_lock());
ASSERT(old_space->tasks() == 0);
}
#endif
// TODO(5411455): For now just make sure there are no current isolates
// as we are shutting down the isolate.
Thread::ExitIsolate();
// Run isolate specific cleanup function for all non "vm-isolate's.
if (Dart::vm_isolate() != this) {
Dart_IsolateCleanupCallback cleanup = Isolate::CleanupCallback();
if (cleanup != nullptr) {
cleanup(isolate_group_->embedder_data(), init_callback_data());
}
}
}
Dart_InitializeIsolateCallback Isolate::initialize_callback_ = nullptr;
Dart_IsolateGroupCreateCallback Isolate::create_group_callback_ = nullptr;
Dart_IsolateShutdownCallback Isolate::shutdown_callback_ = nullptr;
Dart_IsolateCleanupCallback Isolate::cleanup_callback_ = nullptr;
Dart_IsolateGroupCleanupCallback Isolate::cleanup_group_callback_ = nullptr;
Monitor* Isolate::isolates_list_monitor_ = nullptr;
Isolate* Isolate::isolates_list_head_ = nullptr;
bool Isolate::creation_enabled_ = false;
RwLock* IsolateGroup::isolate_groups_rwlock_ = nullptr;
IntrusiveDList<IsolateGroup>* IsolateGroup::isolate_groups_ = nullptr;
void Isolate::VisitObjectPointers(ObjectPointerVisitor* visitor,
ValidationPolicy validate_frames) {
ASSERT(visitor != nullptr);
// Visit objects in the object store.
object_store()->VisitObjectPointers(visitor);
// Visit objects in the class table.
class_table()->VisitObjectPointers(visitor);
// Visit objects in the field table.
field_table()->VisitObjectPointers(visitor);
// Visit the dart api state for all local and persistent handles.
if (api_state() != nullptr) {
api_state()->VisitObjectPointers(visitor);
}
visitor->clear_gc_root_type();
// Visit the objects directly referenced from the isolate structure.
visitor->VisitPointer(reinterpret_cast<RawObject**>(¤t_tag_));
visitor->VisitPointer(reinterpret_cast<RawObject**>(&default_tag_));
visitor->VisitPointer(reinterpret_cast<RawObject**>(&ic_miss_code_));
visitor->VisitPointer(reinterpret_cast<RawObject**>(&tag_table_));
visitor->VisitPointer(
reinterpret_cast<RawObject**>(&deoptimized_code_array_));
visitor->VisitPointer(reinterpret_cast<RawObject**>(&sticky_error_));
#if !defined(PRODUCT)
visitor->VisitPointer(
reinterpret_cast<RawObject**>(&pending_service_extension_calls_));
visitor->VisitPointer(
reinterpret_cast<RawObject**>(®istered_service_extension_handlers_));
#endif // !defined(PRODUCT)
// Visit the boxed_field_list_.
// 'boxed_field_list_' access via mutator and background compilation threads
// is guarded with a monitor. This means that we can visit it only
// when at safepoint or the field_list_mutex_ lock has been taken.
visitor->VisitPointer(reinterpret_cast<RawObject**>(&boxed_field_list_));
if (background_compiler() != nullptr) {
background_compiler()->VisitPointers(visitor);
}
if (optimizing_background_compiler() != nullptr) {
optimizing_background_compiler()->VisitPointers(visitor);
}
#if !defined(PRODUCT)
// Visit objects in the debugger.
debugger()->VisitObjectPointers(visitor);
#if !defined(DART_PRECOMPILED_RUNTIME)
// Visit objects that are being used for isolate reload.
if (reload_context() != nullptr) {
reload_context()->VisitObjectPointers(visitor);
reload_context()->group_reload_context()->VisitObjectPointers(visitor);
}
#endif // !defined(DART_PRECOMPILED_RUNTIME)
if (ServiceIsolate::IsServiceIsolate(this)) {
ServiceIsolate::VisitObjectPointers(visitor);
}
#endif // !defined(PRODUCT)
#if !defined(DART_PRECOMPILED_RUNTIME)
// Visit objects that are being used for deoptimization.
if (deopt_context() != nullptr) {
deopt_context()->VisitObjectPointers(visitor);
}
#endif // !defined(DART_PRECOMPILED_RUNTIME)
VisitStackPointers(visitor, validate_frames);
}
void Isolate::VisitStackPointers(ObjectPointerVisitor* visitor,
ValidationPolicy validate_frames) {
visitor->set_gc_root_type("stack");
// Visit objects in all threads (e.g., Dart stack, handles in zones).
thread_registry()->VisitObjectPointers(this, visitor, validate_frames);
// Visit mutator thread, even if the isolate isn't entered/scheduled (there
// might be live API handles to visit).
if (mutator_thread_ != nullptr) {
mutator_thread_->VisitObjectPointers(visitor, validate_frames);
}
visitor->clear_gc_root_type();
}
void Isolate::VisitWeakPersistentHandles(HandleVisitor* visitor) {
if (api_state() != nullptr) {
api_state()->VisitWeakHandles(visitor);
}
}
void Isolate::ReleaseStoreBuffers() {
thread_registry()->ReleaseStoreBuffers(this);
}
void Isolate::EnableIncrementalBarrier(MarkingStack* marking_stack,
MarkingStack* deferred_marking_stack) {
ASSERT(marking_stack_ == nullptr);
marking_stack_ = marking_stack;
deferred_marking_stack_ = deferred_marking_stack;
thread_registry()->AcquireMarkingStacks(this);
ASSERT(Thread::Current()->is_marking());
}
void Isolate::DisableIncrementalBarrier() {
thread_registry()->ReleaseMarkingStacks(this);
ASSERT(marking_stack_ != nullptr);
marking_stack_ = nullptr;
deferred_marking_stack_ = nullptr;
ASSERT(!Thread::Current()->is_marking());
}
void IsolateGroup::ForEachIsolate(
std::function<void(Isolate* isolate)> function) {
ReadRwLocker wl(ThreadState::Current(), isolates_rwlock_.get());
for (Isolate* isolate : isolates_) {
function(isolate);
}
}
void IsolateGroup::RunWithStoppedMutators(
std::function<void()> single_current_mutator,
std::function<void()> otherwise,
bool use_force_growth_in_otherwise) {
auto thread = Thread::Current();
ReadRwLocker wl(thread, isolates_rwlock_.get());
const bool only_one_isolate = isolates_.First() == isolates_.Last();
if (thread->IsMutatorThread() && only_one_isolate) {
single_current_mutator();
} else {
// We use the more strict safepoint operation scope here (which ensures that
// all other threads, including auxiliary threads are at a safepoint), even
// though we only need to ensure that the mutator threads are stopped.
if (use_force_growth_in_otherwise) {
ForceGrowthSafepointOperationScope safepoint_scope(thread);
otherwise();
} else {
SafepointOperationScope safepoint_scope(thread);
otherwise();
}
}
}
RawClass* Isolate::GetClassForHeapWalkAt(intptr_t cid) {
RawClass* raw_class = nullptr;
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
if (group()->IsReloading()) {
raw_class = reload_context()->GetClassForHeapWalkAt(cid);
} else {
raw_class = class_table()->At(cid);
}
#else
raw_class = class_table()->At(cid);
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
ASSERT(raw_class != nullptr);
ASSERT(remapping_cids() || raw_class->ptr()->id_ == cid);
return raw_class;
}
intptr_t Isolate::GetClassSizeForHeapWalkAt(intptr_t cid) {
#if !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
if (group()->IsReloading()) {
return group()->reload_context()->GetClassSizeForHeapWalkAt(cid);
} else {
return class_table()->SizeAt(cid);
}
#else
return class_table()->SizeAt(cid);
#endif // !defined(PRODUCT) && !defined(DART_PRECOMPILED_RUNTIME)
}
void Isolate::AddPendingDeopt(uword fp, uword pc) {
// GrowableArray::Add is not atomic and may be interrupt by a profiler
// stack walk.
MallocGrowableArray<PendingLazyDeopt>* old_pending_deopts = pending_deopts_;
MallocGrowableArray<PendingLazyDeopt>* new_pending_deopts =
new MallocGrowableArray<PendingLazyDeopt>(old_pending_deopts->length() +
1);
for (intptr_t i = 0; i < old_pending_deopts->length(); i++) {
ASSERT((*old_pending_deopts)[i].fp() != fp);
new_pending_deopts->Add((*old_pending_deopts)[i]);
}
PendingLazyDeopt deopt(fp, pc);
new_pending_deopts->Add(deopt);
pending_deopts_ = new_pending_deopts;
delete old_pending_deopts;
}
uword Isolate::FindPendingDeopt(uword fp) const {
for (intptr_t i = 0; i < pending_deopts_->length(); i++) {
if ((*pending_deopts_)[i].fp() == fp) {
return (*pending_deopts_)[i].pc();
}
}
FATAL("Missing pending deopt entry");
return 0;
}
void Isolate::ClearPendingDeoptsAtOrBelow(uword fp) const {
for (intptr_t i = pending_deopts_->length() - 1; i >= 0; i--) {
if ((*pending_deopts_)[i].fp() <= fp) {
pending_deopts_->RemoveAt(i);
}
}
}
#ifndef PRODUCT
static const char* ExceptionPauseInfoToServiceEnum(Dart_ExceptionPauseInfo pi) {
switch (pi) {
case kPauseOnAllExceptions:
return "All";
case kNoPauseOnExceptions:
return "None";
case kPauseOnUnhandledExceptions:
return "Unhandled";
default:
UNIMPLEMENTED();
return nullptr;
}
}
void Isolate::PrintJSON(JSONStream* stream, bool ref) {
if (!FLAG_support_service) {
return;
}
JSONObject jsobj(stream);
jsobj.AddProperty("type", (ref ? "@Isolate" : "Isolate"));
jsobj.AddServiceId(ISOLATE_SERVICE_ID_FORMAT_STRING,
static_cast<int64_t>(main_port()));
jsobj.AddProperty("name", name());
jsobj.AddPropertyF("number", "%" Pd64 "", static_cast<int64_t>(main_port()));
if (ref) {
return;
}
jsobj.AddPropertyF("_originNumber", "%" Pd64 "",
static_cast<int64_t>(origin_id()));
int64_t uptime_millis = UptimeMicros() / kMicrosecondsPerMillisecond;
int64_t start_time = OS::GetCurrentTimeMillis() - uptime_millis;
jsobj.AddPropertyTimeMillis("startTime", start_time);
{
JSONObject jsheap(&jsobj, "_heaps");
heap()->PrintToJSONObject(Heap::kNew, &jsheap);
heap()->PrintToJSONObject(Heap::kOld, &jsheap);
}
jsobj.AddProperty("runnable", is_runnable());
jsobj.AddProperty("livePorts", message_handler()->live_ports());
jsobj.AddProperty("pauseOnExit", message_handler()->should_pause_on_exit());
#if !defined(DART_PRECOMPILED_RUNTIME)
jsobj.AddProperty("_isReloading", group()->IsReloading());
#endif // !defined(DART_PRECOMPILED_RUNTIME)
if (!is_runnable()) {
// Isolate is not yet runnable.
ASSERT((debugger() == nullptr) || (debugger()->PauseEvent() == nullptr));
ServiceEvent pause_event(this, ServiceEvent::kNone);
jsobj.AddProperty("pauseEvent", &pause_event);
} else if (message_handler()->should_pause_on_start()) {
if (message_handler()->is_paused_on_start()) {
ASSERT((debugger() == nullptr) || (debugger()->PauseEvent() == nullptr));
ServiceEvent pause_event(this, ServiceEvent::kPauseStart);
jsobj.AddProperty("pauseEvent", &pause_event);
} else {
// Isolate is runnable but not paused on start.
// Some service clients get confused if they see:
// NotRunnable -> Runnable -> PausedAtStart
// Treat Runnable+ShouldPauseOnStart as NotRunnable so they see:
// NonRunnable -> PausedAtStart
// The should_pause_on_start flag is set to false after resume.
ASSERT((debugger() == nullptr) || (debugger()->PauseEvent() == nullptr));
ServiceEvent pause_event(this, ServiceEvent::kNone);
jsobj.AddProperty("pauseEvent", &pause_event);
}
} else if (message_handler()->is_paused_on_exit() &&
((debugger() == nullptr) ||
(debugger()->PauseEvent() == nullptr))) {
ServiceEvent pause_event(this, ServiceEvent::kPauseExit);
jsobj.AddProperty("pauseEvent", &pause_event);
} else if ((debugger() != nullptr) && (debugger()->PauseEvent() != nullptr) &&
!ResumeRequest()) {
jsobj.AddProperty("pauseEvent", debugger()->PauseEvent());
} else {
ServiceEvent pause_event(this, ServiceEvent::kResume);
if (debugger() != nullptr) {
// TODO(turnidge): Don't compute a full stack trace.
DebuggerStackTrace* stack = debugger()->StackTrace();
if (stack->Length() > 0) {
pause_event.set_top_frame(stack->FrameAt(0));
}
}
jsobj.AddProperty("pauseEvent", &pause_event);
}
const Library& lib = Library::Handle(object_store()->root_library());
if (!lib.IsNull()) {
jsobj.AddProperty("rootLib", lib);
}
intptr_t zone_handle_count = thread_registry()->CountZoneHandles(this);
intptr_t scoped_handle_count = thread_registry()->CountScopedHandles(this);
jsobj.AddProperty("_numZoneHandles", zone_handle_count);
jsobj.AddProperty("_numScopedHandles", scoped_handle_count);
if (FLAG_profiler) {
JSONObject tagCounters(&jsobj, "_tagCounters");
vm_tag_counters()->PrintToJSONObject(&tagCounters);
}
if (Thread::Current()->sticky_error() != Object::null()) {
Error& error = Error::Handle(Thread::Current()->sticky_error());
ASSERT(!error.IsNull());
jsobj.AddProperty("error", error, false);
} else if (sticky_error() != Object::null()) {
Error& error = Error::Handle(sticky_error());
ASSERT(!error.IsNull());
jsobj.AddProperty("error", error, false);
}
{
const GrowableObjectArray& libs =
GrowableObjectArray::Handle(object_store()->libraries());
intptr_t num_libs = libs.Length();
Library& lib = Library::Handle();
JSONArray lib_array(&jsobj, "libraries");
for (intptr_t i = 0; i < num_libs; i++) {
lib ^= libs.At(i);
ASSERT(!lib.IsNull());
lib_array.AddValue(lib);
}
}
{
JSONArray breakpoints(&jsobj, "breakpoints");
if (debugger() != nullptr) {
debugger()->PrintBreakpointsToJSONArray(&breakpoints);
}
}
Dart_ExceptionPauseInfo pause_info = (debugger() != nullptr)
? debugger()->GetExceptionPauseInfo()
: kNoPauseOnExceptions;
jsobj.AddProperty("exceptionPauseMode",
ExceptionPauseInfoToServiceEnum(pause_info));
if (debugger() != nullptr) {
JSONObject settings(&jsobj, "_debuggerSettings");
debugger()->PrintSettingsToJSONObject(&settings);
}
{
GrowableObjectArray& handlers =
GrowableObjectArray::Handle(registered_service_extension_handlers());
if (!handlers.IsNull()) {
JSONArray extensions(&jsobj, "extensionRPCs");
String& handler_name = String::Handle();
for (intptr_t i = 0; i < handlers.Length(); i += kRegisteredEntrySize) {
handler_name ^= handlers.At(i + kRegisteredNameIndex);
extensions.AddValue(handler_name.ToCString());
}
}
}
jsobj.AddProperty("_threads", thread_registry());
{
JSONObject isolate_group(&jsobj, "isolate_group");
group()->PrintToJSONObject(&isolate_group, /*ref=*/true);
}
}
void Isolate::PrintMemoryUsageJSON(JSONStream* stream) {
if (!FLAG_support_service) {
return;
}
heap()->PrintMemoryUsageJSON(stream);
}
#endif
void Isolate::set_tag_table(const GrowableObjectArray& value) {
tag_table_ = value.raw();
}
void Isolate::set_current_tag(const UserTag& tag) {
uword user_tag = tag.tag();
ASSERT(user_tag < kUwordMax);
set_user_tag(user_tag);
current_tag_ = tag.raw();
}
void Isolate::set_default_tag(const UserTag& tag) {
default_tag_ = tag.raw();
}
void Isolate::set_ic_miss_code(const Code& code) {
ic_miss_code_ = code.raw();
}
void Isolate::set_deoptimized_code_array(const GrowableObjectArray& value) {
ASSERT(Thread::Current()->IsMutatorThread());
deoptimized_code_array_ = value.raw();
}
void Isolate::TrackDeoptimizedCode(const Code& code) {
ASSERT(!code.IsNull());
const GrowableObjectArray& deoptimized_code =
GrowableObjectArray::Handle(deoptimized_code_array());
if (deoptimized_code.IsNull()) {
// Not tracking deoptimized code.
return;
}
// TODO(johnmccutchan): Scan this array and the isolate's profile before
// old space GC and remove the keep_code flag.
deoptimized_code.Add(code);
}
RawError* Isolate::StealStickyError() {
NoSafepointScope no_safepoint;
RawError* return_value = sticky_error_;
sticky_error_ = Error::null();
return return_value;
}
#if !defined(PRODUCT)
void Isolate::set_pending_service_extension_calls(
const GrowableObjectArray& value) {
pending_service_extension_calls_ = value.raw();
}
void Isolate::set_registered_service_extension_handlers(
const GrowableObjectArray& value) {
registered_service_extension_handlers_ = value.raw();
}
#endif // !defined(PRODUCT)
void Isolate::AddDeoptimizingBoxedField(const Field& field) {
ASSERT(Compiler::IsBackgroundCompilation());
ASSERT(!field.IsOriginal());
// The enclosed code allocates objects and can potentially trigger a GC,
// ensure that we account for safepoints when grabbing the lock.
SafepointMutexLocker ml(&field_list_mutex_);
if (boxed_field_list_ == GrowableObjectArray::null()) {
boxed_field_list_ = GrowableObjectArray::New(Heap::kOld);
}
const GrowableObjectArray& array =
GrowableObjectArray::Handle(boxed_field_list_);
array.Add(Field::Handle(field.Original()), Heap::kOld);
}
RawField* Isolate::GetDeoptimizingBoxedField() {
ASSERT(Thread::Current()->IsMutatorThread());
SafepointMutexLocker ml(&field_list_mutex_);
if (boxed_field_list_ == GrowableObjectArray::null()) {
return Field::null();
}
const GrowableObjectArray& array =
GrowableObjectArray::Handle(boxed_field_list_);
if (array.Length() == 0) {
return Field::null();
}
return Field::RawCast(array.RemoveLast());
}
#ifndef PRODUCT
RawError* Isolate::InvokePendingServiceExtensionCalls() {
if (!FLAG_support_service) {
return Error::null();
}
GrowableObjectArray& calls =
GrowableObjectArray::Handle(GetAndClearPendingServiceExtensionCalls());
if (calls.IsNull()) {
return Error::null();
}
// Grab run function.
const Library& developer_lib = Library::Handle(Library::DeveloperLibrary());
ASSERT(!developer_lib.IsNull());
const Function& run_extension = Function::Handle(
developer_lib.LookupLocalFunction(Symbols::_runExtension()));
ASSERT(!run_extension.IsNull());
const Array& arguments =
Array::Handle(Array::New(kPendingEntrySize + 1, Heap::kNew));
Object& result = Object::Handle();
String& method_name = String::Handle();
Instance& closure = Instance::Handle();
Array& parameter_keys = Array::Handle();
Array& parameter_values = Array::Handle();
Instance& reply_port = Instance::Handle();
Instance& id = Instance::Handle();
for (intptr_t i = 0; i < calls.Length(); i += kPendingEntrySize) {
// Grab arguments for call.
closure ^= calls.At(i + kPendingHandlerIndex);
ASSERT(!closure.IsNull());
arguments.SetAt(kPendingHandlerIndex, closure);
method_name ^= calls.At(i + kPendingMethodNameIndex);
ASSERT(!method_name.IsNull());
arguments.SetAt(kPendingMethodNameIndex, method_name);
parameter_keys ^= calls.At(i + kPendingKeysIndex);
ASSERT(!parameter_keys.IsNull());
arguments.SetAt(kPendingKeysIndex, parameter_keys);
parameter_values ^= calls.At(i + kPendingValuesIndex);
ASSERT(!parameter_values.IsNull());
arguments.SetAt(kPendingValuesIndex, parameter_values);
reply_port ^= calls.At(i + kPendingReplyPortIndex);
ASSERT(!reply_port.IsNull());
arguments.SetAt(kPendingReplyPortIndex, reply_port);
id ^= calls.At(i + kPendingIdIndex);
arguments.SetAt(kPendingIdIndex, id);
arguments.SetAt(kPendingEntrySize, Bool::Get(FLAG_trace_service));
if (FLAG_trace_service) {
OS::PrintErr("[+%" Pd64 "ms] Isolate %s invoking _runExtension for %s\n",
Dart::UptimeMillis(), name(), method_name.ToCString());
}
result = DartEntry::InvokeFunction(run_extension, arguments);
if (FLAG_trace_service) {
OS::PrintErr("[+%" Pd64 "ms] Isolate %s _runExtension complete for %s\n",
Dart::UptimeMillis(), name(), method_name.ToCString());
}
// Propagate the error.
if (result.IsError()) {
// Remaining service extension calls are dropped.
if (!result.IsUnwindError()) {
// Send error back over the protocol.
Service::PostError(method_name, parameter_keys, parameter_values,
reply_port, id, Error::Cast(result));
}
return Error::Cast(result).raw();
}
// Drain the microtask queue.
result = DartLibraryCalls::DrainMicrotaskQueue();
// Propagate the error.
if (result.IsError()) {
// Remaining service extension calls are dropped.
return Error::Cast(result).raw();
}
}
return Error::null();
}
RawGrowableObjectArray* Isolate::GetAndClearPendingServiceExtensionCalls() {
RawGrowableObjectArray* r = pending_service_extension_calls_;
pending_service_extension_calls_ = GrowableObjectArray::null();
return r;
}
void Isolate::AppendServiceExtensionCall(const Instance& closure,
const String& method_name,
const Array& parameter_keys,
const Array& parameter_values,
const Instance& reply_port,
const Instance& id) {
if (FLAG_trace_service) {
OS::PrintErr("[+%" Pd64
"ms] Isolate %s ENQUEUING request for extension %s\n",
Dart::UptimeMillis(), name(), method_name.ToCString());
}
GrowableObjectArray& calls =
GrowableObjectArray::Handle(pending_service_extension_calls());
bool schedule_drain = false;
if (calls.IsNull()) {
calls = GrowableObjectArray::New();
ASSERT(!calls.IsNull());
set_pending_service_extension_calls(calls);
schedule_drain = true;
}
ASSERT(kPendingHandlerIndex == 0);
calls.Add(closure);
ASSERT(kPendingMethodNameIndex == 1);
calls.Add(method_name);
ASSERT(kPendingKeysIndex == 2);
calls.Add(parameter_keys);
ASSERT(kPendingValuesIndex == 3);
calls.Add(parameter_values);
ASSERT(kPendingReplyPortIndex == 4);
calls.Add(reply_port);
ASSERT(kPendingIdIndex == 5);
calls.Add(id);
if (schedule_drain) {
const Array& msg = Array::Handle(Array::New(3));
Object& element = Object::Handle();
element = Smi::New(Message::kIsolateLibOOBMsg);
msg.SetAt(0, element);
element = Smi::New(Isolate::kDrainServiceExtensionsMsg);
msg.SetAt(1, element);
element = Smi::New(Isolate::kBeforeNextEventAction);
msg.SetAt(2, element);
MessageWriter writer(false);
std::unique_ptr<Message> message =
writer.WriteMessage(msg, main_port(), Message::kOOBPriority);
bool posted = PortMap::PostMessage(std::move(message));
ASSERT(posted);
}
}
// This function is written in C++ and not Dart because we must do this
// operation atomically in the face of random OOB messages. Do not port
// to Dart code unless you can ensure that the operations will can be
// done atomically.
void Isolate::RegisterServiceExtensionHandler(const String& name,
const Instance& closure) {
if (!FLAG_support_service || Isolate::IsVMInternalIsolate(this)) {
return;
}
GrowableObjectArray& handlers =
GrowableObjectArray::Handle(registered_service_extension_handlers());
if (handlers.IsNull()) {
handlers = GrowableObjectArray::New(Heap::kOld);
set_registered_service_extension_handlers(handlers);
}
#if defined(DEBUG)
{
// Sanity check.
const Instance& existing_handler =
Instance::Handle(LookupServiceExtensionHandler(name));
ASSERT(existing_handler.IsNull());
}
#endif
ASSERT(kRegisteredNameIndex == 0);
handlers.Add(name, Heap::kOld);
ASSERT(kRegisteredHandlerIndex == 1);
handlers.Add(closure, Heap::kOld);
{
// Fire off an event.
ServiceEvent event(this, ServiceEvent::kServiceExtensionAdded);
event.set_extension_rpc(&name);
Service::HandleEvent(&event);
}
}
// This function is written in C++ and not Dart because we must do this
// operation atomically in the face of random OOB messages. Do not port
// to Dart code unless you can ensure that the operations will can be
// done atomically.
RawInstance* Isolate::LookupServiceExtensionHandler(const String& name) {
if (!FLAG_support_service) {
return Instance::null();
}
const GrowableObjectArray& handlers =
GrowableObjectArray::Handle(registered_service_extension_handlers());
if (handlers.IsNull()) {
return Instance::null();
}
String& handler_name = String::Handle();
for (intptr_t i = 0; i < handlers.Length(); i += kRegisteredEntrySize) {
handler_name ^= handlers.At(i + kRegisteredNameIndex);
ASSERT(!handler_name.IsNull());
if (handler_name.Equals(name)) {
return Instance::RawCast(handlers.At(i + kRegisteredHandlerIndex));
}
}
return Instance::null();
}
void Isolate::WakePauseEventHandler(Dart_Isolate isolate) {
Isolate* iso = reinterpret_cast<Isolate*>(isolate);
MonitorLocker ml(iso->pause_loop_monitor_);
ml.Notify();
}
void Isolate::PauseEventHandler() {
// We are stealing a pause event (like a breakpoint) from the
// embedder. We don't know what kind of thread we are on -- it
// could be from our thread pool or it could be a thread from the
// embedder. Sit on the current thread handling service events
// until we are told to resume.
if (pause_loop_monitor_ == nullptr) {
pause_loop_monitor_ = new Monitor();
}
Dart_EnterScope();
MonitorLocker ml(pause_loop_monitor_, false);
Dart_MessageNotifyCallback saved_notify_callback = message_notify_callback();
set_message_notify_callback(Isolate::WakePauseEventHandler);
#if !defined(DART_PRECOMPILED_RUNTIME)
const bool had_isolate_reload_context = reload_context() != nullptr;
const int64_t start_time_micros =
!had_isolate_reload_context
? 0
: reload_context()->group_reload_context()->start_time_micros();
#endif // !defined(DART_PRECOMPILED_RUNTIME)
bool resume = false;
bool handle_non_service_messages = false;
while (true) {
// Handle all available vm service messages, up to a resume
// request.
while (!resume && Dart_HasServiceMessages()) {
ml.Exit();
resume = Dart_HandleServiceMessages();
ml.Enter();
}
if (resume) {
break;
} else {
handle_non_service_messages = true;
}
#if !defined(DART_PRECOMPILED_RUNTIME)
if (had_isolate_reload_context && (reload_context() == nullptr)) {
if (FLAG_trace_reload) {
const int64_t reload_time_micros =
OS::GetCurrentMonotonicMicros() - start_time_micros;
double reload_millis = MicrosecondsToMilliseconds(reload_time_micros);
OS::PrintErr("Reloading has finished! (%.2f ms)\n", reload_millis);
}
break;
}
#endif // !defined(DART_PRECOMPILED_RUNTIME)
// Wait for more service messages.
Monitor::WaitResult res = ml.Wait();
ASSERT(res == Monitor::kNotified);
}
// If any non-service messages came in, we need to notify the registered
// message notify callback to check for unhandled messages. Otherwise, events
// may be left unhandled until the next event comes in. See
// https://github.com/dart-lang/sdk/issues/37312.
if ((saved_notify_callback != nullptr) && handle_non_service_messages) {
saved_notify_callback(Api::CastIsolate(this));
}
set_message_notify_callback(saved_notify_callback);
Dart_ExitScope();
}
#endif // !PRODUCT
void Isolate::VisitIsolates(IsolateVisitor* visitor) {
if (visitor == nullptr) {
return;
}
// The visitor could potentially run code that could safepoint so use
// SafepointMonitorLocker to ensure the lock has safepoint checks.
SafepointMonitorLocker ml(isolates_list_monitor_);
Isolate* current = isolates_list_head_;
while (current != nullptr) {
visitor->VisitIsolate(current);
current = current->next_;
}
}
intptr_t Isolate::IsolateListLength() {
MonitorLocker ml(isolates_list_monitor_);
intptr_t count = 0;
Isolate* current = isolates_list_head_;
while (current != nullptr) {
count++;
current = current->next_;
}
return count;
}
Isolate* Isolate::LookupIsolateByPort(Dart_Port port) {
MonitorLocker ml(isolates_list_monitor_);
Isolate* current = isolates_list_head_;
while (current != nullptr) {
if (current->main_port() == port) {
return current;
}
current = current->next_;
}
return nullptr;
}
std::unique_ptr<char[]> Isolate::LookupIsolateNameByPort(Dart_Port port) {
MonitorLocker ml(isolates_list_monitor_);
Isolate* current = isolates_list_head_;
while (current != nullptr) {
if (current->main_port() == port) {
const size_t len = strlen(current->name()) + 1;
auto result = std::unique_ptr<char[]>(new char[len]);
strncpy(result.get(), current->name(), len);
return result;
}
current = current->next_;
}
return std::unique_ptr<char[]>();
}
bool Isolate::AddIsolateToList(Isolate* isolate) {
MonitorLocker ml(isolates_list_monitor_);
if (!creation_enabled_) {
return false;
}
ASSERT(isolate != nullptr);
ASSERT(isolate->next_ == nullptr);
isolate->next_ = isolates_list_head_;
isolates_list_head_ = isolate;
return true;
}
void Isolate::RemoveIsolateFromList(Isolate* isolate) {
MonitorLocker ml(isolates_list_monitor_);
ASSERT(isolate != nullptr);
if (isolate == isolates_list_head_) {
isolates_list_head_ = isolate->next_;
if (!creation_enabled_) {
ml.Notify();
}
return;
}
Isolate* previous = nullptr;
Isolate* current = isolates_list_head_;
while (current != nullptr) {
if (current == isolate) {
ASSERT(previous != nullptr);
previous->next_ = current->next_;
if (!creation_enabled_) {
ml.Notify();
}
return;
}
previous = current;
current = current->next_;
}
// If we are shutting down the VM, the isolate may not be in the list.
ASSERT(!creation_enabled_);
}
void Isolate::DisableIsolateCreation() {
MonitorLocker ml(isolates_list_monitor_);
creation_enabled_ = false;
}
void Isolate::EnableIsolateCreation() {
MonitorLocker ml(isolates_list_monitor_);
creation_enabled_ = true;
}
bool Isolate::IsolateCreationEnabled() {
MonitorLocker ml(isolates_list_monitor_);
return creation_enabled_;
}
bool Isolate::IsVMInternalIsolate(const Isolate* isolate) {
return (isolate == Dart::vm_isolate()) ||
ServiceIsolate::IsServiceIsolateDescendant(isolate) ||
KernelIsolate::IsKernelIsolate(isolate);
}
void Isolate::KillLocked(LibMsgId msg_id) {
Dart_CObject kill_msg;
Dart_CObject* list_values[4];
kill_msg.type = Dart_CObject_kArray;
kill_msg.value.as_array.length = 4;
kill_msg.value.as_array.values = list_values;
Dart_CObject oob;
oob.type = Dart_CObject_kInt32;
oob.value.as_int32 = Message::kIsolateLibOOBMsg;
list_values[0] = &oob;
Dart_CObject msg_type;
msg_type.type = Dart_CObject_kInt32;
msg_type.value.as_int32 = msg_id;
list_values[1] = &msg_type;
Dart_CObject cap;
cap.type = Dart_CObject_kCapability;
cap.value.as_capability.id = terminate_capability();
list_values[2] = ∩
Dart_CObject imm;
imm.type = Dart_CObject_kInt32;
imm.value.as_int32 = Isolate::kImmediateAction;
list_values[3] = &imm;
{
ApiMessageWriter writer;
std::unique_ptr<Message> message =
writer.WriteCMessage(&kill_msg, main_port(), Message::kOOBPriority);
ASSERT(message != nullptr);
// Post the message at the given port.
bool success = PortMap::PostMessage(std::move(message));
ASSERT(success);
}
}
class IsolateKillerVisitor : public IsolateVisitor {
public:
explicit IsolateKillerVisitor(Isolate::LibMsgId msg_id)
: target_(nullptr), msg_id_(msg_id) {}
IsolateKillerVisitor(Isolate* isolate, Isolate::LibMsgId msg_id)
: target_(isolate), msg_id_(msg_id) {
ASSERT(isolate != Dart::vm_isolate());
}
virtual ~IsolateKillerVisitor() {}
void VisitIsolate(Isolate* isolate) {
ASSERT(isolate != nullptr);
if (ShouldKill(isolate)) {
isolate->KillLocked(msg_id_);
}
}
private:
bool ShouldKill(Isolate* isolate) {
// If a target_ is specified, then only kill the target_.
// Otherwise, don't kill the service isolate or vm isolate.
return (((target_ != nullptr) && (isolate == target_)) ||
((target_ == nullptr) && !IsVMInternalIsolate(isolate)));
}
Isolate* target_;
Isolate::LibMsgId msg_id_;
};
void Isolate::KillAllIsolates(LibMsgId msg_id) {
IsolateKillerVisitor visitor(msg_id);
VisitIsolates(&visitor);
}
void Isolate::KillIfExists(Isolate* isolate, LibMsgId msg_id) {
IsolateKillerVisitor visitor(isolate, msg_id);
VisitIsolates(&visitor);
}
void Isolate::IncrementSpawnCount() {
MonitorLocker ml(&spawn_count_monitor_);
spawn_count_++;
}
void Isolate::DecrementSpawnCount() {
MonitorLocker ml(&spawn_count_monitor_);
ASSERT(spawn_count_ > 0);
spawn_count_--;
ml.Notify();
}
void Isolate::WaitForOutstandingSpawns() {
Thread* thread = Thread::Current();
ASSERT(thread != NULL);
MonitorLocker ml(&spawn_count_monitor_);
while (spawn_count_ > 0) {
ml.WaitWithSafepointCheck(thread);
}
}
Monitor* IsolateGroup::threads_lock() const {
return thread_registry_->threads_lock();
}
Thread* Isolate::ScheduleThread(bool is_mutator, bool bypass_safepoint) {
// We are about to associate the thread with an isolate group and it would
// not be possible to correctly track no_safepoint_scope_depth for the
// thread in the constructor/destructor of MonitorLocker,
// so we create a MonitorLocker object which does not do any
// no_safepoint_scope_depth increments/decrements.
MonitorLocker ml(group()->threads_lock(), false);
// Check to make sure we don't already have a mutator thread.
if (is_mutator && scheduled_mutator_thread_ != nullptr) {
return nullptr;
}
// NOTE: We cannot just use `Dart::vm_isolate() == this` here, since during
// VM startup it might not have been set at this point.
const bool is_vm_isolate =
Dart::vm_isolate() == nullptr || Dart::vm_isolate() == this;
// We lazily create a [Thread] structure for the mutator thread, but we'll
// reuse it until the death of the isolate.
Thread* existing_mutator_thread = is_mutator ? mutator_thread_ : nullptr;
// Schedule the thread into the isolate by associating a 'Thread' structure
// with it (this is done while we are holding the thread registry lock).
Thread* thread =
group()->ScheduleThreadLocked(&ml, existing_mutator_thread, is_vm_isolate,
is_mutator, bypass_safepoint);
if (is_mutator) {
ASSERT(mutator_thread_ == nullptr || mutator_thread_ == thread);
mutator_thread_ = thread;
scheduled_mutator_thread_ = thread;
}
thread->isolate_ = this;
thread->field_table_values_ = field_table_->table();
ASSERT(heap() != nullptr);
thread->heap_ = heap();
return thread;
}
void Isolate::UnscheduleThread(Thread* thread,
bool is_mutator,
bool bypass_safepoint) {
// Disassociate the 'Thread' structure and unschedule the thread
// from this isolate.
// We are disassociating the thread from an isolate and it would
// not be possible to correctly track no_safepoint_scope_depth for the
// thread in the constructor/destructor of MonitorLocker,
// so we create a MonitorLocker object which does not do any
// no_safepoint_scope_depth increments/decrements.
MonitorLocker ml(group()->threads_lock(), false);
// Clear since GC will not visit the thread once it is unscheduled. Do this
// under the thread lock to prevent races with the GC visiting thread roots.
thread->ClearReusableHandles();
if (!is_mutator) {
thread->heap()->AbandonRemainingTLAB(thread);
}
if (is_mutator) {
if (thread->sticky_error() != Error::null()) {
ASSERT(sticky_error_ == Error::null());
sticky_error_ = thread->StealStickyError();
}
ASSERT(mutator_thread_ == thread);
ASSERT(mutator_thread_ == scheduled_mutator_thread_);
scheduled_mutator_thread_ = nullptr;
}
thread->field_table_values_ = nullptr;
group()->UnscheduleThreadLocked(&ml, thread, is_mutator, bypass_safepoint);
}
static const char* NewConstChar(const char* chars) {
size_t len = strlen(chars);
char* mem = new char[len + 1];
memmove(mem, chars, len + 1);
return mem;
}
IsolateSpawnState::IsolateSpawnState(Dart_Port parent_port,
Dart_Port origin_id,
const char* script_url,
const Function& func,
SerializedObjectBuffer* message_buffer,
const char* package_config,
bool paused,
bool errors_are_fatal,
Dart_Port on_exit_port,
Dart_Port on_error_port,
const char* debug_name,
IsolateGroup* isolate_group)
: isolate_(nullptr),
parent_port_(parent_port),
origin_id_(origin_id),
on_exit_port_(on_exit_port),
on_error_port_(on_error_port),
script_url_(script_url),
package_config_(package_config),
library_url_(nullptr),
class_name_(nullptr),
function_name_(nullptr),
debug_name_(debug_name),
isolate_group_(isolate_group),
serialized_args_(nullptr),
serialized_message_(message_buffer->StealMessage()),
paused_(paused),
errors_are_fatal_(errors_are_fatal) {
const Class& cls = Class::Handle(func.Owner());
const Library& lib = Library::Handle(cls.library());
const String& lib_url = String::Handle(lib.url());
library_url_ = NewConstChar(lib_url.ToCString());
String& func_name = String::Handle();
func_name = func.name();
function_name_ = NewConstChar(String::ScrubName(func_name));
if (!cls.IsTopLevel()) {
const String& class_name = String::Handle(cls.Name());
class_name_ = NewConstChar(class_name.ToCString());
}
// Inherit flags from spawning isolate.
Isolate::Current()->FlagsCopyTo(isolate_flags());
}
IsolateSpawnState::IsolateSpawnState(Dart_Port parent_port,
const char* script_url,
const char* package_config,
SerializedObjectBuffer* args_buffer,
SerializedObjectBuffer* message_buffer,
bool paused,
bool errors_are_fatal,
Dart_Port on_exit_port,
Dart_Port on_error_port,
const char* debug_name,
IsolateGroup* group)
: isolate_(nullptr),
parent_port_(parent_port),
origin_id_(ILLEGAL_PORT),
on_exit_port_(on_exit_port),
on_error_port_(on_error_port),
script_url_(script_url),
package_config_(package_config),
library_url_(nullptr),
class_name_(nullptr),
function_name_(nullptr),
debug_name_(debug_name),
isolate_group_(group),
serialized_args_(args_buffer->StealMessage()),
serialized_message_(message_buffer->StealMessage()),
isolate_flags_(),
paused_(paused),
errors_are_fatal_(errors_are_fatal) {
function_name_ = NewConstChar("main");
// By default inherit flags from spawning isolate. These can be overridden
// from the calling code.
Isolate::Current()->FlagsCopyTo(isolate_flags());
}
IsolateSpawnState::~IsolateSpawnState() {
delete[] script_url_;
delete[] package_config_;
delete[] library_url_;
delete[] class_name_;
delete[] function_name_;
delete[] debug_name_;
}
RawObject* IsolateSpawnState::ResolveFunction() {
Thread* thread = Thread::Current();
Zone* zone = thread->zone();
const String& func_name = String::Handle(zone, String::New(function_name()));
if (library_url() == nullptr) {
// Handle spawnUri lookup rules.
// Check whether the root library defines a main function.
const Library& lib =
Library::Handle(zone, I->object_store()->root_library());
Function& func = Function::Handle(zone, lib.LookupLocalFunction(func_name));
if (func.IsNull()) {
// Check whether main is reexported from the root library.
const Object& obj = Object::Handle(zone, lib.LookupReExport(func_name));
if (obj.IsFunction()) {
func ^= obj.raw();
}
}
if (func.IsNull()) {
const String& msg = String::Handle(
zone, String::NewFormatted(
"Unable to resolve function '%s' in script '%s'.",
function_name(), script_url()));
return LanguageError::New(msg);
}
return func.raw();
}
// Lookup the to be spawned function for the Isolate.spawn implementation.
// Resolve the library.
const String& lib_url = String::Handle(zone, String::New(library_url()));
const Library& lib =
Library::Handle(zone, Library::LookupLibrary(thread, lib_url));
if (lib.IsNull() || lib.IsError()) {
const String& msg = String::Handle(
zone,
String::NewFormatted("Unable to find library '%s'.", library_url()));
return LanguageError::New(msg);
}
// Resolve the function.
if (class_name() == nullptr) {
const Function& func =
Function::Handle(zone, lib.LookupLocalFunction(func_name));
if (func.IsNull()) {
const String& msg = String::Handle(
zone, String::NewFormatted(
"Unable to resolve function '%s' in library '%s'.",
function_name(), library_url()));
return LanguageError::New(msg);
}
return func.raw();
}
const String& cls_name = String::Handle(zone, String::New(class_name()));
const Class& cls = Class::Handle(zone, lib.LookupLocalClass(cls_name));
if (cls.IsNull()) {
const String& msg = String::Handle(
zone, String::NewFormatted(
"Unable to resolve class '%s' in library '%s'.", class_name(),
(library_url() != nullptr ? library_url() : script_url())));
return LanguageError::New(msg);
}
const Function& func =
Function::Handle(zone, cls.LookupStaticFunctionAllowPrivate(func_name));
if (func.IsNull()) {
const String& msg = String::Handle(
zone, String::NewFormatted(
"Unable to resolve static method '%s.%s' in library '%s'.",
class_name(), function_name(),
(library_url() != nullptr ? library_url() : script_url())));
return LanguageError::New(msg);
}
return func.raw();
}
RawInstance* IsolateSpawnState::BuildArgs(Thread* thread) {
return DeserializeMessage(thread, serialized_args_.get());
}
RawInstance* IsolateSpawnState::BuildMessage(Thread* thread) {
return DeserializeMessage(thread, serialized_message_.get());
}
} // namespace dart
|
; A033131: Base-4 digits are, in order, the first n terms of the periodic sequence with initial period 1,1,0.
; 1,5,20,81,325,1300,5201,20805,83220,332881,1331525,5326100,21304401,85217605,340870420,1363481681,5453926725,21815706900,87262827601,349051310405,1396205241620,5584820966481,22339283865925,89357135463700,357428541854801,1429714167419205,5718856669676820,22875426678707281,91501706714829125,366006826859316500,1464027307437266001,5856109229749064005,23424436918996256020,93697747675985024081,374790990703940096325,1499163962815760385300,5996655851263041541201,23986623405052166164805
mov $1,4
pow $1,$0
mul $1,80
div $1,63
mov $0,$1
|
IDEAL
ASSUME CS:SEG1, DS:SEG1, ES:SEG1, SS:SEG1
SEGMENT SEG1 PUBLIC
ORG 100h
start:
MOV AX, 1234h
ENDS
PUBLIC start
END start
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r15
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x542d, %rsi
lea addresses_normal_ht+0x1569f, %rdi
nop
nop
xor %r11, %r11
mov $39, %rcx
rep movsb
and %r15, %r15
lea addresses_A_ht+0x121a5, %rbx
nop
and $4016, %r13
movb $0x61, (%rbx)
nop
and $8399, %rcx
lea addresses_UC_ht+0x12e6d, %rcx
nop
nop
nop
nop
nop
dec %rdi
mov $0x6162636465666768, %r13
movq %r13, %xmm7
and $0xffffffffffffffc0, %rcx
movntdq %xmm7, (%rcx)
nop
nop
nop
nop
nop
add $19819, %r11
lea addresses_A_ht+0xcabf, %rbx
nop
nop
nop
nop
and $130, %r15
mov $0x6162636465666768, %r13
movq %r13, (%rbx)
nop
nop
and %r13, %r13
lea addresses_D_ht+0x3c65, %rcx
nop
nop
nop
nop
nop
cmp $4017, %rdi
mov $0x6162636465666768, %r11
movq %r11, %xmm1
vmovups %ymm1, (%rcx)
xor $43505, %r15
lea addresses_A_ht+0x11a6d, %rsi
lea addresses_WT_ht+0x1382d, %rdi
nop
nop
nop
nop
nop
inc %r11
mov $80, %rcx
rep movsq
nop
nop
and %rsi, %rsi
lea addresses_UC_ht+0x28a5, %r15
nop
and %rcx, %rcx
movw $0x6162, (%r15)
nop
and %rsi, %rsi
lea addresses_WC_ht+0x66d, %r13
nop
inc %rdi
mov $0x6162636465666768, %rsi
movq %rsi, %xmm4
vmovups %ymm4, (%r13)
nop
add %rsi, %rsi
lea addresses_A_ht+0xab6d, %r11
nop
nop
nop
sub %rbx, %rbx
mov (%r11), %r15w
cmp %r11, %r11
lea addresses_WT_ht+0x1ed6d, %rsi
lea addresses_normal_ht+0x179d, %rdi
clflush (%rsi)
nop
nop
nop
cmp %rbx, %rbx
mov $114, %rcx
rep movsw
nop
nop
sub %rbx, %rbx
lea addresses_normal_ht+0x566d, %r13
clflush (%r13)
nop
and $64766, %rdi
mov $0x6162636465666768, %r11
movq %r11, %xmm2
and $0xffffffffffffffc0, %r13
vmovaps %ymm2, (%r13)
nop
nop
and $40305, %r13
lea addresses_UC_ht+0x106ed, %r15
nop
nop
cmp %rdi, %rdi
movl $0x61626364, (%r15)
nop
nop
sub %rsi, %rsi
lea addresses_A_ht+0x1d04d, %rsi
lea addresses_A_ht+0xdded, %rdi
nop
nop
nop
nop
nop
xor %rbx, %rbx
mov $124, %rcx
rep movsq
nop
nop
add $24319, %rdi
lea addresses_WT_ht+0x1332d, %r11
xor $44408, %r13
mov $0x6162636465666768, %r15
movq %r15, %xmm7
movups %xmm7, (%r11)
add %rdi, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r15
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r9
push %rax
push %rbp
push %rcx
// Faulty Load
lea addresses_D+0x1fa6d, %rbp
nop
nop
nop
add %rcx, %rcx
movb (%rbp), %al
lea oracles, %r13
and $0xff, %rax
shlq $12, %rax
mov (%r13,%rax,1), %rax
pop %rcx
pop %rbp
pop %rax
pop %r9
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 2}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_WT_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 8}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 8}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': True, 'size': 32, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 7}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 4}}
{'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
*/
|
/****************************************************************************
**
** This file is part of the LibreCAD project, a 2D CAD program
**
** Copyright (C) 2010 R. van Twisk (librecad@rvt.dds.nl)
** Copyright (C) 2001-2003 RibbonSoft. All rights reserved.
**
**
** This file may be distributed and/or modified under the terms of the
** GNU General Public License version 2 as published by the Free Software
** Foundation and appearing in the file gpl-2.0.txt included in the
** packaging of this file.
**
** 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 02110-1301 USA
**
** This copyright notice MUST APPEAR in all copies of the script!
**
**********************************************************************/
#include<cstdlib>
#include "rs_filterdxfrw.h"
#include "rs_filterdxf1.h"
#include "rs_arc.h"
#include "rs_circle.h"
#include "rs_ellipse.h"
#include "rs_line.h"
#include "rs_font.h"
#include "rs_information.h"
#include "rs_utility.h"
#include "rs_system.h"
#include "rs_dimlinear.h"
#include "rs_dimaligned.h"
#include "rs_dimangular.h"
#include "rs_dimdiametric.h"
#include "rs_dimradial.h"
#include "rs_layer.h"
#include "rs_leader.h"
#include "rs_point.h"
#include "rs_math.h"
#include "rs_debug.h"
/**
* Default constructor.
*/
RS_FilterDXF1::RS_FilterDXF1()
:RS_FilterInterface()
, graphic(nullptr)
{
RS_DEBUG->print("Setting up DXF 1 filter...");
}
/**
* Implementation of the method used for RS_Import to communicate
* with this filter.
*
* @param graphic The graphic in which the entities from the file
* will be created or the graphics from which the entities are
* taken to be stored in a file.
*/
bool RS_FilterDXF1::fileImport(RS_Graphic& g, const QString& file, RS2::FormatType /*type*/) {
RS_DEBUG->print("DXF1 Filter: importing file '%s'...", file.toLatin1().data());
this->graphic = &g;
fPointer=0;
fBuf=0;
fBufP=0;
fSize=0;
dosFile=false;
name = file;
if(readFileInBuffer()) {
separateBuf();
return readFromBuffer();
}
return false;
}
bool RS_FilterDXF1::fileExport(RS_Graphic& /*g*/, const QString& /*file*/,
RS2::FormatType /*type*/) {
RS_DEBUG->print(RS_Debug::D_WARNING,
"Exporting of QCad 1.x file not implemented");
return false;
}
/**
* Reads a dxf1 file from buffer.
*/
bool RS_FilterDXF1::readFromBuffer() {
RS_DEBUG->print( "\nDXF: Read from buffer" );
bool ret; // returned value
QString dxfLine; // A line in the dxf file
QString dxfCode; // A Code in the dxf file as string
int code=-1; // Dxf-code as number
double vx1=0.0, vy1=0.0; // Start point
double vx2=0.0, vy2=0.0; // End point
double vcx=0.0, vcy=0.0; // Centre
double vcr=0.0; // Radius
double va1=0.0, va2=0.0; // Start / End Angle
//double vab=0.0, // Bulge
// vpx=0.0, vpy=0.0; // First Polyline point
//double ax=0.0, ay=0.0; // Current coordinate
//bool plClose=false; // Polyline closed-flag
QString lastLayer; // Last used layer name (test adding only
// if the new layer!=lastLayer)
//int currentLayerNum=0; // Current layer number
RS_Layer* currentLayer=0; // Pointer to current layer
//QList<RGraphic> blockList; // List of blocks
//blockList.setAutoDelete( true );
//bool oldColorNumbers=false; // use old color numbers (qcad<1.5.3)
RS_Pen pen;
///if(!add) graphic->clearLayers();
//graphic->addLayer(DEF_DEFAULTLAYER);
//RS_DEBUG->print( "\nDefault layer added" );
// Loaded graphics without unit information: load as unit less:
//graphic->setUnit( None );
RS_DEBUG->print( "\nUnit set" );
resetBufP();
if(fBuf) {
RS_DEBUG->print( "\nBuffer OK" );
RS_DEBUG->print( "\nBuffer: " );
RS_DEBUG->print( fBuf );
do {
dxfLine=getBufLine();
pen = RS_Pen(RS_Color(RS2::FlagByLayer), RS2::WidthByLayer, RS2::LineByLayer);
RS_DEBUG->print( "\ndxfLine: " );
RS_DEBUG->print( dxfLine.toLatin1().data() );
// $-Setting in the header of DXF found
// RVT_PORT changed all occurenses of if (dxfline && ....) to if (dxfline.size() ......)
if( dxfLine.size() &&
dxfLine[0]=='$' ) {
// Units:
//
if( dxfLine=="$INSUNITS" ) {
dxfCode=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==70 ) {
dxfLine=getBufLine() ;
if( dxfLine.size() ) {
graphic->addVariable("$INSUNITS", dxfLine, 70);
/*
switch( dxfLine.toInt() ) {
case 0: graphic->setUnit( RS2::None ); break;
case 1: graphic->setUnit( RS2::Inch ); break;
case 2: graphic->setUnit( RS2::Foot ); break;
case 3: graphic->setUnit( RS2::Mile ); break;
case 4: graphic->setUnit( RS2::Millimeter ); break;
case 5: graphic->setUnit( RS2::Centimeter ); break;
case 6: graphic->setUnit( RS2::Meter ); break;
case 7: graphic->setUnit( RS2::Kilometer ); break;
case 8: graphic->setUnit( RS2::Microinch ); break;
case 9: graphic->setUnit( RS2::Mil ); break;
case 10: graphic->setUnit( RS2::Yard ); break;
case 11: graphic->setUnit( RS2::Angstrom ); break;
case 12: graphic->setUnit( RS2::Nanometer ); break;
case 13: graphic->setUnit( RS2::Micron ); break;
case 14: graphic->setUnit( RS2::Decimeter ); break;
case 15: graphic->setUnit( RS2::Decameter ); break;
case 16: graphic->setUnit( RS2::Hectometer ); break;
case 17: graphic->setUnit( RS2::Gigameter ); break;
case 18: graphic->setUnit( RS2::Astro ); break;
case 19: graphic->setUnit( RS2::Lightyear ); break;
case 20: graphic->setUnit( RS2::Parsec ); break;
}
graphic->setDimensionUnit( graphic->getUnit() );
//graphic->setGridUnit( graphic->getUnit() );
*/
}
}
}
}
// Dimenison Units:
//
else if( dxfLine=="$DIMALT" ) {
dxfCode=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==70 ) {
dxfLine=getBufLine();
if( dxfLine.size() ) {
graphic->addVariable("$DIMALT", dxfLine, 70);
/*
switch( dxfLine.toInt() ) {
case 0: graphic->setDimensionUnit( RS2::None ); break;
case 1: graphic->setDimensionUnit( RS2::Inch ); break;
case 2: graphic->setDimensionUnit( RS2::Foot ); break;
case 3: graphic->setDimensionUnit( RS2::Mile ); break;
case 4: graphic->setDimensionUnit( RS2::Millimeter ); break;
case 5: graphic->setDimensionUnit( RS2::Centimeter ); break;
case 6: graphic->setDimensionUnit( RS2::Meter ); break;
case 7: graphic->setDimensionUnit( RS2::Kilometer ); break;
case 8: graphic->setDimensionUnit( RS2::Microinch ); break;
case 9: graphic->setDimensionUnit( RS2::Mil ); break;
case 10: graphic->setDimensionUnit( RS2::Yard ); break;
case 11: graphic->setDimensionUnit( RS2::Angstrom ); break;
case 12: graphic->setDimensionUnit( RS2::Nanometer ); break;
case 13: graphic->setDimensionUnit( RS2::Micron ); break;
case 14: graphic->setDimensionUnit( RS2::Decimeter ); break;
case 15: graphic->setDimensionUnit( RS2::Decameter ); break;
case 16: graphic->setDimensionUnit( RS2::Hectometer ); break;
case 17: graphic->setDimensionUnit( RS2::Gigameter ); break;
case 18: graphic->setDimensionUnit( RS2::Astro ); break;
case 19: graphic->setDimensionUnit( RS2::Lightyear ); break;
case 20: graphic->setDimensionUnit( RS2::Parsec ); break;
}
*/
}
}
}
}
// Dimension Format:
//
/*else if( dxfLine=="$DIMLUNIT" ) {
if(dxfCode=getBufLine()) {
if( dxfCode.toInt()==70 ) {
if( dxfLine=getBufLine() ) {
switch( dxfLine.toInt() ) {
case 1: graphic->setDimensionFormat( Scientific ); break;
case 2:
case 3: graphic->setDimensionFormat( Decimal ); break;
case 4:
case 5: graphic->setDimensionFormat( Fractional ); break;
default: break;
}
}
}
}
}*/
// Dimension Arrow Size:
//
else if( dxfLine=="$DIMASZ" ) {
dxfCode=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==40 ) {
dxfLine=getBufLine() ;
if( dxfLine.size()) {
graphic->addVariable("$DIMASZ", dxfLine, 40);
//graphic->setDimensionArrowSize( dxfLine.toDouble() );
}
}
}
}
// Dimension Scale:
//
/*
else if( dxfLine=="$DIMSCALE" ) {
if(dxfCode=getBufLine()) {
if( dxfCode.toInt()==40 ) {
if( dxfLine=getBufLine() ) {
graphic->setDimensionScale( dxfLine.toDouble() );
}
}
}
}
*/
// Dimension Text Height:
//
else if( dxfLine=="$DIMTXT" ) {
dxfLine=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==40 ) {
dxfLine=getBufLine();
if( dxfLine.size() ) {
graphic->addVariable("$DIMTXT", dxfLine, 40);
//graphic->setDimensionTextHeight( dxfLine.toDouble() );
}
}
}
}
// Dimension exactness:
//
else if( dxfLine=="$DIMRND" ) {
dxfLine=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==40 ) {
dxfLine=getBufLine();
if( dxfLine.size() ) {
graphic->addVariable("$DIMRND", dxfLine, 40);
//if( dxfLine.toDouble()>0.000001 ) {
//graphic->setDimensionExactness( dxfLine.toDouble() );
}
//}
}
}
}
// Dimension over length:
//
else if( dxfLine=="$DIMEXE" ) {
dxfLine=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==40 ) {
dxfLine=getBufLine();
if( dxfLine.size() ) {
graphic->addVariable("$DIMEXE", dxfLine, 40);
//graphic->setDimensionOverLength( dxfLine.toDouble() );
}
}
}
}
// Dimension under length:
//
else if( dxfLine=="$DIMEXO" ) {
dxfLine=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==40 ) {
dxfLine=getBufLine();
if( dxfLine.size() ) {
graphic->addVariable("$DIMEXO", dxfLine, 40);
//graphic->setDimensionUnderLength( dxfLine.toDouble() );
}
}
}
}
// Angle dimension format:
//
else if( dxfLine=="$DIMAUNIT" ) {
dxfLine=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==70 ) {
dxfLine=getBufLine();
if( dxfLine.size() ) {
graphic->addVariable("$DIMAUNIT", dxfLine, 70);
/*
switch( dxfLine.toInt() ) {
case 0: graphic->setAngleDimensionFormat( DecimalDegrees ); break;
case 1: graphic->setAngleDimensionFormat( DegreesMinutesSeconds ); break;
case 2: graphic->setAngleDimensionFormat( Gradians ); break;
case 3: graphic->setAngleDimensionFormat( Radians ); break;
case 4: graphic->setAngleDimensionFormat( Surveyor ); break;
default: break;
}
*/
}
}
}
}
// Angle dimension exactness:
//
else if( dxfLine=="$DIMADEC" ) {
dxfLine=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==70 ) {
dxfLine=getBufLine();
if( dxfLine.size() ) {
graphic->addVariable("$DIMADEC", dxfLine, 70);
//graphic->setAngleDimensionExactness( RS_Math::pow(0.1, dxfLine.toInt()) );
}
}
}
}
// Grid x/y:
//
else if( dxfLine=="$GRIDUNIT" ) {
dxfLine=getBufLine();
if(dxfCode.size()) {
if( dxfCode.toInt()==10 ) {
dxfLine=getBufLine();
if (dxfLine.size()) {
double x = atof(dxfLine.toLatin1().data());
dxfLine=getBufLine();
if (dxfLine.size()) {
double y = atof(dxfLine.toLatin1().data());
graphic->addVariable("$GRIDUNIT", RS_Vector(x,y), 10);
}
}
}
}
}
/*
double gx=dxfLine.toDouble();
if (gx<0.0001) gx=0.0001;
graphic->setMinGridX(gx);
graphic->setGridFormat( Fractional );
for( double q=0.00000001; q<=100000.0; q*=10.0 ) {
if( mtCompFloat(gx, q, q/1000.0) ) {
graphic->setGridFormat( Decimal );
break;
}
}
}
}
}
if(dxfCode=getBufLine()) {
if( dxfCode.toInt()==20 ) {
if( dxfLine=getBufLine() ) {
double gy=dxfLine.toDouble();
if (gy<0.0001) gy=0.0001;
graphic->setMinGridY(gy);
}
}
}
*/
// Page limits min x/y:
//
/*else if( dxfLine=="$PLIMMIN" ) {
if(dxfCode=getBufLine()) {
if( dxfCode.toInt()==10 ) {
if( dxfLine=getBufLine() ) {
graphic->setPageOriginX( dxfLine.toDouble() );
}
}
}
if(dxfCode=getBufLine()) {
if( dxfCode.toInt()==20 ) {
if( dxfLine=getBufLine() ) {
graphic->setPageOriginY( dxfLine.toDouble() );
}
}
}
}
*/
// Page limits min x/y:
//
/*
else if( dxfLine=="$PLIMMAX" ) {
if(dxfCode=getBufLine()) {
if( dxfCode.toInt()==10 ) {
if( dxfLine=getBufLine() ) {
graphic->setPageSizeX( dxfLine.toDouble() - graphic->getPageOriginX() );
}
}
}
if(dxfCode=getBufLine()) {
if( dxfCode.toInt()==20 ) {
if( dxfLine=getBufLine() ) {
graphic->setPageSizeY( dxfLine.toDouble() - graphic->getPageOriginY() );
}
}
}
}
*/
// Paper space scale:
//
/*
else if( dxfLine=="$PSVPSCALE" ) {
if(dxfCode=getBufLine()) {
if( dxfCode.toInt()==40 ) {
if( dxfLine=getBufLine() ) {
graphic->setPaperSpace( dxfLine.toDouble() );
}
}
}
}
*/
}
// Entity
//
else if(dxfLine.size() &&
dxfLine[0]>='A' && dxfLine[0]<='Z') {
if(dxfLine=="EOF") {
// End of file reached
//
}
// ------
// Layer:
// ------
else if(dxfLine=="LAYER") {
currentLayer=0;
do {
dxfCode=getBufLine();
if(dxfCode.size())
code=dxfCode.toInt();
if(dxfCode.size() && code!=0) {
dxfLine=getBufLine();
if(dxfLine.size()) {
switch(code) {
case 2: // Layer name
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->addLayer(new RS_Layer(dxfLine));
graphic->activateLayer(dxfLine);
currentLayer = graphic->getActiveLayer();
lastLayer=dxfLine;
break;
case 70: // Visibility
/*
if(dxfLine.toInt()&5) {
if(currentLayerNum>=0 && currentLayerNum<DEF_MAXLAYERS) {
graphic->layer[currentLayerNum].DelFlag(Y_VISIBLE);
}
}
*/
break;
case 6: // style
//if(currentLayer)
//currentLayer->setStyle( graphic->nameToStyle(dxfLine) );
pen.setLineType(RS_FilterDXFRW::nameToLineType(dxfLine));
break;
case 39: // Thickness
//if(currentLayer) currentLayer->setWidth(dxfLine.toInt());
pen.setWidth(numberToWidth(dxfLine.toInt()));
break;
case 62: // Color
pen.setColor(RS_FilterDXFRW::numberToColor(dxfLine.toInt()));
//if(currentLayer) {
// currentLayer->setColor( graphic->numberToColor(dxfLine.toInt(), !oldColorNumbers));
//}
break;
default:
break;
}
}
}
} while(dxfCode.size() && code!=0);
if (currentLayer) {
currentLayer->setPen(pen);
}
//graphic->setStyle("CONTINUOUS");
//graphic->setWidth(0);
//graphic->setColor(0, false);
}
// ------
// Point:
// ------
else if(dxfLine=="POINT") {
do {
dxfCode=getBufLine();
if(dxfCode.size())
code=dxfCode.toInt();
if(dxfCode.size() && code!=0) {
dxfLine=getBufLine();
if(dxfLine.size()) {
switch(code) {
case 6: // style
pen.setLineType(RS_FilterDXFRW::nameToLineType(dxfLine));
break;
case 8: // Layer
//if(dxfLine!=lastLayer) {
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->activateLayer(dxfLine);
//lastLayer=dxfLine;
//}
break;
case 10: // X1
dxfLine.replace( QRegExp(","), "." );
vx1 = dxfLine.toDouble();
break;
case 20: // Y1
dxfLine.replace( QRegExp(","), "." );
vy1 = dxfLine.toDouble();
break;
case 39: // Thickness
pen.setWidth(numberToWidth(dxfLine.toInt()));
break;
case 62: // Color
pen.setColor(RS_FilterDXFRW::numberToColor(dxfLine.toInt()));
break;
default:
break;
}
}
}
} while(dxfCode.size() && code!=0);
graphic->setActivePen(pen);
graphic->addEntity(new RS_Point(graphic,
RS_PointData(RS_Vector(vx1, vy1))));
}
// -----
// Line:
// -----
else if(dxfLine=="LINE") {
do {
dxfCode=getBufLine();
if(dxfCode.size())
code=dxfCode.toInt();
if(dxfCode.size() && code!=0) {
dxfLine=getBufLine();
if(dxfLine.size()) {
switch(code) {
case 6: // style
pen.setLineType(RS_FilterDXFRW::nameToLineType(dxfLine));
break;
case 8: // Layer
//if(dxfLine!=lastLayer) {
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->activateLayer(dxfLine);
//lastLayer=dxfLine;
//}
break;
case 10: // X1
dxfLine.replace( QRegExp(","), "." );
vx1 = dxfLine.toDouble();
break;
case 20: // Y1
dxfLine.replace( QRegExp(","), "." );
vy1 = dxfLine.toDouble();
break;
case 11: // X2
dxfLine.replace( QRegExp(","), "." );
vx2 = dxfLine.toDouble();
break;
case 21: // Y2
dxfLine.replace( QRegExp(","), "." );
vy2 = dxfLine.toDouble();
break;
case 39: // Thickness
pen.setWidth(numberToWidth(dxfLine.toInt()));
break;
case 62: // Color
pen.setColor(RS_FilterDXFRW::numberToColor(dxfLine.toInt()));
break;
default:
break;
}
}
}
} while(dxfCode.size() && code!=0);
//if(!mtCompFloat(vx1, vx2) || !mtCompFloat(vy1, vy2)) {
//graphic->addLine(vx1, vy1, vx2, vy2, currentLayerNum, add);
graphic->setActivePen(pen);
graphic->addEntity(new RS_Line{graphic,
{vx1, vy1}, {vx2, vy2}});
//}
}
// ----
// Arc:
// ----
else if(dxfLine=="ARC") {
do {
dxfCode=getBufLine();
if(dxfCode.size())
code=dxfCode.toInt();
if(dxfCode.size() && code!=0) {
dxfLine=getBufLine();
if(dxfLine.size()) {
switch(code) {
case 6: // style
pen.setLineType(RS_FilterDXFRW::nameToLineType(dxfLine));
break;
case 8: // Layer
//if(dxfLine!=lastLayer) {
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->activateLayer(dxfLine);
//lastLayer=dxfLine;
//}
break;
case 10: // Centre X
dxfLine.replace( QRegExp(","), "." );
vcx = dxfLine.toDouble();
break;
case 20: // Centre Y
dxfLine.replace( QRegExp(","), "." );
vcy = dxfLine.toDouble();
break;
case 40: // Radius
dxfLine.replace( QRegExp(","), "." );
vcr = dxfLine.toDouble();
break;
case 50: // Start Angle
dxfLine.replace( QRegExp(","), "." );
va1 = RS_Math::correctAngle(dxfLine.toDouble()/ARAD);
break;
case 51: // End Angle
dxfLine.replace( QRegExp(","), "." );
va2 = RS_Math::correctAngle(dxfLine.toDouble()/ARAD);
break;
case 39: // Thickness
pen.setWidth(numberToWidth(dxfLine.toInt()));
break;
case 62: // Color
pen.setColor(RS_FilterDXFRW::numberToColor(dxfLine.toInt()));
break;
default:
break;
}
}
}
} while(dxfCode.size() && code!=0);
//if(vcr>0.0 && !mtCompFloat(va1, va2)) {
// graphic->addArc(vcx, vcy, vcr, va1, va2, false, currentLayerNum, add);
//}
graphic->setActivePen(pen);
graphic->addEntity(new RS_Arc(graphic,
RS_ArcData(RS_Vector(vcx, vcy),
vcr, va1, va2, false)));
}
// -------
// Circle:
// -------
else if(dxfLine=="CIRCLE") {
do {
dxfCode=getBufLine();
if(dxfCode.size())
code=dxfCode.toInt();
if(dxfCode.size() && code!=0) {
dxfLine=getBufLine();
if(dxfLine.size()) {
switch(code) {
case 6: // style
pen.setLineType(RS_FilterDXFRW::nameToLineType(dxfLine));
break;
case 8: // Layer
//if(dxfLine!=lastLayer) {
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->activateLayer(dxfLine);
//lastLayer=dxfLine;
//}
break;
case 10: // Centre X
dxfLine.replace( QRegExp(","), "." );
vcx = dxfLine.toDouble();
break;
case 20: // Centre Y
dxfLine.replace( QRegExp(","), "." );
vcy = dxfLine.toDouble();
break;
case 40: // Radius
dxfLine.replace( QRegExp(","), "." );
vcr = dxfLine.toDouble();
break;
case 39: // Thickness
pen.setWidth(numberToWidth(dxfLine.toInt()));
break;
case 62: // Color
pen.setColor(RS_FilterDXFRW::numberToColor(dxfLine.toInt()));
break;
default:
break;
}
}
}
} while(dxfCode.size() && code!=0);
/*if(vcr>0.0) {
graphic->addCircle(vcx, vcy, vcr, 0.0, 360.0, false, currentLayerNum, add);
}*/
graphic->setActivePen(pen);
graphic->addEntity(new RS_Circle(graphic,
{{vcx, vcy}, vcr}));
}
// ------
// Hatch:
// ------
/*
if(dxfLine=="HATCH") {
do {
dxfCode=getBufLine();
if(dxfCode) code=dxfCode.toInt();
if(dxfCode && code!=0) {
dxfLine=getBufLine();
if(dxfLine) {
switch(code) {
case 8: // Layer
// if(dxfLine!=lastLayer) {
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->activateLayer(dxfLine);
//lastLayer=dxfLine;
//}
break;
case 10: // X1
vx1 = dxfLine.toDouble();
break;
case 20: // Y1
vy1 = dxfLine.toDouble();
//graphic->Vec[vc].CreatePoint(vy1, vx1, currentLayerNum);
//if(vc<vElements-1) ++vc;
break;
case 11: // X2
vx2 = dxfLine.toDouble();
break;
case 21: // Y2
vy2 = dxfLine.toDouble();
//graphic->Vec[vc].CreatePoint(vy2, vx2, currentLayerNum);
//if(vc<vElements-1) ++vc;
break;
default:
break;
}
}
}
}while(dxfCode && code!=0);
/ *
if(!mt.CompFloat(vx1, vx2) || !mt.CompFloat(vy1, vy2)) {
graphic->Vec[vc].CreateLine(vx1, vy1, vx2, vy2, currentLayerNum);
if(vc<vElements-1) ++vc;
}
if(++updProgress==1000) {
np->getStateWin()->UpdateProgressBar((int)(pcFact*vc)+25);
updProgress=0;
}
* /
}
*/
// -----
// Text:
// -----
else if(dxfLine=="TEXT") {
QString vtext; // the text
char vtextStyle[256]; // text style (normal_ro, cursive_ri, normal_st, ...)
double vheight=10.0; // text height
double vtextAng=0.0; // text angle
//double vradius=0.0; // text radius
//double vletterspace=2.0; // Text letter space
//double vwordspace=6.0; // Text wordspace
QString vfont; // font "normal", "cursive", ...
RS_MTextData::HAlign vhalign=RS_MTextData::HALeft;
// alignment (0=left, 1=center, 2=right)
//int vattachement=7; // 1=top left, 2, 3, 4, 5, 6, 7, 8, 9=bottom right
//unsigned vfl=0; // special flags
//RLZ: unused bool codeSeven=false; // Have we found a code seven?
vtextStyle[0] = '\0';
vfont="normal";
do {
dxfCode=getBufLine();
if(dxfCode.size())
code=dxfCode.toInt();
if(dxfCode.size() && code!=0) {
if(code!=1 && code!=3 && code!=7)
dxfLine=getBufLine();
if(dxfLine.size() || code==1 || code==3 || code==7) {
switch(code) {
case 1: // Text itself
vtext=getBufLine();
strDecodeDxfString(vtext);
break;
case 3: // Text parts (always 250 chars)
vtext=getBufLine();
break;
case 6: // style
pen.setLineType(RS_FilterDXFRW::nameToLineType(dxfLine));
break;
case 7:
// Text style (normal_ro#50.0,
// cursive_ri#20.0, normal_st)
qstrncpy(vtextStyle, getBufLine().toLatin1().data(), 249);
// get font typ:
//
{
char dummy[256];
sscanf(vtextStyle, "%[^_#\n]", dummy);
vfont=dummy;
}
// get text style:
//
/*
if(strstr(vtextStyle, "_ro"))
vfl=vfl|E_ROUNDOUT;
else if(strstr(vtextStyle, "_ri"))
vfl=vfl|E_ROUNDIN;
else
vfl=vfl|E_STRAIGHT;
*/
/*if(strstr(vtextStyle, "_fix")) {
vfl=vfl|E_FIXEDWIDTH;
}*/
// get radius, letterspace, wordspace:
//
{
char *ptr; // pointer to value
ptr = strchr(vtextStyle, '#');
if(ptr) {
// Parse radius
/*if(vfl&E_ROUNDOUT || vfl&E_ROUNDIN) {
++ptr;
if(ptr[0]) {
sscanf(ptr, "%lf", &vradius);
}
ptr = strchr(ptr, '#');
}*/
/*if(ptr) {
// Parse letter space:
++ptr;
if(ptr[0]) {
sscanf(ptr, "%lf", &vletterspace);
}
// Parse word space:
ptr = strchr(ptr, '#');
if(ptr) {
++ptr;
if(ptr[0]) {
sscanf(ptr, "%lf", &vwordspace);
}
}
}*/
}
}
//RLZ: unused codeSeven=true;
break;
case 8: // Layer
//if(dxfLine!=lastLayer) {
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->activateLayer(dxfLine);
//lastLayer=dxfLine;
//}
break;
case 10: // X1
dxfLine.replace( QRegExp(","), "." );
vx1 = dxfLine.toDouble();
break;
case 20: // Y1
dxfLine.replace( QRegExp(","), "." );
vy1 = dxfLine.toDouble();
break;
case 40: // height
dxfLine.replace( QRegExp(","), "." );
vheight = dxfLine.toDouble();
/*if(!codeSeven) {
vletterspace = vheight*0.2;
vwordspace = vheight*0.6;
}*/
break;
case 50: // angle
dxfLine.replace( QRegExp(","), "." );
vtextAng = dxfLine.toDouble() / ARAD;
break;
case 72: {// alignment
//if(!mtext) {
int v = dxfLine.toInt();
if(v==1)
vhalign = RS_MTextData::HACenter;
else if(v==2)
vhalign = RS_MTextData::HARight;
else
vhalign = RS_MTextData::HALeft;
//}
}
break;
case 39: // Thickness
pen.setWidth(numberToWidth(dxfLine.toInt()));
break;
case 62: // Color
pen.setColor(RS_FilterDXFRW::numberToColor(dxfLine.toInt()));
break;
default:
break;
}
}
}
} while(dxfCode.size() && code!=0);
char* i=strchr(vtextStyle, '#');
if (i) {
i[0] = '\0';
}
graphic->addEntity(
new RS_MText(graphic,
RS_MTextData(
RS_Vector(vx1, vy1),
vheight,
100.0,
RS_MTextData::VABottom,
vhalign,
RS_MTextData::LeftToRight,
RS_MTextData::Exact,
1.0,
vtext,
vtextStyle,
vtextAng
)
)
);
}
// ----------
// Dimension:
// ----------
else if(dxfLine=="DIMENSION") {
int typ=1;
double v10=0.0, v20=0.0;
double v13=0.0, v23=0.0;
double v14=0.0, v24=0.0;
double v15=0.0, v25=0.0;
double v16=0.0, v26=0.0;
double v40=0.0, v50=0.0;
QString dimText;
do {
dxfCode=getBufLine();
if(dxfCode.size()) {
code=dxfCode.toInt();
}
if(dxfCode.size() && code!=0) {
dxfLine=getBufLine();
if(dxfLine.size()) {
switch(code) {
case 1: // Text (if any)
dimText=dxfLine;
// Mend unproper savings of older versions:
if(dimText==" " || dimText==";;")
dimText="";
//else dimText.replace(QRegExp("%%c"), "¯");
else
strDecodeDxfString(dimText);
break;
case 6: // style
pen.setLineType(RS_FilterDXFRW::nameToLineType(dxfLine));
break;
case 8: // Layer
//if(dxfLine!=lastLayer) {
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->activateLayer(dxfLine);
//lastLayer=dxfLine;
//}
break;
case 10: // line position x
dxfLine.replace( QRegExp(","), "." );
v10 = dxfLine.toDouble();
break;
case 20: // line position y
dxfLine.replace( QRegExp(","), "." );
v20 = dxfLine.toDouble();
break;
case 13: // X1
dxfLine.replace( QRegExp(","), "." );
v13 = dxfLine.toDouble();
break;
case 23: // Y1
dxfLine.replace( QRegExp(","), "." );
v23 = dxfLine.toDouble();
break;
case 14: // X2
dxfLine.replace( QRegExp(","), "." );
v14 = dxfLine.toDouble();
break;
case 24: // Y2
dxfLine.replace( QRegExp(","), "." );
v24 = dxfLine.toDouble();
break;
case 15: // X3
dxfLine.replace( QRegExp(","), "." );
v15 = dxfLine.toDouble();
break;
case 25: // Y3
dxfLine.replace( QRegExp(","), "." );
v25 = dxfLine.toDouble();
break;
case 16: // X4
dxfLine.replace( QRegExp(","), "." );
v16 = dxfLine.toDouble();
break;
case 26: // Y4
dxfLine.replace( QRegExp(","), "." );
v26 = dxfLine.toDouble();
break;
case 40:
dxfLine.replace( QRegExp(","), "." );
v40 = dxfLine.toDouble();
break;
case 50:
dxfLine.replace( QRegExp(","), "." );
v50 = dxfLine.toDouble();
break;
case 70: // Typ
typ = dxfLine.toInt();
break;
case 39: // Thickness
pen.setWidth(numberToWidth(dxfLine.toInt()));
break;
case 62: // Color
pen.setColor(RS_FilterDXFRW::numberToColor(dxfLine.toInt()));
break;
default:
break;
}
}
}
} while(dxfCode.size() && code!=0);
//double dist;
// Remove Bit values:
if(typ>=128) {
typ-=128; // Location of Text
}
if(typ>= 64) {
typ-= 64; // Ordinate
}
switch(typ) {
// Horiz. / vert.:
case 0: {
RS_DimLinear* d =
new RS_DimLinear(
graphic,
RS_DimensionData(
RS_Vector(v10, v20),
RS_Vector(0.0, 0.0),
RS_MTextData::VABottom,
RS_MTextData::HACenter,
RS_MTextData::Exact,
1.0,
dimText,
"ISO-25",
0.0
),
RS_DimLinearData(
RS_Vector(v13, v23),
RS_Vector(v14, v24),
v50/ARAD,
0.0
)
);
d->update();
graphic->addEntity(d);
}
break;
// Aligned:
case 1: {
double angle =
RS_Vector(v13, v23).angleTo(RS_Vector(v10,v20));
double dist =
RS_Vector(v13, v23).distanceTo(RS_Vector(v10,v20));
RS_Vector defP = RS_Vector::polar(dist, angle);
defP+=RS_Vector(v14, v24);
RS_DimAligned* d =
new RS_DimAligned(
graphic,
RS_DimensionData(
defP,
RS_Vector(0.0, 0.0),
RS_MTextData::VABottom,
RS_MTextData::HACenter,
RS_MTextData::Exact,
1.0,
dimText,
"ISO-25",
0.0
),
RS_DimAlignedData(
RS_Vector(v13, v23),
RS_Vector(v14, v24)
)
);
d->update();
graphic->addEntity(d);
}
break;
// Angle:
case 2: {
RS_Line tl1{{v13, v23}, {v14, v24}};
RS_Line tl2{{v10, v20}, {v15, v25}};
//bool inters=false;
//tmpEl1.getIntersection(&tmpEl2,
// &inters, &vcx, &vcy, 0,0,0,0, false);
RS_VectorSolutions const& s = RS_Information::getIntersection(
&tl1, &tl2, false);
if (s.get(0).valid) {
vcx = s.get(0).x;
vcy = s.get(0).y;
//vcr = RS_Vector(vcx, vcy).distanceTo(v16, v26);
/*if(RS_Vector(vcx,vcy).distanceTo(v13,v23)<vcr) {
va1 = tl1.getAngle1();
} else {
va1 = tl2.getAngle2();
}
if(RS_Vector(vcx,vcy).distanceTo(v10,v20)<vcr) {
va2 = tl2.getAngle1();
} else {
va2 = tl2.getAngle2();
}
*/
/*
graphic->addDimension(vcx, vcy, va1, va2,
mtGetDistance(vcx, vcy, v13, v23),
mtGetDistance(vcx, vcy, v10, v20),
vcr,
E_ROUNDOUT,
currentLayerNum,
add);
*/
//RS_Vector dp4;
//dp4.setPolar();
RS_DimAngular* d =
new RS_DimAngular(
graphic,
RS_DimensionData(
RS_Vector(v10, v20),
RS_Vector(0.0, 0.0),
RS_MTextData::VABottom,
RS_MTextData::HACenter,
RS_MTextData::Exact,
1.0,
dimText,
"ISO-25",
0.0
),
RS_DimAngularData(
RS_Vector(v13, v23),
RS_Vector(vcx, vcy),
RS_Vector(vcx, vcy),
RS_Vector(v16, v26)
)
);
d->update();
graphic->addEntity(d);
}
}
break;
// Radius:
case 4: {
/*
graphic->addDimension(v10, v20, v15, v25,
0.0, 0.0,
v40,
E_STRAIGHT|E_RADIUS,
currentLayerNum,
add);
*/
double ang =
RS_Vector(v10, v20)
.angleTo(RS_Vector(v15, v25));
RS_Vector v2 = RS_Vector::polar(v40, ang);
RS_DimRadial* d =
new RS_DimRadial(
graphic,
RS_DimensionData(
RS_Vector(v10, v20),
RS_Vector(0.0, 0.0),
RS_MTextData::VABottom,
RS_MTextData::HACenter,
RS_MTextData::Exact,
1.0,
dimText,
"ISO-25",
0.0
),
RS_DimRadialData(
RS_Vector(v10, v20) + v2,
0.0
)
);
d->update();
graphic->addEntity(d);
}
break;
// Arrow:
case 7: {
/*
graphic->addDimension(v13, v23, v14, v24,
0.0, 0.0, 0.0,
E_STRAIGHT|E_ARROW,
currentLayerNum,
add);
*/
/*
double ang =
RS_Vector(v10, v20)
.angleTo(RS_Vector(v15, v25));
RS_Vector v2;
v2.setPolar(v40, ang);
RS_DimDiametric* d =
new RS_DimDiametric(
graphic,
RS_DimensionData(
RS_Vector(v10, v20),
RS_Vector(0.0, 0.0),
RS2::VAlignBottom,
RS2::HAlignCenter,
RS2::Exact,
1.0,
dimText,
"ISO-25",
0.0
),
RS_DimDiametricData(
RS_Vector(v10, v20) + v2,
0.0
)
);
d->update();
graphic->addEntity(d);
*/
RS_LeaderData data(true);
RS_Leader* d =
new RS_Leader(graphic, data);
d->addVertex(RS_Vector(v14, v24));
d->addVertex(RS_Vector(v10, v20));
d->update();
graphic->addEntity(d);
}
break;
}
//graphic->elementCurrent()->setText(dimText);
}
// ---------
// Hatching:
// ---------
/*
else if(dxfLine=="HATCH") {
QString patternName="45";
double patternScale=1.0;
//int numPaths=1;
//int numEdges=1;
int nextObjectTyp=T_LINE;
double v10=0.0, v20=0.0,
v11=0.0, v21=0.0,
v40=0.0, v50=0.0,
v51=0.0;
do {
dxfCode=getBufLine();
if(dxfCode) code=dxfCode.toInt();
if(dxfCode && code!=0) {
dxfLine=getBufLine();
if(dxfLine) {
switch(code) {
case 2:
patternName = dxfLine;
break;
case 6: // style
pen.setLineType(RS_FilterDXF::nameToLineType(dxfLine));
break;
case 8: // Layer
// if(dxfLine!=lastLayer) {
if (dxfLine=="(null)" || dxfLine=="default") {
dxfLine = "0";
}
graphic->activateLayer(dxfLine);
//lastLayer=dxfLine;
//}
break;
case 10: // Start point/center of boundary line/arc
dxfLine.replace( QRegExp(","), "." );
v10=dxfLine.toDouble();
break;
case 20: // Start point/center of boundary line/arc
dxfLine.replace( QRegExp(","), "." );
v20=dxfLine.toDouble();
break;
case 11: // End point of boundary line
dxfLine.replace( QRegExp(","), "." );
v11=dxfLine.toDouble();
break;
case 21: // End point of boundary line
dxfLine.replace( QRegExp(","), "." );
v21=dxfLine.toDouble();
if(nextObjectTyp==T_LINE) {
int elnu=graphic->addLine(v10, v20, v11, v21, currentLayerNum, add);
graphic->elementAt(elnu)->setFlag(E_TAGGED);
}
break;
case 40: // Radius of boundary entity
dxfLine.replace( QRegExp(","), "." );
v40=dxfLine.toDouble();
break;
case 50: // Start angle
dxfLine.replace( QRegExp(","), "." );
v50=dxfLine.toDouble();
break;
case 51: // End angle
dxfLine.replace( QRegExp(","), "." );
v51=dxfLine.toDouble();
break;
case 73: // Counterclockwise?
if(nextObjectTyp==T_ARC) {
int elnu;
if( mtCompFloat( v50, 0.0 ) && mtCompFloat( v51, 0.0 ) ) {
elnu=graphic->addCircle(v10, v20, v40, 0.0, 360.0, (bool)dxfLine.toInt(), currentLayerNum, add);
}
else {
elnu=graphic->addArc(v10, v20, v40, v50, v51, (bool)dxfLine.toInt(), currentLayerNum, add);
}
graphic->elementAt(elnu)->setFlag(E_TAGGED);
//newEl = new RElement( graphic );
//newEl->createArc(v10, v20, v40, v50, v51, (bool)dxfLine.toInt());
//boundaryList.append(newEl);
}
break;
case 41: // Scale
dxfLine.replace( QRegExp(","), "." );
patternScale=dxfLine.toDouble();
break;
case 52: // Angle
break;
case 70: // Solid (=1) or pattern (=0)
break;
case 39: // Thickness
pen.setWidth(RS_FilterDXF::numberToWidth(dxfLine.toInt()));
break;
case 62: // Color
pen.setColor(RS_FilterDXF::numberToColor(dxfLine.toInt()));
break;
case 91: // Number of boundary paths (loops)
//numPaths=dxfLine.toInt();
break;
case 92: // Typ of boundary
break;
case 93: // Number of edges in this boundary
//numEdges=dxfLine.toInt();
break;
case 72: // Edge typ
switch(dxfLine.toInt()) {
case 1: nextObjectTyp=T_LINE; break;
case 2: nextObjectTyp=T_ARC; break;
default: break;
}
break;
default:
break;
}
}
}
}while(dxfCode && code!=0);
graphic->addHatching(patternScale,
patternName,
currentLayerNum,
add);
graphic->editDelete(false);
}
*/
}
}
while(dxfLine.size() && dxfLine!="EOF");
//graphic->terminateAction();
//graphic->debugElements();
ret=true;
} else {
ret=false;
}
return ret;
}
/**
* Resets the whole object
* (base class too)
*/
void RS_FilterDXF1::reset() {
file.reset();
delBuffer();
fBufP=0;
fSize=0;
if(fPointer) {
fclose(fPointer);
fPointer=0;
}
}
/**
* Reset buffer pointer to the beginning of the buffer:
*/
void RS_FilterDXF1::resetBufP() {
fBufP=0;
}
/**
* Set buffer pointer to the given index:
*/
void RS_FilterDXF1::setBufP(int _fBufP) {
if(_fBufP<(int)fSize) {
fBufP = _fBufP;
}
}
/**
* delete buffer:
*/
void RS_FilterDXF1::delBuffer() {
if(fBuf) {
delete[] fBuf;
fBuf=0;
}
}
/**
* Remove any 13-characters in the buffer:
*/
void RS_FilterDXF1::dos2unix() {
char *src = fBuf, *dst = fBuf;
if (!fBuf)
return;
while (*src != '\0') {
if (*src == '\r') {
dosFile = true;
} else {
*dst++ = *src;
}
src++;
}
*dst = '\0';
}
// Get next line in the buffer:
// and overread ALL separators
//
// return: -Null-string: end of buffer
// -String which is the next line in buffer
//
QString RS_FilterDXF1::getBufLine() {
char *ret;
QString str;
if (fBufP >= (int)fSize)
return QString::null;
ret = &fBuf[fBufP];
// Skip empty lines
/*if (*ret == '\0' && noEmptyLines) {
while (++fBufP < (int)fSize && fBuf[fBufP] == '\0')
;
if (fBufP >= (int)fSize)
return QString::null;
ret = &fBuf[fBufP];
}*/
// Move fBufP pointer to the next line
while (fBufP < (int)fSize && fBuf[fBufP++] != '\0')
;
str = QString::fromLocal8Bit(ret).simplified();
if (str.isNull()) {
return "";
} else {
return str;
}
}
// Get next line in the buffer:
// and overread ALL separators
//
// return: -Null-string: end of buffer
// -String which is the next line in buffer
//
char* RS_FilterDXF1::getBufLineCh() {
char *ret;
if (fBufP >= (int)fSize)
return 0;
ret = &fBuf[fBufP];
// Skip empty lines
/*if (*ret == '\0' && noEmptyLines) {
while (++fBufP < (int)fSize && fBuf[fBufP] == '\0')
;
if (fBufP >= (int)fSize)
return 0;
ret = &fBuf[fBufP];
}*/
// Move fBufP pointer to the next line
while (fBufP < (int)fSize && fBuf[fBufP++] != '\0')
;
return ret;
}
// Copy buffer from a given string:
//
void RS_FilterDXF1::copyBufFrom(const char* _buf) {
if(_buf) {
fBuf = new char[strlen(_buf)+16];
strcpy(fBuf, _buf);
}
}
// Go to the next '_lstr'-line in buffer:
//
// return: true: line found
// false: end of buffer
//
bool RS_FilterDXF1::gotoBufLine(char* _lstr) {
QString l;
do {
l=getBufLine();
} while(!l.isNull() && l!=_lstr);
if(!l.isNull())
return true;
return false;
}
// Goto next line where the string _lstr appears:
//
// return: true: string in line found
// false: end of buffer
//
//
bool RS_FilterDXF1::gotoBufLineString(char* _lstr) {
QString l;
do {
l=getBufLine();
} while(!l.isNull() && l.contains(_lstr));
if(!l.isNull())
return true;
return false;
}
// Replace bynary Bytes (<32) by an other (given) byte:
//
void RS_FilterDXF1::replaceBinaryBytesBy(char _c) {
int bc;
for(bc=0; bc<(int)fSize; ++bc) {
if(fBuf[bc]<32 && fBuf[bc]>=0) {
fBuf[bc] = _c;
}
}
}
// Separate buffer (change chars sc1 and sc2 in '\0'
//
void RS_FilterDXF1::separateBuf(char _c1,
char _c2,
char _c3,
char _c4) {
int bc;
for(bc=0; bc<(int)fSize; ++bc) {
if(fBuf[bc]==_c1 || fBuf[bc]==_c2 ||
fBuf[bc]==_c3 || fBuf[bc]==_c4 ) {
fBuf[bc] = '\0';
}
}
}
// remove comment between '_fc' and '_lc'
// comments get replaced by '\0'
//
void RS_FilterDXF1::removeComment(char _fc, char _lc) {
bool rem=false; // Are we removing currrently?
int bc; // counter
for(bc=0; bc<(int)fSize; ++bc) {
if(fBuf[bc]==_fc)
rem=true;
if(fBuf[bc]==_lc) {
fBuf[bc]='\0';
rem=false;
}
if(rem)
fBuf[bc]='\0';
}
}
// Read file '_name' in buffer (buf)
//
// '_bNum' : Max number of Bytes
// : -1: All
// return: true: successful
// false: file not found
//
bool RS_FilterDXF1::readFileInBuffer(char* _name, int _bNum) {
file.setFileName(_name);
return readFileInBuffer(_bNum);
}
// Read file in buffer (buf)
//
// 'bNum' : Max number of Bytes
// : -1: All
// return: true: successful
// false: file not found
//
bool RS_FilterDXF1::readFileInBuffer(int _bNum) {
fPointer = fopen(name.toLatin1().data(), "rb");//RLZ verify with locales
if(fPointer) {
if(file.open(fPointer, QIODevice::ReadOnly)) {
fSize=file.size();
if(_bNum==-1)
_bNum=fSize;
fBuf = new char[_bNum+16];
file.read(fBuf, _bNum);
fBuf[_bNum] = '\0';
file.close();
}
fclose(fPointer);
// Convert 13/10 to 10
dos2unix();
fPointer=nullptr;
return true;
}
return false;
}
// Decode a DXF string to the C-convention (special character \P is a \n)
//
void RS_FilterDXF1::strDecodeDxfString(QString& str) {
if (str.isEmpty())
return;
str.replace(QRegExp("%%c"), QChar(0xF8)); // Diameter
str.replace(QRegExp("%%d"), QChar(0xB0)); // Degree
str.replace(QRegExp("%%p"), QChar(0xB1)); // Plus/minus
str.replace(QRegExp("\\\\[pP]"), QChar('\n'));
}
// Compare two double values:
//
// return: true: values are equal
// false: values are not equal
//
bool RS_FilterDXF1::mtCompFloat(double _v1, double _v2, double _tol) {
double delta = _v2-_v1;
if(delta>-_tol && delta<_tol)
return true;
else
return false;
}
/**
* Converts a line width number (e.g. 1) into a RS2::LineWidth.
*/
RS2::LineWidth RS_FilterDXF1::numberToWidth(int num) {
switch (num) {
case -1:
return RS2::WidthByLayer;
break;
case -2:
return RS2::WidthByBlock;
break;
case -3:
return RS2::WidthDefault;
break;
default:
if (num<3) {
return RS2::Width00;
} else if (num<7) {
return RS2::Width01;
} else if (num<11) {
return RS2::Width02;
} else if (num<14) {
return RS2::Width03;
} else if (num<16) {
return RS2::Width04;
} else if (num<19) {
return RS2::Width05;
} else if (num<22) {
return RS2::Width06;
} else if (num<27) {
return RS2::Width07;
} else if (num<32) {
return RS2::Width08;
} else if (num<37) {
return RS2::Width09;
} else if (num<45) {
return RS2::Width10;
} else if (num<52) {
return RS2::Width11;
} else if (num<57) {
return RS2::Width12;
} else if (num<65) {
return RS2::Width13;
} else if (num<75) {
return RS2::Width14;
} else if (num<85) {
return RS2::Width15;
} else if (num<95) {
return RS2::Width16;
} else if (num<103) {
return RS2::Width17;
} else if (num<112) {
return RS2::Width18;
} else if (num<130) {
return RS2::Width19;
} else if (num<149) {
return RS2::Width20;
} else if (num<180) {
return RS2::Width21;
} else if (num<205) {
return RS2::Width22;
} else {
return RS2::Width23;
}
break;
}
return (RS2::LineWidth)num;
}
/**
* Converts a RS2::LineWidth into an int width.
*/
int RS_FilterDXF1::widthToNumber(RS2::LineWidth width) {
switch (width) {
case RS2::WidthByLayer:
return -1;
break;
case RS2::WidthByBlock:
return -2;
break;
case RS2::WidthDefault:
return -3;
break;
default:
return (int)width;
break;
}
return (int)width;
}
// EOF
|
; Copyright © 2021, VideoLAN and dav1d authors
; Copyright © 2021, Two Orioles, LLC
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this
; list of conditions and the following disclaimer.
;
; 2. 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.
;
; 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 "config.asm"
%include "ext/x86/x86inc.asm"
SECTION_RODATA
wiener_shufA: db 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 8, 9, 8, 9, 10, 11
wiener_shufB: db 6, 7, 4, 5, 8, 9, 6, 7, 10, 11, 8, 9, 12, 13, 10, 11
wiener_shufC: db 6, 7, 8, 9, 8, 9, 10, 11, 10, 11, 12, 13, 12, 13, 14, 15
wiener_shufD: db 2, 3, -1, -1, 4, 5, -1, -1, 6, 7, -1, -1, 8, 9, -1, -1
wiener_shufE: db 0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15
wiener_lshuf5: db 0, 1, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
wiener_lshuf7: db 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7
sgr_lshuf3: db 0, 1, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
sgr_lshuf5: db 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
pb_0to15: db 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
pb_m14_m13: times 8 db -14,-13
pb_m10_m9: times 8 db -10, -9
pb_m6_m5: times 8 db -6, -5
pb_m2_m1: times 8 db -2, -1
pb_2_3: times 8 db 2, 3
pb_6_7: times 8 db 6, 7
pw_256: times 8 dw 256
pw_1023: times 8 dw 1023
pd_8: times 4 dd 8
pd_4096: times 4 dd 4096
pd_34816: times 4 dd 34816
pd_m262128: times 4 dd -262128
pd_0xffff: times 4 dd 0xffff
pd_0xf00800a4: times 4 dd 0xf00800a4
pd_0xf00801c7: times 4 dd 0xf00801c7
pd_0xfffffff0: times 4 dd 0xfffffff0
wiener_shifts: dw 4, 4, 2048, 2048, 1, 1, 8192, 8192
wiener_round: dd 1049600, 1048832
cextern sgr_x_by_x
SECTION .text
%macro movif64 2 ; dst, src
%if ARCH_X86_64
mov %1, %2
%endif
%endmacro
%macro movif32 2 ; dst, src
%if ARCH_X86_32
mov %1, %2
%endif
%endmacro
INIT_XMM ssse3
%if ARCH_X86_32
DECLARE_REG_TMP 4, 6
%if STACK_ALIGNMENT < 16
%assign extra_stack 14*16
%else
%assign extra_stack 12*16
%endif
cglobal wiener_filter7_16bpc, 5, 7, 8, -384*12-16-extra_stack, \
dst, dst_stride, left, lpf, lpf_stride, w, flt
%if STACK_ALIGNMENT < 16
%define lpfm dword [esp+calloff+16*12+ 0]
%define lpf_stridem dword [esp+calloff+16*12+ 4]
%define wm dword [esp+calloff+16*12+ 8]
%define hd dword [esp+calloff+16*12+12]
%define edgeb byte [esp+calloff+16*12+16]
%define edged dword [esp+calloff+16*12+16]
%else
%define hd dword r6m
%define edgeb byte r8m
%endif
%define PICmem dword [esp+calloff+4*0]
%define t0m dword [esp+calloff+4*1] ; wiener ring buffer pointers
%define t1m dword [esp+calloff+4*2]
%define t2m dword [esp+calloff+4*3]
%define t3m dword [esp+calloff+4*4]
%define t4m dword [esp+calloff+4*5]
%define t5m dword [esp+calloff+4*6]
%define t6m dword [esp+calloff+4*7]
%define t2 t2m
%define t3 t3m
%define t4 t4m
%define t5 t5m
%define t6 t6m
%define m8 [esp+calloff+16*2]
%define m9 [esp+calloff+16*3]
%define m10 [esp+calloff+16*4]
%define m11 [esp+calloff+16*5]
%define m12 [esp+calloff+16*6]
%define m13 [esp+calloff+16*7]
%define m14 [esp+calloff+16*8]
%define m15 [esp+calloff+16*9]
%define r10 r5
%define base t0-wiener_shifts
%assign calloff 0
%if STACK_ALIGNMENT < 16
mov wd, [rstk+stack_offset+24]
mov lpf_stridem, lpf_strideq
mov wm, wd
mov r4, [rstk+stack_offset+28]
mov hd, r4
mov r4, [rstk+stack_offset+36]
mov edged, r4 ; edge
%endif
%else
DECLARE_REG_TMP 4, 9, 7, 11, 12, 13, 14 ; wiener ring buffer pointers
cglobal wiener_filter7_16bpc, 5, 15, 16, -384*12-16, dst, dst_stride, left, lpf, \
lpf_stride, w, edge, flt, h
%define base
%endif
%if ARCH_X86_64 || STACK_ALIGNMENT >= 16
movifnidn wd, wm
%endif
%if ARCH_X86_64
mov fltq, fltmp
mov edged, r8m
mov hd, r6m
mov t3d, r9m ; pixel_max
movq m13, [fltq]
movq m15, [fltq+16]
%else
%if STACK_ALIGNMENT < 16
mov t0, [rstk+stack_offset+32]
mov t1, [rstk+stack_offset+40] ; pixel_max
movq m1, [t0] ; fx
movq m3, [t0+16] ; fy
LEA t0, wiener_shifts
%else
LEA t0, wiener_shifts
mov fltq, r7m
movq m1, [fltq]
movq m3, [fltq+16]
mov t1, r9m ; pixel_max
%endif
mov PICmem, t0
%endif
mova m6, [base+wiener_shufA]
mova m7, [base+wiener_shufB]
%if ARCH_X86_64
lea t4, [wiener_shifts]
add wd, wd
pshufd m12, m13, q0000 ; x0 x1
pshufd m13, m13, q1111 ; x2 x3
pshufd m14, m15, q0000 ; y0 y1
pshufd m15, m15, q1111 ; y2 y3
mova m8, [wiener_shufC]
mova m9, [wiener_shufD]
add lpfq, wq
lea t1, [rsp+wq+16]
add dstq, wq
neg wq
shr t3d, 11
%define base t4-wiener_shifts
movd m10, [base+wiener_round+t3*4]
movq m11, [base+wiener_shifts+t3*8]
pshufd m10, m10, q0000
pshufd m0, m11, q0000
pshufd m11, m11, q1111
pmullw m12, m0 ; upshift filter coefs to make the
pmullw m13, m0 ; horizontal downshift constant
DEFINE_ARGS dst, dst_stride, left, lpf, lpf_stride, _, edge, _, h, _, w
%define lpfm [rsp+0]
%define lpf_stridem [rsp+8]
%define base
%define wiener_lshuf7_mem [wiener_lshuf7]
%define pd_m262128_mem [pd_m262128]
%else
add wd, wd
mova m4, [base+wiener_shufC]
mova m5, [base+wiener_shufD]
pshufd m0, m1, q0000
pshufd m1, m1, q1111
pshufd m2, m3, q0000
pshufd m3, m3, q1111
mova m8, m4
mova m9, m5
mova m14, m2
mova m15, m3
shr t1, 11
add lpfq, wq
mova m3, [base+pd_m262128]
movd m4, [base+wiener_round+t1*4]
movq m5, [base+wiener_shifts+t1*8]
lea t1, [esp+extra_stack+wq+16]
add dstq, wq
neg wq
pshufd m4, m4, q0000
pshufd m2, m5, q0000
pshufd m5, m5, q1111
mov wm, wq
pmullw m0, m2
pmullw m1, m2
mova m2, [base+wiener_lshuf7]
%define pd_m262128_mem [esp+calloff+16*10]
mova pd_m262128_mem, m3
mova m10, m4
mova m11, m5
mova m12, m0
mova m13, m1
%define wiener_lshuf7_mem [esp+calloff+16*11]
mova wiener_lshuf7_mem, m2
%endif
test edgeb, 4 ; LR_HAVE_TOP
jz .no_top
call .h_top
%if ARCH_X86_64
add lpfq, lpf_strideq
%else
add lpfq, lpf_stridem
%endif
mov t6, t1
mov t5, t1
add t1, 384*2
call .h_top
movif32 lpf_strideq, lpf_stridem
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
mov t4, t1
add t1, 384*2
movif64 lpf_stridem, lpf_strideq
add r10, lpf_strideq
mov lpfm, r10 ; below
call .h
mov t3, t1
mov t2, t1
dec hd
jz .v1
add lpfq, dst_strideq
add t1, 384*2
call .h
mov t2, t1
dec hd
jz .v2
add lpfq, dst_strideq
add t1, 384*2
call .h
dec hd
jz .v3
.main:
lea t0, [t1+384*2]
.main_loop:
call .hv
dec hd
jnz .main_loop
test edgeb, 8 ; LR_HAVE_BOTTOM
jz .v3
mov lpfq, lpfm
call .hv_bottom
add lpfq, lpf_stridem
call .hv_bottom
.v1:
call .v
RET
.no_top:
movif32 lpf_strideq, lpf_stridem
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
movif64 lpf_stridem, lpf_strideq
lea r10, [r10+lpf_strideq*2]
mov lpfm, r10
call .h
mov t6, t1
mov t5, t1
mov t4, t1
mov t3, t1
mov t2, t1
dec hd
jz .v1
add lpfq, dst_strideq
add t1, 384*2
call .h
mov t2, t1
dec hd
jz .v2
add lpfq, dst_strideq
add t1, 384*2
call .h
dec hd
jz .v3
lea t0, [t1+384*2]
call .hv
dec hd
jz .v3
add t0, 384*8
call .hv
dec hd
jnz .main
.v3:
call .v
movif32 wq, wm
.v2:
call .v
movif32 wq, wm
jmp .v1
.extend_right:
%assign stack_offset stack_offset+8
%assign calloff 8
movif32 t0, PICmem
pxor m0, m0
movd m1, wd
mova m2, [base+pb_0to15]
pshufb m1, m0
mova m0, [base+pb_6_7]
psubb m0, m1
pminub m0, m2
pshufb m3, m0
mova m0, [base+pb_m2_m1]
psubb m0, m1
pminub m0, m2
pshufb m4, m0
mova m0, [base+pb_m10_m9]
psubb m0, m1
pminub m0, m2
pshufb m5, m0
movif32 t0, t0m
ret
%assign stack_offset stack_offset-4
%assign calloff 4
.h:
movif64 wq, r5
movif32 wq, wm
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
movq m3, [leftq]
movhps m3, [lpfq+wq]
add leftq, 8
jmp .h_main
.h_extend_left:
mova m3, [lpfq+wq] ; avoid accessing memory located
pshufb m3, wiener_lshuf7_mem ; before the start of the buffer
jmp .h_main
.h_top:
movif64 wq, r5
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
.h_loop:
movu m3, [lpfq+wq-8]
.h_main:
mova m4, [lpfq+wq+0]
movu m5, [lpfq+wq+8]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .h_have_right
cmp wd, -18
jl .h_have_right
call .extend_right
.h_have_right:
pshufb m0, m3, m6
pshufb m1, m4, m7
paddw m0, m1
pshufb m3, m8
pmaddwd m0, m12
pshufb m1, m4, m9
paddw m3, m1
pshufb m1, m4, m6
pmaddwd m3, m13
pshufb m2, m5, m7
paddw m1, m2
mova m2, pd_m262128_mem ; (1 << 4) - (1 << 18)
pshufb m4, m8
pmaddwd m1, m12
pshufb m5, m9
paddw m4, m5
pmaddwd m4, m13
paddd m0, m2
paddd m1, m2
paddd m0, m3
paddd m1, m4
psrad m0, 4
psrad m1, 4
packssdw m0, m1
psraw m0, 1
mova [t1+wq], m0
add wq, 16
jl .h_loop
movif32 wq, wm
ret
ALIGN function_align
.hv:
add lpfq, dst_strideq
movif64 wq, r5
movif32 t0m, t0
movif32 t1m, t1
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv_extend_left
movq m3, [leftq]
movhps m3, [lpfq+wq]
add leftq, 8
jmp .hv_main
.hv_extend_left:
mova m3, [lpfq+wq]
pshufb m3, wiener_lshuf7_mem
jmp .hv_main
.hv_bottom:
movif64 wq, r5
movif32 t0m, t0
movif32 t1m, t1
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv_extend_left
.hv_loop:
movu m3, [lpfq+wq-8]
.hv_main:
mova m4, [lpfq+wq+0]
movu m5, [lpfq+wq+8]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .hv_have_right
cmp wd, -18
jl .hv_have_right
call .extend_right
.hv_have_right:
movif32 t1, t4m
movif32 t0, t2m
pshufb m0, m3, m6
pshufb m1, m4, m7
paddw m0, m1
pshufb m3, m8
pmaddwd m0, m12
pshufb m1, m4, m9
paddw m3, m1
pshufb m1, m4, m6
pmaddwd m3, m13
pshufb m2, m5, m7
paddw m1, m2
mova m2, pd_m262128_mem
pshufb m4, m8
pmaddwd m1, m12
pshufb m5, m9
paddw m4, m5
pmaddwd m4, m13
paddd m0, m2
paddd m1, m2
%if ARCH_X86_64
mova m2, [t4+wq]
paddw m2, [t2+wq]
mova m5, [t3+wq]
%else
mova m2, [t1+wq]
paddw m2, [t0+wq]
mov t1, t3m
mov t0, t5m
mova m5, [t1+wq]
mov t1, t1m
%endif
paddd m0, m3
paddd m1, m4
psrad m0, 4
psrad m1, 4
packssdw m0, m1
%if ARCH_X86_64
mova m4, [t5+wq]
paddw m4, [t1+wq]
psraw m0, 1
paddw m3, m0, [t6+wq]
%else
mova m4, [t0+wq]
paddw m4, [t1+wq]
mov t0, t0m
mov t1, t6m
psraw m0, 1
paddw m3, m0, [t1+wq]
%endif
mova [t0+wq], m0
punpcklwd m0, m2, m5
pmaddwd m0, m15
punpckhwd m2, m5
pmaddwd m2, m15
punpcklwd m1, m3, m4
pmaddwd m1, m14
punpckhwd m3, m4
pmaddwd m3, m14
paddd m0, m10
paddd m2, m10
paddd m0, m1
paddd m2, m3
psrad m0, 6
psrad m2, 6
packssdw m0, m2
pmulhw m0, m11
pxor m1, m1
pmaxsw m0, m1
mova [dstq+wq], m0
add wq, 16
jl .hv_loop
%if ARCH_X86_64
mov t6, t5
mov t5, t4
mov t4, t3
mov t3, t2
mov t2, t1
mov t1, t0
mov t0, t6
%else
mov r5, t5m
mov t1, t4m
mov t6m, r5
mov t5m, t1
mov r5, t3m
mov t1, t2m
mov t4m, r5
mov t3m, t1
mov r5, t1m
mov t1, t0
mov t2m, r5
mov t0, t6m
mov wq, wm
%endif
add dstq, dst_strideq
ret
.v:
movif64 wq, r5
movif32 t0m, t0
movif32 t1m, t1
.v_loop:
%if ARCH_X86_64
mova m1, [t4+wq]
paddw m1, [t2+wq]
mova m2, [t3+wq]
mova m4, [t1+wq]
paddw m3, m4, [t6+wq]
paddw m4, [t5+wq]
%else
mov t0, t4m
mov t1, t2m
mova m1, [t0+wq]
paddw m1, [t1+wq]
mov t0, t3m
mov t1, t1m
mova m2, [t0+wq]
mova m4, [t1+wq]
mov t0, t6m
mov t1, t5m
paddw m3, m4, [t0+wq]
paddw m4, [t1+wq]
%endif
punpcklwd m0, m1, m2
pmaddwd m0, m15
punpckhwd m1, m2
pmaddwd m1, m15
punpcklwd m2, m3, m4
pmaddwd m2, m14
punpckhwd m3, m4
pmaddwd m3, m14
paddd m0, m10
paddd m1, m10
paddd m0, m2
paddd m1, m3
psrad m0, 6
psrad m1, 6
packssdw m0, m1
pmulhw m0, m11
pxor m1, m1
pmaxsw m0, m1
mova [dstq+wq], m0
add wq, 16
jl .v_loop
%if ARCH_X86_64
mov t6, t5
mov t5, t4
mov t4, t3
mov t3, t2
mov t2, t1
%else
mov t0, t5m
mov t1, t4m
mov r5, t3m
mov t6m, t0
mov t5m, t1
mov t4m, r5
mov r5, t2m
mov t1, t1m
mov t0, t0m
mov t3m, r5
mov t2m, t1
%endif
add dstq, dst_strideq
ret
%if ARCH_X86_32
%if STACK_ALIGNMENT < 16
%assign stack_size 12*16+384*8
%else
%assign stack_size 11*16+384*8
%endif
cglobal wiener_filter5_16bpc, 5, 7, 8, -stack_size, dst, dst_stride, left, \
lpf, lpf_stride, w, flt
%if STACK_ALIGNMENT < 16
%define lpfm dword [esp+calloff+4*6]
%define lpf_stridem dword [esp+calloff+4*7]
%define wm dword [esp+calloff+16*10+0]
%define hd dword [esp+calloff+16*10+4]
%define edgeb byte [esp+calloff+16*10+8]
%define edged dword [esp+calloff+16*10+8]
%else
%define hd dword r6m
%define edgeb byte r8m
%endif
%define PICmem dword [esp+calloff+4*0]
%define t0m dword [esp+calloff+4*1] ; wiener ring buffer pointers
%define t1m dword [esp+calloff+4*2]
%define t2m dword [esp+calloff+4*3]
%define t3m dword [esp+calloff+4*4]
%define t4m dword [esp+calloff+4*5]
%define t2 t2m
%define t3 t3m
%define t4 t4m
%define m8 [esp+calloff+16*2]
%define m9 [esp+calloff+16*3]
%define m10 [esp+calloff+16*4]
%define m11 [esp+calloff+16*5]
%define m12 [esp+calloff+16*6]
%define m13 [esp+calloff+16*7]
%define m14 [esp+calloff+16*8]
%define m15 [esp+calloff+16*9]
%define base t0-wiener_shifts
%assign calloff 0
%if STACK_ALIGNMENT < 16
mov wd, [rstk+stack_offset+24]
mov lpf_stridem, lpf_strideq
mov wm, wd
mov r4, [rstk+stack_offset+28]
mov hd, r4
mov r4, [rstk+stack_offset+36]
mov edged, r4 ; edge
%endif
%else
cglobal wiener_filter5_16bpc, 5, 14, 16, 384*8+16, dst, dst_stride, left, lpf, \
lpf_stride, w, edge, flt, h
%define base
%endif
%if ARCH_X86_64 || STACK_ALIGNMENT >= 16
movifnidn wd, wm
%endif
%if ARCH_X86_64
mov fltq, fltmp
mov edged, r8m
mov hd, r6m
mov t3d, r9m ; pixel_max
movq m12, [fltq]
movq m14, [fltq+16]
%else
%if STACK_ALIGNMENT < 16
mov t0, [rstk+stack_offset+32]
mov t1, [rstk+stack_offset+40] ; pixel_max
movq m1, [t0] ; fx
movq m3, [t0+16] ; fy
LEA t0, wiener_shifts
%else
LEA t0, wiener_shifts
mov fltq, r7m
movq m1, [fltq]
movq m3, [fltq+16]
mov t1, r9m ; pixel_max
%endif
mov PICmem, t0
%endif
mova m5, [base+wiener_shufE]
mova m6, [base+wiener_shufB]
mova m7, [base+wiener_shufD]
%if ARCH_X86_64
lea t4, [wiener_shifts]
add wd, wd
punpcklwd m11, m12, m12
pshufd m11, m11, q1111 ; x1
pshufd m12, m12, q1111 ; x2 x3
punpcklwd m13, m14, m14
pshufd m13, m13, q1111 ; y1
pshufd m14, m14, q1111 ; y2 y3
shr t3d, 11
mova m8, [pd_m262128] ; (1 << 4) - (1 << 18)
add lpfq, wq
lea t1, [rsp+wq+16]
add dstq, wq
neg wq
%define base t4-wiener_shifts
movd m9, [base+wiener_round+t3*4]
movq m10, [base+wiener_shifts+t3*8]
pshufd m9, m9, q0000
pshufd m0, m10, q0000
pshufd m10, m10, q1111
mova m15, [wiener_lshuf5]
pmullw m11, m0
pmullw m12, m0
DEFINE_ARGS dst, dst_stride, left, lpf, lpf_stride, _, edge, _, h, _, w
%define lpfm [rsp+0]
%define lpf_stridem [rsp+8]
%define base
%else
add wd, wd
punpcklwd m0, m1, m1
pshufd m0, m0, q1111 ; x1
pshufd m1, m1, q1111 ; x2 x3
punpcklwd m2, m3, m3
pshufd m2, m2, q1111 ; y1
pshufd m3, m3, q1111 ; y2 y3
mova m4, [base+pd_m262128] ; (1 << 4) - (1 << 18)
mova m13, m2
mova m14, m3
mova m8, m4
shr t1, 11
add lpfq, wq
movd m2, [base+wiener_round+t1*4]
movq m3, [base+wiener_shifts+t1*8]
%if STACK_ALIGNMENT < 16
lea t1, [esp+16*11+wq+16]
%else
lea t1, [esp+16*10+wq+16]
%endif
add dstq, wq
neg wq
pshufd m2, m2, q0000
pshufd m4, m3, q0000
pshufd m3, m3, q1111
mov wm, wq
pmullw m0, m4
pmullw m1, m4
mova m4, [base+wiener_lshuf5]
mova m9, m2
mova m10, m3
mova m11, m0
mova m12, m1
mova m15, m4
%endif
test edgeb, 4 ; LR_HAVE_TOP
jz .no_top
call .h_top
%if ARCH_X86_64
add lpfq, lpf_strideq
%else
add lpfq, lpf_stridem
%endif
mov t4, t1
add t1, 384*2
call .h_top
movif32 lpf_strideq, lpf_stridem
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
mov t3, t1
add t1, 384*2
movif64 lpf_stridem, lpf_strideq
add r10, lpf_strideq
mov lpfm, r10 ; below
call .h
mov t2, t1
dec hd
jz .v1
add lpfq, dst_strideq
add t1, 384*2
call .h
dec hd
jz .v2
.main:
mov t0, t4
.main_loop:
call .hv
dec hd
jnz .main_loop
test edgeb, 8 ; LR_HAVE_BOTTOM
jz .v2
mov lpfq, lpfm
call .hv_bottom
add lpfq, lpf_stridem
call .hv_bottom
.end:
RET
.no_top:
movif32 lpf_strideq, lpf_stridem
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
movif64 lpf_stridem, lpf_strideq
lea r10, [r10+lpf_strideq*2]
mov lpfm, r10
call .h
mov t4, t1
mov t3, t1
mov t2, t1
dec hd
jz .v1
add lpfq, dst_strideq
add t1, 384*2
call .h
dec hd
jz .v2
lea t0, [t1+384*2]
call .hv
dec hd
jz .v2
add t0, 384*6
call .hv
dec hd
jnz .main
.v2:
call .v
%if ARCH_X86_64
mov t4, t3
mov t3, t2
mov t2, t1
%else
mov t0, t3m
mov r5, t2m
mov t1, t1m
mov t4m, t0
mov t3m, r5
mov t2m, t1
mov wq, wm
%endif
add dstq, dst_strideq
.v1:
call .v
jmp .end
.extend_right:
%assign stack_offset stack_offset+8
%assign calloff 8
movif32 t0, PICmem
pxor m1, m1
movd m2, wd
mova m0, [base+pb_2_3]
pshufb m2, m1
mova m1, [base+pb_m6_m5]
psubb m0, m2
psubb m1, m2
mova m2, [base+pb_0to15]
pminub m0, m2
pminub m1, m2
pshufb m3, m0
pshufb m4, m1
ret
%assign stack_offset stack_offset-4
%assign calloff 4
.h:
movif64 wq, r5
movif32 wq, wm
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
mova m4, [lpfq+wq]
movd m3, [leftq+4]
pslldq m4, 4
por m3, m4
add leftq, 8
jmp .h_main
.h_extend_left:
mova m3, [lpfq+wq] ; avoid accessing memory located
pshufb m3, m15 ; before the start of the buffer
jmp .h_main
.h_top:
movif64 wq, r5
movif32 wq, wm
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
.h_loop:
movu m3, [lpfq+wq-4]
.h_main:
movu m4, [lpfq+wq+4]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .h_have_right
cmp wd, -18
jl .h_have_right
call .extend_right
.h_have_right:
pshufb m0, m3, m5
pmaddwd m0, m11
pshufb m1, m4, m5
pmaddwd m1, m11
pshufb m2, m3, m6
pshufb m3, m7
paddw m2, m3
pshufb m3, m4, m6
pmaddwd m2, m12
pshufb m4, m7
paddw m3, m4
pmaddwd m3, m12
paddd m0, m8
paddd m1, m8
paddd m0, m2
paddd m1, m3
psrad m0, 4
psrad m1, 4
packssdw m0, m1
psraw m0, 1
mova [t1+wq], m0
add wq, 16
jl .h_loop
movif32 wq, wm
ret
ALIGN function_align
.hv:
add lpfq, dst_strideq
movif64 wq, r5
movif32 t0m, t0
movif32 t1m, t1
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv_extend_left
mova m4, [lpfq+wq]
movd m3, [leftq+4]
pslldq m4, 4
por m3, m4
add leftq, 8
jmp .hv_main
.hv_extend_left:
mova m3, [lpfq+wq]
pshufb m3, m15
jmp .hv_main
.hv_bottom:
movif64 wq, r5
movif32 t0m, t0
movif32 t1m, t1
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv_extend_left
.hv_loop:
movu m3, [lpfq+wq-4]
.hv_main:
movu m4, [lpfq+wq+4]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .hv_have_right
cmp wd, -18
jl .hv_have_right
call .extend_right
.hv_have_right:
movif32 t1, t1m
movif32 t0, t3m
pshufb m0, m3, m5
pmaddwd m0, m11
pshufb m1, m4, m5
pmaddwd m1, m11
pshufb m2, m3, m6
pshufb m3, m7
paddw m2, m3
pshufb m3, m4, m6
pmaddwd m2, m12
pshufb m4, m7
paddw m3, m4
pmaddwd m3, m12
paddd m0, m8
paddd m1, m8
paddd m0, m2
%if ARCH_X86_64
mova m2, [t3+wq]
paddw m2, [t1+wq]
paddd m1, m3
mova m4, [t2+wq]
%else
mova m2, [t0+wq]
mov t0, t2m
paddw m2, [t1+wq]
mov t1, t4m
paddd m1, m3
mova m4, [t0+wq]
mov t0, t0m
%endif
punpckhwd m3, m2, m4
pmaddwd m3, m14
punpcklwd m2, m4
%if ARCH_X86_64
mova m4, [t4+wq]
%else
mova m4, [t1+wq]
%endif
psrad m0, 4
psrad m1, 4
packssdw m0, m1
pmaddwd m2, m14
psraw m0, 1
mova [t0+wq], m0
punpckhwd m1, m0, m4
pmaddwd m1, m13
punpcklwd m0, m4
pmaddwd m0, m13
paddd m3, m9
paddd m2, m9
paddd m1, m3
paddd m0, m2
psrad m1, 6
psrad m0, 6
packssdw m0, m1
pmulhw m0, m10
pxor m1, m1
pmaxsw m0, m1
mova [dstq+wq], m0
add wq, 16
jl .hv_loop
%if ARCH_X86_64
mov t4, t3
mov t3, t2
mov t2, t1
mov t1, t0
mov t0, t4
%else
mov r5, t3m
mov t1, t2m
mov t4m, r5
mov t3m, t1
mov r5, t1m
mov t1, t0
mov t2m, r5
mov t0, t4m
mov wq, wm
%endif
add dstq, dst_strideq
ret
.v:
movif64 wq, r5
movif32 t1m, t1
.v_loop:
%if ARCH_X86_64
mova m0, [t1+wq]
paddw m2, m0, [t3+wq]
mova m1, [t2+wq]
mova m4, [t4+wq]
%else
mov t0, t3m
mova m0, [t1+wq]
mov t1, t2m
paddw m2, m0, [t0+wq]
mov t0, t4m
mova m1, [t1+wq]
mova m4, [t0+wq]
%endif
punpckhwd m3, m2, m1
pmaddwd m3, m14
punpcklwd m2, m1
pmaddwd m2, m14
punpckhwd m1, m0, m4
pmaddwd m1, m13
punpcklwd m0, m4
pmaddwd m0, m13
paddd m3, m9
paddd m2, m9
paddd m1, m3
paddd m0, m2
psrad m1, 6
psrad m0, 6
packssdw m0, m1
pmulhw m0, m10
pxor m1, m1
pmaxsw m0, m1
mova [dstq+wq], m0
add wq, 16
%if ARCH_X86_64
jl .v_loop
%else
jge .v_end
mov t1, t1m
jmp .v_loop
.v_end:
%endif
ret
%macro GATHERDD 3 ; dst, src, tmp
movd %3d, %2
%if ARCH_X86_64
movd %1, [r13+%3]
pextrw %3d, %2, 2
pinsrw %1, [r13+%3+2], 3
pextrw %3d, %2, 4
pinsrw %1, [r13+%3+2], 5
pextrw %3d, %2, 6
pinsrw %1, [r13+%3+2], 7
%else
movd %1, [base+sgr_x_by_x-0xf03+%3]
pextrw %3, %2, 2
pinsrw %1, [base+sgr_x_by_x-0xf03+%3+2], 3
pextrw %3, %2, 4
pinsrw %1, [base+sgr_x_by_x-0xf03+%3+2], 5
pextrw %3, %2, 6
pinsrw %1, [base+sgr_x_by_x-0xf03+%3+2], 7
%endif
%endmacro
%macro GATHER_X_BY_X 5 ; dst, src0, src1, tmp32, tmp32_restore
%if ARCH_X86_64
%define tmp r14
%else
%define tmp %4
%endif
GATHERDD %1, %2, tmp
GATHERDD %2, %3, tmp
movif32 %4, %5
psrld %1, 24
psrld %2, 24
packssdw %1, %2
%endmacro
%macro MAXSD 3-4 0 ; dst, src, restore_tmp
pcmpgtd %3, %1, %2
pand %1, %3
pandn %3, %2
por %1, %3
%if %4 == 1
pxor %3, %3
%endif
%endmacro
%macro MULLD 3 ; dst, src, tmp
pmulhuw %3, %1, %2
pmullw %1, %2
pslld %3, 16
paddd %1, %3
%endmacro
%if ARCH_X86_32
DECLARE_REG_TMP 0, 1, 2, 3, 4
%if STACK_ALIGNMENT < 16
%assign extra_stack 5*16
%else
%assign extra_stack 3*16
%endif
cglobal sgr_filter_5x5_16bpc, 1, 7, 8, -400*24-16-extra_stack, \
dst, dst_stride, left, lpf, lpf_stride, w, params, h
%if STACK_ALIGNMENT < 16
%define dstm dword [esp+calloff+16*0+4*6]
%define dst_stridemp dword [esp+calloff+16*0+4*7]
%define leftm dword [esp+calloff+16*3+4*0]
%define lpfm dword [esp+calloff+16*3+4*1]
%define lpf_stridem dword [esp+calloff+16*3+4*2]
%define w0m dword [esp+calloff+16*3+4*3]
%define hd dword [esp+calloff+16*3+4*4]
%define edgeb byte [esp+calloff+16*3+4*5]
%define edged dword [esp+calloff+16*3+4*5]
%define leftmp leftm
%else
%define w0m wm
%define hd dword r6m
%define edgeb byte r8m
%define edged dword r8m
%endif
%define hvsrcm dword [esp+calloff+4*0]
%define w1m dword [esp+calloff+4*1]
%define t0m dword [esp+calloff+4*2]
%define t2m dword [esp+calloff+4*3]
%define t3m dword [esp+calloff+4*4]
%define t4m dword [esp+calloff+4*5]
%define m8 [base+pd_8]
%define m9 [base+pd_0xfffffff0]
%define m10 [esp+calloff+16*2]
%define m11 [base+pd_0xf00800a4]
%define m12 [base+sgr_lshuf5]
%define m13 [base+pd_34816]
%define m14 [base+pw_1023]
%define r10 r5
%define base r6-$$
%assign calloff 0
%if STACK_ALIGNMENT < 16
mov dst_strideq, [rstk+stack_offset+ 8]
mov leftq, [rstk+stack_offset+12]
mov lpfq, [rstk+stack_offset+16]
mov lpf_strideq, [rstk+stack_offset+20]
mov wd, [rstk+stack_offset+24]
mov dstm, dstq
mov dst_stridemp, dst_strideq
mov leftm, leftq
mov r1, [rstk+stack_offset+28]
mov r2, [rstk+stack_offset+36]
mov lpfm, lpfq
mov lpf_stridem, lpf_strideq
mov hd, r1
mov edged, r2
%endif
%else
cglobal sgr_filter_5x5_16bpc, 5, 15, 15, -400*24-16, dst, dst_stride, left, lpf, \
lpf_stride, w, edge, params, h
%endif
%if ARCH_X86_64 || STACK_ALIGNMENT >= 16
movifnidn wd, wm
%endif
%if ARCH_X86_64
mov paramsq, paramsmp
lea r13, [sgr_x_by_x-0xf03]
mov edged, r8m
add wd, wd
mov hd, r6m
movu m10, [paramsq]
mova m12, [sgr_lshuf5]
add lpfq, wq
mova m8, [pd_8]
lea t1, [rsp+wq+20]
mova m9, [pd_0xfffffff0]
add dstq, wq
lea t3, [rsp+wq*2+400*12+16]
mova m11, [pd_0xf00800a4]
lea t4, [rsp+wq+400*20+16]
pshufhw m7, m10, q0000
pshufb m10, [pw_256] ; s0
punpckhqdq m7, m7 ; w0
neg wq
mova m13, [pd_34816] ; (1 << 11) + (1 << 15)
pxor m6, m6
mova m14, [pw_1023]
psllw m7, 4
DEFINE_ARGS dst, dst_stride, left, lpf, lpf_stride, _, edge, _, h, _, w
%define lpfm [rsp+0]
%define lpf_stridem [rsp+8]
%else
mov r1, [rstk+stack_offset+32] ; params
LEA r6, $$
add wd, wd
movu m1, [r1]
add lpfm, wq
lea t1, [rsp+extra_stack+wq+20]
add dstq, wq
lea t3, [rsp+extra_stack+wq*2+400*12+16]
mov dstm, dstq
lea t4, [rsp+extra_stack+wq+400*20+16]
mov t3m, t3
pshufhw m7, m1, q0000
mov t4m, t4
pshufb m1, [base+pw_256] ; s0
punpckhqdq m7, m7 ; w0
psllw m7, 4
neg wq
mova m10, m1
pxor m6, m6
mov w1m, wd
sub wd, 4
mov lpfq, lpfm
mov lpf_strideq, lpf_stridem
mov w0m, wd
%endif
test edgeb, 4 ; LR_HAVE_TOP
jz .no_top
call .h_top
add lpfq, lpf_strideq
movif32 t2m, t1
mov t2, t1
call .top_fixup
add t1, 400*6
call .h_top
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
movif64 lpf_stridem, lpf_strideq
add r10, lpf_strideq
mov lpfm, r10 ; below
movif32 t0m, t2
mov t0, t2
dec hd
jz .height1
or edged, 16
call .h
.main:
add lpfq, dst_stridemp
movif32 t4, t4m
call .hv
call .prep_n
sub hd, 2
jl .extend_bottom
.main_loop:
movif32 lpfq, hvsrcm
add lpfq, dst_stridemp
%if ARCH_X86_64
test hb, hb
%else
mov r5, hd
test r5, r5
%endif
jz .odd_height
call .h
add lpfq, dst_stridemp
call .hv
movif32 dstq, dstm
call .n0
call .n1
sub hd, 2
movif32 t0, t0m
jge .main_loop
test edgeb, 8 ; LR_HAVE_BOTTOM
jz .extend_bottom
mov lpfq, lpfm
call .h_top
add lpfq, lpf_stridem
call .hv_bottom
.end:
movif32 dstq, dstm
call .n0
call .n1
.end2:
RET
.height1:
movif32 t4, t4m
call .hv
call .prep_n
jmp .odd_height_end
.odd_height:
call .hv
movif32 dstq, dstm
call .n0
call .n1
.odd_height_end:
call .v
movif32 dstq, dstm
call .n0
jmp .end2
.extend_bottom:
call .v
jmp .end
.no_top:
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
movif64 lpf_stridem, lpf_strideq
lea r10, [r10+lpf_strideq*2]
mov lpfm, r10
call .h
lea t2, [t1+400*6]
movif32 t2m, t2
call .top_fixup
dec hd
jz .no_top_height1
or edged, 16
mov t0, t1
mov t1, t2
movif32 t0m, t0
jmp .main
.no_top_height1:
movif32 t3, t3m
movif32 t4, t4m
call .v
call .prep_n
jmp .odd_height_end
.extend_right:
movd m0, wd
movd m1, [lpfq-2]
mova m2, [base+pw_256]
mova m3, [base+pb_m14_m13]
pshufb m0, m6
pshufb m1, m2
psubb m2, m0
psubb m3, m0
mova m0, [base+pb_0to15]
pcmpgtb m2, m0
pcmpgtb m3, m0
pand m4, m2
pand m5, m3
pandn m2, m1
pandn m3, m1
por m4, m2
por m5, m3
ret
%assign stack_offset stack_offset+4
%assign calloff 4
.h: ; horizontal boxsum
%if ARCH_X86_64
lea wq, [r5-4]
%else
%define leftq r5
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
movif32 leftq, leftm
movddup m5, [leftq]
movif32 wq, w0m
mova m4, [lpfq+wq+4]
add leftmp, 8
palignr m4, m5, 10
jmp .h_main
.h_extend_left:
movif32 wq, w0m
mova m4, [lpfq+wq+4]
pshufb m4, m12
jmp .h_main
.h_top:
%if ARCH_X86_64
lea wq, [r5-4]
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
movif32 wq, w0m
.h_loop:
movu m4, [lpfq+wq- 2]
.h_main:
movu m5, [lpfq+wq+14]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .h_have_right
cmp wd, -20
jl .h_have_right
call .extend_right
.h_have_right:
palignr m2, m5, m4, 2
paddw m0, m4, m2
palignr m3, m5, m4, 6
paddw m0, m3
punpcklwd m1, m2, m3
pmaddwd m1, m1
punpckhwd m2, m3
pmaddwd m2, m2
palignr m5, m4, 8
paddw m0, m5
punpcklwd m3, m4, m5
pmaddwd m3, m3
paddd m1, m3
punpckhwd m3, m4, m5
pmaddwd m3, m3
shufps m4, m5, q2121
paddw m0, m4 ; sum
punpcklwd m5, m4, m6
pmaddwd m5, m5
punpckhwd m4, m6
pmaddwd m4, m4
paddd m2, m3
test edgeb, 16 ; y > 0
jz .h_loop_end
paddw m0, [t1+wq+400*0]
paddd m1, [t1+wq+400*2]
paddd m2, [t1+wq+400*4]
.h_loop_end:
paddd m1, m5 ; sumsq
paddd m2, m4
mova [t1+wq+400*0], m0
mova [t1+wq+400*2], m1
mova [t1+wq+400*4], m2
add wq, 16
jl .h_loop
ret
.top_fixup:
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov wd, w0m
%endif
.top_fixup_loop: ; the sums of the first row needs to be doubled
mova m0, [t1+wq+400*0]
mova m1, [t1+wq+400*2]
mova m2, [t1+wq+400*4]
paddw m0, m0
paddd m1, m1
paddd m2, m2
mova [t2+wq+400*0], m0
mova [t2+wq+400*2], m1
mova [t2+wq+400*4], m2
add wq, 16
jl .top_fixup_loop
ret
ALIGN function_align
.hv: ; horizontal boxsum + vertical boxsum + ab
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv_extend_left
movif32 leftq, leftm
movddup m5, [leftq]
movif32 wq, w0m
mova m4, [lpfq+wq+4]
add leftmp, 8
palignr m4, m5, 10
jmp .hv_main
.hv_extend_left:
movif32 wq, w0m
mova m4, [lpfq+wq+4]
pshufb m4, m12
jmp .hv_main
.hv_bottom:
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv_extend_left
movif32 wq, w0m
%if ARCH_X86_32
jmp .hv_loop_start
%endif
.hv_loop:
movif32 lpfq, hvsrcm
.hv_loop_start:
movu m4, [lpfq+wq- 2]
.hv_main:
movu m5, [lpfq+wq+14]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .hv_have_right
cmp wd, -20
jl .hv_have_right
call .extend_right
.hv_have_right:
movif32 t3, hd
palignr m3, m5, m4, 2
paddw m0, m4, m3
palignr m1, m5, m4, 6
paddw m0, m1
punpcklwd m2, m3, m1
pmaddwd m2, m2
punpckhwd m3, m1
pmaddwd m3, m3
palignr m5, m4, 8
paddw m0, m5
punpcklwd m1, m4, m5
pmaddwd m1, m1
paddd m2, m1
punpckhwd m1, m4, m5
pmaddwd m1, m1
shufps m4, m5, q2121
paddw m0, m4 ; h sum
punpcklwd m5, m4, m6
pmaddwd m5, m5
punpckhwd m4, m6
pmaddwd m4, m4
paddd m3, m1
paddd m2, m5 ; h sumsq
paddd m3, m4
paddw m1, m0, [t1+wq+400*0]
paddd m4, m2, [t1+wq+400*2]
paddd m5, m3, [t1+wq+400*4]
%if ARCH_X86_64
test hd, hd
%else
test t3, t3
%endif
jz .hv_last_row
.hv_main2:
paddw m1, [t2+wq+400*0] ; hv sum
paddd m4, [t2+wq+400*2] ; hv sumsq
paddd m5, [t2+wq+400*4]
mova [t0+wq+400*0], m0
mova [t0+wq+400*2], m2
mova [t0+wq+400*4], m3
psrlw m3, m1, 1
paddd m4, m8
pavgw m3, m6 ; (b + 2) >> 2
paddd m5, m8
pand m4, m9 ; ((a + 8) >> 4) << 4
pand m5, m9
psrld m2, m4, 4
psrld m0, m5, 4
paddd m2, m4
psrld m4, 1
paddd m0, m5
psrld m5, 1
paddd m4, m2 ; a * 25
paddd m5, m0
punpcklwd m2, m3, m6
punpckhwd m3, m6
pmaddwd m2, m2 ; b * b
pmaddwd m3, m3
punpcklwd m0, m1, m6 ; b
punpckhwd m1, m6
MAXSD m4, m2, m6
MAXSD m5, m3, m6, 1
psubd m4, m2 ; p
psubd m5, m3
MULLD m4, m10, m2 ; p * s
MULLD m5, m10, m2
pmaddwd m0, m11 ; b * 164
pmaddwd m1, m11
paddusw m4, m11
paddusw m5, m11
psrld m4, 20 ; min(z, 255)
movif32 t3, t3m
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, t2, t2m
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m2
MULLD m1, m5, m2
paddd m0, m13 ; x * b * 164 + (1 << 11) + (1 << 15)
paddd m1, m13
mova [t4+wq+4], m3
psrld m0, 12 ; b
psrld m1, 12
mova [t3+wq*2+ 8], m0
mova [t3+wq*2+24], m1
add wq, 16
jl .hv_loop
mov t2, t1
mov t1, t0
mov t0, t2
movif32 t2m, t2
movif32 t0m, t0
ret
.hv_last_row: ; esoteric edge case for odd heights
mova [t1+wq+400*0], m1
paddw m1, m0
mova [t1+wq+400*2], m4
paddd m4, m2
mova [t1+wq+400*4], m5
paddd m5, m3
jmp .hv_main2
.v: ; vertical boxsum + ab
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov wd, w0m
%endif
.v_loop:
mova m0, [t1+wq+400*0]
mova m2, [t1+wq+400*2]
mova m3, [t1+wq+400*4]
paddw m1, m0, [t2+wq+400*0]
paddd m4, m2, [t2+wq+400*2]
paddd m5, m3, [t2+wq+400*4]
paddw m0, m0
paddd m2, m2
paddd m3, m3
paddw m1, m0 ; hv sum
paddd m4, m2 ; hv sumsq
paddd m5, m3
psrlw m3, m1, 1
paddd m4, m8
pavgw m3, m6 ; (b + 2) >> 2
paddd m5, m8
pand m4, m9 ; ((a + 8) >> 4) << 4
pand m5, m9
psrld m2, m4, 4
psrld m0, m5, 4
paddd m2, m4
psrld m4, 1
paddd m0, m5
psrld m5, 1
paddd m4, m2 ; a * 25
paddd m5, m0
punpcklwd m2, m3, m6
punpckhwd m3, m6
pmaddwd m2, m2 ; b * b
pmaddwd m3, m3
punpcklwd m0, m1, m6 ; b
punpckhwd m1, m6
MAXSD m4, m2, m6
MAXSD m5, m3, m6, 1
psubd m4, m2 ; p
psubd m5, m3
MULLD m4, m10, m2 ; p * s
MULLD m5, m10, m2
pmaddwd m0, m11 ; b * 164
pmaddwd m1, m11
paddusw m4, m11
paddusw m5, m11
psrld m4, 20 ; min(z, 255)
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, t2, t2m
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m2
MULLD m1, m5, m2
paddd m0, m13 ; x * b * 164 + (1 << 11) + (1 << 15)
paddd m1, m13
mova [t4+wq+4], m3
psrld m0, 12 ; b
psrld m1, 12
mova [t3+wq*2+ 8], m0
mova [t3+wq*2+24], m1
add wq, 16
jl .v_loop
ret
.prep_n: ; initial neighbor setup
movif64 wq, r5
movif32 wd, w1m
.prep_n_loop:
movu m0, [t4+wq*1+ 2]
movu m3, [t4+wq*1+ 4]
movu m1, [t3+wq*2+ 4]
movu m4, [t3+wq*2+ 8]
movu m2, [t3+wq*2+20]
movu m5, [t3+wq*2+24]
paddw m3, m0
paddd m4, m1
paddd m5, m2
paddw m3, [t4+wq*1+ 0]
paddd m4, [t3+wq*2+ 0]
paddd m5, [t3+wq*2+16]
paddw m0, m3
psllw m3, 2
paddd m1, m4
pslld m4, 2
paddd m2, m5
pslld m5, 2
paddw m0, m3 ; a 565
paddd m1, m4 ; b 565
paddd m2, m5
mova [t4+wq*1+400*2+ 0], m0
mova [t3+wq*2+400*4+ 0], m1
mova [t3+wq*2+400*4+16], m2
add wq, 16
jl .prep_n_loop
ret
ALIGN function_align
.n0: ; neighbor + output (even rows)
movif64 wq, r5
movif32 wd, w1m
.n0_loop:
movu m0, [t4+wq*1+ 2]
movu m3, [t4+wq*1+ 4]
movu m1, [t3+wq*2+ 4]
movu m4, [t3+wq*2+ 8]
movu m2, [t3+wq*2+20]
movu m5, [t3+wq*2+24]
paddw m3, m0
paddd m4, m1
paddd m5, m2
paddw m3, [t4+wq*1+ 0]
paddd m4, [t3+wq*2+ 0]
paddd m5, [t3+wq*2+16]
paddw m0, m3
psllw m3, 2
paddd m1, m4
pslld m4, 2
paddd m2, m5
pslld m5, 2
paddw m0, m3 ; a 565
paddd m1, m4 ; b 565
paddd m2, m5
paddw m3, m0, [t4+wq*1+400*2+ 0]
paddd m4, m1, [t3+wq*2+400*4+ 0]
paddd m5, m2, [t3+wq*2+400*4+16]
mova [t4+wq*1+400*2+ 0], m0
mova [t3+wq*2+400*4+ 0], m1
mova [t3+wq*2+400*4+16], m2
mova m0, [dstq+wq]
punpcklwd m1, m0, m6 ; src
punpcklwd m2, m3, m6 ; a
pmaddwd m2, m1 ; a * src
punpckhwd m1, m0, m6
punpckhwd m3, m6
pmaddwd m3, m1
psubd m4, m2 ; b - a * src + (1 << 8)
psubd m5, m3
psrad m4, 9
psrad m5, 9
packssdw m4, m5
pmulhrsw m4, m7
paddw m0, m4
pmaxsw m0, m6
pminsw m0, m14
mova [dstq+wq], m0
add wq, 16
jl .n0_loop
add dstq, dst_stridemp
ret
ALIGN function_align
.n1: ; neighbor + output (odd rows)
movif64 wq, r5
movif32 wd, w1m
.n1_loop:
mova m0, [dstq+wq]
mova m3, [t4+wq*1+400*2+ 0]
mova m4, [t3+wq*2+400*4+ 0]
mova m5, [t3+wq*2+400*4+16]
punpcklwd m1, m0, m6 ; src
punpcklwd m2, m3, m6 ; a
pmaddwd m2, m1
punpckhwd m1, m0, m6
punpckhwd m3, m6
pmaddwd m3, m1
psubd m4, m2 ; b - a * src + (1 << 7)
psubd m5, m3
psrad m4, 8
psrad m5, 8
packssdw m4, m5
pmulhrsw m4, m7
paddw m0, m4
pmaxsw m0, m6
pminsw m0, m14
mova [dstq+wq], m0
add wq, 16
jl .n1_loop
add dstq, dst_stridemp
movif32 dstm, dstq
ret
%if ARCH_X86_32
%if STACK_ALIGNMENT < 16
%assign extra_stack 4*16
%else
%assign extra_stack 2*16
%endif
cglobal sgr_filter_3x3_16bpc, 1, 7, 8, -400*42-16-extra_stack, \
dst, dst_stride, left, lpf, lpf_stride, w, params, h
%if STACK_ALIGNMENT < 16
%define dstm dword [esp+calloff+16*2+4*0]
%define dst_stridemp dword [esp+calloff+16*2+4*1]
%define leftm dword [esp+calloff+16*2+4*2]
%define lpfm dword [esp+calloff+16*2+4*3]
%define lpf_stridem dword [esp+calloff+16*2+4*4]
%define w0m dword [esp+calloff+16*2+4*5]
%define hd dword [esp+calloff+16*2+4*6]
%define edgeb byte [esp+calloff+16*2+4*7]
%define edged dword [esp+calloff+16*2+4*7]
%define leftmp leftm
%else
%define w0m wm
%define hd dword r6m
%define edgeb byte r8m
%define edged dword r8m
%endif
%define hvsrcm dword [esp+calloff+4*0]
%define w1m dword [esp+calloff+4*1]
%define t3m dword [esp+calloff+4*2]
%define t4m dword [esp+calloff+4*3]
%define m8 [base+pd_8]
%define m9 [esp+calloff+16*1]
%define m10 [base+pd_0xf00801c7]
%define m11 [base+pd_34816]
%define m12 [base+sgr_lshuf3]
%define m13 [base+pw_1023]
%define m14 m6
%define base r6-$$
%assign calloff 0
%if STACK_ALIGNMENT < 16
mov dst_strideq, [rstk+stack_offset+ 8]
mov leftq, [rstk+stack_offset+12]
mov lpfq, [rstk+stack_offset+16]
mov lpf_strideq, [rstk+stack_offset+20]
mov wd, [rstk+stack_offset+24]
mov dstm, dstq
mov dst_stridemp, dst_strideq
mov leftm, leftq
mov r1, [rstk+stack_offset+28]
mov r2, [rstk+stack_offset+36]
mov lpfm, lpfq
mov lpf_stridem, lpf_strideq
mov hd, r1
mov edged, r2
%endif
%else
cglobal sgr_filter_3x3_16bpc, 5, 15, 15, -400*42-8, dst, dst_stride, left, lpf, \
lpf_stride, w, edge, params, h
%endif
%if ARCH_X86_64 || STACK_ALIGNMENT >= 16
movifnidn wd, wm
%endif
%if ARCH_X86_64
mov paramsq, paramsmp
lea r13, [sgr_x_by_x-0xf03]
mov edged, r8m
add wd, wd
mov hd, r6m
movq m9, [paramsq+4]
add lpfq, wq
lea t1, [rsp+wq+12]
mova m8, [pd_8]
add dstq, wq
lea t3, [rsp+wq*2+400*12+8]
mova m10, [pd_0xf00801c7]
lea t4, [rsp+wq+400*32+8]
mova m11, [pd_34816]
pshuflw m7, m9, q3333
pshufb m9, [pw_256] ; s1
punpcklqdq m7, m7 ; w1
neg wq
pxor m6, m6
mova m13, [pw_1023]
psllw m7, 4
mova m12, [sgr_lshuf3]
DEFINE_ARGS dst, dst_stride, left, lpf, lpf_stride, _, edge, _, h, _, w
%define lpfm [rsp]
%else
mov r1, [rstk+stack_offset+32] ; params
LEA r6, $$
add wd, wd
movq m1, [r1+4]
add lpfm, wq
lea t1, [rsp+extra_stack+wq+20]
add dstq, wq
lea t3, [rsp+extra_stack+wq*2+400*12+16]
mov dstm, dstq
lea t4, [rsp+extra_stack+wq+400*32+16]
mov t3m, t3
pshuflw m7, m1, q3333
mov t4m, t4
pshufb m1, [base+pw_256] ; s1
punpcklqdq m7, m7 ; w1
psllw m7, 4
neg wq
mova m9, m1
pxor m6, m6
mov w1m, wd
sub wd, 4
mov lpfq, lpfm
mov lpf_strideq, lpf_stridem
mov w0m, wd
%endif
test edgeb, 4 ; LR_HAVE_TOP
jz .no_top
call .h_top
add lpfq, lpf_strideq
mov t2, t1
add t1, 400*6
call .h_top
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
add r10, lpf_strideq
mov lpfm, r10 ; below
movif32 t4, t4m
call .hv0
.main:
dec hd
jz .height1
movif32 lpfq, hvsrcm
add lpfq, dst_stridemp
call .hv1
call .prep_n
sub hd, 2
jl .extend_bottom
.main_loop:
movif32 lpfq, hvsrcm
add lpfq, dst_stridemp
call .hv0
%if ARCH_X86_64
test hb, hb
%else
mov r5, hd
test r5, r5
%endif
jz .odd_height
movif32 lpfq, hvsrcm
add lpfq, dst_stridemp
call .hv1
call .n0
call .n1
sub hd, 2
jge .main_loop
test edgeb, 8 ; LR_HAVE_BOTTOM
jz .extend_bottom
mov lpfq, lpfm
call .hv0_bottom
%if ARCH_X86_64
add lpfq, lpf_strideq
%else
mov lpfq, hvsrcm
add lpfq, lpf_stridem
%endif
call .hv1_bottom
.end:
call .n0
call .n1
.end2:
RET
.height1:
call .v1
call .prep_n
jmp .odd_height_end
.odd_height:
call .v1
call .n0
call .n1
.odd_height_end:
call .v0
call .v1
call .n0
jmp .end2
.extend_bottom:
call .v0
call .v1
jmp .end
.no_top:
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
lea r10, [r10+lpf_strideq*2]
mov lpfm, r10
call .h
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov wq, w0m
mov hvsrcm, lpfq
%endif
lea t2, [t1+400*6]
.top_fixup_loop:
mova m0, [t1+wq+400*0]
mova m1, [t1+wq+400*2]
mova m2, [t1+wq+400*4]
mova [t2+wq+400*0], m0
mova [t2+wq+400*2], m1
mova [t2+wq+400*4], m2
add wq, 16
jl .top_fixup_loop
movif32 t3, t3m
movif32 t4, t4m
call .v0
jmp .main
.extend_right:
movd m1, wd
movd m5, [lpfq-2]
mova m2, [base+pw_256]
mova m3, [base+pb_0to15]
pshufb m1, m6
pshufb m5, m2
psubb m2, m1
pcmpgtb m2, m3
pand m4, m2
pandn m2, m5
por m4, m2
ret
%assign stack_offset stack_offset+4
%assign calloff 4
.h: ; horizontal boxsum
%if ARCH_X86_64
lea wq, [r5-4]
%else
%define leftq r5
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
movif32 leftq, leftm
movddup m5, [leftq]
movif32 wq, w0m
mova m4, [lpfq+wq+4]
add leftmp, 8
palignr m4, m5, 12
jmp .h_main
.h_extend_left:
movif32 wq, w0m
mova m4, [lpfq+wq+4]
pshufb m4, m12
jmp .h_main
.h_top:
%if ARCH_X86_64
lea wq, [r5-4]
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
movif32 wq, w0m
.h_loop:
movu m4, [lpfq+wq+ 0]
.h_main:
movu m5, [lpfq+wq+16]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .h_have_right
cmp wd, -18
jl .h_have_right
call .extend_right
.h_have_right:
palignr m0, m5, m4, 2
paddw m1, m4, m0
punpcklwd m2, m4, m0
pmaddwd m2, m2
punpckhwd m3, m4, m0
pmaddwd m3, m3
palignr m5, m4, 4
paddw m1, m5 ; sum
punpcklwd m4, m5, m6
pmaddwd m4, m4
punpckhwd m5, m6
pmaddwd m5, m5
paddd m2, m4 ; sumsq
paddd m3, m5
mova [t1+wq+400*0], m1
mova [t1+wq+400*2], m2
mova [t1+wq+400*4], m3
add wq, 16
jl .h_loop
ret
ALIGN function_align
.hv0: ; horizontal boxsum + vertical boxsum + ab (even rows)
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv0_extend_left
movif32 leftq, leftm
movddup m5, [leftq]
movif32 wq, w0m
mova m4, [lpfq+wq+4]
add leftmp, 8
palignr m4, m5, 12
jmp .hv0_main
.hv0_extend_left:
movif32 wq, w0m
mova m4, [lpfq+wq+4]
pshufb m4, m12
jmp .hv0_main
.hv0_bottom:
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv0_extend_left
movif32 wq, w0m
%if ARCH_X86_32
jmp .hv0_loop_start
%endif
.hv0_loop:
movif32 lpfq, hvsrcm
.hv0_loop_start:
movu m4, [lpfq+wq+ 0]
.hv0_main:
movu m5, [lpfq+wq+16]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .hv0_have_right
cmp wd, -18
jl .hv0_have_right
call .extend_right
.hv0_have_right:
palignr m0, m5, m4, 2
paddw m1, m4, m0
punpcklwd m2, m4, m0
pmaddwd m2, m2
punpckhwd m3, m4, m0
pmaddwd m3, m3
palignr m5, m4, 4
paddw m1, m5 ; sum
punpcklwd m4, m5, m6
pmaddwd m4, m4
punpckhwd m5, m6
pmaddwd m5, m5
paddd m2, m4 ; sumsq
paddd m3, m5
paddw m0, m1, [t1+wq+400*0]
paddd m4, m2, [t1+wq+400*2]
paddd m5, m3, [t1+wq+400*4]
mova [t1+wq+400*0], m1
mova [t1+wq+400*2], m2
mova [t1+wq+400*4], m3
paddw m1, m0, [t2+wq+400*0]
paddd m2, m4, [t2+wq+400*2]
paddd m3, m5, [t2+wq+400*4]
mova [t2+wq+400*0], m0
mova [t2+wq+400*2], m4
mova [t2+wq+400*4], m5
paddd m2, m8
paddd m3, m8
psrld m2, 4 ; (a + 8) >> 4
psrld m3, 4
pslld m4, m2, 3
pslld m5, m3, 3
paddd m4, m2 ; ((a + 8) >> 4) * 9
paddd m5, m3
psrlw m3, m1, 1
pavgw m3, m6 ; (b + 2) >> 2
punpcklwd m2, m3, m6
pmaddwd m2, m2
punpckhwd m3, m6
pmaddwd m3, m3
punpcklwd m0, m1, m6 ; b
punpckhwd m1, m6
MAXSD m4, m2, m14
MAXSD m5, m3, m14
psubd m4, m2 ; p
psubd m5, m3
MULLD m4, m9, m14 ; p * s
MULLD m5, m9, m14
pmaddwd m0, m10 ; b * 455
pmaddwd m1, m10
paddusw m4, m10
paddusw m5, m10
psrld m4, 20 ; min(z, 255)
movif32 t3, t3m
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, r0, dstm
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m14
MULLD m1, m5, m14
%if ARCH_X86_32
pxor m6, m6
%endif
paddd m0, m11 ; x * b * 455 + (1 << 11) + (1 << 15)
paddd m1, m11
mova [t4+wq+4], m3
psrld m0, 12
psrld m1, 12
mova [t3+wq*2+ 8], m0
mova [t3+wq*2+24], m1
add wq, 16
jl .hv0_loop
ret
ALIGN function_align
.hv1: ; horizontal boxsums + vertical boxsums + ab (odd rows)
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv1_extend_left
movif32 leftq, leftm
movddup m5, [leftq]
movif32 wq, w0m
mova m4, [lpfq+wq+4]
add leftmp, 8
palignr m4, m5, 12
jmp .hv1_main
.hv1_extend_left:
movif32 wq, w0m
mova m4, [lpfq+wq+4]
pshufb m4, m12
jmp .hv1_main
.hv1_bottom:
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv1_extend_left
movif32 wq, w0m
%if ARCH_X86_32
jmp .hv1_loop_start
%endif
.hv1_loop:
movif32 lpfq, hvsrcm
.hv1_loop_start:
movu m4, [lpfq+wq+ 0]
.hv1_main:
movu m5, [lpfq+wq+16]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .hv1_have_right
cmp wd, -18
jl .hv1_have_right
call .extend_right
.hv1_have_right:
palignr m1, m5, m4, 2
paddw m0, m4, m1
punpcklwd m2, m4, m1
pmaddwd m2, m2
punpckhwd m3, m4, m1
pmaddwd m3, m3
palignr m5, m4, 4
paddw m0, m5 ; h sum
punpcklwd m1, m5, m6
pmaddwd m1, m1
punpckhwd m5, m6
pmaddwd m5, m5
paddd m2, m1 ; h sumsq
paddd m3, m5
paddw m1, m0, [t2+wq+400*0]
paddd m4, m2, [t2+wq+400*2]
paddd m5, m3, [t2+wq+400*4]
mova [t2+wq+400*0], m0
mova [t2+wq+400*2], m2
mova [t2+wq+400*4], m3
paddd m4, m8
paddd m5, m8
psrld m4, 4 ; (a + 8) >> 4
psrld m5, 4
pslld m2, m4, 3
pslld m3, m5, 3
paddd m4, m2 ; ((a + 8) >> 4) * 9
paddd m5, m3
psrlw m3, m1, 1
pavgw m3, m6 ; (b + 2) >> 2
punpcklwd m2, m3, m6
pmaddwd m2, m2
punpckhwd m3, m6
pmaddwd m3, m3
punpcklwd m0, m1, m6 ; b
punpckhwd m1, m6
MAXSD m4, m2, m14
MAXSD m5, m3, m14
psubd m4, m2 ; p
psubd m5, m3
MULLD m4, m9, m14 ; p * s
MULLD m5, m9, m14
pmaddwd m0, m10 ; b * 455
pmaddwd m1, m10
paddusw m4, m10
paddusw m5, m10
psrld m4, 20 ; min(z, 255)
movif32 t3, t3m
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, r0, dstm
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m14
MULLD m1, m5, m14
%if ARCH_X86_32
pxor m6, m6
%endif
paddd m0, m11 ; x * b * 455 + (1 << 11) + (1 << 15)
paddd m1, m11
mova [t4+wq*1+400*2 +4], m3
psrld m0, 12
psrld m1, 12
mova [t3+wq*2+400*4+ 8], m0
mova [t3+wq*2+400*4+24], m1
add wq, 16
jl .hv1_loop
mov r10, t2
mov t2, t1
mov t1, r10
ret
.v0: ; vertical boxsums + ab (even rows)
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov wd, w0m
%endif
.v0_loop:
mova m0, [t1+wq+400*0]
mova m4, [t1+wq+400*2]
mova m5, [t1+wq+400*4]
paddw m0, m0
paddd m4, m4
paddd m5, m5
paddw m1, m0, [t2+wq+400*0]
paddd m2, m4, [t2+wq+400*2]
paddd m3, m5, [t2+wq+400*4]
mova [t2+wq+400*0], m0
mova [t2+wq+400*2], m4
mova [t2+wq+400*4], m5
paddd m2, m8
paddd m3, m8
psrld m2, 4 ; (a + 8) >> 4
psrld m3, 4
pslld m4, m2, 3
pslld m5, m3, 3
paddd m4, m2 ; ((a + 8) >> 4) * 9
paddd m5, m3
psrlw m3, m1, 1
pavgw m3, m6 ; (b + 2) >> 2
punpcklwd m2, m3, m6
pmaddwd m2, m2
punpckhwd m3, m6
pmaddwd m3, m3
punpcklwd m0, m1, m6 ; b
punpckhwd m1, m6
MAXSD m4, m2, m14
MAXSD m5, m3, m14
psubd m4, m2 ; p
psubd m5, m3
MULLD m4, m9, m14 ; p * s
MULLD m5, m9, m14
pmaddwd m0, m10 ; b * 455
pmaddwd m1, m10
paddusw m4, m10
paddusw m5, m10
psrld m4, 20 ; min(z, 255)
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, r0, dstm
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m14
MULLD m1, m5, m14
%if ARCH_X86_32
pxor m6, m6
%endif
paddd m0, m11 ; x * b * 455 + (1 << 11) + (1 << 15)
paddd m1, m11
mova [t4+wq*1+400*0+ 4], m3
psrld m0, 12
psrld m1, 12
mova [t3+wq*2+400*0+ 8], m0
mova [t3+wq*2+400*0+24], m1
add wq, 16
jl .v0_loop
ret
.v1: ; vertical boxsums + ab (odd rows)
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov wd, w0m
%endif
.v1_loop:
mova m0, [t1+wq+400*0]
mova m4, [t1+wq+400*2]
mova m5, [t1+wq+400*4]
paddw m1, m0, [t2+wq+400*0]
paddd m2, m4, [t2+wq+400*2]
paddd m3, m5, [t2+wq+400*4]
mova [t2+wq+400*0], m0
mova [t2+wq+400*2], m4
mova [t2+wq+400*4], m5
paddd m2, m8
paddd m3, m8
psrld m2, 4 ; (a + 8) >> 4
psrld m3, 4
pslld m4, m2, 3
pslld m5, m3, 3
paddd m4, m2 ; ((a + 8) >> 4) * 9
paddd m5, m3
psrlw m3, m1, 1
pavgw m3, m6 ; (b + 2) >> 2
punpcklwd m2, m3, m6
pmaddwd m2, m2
punpckhwd m3, m6
pmaddwd m3, m3
punpcklwd m0, m1, m6 ; b
punpckhwd m1, m6
MAXSD m4, m2, m14
MAXSD m5, m3, m14
psubd m4, m2 ; p
psubd m5, m3
MULLD m4, m9, m14 ; p * s
MULLD m5, m9, m14
pmaddwd m0, m10 ; b * 455
pmaddwd m1, m10
paddusw m4, m10
paddusw m5, m10
psrld m4, 20 ; min(z, 255)
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, r0, dstm
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m14
MULLD m1, m5, m14
%if ARCH_X86_32
pxor m6, m6
%endif
paddd m0, m11 ; x * b * 455 + (1 << 11) + (1 << 15)
paddd m1, m11
mova [t4+wq*1+400*2+ 4], m3
psrld m0, 12
psrld m1, 12
mova [t3+wq*2+400*4+ 8], m0
mova [t3+wq*2+400*4+24], m1
add wq, 16
jl .v1_loop
mov r10, t2
mov t2, t1
mov t1, r10
ret
.prep_n: ; initial neighbor setup
movif64 wq, r5
movif32 wd, w1m
.prep_n_loop:
movu m0, [t4+wq*1+400*0+ 4]
movu m1, [t3+wq*2+400*0+ 8]
movu m2, [t3+wq*2+400*0+24]
movu m3, [t4+wq*1+400*0+ 2]
movu m4, [t3+wq*2+400*0+ 4]
movu m5, [t3+wq*2+400*0+20]
paddw m0, [t4+wq*1+400*0+ 0]
paddd m1, [t3+wq*2+400*0+ 0]
paddd m2, [t3+wq*2+400*0+16]
paddw m3, m0
paddd m4, m1
paddd m5, m2
psllw m3, 2 ; a[-1] 444
pslld m4, 2 ; b[-1] 444
pslld m5, 2
psubw m3, m0 ; a[-1] 343
psubd m4, m1 ; b[-1] 343
psubd m5, m2
mova [t4+wq*1+400*4], m3
mova [t3+wq*2+400*8+ 0], m4
mova [t3+wq*2+400*8+16], m5
movu m0, [t4+wq*1+400*2+ 4]
movu m1, [t3+wq*2+400*4+ 8]
movu m2, [t3+wq*2+400*4+24]
movu m3, [t4+wq*1+400*2+ 2]
movu m4, [t3+wq*2+400*4+ 4]
movu m5, [t3+wq*2+400*4+20]
paddw m0, [t4+wq*1+400*2+ 0]
paddd m1, [t3+wq*2+400*4+ 0]
paddd m2, [t3+wq*2+400*4+16]
paddw m3, m0
paddd m4, m1
paddd m5, m2
psllw m3, 2 ; a[ 0] 444
pslld m4, 2 ; b[ 0] 444
pslld m5, 2
mova [t4+wq*1+400* 6], m3
mova [t3+wq*2+400*12+ 0], m4
mova [t3+wq*2+400*12+16], m5
psubw m3, m0 ; a[ 0] 343
psubd m4, m1 ; b[ 0] 343
psubd m5, m2
mova [t4+wq*1+400* 8], m3
mova [t3+wq*2+400*16+ 0], m4
mova [t3+wq*2+400*16+16], m5
add wq, 16
jl .prep_n_loop
ret
ALIGN function_align
.n0: ; neighbor + output (even rows)
movif64 wq, r5
movif32 wd, w1m
.n0_loop:
movu m3, [t4+wq*1+400*0+4]
movu m1, [t4+wq*1+400*0+2]
paddw m3, [t4+wq*1+400*0+0]
paddw m1, m3
psllw m1, 2 ; a[ 1] 444
psubw m2, m1, m3 ; a[ 1] 343
paddw m3, m2, [t4+wq*1+400*4]
paddw m3, [t4+wq*1+400*6]
mova [t4+wq*1+400*4], m2
mova [t4+wq*1+400*6], m1
movu m4, [t3+wq*2+400*0+8]
movu m1, [t3+wq*2+400*0+4]
paddd m4, [t3+wq*2+400*0+0]
paddd m1, m4
pslld m1, 2 ; b[ 1] 444
psubd m2, m1, m4 ; b[ 1] 343
paddd m4, m2, [t3+wq*2+400* 8+ 0]
paddd m4, [t3+wq*2+400*12+ 0]
mova [t3+wq*2+400* 8+ 0], m2
mova [t3+wq*2+400*12+ 0], m1
movu m5, [t3+wq*2+400*0+24]
movu m1, [t3+wq*2+400*0+20]
paddd m5, [t3+wq*2+400*0+16]
paddd m1, m5
pslld m1, 2
psubd m2, m1, m5
paddd m5, m2, [t3+wq*2+400* 8+16]
paddd m5, [t3+wq*2+400*12+16]
mova [t3+wq*2+400* 8+16], m2
mova [t3+wq*2+400*12+16], m1
mova m0, [dstq+wq]
punpcklwd m1, m0, m6
punpcklwd m2, m3, m6
pmaddwd m2, m1 ; a * src
punpckhwd m1, m0, m6
punpckhwd m3, m6
pmaddwd m3, m1
psubd m4, m2 ; b - a * src + (1 << 8)
psubd m5, m3
psrad m4, 9
psrad m5, 9
packssdw m4, m5
pmulhrsw m4, m7
paddw m0, m4
pmaxsw m0, m6
pminsw m0, m13
mova [dstq+wq], m0
add wq, 16
jl .n0_loop
add dstq, dst_stridemp
ret
ALIGN function_align
.n1: ; neighbor + output (odd rows)
movif64 wq, r5
movif32 wd, w1m
.n1_loop:
movu m3, [t4+wq*1+400*2+4]
movu m1, [t4+wq*1+400*2+2]
paddw m3, [t4+wq*1+400*2+0]
paddw m1, m3
psllw m1, 2 ; a[ 1] 444
psubw m2, m1, m3 ; a[ 1] 343
paddw m3, m2, [t4+wq*1+400*6]
paddw m3, [t4+wq*1+400*8]
mova [t4+wq*1+400*6], m1
mova [t4+wq*1+400*8], m2
movu m4, [t3+wq*2+400*4+8]
movu m1, [t3+wq*2+400*4+4]
paddd m4, [t3+wq*2+400*4+0]
paddd m1, m4
pslld m1, 2 ; b[ 1] 444
psubd m2, m1, m4 ; b[ 1] 343
paddd m4, m2, [t3+wq*2+400*12+ 0]
paddd m4, [t3+wq*2+400*16+ 0]
mova [t3+wq*2+400*12+ 0], m1
mova [t3+wq*2+400*16+ 0], m2
movu m5, [t3+wq*2+400*4+24]
movu m1, [t3+wq*2+400*4+20]
paddd m5, [t3+wq*2+400*4+16]
paddd m1, m5
pslld m1, 2
psubd m2, m1, m5
paddd m5, m2, [t3+wq*2+400*12+16]
paddd m5, [t3+wq*2+400*16+16]
mova [t3+wq*2+400*12+16], m1
mova [t3+wq*2+400*16+16], m2
mova m0, [dstq+wq]
punpcklwd m1, m0, m6
punpcklwd m2, m3, m6
pmaddwd m2, m1 ; a * src
punpckhwd m1, m0, m6
punpckhwd m3, m6
pmaddwd m3, m1
psubd m4, m2 ; b - a * src + (1 << 8)
psubd m5, m3
psrad m4, 9
psrad m5, 9
packssdw m4, m5
pmulhrsw m4, m7
paddw m0, m4
pmaxsw m0, m6
pminsw m0, m13
mova [dstq+wq], m0
add wq, 16
jl .n1_loop
add dstq, dst_stridemp
movif32 dstm, dstq
ret
%if ARCH_X86_32
%if STACK_ALIGNMENT < 16
%assign extra_stack 10*16
%else
%assign extra_stack 8*16
%endif
cglobal sgr_filter_mix_16bpc, 1, 7, 8, -400*66-48-extra_stack, \
dst, dst_stride, left, lpf, lpf_stride, w, params, h
%if STACK_ALIGNMENT < 16
%define dstm dword [esp+calloff+16*8+4*0]
%define dst_stridemp dword [esp+calloff+16*8+4*1]
%define leftm dword [esp+calloff+16*8+4*2]
%define lpfm dword [esp+calloff+16*8+4*3]
%define lpf_stridem dword [esp+calloff+16*8+4*4]
%define w0m dword [esp+calloff+16*8+4*5]
%define hd dword [esp+calloff+16*8+4*6]
%define edgeb byte [esp+calloff+16*8+4*7]
%define edged dword [esp+calloff+16*8+4*7]
%define leftmp leftm
%else
%define w0m wm
%define hd dword r6m
%define edgeb byte r8m
%define edged dword r8m
%endif
%define hvsrcm dword [esp+calloff+4*0]
%define w1m dword [esp+calloff+4*1]
%define t3m dword [esp+calloff+4*2]
%define t4m dword [esp+calloff+4*3]
%xdefine m8 m6
%define m9 [base+pd_8]
%define m10 [base+pd_34816]
%define m11 [base+pd_0xf00801c7]
%define m12 [base+pd_0xf00800a4]
%define m13 [esp+calloff+16*4]
%define m14 [esp+calloff+16*5]
%define m15 [esp+calloff+16*6]
%define m6 [esp+calloff+16*7]
%define base r6-$$
%assign calloff 0
%if STACK_ALIGNMENT < 16
mov dst_strideq, [rstk+stack_offset+ 8]
mov leftq, [rstk+stack_offset+12]
mov lpfq, [rstk+stack_offset+16]
mov lpf_strideq, [rstk+stack_offset+20]
mov wd, [rstk+stack_offset+24]
mov dstm, dstq
mov dst_stridemp, dst_strideq
mov leftm, leftq
mov r1, [rstk+stack_offset+28]
mov r2, [rstk+stack_offset+36]
mov lpfm, lpfq
mov lpf_stridem, lpf_strideq
mov hd, r1
mov edged, r2
%endif
%else
cglobal sgr_filter_mix_16bpc, 5, 15, 16, -400*66-40, dst, dst_stride, left, \
lpf, lpf_stride, w, edge, \
params, h
%endif
%if ARCH_X86_64 || STACK_ALIGNMENT >= 16
movifnidn wd, wm
%endif
%if ARCH_X86_64
mov paramsq, paramsmp
lea r13, [sgr_x_by_x-0xf03]
mov edged, r8m
add wd, wd
mov hd, r6m
mova m14, [paramsq]
add lpfq, wq
mova m9, [pd_8]
lea t1, [rsp+wq+44]
mova m10, [pd_34816]
add dstq, wq
mova m11, [pd_0xf00801c7]
lea t3, [rsp+wq*2+400*24+40]
mova m12, [pd_0xf00800a4]
lea t4, [rsp+wq+400*52+40]
neg wq
pshufd m15, m14, q2222 ; w0 w1
punpcklwd m14, m14
pshufd m13, m14, q0000 ; s0
pshufd m14, m14, q2222 ; s1
pxor m6, m6
psllw m15, 2
DEFINE_ARGS dst, dst_stride, left, lpf, lpf_stride, _, edge, _, h, _, w
%define lpfm [rsp]
%else
mov r1, [rstk+stack_offset+32] ; params
LEA r6, $$
add wd, wd
mova m2, [r1]
add lpfm, wq
lea t1, [rsp+extra_stack+wq+52]
add dstq, wq
lea t3, [rsp+extra_stack+wq*2+400*24+48]
mov dstm, dstq
lea t4, [rsp+extra_stack+wq+400*52+48]
mov t3m, t3
mov t4m, t4
neg wq
pshuflw m0, m2, q0000
pshuflw m1, m2, q2222
pshufhw m2, m2, q1010
punpcklqdq m0, m0 ; s0
punpcklqdq m1, m1 ; s1
punpckhqdq m2, m2 ; w0 w1
mov w1m, wd
pxor m3, m3
psllw m2, 2
mova m13, m0
mova m14, m1
sub wd, 4
mova m15, m2
mova m6, m3
mov lpfq, lpfm
mov lpf_strideq, lpf_stridem
mov w0m, wd
%endif
test edgeb, 4 ; LR_HAVE_TOP
jz .no_top
call .h_top
add lpfq, lpf_strideq
mov t2, t1
%if ARCH_X86_64
call mangle(private_prefix %+ _sgr_filter_5x5_16bpc_ssse3).top_fixup
%else
mov wq, w0m
call mangle(private_prefix %+ _sgr_filter_5x5_16bpc_ssse3).top_fixup_loop
%endif
add t1, 400*12
call .h_top
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
add r10, lpf_strideq
mov lpfm, r10 ; below
movif32 t4, t4m
call .hv0
.main:
dec hd
jz .height1
movif32 lpfq, hvsrcm
add lpfq, dst_stridemp
call .hv1
call .prep_n
sub hd, 2
jl .extend_bottom
.main_loop:
movif32 lpfq, hvsrcm
add lpfq, dst_stridemp
call .hv0
%if ARCH_X86_64
test hd, hd
%else
mov r5, hd
test r5, r5
%endif
jz .odd_height
movif32 lpfq, hvsrcm
add lpfq, dst_stridemp
call .hv1
call .n0
call .n1
sub hd, 2
jge .main_loop
test edgeb, 8 ; LR_HAVE_BOTTOM
jz .extend_bottom
mov lpfq, lpfm
call .hv0_bottom
%if ARCH_X86_64
add lpfq, lpf_strideq
%else
mov lpfq, hvsrcm
add lpfq, lpf_stridem
%endif
call .hv1_bottom
.end:
call .n0
call .n1
.end2:
RET
.height1:
call .v1
call .prep_n
jmp .odd_height_end
.odd_height:
call .v1
call .n0
call .n1
.odd_height_end:
call .v0
call .v1
call .n0
jmp .end2
.extend_bottom:
call .v0
call .v1
jmp .end
.no_top:
lea r10, [lpfq+lpf_strideq*4]
mov lpfq, dstq
lea r10, [r10+lpf_strideq*2]
mov lpfm, r10
call .h
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov wq, w0m
mov hvsrcm, lpfq
%endif
lea t2, [t1+400*12]
.top_fixup_loop:
mova m0, [t1+wq+400* 0]
mova m1, [t1+wq+400* 2]
mova m2, [t1+wq+400* 4]
paddw m0, m0
mova m3, [t1+wq+400* 6]
paddd m1, m1
mova m4, [t1+wq+400* 8]
paddd m2, m2
mova m5, [t1+wq+400*10]
mova [t2+wq+400* 0], m0
mova [t2+wq+400* 2], m1
mova [t2+wq+400* 4], m2
mova [t2+wq+400* 6], m3
mova [t2+wq+400* 8], m4
mova [t2+wq+400*10], m5
add wq, 16
jl .top_fixup_loop
movif32 t3, t3m
movif32 t4, t4m
call .v0
jmp .main
.h: ; horizontal boxsum
%assign stack_offset stack_offset+4
%assign calloff 4
%if ARCH_X86_64
lea wq, [r5-4]
%else
%define leftq r5
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
movif32 leftq, leftm
movddup m5, [leftq]
movif32 wq, w0m
mova m4, [lpfq+wq+4]
add leftmp, 8
palignr m4, m5, 10
jmp .h_main
.h_extend_left:
movif32 wq, w0m
mova m4, [lpfq+wq+4]
pshufb m4, [base+sgr_lshuf5]
jmp .h_main
.h_top:
%if ARCH_X86_64
lea wq, [r5-4]
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .h_extend_left
movif32 wq, w0m
.h_loop:
movu m4, [lpfq+wq- 2]
.h_main:
movu m5, [lpfq+wq+14]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .h_have_right
cmp wd, -20
jl .h_have_right
%if ARCH_X86_32
pxor m8, m8
%endif
call mangle(private_prefix %+ _sgr_filter_5x5_16bpc_ssse3).extend_right
.h_have_right:
palignr m3, m5, m4, 2
palignr m0, m5, m4, 4
paddw m1, m3, m0
punpcklwd m2, m3, m0
pmaddwd m2, m2
punpckhwd m3, m0
pmaddwd m3, m3
palignr m0, m5, m4, 6
paddw m1, m0 ; sum3
punpcklwd m7, m0, m6
pmaddwd m7, m7
punpckhwd m0, m6
pmaddwd m0, m0
paddd m2, m7 ; sumsq3
palignr m5, m4, 8
punpcklwd m7, m5, m4
paddw m8, m4, m5
pmaddwd m7, m7
punpckhwd m5, m4
pmaddwd m5, m5
paddd m3, m0
mova [t1+wq+400* 6], m1
mova [t1+wq+400* 8], m2
mova [t1+wq+400*10], m3
paddw m8, m1 ; sum5
paddd m7, m2 ; sumsq5
paddd m5, m3
mova [t1+wq+400* 0], m8
mova [t1+wq+400* 2], m7
mova [t1+wq+400* 4], m5
add wq, 16
jl .h_loop
ret
ALIGN function_align
.hv0: ; horizontal boxsum + vertical boxsum + ab3 (even rows)
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv0_extend_left
movif32 leftq, leftm
movddup m5, [leftq]
movif32 wq, w0m
mova m4, [lpfq+wq+4]
add leftmp, 8
palignr m4, m5, 10
jmp .hv0_main
.hv0_extend_left:
movif32 wq, w0m
mova m4, [lpfq+wq+4]
pshufb m4, [base+sgr_lshuf5]
jmp .hv0_main
.hv0_bottom:
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv0_extend_left
movif32 wq, w0m
%if ARCH_X86_32
jmp .hv0_loop_start
%endif
.hv0_loop:
movif32 lpfq, hvsrcm
.hv0_loop_start:
movu m4, [lpfq+wq- 2]
.hv0_main:
movu m5, [lpfq+wq+14]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .hv0_have_right
cmp wd, -20
jl .hv0_have_right
%if ARCH_X86_32
pxor m8, m8
%endif
call mangle(private_prefix %+ _sgr_filter_5x5_16bpc_ssse3).extend_right
.hv0_have_right:
palignr m3, m5, m4, 2
palignr m0, m5, m4, 4
movif32 t3, t3m
paddw m1, m3, m0
punpcklwd m2, m3, m0
pmaddwd m2, m2
punpckhwd m3, m0
pmaddwd m3, m3
palignr m0, m5, m4, 6
paddw m1, m0 ; h sum3
punpcklwd m7, m0, m6
pmaddwd m7, m7
punpckhwd m0, m6
pmaddwd m0, m0
paddd m2, m7 ; h sumsq3
palignr m5, m4, 8
punpcklwd m7, m5, m4
paddw m8, m4, m5
pmaddwd m7, m7
punpckhwd m5, m4
pmaddwd m5, m5
paddd m3, m0
paddw m8, m1 ; h sum5
paddd m7, m2 ; h sumsq5
paddd m5, m3
mova [t3+wq*2+400*8+ 8], m8
mova [t3+wq*2+400*0+ 8], m7
mova [t3+wq*2+400*0+24], m5
paddw m8, [t1+wq+400* 0]
paddd m7, [t1+wq+400* 2]
paddd m5, [t1+wq+400* 4]
mova [t1+wq+400* 0], m8
mova [t1+wq+400* 2], m7
mova [t1+wq+400* 4], m5
paddw m0, m1, [t1+wq+400* 6]
paddd m4, m2, [t1+wq+400* 8]
paddd m5, m3, [t1+wq+400*10]
mova [t1+wq+400* 6], m1
mova [t1+wq+400* 8], m2
mova [t1+wq+400*10], m3
paddw m1, m0, [t2+wq+400* 6]
paddd m2, m4, [t2+wq+400* 8]
paddd m3, m5, [t2+wq+400*10]
mova [t2+wq+400* 6], m0
mova [t2+wq+400* 8], m4
mova [t2+wq+400*10], m5
paddd m2, m9
paddd m3, m9
psrld m2, 4 ; (a3 + 8) >> 4
psrld m3, 4
%if ARCH_X86_32
pxor m7, m7
%else
SWAP m7, m6
%endif
pslld m4, m2, 3
pslld m5, m3, 3
paddd m4, m2 ; ((a3 + 8) >> 4) * 9
paddd m5, m3
psrlw m3, m1, 1
pavgw m3, m7 ; (b3 + 2) >> 2
punpcklwd m2, m3, m7
pmaddwd m2, m2
punpckhwd m3, m7
pmaddwd m3, m3
punpcklwd m0, m1, m7 ; b3
punpckhwd m1, m7
%if ARCH_X86_64
SWAP m7, m6
%endif
MAXSD m4, m2, m7
MAXSD m5, m3, m7
psubd m4, m2 ; p3
psubd m5, m3
MULLD m4, m14, m7 ; p3 * s1
MULLD m5, m14, m7
pmaddwd m0, m11 ; b3 * 455
pmaddwd m1, m11
paddusw m4, m11
paddusw m5, m11
psrld m4, 20 ; min(z3, 255)
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, r0, dstm
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m7
MULLD m1, m5, m7
paddd m0, m10 ; x3 * b3 * 455 + (1 << 11) + (1 << 15)
paddd m1, m10
mova [t4+wq*1+400*2+ 4], m3
psrld m0, 12
psrld m1, 12
mova [t3+wq*2+400*4+ 8], m0
mova [t3+wq*2+400*4+24], m1
add wq, 16
jl .hv0_loop
ret
ALIGN function_align
.hv1: ; horizontal boxsums + vertical boxsums + ab (odd rows)
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv1_extend_left
movif32 leftq, leftm
movddup m5, [leftq]
movif32 wq, w0m
mova m4, [lpfq+wq+4]
add leftmp, 8
palignr m4, m5, 10
jmp .hv1_main
.hv1_extend_left:
movif32 wq, w0m
mova m4, [lpfq+wq+4]
pshufb m4, [base+sgr_lshuf5]
jmp .hv1_main
.hv1_bottom:
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov hvsrcm, lpfq
%endif
test edgeb, 1 ; LR_HAVE_LEFT
jz .hv1_extend_left
movif32 wq, w0m
%if ARCH_X86_32
jmp .hv1_loop_start
%endif
.hv1_loop:
movif32 lpfq, hvsrcm
.hv1_loop_start:
movu m4, [lpfq+wq- 2]
.hv1_main:
movu m5, [lpfq+wq+14]
test edgeb, 2 ; LR_HAVE_RIGHT
jnz .hv1_have_right
cmp wd, -20
jl .hv1_have_right
%if ARCH_X86_32
pxor m8, m8
%endif
call mangle(private_prefix %+ _sgr_filter_5x5_16bpc_ssse3).extend_right
.hv1_have_right:
palignr m7, m5, m4, 2
palignr m3, m5, m4, 4
paddw m2, m7, m3
punpcklwd m0, m7, m3
pmaddwd m0, m0
punpckhwd m7, m3
pmaddwd m7, m7
palignr m3, m5, m4, 6
paddw m2, m3 ; h sum3
punpcklwd m1, m3, m6
pmaddwd m1, m1
punpckhwd m3, m6
pmaddwd m3, m3
paddd m0, m1 ; h sumsq3
palignr m5, m4, 8
punpckhwd m1, m4, m5
paddw m8, m4, m5
pmaddwd m1, m1
punpcklwd m4, m5
pmaddwd m4, m4
paddd m7, m3
paddw m5, m2, [t2+wq+400* 6]
mova [t2+wq+400* 6], m2
paddw m8, m2 ; h sum5
paddd m2, m0, [t2+wq+400* 8]
paddd m3, m7, [t2+wq+400*10]
mova [t2+wq+400* 8], m0
mova [t2+wq+400*10], m7
paddd m4, m0 ; h sumsq5
paddd m1, m7
paddd m2, m9
paddd m3, m9
psrld m2, 4 ; (a3 + 8) >> 4
psrld m3, 4
pslld m0, m2, 3
pslld m7, m3, 3
paddd m2, m0 ; ((a3 + 8) >> 4) * 9
paddd m3, m7
psrlw m7, m5, 1
pavgw m7, m6 ; (b3 + 2) >> 2
punpcklwd m0, m7, m6
pmaddwd m0, m0
punpckhwd m7, m6
pmaddwd m7, m7
%if ARCH_X86_32
mova [esp+20], m8
%else
SWAP m8, m6
%endif
MAXSD m2, m0, m8
MAXSD m3, m7, m8
pxor m8, m8
psubd m2, m0 ; p3
psubd m3, m7
punpcklwd m0, m5, m8 ; b3
punpckhwd m5, m8
MULLD m2, m14, m8 ; p3 * s1
MULLD m3, m14, m8
pmaddwd m0, m11 ; b3 * 455
pmaddwd m5, m11
paddusw m2, m11
paddusw m3, m11
psrld m2, 20 ; min(z3, 255)
movif32 t3, t3m
psrld m3, 20
GATHER_X_BY_X m8, m2, m3, r0, dstm
punpcklwd m2, m8, m8
punpckhwd m3, m8, m8
MULLD m0, m2, m7
MULLD m5, m3, m7
paddd m0, m10 ; x3 * b3 * 455 + (1 << 11) + (1 << 15)
paddd m5, m10
psrld m0, 12
psrld m5, 12
mova [t4+wq*1+400*4+4], m8
mova [t3+wq*2+400*8+ 8], m0
mova [t3+wq*2+400*8+24], m5
%if ARCH_X86_32
mova m8, [esp+20]
%else
SWAP m6, m8
pxor m6, m6
%endif
paddw m5, m8, [t2+wq+400*0]
paddd m2, m4, [t2+wq+400*2]
paddd m3, m1, [t2+wq+400*4]
paddw m5, [t1+wq+400*0]
paddd m2, [t1+wq+400*2]
paddd m3, [t1+wq+400*4]
mova [t2+wq+400*0], m8
paddd m2, m9
paddd m3, m9
psrld m2, 4 ; (a5 + 8) >> 4
psrld m3, 4
mova [t2+wq+400*2], m4
pslld m8, m2, 4
mova [t2+wq+400*4], m1
pslld m4, m3, 4
paddd m8, m2
pslld m2, 3
paddd m4, m3
pslld m3, 3
paddd m2, m8 ; ((a5 + 8) >> 4) * 25
paddd m3, m4
%if ARCH_X86_32
pxor m7, m7
%else
SWAP m7, m6
%endif
psrlw m1, m5, 1
pavgw m1, m7 ; (b5 + 2) >> 2
punpcklwd m4, m1, m7
pmaddwd m4, m4
punpckhwd m1, m7
pmaddwd m1, m1
punpcklwd m0, m5, m7 ; b5
punpckhwd m5, m7
%if ARCH_X86_64
SWAP m7, m6
%endif
MAXSD m2, m4, m7
psubd m2, m4 ; p5
MAXSD m3, m1, m7
psubd m3, m1
MULLD m2, m13, m7 ; p5 * s0
MULLD m3, m13, m7
pmaddwd m0, m12 ; b5 * 164
pmaddwd m5, m12
paddusw m2, m12
paddusw m3, m12
psrld m2, 20 ; min(z5, 255)
psrld m3, 20
GATHER_X_BY_X m1, m2, m3, r0, dstm
punpcklwd m2, m1, m1
punpckhwd m3, m1, m1
MULLD m0, m2, m7
MULLD m5, m3, m7
paddd m0, m10 ; x5 * b5 * 164 + (1 << 11) + (1 << 15)
paddd m5, m10
mova [t4+wq*1+400*0+ 4], m1
psrld m0, 12
psrld m5, 12
mova [t3+wq*2+400*0+ 8], m0
mova [t3+wq*2+400*0+24], m5
add wq, 16
jl .hv1_loop
mov r10, t2
mov t2, t1
mov t1, r10
ret
.v0: ; vertical boxsums + ab3 (even rows)
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov wd, w0m
%endif
.v0_loop:
mova m0, [t1+wq+400* 6]
mova m4, [t1+wq+400* 8]
mova m5, [t1+wq+400*10]
paddw m0, m0
paddd m4, m4
paddd m5, m5
paddw m1, m0, [t2+wq+400* 6]
paddd m2, m4, [t2+wq+400* 8]
paddd m3, m5, [t2+wq+400*10]
mova [t2+wq+400* 6], m0
mova [t2+wq+400* 8], m4
mova [t2+wq+400*10], m5
paddd m2, m9
paddd m3, m9
psrld m2, 4 ; (a3 + 8) >> 4
psrld m3, 4
%if ARCH_X86_32
pxor m7, m7
%else
SWAP m7, m6
%endif
pslld m4, m2, 3
pslld m5, m3, 3
paddd m4, m2 ; ((a3 + 8) >> 4) * 9
paddd m5, m3
psrlw m3, m1, 1
pavgw m3, m7 ; (b3 + 2) >> 2
punpcklwd m2, m3, m7
pmaddwd m2, m2
punpckhwd m3, m7
pmaddwd m3, m3
punpcklwd m0, m1, m7 ; b3
punpckhwd m1, m7
%if ARCH_X86_64
SWAP m7, m6
%endif
MAXSD m4, m2, m7
MAXSD m5, m3, m7
psubd m4, m2 ; p3
psubd m5, m3
MULLD m4, m14, m7 ; p3 * s1
MULLD m5, m14, m7
pmaddwd m0, m11 ; b3 * 455
pmaddwd m1, m11
paddusw m4, m11
paddusw m5, m11
psrld m4, 20 ; min(z3, 255)
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, r0, dstm
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m7
MULLD m1, m5, m7
paddd m0, m10 ; x3 * b3 * 455 + (1 << 11) + (1 << 15)
paddd m1, m10
mova [t4+wq*1+400*2+4], m3
psrld m0, 12
psrld m1, 12
mova m3, [t1+wq+400*0]
mova m4, [t1+wq+400*2]
mova m5, [t1+wq+400*4]
mova [t3+wq*2+400*8+ 8], m3
mova [t3+wq*2+400*0+ 8], m4
mova [t3+wq*2+400*0+24], m5
paddw m3, m3 ; cc5
paddd m4, m4
paddd m5, m5
mova [t1+wq+400*0], m3
mova [t1+wq+400*2], m4
mova [t1+wq+400*4], m5
mova [t3+wq*2+400*4+ 8], m0
mova [t3+wq*2+400*4+24], m1
add wq, 16
jl .v0_loop
ret
.v1: ; vertical boxsums + ab (odd rows)
%if ARCH_X86_64
lea wq, [r5-4]
%else
mov wd, w0m
%endif
.v1_loop:
mova m4, [t1+wq+400* 6]
mova m5, [t1+wq+400* 8]
mova m7, [t1+wq+400*10]
paddw m1, m4, [t2+wq+400* 6]
paddd m2, m5, [t2+wq+400* 8]
paddd m3, m7, [t2+wq+400*10]
mova [t2+wq+400* 6], m4
mova [t2+wq+400* 8], m5
mova [t2+wq+400*10], m7
paddd m2, m9
paddd m3, m9
psrld m2, 4 ; (a3 + 8) >> 4
psrld m3, 4
%if ARCH_X86_32
pxor m7, m7
%else
SWAP m7, m6
%endif
pslld m4, m2, 3
pslld m5, m3, 3
paddd m4, m2 ; ((a3 + 8) >> 4) * 9
paddd m5, m3
psrlw m3, m1, 1
pavgw m3, m7 ; (b3 + 2) >> 2
punpcklwd m2, m3, m7
pmaddwd m2, m2
punpckhwd m3, m7
pmaddwd m3, m3
punpcklwd m0, m1, m7 ; b3
punpckhwd m1, m7
%if ARCH_X86_64
SWAP m7, m6
%endif
MAXSD m4, m2, m7
MAXSD m5, m3, m7
psubd m4, m2 ; p3
psubd m5, m3
MULLD m4, m14, m7 ; p3 * s1
MULLD m5, m14, m7
pmaddwd m0, m11 ; b3 * 455
pmaddwd m1, m11
paddusw m4, m11
paddusw m5, m11
psrld m4, 20 ; min(z3, 255)
psrld m5, 20
GATHER_X_BY_X m3, m4, m5, r0, dstm
punpcklwd m4, m3, m3
punpckhwd m5, m3, m3
MULLD m0, m4, m7
MULLD m1, m5, m7
paddd m0, m10 ; x3 * b3 * 455 + (1 << 11) + (1 << 15)
paddd m1, m10
mova [t4+wq*1+400*4+4], m3
psrld m0, 12
psrld m8, m1, 12
mova m4, [t3+wq*2+400*8+ 8]
mova m5, [t3+wq*2+400*0+ 8]
mova m7, [t3+wq*2+400*0+24]
paddw m1, m4, [t2+wq+400*0]
paddd m2, m5, [t2+wq+400*2]
paddd m3, m7, [t2+wq+400*4]
paddw m1, [t1+wq+400*0]
paddd m2, [t1+wq+400*2]
paddd m3, [t1+wq+400*4]
mova [t2+wq+400*0], m4
mova [t2+wq+400*2], m5
mova [t2+wq+400*4], m7
paddd m2, m9
paddd m3, m9
psrld m2, 4 ; (a5 + 8) >> 4
psrld m3, 4
mova [t3+wq*2+400*8+ 8], m0
pslld m4, m2, 4
mova [t3+wq*2+400*8+24], m8
pslld m5, m3, 4
paddd m4, m2
pslld m2, 3
paddd m5, m3
pslld m3, 3
paddd m2, m4
paddd m3, m5
%if ARCH_X86_32
pxor m7, m7
%else
SWAP m7, m6
%endif
psrlw m5, m1, 1
pavgw m5, m7 ; (b5 + 2) >> 2
punpcklwd m4, m5, m7
pmaddwd m4, m4
punpckhwd m5, m7
pmaddwd m5, m5
punpcklwd m0, m1, m7 ; b5
punpckhwd m1, m7
%if ARCH_X86_64
SWAP m7, m6
%endif
MAXSD m2, m4, m7
psubd m2, m4 ; p5
MAXSD m3, m5, m7
psubd m3, m5
MULLD m2, m13, m7 ; p5 * s0
MULLD m3, m13, m7
pmaddwd m0, m12 ; b5 * 164
pmaddwd m1, m12
paddusw m2, m12
paddusw m3, m12
psrld m2, 20 ; min(z5, 255)
psrld m3, 20
GATHER_X_BY_X m4, m2, m3, r0, dstm
punpcklwd m2, m4, m4
punpckhwd m3, m4, m4
MULLD m0, m2, m7
MULLD m1, m3, m7
paddd m0, m10 ; x5 * b5 * 164 + (1 << 11) + (1 << 15)
paddd m1, m10
mova [t4+wq*1+400*0+ 4], m4
psrld m0, 12
psrld m1, 12
mova [t3+wq*2+400*0+ 8], m0
mova [t3+wq*2+400*0+24], m1
add wq, 16
jl .v1_loop
mov r10, t2
mov t2, t1
mov t1, r10
ret
.prep_n: ; initial neighbor setup
movif64 wq, r5
movif32 wd, w1m
.prep_n_loop:
movu m0, [t4+wq*1+400*0+ 2]
movu m1, [t3+wq*2+400*0+ 4]
movu m2, [t3+wq*2+400*0+20]
movu m7, [t4+wq*1+400*0+ 4]
movu m8, [t3+wq*2+400*0+ 8]
paddw m3, m0, [t4+wq*1+400*0+ 0]
paddd m4, m1, [t3+wq*2+400*0+ 0]
paddd m5, m2, [t3+wq*2+400*0+16]
paddw m3, m7
paddd m4, m8
movu m7, [t3+wq*2+400*0+24]
paddw m0, m3
paddd m1, m4
psllw m3, 2
pslld m4, 2
paddd m5, m7
paddd m2, m5
pslld m5, 2
paddw m0, m3 ; a5 565
paddd m1, m4 ; b5 565
paddd m2, m5
mova [t4+wq*1+400* 6+ 0], m0
mova [t3+wq*2+400*12+ 0], m1
mova [t3+wq*2+400*12+16], m2
movu m0, [t4+wq*1+400*2+ 4]
movu m1, [t3+wq*2+400*4+ 8]
movu m2, [t3+wq*2+400*4+24]
movu m3, [t4+wq*1+400*2+ 2]
movu m4, [t3+wq*2+400*4+ 4]
movu m5, [t3+wq*2+400*4+20]
paddw m0, [t4+wq*1+400*2+ 0]
paddd m1, [t3+wq*2+400*4+ 0]
paddd m2, [t3+wq*2+400*4+16]
paddw m3, m0
paddd m4, m1
paddd m5, m2
psllw m3, 2 ; a3[-1] 444
pslld m4, 2 ; b3[-1] 444
pslld m5, 2
psubw m3, m0 ; a3[-1] 343
psubd m4, m1 ; b3[-1] 343
psubd m5, m2
mova [t4+wq*1+400* 8+ 0], m3
mova [t3+wq*2+400*16+ 0], m4
mova [t3+wq*2+400*16+16], m5
movu m0, [t4+wq*1+400*4+ 4]
movu m1, [t3+wq*2+400*8+ 8]
movu m2, [t3+wq*2+400*8+24]
movu m3, [t4+wq*1+400*4+ 2]
movu m4, [t3+wq*2+400*8+ 4]
movu m5, [t3+wq*2+400*8+20]
paddw m0, [t4+wq*1+400*4+ 0]
paddd m1, [t3+wq*2+400*8+ 0]
paddd m2, [t3+wq*2+400*8+16]
paddw m3, m0
paddd m4, m1
paddd m5, m2
psllw m3, 2 ; a3[ 0] 444
pslld m4, 2 ; b3[ 0] 444
pslld m5, 2
mova [t4+wq*1+400*10+ 0], m3
mova [t3+wq*2+400*20+ 0], m4
mova [t3+wq*2+400*20+16], m5
psubw m3, m0 ; a3[ 0] 343
psubd m4, m1 ; b3[ 0] 343
psubd m5, m2
mova [t4+wq*1+400*12+ 0], m3
mova [t3+wq*2+400*24+ 0], m4
mova [t3+wq*2+400*24+16], m5
add wq, 16
jl .prep_n_loop
ret
ALIGN function_align
.n0: ; neighbor + output (even rows)
movif64 wq, r5
movif32 wd, w1m
.n0_loop:
movu m0, [t4+wq*1+ 4]
movu m2, [t4+wq*1+ 2]
paddw m0, [t4+wq*1+ 0]
paddw m0, m2
paddw m2, m0
psllw m0, 2
paddw m0, m2 ; a5
movu m4, [t3+wq*2+ 8]
movu m5, [t3+wq*2+24]
movu m1, [t3+wq*2+ 4]
movu m3, [t3+wq*2+20]
paddd m4, [t3+wq*2+ 0]
paddd m5, [t3+wq*2+16]
paddd m4, m1
paddd m5, m3
paddd m1, m4
paddd m3, m5
pslld m4, 2
pslld m5, 2
paddd m4, m1 ; b5
paddd m5, m3
movu m2, [t4+wq*1+400* 6]
paddw m2, m0
mova [t4+wq*1+400* 6], m0
paddd m0, m4, [t3+wq*2+400*12+ 0]
paddd m1, m5, [t3+wq*2+400*12+16]
mova [t3+wq*2+400*12+ 0], m4
mova [t3+wq*2+400*12+16], m5
mova [rsp+16+ARCH_X86_32*4], m1
movu m3, [t4+wq*1+400*2+4]
movu m5, [t4+wq*1+400*2+2]
paddw m3, [t4+wq*1+400*2+0]
paddw m5, m3
psllw m5, 2 ; a3[ 1] 444
psubw m4, m5, m3 ; a3[ 1] 343
movu m3, [t4+wq*1+400* 8]
paddw m3, [t4+wq*1+400*10]
paddw m3, m4
mova [t4+wq*1+400* 8], m4
mova [t4+wq*1+400*10], m5
movu m1, [t3+wq*2+400*4+ 8]
movu m5, [t3+wq*2+400*4+ 4]
movu m7, [t3+wq*2+400*4+24]
movu m8, [t3+wq*2+400*4+20]
paddd m1, [t3+wq*2+400*4+ 0]
paddd m7, [t3+wq*2+400*4+16]
paddd m5, m1
paddd m8, m7
pslld m5, 2 ; b3[ 1] 444
pslld m8, 2
psubd m4, m5, m1 ; b3[ 1] 343
%if ARCH_X86_32
mova [esp+52], m8
psubd m8, m7
%else
psubd m6, m8, m7
SWAP m8, m6
%endif
paddd m1, m4, [t3+wq*2+400*16+ 0]
paddd m7, m8, [t3+wq*2+400*16+16]
paddd m1, [t3+wq*2+400*20+ 0]
paddd m7, [t3+wq*2+400*20+16]
mova [t3+wq*2+400*16+ 0], m4
mova [t3+wq*2+400*16+16], m8
mova [t3+wq*2+400*20+ 0], m5
%if ARCH_X86_32
mova m8, [esp+52]
%else
SWAP m8, m6
pxor m6, m6
%endif
mova [t3+wq*2+400*20+16], m8
mova [rsp+32+ARCH_X86_32*4], m7
movu m5, [dstq+wq]
punpcklwd m4, m5, m6
punpcklwd m7, m2, m6
pmaddwd m7, m4 ; a5 * src
punpcklwd m8, m3, m6
pmaddwd m8, m4 ; a3 * src
punpckhwd m5, m6
punpckhwd m2, m6
pmaddwd m2, m5
punpckhwd m3, m6
pmaddwd m3, m5
pslld m4, 13
pslld m5, 13
psubd m0, m7 ; b5 - a5 * src + (1 << 8)
psubd m1, m8 ; b3 - a3 * src + (1 << 8)
mova m7, [base+pd_0xffff]
psrld m0, 9
pslld m1, 7
pand m0, m7
pandn m8, m7, m1
por m0, m8
mova m1, [rsp+16+ARCH_X86_32*4]
mova m8, [rsp+32+ARCH_X86_32*4]
psubd m1, m2
psubd m8, m3
mova m2, [base+pd_4096]
psrld m1, 9
pslld m8, 7
pand m1, m7
pandn m7, m8
por m1, m7
pmaddwd m0, m15
pmaddwd m1, m15
%if ARCH_X86_32
pxor m7, m7
%else
SWAP m7, m6
%endif
paddd m4, m2
paddd m5, m2
paddd m0, m4
paddd m1, m5
psrad m0, 8
psrad m1, 8
packssdw m0, m1 ; clip
pmaxsw m0, m7
psrlw m0, 5
mova [dstq+wq], m0
add wq, 16
jl .n0_loop
add dstq, dst_stridemp
ret
%if ARCH_X86_64
SWAP m6, m7
%endif
ALIGN function_align
.n1: ; neighbor + output (odd rows)
movif64 wq, r5
movif32 wd, w1m
.n1_loop:
movu m3, [t4+wq*1+400*4+4]
movu m5, [t4+wq*1+400*4+2]
paddw m3, [t4+wq*1+400*4+0]
paddw m5, m3
psllw m5, 2 ; a3[ 1] 444
psubw m4, m5, m3 ; a3[ 1] 343
paddw m3, m4, [t4+wq*1+400*12]
paddw m3, [t4+wq*1+400*10]
mova [t4+wq*1+400*10], m5
mova [t4+wq*1+400*12], m4
movu m1, [t3+wq*2+400*8+ 8]
movu m5, [t3+wq*2+400*8+ 4]
movu m7, [t3+wq*2+400*8+24]
movu m8, [t3+wq*2+400*8+20]
paddd m1, [t3+wq*2+400*8+ 0]
paddd m7, [t3+wq*2+400*8+16]
paddd m5, m1
paddd m8, m7
pslld m5, 2 ; b3[ 1] 444
pslld m8, 2
psubd m4, m5, m1 ; b3[ 1] 343
psubd m0, m8, m7
paddd m1, m4, [t3+wq*2+400*24+ 0]
paddd m7, m0, [t3+wq*2+400*24+16]
paddd m1, [t3+wq*2+400*20+ 0]
paddd m7, [t3+wq*2+400*20+16]
mova [t3+wq*2+400*20+ 0], m5
mova [t3+wq*2+400*20+16], m8
mova [t3+wq*2+400*24+ 0], m4
mova [t3+wq*2+400*24+16], m0
mova m5, [dstq+wq]
mova m2, [t4+wq*1+400* 6]
punpcklwd m4, m5, m6
punpcklwd m8, m2, m6
pmaddwd m8, m4 ; a5 * src
punpcklwd m0, m3, m6
pmaddwd m0, m4 ; a3 * src
punpckhwd m5, m6
punpckhwd m2, m6
pmaddwd m2, m5
punpckhwd m3, m6
pmaddwd m3, m5
psubd m1, m0 ; b3 - a3 * src + (1 << 8)
pslld m4, 13
pslld m5, 13
mova m0, [t3+wq*2+400*12+ 0]
psubd m0, m8 ; b5 - a5 * src + (1 << 8)
mova m8, [t3+wq*2+400*12+16]
psubd m8, m2
psubd m7, m3
mova m2, [base+pd_0xffff]
pslld m1, 7
psrld m0, 8
psrld m8, 8
pslld m7, 7
pand m0, m2
pandn m3, m2, m1
por m0, m3
pand m8, m2
pandn m2, m7
por m2, m8
mova m1, [base+pd_4096]
pmaddwd m0, m15
pmaddwd m2, m15
%if ARCH_X86_64
SWAP m7, m6
%endif
pxor m7, m7
paddd m4, m1
paddd m5, m1
paddd m0, m4
paddd m2, m5
psrad m0, 8
psrad m2, 8
packssdw m0, m2 ; clip
pmaxsw m0, m7
psrlw m0, 5
mova [dstq+wq], m0
add wq, 16
jl .n1_loop
add dstq, dst_stridemp
movif32 dstm, dstq
ret
|
;;
;; Copyright (c) 2012-2018, 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 "job_aes_hmac.asm"
%include "mb_mgr_datastruct.asm"
%include "include/reg_sizes.asm"
%include "include/memcpy.asm"
%include "include/const.inc"
extern sha512_x2_avx
section .data
default rel
align 16
byteswap: ;ddq 0x08090a0b0c0d0e0f0001020304050607
dq 0x0001020304050607, 0x08090a0b0c0d0e0f
section .text
%ifndef FUNC
%define FUNC submit_job_hmac_sha_512_avx
%define SHA_X_DIGEST_SIZE 512
%endif
%if 1
%ifdef LINUX
%define arg1 rdi
%define arg2 rsi
%define reg3 rcx
%define reg4 rdx
%else
%define arg1 rcx
%define arg2 rdx
%define reg3 rdi
%define reg4 rsi
%endif
%define state arg1
%define job arg2
%define len2 arg2
; idx needs to be in rbx, rbp, r12-r15
%define last_len rbp
%define idx rbp
%define p r11
%define start_offset r11
%define unused_lanes rbx
%define tmp4 rbx
%define job_rax rax
%define len rax
%define size_offset reg3
%define tmp2 reg3
%define lane reg4
%define tmp3 reg4
%define extra_blocks r8
%define tmp r9
%define p2 r9
%define lane_data r10
%endif
; This routine clobbers rbx, rbp, rsi, rdi
struc STACK
_gpr_save: resq 4
_rsp_save: resq 1
endstruc
; JOB* FUNC(MB_MGR_HMAC_sha_512_OOO *state, JOB_AES_HMAC *job)
; arg 1 : rcx : state
; arg 2 : rdx : job
MKGLOBAL(FUNC,function,internal)
FUNC:
mov rax, rsp
sub rsp, STACK_size
and rsp, -16
mov [rsp + _gpr_save + 8*0], rbx
mov [rsp + _gpr_save + 8*1], rbp
%ifndef LINUX
mov [rsp + _gpr_save + 8*2], rsi
mov [rsp + _gpr_save + 8*3], rdi
%endif
mov [rsp + _rsp_save], rax ; original SP
mov unused_lanes, [state + _unused_lanes_sha512]
movzx lane, BYTE(unused_lanes)
shr unused_lanes, 8
imul lane_data, lane, _SHA512_LANE_DATA_size
lea lane_data, [state + _ldata_sha512 + lane_data]
mov [state + _unused_lanes_sha512], unused_lanes
mov len, [job + _msg_len_to_hash_in_bytes]
mov tmp, len
shr tmp, 7 ; divide by 128, len in terms of blocks
mov [lane_data + _job_in_lane_sha512], job
mov dword [lane_data + _outer_done_sha512], 0
vmovdqa xmm0, [state + _lens_sha512]
XVPINSRW xmm0, xmm1, p, lane, tmp, scale_x16
vmovdqa [state + _lens_sha512], xmm0
mov last_len, len
and last_len, 127
lea extra_blocks, [last_len + 17 + 127]
shr extra_blocks, 7
mov [lane_data + _extra_blocks_sha512], DWORD(extra_blocks)
mov p, [job + _src]
add p, [job + _hash_start_src_offset_in_bytes]
mov [state + _args_data_ptr_sha512 + PTR_SZ*lane], p
cmp len, 128
jb copy_lt128
fast_copy:
add p, len
%assign I 0
%rep 2
vmovdqu xmm0, [p - 128 + I*4*16 + 0*16]
vmovdqu xmm1, [p - 128 + I*4*16 + 1*16]
vmovdqu xmm2, [p - 128 + I*4*16 + 2*16]
vmovdqu xmm3, [p - 128 + I*4*16 + 3*16]
vmovdqa [lane_data + _extra_block_sha512 + I*4*16 + 0*16], xmm0
vmovdqa [lane_data + _extra_block_sha512 + I*4*16 + 1*16], xmm1
vmovdqa [lane_data + _extra_block_sha512 + I*4*16 + 2*16], xmm2
vmovdqa [lane_data + _extra_block_sha512 + I*4*16 + 3*16], xmm3
%assign I (I+1)
%endrep
end_fast_copy:
mov size_offset, extra_blocks
shl size_offset, 7
sub size_offset, last_len
add size_offset, 128-8
mov [lane_data + _size_offset_sha512], DWORD(size_offset)
mov start_offset, 128
sub start_offset, last_len
mov [lane_data + _start_offset_sha512], DWORD(start_offset)
lea tmp, [8*128 + 8*len]
bswap tmp
mov [lane_data + _extra_block_sha512 + size_offset], tmp
mov tmp, [job + _auth_key_xor_ipad]
%assign I 0
%rep 4
vmovdqu xmm0, [tmp + I * 2 * 8]
vmovq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*lane + (2*I)*SHA512_DIGEST_ROW_SIZE], xmm0
vpextrq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*lane + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], xmm0, 1
%assign I (I+1)
%endrep
test len, ~127
jnz ge128_bytes
lt128_bytes:
vmovdqa xmm0, [state + _lens_sha512]
XVPINSRW xmm0, xmm1, tmp, lane, extra_blocks, scale_x16
vmovdqa [state + _lens_sha512], xmm0
lea tmp, [lane_data + _extra_block_sha512 + start_offset]
mov [state + _args_data_ptr_sha512 + PTR_SZ*lane], tmp ;; 8 to hold a UINT8
mov dword [lane_data + _extra_blocks_sha512], 0
ge128_bytes:
cmp unused_lanes, 0xff
jne return_null
jmp start_loop
align 16
start_loop:
; Find min length
vmovdqa xmm0, [state + _lens_sha512]
vphminposuw xmm1, xmm0
vpextrw DWORD(len2), xmm1, 0 ; min value
vpextrw DWORD(idx), xmm1, 1 ; min index (0...1)
cmp len2, 0
je len_is_0
vpshuflw xmm1, xmm1, 0xA0
vpsubw xmm0, xmm0, xmm1
vmovdqa [state + _lens_sha512], xmm0
; "state" and "args" are the same address, arg1
; len is arg2
call sha512_x2_avx
; state and idx are intact
len_is_0:
; process completed job "idx"
imul lane_data, idx, _SHA512_LANE_DATA_size
lea lane_data, [state + _ldata_sha512 + lane_data]
mov DWORD(extra_blocks), [lane_data + _extra_blocks_sha512]
cmp extra_blocks, 0
jne proc_extra_blocks
cmp dword [lane_data + _outer_done_sha512], 0
jne end_loop
proc_outer:
mov dword [lane_data + _outer_done_sha512], 1
mov DWORD(size_offset), [lane_data + _size_offset_sha512]
mov qword [lane_data + _extra_block_sha512 + size_offset], 0
vmovdqa xmm0, [state + _lens_sha512]
XVPINSRW xmm0, xmm1, tmp, idx, 1, scale_x16
vmovdqa [state + _lens_sha512], xmm0
lea tmp, [lane_data + _outer_block_sha512]
mov job, [lane_data + _job_in_lane_sha512]
mov [state + _args_data_ptr_sha512 + PTR_SZ*idx], tmp
%assign I 0
%rep (SHA_X_DIGEST_SIZE / (8 * 16))
vmovq xmm0, [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*I*SHA512_DIGEST_ROW_SIZE]
vpinsrq xmm0, [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], 1
vpshufb xmm0, [rel byteswap]
vmovdqa [lane_data + _outer_block_sha512 + I * 16], xmm0
%assign I (I+1)
%endrep
mov tmp, [job + _auth_key_xor_opad]
%assign I 0
%rep 4
vmovdqu xmm0, [tmp + I * 16]
vmovq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*I*SHA512_DIGEST_ROW_SIZE], xmm0
vpextrq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], xmm0, 1
%assign I (I+1)
%endrep
jmp start_loop
align 16
proc_extra_blocks:
mov DWORD(start_offset), [lane_data + _start_offset_sha512]
vmovdqa xmm0, [state + _lens_sha512]
XVPINSRW xmm0, xmm1, tmp, idx, extra_blocks, scale_x16
vmovdqa [state + _lens_sha512], xmm0
lea tmp, [lane_data + _extra_block_sha512 + start_offset]
mov [state + _args_data_ptr_sha512 + PTR_SZ*idx], tmp ;; idx is index of shortest length message
mov dword [lane_data + _extra_blocks_sha512], 0
jmp start_loop
align 16
copy_lt128:
;; less than one message block of data
;; destination extra block but backwards by len from where 0x80 pre-populated
lea p2, [lane_data + _extra_block + 128]
sub p2, len
memcpy_avx_128_1 p2, p, len, tmp4, tmp2, xmm0, xmm1, xmm2, xmm3
mov unused_lanes, [state + _unused_lanes_sha512]
jmp end_fast_copy
return_null:
xor job_rax, job_rax
jmp return
align 16
end_loop:
mov job_rax, [lane_data + _job_in_lane_sha512]
mov unused_lanes, [state + _unused_lanes_sha512]
mov qword [lane_data + _job_in_lane_sha512], 0
or dword [job_rax + _status], STS_COMPLETED_HMAC
shl unused_lanes, 8
or unused_lanes, idx
mov [state + _unused_lanes_sha512], unused_lanes
mov p, [job_rax + _auth_tag_output]
%if (SHA_X_DIGEST_SIZE != 384)
cmp qword [job_rax + _auth_tag_output_len_in_bytes], 32
jne copy_full_digest
%else
cmp qword [job_rax + _auth_tag_output_len_in_bytes], 24
jne copy_full_digest
%endif
;; copy 32 bytes for SHA512 / 24 bytes and SHA384
mov QWORD(tmp), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 0*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 1*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp3), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*SHA512_DIGEST_ROW_SIZE]
%if (SHA_X_DIGEST_SIZE != 384)
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 3*SHA512_DIGEST_ROW_SIZE]
%endif
bswap QWORD(tmp)
bswap QWORD(tmp2)
bswap QWORD(tmp3)
%if (SHA_X_DIGEST_SIZE != 384)
bswap QWORD(tmp4)
%endif
mov [p + 0*8], QWORD(tmp)
mov [p + 1*8], QWORD(tmp2)
mov [p + 2*8], QWORD(tmp3)
%if (SHA_X_DIGEST_SIZE != 384)
mov [p + 3*8], QWORD(tmp4)
%endif
jmp clear_ret
copy_full_digest:
;; copy 64 bytes for SHA512 / 48 bytes and SHA384
mov QWORD(tmp), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 0*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 1*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp3), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 3*SHA512_DIGEST_ROW_SIZE]
bswap QWORD(tmp)
bswap QWORD(tmp2)
bswap QWORD(tmp3)
bswap QWORD(tmp4)
mov [p + 0*8], QWORD(tmp)
mov [p + 1*8], QWORD(tmp2)
mov [p + 2*8], QWORD(tmp3)
mov [p + 3*8], QWORD(tmp4)
mov QWORD(tmp), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 4*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 5*SHA512_DIGEST_ROW_SIZE]
%if (SHA_X_DIGEST_SIZE != 384)
mov QWORD(tmp3), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 6*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 7*SHA512_DIGEST_ROW_SIZE]
%endif
bswap QWORD(tmp)
bswap QWORD(tmp2)
%if (SHA_X_DIGEST_SIZE != 384)
bswap QWORD(tmp3)
bswap QWORD(tmp4)
%endif
mov [p + 4*8], QWORD(tmp)
mov [p + 5*8], QWORD(tmp2)
%if (SHA_X_DIGEST_SIZE != 384)
mov [p + 6*8], QWORD(tmp3)
mov [p + 7*8], QWORD(tmp4)
%endif
clear_ret:
%ifdef SAFE_DATA
;; Clear digest (48B/64B), outer_block (48B/64B) and extra_block (128B) of returned job
%assign J 0
%rep 6
mov qword [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + J*SHA512_DIGEST_ROW_SIZE], 0
%assign J (J+1)
%endrep
%if (SHA_X_DIGEST_SIZE != 384)
mov qword [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 6*SHA256_DIGEST_ROW_SIZE], 0
mov qword [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 7*SHA256_DIGEST_ROW_SIZE], 0
%endif
vpxor xmm0, xmm0
imul lane_data, idx, _SHA512_LANE_DATA_size
lea lane_data, [state + _ldata_sha512 + lane_data]
;; Clear first 128 bytes of extra_block
%assign offset 0
%rep 8
vmovdqa [lane_data + _extra_block + offset], xmm0
%assign offset (offset + 16)
%endrep
;; Clear first 48 bytes (SHA-384) or 64 bytes (SHA-512) of outer_block
vmovdqa [lane_data + _outer_block], xmm0
vmovdqa [lane_data + _outer_block + 16], xmm0
vmovdqa [lane_data + _outer_block + 32], xmm0
%if (SHA_X_DIGEST_SIZE != 384)
vmovdqa [lane_data + _outer_block + 48], xmm0
%endif
%endif ;; SAFE_DATA
return:
mov rbx, [rsp + _gpr_save + 8*0]
mov rbp, [rsp + _gpr_save + 8*1]
%ifndef LINUX
mov rsi, [rsp + _gpr_save + 8*2]
mov rdi, [rsp + _gpr_save + 8*3]
%endif
mov rsp, [rsp + _rsp_save] ; original SP
ret
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
BuildItemMessage:
ld hl, ItemNamePointers
ldh a, [$F1]
ld d, $00
ld e, a
add hl, de
add hl, de
ldi a, [hl]
ld h, [hl]
ld l, a
ld de, wCustomMessage
jp MessageCopyString
FoundItemForOtherPlayerPostfix:
db m" for another player", $ff
GotItemFromOtherPlayerPostfix:
db m" from another player", $ff
MessagePad:
jr .start
.loop:
ld a, $20
ld [de], a
inc de
ld a, $ff
ld [de], a
.start:
ld a, e
and $0F
jr nz, .loop
ret
MessageAddTargetPlayer:
call MessagePad
ld hl, FoundItemForOtherPlayerPostfix
call MessageCopyString
ret
MessageAddFromPlayer:
call MessagePad
ld hl, GotItemFromOtherPlayerPostfix
call MessageCopyString
ret
MessageCopyString:
.loop:
ldi a, [hl]
ld [de], a
cp $ff
ret z
inc de
jr .loop
MessageAddSpace:
ld a, $20
ld [de], a
inc de
ld a, $ff
ld [de], a
ret
ItemNamePointers:
dw ItemNamePowerBracelet
dw ItemNameShield
dw ItemNameBow
dw ItemNameHookshot
dw ItemNameMagicRod
dw ItemNamePegasusBoots
dw ItemNameOcarina
dw ItemNameFeather
dw ItemNameShovel
dw ItemNameMagicPowder
dw ItemNameBomb
dw ItemNameSword
dw ItemNameFlippers
dw ItemNameNone
dw ItemNameBoomerang
dw ItemNameSlimeKey
dw ItemNameMedicine
dw ItemNameTailKey
dw ItemNameAnglerKey
dw ItemNameFaceKey
dw ItemNameBirdKey
dw ItemNameGoldLeaf
dw ItemNameMap
dw ItemNameCompass
dw ItemNameStoneBeak
dw ItemNameNightmareKey
dw ItemNameSmallKey
dw ItemNameRupees50
dw ItemNameRupees20
dw ItemNameRupees100
dw ItemNameRupees200
dw ItemNameRupees500
dw ItemNameSeashell
dw ItemNameMessage
dw ItemNameNone
dw ItemNameKey1
dw ItemNameKey2
dw ItemNameKey3
dw ItemNameKey4
dw ItemNameKey5
dw ItemNameKey6
dw ItemNameKey7
dw ItemNameKey8
dw ItemNameKey9
dw ItemNameMap1
dw ItemNameMap2
dw ItemNameMap3
dw ItemNameMap4
dw ItemNameMap5
dw ItemNameMap6
dw ItemNameMap7
dw ItemNameMap8
dw ItemNameMap9
dw ItemNameCompass1
dw ItemNameCompass2
dw ItemNameCompass3
dw ItemNameCompass4
dw ItemNameCompass5
dw ItemNameCompass6
dw ItemNameCompass7
dw ItemNameCompass8
dw ItemNameCompass9
dw ItemNameStoneBeak1
dw ItemNameStoneBeak2
dw ItemNameStoneBeak3
dw ItemNameStoneBeak4
dw ItemNameStoneBeak5
dw ItemNameStoneBeak6
dw ItemNameStoneBeak7
dw ItemNameStoneBeak8
dw ItemNameStoneBeak9
dw ItemNameNightmareKey1
dw ItemNameNightmareKey2
dw ItemNameNightmareKey3
dw ItemNameNightmareKey4
dw ItemNameNightmareKey5
dw ItemNameNightmareKey6
dw ItemNameNightmareKey7
dw ItemNameNightmareKey8
dw ItemNameNightmareKey9
dw ItemNameToadstool
dw ItemNameNone ; 0x51
dw ItemNameNone ; 0x52
dw ItemNameNone ; 0x53
dw ItemNameNone ; 0x54
dw ItemNameNone ; 0x55
dw ItemNameNone ; 0x56
dw ItemNameNone ; 0x57
dw ItemNameNone ; 0x58
dw ItemNameNone ; 0x59
dw ItemNameNone ; 0x5a
dw ItemNameNone ; 0x5b
dw ItemNameNone ; 0x5c
dw ItemNameNone ; 0x5d
dw ItemNameNone ; 0x5e
dw ItemNameNone ; 0x5f
dw ItemNameNone ; 0x60
dw ItemNameNone ; 0x61
dw ItemNameNone ; 0x62
dw ItemNameNone ; 0x63
dw ItemNameNone ; 0x64
dw ItemNameNone ; 0x65
dw ItemNameNone ; 0x66
dw ItemNameNone ; 0x67
dw ItemNameNone ; 0x68
dw ItemNameNone ; 0x69
dw ItemNameNone ; 0x6a
dw ItemNameNone ; 0x6b
dw ItemNameNone ; 0x6c
dw ItemNameNone ; 0x6d
dw ItemNameNone ; 0x6e
dw ItemNameNone ; 0x6f
dw ItemNameNone ; 0x70
dw ItemNameNone ; 0x71
dw ItemNameNone ; 0x72
dw ItemNameNone ; 0x73
dw ItemNameNone ; 0x74
dw ItemNameNone ; 0x75
dw ItemNameNone ; 0x76
dw ItemNameNone ; 0x77
dw ItemNameNone ; 0x78
dw ItemNameNone ; 0x79
dw ItemNameNone ; 0x7a
dw ItemNameNone ; 0x7b
dw ItemNameNone ; 0x7c
dw ItemNameNone ; 0x7d
dw ItemNameNone ; 0x7e
dw ItemNameNone ; 0x7f
dw ItemNameHeartPiece ; 0x80
dw ItemNameBowwow
dw ItemName10Arrows
dw ItemNameSingleArrow
dw ItemNamePowderUpgrade
dw ItemNameBombUpgrade
dw ItemNameArrowUpgrade
dw ItemNameRedTunic
dw ItemNameBlueTunic
dw ItemNameHeartContainer
dw ItemNameBadHeartContainer
dw ItemNameSong1
dw ItemNameSong2
dw ItemNameSong3
dw ItemInstrument1
dw ItemInstrument2
dw ItemInstrument3
dw ItemInstrument4
dw ItemInstrument5
dw ItemInstrument6
dw ItemInstrument7
dw ItemInstrument8
ItemNameNone:
db m"NONE", $ff
ItemNamePowerBracelet:
db m"Got the Power Bracelet", $ff
ItemNameShield:
db m"Got a Shield", $ff
ItemNameBow:
db m"Got the Bow", $ff
ItemNameHookshot:
db m"Got the Hookshot", $ff
ItemNameMagicRod:
db m"Got the Magic Rod", $ff
ItemNamePegasusBoots:
db m"Got the Pegasus Boots", $ff
ItemNameOcarina:
db m"Got the Ocarina", $ff
ItemNameFeather:
db m"Got the Feather", $ff
ItemNameShovel:
db m"Got the Shovel", $ff
ItemNameMagicPowder:
db m"Got Magic Powder", $ff
ItemNameBomb:
db m"Got Bombs", $ff
ItemNameSword:
db m"Got a Sword", $ff
ItemNameFlippers:
db m"Got the Flippers", $ff
ItemNameBoomerang:
db m"Got the Boomerang", $ff
ItemNameSlimeKey:
db m"Got the Slime Key", $ff
ItemNameMedicine:
db m"Got some Medicine", $ff
ItemNameTailKey:
db m"Got the Tail Key", $ff
ItemNameAnglerKey:
db m"Got the Angler Key", $ff
ItemNameFaceKey:
db m"Got the Face Key", $ff
ItemNameBirdKey:
db m"Got the Bird Key", $ff
ItemNameGoldLeaf:
db m"Got the Golden Leaf", $ff
ItemNameMap:
db m"Got the Dungeon Map", $ff
ItemNameCompass:
db m"Got the Dungeon Compass", $ff
ItemNameStoneBeak:
db m"Got the Stone Beak", $ff
ItemNameNightmareKey:
db m"Got the Nightmare Key", $ff
ItemNameSmallKey:
db m"Got a Small Key", $ff
ItemNameRupees50:
db m"Got 50 Rupees", $ff
ItemNameRupees20:
db m"Got 20 Rupees", $ff
ItemNameRupees100:
db m"Got 100 Rupees", $ff
ItemNameRupees200:
db m"Got 200 Rupees", $ff
ItemNameRupees500:
db m"Got 500 Rupees", $ff
ItemNameSeashell:
db m"Got a Secret Seashell", $ff
ItemNameMessage:
db m"Got ... nothing?", $ff
ItemNameKey1:
db m"Got a Tail Cave Small Key", $ff
ItemNameKey2:
db m"Got a Bottle Grotto Small Key", $ff
ItemNameKey3:
db m"Got a Key Cavern Small Key", $ff
ItemNameKey4:
db m"Got a Angler's Tunnel Small Key", $ff
ItemNameKey5:
db m"Got a Catfish's Maw Small Key", $ff
ItemNameKey6:
db m"Got a Face Shrine Small Key", $ff
ItemNameKey7:
db m"Got a Eagle's Tower Small Key", $ff
ItemNameKey8:
db m"Got a Turtle Rock Small Key", $ff
ItemNameKey9:
db m"Got a Color Dungeon Small Key", $ff
ItemNameMap1:
db m"Got the Tail Cave Map", $ff
ItemNameMap2:
db m"Got the Bottle Grotto Map", $ff
ItemNameMap3:
db m"Got the Key Cavern Map", $ff
ItemNameMap4:
db m"Got the Angler's Tunnel Map", $ff
ItemNameMap5:
db m"Got the Catfish's Maw Map", $ff
ItemNameMap6:
db m"Got the Face Shrine Map", $ff
ItemNameMap7:
db m"Got the Eagle's Tower Map", $ff
ItemNameMap8:
db m"Got the Turtle Rock Map", $ff
ItemNameMap9:
db m"Got the Color Dungeon Map", $ff
ItemNameCompass1:
db m"Got the Tail Cave Compass", $ff
ItemNameCompass2:
db m"Got the Bottle Grotto Compass", $ff
ItemNameCompass3:
db m"Got the Key Cavern Compass", $ff
ItemNameCompass4:
db m"Got the Angler's Tunnel Compass", $ff
ItemNameCompass5:
db m"Got the Catfish's Maw Compass", $ff
ItemNameCompass6:
db m"Got the Face Shrine Compass", $ff
ItemNameCompass7:
db m"Got the Eagle's Tower Compass", $ff
ItemNameCompass8:
db m"Got the Turtle Rock Compass", $ff
ItemNameCompass9:
db m"Got the Color Dungeon Compass", $ff
ItemNameStoneBeak1:
db m"Got the Tail Cave Stone Beak", $ff
ItemNameStoneBeak2:
db m"Got the Bottle Grotto Stone Beak", $ff
ItemNameStoneBeak3:
db m"Got the Key Cavern Stone Beak", $ff
ItemNameStoneBeak4:
db m"Got the Angler's Tunnel Stone Beak", $ff
ItemNameStoneBeak5:
db m"Got the Catfish's Maw Stone Beak", $ff
ItemNameStoneBeak6:
db m"Got the Face Shrine Stone Beak", $ff
ItemNameStoneBeak7:
db m"Got the Eagle's Tower Stone Beak", $ff
ItemNameStoneBeak8:
db m"Got the Turtle Rock Stone Beak", $ff
ItemNameStoneBeak9:
db m"Got the Color Dungeon Stone Beak", $ff
ItemNameNightmareKey1:
db m"Got the Tail Cave Nightmare Key", $ff
ItemNameNightmareKey2:
db m"Got the Bottle Grotto Nightmare Key", $ff
ItemNameNightmareKey3:
db m"Got the Key Cavern Nightmare Key", $ff
ItemNameNightmareKey4:
db m"Got the Angler's Tunnel Nightmare Key", $ff
ItemNameNightmareKey5:
db m"Got the Catfish's Maw Nightmare Key", $ff
ItemNameNightmareKey6:
db m"Got the Face Shrine Nightmare Key", $ff
ItemNameNightmareKey7:
db m"Got the Eagle's Tower Nightmare Key", $ff
ItemNameNightmareKey8:
db m"Got the Turtle Rock Nightmare Key", $ff
ItemNameNightmareKey9:
db m"Got the Color Dungeon Nightmare Key", $ff
ItemNameToadstool:
db m"Got the Toadstool", $ff
ItemNameHeartPiece:
db m"Got the Piece of Heart", $ff
ItemNameBowwow:
db m"Got the Bowwow", $ff
ItemName10Arrows:
db m"Got 10 Arrows", $ff
ItemNameSingleArrow:
db m"Got the Single Arrow", $ff
ItemNamePowderUpgrade:
db m"Got the Magic Powder Upgrade", $ff
ItemNameBombUpgrade:
db m"Got the Bombs Upgrade", $ff
ItemNameArrowUpgrade:
db m"Got the Arrow Upgrade", $ff
ItemNameRedTunic:
db m"Got the Red Tunic", $ff
ItemNameBlueTunic:
db m"Got the Blue Tunic", $ff
ItemNameHeartContainer:
db m"Got the Heart Container", $ff
ItemNameBadHeartContainer:
db m"Got the Bad Heart Container", $ff
ItemNameSong1:
db m"Got the Ballad of the Wind Fish", $ff
ItemNameSong2:
db m"Got the Manbo's Mambo", $ff
ItemNameSong3:
db m"Got Frog's Song of Soul", $ff
ItemInstrument1:
db m"You've got the Full Moon Cello", $ff
ItemInstrument2:
db m"You've got the Conch Horn", $ff
ItemInstrument3:
db m"You've got the Sea Lily's Bell", $ff
ItemInstrument4:
db m"You've got the Surf Harp", $ff
ItemInstrument5:
db m"You've got the Wind Marimba", $ff
ItemInstrument6:
db m"You've got the Coral Triangle", $ff
ItemInstrument7:
db m"You've got the Organ of Evening Calm", $ff
ItemInstrument8:
db m"You've got the Thunder Drum", $ff
|
/* Copyright 2016 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/tools/graph_transforms/transform_graph.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/util/command_line_flags.h"
#include "tensorflow/tools/graph_transforms/transform_utils.h"
namespace tensorflow {
namespace graph_transforms {
using tensorflow::strings::Scanner;
Status ParseTransformParameters(const string& transforms_string,
TransformParameters* params_list) {
params_list->clear();
enum {
TRANSFORM_NAME,
TRANSFORM_PARAM_NAME,
TRANSFORM_PARAM_VALUE,
} state = TRANSFORM_NAME;
StringPiece remaining(transforms_string);
StringPiece match;
StringPiece transform_name;
StringPiece parameter_name;
StringPiece parameter_value;
TransformFuncParameters func_parameters;
while (!remaining.empty()) {
if (state == TRANSFORM_NAME) {
// Reset the list of parameters.
func_parameters.clear();
// Eat up any leading spaces.
Scanner(remaining).AnySpace().GetResult(&remaining, &match);
if (remaining.empty()) {
// Nothing remains after consuming trailing spaces.
// Consumed all transform parameter string without errors.
return Status::OK();
}
// See if we have a valid transform name.
const bool found_transform_name =
Scanner(remaining)
.Many(Scanner::LETTER_DIGIT_UNDERSCORE)
.GetResult(&remaining, &transform_name);
if (!found_transform_name) {
return errors::InvalidArgument("Looking for transform name, but found ",
remaining.ToString().c_str());
}
if (Scanner(remaining).OneLiteral("(").GetResult(&remaining, &match)) {
state = TRANSFORM_PARAM_NAME;
} else {
// Add a transform with no parameters.
params_list->push_back({transform_name.ToString(), func_parameters});
transform_name = "";
state = TRANSFORM_NAME;
}
} else if (state == TRANSFORM_PARAM_NAME) {
if (Scanner(remaining).OneLiteral(")").GetResult(&remaining, &match)) {
params_list->push_back({transform_name.ToString(), func_parameters});
transform_name = "";
state = TRANSFORM_NAME;
} else {
// Eat up any leading spaces or commas.
Scanner(remaining).ZeroOrOneLiteral(",").GetResult(&remaining, &match);
Scanner(remaining).AnySpace().GetResult(&remaining, &match);
// See if we have a valid parameter name.
const bool found_parameter_name =
Scanner(remaining)
.Many(Scanner::LETTER_DIGIT_UNDERSCORE)
.GetResult(&remaining, ¶meter_name);
if (!found_parameter_name) {
return errors::InvalidArgument(
"Looking for parameter name, but found ",
remaining.ToString().c_str());
}
if (Scanner(remaining).OneLiteral("=").GetResult(&remaining, &match)) {
state = TRANSFORM_PARAM_VALUE;
} else {
return errors::InvalidArgument("Looking for =, but found ",
remaining.ToString().c_str());
}
}
} else if (state == TRANSFORM_PARAM_VALUE) {
bool found_parameter_value;
// Deal with quoted values.
if (Scanner(remaining).OneLiteral("\"").GetResult(&remaining, &match)) {
found_parameter_value =
Scanner(remaining).ScanEscapedUntil('"').GetResult(
&remaining, ¶meter_value);
if (found_parameter_value) {
Scanner(remaining).OneLiteral("\"").GetResult(&remaining, &match);
}
} else {
// See if we have a valid parameter name.
found_parameter_value =
Scanner(remaining)
.Many(Scanner::LETTER_DIGIT_DASH_DOT_SLASH_UNDERSCORE)
.GetResult(&remaining, ¶meter_value);
}
if (!found_parameter_value) {
return errors::InvalidArgument("Looking for parameter name, but found ",
remaining.ToString().c_str());
}
func_parameters[parameter_name.ToString()].push_back(
parameter_value.ToString());
// Eat up any trailing quotes.
Scanner(remaining).ZeroOrOneLiteral("\"").GetResult(&remaining, &match);
Scanner(remaining).ZeroOrOneLiteral("'").GetResult(&remaining, &match);
state = TRANSFORM_PARAM_NAME;
}
}
return Status::OK();
}
int ParseFlagsAndTransformGraph(int argc, char* argv[], bool init_main) {
string in_graph = "";
string out_graph = "";
string inputs_string = "";
string outputs_string = "";
string transforms_string = "";
bool output_as_text = false;
std::vector<Flag> flag_list = {
Flag("in_graph", &in_graph, "input graph file name"),
Flag("out_graph", &out_graph, "output graph file name"),
Flag("inputs", &inputs_string, "inputs"),
Flag("outputs", &outputs_string, "outputs"),
Flag("transforms", &transforms_string, "list of transforms"),
Flag("output_as_text", &output_as_text,
"whether to write the graph in text protobuf format"),
};
string usage = Flags::Usage(argv[0], flag_list);
usage += "\nTransforms are:\n";
TransformRegistry* transform_registry = GetTransformRegistry();
for (const auto& pair : *transform_registry) {
usage += pair.first + "\n";
}
const bool parse_result = Flags::Parse(&argc, argv, flag_list);
// We need to call this to set up global state for TensorFlow.
if (init_main) {
port::InitMain(argv[0], &argc, &argv);
}
if (!parse_result) {
LOG(ERROR) << usage;
return -1;
}
if (argc > 1) {
LOG(ERROR) << "Unknown argument " << argv[1] << ".\n" << usage;
return -1;
}
if (in_graph.empty()) {
LOG(ERROR) << "in_graph graph can't be empty.\n" << usage;
return -1;
}
if (out_graph.empty()) {
LOG(ERROR) << "out_graph graph can't be empty.\n" << usage;
return -1;
}
if (transforms_string.empty()) {
LOG(ERROR) << "You must specify at least one transform.\n" << usage;
return -1;
}
std::vector<string> inputs = str_util::Split(inputs_string, ',');
std::vector<string> outputs = str_util::Split(outputs_string, ',');
TransformParameters transform_params;
Status parse_status =
ParseTransformParameters(transforms_string, &transform_params);
if (!parse_status.ok()) {
LOG(ERROR) << "Failed to parse --transform argument, error was "
<< parse_status.error_message();
return -1;
}
if (transform_params.empty()) {
LOG(ERROR) << "You must specify at least one transform.\n" << usage;
return -1;
}
GraphDef graph_def;
Status load_status = LoadTextOrBinaryGraphFile(in_graph, &graph_def);
if (!load_status.ok()) {
LOG(ERROR) << "Loading graph '" << in_graph << "' failed with "
<< load_status.error_message();
LOG(ERROR) << usage;
return -1;
}
Status transform_result =
TransformGraph(inputs, outputs, transform_params, &graph_def);
if (!transform_result.ok()) {
LOG(ERROR) << transform_result.error_message();
LOG(ERROR) << usage;
return -1;
}
Status save_status;
if (output_as_text) {
save_status = WriteTextProto(Env::Default(), out_graph, graph_def);
} else {
save_status = WriteBinaryProto(Env::Default(), out_graph, graph_def);
}
if (!save_status.ok()) {
LOG(ERROR) << "Saving graph '" << out_graph << "' failed with "
<< save_status.error_message();
return -1;
}
return 0;
}
Status ShouldIgnoreErrors(const TransformFuncParameters& transform_params,
bool* ignore_errors) {
*ignore_errors = false;
if (transform_params.count("ignore_errors") &&
(!transform_params.at("ignore_errors").empty())) {
const string& ignore_errors_string =
str_util::Lowercase(transform_params.at("ignore_errors").at(0));
if (ignore_errors_string == "true") {
*ignore_errors = true;
} else if (ignore_errors_string == "false") {
*ignore_errors = false;
} else {
return errors::InvalidArgument(
"ignore_errors should be true or false, found ",
ignore_errors_string);
}
}
return Status::OK();
}
Status TransformGraph(const std::vector<string>& inputs,
const std::vector<string>& outputs,
const TransformParameters& transform_params,
GraphDef* graph_def) {
TransformRegistry* transform_registry = GetTransformRegistry();
for (const auto& transform_info : transform_params) {
const string& transform_name = transform_info.first;
if (transform_name.empty()) {
continue;
}
if (!transform_registry->count(transform_name)) {
return errors::InvalidArgument("Transform '", transform_name,
"' not recognized.");
}
LOG(INFO) << "Applying " << transform_name;
const TransformFunc& transform_func =
transform_registry->at(transform_name);
TransformFuncContext context;
context.input_names = inputs;
context.output_names = outputs;
context.params = transform_info.second;
bool ignore_errors;
TF_RETURN_IF_ERROR(
ShouldIgnoreErrors(transform_info.second, &ignore_errors));
GraphDef transformed_graph_def;
Status transform_result =
transform_func(*graph_def, context, &transformed_graph_def);
if (!transform_result.ok()) {
if (ignore_errors) {
LOG(ERROR) << transform_name << ": Ignoring error "
<< transform_result.error_message();
transformed_graph_def = *graph_def;
} else {
return transform_result;
}
}
// Copy over the library from the original input graph.
*transformed_graph_def.mutable_library() = graph_def->library();
TF_RETURN_IF_ERROR(IsGraphValid(transformed_graph_def));
*graph_def = transformed_graph_def;
}
return Status::OK();
}
} // namespace graph_transforms
} // namespace tensorflow
|
.module Things
Code:
; ==========================================================================
; SubSectorStack.Push
; --------------------------------------------------------------------------
; Pushes information about the subsector to draw to the stack.
; --------------------------------------------------------------------------
; Inputs: IX: Pointer to the subsector containing the things to draw.
; Destroyed: AF, BC, DE, HL.
; ==========================================================================
SubSectorStack.Push:
; --------------------------------------------------------------------------
; Check that we have space on the stack.
; --------------------------------------------------------------------------
ld a,(SubSectorStack.EntriesFree)
or a
ret z
dec a
ld (SubSectorStack.EntriesFree),a
; --------------------------------------------------------------------------
; Move the stack pointer.
; --------------------------------------------------------------------------
ld hl,(SubSectorStack.Current)
ld de,-SubSectorStack.EntrySize
add hl,de
ld (SubSectorStack.Current),hl
; --------------------------------------------------------------------------
; Store the subsector pointer.
; --------------------------------------------------------------------------
push ix
pop de
ld (hl),e
inc hl
ld (hl),d
inc hl
; --------------------------------------------------------------------------
; Store the top edge clipping regions.
; --------------------------------------------------------------------------
ex de,hl
ld hl,TopEdgeClip
ld bc,96
ldir
; --------------------------------------------------------------------------
; Store the bottom edge clipping regions.
; --------------------------------------------------------------------------
ld hl,BottomEdgeClip
ld bc,96
ldir
ret
; ==========================================================================
; Draw
; --------------------------------------------------------------------------
; Draws all things.
; --------------------------------------------------------------------------
; Destroyed: AF, BC, DE, HL, IX.
; ==========================================================================
Draw:
ld a,(SubSectorStack.EntriesFree)
ld b,a
ld a,(SubSectorStack.MaximumCapacity)
sub b
ret z
ld b,a
Draw.Loop:
push bc
; --------------------------------------------------------------------------
; Fetch (and advance for the next loop) the stack pointer.
; --------------------------------------------------------------------------
ld hl,(SubSectorStack.Current)
push hl
ld de,SubSectorStack.EntrySize
add hl,de
ld (SubSectorStack.Current),hl
pop hl
; --------------------------------------------------------------------------
; Retrieve the pointer to the subsector to draw.
; --------------------------------------------------------------------------
ld e,(hl)
inc hl
ld d,(hl)
inc hl
ld (DrawingSubSector),de
; --------------------------------------------------------------------------
; Restore the upper clipping region.
; --------------------------------------------------------------------------
ld de,TopEdgeClip
ld bc,96
ldir
; --------------------------------------------------------------------------
; Restore the lower clipping region.
; --------------------------------------------------------------------------
ld de,BottomEdgeClip
ld bc,96
ldir
; --------------------------------------------------------------------------
; We have not yet added anything to the sorted sprite buffer.
; --------------------------------------------------------------------------
xor a
ld (SortedSpriteBuffer.Count),a
; --------------------------------------------------------------------------
; Find the things to draw in turn.
; --------------------------------------------------------------------------
ld hl,(DrawingSubSector)
inc hl
ld l,(hl)
; --------------------------------------------------------------------------
; We have the index of the thing to draw in L.
; --------------------------------------------------------------------------
SortNextThing:
ld h,0
add hl,hl
add hl,hl
add hl,hl
ld de,(Level.Things)
add hl,de
; --------------------------------------------------------------------------
; Fetch the pointer to the next thing.
; --------------------------------------------------------------------------
ld a,(hl)
ld (NextThing.Index),a
inc hl
; --------------------------------------------------------------------------
; Look up the thing's type.
; --------------------------------------------------------------------------
push hl
ld l,(hl)
ld h,0
add hl,hl
ld de,Thing.Types
add hl,de
ld e,(hl)
inc hl
ld d,(hl)
ld (Appearance.Offset),de
pop hl
inc hl
; --------------------------------------------------------------------------
; Skip over the two reserved bytes.
; --------------------------------------------------------------------------
inc hl
inc hl
; --------------------------------------------------------------------------
; Get the coordinates of the thing.
; --------------------------------------------------------------------------
ld c,(hl) \ inc hl
ld b,(hl) \ inc hl
ld e,(hl) \ inc hl
ld d,(hl)
; --------------------------------------------------------------------------
; Transform it.
; --------------------------------------------------------------------------
call Vertices.Transform
; --------------------------------------------------------------------------
; Is it behind the camera?
; --------------------------------------------------------------------------
ld a,d
or a
jp m,Buffer.Skip
; --------------------------------------------------------------------------
; Store the transformed position.
; --------------------------------------------------------------------------
ld (Transformed.X),bc
ld (Transformed.Y),de
; --------------------------------------------------------------------------
; Fudge the distance factor to allow the centre of the sprite object to
; appear beyond the left or right edge of the display rather than vanish
; when there's still half of it to display.
; --------------------------------------------------------------------------
inc d
; --------------------------------------------------------------------------
; Is it outside Y=+X?
; --------------------------------------------------------------------------
ld l,c
ld a,b \ xor $80 \ ld h,a
ld a,d \ xor $80 \ ld d,a
or a
sbc hl,de
jp nc,Buffer.Skip
; --------------------------------------------------------------------------
; Is it outside Y=-X?
; --------------------------------------------------------------------------
add hl,de
neg_de()
or a
sbc hl,de
jp c,Buffer.Skip
; --------------------------------------------------------------------------
; Now we have the thing to draw, we need to add it to our sorting buffer.
; --------------------------------------------------------------------------
ld de,SortedSpriteBuffer
ld a,(SortedSpriteBuffer.Count)
or a
jr z,SortedSpriteBuffer.Add
; --------------------------------------------------------------------------
; We need to find somewhere to add the sprite.
; --------------------------------------------------------------------------
ld b,a
FindInsertionPoint:
ex de,hl
ld e,(hl)
inc hl
ld d,(hl)
dec hl
ex de,hl
push bc
ld bc,(Transformed.Y)
or a
sbc hl,bc
pop bc
jr nc,IsCloser
; --------------------------------------------------------------------------
; The sprite is further from the camera than the one at (DE).
; --------------------------------------------------------------------------
IsFurther:
push de
ld l,b
ld h,0
add hl,hl
add hl,hl
add hl,hl
ld b,h \ ld c,l
; BC = number of bytes to move.
ld a,(SortedSpriteBuffer.Count)
ld l,a
ld h,0
add hl,hl
add hl,hl
add hl,hl
ld de,SortedSpriteBuffer-1
add hl,de
; HL->Current end of buffer.
push hl
ld de,8
add hl,de
ex de,hl
pop hl
; DE->End of buffer + 8
lddr
pop de
jr SortedSpriteBuffer.Add
IsCloser:
ld hl,8
add hl,de
ex de,hl
djnz FindInsertionPoint
; --------------------------------------------------------------------------
; Add the sorted sprite to the buffer.
; --------------------------------------------------------------------------
SortedSpriteBuffer.Add:
push bc
ld hl,Transformed.Y
ldi \ ldi ; Y
ldi \ ldi ; X
ld hl,Appearance.Offset
ldi \ ldi
ldi \ ldi ; (Dummy)
pop bc
; --------------------------------------------------------------------------
; We have one more item in the sprite buffer.
; --------------------------------------------------------------------------
ld a,(SortedSpriteBuffer.Count)
inc a
ld (SortedSpriteBuffer.Count),a
; --------------------------------------------------------------------------
; Do we have any more things to sort?
; --------------------------------------------------------------------------
Buffer.Skip:
ld a,(NextThing.Index)
or a
jr z,+
ld l,a
jp SortNextThing
+:
; --------------------------------------------------------------------------
; We now have a buffer full of sorted sprites. Draw them!
; --------------------------------------------------------------------------
ld a,(SortedSpriteBuffer.Count)
or a
jp z,AdvanceToNextSubsector
ld b,a
ld hl,SortedSpriteBuffer
DrawSortedSprite.Loop:
push bc
ld de,Transformed.Y
ldi \ ldi ; Y
ldi \ ldi ; X
ld de,Appearance.Offset
ldi \ ldi
inc hl \ inc hl
push hl
; --------------------------------------------------------------------------
; Get the sprite appearance information.
; --------------------------------------------------------------------------
ld hl,(Appearance.Offset)
ld de,Appearance
ld bc,Appearance.Size
ldir
ld (Sprite.Data),hl
; --------------------------------------------------------------------------
; Project to X.
; --------------------------------------------------------------------------
; 48 * X / Y
ld hl,(Transformed.X)
call Maths.Mul.S48
ld b,h \ ld c,l
ld de,(Transformed.Y)
call Maths.Div.S24S16
; Offset by the centre of the screen.
ld a,c
add a,48
ld (Projected.X),a
; --------------------------------------------------------------------------
; Project to Y.
; --------------------------------------------------------------------------
ld hl,(DrawingSubSector)
ld l,(hl)
ld h,0
.if Sector.DataSize != 4
.echoln "Sectors are no longer 4 bytes (fix this)"
.endif
add hl,hl
add hl,hl
ld de,(Level.Sectors)
add hl,de
ld e,(hl)
inc hl
ld d,(hl)
ld hl,(Render.Camera.Z)
add hl,de
ld de,(Transformed.Y)
call Maths.Div.S16S16
call Wall.Clip24To16
ld hl,(Render.Camera.YShear)
or a
sbc hl,bc
ld (Sprite.Column.Bottom),hl
call Wall.Clip16ToRowPlusOne
inc a
ld (Sprite.Column.Bottom.Clipped),a
; --------------------------------------------------------------------------
; Calculate the height and therefore top.
; --------------------------------------------------------------------------
ld hl,(Appearance.WorldHeight)
call Maths.Div.S16S16
call Wall.Clip24To16
ld a,b
or a
jp nz,Draw.Skip
ld a,c
or a
jp m,Draw.Skip
jp z,Draw.Skip
ld (Projected.Height),a
or a
jp z,Draw.Skip
ld hl,(Sprite.Column.Bottom)
sbc hl,bc
ld (Sprite.Column.Top),hl
call Wall.Clip16ToRowPlusOne
inc a
ld (Sprite.Column.Top.Clipped),a
; --------------------------------------------------------------------------
; Calculate the width.
; --------------------------------------------------------------------------
ld hl,(Appearance.WorldWidth)
ld de,(Transformed.Y)
call Maths.Div.S16S16
call Wall.Clip24To16
ld a,b
or a
jp nz,Draw.Skip
ld a,c
or a
jp m,Draw.Skip
jp z,Draw.Skip
ld (Projected.Width),a
; --------------------------------------------------------------------------
; Copy the width and height values over.
; --------------------------------------------------------------------------
ld a,(Projected.Height)
ld (Sprite.Column.DestinationHeight),a
ld a,(Appearance.SpriteHeight)
ld (Sprite.Column.SourceHeight),a
ld a,(Projected.Width)
ld (Delta.DestinationWidth),a
ld a,(Appearance.SpriteWidth)
ld (Delta.SourceWidth),a
ld a,(Delta.DestinationWidth)
ld (ColumnError),a
; --------------------------------------------------------------------------
; Draw the thing.
; --------------------------------------------------------------------------
ld a,(Projected.X)
ld l,a
ld a,(Projected.Width)
ld h,a
srl a
neg
add a,l
ld l,a
; --------------------------------------------------------------------------
; Initialise the per-row source offset.
; --------------------------------------------------------------------------
ld de,(Sprite.Data)
ld (Sprite.Column.SourceData),de
; --------------------------------------------------------------------------
; Draw a column.
; --------------------------------------------------------------------------
ColumnLoop:
push hl
call Sprite.DrawColumn
SkipColumn:
; --------------------------------------------------------------------------
; Advance to the next column if required.
; --------------------------------------------------------------------------
ColumnError = $+1
ld a,0
Delta.DestinationWidth = $+1
Delta.SourceWidth = $+2
ld de,0
sub d
jp p,NoAdvanceColumn
ld hl,(Sprite.Column.SourceData)
ld bc,(Appearance.ColumnStride)
-: add hl,bc
add a,e
jp m,-
ld (Sprite.Column.SourceData),hl
NoAdvanceColumn:
ld (ColumnError),a
pop hl
inc l
dec h
jp nz,ColumnLoop
Draw.Skip:
pop hl
pop bc
djnz +
jr AdvanceToNextSubsector
+: jp DrawSortedSprite.Loop
AdvanceToNextSubsector:
pop bc
djnz +
ret
+: jp Draw.Loop
; ==========================================================================
; GetPointerFromIndex
; --------------------------------------------------------------------------
; Gets a pointer to the thing's data by its index.
; --------------------------------------------------------------------------
; Inputs: A: Thing index.
; Outputs: HL: Pointer to the thing's data.
; Destroyed: F, DE.
; ==========================================================================
GetPointerFromIndex:
ld l,a
ld h,0
add hl,hl
add hl,hl
add hl,hl
ld de,(Level.Things)
add hl,de
ret
; ==========================================================================
; SetPosition
; --------------------------------------------------------------------------
; Sets a thing's position.
; --------------------------------------------------------------------------
; Inputs: A: Thing index.
; HL: X coordinate of the thing's position.
; DE: Y coordinate of the thing's position.
; Destroyed: AF, BC, DE, HL, IX.
; ==========================================================================
SetPosition:
; --------------------------------------------------------------------------
; Store the index and destination position for later use.
; --------------------------------------------------------------------------
ld (Move.Index),a
ld (Move.X),hl
ld (Move.Y),de
; --------------------------------------------------------------------------
; Get the pointer to the thing to move.
; --------------------------------------------------------------------------
call GetPointerFromIndex
ld (Move.Pointer),hl
; --------------------------------------------------------------------------
; Get the current thing position.
; --------------------------------------------------------------------------
ld de,4
add hl,de
ld c,(hl) \ inc hl
ld b,(hl) \ inc hl
ld e,(hl) \ inc hl
ld d,(hl)
ld l,c \ ld h,b
; --------------------------------------------------------------------------
; Walk the BSP tree to determine which leaf the thing is currently in.
; --------------------------------------------------------------------------
call SetPosition.FindLeaf
ld (Move.SourceLeaf),ix
; --------------------------------------------------------------------------
; Walk the BSP tree to determine which leaf the thing is moving to.
; --------------------------------------------------------------------------
ld hl,(Move.X)
ld de,(Move.Y)
call SetPosition.FindLeaf
ld (Move.DestinationLeaf),ix
; --------------------------------------------------------------------------
; Have we moved from one leaf to another?
; --------------------------------------------------------------------------
ld hl,(Move.DestinationLeaf)
ld de,(Move.SourceLeaf)
or a
sbc hl,de
jr z,SetPosition.SkipMoveLeaf
; --------------------------------------------------------------------------
; Remove the thing from the old leaf.
; --------------------------------------------------------------------------
ex de,hl
inc hl ; Node type.
inc hl ; Sector index.
-: ld a,(Move.Index)
cp (hl)
jr z,SetPosition.FoundOldLeafIndex
ld a,(hl)
call GetPointerFromIndex
jr -
SetPosition.FoundOldLeafIndex:
; --------------------------------------------------------------------------
; HL points to the index of the thing in the current subsector.
; Replace this index with the index of the *next* thing.
; --------------------------------------------------------------------------
push hl
ld a,(hl)
call GetPointerFromIndex
ld a,(hl)
pop hl
ld (hl),a
; --------------------------------------------------------------------------
; Insert the thing to the head of the list in the new leaf.
; --------------------------------------------------------------------------
ld hl,(Move.DestinationLeaf)
inc hl ; Node type.
inc hl ; Sector index.
ld a,(hl)
push af
ld a,(Move.Index)
ld (hl),a
pop af
ld hl,(Move.Pointer)
ld (hl),a
jr SetPosition.ChangedLeaf
SetPosition.SkipMoveLeaf:
; --------------------------------------------------------------------------
; We didn't move the thing to a new leaf.
; --------------------------------------------------------------------------
ld hl,(Move.Pointer)
SetPosition.ChangedLeaf:
ld de,4
add hl,de
; --------------------------------------------------------------------------
; Write the new position to the thing.
; --------------------------------------------------------------------------
ld de,(Move.X)
ld (hl),e \ inc hl
ld (hl),d \ inc hl
ld de,(Move.Y)
ld (hl),e \ inc hl
ld (hl),d
ret
SetPosition.FindLeaf:
ld bc,SetPosition.FindLeafFunction
ld (SetPosition.FindLeafFunction.SP),sp
ld ix,(Level.Tree)
jp Tree.Walk
SetPosition.FindLeafFunction:
SetPosition.FindLeafFunction.SP = $+1
ld sp,0
ret
.if Options.ReportModuleSizes \ .echoln strformat("Things module: {0:N0} bytes.", $-Code) \ .endif
.endmodule |
macro MainHash_Save lcopy, entr, key16, vvalue, bbounder, ddepth, mmove, eev
local dont_write_move, write_everything, write_after_move, done
;ProfileInc MainHash_Save
if vvalue eq edx
else if vvalue eq 0
xor edx, edx
else
err 'val argument of HashTable_Save is not edx or 0'
end if
if mmove eq eax
else if mmove eq 0
xor eax, eax
else
err 'move argument of HashTable_Save is not eax or 0'
end if
mov rcx, qword[entr]
mov qword[lcopy], rcx
mov rcx, entr
shr ecx, 3 - 1
and ecx, 3 shl 1
Assert b, ecx, 3 shl 1, 'index 3 in cluster encountered'
neg rcx
lea rcx, [8*3+3*rcx]
add rcx, entr
cmp key16, word[rcx]
jne write_everything
if mmove eq 0
if bbounder eq BOUND_EXACT
jmp write_after_move
else
end if
else
test eax, eax
if bbounder eq BOUND_EXACT
jz write_after_move
else
jz dont_write_move
end if
mov word[lcopy+MainHashEntry.move], ax
end if
dont_write_move:
if bbounder eq BOUND_EXACT
jmp write_after_move
else
mov al, bbounder
cmp al, BOUND_EXACT
je write_after_move
movsx eax, byte[lcopy+MainHashEntry.depth]
sub eax, 4
cmp al, ddepth
jl write_after_move
jmp done
end if
write_everything:
mov word[lcopy+MainHashEntry.move], ax
mov word[rcx], key16
write_after_move:
mov al, byte[mainHash.date]
or al, bbounder
mov byte[lcopy+MainHashEntry.genBound], al
mov al, ddepth
mov byte[lcopy+MainHashEntry.depth], al
match size[addr], eev
movsx eax, eev
mov word[lcopy+MainHashEntry.eval_], ax
else
if eev relativeto 0
mov word[lcopy+MainHashEntry.eval_], eev
else
movsx eax, eev
mov word[lcopy+MainHashEntry.eval_], ax
end if
end match
mov word[lcopy+MainHashEntry.value_], dx
done:
mov rax, qword[lcopy]
mov qword[entr], rax
end macro
|
;=======================================
;
; MSU-1 Enhanced Audio Patch
; Zelda no Densetsu - Kamigami no Triforce
; Modified for VT Randomizer
;
; Author: qwertymodo
;
; Free space used: 0x77DDD-0x77F8A
;
;=======================================
!REG_MSU_STATUS = $2000
!REG_MSU_ID_0 = $2002
!REG_MSU_ID_1 = $2003
!REG_MSU_ID_2 = $2004
!REG_MSU_ID_3 = $2005
!REG_MSU_ID_4 = $2006
!REG_MSU_ID_5 = $2007
!REG_MSU_ID_01 = $2002
!REG_MSU_ID_23 = $2004
!REG_MSU_ID_45 = $2006
!VAL_MSU_ID_0 = #$53 ; 'S'
!VAL_MSU_ID_1 = #$2D ; '-'
!VAL_MSU_ID_2 = #$4D ; 'M'
!VAL_MSU_ID_3 = #$53 ; 'S'
!VAL_MSU_ID_4 = #$55 ; 'U'
!VAL_MSU_ID_5 = #$31 ; '1'
!VAL_MSU_ID_01 = #$2D53 ; 'S-'
!VAL_MSU_ID_23 = #$534D ; 'MS'
!VAL_MSU_ID_45 = #$3155 ; 'U1'
!REG_MSU_TRACK = $2004
!REG_MSU_TRACK_LO = $2004
!REG_MSU_TRACK_HI = $2005
!REG_MSU_VOLUME = $2006
!REG_MSU_CONTROL = $2007
!FLAG_MSU_PLAY = #$01
!FLAG_MSU_REPEAT = #$02
!FLAG_MSU_STATUS_TRACK_MISSING = #$08
!FLAG_MSU_STATUS_AUDIO_PLAYING = #$10
!FLAG_MSU_STATUS_AUDIO_REPEATING = #$20
!FLAG_MSU_STATUS_AUDIO_BUSY = #$40
!FLAG_MSU_STATUS_DATA_BUSY = #$80
!REG_CURRENT_VOLUME = $0127
!REG_TARGET_VOLUME = $0129
!REG_CURRENT_MSU_TRACK = $012B
!REG_MUSIC_CONTROL = $012C
!REG_CURRENT_TRACK = $0130
!REG_CURRENT_COMMAND = $0133
!REG_MSU_LOAD_FLAG = $7F509B
!REG_SPC_CONTROL = $2140
!REG_NMI_FLAGS = $4210
!VAL_COMMAND_FADE_OUT = #$F1
!VAL_COMMAND_FADE_HALF = #$F2
!VAL_COMMAND_FULL_VOLUME = #$F3
!VAL_COMMAND_LOAD_NEW_BANK = #$FF
!VAL_VOLUME_INCREMENT = #$10
!VAL_VOLUME_DECREMENT = #$02
!VAL_VOLUME_HALF = #$80
!VAL_VOLUME_FULL = #$FF
msu_main:
SEP #$20 ; set 8-BIT accumulator
LDA $4210 ; thing we wrote over
REP #$20 ; set 16-BIT accumulator
LDA !REG_MSU_ID_01 : CMP !VAL_MSU_ID_01 : BEQ .continue
.nomsu
SEP #$30
JML spc_continue
.continue
LDA !REG_MSU_ID_23 : CMP !VAL_MSU_ID_23 : BNE .nomsu
LDA !REG_MSU_ID_45 : CMP !VAL_MSU_ID_45 : BNE .nomsu
SEP #$30
LDX !REG_MUSIC_CONTROL : BNE command_ff
LDA !REG_MSU_LOAD_FLAG : BEQ do_fade
msu_check_busy:
LDA !REG_MSU_STATUS : BIT !FLAG_MSU_STATUS_AUDIO_BUSY : BEQ .ready
JML spc_continue
.ready
LDA !REG_MSU_STATUS : BIT !FLAG_MSU_STATUS_TRACK_MISSING : BNE spc_fallback
LDA !VAL_VOLUME_FULL
STA !REG_TARGET_VOLUME
STA !REG_CURRENT_VOLUME
STA !REG_MSU_VOLUME
LDA !REG_MSU_LOAD_FLAG
STA !REG_MSU_CONTROL
LDA #$00
STA !REG_MSU_LOAD_FLAG
JML spc_continue
spc_fallback:
STZ !REG_MSU_CONTROL
STZ !REG_CURRENT_MSU_TRACK
STZ !REG_TARGET_VOLUME
STZ !REG_CURRENT_VOLUME
STZ !REG_MSU_VOLUME
JML spc_continue
do_fade:
LDA !REG_CURRENT_VOLUME : CMP !REG_TARGET_VOLUME : BNE .continue
JML spc_continue
.continue
BCC .increment
.decrement
SBC !VAL_VOLUME_DECREMENT : BCS .set
.mute
STZ !REG_CURRENT_VOLUME
STZ !REG_MSU_CONTROL
BRA .set
.increment
ADC !VAL_VOLUME_INCREMENT : BCC .set
LDA !VAL_VOLUME_FULL
.set
STA !REG_CURRENT_VOLUME
STA !REG_MSU_VOLUME
JML spc_continue
command_ff:
CPX !VAL_COMMAND_LOAD_NEW_BANK : BNE command_f3
JML spc_continue
command_f3:
CPX !VAL_COMMAND_FULL_VOLUME : BNE command_f2
STX !REG_SPC_CONTROL
LDA !VAL_VOLUME_FULL
STA !REG_TARGET_VOLUME
JML spc_continue
command_f2:
CPX !VAL_COMMAND_FADE_HALF : BNE command_f1
STX !REG_SPC_CONTROL
LDA !VAL_VOLUME_HALF
STA !REG_TARGET_VOLUME
JML spc_continue
command_f1:
CPX !VAL_COMMAND_FADE_OUT : BNE load_track
STX !REG_SPC_CONTROL
STZ !REG_TARGET_VOLUME
STZ !REG_CURRENT_MSU_TRACK
JML spc_continue
load_track:
CPX !REG_CURRENT_MSU_TRACK : BNE .continue
CPX #$1B : BEQ .continue
JML spc_continue
.continue
STX !REG_MSU_TRACK_LO
STZ !REG_MSU_TRACK_HI
STZ !REG_MSU_CONTROL
LDA.l MSUTrackList,x
STA !REG_MSU_LOAD_FLAG
STX !REG_CURRENT_MSU_TRACK
JML spc_continue
pendant_fanfare:
LDA TournamentSeed : BNE .spc
REP #$20
LDA !REG_MSU_ID_01 : CMP !VAL_MSU_ID_01 : BNE .spc
LDA !REG_MSU_ID_23 : CMP !VAL_MSU_ID_23 : BNE .spc
LDA !REG_MSU_ID_45 : CMP !VAL_MSU_ID_45 : BNE .spc
SEP #$20
LDA !REG_MSU_STATUS : BIT !FLAG_MSU_STATUS_TRACK_MISSING : BNE .spc
LDA !REG_MSU_LOAD_FLAG : BNE .continue
LDA !REG_MSU_STATUS : BIT !FLAG_MSU_STATUS_AUDIO_PLAYING : BEQ .done
.continue
jml pendant_continue
.spc
SEP #$20
LDA !REG_SPC_CONTROL : BNE .continue
.done
jml pendant_done
crystal_fanfare:
LDA TournamentSeed : BNE .spc
REP #$20
LDA !REG_MSU_ID_01 : CMP !VAL_MSU_ID_01 : BNE .spc
LDA !REG_MSU_ID_23 : CMP !VAL_MSU_ID_23 : BNE .spc
LDA !REG_MSU_ID_45 : CMP !VAL_MSU_ID_45 : BNE .spc
SEP #$20
LDA !REG_MSU_STATUS : BIT !FLAG_MSU_STATUS_TRACK_MISSING : BNE .spc
LDA !REG_MSU_LOAD_FLAG : BNE .continue
LDA !REG_MSU_STATUS : BIT !FLAG_MSU_STATUS_AUDIO_PLAYING : BEQ .done
.continue
jml crystal_continue
.spc
SEP #$20
LDA !REG_SPC_CONTROL : BNE .continue
.done
jml crystal_done
ending_wait:
REP #$20
LDA !REG_MSU_ID_01 : CMP !VAL_MSU_ID_01 : BNE .done
LDA !REG_MSU_ID_23 : CMP !VAL_MSU_ID_23 : BNE .done
LDA !REG_MSU_ID_45 : CMP !VAL_MSU_ID_45 : BNE .done
SEP #$20
.wait
LDA !REG_MSU_STATUS : BIT !FLAG_MSU_STATUS_AUDIO_PLAYING : BNE .wait
.done
SEP #$20
LDA #$22
RTL
|
; A226695: Pell equation solutions (32*b(n))^2 - 41*(5*a(n))^2 = -1 with b(n) := A226694(n), n>=0.
; Submitted by Christian Krause
; 1,4097,16789505,68803387393,281956264747009,1155456704129855489,4735061291567883046913,19404280017388480596393985,79518734776196701916139503617,325867755708574067063859089428481,1335405983375001750630992632338411521
mov $3,1
lpb $0
sub $0,$3
mov $1,$4
mul $1,4096
add $2,1
add $2,$1
add $4,$2
lpe
mov $0,$4
mul $0,4096
add $0,1
|
#ifndef BLOCK_ZERO_BREAKABLE_HPP
#define BLOCK_ZERO_BREAKABLE_HPP
#include <swapShop/SwapEntity.hpp>
class BlockZeroBreakable : public SwapEntity
{
public:
BlockZeroBreakable(const sf::Texture& texture);
private:
virtual void updateCurrent(sf::Time dt, Context context);
virtual void handleEventCurrent(const sf::Event& event, Context context);
virtual void drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const;
};
#endif
|
; A163301: a(n) = Sum_{x=n-th even nonprime..n-th odd nonprime} -x*(-1)^x.
; Submitted by Jamie Morken(s1)
; 1,3,5,7,8,8,10,10,11,13,14,14,15,15,17,17,18,20,20,21,22,22,23,23,23,24,26,28,29,29,29,29,29,29,30,31,31,33,33,33,33,35,35,36,36,37,38,38,39,39,41,41,41,41,43,45,45,45,45,45,46,46,46,46,46,47,49,50,50,52,52
add $0,1
mov $1,$0
lpb $1
mov $2,$0
mov $4,$1
lpb $2
sub $0,2
dif $2,$4
mov $5,$0
mov $0,1
max $5,0
seq $5,326586 ; Odd numbers which do not satisfy Korselt's criterion, complement of A324050.
lpe
cmp $3,0
add $5,$3
div $1,$5
lpe
mov $0,$5
sub $0,1
div $0,2
sub $0,$4
add $0,1
|
; A001077: Numerators of continued fraction convergents to sqrt(5).
; Submitted by Jon Maiga
; 1,2,9,38,161,682,2889,12238,51841,219602,930249,3940598,16692641,70711162,299537289,1268860318,5374978561,22768774562,96450076809,408569081798,1730726404001,7331474697802,31056625195209,131557975478638,557288527109761,2360712083917682,10000136862780489,42361259535039638,179445175002939041,760141959546795802,3220013013190122249,13640194012307284798,57780789062419261441,244763350261984330562,1036834190110356583689,4392100110703410665318,18605234632923999244961,78813038642399407645162
mov $3,1
lpb $0
sub $0,1
add $2,$3
mov $3,$1
mov $1,$2
mul $2,2
add $3,$2
lpe
mov $0,$3
|
--- FUNCTION SOURCE (SetFunctionName) id{0,0} ---
(g,h,i){
if((typeof(h)==='symbol')){
h="["+%SymbolDescription(h)+"]";
}
if((i===(void 0))){
%FunctionSetName(g,h);
}else{
%FunctionSetName(g,i+" "+h);
}
}
--- END ---
--- FUNCTION SOURCE (ToName) id{1,0} ---
(i){
return(typeof(i)==='symbol')?i:ToString(i);
}
--- END ---
--- FUNCTION SOURCE (join) id{2,0} ---
(C){
if((this==null)&&!(%_IsUndetectableObject(this)))throw MakeTypeError(14,"Array.prototype.join");
var o=((%_IsSpecObject(%IS_VAR(this)))?this:$toObject(this));
var v=(o.length>>>0);
return InnerArrayJoin(C,o,v);
}
--- END ---
--- FUNCTION SOURCE (DoRegExpExec) id{3,0} ---
(j,k,l){
var m=%_RegExpExec(j,k,l,e);
if(m!==null)$regexpLastMatchInfoOverride=null;
return m;
}
--- END ---
--- FUNCTION SOURCE (PropertyDescriptor_HasValue) id{4,0} ---
(){
return this.hasValue_;
}
--- END ---
--- FUNCTION SOURCE (posix._makeLong) id{5,0} ---
(path) {
return path;
}
--- END ---
--- FUNCTION SOURCE (PropertyDescriptor_HasGetter) id{6,0} ---
(){
return this.hasGetter_;
}
--- END ---
--- FUNCTION SOURCE (IsAccessorDescriptor) id{7,0} ---
(G){
if((G===(void 0)))return false;
return G.hasGetter()||G.hasSetter();
}
--- END ---
--- FUNCTION SOURCE (IsDataDescriptor) id{8,0} ---
(G){
if((G===(void 0)))return false;
return G.hasValue()||G.hasWritable();
}
--- END ---
--- FUNCTION SOURCE (PropertyDescriptor_HasEnumerable) id{9,0} ---
(){
return this.hasEnumerable_;
}
--- END ---
--- FUNCTION SOURCE (PropertyDescriptor_HasConfigurable) id{10,0} ---
(){
return this.hasConfigurable_;
}
--- END ---
--- FUNCTION SOURCE (PropertyDescriptor_HasSetter) id{11,0} ---
(){
return this.hasSetter_;
}
--- END ---
--- FUNCTION SOURCE (GifReaderLZWOutputIndexStream) id{12,0} ---
(code_stream, p, output, output_length) {
var min_code_size = code_stream[p++];
var clear_code = 1 << min_code_size;
var eoi_code = clear_code + 1;
var next_code = eoi_code + 1;
var cur_code_size = min_code_size + 1; // Number of bits per code.
// NOTE: This shares the same name as the encoder, but has a different
// meaning here. Here this masks each code coming from the code stream.
var code_mask = (1 << cur_code_size) - 1;
var cur_shift = 0;
var cur = 0;
var op = 0; // Output pointer.
var subblock_size = code_stream[p++];
// TODO(deanm): Would using a TypedArray be any faster? At least it would
// solve the fast mode / backing store uncertainty.
// var code_table = Array(4096);
var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.
var prev_code = null; // Track code-1.
while (true) {
// Read up to two bytes, making sure we always 12-bits for max sized code.
while (cur_shift < 16) {
if (subblock_size === 0) break; // No more data to be read.
cur |= code_stream[p++] << cur_shift;
cur_shift += 8;
if (subblock_size === 1) { // Never let it get to 0 to hold logic above.
subblock_size = code_stream[p++]; // Next subblock.
} else {
--subblock_size;
}
}
// TODO(deanm): We should never really get here, we should have received
// and EOI.
if (cur_shift < cur_code_size)
break;
var code = cur & code_mask;
cur >>= cur_code_size;
cur_shift -= cur_code_size;
// TODO(deanm): Maybe should check that the first code was a clear code,
// at least this is what you're supposed to do. But actually our encoder
// now doesn't emit a clear code first anyway.
if (code === clear_code) {
// We don't actually have to clear the table. This could be a good idea
// for greater error checking, but we don't really do any anyway. We
// will just track it with next_code and overwrite old entries.
next_code = eoi_code + 1;
cur_code_size = min_code_size + 1;
code_mask = (1 << cur_code_size) - 1;
// Don't update prev_code ?
prev_code = null;
continue;
} else if (code === eoi_code) {
break;
}
// We have a similar situation as the decoder, where we want to store
// variable length entries (code table entries), but we want to do in a
// faster manner than an array of arrays. The code below stores sort of a
// linked list within the code table, and then "chases" through it to
// construct the dictionary entries. When a new entry is created, just the
// last byte is stored, and the rest (prefix) of the entry is only
// referenced by its table entry. Then the code chases through the
// prefixes until it reaches a single byte code. We have to chase twice,
// first to compute the length, and then to actually copy the data to the
// output (backwards, since we know the length). The alternative would be
// storing something in an intermediate stack, but that doesn't make any
// more sense. I implemented an approach where it also stored the length
// in the code table, although it's a bit tricky because you run out of
// bits (12 + 12 + 8), but I didn't measure much improvements (the table
// entries are generally not the long). Even when I created benchmarks for
// very long table entries the complexity did not seem worth it.
// The code table stores the prefix entry in 12 bits and then the suffix
// byte in 8 bits, so each entry is 20 bits.
var chase_code = code < next_code ? code : prev_code;
// Chase what we will output, either {CODE} or {CODE-1}.
var chase_length = 0;
var chase = chase_code;
while (chase > clear_code) {
chase = code_table[chase] >> 8;
++chase_length;
}
var k = chase;
var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
if (op_end > output_length) {
console.log("Warning, gif stream longer than expected.");
return;
}
// Already have the first byte from the chase, might as well write it fast.
output[op++] = k;
op += chase_length;
var b = op; // Track pointer, writing backwards.
if (chase_code !== code) // The case of emitting {CODE-1} + k.
output[op++] = k;
chase = chase_code;
while (chase_length--) {
chase = code_table[chase];
output[--b] = chase & 0xff; // Write backwards.
chase >>= 8; // Pull down to the prefix code.
}
if (prev_code !== null && next_code < 4096) {
code_table[next_code++] = prev_code << 8 | k;
// TODO(deanm): Figure out this clearing vs code growth logic better. I
// have an feeling that it should just happen somewhere else, for now it
// is awkward between when we grow past the max and then hit a clear code.
// For now just check if we hit the max 12-bits (then a clear code should
// follow, also of course encoded in 12-bits).
if (next_code >= code_mask+1 && cur_code_size < 12) {
++cur_code_size;
code_mask = code_mask << 1 | 1;
}
}
prev_code = code;
}
if (op !== output_length) {
console.log("Warning, gif stream shorter than expected.");
}
return output;
}
--- END ---
[deoptimizing (DEOPT soft): begin 0x7bbfe0a7e29 <JS Function GifReaderLZWOutputIndexStream (SharedFunctionInfo 0x2ac9639f3819)> (opt #12) @53, FP to SP delta: 512]
;;; deoptimize at 0_5213: Insufficient type feedback for combined type of binary operation
reading input frame GifReaderLZWOutputIndexStream => node=5, args=290, height=20; inputs:
0: 0x7bbfe0a7e29 ; (frame function) 0x7bbfe0a7e29 <JS Function GifReaderLZWOutputIndexStream (SharedFunctionInfo 0x2ac9639f3819)>
1: 0x36cdc0e04131 ; [fp - 288] 0x36cdc0e04131 <undefined>
2: 0x7bbfe006401 ; [fp - 280] 0x7bbfe006401 <an Uint8Array with map 0x3d4eb9d1d389>
3: 91597 ; (int) [fp - 440]
4: 0x7bbfe0bbaf1 ; [fp - 264] 0x7bbfe0bbaf1 <an Uint8Array with map 0x3d4eb9d1d331>
5: 0x57e4000000000 ; [fp - 256] 360000
6: 0x7bbfe0a7cb9 ; [fp - 248] 0x7bbfe0a7cb9 <FixedArray[6]>
7: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
8: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
9: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
10: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
11: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
12: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
13: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
14: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
15: 0x57e4000000000 ; [fp - 408] 360000
16: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
17: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
18: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
19: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
20: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
21: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
22: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
23: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
24: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
25: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
translating frame GifReaderLZWOutputIndexStream => node=290, height=152
0x7ffc654cd668: [top + 216] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd660: [top + 208] <- 0x7bbfe006401 ; 0x7bbfe006401 <an Uint8Array with map 0x3d4eb9d1d389> (input #2)
0x7ffc654cd658: [top + 200] <- 0x165cd00000000 ; 91597 (input #3)
0x7ffc654cd650: [top + 192] <- 0x7bbfe0bbaf1 ; 0x7bbfe0bbaf1 <an Uint8Array with map 0x3d4eb9d1d331> (input #4)
0x7ffc654cd648: [top + 184] <- 0x57e4000000000 ; 360000 (input #5)
0x7ffc654cd640: [top + 176] <- 0x376e6fee7ace ; caller's pc
0x7ffc654cd638: [top + 168] <- 0x7ffc654cd720 ; caller's fp
0x7ffc654cd630: [top + 160] <- 0x7bbfe0a7cb9 ; context 0x7bbfe0a7cb9 <FixedArray[6]> (input #6)
0x7ffc654cd628: [top + 152] <- 0x7bbfe0a7e29 ; function 0x7bbfe0a7e29 <JS Function GifReaderLZWOutputIndexStream (SharedFunctionInfo 0x2ac9639f3819)> (input #0)
0x7ffc654cd620: [top + 144] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #7)
0x7ffc654cd618: [top + 136] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #8)
0x7ffc654cd610: [top + 128] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #9)
0x7ffc654cd608: [top + 120] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #10)
0x7ffc654cd600: [top + 112] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #11)
0x7ffc654cd5f8: [top + 104] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #12)
0x7ffc654cd5f0: [top + 96] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #13)
0x7ffc654cd5e8: [top + 88] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #14)
0x7ffc654cd5e0: [top + 80] <- 0x57e4000000000 ; 360000 (input #15)
0x7ffc654cd5d8: [top + 72] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #16)
0x7ffc654cd5d0: [top + 64] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #17)
0x7ffc654cd5c8: [top + 56] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #18)
0x7ffc654cd5c0: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #19)
0x7ffc654cd5b8: [top + 40] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #20)
0x7ffc654cd5b0: [top + 32] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #21)
0x7ffc654cd5a8: [top + 24] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #22)
0x7ffc654cd5a0: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #23)
0x7ffc654cd598: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #24)
0x7ffc654cd590: [top + 0] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #25)
[deoptimizing (soft): end 0x7bbfe0a7e29 <JS Function GifReaderLZWOutputIndexStream (SharedFunctionInfo 0x2ac9639f3819)> @53 => node=290, pc=0x376e6fee94b2, state=NO_REGISTERS, alignment=no padding, took 0.072 ms]
--- FUNCTION SOURCE (GifReader.decodeAndBlitFrameRGBA) id{13,0} ---
(frame_num, pixels) {
var frame = this.frameInfo(frame_num);
var num_pixels = frame.width * frame.height;
var index_stream = new Uint8Array(num_pixels); // At most 8-bit indices.
GifReaderLZWOutputIndexStream(
buf, frame.data_offset, index_stream, num_pixels);
var palette_offset = frame.palette_offset;
// NOTE(deanm): It seems to be much faster to compare index to 256 than
// to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
// the profile, not sure if it's related to using a Uint8Array.
var trans = frame.transparent_index;
if (trans === null) trans = 256;
// We are possibly just blitting to a portion of the entire frame.
// That is a subrect within the framerect, so the additional pixels
// must be skipped over after we finished a scanline.
var framewidth = frame.width;
var framestride = width - framewidth;
var xleft = framewidth; // Number of subrect pixels left in scanline.
// Output indicies of the top left and bottom right corners of the subrect.
var opbeg = ((frame.y * width) + frame.x) * 4;
var opend = ((frame.y + frame.height) * width + frame.x) * 4;
var op = opbeg;
var scanstride = framestride * 4;
// Use scanstride to skip past the rows when interlacing. This is skipping
// 7 rows for the first two passes, then 3 then 1.
if (frame.interlaced === true) {
scanstride += width * 4 * 7; // Pass 1.
}
var interlaceskip = 8; // Tracking the row interval in the current pass.
for (var i = 0, il = index_stream.length; i < il; ++i) {
var index = index_stream[i];
if (xleft === 0) { // Beginning of new scan line
op += scanstride;
xleft = framewidth;
if (op >= opend) { // Catch the wrap to switch passes when interlacing.
scanstride = framestride * 4 + width * 4 * (interlaceskip-1);
// interlaceskip / 2 * 4 is interlaceskip << 1.
op = opbeg + (framewidth + framestride) * (interlaceskip << 1);
interlaceskip >>= 1;
}
}
if (index === trans) {
op += 4;
} else {
var r = buf[palette_offset + index * 3];
var g = buf[palette_offset + index * 3 + 1];
var b = buf[palette_offset + index * 3 + 2];
pixels[op++] = r;
pixels[op++] = g;
pixels[op++] = b;
pixels[op++] = 255;
}
--xleft;
}
}
--- END ---
--- FUNCTION SOURCE (GifReaderLZWOutputIndexStream) id{14,0} ---
(code_stream, p, output, output_length) {
var min_code_size = code_stream[p++];
var clear_code = 1 << min_code_size;
var eoi_code = clear_code + 1;
var next_code = eoi_code + 1;
var cur_code_size = min_code_size + 1; // Number of bits per code.
// NOTE: This shares the same name as the encoder, but has a different
// meaning here. Here this masks each code coming from the code stream.
var code_mask = (1 << cur_code_size) - 1;
var cur_shift = 0;
var cur = 0;
var op = 0; // Output pointer.
var subblock_size = code_stream[p++];
// TODO(deanm): Would using a TypedArray be any faster? At least it would
// solve the fast mode / backing store uncertainty.
// var code_table = Array(4096);
var code_table = new Int32Array(4096); // Can be signed, we only use 20 bits.
var prev_code = null; // Track code-1.
while (true) {
// Read up to two bytes, making sure we always 12-bits for max sized code.
while (cur_shift < 16) {
if (subblock_size === 0) break; // No more data to be read.
cur |= code_stream[p++] << cur_shift;
cur_shift += 8;
if (subblock_size === 1) { // Never let it get to 0 to hold logic above.
subblock_size = code_stream[p++]; // Next subblock.
} else {
--subblock_size;
}
}
// TODO(deanm): We should never really get here, we should have received
// and EOI.
if (cur_shift < cur_code_size)
break;
var code = cur & code_mask;
cur >>= cur_code_size;
cur_shift -= cur_code_size;
// TODO(deanm): Maybe should check that the first code was a clear code,
// at least this is what you're supposed to do. But actually our encoder
// now doesn't emit a clear code first anyway.
if (code === clear_code) {
// We don't actually have to clear the table. This could be a good idea
// for greater error checking, but we don't really do any anyway. We
// will just track it with next_code and overwrite old entries.
next_code = eoi_code + 1;
cur_code_size = min_code_size + 1;
code_mask = (1 << cur_code_size) - 1;
// Don't update prev_code ?
prev_code = null;
continue;
} else if (code === eoi_code) {
break;
}
// We have a similar situation as the decoder, where we want to store
// variable length entries (code table entries), but we want to do in a
// faster manner than an array of arrays. The code below stores sort of a
// linked list within the code table, and then "chases" through it to
// construct the dictionary entries. When a new entry is created, just the
// last byte is stored, and the rest (prefix) of the entry is only
// referenced by its table entry. Then the code chases through the
// prefixes until it reaches a single byte code. We have to chase twice,
// first to compute the length, and then to actually copy the data to the
// output (backwards, since we know the length). The alternative would be
// storing something in an intermediate stack, but that doesn't make any
// more sense. I implemented an approach where it also stored the length
// in the code table, although it's a bit tricky because you run out of
// bits (12 + 12 + 8), but I didn't measure much improvements (the table
// entries are generally not the long). Even when I created benchmarks for
// very long table entries the complexity did not seem worth it.
// The code table stores the prefix entry in 12 bits and then the suffix
// byte in 8 bits, so each entry is 20 bits.
var chase_code = code < next_code ? code : prev_code;
// Chase what we will output, either {CODE} or {CODE-1}.
var chase_length = 0;
var chase = chase_code;
while (chase > clear_code) {
chase = code_table[chase] >> 8;
++chase_length;
}
var k = chase;
var op_end = op + chase_length + (chase_code !== code ? 1 : 0);
if (op_end > output_length) {
console.log("Warning, gif stream longer than expected.");
return;
}
// Already have the first byte from the chase, might as well write it fast.
output[op++] = k;
op += chase_length;
var b = op; // Track pointer, writing backwards.
if (chase_code !== code) // The case of emitting {CODE-1} + k.
output[op++] = k;
chase = chase_code;
while (chase_length--) {
chase = code_table[chase];
output[--b] = chase & 0xff; // Write backwards.
chase >>= 8; // Pull down to the prefix code.
}
if (prev_code !== null && next_code < 4096) {
code_table[next_code++] = prev_code << 8 | k;
// TODO(deanm): Figure out this clearing vs code growth logic better. I
// have an feeling that it should just happen somewhere else, for now it
// is awkward between when we grow past the max and then hit a clear code.
// For now just check if we hit the max 12-bits (then a clear code should
// follow, also of course encoded in 12-bits).
if (next_code >= code_mask+1 && cur_code_size < 12) {
++cur_code_size;
code_mask = code_mask << 1 | 1;
}
}
prev_code = code;
}
if (op !== output_length) {
console.log("Warning, gif stream shorter than expected.");
}
return output;
}
--- END ---
--- FUNCTION SOURCE (ArrayBuffer) id{15,0} ---
(i){
if(%_IsConstructCall()){
var j=$toPositiveInteger(i,125);
%ArrayBufferInitialize(this,j,false);
}else{
throw MakeTypeError(20,"ArrayBuffer");
}
}
--- END ---
--- FUNCTION SOURCE (slice) id{16,0} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
--- FUNCTION SOURCE () id{17,0} ---
(a, b) {
return (a[0] + a[1] + a[2] + a[3]) - (b[0] + b[1] + b[2] + b[3])
}
--- END ---
--- FUNCTION SOURCE (subarray) id{18,0} ---
(R,S){
if(!(%_ClassOf(this)==='Uint8Array')){
throw MakeTypeError(33,"Uint8Array.subarray",this);
}
var T=(%_IsSmi(%IS_VAR(R))?R:%NumberToInteger($toNumber(R)));
if(!(S===(void 0))){
S=(%_IsSmi(%IS_VAR(S))?S:%NumberToInteger($toNumber(S)));
}
var U=%_TypedArrayGetLength(this);
if(T<0){
T=q(0,U+T);
}else{
T=r(U,T);
}
var V=(S===(void 0))?U:S;
if(V<0){
V=q(0,U+V);
}else{
V=r(V,U);
}
if(V<T){
V=T;
}
var C=V-T;
var W=
%_ArrayBufferViewGetByteOffset(this)+T*1;
return new h(%TypedArrayGetBuffer(this),
W,C);
}
--- END ---
--- FUNCTION SOURCE (Uint8ArrayConstructByArrayBuffer) id{19,0} ---
(v,w,x,y){
if(!(x===(void 0))){
x=
$toPositiveInteger(x,139);
}
if(!(y===(void 0))){
y=$toPositiveInteger(y,139);
}
var z=%_ArrayBufferGetByteLength(w);
var A;
if((x===(void 0))){
A=0;
}else{
A=x;
if(A % 1!==0){
throw MakeRangeError(138,
"start offset","Uint8Array",1);
}
if(A>z){
throw MakeRangeError(140);
}
}
var B;
var C;
if((y===(void 0))){
if(z % 1!==0){
throw MakeRangeError(138,
"byte length","Uint8Array",1);
}
B=z-A;
C=B/1;
}else{
var C=y;
B=C*1;
}
if((A+B>z)
||(C>%_MaxSmi())){
throw MakeRangeError(139);
}
%_TypedArrayInitialize(v,1,w,A,B,true);
}
--- END ---
--- FUNCTION SOURCE (Buffer) id{20,0} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
--- FUNCTION SOURCE (fromString) id{20,1} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{20,1} AS 1 AT <0:247>
--- FUNCTION SOURCE (slice) id{20,2} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{20,2} AS 2 AT <1:382>
--- FUNCTION SOURCE (alignPool) id{20,3} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{20,3} AS 3 AT <1:448>
--- FUNCTION SOURCE (QuickSort) id{21,0} ---
(y,m,aF){
var aM=0;
while(true){
if(aF-m<=10){
aE(y,m,aF);
return;
}
if(aF-m>1000){
aM=aJ(y,m,aF);
}else{
aM=m+((aF-m)>>1);
}
var aO=y[m];
var aP=y[aF-1];
var aQ=y[aM];
var aR=%_CallFunction((void 0),aO,aP,aC);
if(aR>0){
var aH=aO;
aO=aP;
aP=aH;
}
var aS=%_CallFunction((void 0),aO,aQ,aC);
if(aS>=0){
var aH=aO;
aO=aQ;
aQ=aP;
aP=aH;
}else{
var aT=%_CallFunction((void 0),aP,aQ,aC);
if(aT>0){
var aH=aP;
aP=aQ;
aQ=aH;
}
}
y[m]=aO;
y[aF-1]=aQ;
var aU=aP;
var aV=m+1;
var aW=aF-1;
y[aM]=y[aV];
y[aV]=aU;
partition:for(var t=aV+1;t<aW;t++){
var aG=y[t];
var aI=%_CallFunction((void 0),aG,aU,aC);
if(aI<0){
y[t]=y[aV];
y[aV]=aG;
aV++;
}else if(aI>0){
do{
aW--;
if(aW==t)break partition;
var aX=y[aW];
aI=%_CallFunction((void 0),aX,aU,aC);
}while(aI>0);
y[t]=y[aW];
y[aW]=aG;
if(aI<0){
aG=y[t];
y[t]=y[aV];
y[aV]=aG;
aV++;
}
}
}
if(aF-aW<aV-m){
aN(y,aW,aF);
aF=aV;
}else{
aN(y,m,aV);
m=aW;
}
}
}
--- END ---
--- FUNCTION SOURCE (alignPool) id{22,0} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
--- FUNCTION SOURCE (sortPixels) id{23,0} ---
(pixels) {
var split = []
for (var i = 0; i < pixels.length; i += 4) {
split.push(pixels.slice(i, i + 4))
}
var sorted = split.sort(function (a, b) {
return (a[0] + a[1] + a[2] + a[3]) - (b[0] + b[1] + b[2] + b[3])
})
var newbuff = new Buffer(pixels.length)
for (var j = 0; j < sorted.length; j++) {
newbuff[j * 4] = sorted[j][0]
newbuff[j * 4 + 1] = sorted[j][1]
newbuff[j * 4 + 2] = sorted[j][2]
newbuff[j * 4 + 3] = sorted[j][3]
}
return newbuff
}
--- END ---
--- FUNCTION SOURCE (slice) id{23,1} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{23,1} AS 1 AT <0:97>
--- FUNCTION SOURCE (Buffer) id{23,2} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{23,2} AS 2 AT <0:252>
--- FUNCTION SOURCE (fromString) id{23,3} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{23,3} AS 3 AT <2:247>
--- FUNCTION SOURCE (slice) id{23,4} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{23,4} AS 4 AT <3:382>
--- FUNCTION SOURCE (alignPool) id{23,5} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{23,5} AS 5 AT <3:448>
--- FUNCTION SOURCE (min) id{24,0} ---
(h,i){
var j=%_ArgumentsLength();
if(j==2){
h=((typeof(%IS_VAR(h))==='number')?h:$nonNumberToNumber(h));
i=((typeof(%IS_VAR(i))==='number')?i:$nonNumberToNumber(i));
if(i>h)return h;
if(h>i)return i;
if(h==i){
return(h===0&&%_IsMinusZero(h))?h:i;
}
return $NaN;
}
var k=(1/0);
for(var l=0;l<j;l++){
var m=%_Arguments(l);
m=((typeof(%IS_VAR(m))==='number')?m:$nonNumberToNumber(m));
if((!%_IsSmi(%IS_VAR(m))&&!(m==m))||m<k||(k===0&&m===0&&%_IsMinusZero(m))){
k=m;
}
}
return k;
}
--- END ---
--- FUNCTION SOURCE (ToPositiveInteger) id{25,0} ---
(i,aa){
var M=(%_IsSmi(%IS_VAR(i))?i:%NumberToIntegerMapMinusZero($toNumber(i)));
if(M<0)throw MakeRangeError(aa);
return M;
}
--- END ---
--- FUNCTION SOURCE (medianPixel) id{26,0} ---
(pixels) {
var sorted = sortPixels(pixels)
var mid = (sorted.length / 2) - ((sorted.length / 2) % 4)
return sorted.slice(mid, mid + 4)
}
--- END ---
--- FUNCTION SOURCE (sortPixels) id{26,1} ---
(pixels) {
var split = []
for (var i = 0; i < pixels.length; i += 4) {
split.push(pixels.slice(i, i + 4))
}
var sorted = split.sort(function (a, b) {
return (a[0] + a[1] + a[2] + a[3]) - (b[0] + b[1] + b[2] + b[3])
})
var newbuff = new Buffer(pixels.length)
for (var j = 0; j < sorted.length; j++) {
newbuff[j * 4] = sorted[j][0]
newbuff[j * 4 + 1] = sorted[j][1]
newbuff[j * 4 + 2] = sorted[j][2]
newbuff[j * 4 + 3] = sorted[j][3]
}
return newbuff
}
--- END ---
INLINE (sortPixels) id{26,1} AS 1 AT <0:26>
--- FUNCTION SOURCE (slice) id{26,2} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{26,2} AS 2 AT <1:97>
--- FUNCTION SOURCE (Buffer) id{26,3} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{26,3} AS 3 AT <1:252>
--- FUNCTION SOURCE (fromString) id{26,4} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{26,4} AS 4 AT <3:247>
--- FUNCTION SOURCE (slice) id{26,5} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{26,5} AS 5 AT <4:382>
--- FUNCTION SOURCE (alignPool) id{26,6} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{26,6} AS 6 AT <4:448>
--- FUNCTION SOURCE (slice) id{26,7} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{26,7} AS 7 AT <0:121>
--- FUNCTION SOURCE (sort) id{27,0} ---
(aC){
if((this==null)&&!(%_IsUndetectableObject(this)))throw MakeTypeError(14,"Array.prototype.sort");
var o=$toObject(this);
var v=(o.length>>>0);
return %_CallFunction(o,v,aC,InnerArraySort);
}
--- END ---
--- FUNCTION SOURCE (allocate) id{28,0} ---
(size) {
if (size === 0) {
const ui8 = new Uint8Array(size);
Object.setPrototypeOf(ui8, Buffer.prototype);
return ui8;
}
if (size < (Buffer.poolSize >>> 1)) {
if (size > (poolSize - poolOffset))
createPool();
var b = allocPool.slice(poolOffset, poolOffset + size);
poolOffset += size;
alignPool();
return b;
} else {
// Even though this is checked above, the conditional is a safety net and
// sanity check to prevent any subsequent typed array allocation from not
// being zero filled.
if (size > 0)
flags[kNoZeroFill] = 1;
const ui8 = new Uint8Array(size);
Object.setPrototypeOf(ui8, Buffer.prototype);
return ui8;
}
}
--- END ---
--- FUNCTION SOURCE (createPool) id{28,1} ---
() {
poolSize = Buffer.poolSize;
if (poolSize > 0)
flags[kNoZeroFill] = 1;
allocPool = new Uint8Array(poolSize);
Object.setPrototypeOf(allocPool, Buffer.prototype);
poolOffset = 0;
}
--- END ---
INLINE (createPool) id{28,1} AS 1 AT <0:223>
--- FUNCTION SOURCE (slice) id{28,2} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{28,2} AS 2 AT <0:259>
--- FUNCTION SOURCE (alignPool) id{28,3} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{28,3} AS 3 AT <0:325>
--- FUNCTION SOURCE (Uint8ArrayConstructByLength) id{29,0} ---
(v,y){
var D=(y===(void 0))?
0:$toPositiveInteger(y,139);
if(D>%_MaxSmi()){
throw MakeRangeError(139);
}
var E=D*1;
if(E>%_TypedArrayMaxSizeInHeap()){
var w=new d(E);
%_TypedArrayInitialize(v,1,w,0,E,true);
}else{
%_TypedArrayInitialize(v,1,null,0,E,true);
}
}
--- END ---
--- FUNCTION SOURCE (Uint8Array) id{30,0} ---
(O,P,Q){
if(%_IsConstructCall()){
if((%_ClassOf(O)==='ArrayBuffer')||(%_ClassOf(O)==='SharedArrayBuffer')){
Uint8ArrayConstructByArrayBuffer(this,O,P,Q);
}else if((typeof(O)==='number')||(typeof(O)==='string')||
(typeof(O)==='boolean')||(O===(void 0))){
Uint8ArrayConstructByLength(this,O);
}else{
var J=O[symbolIterator];
if((J===(void 0))||J===$arrayValues){
Uint8ArrayConstructByArrayLike(this,O);
}else{
Uint8ArrayConstructByIterable(this,O,J);
}
}
}else{
throw MakeTypeError(20,"Uint8Array")
}
}
--- END ---
--- FUNCTION SOURCE (setPrototypeOf) id{31,0} ---
(J,am){
if((J==null)&&!(%_IsUndetectableObject(J)))throw MakeTypeError(14,"Object.setPrototypeOf");
if(am!==null&&!(%_IsSpecObject(am))){
throw MakeTypeError(79,am);
}
if((%_IsSpecObject(J))){
%SetPrototype(J,am);
}
return J;
}
--- END ---
--- FUNCTION SOURCE (InnerArraySort) id{32,0} ---
(v,aC){
if(!(%_ClassOf(aC)==='Function')){
aC=function(O,aD){
if(O===aD)return 0;
if(%_IsSmi(O)&&%_IsSmi(aD)){
return %SmiLexicographicCompare(O,aD);
}
O=$toString(O);
aD=$toString(aD);
if(O==aD)return 0;
else return O<aD?-1:1;
};
}
var aE=function InsertionSort(y,m,aF){
for(var t=m+1;t<aF;t++){
var aG=y[t];
for(var am=t-1;am>=m;am--){
var aH=y[am];
var aI=%_CallFunction((void 0),aH,aG,aC);
if(aI>0){
y[am+1]=aH;
}else{
break;
}
}
y[am+1]=aG;
}
};
var aJ=function(y,m,aF){
var aK=[];
var aL=200+((aF-m)&15);
for(var t=m+1,am=0;t<aF-1;t+=aL,am++){
aK[am]=[t,y[t]];
}
%_CallFunction(aK,function(y,z){
return %_CallFunction((void 0),y[1],z[1],aC);
},ArraySort);
var aM=aK[aK.length>>1][0];
return aM;
}
var aN=function QuickSort(y,m,aF){
var aM=0;
while(true){
if(aF-m<=10){
aE(y,m,aF);
return;
}
if(aF-m>1000){
aM=aJ(y,m,aF);
}else{
aM=m+((aF-m)>>1);
}
var aO=y[m];
var aP=y[aF-1];
var aQ=y[aM];
var aR=%_CallFunction((void 0),aO,aP,aC);
if(aR>0){
var aH=aO;
aO=aP;
aP=aH;
}
var aS=%_CallFunction((void 0),aO,aQ,aC);
if(aS>=0){
var aH=aO;
aO=aQ;
aQ=aP;
aP=aH;
}else{
var aT=%_CallFunction((void 0),aP,aQ,aC);
if(aT>0){
var aH=aP;
aP=aQ;
aQ=aH;
}
}
y[m]=aO;
y[aF-1]=aQ;
var aU=aP;
var aV=m+1;
var aW=aF-1;
y[aM]=y[aV];
y[aV]=aU;
partition:for(var t=aV+1;t<aW;t++){
var aG=y[t];
var aI=%_CallFunction((void 0),aG,aU,aC);
if(aI<0){
y[t]=y[aV];
y[aV]=aG;
aV++;
}else if(aI>0){
do{
aW--;
if(aW==t)break partition;
var aX=y[aW];
aI=%_CallFunction((void 0),aX,aU,aC);
}while(aI>0);
y[t]=y[aW];
y[aW]=aG;
if(aI<0){
aG=y[t];
y[t]=y[aV];
y[aV]=aG;
aV++;
}
}
}
if(aF-aW<aV-m){
aN(y,aW,aF);
aF=aV;
}else{
aN(y,m,aV);
m=aW;
}
}
};
var aY=function CopyFromPrototype(aZ,v){
var ba=0;
for(var bb=%_GetPrototype(aZ);bb;bb=%_GetPrototype(bb)){
var p=%GetArrayKeys(bb,v);
if((typeof(p)==='number')){
var bc=p;
for(var t=0;t<bc;t++){
if(!(%_CallFunction(aZ,t,i))&&(%_CallFunction(bb,t,i))){
aZ[t]=bb[t];
if(t>=ba){ba=t+1;}
}
}
}else{
for(var t=0;t<p.length;t++){
var Y=p[t];
if(!(Y===(void 0))&&!(%_CallFunction(aZ,Y,i))
&&(%_CallFunction(bb,Y,i))){
aZ[Y]=bb[Y];
if(Y>=ba){ba=Y+1;}
}
}
}
}
return ba;
};
var bd=function(aZ,m,aF){
for(var bb=%_GetPrototype(aZ);bb;bb=%_GetPrototype(bb)){
var p=%GetArrayKeys(bb,aF);
if((typeof(p)==='number')){
var bc=p;
for(var t=m;t<bc;t++){
if((%_CallFunction(bb,t,i))){
aZ[t]=(void 0);
}
}
}else{
for(var t=0;t<p.length;t++){
var Y=p[t];
if(!(Y===(void 0))&&m<=Y&&
(%_CallFunction(bb,Y,i))){
aZ[Y]=(void 0);
}
}
}
}
};
var be=function SafeRemoveArrayHoles(aZ){
var bf=0;
var bg=v-1;
var bh=0;
while(bf<bg){
while(bf<bg&&
!(aZ[bf]===(void 0))){
bf++;
}
if(!(%_CallFunction(aZ,bf,i))){
bh++;
}
while(bf<bg&&
(aZ[bg]===(void 0))){
if(!(%_CallFunction(aZ,bg,i))){
bh++;
}
bg--;
}
if(bf<bg){
aZ[bf]=aZ[bg];
aZ[bg]=(void 0);
}
}
if(!(aZ[bf]===(void 0)))bf++;
var t;
for(t=bf;t<v-bh;t++){
aZ[t]=(void 0);
}
for(t=v-bh;t<v;t++){
if(t in %_GetPrototype(aZ)){
aZ[t]=(void 0);
}else{
delete aZ[t];
}
}
return bf;
};
if(v<2)return this;
var J=(%_IsArray(this));
var bi;
if(!J){
bi=aY(this,v);
}
var bj=%RemoveArrayHoles(this,v);
if(bj==-1){
bj=be(this);
}
aN(this,0,bj);
if(!J&&(bj+1<bi)){
bd(this,bj,bi);
}
return this;
}
--- END ---
--- FUNCTION SOURCE (avg) id{33,0} ---
(frames, alg) {
// Some images strangely have different pixel counts per frame.
// Pick the largest and go with that I guess?
var len = frames.reduce(function min(p, c) {
var length = c.data.length
if (length <= p) {
return length
}
return p
}, Number.MAX_VALUE)
if (len === 1) {
return frames[0].data
}
var avgFrame = new Buffer(len)
for (var i = 0; i < len; i += 4) {
var pixels = new Buffer(4 * frames.length)
for (var j = 0; j < frames.length; j++) {
frames[j].data.copy(pixels, j * 4, i, i + 4)
//pixels[j*4] = frames[j].data[i]
//pixels[j*4+1] = frames[j].data[i+1]
//pixels[j*4+2] = frames[j].data[i+2]
//pixels[j*4+3] = frames[j].data[i+3]
}
var avgPixel = alg(pixels)
avgPixel.copy(avgFrame, i)
}
return avgFrame
}
--- END ---
--- FUNCTION SOURCE (Buffer) id{33,1} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{33,1} AS 1 AT <0:360>
--- FUNCTION SOURCE (fromString) id{33,2} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{33,2} AS 2 AT <1:247>
--- FUNCTION SOURCE (slice) id{33,3} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{33,3} AS 3 AT <2:382>
--- FUNCTION SOURCE (alignPool) id{33,4} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{33,4} AS 4 AT <2:448>
--- FUNCTION SOURCE (Buffer) id{33,5} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{33,5} AS 5 AT <0:430>
--- FUNCTION SOURCE (fromString) id{33,6} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{33,6} AS 6 AT <5:247>
--- FUNCTION SOURCE (slice) id{33,7} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{33,7} AS 7 AT <6:382>
--- FUNCTION SOURCE (alignPool) id{33,8} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{33,8} AS 8 AT <6:448>
--- FUNCTION SOURCE (medianPixel) id{33,9} ---
(pixels) {
var sorted = sortPixels(pixels)
var mid = (sorted.length / 2) - ((sorted.length / 2) % 4)
return sorted.slice(mid, mid + 4)
}
--- END ---
INLINE (medianPixel) id{33,9} AS 9 AT <0:754>
--- FUNCTION SOURCE (sortPixels) id{33,10} ---
(pixels) {
var split = []
for (var i = 0; i < pixels.length; i += 4) {
split.push(pixels.slice(i, i + 4))
}
var sorted = split.sort(function (a, b) {
return (a[0] + a[1] + a[2] + a[3]) - (b[0] + b[1] + b[2] + b[3])
})
var newbuff = new Buffer(pixels.length)
for (var j = 0; j < sorted.length; j++) {
newbuff[j * 4] = sorted[j][0]
newbuff[j * 4 + 1] = sorted[j][1]
newbuff[j * 4 + 2] = sorted[j][2]
newbuff[j * 4 + 3] = sorted[j][3]
}
return newbuff
}
--- END ---
INLINE (sortPixels) id{33,10} AS 10 AT <9:26>
--- FUNCTION SOURCE (slice) id{33,11} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{33,11} AS 11 AT <10:97>
--- FUNCTION SOURCE (Buffer) id{33,12} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{33,12} AS 12 AT <10:252>
--- FUNCTION SOURCE (fromString) id{33,13} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{33,13} AS 13 AT <12:247>
--- FUNCTION SOURCE (slice) id{33,14} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{33,14} AS 14 AT <13:382>
--- FUNCTION SOURCE (alignPool) id{33,15} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{33,15} AS 15 AT <13:448>
[deoptimizing (DEOPT eager): begin 0x100fecf4dc39 <JS Function avg (SharedFunctionInfo 0x2ac96392ee49)> (opt #33) @45, FP to SP delta: 440]
;;; deoptimize at 5_272: out of bounds
reading input frame avg => node=3, args=106, height=7; inputs:
0: 0x100fecf4dc39 ; (frame function) 0x100fecf4dc39 <JS Function avg (SharedFunctionInfo 0x2ac96392ee49)>
1: 0x36cdc0e04131 ; r9 0x36cdc0e04131 <undefined>
2: 0x100fecfa5909 ; r8 0x100fecfa5909 <JS Array[51]>
3: 0x100fecf4dbf1 ; rsi 0x100fecf4dbf1 <JS Function medianPixel (SharedFunctionInfo 0x2ac96392eba9)>
4: 0x100fecf4dac9 ; rcx 0x100fecf4dac9 <FixedArray[26]>
5: 1440000 ; rdx
6: 0x100fecfa58b9 ; rbx 0x100fecfa58b9 <an Uint8Array with map 0x3d4eb9d1d389>
7: 1788 ; rax
8: 0x36cdc0e04131 ; (literal 7) 0x36cdc0e04131 <undefined>
9: 0x36cdc0e04131 ; (literal 7) 0x36cdc0e04131 <undefined>
10: 0x36cdc0e04131 ; (literal 7) 0x36cdc0e04131 <undefined>
translating frame avg => node=106, height=48
0x7ffc654cd5f0: [top + 96] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd5e8: [top + 88] <- 0x100fecfa5909 ; 0x100fecfa5909 <JS Array[51]> (input #2)
0x7ffc654cd5e0: [top + 80] <- 0x100fecf4dbf1 ; 0x100fecf4dbf1 <JS Function medianPixel (SharedFunctionInfo 0x2ac96392eba9)> (input #3)
0x7ffc654cd5d8: [top + 72] <- 0x376e6fef0f21 ; caller's pc
0x7ffc654cd5d0: [top + 64] <- 0x7ffc654cd610 ; caller's fp
0x7ffc654cd5c8: [top + 56] <- 0x100fecf4dac9 ; context 0x100fecf4dac9 <FixedArray[26]> (input #4)
0x7ffc654cd5c0: [top + 48] <- 0x100fecf4dc39 ; function 0x100fecf4dc39 <JS Function avg (SharedFunctionInfo 0x2ac96392ee49)> (input #0)
0x7ffc654cd5b8: [top + 40] <- 0x15f90000000000 ; 1440000 (input #5)
0x7ffc654cd5b0: [top + 32] <- 0x100fecfa58b9 ; 0x100fecfa58b9 <an Uint8Array with map 0x3d4eb9d1d389> (input #6)
0x7ffc654cd5a8: [top + 24] <- 0x6fc00000000 ; 1788 (input #7)
0x7ffc654cd5a0: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #8)
0x7ffc654cd598: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #9)
0x7ffc654cd590: [top + 0] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #10)
[deoptimizing (eager): end 0x100fecf4dc39 <JS Function avg (SharedFunctionInfo 0x2ac96392ee49)> @45 => node=106, pc=0x376e6fef14e0, state=NO_REGISTERS, alignment=no padding, took 0.052 ms]
--- FUNCTION SOURCE (InsertionSort) id{34,0} ---
(y,m,aF){
for(var t=m+1;t<aF;t++){
var aG=y[t];
for(var am=t-1;am>=m;am--){
var aH=y[am];
var aI=%_CallFunction((void 0),aH,aG,aC);
if(aI>0){
y[am+1]=aH;
}else{
break;
}
}
y[am+1]=aG;
}
}
--- END ---
--- FUNCTION SOURCE (avg) id{35,0} ---
(frames, alg) {
// Some images strangely have different pixel counts per frame.
// Pick the largest and go with that I guess?
var len = frames.reduce(function min(p, c) {
var length = c.data.length
if (length <= p) {
return length
}
return p
}, Number.MAX_VALUE)
if (len === 1) {
return frames[0].data
}
var avgFrame = new Buffer(len)
for (var i = 0; i < len; i += 4) {
var pixels = new Buffer(4 * frames.length)
for (var j = 0; j < frames.length; j++) {
frames[j].data.copy(pixels, j * 4, i, i + 4)
//pixels[j*4] = frames[j].data[i]
//pixels[j*4+1] = frames[j].data[i+1]
//pixels[j*4+2] = frames[j].data[i+2]
//pixels[j*4+3] = frames[j].data[i+3]
}
var avgPixel = alg(pixels)
avgPixel.copy(avgFrame, i)
}
return avgFrame
}
--- END ---
--- FUNCTION SOURCE (Buffer) id{35,1} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{35,1} AS 1 AT <0:360>
--- FUNCTION SOURCE (fromString) id{35,2} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{35,2} AS 2 AT <1:247>
--- FUNCTION SOURCE (slice) id{35,3} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{35,3} AS 3 AT <2:382>
--- FUNCTION SOURCE (alignPool) id{35,4} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{35,4} AS 4 AT <2:448>
--- FUNCTION SOURCE (Buffer) id{35,5} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{35,5} AS 5 AT <0:430>
--- FUNCTION SOURCE (fromString) id{35,6} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{35,6} AS 6 AT <5:247>
--- FUNCTION SOURCE (slice) id{35,7} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{35,7} AS 7 AT <6:382>
--- FUNCTION SOURCE (alignPool) id{35,8} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{35,8} AS 8 AT <6:448>
--- FUNCTION SOURCE (medianPixel) id{35,9} ---
(pixels) {
var sorted = sortPixels(pixels)
var mid = (sorted.length / 2) - ((sorted.length / 2) % 4)
return sorted.slice(mid, mid + 4)
}
--- END ---
INLINE (medianPixel) id{35,9} AS 9 AT <0:754>
--- FUNCTION SOURCE (sortPixels) id{35,10} ---
(pixels) {
var split = []
for (var i = 0; i < pixels.length; i += 4) {
split.push(pixels.slice(i, i + 4))
}
var sorted = split.sort(function (a, b) {
return (a[0] + a[1] + a[2] + a[3]) - (b[0] + b[1] + b[2] + b[3])
})
var newbuff = new Buffer(pixels.length)
for (var j = 0; j < sorted.length; j++) {
newbuff[j * 4] = sorted[j][0]
newbuff[j * 4 + 1] = sorted[j][1]
newbuff[j * 4 + 2] = sorted[j][2]
newbuff[j * 4 + 3] = sorted[j][3]
}
return newbuff
}
--- END ---
INLINE (sortPixels) id{35,10} AS 10 AT <9:26>
--- FUNCTION SOURCE (slice) id{35,11} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{35,11} AS 11 AT <10:97>
--- FUNCTION SOURCE (Buffer) id{35,12} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{35,12} AS 12 AT <10:252>
--- FUNCTION SOURCE (fromString) id{35,13} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{35,13} AS 13 AT <12:247>
--- FUNCTION SOURCE (slice) id{35,14} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{35,14} AS 14 AT <13:382>
--- FUNCTION SOURCE (alignPool) id{35,15} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{35,15} AS 15 AT <13:448>
--- FUNCTION SOURCE () id{36,0} ---
(a, b) {
return (a[0] + a[1] + a[2] + a[3]) - (b[0] + b[1] + b[2] + b[3])
}
--- END ---
--- FUNCTION SOURCE (QuickSort) id{37,0} ---
(y,m,aF){
var aM=0;
while(true){
if(aF-m<=10){
aE(y,m,aF);
return;
}
if(aF-m>1000){
aM=aJ(y,m,aF);
}else{
aM=m+((aF-m)>>1);
}
var aO=y[m];
var aP=y[aF-1];
var aQ=y[aM];
var aR=%_CallFunction((void 0),aO,aP,aC);
if(aR>0){
var aH=aO;
aO=aP;
aP=aH;
}
var aS=%_CallFunction((void 0),aO,aQ,aC);
if(aS>=0){
var aH=aO;
aO=aQ;
aQ=aP;
aP=aH;
}else{
var aT=%_CallFunction((void 0),aP,aQ,aC);
if(aT>0){
var aH=aP;
aP=aQ;
aQ=aH;
}
}
y[m]=aO;
y[aF-1]=aQ;
var aU=aP;
var aV=m+1;
var aW=aF-1;
y[aM]=y[aV];
y[aV]=aU;
partition:for(var t=aV+1;t<aW;t++){
var aG=y[t];
var aI=%_CallFunction((void 0),aG,aU,aC);
if(aI<0){
y[t]=y[aV];
y[aV]=aG;
aV++;
}else if(aI>0){
do{
aW--;
if(aW==t)break partition;
var aX=y[aW];
aI=%_CallFunction((void 0),aX,aU,aC);
}while(aI>0);
y[t]=y[aW];
y[aW]=aG;
if(aI<0){
aG=y[t];
y[t]=y[aV];
y[aV]=aG;
aV++;
}
}
}
if(aF-aW<aV-m){
aN(y,aW,aF);
aF=aV;
}else{
aN(y,m,aV);
m=aW;
}
}
}
--- END ---
--- FUNCTION SOURCE (InsertionSort) id{38,0} ---
(y,m,aF){
for(var t=m+1;t<aF;t++){
var aG=y[t];
for(var am=t-1;am>=m;am--){
var aH=y[am];
var aI=%_CallFunction((void 0),aH,aG,aC);
if(aI>0){
y[am+1]=aH;
}else{
break;
}
}
y[am+1]=aG;
}
}
--- END ---
--- FUNCTION SOURCE (ToObject) id{39,0} ---
(i){
if((typeof(i)==='string'))return new e(i);
if((typeof(i)==='number'))return new g(i);
if((typeof(i)==='boolean'))return new d(i);
if((typeof(i)==='symbol'))return %NewSymbolWrapper(i);
if((i==null)&&!(%_IsUndetectableObject(i))){
throw MakeTypeError(113);
}
return i;
}
--- END ---
--- FUNCTION SOURCE (abs) id{40,0} ---
(e){
e=+e;
return(e>0)?e:0-e;
}
--- END ---
--- FUNCTION SOURCE (replaceBackground) id{41,0} ---
(frames, replacer, tolerance) {
tolerance = tolerance != null ? tolerance : 50
// var background = meanFrame(frames)
var background = medianFrame(frames)
for (var i = 0; i < frames.length; i++) {
var dupe = copy(frames[i].data)
replacer(dupe)
var rgba = frames[i].data
for (var j = 0; j < background.length; j += 4) {
var rDiff = Math.abs(rgba[j] - background[j])
var gDiff = Math.abs(rgba[j+1] - background[j+1])
var bDiff = Math.abs(rgba[j+2] - background[j+2])
if (!(rDiff > tolerance || gDiff > tolerance || bDiff > tolerance)) {
//if (rDiff + gDiff + bDiff < tolerance) {
var start = (j > dupe.length) ? 0 : j
rgba[j] = dupe[start + 0]
rgba[j+1] = dupe[start + 1]
rgba[j+2] = dupe[start + 2]
}
}
}
}
--- END ---
--- FUNCTION SOURCE (medianFrame) id{41,1} ---
(frames, alg) {
return avg(frames, medianPixel)
}
--- END ---
INLINE (medianFrame) id{41,1} AS 1 AT <0:140>
--- FUNCTION SOURCE (copy) id{41,2} ---
(rgba) {
var dupe = new Buffer(rgba.length)
rgba.copy(dupe)
return dupe
}
--- END ---
INLINE (copy) id{41,2} AS 2 AT <0:219>
--- FUNCTION SOURCE (Buffer) id{41,3} ---
(arg) {
// Common case.
if (typeof arg === 'number') {
// If less than zero, or NaN.
if (arg < 0 || arg !== arg)
arg = 0;
return allocate(arg);
}
// Slightly less common case.
if (typeof arg === 'string') {
return fromString(arg, arguments[1]);
}
// Unusual.
return fromObject(arg);
}
--- END ---
INLINE (Buffer) id{41,3} AS 3 AT <2:22>
--- FUNCTION SOURCE (fromString) id{41,4} ---
(string, encoding) {
if (typeof encoding !== 'string' || encoding === '')
encoding = 'utf8';
var length = byteLength(string, encoding);
if (length >= (Buffer.poolSize >>> 1))
return binding.createFromString(string, encoding);
if (length > (poolSize - poolOffset))
createPool();
var actual = allocPool.write(string, poolOffset, encoding);
var b = allocPool.slice(poolOffset, poolOffset + actual);
poolOffset += actual;
alignPool();
return b;
}
--- END ---
INLINE (fromString) id{41,4} AS 4 AT <3:247>
--- FUNCTION SOURCE (slice) id{41,5} ---
(start, end) {
const buffer = this.subarray(start, end);
Object.setPrototypeOf(buffer, Buffer.prototype);
return buffer;
}
--- END ---
INLINE (slice) id{41,5} AS 5 AT <4:382>
--- FUNCTION SOURCE (alignPool) id{41,6} ---
() {
// Ensure aligned slices
if (poolOffset & 0x7) {
poolOffset |= 0x7;
poolOffset++;
}
}
--- END ---
INLINE (alignPool) id{41,6} AS 6 AT <4:448>
--- FUNCTION SOURCE (replacer) id{41,7} ---
(frame) {
frame.fill(0)
}
--- END ---
INLINE (replacer) id{41,7} AS 7 AT <0:244>
--- FUNCTION SOURCE (DefineOwnProperty) id{42,0} ---
(J,V,G,Y){
if(%_IsJSProxy(J)){
if((typeof(V)==='symbol'))return false;
var w=FromGenericPropertyDescriptor(G);
return DefineProxyProperty(J,V,w,Y);
}else if((%_IsArray(J))){
return DefineArrayProperty(J,V,G,Y);
}else{
return DefineObjectProperty(J,V,G,Y);
}
}
--- END ---
--- FUNCTION SOURCE (GIFEncoder.removeAlphaChannel) id{43,0} ---
(data) {
var w = this.width;
var h = this.height;
var pixels = new Uint8Array(w * h * 3);
var count = 0;
for (var i = 0; i < h; i++) {
for (var j = 0; j < w; j++) {
var b = (i * w * 4) + j * 4;
pixels[count++] = data[b];
pixels[count++] = data[b+1];
pixels[count++] = data[b+2];
}
}
return pixels;
}
--- END ---
[deoptimizing (DEOPT eager): begin 0x3ed23a86f091 <JS Function abs (SharedFunctionInfo 0x36cdc0e69bd9)> (opt #40) @2, FP to SP delta: 24]
;;; deoptimize at 0_8: lost precision
reading input frame abs => node=2, args=3, height=1; inputs:
0: 0x3ed23a86f091 ; (frame function) 0x3ed23a86f091 <JS Function abs (SharedFunctionInfo 0x36cdc0e69bd9)>
1: 0x3ed23a854651 ; [fp + 24] 0x3ed23a854651 <a MathConstructor with map 0x3d4eb9d0ad49>
2: 0x7bbff3ebea1 ; [fp + 16] 0x7bbff3ebea1 <Number: 0.015625>
3: 0x3ed23a871969 ; [fp - 24] 0x3ed23a871969 <FixedArray[15]>
translating frame abs => node=3, height=0
0x7ffc654cd278: [top + 40] <- 0x3ed23a854651 ; 0x3ed23a854651 <a MathConstructor with map 0x3d4eb9d0ad49> (input #1)
0x7ffc654cd270: [top + 32] <- 0x7bbff3ebea1 ; 0x7bbff3ebea1 <Number: 0.015625> (input #2)
0x7ffc654cd268: [top + 24] <- 0x376e6ff4264e ; caller's pc
0x7ffc654cd260: [top + 16] <- 0x7ffc654cd2e0 ; caller's fp
0x7ffc654cd258: [top + 8] <- 0x3ed23a871969 ; context 0x3ed23a871969 <FixedArray[15]> (input #3)
0x7ffc654cd250: [top + 0] <- 0x3ed23a86f091 ; function 0x3ed23a86f091 <JS Function abs (SharedFunctionInfo 0x36cdc0e69bd9)> (input #0)
[deoptimizing (eager): end 0x3ed23a86f091 <JS Function abs (SharedFunctionInfo 0x36cdc0e69bd9)> @2 => node=3, pc=0x376e6ff0d186, state=NO_REGISTERS, alignment=no padding, took 0.037 ms]
--- FUNCTION SOURCE (abs) id{44,0} ---
(e){
e=+e;
return(e>0)?e:0-e;
}
--- END ---
--- FUNCTION SOURCE (contest) id{45,0} ---
(b, g, r) {
/*
finds closest neuron (min dist) and updates freq
finds best neuron (min dist-bias) and returns position
for frequently chosen neurons, freq[i] is high and bias[i] is negative
bias[i] = gamma * ((1 / netsize) - freq[i])
*/
var bestd = ~(1 << 31);
var bestbiasd = bestd;
var bestpos = -1;
var bestbiaspos = bestpos;
var i, n, dist, biasdist, betafreq;
for (i = 0; i < netsize; i++) {
n = network[i];
dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
betafreq = (freq[i] >> betashift);
freq[i] -= betafreq;
bias[i] += (betafreq << gammashift);
}
freq[bestpos] += beta;
bias[bestpos] -= betagamma;
return bestbiaspos;
}
--- END ---
--- FUNCTION SOURCE (alterneigh) id{46,0} ---
(radius, i, b, g, r) {
var lo = Math.abs(i - radius);
var hi = Math.min(i + radius, netsize);
var j = i + 1;
var k = i - 1;
var m = 1;
var p, a;
while ((j < hi) || (k > lo)) {
a = radpower[m++];
if (j < hi) {
p = network[j++];
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
}
if (k > lo) {
p = network[k--];
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
}
}
}
--- END ---
--- FUNCTION SOURCE (altersingle) id{47,0} ---
(alpha, i, b, g, r) {
network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;
network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;
network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;
}
--- END ---
[deoptimizing (DEOPT soft): begin 0x7bbfe01ac69 <JS Function alterneigh (SharedFunctionInfo 0x100fecfd14a1)> (opt #46) @26, FP to SP delta: 64]
;;; deoptimize at 0_473: Insufficient type feedback for keyed load
reading input frame alterneigh => node=6, args=499, height=8; inputs:
0: 0x7bbfe01ac69 ; (frame function) 0x7bbfe01ac69 <JS Function alterneigh (SharedFunctionInfo 0x100fecfd14a1)>
1: 0x36cdc0e04131 ; [fp + 56] 0x36cdc0e04131 <undefined>
2: 0x1300000000 ; [fp + 48] 19
3: 0x4600000000 ; [fp + 40] 70
4: 0xc2000000000 ; r12 3104
5: 0x46000000000 ; [fp + 24] 1120
6: 0x2000000000 ; r14 32
7: 0x7bbfe01aad1 ; [fp - 24] 0x7bbfe01aad1 <FixedArray[18]>
8: 5.100000e+01 ; xmm1 (bool)
9: 8.900000e+01 ; xmm2 (bool)
10: 72 ; rax
11: 69 ; rdx
12: 2 ; (int) [fp - 32]
13: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
14: 223541 ; rbx
translating frame alterneigh => node=499, height=56
0x7ffc654cd308: [top + 128] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd300: [top + 120] <- 0x1300000000 ; 19 (input #2)
0x7ffc654cd2f8: [top + 112] <- 0x4600000000 ; 70 (input #3)
0x7ffc654cd2f0: [top + 104] <- 0xc2000000000 ; 3104 (input #4)
0x7ffc654cd2e8: [top + 96] <- 0x46000000000 ; 1120 (input #5)
0x7ffc654cd2e0: [top + 88] <- 0x2000000000 ; 32 (input #6)
0x7ffc654cd2d8: [top + 80] <- 0x376e6ff41f51 ; caller's pc
0x7ffc654cd2d0: [top + 72] <- 0x7ffc654cd398 ; caller's fp
0x7ffc654cd2c8: [top + 64] <- 0x7bbfe01aad1 ; context 0x7bbfe01aad1 <FixedArray[18]> (input #7)
0x7ffc654cd2c0: [top + 56] <- 0x7bbfe01ac69 ; function 0x7bbfe01ac69 <JS Function alterneigh (SharedFunctionInfo 0x100fecfd14a1)> (input #0)
0x7ffc654cd2b8: [top + 48] <- 0x3300000000 ; 51 (input #8)
0x7ffc654cd2b0: [top + 40] <- 0x5900000000 ; 89 (input #9)
0x7ffc654cd2a8: [top + 32] <- 0x4800000000 ; 72 (input #10)
0x7ffc654cd2a0: [top + 24] <- 0x4500000000 ; 69 (input #11)
0x7ffc654cd298: [top + 16] <- 0x200000000 ; 2 (input #12)
0x7ffc654cd290: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #13)
0x7ffc654cd288: [top + 0] <- 0x3693500000000 ; 223541 (input #14)
[deoptimizing (soft): end 0x7bbfe01ac69 <JS Function alterneigh (SharedFunctionInfo 0x100fecfd14a1)> @26 => node=499, pc=0x376e6ff43793, state=NO_REGISTERS, alignment=no padding, took 0.054 ms]
--- FUNCTION SOURCE (alterneigh) id{48,0} ---
(radius, i, b, g, r) {
var lo = Math.abs(i - radius);
var hi = Math.min(i + radius, netsize);
var j = i + 1;
var k = i - 1;
var m = 1;
var p, a;
while ((j < hi) || (k > lo)) {
a = radpower[m++];
if (j < hi) {
p = network[j++];
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
}
if (k > lo) {
p = network[k--];
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
}
}
}
--- END ---
--- FUNCTION SOURCE (inxbuild) id{49,0} ---
() {
var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; // index on g
// find smallest in i..netsize-1
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) { // index on g
smallpos = j;
smallval = q[1]; // index on g
}
}
q = network[smallpos];
// swap p (i) and q (smallpos) entries
if (i != smallpos) {
j = q[0]; q[0] = p[0]; p[0] = j;
j = q[1]; q[1] = p[1]; p[1] = j;
j = q[2]; q[2] = p[2]; p[2] = j;
j = q[3]; q[3] = p[3]; p[3] = j;
}
// smallval entry is now in position i
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++)
netindex[j] = i;
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++)
netindex[j] = maxnetpos; // really 256
}
--- END ---
[deoptimizing (DEOPT soft): begin 0x7bbfe01acf9 <JS Function inxbuild (SharedFunctionInfo 0x100fecfd15f1)> (opt #49) @39, FP to SP delta: 184]
;;; deoptimize at 0_1035: Insufficient type feedback for LHS of binary operation
reading input frame inxbuild => node=1, args=52, height=9; inputs:
0: 0x7bbfe01acf9 ; (frame function) 0x7bbfe01acf9 <JS Function inxbuild (SharedFunctionInfo 0x100fecfd15f1)>
1: 0x36cdc0e04131 ; [fp - 112] 0x36cdc0e04131 <undefined>
2: 0x7bbfe01aad1 ; [fp - 96] 0x7bbfe01aad1 <FixedArray[18]>
3: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
4: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
5: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
6: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
7: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
8: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
9: 0x7bbfe214819 ; rbx 0x7bbfe214819 <Number: 255>
10: 0xff00000000 ; [fp - 104] 255
translating frame inxbuild => node=52, height=64
0x7ffc654cd3a8: [top + 96] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd3a0: [top + 88] <- 0x376e6ff4046a ; caller's pc
0x7ffc654cd398: [top + 80] <- 0x7ffc654cd3c8 ; caller's fp
0x7ffc654cd390: [top + 72] <- 0x7bbfe01aad1 ; context 0x7bbfe01aad1 <FixedArray[18]> (input #2)
0x7ffc654cd388: [top + 64] <- 0x7bbfe01acf9 ; function 0x7bbfe01acf9 <JS Function inxbuild (SharedFunctionInfo 0x100fecfd15f1)> (input #0)
0x7ffc654cd380: [top + 56] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #3)
0x7ffc654cd378: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #4)
0x7ffc654cd370: [top + 40] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #5)
0x7ffc654cd368: [top + 32] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd360: [top + 24] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #7)
0x7ffc654cd358: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #8)
0x7ffc654cd350: [top + 8] <- 0x7bbfe214819 ; 0x7bbfe214819 <Number: 255> (input #9)
0x7ffc654cd348: [top + 0] <- 0xff00000000 ; 255 (input #10)
[deoptimizing (soft): end 0x7bbfe01acf9 <JS Function inxbuild (SharedFunctionInfo 0x100fecfd15f1)> @39 => node=52, pc=0x376e6ff44e8d, state=NO_REGISTERS, alignment=no padding, took 0.042 ms]
--- FUNCTION SOURCE (inxsearch) id{50,0} ---
(b, g, r) {
var a, p, dist;
var bestd = 1000; // biggest possible dist is 256*3
var best = -1;
var i = netindex[g]; // index on g
var j = i - 1; // start at netindex[g] and work outwards
while ((i < netsize) || (j >= 0)) {
if (i < netsize) {
p = network[i];
dist = p[1] - g; // inx key
if (dist >= bestd) i = netsize; // stop iter
else {
i++;
if (dist < 0) dist = -dist;
a = p[0] - b; if (a < 0) a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r; if (a < 0) a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
if (j >= 0) {
p = network[j];
dist = g - p[1]; // inx key - reverse dif
if (dist >= bestd) j = -1; // stop iter
else {
j--;
if (dist < 0) dist = -dist;
a = p[0] - b; if (a < 0) a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r; if (a < 0) a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
}
return best;
}
--- END ---
--- FUNCTION SOURCE (GIFEncoder.analyzePixels) id{51,0} ---
() {
var len = this.pixels.length;
var nPix = len / 3;
// TODO: Re-use indexedPixels
this.indexedPixels = new Uint8Array(nPix);
var imgq = new NeuQuant(this.pixels, this.sample);
imgq.buildColormap(); // create reduced palette
this.colorTab = imgq.getColormap();
// map image pixels to new palette
var k = 0;
for (var j = 0; j < nPix; j++) {
var index = imgq.lookupRGB(
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff
);
this.usedEntry[index] = true;
this.indexedPixels[j] = index;
}
this.pixels = null;
this.colorDepth = 8;
this.palSize = 7;
// get closest match to transparent color if specified
if (this.transparent !== null) {
this.transIndex = this.findClosest(this.transparent);
}
}
--- END ---
[deoptimizing (DEOPT soft): begin 0x3ed23a8fced1 <JS Function inxsearch (SharedFunctionInfo 0x100fecfd1699)> (opt #50) @27, FP to SP delta: 24]
;;; deoptimize at 0_940: Insufficient type feedback for combined type of binary operation
reading input frame inxsearch => node=4, args=495, height=8; inputs:
0: 0x3ed23a8fced1 ; (frame function) 0x3ed23a8fced1 <JS Function inxsearch (SharedFunctionInfo 0x100fecfd1699)>
1: 0x3ed23a8fcf19 ; [fp + 40] 0x3ed23a8fcf19 <a NeuQuant with map 0x3d4eb9d0eb81>
2: 0x8700000000 ; r9 135
3: 0x6c00000000 ; r8 108
4: 0x00000000 ; r11 0
5: 0x3ed23a8fce31 ; [fp - 24] 0x3ed23a8fce31 <FixedArray[18]>
6: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
7: 0xc518ec195b9 ; rdx 0xc518ec195b9 <a Float64Array with map 0x3d4eb9d157c9>
8: 0.000000e+00 ; xmm7 (bool)
9: 0x7bbff1f1dc1 ; r12 0x7bbff1f1dc1 <Number: 135>
10: 1.080000e+02 ; xmm6 (bool)
11: 74 ; rax
12: 72 ; rbx
translating frame inxsearch => node=495, height=56
0x7ffc654cd390: [top + 112] <- 0x3ed23a8fcf19 ; 0x3ed23a8fcf19 <a NeuQuant with map 0x3d4eb9d0eb81> (input #1)
0x7ffc654cd388: [top + 104] <- 0x8700000000 ; 135 (input #2)
0x7ffc654cd380: [top + 96] <- 0x6c00000000 ; 108 (input #3)
0x7ffc654cd378: [top + 88] <- 0x00000000 ; 0 (input #4)
0x7ffc654cd370: [top + 80] <- 0x376e6ff49dfc ; caller's pc
0x7ffc654cd368: [top + 72] <- 0x7ffc654cd428 ; caller's fp
0x7ffc654cd360: [top + 64] <- 0x3ed23a8fce31 ; context 0x3ed23a8fce31 <FixedArray[18]> (input #5)
0x7ffc654cd358: [top + 56] <- 0x3ed23a8fced1 ; function 0x3ed23a8fced1 <JS Function inxsearch (SharedFunctionInfo 0x100fecfd1699)> (input #0)
0x7ffc654cd350: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd348: [top + 40] <- 0xc518ec195b9 ; 0xc518ec195b9 <a Float64Array with map 0x3d4eb9d157c9> (input #7)
0x7ffc654cd340: [top + 32] <- 0x00000000 ; 0 (input #8)
0x7ffc654cd338: [top + 24] <- 0x7bbff1f1dc1 ; 0x7bbff1f1dc1 <Number: 135> (input #9)
0x7ffc654cd330: [top + 16] <- 0x6c00000000 ; 108 (input #10)
0x7ffc654cd328: [top + 8] <- 0x4a00000000 ; 74 (input #11)
0x7ffc654cd320: [top + 0] <- 0x4800000000 ; 72 (input #12)
[deoptimizing (soft): end 0x3ed23a8fced1 <JS Function inxsearch (SharedFunctionInfo 0x100fecfd1699)> @27 => node=495, pc=0x376e6ff473e7, state=NO_REGISTERS, alignment=no padding, took 0.089 ms]
[deoptimizing (DEOPT eager): begin 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> (opt #51) @31, FP to SP delta: 144]
;;; deoptimize at 0_522: out of bounds
reading input frame GIFEncoder.analyzePixels => node=1, args=226, height=8; inputs:
0: 0x2ac96395d689 ; (frame function) 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)>
1: 0x3ed23a8fcf31 ; rbx 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d3f149>
2: 0x100fecf7fb11 ; [fp - 128] 0x100fecf7fb11 <FixedArray[8]>
3: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
4: 360000 ; (int) [fp - 120]
5: 0x3ed23a8fcf19 ; [fp - 112] 0x3ed23a8fcf19 <a NeuQuant with map 0x3d4eb9d0eb81>
6: 360873 ; (int) [fp - 144]
7: 120290 ; (int) [fp - 104]
8: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
9: 0x7bbff1f22f1 ; rax 0x7bbff1f22f1 <Number: 67>
translating frame GIFEncoder.analyzePixels => node=226, height=56
0x7ffc654cd438: [top + 88] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d3f149> (input #1)
0x7ffc654cd430: [top + 80] <- 0x376e6ff3e4d3 ; caller's pc
0x7ffc654cd428: [top + 72] <- 0x7ffc654cd458 ; caller's fp
0x7ffc654cd420: [top + 64] <- 0x100fecf7fb11 ; context 0x100fecf7fb11 <FixedArray[8]> (input #2)
0x7ffc654cd418: [top + 56] <- 0x2ac96395d689 ; function 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> (input #0)
0x7ffc654cd410: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #3)
0x7ffc654cd408: [top + 40] <- 0x57e4000000000 ; 360000 (input #4)
0x7ffc654cd400: [top + 32] <- 0x3ed23a8fcf19 ; 0x3ed23a8fcf19 <a NeuQuant with map 0x3d4eb9d0eb81> (input #5)
0x7ffc654cd3f8: [top + 24] <- 0x581a900000000 ; 360873 (input #6)
0x7ffc654cd3f0: [top + 16] <- 0x1d5e200000000 ; 120290 (input #7)
0x7ffc654cd3e8: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #8)
0x7ffc654cd3e0: [top + 0] <- 0x7bbff1f22f1 ; 0x7bbff1f22f1 <Number: 67> (input #9)
[deoptimizing (eager): end 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> @31 => node=226, pc=0x376e6ff3fd7f, state=TOS_REG, alignment=no padding, took 0.059 ms]
--- FUNCTION SOURCE (inxsearch) id{52,0} ---
(b, g, r) {
var a, p, dist;
var bestd = 1000; // biggest possible dist is 256*3
var best = -1;
var i = netindex[g]; // index on g
var j = i - 1; // start at netindex[g] and work outwards
while ((i < netsize) || (j >= 0)) {
if (i < netsize) {
p = network[i];
dist = p[1] - g; // inx key
if (dist >= bestd) i = netsize; // stop iter
else {
i++;
if (dist < 0) dist = -dist;
a = p[0] - b; if (a < 0) a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r; if (a < 0) a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
if (j >= 0) {
p = network[j];
dist = g - p[1]; // inx key - reverse dif
if (dist >= bestd) j = -1; // stop iter
else {
j--;
if (dist < 0) dist = -dist;
a = p[0] - b; if (a < 0) a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r; if (a < 0) a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
}
return best;
}
--- END ---
--- FUNCTION SOURCE (GIFEncoder.analyzePixels) id{53,0} ---
() {
var len = this.pixels.length;
var nPix = len / 3;
// TODO: Re-use indexedPixels
this.indexedPixels = new Uint8Array(nPix);
var imgq = new NeuQuant(this.pixels, this.sample);
imgq.buildColormap(); // create reduced palette
this.colorTab = imgq.getColormap();
// map image pixels to new palette
var k = 0;
for (var j = 0; j < nPix; j++) {
var index = imgq.lookupRGB(
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff
);
this.usedEntry[index] = true;
this.indexedPixels[j] = index;
}
this.pixels = null;
this.colorDepth = 8;
this.palSize = 7;
// get closest match to transparent color if specified
if (this.transparent !== null) {
this.transIndex = this.findClosest(this.transparent);
}
}
--- END ---
[deoptimizing (DEOPT soft): begin 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> (opt #53) @35, FP to SP delta: 144]
;;; deoptimize at 0_584: Insufficient type feedback for generic named access
reading input frame GIFEncoder.analyzePixels => node=1, args=178, height=7; inputs:
0: 0x2ac96395d689 ; (frame function) 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)>
1: 0x3ed23a8fcf31 ; rdx 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d3f149>
2: 0x100fecf7fb11 ; [fp - 128] 0x100fecf7fb11 <FixedArray[8]>
3: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
4: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
5: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
6: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
7: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
8: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
translating frame GIFEncoder.analyzePixels => node=178, height=48
0x7ffc654cd438: [top + 80] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d3f149> (input #1)
0x7ffc654cd430: [top + 72] <- 0x376e6ff3e4d3 ; caller's pc
0x7ffc654cd428: [top + 64] <- 0x7ffc654cd458 ; caller's fp
0x7ffc654cd420: [top + 56] <- 0x100fecf7fb11 ; context 0x100fecf7fb11 <FixedArray[8]> (input #2)
0x7ffc654cd418: [top + 48] <- 0x2ac96395d689 ; function 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> (input #0)
0x7ffc654cd410: [top + 40] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #3)
0x7ffc654cd408: [top + 32] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #4)
0x7ffc654cd400: [top + 24] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #5)
0x7ffc654cd3f8: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd3f0: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #7)
0x7ffc654cd3e8: [top + 0] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #8)
[deoptimizing (soft): end 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> @35 => node=178, pc=0x376e6ff3fe8f, state=NO_REGISTERS, alignment=no padding, took 0.055 ms]
[marking dependent code 0x376e6ff4ac41 (opt #53) for deoptimization, reason: prototype-check]
[marking dependent code 0x376e6ff499a1 (opt #51) for deoptimization, reason: prototype-check]
[deoptimize marked code in all contexts]
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{54,0} ---
(val) {
this.data.push(val);
}
--- END ---
--- FUNCTION SOURCE (nextPixel) id{55,0} ---
() {
if (remaining === 0) return EOF;
--remaining;
var pix = pixels[curPixel++];
return pix & 0xff;
}
--- END ---
--- FUNCTION SOURCE (compress) id{56,0} ---
(init_bits, outs) {
var fcode, c, i, ent, disp, hsize_reg, hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = nextPixel();
hshift = 0;
for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = HSIZE;
cl_hash(hsize_reg); // clear hash table
output(ClearCode, outs);
outer_loop: while ((c = nextPixel()) != EOF) {
fcode = (c << BITS) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] === fcode) {
ent = codetab[i];
continue;
} else if (htab[i] >= 0) { // non-empty slot
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i === 0) disp = 1;
do {
if ((i -= disp) < 0) i += hsize_reg;
if (htab[i] === fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < 1 << BITS) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
} else {
cl_block(outs);
}
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
}
--- END ---
--- FUNCTION SOURCE (MAXCODE) id{56,1} ---
(n_bits) {
return (1 << n_bits) - 1;
}
--- END ---
INLINE (MAXCODE) id{56,1} AS 1 AT <0:264>
--- FUNCTION SOURCE (nextPixel) id{56,2} ---
() {
if (remaining === 0) return EOF;
--remaining;
var pix = pixels[curPixel++];
return pix & 0xff;
}
--- END ---
INLINE (nextPixel) id{56,2} AS 2 AT <0:424>
--- FUNCTION SOURCE (cl_hash) id{56,3} ---
(hsize) {
for (var i = 0; i < hsize; ++i) htab[i] = -1;
}
--- END ---
INLINE (cl_hash) id{56,3} AS 3 AT <0:596>
--- FUNCTION SOURCE (nextPixel) id{56,4} ---
() {
if (remaining === 0) return EOF;
--remaining;
var pix = pixels[curPixel++];
return pix & 0xff;
}
--- END ---
INLINE (nextPixel) id{56,4} AS 4 AT <0:695>
--- FUNCTION SOURCE (char_out) id{57,0} ---
(c, outs) {
accum[a_count++] = c;
if (a_count >= 254) flush_char(outs);
}
--- END ---
[marking dependent code 0x376e6ff515e1 (opt #56) for deoptimization, reason: property-cell-changed]
[deoptimize marked code in all contexts]
[deoptimizer unlinked: compress / 7bbfe1c9b11]
[deoptimizing (DEOPT lazy): begin 0x7bbfe1c9b11 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (opt #56) @40, FP to SP delta: 168]
reading input frame compress => node=3, args=560, height=8; inputs:
0: 0x7bbfe1c9b11 ; (frame function) 0x7bbfe1c9b11 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)>
1: 0x36cdc0e04131 ; [fp - 144] 0x36cdc0e04131 <undefined>
2: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
3: 0x3ed23a8fcf31 ; [fp - 136] 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
4: 0x7bbfe1c9949 ; [fp - 128] 0x7bbfe1c9949 <FixedArray[28]>
5: 49663 ; (int) [fp - 160]
6: 12 ; (int) [fp - 152]
7: 0x13f00000000 ; [fp - 168] 319
8: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
9: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
10: 0x138b00000000 ; [fp - 120] 5003
11: 4 ; (int) [fp - 112]
translating frame compress => node=560, height=56
0x7ffc654cd3d0: [top + 104] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd3c8: [top + 96] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #2)
0x7ffc654cd3c0: [top + 88] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #3)
0x7ffc654cd3b8: [top + 80] <- 0x376e6ff4e19e ; caller's pc
0x7ffc654cd3b0: [top + 72] <- 0x7ffc654cd3f0 ; caller's fp
0x7ffc654cd3a8: [top + 64] <- 0x7bbfe1c9949 ; context 0x7bbfe1c9949 <FixedArray[28]> (input #4)
0x7ffc654cd3a0: [top + 56] <- 0x7bbfe1c9b11 ; function 0x7bbfe1c9b11 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (input #0)
0x7ffc654cd398: [top + 48] <- 0xc1ff00000000 ; 49663 (input #5)
0x7ffc654cd390: [top + 40] <- 0xc00000000 ; 12 (input #6)
0x7ffc654cd388: [top + 32] <- 0x13f00000000 ; 319 (input #7)
0x7ffc654cd380: [top + 24] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #8)
0x7ffc654cd378: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #9)
0x7ffc654cd370: [top + 8] <- 0x138b00000000 ; 5003 (input #10)
0x7ffc654cd368: [top + 0] <- 0x400000000 ; 4 (input #11)
[deoptimizing (lazy): end 0x7bbfe1c9b11 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> @40 => node=560, pc=0x376e6ff4eb9d, state=NO_REGISTERS, alignment=no padding, took 0.062 ms]
--- FUNCTION SOURCE (compress) id{58,0} ---
(init_bits, outs) {
var fcode, c, i, ent, disp, hsize_reg, hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = nextPixel();
hshift = 0;
for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = HSIZE;
cl_hash(hsize_reg); // clear hash table
output(ClearCode, outs);
outer_loop: while ((c = nextPixel()) != EOF) {
fcode = (c << BITS) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] === fcode) {
ent = codetab[i];
continue;
} else if (htab[i] >= 0) { // non-empty slot
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i === 0) disp = 1;
do {
if ((i -= disp) < 0) i += hsize_reg;
if (htab[i] === fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < 1 << BITS) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
} else {
cl_block(outs);
}
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
}
--- END ---
--- FUNCTION SOURCE (MAXCODE) id{58,1} ---
(n_bits) {
return (1 << n_bits) - 1;
}
--- END ---
INLINE (MAXCODE) id{58,1} AS 1 AT <0:264>
--- FUNCTION SOURCE (nextPixel) id{58,2} ---
() {
if (remaining === 0) return EOF;
--remaining;
var pix = pixels[curPixel++];
return pix & 0xff;
}
--- END ---
INLINE (nextPixel) id{58,2} AS 2 AT <0:424>
--- FUNCTION SOURCE (cl_hash) id{58,3} ---
(hsize) {
for (var i = 0; i < hsize; ++i) htab[i] = -1;
}
--- END ---
INLINE (cl_hash) id{58,3} AS 3 AT <0:596>
--- FUNCTION SOURCE (nextPixel) id{58,4} ---
() {
if (remaining === 0) return EOF;
--remaining;
var pix = pixels[curPixel++];
return pix & 0xff;
}
--- END ---
INLINE (nextPixel) id{58,4} AS 4 AT <0:695>
[deoptimizing (DEOPT soft): begin 0x7bbfe1c9b11 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (opt #58) @39, FP to SP delta: 168]
;;; deoptimize at 0_1002: Insufficient type feedback for combined type of binary operation
reading input frame compress => node=3, args=419, height=9; inputs:
0: 0x7bbfe1c9b11 ; (frame function) 0x7bbfe1c9b11 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)>
1: 0x36cdc0e04131 ; r9 0x36cdc0e04131 <undefined>
2: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
3: 0x3ed23a8fcf31 ; r8 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
4: 0x7bbfe1c9949 ; rsi 0x7bbfe1c9949 <FixedArray[28]>
5: 258796 ; r12
6: 63 ; r11
7: 284 ; rdi
8: 748 ; rdx
9: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
10: 0x138b00000000 ; rbx 5003
11: 4 ; rax
12: 4719 ; rcx
translating frame compress => node=419, height=64
0x7ffc654cd3d0: [top + 112] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd3c8: [top + 104] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #2)
0x7ffc654cd3c0: [top + 96] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #3)
0x7ffc654cd3b8: [top + 88] <- 0x376e6ff4e19e ; caller's pc
0x7ffc654cd3b0: [top + 80] <- 0x7ffc654cd3f0 ; caller's fp
0x7ffc654cd3a8: [top + 72] <- 0x7bbfe1c9949 ; context 0x7bbfe1c9949 <FixedArray[28]> (input #4)
0x7ffc654cd3a0: [top + 64] <- 0x7bbfe1c9b11 ; function 0x7bbfe1c9b11 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (input #0)
0x7ffc654cd398: [top + 56] <- 0x3f2ec00000000 ; 258796 (input #5)
0x7ffc654cd390: [top + 48] <- 0x3f00000000 ; 63 (input #6)
0x7ffc654cd388: [top + 40] <- 0x11c00000000 ; 284 (input #7)
0x7ffc654cd380: [top + 32] <- 0x2ec00000000 ; 748 (input #8)
0x7ffc654cd378: [top + 24] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #9)
0x7ffc654cd370: [top + 16] <- 0x138b00000000 ; 5003 (input #10)
0x7ffc654cd368: [top + 8] <- 0x400000000 ; 4 (input #11)
0x7ffc654cd360: [top + 0] <- 0x126f00000000 ; 4719 (input #12)
[deoptimizing (soft): end 0x7bbfe1c9b11 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> @39 => node=419, pc=0x376e6ff4e954, state=TOS_REG, alignment=no padding, took 0.048 ms]
--- FUNCTION SOURCE (compress) id{59,0} ---
(init_bits, outs) {
var fcode, c, i, ent, disp, hsize_reg, hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = nextPixel();
hshift = 0;
for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = HSIZE;
cl_hash(hsize_reg); // clear hash table
output(ClearCode, outs);
outer_loop: while ((c = nextPixel()) != EOF) {
fcode = (c << BITS) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] === fcode) {
ent = codetab[i];
continue;
} else if (htab[i] >= 0) { // non-empty slot
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i === 0) disp = 1;
do {
if ((i -= disp) < 0) i += hsize_reg;
if (htab[i] === fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < 1 << BITS) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
} else {
cl_block(outs);
}
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
}
--- END ---
--- FUNCTION SOURCE (MAXCODE) id{59,1} ---
(n_bits) {
return (1 << n_bits) - 1;
}
--- END ---
INLINE (MAXCODE) id{59,1} AS 1 AT <0:264>
--- FUNCTION SOURCE (nextPixel) id{59,2} ---
() {
if (remaining === 0) return EOF;
--remaining;
var pix = pixels[curPixel++];
return pix & 0xff;
}
--- END ---
INLINE (nextPixel) id{59,2} AS 2 AT <0:424>
--- FUNCTION SOURCE (cl_hash) id{59,3} ---
(hsize) {
for (var i = 0; i < hsize; ++i) htab[i] = -1;
}
--- END ---
INLINE (cl_hash) id{59,3} AS 3 AT <0:596>
--- FUNCTION SOURCE (nextPixel) id{59,4} ---
() {
if (remaining === 0) return EOF;
--remaining;
var pix = pixels[curPixel++];
return pix & 0xff;
}
--- END ---
INLINE (nextPixel) id{59,4} AS 4 AT <0:695>
--- FUNCTION SOURCE (output) id{60,0} ---
(code, outs) {
cur_accum &= masks[cur_bits];
if (cur_bits > 0) cur_accum |= (code << cur_bits);
else cur_accum = code;
cur_bits += n_bits;
while (cur_bits >= 8) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg) {
if (clear_flg) {
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
} else {
++n_bits;
if (n_bits == BITS) maxcode = 1 << BITS;
else maxcode = MAXCODE(n_bits);
}
}
if (code == EOFCode) {
// At EOF, write the rest of the buffer.
while (cur_bits > 0) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
flush_char(outs);
}
}
--- END ---
--- FUNCTION SOURCE (char_out) id{60,1} ---
(c, outs) {
accum[a_count++] = c;
if (a_count >= 254) flush_char(outs);
}
--- END ---
INLINE (char_out) id{60,1} AS 1 AT <0:192>
--- FUNCTION SOURCE (flush_char) id{60,2} ---
(outs) {
if (a_count > 0) {
outs.writeByte(a_count);
outs.writeBytes(accum, 0, a_count);
a_count = 0;
}
}
--- END ---
INLINE (flush_char) id{60,2} AS 2 AT <1:62>
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{60,3} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{60,3} AS 3 AT <2:43>
--- FUNCTION SOURCE (ByteCapacitor.writeBytes) id{60,4} ---
(array, offset, length) {
for (var l = length || array.length, i = offset || 0; i < l; i++) {
this.writeByte(array[i]);
}
}
--- END ---
INLINE (ByteCapacitor.writeBytes) id{60,4} AS 4 AT <2:74>
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{60,5} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{60,5} AS 5 AT <4:105>
--- FUNCTION SOURCE (MAXCODE) id{60,6} ---
(n_bits) {
return (1 << n_bits) - 1;
}
--- END ---
INLINE (MAXCODE) id{60,6} AS 6 AT <0:631>
[deoptimizing (DEOPT soft): begin 0x7bbfe1c9c79 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> (opt #60) @36, FP to SP delta: 72]
;;; deoptimize at 0_599: Insufficient type feedback for RHS of binary operation
reading input frame output => node=3, args=268, height=1; inputs:
0: 0x7bbfe1c9c79 ; (frame function) 0x7bbfe1c9c79 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)>
1: 0x36cdc0ec8a59 ; [fp + 32] 0x36cdc0ec8a59 <JS Global Object>
2: 0x64500000000 ; [fp + 24] 1605
3: 0x3ed23a8fcf31 ; r8 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
4: 0x7bbfe1c9949 ; rax 0x7bbfe1c9949 <FixedArray[28]>
translating frame output => node=268, height=0
0x7ffc654cd2f8: [top + 48] <- 0x36cdc0ec8a59 ; 0x36cdc0ec8a59 <JS Global Object> (input #1)
0x7ffc654cd2f0: [top + 40] <- 0x64500000000 ; 1605 (input #2)
0x7ffc654cd2e8: [top + 32] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #3)
0x7ffc654cd2e0: [top + 24] <- 0x376e6ff545c4 ; caller's pc
0x7ffc654cd2d8: [top + 16] <- 0x7ffc654cd3b0 ; caller's fp
0x7ffc654cd2d0: [top + 8] <- 0x7bbfe1c9949 ; context 0x7bbfe1c9949 <FixedArray[28]> (input #4)
0x7ffc654cd2c8: [top + 0] <- 0x7bbfe1c9c79 ; function 0x7bbfe1c9c79 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> (input #0)
[deoptimizing (soft): end 0x7bbfe1c9c79 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> @36 => node=268, pc=0x376e6ff4f8ca, state=NO_REGISTERS, alignment=no padding, took 0.034 ms]
--- FUNCTION SOURCE (output) id{61,0} ---
(code, outs) {
cur_accum &= masks[cur_bits];
if (cur_bits > 0) cur_accum |= (code << cur_bits);
else cur_accum = code;
cur_bits += n_bits;
while (cur_bits >= 8) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg) {
if (clear_flg) {
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
} else {
++n_bits;
if (n_bits == BITS) maxcode = 1 << BITS;
else maxcode = MAXCODE(n_bits);
}
}
if (code == EOFCode) {
// At EOF, write the rest of the buffer.
while (cur_bits > 0) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
flush_char(outs);
}
}
--- END ---
--- FUNCTION SOURCE (char_out) id{61,1} ---
(c, outs) {
accum[a_count++] = c;
if (a_count >= 254) flush_char(outs);
}
--- END ---
INLINE (char_out) id{61,1} AS 1 AT <0:192>
--- FUNCTION SOURCE (flush_char) id{61,2} ---
(outs) {
if (a_count > 0) {
outs.writeByte(a_count);
outs.writeBytes(accum, 0, a_count);
a_count = 0;
}
}
--- END ---
INLINE (flush_char) id{61,2} AS 2 AT <1:62>
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{61,3} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{61,3} AS 3 AT <2:43>
--- FUNCTION SOURCE (ByteCapacitor.writeBytes) id{61,4} ---
(array, offset, length) {
for (var l = length || array.length, i = offset || 0; i < l; i++) {
this.writeByte(array[i]);
}
}
--- END ---
INLINE (ByteCapacitor.writeBytes) id{61,4} AS 4 AT <2:74>
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{61,5} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{61,5} AS 5 AT <4:105>
--- FUNCTION SOURCE (MAXCODE) id{61,6} ---
(n_bits) {
return (1 << n_bits) - 1;
}
--- END ---
INLINE (MAXCODE) id{61,6} AS 6 AT <0:631>
[deoptimizing (DEOPT soft): begin 0x7bbfe1c9c79 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> (opt #61) @40, FP to SP delta: 72]
;;; deoptimize at 0_759: Insufficient type feedback for combined type of binary operation
reading input frame output => node=3, args=329, height=1; inputs:
0: 0x7bbfe1c9c79 ; (frame function) 0x7bbfe1c9c79 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)>
1: 0x36cdc0e04131 ; [fp + 32] 0x36cdc0e04131 <undefined>
2: 0x10100000000 ; [fp + 24] 257
3: 0x3ed23a8fcf31 ; [fp + 16] 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
4: 0x7bbfe1c9949 ; rbx 0x7bbfe1c9949 <FixedArray[28]>
translating frame output => node=329, height=0
0x7ffc654cd2f8: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd2f0: [top + 40] <- 0x10100000000 ; 257 (input #2)
0x7ffc654cd2e8: [top + 32] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #3)
0x7ffc654cd2e0: [top + 24] <- 0x376e6ff547eb ; caller's pc
0x7ffc654cd2d8: [top + 16] <- 0x7ffc654cd3b0 ; caller's fp
0x7ffc654cd2d0: [top + 8] <- 0x7bbfe1c9949 ; context 0x7bbfe1c9949 <FixedArray[28]> (input #4)
0x7ffc654cd2c8: [top + 0] <- 0x7bbfe1c9c79 ; function 0x7bbfe1c9c79 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> (input #0)
[deoptimizing (soft): end 0x7bbfe1c9c79 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> @40 => node=329, pc=0x376e6ff4fb90, state=NO_REGISTERS, alignment=no padding, took 0.034 ms]
--- FUNCTION SOURCE (Float64Array) id{62,0} ---
(O,P,Q){
if(%_IsConstructCall()){
if((%_ClassOf(O)==='ArrayBuffer')||(%_ClassOf(O)==='SharedArrayBuffer')){
Float64ArrayConstructByArrayBuffer(this,O,P,Q);
}else if((typeof(O)==='number')||(typeof(O)==='string')||
(typeof(O)==='boolean')||(O===(void 0))){
Float64ArrayConstructByLength(this,O);
}else{
var J=O[symbolIterator];
if((J===(void 0))||J===$arrayValues){
Float64ArrayConstructByArrayLike(this,O);
}else{
Float64ArrayConstructByIterable(this,O,J);
}
}
}else{
throw MakeTypeError(20,"Float64Array")
}
}
--- END ---
--- FUNCTION SOURCE (learn) id{63,0} ---
() {
var i;
var lengthcount = pixels.length;
var alphadec = 30 + ((samplefac - 1) / 3);
var samplepixels = lengthcount / (3 * samplefac);
var delta = ~~(samplepixels / ncycles);
var alpha = initalpha;
var radius = initradius;
var rad = radius >> radiusbiasshift;
if (rad <= 1) rad = 0;
for (i = 0; i < rad; i++)
radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));
var step;
if (lengthcount < minpicturebytes) {
samplefac = 1;
step = 3;
} else if ((lengthcount % prime1) !== 0) {
step = 3 * prime1;
} else if ((lengthcount % prime2) !== 0) {
step = 3 * prime2;
} else if ((lengthcount % prime3) !== 0) {
step = 3 * prime3;
} else {
step = 3 * prime4;
}
var b, g, r, j;
var pix = 0; // current pixel
i = 0;
while (i < samplepixels) {
b = (pixels[pix] & 0xff) << netbiasshift;
g = (pixels[pix + 1] & 0xff) << netbiasshift;
r = (pixels[pix + 2] & 0xff) << netbiasshift;
j = contest(b, g, r);
altersingle(alpha, j, b, g, r);
if (rad !== 0) alterneigh(rad, j, b, g, r); // alter neighbours
pix += step;
if (pix >= lengthcount) pix -= lengthcount;
i++;
if (delta === 0) delta = 1;
if (i % delta === 0) {
alpha -= alpha / alphadec;
radius -= radius / radiusdec;
rad = radius >> radiusbiasshift;
if (rad <= 1) rad = 0;
for (j = 0; j < rad; j++)
radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
}
}
}
--- END ---
--- FUNCTION SOURCE (inxbuild) id{64,0} ---
() {
var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; // index on g
// find smallest in i..netsize-1
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) { // index on g
smallpos = j;
smallval = q[1]; // index on g
}
}
q = network[smallpos];
// swap p (i) and q (smallpos) entries
if (i != smallpos) {
j = q[0]; q[0] = p[0]; p[0] = j;
j = q[1]; q[1] = p[1]; p[1] = j;
j = q[2]; q[2] = p[2]; p[2] = j;
j = q[3]; q[3] = p[3]; p[3] = j;
}
// smallval entry is now in position i
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++)
netindex[j] = i;
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++)
netindex[j] = maxnetpos; // really 256
}
--- END ---
--- FUNCTION SOURCE (GIFEncoder.analyzePixels) id{65,0} ---
() {
var len = this.pixels.length;
var nPix = len / 3;
// TODO: Re-use indexedPixels
this.indexedPixels = new Uint8Array(nPix);
var imgq = new NeuQuant(this.pixels, this.sample);
imgq.buildColormap(); // create reduced palette
this.colorTab = imgq.getColormap();
// map image pixels to new palette
var k = 0;
for (var j = 0; j < nPix; j++) {
var index = imgq.lookupRGB(
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff
);
this.usedEntry[index] = true;
this.indexedPixels[j] = index;
}
this.pixels = null;
this.colorDepth = 8;
this.palSize = 7;
// get closest match to transparent color if specified
if (this.transparent !== null) {
this.transIndex = this.findClosest(this.transparent);
}
}
--- END ---
--- FUNCTION SOURCE (getColormap) id{65,1} ---
() {
var map = [];
var index = [];
for (var i = 0; i < netsize; i++)
index[network[i][3]] = i;
var k = 0;
for (var l = 0; l < netsize; l++) {
var j = index[l];
map[k++] = (network[j][0]);
map[k++] = (network[j][1]);
map[k++] = (network[j][2]);
}
return map;
}
--- END ---
INLINE (getColormap) id{65,1} AS 1 AT <0:264>
[deoptimizing (DEOPT eager): begin 0x2ac96395d1e1 <JS Function ByteCapacitor.writeByte (SharedFunctionInfo 0x2ac96394aca1)> (opt #54) @3, FP to SP delta: 24]
;;; deoptimize at 0_20: wrong map
reading input frame ByteCapacitor.writeByte => node=2, args=3, height=1; inputs:
0: 0x2ac96395d1e1 ; (frame function) 0x2ac96395d1e1 <JS Function ByteCapacitor.writeByte (SharedFunctionInfo 0x2ac96394aca1)>
1: 0x3ed23a8fcf31 ; rbx 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
2: 0x2100000000 ; [fp + 16] 33
3: 0x100fecf7fb11 ; [fp - 24] 0x100fecf7fb11 <FixedArray[8]>
translating frame ByteCapacitor.writeByte => node=3, height=0
0x7ffc654cd400: [top + 40] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #1)
0x7ffc654cd3f8: [top + 32] <- 0x2100000000 ; 33 (input #2)
0x7ffc654cd3f0: [top + 24] <- 0x376e6ff4cf7a ; caller's pc
0x7ffc654cd3e8: [top + 16] <- 0x7ffc654cd430 ; caller's fp
0x7ffc654cd3e0: [top + 8] <- 0x100fecf7fb11 ; context 0x100fecf7fb11 <FixedArray[8]> (input #3)
0x7ffc654cd3d8: [top + 0] <- 0x2ac96395d1e1 ; function 0x2ac96395d1e1 <JS Function ByteCapacitor.writeByte (SharedFunctionInfo 0x2ac96394aca1)> (input #0)
[deoptimizing (eager): end 0x2ac96395d1e1 <JS Function ByteCapacitor.writeByte (SharedFunctionInfo 0x2ac96394aca1)> @3 => node=3, pc=0x376e6ff38cde, state=NO_REGISTERS, alignment=no padding, took 0.043 ms]
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{66,0} ---
(val) {
this.data.push(val);
}
--- END ---
[deoptimizing (DEOPT eager): begin 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (opt #59) @25, FP to SP delta: 176]
;;; deoptimize at 0_695: value mismatch
reading input frame compress => node=3, args=274, height=8; inputs:
0: 0x7bbfe085861 ; (frame function) 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)>
1: 0x36cdc0e04131 ; r9 0x36cdc0e04131 <undefined>
2: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
3: 0x3ed23a8fcf31 ; r8 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
4: 0x7bbfe085699 ; rsi 0x7bbfe085699 <FixedArray[28]>
5: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
6: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
7: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
8: 329 ; rdx
9: 0x36cdc0e04131 ; (literal 4) 0x36cdc0e04131 <undefined>
10: 5003 ; rbx
11: 4 ; (int) [fp - 120]
translating frame compress => node=274, height=56
0x7ffc654cd3d0: [top + 104] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd3c8: [top + 96] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #2)
0x7ffc654cd3c0: [top + 88] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #3)
0x7ffc654cd3b8: [top + 80] <- 0x376e6ff4e19e ; caller's pc
0x7ffc654cd3b0: [top + 72] <- 0x7ffc654cd3f0 ; caller's fp
0x7ffc654cd3a8: [top + 64] <- 0x7bbfe085699 ; context 0x7bbfe085699 <FixedArray[28]> (input #4)
0x7ffc654cd3a0: [top + 56] <- 0x7bbfe085861 ; function 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (input #0)
0x7ffc654cd398: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #5)
0x7ffc654cd390: [top + 40] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd388: [top + 32] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #7)
0x7ffc654cd380: [top + 24] <- 0x14900000000 ; 329 (input #8)
0x7ffc654cd378: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #9)
0x7ffc654cd370: [top + 8] <- 0x138b00000000 ; 5003 (input #10)
0x7ffc654cd368: [top + 0] <- 0x400000000 ; 4 (input #11)
[deoptimizing (eager): end 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> @25 => node=274, pc=0x376e6ff4ed15, state=NO_REGISTERS, alignment=no padding, took 0.045 ms]
--- FUNCTION SOURCE (compress) id{67,0} ---
(init_bits, outs) {
var fcode, c, i, ent, disp, hsize_reg, hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = nextPixel();
hshift = 0;
for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = HSIZE;
cl_hash(hsize_reg); // clear hash table
output(ClearCode, outs);
outer_loop: while ((c = nextPixel()) != EOF) {
fcode = (c << BITS) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] === fcode) {
ent = codetab[i];
continue;
} else if (htab[i] >= 0) { // non-empty slot
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i === 0) disp = 1;
do {
if ((i -= disp) < 0) i += hsize_reg;
if (htab[i] === fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < 1 << BITS) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
} else {
cl_block(outs);
}
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
}
--- END ---
--- FUNCTION SOURCE (cl_block) id{67,1} ---
(outs) {
cl_hash(HSIZE);
free_ent = ClearCode + 2;
clear_flg = true;
output(ClearCode, outs);
}
--- END ---
INLINE (cl_block) id{67,1} AS 1 AT <0:1405>
--- FUNCTION SOURCE (cl_hash) id{67,2} ---
(hsize) {
for (var i = 0; i < hsize; ++i) htab[i] = -1;
}
--- END ---
INLINE (cl_hash) id{67,2} AS 2 AT <1:13>
--- FUNCTION SOURCE (ByteCapacitor.writeBytes) id{68,0} ---
(array, offset, length) {
for (var l = length || array.length, i = offset || 0; i < l; i++) {
this.writeByte(array[i]);
}
}
--- END ---
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{68,1} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{68,1} AS 1 AT <0:105>
--- FUNCTION SOURCE (output) id{69,0} ---
(code, outs) {
cur_accum &= masks[cur_bits];
if (cur_bits > 0) cur_accum |= (code << cur_bits);
else cur_accum = code;
cur_bits += n_bits;
while (cur_bits >= 8) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg) {
if (clear_flg) {
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
} else {
++n_bits;
if (n_bits == BITS) maxcode = 1 << BITS;
else maxcode = MAXCODE(n_bits);
}
}
if (code == EOFCode) {
// At EOF, write the rest of the buffer.
while (cur_bits > 0) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
flush_char(outs);
}
}
--- END ---
--- FUNCTION SOURCE (MAXCODE) id{69,1} ---
(n_bits) {
return (1 << n_bits) - 1;
}
--- END ---
INLINE (MAXCODE) id{69,1} AS 1 AT <0:468>
--- FUNCTION SOURCE (char_out) id{69,2} ---
(c, outs) {
accum[a_count++] = c;
if (a_count >= 254) flush_char(outs);
}
--- END ---
INLINE (char_out) id{69,2} AS 2 AT <0:774>
--- FUNCTION SOURCE (flush_char) id{69,3} ---
(outs) {
if (a_count > 0) {
outs.writeByte(a_count);
outs.writeBytes(accum, 0, a_count);
a_count = 0;
}
}
--- END ---
INLINE (flush_char) id{69,3} AS 3 AT <0:872>
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{69,4} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{69,4} AS 4 AT <3:43>
--- FUNCTION SOURCE (ByteCapacitor.writeBytes) id{69,5} ---
(array, offset, length) {
for (var l = length || array.length, i = offset || 0; i < l; i++) {
this.writeByte(array[i]);
}
}
--- END ---
INLINE (ByteCapacitor.writeBytes) id{69,5} AS 5 AT <3:74>
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{69,6} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{69,6} AS 6 AT <5:105>
[deoptimizing (DEOPT eager): begin 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (opt #67) @31, FP to SP delta: 192]
;;; deoptimize at 0_1405: value mismatch
reading input frame compress => node=3, args=586, height=8; inputs:
0: 0x7bbfe085861 ; (frame function) 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)>
1: 0x36cdc0e04131 ; [fp - 152] 0x36cdc0e04131 <undefined>
2: 0x36cdc0e04131 ; (literal 3) 0x36cdc0e04131 <undefined>
3: 0x3ed23a8fcf31 ; [fp - 144] 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
4: 0x7bbfe085699 ; rax 0x7bbfe085699 <FixedArray[28]>
5: 0x36cdc0e04131 ; (literal 3) 0x36cdc0e04131 <undefined>
6: 0x36cdc0e04131 ; (literal 3) 0x36cdc0e04131 <undefined>
7: 0x36cdc0e04131 ; (literal 3) 0x36cdc0e04131 <undefined>
8: 0x4e00000000 ; [fp - 168] 78
9: 0x36cdc0e04131 ; (literal 3) 0x36cdc0e04131 <undefined>
10: 5003 ; (int) [fp - 128]
11: 4 ; (int) [fp - 120]
translating frame compress => node=586, height=56
0x7ffc654cd3d0: [top + 104] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd3c8: [top + 96] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #2)
0x7ffc654cd3c0: [top + 88] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #3)
0x7ffc654cd3b8: [top + 80] <- 0x376e6ff4e19e ; caller's pc
0x7ffc654cd3b0: [top + 72] <- 0x7ffc654cd3f0 ; caller's fp
0x7ffc654cd3a8: [top + 64] <- 0x7bbfe085699 ; context 0x7bbfe085699 <FixedArray[28]> (input #4)
0x7ffc654cd3a0: [top + 56] <- 0x7bbfe085861 ; function 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (input #0)
0x7ffc654cd398: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #5)
0x7ffc654cd390: [top + 40] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd388: [top + 32] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #7)
0x7ffc654cd380: [top + 24] <- 0x4e00000000 ; 78 (input #8)
0x7ffc654cd378: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #9)
0x7ffc654cd370: [top + 8] <- 0x138b00000000 ; 5003 (input #10)
0x7ffc654cd368: [top + 0] <- 0x400000000 ; 4 (input #11)
[deoptimizing (eager): end 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> @31 => node=586, pc=0x376e6ff4ecbc, state=NO_REGISTERS, alignment=no padding, took 0.046 ms]
[deoptimizing (DEOPT eager): begin 0x7bbfe0859c9 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> (opt #69) @15, FP to SP delta: 96]
;;; deoptimize at 0_468: value mismatch
reading input frame output => node=3, args=237, height=4; inputs:
0: 0x7bbfe0859c9 ; (frame function) 0x7bbfe0859c9 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)>
1: 0x36cdc0e04131 ; [fp + 32] 0x36cdc0e04131 <undefined>
2: 0x10000000000 ; [fp + 24] 256
3: 0x3ed23a8fcf31 ; [fp + 16] 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
4: 0x7bbfe085699 ; rbx 0x7bbfe085699 <FixedArray[28]>
5: 0x7bbfe085939 ; rsi 0x7bbfe085939 <JS Function MAXCODE (SharedFunctionInfo 0xc518ec2e299)>
6: 0x36cdc0e04131 ; (literal 6) 0x36cdc0e04131 <undefined>
7: 0x900000000 ; rdi 9
translating frame output => node=237, height=24
0x7ffc654cd320: [top + 72] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd318: [top + 64] <- 0x10000000000 ; 256 (input #2)
0x7ffc654cd310: [top + 56] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #3)
0x7ffc654cd308: [top + 48] <- 0x376e6ff57e0d ; caller's pc
0x7ffc654cd300: [top + 40] <- 0x7ffc654cd340 ; caller's fp
0x7ffc654cd2f8: [top + 32] <- 0x7bbfe085699 ; context 0x7bbfe085699 <FixedArray[28]> (input #4)
0x7ffc654cd2f0: [top + 24] <- 0x7bbfe0859c9 ; function 0x7bbfe0859c9 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> (input #0)
0x7ffc654cd2e8: [top + 16] <- 0x7bbfe085939 ; 0x7bbfe085939 <JS Function MAXCODE (SharedFunctionInfo 0xc518ec2e299)> (input #5)
0x7ffc654cd2e0: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd2d8: [top + 0] <- 0x900000000 ; 9 (input #7)
[deoptimizing (eager): end 0x7bbfe0859c9 <JS Function output (SharedFunctionInfo 0xc518ec2e3e9)> @15 => node=237, pc=0x376e6ff4f791, state=TOS_REG, alignment=no padding, took 0.034 ms]
--- FUNCTION SOURCE (compress) id{70,0} ---
(init_bits, outs) {
var fcode, c, i, ent, disp, hsize_reg, hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = nextPixel();
hshift = 0;
for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = HSIZE;
cl_hash(hsize_reg); // clear hash table
output(ClearCode, outs);
outer_loop: while ((c = nextPixel()) != EOF) {
fcode = (c << BITS) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] === fcode) {
ent = codetab[i];
continue;
} else if (htab[i] >= 0) { // non-empty slot
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i === 0) disp = 1;
do {
if ((i -= disp) < 0) i += hsize_reg;
if (htab[i] === fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < 1 << BITS) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
} else {
cl_block(outs);
}
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
}
--- END ---
[deoptimizing (DEOPT eager): begin 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (opt #70) @44, FP to SP delta: 184]
;;; deoptimize at 0_1471: value mismatch
reading input frame compress => node=3, args=275, height=8; inputs:
0: 0x7bbfe085861 ; (frame function) 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)>
1: 0x36cdc0e04131 ; [fp - 152] 0x36cdc0e04131 <undefined>
2: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
3: 0x3ed23a8fcf31 ; [fp - 144] 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
4: 0x7bbfe085699 ; rax 0x7bbfe085699 <FixedArray[28]>
5: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
6: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
7: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
8: 1137 ; rsi
9: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
10: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
11: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
translating frame compress => node=275, height=56
0x7ffc654cd3d0: [top + 104] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #1)
0x7ffc654cd3c8: [top + 96] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #2)
0x7ffc654cd3c0: [top + 88] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #3)
0x7ffc654cd3b8: [top + 80] <- 0x376e6ff4e19e ; caller's pc
0x7ffc654cd3b0: [top + 72] <- 0x7ffc654cd3f0 ; caller's fp
0x7ffc654cd3a8: [top + 64] <- 0x7bbfe085699 ; context 0x7bbfe085699 <FixedArray[28]> (input #4)
0x7ffc654cd3a0: [top + 56] <- 0x7bbfe085861 ; function 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> (input #0)
0x7ffc654cd398: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #5)
0x7ffc654cd390: [top + 40] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd388: [top + 32] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #7)
0x7ffc654cd380: [top + 24] <- 0x47100000000 ; 1137 (input #8)
0x7ffc654cd378: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #9)
0x7ffc654cd370: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #10)
0x7ffc654cd368: [top + 0] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #11)
[deoptimizing (eager): end 0x7bbfe085861 <JS Function compress (SharedFunctionInfo 0xc518ec2e0a1)> @44 => node=275, pc=0x376e6ff4ed1a, state=NO_REGISTERS, alignment=no padding, took 0.047 ms]
[marking dependent code 0x376e6ff61d21 (opt #65) for deoptimization, reason: prototype-check]
[deoptimize marked code in all contexts]
[deoptimizer unlinked: GIFEncoder.analyzePixels / 2ac96395d689]
[deoptimizing (DEOPT lazy): begin 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> (opt #65) @9, FP to SP delta: 152]
reading input frame GIFEncoder.analyzePixels => node=1, args=99, height=8; inputs:
0: 0x2ac96395d689 ; (frame function) 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)>
1: 0x3ed23a8fcf31 ; [fp + 16] 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
2: 0x100fecf7fb11 ; [fp - 72] 0x100fecf7fb11 <FixedArray[8]>
3: 0x36cdc0e04131 ; (literal 2) 0x36cdc0e04131 <undefined>
4: 360000 ; (int) [fp - 80]
5: 0x36cdc0e04131 ; (literal 2) 0x36cdc0e04131 <undefined>
6: 0x36cdc0e04131 ; (literal 2) 0x36cdc0e04131 <undefined>
7: 0x36cdc0e04131 ; (literal 2) 0x36cdc0e04131 <undefined>
8: 0x36cdc0e04131 ; (literal 2) 0x36cdc0e04131 <undefined>
9: 0x7bbfe0db2a9 ; rax 0x7bbfe0db2a9 <a NeuQuant with map 0x3d4eb9d404e1>
translating frame GIFEncoder.analyzePixels => node=99, height=56
0x7ffc654cd438: [top + 88] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #1)
0x7ffc654cd430: [top + 80] <- 0x376e6ff3e4d3 ; caller's pc
0x7ffc654cd428: [top + 72] <- 0x7ffc654cd458 ; caller's fp
0x7ffc654cd420: [top + 64] <- 0x100fecf7fb11 ; context 0x100fecf7fb11 <FixedArray[8]> (input #2)
0x7ffc654cd418: [top + 56] <- 0x2ac96395d689 ; function 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> (input #0)
0x7ffc654cd410: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #3)
0x7ffc654cd408: [top + 40] <- 0x57e4000000000 ; 360000 (input #4)
0x7ffc654cd400: [top + 32] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #5)
0x7ffc654cd3f8: [top + 24] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd3f0: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #7)
0x7ffc654cd3e8: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #8)
0x7ffc654cd3e0: [top + 0] <- 0x7bbfe0db2a9 ; 0x7bbfe0db2a9 <a NeuQuant with map 0x3d4eb9d404e1> (input #9)
[deoptimizing (lazy): end 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> @9 => node=99, pc=0x376e6ff3fab0, state=TOS_REG, alignment=no padding, took 0.043 ms]
--- FUNCTION SOURCE (GIFEncoder.analyzePixels) id{71,0} ---
() {
var len = this.pixels.length;
var nPix = len / 3;
// TODO: Re-use indexedPixels
this.indexedPixels = new Uint8Array(nPix);
var imgq = new NeuQuant(this.pixels, this.sample);
imgq.buildColormap(); // create reduced palette
this.colorTab = imgq.getColormap();
// map image pixels to new palette
var k = 0;
for (var j = 0; j < nPix; j++) {
var index = imgq.lookupRGB(
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff
);
this.usedEntry[index] = true;
this.indexedPixels[j] = index;
}
this.pixels = null;
this.colorDepth = 8;
this.palSize = 7;
// get closest match to transparent color if specified
if (this.transparent !== null) {
this.transIndex = this.findClosest(this.transparent);
}
}
--- END ---
--- FUNCTION SOURCE (compress) id{72,0} ---
(init_bits, outs) {
var fcode, c, i, ent, disp, hsize_reg, hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = nextPixel();
hshift = 0;
for (fcode = HSIZE; fcode < 65536; fcode *= 2) ++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = HSIZE;
cl_hash(hsize_reg); // clear hash table
output(ClearCode, outs);
outer_loop: while ((c = nextPixel()) != EOF) {
fcode = (c << BITS) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] === fcode) {
ent = codetab[i];
continue;
} else if (htab[i] >= 0) { // non-empty slot
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i === 0) disp = 1;
do {
if ((i -= disp) < 0) i += hsize_reg;
if (htab[i] === fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < 1 << BITS) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
} else {
cl_block(outs);
}
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
}
--- END ---
--- FUNCTION SOURCE (output) id{73,0} ---
(code, outs) {
cur_accum &= masks[cur_bits];
if (cur_bits > 0) cur_accum |= (code << cur_bits);
else cur_accum = code;
cur_bits += n_bits;
while (cur_bits >= 8) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg) {
if (clear_flg) {
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
} else {
++n_bits;
if (n_bits == BITS) maxcode = 1 << BITS;
else maxcode = MAXCODE(n_bits);
}
}
if (code == EOFCode) {
// At EOF, write the rest of the buffer.
while (cur_bits > 0) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
flush_char(outs);
}
}
--- END ---
--- FUNCTION SOURCE (cl_hash) id{74,0} ---
(hsize) {
for (var i = 0; i < hsize; ++i) htab[i] = -1;
}
--- END ---
[marking dependent code 0x376e6ff676a1 (opt #71) for deoptimization, reason: prototype-check]
[deoptimize marked code in all contexts]
[deoptimizer unlinked: GIFEncoder.analyzePixels / 2ac96395d689]
[deoptimizing (DEOPT lazy): begin 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> (opt #71) @9, FP to SP delta: 136]
reading input frame GIFEncoder.analyzePixels => node=1, args=99, height=8; inputs:
0: 0x2ac96395d689 ; (frame function) 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)>
1: 0x3ed23a8fcf31 ; [fp + 16] 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9>
2: 0x100fecf7fb11 ; [fp - 72] 0x100fecf7fb11 <FixedArray[8]>
3: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
4: 360000 ; (int) [fp - 80]
5: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
6: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
7: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
8: 0x36cdc0e04131 ; (literal 1) 0x36cdc0e04131 <undefined>
9: 0x7bbff37b521 ; rax 0x7bbff37b521 <a NeuQuant with map 0x3d4eb9d40539>
translating frame GIFEncoder.analyzePixels => node=99, height=56
0x7ffc654cd438: [top + 88] <- 0x3ed23a8fcf31 ; 0x3ed23a8fcf31 <a GIFEncoder with map 0x3d4eb9d454f9> (input #1)
0x7ffc654cd430: [top + 80] <- 0x376e6ff3e4d3 ; caller's pc
0x7ffc654cd428: [top + 72] <- 0x7ffc654cd458 ; caller's fp
0x7ffc654cd420: [top + 64] <- 0x100fecf7fb11 ; context 0x100fecf7fb11 <FixedArray[8]> (input #2)
0x7ffc654cd418: [top + 56] <- 0x2ac96395d689 ; function 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> (input #0)
0x7ffc654cd410: [top + 48] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #3)
0x7ffc654cd408: [top + 40] <- 0x57e4000000000 ; 360000 (input #4)
0x7ffc654cd400: [top + 32] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #5)
0x7ffc654cd3f8: [top + 24] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #6)
0x7ffc654cd3f0: [top + 16] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #7)
0x7ffc654cd3e8: [top + 8] <- 0x36cdc0e04131 ; 0x36cdc0e04131 <undefined> (input #8)
0x7ffc654cd3e0: [top + 0] <- 0x7bbff37b521 ; 0x7bbff37b521 <a NeuQuant with map 0x3d4eb9d40539> (input #9)
[deoptimizing (lazy): end 0x2ac96395d689 <JS Function GIFEncoder.analyzePixels (SharedFunctionInfo 0x2ac96394b679)> @9 => node=99, pc=0x376e6ff3fab0, state=TOS_REG, alignment=no padding, took 0.051 ms]
--- FUNCTION SOURCE (GIFEncoder.analyzePixels) id{75,0} ---
() {
var len = this.pixels.length;
var nPix = len / 3;
// TODO: Re-use indexedPixels
this.indexedPixels = new Uint8Array(nPix);
var imgq = new NeuQuant(this.pixels, this.sample);
imgq.buildColormap(); // create reduced palette
this.colorTab = imgq.getColormap();
// map image pixels to new palette
var k = 0;
for (var j = 0; j < nPix; j++) {
var index = imgq.lookupRGB(
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff,
this.pixels[k++] & 0xff
);
this.usedEntry[index] = true;
this.indexedPixels[j] = index;
}
this.pixels = null;
this.colorDepth = 8;
this.palSize = 7;
// get closest match to transparent color if specified
if (this.transparent !== null) {
this.transIndex = this.findClosest(this.transparent);
}
}
--- END ---
--- FUNCTION SOURCE (flush_char) id{76,0} ---
(outs) {
if (a_count > 0) {
outs.writeByte(a_count);
outs.writeBytes(accum, 0, a_count);
a_count = 0;
}
}
--- END ---
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{76,1} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{76,1} AS 1 AT <0:43>
--- FUNCTION SOURCE (ByteCapacitor.writeBytes) id{76,2} ---
(array, offset, length) {
for (var l = length || array.length, i = offset || 0; i < l; i++) {
this.writeByte(array[i]);
}
}
--- END ---
INLINE (ByteCapacitor.writeBytes) id{76,2} AS 2 AT <0:74>
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{76,3} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{76,3} AS 3 AT <2:105>
--- FUNCTION SOURCE (Float64ArrayConstructByArrayLike) id{77,0} ---
(v,F){
var y=F.length;
var D=$toPositiveInteger(y,139);
if(D>%_MaxSmi()){
throw MakeRangeError(139);
}
var G=false;
var E=D*8;
if(E<=%_TypedArrayMaxSizeInHeap()){
%_TypedArrayInitialize(v,8,null,0,E,false);
}else{
G=
%TypedArrayInitializeFromArrayLike(v,8,F,D);
}
if(!G){
for(var H=0;H<D;H++){
v[H]=F[H];
}
}
}
--- END ---
--- FUNCTION SOURCE (Int32ArrayConstructByLength) id{78,0} ---
(v,y){
var D=(y===(void 0))?
0:$toPositiveInteger(y,139);
if(D>%_MaxSmi()){
throw MakeRangeError(139);
}
var E=D*4;
if(E>%_TypedArrayMaxSizeInHeap()){
var w=new d(E);
%_TypedArrayInitialize(v,6,w,0,E,true);
}else{
%_TypedArrayInitialize(v,6,null,0,E,true);
}
}
--- END ---
--- FUNCTION SOURCE (debugs.(anonymous function)) id{79,0} ---
() {}
--- END ---
--- FUNCTION SOURCE (GIFEncoder.writeShort) id{80,0} ---
(pValue) {
this.writeByte(pValue & 0xFF);
this.writeByte((pValue >> 8) & 0xFF);
}
--- END ---
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{80,1} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{80,1} AS 1 AT <0:18>
--- FUNCTION SOURCE (ByteCapacitor.writeByte) id{80,2} ---
(val) {
this.data.push(val);
}
--- END ---
INLINE (ByteCapacitor.writeByte) id{80,2} AS 2 AT <0:51>
--- FUNCTION SOURCE (isNull) id{81,0} ---
(arg) {
return arg === null;
}
--- END ---
--- FUNCTION SOURCE (MAXCODE) id{82,0} ---
(n_bits) {
return (1 << n_bits) - 1;
}
--- END ---
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r13
push %r8
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x1c4d1, %r11
clflush (%r11)
nop
add %r13, %r13
movups (%r11), %xmm7
vpextrq $1, %xmm7, %r12
nop
nop
and $22412, %r8
lea addresses_normal_ht+0xed11, %r12
nop
cmp %r11, %r11
mov (%r12), %esi
nop
nop
nop
xor %r12, %r12
lea addresses_A_ht+0x18811, %rsi
lea addresses_A_ht+0x16761, %rdi
nop
nop
dec %rax
mov $12, %rcx
rep movsl
nop
xor $56531, %r12
lea addresses_A_ht+0x3411, %r8
nop
nop
nop
cmp %rdi, %rdi
mov (%r8), %r11d
nop
cmp %rax, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r13
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r8
push %rax
push %rdi
push %rdx
// Load
mov $0xca1, %rax
nop
nop
nop
nop
nop
sub $50902, %r10
mov (%rax), %r12d
nop
nop
nop
nop
inc %r10
// Store
mov $0x71, %r10
nop
and $65360, %rdx
movl $0x51525354, (%r10)
nop
nop
nop
nop
nop
sub %rax, %rax
// Store
lea addresses_A+0x1c927, %r10
nop
nop
nop
and $417, %rdx
movb $0x51, (%r10)
nop
nop
nop
nop
nop
cmp $8794, %rdx
// Store
lea addresses_US+0xe611, %r11
nop
and $24951, %r12
movb $0x51, (%r11)
add $41048, %r12
// Store
lea addresses_UC+0x1ea11, %rax
nop
sub $53502, %r12
mov $0x5152535455565758, %r10
movq %r10, (%rax)
cmp %r11, %r11
// Store
lea addresses_US+0xb611, %r8
nop
nop
nop
nop
nop
and $57327, %r11
movw $0x5152, (%r8)
nop
and $26367, %r12
// Load
lea addresses_WT+0x1a938, %rdi
nop
nop
nop
sub $15635, %r12
movups (%rdi), %xmm3
vpextrq $0, %xmm3, %r11
nop
nop
nop
nop
nop
add $29485, %r8
// Store
mov $0xec3, %rdi
nop
nop
nop
nop
and $41309, %r12
movw $0x5152, (%rdi)
nop
nop
add $53838, %r12
// Store
lea addresses_RW+0x12d1, %r11
nop
nop
sub %rdx, %rdx
movl $0x51525354, (%r11)
nop
cmp $3883, %rdx
// Faulty Load
lea addresses_US+0xe611, %r10
and %rdx, %rdx
movups (%r10), %xmm5
vpextrq $1, %xmm5, %rdi
lea oracles, %r10
and $0xff, %rdi
shlq $12, %rdi
mov (%r10,%rdi,1), %rdi
pop %rdx
pop %rdi
pop %rax
pop %r8
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_P', 'AVXalign': False, 'congruent': 4, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'congruent': 5, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 10, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 11, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'congruent': 1, 'size': 2, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 5, 'size': 4, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 6, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 6, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 6, 'size': 4, 'same': False, 'NT': False}}
{'08': 1428, '59': 398, '72': 1, '45': 19000, '00': 717, 'c5': 3, '40': 161, 'f9': 1, '74': 21, 'ff': 90, '25': 9}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 45 00 ff 00 ff 00 00 00 ff 00 ff 00 ff 00 ff 00 ff 00 ff 00 00 ff 00 ff 00 ff 00 ff 00 ff 00 ff 00 00 ff 00 00 ff 00 00 ff 00 ff 00 ff 00 00 ff 00 ff 00 ff 00 00 ff 00 ff 00 00 ff 00 ff 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 08 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45
*/
|
; A299261: Partial sums of A299255.
; 1,8,31,81,168,303,497,760,1103,1537,2072,2719,3489,4392,5439,6641,8008,9551,11281,13208,15343,17697,20280,23103,26177,29512,33119,37009,41192,45679,50481,55608,61071,66881,73048,79583,86497,93800,101503,109617,118152,127119,136529,146392,156719,167521,178808,190591,202881,215688,229023,242897,257320,272303,287857,303992,320719,338049,355992,374559,393761,413608,434111,455281,477128,499663,522897,546840,571503,596897,623032,649919,677569,705992,735199,765201,796008,827631,860081,893368,927503
lpb $0
mov $2,$0
sub $0,1
seq $2,299255 ; Coordination sequence for 3D uniform tiling formed by stacking parallel layers of the 3.3.4.3.4 2D tiling (cf. A219529).
add $1,$2
lpe
add $1,1
mov $0,$1
|
; A274979: Integers of the form m*(m + 7)/8.
; 0,1,15,18,46,51,93,100,156,165,235,246,330,343,441,456,568,585,711,730,870,891,1045,1068,1236,1261,1443,1470,1666,1695,1905,1936,2160,2193,2431,2466,2718,2755,3021,3060,3340,3381,3675,3718,4026,4071,4393,4440,4776,4825,5175,5226,5590,5643,6021,6076,6468,6525,6931,6990,7410,7471,7905,7968,8416,8481,8943,9010,9486,9555,10045,10116,10620,10693,11211,11286,11818,11895,12441,12520,13080,13161,13735,13818,14406,14491,15093,15180,15796,15885,16515,16606,17250,17343,18001,18096,18768,18865,19551,19650,20350,20451,21165,21268,21996,22101,22843,22950,23706,23815,24585,24696,25480,25593,26391,26506,27318,27435,28261,28380,29220,29341,30195,30318,31186,31311,32193,32320,33216,33345,34255,34386,35310,35443,36381,36516,37468,37605,38571,38710,39690,39831,40825,40968,41976,42121,43143,43290,44326,44475,45525,45676,46740,46893,47971,48126,49218,49375,50481,50640,51760,51921,53055,53218,54366,54531,55693,55860,57036,57205,58395,58566,59770,59943,61161,61336,62568,62745,63991,64170,65430,65611,66885,67068,68356,68541,69843,70030,71346,71535,72865,73056,74400,74593,75951,76146,77518,77715,79101,79300,80700,80901,82315,82518,83946,84151,85593,85800,87256,87465,88935,89146,90630,90843,92341,92556,94068,94285,95811,96030,97570,97791,99345,99568,101136,101361,102943,103170,104766,104995,106605,106836,108460,108693,110331,110566,112218,112455,114121,114360,116040,116281,117975,118218,119926,120171,121893,122140,123876,124125
mov $1,$0
mov $2,$0
mov $3,$0
trn $0,1
add $3,1
add $3,$2
lpb $0,1
sub $0,1
trn $0,1
add $3,8
add $1,$3
lpe
|
;RootDir: Dump Win-95 longnames (the brain-dead ~1 style) from the root directory of a floppy to stdout (a la DIR roughly) - will show ~1 name, space, long name (aka "dead name" ie "brain dead")
;Note: Dead names consist of Unicode characters. This program assumes that the high bytes are all 0, and dumps the low bytes only. This could cause odd problems with (1) Chinese/Japanese etc characters; (2) maybe endashes, emdashes, "smart" quotes, etc.
;Eventually, maybe, I'll make a REXX-callable DLL which lists to a stem, same way
;Note: This is all the docs you get, apart from the brief README.TXT. Sorry, but I mainly built this for my own use.
;For a more powerful program, which (unfortunately) doesn't work on FAT12, look for "wir" (pun on "dir" presumably).
;Note: Currently the path is hardcoded into the data segment. To work on a different drive, just change the value of 'path' below. It *must* be a drive letter, a colon, and a null byte.
;This program is open source. If you like it, please send me an email at talldad@kepl.com.au - I'd love to hear from you!
;The version number is the first entry in the data area (immediately before the CR/LF), and consists of:
;1) A one letter code - C for Chris Angelico's version, other people please use other codes.
;2) Three bytes, storing the major, minor, revision components of the version number.
;The latest version of this program should always be available at http://www.kepl.com.au/esstu/RootDir.HTML (on The Esstu Pack).
;The long names are dumped in 13-character blocks (due to the internal structure of a brain-dead long name - 13 characters per directory entry), as follows:
;First block is the DOS name. Eight chars for the base name, space, three for the extension, one more space.
;The rest of the blocks have the long name, 13 bytes at a time. The last block is null-terminated and then seems to be padded with 0xFF's (don't rely on this though).
;Each file name is sent to STDOUT, followed by a CR/LF pair. Hidden files and deleted files are displayed along with everything else.
;This source should compile with nasm (I use 0.98.24), with the Esstu Macros library (s2macros.asm) version 1.1.0 in the parent directory. This is referred to once, in the %include line; change it if required.
;The makefile assumes that nasm is installed as c:\nasm\nasm.exe - correct if wrong.
;Version history:
;1.0.0 - initial release.
;1.0.1 - added this version history, more comments, and a CMD for applying .LONGNAME EAs. Also removed two bugs - the first entry was being ignored, and something was PUSHing more than it POPped.
%include "..\s2macros.asm" ;Handy macros
section _TEXT class=CODE use32 flat
..start: ;Set the entry point for the EXE
main: ;"Ordinary" label to allow local labels (can't have local labels after ..start)
callos2 DosOpen,path,handle,action,0,0,1,1000001101000000b,0 ;Open the drive as a single file
or eax,eax
jnz near .finnoclose ;If error, exit (without closing)
callos2 DosRead,[handle],data,0x20,nwritten ;Read in 32 bytes, and thus get the BIOS Parameter Block
or eax,eax
jnz near .fin ;If error, exit (first closing the file)
;Set EAX to word[data+0x0E]+byte[data+0x10]*word[data+0x16]
;0x0E is the number of sectors in the reserved area; 0x10 is the number of copies of the FAT (usu 2); 0x16 is sectors per FAT.
mov ax,[data+0x0E] ;Yes, AX not EAX - need 16-bit fetch
movzx ecx,byte[data+0x10] ;Get a single byte into a 32-bit register
.loop:
add ax,[data+0x16]
loop .loop
;EAX now has the sector number of the root directory.
movzx ebx,word[data+0x0B] ;Get bytes per sector (a word value) into a dword register
mul ebx ;Multiply EAX*EBX and put the result in EDX:EAX (but since the high words of EAX and EBX should be 0, EDX should end up 0). I could do this with word arithmetic (mul bx), but it's more convenient to have the result in EAX instead of DX:AX.
movzx ecx,word[data+0x11] ;Number of root directory entries
cmp ecx,maxdirents ;Check against the maximum number of directory entries - there's storage sufficient for maxdirents directory entries.
jbe .nomax
mov ecx,maxdirents ;Max out ecx
.nomax:
push ecx ;Store the count of entries, for later
shl ecx,5 ;Multiply by 32 to get number of bytes to read (32 bytes per entry)
push ecx ;Store the number of bytes, for later
;EAX now holds the number of bytes in the pre-directory-entry information, which equals the byte offset at which to start reading. We could set the file pointer to this, but the commented-out call below seems to crash the program.
;callos2 DosSetFilePtr,[handle],eax,0,[newptr] ;There's something wrong with this line.
sub eax,0x20 ;We've already read in 0x20 bytes
callos2 DosRead,[handle],data,eax,nwritten ;So we read in the right number of bytes - the target position minus 20 hex.
or eax,eax
jnz near .fin ;If error, quit
pop ecx ;Get back the number of bytes to read
callos2 DosRead,[handle],data,ecx,nwritten ;And read them
or eax,eax
jnz near .fin ;If error, quit
mov esi,data ;Get a pointer
pop ecx ;And the count
;OK, the main loop.
.getdirent:
cmp byte[esi],0 ;If the first byte of the file name is a null, we've reached the end of the list (DOS standard since v2.0).
jz near .enddirent
cmp byte[esi+0x0B],0x0F ;The extra entries have attribute 0x0F - they're hidden, system, read-only volume labels!
jnz .notdeadname ;If it's not 0x0F, it's not a (brain-)dead name
mov edi,longname ;If it is, we'll get a pointer to the right place.
push ecx ;Save the main loop's ecx - we need another loop here.
movzx ecx,byte[esi] ;This byte is the index number of the entry. 01 for 1st, 02 for 2nd, etc.
test cl,0x40
pushf ;Will use these flags later.
and cl,0x3F ;The _last_ entry (ie tail end of name) has its index 0x40 higher - 0x41, 0x42 or whatever. I'm using this value further down - hence the pushf.
.addedi:
add edi,13 ;Add 13*ecx to edi
loop .addedi
;At this point EDI has a pointer into longname. This pointer is such that filling in all the entries will give a 13-byte hole, then the long name, null-terminated. See below for what the 13-byte header is used for!
;Skip one byte, grab 5 characters, skip 3 bytes, grab 6, skip two, grab two.
push esi ;We need to preserve esi
inc esi ;Skip the first byte
mov ecx,5
.loop1:
lodsw ;Grab a word, store a byte - ignore the high byte of each Unicode character
stosb
loop .loop1
add esi,3
mov ecx,6
.loop2:
lodsw
stosb
loop .loop2
inc esi
inc esi
lodsw
stosb
lodsw
stosb
pop esi ;Restore the main loop's esi
popf ;Get back the flags stored above
jz .notlast
sub edi,longname
mov [nbytes],edi ;Store the number of bytes, if this one had 0x40 on it.
.notlast:
pop ecx ;Restore the main loop's ecx
jmp .endloop ;Skip the notdeadname code
.notdeadname: ;This is a real entry.
mov edi,longname ;Now _here_ we use the first 13 bytes!
push ecx ;Save ecx and esi - we need them.
push esi
mov ecx,8 ;Copy 8 bytes of base name
rep movsb
mov al,' ' ;Add a space
stosb
mov ecx,3 ;Three bytes of extension
rep movsb
stosb ;Another space - AL still has ' '
callos2 DosWrite,1,longname,[nbytes],nwritten ;Send it to STDOUT
say crlf ;And follow it with a CRLF
mov dword[nbytes],13 ;Reset [nbytes] in case the next entry doesn't have a long name
pop esi ;Restore esi and ecx
pop ecx
.endloop: ;Here the two routines finish, and the loop resumes.
add esi,32 ;Point to the next directory entry
dec ecx ;Can't use loop if the target is too high. Could use call for the routines, or slim them down, or something, but I don't feel like it.
jnz near .getdirent
;loop .getdirent
.enddirent:
.finok:
xor eax,eax ;Zero eax to indicate successful termination
.fin:
push eax ;Save eax - if .fin was jmp'd it will have an error code.
callos2 DosClose,[handle] ;Close the file. This returns a value in eax - almost certainly 0.
pop eax ;And restore eax
.finnoclose: ;JMP here to terminate without closing - only used if error on DosOpen.
callos2 DosExit,1,eax ;Exit all threads, return eax
group DGROUP STACK ;This is the only thing in DGROUP. The linker expects this setup, I think
section STACK stack class=STCK use32
resb 32768 ;32KB stack - can increase or decrease as required
section _DATA dword public class=DATA use32 flat
version db "C",1,0,1 ;A "C" for "Chris" signifying my version, then three bytes, major minor revision, storing the version number.
msg crlf,13,10 ;Used in the main loop - 'say crlf'
nwritten dd 0 ;Used by all DosWrites (and DosReads!)
handle dd 0 ;Gets the file handle from DosOpen
action dd 0 ;Gets the open action from DosOpen - ignored.
path db "A:",0 ;The path - can be changed as required.
newptr dd 0 ;From DosSetFilePtr
nbytes dd 13 ;For the longname display
maxdirents equ 224 ;Size of root directory on 1.44MB floppy. The number of entries listed in the boot sector is capped at this value - any further entries will be ignored.
data resb maxdirents*32 ;Big enough to hold the data for maxdirents directory entries
longname resb 20480-($-$$) ;Plenty of space - fill so the _DATA segment is 20KB. Can be shrunk; but in this version don't let the total size of data+longname fall too short - DosRead is used instead of DosSetFilePtr.
|
;--------------------------------------------------------
; File Created by SDCC : free open source ANSI-C Compiler
; Version 4.1.4 #12246 (Mac OS X x86_64)
;--------------------------------------------------------
.module background_5
.optsdcc -mgbz80
;--------------------------------------------------------
; Public variables in this module
;--------------------------------------------------------
.globl _background_5
.globl ___bank_background_5
;--------------------------------------------------------
; special function registers
;--------------------------------------------------------
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
.area _DATA
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
.area _INITIALIZED
;--------------------------------------------------------
; absolute external ram data
;--------------------------------------------------------
.area _DABS (ABS)
;--------------------------------------------------------
; global & static initialisations
;--------------------------------------------------------
.area _HOME
.area _GSINIT
.area _GSFINAL
.area _GSINIT
;--------------------------------------------------------
; Home
;--------------------------------------------------------
.area _HOME
.area _HOME
;--------------------------------------------------------
; code
;--------------------------------------------------------
.area _CODE_255
.area _CODE_255
___bank_background_5 = 0x00ff
_background_5:
.db #0x50 ; 80 'P'
.db #0x12 ; 18
.byte ___bank_tileset_2
.dw _tileset_2
.db #0x00 ; 0
.dw #0x0000
.byte ___bank_background_5_map
.dw _background_5_map
.byte ___bank_scene_5_colors
.dw _scene_5_colors
.area _INITIALIZER
.area _CABS (ABS)
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1992 -- All Rights Reserved
PROJECT: PC GEOS
MODULE:
FILE: legendGeometry.asm
AUTHOR: Chris Boyke
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
cdb 6/10/92 Initial version.
DESCRIPTION:
$Id: legendGeometry.asm,v 1.1 97/04/04 17:46:32 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendItemRecalcSize
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DESCRIPTION: Recalc the size of this legend item
PASS: *ds:si - LegendItemClass object
ds:di - LegendItemClass instance data
es - segment of LegendItemClass
RETURN:
DESTROYED: nothing
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/ 6/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendItemRecalcSize method dynamic LegendItemClass,
MSG_CHART_OBJECT_RECALC_SIZE
uses ax,bp
.enter
cmp ds:[di].LII_type, LIT_TEXT
je legendText
mov cx, LEGEND_ITEM_MIN_WIDTH
mov dx, LEGEND_ITEM_MIN_HEIGHT
callSuper:
.leave
mov di, offset LegendItemClass
GOTO ObjCallSuperNoLock
legendText:
push es
;
; TEXT:
;
; get the OD of the text grobj for this legend item.
; Get the TEXT for this item
; create a gstate for calculations, and figure out the text
; size. We can't just query the grobj text object directly,
; because:
; 1) There may not be a grobj text object yet
; 2) the text may have changed since the last time it
; was set.
;
; This is actually a design problem (ie, grobj objects
; should be created BEFORE doing geometry), but fixing it
; would be a major overhaul, for minor benefit.
;
;
sub sp, CHART_TEXT_BUFFER_SIZE
mov di, sp
segmov es, ss
call LegendItemGetText
call UtilGetTextSize
add sp, CHART_TEXT_BUFFER_SIZE
Max cx, LEGEND_ITEM_MIN_WIDTH
Max dx, LEGEND_ITEM_MIN_HEIGHT
pop es
jmp callSuper
LegendItemRecalcSize endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendItemGetText
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: get the text for this legend item
CALLED BY: LegendItemRecalcSize
PASS: *ds:si - legend item
es:di - buffer of CHART_TEXT_BUFFER_SIZE to fill in
RETURN: es:di - buffer filled in
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/19/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendItemGetText proc near
uses ax,bx,cx,dx,di,si,bp
.enter
;
; Find out the # of this object's parent in ITS parent's list
;
mov ax, MSG_CHART_OBJECT_FIND_PARENT
call ObjCallInstanceNoLock
push cx ; LegendPair
mov si, cx
mov ax, MSG_CHART_OBJECT_FIND_PARENT
call ObjCallInstanceNoLock
mov si, cx
pop dx
mov cx, ds:[LMBH_handle]
call ChartCompFindChild ; bp - position
call UtilGetChartAttributes
mov cx, bp ; position
test dx, mask CF_SINGLE_SERIES
jnz categoryTitle
mov ax, MSG_CHART_GROUP_GET_SERIES_TITLE
jmp callIt
categoryTitle:
mov ax, MSG_CHART_GROUP_GET_CATEGORY_TITLE
callIt:
mov dx, ss
mov bp, di
call UtilCallChartGroup
.leave
ret
LegendItemGetText endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendRecalcSize
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DESCRIPTION: for VERTICAL legends:
make all legend items the same width
for HORIZONTAL legends:
make the legend items of each pair the same width
PASS: *ds:si - LegendClass object
ds:di - LegendClass instance data
es - segment of LegendClass
cx, dx - suggested size
RETURN: cx, dx - new size
DESTROYED: nothing
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/11/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendRecalcSize method dynamic LegendClass,
MSG_CHART_OBJECT_RECALC_SIZE
uses ax,bp
.enter
call LegendSetMargins
mov di, offset LegendClass
call ObjCallSuperNoLock
push cx, dx ; save bounds to return to caller
clr bp ; initial max width
mov bx, offset LegendGetMaxPairWidthCB
call LegendProcessChildren
;
; For vertical legends, make all pairs the same width
;
DerefChartObject ds, si, di
cmp ds:[di].CCI_compType, CCT_VERTICAL
jne done
mov bx, offset LegendSetPairWidthCB
call LegendProcessChildren
done:
pop cx, dx ; legend bounds for caller
.leave
ret
LegendRecalcSize endm
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendGetMaxPairWidthCB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: return the maximum of the passed width and this
LegendPair's width
CALLED BY: LegendRecalcSize via ObjCompProcessChildren
PASS: *ds:si - LegendPair object
bp - passed width
RETURN: bp - updated
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/11/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendGetMaxPairWidthCB proc far
class LegendPairClass
push bp ; max so far
clr bp
;
; Get the max item width. While we're at it, set both items
; to the same width.
;
mov bx, offset LegendGetMaxItemWidthCB
call LegendProcessChildren
mov bx, offset LegendSetItemWidthCB
call LegendProcessChildren
;
; Add this pair's left/right margins to the returned width
;
DerefChartObject ds, si, di
add bp, ds:[di].CCI_margin.R_left
add bp, ds:[di].CCI_margin.R_right
pop cx
Max bp, cx ; return the max
clc
ret
LegendGetMaxPairWidthCB endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendGetMaxItemWidthCB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: callback routine to return the maximum of the passed
width and the object's width
CALLED BY: LegendGetMaxPairWidthCB via LegendProcessChildren
PASS: bp - current maximum
*ds:si - object
RETURN: bp - maximum of object's width and current max
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/11/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendGetMaxItemWidthCB proc far
class LegendItemClass
DerefChartObject ds, si, di
Max bp, ds:[di].COI_size.P_x
clc
ret
LegendGetMaxItemWidthCB endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendSetItemWidthCB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set this item's width to the passed width
CALLED BY: LegendGetMaxPairWidthCB via ObjCompProcessChildren
PASS: bp - width to set
*ds:si - object
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/11/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendSetItemWidthCB proc far
class LegendItemClass
DerefChartObject ds, si, di ; clears carry
mov ds:[di].COI_size.P_x, bp
ret
LegendSetItemWidthCB endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendSetPairWidthCB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the width of this pair. Subtract off the pair's
left and right margins, and set the widths of the
children.
CALLED BY: LegendRecalcSize via ObjCompProcessChildren
PASS: *ds:si - legend pair
bp - width to set
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/11/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendSetPairWidthCB proc far
class LegendPairClass
DerefChartObject ds, si, di
mov ds:[di].COI_size.P_x, bp
sub bp, ds:[di].CCI_margin.R_left
sub bp, ds:[di].CCI_margin.R_right
mov bx, offset LegendSetItemWidthCB
call LegendProcessChildren
clc
ret
LegendSetPairWidthCB endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendSetMargins
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the margins for this legend. Set them each time
we recalc size, because the user may be switching from
horizontal to vertical, and vice-versa.
CALLED BY: LegendRecalcSize
PASS: *ds:si - legend
RETURN: nothing
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/12/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendSetMargins proc near
uses ax,bx,cx,dx,di
class LegendClass
.enter
mov cl, ds:[di].CCI_compType
;
; If the legend is vertical, then store a value in the left
; margin, to separate it from the rest of the chart.
;
mov cl, ds:[di].CCI_compType
cmp cl, CCT_VERTICAL
je vertical
mov ds:[di].CCI_margin.R_top, LEGEND_VERTICAL_MARGIN*2
mov ds:[di].CCI_margin.R_bottom, LEGEND_VERTICAL_MARGIN
jmp callKids
vertical:
mov ds:[di].CCI_margin.R_left, LEGEND_HORIZONTAL_MARGIN
mov ds:[di].CCI_margin.R_right, LEGEND_HORIZONTAL_MARGIN
callKids:
mov bx, offset LegendSetMarginsCB
call LegendProcessChildren
.leave
ret
LegendSetMargins endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendSetMarginsCB
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Set the margin for this LegendPair
CALLED BY: LegendSetMargins
PASS: *ds:si - LegendPair
cl - ChartCompType of legend (horiz or vertical)
RETURN: carry clear
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 1/12/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendSetMarginsCB proc far
.enter
class LegendPairClass
DerefChartObject ds, si, di
cmp cl, CCT_VERTICAL
je vertical
;
; Set margin for each LegendPair of a HORIZONTAL legend
;
mov ds:[di].CCI_margin.R_left, LEGEND_HORIZONTAL_MARGIN/2
mov ds:[di].CCI_margin.R_right, LEGEND_HORIZONTAL_MARGIN/2
clr ds:[di].CCI_margin.R_top
clr ds:[di].CCI_margin.R_bottom
jmp done
vertical:
mov ds:[di].CCI_margin.R_top, LEGEND_VERTICAL_MARGIN/2
mov ds:[di].CCI_margin.R_bottom, LEGEND_VERTICAL_MARGIN/2
clr ds:[di].CCI_margin.R_right
clr ds:[di].CCI_margin.R_left
done:
clc
.leave
ret
LegendSetMarginsCB endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
LegendMarkInvalid
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DESCRIPTION: Mark all children invalid
PASS: *ds:si - LegendClass object
ds:di - LegendClass instance data
es - segment of LegendClass
RETURN: nothing
DESTROYED: nothing
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
chrisb 9/29/93 Initial version.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
LegendMarkInvalid method dynamic LegendClass,
MSG_CHART_OBJECT_MARK_INVALID
uses ax,cx,dx,bp
.enter
mov di, offset LegendClass
call ObjCallSuperNoLock
test cl, mask COS_IMAGE_PATH
jz done
;
; If IMAGE_PATH, then one of the children has marked its image
; invalid. If one legend item is given a REALIZE, then they all
; must get it, so mark all the other children invalid as well.
;
mov cl, mask COS_IMAGE_INVALID
mov ax, MSG_CHART_OBJECT_MARK_TREE_INVALID
call ObjCallInstanceNoLock
done:
.leave
ret
LegendMarkInvalid endm
|
; A144083: Triangle read by rows, partial sums from the right an A010892 subsequences decrescendo triangle
; 1,2,1,2,2,1,1,2,2,1,0,1,2,2,1,0,0,1,2,2,1,1,0,0,1,2,2,1,2,1,0,0,1,2,2,1,2,2,1,0,0,1,2,2,1,1,2,2,1,0,0,1,2,2,1,0,1,2,2,1,0,0,1,2,2,1,0,0,1,2,2,1,0,0,1,2,2,1
seq $0,25676 ; Exponent of 8 (value of i) in n-th number of form 8^i*9^j.
dif $0,2
mod $0,3
dif $0,-2
add $0,1
|
/*
Copyright 2020 The OneFlow 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 "oneflow/core/graph/boxing/b21_sub_task_graph_builder.h"
#include "oneflow/core/graph/boxing/sub_task_graph_builder_util.h"
namespace oneflow {
Maybe<void> B21SubTskGphBuilder::Build(SubTskGphBuilderCtx* ctx,
const std::vector<CompTaskNode*>& sorted_src_comp_tasks,
const std::vector<CompTaskNode*>& sorted_dst_comp_tasks,
const ParallelDesc& src_parallel_desc,
const ParallelDesc& dst_parallel_desc,
const LogicalBlobId& lbi, const BlobDesc& logical_blob_desc,
const SbpParallel& src_sbp_parallel,
const SbpParallel& dst_sbp_parallel) const {
if ((src_parallel_desc.parallel_num() == 1 || src_sbp_parallel.has_broadcast_parallel())
&& dst_parallel_desc.parallel_num() == 1) {
CompTaskNode* dst_node = sorted_dst_comp_tasks.front();
CompTaskNode* nearest_src_node =
SubTskGphBuilderUtil::FindNearestNode(sorted_src_comp_tasks, dst_node);
CHECK_NOTNULL(nearest_src_node);
TaskNode* proxy = ctx->GetProxyNode(nearest_src_node, nearest_src_node->MemZoneId121(),
dst_node->machine_id(), dst_node->MemZoneId121());
Connect<TaskNode>(proxy, ctx->task_graph()->NewEdge(), dst_node);
return Maybe<void>::Ok();
} else {
return Error::BoxingNotSupported();
}
}
} // namespace oneflow
|
; A224327: Number of idempotent n X n 0..2 matrices of rank n-1.
; 1,10,51,212,805,2910,10199,34984,118089,393650,1299067,4251516,13817453,44641030,143489055,459165008,1463588497,4649045850,14721978563,46490458660,146444944821,460255540910,1443528741991,4518872583672,14121476824025,44059007691010,137260754729739,427033459159244,1326853962387709,4117822641892950,12765250189868207,39531097362172576,122299332464221473,378016118525775530,1167402718976659795,3602271247127978868,11107003011977934917,34221576847715799550,105366433978493382903,324204412241518101320,996928567642668161641,3063731695682346057810,9410033065310062891931,28886613130719262831132,88629381196525010959245,271796769002676700275110,833116183247335103017279,2552526178459920315627504,7817111421533505966609329,23929932923061752959008250,73225594744568964054565347,223984172159858007696317636,684874680258027369686817493,2093390532109442148854046030,6396471070334406565942918535,19538311633021460055971096728,59661630165119101242340313337,182124976293521466950302009250,555795186275056890520749235243,1695646331008648140571777327980,5171721309576376828743920850461,15769510878380427707317529150710,48071573484095174785209887249871,146503842999147199345401561142592,446378896638026623005520381606465,1359738792835834943924508239355210,4141022687272770056497366001672819,12608486988114105843663621855839764,38381717743229704553505437119982949,116813923566351274728060026017339550,355448081709040307386811222024190487
add $0,1
mov $1,$0
mov $2,$0
lpb $1
sub $1,1
add $3,$0
add $3,$0
mov $0,$3
lpe
sub $0,$2
|
;++
;
; Copyright (c) Microsoft Corporation
;
; Module Name:
;
; blidt.asm
;
; Abstract:
;
; This module implements IDT functions for the boot loader.
;
; Environment:
;
; Boot loader.
;
;--
include bl.inc
.686p
.model flat
.code
assume ds:flat
assume es:flat
assume ss:flat
assume fs:flat
extrn ?BlTrapFatal@@YIXKPAU_BL_TRAP_CONTEXT@@@Z:near
;++
;
; VOID
; BlTrapEnter(
; VOID
; )
;
; Routine Description:
;
; Entry point for incoming exceptions.
;
;--
align 16
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The IDT_ENTER building macros insure that each IDT target has
;;; an offset of form BlTrapEnter + 0x10 * interrupt_number.
;;;
IDT_ENTER_NOERR MACRO num:req
push 77h ; No error
call @f
align 8
ENDM
IDT_ENTER_ERR MACRO num:req
call @f
align 8
ENDM
align 16
?BlTrapEnter@@YIXXZ proc
IDT_ENTER_NOERR 000h ; #DE Divide-by-Zero
IDT_ENTER_NOERR 001h ; #DB Debug Exception
IDT_ENTER_NOERR 002h ; NMI Non-Maskable-Interrupt
IDT_ENTER_NOERR 003h ; #BP Breakpoint
IDT_ENTER_NOERR 004h ; #OF OVerflow
IDT_ENTER_NOERR 005h ; #BR Bound-Range
IDT_ENTER_NOERR 006h ; #UD Invalid Opcode
IDT_ENTER_NOERR 007h ; #NM Device Not Available
IDT_ENTER_ERR 008h ; #DF Double Fault
IDT_ENTER_NOERR 009h ; Unused (was x87 segment except)
IDT_ENTER_ERR 00ah ; #TS Invalid TSS
IDT_ENTER_ERR 00bh ; #NP Sgement Not Present
IDT_ENTER_ERR 00ch ; #SS Stack Exception
IDT_ENTER_ERR 00dh ; #GP General Protection
IDT_ENTER_ERR 00eh ; #PF Page Fault
IDT_ENTER_NOERR 00fh ; Reserved
IDT_ENTER_NOERR 010h ; #MF x87 Math Error
IDT_ENTER_ERR 011h ; #AC Alignment Check
IDT_ENTER_NOERR 012h ; #MC Machine Check
IDT_ENTER_NOERR 013h ; #XF SIMD Exception
inum = 014h ; 014h to 020h
WHILE inum LE 020h
IDT_ENTER_NOERR inum
inum = inum + 1
ENDM
@@:
push eax
push ebx
push ecx
push edx
push esi
push edi
push ebp
mov eax, esp
add eax, 48
push eax
mov eax, cr2
push eax
mov edx, esp
mov ecx, [edx].BL_TRAP_CONTEXT.TrapNum
sub ecx, ?BlTrapEnter@@YIXXZ
shr ecx, 3
mov [edx].BL_TRAP_CONTEXT.TrapNum, ecx
call ?BlTrapFatal@@YIXKPAU_BL_TRAP_CONTEXT@@@Z
@@:
jmp @b
?BlTrapEnter@@YIXXZ endp
;++
;
; VOID
; FASTCALL
; BlTrapSetIdtr(
; PIDTR Idtr
; )
;
; Routine Description:
;
; This function sets the IDTR register.
;
; Arguments:
;
; Idtr - Supplies the data to write to the IDTR register.
;
;--
?BlTrapSetIdtr@@YIXPAU_IDTR@@@Z proc
lidt fword ptr [ecx]
ret
?BlTrapSetIdtr@@YIXPAU_IDTR@@@Z endp
end
|
; A070389: a(n) = 5^n mod 43.
; 1,5,25,39,23,29,16,37,13,22,24,34,41,33,36,8,40,28,11,12,17,42,38,18,4,20,14,27,6,30,21,19,9,2,10,7,35,3,15,32,31,26,1,5,25,39,23,29,16,37,13,22,24,34,41,33,36,8,40,28,11,12,17,42,38,18,4,20,14,27,6,30,21,19,9,2,10,7,35,3,15,32,31,26,1,5,25,39,23,29,16,37,13,22,24,34,41,33,36,8
mov $1,1
mov $2,$0
lpb $2
mul $1,5
mod $1,43
sub $2,1
lpe
mov $0,$1
|
ori $ra,$ra,0xf
ori $0,$0,35865
ori $6,$6,62202
srav $3,$0,$3
lb $6,13($0)
div $5,$ra
mfhi $4
divu $2,$ra
lb $4,2($0)
lui $5,9281
multu $1,$2
div $1,$ra
sll $5,$1,2
ori $1,$5,1232
div $4,$ra
multu $5,$4
mult $3,$0
mthi $5
srav $6,$6,$6
multu $1,$0
div $2,$ra
mflo $2
addiu $6,$6,17239
ori $4,$4,29743
multu $6,$4
mult $0,$6
mult $4,$4
addiu $2,$2,31202
divu $4,$ra
sb $4,3($0)
ori $5,$1,35223
srav $6,$5,$6
mfhi $4
ori $5,$5,42040
sll $4,$4,19
mflo $3
divu $1,$ra
srav $5,$5,$6
div $4,$ra
mult $1,$4
sb $4,9($0)
mfhi $4
lui $2,65312
mflo $4
mtlo $6
div $5,$ra
mfhi $0
mult $6,$6
lui $1,49988
lui $2,35849
lui $2,25812
mtlo $5
sll $1,$2,14
mfhi $4
mthi $4
mthi $4
srav $2,$2,$1
ori $1,$4,35130
divu $5,$ra
lb $4,2($0)
lui $3,44089
divu $1,$ra
mflo $0
lui $4,62632
mfhi $4
sb $5,5($0)
lui $0,41607
srav $4,$2,$2
srav $6,$2,$3
lb $4,12($0)
sb $4,5($0)
divu $4,$ra
addu $1,$5,$2
lui $2,59699
lui $4,49295
srav $5,$5,$5
multu $2,$2
srav $3,$2,$3
multu $2,$5
mfhi $2
sll $3,$5,12
lb $5,16($0)
srav $4,$4,$6
multu $4,$5
lb $5,12($0)
srav $5,$5,$0
ori $3,$5,36046
mtlo $2
ori $0,$2,24996
srav $3,$0,$3
mtlo $4
srav $1,$1,$1
sll $5,$5,5
lui $0,42173
sll $1,$1,6
lui $1,25080
multu $6,$5
sll $6,$4,27
lb $2,9($0)
multu $1,$2
addu $1,$5,$5
lui $0,58777
sll $4,$1,12
div $6,$ra
mtlo $5
multu $5,$6
lb $1,15($0)
addiu $0,$5,18427
mtlo $5
ori $4,$1,637
mtlo $6
ori $4,$4,37297
addu $4,$4,$4
mflo $4
divu $1,$ra
ori $4,$4,65073
mflo $4
multu $2,$4
multu $1,$2
divu $0,$ra
multu $1,$4
lui $5,45956
multu $1,$0
addu $4,$2,$4
divu $1,$ra
srav $6,$2,$2
addu $3,$3,$3
div $2,$ra
addiu $3,$2,-12662
lb $0,9($0)
multu $6,$5
ori $0,$4,46993
mfhi $4
ori $5,$5,46086
mflo $5
lb $1,7($0)
srav $1,$2,$5
srav $5,$4,$5
sll $1,$3,26
srav $2,$2,$3
mflo $5
mtlo $2
mult $4,$2
lui $5,630
lb $6,9($0)
srav $4,$4,$6
ori $1,$4,28720
mtlo $1
lb $4,8($0)
mfhi $4
addu $3,$3,$3
mthi $1
divu $4,$ra
mtlo $3
lui $0,63591
srav $6,$5,$4
mflo $4
divu $1,$ra
srav $2,$2,$1
sll $6,$6,10
mult $2,$2
multu $2,$2
mflo $6
addu $1,$2,$2
srav $2,$2,$5
lb $6,6($0)
mtlo $0
mthi $3
srav $5,$1,$1
mthi $2
multu $0,$4
lb $1,15($0)
multu $5,$5
mtlo $5
addu $3,$2,$3
lb $0,7($0)
ori $4,$6,31180
sll $1,$2,6
mfhi $3
mthi $4
ori $0,$2,11237
mthi $1
mfhi $0
mflo $3
mflo $6
mfhi $4
mthi $4
divu $3,$ra
addu $4,$6,$6
mflo $5
lui $4,43147
divu $1,$ra
addu $6,$6,$6
sll $6,$6,22
mfhi $5
addu $4,$5,$2
multu $1,$6
addiu $4,$1,-26673
multu $2,$0
addiu $6,$6,7082
lb $0,12($0)
ori $1,$3,25018
div $1,$ra
lb $1,0($0)
ori $1,$1,28419
addu $1,$1,$1
mtlo $1
lui $3,40302
addiu $4,$4,-28821
mthi $5
sb $1,1($0)
lui $1,58730
mflo $4
sll $1,$5,25
mtlo $1
lui $1,3463
addu $4,$0,$0
div $0,$ra
lui $1,62043
sll $5,$5,13
divu $4,$ra
mult $1,$2
mult $0,$0
mthi $5
addiu $4,$5,-12234
div $4,$ra
addiu $1,$4,725
sll $4,$4,13
mtlo $5
mfhi $5
mtlo $6
mthi $6
lui $3,37348
sb $5,6($0)
mtlo $0
lui $2,18196
lb $0,1($0)
divu $2,$ra
sll $4,$6,9
mthi $5
divu $0,$ra
srav $1,$2,$2
multu $4,$4
sll $1,$2,6
sll $5,$1,29
mfhi $2
sb $5,7($0)
multu $1,$2
sll $0,$3,27
lui $0,58580
mflo $2
ori $1,$6,64109
addu $4,$0,$0
lb $2,15($0)
lui $6,65351
mflo $4
mtlo $4
divu $4,$ra
mult $5,$5
mflo $6
lui $0,9313
mult $1,$5
addu $5,$1,$4
mult $5,$5
multu $1,$1
ori $1,$6,1982
srav $2,$2,$0
mtlo $1
mfhi $4
mflo $5
sb $0,1($0)
ori $5,$2,48690
ori $1,$5,35887
srav $0,$5,$1
mthi $4
ori $2,$2,30445
mtlo $2
mfhi $1
mult $4,$1
mfhi $1
divu $2,$ra
mthi $4
mfhi $5
sb $2,0($0)
mthi $4
sb $6,1($0)
mult $5,$4
sll $3,$4,20
mflo $6
multu $6,$6
mthi $4
lb $6,12($0)
srav $3,$3,$3
mtlo $4
mflo $2
mthi $4
divu $1,$ra
srav $4,$1,$4
mult $4,$6
div $5,$ra
lb $0,16($0)
addiu $1,$4,-18172
mult $4,$3
lui $4,4693
divu $0,$ra
div $1,$ra
div $0,$ra
multu $6,$0
srav $3,$3,$3
ori $5,$4,55447
mflo $3
mfhi $4
mfhi $4
ori $5,$4,60853
addu $4,$1,$3
div $6,$ra
lui $1,34708
mflo $1
div $6,$ra
multu $5,$1
mtlo $4
mthi $2
mult $0,$5
mtlo $4
ori $4,$5,46445
sll $4,$2,29
mflo $4
lb $5,2($0)
addu $5,$0,$3
lb $1,13($0)
mtlo $0
lb $4,0($0)
sb $1,3($0)
addiu $4,$4,19051
lui $3,28518
addu $4,$5,$4
ori $0,$2,18532
mfhi $6
lui $4,44698
mtlo $5
lb $5,2($0)
mthi $4
lb $4,16($0)
ori $1,$1,48049
sll $5,$2,22
srav $5,$2,$3
srav $3,$3,$3
mthi $6
multu $5,$5
mthi $2
lui $5,11942
addiu $4,$5,31836
addu $1,$1,$6
sll $6,$5,1
div $5,$ra
divu $5,$ra
mflo $2
mthi $5
lui $5,21841
mthi $0
lb $5,12($0)
srav $2,$2,$2
lui $4,18005
addiu $6,$2,23715
ori $1,$1,11968
lb $1,12($0)
mthi $1
mflo $4
addiu $1,$1,1311
mtlo $1
mult $4,$2
mult $1,$1
mfhi $3
mflo $5
mtlo $4
divu $5,$ra
div $4,$ra
mthi $6
divu $4,$ra
mfhi $4
addiu $4,$5,21375
multu $2,$2
lui $3,4817
lb $4,0($0)
sll $2,$5,16
lb $1,10($0)
srav $5,$1,$3
lb $5,14($0)
multu $0,$4
srav $1,$2,$2
divu $2,$ra
lui $5,35271
srav $4,$4,$4
mfhi $0
mthi $4
mfhi $5
sll $4,$0,29
sb $5,10($0)
lui $1,22611
lb $2,15($0)
mult $5,$4
multu $5,$1
mult $4,$4
mfhi $5
addiu $1,$4,20095
mtlo $2
mfhi $2
sb $4,11($0)
sll $1,$1,3
sb $5,11($0)
lui $3,58489
lui $4,31128
lb $0,10($0)
mult $4,$2
ori $3,$1,45161
div $6,$ra
mult $5,$3
ori $4,$1,24485
div $0,$ra
mfhi $4
ori $4,$6,59765
lb $1,4($0)
lui $1,62927
mult $5,$5
lb $2,5($0)
mult $4,$0
div $4,$ra
lui $6,57379
lui $4,65528
divu $5,$ra
ori $1,$1,26506
mflo $5
multu $3,$3
divu $1,$ra
mflo $6
lb $5,8($0)
sll $3,$3,17
multu $4,$4
sll $3,$1,29
sb $4,1($0)
addu $3,$2,$3
multu $0,$2
multu $0,$5
lb $4,4($0)
div $5,$ra
addiu $0,$5,1525
mtlo $4
sb $1,6($0)
mtlo $1
addiu $1,$4,13330
multu $4,$6
mfhi $0
mult $5,$5
sb $4,6($0)
ori $6,$4,58866
divu $6,$ra
addiu $5,$5,7260
mtlo $1
mult $2,$4
addiu $5,$5,-21912
lui $0,15591
lb $5,2($0)
addiu $2,$2,26918
lb $0,15($0)
ori $3,$5,60193
mult $5,$4
sb $4,8($0)
mthi $4
multu $1,$1
multu $4,$2
ori $4,$5,21054
sll $5,$2,2
addiu $1,$2,-27785
sll $4,$2,29
sb $4,7($0)
sll $1,$1,12
div $0,$ra
multu $4,$4
srav $4,$3,$3
divu $6,$ra
mthi $2
multu $3,$1
mfhi $4
srav $5,$1,$2
sll $1,$2,30
div $1,$ra
multu $3,$5
divu $0,$ra
mtlo $3
lb $1,7($0)
sll $3,$6,29
addu $0,$5,$0
divu $1,$ra
mtlo $5
mtlo $4
srav $1,$5,$4
mthi $1
mthi $1
mfhi $5
sll $1,$0,15
srav $2,$2,$2
sll $5,$1,11
multu $4,$2
mflo $1
addiu $4,$4,20806
multu $5,$0
lb $1,4($0)
mthi $4
mtlo $4
lb $4,0($0)
lb $3,4($0)
mult $6,$4
divu $1,$ra
sb $1,7($0)
lb $1,1($0)
sll $4,$6,31
multu $4,$4
mfhi $0
mflo $4
sb $0,2($0)
srav $4,$2,$2
mfhi $4
mflo $1
div $4,$ra
lui $2,45581
mthi $5
div $4,$ra
mtlo $1
addiu $4,$4,-19371
srav $0,$4,$5
ori $4,$1,65212
addu $3,$5,$3
multu $0,$4
divu $1,$ra
addiu $5,$4,9892
mthi $6
sb $6,2($0)
divu $1,$ra
ori $5,$3,64501
mfhi $1
addiu $6,$5,-6488
sll $4,$5,6
addiu $6,$2,-6933
mtlo $3
mthi $4
sb $1,0($0)
lb $4,9($0)
srav $2,$2,$5
srav $4,$2,$4
div $6,$ra
srav $1,$1,$1
sll $5,$2,10
mfhi $0
ori $0,$0,2689
mfhi $5
mfhi $1
lb $3,8($0)
mthi $1
mtlo $2
mfhi $5
addiu $4,$2,-16510
divu $4,$ra
sll $4,$2,15
srav $3,$1,$3
multu $2,$2
multu $4,$4
sll $2,$4,8
sb $4,1($0)
divu $6,$ra
div $0,$ra
lb $1,1($0)
sb $3,15($0)
mflo $2
multu $6,$5
mfhi $4
sll $1,$1,7
div $1,$ra
divu $5,$ra
srav $3,$3,$3
ori $0,$0,48813
srav $3,$3,$3
ori $6,$2,59965
lui $5,10813
mthi $4
mtlo $4
lb $1,0($0)
div $4,$ra
mthi $1
mult $4,$3
multu $1,$1
sb $6,10($0)
mult $4,$5
sb $5,9($0)
addiu $4,$2,14716
lb $3,13($0)
mfhi $5
addu $4,$2,$2
mfhi $4
multu $4,$2
multu $1,$1
mult $2,$1
sll $5,$2,6
sll $5,$2,3
ori $5,$4,10435
divu $4,$ra
div $2,$ra
divu $3,$ra
lui $0,26351
multu $6,$6
mthi $3
mflo $2
mult $2,$2
sb $4,3($0)
divu $5,$ra
lui $1,43491
lui $1,10554
div $0,$ra
mthi $2
mflo $3
ori $5,$5,24978
ori $0,$2,21345
sll $2,$2,23
div $4,$ra
lui $4,11341
sll $5,$4,1
lb $2,3($0)
divu $3,$ra
ori $4,$2,16393
addiu $1,$3,27501
addu $5,$3,$3
mtlo $5
sll $6,$6,2
sll $5,$2,8
div $5,$ra
addu $4,$4,$2
divu $1,$ra
addiu $1,$3,22823
lui $2,12372
ori $5,$0,38055
mult $5,$2
mult $6,$4
div $6,$ra
ori $5,$5,27047
mthi $5
addu $4,$0,$1
divu $5,$ra
addu $3,$3,$3
mthi $1
multu $1,$5
sb $5,0($0)
lui $6,15260
mfhi $5
sll $1,$1,21
mult $6,$2
lui $4,40823
divu $4,$ra
sll $4,$4,15
lb $5,8($0)
lb $4,5($0)
mthi $5
divu $0,$ra
mtlo $0
lb $4,14($0)
sll $1,$2,0
sll $4,$5,24
divu $5,$ra
mult $0,$5
addiu $3,$4,4179
sll $1,$1,8
div $4,$ra
mtlo $3
mflo $1
srav $4,$6,$6
ori $6,$4,31360
mflo $3
mtlo $0
ori $0,$1,65421
mult $0,$5
multu $4,$0
ori $4,$2,4395
multu $0,$4
div $4,$ra
mflo $5
addiu $4,$4,-24887
divu $4,$ra
addiu $4,$4,25133
sll $1,$4,26
divu $0,$ra
multu $5,$5
sll $4,$4,20
div $6,$ra
lui $5,29568
mthi $2
srav $3,$2,$3
ori $4,$4,11983
addiu $4,$1,31484
addiu $5,$4,-1566
mult $6,$6
sll $2,$0,6
sb $1,15($0)
sb $2,11($0)
sll $5,$5,7
lb $5,12($0)
divu $4,$ra
addiu $4,$4,-16293
multu $5,$1
lui $4,16157
multu $4,$0
divu $5,$ra
sll $5,$5,17
addu $4,$5,$4
mthi $3
mult $4,$4
lui $5,39606
mfhi $1
mult $6,$0
ori $3,$5,60391
addu $5,$2,$2
lb $6,15($0)
divu $4,$ra
srav $1,$5,$5
multu $4,$2
sb $4,4($0)
mult $0,$1
divu $4,$ra
ori $5,$4,5888
mult $4,$4
sb $4,12($0)
divu $4,$ra
mult $4,$4
mflo $5
sb $4,6($0)
mfhi $4
mthi $1
mthi $4
addiu $5,$4,-9626
sb $4,15($0)
lb $5,10($0)
mult $4,$2
sb $2,2($0)
mfhi $3
mfhi $4
addu $4,$4,$5
lb $5,11($0)
mtlo $1
mflo $5
lb $1,14($0)
addiu $6,$3,-19123
mfhi $5
div $2,$ra
mult $4,$2
sll $5,$5,9
ori $1,$5,42735
mthi $5
mult $6,$2
srav $4,$1,$3
div $1,$ra
div $2,$ra
mfhi $6
ori $4,$4,59564
div $5,$ra
addu $4,$4,$4
mthi $4
addu $6,$6,$3
lb $1,13($0)
addu $3,$3,$3
mtlo $2
addu $1,$1,$1
lb $1,14($0)
mult $3,$5
addiu $5,$6,-19458
mthi $3
addu $1,$1,$1
multu $0,$1
sll $5,$5,30
sll $4,$4,20
lb $4,13($0)
div $1,$ra
sb $4,8($0)
div $1,$ra
srav $4,$1,$1
ori $4,$4,16355
mthi $1
ori $1,$2,55650
lb $5,9($0)
divu $1,$ra
mult $4,$5
lui $0,55944
sb $5,12($0)
lui $0,63546
lb $4,13($0)
sb $6,8($0)
divu $4,$ra
multu $4,$4
mult $2,$2
mult $3,$2
mult $1,$3
mthi $4
multu $4,$4
mthi $4
mult $2,$2
sll $5,$4,28
sb $5,9($0)
sb $1,10($0)
mflo $4
addu $6,$1,$6
srav $4,$6,$2
addu $4,$1,$1
mfhi $5
addiu $5,$4,1289
mthi $2
mflo $6
mfhi $2
srav $2,$4,$2
mtlo $4
div $5,$ra
sb $1,10($0)
mult $4,$2
mtlo $5
mtlo $1
srav $6,$5,$4
divu $5,$ra
multu $5,$3
multu $4,$2
mthi $4
sb $0,4($0)
multu $4,$5
divu $1,$ra
mtlo $3
srav $1,$2,$1
lb $5,5($0)
addiu $5,$5,-16945
srav $5,$5,$5
sll $4,$2,21
mfhi $4
srav $3,$0,$3
srav $0,$1,$3
mfhi $4
sll $1,$0,14
multu $1,$5
sb $5,3($0)
addiu $1,$4,17426
multu $4,$1
mfhi $5
multu $2,$4
multu $5,$1
addu $0,$0,$3
mflo $1
sll $4,$2,2
sb $4,1($0)
multu $6,$6
srav $4,$2,$4
sll $1,$2,10
mfhi $4
lb $1,12($0)
lb $4,12($0)
lui $2,10586
addu $6,$2,$4
divu $4,$ra
mfhi $0
div $4,$ra
mfhi $1
divu $4,$ra
addiu $5,$4,19473
mult $4,$6
div $2,$ra
sb $5,6($0)
lb $1,3($0)
div $6,$ra
addiu $3,$3,18013
mthi $1
mult $4,$4
sll $3,$2,31
sll $5,$5,15
multu $5,$4
lb $6,0($0)
mthi $4
divu $0,$ra
srav $3,$2,$3
lb $4,11($0)
mflo $1
mtlo $3
sb $4,3($0)
mtlo $2
mfhi $1
ori $5,$1,38312
srav $4,$1,$4
mflo $5
srav $6,$0,$0
|
;*****************************************************************************
; AMD Generic Encapsulated Software Architecture
;
; Workfile: arch2008.asm $Revision: 37157 $ $Date: 2010-09-01 03:24:07 +0800 (Wed, 01 Sep 2010) $
;
; Description: ARCH2008.ASM - AGESA Architecture 2008 Wrapper Template
;
;*****************************************************************************
;
; Copyright (c) 2011, Advanced Micro Devices, 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 Advanced Micro Devices, 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 ADVANCED MICRO DEVICES, INC. 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.
;
;*****************************************************************************
.XLIST
INCLUDE agesa.inc
INCLUDE acwrapg.inc ; Necessary support file as part of wrapper, including but not limited to segment start/end macros.
INCLUDE acwrap.inc ; IBVs may specify host BIOS-specific include files required when building.
INCLUDE cpcarmac.inc
INCLUDE bridge32.inc
.LIST
.586p
.mmx
;----------------------------------------------------------------------------
; Local definitions
;----------------------------------------------------------------------------
sOemCallout STRUCT
FuncName DD ? ; Call out function name
FuncPtr DW ? ; Call out function pointer
sOemCallout ENDS
sOemEventHandler STRUCT
ClassCode DD ? ; AGESA event log sub-class code
FuncPtr DW ? ; Event handler function pointer
sOemEventHandler ENDS
;; A typical legacy BIOS implementation may require the E000 and F000 segments
;; to be cached.
EXE_CACHE_REGION_BASE_0 EQU 0E0000h
EXE_CACHE_REGION_SIZE_0 EQU 20000h
;; In this sample implementation, the B1 and B2 images are placed next to each
;; other in the BIOS ROM to help with the maximization of cached code.
EXE_CACHE_REGION_BASE_1 EQU AGESA_B1_ADDRESS
EXE_CACHE_REGION_SIZE_1 EQU 40000h
;; The third region is not needed in our example.
EXE_CACHE_REGION_BASE_2 EQU 0
EXE_CACHE_REGION_SIZE_2 EQU 0
;----------------------------------------------------------------------------
; PERSISTENT SEGMENT
; This segment is required to be present throughout all BIOS execution.
;----------------------------------------------------------------------------
AMD_PERSISTENT_START
;----------------------------------------------------------------------------
; Instantiate the global descriptor table
;----------------------------------------------------------------------------
AMD_BRIDGE_32_GDT AMD_GDT ; Instantiate the global descriptor table
; required by the push-high mechanism.
;----------------------------------------------------------------------------
; Declare the external routines required in the persistent segment
;----------------------------------------------------------------------------
;+-------------------------------------------------------------------------
;
; AmdDfltRet
;
; Entry:
; None
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; Near stub procedure. Simply perform a retn instruction.
;
EXTERN AmdDfltRet:NEAR
;+-------------------------------------------------------------------------
;
; AmdDfltRetFar
;
; Entry:
; None
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; Far stub procedure. Simply perform a retf instruction.
;
EXTERN AmdDfltRetFar:FAR
;----------------------------------------------------------------------------
; Declare the optional external routines in the persistent segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; myModuleTypeMismatchHandler (Example)
;
; Entry:
; ESI - Pointer to the EVENT_PARAMS structure of the failure.
; [ESI].DataParam1 - Socket
; [ESI].DataParam2 - DCT
; [ESI].DataParam3 - Channel
; [ESI].DataParam4 - 0x00000000
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; This procedure can be used to react to a memory module type
; mismatch error discovered by the AGESA code. Actions taken
; may include, but are not limited to:
; Logging the event to NV for display later
; Reset, excluding the mismatch on subsequent reboot
; Do nothing
;
; Dependencies:
; None
;
EXTERN myModuleTypeMismatchHandler(AmdDfltRet):NEAR
;+---------------------------------------------------------------------------
;
; oemPlatformConfigInit (Optional)
;
; Entry:
; EDI - 32-bit flat pointer to the PLATFORM_CONFIGURATION to be
; passed in to the next AGESA entry point.
;
; typedef struct {
; IN PERFORMANCE_PROFILE PlatformProfile;
; IN CPU_HT_DEEMPHASIS_LEVEL *PlatformDeemphasisList;
; IN UINT8 CoreLevelingMode;
; IN PLATFORM_C1E_MODES C1eMode;
; IN UINT32 C1ePlatformData;
; IN UINT32 C1ePlatformData1;
; IN UINT32 C1ePlatformData2;
; IN BOOLEAN UserOptionDmi;
; IN BOOLEAN UserOptionPState;
; IN BOOLEAN UserOptionSrat;
; IN BOOLEAN UserOptionSlit;
; IN BOOLEAN UserOptionWhea;
; IN UINT32 PowerCeiling;
; IN BOOLEAN PstateIndependent;
; } PLATFORM_CONFIGURATION;
;
; typedef struct {
; IN UINT8 Socket;
; IN UINT8 Link;
; IN UINT8 LoFreq;
; IN UINT8 HighFreq;
; IN PLATFORM_DEEMPHASIS_LEVEL ReceiverDeemphasis;
; IN PLATFORM_DEEMPHASIS_LEVEL DcvDeemphasis;
; } CPU_HT_DEEMPHASIS_LEVEL;
;
; typedef struct {
; IN PLATFORM_CONTROL_FLOW PlatformControlFlowMode;
; IN BOOLEAN UseHtAssist;
; IN BOOLEAN UseAtmMode;
; IN BOOLEAN Use32ByteRefresh;
; IN BOOLEAN UseVariableMctIsocPriority;
; } PERFORMANCE_PROFILE;
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; Provide a single hook routine to modify the parameters of a
; PLATFORM_CONFIGURATION structure before any entry point that
; has such a structure as an input.
;
; Dependencies:
; None
;
; Example:
; If your platform is running in UMA mode, the following code
; may be added:
; mov (PLATFORM_CONFIGURATION PTR [edi]).PlatformProfile.PlatformControlFlowMode, UmaDr
;
EXTERN oemPlatformConfigInit(AmdDfltRetFar):FAR
;+---------------------------------------------------------------------------
;
; oemCallout (Optional)
;
; Entry:
; ECX - Callout function number
; EDX - Function-specific UINTN
; ESI - Pointer to function specific data
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
;
; Modified:
; None
;
; Purpose:
; The default call out router function which resides in the same
; segment as the push-high bridge code.
;
; Dependencies:
; None
;
EXTERN oemCallout(AmdDfltRet):NEAR
;----------------------------------------------------------------------------
; Define the sample wrapper routines for the persistent segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; AmdBridge32
;
; Entry:
; EDX - A Real Mode FAR pointer using seg16:Offset16 format that
; points to a local host environment call-out router. If
; this pointer is not equal to zero, then this pointer is
; used as the call-out router instead of the standard
; OemCallout. This may be useful when the call-out router
; is not located in the same segment as the AmdBridge32 and
; AmdCallout16 routines.
; ESI - A Flat Mode pointer (32-bit address) that points to the
; configuration block (AMD_CONFIG_PARAMS) for the AGESA
; software function.
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
;
; Modified:
; None
;
; Purpose:
; Execute an AGESA software function through the Push-High interface.
;
; Dependencies:
; This procedure requires a stack. The host environment must use the
; provided service function to establish the stack environment prior
; to making the call to this procedure.
;
AmdBridge32 PROC FAR PUBLIC
AMD_BRIDGE_32 AMD_GDT ; use the macro for the body
ret
AmdBridge32 ENDP
;+---------------------------------------------------------------------------
;
; AmdEnableStack
;
; Entry:
; BX - Return address
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
; SS:ESP - Points to the private stack location for this processor core.
; ECX - Upon success, contains this processor core's stack size in bytes.
;
; Modified:
; EAX, ECX, EDX, EDI, ESI, ESP, DS, ES
;
; Purpose:
; This procedure is used to establish the stack within the host environment.
;
; Dependencies:
; The host environment must use this procedure and not rely on any other
; sources to create the stack region.
;
AmdEnableStack PROC NEAR PUBLIC
AMD_ENABLE_STACK
;; EAX = AGESA_SUCCESS, The stack space has been allocated for this core.
;; EAX = AGESA_WARNING, The stack has already been set up. SS:ESP is set
;; to stack top, and ECX is the stack size in bytes.
jmp bx
AmdEnableStack ENDP
;+---------------------------------------------------------------------------
;
; AmdDisableStack
;
; Entry:
; BX - Return address
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
;
; Modified:
; EAX, ECX, EDX, ESI, ESP
;
; Purpose:
; This procedure is used to remove the pre-memory stack from within the
; host environment.
; The exit state for the BSP is described as follows:
; Memory region 00000-9FFFF MTRRS are set as WB memory.
; Processor Cache is enabled (CD bit is cleared).
; MTRRs used for execution cache are kept.
; Cache content is flushed (invalidated without write-back).
; Any family-specific clean-up done.
; The exit state for the APs is described as follows:
; Memory region 00000-9FFFF MTRRS are set as WB memory.
; Memory region A0000-DFFFF MTRRS are set as UC IO.
; Memory region E0000-FFFFF MTRRS are set as UC memory.
; MTRRs used for execution cache are cleared.
; Processor Cache is disabled (CD bit is set).
; Top-of-Memory (TOM) set to the system top of memory as determined
; by the memory initialization routines.
; System lock command is enabled.
; Any family-specific clean-up done.
;
; Dependencies:
; The host environment must use this procedure and not rely on any other
; sources to break down the stack region.
; If executing in 16-bit code, the host environment must establish the
; "Big Real" mode of 32-bit addressing of data.
;
AmdDisableStack PROC NEAR PUBLIC
AMD_DISABLE_STACK
;; EAX = AGESA_SUCCESS, The stack space has been disabled for this core.
jmp bx
AmdDisableStack ENDP
;+---------------------------------------------------------------------------
;
; AmdCallout16
;
; Entry:
; [esp+8] - Func
; [esp+12] - Data
; [esp+16] - Configuration Block
; [esp+4] - Return address to AGESA
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
;
; Modified:
; None
;
; Purpose:
; Execute callback from the push-high interface.
;
; Dependencies:
; None
;
AmdCallout16 PROC FAR PUBLIC ; declare the procedure
AMD_CALLOUT_16 oemCallout ; use the macro for the body
ret
AmdCallout16 ENDP
;+---------------------------------------------------------------------------
;
; AmdProcessAgesaErrors (Optional)
;
; Entry:
; AL - Heap status of the AGESA entry point that was just invoked.
; EBX - AGESA image base address.
; EDX - Segment / Offset of the appropriate callout router function.
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; This procedure is used to handle any errors that may have occurred
; during an AGESA entry point.
;
; Dependencies:
; None
;
AmdProcessAgesaErrors PROC FAR PUBLIC
LOCAL localCpuInterfaceBlock:EVENT_PARAMS
pushad
xor edi, edi
mov di, ss
shl edi, 4
lea esi, localCpuInterfaceBlock
add esi, edi
; Fill default config block
mov (EVENT_PARAMS PTR [esi]).StdHeader.Func, AMD_READ_EVENT_LOG
mov (EVENT_PARAMS PTR [esi]).StdHeader.ImageBasePtr, ebx
mov (EVENT_PARAMS PTR [esi]).StdHeader.AltImageBasePtr, 0
mov (EVENT_PARAMS PTR [esi]).StdHeader.HeapStatus, al
mov edi, SEG AmdCallout16
shl edi, 4
add edi, OFFSET AmdCallout16
mov (EVENT_PARAMS PTR [esi]).StdHeader.CalloutPtr, edi
; Flush the event log searching for, and handling all monitored events
xor eax, eax
.while (eax == 0)
push edx
call AmdBridge32
pop edx
.if (eax == AGESA_SUCCESS)
mov eax, (EVENT_PARAMS PTR [esi]).EventInfo
.if (eax != 0)
lea di, cs:AgesaEventTable
loopThruTable:
cmp di, OFFSET cs:AgesaEventTableEnd
jae unhandledEvent
cmp eax, cs:[di].sOemEventHandler.ClassCode
je FoundMatch
add di, SIZEOF sOemEventHandler
jmp loopThruTable
FoundMatch:
mov bx, cs:[di].sOemEventHandler.FuncPtr
call bx
unhandledEvent:
xor eax, eax
.else
mov al, 1
.endif
.endif
.endw
popad
ret
AmdProcessAgesaErrors ENDP
;----------------------------------------------------------------------------
; Define the error handler table
;----------------------------------------------------------------------------
AgesaEventTable LABEL BYTE
;; Add entries as desired
;;---------
;; EXAMPLE
;;---------
sOemEventHandler <MEM_ERROR_MODULE_TYPE_MISMATCH_DIMM, OFFSET myModuleTypeMismatchHandler>
AgesaEventTableEnd LABEL BYTE
AMD_PERSISTENT_END
;----------------------------------------------------------------------------
; RECOVERY SEGMENT
; This segment resides in the classic 'boot-block,' and is used
; for recovery.
;----------------------------------------------------------------------------
AMD_RECOVERY_START
;----------------------------------------------------------------------------
; Declare the external routines required in the recovery segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; myReadSPDRecovery (Required for proper recovery mode operation)
;
; Entry:
; ESI - Pointer to an AGESA_READ_SPD_PARAMS structure.
;
; typedef struct {
; IN OUT AMD_CONFIG_PARAMS StdHeader;
; IN UINT8 SocketId;
; IN UINT8 MemChannelId;
; IN UINT8 DimmId;
; IN OUT UINT8 *Buffer;
; IN OUT MEM_DATA_STRUCT *MemData;
; } AGESA_READ_SPD_PARAMS;
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS Indicates the SPD block for the indicated
; DIMM was read successfully.
; AGESA_BOUNDS_CHK The specified DIMM is not present.
; AGESA_UNSUPPORTED This is a required function, so this
; value being returned causes a critical
; error response value from the AGESA
; software function and no memory initialized.
; AGESA_ERROR The DIMM SPD read process has generated
; communication errors.
;
; Modified:
; None
;
; Purpose:
; This call out reads a block of memory SPD data and places it
; into the provided buffer.
;
; Dependencies:
; None
;
EXTERN myReadSPDRecovery:NEAR
;----------------------------------------------------------------------------
; Define the sample wrapper routines for the recovery segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; AmdInitResetWrapper
;
; Entry:
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; A minimal initialization of the processor core is performed. This
; procedure must be called by all processor cores. The code path
; separates the BSP from the APs and performs a separate and appropriate
; list of tasks for each class of core.
; For the BSP, the following actions are performed:
; Internal heap sub-system initialization
; Primary non-coherent HyperTransportT link initialization
; Return to the host environment to test for Recovery Mode.
; The AP processor cores do not participate in the recovery process.
; However, they execute this routine after being released to execute
; by the BSP during the main boot process. Their actions include the
; following:
; Internal heap sub-system initialization
; Proceed to a wait loop waiting for commands from the BSP
;
; For the cache regions, up to three regions of execution cache can be
; allocated following the following rules:
; 1. Once a region is allocated, it cannot be de-allocated. However, it
; can be expanded.
; 2. At most, two of the three regions can be located above 1 MByte. A
; region failing this rule is ignored.
; 3. All region addresses must be at or above the 0x000D0000 linear
; address. A region failing this rule is ignored.
; 4. The address is aligned on a 32-KByte boundary. Starting addresses
; is rounded down to the nearest 32-Kbyte boundary.
; 5. The execution cache size must be a multiple of 32 KByte. Size is
; rounded up to the next multiple of 32 KByte.
; 6. A region must not span either the 1-MByte boundary or the 4-GByte
; boundary. Allocated size is truncated to not span the boundary.
; 7. The granted cached execution regions, address, and size are calculated
; based on the available cache resources of the processor core.
; Allocations are made up to the limit of cache available on the
; installed processor.
; Warning: Enabling instruction cache outside of this interface can cause
; data corruption.
;
; Dependencies:
; This procedure is expected to be executed soon after a system reset
; for the main boot path or resume path of execution.
;
; This procedure requires a stack.
;
; Because the heap system is not yet operational at the point of the
; interface call, the host environment must allocate the storage for
; the AMD_RESET_PARAMS structure before making the first call to
; AmdCreateStruct. This is the ByHost method of allocation.
;
AmdInitResetWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
local localResetParams:AMD_RESET_PARAMS
pushad
; Prepare for the call to initialize the input parameters for AmdInitReset
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B1_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
; Use the 'ByHost' allocation method because the heap has not been initialized as of yet.
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_INIT_RESET
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, ByHost
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, sizeof AMD_RESET_PARAMS
lea edx, localResetParams
add edx, eax
push edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr, edx
mov dx, SEG AmdCalloutRouterRecovery
shl edx, 16
mov dx, OFFSET AmdCalloutRouterRecovery
push edx
call AmdBridge32
pop edx
pop esi
; The structure has been initialized. Now modify the default settings as desired.
; Allocate the execution cache to maximize the amount of code in ROM that is cached.
; Placing the B1 and B2 images near one another is a good way to ensure the AGESA code
; is cached.
mov (AMD_RESET_PARAMS ptr [esi]).CacheRegion.ExeCacheStartAddr, EXE_CACHE_REGION_BASE_0
mov (AMD_RESET_PARAMS ptr [esi]).CacheRegion.ExeCacheSize, EXE_CACHE_REGION_SIZE_0
mov (AMD_RESET_PARAMS ptr [esi + sizeof EXECUTION_CACHE_REGION]).CacheRegion.ExeCacheStartAddr, EXE_CACHE_REGION_BASE_1
mov (AMD_RESET_PARAMS ptr [esi + sizeof EXECUTION_CACHE_REGION]).CacheRegion.ExeCacheSize, EXE_CACHE_REGION_SIZE_1
mov (AMD_RESET_PARAMS ptr [esi + (2 * sizeof EXECUTION_CACHE_REGION)]).CacheRegion.ExeCacheStartAddr, EXE_CACHE_REGION_BASE_2
mov (AMD_RESET_PARAMS ptr [esi + (2 * sizeof EXECUTION_CACHE_REGION)]).CacheRegion.ExeCacheSize, EXE_CACHE_REGION_SIZE_2
; Call in to the AmdInitReset entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS Early initialization completed successfully.
;; AGESA_WARNING One or more of the execution cache allocation
;; rules were violated, but an adjustment was made
;; and space was allocated.
;; AGESA_ERROR One or more of the execution cache allocation rules
;; were violated, which resulted in a requested cache
;; region to not be allocated.
;; The storage space allocated for the AMD_RESET_PARAMS
;; structure is insufficient.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_RESET_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B1_ADDRESS
call AmdProcessAgesaErrors
.endif
;; Here are what the MTRRs should look like based off of the CacheRegions specified above:
;; Fixed-Range MTRRs
;; Name Address Value
;; ---------------- -------- ----------------
;; MTRRfix4k_E0000 0000026C 0505050505050505
;; MTRRfix4k_E8000 0000026D 0505050505050505
;; MTRRfix4k_F0000 0000026E 0505050505050505
;; MTRRfix4k_F8000 0000026F 0505050505050505
;; MTRRdefType 000002FF 0000000000000C00
;;
;; Variable-Range MTRRs and IO Range
;; MTRRphysBase(n) MTRRphysMask(n)
;; ----------------- -----------------
;; n=0 0000000000000000 0000000000000000
;; n=1 0000000000000000 0000000000000000
;; n=2 0000000000000000 0000000000000000
;; n=3 0000000000000000 0000000000000000
;; n=4 0000000000000000 0000000000000000
;; n=5 Heap Base (Varies by core) 0000FFFFFFFF0800
;; n=6 AGESA_B1_ADDRESS | 6 0000FFFFFFFC0800
;; n=7 0000000000000000 0000000000000000
;; Because the allocation method is 'ByHost,' the call to AMD_RELEASE_STRUCT is
;; not necessary. Stack space reclamation is left up to the host BIOS.
popad
ret
AmdInitResetWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdInitRecoveryWrapper
;
; Entry:
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; Perform a minimum initialization of the processor and memory to
; support a recovery mode flash ROM update.
; For the BSP, the following actions are performed:
; Configuration of CPU core for recovery process
; Minimal initialization of some memory
; The AP processor cores do not participate in the recovery process.
; No actions or tasks are performed by the AP cores for this time point.
;
; Dependencies:
; This procedure requires a stack. The host environment must use one of
; the provided service functions to establish the stack environment prior
; to making the call to this procedure.
;
AmdInitRecoveryWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdInitRecovery
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B1_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_INIT_RECOVERY
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PreMemHeap
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterRecovery
shl edx, 16
mov dx, OFFSET AmdCalloutRouterRecovery
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
; Call in to the AmdInitRecovery entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS The function has completed successfully.
;; AGESA_WARNING One or more of the allocation rules were violated,
;; but an adjustment was made and space was allocated.
;; AGESA_ERROR One or more of the allocation rules were violated,
;; which resulted in a requested cache region to not be
;; allocated.
;; AGESA_FATAL No memory was found in the system.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_RECOVERY_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B1_ADDRESS
call AmdProcessAgesaErrors
.endif
; Allow AGESA to free the space used by AmdInitRecovery
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdInitRecoveryWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdCalloutRouterRecovery
;
; Entry:
; ECX - Callout function number
; EDX - Function-specific UINTN
; ESI - Pointer to function specific data
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
;
; Modified:
; None
;
; Purpose:
; The call out router function for AmdInitReset and
; AmdInitRecovery.
;
; Dependencies:
; None
;
AmdCalloutRouterRecovery PROC FAR PUBLIC USES ECX EBX ESI BX DI DS ES
xor ax, ax
mov ds, ax
mov es, ax
lea di, cs:CalloutRouterTableRecovery
mov eax, AGESA_UNSUPPORTED
loopThruTable:
cmp di, OFFSET cs:CalloutRouterTableRecoveryEnd
jae amdCpuCalloutExit ; exit with AGESA_UNSUPPORTED
cmp ecx, cs:[di].sOemCallout.FuncName
je FoundMatch
add di, SIZEOF sOemCallout
jmp loopThruTable
FoundMatch:
mov bx, cs:[di].sOemCallout.FuncPtr
call bx
amdCpuCalloutExit:
ret
AmdCalloutRouterRecovery ENDP
;----------------------------------------------------------------------------
; Define the callout dispatch table for the recovery segment
;----------------------------------------------------------------------------
CalloutRouterTableRecovery LABEL BYTE
;; Standard B1 implementations only need the SPD reader call out function to be implemented.
sOemCallout <AGESA_READ_SPD, OFFSET myReadSPDRecovery>
CalloutRouterTableRecoveryEnd LABEL BYTE
AMD_RECOVERY_END
;----------------------------------------------------------------------------
; PRE-MEMORY SEGMENT
; This segment must be uncompressed in the ROM image.
;----------------------------------------------------------------------------
AMD_PREMEM_START
;----------------------------------------------------------------------------
; Declare the external routines required in the recovery segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; myReadSPDPremem (Required)
;
; Entry:
; ESI - Pointer to an AGESA_READ_SPD_PARAMS structure
;
; typedef struct {
; IN OUT AMD_CONFIG_PARAMS StdHeader;
; IN UINT8 SocketId;
; IN UINT8 MemChannelId;
; IN UINT8 DimmId;
; IN OUT UINT8 *Buffer;
; IN OUT MEM_DATA_STRUCT *MemData;
; } AGESA_READ_SPD_PARAMS;
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS Indicates the SPD block for the indicated
; DIMM was read successfully.
; AGESA_BOUNDS_CHK The specified DIMM is not present.
; AGESA_UNSUPPORTED This is a required function, so this
; value being returned causes a critical
; error response value from the AGESA
; software function and no memory initialized.
; AGESA_ERROR The DIMM SPD read process has generated
; communication errors.
;
; Modified:
; None
;
; Purpose:
; This call out reads a block of memory SPD data and places it
; into the provided buffer.
;
; Dependencies:
; None
;
EXTERN myReadSPDPremem:NEAR
;+-------------------------------------------------------------------------
;
; AmdDfltRetPremem
;
; Entry:
; None
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; Near stub procedure in the prememory segment. Simply perform a
; retn instruction.
;
EXTERN AmdDfltRetPremem:NEAR
;+---------------------------------------------------------------------------
;
; myDoReset (Required)
;
; Entry:
; EDX - Reset type
; 1 - Warm reset whenever
; 2 - Cold reset whenever
; 3 - Warm reset immediately
; 4 - Cold reset immediately
; ESI - Pointer to an AMD_CONFIG_PARAMS structure.
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS The function has completed successfully.
; AGESA_UNSUPPORTED This is a required function, so this
; value being returned causes a critical
; error response value from the AGESA
; software function.
;
; Modified:
; None
;
; Purpose:
; This host environment function must initiate the specified type
; of system reset.
;
; Implementation of this function by the host environment is
; REQUIRED. Some host environments may record this as a request
; allowing other elements in the system to perform some additional
; tasks before the actual reset is issued.
;
; Dependencies:
; The AMD processor contains 3 bits (BiosRstDet[2:0]) in a PCI
; register (F0x6C Link Initialization Control Register) that
; indicate the reset status. These bits are reserved for use by
; the AGESA software and should not be modified by the host
; environment.
;
EXTERN myDoReset:NEAR
;+---------------------------------------------------------------------------
;
; myGetNonVolatileS3Context (Required for proper S3 operation)
;
; Entry:
; None
;
; Exit:
; EBX - Pointer to the non-volatile S3 context block
; ECX - Size in bytes of the non-volatile S3 context block
;
; Modified:
; None
;
; Purpose:
; The host environment must return the pointer to the data
; saved during the mySaveNonVolatileS3Context routine.
;
; Dependencies:
; None
;
EXTERN myGetNonVolatileS3Context:NEAR
;----------------------------------------------------------------------------
; Declare the optional external routines in the prememory segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; myAgesaHookBeforeExitSelfRefresh (Optional)
;
; Entry:
; Prior to this hook, AGESA will display - AGESA_TESTPOINT - 44h
; ESI - Pointer to a data structure containing the memory information
;
; Exit:
; After returning control to AGESA, AGESA will display: - AGESA_TESTPOINT - 45h
; EAX - Contains the AGESA_STATUS return code
; AGESA_SUCCESS The function has completed successfully
; AGESA_UNSUPPORTED This function is not implemented by the host environment
; AGESA_WARNING A non-critical issue has occued in the host environment
;
; Modified:
; None
;
; Purpose:
; General purpose hook called before the exiting self refresh
; This procedure is called once per channel
;
; Implementation of this function is optional for the host environment
; This call-out is an opportunity for the host environment to make dynamic
; modifications to the memory timing settings specific to the board or host
; environment before exiting self refresh on S3 resume
;
; Dependencies:
; This procedure is called before the exit self refresh bit is set in the resume
; sequence. The host environment must initiate the OS restart process. This procedure
; requires a stack. The host environment must establish the stack environment prior
; to making the call to this procedure
;
EXTERN myAgesaHookBeforeExitSelfRefresh(AmdDfltRetPremem):NEAR
;+---------------------------------------------------------------------------
;
; myHookBeforeDramInit (Optional)
;
; Entry:
; Prior to this hook, AGESA will display - AGESA_TESTPOINT - 40h
; ESI - Pointer to a data structure containing the memory information
;
; Exit:
; After returning control to AGESA, AGESA will display - AGESA_TESTPOINT - 41h
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS The function has completed successfully.
; AGESA_UNSUPPORTED This function is not implemented by the host environment
;
; Modified:
; None
;
; Purpose:
; General-purpose hook called before the DRAM_Init bit is set. Called
; once per MCT
;
; Implementation of this function is optional for the host environment
; This call-out is an opportunity for the host environment to make
; dynamic modifications to the memory timing settings specific to the
; board or host environment
;
; Dependencies:
; None
;
EXTERN myHookBeforeDramInit(AmdDfltRetPremem):NEAR
;+---------------------------------------------------------------------------
;
; myHookBeforeDQSTraining (Optional)
;
; Entry:
; Prior to this hook, AGESA will display - AGESA_TESTPOINT - 42h
; ESI - Pointer to a data structure containing the memory information.
;
; Exit:
; After returning control to AGESA, AGESA will display - AGESA_TESTPOINT - 43h
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS The function has completed successfully.
; AGESA_UNSUPPORTED This function is not implemented by the
; host environment.
;
; Modified:
; None
;
; Purpose:
; General-purpose hook called just before the memory training processes
; begin. Called once per MCT.
;
; Implementation of this function is optional for the host environment.
; This call-out is an opportunity for the host environment to make
; dynamic modifications to the memory timing settings specific to the
; board or host environment.
;
; The host environment may also use this call-out for some board-
; specific features that should be activated at this time point,
; such as:
; Low voltage DIMMs-the host environment should set the recommended
; voltages found in the memory data structure for each memory
; channel. This needs to occur before training begins.
;
; Dependencies:
; None
;
EXTERN myHookBeforeDQSTraining(AmdDfltRetPremem):NEAR
;----------------------------------------------------------------------------
; Define the sample wrapper routines for the prememory segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; AmdInitEarlyWrapper
;
; Entry:
; On Entry to "AmdInitEarly" AGESA will display AGESA_TESTPOINT - C4h
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; On Exit from "AmdInitEarly" AGESA will display AGESA_TESTPOINT - C5h
; None
;
; Modified:
; None
;
; Purpose:
; A full initialization of the processor is performed. Action details
; differ for the BSP and AP processor cores.
; For the BSP, the following actions are performed:
; Full HyperTransportT link initialization, coherent and non-coherent
; Processor register loading
; Microcode patch load
; Errata workaround processing
; Launch all processor cores
; Configure the processor power management capabilities
; Request a warm reset if needed
; For the AP, the following actions are performed:
; Processor register loading
; Microcode patch load
; Errata workaround processing
; Configure the processor power management capabilities
;
; Dependencies:
; This procedure is expected to be called before main memory initialization
; and before the system warm reset. Prior to this, the basic configuration
; done by the AmdInitReset routine must be completed.
;
; This procedure requires a stack. The host environment must use one of the
; provided service functions to establish the stack environment prior to
; making the call to this procedure.
;
; The processes performed at this time point require communication between
; processor cores.
;
; The host environment must recognize that all processor cores are running
; in parallel and avoid activities that might interfere with the core-to-core
; communication, such as modifying the MTRR settings or writing to the APIC
; registers.
;
AmdInitEarlyWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdInitEarly
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_INIT_EARLY
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PreMemHeap
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPremem
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPremem
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
mov edi, esi
add edi, (SIZEOF AMD_CONFIG_PARAMS + (3 * (SIZEOF EXECUTION_CACHE_REGION)))
call oemPlatformConfigInit
; Call in to the AmdInitEarly entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS The function has completed successfully.
;; AGESA_ALERT An HyperTransportT link CRC error was observed.
;; AGESA_WARNING One of more of the allocation rules were violated,
;; but an adjustment was made and space was allocated.
;; Or a HyperTransport device does not have the expected
;; capabilities, or unusable redundant HyperTransport
;; links were found.
;; AGESA_ERROR One or more of the allocation rules were violated, which
;; resulted in a requested cache region to not be allocated.
;; Or, a HyperTransport device failed to initialize.
;; AGESA_CRITICAL An illegal or unsupported mixture of processor types was
;; found, or the processors installed were found to have an
;; insufficient MP capability rating for this platform.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_EARLY_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B2_ADDRESS
call AmdProcessAgesaErrors
.endif
; Allow AGESA to free the space used by AmdInitEarly
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdInitEarlyWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdInitPostWrapper
;
; Entry:
; On Entry to "AmdInitPost" AGESA will display AGESA_TESTPOINT - C6h
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; On Exit from "AmdInitPost" AGESA will display AGESA_TESTPOINT - C7h
; None
;
; Modified:
; None
;
; Purpose:
; The main system memory is located, initialized, and brought on-line.
; The processor(s) are prepared for full operation and control by the
; host environment. Action details differ for the BSP and AP processor
; cores.
; For the BSP, the following actions are performed:
; Full memory initialization and configuration. BSP is the master for
; this process and may delegate some tasks to APs.
; AP collection of data for use later.
; Transfer the HOBs including the artifact data out of the pre-memory
; cache storage into a temporary holding buffer in the main memory.
; Check the BIST status of the BSP
; Shut down the APs.
; Prepare for the host environment to begin main boot activity.
; Disable the pre-memory stack.
; For the APs, the following actions are performed:
; Report core identity information.
; Execute indicated memory initialization processes as directed.
; Check the BIST status of the AP
; Disable the pre-memory stack.
; Prepare to halt, giving control to host environment.
; The entire range of system memory is enabled for Write-Back cache.
; The fixed MTRRs and the variable MTRRs[7:6] are not changed in order
; to leave in place any flash ROM region currently set for Write-Protect
; execution cache.
;
; Dependencies:
; This procedure is called after the host environment has determined that
; a normal boot to operating system should be performed after any system
; warm reset is completed and after the configuration done by AmdInitEarly
; has completed.
;
; This procedure requires a stack. The host environment must use one of the
; provided service functions to establish the stack environment prior to
; making the call to this procedure.
;
; The processes performed at this time point require communication between
; processor cores. The host environment must recognize that all processor
; cores are running in parallel and avoid activities that might interfere
; with the core-to-core communication, such as modifying the MTRR settings
; or writing to the APIC registers.
;
AmdInitPostWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdInitPost
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_INIT_POST
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PreMemHeap
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPremem
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPremem
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
mov edi, esi
add edi, SIZEOF AMD_CONFIG_PARAMS
call oemPlatformConfigInit
; Call in to the AmdInitPost entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS The function has completed successfully.
;; AGESA_ALERT A BIST error was found on one of the cores.
;; AGESA_WARNING HT Assist feature is running sub-optimally.
;; AGESA_FATAL Memory initialization failed.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_POST_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B2_ADDRESS
call AmdProcessAgesaErrors
.endif
; Allow AGESA to free the space used by AmdInitPost
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdInitPostWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdInitResumeWrapper
;
; Entry:
; On Entry to "AmdInitResume" AGESA will display AGESA_TESTPOINT - D0h
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; On Exit from "AmdInitResume" AGESA will display AGESA_TESTPOINT - D1h
; None
;
; Modified:
; None
;
; Purpose:
; This procedure initializes or re-initializes the silicon components
; for the resume boot path. For the processor, main memory is brought
; out of self-refresh mode. This procedure will use the context data
; in the NvStorage area of the input structure to re-start the main
; memory. The host environment must fill the AMD_S3_PARAMS NvStorage
; and VolatileStorage pointers and related size elements to describe
; the location of the context data. Note that for this procedure, the
; two data areas do not need to be contained in one buffer zone, they
; can be anywhere in the accessible memory address space. If the host
; environment uses a non-volatile storage device accessed on the system
; address bus such as flashROM, then the context data does not need to
; be moved prior to this call. If the host environment uses a non-
; volatile storage device not located on the system address bus (e.g.
; CMOS or SSEPROM) then the host environment must transfer the context
; data to a buffer in main memory prior to calling this procedure.
;
; Dependencies:
; The host environment must have determined that the system should take
; the resume path prior to calling this procedure. The configuration
; done by AmdInitEarly and any necessary warm reset must be complete.
; After this procedure, execution proceeds to general system restoration.
;
; This procedure requires a stack. The host environment must use one of
; the provided service functions to establish the stack environment prior
; to making the call to this procedure.
;
AmdInitResumeWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdInitResume
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_INIT_RESUME
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PreMemHeap
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPremem
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPremem
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
mov edi, esi
add edi, (SIZEOF AMD_CONFIG_PARAMS + SIZEOF AMD_S3_PARAMS)
call oemPlatformConfigInit
call myGetNonVolatileS3Context
mov (AMD_RESUME_PARAMS ptr [esi]).S3DataBlock.NvStorage, ebx
mov (AMD_RESUME_PARAMS ptr [esi]).S3DataBlock.NvStorageSize, ecx
; Call in to the AmdInitResume entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS Re-initialization has been completed successfully.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_RESUME_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B2_ADDRESS
call AmdProcessAgesaErrors
.endif
; Allow AGESA to free the space used by AmdInitResume
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdInitResumeWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdCalloutRouterPremem
;
; Entry:
; ECX - Callout function number
; EDX - Function-specific UINTN
; ESI - Pointer to function specific data
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
;
; Modified:
; None
;
; Purpose:
; The call out router function for AmdInitEarly,
; AmdInitPost, and AmdInitResume.
;
; Dependencies:
; None
;
AmdCalloutRouterPremem PROC FAR PUBLIC USES ECX EBX ESI BX DI DS ES
xor ax, ax
mov ds, ax
mov es, ax
lea di, cs:CalloutRouterTablePremem
mov eax, AGESA_UNSUPPORTED
loopThruTable:
cmp di, OFFSET cs:CalloutRouterTablePrememEnd
jae amdCpuCalloutExit ; exit with AGESA_UNSUPPORTED
cmp ecx, cs:[di].sOemCallout.FuncName
je FoundMatch
add di, SIZEOF sOemCallout
jmp loopThruTable
FoundMatch:
mov bx, cs:[di].sOemCallout.FuncPtr
call bx
amdCpuCalloutExit:
ret
AmdCalloutRouterPremem ENDP
;----------------------------------------------------------------------------
; Define the callout dispatch table for the prememory segment
;----------------------------------------------------------------------------
CalloutRouterTablePremem LABEL BYTE
;; Add entries as desired.
sOemCallout <AGESA_READ_SPD, OFFSET myReadSPDPremem>
sOemCallout <AGESA_HOOKBEFORE_DRAM_INIT, OFFSET myHookBeforeDramInit>
sOemCallout <AGESA_HOOKBEFORE_DQS_TRAINING, OFFSET myHookBeforeDQSTraining>
sOemCallout <AGESA_HOOKBEFORE_EXIT_SELF_REF, OFFSET myAgesaHookBeforeExitSelfRefresh>
sOemCallout <AGESA_DO_RESET, OFFSET myDoReset>
CalloutRouterTablePrememEnd LABEL BYTE
AMD_PREMEM_END
;----------------------------------------------------------------------------
; POST SEGMENT
; This segment may be decompressed and run from system RAM.
;----------------------------------------------------------------------------
AMD_POST_START
;----------------------------------------------------------------------------
; Declare the external routines required in the POST segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; myAllocateBuffer (Required)
;
; Entry:
; Prior to this hook, AGESA will display - AGESA_TESTPOINT - E2h
; ESI - Pointer to an AGESA_BUFFER_PARAMS structure.
;
; typedef struct {
; IN OUT AMD_CONFIG_PARAMS StdHeader;
; IN UINT32 BufferLength;
; IN UINT32 BufferHandle;
; OUT VOID *BufferPointer;
; } AGESA_BUFFER_PARAMS;
;
; Exit:
; After this hook, AGESA will display - AGESA_TESTPOINT - E3h
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS The requested size of memory has been
; successfully allocated.
; AGESA_UNSUPPORTED This is a required function, so this
; value being returned causes a critical
; error response value from the AGESA
; software function.
; AGESA_ERROR Less than the requested amount of memory
; was allocated.
;
; Modified:
; EAX
;
; Purpose:
; This function is used after main memory has been initialized
; and the host environment has taken control of memory allocation.
; This function must allocate a buffer of the requested size or
; larger. This function is required to be implemented by the host
; environment.
;
; Dependencies:
; The following call-outs must work together in the host system.
; Parameters of the same name have the same function and must be
; treated the same in each function:
; AgesaAllocateBuffer
; AgesaDeallocateBuffer
; AgesaLocateBuffer
; AgesaRunFcnOnAp
; The host environment may need to reserve a location in the buffer
; to store any host environment specific value(s). The returned
; pointer must not include this reserved space. The host environment
; on the AgesaDeallocateBuffer call needs to account for the reserved
; space. This reserved space may be an identifier or the "handle"
; used to identify the specific memory block.
;
EXTERN myAllocateBuffer:NEAR
;+---------------------------------------------------------------------------
;
; myDeallocateBuffer (Required)
;
; Entry:
; Prior to this hook, AGESA will display - AGESA_TESTPOINT - E4h
; ESI - Pointer to an AGESA_BUFFER_PARAMS structure.
;
; typedef struct {
; IN OUT AMD_CONFIG_PARAMS StdHeader;
; IN UINT32 BufferLength;
; IN UINT32 BufferHandle;
; OUT VOID *BufferPointer;
; } AGESA_BUFFER_PARAMS;
;
; Exit:
; After this hook, AGESA will display - AGESA_TESTPOINT - E5h
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS The function has completed successfully.
; AGESA_BOUNDS_CHK The BufferHandle is invalid. The AGESA
; software continues with its function.
; AGESA_UNSUPPORTED This is a required function, so this
; value being returned causes a critical
; error response value from the AGESA
; software function.
;
; Modified:
; EAX
;
; Purpose:
; This function is used after main memory has been initialized
; and the host environment has taken control of memory allocation.
; This function releases a valid working buffer. This function is
; required for the host environment to implement.
;
; Dependencies:
; The following call-outs must work together in the host system.
; Parameters of the same name have the same function and must be
; treated the same in each function:
; AgesaAllocateBuffer
; AgesaDeallocateBuffer
; AgesaLocateBuffer
; AgesaRunFcnOnAp
;
EXTERN myDeallocateBuffer:NEAR
;+---------------------------------------------------------------------------
;
; myLocateBuffer (Required)
;
; Entry:
; Prior to this hook, AGESA will display - AGESA_TESTPOINT - E6h
; ESI - Pointer to an AGESA_BUFFER_PARAMS structure.
;
; typedef struct {
; IN OUT AMD_CONFIG_PARAMS StdHeader;
; IN UINT32 BufferLength;
; IN UINT32 BufferHandle;
; OUT VOID *BufferPointer;
; } AGESA_BUFFER_PARAMS;
;
; Exit:
; After this hook, AGESA will display - AGESA_TESTPOINT - E7h
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS The function has completed successfully.
; AGESA_BOUNDS_CHK The presented handle is invalid or the
; buffer could not be located.
;
; Modified:
; EAX
;
; Purpose:
; This function is used after main memory has been initialized
; and the host environment has taken control of memory allocation.
; This function must locate the buffer related to the indicated
; handle and return the address of the buffer and its length.
; This function is required to be implemented in the host
; environment.
;
; Dependencies:
; The following call-outs must work together in the host system.
; Parameters of the same name have the same function and must be
; treated the same in each function:
; AgesaAllocateBuffer
; AgesaDeallocateBuffer
; AgesaLocateBuffer
; AgesaRunFcnOnAp
;
EXTERN myLocateBuffer:NEAR
;+---------------------------------------------------------------------------
;
; myRunFuncOnAp (Required)
;
; Entry:
; EDX - Local APIC ID of the target core.
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; The host environment must route execution to the target AP and
; have that AP call the AmdLateRunApTaskWrapper routine defined
; above.
;
; Dependencies:
; None
;
EXTERN myRunFuncOnAp:NEAR
;+---------------------------------------------------------------------------
;
; mySaveNonVolatileS3Context (Required for proper S3 operation)
;
; Entry:
; EBX - Pointer to the non-volatile S3 context block
; ECX - Size in bytes of the non-volatile S3 context block
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; The host environment must save the non-volatile data to an area
; that will not lose context while in the ACPI S3 sleep state, but
; cannot be placed in system RAM. This data will need to be
; available during the call to AmdInitResume.
;
; Dependencies:
; None
;
EXTERN mySaveNonVolatileS3Context:NEAR
;+---------------------------------------------------------------------------
;
; mySaveVolatileS3Context (Required for proper S3 operation)
;
; Entry:
; EBX - Pointer to the volatile S3 context block
; ECX - Size in bytes of the volatile S3 context block
;
; Exit:
; None
;
; Modified:
; None
;
; Purpose:
; The host environment must save the volatile data to an area
; that will not lose context while in the ACPI S3 sleep state.
; This data will need to be available during the call to
; AmdS3LateRestore.
;
; Dependencies:
; None
;
EXTERN mySaveVolatileS3Context:NEAR
;+---------------------------------------------------------------------------
;
; myGetVolatileS3Context (Required for proper S3 operation)
;
; Entry:
; None
;
; Exit:
; EBX - Pointer to the volatile S3 context block
; ECX - Size in bytes of the volatile S3 context block
;
; Modified:
; None
;
; Purpose:
; The host environment must return the pointer to the data
; saved during the mySaveVolatileS3Context routine.
;
; Dependencies:
; None
;
EXTERN myGetVolatileS3Context:NEAR
;----------------------------------------------------------------------------
; Define the sample wrapper routines for the POST segment
;----------------------------------------------------------------------------
;+---------------------------------------------------------------------------
;
; AmdInitEnvWrapper
;
; Entry:
; On Entry to "AmdInitEnv" AGESA will display AGESA_TESTPOINT - C8h
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; On Exit from "AmdInitEnv" AGESA will display AGESA_TESTPOINT - C9h
; None
;
; Modified:
; None
;
; Purpose:
; This procedure uses the AgesaAllocateBuffer call-out to acquire
; permanent buffer space for the UEFI Hand-Off Blocks (HOBs). This
; is also known as, or includes, artifact data being used by the
; AGESA software. Upon entry to this procedure, the data is being
; held in a temporary memory location and it must be moved to a
; location controlled and protected by the host environment.
;
; These actions are performed by the BSP. The APs are not assigned
; any tasks at this time point.
;
; Dependencies:
; This procedure must be called after full memory is initialized and
; the host environment has taken control of main memory allocation.
; This procedure should be called before the PCI enumeration takes
; place and as soon as possible after the host environment memory
; allocation sub-system has started.
;
; This procedure requires a stack. The host environment must use one
; of the provided service functions to establish the stack environment
; prior to making the call to this procedure.
;
AmdInitEnvWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdInitEnv
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_INIT_ENV
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PostMemDram
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPost
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPost
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
mov edi, esi
add edi, SIZEOF AMD_CONFIG_PARAMS
call oemPlatformConfigInit
; Call in to the AmdInitEnv entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS The function has completed successfully.
;; AGESA_ERROR The artifact data could not be found or the host
;; environment failed to allocate sufficient buffer space.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_ENV_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B2_ADDRESS
call AmdProcessAgesaErrors
.endif
; Allow AGESA to free the space used by AmdInitEnv
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdInitEnvWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdInitMidWrapper
;
; Entry:
; On Entry to "AmdInitMid" AGESA will display AGESA_TESTPOINT - CAh
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; On Exit from "AmdInitMid" AGESA will display AGESA_TESTPOINT - CBh
; None
;
; Modified:
; None
;
; Purpose:
; This procedure call performs special configuration requirements for
; the graphics display hardware.
;
; These actions are performed by the BSP. The APs are not assigned any
; tasks at this time point.
;
; Dependencies:
; This procedure must be called after PCI enumeration has allocated
; resources, but before the video BIOS call is performed.
;
; This procedure requires a stack. The host environment must use one
; of the provided service functions to establish the stack environment
; prior to making the call to this procedure.
;
AmdInitMidWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdInitMid
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_INIT_MID
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PostMemDram
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPost
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPost
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
mov edi, esi
add edi, SIZEOF AMD_CONFIG_PARAMS
call oemPlatformConfigInit
; Call in to the AmdInitMid entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS The function has completed successfully.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_MID_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B2_ADDRESS
call AmdProcessAgesaErrors
.endif
; Allow AGESA to free the space used by AmdInitMid
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdInitMidWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdInitLateWrapper
;
; Entry:
; On Entry to "AmdInitLate" AGESA will display AGESA_TESTPOINT - CCh
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; On Exit from "AmdInitLate" AGESA will display AGESA_TESTPOINT - CDh
; None
;
; Modified:
; None
;
; Purpose:
; The main purpose of this function is to generate informational
; data tables used by the operating system. The individual tables
; can be selected for generation through the user selection entries
; on the input parameters.
;
; This routine uses the Call-Out AgesaAllocateBuffer to allocate a
; buffer of the proper size to contain the data.
;
; The code path separates the BSP from the APs and perform a separate
; and appropriate list of tasks for each class of core.
; For the BSP, the following actions are performed:
; Allocate buffer space for the tables.
; Generate the table contents.
; Make sure that the CPU is in a known good power state before
; proceeding to boot the OS.
; For the APs, the following actions are performed:
; Final register settings preparing for entry to OS.
; Establish the final PState for entry to OS.
;
; Dependencies:
; This routine is expected to be executed late in the boot sequence
; after main memory has been initialized, after PCI enumeration has
; completed, after the host environment ACPI sub-system has started,
; after the host environment has taken control of the APs, but just
; before the start of OS boot.
;
; The host environment must provide the required call-outs listed in
; the "Required Call-Out Procedures" section of the AGESA interface
; specification to provide the buffer space in main memory and execute
; code on the APs. The host environment must register the created ACPI
; table in the main ACPI pointer tables. This may require moving the
; generated tables to another location in memory.
;
; This procedure requires a stack. The host environment must establish
; the stack environment prior to making the call to this procedure.
; Some functions depend upon the preservation of the heap data across
; the shift from pre-memory environment to a post-memory environment.
; If that data was not preserved, then those functions cannot complete
; and an error is returned.
;
AmdInitLateWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdInitLate
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_INIT_LATE
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PostMemDram
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPost
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPost
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
mov edi, esi
add edi, SIZEOF AMD_CONFIG_PARAMS
call oemPlatformConfigInit
; Call in to the AmdInitLate entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS The function has completed successfully.
;; AGESA_ALERT
;; AGESA_ERROR The system could not allocate the needed amount of
;; buffer space; or could not locate the artifact data block in
;; memory. Likely cause: the host environment may not have preserved
;; the data properly.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_LATE_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B2_ADDRESS
call AmdProcessAgesaErrors
.endif
push es
mov ax, SEG AmdAcpiSratPointer
mov es, ax
mov ebx, (AMD_LATE_PARAMS ptr [esi]).AcpiSrat
mov es:AmdAcpiSratPointer, ebx
mov eax, DWORD PTR [ebx + 4]
mov es:AmdAcpiSratSize, eax
mov ebx, (AMD_LATE_PARAMS ptr [esi]).AcpiSlit
mov es:AmdAcpiSlitPointer, ebx
mov eax, DWORD PTR [ebx + 4]
mov es:AmdAcpiSlitSize, eax
mov ebx, (AMD_LATE_PARAMS ptr [esi]).AcpiPState
mov es:AmdAcpiSsdtPointer, ebx
mov eax, DWORD PTR [ebx + 4]
mov es:AmdAcpiSsdtSize, eax
xor eax, eax
mov ebx, (AMD_LATE_PARAMS ptr [esi]).AcpiWheaMce
mov es:AmdAcpiWheaMcePointer, ebx
mov ax, WORD PTR [ebx]
mov es:AmdAcpiWheaMceSize, eax
mov ebx, (AMD_LATE_PARAMS ptr [esi]).AcpiWheaMce
mov es:AmdAcpiWheaCmcPointer, ebx
mov ax, WORD PTR [ebx]
mov es:AmdAcpiWheaCmcSize, eax
mov eax, (AMD_LATE_PARAMS ptr [esi]).DmiTable
mov es:AmdDmiInfoPointer, eax
pop es
; Allow AGESA to free the space used by AmdInitLate
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdInitLateWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdS3SaveWrapper
;
; Entry:
; On Entry to "AmdS3Save" AGESA will display AGESA_TESTPOINT - CEh
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; On Entry to "AmdS3Save" AGESA will display AGESA_TESTPOINT - CFh
; None
;
; Modified:
; None
;
; Purpose:
; This procedure saves critical registers and/or configuration
; information for preservation across a system suspend mode. All
; actions needed to prepare the processor for suspend mode is
; performed, however this procedure does NOT initiate the suspend
; process. The host environment is expected to perform that duty.
;
; These actions are performed by the BSP. The APs are not assigned
; any tasks at this time point.
;
; The initializer routine will NULL out the save area pointers and
; sizes. This procedure will determine the size of storage needed
; for all the processor context, and make a call out to the environment
; for allocation of one buffer to store all of the data. Upon exit, the
; pointers and sizes within the AMD_S3_PARAMS structure will be updated
; with the appropriate addresses within the buffer that was allocated.
; The host environment is expected to then transfer the data pointed to
; by NvStorage to a non-volatile storage area, and the data pointed to
; by VolatileStorage to either a non-volatile storage area or system
; RAM that retains its content across suspend.
;
; Dependencies:
; The host environment must initiate the suspend process.
;
; This procedure requires a stack. The host environment must establish
; the stack environment prior to making the call to this procedure.
;
AmdS3SaveWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdS3Save
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_S3_SAVE
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PostMemDram
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPost
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPost
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
mov edi, esi
add edi, (SIZEOF AMD_CONFIG_PARAMS + SIZEOF AMD_S3_PARAMS)
call oemPlatformConfigInit
; Call in to the AmdS3Save entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS All suspend duties have been completed successfully.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_S3SAVE_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B2_ADDRESS
call AmdProcessAgesaErrors
.endif
mov ecx, (AMD_S3SAVE_PARAMS ptr [esi]).S3DataBlock.NvStorageSize
.if (ecx != 0)
mov ebx, (AMD_S3SAVE_PARAMS ptr [esi]).S3DataBlock.NvStorage
call mySaveNonVolatileS3Context
.endif
mov ecx, (AMD_S3SAVE_PARAMS ptr [esi]).S3DataBlock.VolatileStorageSize
.if (ecx != 0)
mov ebx, (AMD_S3SAVE_PARAMS ptr [esi]).S3DataBlock.VolatileStorage
call mySaveVolatileS3Context
.endif
; Allow AGESA to free the space used by AmdS3Save
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdS3SaveWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdS3LateRestoreWrapper
;
; Entry:
; On Entry to "AmdS3LateRestore" AGESA will display AGESA_TESTPOINT - D2h
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; On Exit from "AmdS3LateRestore" AGESA will display AGESA_TESTPOINT - D3h
; None
;
; Modified:
; None
;
; Purpose:
; This procedure restores the processor state, reloads critical
; silicon component registers, and performs any re-initialization
; required by the silicon. This procedure will use the context data
; in the VolatileStorage area of the input structure to restore the
; processor registers.
;
; The host environment must fill the AMD_S3_PARAMS NvStorage and
; VolatileStorage pointers and related size elements to describe
; the location of the context data. Note that for this procedure,
; the two data areas do not need to be contained in one buffer zone,
; they can be anywhere in the accessible memory address space. If
; the host environment uses a non-volatile storage device accessed
; on the system address bus such as flashROM, then the context data
; does not need to be moved prior to this call. If the host
; environment uses a non-volatile storage device not located on the
; system address bus (e.g. CMOS or SSEPROM) then the host environment
; must transfer the context data to a buffer in main memory prior to
; calling this procedure.
;
; These actions are performed by the BSP. The APs are not assigned
; any tasks at this time point.
;
; Dependencies:
; This procedure is called late in the resume sequence, after the
; PCI control space is restored and just before resuming operating
; system execution.
;
; The host environment must initiate the OS restart process.
;
; This procedure requires a stack. The host environment must establish
; the stack environment prior to making the call to this procedure.
;
AmdS3LateRestoreWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdS3LateRestore
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_S3LATE_RESTORE
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PostMemDram
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPost
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPost
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
mov edi, esi
add edi, (SIZEOF AMD_CONFIG_PARAMS + SIZEOF AMD_S3_PARAMS)
call oemPlatformConfigInit
call myGetVolatileS3Context
mov (AMD_S3LATE_PARAMS ptr [esi]).S3DataBlock.VolatileStorage, ebx
mov (AMD_S3LATE_PARAMS ptr [esi]).S3DataBlock.VolatileStorageSize, ecx
; Call in to the AmdS3LateRestore entry point
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
;; AGESA_SUCCESS All resume processes have been completed successfully.
.if (eax != AGESA_SUCCESS)
mov al, (AMD_S3LATE_PARAMS ptr [esi]).StdHeader.HeapStatus
mov ebx, AGESA_B2_ADDRESS
call AmdProcessAgesaErrors
.endif
; Allow AGESA to free the space used by AmdS3LateRestore
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdS3LateRestoreWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdLateRunApTaskWrapper
;
; Entry:
; Prior to this hook, AGESA will display - AGESA_TESTPOINT - D4h
; DS - 0000 with 4 gigabyte access
; ES - 0000 with 4 gigabyte access
;
; Exit:
; After this hook, AGESA will display - AGESA_TESTPOINT - D5h
; None
;
; Modified:
; None
;
; Purpose:
; This entry point is tightly connected with the "AgesaRunFcnOnAp"
; call out. The AGESA software will call the call-out "AgesaRunFcnOnAp";
; the host environment will then call this entry point to have the AP
; execute the requested function. This is needed late in the Post and
; Resume branches for running an AP task since the AGESA software has
; relinquished control of the APs to the host environment.
;
; Dependencies:
; The host environment must implement the"AgesaRunFcnOnAp" call-out
; and route execution to the target AP.
;
AmdLateRunApTaskWrapper PROC NEAR PUBLIC
local localCfgBlock:AMD_INTERFACE_PARAMS
pushad
; Prepare for the call to create and initialize the input parameters for AmdLateRunApTask
xor eax, eax
mov ax, ss
shl eax, 4
lea esi, localCfgBlock
add esi, eax
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.ImageBasePtr, AGESA_B2_ADDRESS
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_CREATE_STRUCT
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.AltImageBasePtr, 0
mov edx, SEG AmdCallout16
shl edx, 4
add edx, OFFSET AmdCallout16
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.CalloutPtr, edx
mov (AMD_INTERFACE_PARAMS ptr [esi]).AgesaFunctionName, AMD_LATE_RUN_AP_TASK
mov (AMD_INTERFACE_PARAMS ptr [esi]).AllocationMethod, PostMemDram
mov (AMD_INTERFACE_PARAMS ptr [esi]).NewStructSize, 0
push esi
mov dx, SEG AmdCalloutRouterPost
shl edx, 16
mov dx, OFFSET AmdCalloutRouterPost
push edx
call AmdBridge32
pop edx
mov esi, (AMD_INTERFACE_PARAMS ptr [esi]).NewStructPtr
; The structure has been initialized. Now modify the default settings as desired.
push es
mov ax, SEG AmdRunCodeOnApDataPointer
mov es, ax
mov eax, es:AmdRunCodeOnApDataPointer
mov (AP_EXE_PARAMS PTR [esi]).RelatedDataBlock, eax
mov eax, es:AmdRunCodeOnApDataSize
mov (AP_EXE_PARAMS PTR [esi]).RelatedBlockLength, eax
mov eax, es:AmdRunCodeOnApFunction
mov (AP_EXE_PARAMS PTR [esi]).FunctionNumber, eax
pop es
; Call in to the AmdLateRunApTask dispatcher
push edx
call AmdBridge32
pop edx
;; EAX = AGESA_STATUS
push es
mov bx, SEG AmdRunCodeOnApStatus
mov es, bx
mov es:AmdRunCodeOnApStatus, eax
pop es
; Allow AGESA to free the space used by AmdLateRunApTask
pop esi
mov (AMD_INTERFACE_PARAMS ptr [esi]).StdHeader.Func, AMD_RELEASE_STRUCT
call AmdBridge32
popad
ret
AmdLateRunApTaskWrapper ENDP
;+---------------------------------------------------------------------------
;
; AmdRunFuncOnAp (Required)
;
; Entry:
; Prior to this hook, AGESA will display - AGESA_TESTPOINT - E8h
; EDX - Local APIC ID of the target core.
; ESI - Pointer to an AP_EXE_PARAMS structure.
;
; typedef struct {
; IN OUT AMD_CONFIG_PARAMS StdHeader;
; IN UINT32 FunctionNumber;
; IN VOID *RelatedDataBlock;
; IN UINT32 RelatedDataBlockLength;
; } AP_EXE_PARAMS;
;
; Exit:
; After this hook, AGESA will display - AGESA_TESTPOINT - E9h
; EAX - Contains the AGESA_STATUS return code.
; AGESA_SUCCESS The function has completed successfully.
; AGESA_UNSUPPORTED This is a required function, so this value
; being returned causes a critical error
; response value from the AGESAT software
; function and no memory initialized.
; AGESA_WARNING The AP did not respond.
;
; Modified:
; EAX
;
; Purpose:
; This function is used after main memory has been initialized
; and the host environment has taken control of AP task dispatching.
; This function must cause the indicated function code to be executed
; upon the specified Application Processor. This procedure must be
; executed in 32-bit mode. This function is required to be implemented
; in the host environment.
;
; Dependencies:
; The host environment must route execution to the target AP and
; have that AP call the"AmdLateRunApTask" entry point.
;
AmdRunFuncOnAp PROC NEAR PUBLIC
push es
mov ax, SEG AmdRunCodeOnApDataPointer
mov es, ax
mov eax, (AP_EXE_PARAMS PTR [esi]).RelatedDataBlock
mov es:AmdRunCodeOnApDataPointer, eax
mov eax, (AP_EXE_PARAMS PTR [esi]).RelatedBlockLength
mov es:AmdRunCodeOnApDataSize, eax
mov eax, (AP_EXE_PARAMS PTR [esi]).FunctionNumber
mov es:AmdRunCodeOnApFunction, eax
mov eax, AGESA_UNSUPPORTED
mov es:AmdRunCodeOnApStatus, eax
pop es
call myRunFuncOnAp
push es
mov ax, SEG AmdRunCodeOnApStatus
mov es, ax
mov eax, es:AmdRunCodeOnApStatus
pop es
ret
AmdRunFuncOnAp ENDP
;+---------------------------------------------------------------------------
;
; AmdCalloutRouterPost
;
; Entry:
; ECX - Callout function number
; EDX - Function-specific UINTN
; ESI - Pointer to function specific data
;
; Exit:
; EAX - Contains the AGESA_STATUS return code.
;
; Modified:
; None
;
; Purpose:
; The call out router function for AmdInitEnv,
; AmdInitMid, AmdInitLate, AmdS3Save, and
; AmdS3LateRestore.
;
; Dependencies:
; None
;
AmdCalloutRouterPost PROC FAR PUBLIC USES ECX EBX ESI BX DI DS ES
xor ax, ax
mov ds, ax
mov es, ax
lea di, cs:CalloutRouterTablePost
mov eax, AGESA_UNSUPPORTED
loopThruTable:
cmp di, OFFSET cs:CalloutRouterTablePostEnd
jae amdCpuCalloutExit ; exit with AGESA_UNSUPPORTED
cmp ecx, cs:[di].sOemCallout.FuncName
je FoundMatch
add di, SIZEOF sOemCallout
jmp loopThruTable
FoundMatch:
mov bx, cs:[di].sOemCallout.FuncPtr
call bx
amdCpuCalloutExit:
ret
AmdCalloutRouterPost ENDP
;----------------------------------------------------------------------------
; Define the callout dispatch table for the POST segment
;----------------------------------------------------------------------------
CalloutRouterTablePost LABEL BYTE
;; Add entries as desired.
sOemCallout <AGESA_ALLOCATE_BUFFER, OFFSET myAllocateBuffer>
sOemCallout <AGESA_DEALLOCATE_BUFFER, OFFSET myDeallocateBuffer>
sOemCallout <AGESA_LOCATE_BUFFER, OFFSET myLocateBuffer>
sOemCallout <AGESA_RUNFUNC_ONAP, OFFSET AmdRunFuncOnAp>
CalloutRouterTablePostEnd LABEL BYTE
AMD_POST_END
;----------------------------------------------------------------------------
; CPU DATA SEGMENT
; This segment must be writable, and present at the time that
; AmdInitLate is run.
;----------------------------------------------------------------------------
CPU_DATASEG_START
;; Data used to store pointers for later use by the host environment.
PUBLIC AmdAcpiSratPointer
PUBLIC AmdAcpiSratSize
PUBLIC AmdAcpiSlitPointer
PUBLIC AmdAcpiSlitSize
PUBLIC AmdAcpiSsdtPointer
PUBLIC AmdAcpiSsdtSize
PUBLIC AmdAcpiWheaMcePointer
PUBLIC AmdAcpiWheaMceSize
PUBLIC AmdAcpiWheaCmcPointer
PUBLIC AmdAcpiWheaCmcSize
PUBLIC AmdDmiInfoPointer
AmdAcpiSratPointer DWORD ?
AmdAcpiSratSize DWORD ?
AmdAcpiSlitPointer DWORD ?
AmdAcpiSlitSize DWORD ?
AmdAcpiSsdtPointer DWORD ?
AmdAcpiSsdtSize DWORD ?
AmdAcpiWheaMcePointer DWORD ?
AmdAcpiWheaMceSize DWORD ?
AmdAcpiWheaCmcPointer DWORD ?
AmdAcpiWheaCmcSize DWORD ?
AmdDmiInfoPointer DWORD ?
;; Data used for communication between the AP and the BSP.
PUBLIC AmdRunCodeOnApDataPointer
PUBLIC AmdRunCodeOnApDataSize
PUBLIC AmdRunCodeOnApFunction
PUBLIC AmdRunCodeOnApStatus
AmdRunCodeOnApDataPointer DWORD ?
AmdRunCodeOnApDataSize DWORD ?
AmdRunCodeOnApFunction DWORD ?
AmdRunCodeOnApStatus DWORD ?
CPU_DATASEG_END
END
|
; A250353: Number of length 4 arrays x(i), i=1..4 with x(i) in i..i+n and no value appearing more than 2 times.
; 16,75,235,581,1221,2287,3935,6345,9721,14291,20307,28045,37805,49911,64711,82577,103905,129115,158651,192981,232597,278015,329775,388441,454601,528867,611875,704285,806781,920071,1044887,1181985,1332145,1496171,1674891,1869157,2079845,2307855,2554111,2819561,3105177,3411955,3740915,4093101,4469581,4871447,5299815,5755825,6240641,6755451,7301467,7879925,8492085,9139231,9822671,10543737,11303785,12104195,12946371,13831741,14761757,15737895,16761655,17834561,18958161,20134027,21363755,22648965,23991301,25392431,26854047,28377865,29965625,31619091,33340051,35130317,36991725,38926135,40935431,43021521,45186337,47431835,49759995,52172821,54672341,57260607,59939695,62711705,65578761,68543011,71606627,74771805,78040765,81415751,84899031,88492897,92199665,96021675,99961291,104020901,108202917,112509775,116943935,121507881,126204121,131035187,136003635,141112045,146363021,151759191,157303207,162997745,168845505,174849211,181011611,187335477,193823605,200478815,207303951,214301881,221475497,228827715,236361475,244079741,251985501,260081767,268371575,276857985,285544081,294432971,303527787,312831685,322347845,332079471,342029791,352202057,362599545,373225555,384083411,395176461,406508077,418081655,429900615,441968401,454288481,466864347,479699515,492797525,506161941,519796351,533704367,547889625,562355785,577106531,592145571,607476637,623103485,639029895,655259671,671796641,688644657,705807595,723289355,741093861,759225061,777686927,796483455,815618665,835096601,854921331,875096947,895627565,916517325,937770391,959390951,981383217,1003751425,1026499835,1049632731,1073154421,1097069237,1121381535,1146095695,1171216121,1196747241,1222693507,1249059395,1275849405,1303068061,1330719911,1358809527,1387341505,1416320465,1445751051,1475637931,1505985797,1536799365,1568083375,1599842591,1632081801,1664805817,1698019475,1731727635,1765935181,1800647021,1835868087,1871603335,1907857745,1944636321,1981944091
mov $1,$0
mov $3,$0
trn $0,1
sub $1,$0
add $1,16
mov $2,29
mov $4,$3
lpb $2,1
add $1,$4
sub $2,1
lpe
mov $6,$3
lpb $6,1
add $5,$4
sub $6,1
lpe
mov $2,20
mov $4,$5
lpb $2,1
add $1,$4
sub $2,1
lpe
mov $5,0
mov $6,$3
lpb $6,1
add $5,$4
sub $6,1
lpe
mov $2,8
mov $4,$5
lpb $2,1
add $1,$4
sub $2,1
lpe
mov $5,0
mov $6,$3
lpb $6,1
add $5,$4
sub $6,1
lpe
mov $2,1
mov $4,$5
lpb $2,1
add $1,$4
sub $2,1
lpe
|
; A025901: Expansion of 1/((1-x^6)(1-x^7)(1-x^12)).
; 1,0,0,0,0,0,1,1,0,0,0,0,2,1,1,0,0,0,2,2,1,1,0,0,3,2,2,1,1,0,3,3,2,2,1,1,4,3,3,2,2,1,5,4,3,3,2,2,6,5,4,3,3,2,7,6,5,4,3,3,8,7,6,5,4,3,9,8,7,6,5,4,10,9,8,7,6,5,11,10
mov $3,2
mov $5,$0
lpb $3
mov $0,$5
sub $3,1
add $0,$3
trn $0,1
seq $0,29110 ; Expansion of 1/((1-x)(1-x^6)(1-x^7)(1-x^12)).
mov $2,$3
mul $2,$0
add $4,$2
lpe
min $5,1
mul $5,$0
mov $0,$4
sub $0,$5
|
%include "defs.asm"
;************************* physseed64.asm **********************************
; Author: Agner Fog
; Date created: 2010-08-03
; Last modified: 2013-09-13
; Source URL: www.agner.org/optimize
; Project: asmlib.zip
; C++ prototype:
; extern "C" int PhysicalSeed(int seeds[], int NumSeeds);
;
; Description:
; Generates a non-deterministic random seed from a physical random number generator
; which is available on some processors.
; Uses the time stamp counter (which is less random) if no physical random number
; generator is available.
; The code is not optimized for speed because it is typically called only once.
;
; Parameters:
; int seeds[] An array which will be filled with random numbers
; int NumSeeds Indicates the desired number of 32-bit random numbers
;
; Return value: 0 Failure. No suitable instruction available (processor older than Pentium)
; 1 No physical random number generator. Used time stamp counter instead
; 2 Success. VIA physical random number generator used
; 3 Success. Intel physical random number generator used
; 4 Success. Intel physical seed generator used
;
; The return value will indicate the availability of a physical random number generator
; even if NumSeeds = 0.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
default rel
%define NUM_TRIES 20 ; max number of tries for rdseed and rdrand instructions
%define TESTING 0 ; 1 for test only
global PhysicalSeed
; Direct entries to CPU-specific versions
global PhysicalSeedNone: function
global PhysicalSeedRDTSC: function
global PhysicalSeedVIA: function
global PhysicalSeedRDRand: function
global PhysicalSeedRDSeed function
; ***************************************************************************
; Define registers used for function parameters, used in 64-bit mode only
; ***************************************************************************
%IFDEF WINDOWS
%define par1 rcx
%define par2 rdx
%define par3 r8
%define par1d ecx
%define par2d edx
%define par3d r8d
%ENDIF
%IFDEF UNIX
%define par1 rdi
%define par2 rsi
%define par3 rdx
%define par1d edi
%define par2d esi
%define par3d edx
%ENDIF
SECTION .text align=16
%IFDEF WINDOWS
global PhysicalSeedD@8 ; DLL version
PhysicalSeedD@8:
%ENDIF
PhysicalSeed:
jmp [PhysicalSeedDispatch] ; Go to appropriate version, depending on instructions available
PhysicalSeedRDSeed:
push rbx
test par2d, par2d ; NumSeeds
jz S300
js S900
mov par3d, par2d ; NumSeeds
shr par3d, 1
jz S150
; do 64 bits at a time
S100: mov ebx, NUM_TRIES
S110: ; rdseed rax
%if TESTING
mov eax, par3d
stc
%ELSE
db 48h, 0Fh, 0C7h, 0F8h ; rdseed rax
%ENDIF
jc S120
; failed. try again
dec ebx
jz S900
jmp S110
S120: mov [par1], rax
add par1, 8
dec par3d
jnz S100 ; loop 64 bits
S150:
and par2d, 1
jz S300
; an odd 32 bit remains
S200: mov ebx, NUM_TRIES
S210: ; rdseed rax
%if TESTING
mov eax, par3d
stc
%ELSE
db 0Fh, 0C7h, 0F8h ; rdseed eax
%ENDIF
jc S220
; failed. try again
dec ebx
jz S900
jmp S210
S220: mov [par1], eax
S300: mov eax, 4 ; return value
pop rbx
ret
S900: ; failure
xor eax, eax ; return 0
pop rbx
ret
PhysicalSeedRDRand:
push rbx
test par2d, par2d ; NumSeeds
jz R300
js R900
mov par3d, par2d ; NumSeeds
shr par3d, 1 ; NumSeeds/2
jz R150
; do 64 bits at a time
R100: mov ebx, NUM_TRIES
R110: ; rdrand rax
%if TESTING
mov eax, par3d
stc
%ELSE
db 48h, 0Fh, 0C7h, 0F0h ; rdrand rax
%ENDIF
jc R120
; failed. try again
dec ebx
jz R900
jmp R110
R120: mov [par1], rax
add par1, 8
dec par3d
jnz R100 ; loop 64 bits
R150:
and par2d, 1
jz R300
; an odd 32 bit remains
R200: mov ebx, NUM_TRIES
R210: ; rdrand eax
%if TESTING
mov eax, par3d
stc
%ELSE
db 0Fh, 0C7h, 0F0h ; rdrand eax
%ENDIF
jc R220
; failed. try again
dec ebx
jz R900
jmp R210
R220: mov [par1], eax
R300: mov eax, 4 ; return value
pop rbx
ret
R900: ; failure
xor eax, eax ; return 0
pop rbx
ret
PhysicalSeedVIA:
; VIA XSTORE supported
push rbx
%IFDEF WINDOWS
push rsi
push rdi
mov rdi, rcx ; seeds
mov esi, edx ; NumSeeds
%ENDIF
mov ecx, esi ; NumSeeds
and ecx, -2 ; round down to nearest even
jz T200 ; NumSeeds <= 1
; make an even number of random dwords
shl ecx, 2 ; number of bytes (divisible by 8)
mov edx, 3 ; quality factor
%if TESTING
mov eax, 1
rep stosb
%ELSE
db 0F3H, 00FH, 0A7H, 0C0H ; rep xstore instuction
%ENDIF
T200:
test esi, 1
jz T300
; NumSeeds is odd. Make 8 bytes in temporary buffer and store 4 of the bytes
mov rbx, rdi ; current output pointer
mov ecx, 4 ; Will generate 4 or 8 bytes, depending on CPU
mov edx, 3 ; quality factor
push rcx ; make temporary space on stack
mov rdi, rsp ; point to buffer on stack
%if TESTING
mov eax, 1
rep stosb
%ELSE
db 0F3H, 00FH, 0A7H, 0C0H ; rep xstore instuction
%ENDIF
pop rax
mov [rbx], eax ; store the last 4 bytes
T300:
mov eax, 2 ; return value
%IFDEF WINDOWS
pop rdi
pop rsi
%ENDIF
pop rbx
ret
PhysicalSeedRDTSC:
%IFDEF WINDOWS
push rbx
push rcx
push rdx
xor eax, eax
cpuid ; serialize
rdtsc ; get time stamp counter
pop rbx ; numseeds
pop rcx ; seeds
test ebx, ebx
jz U300 ; zero seeds
js U900 ; failure
mov [rcx], eax ; store time stamp counter as seeds[0]
add rcx, 4
dec ebx
jz U300
mov [rcx], edx ; store upper part of time stamp counter as seeds[1]
add rcx, 4
dec ebx
jz U300
xor eax, eax
U100: mov [rcx], eax ; store 0 for the rest
add rcx, 4
dec ebx
jnz U100
U300: mov eax, 1 ; return value
pop rbx
ret
U900: ; failure
xor eax, eax ; return 0
pop rbx
ret
%ELSE ; UNIX
push rbx
xor eax, eax
cpuid ; serialize
rdtsc ; get time stamp counter
test esi, esi ; numseeds
jz U300 ; zero seeds
js U900 ; failure
mov [rdi], eax ; store time stamp counter as seeds[0]
add rdi, 4
dec esi
jz U300
mov [rdi], edx ; store upper part of time stamp counter as seeds[1]
add rdi, 4
dec esi
jz U300
xor eax, eax
U100: mov [rdi], eax ; store 0 for the rest
add rdi, 4
dec esi
jnz U100
U300: mov eax, 1 ; return value
pop rbx
ret
U900: ; failure
xor eax, eax ; return 0
pop rbx
ret
%ENDIF
PhysicalSeedNone: ; no possible generation
xor eax, eax
test par2d, par2d ; numseeds
jz N200
N100: mov [par1], eax
add par1, 4
dec par2d
jnz N100
N200: ret ; return 0
PhysicalSeedDispatcher:
push rbx
%IFDEF WINDOWS
push rcx
push rdx
%ENDIF
; test if RDSEED supported
xor eax, eax
cpuid
cmp eax, 7
jb P200 ; RDSEED not supported
mov eax, 7
xor ecx, ecx
cpuid
bt ebx, 18
; jc USE_RDSEED ; not tested yet!!
P200: ; test if RDRAND supported
mov eax, 1
cpuid
bt ecx, 30
jc USE_RDRAND
; test if VIA xstore instruction supported
mov eax, 0C0000000H
push rax
cpuid
pop rbx
cmp eax, ebx
jna P300 ; not a VIA processor
lea eax, [rbx+1]
cpuid
bt edx, 3
jc VIA_METHOD
P300: ; test if RDTSC supported
mov eax, 1
cpuid
bt edx, 4
jc USE_RDTSC ; XSTORE instruction not supported or not enabled
FAILURE: ; No useful instruction supported
lea rax, [PhysicalSeedNone]
jmp P800
USE_RDRAND: ; Use RDRAND instruction
lea rax, [PhysicalSeedRDRand]
jmp P800
USE_RDSEED: ; Use RDSEED instruction (not tested yet)
lea rax, [PhysicalSeedRDSeed]
jmp P800
VIA_METHOD: ; Use VIA xstore instructions
lea rax, [PhysicalSeedVIA]
jmp P800
USE_RDTSC:
lea rax, [PhysicalSeedRDTSC]
;jmp P800
P800: mov [PhysicalSeedDispatch], rax
%IFDEF WINDOWS
pop rdx
pop rcx
%ENDIF
pop rbx
jmp rax ; continue in dispatched version
; -----------------------------------------------------------------
; Data section for dispatcher
; -----------------------------------------------------------------
SECTION .data
; Pointer to appropriate versions. Initially point to dispatcher
PhysicalSeedDispatch DQ PhysicalSeedDispatcher
%IFDEF POSITIONINDEPENDENT
; Fix potential problem in Mac linker
DD 0, 0
%ENDIF
|
; A122416: Numbers from an irrationality measure for e, with a(1) = 2.
; Submitted by Jamie Morken(s3)
; 2,3,4,5,6,4,8,5,7,6,12,5,14,8,6,7,18,7,20,6,8,12,24,5,11,14,10,8,30,6,32,9,12,18,8,7,38,20,14,6,42,8,44,12,7,24,48,7,15,11,18,14,54,10,12,8,20,30,60,6,62,32,8,9,14,12,68,18,24,8,72,7,74,38,11,20,12,14,80,7,10
add $0,1
mov $2,2
mov $3,$0
mov $4,$0
mov $5,1
lpb $3
cmp $0,$5
mov $6,$2
add $2,1
mul $5,$6
mov $6,$0
cmp $6,0
sub $3,$6
mod $5,$4
lpe
mov $0,$2
|
; A089820: Number of subsets of {1,..,n} containing at least one prime.
; Submitted by Jamie Morken(w4)
; 0,2,6,12,28,56,120,240,480,960,1984,3968,8064,16128,32256,64512,130048,260096,522240,1044480,2088960,4177920,8372224,16744448,33488896,66977792,133955584,267911168,536346624,1072693248,2146435072,4292870144,8585740288,17171480576,34342961152,68685922304,137405399040,274810798080,549621596160,1099243192320,2198754820096,4397509640192,8795556151296,17591112302592,35182224605184,70364449210368,140733193388032,281466386776064,562932773552128,1125865547104256,2251731094208512,4503462188417024
mov $3,$0
seq $0,89819 ; Number of subsets of {1,2,...,n} containing no primes.
mov $2,2
add $3,1
pow $2,$3
sub $2,$0
mov $0,$2
|
#include "ChordAlgSrc/chordalg_string.h"
#include <algorithm>
#include <cstring>
#include <iterator>
#include <sstream>
#include <string>
namespace chordalg {
// True iff str is a natural number
bool IsNum(const std::string& str) {
for (auto c : str) {
if (!std::isdigit(c)) {
return false;
}
}
return str.empty() ? false : true;
}
// Splits string and changes chars to lowercase
StringTokens Split(const std::string& str, const std::string& delim) {
StringTokens tokens;
char* pch = nullptr;
char* cstr = new char[str.length() + 1];
char* saveptr;
std::snprintf(cstr, str.length() + 1, "%s", str.c_str());
pch = strtok_r(cstr, delim.c_str(), &saveptr);
while (pch) {
std::string tok(pch);
for (size_t i = 0; i < tok.length(); ++i) {
if (isalpha(tok[i]) && !islower(tok[i])) {
tok[i] = tolower(tok[i]);
}
}
tokens.push_back(tok);
pch = strtok_r(nullptr, delim.c_str(), &saveptr);
}
delete cstr;
return tokens;
}
std::string VectorToStr(const std::vector< size_t >& V) {
if (V.empty()) {
return std::string();
} else {
std::ostringstream oss;
std::copy(V.begin(), V.end() - 1, std::ostream_iterator<size_t>(oss, " "));
oss << V.back();
return oss.str();
}
}
} // namespace chordalg
|
; A325517: a(n) = n*((2*n + 1)*(2*n^2 + 2*n + 3) - 3*(-1)^n)/24.
; 0,1,6,24,64,145,282,504,832,1305,1950,2816,3936,5369,7154,9360,12032,15249,19062,23560,28800,34881,41866,49864,58944,69225,80782,93744,108192,124265,142050,161696,183296,207009,232934,261240,292032,325489,361722,400920,443200
mov $15,$0
mov $17,$0
lpb $17
clr $0,15
mov $0,$15
sub $17,1
sub $0,$17
mov $12,$0
mov $14,$0
lpb $14
clr $0,12
mov $0,$12
sub $14,1
sub $0,$14
mov $9,$0
mov $11,$0
lpb $11
mov $0,$9
sub $11,1
sub $0,$11
mov $1,$0
sub $0,1
mov $2,$1
trn $2,2
mov $6,0
add $6,$2
add $6,$0
gcd $0,2
mul $6,$0
add $1,$6
add $10,$1
lpe
add $13,$10
lpe
add $16,$13
lpe
mov $1,$16
|
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2013 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// @ref gtc_type_ptr
/// @file glm/gtc/type_ptr.hpp
/// @date 2009-05-06 / 2011-06-05
/// @author Christophe Riccio
///
/// @see core (dependence)
/// @see gtc_half_float (dependence)
/// @see gtc_quaternion (dependence)
///
/// @defgroup gtc_type_ptr GLM_GTC_type_ptr
/// @ingroup gtc
///
/// @brief Handles the interaction between pointers and vector, matrix types.
///
/// This extension defines an overloaded function, glm::value_ptr, which
/// takes any of the \ref core_template "core template types". It returns
/// a pointer to the memory layout of the object. Matrix types store their values
/// in column-major order.
///
/// This is useful for uploading data to matrices or copying data to buffer objects.
///
/// Example:
/// @code
/// #include <glm/glm.hpp>
/// #include <glm/gtc/type_ptr.hpp>
///
/// glm::vec3 aVector(3);
/// glm::mat4 someMatrix(1.0);
///
/// glUniform3fv(uniformLoc, 1, glm::value_ptr(aVector));
/// glUniformMatrix4fv(uniformMatrixLoc, 1, GL_FALSE, glm::value_ptr(someMatrix));
/// @endcode
///
/// <glm/gtc/type_ptr.hpp> need to be included to use these functionalities.
///////////////////////////////////////////////////////////////////////////////////
#ifndef GLM_GTC_type_ptr
#define GLM_GTC_type_ptr GLM_VERSION
// Dependency:
#include "../glm.hpp"
#include "../gtc/half_float.hpp"
#include "../gtc/quaternion.hpp"
#include <cstring>
#if(defined(GLM_MESSAGES) && !defined(glm_ext))
# pragma message("GLM: GLM_GTC_type_ptr extension included")
#endif
namespace glm
{
/// @addtogroup gtc_type_ptr
/// @{
/// Return the constant address to the data of the input parameter.
/// @see gtc_type_ptr
template<typename genType>
typename genType::value_type const * value_ptr(genType const & vec);
/// Build a vector from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tvec2<T> make_vec2(T const * const ptr);
/// Build a vector from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tvec3<T> make_vec3(T const * const ptr);
/// Build a vector from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tvec4<T> make_vec4(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat2x2<T> make_mat2x2(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat2x3<T> make_mat2x3(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat2x4<T> make_mat2x4(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat3x2<T> make_mat3x2(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat3x3<T> make_mat3x3(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat3x4<T> make_mat3x4(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat4x2<T> make_mat4x2(
T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat4x3<T> make_mat4x3(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat4x4<T> make_mat4x4(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat2x2<T> make_mat2(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat3x3<T> make_mat3(T const * const ptr);
/// Build a matrix from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tmat4x4<T> make_mat4(T const * const ptr);
/// Build a quaternion from a pointer.
/// @see gtc_type_ptr
template<typename T>
detail::tquat<T> make_quat(T const * const ptr);
/// @}
}//namespace glm
#include "type_ptr.inl"
#endif//GLM_GTC_type_ptr
|
; A315745: Coordination sequence Gal.4.137.4 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,6,12,18,23,28,34,40,46,52,58,64,69,74,80,86,92,98,104,110,115,120,126,132,138,144,150,156,161,166,172,178,184,190,196,202,207,212,218,224,230,236,242,248,253,258,264,270,276,282
mov $2,$0
sub $0,1
mov $4,5
lpb $0
add $1,$0
sub $4,$3
trn $4,1
add $0,$4
trn $0,6
trn $1,$0
trn $0,2
add $3,3
lpe
lpb $2
add $1,5
sub $2,1
lpe
add $1,1
|
; A024896: Numbers k such that 5*k - 2 is prime.
; 1,3,5,9,11,15,17,21,23,33,35,39,45,47,53,57,59,63,71,75,77,87,89,93,101,105,113,119,123,129,131,135,137,147,149,155,165,171,173,177,191,197,203,207,213,219,221,225,231,233,239,243,245,257,261,275,285,287,291,297,299,305,309,311,317,323,333,339,345,347,351,357,365,375,383,387,395,399,401,411,413,417,423,429,431,441,443,449,455,459,467,477,479,485,495,501,509,519,527,533
seq $0,87505 ; Numbers k such that 5*k+3 is a prime.
add $0,1
|
.data
str: .space 256
rev: .space 256
newLine: .byte '\n'
string: .asciiz "Enter string: "
revstring: .asciiz "Reversed string:"
.text
main:
la $a0,string
li $v0,4
syscall
la $a0,str
la $a1,6
li $v0,8
syscall
la $t3, str
li $t1,-1
lb $t4, newl
strloop:
add $t1,$t1,1
lb $t2, str+0($t1) #not the best method imo, would be better to load address into a register and then use that, rather than add address to register each time
beq $t2,$t4,revstr
bne $t2,$0,strloop
revstr:
add $t1,$t1,-1
add $t0,$t0,1
blt $t1,0,end
lb $t2, str+0($t1)
sb $t2,rev+-1($t0)
j revstr
end:
xor $t4,$t4,$t4
la $a0,revstring
li $v0,4
syscall
sb $t4,rev+0($t0)
la $a0,rev
li $v0,4
syscall
li $v0,10
syscall |
SECTION "Vblank", ROM0[$0040]
call VblankInt
reti
SECTION "LCDC", ROM0[$0048]
reti
SECTION "Timer", ROM0[$0050]
call TimerInt
reti
SECTION "Serial", ROM0[$0058]
call SerialInt
reti
SECTION "Joypad", ROM0[$0060]
reti
SECTION "Entry", ROM0[$100]
di
jp Start
SECTION "Header", ROM0[$104]
REPT $150-$104
db 0
ENDR |
#include <iostream>
#include<math.h>
#include<iomanip>
#include<cmath>
#include<fstream>
using namespace std;
float f(float x){
return (pow(x,0.1))*(1.2-x)*(1-pow(2.71828,20*(x-1)));
}
float trapezoidal(float a, float b, int n){
float x[10000];
for(int i=0; i<=n; i++){
x[i] = a + i*((b-a)/n);
}
float sum = 0.0;
for(int i=0; i<n; i++){
sum+=f(x[i]) + f(x[i+1]);
}
return ((b-a)/(2*n))*sum;
}
float simpson1_3(float a, float b, int n){
float x[10000];
for(int i=0; i<=n; i++){
x[i] = a + i*((b-a)/n);
}
float sum = 0.0;
for(int i=0; i<=n; i++){
if(i==0 || i==n){
sum+=f(x[i]);
}
else if(i%2==0){
sum+=2*f(x[i]);
}
else{
sum+=4*f(x[i]);
}
}
return ((b-a)/(3*n))*sum;
}
float simpson3_8Partial(float a, float b, int n){
float x[1000];
float h = (b-a)/3;
x[0] = a;
x[1] = a+h;
x[2] = a+ 2*h;
x[3] = b;
return ((b-a)/(8))*(f(x[0]) + 3*f(x[1]) + 3*f(x[2]) + f(x[3]));
}
float simpson3_8(float a, float b, int n){
float x[10000];
for(int i=0; i<=n; i++){
x[i] = a + i*((b-a)/n);
}
float sum = 0.0;
for(int i=0; i<n; i++){
sum+=simpson3_8Partial(x[i],x[i+1],n);
}
return sum;
}
int main(){
float a = 0, b = 1;
//cout<<"Enter the value of n:\t";
int n = 5;
//cin>>n;
ofstream myfile;
myfile.open ("example.csv", ios::out);
while(n<500){
float err1, err2, err3, val1, val2, val3;
cout<<endl<<n<<endl;
cout<<"\nTrapezoidal rule: ";
val1 = trapezoidal(a,b,n);
cout<<val1;
err1 = abs(val1 - 0.602298)/0.00602298;
cout<<"\nSimpson 1/3 rule: ";
val2 = simpson1_3(a,b,n);
cout<<val2;
err2 = abs(val2 - 0.602298)/0.00602298;
cout<<"\nSimpson 3/8 rule: ";
val3 = simpson3_8(a,b,n);
cout<<val3<<endl;
err3 = abs(val3 - 0.602298)/0.00602298;
myfile<<n<<","<<err1<<","<<err2<<","<<err3<<"\n";
n+=5;
}
myfile.close();
return 0;
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "MinimalPerspective.h"
// Berry
#include "berryIViewLayout.h"
MinimalPerspective::MinimalPerspective()
{
}
void MinimalPerspective::CreateInitialLayout(berry::IPageLayout::Pointer layout)
{
// Hides the editor area.
layout->SetEditorAreaVisible(false);
}
|
;================================================================================
; insert kholdstare & trinexx shell gfx file
;--------------------------------------------------------------------------------
GFX_Kholdstare_Shell:
incbin shell.gfx
GFX_Trinexx_Shell:
incbin rocks.gfx
GFX_Trinexx_Shell2:
incbin rocks2.gfx
;--------------------------------------------------------------------------------
|
; A264847: Pluritriangular numbers: a(0) = 0; a(n+1) = a(n) + the number of digits in terms a(0)..a(n).
; 0,1,3,6,10,16,24,34,46,60,76,94,114,137,163,192,224,259,297,338,382,429,479,532,588,647,709,774,842,913,987,1064,1145,1230,1319,1412,1509,1610,1715,1824,1937,2054,2175,2300,2429,2562,2699,2840,2985,3134,3287,3444,3605,3770,3939
mov $10,$0
mov $12,$0
lpb $12
clr $0,10
mov $0,$10
sub $12,1
sub $0,$12
mov $7,$0
mov $9,$0
lpb $9
clr $0,7
mov $0,$7
sub $9,1
sub $0,$9
add $1,$0
add $1,$0
sub $0,$1
mul $0,2
mov $1,1
mul $1,$0
mov $2,2
sub $5,$0
lpb $0
trn $0,$5
add $0,1
add $0,$5
add $1,12
sub $1,$0
mov $0,$1
add $2,1
mul $2,3
div $0,$2
sub $5,$5
add $6,1
lpe
add $8,$6
lpe
add $11,$8
lpe
mov $1,$11
|
#include "tools.h"
#include <iostream>
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
using std::cout;
using std::endl;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
// initialize an empty rmse array
VectorXd rmse(4);
rmse << 0,0,0,0;
// determine if any bad inputs
if (estimations.size() == 0) {
cout << "Estimation vector size should not be zero!" << endl;
return rmse;
}
if (estimations.size() != ground_truth.size()){
cout << "Estimation vector size should equal to ground truth vector size!" << endl;
return rmse;
}
// calculate total squared residuals
for (unsigned int i=0; i < estimations.size(); ++i) {
VectorXd residual = estimations[i] - ground_truth[i];
residual = residual.array() * residual.array();
rmse += residual;
}
// calculate the final rmse
rmse = rmse / estimations.size();
rmse = rmse.array().sqrt();
return rmse;
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
// initialize an empty Hj matrix
MatrixXd Hj(3,4);
// recover state parameters
float px = x_state(0);
float py = x_state(1);
float vx = x_state(2);
float vy = x_state(3);
// calculate Jacobian
float c1 = px*px + py*py;
float c2 = sqrt(c1);
float c3 = c1 * c2;
// check division by zero
// compute the Jacobian matrix
if (fabs(c1) > 0.0001) {
Hj << (px/c2), (py/c2), 0, 0,
-(py/c1), (px/c1), 0, 0,
py*(vx*py-vy*px)/c3, px*(vy*px-vx*py)/c3, px/c2, py/c2;
}
else{
cout << "CalculateJacobian() - Error - Division by zero" << endl;
}
return Hj;
}
|
;
; Y8950 MSX-AUDIO driver
;
; ports
MSXAudio_STATUS_PORT: equ 0C0H
MSXAudio_ADDRESS_PORT: equ 0C0H
MSXAudio_DATA_PORT: equ 0C1H
MSXAudio_CLOCK: equ 3579545
; registers
MSXAudio_TEST: equ 01H
MSXAudio_TIMER_1: equ 02H
MSXAudio_TIMER_2: equ 03H
MSXAudio_FLAG_CONTROL: equ 04H
MSXAudio_KEYBOARD_IN: equ 05H
MSXAudio_KEYBOARD_OUT: equ 06H
MSXAudio_ADPCM_CONTROL: equ 07H
MSXAudio_MISC_CONTROL: equ 08H
MSXAudio_START_ADDRESS_L: equ 09H
MSXAudio_START_ADDRESS_H: equ 0AH
MSXAudio_STOP_ADDRESS_L: equ 0BH
MSXAudio_STOP_ADDRESS_H: equ 0CH
MSXAudio_PRESCALE_L: equ 0DH
MSXAudio_PRESCALE_H: equ 0EH
MSXAudio_ADPCM_DATA: equ 0FH
MSXAudio_DELTA_N_L: equ 10H
MSXAudio_DELTA_N_H: equ 11H
MSXAudio_ENVELOPE_CONTROL: equ 12H
MSXAudio_DAC_DATA_L: equ 15H
MSXAudio_DAC_DATA_H: equ 16H
MSXAudio_DAC_DATA_SHIFT: equ 17H
MSXAudio_IO_CONTROL: equ 18H
MSXAudio_IO_DATA: equ 19H
MSXAudio_PCM_DATA: equ 1AH
MSXAudio_FM_BASE: equ 20H
MSXAudio: MACRO
this:
super: Driver MSXAudio_name, MSXAudio_CLOCK, Driver_PrintInfoImpl
safeControlMirror:
ds MSXAudio_FM_BASE
; e = register
; d = value
SafeWriteRegister:
ld a,e
cp MSXAudio_FM_BASE
jr c,MaskControl
; a = register
; d = value
WriteRegister:
out (MSXAudio_ADDRESS_PORT),a
basePort: equ $ - 1
in a,(MSXAudio_STATUS_PORT) ; wait 12 / 3.58 µs
ld a,(hl) ; "
ld a,d
out (MSXAudio_DATA_PORT),a
in a,(09AH) ; wait 84 / 3.58 µs
in a,(09AH) ; R800: 72 / 7.16 µs
ret
MaskControl:
ld hl,safeControlMirror
ld c,a
ld b,0
add hl,bc
ld (hl),d
cp MSXAudio_FLAG_CONTROL
ret z
cp MSXAudio_MISC_CONTROL
jr z,MaskMiscControl
jr c,WriteRegister
cp MSXAudio_START_ADDRESS_H + 1
jr c,WriteStartAddress
cp MSXAudio_STOP_ADDRESS_H + 1
jr c,WriteStopAddress
cp MSXAudio_IO_CONTROL
jr c,WriteRegister
cp MSXAudio_PCM_DATA
jr nc,WriteRegister
ret
MaskMiscControl:
ld a,d
and 11000100B
ld d,a
ld a,e
jr WriteRegister
WriteStartAddress:
ld hl,safeControlMirror + MSXAudio_MISC_CONTROL
bit 0,(hl)
jr z,WriteRegister
ld hl,(safeControlMirror + MSXAudio_START_ADDRESS_L)
add hl,hl
add hl,hl
add hl,hl
ld d,l
ld a,MSXAudio_START_ADDRESS_L
call WriteRegister
ld d,h
ld a,MSXAudio_START_ADDRESS_H
jr WriteRegister
WriteStopAddress:
ld hl,safeControlMirror + MSXAudio_MISC_CONTROL
bit 0,(hl)
jr z,WriteRegister
ld hl,(safeControlMirror + MSXAudio_STOP_ADDRESS_L)
add hl,hl
add hl,hl
add hl,hl
ld a,l
or 00000111B
ld d,a
ld a,MSXAudio_STOP_ADDRESS_L
call WriteRegister
ld d,h
ld a,MSXAudio_STOP_ADDRESS_H
jr WriteRegister
; bc = count
; hl = source
WriteADPCMData: PROC
di
ld d,70H
ld a,MSXAudio_FLAG_CONTROL
call WriteRegister
dec bc
inc b
inc c
ld e,b
ld b,c
ld c,MSXAudio_DATA_PORT
ld a,MSXAudio_ADPCM_DATA
out (MSXAudio_ADDRESS_PORT),a ; wait 12 / 3.58 µs after
jr Wait
Next:
in a,(MSXAudio_STATUS_PORT) ; wait 12 / 3.58 µs
ld a,MSXAudio_FLAG_CONTROL
out (MSXAudio_ADDRESS_PORT),a
in a,(MSXAudio_STATUS_PORT) ; wait 12 / 3.58 µs
ld a,(hl) ; "
ld a,11110000B
out (MSXAudio_DATA_PORT),a
in a,(MSXAudio_STATUS_PORT) ; wait 12 / 3.58 µs
ld a,(hl) ; "
ld a,MSXAudio_ADPCM_DATA
out (MSXAudio_ADDRESS_PORT),a ; wait 12 / 3.58 µs after
Wait:
in a,(MSXAudio_STATUS_PORT)
and 00001000B
jr z,Wait
outi
jr nz,Next
dec e
jr nz,Next
ld d,78H
ld a,MSXAudio_FLAG_CONTROL
call WriteRegister
ei
ret
ENDP
; dehl = size
; iy = reader
ProcessDataBlock:
ld ix,this
jp MSXAudio_ProcessDataBlock
ENDM
; ix = this
; iy = drivers
MSXAudio_Construct:
call Driver_Construct
call MSXAudio_Detect
jp nc,Driver_NotFound
jr MSXAudio_Reset
; ix = this
MSXAudio_Destruct:
call Driver_IsFound
ret nc
jr MSXAudio_Mute
; e = register
; d = value
; ix = this
MSXAudio_WriteRegister:
ld a,e
ld bc,MSXAudio.WriteRegister
jp Utils_JumpIXOffsetBC
; e = register
; d = value
; ix = this
MSXAudio_SafeWriteRegister:
ld bc,MSXAudio.SafeWriteRegister
jp Utils_JumpIXOffsetBC
; b = count
; e = register base
; d = value
; ix = this
MSXAudio_FillRegisters:
push bc
push de
call MSXAudio_SafeWriteRegister
in a,(09AH) ; R800: ~62 - 5 (ret) / 7.16 µs
pop de
pop bc
inc e
djnz MSXAudio_FillRegisters
ret
; ix = this
MSXAudio_Mute:
ld de,01H << 8 | MSXAudio_ADPCM_CONTROL
call MSXAudio_WriteRegister ; reset ADPCM
ld de,00BDH
call MSXAudio_WriteRegister ; rhythm off
ld b,16H
ld de,0F80H
call MSXAudio_FillRegisters ; max release rate
ld b,16H
ld de,3F40H
call MSXAudio_FillRegisters ; min total level
ld b,09H
ld de,00A0H
call MSXAudio_FillRegisters ; frequency 0
ld b,09H
ld de,00A0H
jr MSXAudio_FillRegisters ; key off
; ix = this
MSXAudio_Reset:
ld b,0C9H
ld de,0000H
jr MSXAudio_FillRegisters
; dehl = size
; ix = this
; iy = reader
MSXAudio_ProcessDataBlock: PROC
push de
push hl
call Reader_ReadDoubleWord_IY ; total rom size
call Reader_ReadDoubleWord_IY ; start address
call MSXAudio_SetADPCMWriteAddress
pop hl
pop de
ld bc,8 ; subtract header from block size
Loop:
and a
sbc hl,bc
ld bc,0
ex de,hl
sbc hl,bc
ex de,hl
call c,System_ThrowException
ld a,h
or l
or e
or d
jr z,Finish
push de
push hl
ld a,d
or e
jr z,LessThan64K
ld hl,0FFFFH
LessThan64K:
ld c,l
ld b,h
call Reader_ReadBlockDirect_IY
push bc
call MSXAudio_WriteADPCMData
pop bc
pop hl
pop de
jr Loop
Finish:
ld d,01H
ld e,MSXAudio_ADPCM_CONTROL
jp MSXAudio_WriteRegister
ENDP
; ehl = write address
; ix = this
MSXAudio_SetADPCMWriteAddress:
srl e
rr h
rr l
call c,System_ThrowException
srl e
rr h
rr l
call c,System_ThrowException
ld a,e
or d
call nz,System_ThrowException
push hl
ld d,l
ld e,MSXAudio_START_ADDRESS_L
call MSXAudio_WriteRegister
pop hl
ld d,h
ld e,MSXAudio_START_ADDRESS_H
call MSXAudio_WriteRegister
ld d,0FFH
ld e,MSXAudio_STOP_ADDRESS_L
call MSXAudio_WriteRegister
ld d,0FFH
ld e,MSXAudio_STOP_ADDRESS_H
call MSXAudio_WriteRegister
ld d,01H
ld e,MSXAudio_ADPCM_CONTROL
call MSXAudio_WriteRegister
ld d,60H
ld e,MSXAudio_ADPCM_CONTROL
jp MSXAudio_WriteRegister
; bc = count
; hl = source
; ix = this
MSXAudio_WriteADPCMData:
ld de,MSXAudio.WriteADPCMData
jp Utils_JumpIXOffsetDE
; ix = this
; f <- c: found
MSXAudio_Detect:
ld c,(ix + MSXAudio.basePort)
; c = base I/O port
; f <- c: Found
; c <- base I/O port
MSXAudio_DetectPort: PROC
in a,(c)
and 11111001B
ret nz
ld de,10000000B << 8 | MSXAudio_ADPCM_CONTROL
call WriteRegister
in a,(c)
and 11111001B
push af
ld de,00000000B << 8 | MSXAudio_ADPCM_CONTROL
call WriteRegister
pop af
xor 00000001B
ret nz
scf
ret
WriteRegister:
out (c),e
in a,(c) ; wait 12 / 3.58 µs
cp (hl) ; "
inc c
out (c),d
dec c
ret
ENDP
;
SECTION RAM
MSXAudio_instance: MSXAudio
ENDS
MSXAudio_interface:
InterfaceOffset MSXAudio.SafeWriteRegister
InterfaceOffset MSXAudio.ProcessDataBlock
MSXAudio_name:
db "MSX-AUDIO",0
|
; ----------------------------------------
; Command line interface program
; to test escape codes.
;
; --------------------------------------------------------------------------------
lxi sp,STACK ; Set stack pointer
lxi h,lb ; Set the H:L register pair to the line buffer.
shld lbc ; Store H and L registers into memory, the line buffer counter.
Start:
lxi h,StartMsg
call printStr
call HelpMenu
; --------------------------------------------------------------------------------
startNewline:
mvi a,'\r'
out PRINT_PORT
mvi a,'\n'
out PRINT_PORT
startPrompt:
lxi h,thePrompt ; Print the prompt.
call printStr
mtLine:
mvi a,0 ; Initialize cursor line position counter.
sta cpc
lxi h,0 ; Set line buffer address counter to zero.
shld lbc
; --------------------------------------------------------------------------------
; Get an input byte
; + Ctrl+c to exit.
; + Process other control keys
; + Output printable key characters to screen.
GetByte:
in INPUT_PORT ; Get input byte value into register A.
cpi 0 ; No character input, nothing to print out.
jz GetByte
; ---------------
; Program options
cpi 'h'
jz HelpMenu
cpi '1'
jz Menu1
cpi '2'
jz Menu2
cpi '3'
jz Menu3
cpi '4'
jz Menu4
cpi '5'
jz Menu5
cpi '6'
jz Menu6
cpi '7'
jz Menu7
; ----------------------------------------
; Handle special keys.
cpi 3 ; Ctrl+c will exit this loop.
jz ExitGetByte
cpi 13 ; If carriage return, send line feed and print the prompt.
jz processLine
cpi 127 ; Handle Backspace.
jz backSpace
cpi 12 ; Ctrl+l, Clear screen.
jz clear
cpi 7 ; Ctrl+g, bell.
jz bell
; ---------------
; Only printable characters
cpi 32
jc GetByte ; Ignore less than 32.
cpi 126
jnc GetByte ; Ignore greater than 126.
; ---------------
; Else,
out PRINT_PORT ; output the character and get a new one.
call inrCpc ; Increment the cursor position.
jmp GetByte
; ----------------------------------------
bell:
out PRINT_PORT ; Bell tone.
jmp GetByte
; ---------------
backSpace:
lda cpc
cpi 0 ; Don't backspace over the prompt.
jz GetByte
;
mvi a,esc ; Esc[ValueD : Move the cursor left n lines (left one space).
out PRINT_PORT
mvi a,'['
out PRINT_PORT
mvi a,'1'
out PRINT_PORT
mvi a,'D'
out PRINT_PORT
;
mvi a,' ' ; Overwrite the character with a blank.
out PRINT_PORT
;
mvi a,esc ; Move back to the blank space.
out PRINT_PORT
mvi a,'['
out PRINT_PORT
mvi a,'1'
out PRINT_PORT
mvi a,'D'
out PRINT_PORT
;
call dcrCpc
jmp GetByte
; ----------------------------------------
; Move the cursor home "Esc[H" and clear the screen "Esc[2J".
clear:
mvi a,esc
out PRINT_PORT
mvi a,'['
out PRINT_PORT
mvi a,'H'
out PRINT_PORT
mvi a,esc
out PRINT_PORT
mvi a,'['
out PRINT_PORT
mvi a,'2'
out PRINT_PORT
mvi a,'J'
out PRINT_PORT
jmp startNewline
;
; --------------------------------------------------------------------------------
; Process a command line entry.
processLine:
lda cpc
cpi 0
jz startNewline ; If nothing entered in the line (MT line), nothing to process.
;
call printNewline
lxi h,processMsg
call printStr
jmp startNewline
;
; --------------------------------------------------------------------------------
Menu1:
;lxi h,Menu1str
;call printStr
call SCRCLR
jmp startPrompt
Menu2:
call CRSUP6
jmp startPrompt
Menu3:
call SCRD1C
jmp startPrompt
Menu4:
lxi h,Menu4str
call printStr
jmp startPrompt
Menu5:
lxi h,Menu5str
call printStr
jmp startPrompt
Menu6:
lxi h,Menu6str
call printStr
jmp startPrompt
Menu7:
lxi h,Menu7str
call printStr
jmp startPrompt
; ----------------------------------------
; Menu
HelpMenu:
lxi h,MenuStart
call printStr
lxi h,Menu1str
call printStr
lxi h,Menu2str
call printStr
lxi h,Menu3str
call printStr
lxi h,MenuBar ; ------
call printStr
lxi h,Menu4str
call printStr
lxi h,Menu5str
call printStr
lxi h,Menu6str
call printStr
lxi h,MenuBar ; ------
call printStr
lxi h,Menu7str
call printStr
lxi h,MenuEnd
call printStr
jmp startNewline
; ---------------
MenuStart db '\r\n+ Escape Sequence Test Menu'
db '\r\n -------------------------\r\n'
db 000h ; Indicator of the end of a text block.
Menu1str db ' 1. Clear screen: Esc[H Esc[2J \r\n'
db 0
Menu2str db ' 2. Move cursor up 6 lines: Esc[6A \r\n'
db 0
Menu3str db ' 3. Clear screen from cursor down: Esc[1B Esc[0J \r\n'
db 0
MenuBar db ' ------\r\n'
db 0
Menu4str db ' 4. NA\r\n'
db 0
Menu5str db ' 5. NA\r\n'
db 0
Menu6str db ' 6. NA\r\n'
db 0
Menu7str db ' 7. NA\r\n'
db 0
MenuEnd db '\r\n ------'
db '\r\n Ctrl+l : clear screen.'
db '\r\n Ctrl+c : exit.\r\n'
db 0
;
; --------------------------------------------------------------------------------
; Store the key press values to the line buffer and increment the counter.
inrCpc:
lhld lbc ; Load H and L registers from memory.
mov m,a ; Move register A to the H:L address. A -> (HL).
inx h ; Increment H:L register pair.
shld lbc ; Store H and L registers into memory.
;
lda cpc ; Increment the cursor position counter
inr a
sta cpc
ret
; --------------------------------------
; Decrement the position counter and store the key press values to the line buffer.
dcrCpc:
lda cpc
dcr a
sta cpc
ret
; --------------------------------------
ExitGetByte: ; Exit the input loop.
lxi h,ExitMsg
call printStr
hlt
jmp Start
; ----------------------------------------------
SCRCLR:
mvi a,esc ; Esc[H
call PRINT
mvi a,'['
call PRINT
mvi a,'H'
call PRINT
mvi a,esc ; Esc[2J
call PRINT
mvi a,'['
call PRINT
mvi a,'2'
call PRINT
mvi a,'J'
call PRINT
ret
;
SIODAT EQU 11H ;88-2SIO DATA PORT
SCRD1C:
push a
mvi a,'|'
out SIODAT
hlt
mvi a,esc ; Move down 1 line: Esc[1B
out SIODAT
mvi a,'['
out SIODAT
mvi a,'1'
out SIODAT
mvi a,'B'
out SIODAT
mvi a,' '
out SIODAT
mvi a,esc ; Clear screen from cursor down. Esc[0J
out SIODAT
mvi a,'['
out SIODAT
mvi a,'0'
out SIODAT
mvi a,'J'
out SIODAT
pop a
hlt
ret
;
CRSUP6:
push a
mvi a,esc ; Esc[6A
call PRINT
mvi a,'['
call PRINT
mvi a,'6'
call PRINT
mvi a,'A'
call PRINT
pop a
ret
PRINT:
out PRINT_PORT ; Out register A to the serial port.
ret
; --------------------------------------------------------------------------------
; Subroutines
; --------------------------------------
; Print a string.
printStr:
mov a,m ; Move the data from H:L address to register A. (HL) -> A.
cpi TERMB ; Compare to see if it's the string terminate byte.
jz sPrintDone
out PRINT_PORT ; Out register A to the serial port.
inx h ; Increment H:L register pair.
jmp printStr
sPrintDone:
ret
; --------------------------------------
printNewline:
mvi a,'\r'
out PRINT_PORT
mvi a,'\n'
out PRINT_PORT
ret
; --------------------------------------
; --------------------------------------
;
StartMsg db '\r\n+++ Program to test VT100 escape code sequences.\r\n\r\n'
db 0
thePrompt db 'Esc ?- '
db 0
processMsg db '++ processLine, Not implemented, yet.'
db 0
ExitMsg db '\r\n+ Later.\r\n'
db 0
;
TERMB equ 0 ; String terminator.
esc equ 27 ; Escape character, which is 0x1B (hex).
;
cpc ds 1 ; Cursor position counter variable.
lbc ds 2 ; Address of last added key value = lb address + cpc-1.
;
lineLength equ 80
lb ds 80 ; Place to store what is typed in, for the current line.
; Cursor position is also the length of the entered text.
;
; ----------------------------------------
; ----------------------------------------
; When using port 2,
; if port 3 is disable, then it defaults to 3, the default serial port.
PRINT_PORT equ 3 ; Output port#.
INPUT_PORT equ 3 ; Input port#.
;
DS 32 ; Stack space
STACK: EQU $
; ----------------------------------------
end
; --------------------------------------------------------------------------------
VT100 reference:
http://ascii-table.com/ansi-escape-sequences-vt-100.php
Esc[H Move cursor to upper left corner, example: Serial.print(F("\033[H"));
Esc[J Clear screen from cursor down, example: Serial.print(F("\033[J"));
Esc[2J Clear entire screen, example: Serial.print(F("\033[H"));
Example: Serial.print(F("\033[H\033[2J")); // Move home and clear entire screen.
Esc[K Clear line from cursor right
Esc[nA Move cursor up n lines.
Example: Serial.print(F("\033[3A")); Cursor Up 3 lines.
Esc[nB Move cursor down n lines.
Example: Serial.print(F("\033[6B")); Cursor down 6 lines.
Esc[nC Move cursor right n positions.
Example: Serial.print(F("\033[H\033[4B\033[2C")); // Print on: row 4, column 2.
Esc[r;cH Move cursor to a specific row(r) and column(c).
Example: Serial.print(F("\033[4;2H*")); // Print on: row 4, column 2 and print "*".
Reference: printf/sprintf formats:
http://www.cplusplus.com/reference/cstdio/printf/
; --------------------------------------------------------------------------------
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; a minimal Commander X16 math library
;; Time-stamp: <2019-10-17 10:15:14 schol-r-lea>
.include "math.inc"
.export parsehex
.proc parsehex
tay
lsr a
lsr a
lsr a
lsr a
cmp #$0A
bcs letterhi
adc #$30
jmp outhi
letterhi:
adc #$36
outhi:
tax
findlo:
tya
and #$0F
cmp #$0A
bcs letterlo
adc #$30
jmp outlo
letterlo:
adc #$36
outlo:
tay
exit:
rts
.endproc
.proc add16
fp = Math::ZP_Scratch
tsx
stx fp
.endproc
|
; A047240: Numbers that are congruent to {0, 1, 2} mod 6.
; 0,1,2,6,7,8,12,13,14,18,19,20,24,25,26,30,31,32,36,37,38,42,43,44,48,49,50,54,55,56,60,61,62,66,67,68,72,73,74,78,79,80,84,85,86,90,91,92,96,97,98,102,103,104,108,109,110,114,115,116,120,121,122,126,127,128,132,133,134,138,139,140,144,145,146,150,151,152,156,157,158,162,163,164,168,169,170,174,175,176,180,181,182,186,187,188,192,193,194,198
mov $1,$0
mul $0,2
mod $1,3
sub $0,$1
|
global _start
section .bss
res resb 1
section .text
_start:
sub ah, ah ; Set ah to 00H
mov al, '9' ; Getting '9' to al
sub al, '3' ; SUB al with '3', the value in al is 06H
aas ; ASCII Adjust After Subtract, the value in al is 06H
mov [res], ax ; Move 06H to [res]
; Print res
mov eax, 4
mov ebx, 1
mov ecx, res
mov edx, 1
int 0x80
; Exit
mov eax, 1
mov ebx, 0
int 0x80
|
; A022964: a(n) = 8-n.
; Submitted by Christian Krause
; 8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,-17,-18,-19,-20,-21,-22,-23,-24,-25,-26,-27,-28,-29,-30,-31,-32,-33,-34,-35,-36,-37,-38,-39,-40,-41,-42,-43,-44,-45,-46,-47,-48,-49,-50,-51
sub $0,8
mul $0,-1
|
; A028841: Iterated sum of digits of n is a Fibonacci number.
; 1,2,3,5,8,10,11,12,14,17,19,20,21,23,26,28,29,30,32,35,37,38,39,41,44,46,47,48,50,53,55,56,57,59,62,64,65,66,68,71,73,74,75,77,80,82,83,84,86,89,91,92,93,95,98,100,101,102,104,107,109,110,111,113,116,118,119,120,122,125,127,128,129,131,134,136,137,138,140,143,145,146,147,149,152,154,155,156,158,161,163,164,165,167,170,172,173,174,176,179,181,182,183,185,188,190,191,192,194,197,199,200,201,203,206,208,209,210,212,215,217,218,219,221,224,226,227,228,230,233,235,236,237,239,242,244,245,246,248,251,253,254,255,257,260,262,263,264,266,269,271,272,273,275,278,280,281,282,284,287,289,290,291,293,296,298,299,300,302,305,307,308,309,311,314,316,317,318,320,323,325,326,327,329,332,334,335,336,338,341,343,344,345,347,350,352,353,354,356,359,361,362,363,365,368,370,371,372,374,377,379,380,381,383,386,388,389,390,392,395,397,398,399,401,404,406,407,408,410,413,415,416,417,419,422,424,425,426,428,431,433,434,435,437,440,442,443,444,446,449
mov $2,$0
mul $0,2
add $0,1
lpb $0,1
trn $1,$0
trn $0,6
add $1,$0
trn $0,4
lpe
add $1,4
lpb $2,1
add $1,1
sub $2,1
lpe
sub $1,3
|
// Tests calling into a function pointer with local variables
// Commodore 64 PRG executable file
.file [name="function-pointer-noarg-call-7.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(__start)
.label SCREEN = $400
.label idx = 2
.segment Code
__start: {
// volatile byte idx = 0
lda #0
sta.z idx
jsr main
rts
}
hello: {
ldx #0
__b1:
// SCREEN[idx++] = msg[i++]
lda msg,x
ldy.z idx
sta SCREEN,y
// SCREEN[idx++] = msg[i++];
inc.z idx
inx
// while(msg[i])
lda msg,x
cmp #0
bne __b1
// }
rts
}
main: {
// do10(f)
jsr do10
// }
rts
}
// void do10(void (*fn)())
do10: {
.label i = 3
lda #0
sta.z i
__b1:
// (*fn)()
jsr hello
// for( byte i: 0..9)
inc.z i
lda #$a
cmp.z i
bne __b1
// }
rts
}
.segment Data
msg: .text "hello "
.byte 0
|
MOV Ix, 7
MOV Ac, 0
MOV Br, 10
Loop:
ADD Br
DEC Ix
JMP Loop -nz
HLT
|
; A217831: Triangle read by rows: label the entries T(0,0), T(1,0), T(0,1), T(2,0), T(1,1), T(0,2), T(3,0), ... Then T(n,k)=T(k,n), T(0,0)=0, T(1,0)=1, and for n>1, T(n,0)=0 and T(n,in+j)=T(n-j,j) (i,j >= 0, not both 0).
; 0,1,1,0,1,0,0,1,1,0,0,1,0,1,0,0,1,1,1,1,0,0,1,0,0,0,1,0,0,1,1,1,1,1,1,0,0,1,0,1,0,1,0,1,0,0,1,1,0,1,1,0,1,1,0,0,1,0,1,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,0,1,0,1,0,0,0,1,0,0,1,1,1,1
lpb $0
mov $1,$0
add $2,1
sub $0,$2
gcd $1,$2
cmp $1,1
lpe
mov $0,$1
|
; uint16_t esx_f_read(unsigned char handle, void *dst, size_t nbytes)
SECTION code_esxdos
PUBLIC esx_f_read_callee
EXTERN asm_esx_f_read
esx_f_read_callee:
pop af
pop bc
pop hl
pop de
push af
ld a,e
jp asm_esx_f_read
|
; $Id: kLdrExeStub-os2.asm 29 2009-07-01 20:30:29Z bird $
;; @file
; kLdr - OS/2 Loader Stub.
;
; This file contains a 64kb code/data/stack segment which is used to kick off
; the loader dll that loads the process.
;
;
; Copyright (c) 2006-2007 Knut St. Osmundsen <bird-kStuff-spamix@anduin.net>
;
; 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.
;
struc KLDRARGS
.fFlags resd 1
.enmSearch resd 1
.szExecutable resb 260
.szDefPrefix resb 16
.szDefSuffix resb 16
.szLibPath resb (4096 - (4 + 4 + 16 + 16 + 260))
endstruc
extern _kLdrDyldLoadExe
segment DATA32 stack CLASS=DATA align=16 use32
..start:
push args
jmp _kLdrDyldLoadExe
;
; Argument structure.
;
align 4
args:
istruc KLDRARGS
at KLDRARGS.fFlags, dd 0
at KLDRARGS.enmSearch, dd 2 ;KLDRDYLD_SEARCH_HOST
at KLDRARGS.szDefPrefix, db ''
at KLDRARGS.szDefSuffix, db '.dll'
; at KLDRARGS.szExecutable, db 'tst-0.exe'
at KLDRARGS.szLibPath, db ''
iend
segment STACK32 stack CLASS=STACK align=16 use32
; pad up to 64KB.
resb 60*1024
global WEAK$ZERO
WEAK$ZERO EQU 0
group DGROUP, DATA32 STACK32
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "netbase.h"
#include "rpcserver.h"
#include "util.h"
#include "stealth.h"
#include "spork.h"
#ifdef ENABLE_WALLET
#include "wallet.h"
#include "walletdb.h"
#endif
#include <stdint.h>
#include <boost/assign/list_of.hpp>
#include "json/json_spirit_utils.h"
#include "json/json_spirit_value.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj, diff;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
if(!fLiteMode)
obj.push_back(Pair("darksend_balance", ValueFromAmount(pwalletMain->GetAnonymizedBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
}
#endif
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("timeoffset", (int64_t)GetTimeOffset()));
#ifndef LOWMEM
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
#endif
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("ip", GetLocalAddress(NULL).ToStringIP()));
//diff.push_back(Pair("proof-of-work", GetDifficulty()));
//diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("testnet", TestNet()));
#ifdef ENABLE_WALLET
if (pwalletMain) {
obj.push_back(Pair("keypoololdest", (int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
}
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue)));
if (pwalletMain && pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (int64_t)nWalletUnlockTime));
#endif
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
#ifdef ENABLE_WALLET
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
private:
isminetype mine;
public:
DescribeAddressVisitor(isminetype mineIn) : mine(mineIn) {}
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
obj.push_back(Pair("isscript", false));
if (mine == ISMINE_SPENDABLE) {
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("pubkey", HexStr(vchPubKey)));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
}
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
if (mine != ISMINE_NO) {
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end())));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CMyceAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
}
return obj;
}
Object operator()(const CStealthAddress &stxAddr) const {
Object obj;
obj.push_back(Pair("todo", true));
return obj;
}
};
#endif
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <Myceaddress>\n"
"Return information about <Myceaddress>.");
CMyceAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
#ifdef ENABLE_WALLET
isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;
ret.push_back(Pair("ismine", (mine & ISMINE_SPENDABLE) ? true : false));
if (mine != ISMINE_NO) {
ret.push_back(Pair("iswatchonly", (mine & ISMINE_WATCH_ONLY) ? true: false));
Object detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
#endif
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw runtime_error(
"validatepubkey <Mycepubkey>\n"
"Return information about <Mycepubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CMyceAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
ret.push_back(Pair("iscompressed", isCompressed));
#ifdef ENABLE_WALLET
isminetype mine = pwalletMain ? IsMine(*pwalletMain, dest) : ISMINE_NO;
ret.push_back(Pair("ismine", (mine & ISMINE_SPENDABLE) ? true : false));
if (mine != ISMINE_NO) {
ret.push_back(Pair("iswatchonly", (mine & ISMINE_WATCH_ONLY) ? true: false));
Object detail = boost::apply_visitor(DescribeAddressVisitor(mine), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain && pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
#endif
}
return ret;
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <Myceaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CMyceAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
return false;
return (pubkey.GetID() == keyID);
}
/*
Used for updating/reading spork settings on the network
*/
Value spork(const Array& params, bool fHelp)
{
if(params.size() == 1 && params[0].get_str() == "show"){
std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin();
Object ret;
while(it != mapSporksActive.end()) {
ret.push_back(Pair(sporkManager.GetSporkNameByID(it->second.nSporkID), it->second.nValue));
it++;
}
return ret;
} else if (params.size() == 2){
int nSporkID = sporkManager.GetSporkIDByName(params[0].get_str());
if(nSporkID == -1){
return "Invalid spork name";
}
// SPORK VALUE
int64_t nValue = params[1].get_int();
//broadcast new spork
if(sporkManager.UpdateSpork(nSporkID, nValue)){
return "success";
} else {
return "failure";
}
}
throw runtime_error(
"spork <name> [<value>]\n"
"<name> is the corresponding spork name, or 'show' to show all current spork settings"
"<value> is a epoch datetime to enable or disable spork"
+ HelpRequiringPassphrase());
}
|
#include "vtkPistonScalarsColors.h"
#include "vtkObjectFactory.h"
#include "vtkScalarsToColors.h"
#include <vector>
vtkStandardNewMacro(vtkPistonScalarsColors);
vtkCxxSetObjectMacro(vtkPistonScalarsColors, LookupTable, vtkScalarsToColors);
//-----------------------------------------------------------------------------
vtkPistonScalarsColors::vtkPistonScalarsColors() : vtkObject(),
NumberOfValues(256),
LookupTable(0)
{
this->TableRange[0] = this->TableRange[1] = 0.0;
this->ComputeColorsTime.Modified();
this->ComputeColorsfTime.Modified();
}
//-----------------------------------------------------------------------------
vtkPistonScalarsColors::~vtkPistonScalarsColors()
{
this->SetLookupTable(0);
}
//-----------------------------------------------------------------------------
void vtkPistonScalarsColors::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "TableRange: " << this->TableRange[0]
<< indent << this->TableRange[1] << endl;
os << indent << "NumberOfValues: " << this->NumberOfValues << endl;
os << indent << "ComputeColorsTime: "
<< this->ComputeColorsTime.GetMTime() << endl;
os << indent << "ScalarsColors: " << &this->ScalarsColors << "\n";
os << indent << "ComputerColorsfTime: "
<< this->ComputeColorsfTime.GetMTime() << endl;
os << indent << "ScalarsColorsf: " << &this->ScalarsColorsf << "\n";
}
//-----------------------------------------------------------------------------
void vtkPistonScalarsColors::SetTableRange(double range[2])
{
this->SetTableRange(range[1], range[2]);
}
//-----------------------------------------------------------------------------
void vtkPistonScalarsColors::SetTableRange(double rmin, double rmax)
{
if (rmax < rmin)
{
vtkErrorMacro("Bad table range: ["<<rmin<<", "<<rmax<<"]");
return;
}
if (this->TableRange[0] == rmin && this->TableRange[1] == rmax)
{
return;
}
this->TableRange[0] = rmin;
this->TableRange[1] = rmax;
this->Modified();
}
//-----------------------------------------------------------------------------
std::vector<unsigned char>* vtkPistonScalarsColors::ComputeScalarsColors(
int numberOfChanels)
{
if(!this->LookupTable)
{
vtkErrorMacro(<< "Invalid look up table");
return NULL;
}
if(numberOfChanels < 1)
{
vtkErrorMacro(<< "Cannot have less than one chanel");
return NULL;
}
if(numberOfChanels > VTK_RGBA)
{
vtkErrorMacro(<< "Cannot have more than four (RGBA) chanels");
return NULL;
}
if(!(this->LookupTable->GetMTime() > this->GetMTime() ||
this->ComputeColorsTime.GetMTime() < this->GetMTime()))
{
return &this->ScalarsColors;
}
std::vector<float> values (this->NumberOfValues);
float *valueptr = &values[0];
this->ComputeValues(valueptr);
// Point to the first element
valueptr = &values[0];
// Colors for those values;
this->ScalarsColors.clear();
this->ScalarsColors.resize(this->NumberOfValues * numberOfChanels);
unsigned char *colorptr = &this->ScalarsColors[0];
this->LookupTable->SetRange(this->TableRange);
this->LookupTable->Build();
this->LookupTable->MapScalarsThroughTable(valueptr, colorptr,
VTK_FLOAT, this->NumberOfValues, 1, numberOfChanels);
this->Modified();
// Now update build time (should be done last)
this->ComputeColorsTime.Modified();
return &this->ScalarsColors;
}
//-----------------------------------------------------------------------------
std::vector<float>* vtkPistonScalarsColors::ComputeScalarsColorsf(
int numberOfChanels)
{
if(!this->LookupTable)
{
vtkErrorMacro(<< "Invalid look up table");
return NULL;
}
if(numberOfChanels < 1)
{
vtkErrorMacro(<< "Cannot have less than one chanel");
return NULL;
}
if(numberOfChanels > VTK_RGBA)
{
vtkErrorMacro(<< "Cannot have more than four (RGBA) chanels");
return NULL;
}
if(!(this->LookupTable->GetMTime() > this->GetMTime() ||
this->ComputeColorsfTime.GetMTime() < this->GetMTime()))
{
return &this->ScalarsColorsf;
}
std::vector<float> values (this->NumberOfValues);
float *valueptr = &values[0];
this->ComputeValues(valueptr);
// Point to the first element
valueptr = &values[0];
// Colors for those values;
this->ScalarsColorsf.clear();
unsigned char *scalarColors =
new unsigned char[this->NumberOfValues * numberOfChanels];
unsigned char *colorptr = scalarColors;
this->LookupTable->SetRange(this->TableRange);
this->LookupTable->Build();
this->LookupTable->MapScalarsThroughTable(valueptr, colorptr,
VTK_FLOAT, this->NumberOfValues, 1, numberOfChanels);
// Convert unsigned char color to float color
this->ScalarsColorsf.resize(this->NumberOfValues * 3);
for (int i = 0, j = 0; i < this->NumberOfValues; ++i, j += 3)
{
float r = (float)colorptr[i*3+0] / 256.0;
float g = (float)colorptr[i*3+1] / 256.0;
float b = (float)colorptr[i*3+2] / 256.0;
this->ScalarsColorsf[j] = r;
this->ScalarsColorsf[j+1] = g;
this->ScalarsColorsf[j+2] = b;
}
delete [] scalarColors;
this->Modified();
// Now update build time (should be done last)
this->ComputeColorsfTime.Modified();
return &this->ScalarsColorsf;
}
//-----------------------------------------------------------------------------
void vtkPistonScalarsColors::ComputeValues(float *values)
{
if(!values)
{
return;
}
for (int i = 0; i < this->NumberOfValues; ++i)
{
*values = this->TableRange[0] +
i * ((this->TableRange[1] - this->TableRange[0]) /
(float) this->NumberOfValues);
values++;
}
}
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2016.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ClassTest.h>
#include <OpenMS/test_config.h>
///////////////////////////
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabetParser.h>
///////////////////////////
using namespace OpenMS;
using namespace ims;
using namespace std;
class IMSAlphabetParserImpl
: public IMSAlphabetParser<>
{
private:
ContainerType elements_;
public:
virtual ContainerType& getElements()
{
return elements_;
}
virtual void parse(std::istream& )
{
// ignore istream, just enter something into the map
elements_.insert(std::make_pair("A", 71.03711));
elements_.insert(std::make_pair("R", 156.10111));
}
};
START_TEST(IMSAlphabetParser, "$Id$")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
// this is an abstract class, that only provides the load method
// it cannot be instanciated so it cannot be tested, therefor we
// test the implementation from above
IMSAlphabetParser<>* ptr = 0;
IMSAlphabetParser<>* null_ptr = 0;
START_SECTION(IMSAlphabetParser())
{
ptr = new IMSAlphabetParserImpl();
TEST_NOT_EQUAL(ptr, null_ptr)
}
END_SECTION
START_SECTION(~IMSAlphabetParser())
{
delete ptr;
}
END_SECTION
IMSAlphabetParser<> * parser = new IMSAlphabetParserImpl();
START_SECTION((void load(const std::string &fname)))
{
TEST_EXCEPTION(Exception::IOException ,parser->load(""))
String filename;
NEW_TMP_FILE(filename)
// just create the file
ofstream of;
of.open(filename.c_str());
of << "just text" << std::endl;
of.close();
parser->load(filename);
TEST_EQUAL(parser->getElements().empty(), false)
}
END_SECTION
START_SECTION((virtual ContainerType& getElements()))
{
TEST_EQUAL(parser->getElements().size(), 2)
TEST_REAL_SIMILAR(parser->getElements()["A"], 71.03711)
TEST_REAL_SIMILAR(parser->getElements()["R"], 156.10111)
}
END_SECTION
START_SECTION((virtual void parse(InputSource &is)))
{
// already tested by load
NOT_TESTABLE
}
END_SECTION
delete parser;
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
|
; CALLER linkage for function pointers
XLIB l_bsearch
LIB l_bsearch_callee
XREF ASMDISP_L_BSEARCH_CALLEE
.l_bsearch
pop af
pop iy
pop hl
pop de
pop bc
push bc
push de
push hl
push hl
push af
jp l_bsearch_callee + ASMDISP_L_BSEARCH_CALLEE
|
INCLUDE "constants.asm"
INCLUDE "macros/wram.asm"
INCLUDE "vram.asm"
SECTION "OAM Buffer", WRAM0
; buffer for OAM data copied by DMA
wOAMBuffer::
; wOAMBufferSprite00 - wOAMBufferSprite39
; example for first sprite
; wOAMBufferSprite00::
; wOAMBufferSprite00YCoord:: db
; wOAMBufferSprite00XCoord:: db
; wOAMBufferSprite00TileID:: db
; wOAMBufferSprite00Attributes:: db
FOR n, NUM_SPRITE_OAM_STRUCTS
wOAMBufferSprite{02d:n}:: sprite_oam_struct wOAMBufferSprite{02d:n}
ENDR
wOAMBufferEnd::
SECTION "WRAM", WRAM0
wGBC:: db
SECTION "Stack", WRAM0
ds $100 - 1
wStack:: db
INCLUDE "hram.asm"
|
lui $1,40715
ori $1,$1,41822
lui $2,56157
ori $2,$2,44874
lui $3,63629
ori $3,$3,37838
lui $4,42879
ori $4,$4,25490
lui $5,48830
ori $5,$5,2525
lui $6,12447
ori $6,$6,44199
mthi $1
mtlo $2
sec0:
nop
nop
nop
beq $3,$2,yes0
nop
no0:addiu $k1,$k1,1
yes0:addiu $k0,$k0,1
sec1:
nop
nop
or $3,$4,$3
beq $3,$2,yes1
nop
no1:addiu $k1,$k1,1
yes1:addiu $k0,$k0,1
sec2:
nop
nop
slti $3,$2,-16280
beq $3,$2,yes2
nop
no2:addiu $k1,$k1,1
yes2:addiu $k0,$k0,1
sec3:
nop
nop
mfhi $3
beq $3,$2,yes3
nop
no3:addiu $k1,$k1,1
yes3:addiu $k0,$k0,1
sec4:
nop
nop
lhu $3,14($0)
beq $3,$2,yes4
nop
no4:addiu $k1,$k1,1
yes4:addiu $k0,$k0,1
sec5:
nop
and $3,$2,$3
nop
beq $3,$2,yes5
nop
no5:addiu $k1,$k1,1
yes5:addiu $k0,$k0,1
sec6:
nop
addu $3,$5,$6
addu $3,$5,$6
beq $3,$2,yes6
nop
no6:addiu $k1,$k1,1
yes6:addiu $k0,$k0,1
sec7:
nop
or $3,$4,$2
addiu $3,$3,-10896
beq $3,$2,yes7
nop
no7:addiu $k1,$k1,1
yes7:addiu $k0,$k0,1
sec8:
nop
sltu $3,$3,$3
mfhi $3
beq $3,$2,yes8
nop
no8:addiu $k1,$k1,1
yes8:addiu $k0,$k0,1
sec9:
nop
slt $3,$2,$2
lhu $3,2($0)
beq $3,$2,yes9
nop
no9:addiu $k1,$k1,1
yes9:addiu $k0,$k0,1
sec10:
nop
andi $3,$4,61836
nop
beq $3,$2,yes10
nop
no10:addiu $k1,$k1,1
yes10:addiu $k0,$k0,1
sec11:
nop
ori $3,$2,38201
subu $3,$3,$5
beq $3,$2,yes11
nop
no11:addiu $k1,$k1,1
yes11:addiu $k0,$k0,1
sec12:
nop
slti $3,$2,-14141
slti $3,$5,-2227
beq $3,$2,yes12
nop
no12:addiu $k1,$k1,1
yes12:addiu $k0,$k0,1
sec13:
nop
lui $3,14846
mfhi $3
beq $3,$2,yes13
nop
no13:addiu $k1,$k1,1
yes13:addiu $k0,$k0,1
sec14:
nop
sltiu $3,$4,-9752
lb $3,1($0)
beq $3,$2,yes14
nop
no14:addiu $k1,$k1,1
yes14:addiu $k0,$k0,1
sec15:
nop
mfhi $3
nop
beq $3,$2,yes15
nop
no15:addiu $k1,$k1,1
yes15:addiu $k0,$k0,1
sec16:
nop
mflo $3
sltu $3,$1,$3
beq $3,$2,yes16
nop
no16:addiu $k1,$k1,1
yes16:addiu $k0,$k0,1
sec17:
nop
mfhi $3
lui $3,21995
beq $3,$2,yes17
nop
no17:addiu $k1,$k1,1
yes17:addiu $k0,$k0,1
sec18:
nop
mflo $3
mflo $3
beq $3,$2,yes18
nop
no18:addiu $k1,$k1,1
yes18:addiu $k0,$k0,1
sec19:
nop
mfhi $3
lb $3,7($0)
beq $3,$2,yes19
nop
no19:addiu $k1,$k1,1
yes19:addiu $k0,$k0,1
sec20:
nop
lhu $3,8($0)
nop
beq $3,$2,yes20
nop
no20:addiu $k1,$k1,1
yes20:addiu $k0,$k0,1
sec21:
nop
lbu $3,11($0)
nor $3,$6,$0
beq $3,$2,yes21
nop
no21:addiu $k1,$k1,1
yes21:addiu $k0,$k0,1
sec22:
nop
lw $3,16($0)
lui $3,16453
beq $3,$2,yes22
nop
no22:addiu $k1,$k1,1
yes22:addiu $k0,$k0,1
sec23:
nop
lh $3,16($0)
mfhi $3
beq $3,$2,yes23
nop
no23:addiu $k1,$k1,1
yes23:addiu $k0,$k0,1
sec24:
nop
lb $3,8($0)
lhu $3,12($0)
beq $3,$2,yes24
nop
no24:addiu $k1,$k1,1
yes24:addiu $k0,$k0,1
sec25:
nor $3,$2,$3
nop
nop
beq $3,$2,yes25
nop
no25:addiu $k1,$k1,1
yes25:addiu $k0,$k0,1
sec26:
sltu $3,$4,$1
nop
and $3,$0,$5
beq $3,$2,yes26
nop
no26:addiu $k1,$k1,1
yes26:addiu $k0,$k0,1
sec27:
xor $3,$3,$6
nop
addiu $3,$6,23287
beq $3,$2,yes27
nop
no27:addiu $k1,$k1,1
yes27:addiu $k0,$k0,1
sec28:
nor $3,$4,$3
nop
mflo $3
beq $3,$2,yes28
nop
no28:addiu $k1,$k1,1
yes28:addiu $k0,$k0,1
sec29:
xor $3,$6,$1
nop
lw $3,8($0)
beq $3,$2,yes29
nop
no29:addiu $k1,$k1,1
yes29:addiu $k0,$k0,1
sec30:
and $3,$6,$6
nor $3,$1,$3
nop
beq $3,$2,yes30
nop
no30:addiu $k1,$k1,1
yes30:addiu $k0,$k0,1
sec31:
nor $3,$2,$4
subu $3,$5,$4
xor $3,$4,$6
beq $3,$2,yes31
nop
no31:addiu $k1,$k1,1
yes31:addiu $k0,$k0,1
sec32:
xor $3,$2,$4
xor $3,$2,$2
slti $3,$3,9177
beq $3,$2,yes32
nop
no32:addiu $k1,$k1,1
yes32:addiu $k0,$k0,1
sec33:
sltu $3,$1,$3
slt $3,$3,$2
mflo $3
beq $3,$2,yes33
nop
no33:addiu $k1,$k1,1
yes33:addiu $k0,$k0,1
sec34:
and $3,$3,$1
nor $3,$6,$4
lw $3,12($0)
beq $3,$2,yes34
nop
no34:addiu $k1,$k1,1
yes34:addiu $k0,$k0,1
sec35:
xor $3,$0,$2
andi $3,$1,62073
nop
beq $3,$2,yes35
nop
no35:addiu $k1,$k1,1
yes35:addiu $k0,$k0,1
sec36:
xor $3,$4,$4
lui $3,8103
addu $3,$2,$4
beq $3,$2,yes36
nop
no36:addiu $k1,$k1,1
yes36:addiu $k0,$k0,1
sec37:
nor $3,$4,$6
lui $3,47102
andi $3,$6,17491
beq $3,$2,yes37
nop
no37:addiu $k1,$k1,1
yes37:addiu $k0,$k0,1
sec38:
and $3,$4,$0
lui $3,240
mfhi $3
beq $3,$2,yes38
nop
no38:addiu $k1,$k1,1
yes38:addiu $k0,$k0,1
sec39:
slt $3,$3,$6
lui $3,58381
lw $3,0($0)
beq $3,$2,yes39
nop
no39:addiu $k1,$k1,1
yes39:addiu $k0,$k0,1
sec40:
subu $3,$1,$5
mfhi $3
nop
beq $3,$2,yes40
nop
no40:addiu $k1,$k1,1
yes40:addiu $k0,$k0,1
sec41:
sltu $3,$3,$2
mfhi $3
nor $3,$3,$4
beq $3,$2,yes41
nop
no41:addiu $k1,$k1,1
yes41:addiu $k0,$k0,1
sec42:
xor $3,$0,$5
mfhi $3
sltiu $3,$3,22843
beq $3,$2,yes42
nop
no42:addiu $k1,$k1,1
yes42:addiu $k0,$k0,1
sec43:
subu $3,$0,$5
mflo $3
mfhi $3
beq $3,$2,yes43
nop
no43:addiu $k1,$k1,1
yes43:addiu $k0,$k0,1
sec44:
subu $3,$4,$1
mfhi $3
lw $3,16($0)
beq $3,$2,yes44
nop
no44:addiu $k1,$k1,1
yes44:addiu $k0,$k0,1
sec45:
or $3,$6,$1
lw $3,0($0)
nop
beq $3,$2,yes45
nop
no45:addiu $k1,$k1,1
yes45:addiu $k0,$k0,1
sec46:
and $3,$2,$5
lw $3,12($0)
subu $3,$6,$1
beq $3,$2,yes46
nop
no46:addiu $k1,$k1,1
yes46:addiu $k0,$k0,1
sec47:
slt $3,$6,$6
lhu $3,12($0)
xori $3,$3,11425
beq $3,$2,yes47
nop
no47:addiu $k1,$k1,1
yes47:addiu $k0,$k0,1
sec48:
and $3,$2,$0
lw $3,16($0)
mflo $3
beq $3,$2,yes48
nop
no48:addiu $k1,$k1,1
yes48:addiu $k0,$k0,1
sec49:
nor $3,$5,$5
lbu $3,2($0)
lw $3,12($0)
beq $3,$2,yes49
nop
no49:addiu $k1,$k1,1
yes49:addiu $k0,$k0,1
sec50:
andi $3,$2,44979
nop
nop
beq $3,$2,yes50
nop
no50:addiu $k1,$k1,1
yes50:addiu $k0,$k0,1
sec51:
ori $3,$2,4047
nop
or $3,$3,$3
beq $3,$2,yes51
nop
no51:addiu $k1,$k1,1
yes51:addiu $k0,$k0,1
sec52:
ori $3,$3,24995
nop
ori $3,$2,51882
beq $3,$2,yes52
nop
no52:addiu $k1,$k1,1
yes52:addiu $k0,$k0,1
sec53:
ori $3,$5,13584
nop
mfhi $3
beq $3,$2,yes53
nop
no53:addiu $k1,$k1,1
yes53:addiu $k0,$k0,1
sec54:
slti $3,$4,-8463
nop
lb $3,0($0)
beq $3,$2,yes54
nop
no54:addiu $k1,$k1,1
yes54:addiu $k0,$k0,1
sec55:
xori $3,$3,17781
addu $3,$1,$3
nop
beq $3,$2,yes55
nop
no55:addiu $k1,$k1,1
yes55:addiu $k0,$k0,1
sec56:
andi $3,$2,57766
sltu $3,$3,$1
and $3,$6,$1
beq $3,$2,yes56
nop
no56:addiu $k1,$k1,1
yes56:addiu $k0,$k0,1
sec57:
addiu $3,$3,-2788
addu $3,$2,$3
sltiu $3,$4,32605
beq $3,$2,yes57
nop
no57:addiu $k1,$k1,1
yes57:addiu $k0,$k0,1
sec58:
xori $3,$5,14163
or $3,$1,$5
mflo $3
beq $3,$2,yes58
nop
no58:addiu $k1,$k1,1
yes58:addiu $k0,$k0,1
sec59:
lui $3,56196
nor $3,$4,$0
lbu $3,16($0)
beq $3,$2,yes59
nop
no59:addiu $k1,$k1,1
yes59:addiu $k0,$k0,1
sec60:
xori $3,$6,40883
lui $3,44548
nop
beq $3,$2,yes60
nop
no60:addiu $k1,$k1,1
yes60:addiu $k0,$k0,1
sec61:
andi $3,$2,9959
ori $3,$4,46404
nor $3,$2,$3
beq $3,$2,yes61
nop
no61:addiu $k1,$k1,1
yes61:addiu $k0,$k0,1
sec62:
sltiu $3,$2,23739
slti $3,$6,5397
ori $3,$2,64812
beq $3,$2,yes62
nop
no62:addiu $k1,$k1,1
yes62:addiu $k0,$k0,1
sec63:
xori $3,$3,57944
slti $3,$4,32674
mfhi $3
beq $3,$2,yes63
nop
no63:addiu $k1,$k1,1
yes63:addiu $k0,$k0,1
sec64:
xori $3,$0,23198
sltiu $3,$2,-31047
lb $3,14($0)
beq $3,$2,yes64
nop
no64:addiu $k1,$k1,1
yes64:addiu $k0,$k0,1
sec65:
slti $3,$0,15993
mflo $3
nop
beq $3,$2,yes65
nop
no65:addiu $k1,$k1,1
yes65:addiu $k0,$k0,1
sec66:
addiu $3,$3,-6139
mfhi $3
addu $3,$3,$2
beq $3,$2,yes66
nop
no66:addiu $k1,$k1,1
yes66:addiu $k0,$k0,1
sec67:
slti $3,$1,-9242
mfhi $3
ori $3,$3,2439
beq $3,$2,yes67
nop
no67:addiu $k1,$k1,1
yes67:addiu $k0,$k0,1
sec68:
sltiu $3,$3,18821
mfhi $3
mflo $3
beq $3,$2,yes68
nop
no68:addiu $k1,$k1,1
yes68:addiu $k0,$k0,1
sec69:
andi $3,$4,54641
mflo $3
lw $3,12($0)
beq $3,$2,yes69
nop
no69:addiu $k1,$k1,1
yes69:addiu $k0,$k0,1
sec70:
lui $3,65021
lhu $3,0($0)
nop
beq $3,$2,yes70
nop
no70:addiu $k1,$k1,1
yes70:addiu $k0,$k0,1
sec71:
andi $3,$5,51326
lhu $3,0($0)
nor $3,$1,$3
beq $3,$2,yes71
nop
no71:addiu $k1,$k1,1
yes71:addiu $k0,$k0,1
sec72:
addiu $3,$3,-7776
lb $3,14($0)
addiu $3,$3,16080
beq $3,$2,yes72
nop
no72:addiu $k1,$k1,1
yes72:addiu $k0,$k0,1
sec73:
lui $3,58745
lhu $3,12($0)
mfhi $3
beq $3,$2,yes73
nop
no73:addiu $k1,$k1,1
yes73:addiu $k0,$k0,1
sec74:
slti $3,$3,-25653
lhu $3,12($0)
lhu $3,16($0)
beq $3,$2,yes74
nop
no74:addiu $k1,$k1,1
yes74:addiu $k0,$k0,1
sec75:
mflo $3
nop
nop
beq $3,$2,yes75
nop
no75:addiu $k1,$k1,1
yes75:addiu $k0,$k0,1
sec76:
mfhi $3
nop
addu $3,$1,$1
beq $3,$2,yes76
nop
no76:addiu $k1,$k1,1
yes76:addiu $k0,$k0,1
sec77:
mfhi $3
nop
sltiu $3,$6,7161
beq $3,$2,yes77
nop
no77:addiu $k1,$k1,1
yes77:addiu $k0,$k0,1
sec78:
mfhi $3
nop
mfhi $3
beq $3,$2,yes78
nop
no78:addiu $k1,$k1,1
yes78:addiu $k0,$k0,1
sec79:
mflo $3
nop
lw $3,0($0)
beq $3,$2,yes79
nop
no79:addiu $k1,$k1,1
yes79:addiu $k0,$k0,1
sec80:
mfhi $3
xor $3,$4,$5
nop
beq $3,$2,yes80
nop
no80:addiu $k1,$k1,1
yes80:addiu $k0,$k0,1
sec81:
mfhi $3
nor $3,$3,$3
sltu $3,$3,$5
beq $3,$2,yes81
nop
no81:addiu $k1,$k1,1
yes81:addiu $k0,$k0,1
sec82:
mfhi $3
and $3,$6,$3
sltiu $3,$3,-16890
beq $3,$2,yes82
nop
no82:addiu $k1,$k1,1
yes82:addiu $k0,$k0,1
sec83:
mflo $3
xor $3,$4,$5
mflo $3
beq $3,$2,yes83
nop
no83:addiu $k1,$k1,1
yes83:addiu $k0,$k0,1
sec84:
mfhi $3
sltu $3,$3,$2
lh $3,6($0)
beq $3,$2,yes84
nop
no84:addiu $k1,$k1,1
yes84:addiu $k0,$k0,1
sec85:
mfhi $3
ori $3,$3,64800
nop
beq $3,$2,yes85
nop
no85:addiu $k1,$k1,1
yes85:addiu $k0,$k0,1
sec86:
mflo $3
lui $3,50396
xor $3,$6,$5
beq $3,$2,yes86
nop
no86:addiu $k1,$k1,1
yes86:addiu $k0,$k0,1
sec87:
mflo $3
sltiu $3,$2,-3022
ori $3,$5,52560
beq $3,$2,yes87
nop
no87:addiu $k1,$k1,1
yes87:addiu $k0,$k0,1
sec88:
mflo $3
slti $3,$4,13443
mflo $3
beq $3,$2,yes88
nop
no88:addiu $k1,$k1,1
yes88:addiu $k0,$k0,1
sec89:
mflo $3
lui $3,33572
lh $3,12($0)
beq $3,$2,yes89
nop
no89:addiu $k1,$k1,1
yes89:addiu $k0,$k0,1
sec90:
mfhi $3
mfhi $3
nop
beq $3,$2,yes90
nop
no90:addiu $k1,$k1,1
yes90:addiu $k0,$k0,1
sec91:
mfhi $3
mflo $3
xor $3,$4,$5
beq $3,$2,yes91
nop
no91:addiu $k1,$k1,1
yes91:addiu $k0,$k0,1
sec92:
mfhi $3
mfhi $3
addiu $3,$1,25302
beq $3,$2,yes92
nop
no92:addiu $k1,$k1,1
yes92:addiu $k0,$k0,1
sec93:
mfhi $3
mfhi $3
mfhi $3
beq $3,$2,yes93
nop
no93:addiu $k1,$k1,1
yes93:addiu $k0,$k0,1
sec94:
mflo $3
mfhi $3
lbu $3,6($0)
beq $3,$2,yes94
nop
no94:addiu $k1,$k1,1
yes94:addiu $k0,$k0,1
sec95:
mflo $3
lb $3,15($0)
nop
beq $3,$2,yes95
nop
no95:addiu $k1,$k1,1
yes95:addiu $k0,$k0,1
sec96:
mfhi $3
lw $3,16($0)
xor $3,$1,$1
beq $3,$2,yes96
nop
no96:addiu $k1,$k1,1
yes96:addiu $k0,$k0,1
sec97:
mflo $3
lhu $3,8($0)
slti $3,$1,18088
beq $3,$2,yes97
nop
no97:addiu $k1,$k1,1
yes97:addiu $k0,$k0,1
sec98:
mflo $3
lb $3,9($0)
mfhi $3
beq $3,$2,yes98
nop
no98:addiu $k1,$k1,1
yes98:addiu $k0,$k0,1
sec99:
mflo $3
lb $3,1($0)
lb $3,16($0)
beq $3,$2,yes99
nop
no99:addiu $k1,$k1,1
yes99:addiu $k0,$k0,1
sec100:
lw $3,12($0)
nop
nop
beq $3,$2,yes100
nop
no100:addiu $k1,$k1,1
yes100:addiu $k0,$k0,1
sec101:
lw $3,16($0)
nop
slt $3,$3,$4
beq $3,$2,yes101
nop
no101:addiu $k1,$k1,1
yes101:addiu $k0,$k0,1
sec102:
lb $3,12($0)
nop
addiu $3,$2,-12165
beq $3,$2,yes102
nop
no102:addiu $k1,$k1,1
yes102:addiu $k0,$k0,1
sec103:
lh $3,2($0)
nop
mflo $3
beq $3,$2,yes103
nop
no103:addiu $k1,$k1,1
yes103:addiu $k0,$k0,1
sec104:
lhu $3,0($0)
nop
lhu $3,0($0)
beq $3,$2,yes104
nop
no104:addiu $k1,$k1,1
yes104:addiu $k0,$k0,1
sec105:
lh $3,8($0)
sltu $3,$3,$4
nop
beq $3,$2,yes105
nop
no105:addiu $k1,$k1,1
yes105:addiu $k0,$k0,1
sec106:
lbu $3,0($0)
sltu $3,$6,$3
or $3,$1,$1
beq $3,$2,yes106
nop
no106:addiu $k1,$k1,1
yes106:addiu $k0,$k0,1
sec107:
lw $3,16($0)
sltu $3,$3,$4
xori $3,$4,19339
beq $3,$2,yes107
nop
no107:addiu $k1,$k1,1
yes107:addiu $k0,$k0,1
sec108:
lhu $3,12($0)
and $3,$0,$6
mfhi $3
beq $3,$2,yes108
nop
no108:addiu $k1,$k1,1
yes108:addiu $k0,$k0,1
sec109:
lw $3,0($0)
or $3,$2,$2
lb $3,12($0)
beq $3,$2,yes109
nop
no109:addiu $k1,$k1,1
yes109:addiu $k0,$k0,1
sec110:
lh $3,12($0)
addiu $3,$5,12998
nop
beq $3,$2,yes110
nop
no110:addiu $k1,$k1,1
yes110:addiu $k0,$k0,1
sec111:
lw $3,16($0)
sltiu $3,$3,-28198
or $3,$3,$2
beq $3,$2,yes111
nop
no111:addiu $k1,$k1,1
yes111:addiu $k0,$k0,1
sec112:
lh $3,8($0)
xori $3,$2,8182
lui $3,12487
beq $3,$2,yes112
nop
no112:addiu $k1,$k1,1
yes112:addiu $k0,$k0,1
sec113:
lw $3,0($0)
lui $3,11342
mflo $3
beq $3,$2,yes113
nop
no113:addiu $k1,$k1,1
yes113:addiu $k0,$k0,1
sec114:
lbu $3,15($0)
xori $3,$2,5300
lbu $3,8($0)
beq $3,$2,yes114
nop
no114:addiu $k1,$k1,1
yes114:addiu $k0,$k0,1
sec115:
lh $3,8($0)
mflo $3
nop
beq $3,$2,yes115
nop
no115:addiu $k1,$k1,1
yes115:addiu $k0,$k0,1
sec116:
lh $3,6($0)
mflo $3
nor $3,$1,$5
beq $3,$2,yes116
nop
no116:addiu $k1,$k1,1
yes116:addiu $k0,$k0,1
sec117:
lb $3,15($0)
mfhi $3
sltiu $3,$3,17180
beq $3,$2,yes117
nop
no117:addiu $k1,$k1,1
yes117:addiu $k0,$k0,1
sec118:
lhu $3,4($0)
mfhi $3
mflo $3
beq $3,$2,yes118
nop
no118:addiu $k1,$k1,1
yes118:addiu $k0,$k0,1
sec119:
lh $3,4($0)
mfhi $3
lhu $3,12($0)
beq $3,$2,yes119
nop
no119:addiu $k1,$k1,1
yes119:addiu $k0,$k0,1
sec120:
lbu $3,13($0)
lh $3,10($0)
nop
beq $3,$2,yes120
nop
no120:addiu $k1,$k1,1
yes120:addiu $k0,$k0,1
sec121:
lbu $3,10($0)
lh $3,4($0)
and $3,$2,$2
beq $3,$2,yes121
nop
no121:addiu $k1,$k1,1
yes121:addiu $k0,$k0,1
sec122:
lh $3,10($0)
lw $3,12($0)
slti $3,$3,22026
beq $3,$2,yes122
nop
no122:addiu $k1,$k1,1
yes122:addiu $k0,$k0,1
sec123:
lhu $3,2($0)
lh $3,2($0)
mflo $3
beq $3,$2,yes123
nop
no123:addiu $k1,$k1,1
yes123:addiu $k0,$k0,1
sec124:
lb $3,13($0)
lb $3,13($0)
lhu $3,12($0)
beq $3,$2,yes124
nop
no124:addiu $k1,$k1,1
yes124:addiu $k0,$k0,1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r15
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x13315, %rsi
lea addresses_A_ht+0x918d, %rdi
nop
nop
nop
sub $42603, %r15
mov $123, %rcx
rep movsw
nop
nop
sub %rbp, %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r15
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
// Store
lea addresses_normal+0x18271, %rbx
nop
nop
nop
nop
nop
and $56093, %rcx
movl $0x51525354, (%rbx)
nop
nop
nop
nop
dec %rbx
// Store
lea addresses_US+0x1998d, %rdi
clflush (%rdi)
nop
nop
add %rax, %rax
movw $0x5152, (%rdi)
nop
nop
nop
nop
sub %rsi, %rsi
// Load
lea addresses_WT+0x168b5, %r12
nop
nop
nop
nop
cmp $16682, %rax
mov (%r12), %ebx
nop
add $58689, %rdi
// Faulty Load
lea addresses_US+0x1998d, %rdi
nop
nop
nop
dec %r10
mov (%rdi), %rbx
lea oracles, %r10
and $0xff, %rbx
shlq $12, %rbx
mov (%r10,%rbx,1), %rbx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_normal', 'size': 4, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 2, 'AVXalign': True}}
{'src': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_WT', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 9, 'same': True}}
{'52': 2821}
52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52
*/
|
; A117940: a(0)=1, thereafter a(3n) = a(3n+1)/3 = a(n), a(3n+2)=0.
; Submitted by Christian Krause
; 1,3,0,3,9,0,0,0,0,3,9,0,9,27,0,0,0,0,0,0,0,0,0,0,0,0,0,3,9,0,9,27,0,0,0,0,9,27,0,27,81,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,9,0,9,27,0,0,0,0,9,27,0,27,81,0,0,0,0,0
mov $1,1
lpb $0
mov $2,$0
div $0,3
add $2,10
mod $2,3
add $2,1
bin $2,2
mul $1,$2
lpe
mov $0,$1
|
lda #<{c1}
sta {m1}
lda #>{c1}
sta {m1}+1
lda {m2}
sta {m1}+2
lda {m2}+1
sta {m1}+3
|
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
KnownPluginList::KnownPluginList() {}
KnownPluginList::~KnownPluginList() {}
void KnownPluginList::clear()
{
ScopedLock lock (typesArrayLock);
if (! types.isEmpty())
{
types.clear();
sendChangeMessage();
}
}
PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
{
ScopedLock lock (typesArrayLock);
for (auto* desc : types)
if (desc->fileOrIdentifier == fileOrIdentifier)
return desc;
return nullptr;
}
PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
{
ScopedLock lock (typesArrayLock);
for (auto* desc : types)
if (desc->matchesIdentifierString (identifierString))
return desc;
return nullptr;
}
bool KnownPluginList::addType (const PluginDescription& type)
{
{
ScopedLock lock (typesArrayLock);
for (auto* desc : types)
{
if (desc->isDuplicateOf (type))
{
// strange - found a duplicate plugin with different info..
jassert (desc->name == type.name);
jassert (desc->isInstrument == type.isInstrument);
*desc = type;
return false;
}
}
types.insert (0, new PluginDescription (type));
}
sendChangeMessage();
return true;
}
void KnownPluginList::removeType (const int index)
{
{
ScopedLock lock (typesArrayLock);
types.remove (index);
}
sendChangeMessage();
}
bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier,
AudioPluginFormat& formatToUse) const
{
if (getTypeForFile (fileOrIdentifier) == nullptr)
return false;
ScopedLock lock (typesArrayLock);
for (auto* d : types)
if (d->fileOrIdentifier == fileOrIdentifier && formatToUse.pluginNeedsRescanning (*d))
return false;
return true;
}
void KnownPluginList::setCustomScanner (CustomScanner* newScanner)
{
scanner.reset (newScanner);
}
bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
const bool dontRescanIfAlreadyInList,
OwnedArray<PluginDescription>& typesFound,
AudioPluginFormat& format)
{
const ScopedLock sl (scanLock);
if (dontRescanIfAlreadyInList
&& getTypeForFile (fileOrIdentifier) != nullptr)
{
bool needsRescanning = false;
ScopedLock lock (typesArrayLock);
for (auto* d : types)
{
if (d->fileOrIdentifier == fileOrIdentifier && d->pluginFormatName == format.getName())
{
if (format.pluginNeedsRescanning (*d))
needsRescanning = true;
else
typesFound.add (new PluginDescription (*d));
}
}
if (! needsRescanning)
return false;
}
if (blacklist.contains (fileOrIdentifier))
return false;
OwnedArray<PluginDescription> found;
{
const ScopedUnlock sl2 (scanLock);
if (scanner != nullptr)
{
if (! scanner->findPluginTypesFor (format, found, fileOrIdentifier))
addToBlacklist (fileOrIdentifier);
}
else
{
format.findAllTypesForFile (found, fileOrIdentifier);
}
}
for (auto* desc : found)
{
jassert (desc != nullptr);
addType (*desc);
typesFound.add (new PluginDescription (*desc));
}
return ! found.isEmpty();
}
void KnownPluginList::scanAndAddDragAndDroppedFiles (AudioPluginFormatManager& formatManager,
const StringArray& files,
OwnedArray<PluginDescription>& typesFound)
{
for (const auto& filenameOrID : files)
{
bool found = false;
for (int j = 0; j < formatManager.getNumFormats(); ++j)
{
auto* format = formatManager.getFormat (j);
if (format->fileMightContainThisPluginType (filenameOrID)
&& scanAndAddFile (filenameOrID, true, typesFound, *format))
{
found = true;
break;
}
}
if (! found)
{
const File f (filenameOrID);
if (f.isDirectory())
{
StringArray s;
for (auto& subFile : f.findChildFiles (File::findFilesAndDirectories, false))
s.add (subFile.getFullPathName());
scanAndAddDragAndDroppedFiles (formatManager, s, typesFound);
}
}
}
scanFinished();
}
void KnownPluginList::scanFinished()
{
if (scanner != nullptr)
scanner->scanFinished();
}
const StringArray& KnownPluginList::getBlacklistedFiles() const
{
return blacklist;
}
void KnownPluginList::addToBlacklist (const String& pluginID)
{
if (! blacklist.contains (pluginID))
{
blacklist.add (pluginID);
sendChangeMessage();
}
}
void KnownPluginList::removeFromBlacklist (const String& pluginID)
{
const int index = blacklist.indexOf (pluginID);
if (index >= 0)
{
blacklist.remove (index);
sendChangeMessage();
}
}
void KnownPluginList::clearBlacklistedFiles()
{
if (blacklist.size() > 0)
{
blacklist.clear();
sendChangeMessage();
}
}
//==============================================================================
struct PluginSorter
{
PluginSorter (KnownPluginList::SortMethod sortMethod, bool forwards) noexcept
: method (sortMethod), direction (forwards ? 1 : -1) {}
bool operator() (const PluginDescription* first, const PluginDescription* second) const
{
int diff = 0;
switch (method)
{
case KnownPluginList::sortByCategory: diff = first->category.compareNatural (second->category, false); break;
case KnownPluginList::sortByManufacturer: diff = first->manufacturerName.compareNatural (second->manufacturerName, false); break;
case KnownPluginList::sortByFormat: diff = first->pluginFormatName.compare (second->pluginFormatName); break;
case KnownPluginList::sortByFileSystemLocation: diff = lastPathPart (first->fileOrIdentifier).compare (lastPathPart (second->fileOrIdentifier)); break;
case KnownPluginList::sortByInfoUpdateTime: diff = compare (first->lastInfoUpdateTime, second->lastInfoUpdateTime); break;
default: break;
}
if (diff == 0)
diff = first->name.compareNatural (second->name, false);
return diff * direction < 0;
}
private:
static String lastPathPart (const String& path)
{
return path.replaceCharacter ('\\', '/').upToLastOccurrenceOf ("/", false, false);
}
static int compare (Time a, Time b) noexcept
{
if (a < b) return -1;
if (b < a) return 1;
return 0;
}
KnownPluginList::SortMethod method;
int direction;
};
void KnownPluginList::sort (const SortMethod method, bool forwards)
{
if (method != defaultOrder)
{
Array<PluginDescription*> oldOrder, newOrder;
{
ScopedLock lock (typesArrayLock);
oldOrder.addArray (types);
std::stable_sort (types.begin(), types.end(), PluginSorter (method, forwards));
newOrder.addArray (types);
}
if (oldOrder != newOrder)
sendChangeMessage();
}
}
//==============================================================================
XmlElement* KnownPluginList::createXml() const
{
auto e = new XmlElement ("KNOWNPLUGINS");
{
ScopedLock lock (typesArrayLock);
for (int i = types.size(); --i >= 0;)
e->prependChildElement (types.getUnchecked(i)->createXml());
}
for (auto& b : blacklist)
e->createNewChildElement ("BLACKLISTED")->setAttribute ("id", b);
return e;
}
void KnownPluginList::recreateFromXml (const XmlElement& xml)
{
clear();
clearBlacklistedFiles();
if (xml.hasTagName ("KNOWNPLUGINS"))
{
forEachXmlChildElement (xml, e)
{
PluginDescription info;
if (e->hasTagName ("BLACKLISTED"))
blacklist.add (e->getStringAttribute ("id"));
else if (info.loadFromXml (*e))
addType (info);
}
}
}
//==============================================================================
struct PluginTreeUtils
{
enum { menuIdBase = 0x324503f4 };
static void buildTreeByFolder (KnownPluginList::PluginTree& tree, const Array<PluginDescription*>& allPlugins)
{
for (auto* pd : allPlugins)
{
auto path = pd->fileOrIdentifier.replaceCharacter ('\\', '/')
.upToLastOccurrenceOf ("/", false, false);
if (path.substring (1, 2) == ":")
path = path.substring (2);
addPlugin (tree, pd, path);
}
optimiseFolders (tree, false);
}
static void optimiseFolders (KnownPluginList::PluginTree& tree, bool concatenateName)
{
for (int i = tree.subFolders.size(); --i >= 0;)
{
auto& sub = *tree.subFolders.getUnchecked(i);
optimiseFolders (sub, concatenateName || (tree.subFolders.size() > 1));
if (sub.plugins.isEmpty())
{
for (auto* s : sub.subFolders)
{
if (concatenateName)
s->folder = sub.folder + "/" + s->folder;
tree.subFolders.add (s);
}
sub.subFolders.clear (false);
tree.subFolders.remove (i);
}
}
}
static void buildTreeByCategory (KnownPluginList::PluginTree& tree,
const Array<PluginDescription*>& sorted,
const KnownPluginList::SortMethod sortMethod)
{
String lastType;
std::unique_ptr<KnownPluginList::PluginTree> current (new KnownPluginList::PluginTree());
for (auto* pd : sorted)
{
auto thisType = (sortMethod == KnownPluginList::sortByCategory ? pd->category
: pd->manufacturerName);
if (! thisType.containsNonWhitespaceChars())
thisType = "Other";
if (! thisType.equalsIgnoreCase (lastType))
{
if (current->plugins.size() + current->subFolders.size() > 0)
{
current->folder = lastType;
tree.subFolders.add (current.release());
current.reset (new KnownPluginList::PluginTree());
}
lastType = thisType;
}
current->plugins.add (pd);
}
if (current->plugins.size() + current->subFolders.size() > 0)
{
current->folder = lastType;
tree.subFolders.add (current.release());
}
}
static void addPlugin (KnownPluginList::PluginTree& tree, PluginDescription* const pd, String path)
{
if (path.isEmpty())
{
tree.plugins.add (pd);
}
else
{
#if JUCE_MAC
if (path.containsChar (':'))
path = path.fromFirstOccurrenceOf (":", false, false); // avoid the special AU formatting nonsense on Mac..
#endif
auto firstSubFolder = path.upToFirstOccurrenceOf ("/", false, false);
auto remainingPath = path.fromFirstOccurrenceOf ("/", false, false);
for (int i = tree.subFolders.size(); --i >= 0;)
{
KnownPluginList::PluginTree& subFolder = *tree.subFolders.getUnchecked(i);
if (subFolder.folder.equalsIgnoreCase (firstSubFolder))
{
addPlugin (subFolder, pd, remainingPath);
return;
}
}
auto newFolder = new KnownPluginList::PluginTree();
newFolder->folder = firstSubFolder;
tree.subFolders.add (newFolder);
addPlugin (*newFolder, pd, remainingPath);
}
}
static bool containsDuplicateNames (const Array<const PluginDescription*>& plugins, const String& name)
{
int matches = 0;
for (int i = 0; i < plugins.size(); ++i)
if (plugins.getUnchecked(i)->name == name)
if (++matches > 1)
return true;
return false;
}
static bool addToMenu (const KnownPluginList::PluginTree& tree, PopupMenu& m,
const OwnedArray<PluginDescription>& allPlugins,
const String& currentlyTickedPluginID)
{
bool isTicked = false;
for (auto* sub : tree.subFolders)
{
PopupMenu subMenu;
const bool isItemTicked = addToMenu (*sub, subMenu, allPlugins, currentlyTickedPluginID);
isTicked = isTicked || isItemTicked;
m.addSubMenu (sub->folder, subMenu, true, nullptr, isItemTicked, 0);
}
for (auto* plugin : tree.plugins)
{
auto name = plugin->name;
if (containsDuplicateNames (tree.plugins, name))
name << " (" << plugin->pluginFormatName << ')';
const bool isItemTicked = plugin->matchesIdentifierString (currentlyTickedPluginID);
isTicked = isTicked || isItemTicked;
m.addItem (allPlugins.indexOf (plugin) + menuIdBase, name, true, isItemTicked);
}
return isTicked;
}
};
KnownPluginList::PluginTree* KnownPluginList::createTree (const SortMethod sortMethod) const
{
Array<PluginDescription*> sorted;
{
ScopedLock lock (typesArrayLock);
sorted.addArray (types);
}
std::stable_sort (sorted.begin(), sorted.end(), PluginSorter (sortMethod, true));
auto* tree = new PluginTree();
if (sortMethod == sortByCategory || sortMethod == sortByManufacturer || sortMethod == sortByFormat)
{
PluginTreeUtils::buildTreeByCategory (*tree, sorted, sortMethod);
}
else if (sortMethod == sortByFileSystemLocation)
{
PluginTreeUtils::buildTreeByFolder (*tree, sorted);
}
else
{
for (auto* p : sorted)
tree->plugins.add (p);
}
return tree;
}
//==============================================================================
void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod,
const String& currentlyTickedPluginID) const
{
std::unique_ptr<PluginTree> tree (createTree (sortMethod));
PluginTreeUtils::addToMenu (*tree, menu, types, currentlyTickedPluginID);
}
int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
{
const int i = menuResultCode - PluginTreeUtils::menuIdBase;
return isPositiveAndBelow (i, types.size()) ? i : -1;
}
//==============================================================================
KnownPluginList::CustomScanner::CustomScanner() {}
KnownPluginList::CustomScanner::~CustomScanner() {}
void KnownPluginList::CustomScanner::scanFinished() {}
bool KnownPluginList::CustomScanner::shouldExit() const noexcept
{
if (auto* job = ThreadPoolJob::getCurrentThreadPoolJob())
return job->shouldExit();
return false;
}
} // namespace juce
|
; A215543: Number of standard Young tableaux of shape [3n,3].
; 0,5,48,154,350,663,1120,1748,2574,3625,4928,6510,8398,10619,13200,16168,19550,23373,27664,32450,37758,43615,50048,57084,64750,73073,82080,91798,102254,113475,125488,138320,151998,166549,182000,198378,215710,234023,253344,273700,295118,317625,341248,366014,391950,419083,447440,477048,507934,540125,573648,608530,644798,682479,721600,762188,804270,847873,893024,939750,988078,1038035,1089648,1142944,1197950,1254693,1313200,1373498,1435614,1499575,1565408,1633140,1702798,1774409,1848000,1923598,2001230,2080923,2162704,2246600,2332638,2420845,2511248,2603874,2698750,2795903,2895360,2997148,3101294,3207825,3316768,3428150,3541998,3658339,3777200,3898608,4022590,4149173,4278384,4410250,4544798,4682055,4822048,4964804,5110350,5258713,5409920,5563998,5720974,5880875,6043728,6209560,6378398,6550269,6725200,6903218,7084350,7268623,7456064,7646700,7840558,8037665,8238048,8441734,8648750,8859123,9072880,9290048,9510654,9734725,9962288,10193370,10427998,10666199,10908000,11153428,11402510,11655273,11911744,12171950,12435918,12703675,12975248,13250664,13529950,13813133,14100240,14391298,14686334,14985375,15288448,15595580,15906798,16222129,16541600,16865238,17193070,17525123,17861424,18202000,18546878,18896085,19249648,19607594,19969950,20336743,20708000,21083748,21464014,21848825,22238208,22632190,23030798,23434059,23842000,24254648,24672030,25094173,25521104,25952850,26389438,26830895,27277248,27728524,28184750,28645953,29112160,29583398,30059694,30541075,31027568,31519200,32015998,32517989,33025200,33537658,34055390,34578423,35106784,35640500,36179598,36724105,37274048,37829454,38390350,38956763,39528720,40106248,40689374,41278125,41872528,42472610,43078398,43689919,44307200,44930268,45559150,46193873,46834464,47480950,48133358,48791715,49456048,50126384,50802750,51485173,52173680,52868298,53569054,54275975,54989088,55708420,56433998,57165849,57904000,58648478,59399310,60156523,60920144,61690200,62466718,63249725,64039248,64835314,65637950,66447183,67263040,68085548,68914734,69750625
mul $0,3
add $0,2
mov $2,$0
bin $0,3
trn $0,$2
mov $1,$0
|
/**
* @file InputUtils.hpp
* @brief InputUtils class prototype.
* @author zer0
* @date 2020-03-22
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_IO_INPUTUTILS_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_IO_INPUTUTILS_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <string>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace io {
TBAG_CONSTEXPR int const INPUT_BUFFER_SIZE = 2048;
TBAG_CONSTEXPR char const * const DEFAULT_READ_INPUT_MESSAGE = "Enter EOF(CTRL+D) to exit the input mode.";
/**
* The string is received from standard input(<code>stdin</code>) until EOF(<code>CTRL+D</code>) is received.
*/
TBAG_API std::string readInput(int buffer_size = INPUT_BUFFER_SIZE);
} // namespace io
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_IO_INPUTUTILS_HPP__
|
extern m7_ippsAESGetSize:function
extern n8_ippsAESGetSize:function
extern y8_ippsAESGetSize:function
extern e9_ippsAESGetSize:function
extern l9_ippsAESGetSize:function
extern n0_ippsAESGetSize:function
extern k0_ippsAESGetSize:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsAESGetSize
.Larraddr_ippsAESGetSize:
dq m7_ippsAESGetSize
dq n8_ippsAESGetSize
dq y8_ippsAESGetSize
dq e9_ippsAESGetSize
dq l9_ippsAESGetSize
dq n0_ippsAESGetSize
dq k0_ippsAESGetSize
segment .text
global ippsAESGetSize:function (ippsAESGetSize.LEndippsAESGetSize - ippsAESGetSize)
.Lin_ippsAESGetSize:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsAESGetSize:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsAESGetSize]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsAESGetSize:
|
db MAROWAK ; pokedex id
db 60 ; base hp
db 80 ; base attack
db 110 ; base defense
db 45 ; base speed
db 50 ; base special
db GROUND ; species type 1
db GROUND ; species type 2
db 75 ; catch rate
db 124 ; base exp yield
INCBIN "pic/gsmon/marowak.pic",0,1 ; 66, sprite dimensions
dw MarowakPicFront
dw MarowakPicBack
; attacks known at lvl 0
db POUND
db 0
db 0
db 0
db 0 ; growth rate
; learnset
tmlearn 1,3,5,6,8
tmlearn 9,10,11,13,14,15
tmlearn 17,18,19,20,23
tmlearn 26,27,28,31,32
tmlearn 34,38,40
tmlearn 44,48
tmlearn 50,54
db BANK(MarowakPicFront)
|
;
; CubicDoom
;
; by Oscar Toledo G.
;
; Creation date: Nov/21/2019.
; Revision date: Nov/22/2019. Now working.
; Revision date: Nov/23/2019. Optimized.
; Revision date: Nov/24/2019. Builds a world. Added evil cubes, and
; can shoot them. 517 bytes.
; Revision date: Nov/25/2019. Optimized last bytes. 509 bytes.
; Revision date: Nov/26/2019. Smaller extract. 508 bytes
; (Peter Ferrie).
;
;
; Tricks used:
; o "Slow" ray-casting so doesn't matter if hits horizontal or
; vertical wall.
;
cpu 8086
EMPTY: equ 0x00 ; Code for empty space
WALL: equ 0x80 ; Code for wall
ENEMY: equ 0xc0 ; Code for enemy, includes shot count
%ifdef com_file
org 0x0100
%else
org 0x7c00
%endif
down: equ 0x000b ; Enemies down
shot: equ 0x000a ; Shot made
rnd: equ 0x0008 ; Random number
px: equ 0x0006 ; Current X position (4.12)
py: equ 0x0004 ; Current Y position (4.12)
pa: equ 0x0002 ; Current screen angle
oldtim: equ 0x0000 ; Old time
maze: equ 0xff00 ; Location of maze (16x16)
;
; Start of the game
;
start:
mov ax,0x0013 ; Graphics mode 320x200x256 colors
int 0x10 ; Setup video mode
mov ax,0xa000 ; Point to video memory.
mov ds,ax
mov es,ax
restart:
cld
xor cx,cx
push cx ; shot+down
in ax,0x40
push ax ; rnd
mov ah,0x18 ; Start point at maze
push ax ; px
push ax ; py
mov cl,0x04
push cx ; pa
push cx ; oldtim
mov bp,sp ; Setup BP to access variables
mov bx,maze ; Point to maze
.0: mov al,bl
add al,0x11 ; Right and bottom borders at zero
cmp al,0x22 ; Inside any border?
jb .5 ; Yes, jump
and al,0x0e ; Inside left/right border?
mov al,EMPTY
jne .4 ; No, jump
.5: mov al,WALL
.4: mov [bx],al ; Put into maze
inc bx ; Next square
jne .0 ; If BX is zero, maze completed
mov cl,12 ; 12 walls and enemies
mov [bp+down],cl ; Take note of enemies down
mov di,maze+34 ; Point to center of maze
mov dl,12 ; Modulo 12 for random number
.2:
call random
mov byte [di+bx],WALL ; Setup a wall
call random
mov byte [di+bx],ENEMY ; Setup an enemy
add di,byte 16 ; Go to next row of maze
loop .2 ; Repeat until filled
game_loop:
call wait_frame ; Wait a frame
and dl,31 ; 32 frames have passed?
jnz .16 ; No, jump
;
; Move cubes
;
call get_dir ; Get player position, also SI=0
call get_pos ; Convert position to maze address
mov cx,bx ; Save into CX
mov bl,0 ; BH already ready, start at corner
.17: cmp byte [bx],ENEMY
jb .18
cmp bx,cx ; Cube over player?
jne .25 ; No, jump
;
; Handle death
;
.22:
mov byte [si],0x0c ; Blood pixel
add si,byte 23 ; Advance by prime number
.23:
je restart ; Zero = full loop, restart game.
jnb .22 ; Carry = one fill complete.
push si
call wait_frame ; Wait a frame (for fast machines)
pop si
jmp .22 ; Continue
.25:
mov di,bx
mov al,bl
mov ah,cl
mov dx,0x0f0f ; Extract columns
and dx,ax
xor ax,dx ; Extract rows
cmp ah,al ; Same row?
je .19 ; Yes, jump
lea di,[bx+0x10] ; Cube moves down
jnb .19
lea di,[bx-0x10] ; Cube moves up
.19: cmp dh,dl ; Same column?
je .20 ; Yes, jump
dec di ; Cube goes left
jb .20
inc di ; Cube goes right
inc di
.20: cmp byte [di],0 ; Can move?
jne .18 ; No, jump.
mov al,[bx] ; Take cube
mov byte [bx],0 ; Erase origin
stosb ; Put into new place
.18:
inc bx ; Continue searching the maze...
jne .17 ; ...until the end
.16:
;
; Draw 3D view
;
mov di,39 ; Column number is 39
.2:
lea ax,[di-20] ; Almost 60 degrees to the left
add ax,[bp+pa] ; Get vision angle
call get_dir ; Get position and direction
.3:
call read_maze ; Verify wall hit
jnc .3 ; Continue if it was open space
.4:
mov cx,0x1204 ; Add grayscale color set...
; ...also load CL with 4. (division by 16)
jz .24 ; Jump if normal wall
mov ch,32 ; Rainbow
cmp di,byte 20
jne .24 ; Jump if not at center
cmp byte [bp+shot],1
je .24 ; Jump if not shooting
call get_pos
inc byte [bx] ; Increase cube hits
cmp byte [bx],ENEMY+3 ; 3 hits?
jne .24 ; No, jump
mov byte [bx],0 ; Yes, remove.
dec byte [bp+down] ; One cube less
je .23 ; Zero means to get another level
.24:
lea ax,[di+12] ; Get cos(-30) to cos(30)
call get_sin ; Get cos (8 bit fraction)
mul si ; Correct wall distance to...
mov bl,ah ; ...avoid fishbowl effect
mov bh,dl ; Divide by 256
inc bx ; Avoid zero value
mov ax,0x0800 ; Constant for projection plane
cwd
div bx ; Divide
cmp ax,198 ; Limit to screen height
jb .14
mov ax,198
.14: mov si,ax ; Height of wall
shr ax,cl ; Divide distance by 16
add al,ch ; Add palette index
xchg ax,bx ; Put into BX
push di
dec cx ; CL=3. Multiply column by 8 pixels
shl di,cl
mov ax,200 ; Height of screen...
sub ax,si ; ...minus wall height
shr ax,1 ; Divide by 2
push ax
push si
xchg ax,cx
mov al,[bp+shot] ; Ceiling color
call fill_column
xchg ax,bx ; Wall color
pop cx
call fill_column
mov al,0x03 ; Floor color (a la Wolfenstein)
pop cx
call fill_column
pop di
dec di ; Decrease column
jns .2 ; Completed? No, jump.
mov ah,0x02 ; Service 0x02 = Read modifier keys
int 0x16 ; Call BIOS
mov bx,[bp+pa] ; Get current angle
test al,0x04 ; Left Ctrl pressed?
je .8
dec bx ; Decrease angle
dec bx
.8:
test al,0x08 ; Left Alt pressed?
je .9
inc bx ; Increase angle
inc bx
.9:
mov ah,1 ; No shot
test al,0x01 ; Right shift pressed?
je .11
test bh,0x01 ; But not before?
jne .11
mov ah,7 ; Indicate shot
.11: mov [bp+shot],ah
mov bh,al
mov [bp+pa],bx ; Update angle
test al,0x02 ; Left shift pressed?
je .10
xchg ax,bx ; Put angle into AX
call get_dir ; Get position and direction
.5: call read_maze ; Move and check for wall hit
jc .10 ; Hit, jump without updating position.
cmp si,byte 4 ; Four times (the speed)
jne .5
mov [bp+px],dx ; Update X position
mov [bp+py],bx ; Update Y position
.10:
jmp game_loop ; Repeat game loop
;
; Get a direction vector
;
get_dir:
xor si,si ; Wall distance = 0
mov dx,[bp+px] ; Get X position
push ax
call get_sin ; Get sine
xchg ax,cx ; Onto DX
pop ax
add al,32 ; Add 90 degrees to get cosine
;
; Get sine
;
get_sin:
test al,64 ; Angle >= 180 degrees?
pushf
test al,32 ; Angle 90-179 or 270-359 degrees?
je .2
xor al,31 ; Invert bits (reduces table)
.2:
and ax,31 ; Only 90 degrees in table
mov bx,sin_table
cs xlat ; Get fraction
popf
je .1 ; Jump if angle less than 180
neg ax ; Else negate result
.1:
mov bx,[bp+py] ; Get Y position
ret
;
; Read maze
;
read_maze:
inc si ; Count distance to wall
add dx,cx ; Move X
add bx,ax ; Move Y
push bx
push cx
call get_pos
mov bl,[bx] ; Read maze byte
shl bl,1 ; Carry = 1 = wall, Zero = Wall 0 / 1
pop cx
pop bx
ret ; Return
;
; Convert coordinates to position
;
get_pos:
mov bl,dh ; X-coordinate
mov cl,0x04 ; Divide by 4096
shr bl,cl
and bh,0xf0 ; Y-coordinate / 4096 * 16
or bl,bh ; Translate to maze array
mov bh,maze>>8
ret
;
; Fill a screen column
;
fill_column:
mov ah,al ; Duplicate pixel value
.1:
stosw ; Draw 2 pixels
stosw ; Draw 2 pixels
stosw ; Draw 2 pixels
stosw ; Draw 2 pixels
add di,0x0138 ; Go to next row
loop .1 ; Repeat until fully drawn
ret ; Return
;
; Generate a pseudo-random number (from bootRogue)
;
random:
mov al,251
mul byte [bp+rnd]
add al,83
mov [bp+rnd],al
mov ah,0
div dl
mov bl,ah
mov bh,0
ret
;
; Wait a frame (18.2 hz)
;
wait_frame:
.1:
mov ah,0x00 ; Get ticks
int 0x1a ; Call BIOS time service
cmp dx,[bp+oldtim] ; Same as old time?
je .1 ; Yes, wait.
mov [bp+oldtim],dx
ret
;
; Sine table (0.8 format)
;
; 32 bytes are 90 degrees.
;
sin_table:
db 0x00,0x09,0x16,0x24,0x31,0x3e,0x47,0x53
db 0x60,0x6c,0x78,0x80,0x8b,0x96,0xa1,0xab
db 0xb5,0xbb,0xc4,0xcc,0xd4,0xdb,0xe0,0xe6
db 0xec,0xf1,0xf5,0xf7,0xfa,0xfd,0xff,0xff
%ifdef com_file
%else
times 510-($-$$) db 0x4f
db 0x55,0xaa ; Make it a bootable sector
%endif
|
;===============================================================================
; Copyright 2015-2020 Intel Corporation
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;===============================================================================
;
;
; Purpose: Cryptography Primitive.
; secp p256r1 specific implementation
;
%include "asmdefs.inc"
%include "ia_32e.inc"
%if (_IPP32E >= _IPP32E_M7)
%assign _xEMULATION_ 1
%assign _ADCX_ADOX_ 1
segment .text align=IPP_ALIGN_FACTOR
align IPP_ALIGN_FACTOR
;; The p256r1 polynomial
Lpoly DQ 0FFFFFFFFFFFFFFFFh,000000000FFFFFFFFh,00000000000000000h,0FFFFFFFF00000001h
;; 2^512 mod P precomputed for p256r1 polynomial
LRR DQ 00000000000000003h,0fffffffbffffffffh,0fffffffffffffffeh,000000004fffffffdh
LOne DD 1,1,1,1,1,1,1,1
LTwo DD 2,2,2,2,2,2,2,2
LThree DD 3,3,3,3,3,3,3,3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_mul_by_2(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_mul_by_2,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rsi,rdi,r12,r13
USES_XMM
COMP_ABI 2
%xdefine a0 r8
%xdefine a1 r9
%xdefine a2 r10
%xdefine a3 r11
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 r12
%xdefine t4 r13
xor t4, t4
mov a0, qword [rsi+sizeof(qword)*0]
mov a1, qword [rsi+sizeof(qword)*1]
mov a2, qword [rsi+sizeof(qword)*2]
mov a3, qword [rsi+sizeof(qword)*3]
shld t4, a3, 1
shld a3, a2, 1
shld a2, a1, 1
shld a1, a0, 1
shl a0, 1
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
sub t0, qword [rel Lpoly+sizeof(qword)*0]
sbb t1, qword [rel Lpoly+sizeof(qword)*1]
sbb t2, qword [rel Lpoly+sizeof(qword)*2]
sbb t3, qword [rel Lpoly+sizeof(qword)*3]
sbb t4, 0
cmovz a0, t0
cmovz a1, t1
cmovz a2, t2
cmovz a3, t3
mov qword [rdi+sizeof(qword)*0], a0
mov qword [rdi+sizeof(qword)*1], a1
mov qword [rdi+sizeof(qword)*2], a2
mov qword [rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_mul_by_2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_div_by_2(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_div_by_2,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rsi,rdi,r12,r13,r14
USES_XMM
COMP_ABI 2
%xdefine a0 r8
%xdefine a1 r9
%xdefine a2 r10
%xdefine a3 r11
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 r12
%xdefine t4 r13
mov a0, qword [rsi+sizeof(qword)*0]
mov a1, qword [rsi+sizeof(qword)*1]
mov a2, qword [rsi+sizeof(qword)*2]
mov a3, qword [rsi+sizeof(qword)*3]
xor t4, t4
xor r14, r14
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
add t0, qword [rel Lpoly+sizeof(qword)*0]
adc t1, qword [rel Lpoly+sizeof(qword)*1]
adc t2, qword [rel Lpoly+sizeof(qword)*2]
adc t3, qword [rel Lpoly+sizeof(qword)*3]
adc t4, 0
test a0, 1
cmovnz a0, t0
cmovnz a1, t1
cmovnz a2, t2
cmovnz a3, t3
cmovnz r14,t4
shrd a0, a1, 1
shrd a1, a2, 1
shrd a2, a3, 1
shrd a3, r14,1
mov qword [rdi+sizeof(qword)*0], a0
mov qword [rdi+sizeof(qword)*1], a1
mov qword [rdi+sizeof(qword)*2], a2
mov qword [rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_div_by_2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_mul_by_3(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_mul_by_3,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rsi,rdi,r12,r13
USES_XMM
COMP_ABI 2
%xdefine a0 r8
%xdefine a1 r9
%xdefine a2 r10
%xdefine a3 r11
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 r12
%xdefine t4 r13
xor t4, t4
mov a0, qword [rsi+sizeof(qword)*0]
mov a1, qword [rsi+sizeof(qword)*1]
mov a2, qword [rsi+sizeof(qword)*2]
mov a3, qword [rsi+sizeof(qword)*3]
shld t4, a3, 1
shld a3, a2, 1
shld a2, a1, 1
shld a1, a0, 1
shl a0, 1
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
sub t0, qword [rel Lpoly+sizeof(qword)*0]
sbb t1, qword [rel Lpoly+sizeof(qword)*1]
sbb t2, qword [rel Lpoly+sizeof(qword)*2]
sbb t3, qword [rel Lpoly+sizeof(qword)*3]
sbb t4, 0
cmovz a0, t0
cmovz a1, t1
cmovz a2, t2
cmovz a3, t3
xor t4, t4
add a0, qword [rsi+sizeof(qword)*0]
adc a1, qword [rsi+sizeof(qword)*1]
adc a2, qword [rsi+sizeof(qword)*2]
adc a3, qword [rsi+sizeof(qword)*3]
adc t4, 0
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
sub t0, qword [rel Lpoly+sizeof(qword)*0]
sbb t1, qword [rel Lpoly+sizeof(qword)*1]
sbb t2, qword [rel Lpoly+sizeof(qword)*2]
sbb t3, qword [rel Lpoly+sizeof(qword)*3]
sbb t4, 0
cmovz a0, t0
cmovz a1, t1
cmovz a2, t2
cmovz a3, t3
mov qword [rdi+sizeof(qword)*0], a0
mov qword [rdi+sizeof(qword)*1], a1
mov qword [rdi+sizeof(qword)*2], a2
mov qword [rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_mul_by_3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_add(uint64_t res[4], uint64_t a[4], uint64_t b[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_add,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rsi,rdi,r12,r13
USES_XMM
COMP_ABI 3
%xdefine a0 r8
%xdefine a1 r9
%xdefine a2 r10
%xdefine a3 r11
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 r12
%xdefine t4 r13
xor t4, t4
mov a0, qword [rsi+sizeof(qword)*0]
mov a1, qword [rsi+sizeof(qword)*1]
mov a2, qword [rsi+sizeof(qword)*2]
mov a3, qword [rsi+sizeof(qword)*3]
add a0, qword [rdx+sizeof(qword)*0]
adc a1, qword [rdx+sizeof(qword)*1]
adc a2, qword [rdx+sizeof(qword)*2]
adc a3, qword [rdx+sizeof(qword)*3]
adc t4, 0
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
sub t0, qword [rel Lpoly+sizeof(qword)*0]
sbb t1, qword [rel Lpoly+sizeof(qword)*1]
sbb t2, qword [rel Lpoly+sizeof(qword)*2]
sbb t3, qword [rel Lpoly+sizeof(qword)*3]
sbb t4, 0
cmovz a0, t0
cmovz a1, t1
cmovz a2, t2
cmovz a3, t3
mov qword [rdi+sizeof(qword)*0], a0
mov qword [rdi+sizeof(qword)*1], a1
mov qword [rdi+sizeof(qword)*2], a2
mov qword [rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_add
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_sub(uint64_t res[4], uint64_t a[4], uint64_t b[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_sub,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rsi,rdi,r12,r13
USES_XMM
COMP_ABI 3
%xdefine a0 r8
%xdefine a1 r9
%xdefine a2 r10
%xdefine a3 r11
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 r12
%xdefine t4 r13
xor t4, t4
mov a0, qword [rsi+sizeof(qword)*0]
mov a1, qword [rsi+sizeof(qword)*1]
mov a2, qword [rsi+sizeof(qword)*2]
mov a3, qword [rsi+sizeof(qword)*3]
sub a0, qword [rdx+sizeof(qword)*0]
sbb a1, qword [rdx+sizeof(qword)*1]
sbb a2, qword [rdx+sizeof(qword)*2]
sbb a3, qword [rdx+sizeof(qword)*3]
sbb t4, 0
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
add t0, qword [rel Lpoly+sizeof(qword)*0]
adc t1, qword [rel Lpoly+sizeof(qword)*1]
adc t2, qword [rel Lpoly+sizeof(qword)*2]
adc t3, qword [rel Lpoly+sizeof(qword)*3]
test t4, t4
cmovnz a0, t0
cmovnz a1, t1
cmovnz a2, t2
cmovnz a3, t3
mov qword [rdi+sizeof(qword)*0], a0
mov qword [rdi+sizeof(qword)*1], a1
mov qword [rdi+sizeof(qword)*2], a2
mov qword [rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_sub
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_neg(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_neg,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rsi,rdi,r12,r13
USES_XMM
COMP_ABI 2
%xdefine a0 r8
%xdefine a1 r9
%xdefine a2 r10
%xdefine a3 r11
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 r12
%xdefine t4 r13
xor t4, t4
xor a0, a0
xor a1, a1
xor a2, a2
xor a3, a3
sub a0, qword [rsi+sizeof(qword)*0]
sbb a1, qword [rsi+sizeof(qword)*1]
sbb a2, qword [rsi+sizeof(qword)*2]
sbb a3, qword [rsi+sizeof(qword)*3]
sbb t4, 0
mov t0, a0
mov t1, a1
mov t2, a2
mov t3, a3
add t0, qword [rel Lpoly+sizeof(qword)*0]
adc t1, qword [rel Lpoly+sizeof(qword)*1]
adc t2, qword [rel Lpoly+sizeof(qword)*2]
adc t3, qword [rel Lpoly+sizeof(qword)*3]
test t4, t4
cmovnz a0, t0
cmovnz a1, t1
cmovnz a2, t2
cmovnz a3, t3
mov qword [rdi+sizeof(qword)*0], a0
mov qword [rdi+sizeof(qword)*1], a1
mov qword [rdi+sizeof(qword)*2], a2
mov qword [rdi+sizeof(qword)*3], a3
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_neg
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_mul_montl(uint64_t res[4], uint64_t a[4], uint64_t b[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; on entry p5=0
; on exit p0=0
;
%macro p256r1_mul_redstep 6.nolist
%xdefine %%p5 %1
%xdefine %%p4 %2
%xdefine %%p3 %3
%xdefine %%p2 %4
%xdefine %%p1 %5
%xdefine %%p0 %6
mov t0, %%p0
shl t0, 32
mov t1, %%p0
shr t1, 32 ;; (t1:t0) = p0*2^32
mov t2, %%p0
mov t3, %%p0
xor %%p0, %%p0
sub t2, t0
sbb t3, t1 ;; (t3:t2) = (p0*2^64+p0) - p0*2^32
add %%p1, t0 ;; (p2:p1) += (t1:t0)
adc %%p2, t1
adc %%p3, t2 ;; (p4:p3) += (t3:t2)
adc %%p4, t3
adc %%p5, 0 ;; extension = {0/1}
%endmacro
align IPP_ALIGN_FACTOR
p256r1_mmull:
%xdefine acc0 r8
%xdefine acc1 r9
%xdefine acc2 r10
%xdefine acc3 r11
%xdefine acc4 r12
%xdefine acc5 r13
%xdefine acc6 r14
%xdefine acc7 r15
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 rbp
%xdefine t4 rbx
; rdi assumed as result
%xdefine aPtr rsi
%xdefine bPtr rbx
xor acc5, acc5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[0]
mov rax, qword [bPtr+sizeof(qword)*0]
mul qword [aPtr+sizeof(qword)*0]
mov acc0, rax
mov acc1, rdx
mov rax, qword [bPtr+sizeof(qword)*0]
mul qword [aPtr+sizeof(qword)*1]
add acc1, rax
adc rdx, 0
mov acc2, rdx
mov rax, qword [bPtr+sizeof(qword)*0]
mul qword [aPtr+sizeof(qword)*2]
add acc2, rax
adc rdx, 0
mov acc3, rdx
mov rax, qword [bPtr+sizeof(qword)*0]
mul qword [aPtr+sizeof(qword)*3]
add acc3, rax
adc rdx, 0
mov acc4, rdx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 0
p256r1_mul_redstep acc5,acc4,acc3,acc2,acc1,acc0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[1]
mov rax, qword [bPtr+sizeof(qword)*1]
mul qword [aPtr+sizeof(qword)*0]
add acc1, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*1]
mul qword [aPtr+sizeof(qword)*1]
add acc2, rcx
adc rdx, 0
add acc2, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*1]
mul qword [aPtr+sizeof(qword)*2]
add acc3, rcx
adc rdx, 0
add acc3, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*1]
mul qword [aPtr+sizeof(qword)*3]
add acc4, rcx
adc rdx, 0
add acc4, rax
adc acc5, rdx
adc acc0, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 1
p256r1_mul_redstep acc0,acc5,acc4,acc3,acc2,acc1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[2]
mov rax, qword [bPtr+sizeof(qword)*2]
mul qword [aPtr+sizeof(qword)*0]
add acc2, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*2]
mul qword [aPtr+sizeof(qword)*1]
add acc3, rcx
adc rdx, 0
add acc3, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*2]
mul qword [aPtr+sizeof(qword)*2]
add acc4, rcx
adc rdx, 0
add acc4, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*2]
mul qword [aPtr+sizeof(qword)*3]
add acc5, rcx
adc rdx, 0
add acc5, rax
adc acc0, rdx
adc acc1, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 2
p256r1_mul_redstep acc1,acc0,acc5,acc4,acc3,acc2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[3]
mov rax, qword [bPtr+sizeof(qword)*3]
mul qword [aPtr+sizeof(qword)*0]
add acc3, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*3]
mul qword [aPtr+sizeof(qword)*1]
add acc4, rcx
adc rdx, 0
add acc4, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*3]
mul qword [aPtr+sizeof(qword)*2]
add acc5, rcx
adc rdx, 0
add acc5, rax
adc rdx, 0
mov rcx, rdx
mov rax, qword [bPtr+sizeof(qword)*3]
mul qword [aPtr+sizeof(qword)*3]
add acc0, rcx
adc rdx, 0
add acc0, rax
adc acc1, rdx
adc acc2, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 3 (final)
p256r1_mul_redstep acc2,acc1,acc0,acc5,acc4,acc3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t0, qword [rel Lpoly+sizeof(qword)*0]
mov t1, qword [rel Lpoly+sizeof(qword)*1]
mov t2, qword [rel Lpoly+sizeof(qword)*2]
mov t3, qword [rel Lpoly+sizeof(qword)*3]
mov t4, acc4 ;; copy reducted result
mov acc3, acc5
mov acc6, acc0
mov acc7, acc1
sub t4, t0 ;; test %if it exceeds prime value
sbb acc3, t1
sbb acc6, t2
sbb acc7, t3
sbb acc2, 0
cmovnc acc4, t4
cmovnc acc5, acc3
cmovnc acc0, acc6
cmovnc acc1, acc7
mov qword [rdi+sizeof(qword)*0], acc4
mov qword [rdi+sizeof(qword)*1], acc5
mov qword [rdi+sizeof(qword)*2], acc0
mov qword [rdi+sizeof(qword)*3], acc1
ret
align IPP_ALIGN_FACTOR
IPPASM p256r1_mul_montl,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rbp,rbx,rsi,rdi,r12,r13,r14,r15
USES_XMM
COMP_ABI 3
%xdefine bPtr rbx
mov bPtr, rdx
call p256r1_mmull
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_mul_montl
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_to_mont(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_to_mont,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rbp,rbx,rsi,rdi,r12,r13,r14,r15
USES_XMM
COMP_ABI 2
lea rbx, [rel LRR]
call p256r1_mmull
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_to_mont
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_mul_montx(uint64_t res[4], uint64_t a[4], uint64_t b[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
%if _IPP32E >= _IPP32E_L9
align IPP_ALIGN_FACTOR
p256r1_mmulx:
%xdefine acc0 r8
%xdefine acc1 r9
%xdefine acc2 r10
%xdefine acc3 r11
%xdefine acc4 r12
%xdefine acc5 r13
%xdefine acc6 r14
%xdefine acc7 r15
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 rbp
%xdefine t4 rbx
; rdi assumed as result
%xdefine aPtr rsi
%xdefine bPtr rbx
xor acc5, acc5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[0]
xor rdx, rdx
mov rdx, qword [bPtr+sizeof(qword)*0]
mulx acc1,acc0, qword [aPtr+sizeof(qword)*0]
mulx acc2,t2, qword [aPtr+sizeof(qword)*1]
add acc1,t2
mulx acc3,t2, qword [aPtr+sizeof(qword)*2]
adc acc2,t2
mulx acc4,t2, qword [aPtr+sizeof(qword)*3]
adc acc3,t2
adc acc4,0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 0
p256r1_mul_redstep acc5,acc4,acc3,acc2,acc1,acc0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[1]
mov rdx, qword [bPtr+sizeof(qword)*1]
mulx t3, t2, qword [aPtr+sizeof(qword)*0]
adcx acc1, t2
adox acc2, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*1]
adcx acc2, t2
adox acc3, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*2]
adcx acc3, t2
adox acc4, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*3]
adcx acc4, t2
adox acc5, t3
adcx acc5, acc0
adox acc0, acc0
adc acc0, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 1
p256r1_mul_redstep acc0,acc5,acc4,acc3,acc2,acc1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[2]
mov rdx, qword [bPtr+sizeof(qword)*2]
mulx t3, t2, qword [aPtr+sizeof(qword)*0]
adcx acc2, t2
adox acc3, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*1]
adcx acc3, t2
adox acc4, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*2]
adcx acc4, t2
adox acc5, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*3]
adcx acc5, t2
adox acc0, t3
adcx acc0, acc1
adox acc1, acc1
adc acc1, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 2
p256r1_mul_redstep acc1,acc0,acc5,acc4,acc3,acc2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; * b[3]
mov rdx, qword [bPtr+sizeof(qword)*3]
mulx t3, t2, qword [aPtr+sizeof(qword)*0]
adcx acc3, t2
adox acc4, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*1]
adcx acc4, t2
adox acc5, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*2]
adcx acc5, t2
adox acc0, t3
mulx t3, t2, qword [aPtr+sizeof(qword)*3]
adcx acc0, t2
adox acc1, t3
adcx acc1, acc2
adox acc2, acc2
adc acc2, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; reduction step 3 (final)
p256r1_mul_redstep acc2,acc1,acc0,acc5,acc4,acc3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t0, qword [rel Lpoly+sizeof(qword)*0]
mov t1, qword [rel Lpoly+sizeof(qword)*1]
mov t2, qword [rel Lpoly+sizeof(qword)*2]
mov t3, qword [rel Lpoly+sizeof(qword)*3]
mov t4, acc4 ;; copy reducted result
mov acc3, acc5
mov acc6, acc0
mov acc7, acc1
sub t4, t0 ;; test %if it exceeds prime value
sbb acc3, t1
sbb acc6, t2
sbb acc7, t3
sbb acc2, 0
cmovnc acc4, t4
cmovnc acc5, acc3
cmovnc acc0, acc6
cmovnc acc1, acc7
mov qword [rdi+sizeof(qword)*0], acc4
mov qword [rdi+sizeof(qword)*1], acc5
mov qword [rdi+sizeof(qword)*2], acc0
mov qword [rdi+sizeof(qword)*3], acc1
ret
%endif
%if _IPP32E >= _IPP32E_L9
align IPP_ALIGN_FACTOR
IPPASM p256r1_mul_montx,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rbp,rbx,rsi,rdi,r12,r13,r14,r15
USES_XMM
COMP_ABI 3
%xdefine bPtr rbx
mov bPtr, rdx
call p256r1_mmulx
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_mul_montx
%endif ;; _IPP32E_L9
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_sqr_montl(uint64_t res[4], uint64_t a[4]);
; void p256r1_sqr_montx(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; on entry e = expasion (previous step)
; on exit p0= expasion (next step)
;
%macro p256r1_prod_redstep 6.nolist
%xdefine %%e %1
%xdefine %%p4 %2
%xdefine %%p3 %3
%xdefine %%p2 %4
%xdefine %%p1 %5
%xdefine %%p0 %6
mov t0, %%p0
shl t0, 32
mov t1, %%p0
shr t1, 32 ;; (t1:t0) = p0*2^32
mov t2, %%p0
mov t3, %%p0
xor %%p0, %%p0
sub t2, t0
sbb t3, t1 ;; (t3:t2) = (p0*2^64+p0) - p0*2^32
add %%p1, t0 ;; (p2:p1) += (t1:t0)
adc %%p2, t1
adc %%p3, t2 ;; (p4:p3) += (t3:t2)
adc %%p4, t3
adc %%p0, 0 ;; extension = {0/1}
%ifnempty %%e
add %%p4, %%e
adc %%p0, 0
%endif
%endmacro
align IPP_ALIGN_FACTOR
IPPASM p256r1_sqr_montl,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rbp,rbx,rsi,rdi,r12,r13,r14,r15
USES_XMM
COMP_ABI 2
%xdefine acc0 r8
%xdefine acc1 r9
%xdefine acc2 r10
%xdefine acc3 r11
%xdefine acc4 r12
%xdefine acc5 r13
%xdefine acc6 r14
%xdefine acc7 r15
%xdefine t0 rcx
%xdefine t1 rbp
%xdefine t2 rbx
%xdefine t3 rdx
%xdefine t4 rax
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t2, qword [aPtr+sizeof(qword)*0]
mov rax,qword [aPtr+sizeof(qword)*1]
mul t2
mov acc1, rax
mov acc2, rdx
mov rax,qword [aPtr+sizeof(qword)*2]
mul t2
add acc2, rax
adc rdx, 0
mov acc3, rdx
mov rax,qword [aPtr+sizeof(qword)*3]
mul t2
add acc3, rax
adc rdx, 0
mov acc4, rdx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t2, qword [aPtr+sizeof(qword)*1]
mov rax,qword [aPtr+sizeof(qword)*2]
mul t2
add acc3, rax
adc rdx, 0
mov t1, rdx
mov rax,qword [aPtr+sizeof(qword)*3]
mul t2
add acc4, rax
adc rdx, 0
add acc4, t1
adc rdx, 0
mov acc5, rdx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t2, qword [aPtr+sizeof(qword)*2]
mov rax,qword [aPtr+sizeof(qword)*3]
mul t2
add acc5, rax
adc rdx, 0
mov acc6, rdx
xor acc7, acc7
shld acc7, acc6, 1
shld acc6, acc5, 1
shld acc5, acc4, 1
shld acc4, acc3, 1
shld acc3, acc2, 1
shld acc2, acc1, 1
shl acc1, 1
mov rax,qword [aPtr+sizeof(qword)*0]
mul rax
mov acc0, rax
add acc1, rdx
adc acc2, 0
mov rax,qword [aPtr+sizeof(qword)*1]
mul rax
add acc2, rax
adc acc3, rdx
adc acc4, 0
mov rax,qword [aPtr+sizeof(qword)*2]
mul rax
add acc4, rax
adc acc5, rdx
adc acc6, 0
mov rax,qword [aPtr+sizeof(qword)*3]
mul rax
add acc6, rax
adc acc7, rdx
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
p256r1_prod_redstep ,acc4,acc3,acc2,acc1,acc0
p256r1_prod_redstep acc0,acc5,acc4,acc3,acc2,acc1
p256r1_prod_redstep acc1,acc6,acc5,acc4,acc3,acc2
p256r1_prod_redstep acc2,acc7,acc6,acc5,acc4,acc3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t0, qword [rel Lpoly+sizeof(qword)*0]
mov t1, qword [rel Lpoly+sizeof(qword)*1]
mov t2, qword [rel Lpoly+sizeof(qword)*2]
mov t3, qword [rel Lpoly+sizeof(qword)*3]
mov t4, acc4
mov acc0, acc5
mov acc1, acc6
mov acc2, acc7
sub t4, t0
sbb acc0, t1
sbb acc1, t2
sbb acc2, t3
sbb acc3, 0
cmovnc acc4, t4
cmovnc acc5, acc0
cmovnc acc6, acc1
cmovnc acc7, acc2
mov qword [rdi+sizeof(qword)*0], acc4
mov qword [rdi+sizeof(qword)*1], acc5
mov qword [rdi+sizeof(qword)*2], acc6
mov qword [rdi+sizeof(qword)*3], acc7
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_sqr_montl
%if _IPP32E >= _IPP32E_L9
align IPP_ALIGN_FACTOR
IPPASM p256r1_sqr_montx,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rbp,rbx,rsi,rdi,r12,r13,r14,r15
USES_XMM
COMP_ABI 2
%xdefine acc0 r8
%xdefine acc1 r9
%xdefine acc2 r10
%xdefine acc3 r11
%xdefine acc4 r12
%xdefine acc5 r13
%xdefine acc6 r14
%xdefine acc7 r15
%xdefine t0 rcx
%xdefine t1 rbp
%xdefine t2 rbx
%xdefine t3 rdx
%xdefine t4 rax
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov rdx, qword [aPtr+sizeof(qword)*0]
mulx acc2, acc1, qword [aPtr+sizeof(qword)*1]
mulx acc3, t0, qword [aPtr+sizeof(qword)*2]
add acc2, t0
mulx acc4, t0, qword [aPtr+sizeof(qword)*3]
adc acc3, t0
adc acc4, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov rdx, qword [aPtr+sizeof(qword)*1]
xor acc5, acc5
mulx t1, t0, qword [aPtr+sizeof(qword)*2]
adcx acc3, t0
adox acc4, t1
mulx t1, t0, qword [aPtr+sizeof(qword)*3]
adcx acc4, t0
adox acc5, t1
adc acc5, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov rdx, qword [aPtr+sizeof(qword)*2]
mulx acc6, t0, qword [aPtr+sizeof(qword)*3]
add acc5, t0
adc acc6, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
xor acc7, acc7
shld acc7, acc6, 1
shld acc6, acc5, 1
shld acc5, acc4, 1
shld acc4, acc3, 1
shld acc3, acc2, 1
shld acc2, acc1, 1
shl acc1, 1
xor acc0, acc0
mov rdx, qword [aPtr+sizeof(qword)*0]
mulx t1, acc0, rdx
adcx acc1, t1
mov rdx, qword [aPtr+sizeof(qword)*1]
mulx t1, t0, rdx
adcx acc2, t0
adcx acc3, t1
mov rdx, qword [aPtr+sizeof(qword)*2]
mulx t1, t0, rdx
adcx acc4, t0
adcx acc5, t1
mov rdx, qword [aPtr+sizeof(qword)*3]
mulx t1, t0, rdx
adcx acc6, t0
adcx acc7, t1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
p256r1_prod_redstep ,acc4,acc3,acc2,acc1,acc0
p256r1_prod_redstep acc0,acc5,acc4,acc3,acc2,acc1
p256r1_prod_redstep acc1,acc6,acc5,acc4,acc3,acc2
p256r1_prod_redstep acc2,acc7,acc6,acc5,acc4,acc3
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
mov t0, qword [rel Lpoly+sizeof(qword)*0]
mov t1, qword [rel Lpoly+sizeof(qword)*1]
mov t2, qword [rel Lpoly+sizeof(qword)*2]
mov t3, qword [rel Lpoly+sizeof(qword)*3]
mov t4, acc4
mov acc0, acc5
mov acc1, acc6
mov acc2, acc7
sub t4, t0
sbb acc0, t1
sbb acc1, t2
sbb acc2, t3
sbb acc3, 0
cmovnc acc4, t4
cmovnc acc5, acc0
cmovnc acc6, acc1
cmovnc acc7, acc2
mov qword [rdi+sizeof(qword)*0], acc4
mov qword [rdi+sizeof(qword)*1], acc5
mov qword [rdi+sizeof(qword)*2], acc6
mov qword [rdi+sizeof(qword)*3], acc7
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_sqr_montx
%endif ;; _IPP32E_L9
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_mont_back(uint64_t res[4], uint64_t a[4]);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_mont_back,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rsi,rdi,r12,r13
USES_XMM
COMP_ABI 2
%xdefine acc0 r8
%xdefine acc1 r9
%xdefine acc2 r10
%xdefine acc3 r11
%xdefine acc4 r12
%xdefine acc5 r13
%xdefine t0 rax
%xdefine t1 rdx
%xdefine t2 rcx
%xdefine t3 rsi
mov acc2, qword [rsi+sizeof(qword)*0]
mov acc3, qword [rsi+sizeof(qword)*1]
mov acc4, qword [rsi+sizeof(qword)*2]
mov acc5, qword [rsi+sizeof(qword)*3]
xor acc0, acc0
xor acc1, acc1
p256r1_mul_redstep acc1,acc0,acc5,acc4,acc3,acc2
p256r1_mul_redstep acc2,acc1,acc0,acc5,acc4,acc3
p256r1_mul_redstep acc3,acc2,acc1,acc0,acc5,acc4
p256r1_mul_redstep acc4,acc3,acc2,acc1,acc0,acc5
mov t0, acc0
mov t1, acc1
mov t2, acc2
mov t3, acc3
sub t0, qword [rel Lpoly+sizeof(qword)*0]
sbb t1, qword [rel Lpoly+sizeof(qword)*1]
sbb t2, qword [rel Lpoly+sizeof(qword)*2]
sbb t3, qword [rel Lpoly+sizeof(qword)*3]
sbb acc4, 0
cmovnc acc0, t0
cmovnc acc1, t1
cmovnc acc2, t2
cmovnc acc3, t3
mov qword [rdi+sizeof(qword)*0], acc0
mov qword [rdi+sizeof(qword)*1], acc1
mov qword [rdi+sizeof(qword)*2], acc2
mov qword [rdi+sizeof(qword)*3], acc3
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_mont_back
;;%if _IPP32E < _IPP32E_L9
%ifndef _DISABLE_ECP_256R1_HARDCODED_BP_TBL_
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; void p256r1_select_ap_w7(AF_POINT *val, const AF_POINT *in_t, int index);
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
align IPP_ALIGN_FACTOR
IPPASM p256r1_select_ap_w7,PUBLIC
%assign LOCAL_FRAME 0
USES_GPR rsi,rdi,r12,r13
USES_XMM xmm6,xmm7,xmm8,xmm9,xmm10,xmm11,xmm12,xmm13,xmm14,xmm15
COMP_ABI 3
%xdefine val rdi
%xdefine in_t rsi
%xdefine idx edx
%xdefine ONE xmm0
%xdefine INDEX xmm1
%xdefine Ra xmm2
%xdefine Rb xmm3
%xdefine Rc xmm4
%xdefine Rd xmm5
%xdefine M0 xmm8
%xdefine T0a xmm9
%xdefine T0b xmm10
%xdefine T0c xmm11
%xdefine T0d xmm12
%xdefine TMP0 xmm15
movdqa ONE, oword [rel LOne]
pxor Ra, Ra
pxor Rb, Rb
pxor Rc, Rc
pxor Rd, Rd
movdqa M0, ONE
movd INDEX, idx
pshufd INDEX, INDEX, 0
; Skip index = 0, is implicictly infty -> load with offset -1
mov rcx, dword 64
.select_loop_sse_w7:
movdqa TMP0, M0
pcmpeqd TMP0, INDEX
paddd M0, ONE
movdqa T0a, oword [in_t+sizeof(oword)*0]
movdqa T0b, oword [in_t+sizeof(oword)*1]
movdqa T0c, oword [in_t+sizeof(oword)*2]
movdqa T0d, oword [in_t+sizeof(oword)*3]
add in_t, sizeof(oword)*4
pand T0a, TMP0
pand T0b, TMP0
pand T0c, TMP0
pand T0d, TMP0
por Ra, T0a
por Rb, T0b
por Rc, T0c
por Rd, T0d
dec rcx
jnz .select_loop_sse_w7
movdqu oword [val+sizeof(oword)*0], Ra
movdqu oword [val+sizeof(oword)*1], Rb
movdqu oword [val+sizeof(oword)*2], Rc
movdqu oword [val+sizeof(oword)*3], Rd
REST_XMM
REST_GPR
ret
ENDFUNC p256r1_select_ap_w7
%endif
;;%endif ;; _IPP32E < _IPP32E_L9
%endif ;; _IPP32E_M7
|
; A124395: Expansion of (1-2*x)/(1-2*x+2*x^3).
; Submitted by Jamie Morken(s4)
; 1,0,0,-2,-4,-8,-12,-16,-16,-8,16,64,144,256,384,480,448,128,-704,-2304,-4864,-8320,-12032,-14336,-12032,0,28672,81408,162816,268288,373760,421888,307200,-133120,-1110016,-2834432,-5402624,-8585216,-11501568,-12197888,-7225344,8552448,41500672,97452032,177799168,272596992,350289920,344981504,144769024,-411041792,-1512046592,-3313631232,-5805178880,-8586264576,-10545266688,-9480175616,-1787822080,17514889216,53990129664,111555903488,188082028544,268183797760,313255788544,250347520000,-35672555520
mov $2,1
lpb $0
sub $0,1
mul $2,2
add $3,$1
mov $4,$1
mov $1,$3
sub $3,$2
mov $2,$4
lpe
mov $0,$2
|
PUBLIC plotpixel
EXTERN coords
;
; $Id: plotpixl.asm,v 1.11 2015/01/19 01:32:52 pauloscustodio Exp $
;
; ******************************************************************
;
; Plot pixel at (x,y) coordinate.
;
; ZX 81 version.
; 64x48 dots.
;
;
.plotpixel
ld a,h
cp 64
ret nc
ld a,l
;cp maxy
cp 48
ret nc ; y0 out of range
ld (coords),hl
push bc
ld c,l
ld b,h
push bc
srl b
srl c
ld hl,(16396)
inc hl
ld a,c
ld c,b ; !!
ld de,33 ; 32+1. Every text line ends with an HALT
and a
jr z,r_zero
ld b,a
.r_loop
add hl,de
djnz r_loop
.r_zero ; hl = char address
ld e,c
add hl,de
ld a,(hl) ; get current symbol
cp 8
jr c,islow ; recode graph symbol to binary -> 0..F
ld a,143
sub (hl)
.islow ex (sp),hl ; save char address <=> restore x,y
cp 16 ; Just to be sure:
jr c,issym ; if it isn't a symbol...
xor a ; .. force to blank sym
.issym
ld b,a
ld a,1 ; the bit we want to draw
bit 0,h
jr z,iseven
add a,a ; move right the bit
.iseven
bit 0,l
jr z,evenrow
add a,a
add a,a ; move down the bit
.evenrow
or b
cp 8 ; Now back from binary to
jr c,hisym ; graph symbols.
ld b,a
ld a,15
sub b
add a,128
.hisym
pop hl
ld (hl),a
pop bc
ret
|
; A055268: a(n) = (11*n + 4)*C(n+3, 3)/4.
; 1,15,65,185,420,826,1470,2430,3795,5665,8151,11375,15470,20580,26860,34476,43605,54435,67165,82005,99176,118910,141450,167050,195975,228501,264915,305515,350610,400520,455576,516120,582505,655095,734265,820401,913900,1015170,1124630,1242710,1369851,1506505,1653135,1810215,1978230,2157676,2349060,2552900,2769725,3000075,3244501,3503565,3777840,4067910,4374370,4697826,5038895,5398205,5776395,6174115,6592026,7030800,7491120,7973680,8479185,9008351,9561905,10140585,10745140,11376330,12034926,12721710,13437475,14183025,14959175,15766751,16606590,17479540,18386460,19328220,20305701,21319795,22371405,23461445,24590840,25760526,26971450,28224570,29520855,30861285,32246851,33678555,35157410,36684440,38260680,39887176,41564985,43295175,45078825,46917025
add $0,3
mov $1,$0
bin $0,3
bin $1,4
mul $1,11
add $1,$0
mov $0,$1
|
section .data
msg : db "hello "
len: equ $-msg
section .text
global _start
_start:
mov rax,01
mov rdi,01
mov rsi,msg
mov rdx,len
syscall
mov rax,60
mov rdi,00
syscall |
#if defined(Hiro_Canvas)
namespace hiro {
auto pCanvas::construct() -> void {
qtWidget = qtCanvas = new QtCanvas(*this);
qtCanvas->setMouseTracking(true);
pWidget::construct();
_rasterize();
qtCanvas->update();
}
auto pCanvas::destruct() -> void {
_release();
delete qtCanvas;
qtWidget = qtCanvas = nullptr;
}
auto pCanvas::minimumSize() const -> Size {
if(auto& icon = state().icon) return {(int)icon.width(), (int)icon.height()};
return {0, 0};
}
auto pCanvas::setColor(Color color) -> void {
update();
}
auto pCanvas::setDroppable(bool droppable) -> void {
qtCanvas->setAcceptDrops(droppable);
}
auto pCanvas::setGeometry(Geometry geometry) -> void {
update();
pWidget::setGeometry(geometry);
}
auto pCanvas::setGradient(Gradient gradient) -> void {
update();
}
auto pCanvas::setIcon(const image& icon) -> void {
update();
}
auto pCanvas::update() -> void {
_rasterize();
qtCanvas->update();
}
auto pCanvas::_rasterize() -> void {
int width = 0;
int height = 0;
if(auto& icon = state().icon) {
width = icon.width();
height = icon.height();
} else {
width = pSizable::state().geometry.width();
height = pSizable::state().geometry.height();
}
if(width <= 0 || height <= 0) return;
if(width != qtImageWidth || height != qtImageHeight) _release();
qtImageWidth = width;
qtImageHeight = height;
if(!qtImage) qtImage = new QImage(width, height, QImage::Format_ARGB32);
auto buffer = (uint32*)qtImage->bits();
if(auto& icon = state().icon) {
memory::copy(buffer, state().icon.data(), width * height * sizeof(uint32));
} else if(auto& gradient = state().gradient) {
auto& colors = gradient.state.colors;
image fill;
fill.allocate(width, height);
fill.gradient(colors[0].value(), colors[1].value(), colors[2].value(), colors[3].value());
memory::copy(buffer, fill.data(), fill.size());
} else {
uint32 color = state().color.value();
for(auto n : range(width * height)) buffer[n] = color;
}
}
auto pCanvas::_release() -> void {
if(qtImage) {
delete qtImage;
qtImage = nullptr;
}
qtImageWidth = 0;
qtImageHeight = 0;
}
auto QtCanvas::dragEnterEvent(QDragEnterEvent* event) -> void {
if(event->mimeData()->hasUrls()) {
event->acceptProposedAction();
}
}
auto QtCanvas::dropEvent(QDropEvent* event) -> void {
if(auto paths = DropPaths(event)) p.self().doDrop(paths);
}
auto QtCanvas::leaveEvent(QEvent* event) -> void {
p.self().doMouseLeave();
}
auto QtCanvas::mouseMoveEvent(QMouseEvent* event) -> void {
p.self().doMouseMove({event->pos().x(), event->pos().y()});
}
auto QtCanvas::mousePressEvent(QMouseEvent* event) -> void {
switch(event->button()) {
case Qt::LeftButton: p.self().doMousePress(Mouse::Button::Left); break;
case Qt::MidButton: p.self().doMousePress(Mouse::Button::Middle); break;
case Qt::RightButton: p.self().doMousePress(Mouse::Button::Right); break;
}
}
auto QtCanvas::mouseReleaseEvent(QMouseEvent* event) -> void {
switch(event->button()) {
case Qt::LeftButton: p.self().doMouseRelease(Mouse::Button::Left); break;
case Qt::MidButton: p.self().doMouseRelease(Mouse::Button::Middle); break;
case Qt::RightButton: p.self().doMouseRelease(Mouse::Button::Right); break;
}
}
auto QtCanvas::paintEvent(QPaintEvent* event) -> void {
if(!p.qtImage) return;
signed sx = 0, sy = 0, dx = 0, dy = 0;
signed width = p.qtImageWidth;
signed height = p.qtImageHeight;
auto geometry = p.pSizable::state().geometry;
if(width <= geometry.width()) {
sx = 0;
dx = (geometry.width() - width) / 2;
} else {
sx = (width - geometry.width()) / 2;
dx = 0;
width = geometry.width();
}
if(height <= geometry.height()) {
sy = 0;
dy = (geometry.height() - height) / 2;
} else {
sy = (height - geometry.height()) / 2;
dy = 0;
height = geometry.height();
}
QPainter painter(p.qtCanvas);
painter.drawImage(dx, dy, *p.qtImage, sx, sy, width, height);
}
}
#endif
|
bits 32
extern _trap
global _alltraps
_alltraps:
; Build trap frame.
push ds
push es
push fs
push gs
pushad
; Set up data segments.
mov ax, 10h ; SEG_KDATA << 3
mov ds, ax
mov es, ax
; Call trap(tf), where tf=%esp
push esp
call _trap
add esp, 4
; Return falls through to trapret...
global _trapret
_trapret:
popad
pop gs
pop fs
pop es
pop ds
add esp, 8 ; Move past trapno and errcode
iret
|
//main: funcdecl , ,
main:// Words: 0
addi $sp, 4
// Words: 1
move $sp, $rr
// Words: 2
addi $0, -1
// Words: 3
swn $ra, $sp, $rr
// Words: 4
addi $rr, -1
// Words: 5
swn $s0, $sp, $rr
// Words: 6
addi $rr, -1
// Words: 7
swn $s1, $sp, $rr
//: loadi tmp, , 5
// Words: 8
// Words: 9
ldi $t0, 5
//: store a, , tmp
// Words: 10
// Words: 11
ldi $k0, -3
// Words: 12
swn $t0, $sp, $k0
//: load tmp, , a
// Words: 13
// Words: 14
ldi $k0, -3
// Words: 15
lwn $t0, $sp, $k0
//: print tmp, ,
// Words: 16
wp $t0, 0
//: funcend , ,
// Words: 17
addi $0, -1
// Words: 18
lwn $ra, $sp, $rr
// Words: 19
addi $rr, -1
// Words: 20
lwn $s0, $sp, $rr
// Words: 21
addi $rr, -1
// Words: 22
lwn $s1, $sp, $rr
// Words: 23
addi $sp -4
// Words: 24
move $sp, $rr
// Words: 25
//jr $ra
infinite: j infinite |
; how to use cmpsb instruction to compare byte strings.
name "cmpsb"
org 100h
; set forward direction:
cld
; load source into ds:si,
; load target into es:di:
mov ax, cs
mov ds, ax
mov es, ax
lea si, str1
lea di, str2
; set counter to string length:
mov cx, size
; compare until equal:
repe cmpsb
jnz not_equal
; "yes" - equal!
mov al, 'y'
mov ah, 0eh
int 10h
jmp exit_here
not_equal:
; "no" - not equal!
mov al, 'n'
mov ah, 0eh
int 10h
exit_here:
; wait for any key press:
mov ah, 0
int 16h
ret
; strings must have equal lengths:
x1:
str1 db 'test string'
str2 db 'test string'
size = ($ - x1) / 2
|
; this file is part of Release, written by Malban in 2017
;
;Note!
; the bevahour routines are ordered, that each one has a different "high" byte
; this is now used as "type" identification!
;
;
; this is the offset in the below defined "stack" structure after the initial pull has been done
u_offset1 = -X_POS ; behaviour offset is determined by next structure element
; all following objects "inherit" from defined Objectstruct
; all vars after "NEXT_OBJECT" can be different for each of the objects
;
; all definitions with the same name must be at the same structure position
struct LetterObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds SPACE_TO_PREVIOUS,2 ; with what value does the animation get updated
ds PREVIOUS_LETTER,2 ; after how many rounds the movement updates (0 = each, 1 = every second etc)
ds DIF_DELAY, 1 ; #noDoubleWarn
end struct
;
struct DragonObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds DRAGON_COUNTER,1 ; DRAGON TICK_COUNTER - on a different position, therfor named differently
; lower nibble is counter for scale move (inward)
; higher nibble is counter for angle move
ds CHILD_1, 2
ds CHILD_2, 2
ds filler, 0 ; #noDoubleWarn
end struct
;
struct DragonChildObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds WIGGLE,1
ds WIGGLE_DIRECTION, 1
; ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds ANGLE_OFFSET,2 ; two byte for easier adding
ds DRAGON, 2 ; my parent - I have to tell him when I die
ds SCALE_OFFSET, 1
ds filler, 0 ; #noDoubleWarn
end struct
;
struct XObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds ANIM_COUNTER,1 ; with what value does the animation get updated
ds TICK_COUNTER,1 ; after how many rounds the movement updates (0 = each, 1 = every second etc)
ds SCALE_DELTA,1 ; with what value does the movement get updated (1-4)?
ds filler, 2 ; #noDoubleWarn
end struct
;
struct ShotObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds filler, 1 ; #noDoubleWarn
ds TICK_COUNTER,1 ; after how many rounds the movement updates (0 = each, 1 = every second etc)
ds SCALE_DELTA,1 ; with what value does the movement get updated (1-4)?
ds filler, 2 ; #noDoubleWarn
end struct
;
struct HunterObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds filler, 1 ; #noDoubleWarn
ds TICK_COUNTER,1 ; after how many rounds the movement updates (0 = each, 1 = every second etc)
ds SCALE_DELTA,1 ; with what value does the movement get updated (1-4)?
ds filler, 2 ; #noDoubleWarn
end struct
;
struct BomberObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds ANIM_COUNTER,1 ; with what value does the animation get updated
ds ANGLE_TICK_COUNTER,1 ; after how many rounds the movement updates (0 = each, 1 = every second etc)
ds SHOT_COUNTER_RESET,1 ; after how many ticks will the counter be resetd next time
ds SHOT_COUNTER,1 ; after how many ticks do I shoot again?
ds ANGLE_DELTA, 1 ; add to angle each countdown
ds filler, 0 ; #noDoubleWarn
end struct
;
struct StarletObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds ANIM_COUNTER,1 ; jmp to current draw routine
ds SCORE_COUNTER, 1 ; next time I spawn a bonus score
ds SCORE_COUNT, 1 ; what is the current bonus score (2-255)
ds I_AM_STAR_NO, 1 ; what number of star am I (0-2)
ds filler, 0 ; #noDoubleWarn
end struct
;
struct ExplosionObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds EXPLOSION_SCALE,1
ds filler, 2 ; #noDoubleWarn
ds EXPLOSION_DATA, 1
ds EXPLOSION_TYPE, 1
end struct
;
struct ScoreObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds SCORE_COUNTDOWN,1 ; how long will I be displayed (countdon to zero)
ds filler, 4 ; #noDoubleWarn
end struct
;
struct ScoreXObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds SCORE_POINTER_1,2 ; current list vectorlist of first score digit
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds SCORE_COUNTDOWN,1 ; how long will I be displayed (countdon to zero)
DS SCORE_POINTER_2,2 ; current list vectorlist of second score digit
DS SCORE_POINTER_3,2 ; current list vectorlist of third score digit
ds filler, 0 ; #noDoubleWarn
end struct
;
struct TimerObjectStruct
ds Y_POS,1 ; current position
ds SCALE,1 ; scale to position the object
ds CURRENT_LIST,2 ; current list vectorlist of first score digit
ds BEHAVIOUR,2
ds X_POS,1
ds ANGLE,2 ; if angle base, angle in degree *2
ds NEXT_OBJECT,2 ; positive = end of list
ds SECOND_COUNTER,1 ; initialized with 50 again and again and countdown
ds filler, 4 ; #noDoubleWarn
end struct
;
struct StarfieldObjectStruct
ds SCALE_1,1
ds POS_1,1
ds SCALE_2,1
ds POS_2,1
ds BEHAVIOUR,2
ds filler,1 ; #noDoubleWarn
ds CIRCLE_ADR,2 ; circle adr preload to y
ds NEXT_OBJECT,2 ; positive = end of list
ds SCALE_3,1
ds POS_3,1 ; current position
ds SCALE_4,1
ds POS_4,1
ds IS_NEW_STARFIELD,1 ; #noDoubleWarn
end struct
;
code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; GENERAL Object functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; this macro is placed at the end of each possible "remove" exit
; it stores the just removed object at the head of the "empty" list and
; sets up its "next" pointer
UPDATE_EMPTY_LIST macro
dec object_count
ldy list_empty_head ; set u free, as new free head
sty NEXT_OBJECT,x ; load to u the next linked list element
stx list_empty_head
endm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; behaviours control (action) and draw all objects
; each object type has an individual behaviour
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; values are set from "u" list as:
; pulu pc,d,x,y ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
; 04a0
xBehaviour ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
lda SCALE+u_offset1,u ; load current scale to a - for later calcs
cmpa #$80 ; if scale is rather large, we cen decipher music in that time
blo noMusic_xb1
jsr [inMovePointer] ; uncrunch one music "piece"
lda SCALE+u_offset1,u
noMusic_xb1
dec TICK_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_scale_update_xb ; if not, scale will not be updated
ldb X_add_delay ; otherwise reset the delay counter for scale update (this is global now, should I use that from the structure?)
stb TICK_COUNTER+u_offset1, u ; store it
suba SCALE_DELTA+u_offset1, u ; and actually descrease the scale with the "decrease" value
bcs die_xb ; if below zero, than base reaches
cmpa #BASE_SCALE+3 ; if lower base scale, than also dead
bhi base_not_reached
; if we reached the base -
; a) moveto was SMALL - finished anyway
; b) not interested in move - nothing will be drawn anymore!
; MY_MOVE_TO_B_END
die_xb
; cancle move
jmp gameOver ; if base was hit -> game over
base_not_reached:
sta SCALE+u_offset1,u ; store the calculated scale (used next round)
no_scale_update_xb:
; check if animation should change
; if yes, get the new vectorlist for NEXT beheaviour round
; (current round uses the X reg from U stack)
dec ANIM_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_anim_update_xb ; if not, scale will not be updated
lda #X_ANIM_DELAY ; anim reset
sta ANIM_COUNTER+u_offset1, u
ldd CURRENT_LIST+u_offset1,u
addd #(enemyXList_1-enemyXList_0)
cmpd #(enemyXList_3+(enemyXList_1-enemyXList_0))
bne not_last_anim_xb
ldd #enemyXList_0
not_last_anim_xb:
std CURRENT_LIST+u_offset1,u
no_anim_update_xb:
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
lda #6 ; set scale value for next print
sta VIA_t1_cnt_lo ; to timer t1 (lo=
lda #$5f ; and preload intensity
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A
jsr myDraw_VL_mode ; draw the list
_ZERO_VECTOR_BEAM ; and zero as fast as you can!
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in u+u_offset1 pointer to the object that must be removed
; destroys x, y
; sets u to pointer of next object in linked list (might be the "return" structure)
; this version is called at the end of an explosion or at the
; end of a score display, called by "behaviours"
; and thus the "return" is the call of the next object thru U stack
removeObject: ;#isfunction
; since often called from "in move" we disable the move!
; set default draw values
; and zero everything
; in the hopes of less glitches (ZERO should actually do all we need)
ldd #$0800
sta VIA_t1_cnt_lo ; disable ramping
stb VIA_t1_cnt_hi ; disable ramping
MY_MOVE_TO_B_END ; end a move to
_ZERO_VECTOR_BEAM
lda #$83 ; a = $18, b = $83 disable RAMP, muxsel=false, channel 1 (integrators offsets)
clr <VIA_port_a ; Clear D/A output
sta <VIA_port_b ; set mux to channel 1, leave mux disabled
dec <VIA_port_b ; enable mux, reset integrator offset values
inc <VIA_port_b ; enable mux, reset integrator offset values
; draw cleanup done, no start the remove
leax u_offset1,u ; x -> pointer object struture (correction of offset)
cmpx list_objects_head ; is it the first?
bne was_not_first_re ; no -> jump
was_first_re
ldu NEXT_OBJECT,x ; u pointer to next objext
stu list_objects_head ; the next object will be the first
bpl was_first_and_last_re ; if the next is "positive" than the removed object also was the last
was_first_not_last_re
UPDATE_EMPTY_LIST ; if not - cleaning up of current "working" list is done
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
was_first_and_last_re
stu list_objects_tail ; if our object was also the last, than also store the "next" object (the returner) to the tail
UPDATE_EMPTY_LIST ; and clean up the empties
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
was_not_first_re ; find previous, go thru all objects from first and look where "I" am the next...
ldy list_objects_head ; start at list head
try_next_re
cmpx NEXT_OBJECT,y ; am I the next object of the current investigated list element
beq found_next_switch_re ; jup -> jump
ldy NEXT_OBJECT,y ; otherwise load the next as new current
bra try_next_re ; and search further
found_next_switch_re
ldu NEXT_OBJECT,x ; we load "our" next object to u
stu NEXT_OBJECT,y ; and store our next in the place of our previous next and thus eleminate ourselfs
bpl was_not_first_but_last_re ; of our next was positive, than we were last,
was_not_first_and_not_last_re
UPDATE_EMPTY_LIST ; if not last, than finish and restore empties
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
was_not_first_but_last_re:
sty list_objects_tail ; otherwise our we were last, than our previous is the new last
UPDATE_EMPTY_LIST ; and clean up the empties
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
scroller1: DB " ORIGINAL BY GIMO GAMES. ",$80
scroller2: db " VECTREX VERSION PROGRAMMED BY malban. MUSIC COMPOSED BY vtk. ",$80
scroller3: db " ORIGINAL SERIAL ROUTINES BY ALEX HERBERT. ADAPTED SERIAL ROUTINES BY THOMAS SONTOWSKI. RELEASE FITTED SERIAL ROUTINES BY MALBAN. ", $80
scroller4: db " GREETINGS GO TO DIVERSE VECTREX PEOPLE ... alex herbert"
db " JOHN DONDZILA"
db " THOMAS SONTOWSKI"
db " RICHARD HUTCHINSON"
db " KRISTOF TUTS"
db " CHRISTOPHER TUMBER"
db " CHRIS PARSONS "
db " CHRIS VECTREXER"
db " CHRIS BINARYSTAR"
db " MADTRONIX "
db " JUAN MATEOS"
db " VECTREXMAD "
db " JACEK SELANSKI"
db " GEORGE ANASTASIADIS"
db " DER LUCHS "
db " VECTREXROLI "
db " CLAY COWGILL "
db " GAUZE "
db " GEORGE PELONIS"
db " AND MANY OTHERS. THE ROOM FOR GREETINGS IS NOT ENDLESS... KEEP THE VECTREX ALIVE. ",$80
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; behaviours control (action) and draw all objects
; each object type has an individual behaviour
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; values are set from "u" list as:
; pulu pc,d,x,y ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
; 0590
hunterBehaviour ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
lda SCALE+u_offset1,u ; load current scale to a - for later calcs
cmpa #$80 ; if scale is rather large, we cen decipher music in that time
blo noMusic_hub1
jsr [inMovePointer] ; uncrunch one music "piece"
lda SCALE+u_offset1,u
noMusic_hub1
dec TICK_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_scale_update_hb ; if not, scale will not be updated
ldb Hunter_add_delay ; otherwise reset the delay counter for scale update (this is global now, should I use that from the structure?)
stb TICK_COUNTER+u_offset1, u ; store it
suba SCALE_DELTA+u_offset1, u ; and actually descrease the scale with the "decrease" value
bcs die_hb ; if below zero, than base reaches
cmpa #BASE_SCALE+3 ; if lower base scale, than also dead
bhi base_not_reached_hb
; bcc base_not_reached ; if the decreas generated an overflow - than we reached the base (scale below zero)
; if we reached the base -
; a) moveto was SMALL - finished anyway
; b) not interested in move - nothing will be drawn anymore!
; MY_MOVE_TO_B_END
die_hb
; cancle move
jmp gameOver ; if base was hit -> game over
base_not_reached_hb:
sta SCALE+u_offset1,u ; store the calculated scale (used next round)
no_scale_update_hb:
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
ldy ,x++ ; load offset of vector list draw
leay >(unloop_start_addressSub+LENGTH_OF_HEADER),y ;
lda #$5f ; intensity
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A
jsr entry_optimized_draw_mvlc_unloop
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; the return version is called by out timing analysier
; it removes in general stars
; but might also remove the occasional explosion if
; there are to many (from shield)
; no cleanup of vectors needed
removeObject_rts: ;#isfunction
leax ,u ; x -> pointer object struture (correction of offset)
cmpx list_objects_head ; is it the first?
bne was_not_first_re_rts ; no -> jump
was_first_rts:
ldu NEXT_OBJECT,x ; u pointer to next objext
stu list_objects_head ; the next object will be the first
bpl was_first_and_last_rts ; if the next is "positive" than the removed object also was the last
was_first_not_last_rts:
UPDATE_EMPTY_LIST ; if not - cleaning up of current "working" list is done
rts
was_first_and_last_rts:
stu list_objects_tail ; if our object was also the last, than also store the "next" object (the returner) to the tail
UPDATE_EMPTY_LIST ; and clean up the empties
rts
was_not_first_re_rts ; find previous, go thru all objects from first and look where "I" am the next...
ldy list_objects_head ; start at list head
try_next_re_rts
cmpx NEXT_OBJECT,y ; am I the next object of the current investigated list element
beq found_next_switch_re_rts ; jup -> jump
ldy NEXT_OBJECT,y ; otherwise load the next as new current
bra try_next_re_rts ; and search further
found_next_switch_re_rts
ldu NEXT_OBJECT,x ; we load "our" next object to u
stu NEXT_OBJECT,y ; and store our next in the place of our previous next and thus eleminate ourselfs
bpl was_not_first_but_last_rts ; of our next was positive, than we were last,
was_not_first_and_not_last_rts
UPDATE_EMPTY_LIST ; if not last, than finish and restore empties
rts
was_not_first_but_last_rts:
sty list_objects_tail ; otherwise our we were last, than our previous is the new last
UPDATE_EMPTY_LIST ; and clean up the empties
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; new list object to U
; leaves with flags set to result
; (positive = not successfull) ROM
; negative = successfull RAM
; destroys d, u , x
newObject ;#isfunction
ldu list_empty_head
bpl cs_done_no ; we don't have any spare objects -> go out
; set the new empty head
ldd NEXT_OBJECT,u ; the next in out empty list will be the new
std list_empty_head ; head of our empty list
; load last of current object list
ldx list_objects_tail ; load current last "working" object
bpl no_next_no ; if positive, than there was no previous last (and no head)
; of the last object, the new object is the next object
stu NEXT_OBJECT,x ; otherwise we will be the next of that working object
bra was_not_only_no
no_next_no:
stu list_objects_head ; if there was no last, than also no first -> therefor set new object as head
was_not_only_no:
ldd #PC_MAIN ; the next object of our current object is "return", since we are last
std NEXT_OBJECT,u
inc object_count ; and remember that we created a new object
stu list_objects_tail ; our new object is the new tail
cs_done_no
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; behaviours control (action) and draw all objects
; each object type has an individual behaviour
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; values are set from "u" list as:
; pulu pc,d,x,y ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
; 0671
hiddenXBehaviour ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
lda SCALE+u_offset1,u ; load current scale to a - for later calcs
cmpa #$80 ; if scale is rather large, we cen decipher music in that time
blo noMusic_hxb1
jsr [inMovePointer] ; uncrunch one music "piece"
noMusic_hxb1
dec ANIM_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_anim_update_hxb ; if not, scale will not be updated
lda #X_ANIM_DELAY ; anim reset
sta ANIM_COUNTER+u_offset1, u
ldd CURRENT_LIST+u_offset1,u
addd #(enemyXList_1-enemyXList_0)
cmpd #(enemyXList_3+(enemyXList_1-enemyXList_0))
bne not_last_anim_hxb
ldd #enemyXList_0
not_last_anim_hxb:
std CURRENT_LIST+u_offset1,u
no_anim_update_hxb:
lda SCALE+u_offset1,u ; load current scale to a - for later calcs
dec TICK_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_scale_update_hxb ; if not, scale will not be updated
ldb HX_add_delay ; otherwise reset the delay counter for scale update (this is global now, should I use that from the structure?)
stb TICK_COUNTER+u_offset1, u ; store it
suba SCALE_DELTA+u_offset1, u ; and actually descrease the scale with the "decrease" value
bcs die_hxb ; if below zero, than base reaches
cmpa #BASE_SCALE+3 ; if lower base scale, than also dead
bhi base_not_reached_hxb ; if the decreas generated an overflow - than we reached the base (scale below zero)
; if we reached the base -
; a) moveto was SMALL - finished anyway
; b) not interested in move - nothing will be drawn anymore!
; MY_MOVE_TO_B_END
die_hxb
; cancle move
jmp gameOver ; if base was hit -> game over
base_not_reached_hxb:
sta SCALE+u_offset1,u ; store the calculated scale (used next round)
no_scale_update_hxb:
; calculate a slowly brightening intensity
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
bita #$80 ; if far away
beq go_on_int_hxb
clra ; make it invisible
bra no_int_hxb
go_on_int_hxb
nega ; inverse the near scale (now -1 - -127)
adda #$8f ; add 143, result is positive intensity
bpl no_int_hxb
suba #$10 ; adjust negative values slightly
no_int_hxb:
ldb #6 ; preload and set scale
stb VIA_t1_cnt_lo ; to timer t1 (lo= scale)
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A ; set the int
jsr myDraw_VL_mode ; and draw
_ZERO_VECTOR_BEAM ; zero as fast as possible
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
;
; all behaviour routines leave
; with u pointed to the next object structure (+ offset of PUL)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; SPECIFIC Object functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
******************************
***** OBJECT X ***************
******************************
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; X SPAWN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in x pointer to new object structure that should be filled with object
; data
spawnX: ; #isfunction
bitb #ALLOW_X ; first check if allowed to spawn
bne spx_allowed ; if so -> jumo
clr spawn_timer ; if not make sure to check spawn next round again
jmp returnSpawnNotAllowed ; and jump back (to the only location we can be called from)
spx_allowed:
jsr newObject ; "create" (or rather get) new object
lbpl cs_done_no ; if positve - there is no object left, jump out
leax ,u ; pointer to new object now in X also
ldd #SpawnX_Sound ; play a sound for out new spawn
jsr play_sfx
; copy and initialze new enemy
lda X_add_delay ; delay between two scale changes (speed of object)
sta TICK_COUNTER, x
lda X_addi ; strength of scale change once we actually do it
sta SCALE_DELTA, x
ldd #xBehaviour
std BEHAVIOUR,x
lda #X_ANIM_DELAY ; anim reset
sta ANIM_COUNTER, x
ldd #enemyXList_0 ; vectorlist
std CURRENT_LIST,x
lda #$ff
lda spawn_max ; maximum our object can spawn at
sta SCALE,x ; start with max scale (for xEnemy)
;
; leaves with angle also in D
; stores the angle to ANGLE,x
ANGLE_0_762 macro
; the following generates an angle between 0 - 762 degrees (we have enough angles in out list to support this) angles are "doubles" so the real angle is 0° - 381°
ldb my_random2 ; make sure this is random2 not just "random", since the random was already used in "creating" the X object, using it again leaves pretty same values for location
andb #%01111111 ; 0 - 127
clra
MY_LSL_D ; double it 0 - 254
tfr d,u
leau d,u
leau d,u ; in u 0-254 times 3 -> 0 - 762
stu ANGLE,x ; store current angle of object
endm
;
STORE_POS_FROM_ANGLE macro
ldd #circle ; circle with angle as offset gives us the actual coordinates
leau d,u ; u pointer to spwan angle coordinates
ldd ,u
sta Y_POS,x ; save start pos
stb X_POS,x ; save start pos
endm
;
ANGLE_0_762
STORE_POS_FROM_ANGLE
rts
******************************
***** OBJECT HUNTER **********
******************************
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Hunter SPAWN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in x pointer to new object structure that should be filled with object
; data
spawnHunter: ; #isfunction
bitb #ALLOW_HUNTER ; first check if allowed to spawn
bne sph_allowed ; if so -> jumo
clr spawn_timer ; if not make sure to check spawn next round again
jmp returnSpawnNotAllowed ; and jump back (to the only location we can be called from)
sph_allowed:
jsr newObject ; "create" (or rather get) new object
lbpl cs_done_no ; if positve - there is no object left, jump out
leax ,u ; pointer to new object now in X also
ldd #SpawnHunter_Sound ; play a sound for out new spawn
jsr play_sfx
; copy and initialze new enemy
lda Hunter_add_delay ; delay between two scale changes (speed of object)
sta TICK_COUNTER, x
lda Hunter_addi ; strength of scale change once we actually do it
sta SCALE_DELTA, x
ldd #hunterBehaviour
std BEHAVIOUR,x
lda spawn_max
sta SCALE,x ; start with max scale (for xEnemy)
ldb my_random2
andb #%01111111
; in a random number between 0 - 127
clra
cmpd #120 ; mod 120
blt noMax_dh ; if higher
subd #120 ; sub 120
; following calculates the correct angle vectorlist for the hunter
noMax_dh
MY_LSL_D ; double it 0 - 240
tfr d,u ; triple it
leau d,u
leau d,u ; u = 0 - 720 -> spawning angle of our new enemy
; leau 31,u looks better with a little offset?
tfr u,d ; u = 0 - 720 -> spawning angle of our new enemy
MY_LSR_D
MY_LSR_D
MY_LSR_D
MY_LSR_D
MY_LSR_D ; angle / 32
MY_LSL_D ; *2, in d now 0 - 44 (in steps of 2)
ldu #HunterList ; take this "angle" as our offsit of our different hunter rotations
leau d,u
ldu ,u
stu CURRENT_LIST,x ; and store as current vectorlist
MY_LSL_D ; *2
MY_LSL_D ; *2
MY_LSL_D ; *2
MY_LSL_D ; *2 retrieved the full 720 angle (0 - 704 actually)
tfr d,u
stu ANGLE,x ; store current angle of object
ldd #circle
leau d,u ; u pointer to spawn angle coordinates
ldd ,u
sta Y_POS,x ; save start pos
stb X_POS,x ; save start pos
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; behaviours control (action) and draw all objects
; each object type has an individual behaviour
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; values are set from "u" list as:
; pulu pc,d,x,y ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
; 0852
starletBehaviour ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
ldy ANGLE+u_offset1,u ; load current scale to a - for later calcs
ldd starletAngle ; and add the "main" starlet angle
leay d,y ; watch out that it isn't to high (modulo 720)
cmpy #720
blt not_oob_sb
leay -720,y
not_oob_sb
ldd #circle ; and get the current positions
leay d,y ;
ldd ,y
sta Y_POS+u_offset1,u ; save pos
stb X_POS+u_offset1,u ; save pos
no_angle_update_sb:
dec ANIM_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_anim_update_sb ; if not, scale will not be updated
lda #STARLET_ANIM_DELAY ; anim reset
sta ANIM_COUNTER+u_offset1, u
ldd CURRENT_LIST+u_offset1,u
addd #(StarletList_1-StarletList_0)
cmpd #(StarletList_10+(StarletList_1-StarletList_0))
bne not_last_anim_sb
ldd #StarletList_0
not_last_anim_sb:
std CURRENT_LIST+u_offset1,u
no_anim_update_sb:
dec SCORE_COUNTER+u_offset1, u ; decrease score "delay" counter
bpl no_score_update_sb ; jump if not minus
lda #STARLET_SCORE_DELAY ; now initiate a new score spawn, first reinstate the next delay
sta SCORE_COUNTER+u_offset1, u
; following code adds two to the current starlet score
; and correct the csa score pointers
; lda SCORE_COUNT+u_offset1, u ; current score value - which is not used anymore
pshs x,u ; save
; if new score is higher than a "digit" we have to check following digits
; sta SCORE_COUNT+u_offset1, u
; scores are now held in the individual score csa counters
; each star accesses its csa counters by their id
lda I_AM_STAR_NO+u_offset1, u ; get ID
lsla
lsla ; times 4 (one csa score is 4 bytes), only need 3 but 4 is easier math
; wasting 3 bytes of precious RAM here!
ldx #star_0_score ; base score
adda #2
leax a,x ; and offset with ID * 4
; in x now pointer to lowest csa score
lda ,x ; score 0
inca ; add two
inca
cmpa #9 ; if rollover
bls score_ok
suba #10 ; reduce by 10 (might be 1m since we added 2)
sta ,x ; store it
lda ,-x ; load next digit, since we rolled over
inca ; add one
cmpa #9 ; check for next roll over
bls score_ok
; suba #10 ; if yes do the same again, reduce by ten
clra ; or simply to 0 since max 1 was added
sta ,x ; store it
lda ,-x ; load next digit
inca ; +1
cmpa #9 ; if rollower, ignore
bls score_ok
lda #9 ; and for safety - the complete score is set to 999
sta 1,x
sta 2,x
bra score_max
score_ok:
sta ,x ; store last digit
score_max:
; pointer x =
; hundreds (0,1,2)
; tens (0-9)
; singles (0-9)
abort_new_new_score_sb
; build a new scoreX object
jsr buildscoreX ; actually spawn a score with above values
puls x,u ; restore
no_score_update_sb
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
lda #3 ; tiny starlet
sta VIA_t1_cnt_lo ; to timer t1 (lo=
lda #$5f ; intensity
ldy ,x++ ; load offset of vector list draw
leay >(unloop_start_addressSub+LENGTH_OF_HEADER),y ;
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A
jsr entry_optimized_draw_mvlc_unloop
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale) ******************************
******************************
***** OBJECT HIDDEN X ********
******************************
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; HIDDEN X SPAWN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in x pointer to new object structure that should be filled with object
; data
spawnHiddenX: ; #isfunction
bitb #ALLOW_HIDDEN_X ; first check if allowed to spawn
bne sphx_allowed ; if so -> jumo
clr spawn_timer ; if not make sure to check spawn next round again
jmp returnSpawnNotAllowed ; and jump back (to the only location we can be called from)
sphx_allowed:
jsr newObject ; "create" (or rather get) new object
lbpl cs_done_no ; if positve - there is no object left, jump out
leax ,u ; pointer to new object now in X also
ldd #SpawnX_Sound ; play a sound for out new spawn
jsr play_sfx
; copy and initialze new enemy
lda HX_add_delay ; delay between two scale changes (speed of object)
sta TICK_COUNTER, x
lda HX_addi ; strength of scale change once we actually do it
sta SCALE_DELTA, x
ldd #hiddenXBehaviour
std BEHAVIOUR,x
lda #X_ANIM_DELAY ; anim reset
sta ANIM_COUNTER, x
ldd #enemyXList_0 ; vectorlist
std CURRENT_LIST,x
lda spawn_max
sta SCALE,x ; start with max scale (for xEnemy)
ANGLE_0_762
STORE_POS_FROM_ANGLE
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 095f
shotBehaviour ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
lda SCALE+u_offset1,u ; load current scale to a - for later calcs
dec TICK_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_scale_update_sb ; if not, scale will not be updated
ldb shot_add_delay ; otherwise reset the delay counter for scale update (this is global now, should I use that from the structure?)
stb TICK_COUNTER+u_offset1, u ; store it
suba SCALE_DELTA+u_offset1, u ; and actually descrease the scale with the "decrease" value
bcs die_sb ; if below zero, than base reaches
cmpa #BASE_SCALE+3 ; if lower base scale, than also dead
bhi base_not_reached_sb
; if we reached the base -
; a) moveto was SMALL - finished anyway
; b) not interested in move - nothing will be drawn anymore!
; MY_MOVE_TO_B_END
die_sb
jmp gameOver ; if base was hit -> game over
base_not_reached_sb:
sta SCALE+u_offset1,u ; store the calculated scale (used next round)
no_scale_update_sb:
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
lda #6
sta VIA_t1_cnt_lo ; to timer t1 (lo=
lda #$7f ; intensity
ldy ,x++ ; load offset of vector list draw
leay >(unloop_start_addressSub_2+LENGTH_OF_HEADER),y ;
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A
jsr my_drawVLC_inner
ldd #$cc98
sta <VIA_cntl ; 22 cycles from switch on ZERO disabled, and BLANK enabled
STb <VIA_aux_cntl ;
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
******************************
***** OBJECT STARLET *********
******************************
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; STARTLET SPAWN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in x pointer to new object structure that should be filled with object
; data
spawnStarlet: ; #isfunction
bitb #ALLOW_STAR ; first check if allowed to spawn
bne sps_allowed ; if so -> jumo
clr spawn_timer ; if not make sure to check spawn next round again
jmp returnSpawnNotAllowed ; and jump back (to the only location we can be called from)
sps_allowed:
jsr newObject ; "create" (or rather get) new object
lbpl cs_done_no ; if positve - there is no object left, jump out
leax ,u ; pointer to new object now in X also
ldd #SpawnX_Sound ; play a sound for out new spawn - OOPS forgotten to do a special Starlet sound!
jsr play_sfx
; copy and initialze new enemy
ldd #starletBehaviour
std BEHAVIOUR,x
ldd #StarletList_0 ; vectorlist
std CURRENT_LIST,x
lda #STARLET_ANIM_DELAY ; anim reset
sta ANIM_COUNTER,x
lda #STAR_SCALE
sta SCALE,x ; start with max scale (for xEnemy)
lda #STARLET_SCORE_DELAY ; delay between score spawns
sta SCORE_COUNTER,x ; to the counter
lda #STARLET_START_SCORE ; initial score to spawn (6 I think)
sta SCORE_COUNT,x
; the three stars are realized as objects, but are still "individuals"
; store the individual ID in the starlet struct
; and initialize our "place" - starlets have "fixed" scales
lda star_active_flag ; bit 0-2 are set for starlets active 1 2 or 3
bita #$01
beq i_am_0
bita #$02
beq i_am_1
i_am_2:
ora #$04
sta star_active_flag
lda SCALE,x
adda #15 -5
sta SCALE,x
lda #2
sta I_AM_STAR_NO,x
bra my_flag_set_ss
i_am_1:
ora #$02
sta star_active_flag
lda SCALE,x
suba #15
sta SCALE,x
lda #1
sta I_AM_STAR_NO,x
bra my_flag_set_ss
i_am_0:
ora #$01
sta star_active_flag
lda #0
sta I_AM_STAR_NO,x
my_flag_set_ss:
; in a my star count. flags should be set
; redundant test
; slightly random angle +- (0-31)
ldb my_random2
lsrb
lsrb
lsrb
tsta
beq storeStarAngle_ss
notFirstStar_ss:
cmpa #1
bne notSecondStar_ss
; addb #120
;
addb #150
bra storeStarAngle_ss
notSecondStar_ss:
addb #90
storeStarAngle_ss
clra
tfr d,u ; angle from 00 to 720
leau d,u
cmpu #720
blt not_oob1_ss
leau -720,u
not_oob1_ss:
stu ANGLE,x ; store current angle of object
ldd starletAngle ; rotation done by main() in opposite direction than base
leau d,u
cmpu #720
blt not_oob_ss
leau -720,u
not_oob_ss:
ldd #circle
leau d,u ; u pointer to spwan angle coordinates
ldd ,u
sta Y_POS,x ; save start pos
stb X_POS,x
; reset quick score math
lda I_AM_STAR_NO,x
lsla
lsla ; times 4
ldu #star_0_score
leau a,u
ldd #0
std ,u++
lda #STARLET_START_SCORE
sta ,u
inc starletCount
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
dragonchildBoundBehaviour ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
; calculate scale, angle and POS and wiggle anew each round
; since parent might have changed something, which effects us
ldy DRAGON+u_offset1,u ; y is offset of out parent, we assume parent is not dead, otherwise we would be a free child
lda SCALE,y ; get the scale of the parent
adda SCALE_OFFSET+u_offset1, u ; and addd our own offset
sta SCALE+u_offset1,u
ldd ANGLE_OFFSET+u_offset1,u ; from child
addd ANGLE,y ; from dragon
bpl noAngleChange_dcb
addd #720
noAngleChange_dcb
std ANGLE+u_offset1,u ; store angle and calculate the actual new position
ldy #circle
leay d,y ; u pointer to spwan angle coordinates
ldd ,y
sta Y_POS+u_offset1,u ; save start pos
stb X_POS+u_offset1,u ; save start pos
lda #6
sta VIA_t1_cnt_lo ; to timer t1 (lo=
; calculate the wiggle offset,
; leaves the calculation with actual current offset in b
; wiggle is allways +-4 in "one" steps
; the direction + or . is given by WIGGLE_DIRECTION
ldb WIGGLE+u_offset1,u
lda WIGGLE_DIRECTION+u_offset1,u
beq wiggle_minus
incb
stb WIGGLE+u_offset1,u
cmpb #4
bne do_changescale
dec WIGGLE_DIRECTION+u_offset1,u
bra do_changescale
wiggle_minus
decb
stb WIGGLE+u_offset1,u
cmpb #-4
bne do_changescale
inc WIGGLE_DIRECTION+u_offset1,u
do_changescale
; wiggle calc finished
addb SCALE+u_offset1, u ; no apply the wiggle to the actual scale
stb SCALE+u_offset1, u ; and store it (for next round)
lda #$5f ; intensity
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
ldx #Dragonchild_List
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A
jsr myDraw_VL_mode
_ZERO_VECTOR_BEAM
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
dragonchildFreeBehaviour ; #isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
lda SCALE+u_offset1,u ; load current scale to a - for later calcs
suba dragonchild_addi ; and actually decrease the scale with the "decrease" value
bcs die_dcfb ; if below zero, than base reaches
cmpa #BASE_SCALE+3 ; if lower base scale, than also dead
bhi base_not_reached_dcfb
; if we reached the base -
; a) moveto was SMALL - finished anyway
; b) not interested in move - nothing will be drawn anymore!
; MY_MOVE_TO_B_END
die_dcfb
; cancle move
jmp gameOver ; if base was hit -> game over
base_not_reached_dcfb:
sta SCALE+u_offset1,u ; store the calculated scale (used next round)
no_scale_update_dcfb:
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
ldx #Dragonchild_List
lda #6
sta VIA_t1_cnt_lo ; to timer t1 (lo=
lda #$7f ; intensity
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A
jsr myDraw_VL_mode
_ZERO_VECTOR_BEAM
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
******************************
***** OBJECT BOMBER **********
******************************
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Bomber SPAWN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in x pointer to new object structure that should be filled with object
; data
spawnBomber: ; #isfunction
bitb #ALLOW_BOMBER ; first check if allowed to spawn
bne spb_allowed ; if so -> jumo
clr spawn_timer ; if not make sure to check spawn next round again
jmp returnSpawnNotAllowed ; and jump back (to the only location we can be called from)
spb_allowed:
jsr newObject ; "create" (or rather get) new object
lbpl cs_done_no ; if positve - there is no object left, jump out
leax ,u ; pointer to new object now in X also
ldd #SpawnBomber_Sound ; play a sound for out new spawn
jsr play_sfx
; copy and initialze new enemy
lda Bomber_add_delay ; delay between two scale changes (speed of object)
sta ANGLE_TICK_COUNTER, x
lda Bomber_addi ; strength of scale change once we actually do it
sta ANGLE_DELTA, x
ldd #bomberBehaviour
std BEHAVIOUR,x
lda #BOMBER_ANIM_DELAY ; anim reset
sta ANIM_COUNTER,x
ldd #BomberList_0
std CURRENT_LIST,x
lda bomber_delay_start
sta SHOT_COUNTER_RESET,x
sta SHOT_COUNTER,x
ldb my_random2
andb #%00011111 ; max 31
addb #100 ;+4
; spawn between scale 63 - 127
stb SCALE,x
; generate another random
ldb my_random
rolb
rolb
rolb
rolb
eorb my_random2
addb my_random2
eorb RecalCounterLow
andb #%01111111
; in a random number between 0 - 127
clra
MY_LSL_D ; double it
tfr d,u
leau d,u
leau d,u ; in u 0-254 times 3 -> 0 - 762
stu ANGLE,x ; store current angle of object
ldd #circle
leau d,u ; u pointer to spwan angle coordinates
ldd ,u
sta Y_POS,x ; save start pos
stb X_POS,x
rts
******************************
***** OBJECT DRAGON **********
******************************
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Dragon SPAWN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in x pointer to new object structure that should be filled with object
; data
spawnDragon: ; #isfunction
bitb #ALLOW_DRAGON ; first check if allowed to spawn
bne spd_allowed ; if so -> jump
clr spawn_timer ; if not make sure to check spawn next round again
jmp returnSpawnNotAllowed ; and jump back (to the only location we can be called from)
spd_allowed:
jsr newObject ; "create" (or rather get) new object
lbpl cs_done_no ; if positve - there is no object left, jump out
leax ,u ; pointer to new object now in X also
ldd #SpawnDragon_Sound ; play a sound for out new spawn
jsr play_sfx
; copy and initialze new enemy
; lower nibble is counter for scale move (inward)
; higher nibble is counter for angle move
;Dragon_Angle_delay
;Dragon_Scale_delay
lda Dragon_Angle_delay ; after how many ticks does an "angle" move occur (circular movement)
lsla
lsla
lsla
lsla
sta tmp_count2
lda Dragon_Scale_delay ; after how many ticks does an "scale" move oocur (inward bound)
anda #%00001111
ora tmp_count2
sta DRAGON_COUNTER, x ; combined delay storage
ldd #dragonBehaviour_full
std BEHAVIOUR,x
ldd #DragonList_0 ; vectorlist
std CURRENT_LIST,x
lda #$ff
ldb my_random2
andb #%00011111 ; max 35
addb #100
; spawn between scale 35 - max
stb SCALE,x
ANGLE_0_762
STORE_POS_FROM_ANGLE
; spawn children
ldd #0 ; vectorlist
std CHILD_1,x ; efault 0 - perhpa not enough objects
std CHILD_2,x ; 0 means "dead" child
tfr x,y ; y is save in respect to newObject
jsr newObject ; build one object to use for child 1
lbpl cs_done_no ; if none left, jump out
ldd #-20 ; first child is 20 positions away
stu CHILD_1,y ; store child struct
sty DRAGON, u ; and that dragon struct to child, both must know each other!
bsr initDragonChild ;
lda #4 ; wiggle +-4
sta WIGGLE,x
lda #0 ; 0 is dec direction of wiggle
sta WIGGLE_DIRECTION, x
jsr newObject
lbpl cs_done_no
ldd #-40 ; first child is 40 positions away
stu CHILD_2,y
sty DRAGON, u
bsr initDragonChild
lda #-4 ; wiggle +-4
sta WIGGLE,x
lda #1 ; one is inc direction of wiggle
sta WIGGLE_DIRECTION, x
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; initializes the dragon child
; in u pointer to child
; in y pointer to dragon
; in a angle offset
; must leave with y intact
initDragonChild
leax ,u ; use x instead of u
std ANGLE_OFFSET, x ; this was loaded from caller either -20 or -40, its the offset of the child to the parent
addd ANGLE,y ; this is actually a angle - diff - since dif is a negative value
bpl noAngleChange_idc ; calc the "real" angle we add the dragon angle to the (negative) offset
addd #720 ; and correct it if neccessary
noAngleChange_idc
std ANGLE, x ; store the thus calculated angle
ldu #circle ; and get pos from circle
leau d,u ; u pointer to spwan angle coordinates
ldd ,u
sta Y_POS,x ; save start pos
stb X_POS,x ; save start pos
ldd #dragonchildBoundBehaviour
std BEHAVIOUR,x
; ldd #Dragonchild_List ; vectorlist
; std CURRENT_LIST,x
ldb SCALE,y
lda ANGLE_OFFSET+1, x ; scale offset of child is also calculated from the angle offset
nega ; its half the angle offset, but positive (further away)
lsra
sta SCALE_OFFSET, x ; store the offset
addb SCALE_OFFSET, x ; and calculate the "active" current scale of the child
stb SCALE,x
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; behaviours control (action) and draw all objects
; each object type has an individual behaviour
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; values are set from "u" list as:
; pulu pc,d,x,y ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
; 0c70
dragonBehaviour_full
nop
dragonBehaviour_half ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
; decode the two in nibbles stored delay counter
lda DRAGON_COUNTER+u_offset1, u
lsra
lsra
lsra
lsra
deca
sta tmp_add
bpl dragon_no_angle_update
ldb Dragon_Angle_delay
stb tmp_add
ldd ANGLE+u_offset1,u ; load current scale to a - for later calcs
addd Dragon_Angle_addi
cmpd #720
blo dragonAngleOk_db
subd #720
dragonAngleOk_db
std ANGLE+u_offset1,u ; load current scale to a - for later calcs
ldy #circle
leay d,y ; u pointer to spwan angle coordinates
ldd ,y
sta Y_POS+u_offset1,u ; save pos
stb X_POS+u_offset1,u ; save pos
dragon_no_angle_update
lda DRAGON_COUNTER+u_offset1, u
anda #%00001111
deca
sta tmp_count2
bpl no_scale_update_db ; if not, scale will not be updated
ldb Dragon_Scale_delay ; otherwise reset the delay counter for scale update (this is global now, should I use that from the structure?)
stb tmp_count2
lda SCALE+u_offset1,u ; load current scale to a - for later calcs
deca
sta SCALE+u_offset1,u ; store the calculated scale (used next round)
cmpa #BASE_SCALE+3 ; if lower base scale, than also dead
bhi base_not_reached_db
; if we reached the base -
; a) moveto was SMALL - finished anyway
; b) not interested in move - nothing will be drawn anymore!
; MY_MOVE_TO_B_END
die_db:
; cancle move
; following is not really necessary - since the player is dead anyway
; but as long as game over is only a "remove" this makes sense
; tell both children, that the parent dragon is dead...
pshs x
ldx CHILD_1+u_offset1,u
beq no_child1_ex_db
ldd #dragonchildFreeBehaviour
std BEHAVIOUR,x
ldd #0
std DRAGON,x
no_child1_ex_db
ldx CHILD_2+u_offset1,u
beq explodeDragonDone_ex_db
ldd #dragonchildFreeBehaviour
std BEHAVIOUR,x
ldd #0
std DRAGON,x
explodeDragonDone_ex_db
puls x
jmp gameOver ; if base was hit -> game over
base_not_reached_db:
; store the two delay values in nibbles and store them to the combined DRAGON COUNTER
no_scale_update_db:
lda tmp_add ; angle delay
lsla
lsla
lsla
lsla
anda #%11110000
ora tmp_count2
; lower nibble is counter for scale move (inward)
; higher nibble is counter for angle move
;Dragon_Angle_delay
;Dragon_Scale_delay
sta DRAGON_COUNTER+u_offset1,u
lda RecalCounterLow ; only every second tick
bita #$01
beq no_anim_update_db
ldd CURRENT_LIST+u_offset1,u
addd #(DragonList_1-DragonList_0)
cmpd #(DragonList_3+(DragonList_1-DragonList_0))
bne not_last_anim_db
ldd #DragonList_0
not_last_anim_db:
std CURRENT_LIST+u_offset1,u
no_anim_update_db:
lda #6
sta VIA_t1_cnt_lo ; to timer t1 (lo=
lda #$4f ; intensity
ldb BEHAVIOUR+1+u_offset1,u ; type byte tells us, if the dragon has been shot once
cmpb #(dragonBehaviour_half) ; and we thus can set the brightness
beq half_dead_dragon
lda #$7f ; intensity
half_dead_dragon:
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
ldy ,x++ ; load offset of vector list draw
leay >(unloop_start_addressSub+LENGTH_OF_HEADER),y ;
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A
jsr entry_optimized_draw_mvlc_unloop
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
******************************
***** OBJECT BONUS ***********
******************************
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Bonus SPAWN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in x pointer to new object structure that should be filled with object
; data
spawnBonus: ; #isfunction
bitb #ALLOW_BONUS ; first check if allowed to spawn
bne bonux_allowed ; if so -> jumo
clr spawn_timer ; if not make sure to check spawn next round again
jmp returnSpawnNotAllowed ; and jump back (to the only location we can be called from)
bonux_allowed:
jsr newObject ; "create" (or rather get) new object
lbpl cs_done_no ; if positve - there is no object left, jump out
inc bonusCounter+1 ; disable other bonus spawns
leax ,u ; pointer to new object
ldd #SpawnBonus_Sound ; play a sound for out new spawn
jsr play_sfx
; copy and initialze new enemy
lda Bonus_add_delay ; delay between two scale changes (speed of object)
sta TICK_COUNTER, x
lda Bonus_addi ; strength of scale change once we actually do it
sta SCALE_DELTA, x
ldd #bonusBehaviour
std BEHAVIOUR,x
lda #BONUS_ANIM_DELAY ; anim reset
sta ANIM_COUNTER, x
ldd #BonusList_0 ; vectorlist
std CURRENT_LIST,x
lda spawn_max
sta SCALE,x ; start with max scale (for xEnemy)
ANGLE_0_762
STORE_POS_FROM_ANGLE
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; behaviours control (action) and draw all objects
; each object type has an individual behaviour
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; values are set from "u" list as:
; pulu pc,d,x,y ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
; 0da0
bonusBehaviour ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
lda SCALE+u_offset1,u ; load current scale to a - for later calcs
cmpa #$80 ; if scale is rather large, we cen decipher music in that time
blo noMusic_bb1
jsr [inMovePointer] ; uncrunch one music "piece"
lda SCALE+u_offset1,u
noMusic_bb1
dec TICK_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_scale_update_bob ; if not, scale will not be updated
ldb X_add_delay ; otherwise reset the delay counter for scale update (this is global now, should I use that from the structure?)
stb TICK_COUNTER+u_offset1, u ; store it
suba SCALE_DELTA+u_offset1, u ; and actually descrease the scale with the "decrease" value
bcs get_bob ; if below zero, than base reaches
cmpa #BASE_SCALE+3 ; if lower base scale, than also dead
bhi base_not_reached_bob
; if we reached the base - we collect the bonus
get_bob:
MY_MOVE_TO_B_END ; probably not needed here, since we have a realy low scale here
_ZERO_VECTOR_BEAM
jmp initBonus ; if base was hit -> game over
base_not_reached_bob:
sta SCALE+u_offset1,u ; store the calculated scale (used next round)
no_scale_update_bob:
dec ANIM_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_anim_update_bob ; if not, scale will not be updated
lda #X_ANIM_DELAY ; anim reset
sta ANIM_COUNTER+u_offset1, u
ldd CURRENT_LIST+u_offset1,u
addd #(BonusList_1-BonusList_0)
cmpd #(BonusList_16+(BonusList_1-BonusList_0))
bne not_last_anim_bob
ldd #BonusList_0
not_last_anim_bob:
std CURRENT_LIST+u_offset1,u
no_anim_update_bob:
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
lda #6
sta VIA_t1_cnt_lo ; to timer t1 (lo=
lda #$5f ; intensity
MY_MOVE_TO_B_END ; end a move to
_INTENSITY_A
jsr myDraw_VL_mode
_ZERO_VECTOR_BEAM
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
******************************
***** STARFIELD **************
******************************
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Starfield SPAWN
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in x pointer to new object structure that should be filled with object
; data
spawnStarfield: ; #isfunction
jsr newObject ; "create" (or rather get) new object
lbpl cs_done_no ; if positve - there is no object left, jump out
leax ,u ; pointer to new object
; copy and initialze new enemy
inc starFieldCounter ; remember how many starfields are active
clr IS_NEW_STARFIELD, x
ldd #starfieldBehaviour
std BEHAVIOUR,x
lda #$ff ; internal indicator for new starfield, the initialization of positions is done ofer time, when the "counters" have run out
sta POS_1, x ; store neg pos as indicator, that nothing is displayed
sta POS_2, x ; store neg pos as indicator, that nothing is displayed
sta POS_3, x ; store neg pos as indicator, that nothing is displayed
sta POS_4, x ; store neg pos as indicator, that nothing is displayed
lda my_random2 ; scale value in initialization of stars are "delay" factors for spawning a "real" star
anda #%01111111
sta SCALE_1, x ; in init - wait for star spawn at 0
; generate another random
lda my_random
rola
eora my_random2
adda my_random2
eora RecalCounterLow
sta my_random2
anda #%01111111
sta SCALE_2, x ; in init - wait for star spawn at 0
lda my_random
rola
eora my_random2
adda my_random2
eora RecalCounterLow
sta my_random2
anda #%01111111
sta SCALE_3, x ; in init - wait for star spawn at 0
lda my_random
rola
eora my_random2
adda my_random2
eora RecalCounterLow
sta my_random2
anda #%01111111
sta SCALE_4, x ; in init - wait for star spawn at 0
rts
******************************
***** OBJECT Letter **********
******************************
; One letter from the title screen that "circles"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; X Letter
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; in a letter that should be built
spawnFailed:
ldu #0 ; exit with status 0
puls a
rts
spawnLetter:
pshs a ; save out letter
jsr newObject ; "create" (or rather get) new object
bpl spawnFailed ; if positve - there is no object left, jump out
leax ,u ; pointer to new object now in X also
; copy and initialze new enemy
puls b ; in b out current letter
_no_space_found_letter_object
SUBB # 'A' ; subtract smallest letter, so A has 0 offset
LSLB ; multiply by two, since addresses are 16 bit
ldu #_abc ; and add the abc (table of vector list address of the alphabet's letters)
LDu b,u ; in x now address of letter vectorlist
cont_letter_object
stu CURRENT_LIST,x
ldd #letterBehaviour
std BEHAVIOUR,x
lda vector_move_scale
sta SCALE,x ; start with max scale (for xEnemy)
; CSA lda #ADD_DELAY
; CSA sta DIF_DELAY,x
rts
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; behaviours control (action) and draw all objects
; each object type has an individual behaviour
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; values are set from "u" list as:
; pulu pc,d,x,y ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
; 0746
bomberBehaviour: ;#isfunction
; do the scaling
stb VIA_t1_cnt_lo ; also stores to scale :-() VIA_t1_cnt_lo ; to timer t1 (lo)
ldb X_POS+u_offset1,u
; start the move to
; following calcs can be done within that move
MY_MOVE_TO_D_START
dec ANGLE_TICK_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_angle_update_bb ; if not, scale will not be updated
ldb Bomber_add_delay ; otherwise reset the delay counter for scale update (this is global now, should I use that from the structure?)
stb ANGLE_TICK_COUNTER+u_offset1, u ; store it
ldd ANGLE+u_offset1,u ; load current scale to a - for later calcs
subd #2
bcc angle_ok_bb ; if below zero, than base reaches
addd #720
angle_ok_bb:
std ANGLE+u_offset1,u ; load current scale to a - for later calcs
ldy #circle
leay d,y ; u pointer to spwan angle coordinates
ldd ,y
sta Y_POS+u_offset1,u ; save start pos
stb X_POS+u_offset1,u ; save start pos
no_angle_update_bb
; check anim
dec ANIM_COUNTER+u_offset1, u ; see if wee need calc at all, compare tick counter with below zero
bpl no_anim_update_bb ; if not, scale will not be updated
lda #BOMBER_ANIM_DELAY ; anim reset
sta ANIM_COUNTER+u_offset1, u
ldd CURRENT_LIST+u_offset1,u
addd #(BomberList_1-BomberList_0)
cmpd #(BomberList_8+(BomberList_1-BomberList_0))
bne not_last_anim_bb
ldd #BomberList_0
not_last_anim_bb:
std CURRENT_LIST+u_offset1,u
no_anim_update_bb:
dec SHOT_COUNTER+u_offset1, u ; decrease shot counter
bne no_shot_update_bb ; if not 0 jump
lda SHOT_COUNTER_RESET+u_offset1, u ; otherwise restore shot "delay"
suba #BOMB_RELOAD_REDUCTION ; and reduce the delay for next shot
cmpa minimum_bomb_reload ; if smaller than minimum
bhi short_timer_ok
lda minimum_bomb_reload ; load the minimum
short_timer_ok
sta SHOT_COUNTER+u_offset1, u ; and store it as next delay counter
sta SHOT_COUNTER_RESET+u_offset1, u ; which also is the next reset value
pshs x,u
jsr buildShot ; "spawnShot"
puls x,u
no_shot_update_bb
ldu NEXT_OBJECT+u_offset1,u ; preload next user stack
lda #6
sta VIA_t1_cnt_lo ; to timer t1 (lo=
lda #$5f ; intensity
MY_MOVE_TO_B_END ; end a move to
ldy ,x++ ; load offset of vector list draw
leay >(unloop_start_addressSub+LENGTH_OF_HEADER),y ;
do_rest_above
_INTENSITY_A
jsr entry_optimized_draw_mvlc_unloop
ldd #$cc98
sta <VIA_cntl ; 22 cycles from switch on ZERO disabled, and BLANK enabled
STb <VIA_aux_cntl ;
pulu d,x,pc ; (D = y,x, X = vectorlist, Y = DDRA+Scale)
|
.text
.abicalls
.section .mdebug.abi32,"",@progbits
.nan legacy
.file "gcc.alias.get_frame_alias_set.ll"
.text
.globl get_frame_alias_set
.align 2
.type get_frame_alias_set,@function
.set nomicromips
.set nomips16
.ent get_frame_alias_set
get_frame_alias_set: # @get_frame_alias_set
.frame $sp,0,$ra
.mask 0x00000000,0
.fmask 0x00000000,0
.set noreorder
.set nomacro
.set noat
# BB#0:
lui $2, %hi(_gp_disp)
addiu $2, $2, %lo(_gp_disp)
addu $4, $2, $25
lw $3, %got(get_frame_alias_set.set)($4)
lw $2, 0($3)
addiu $1, $zero, -1
bne $2, $1, $BB0_6
nop
# BB#1:
b $BB0_2
nop
$BB0_2:
lw $1, %got(flag_strict_aliasing)($4)
lw $1, 0($1)
beqz $1, $BB0_5
addiu $2, $zero, 0
# BB#3:
b $BB0_4
nop
$BB0_4:
lw $1, %got(new_alias_set.last_alias_set)($4)
lw $2, 0($1)
addiu $2, $2, 1
sw $2, 0($1)
$BB0_5: # %new_alias_set.exit
sw $2, 0($3)
$BB0_6:
jr $ra
nop
.set at
.set macro
.set reorder
.end get_frame_alias_set
$func_end0:
.size get_frame_alias_set, ($func_end0)-get_frame_alias_set
.hidden new_alias_set.last_alias_set
.hidden get_frame_alias_set.set
.ident "clang version 3.8.0 (http://llvm.org/git/clang.git 2d49f0a0ae8366964a93e3b7b26e29679bee7160) (http://llvm.org/git/llvm.git 60bc66b44837125843b58ed3e0fd2e6bb948d839)"
.section ".note.GNU-stack","",@progbits
.text
|
; Multiplication Table program (subr.asm)
; Calls external C++ functions.
INCLUDE Irvine32.inc
askForInteger PROTO C
showInt PROTO C, value:SDWORD, outWidth:DWORD
OUT_WIDTH = 8
ENDING_POWER = 10
.data
intVal DWORD ?
.code
;---------------------------------------------
SetTextOutColor PROC C,
color:DWORD
;
; Sets the text colors and clears the console
; window. Calls Irvine32 library functions.
;---------------------------------------------
mov eax,color
call SetTextColor
call Clrscr
ret
SetTextOutColor ENDP
;---------------------------------------------
DisplayTable PROC C
;
; Inputs an integer n and displays a
; multiplication table ranging from n * 2^1
; to n * 2^10.
;----------------------------------------------
INVOKE askForInteger ; call C++ function
mov intVal,eax ; save the integer
mov ecx,ENDING_POWER ; loop counter
L1: push ecx ; save loop counter
shl intVal,1 ; multiply by 2
INVOKE showInt,intVal,OUT_WIDTH
call Crlf
pop ecx ; restore loop counter
loop L1
ret
DisplayTable ENDP
END
|
; nasmfunc
bits 32
global io_hlt, io_cli, io_sti, io_stihlt
global io_in8, io_in16, io_in32
global io_out8, io_out16, io_out32
global io_load_eflags, io_store_eflags
global load_cr0, store_cr0
global load_gdtr, load_idtr, load_tr
global asm_inthandler20, asm_inthandler21, asm_inthandler2c
extern inthandler20, inthandler21, inthandler2c
global memtest_sub
global farjmp
section .text
io_hlt: ; void io_hlt(void);
hlt
ret
io_cli: ; void io_cli(void);
cli
ret
io_sti: ; void io_sti(void);
sti
ret
io_stihlt: ; void io_stihlt(void);
sti
hlt
ret
io_in8: ; int io_in8(int port);
mov edx,[esp+4] ; port
mov eax,0
in al,dx
ret
io_in16: ; int io_in16(int port);
mov edx,[esp+4]
mov eax,0
in ax,dx
ret
io_in32: ; int io_in32(int port);
mov edx,[esp+4]
in eax,dx
ret
io_out8: ; void io_out8(int port, int data);
mov edx,[esp+4]
mov eax,[esp+8]
out dx,al
ret
io_out16: ; void io_out16(int port, int data);
mov edx,[esp+4]
mov eax,[esp+8]
out dx,ax
ret
io_out32: ; void io_out32(int port, int data);
mov edx,[esp+4]
mov eax,[esp+8]
out dx,eax
ret
io_load_eflags: ; int io_load_eflags(void);
pushfd
pop eax
ret
io_store_eflags: ; void io_store_eflags(int eflags);
mov eax,[esp+4]
push eax
popfd
ret
load_cr0: ; int load_cr0(void);
mov eax,cr0
ret
store_cr0: ; void store_cr0(int cr0);
mov eax,[esp+4]
mov cr0,eax
ret
load_gdtr: ; void load_gdtr(int limit, int addr);
mov ax,[esp+4]
mov [esp+6],ax
lgdt [esp+6]
ret
load_idtr: ; void load_idtr(int limit, int addr);
mov ax,[esp+4]
mov [esp+6],ax
lidt [esp+6]
ret
load_tr: ; void load_tr(int tr);
ltr [esp+4]
ret
asm_inthandler20:
push es
push ds
pushad
mov eax,esp
push eax
mov ax,ss
mov ds,ax
mov es,ax
call inthandler20
pop eax
popad
pop ds
pop es
iretd
asm_inthandler21:
push es
push ds
pushad
mov eax,esp
push eax
mov ax,ss
mov ds,ax
mov es,ax
call inthandler21
pop eax
popad
pop ds
pop es
iretd
asm_inthandler2c:
push es
push ds
pushad
mov eax,esp
push eax
mov ax,ss
mov ds,ax
mov es,ax
call inthandler2c
pop eax
popad
pop ds
pop es
iretd
memtest_sub: ; unsigned int memtest_sub(unsigned int start, unsigned int end);
push edi
push esi
push ebx
mov eax,[esp+12+4] ; unsigned int i = start;
mov esi,0xaa55aa55 ; unsigned int pat0 = 0xaa55aa55;
mov edi,0x55aa55aa ; unsigned int pat1 = 0x55aa55aa;
.loop:
mov ebx,eax
add ebx,0xffc ; unsigned int *p = i + 0x0ffc;
mov edx,[ebx] ; unsigned int old = *p;
mov [ebx],esi ; *p = pat0;
xor dword [ebx],0xffffffff ; *p ^= 0xffffffff;
cmp edi,[ebx] ; if (*p != pat1)
jne .fin ; goto .fin;
xor dword [ebx],0xffffffff ; *p ^= 0xffffffff;
cmp esi,[ebx] ; if (*p != pat0)
jne .fin ; goto .fin;
mov [ebx],edx ; *p = old;
add eax,0x1000 ; i += 0x1000;
cmp eax,[esp+12+8] ; if (i < end)
jb .loop ; goto .loop;
pop ebx
pop esi
pop edi
ret
.fin:
mov [ebx],edx ; *p = old;
pop ebx
pop esi
pop edi
ret
farjmp: ; void farjmp(int eip, int cs);
; [esp+4]: eip
; [esp+8]: cs
jmp far [esp+4]
ret |
; A086755: Sum_{k=1..n} (k(k+1))^2/2.
; 2,20,92,292,742,1624,3192,5784,9834,15884,24596,36764,53326,75376,104176,141168,187986,246468,318668,406868,513590,641608,793960,973960,1185210,1431612,1717380,2047052,2425502,2857952,3349984,3907552
add $0,1
cal $0,24166 ; a(n) = Sum_{1 <= i < j <= n} (j-i)^3.
mul $0,2
mov $1,$0
|
; Z88 Small C+ Run time Library
; l_gint+l_gchar variant to be used sometimes by the peephole optimizer
;
PUBLIC l_gintspchar
.l_gintspchar
add hl,sp
inc hl
inc hl
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
ld a,(hl)
ld l,a
rlca
sbc a,a
ld h,a
ret
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x19e1a, %rsi
lea addresses_A_ht+0x170ba, %rdi
nop
dec %rax
mov $90, %rcx
rep movsl
nop
sub $11138, %rdi
lea addresses_A_ht+0x8bba, %rsi
lea addresses_WC_ht+0x2cba, %rdi
xor %r12, %r12
mov $22, %rcx
rep movsl
add $40267, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r15
push %r8
push %rax
push %rdi
// Store
lea addresses_US+0x133ba, %r11
nop
nop
nop
nop
inc %rax
mov $0x5152535455565758, %rdi
movq %rdi, %xmm5
movups %xmm5, (%r11)
nop
nop
nop
sub %rax, %rax
// Store
mov $0x376ff50000000bba, %r12
nop
nop
nop
xor $40872, %r8
mov $0x5152535455565758, %r13
movq %r13, (%r12)
xor %r12, %r12
// Store
mov $0x411e2a00000009aa, %r13
nop
nop
xor %r15, %r15
movw $0x5152, (%r13)
nop
nop
nop
nop
add %r13, %r13
// Store
lea addresses_WC+0x48ba, %r11
nop
nop
xor $4550, %r15
movl $0x51525354, (%r11)
nop
cmp $35350, %rax
// Store
lea addresses_UC+0x8d6a, %r12
nop
nop
nop
nop
nop
dec %rdi
movl $0x51525354, (%r12)
nop
xor $39383, %r12
// Store
lea addresses_PSE+0x134ba, %rax
nop
nop
sub $24423, %r15
movl $0x51525354, (%rax)
nop
nop
add %r11, %r11
// Faulty Load
mov $0x376ff50000000bba, %r15
xor $55690, %rax
mov (%r15), %r8w
lea oracles, %r11
and $0xff, %r8
shlq $12, %r8
mov (%r11,%r8,1), %r8
pop %rdi
pop %rax
pop %r8
pop %r15
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_NC', 'same': True, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 6}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_NC', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_D_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 7}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 10}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 5}}
{'00': 770, '58': 21059}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 00 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 00 58 58 00 58 58 58 00 58 58 58 58 58 58 58 00 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 00 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 00 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
.data
msg: .asciiz "Give a number: "
.text
main:
li $v0, 4
la $a0, msg
syscall
li $v0, 5
syscall
add $a0, $v0, $zero
# if ($a0 < 2) goto exit;
blt $a0, 2, exit
prti 0
prtn
prti 1
prtn
jal fib
exit:
# Rusult
# add $a0, $v0, $zero
# li $v0, 1
# syscall
li $v0, 10
syscall
fib:
# a0=a
# if (a==0) return 0;
# if (a==1) return 1;
#
# int x($t1), y($t2), z($t3), i($t4);
# for (x=0, y=0, z=1, i=1; i<a; ++i) {
# x=y+z;
# y=z;
# z=x;
# }
#
# return(x);
addi $t0, $zero, 1
beqz $a0, return0
beq $a0, $t0, return1
#arxikopiisi
add $t1, $zero, $zero
add $t2, $zero, $zero
addi $t3, $zero, 1
addi $t4, $zero, 1
loop:
bge $t4, $a0, exit
add $t1, $t2, $t3
add $t2, $zero, $t3
add $t3, $zero, $t1
addi $t4, $t4, 1
jal print_output
j loop
return0:
add $v0, $zero, $zero
jr $ra
return1:
addi $v0, $zero, 1
jr $ra
print_output:
prti $t1
prtn
jr $ra
|
; A004939: Nearest integer to n*phi^4, where phi is the golden ratio, A001622.
; 0,7,14,21,27,34,41,48,55,62,69,75,82,89,96,103,110,117,123,130,137,144,151,158,164,171,178,185,192,199,206,212,219,226,233,240,247,254,260,267,274,281,288,295,302,308
mov $1,12
mul $1,$0
mul $1,2
mov $3,$0
add $0,$1
mul $0,2
add $0,14
div $0,27
mov $2,$3
mul $2,5
add $0,$2
|
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.00.23506.0
include listing.inc
INCLUDELIB MSVCRT
INCLUDELIB OLDNAMES
PUBLIC __local_stdio_printf_options
PUBLIC _vfprintf_l
PUBLIC printf
PUBLIC func
PUBLIC main
EXTRN __imp___acrt_iob_func:PROC
EXTRN __imp___stdio_common_vfprintf:PROC
EXTRN gets:PROC
_DATA SEGMENT
COMM ?_OptionsStorage@?1??__local_stdio_printf_options@@9@9:QWORD ; `__local_stdio_printf_options'::`2'::_OptionsStorage
_DATA ENDS
; COMDAT pdata
pdata SEGMENT
$pdata$_vfprintf_l DD imagerel $LN3
DD imagerel $LN3+68
DD imagerel $unwind$_vfprintf_l
pdata ENDS
; COMDAT pdata
pdata SEGMENT
$pdata$printf DD imagerel $LN3
DD imagerel $LN3+88
DD imagerel $unwind$printf
pdata ENDS
pdata SEGMENT
$pdata$func DD imagerel $LN3
DD imagerel $LN3+29
DD imagerel $unwind$func
$pdata$main DD imagerel $LN3
DD imagerel $LN3+16
DD imagerel $unwind$main
pdata ENDS
xdata SEGMENT
$unwind$func DD 010401H
DD 06204H
$unwind$main DD 010401H
DD 04204H
xdata ENDS
; COMDAT xdata
xdata SEGMENT
$unwind$printf DD 011801H
DD 06218H
xdata ENDS
; COMDAT xdata
xdata SEGMENT
$unwind$_vfprintf_l DD 011801H
DD 06218H
xdata ENDS
; Function compile flags: /Odtpy
; File d:\projects\taintanalysis\antitaint\epilog\src\func.c
_TEXT SEGMENT
main PROC
; 17 : {
$LN3:
sub rsp, 40 ; 00000028H
; 18 : func();
call func
; 19 : return 0;
xor eax, eax
; 20 : }
add rsp, 40 ; 00000028H
ret 0
main ENDP
_TEXT ENDS
; Function compile flags: /Odtpy
; File d:\projects\taintanalysis\antitaint\epilog\src\func.c
_TEXT SEGMENT
buf$ = 32
func PROC
; 10 : {
$LN3:
sub rsp, 56 ; 00000038H
; 11 : char buf[8];
; 12 : gets(buf);
lea rcx, QWORD PTR buf$[rsp]
call gets
; 13 : printf(buf);
lea rcx, QWORD PTR buf$[rsp]
call printf
; 14 : }
add rsp, 56 ; 00000038H
ret 0
func ENDP
_TEXT ENDS
; Function compile flags: /Odtpy
; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h
; COMDAT printf
_TEXT SEGMENT
_Result$ = 32
_ArgList$ = 40
_Format$ = 64
printf PROC ; COMDAT
; 950 : {
$LN3:
mov QWORD PTR [rsp+8], rcx
mov QWORD PTR [rsp+16], rdx
mov QWORD PTR [rsp+24], r8
mov QWORD PTR [rsp+32], r9
sub rsp, 56 ; 00000038H
; 951 : int _Result;
; 952 : va_list _ArgList;
; 953 : __crt_va_start(_ArgList, _Format);
lea rax, QWORD PTR _Format$[rsp+8]
mov QWORD PTR _ArgList$[rsp], rax
; 954 : _Result = _vfprintf_l(stdout, _Format, NULL, _ArgList);
mov ecx, 1
call QWORD PTR __imp___acrt_iob_func
mov r9, QWORD PTR _ArgList$[rsp]
xor r8d, r8d
mov rdx, QWORD PTR _Format$[rsp]
mov rcx, rax
call _vfprintf_l
mov DWORD PTR _Result$[rsp], eax
; 955 : __crt_va_end(_ArgList);
mov QWORD PTR _ArgList$[rsp], 0
; 956 : return _Result;
mov eax, DWORD PTR _Result$[rsp]
; 957 : }
add rsp, 56 ; 00000038H
ret 0
printf ENDP
_TEXT ENDS
; Function compile flags: /Odtpy
; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h
; COMDAT _vfprintf_l
_TEXT SEGMENT
_Stream$ = 64
_Format$ = 72
_Locale$ = 80
_ArgList$ = 88
_vfprintf_l PROC ; COMDAT
; 638 : {
$LN3:
mov QWORD PTR [rsp+32], r9
mov QWORD PTR [rsp+24], r8
mov QWORD PTR [rsp+16], rdx
mov QWORD PTR [rsp+8], rcx
sub rsp, 56 ; 00000038H
; 639 : return __stdio_common_vfprintf(_CRT_INTERNAL_LOCAL_PRINTF_OPTIONS, _Stream, _Format, _Locale, _ArgList);
call __local_stdio_printf_options
mov rcx, QWORD PTR _ArgList$[rsp]
mov QWORD PTR [rsp+32], rcx
mov r9, QWORD PTR _Locale$[rsp]
mov r8, QWORD PTR _Format$[rsp]
mov rdx, QWORD PTR _Stream$[rsp]
mov rcx, QWORD PTR [rax]
call QWORD PTR __imp___stdio_common_vfprintf
; 640 : }
add rsp, 56 ; 00000038H
ret 0
_vfprintf_l ENDP
_TEXT ENDS
; Function compile flags: /Odtpy
; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\corecrt_stdio_config.h
; COMDAT __local_stdio_printf_options
_TEXT SEGMENT
__local_stdio_printf_options PROC ; COMDAT
; 74 : static unsigned __int64 _OptionsStorage;
; 75 : return &_OptionsStorage;
lea rax, OFFSET FLAT:?_OptionsStorage@?1??__local_stdio_printf_options@@9@9 ; `__local_stdio_printf_options'::`2'::_OptionsStorage
; 76 : }
ret 0
__local_stdio_printf_options ENDP
_TEXT ENDS
END
|
// Minimal struct - array of struct
// Commodore 64 PRG executable file
.file [name="struct-ptr-0.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(main)
.const OFFSET_STRUCT_POINT_Y = 1
.segment Code
main: {
.label SCREEN = $400
.label __4 = 2
ldx #0
__b1:
// points[i].x = i
txa
asl
sta.z __4
tay
txa
sta points,y
// i+1
txa
tay
iny
// points[i].y = i+1
tya
ldy.z __4
sta points+OFFSET_STRUCT_POINT_Y,y
// for( byte i: 0..4)
inx
cpx #5
bne __b1
ldy #0
__b2:
// SCREEN[i] = points[i].x
tya
asl
tax
lda points,x
sta SCREEN,y
// (SCREEN+40)[i] = points[i].y
lda points+OFFSET_STRUCT_POINT_Y,x
sta SCREEN+$28,y
// for( byte i: 0..4)
iny
cpy #5
bne __b2
// }
rts
}
.segment Data
points: .fill 2*4, 0
|
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file ai_enginelist.hpp List all the engines. */
#ifndef AI_ENGINELIST_HPP
#define AI_ENGINELIST_HPP
#include "ai_list.hpp"
#include "ai_vehicle.hpp"
/**
* Create a list of engines based on a vehicle type.
* @ingroup AIList
*/
class AIEngineList : public AIList {
public:
/** Get the name of this class to identify it towards squirrel. */
static const char *GetClassName() { return "AIEngineList"; }
/**
* @param vehicle_type The type of vehicle to make a list of engines for.
*/
AIEngineList(AIVehicle::VehicleType vehicle_type);
};
#endif /* AI_ENGINELIST_HPP */
|
#include <glbinding/FunctionCall.h>
#include <glbinding/AbstractFunction.h>
#include <glbinding/AbstractValue.h>
#include <glbinding/CallbackMask.h>
namespace glbinding
{
FunctionCall::FunctionCall(const AbstractFunction * _function)
: function(_function)
, returnValue(nullptr)
{
if (function->isAnyEnabled(CallbackMask::Timestamp))
{
timestamp = std::chrono::system_clock::now();
}
}
FunctionCall::FunctionCall(FunctionCall && other)
: function(std::move(other.function))
, timestamp(std::move(other.timestamp))
, parameters(std::move(other.parameters))
, returnValue(std::move(other.returnValue))
{
}
FunctionCall::~FunctionCall()
{
}
FunctionCall & FunctionCall::operator=(FunctionCall && other)
{
function = std::move(other.function);
timestamp = std::move(other.timestamp);
parameters = std::move(other.parameters);
returnValue = std::move(other.returnValue);
return *this;
}
} // namespace glbinding |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.