text stringlengths 1 1.05M |
|---|
/* Copyright 2017 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/contrib/tensorboard/db/summary_file_writer.h"
#include "tensorflow/core/framework/summary.pb.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/refcount.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/io/record_reader.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/util/event.pb.h"
namespace tensorflow {
namespace {
class FakeClockEnv : public EnvWrapper {
public:
FakeClockEnv() : EnvWrapper(Env::Default()), current_millis_(0) {}
void AdvanceByMillis(const uint64 millis) { current_millis_ += millis; }
uint64 NowMicros() override { return current_millis_ * 1000; }
uint64 NowSeconds() override { return current_millis_ * 1000; }
private:
uint64 current_millis_;
};
class SummaryFileWriterTest : public ::testing::Test {
protected:
Status SummaryTestHelper(
const string& test_name,
const std::function<Status(SummaryWriterInterface*)>& writer_fn,
const std::function<void(const Event&)>& test_fn) {
static std::set<string>* tests = new std::set<string>();
CHECK(tests->insert(test_name).second) << ": " << test_name;
SummaryWriterInterface* writer;
TF_CHECK_OK(CreateSummaryFileWriter(1, 1, testing::TmpDir(), test_name,
&env_, &writer));
core::ScopedUnref deleter(writer);
TF_CHECK_OK(writer_fn(writer));
TF_CHECK_OK(writer->Flush());
std::vector<string> files;
TF_CHECK_OK(env_.GetChildren(testing::TmpDir(), &files));
bool found = false;
for (const string& f : files) {
if (str_util::StrContains(f, test_name)) {
if (found) {
return errors::Unknown("Found more than one file for ", test_name);
}
found = true;
std::unique_ptr<RandomAccessFile> read_file;
TF_CHECK_OK(env_.NewRandomAccessFile(io::JoinPath(testing::TmpDir(), f),
&read_file));
io::RecordReader reader(read_file.get(), io::RecordReaderOptions());
string record;
uint64 offset = 0;
TF_CHECK_OK(
reader.ReadRecord(&offset,
&record)); // The first event is irrelevant
TF_CHECK_OK(reader.ReadRecord(&offset, &record));
Event e;
e.ParseFromString(record);
test_fn(e);
}
}
if (!found) {
return errors::Unknown("Found no file for ", test_name);
}
return Status::OK();
}
FakeClockEnv env_;
};
TEST_F(SummaryFileWriterTest, WriteTensor) {
TF_CHECK_OK(SummaryTestHelper("tensor_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(writer->WriteTensor(
2, one, "name",
SummaryMetadata().SerializeAsString()));
TF_RETURN_IF_ERROR(writer->Flush());
return Status::OK();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name");
}));
TF_CHECK_OK(SummaryTestHelper(
"string_tensor_test",
[](SummaryWriterInterface* writer) {
Tensor hello(DT_STRING, TensorShape({}));
hello.scalar<string>()() = "hello";
TF_RETURN_IF_ERROR(writer->WriteTensor(
2, hello, "name", SummaryMetadata().SerializeAsString()));
TF_RETURN_IF_ERROR(writer->Flush());
return Status::OK();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name");
EXPECT_EQ(e.summary().value(0).tensor().dtype(), DT_STRING);
EXPECT_EQ(e.summary().value(0).tensor().string_val()[0], "hello");
}));
}
TEST_F(SummaryFileWriterTest, WriteScalar) {
TF_CHECK_OK(SummaryTestHelper(
"scalar_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(writer->WriteScalar(2, one, "name"));
TF_RETURN_IF_ERROR(writer->Flush());
return Status::OK();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name");
EXPECT_EQ(e.summary().value(0).simple_value(), 1.0);
}));
}
TEST_F(SummaryFileWriterTest, WriteHistogram) {
TF_CHECK_OK(SummaryTestHelper("hist_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(
writer->WriteHistogram(2, one, "name"));
TF_RETURN_IF_ERROR(writer->Flush());
return Status::OK();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name");
EXPECT_TRUE(e.summary().value(0).has_histo());
}));
}
TEST_F(SummaryFileWriterTest, WriteImage) {
TF_CHECK_OK(SummaryTestHelper(
"image_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_UINT8, TensorShape({1, 1, 1, 1}));
one.scalar<int8>()() = 1;
TF_RETURN_IF_ERROR(writer->WriteImage(2, one, "name", 1, Tensor()));
TF_RETURN_IF_ERROR(writer->Flush());
return Status::OK();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name/image");
CHECK(e.summary().value(0).has_image());
EXPECT_EQ(e.summary().value(0).image().height(), 1);
EXPECT_EQ(e.summary().value(0).image().width(), 1);
EXPECT_EQ(e.summary().value(0).image().colorspace(), 1);
}));
}
TEST_F(SummaryFileWriterTest, WriteAudio) {
TF_CHECK_OK(SummaryTestHelper(
"audio_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({1, 1}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(writer->WriteAudio(2, one, "name", 1, 1));
TF_RETURN_IF_ERROR(writer->Flush());
return Status::OK();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 2);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "name/audio");
CHECK(e.summary().value(0).has_audio());
}));
}
TEST_F(SummaryFileWriterTest, WriteEvent) {
TF_CHECK_OK(
SummaryTestHelper("event_test",
[](SummaryWriterInterface* writer) {
std::unique_ptr<Event> e{new Event};
e->set_step(7);
e->mutable_summary()->add_value()->set_tag("hi");
TF_RETURN_IF_ERROR(writer->WriteEvent(std::move(e)));
TF_RETURN_IF_ERROR(writer->Flush());
return Status::OK();
},
[](const Event& e) {
EXPECT_EQ(e.step(), 7);
CHECK_EQ(e.summary().value_size(), 1);
EXPECT_EQ(e.summary().value(0).tag(), "hi");
}));
}
TEST_F(SummaryFileWriterTest, WallTime) {
env_.AdvanceByMillis(7023);
TF_CHECK_OK(SummaryTestHelper(
"wall_time_test",
[](SummaryWriterInterface* writer) {
Tensor one(DT_FLOAT, TensorShape({}));
one.scalar<float>()() = 1.0;
TF_RETURN_IF_ERROR(writer->WriteScalar(2, one, "name"));
TF_RETURN_IF_ERROR(writer->Flush());
return Status::OK();
},
[](const Event& e) { EXPECT_EQ(e.wall_time(), 7.023); }));
}
} // namespace
} // namespace tensorflow
|
; A301672: Coordination sequence for node of type V2 in "krr" 2-D tiling (or net).
; 1,4,8,13,17,20,25,30,33,37,42,46,50,54,58,63,67,70,75,80,83,87,92,96,100,104,108,113,117,120,125,130,133,137,142,146,150,154,158,163,167,170,175,180,183,187,192,196,200,204,208,213,217,220,225,230,233,237,242,246,250,254,258,263,267,270,275,280,283,287,292,296,300,304,308,313,317,320,325,330,333,337,342,346,350,354,358,363,367,370,375,380,383,387,392,396,400,404,408,413
mov $3,2
mov $5,$0
lpb $3
mov $0,$5
sub $3,1
add $0,$3
trn $0,1
seq $0,301673 ; Partial sums of A301672.
mov $2,$3
mul $2,$0
add $1,$2
mov $4,$0
lpe
min $5,1
mul $5,$4
sub $1,$5
mov $0,$1
|
;
; CPC Maths Routines
;
; August 2003 **_|warp6|_** <kbaccam /at/ free.fr>
;
; $Id: rad.asm,v 1.2 2007/07/21 21:28:22 dom Exp $
;
INCLUDE "#cpcfirm.def"
INCLUDE "#cpcfp.def"
XLIB rad
XDEF radc
XREF fa
.rad xor a
call firmware
.radc defw CPCFP_FLO_DEG_RAD
ret
|
//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include "ngraph/op/less.hpp"
#include "ngraph/runtime/host_tensor.hpp"
#include "ngraph/runtime/reference/less.hpp"
using namespace std;
using namespace ngraph;
// ----------------------------- v0 --------------------------------------------
constexpr NodeTypeInfo op::v0::Less::type_info;
op::v0::Less::Less(const Output<Node>& arg0,
const Output<Node>& arg1,
const AutoBroadcastSpec& auto_broadcast)
: BinaryElementwiseComparison(arg0, arg1, auto_broadcast)
{
constructor_validate_and_infer_types();
}
shared_ptr<Node> op::v0::Less::clone_with_new_inputs(const OutputVector& new_args) const
{
check_new_args_count(this, new_args);
return make_shared<op::v0::Less>(new_args.at(0), new_args.at(1), this->get_autob());
}
namespace
{
template <element::Type_t ET>
bool evaluate(const HostTensorPtr& arg0,
const HostTensorPtr& arg1,
const HostTensorPtr& out,
const op::AutoBroadcastSpec& broadcast_spec)
{
runtime::reference::less(arg0->get_data_ptr<ET>(),
arg1->get_data_ptr<ET>(),
out->get_data_ptr<element::Type_t::boolean>(),
arg0->get_shape(),
arg1->get_shape(),
broadcast_spec);
return true;
}
bool evaluate_less(const HostTensorPtr& arg0,
const HostTensorPtr& arg1,
const HostTensorPtr& out,
const op::AutoBroadcastSpec& broadcast_spec)
{
bool rc = true;
out->set_broadcast(broadcast_spec, arg0, arg1, element::boolean);
switch (arg0->get_element_type())
{
TYPE_CASE(boolean)(arg0, arg1, out, broadcast_spec);
break;
TYPE_CASE(i32)(arg0, arg1, out, broadcast_spec);
break;
TYPE_CASE(i64)(arg0, arg1, out, broadcast_spec);
break;
TYPE_CASE(u32)(arg0, arg1, out, broadcast_spec);
break;
TYPE_CASE(u64)(arg0, arg1, out, broadcast_spec);
break;
TYPE_CASE(f16)(arg0, arg1, out, broadcast_spec);
break;
TYPE_CASE(f32)(arg0, arg1, out, broadcast_spec);
break;
default: rc = false; break;
}
return rc;
}
}
bool op::v0::Less::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs)
{
return evaluate_less(inputs[0], inputs[1], outputs[0], get_autob());
}
// ----------------------------- v1 --------------------------------------------
constexpr NodeTypeInfo op::v1::Less::type_info;
op::v1::Less::Less(const Output<Node>& arg0,
const Output<Node>& arg1,
const AutoBroadcastSpec& auto_broadcast)
: BinaryElementwiseComparison(arg0, arg1, auto_broadcast)
{
constructor_validate_and_infer_types();
}
shared_ptr<Node> op::v1::Less::clone_with_new_inputs(const OutputVector& new_args) const
{
check_new_args_count(this, new_args);
return make_shared<op::v1::Less>(new_args.at(0), new_args.at(1), this->get_autob());
}
bool op::v1::Less::evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs)
{
return evaluate_less(inputs[0], inputs[1], outputs[0], get_autob());
}
|
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
vector<int> minAnd2ndMin(int a[], int n);
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++)
cin >> a[i];
vector<int> ans = minAnd2ndMin(a, n);
if (ans[0] == -1)
cout << -1 << endl;
else
cout << ans[0] << " " << ans[1] << endl;
}
return 0;
}// } Driver Code Ends
vector<int> minAnd2ndMin(int a[], int n) {
int smallest = -1;
int second_smallest = -1;
sort(a, a + n);
smallest = a[0];
for(int i = 1; i < n; i++) {
if(a[i] != smallest) {
second_smallest = a[i];
break;
}
}
vector<int> v;
if(second_smallest == -1) {
v.push_back(-1);
return v;
}
v.push_back(smallest);
v.push_back(second_smallest);
return v;
}
|
; A164894: Base-10 representation of the binary string formed by appending 10, 100, 1000, 10000, ..., etc., to 1.
; 1,6,52,840,26896,1721376,220336192,56406065280,28879905423616,29573023153783296,60565551418948191232,248076498612011791288320,2032242676629600594233921536,33296264013899376135928570454016
add $0,1
mov $2,1
lpb $0
sub $0,1
add $1,1
mul $2,2
mul $1,$2
lpe
div $1,2
mov $0,$1
|
; F-Zero Climax Translation by Normmatt
.align 4
Profile24_CharacterProfile:
.sjis "本職は、惑星間運送",TextNL,"業者。相棒のドラク",TextNL,"につき合い、受取人",TextNL,"不明の荷物だった",TextNL,"F-ZEROマシン",TextNL,"で参戦している。",TextNL,"最初グランプリには",TextNL,"あまり興味を示して",TextNL,"いなかったが次第に",TextNL,"F-ZEROの世界",TextNL,"のとりこになり、今",TextNL,"では一流パイロット",TextNL,"の仲間入りを果たし",TextNL,"ている。",TextNL,""
.align 4
Profile24_VehicleProfile:
.sjis "マシンナンバー28",TextNL,TextNL,"ブーストとグリップ",TextNL,"の性能は比かく的高",TextNL,"いが、ボディの強度",TextNL,"に欠かんがあり、軽",TextNL,"量マシン並みに弱い。",TextNL,"そんな性能を逆手に",TextNL,"取ってロジャーは",TextNL,"次々とドライビング",TextNL,"テクニックをマス",TextNL,"ターしている。",TextNL,""
; make sure to leave an empty line at the end |
;; Author: Moss Gallagher
;; Date: 12-Oct-21
%include "std/sys.asm"
%include "std/str.asm"
global _start
section .data
str: db "Hello", 0
loop_num: equ 25
section .text
_start:
mov r15, rsp
call main
mov eax, esi ; exit code
call sys~exit ; call exit
main:
mov r8, 1
.num_loop:
mov rax, str
call cstr~println
add r8, 1
cmp r8, loop_num
jle .num_loop
.return:
mov rsi, 0
ret
|
db 0 ; 495 DEX NO
db 80, 100, 50, 200, 100, 50
; hp atk def spd sat sdf
db ELECTRIC, ELECTRIC ; type
db 3 ; catch rate
db 219 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_UNKNOWN ; gender ratio
db 100 ; unknown 1
db 120 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/other/regieleki/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_SLOW ; growth rate
dn EGG_NONE, EGG_NONE ; egg groups
; tm/hm learnset
tmhm
; end
|
BITS 32
; XOR [ESP], ESI and XOR ESI, [ESP] can be encoded in two ways, one of which is
; alphanumeric. NASM chooses the wrong one, which is why we have these:
%define xor_esp_esi db 0x31, 0x34, 0x64
%define xor_esi_esp db 0x33, 0x34, 0x64
start:
PUSH 0x66666666
; IMUL ESI, [ESP], 0x69
db 0x6B, 0x34, 0x64, 0x69
esi_value equ -0x2A ; -Something
decode_loop:
INC ESI
IMUL EAX, [BYTE ECX + 2*ESI + jnz_marker + 1 - ((esi_value+1)*2)], BYTE 0x30
XOR AL, [BYTE ECX + 2*ESI + jnz_marker + 2 - ((esi_value+1)*2)]
XOR [BYTE ECX + ESI + jnz_marker + 1 - (esi_value+1)], AL
jnz_marker:
; Jump back 0x10 bytes => F0, this must be encoded
; Assume byte1 is 0x4? and byte2 is 0x4?
; Working back: the offset is eventually stored by XORing over byte1, so the
; decoded value must be F0 ^ 4? => B?. Before that the value is XORed with
; byte2, so the value before this must be B? ^ 4? => F?. F0 can be created
; using 0x?5 * 0x30 => 0xF0, so byte1 must be 0x45.
; Working back again, using the knowledge that byte1 must be 0x45: the offset is
; eventually stored by XORing over byte1, so the decoded value must be F0 ^ 45
; => B5. Before that the value is XORed with byte2 to and the result of that
; must be F0. B5 ^ F0 => 0x45, so byte2 must be 0x45 as well.
db 0x75 ; JNZ
db 0x45 ; high nibble of offset to decode_loop
db 0x45 ; low nibble of offset to decode_loop
|
;
; Sharp OZ family functions
;
; ported from the OZ-7xx SDK by by Alexander R. Pruss
; by Stefano Bodrato - Oct. 2003
;
; Serial libraries
; serial control commands
;
; ------
; $Id: ozgetlcr.asm,v 1.1 2003/10/22 09:56:34 stefano Exp $
;
XLIB ozgetlcr
ozgetlcr:
in a,(43h)
ld l,a
ld h,0
ret
|
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "include/core/SkCanvas.h"
#include "include/core/SkColorFilter.h"
#include "include/core/SkImage.h"
#include "include/core/SkImageFilter.h"
#include "include/core/SkPathEffect.h"
#include "include/core/SkPicture.h"
#include "include/core/SkRRect.h"
#include "include/core/SkRasterHandleAllocator.h"
#include "include/core/SkString.h"
#include "include/core/SkTextBlob.h"
#include "include/core/SkVertices.h"
#include "include/effects/SkRuntimeEffect.h"
#include "include/private/SkNx.h"
#include "include/private/SkTo.h"
#include "include/utils/SkNoDrawCanvas.h"
#include "src/core/SkArenaAlloc.h"
#include "src/core/SkBitmapDevice.h"
#include "src/core/SkCanvasPriv.h"
#include "src/core/SkClipOpPriv.h"
#include "src/core/SkClipStack.h"
#include "src/core/SkDraw.h"
#include "src/core/SkGlyphRun.h"
#include "src/core/SkImageFilterCache.h"
#include "src/core/SkImageFilter_Base.h"
#include "src/core/SkLatticeIter.h"
#include "src/core/SkMSAN.h"
#include "src/core/SkMarkerStack.h"
#include "src/core/SkMatrixPriv.h"
#include "src/core/SkMatrixUtils.h"
#include "src/core/SkPaintPriv.h"
#include "src/core/SkRasterClip.h"
#include "src/core/SkSpecialImage.h"
#include "src/core/SkStrikeCache.h"
#include "src/core/SkTLazy.h"
#include "src/core/SkTextFormatParams.h"
#include "src/core/SkTraceEvent.h"
#include "src/core/SkVerticesPriv.h"
#include "src/image/SkImage_Base.h"
#include "src/image/SkSurface_Base.h"
#include "src/utils/SkPatchUtils.h"
#include <new>
#if SK_SUPPORT_GPU
#include "include/gpu/GrContext.h"
#include "src/gpu/SkGr.h"
#endif
#define RETURN_ON_NULL(ptr) do { if (nullptr == (ptr)) return; } while (0)
#define RETURN_ON_FALSE(pred) do { if (!(pred)) return; } while (0)
// This is a test: static_assert with no message is a c++17 feature,
// and std::max() is constexpr only since the c++14 stdlib.
static_assert(std::max(3,4) == 4);
///////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Return true if the drawing this rect would hit every pixels in the canvas.
*
* Returns false if
* - rect does not contain the canvas' bounds
* - paint is not fill
* - paint would blur or otherwise change the coverage of the rect
*/
bool SkCanvas::wouldOverwriteEntireSurface(const SkRect* rect, const SkPaint* paint,
ShaderOverrideOpacity overrideOpacity) const {
static_assert((int)SkPaintPriv::kNone_ShaderOverrideOpacity ==
(int)kNone_ShaderOverrideOpacity,
"need_matching_enums0");
static_assert((int)SkPaintPriv::kOpaque_ShaderOverrideOpacity ==
(int)kOpaque_ShaderOverrideOpacity,
"need_matching_enums1");
static_assert((int)SkPaintPriv::kNotOpaque_ShaderOverrideOpacity ==
(int)kNotOpaque_ShaderOverrideOpacity,
"need_matching_enums2");
const SkISize size = this->getBaseLayerSize();
const SkRect bounds = SkRect::MakeIWH(size.width(), size.height());
// if we're clipped at all, we can't overwrite the entire surface
{
SkBaseDevice* base = this->getDevice();
SkBaseDevice* top = this->getTopDevice();
if (base != top) {
return false; // we're in a saveLayer, so conservatively don't assume we'll overwrite
}
if (!base->clipIsWideOpen()) {
return false;
}
}
if (rect) {
if (!this->getTotalMatrix().isScaleTranslate()) {
return false; // conservative
}
SkRect devRect;
this->getTotalMatrix().mapRectScaleTranslate(&devRect, *rect);
if (!devRect.contains(bounds)) {
return false;
}
}
if (paint) {
SkPaint::Style paintStyle = paint->getStyle();
if (!(paintStyle == SkPaint::kFill_Style ||
paintStyle == SkPaint::kStrokeAndFill_Style)) {
return false;
}
if (paint->getMaskFilter() || paint->getPathEffect() || paint->getImageFilter()) {
return false; // conservative
}
}
return SkPaintPriv::Overwrites(paint, (SkPaintPriv::ShaderOverrideOpacity)overrideOpacity);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// experimental for faster tiled drawing...
//#define SK_TRACE_SAVERESTORE
#ifdef SK_TRACE_SAVERESTORE
static int gLayerCounter;
static void inc_layer() { ++gLayerCounter; printf("----- inc layer %d\n", gLayerCounter); }
static void dec_layer() { --gLayerCounter; printf("----- dec layer %d\n", gLayerCounter); }
static int gRecCounter;
static void inc_rec() { ++gRecCounter; printf("----- inc rec %d\n", gRecCounter); }
static void dec_rec() { --gRecCounter; printf("----- dec rec %d\n", gRecCounter); }
static int gCanvasCounter;
static void inc_canvas() { ++gCanvasCounter; printf("----- inc canvas %d\n", gCanvasCounter); }
static void dec_canvas() { --gCanvasCounter; printf("----- dec canvas %d\n", gCanvasCounter); }
#else
#define inc_layer()
#define dec_layer()
#define inc_rec()
#define dec_rec()
#define inc_canvas()
#define dec_canvas()
#endif
typedef SkTLazy<SkPaint> SkLazyPaint;
void SkCanvas::predrawNotify(bool willOverwritesEntireSurface) {
if (fSurfaceBase) {
fSurfaceBase->aboutToDraw(willOverwritesEntireSurface
? SkSurface::kDiscard_ContentChangeMode
: SkSurface::kRetain_ContentChangeMode);
}
}
void SkCanvas::predrawNotify(const SkRect* rect, const SkPaint* paint,
ShaderOverrideOpacity overrideOpacity) {
if (fSurfaceBase) {
SkSurface::ContentChangeMode mode = SkSurface::kRetain_ContentChangeMode;
// Since willOverwriteAllPixels() may not be complete free to call, we only do so if
// there is an outstanding snapshot, since w/o that, there will be no copy-on-write
// and therefore we don't care which mode we're in.
//
if (fSurfaceBase->outstandingImageSnapshot()) {
if (this->wouldOverwriteEntireSurface(rect, paint, overrideOpacity)) {
mode = SkSurface::kDiscard_ContentChangeMode;
}
}
fSurfaceBase->aboutToDraw(mode);
}
}
///////////////////////////////////////////////////////////////////////////////
/* This is the record we keep for each SkBaseDevice that the user installs.
The clip/matrix/proc are fields that reflect the top of the save/restore
stack. Whenever the canvas changes, it marks a dirty flag, and then before
these are used (assuming we're not on a layer) we rebuild these cache
values: they reflect the top of the save stack, but translated and clipped
by the device's XY offset and bitmap-bounds.
*/
struct DeviceCM {
DeviceCM* fNext;
sk_sp<SkBaseDevice> fDevice;
SkRasterClip fClip;
std::unique_ptr<const SkPaint> fPaint; // may be null (in the future)
SkMatrix fStashedMatrix; // original CTM; used by imagefilter in saveLayer
sk_sp<SkImage> fClipImage;
SkMatrix fClipMatrix;
DeviceCM(sk_sp<SkBaseDevice> device, const SkPaint* paint, const SkMatrix& stashed,
const SkImage* clipImage, const SkMatrix* clipMatrix)
: fNext(nullptr)
, fDevice(std::move(device))
, fPaint(paint ? std::make_unique<SkPaint>(*paint) : nullptr)
, fStashedMatrix(stashed)
, fClipImage(sk_ref_sp(const_cast<SkImage*>(clipImage)))
, fClipMatrix(clipMatrix ? *clipMatrix : SkMatrix::I())
{}
void reset(const SkIRect& bounds) {
SkASSERT(!fPaint);
SkASSERT(!fNext);
SkASSERT(fDevice);
fClip.setRect(bounds);
}
};
namespace {
// Encapsulate state needed to restore from saveBehind()
struct BackImage {
sk_sp<SkSpecialImage> fImage;
SkIPoint fLoc;
};
}
/* This is the record we keep for each save/restore level in the stack.
Since a level optionally copies the matrix and/or stack, we have pointers
for these fields. If the value is copied for this level, the copy is
stored in the ...Storage field, and the pointer points to that. If the
value is not copied for this level, we ignore ...Storage, and just point
at the corresponding value in the previous level in the stack.
*/
class SkCanvas::MCRec {
public:
DeviceCM* fLayer;
/* If there are any layers in the stack, this points to the top-most
one that is at or below this level in the stack (so we know what
bitmap/device to draw into from this level. This value is NOT
reference counted, since the real owner is either our fLayer field,
or a previous one in a lower level.)
*/
DeviceCM* fTopLayer;
std::unique_ptr<BackImage> fBackImage;
SkConservativeClip fRasterClip;
SkM44 fMatrix;
int fDeferredSaveCount;
MCRec() {
fLayer = nullptr;
fTopLayer = nullptr;
fMatrix.setIdentity();
fDeferredSaveCount = 0;
// don't bother initializing fNext
inc_rec();
}
MCRec(const MCRec& prev) : fRasterClip(prev.fRasterClip), fMatrix(prev.fMatrix) {
fLayer = nullptr;
fTopLayer = prev.fTopLayer;
fDeferredSaveCount = 0;
// don't bother initializing fNext
inc_rec();
}
~MCRec() {
delete fLayer;
dec_rec();
}
void reset(const SkIRect& bounds) {
SkASSERT(fLayer);
SkASSERT(fDeferredSaveCount == 0);
fMatrix.setIdentity();
fRasterClip.setRect(bounds);
fLayer->reset(bounds);
}
};
class SkDrawIter {
public:
SkDrawIter(SkCanvas* canvas)
: fDevice(nullptr), fCurrLayer(canvas->fMCRec->fTopLayer), fPaint(nullptr)
{}
bool next() {
const DeviceCM* rec = fCurrLayer;
if (rec && rec->fDevice) {
fDevice = rec->fDevice.get();
fPaint = rec->fPaint.get();
fCurrLayer = rec->fNext;
// fCurrLayer may be nullptr now
return true;
}
return false;
}
const SkPaint* getPaint() const { return fPaint; }
SkBaseDevice* fDevice;
private:
const DeviceCM* fCurrLayer;
const SkPaint* fPaint; // May be null.
};
#define FOR_EACH_TOP_DEVICE( code ) \
do { \
DeviceCM* layer = fMCRec->fTopLayer; \
while (layer) { \
SkBaseDevice* device = layer->fDevice.get(); \
if (device) { \
code; \
} \
layer = layer->fNext; \
} \
} while (0)
/////////////////////////////////////////////////////////////////////////////
/**
* If the paint has an imagefilter, but it can be simplified to just a colorfilter, return that
* colorfilter, else return nullptr.
*/
static sk_sp<SkColorFilter> image_to_color_filter(const SkPaint& paint) {
SkImageFilter* imgf = paint.getImageFilter();
if (!imgf) {
return nullptr;
}
SkColorFilter* imgCFPtr;
if (!imgf->asAColorFilter(&imgCFPtr)) {
return nullptr;
}
sk_sp<SkColorFilter> imgCF(imgCFPtr);
SkColorFilter* paintCF = paint.getColorFilter();
if (nullptr == paintCF) {
// there is no existing paint colorfilter, so we can just return the imagefilter's
return imgCF;
}
// The paint has both a colorfilter(paintCF) and an imagefilter-which-is-a-colorfilter(imgCF)
// and we need to combine them into a single colorfilter.
return imgCF->makeComposed(sk_ref_sp(paintCF));
}
/**
* There are many bounds in skia. A circle's bounds is just its center extended by its radius.
* However, if we stroke a circle, then the "bounds" of that is larger, since it will now draw
* outside of its raw-bounds by 1/2 the stroke width. SkPaint has lots of optional
* effects/attributes that can modify the effective bounds of a given primitive -- maskfilters,
* patheffects, stroking, etc. This function takes a raw bounds and a paint, and returns the
* conservative "effective" bounds based on the settings in the paint... with one exception. This
* function does *not* look at the imagefilter, which can also modify the effective bounds. It is
* deliberately ignored.
*/
static const SkRect& apply_paint_to_bounds_sans_imagefilter(const SkPaint& paint,
const SkRect& rawBounds,
SkRect* storage) {
SkPaint tmpUnfiltered(paint);
tmpUnfiltered.setImageFilter(nullptr);
if (tmpUnfiltered.canComputeFastBounds()) {
return tmpUnfiltered.computeFastBounds(rawBounds, storage);
} else {
return rawBounds;
}
}
class AutoLayerForImageFilter {
public:
// "rawBounds" is the original bounds of the primitive about to be drawn, unmodified by the
// paint. It's used to determine the size of the offscreen layer for filters.
// If null, the clip will be used instead.
AutoLayerForImageFilter(SkCanvas* canvas, const SkPaint& origPaint,
bool skipLayerForImageFilter = false,
const SkRect* rawBounds = nullptr) {
fCanvas = canvas;
fPaint = &origPaint;
fSaveCount = canvas->getSaveCount();
fTempLayerForImageFilter = false;
if (auto simplifiedCF = image_to_color_filter(origPaint)) {
SkASSERT(!fLazyPaint.isValid());
SkPaint* paint = fLazyPaint.set(origPaint);
paint->setColorFilter(std::move(simplifiedCF));
paint->setImageFilter(nullptr);
fPaint = paint;
}
if (!skipLayerForImageFilter && fPaint->getImageFilter()) {
/**
* We implement ImageFilters for a given draw by creating a layer, then applying the
* imagefilter to the pixels of that layer (its backing surface/image), and then
* we call restore() to xfer that layer to the main canvas.
*
* 1. SaveLayer (with a paint containing the current imagefilter and xfermode)
* 2. Generate the src pixels:
* Remove the imagefilter and the xfermode from the paint that we (AutoDrawLooper)
* return (fPaint). We then draw the primitive (using srcover) into a cleared
* buffer/surface.
* 3. Restore the layer created in #1
* The imagefilter is passed the buffer/surface from the layer (now filled with the
* src pixels of the primitive). It returns a new "filtered" buffer, which we
* draw onto the previous layer using the xfermode from the original paint.
*/
SkPaint restorePaint;
restorePaint.setImageFilter(fPaint->refImageFilter());
restorePaint.setBlendMode(fPaint->getBlendMode());
SkRect storage;
if (rawBounds) {
// Make rawBounds include all paint outsets except for those due to image filters.
rawBounds = &apply_paint_to_bounds_sans_imagefilter(*fPaint, *rawBounds, &storage);
}
(void)canvas->internalSaveLayer(SkCanvas::SaveLayerRec(rawBounds, &restorePaint),
SkCanvas::kFullLayer_SaveLayerStrategy);
fTempLayerForImageFilter = true;
// Remove the restorePaint fields from our "working" paint
SkASSERT(!fLazyPaint.isValid());
SkPaint* paint = fLazyPaint.set(origPaint);
paint->setImageFilter(nullptr);
paint->setBlendMode(SkBlendMode::kSrcOver);
fPaint = paint;
}
}
~AutoLayerForImageFilter() {
if (fTempLayerForImageFilter) {
fCanvas->internalRestore();
}
SkASSERT(fCanvas->getSaveCount() == fSaveCount);
}
const SkPaint& paint() const {
SkASSERT(fPaint);
return *fPaint;
}
private:
SkLazyPaint fLazyPaint; // base paint storage in case we need to modify it
SkCanvas* fCanvas;
const SkPaint* fPaint; // points to either the original paint, or lazy (if we needed it)
int fSaveCount;
bool fTempLayerForImageFilter;
};
////////// macros to place around the internal draw calls //////////////////
#define DRAW_BEGIN_DRAWBITMAP(paint, skipLayerForFilter, bounds) \
this->predrawNotify(); \
AutoLayerForImageFilter draw(this, paint, skipLayerForFilter, bounds); \
{ SkDrawIter iter(this);
#define DRAW_BEGIN_DRAWDEVICE(paint) \
this->predrawNotify(); \
AutoLayerForImageFilter draw(this, paint, true); \
{ SkDrawIter iter(this);
#define DRAW_BEGIN(paint, bounds) \
this->predrawNotify(); \
AutoLayerForImageFilter draw(this, paint, false, bounds); \
{ SkDrawIter iter(this);
#define DRAW_BEGIN_CHECK_COMPLETE_OVERWRITE(paint, bounds, auxOpaque) \
this->predrawNotify(bounds, &paint, auxOpaque); \
AutoLayerForImageFilter draw(this, paint, false, bounds); \
{ SkDrawIter iter(this);
#define DRAW_END }
////////////////////////////////////////////////////////////////////////////
static inline SkRect qr_clip_bounds(const SkIRect& bounds) {
if (bounds.isEmpty()) {
return SkRect::MakeEmpty();
}
// Expand bounds out by 1 in case we are anti-aliasing. We store the
// bounds as floats to enable a faster quick reject implementation.
SkRect dst;
SkNx_cast<float>(Sk4i::Load(&bounds.fLeft) + Sk4i(-1,-1,1,1)).store(&dst.fLeft);
return dst;
}
void SkCanvas::resetForNextPicture(const SkIRect& bounds) {
this->restoreToCount(1);
fMCRec->reset(bounds);
// We're peering through a lot of structs here. Only at this scope do we
// know that the device is a SkNoPixelsDevice.
static_cast<SkNoPixelsDevice*>(fMCRec->fLayer->fDevice.get())->resetForNextPicture(bounds);
fDeviceClipBounds = qr_clip_bounds(bounds);
fIsScaleTranslate = true;
}
void SkCanvas::init(sk_sp<SkBaseDevice> device) {
fMarkerStack = sk_make_sp<SkMarkerStack>();
fSaveCount = 1;
fMCRec = (MCRec*)fMCStack.push_back();
new (fMCRec) MCRec;
fMCRec->fRasterClip.setDeviceClipRestriction(&fClipRestrictionRect);
fIsScaleTranslate = true;
SkASSERT(sizeof(DeviceCM) <= sizeof(fDeviceCMStorage));
fMCRec->fLayer = (DeviceCM*)fDeviceCMStorage;
new (fDeviceCMStorage) DeviceCM(device, nullptr, fMCRec->fMatrix.asM33(), nullptr, nullptr);
fMCRec->fTopLayer = fMCRec->fLayer;
fSurfaceBase = nullptr;
fDeviceClipBounds = {0, 0, 0, 0};
if (device) {
// The root device and the canvas should always have the same pixel geometry
SkASSERT(fProps.pixelGeometry() == device->surfaceProps().pixelGeometry());
fMCRec->fRasterClip.setRect(device->getGlobalBounds());
fDeviceClipBounds = qr_clip_bounds(device->getGlobalBounds());
device->androidFramework_setDeviceClipRestriction(&fClipRestrictionRect);
device->setMarkerStack(fMarkerStack.get());
}
fScratchGlyphRunBuilder = std::make_unique<SkGlyphRunBuilder>();
}
SkCanvas::SkCanvas()
: fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
, fProps(SkSurfaceProps::kLegacyFontHost_InitType)
{
inc_canvas();
this->init(nullptr);
}
SkCanvas::SkCanvas(int width, int height, const SkSurfaceProps* props)
: fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
, fProps(SkSurfacePropsCopyOrDefault(props))
{
inc_canvas();
this->init(sk_make_sp<SkNoPixelsDevice>(
SkIRect::MakeWH(std::max(width, 0), std::max(height, 0)), fProps));
}
SkCanvas::SkCanvas(const SkIRect& bounds)
: fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
, fProps(SkSurfaceProps::kLegacyFontHost_InitType)
{
inc_canvas();
SkIRect r = bounds.isEmpty() ? SkIRect::MakeEmpty() : bounds;
this->init(sk_make_sp<SkNoPixelsDevice>(r, fProps));
}
SkCanvas::SkCanvas(sk_sp<SkBaseDevice> device)
: fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
, fProps(device->surfaceProps())
{
inc_canvas();
this->init(device);
}
SkCanvas::SkCanvas(const SkBitmap& bitmap, const SkSurfaceProps& props)
: fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
, fProps(props)
{
inc_canvas();
sk_sp<SkBaseDevice> device(new SkBitmapDevice(bitmap, fProps, nullptr, nullptr));
this->init(device);
}
SkCanvas::SkCanvas(const SkBitmap& bitmap, std::unique_ptr<SkRasterHandleAllocator> alloc,
SkRasterHandleAllocator::Handle hndl)
: fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
, fProps(SkSurfaceProps::kLegacyFontHost_InitType)
, fAllocator(std::move(alloc))
{
inc_canvas();
sk_sp<SkBaseDevice> device(new SkBitmapDevice(bitmap, fProps, hndl, nullptr));
this->init(device);
}
SkCanvas::SkCanvas(const SkBitmap& bitmap) : SkCanvas(bitmap, nullptr, nullptr) {}
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
SkCanvas::SkCanvas(const SkBitmap& bitmap, ColorBehavior)
: fMCStack(sizeof(MCRec), fMCRecStorage, sizeof(fMCRecStorage))
, fProps(SkSurfaceProps::kLegacyFontHost_InitType)
, fAllocator(nullptr)
{
inc_canvas();
SkBitmap tmp(bitmap);
*const_cast<SkImageInfo*>(&tmp.info()) = tmp.info().makeColorSpace(nullptr);
sk_sp<SkBaseDevice> device(new SkBitmapDevice(tmp, fProps, nullptr, nullptr));
this->init(device);
}
#endif
SkCanvas::~SkCanvas() {
// free up the contents of our deque
this->restoreToCount(1); // restore everything but the last
this->internalRestore(); // restore the last, since we're going away
dec_canvas();
}
///////////////////////////////////////////////////////////////////////////////
void SkCanvas::flush() {
this->onFlush();
}
void SkCanvas::onFlush() {
SkBaseDevice* device = this->getDevice();
if (device) {
device->flush();
}
}
SkSurface* SkCanvas::getSurface() const {
return fSurfaceBase;
}
SkISize SkCanvas::getBaseLayerSize() const {
SkBaseDevice* d = this->getDevice();
return d ? SkISize::Make(d->width(), d->height()) : SkISize::Make(0, 0);
}
SkIRect SkCanvas::getTopLayerBounds() const {
SkBaseDevice* d = this->getTopDevice();
if (!d) {
return SkIRect::MakeEmpty();
}
return d->getGlobalBounds();
}
SkBaseDevice* SkCanvas::getDevice() const {
// return root device
MCRec* rec = (MCRec*) fMCStack.front();
SkASSERT(rec && rec->fLayer);
return rec->fLayer->fDevice.get();
}
SkBaseDevice* SkCanvas::getTopDevice() const {
return fMCRec->fTopLayer->fDevice.get();
}
bool SkCanvas::readPixels(const SkPixmap& pm, int x, int y) {
SkBaseDevice* device = this->getDevice();
return device && pm.addr() && device->readPixels(pm, x, y);
}
bool SkCanvas::readPixels(const SkImageInfo& dstInfo, void* dstP, size_t rowBytes, int x, int y) {
return this->readPixels({ dstInfo, dstP, rowBytes}, x, y);
}
bool SkCanvas::readPixels(const SkBitmap& bm, int x, int y) {
SkPixmap pm;
return bm.peekPixels(&pm) && this->readPixels(pm, x, y);
}
bool SkCanvas::writePixels(const SkBitmap& bitmap, int x, int y) {
SkPixmap pm;
if (bitmap.peekPixels(&pm)) {
return this->writePixels(pm.info(), pm.addr(), pm.rowBytes(), x, y);
}
return false;
}
bool SkCanvas::writePixels(const SkImageInfo& srcInfo, const void* pixels, size_t rowBytes,
int x, int y) {
SkBaseDevice* device = this->getDevice();
if (!device) {
return false;
}
// This check gives us an early out and prevents generation ID churn on the surface.
// This is purely optional: it is a subset of the checks performed by SkWritePixelsRec.
SkIRect srcRect = SkIRect::MakeXYWH(x, y, srcInfo.width(), srcInfo.height());
if (!srcRect.intersect({0, 0, device->width(), device->height()})) {
return false;
}
// Tell our owning surface to bump its generation ID.
const bool completeOverwrite =
srcRect.size() == SkISize::Make(device->width(), device->height());
this->predrawNotify(completeOverwrite);
// This can still fail, most notably in the case of a invalid color type or alpha type
// conversion. We could pull those checks into this function and avoid the unnecessary
// generation ID bump. But then we would be performing those checks twice, since they
// are also necessary at the bitmap/pixmap entry points.
return device->writePixels({srcInfo, pixels, rowBytes}, x, y);
}
//////////////////////////////////////////////////////////////////////////////
void SkCanvas::checkForDeferredSave() {
if (fMCRec->fDeferredSaveCount > 0) {
this->doSave();
}
}
int SkCanvas::getSaveCount() const {
#ifdef SK_DEBUG
int count = 0;
SkDeque::Iter iter(fMCStack, SkDeque::Iter::kFront_IterStart);
for (;;) {
const MCRec* rec = (const MCRec*)iter.next();
if (!rec) {
break;
}
count += 1 + rec->fDeferredSaveCount;
}
SkASSERT(count == fSaveCount);
#endif
return fSaveCount;
}
int SkCanvas::save() {
fSaveCount += 1;
fMCRec->fDeferredSaveCount += 1;
return this->getSaveCount() - 1; // return our prev value
}
void SkCanvas::doSave() {
this->willSave();
SkASSERT(fMCRec->fDeferredSaveCount > 0);
fMCRec->fDeferredSaveCount -= 1;
this->internalSave();
}
void SkCanvas::restore() {
if (fMCRec->fDeferredSaveCount > 0) {
SkASSERT(fSaveCount > 1);
fSaveCount -= 1;
fMCRec->fDeferredSaveCount -= 1;
} else {
// check for underflow
if (fMCStack.count() > 1) {
this->willRestore();
SkASSERT(fSaveCount > 1);
fSaveCount -= 1;
this->internalRestore();
this->didRestore();
}
}
}
void SkCanvas::restoreToCount(int count) {
// sanity check
if (count < 1) {
count = 1;
}
int n = this->getSaveCount() - count;
for (int i = 0; i < n; ++i) {
this->restore();
}
}
void SkCanvas::internalSave() {
MCRec* newTop = (MCRec*)fMCStack.push_back();
new (newTop) MCRec(*fMCRec); // balanced in restore()
fMCRec = newTop;
FOR_EACH_TOP_DEVICE(device->save());
}
bool SkCanvas::BoundsAffectsClip(SaveLayerFlags saveLayerFlags) {
return !(saveLayerFlags & SkCanvasPriv::kDontClipToLayer_SaveLayerFlag);
}
bool SkCanvas::clipRectBounds(const SkRect* bounds, SaveLayerFlags saveLayerFlags,
SkIRect* intersection, const SkImageFilter* imageFilter) {
// clipRectBounds() is called to determine the input layer size needed for a given image filter.
// The coordinate space of the rectangle passed to filterBounds(kReverse) is meant to be in the
// filtering layer space. Here, 'clipBounds' is always in the true device space. When an image
// filter does not require a decomposed CTM matrix, the filter space and device space are the
// same. When it has been decomposed, we want the original image filter node to process the
// bounds in the layer space represented by the decomposed scale matrix. 'imageFilter' is no
// longer the original filter, but has the remainder matrix baked into it, and passing in the
// the true device clip bounds ensures that the matrix image filter provides a layer clip bounds
// to the original filter node (barring inflation from consecutive calls to mapRect). While
// initially counter-intuitive given the apparent inconsistency of coordinate spaces, always
// passing getDeviceClipBounds() to 'imageFilter' is correct.
// FIXME (michaelludwig) - When the remainder matrix is instead applied as a final draw, it will
// be important to more accurately calculate the clip bounds in the layer space for the original
// image filter (similar to how matrix image filter does it, but ideally without the inflation).
SkIRect clipBounds = this->getDeviceClipBounds();
if (clipBounds.isEmpty()) {
return false;
}
const SkMatrix& ctm = fMCRec->fMatrix.asM33(); // this->getTotalMatrix()
if (imageFilter && bounds && !imageFilter->canComputeFastBounds()) {
// If the image filter DAG affects transparent black then we will need to render
// out to the clip bounds
bounds = nullptr;
}
SkIRect inputSaveLayerBounds;
if (bounds) {
SkRect r;
ctm.mapRect(&r, *bounds);
r.roundOut(&inputSaveLayerBounds);
} else { // no user bounds, so just use the clip
inputSaveLayerBounds = clipBounds;
}
if (imageFilter) {
// expand the clip bounds by the image filter DAG to include extra content that might
// be required by the image filters.
clipBounds = imageFilter->filterBounds(clipBounds, ctm,
SkImageFilter::kReverse_MapDirection,
&inputSaveLayerBounds);
}
SkIRect clippedSaveLayerBounds;
if (bounds) {
// For better or for worse, user bounds currently act as a hard clip on the layer's
// extent (i.e., they implement the CSS filter-effects 'filter region' feature).
clippedSaveLayerBounds = inputSaveLayerBounds;
} else {
// If there are no user bounds, we don't want to artificially restrict the resulting
// layer bounds, so allow the expanded clip bounds free reign.
clippedSaveLayerBounds = clipBounds;
}
// early exit if the layer's bounds are clipped out
if (!clippedSaveLayerBounds.intersect(clipBounds)) {
if (BoundsAffectsClip(saveLayerFlags)) {
fMCRec->fTopLayer->fDevice->clipRegion(SkRegion(), SkClipOp::kIntersect); // empty
fMCRec->fRasterClip.setEmpty();
fDeviceClipBounds.setEmpty();
}
return false;
}
SkASSERT(!clippedSaveLayerBounds.isEmpty());
if (BoundsAffectsClip(saveLayerFlags)) {
// Simplify the current clips since they will be applied properly during restore()
fMCRec->fRasterClip.setRect(clippedSaveLayerBounds);
fDeviceClipBounds = qr_clip_bounds(clippedSaveLayerBounds);
}
if (intersection) {
*intersection = clippedSaveLayerBounds;
}
return true;
}
int SkCanvas::saveLayer(const SkRect* bounds, const SkPaint* paint) {
return this->saveLayer(SaveLayerRec(bounds, paint, 0));
}
int SkCanvas::saveLayer(const SaveLayerRec& rec) {
TRACE_EVENT0("skia", TRACE_FUNC);
if (rec.fPaint && rec.fPaint->nothingToDraw()) {
// no need for the layer (or any of the draws until the matching restore()
this->save();
this->clipRect({0,0,0,0});
} else {
SaveLayerStrategy strategy = this->getSaveLayerStrategy(rec);
fSaveCount += 1;
this->internalSaveLayer(rec, strategy);
}
return this->getSaveCount() - 1;
}
int SkCanvas::only_axis_aligned_saveBehind(const SkRect* bounds) {
if (bounds && !this->getLocalClipBounds().intersects(*bounds)) {
// Assuming clips never expand, if the request bounds is outside of the current clip
// there is no need to copy/restore the area, so just devolve back to a regular save.
this->save();
} else {
bool doTheWork = this->onDoSaveBehind(bounds);
fSaveCount += 1;
this->internalSave();
if (doTheWork) {
this->internalSaveBehind(bounds);
}
}
return this->getSaveCount() - 1;
}
void SkCanvas::DrawDeviceWithFilter(SkBaseDevice* src, const SkImageFilter* filter,
SkBaseDevice* dst, const SkIPoint& dstOrigin,
const SkMatrix& ctm) {
// The local bounds of the src device; all the bounds passed to snapSpecial must be intersected
// with this rect.
const SkIRect srcDevRect = SkIRect::MakeWH(src->width(), src->height());
// TODO(michaelludwig) - Update this function to use the relative transforms between src and
// dst; for now, since devices never have complex transforms, we can keep using getOrigin().
if (!filter) {
// All non-filtered devices are currently axis aligned, so they only differ by their origin.
// This means that we only have to copy a dst-sized block of pixels out of src and translate
// it to the matching position relative to dst's origin.
SkIRect snapBounds = SkIRect::MakeXYWH(dstOrigin.x() - src->getOrigin().x(),
dstOrigin.y() - src->getOrigin().y(),
dst->width(), dst->height());
if (!snapBounds.intersect(srcDevRect)) {
return;
}
auto special = src->snapSpecial(snapBounds);
if (special) {
// The image is drawn at 1-1 scale with integer translation, so no filtering is needed.
SkPaint p;
dst->drawSpecial(special.get(), 0, 0, p, nullptr, SkMatrix::I());
}
return;
}
// First decompose the ctm into a post-filter transform and a filter matrix that is supported
// by the backdrop filter.
SkMatrix toRoot, layerMatrix;
SkSize scale;
if (ctm.isScaleTranslate() || as_IFB(filter)->canHandleComplexCTM()) {
toRoot = SkMatrix::I();
layerMatrix = ctm;
} else if (ctm.decomposeScale(&scale, &toRoot)) {
layerMatrix = SkMatrix::Scale(scale.fWidth, scale.fHeight);
} else {
// Perspective, for now, do no scaling of the layer itself.
// TODO (michaelludwig) - perhaps it'd be better to explore a heuristic scale pulled from
// the matrix, e.g. based on the midpoint of the near/far planes?
toRoot = ctm;
layerMatrix = SkMatrix::I();
}
// We have to map the dst bounds from the root space into the layer space where filtering will
// occur. If we knew the input bounds of the content that defined the original dst bounds, we
// could map that forward by layerMatrix and have tighter bounds, but toRoot^-1 * dst bounds
// is a safe, conservative estimate.
SkMatrix fromRoot;
if (!toRoot.invert(&fromRoot)) {
return;
}
// This represents what the backdrop filter needs to produce in the layer space, and is sized
// such that drawing it into dst with the toRoot transform will cover the actual dst device.
SkIRect layerTargetBounds = fromRoot.mapRect(
SkRect::MakeXYWH(dstOrigin.x(), dstOrigin.y(), dst->width(), dst->height())).roundOut();
// While layerTargetBounds is what needs to be output by the filter, the filtering process may
// require some extra input pixels.
SkIRect layerInputBounds = filter->filterBounds(
layerTargetBounds, layerMatrix, SkImageFilter::kReverse_MapDirection,
&layerTargetBounds);
// Map the required input into the root space, then make relative to the src device. This will
// be the conservative contents required to fill a layerInputBounds-sized surface with the
// backdrop content (transformed back into the layer space using fromRoot).
SkIRect backdropBounds = toRoot.mapRect(SkRect::Make(layerInputBounds)).roundOut();
backdropBounds.offset(-src->getOrigin().x(), -src->getOrigin().y());
if (!backdropBounds.intersect(srcDevRect)) {
return;
}
auto special = src->snapSpecial(backdropBounds);
if (!special) {
return;
}
SkColorType colorType = src->imageInfo().colorType();
if (colorType == kUnknown_SkColorType) {
colorType = kRGBA_8888_SkColorType;
}
SkColorSpace* colorSpace = src->imageInfo().colorSpace();
SkPaint p;
if (!toRoot.isIdentity()) {
// Drawing the temporary and final filtered image requires a higher filter quality if the
// 'toRoot' transformation is not identity, in order to minimize the impact on already
// rendered edges/content.
// TODO (michaelludwig) - Explore reducing this quality, identify visual tradeoffs
p.setFilterQuality(kHigh_SkFilterQuality);
// The snapped backdrop content needs to be transformed by fromRoot into the layer space,
// and stored in a temporary surface, which is then used as the input to the actual filter.
auto tmpSurface = special->makeSurface(colorType, colorSpace, layerInputBounds.size());
if (!tmpSurface) {
return;
}
auto tmpCanvas = tmpSurface->getCanvas();
tmpCanvas->clear(SK_ColorTRANSPARENT);
// Reading in reverse, this takes the backdrop bounds from src device space into the root
// space, then maps from root space into the layer space, then maps it so the input layer's
// top left corner is (0, 0). This transformation automatically accounts for any cropping
// performed on backdropBounds.
tmpCanvas->translate(-layerInputBounds.fLeft, -layerInputBounds.fTop);
tmpCanvas->concat(fromRoot);
tmpCanvas->translate(src->getOrigin().x(), src->getOrigin().y());
tmpCanvas->drawImageRect(special->asImage(), special->subset(),
SkRect::Make(backdropBounds), &p, kStrict_SrcRectConstraint);
special = tmpSurface->makeImageSnapshot();
} else {
// Since there is no extra transform that was done, update the input bounds to reflect
// cropping of the snapped backdrop image. In this case toRoot = I, so layerInputBounds
// was equal to backdropBounds before it was made relative to the src device and cropped.
// When we use the original snapped image directly, just map the update backdrop bounds
// back into the shared layer space
layerInputBounds = backdropBounds;
layerInputBounds.offset(src->getOrigin().x(), src->getOrigin().y());
// Similar to the unfiltered case above, when toRoot is the identity, then the final
// draw will be 1-1 so there is no need to increase filter quality.
p.setFilterQuality(kNone_SkFilterQuality);
}
// Now evaluate the filter on 'special', which contains the backdrop content mapped back into
// layer space. This has to further offset everything so that filter evaluation thinks the
// source image's top left corner is (0, 0).
// TODO (michaelludwig) - Once image filters are robust to non-(0,0) image origins for inputs,
// this can be simplified.
layerTargetBounds.offset(-layerInputBounds.fLeft, -layerInputBounds.fTop);
SkMatrix filterCTM = layerMatrix;
filterCTM.postTranslate(-layerInputBounds.fLeft, -layerInputBounds.fTop);
skif::Context ctx(filterCTM, layerTargetBounds, nullptr, colorType, colorSpace, special.get());
SkIPoint offset;
special = as_IFB(filter)->filterImage(ctx).imageAndOffset(&offset);
if (special) {
// Draw the filtered backdrop content into the dst device. We add layerInputBounds origin
// to offset because the original value in 'offset' was relative to 'filterCTM'. 'filterCTM'
// had subtracted the layerInputBounds origin, so adding that back makes 'offset' relative
// to 'layerMatrix' (what we need it to be when drawing the image by 'toRoot').
offset += layerInputBounds.topLeft();
// Manually setting the device's CTM requires accounting for the device's origin.
// TODO (michaelludwig) - This could be simpler if the dst device had its origin configured
// before filtering the backdrop device, and if SkAutoDeviceTransformRestore had a way to accept
// a global CTM instead of a device CTM.
SkMatrix dstCTM = toRoot;
dstCTM.postTranslate(-dstOrigin.x(), -dstOrigin.y());
SkAutoDeviceTransformRestore adr(dst, dstCTM);
// And because devices don't have a special-image draw function that supports arbitrary
// matrices, we are abusing the asImage() functionality here...
SkRect specialSrc = SkRect::Make(special->subset());
auto looseImage = special->asImage();
dst->drawImageRect(
looseImage.get(), &specialSrc,
SkRect::MakeXYWH(offset.x(), offset.y(), special->width(), special->height()),
p, kStrict_SrcRectConstraint);
}
}
static SkImageInfo make_layer_info(const SkImageInfo& prev, int w, int h, const SkPaint* paint) {
SkColorType ct = prev.colorType();
if (prev.bytesPerPixel() <= 4 &&
prev.colorType() != kRGBA_8888_SkColorType &&
prev.colorType() != kBGRA_8888_SkColorType) {
// "Upgrade" A8, G8, 565, 4444, 1010102, 101010x, and 888x to 8888,
// ensuring plenty of alpha bits for the layer, perhaps losing some color bits in return.
ct = kN32_SkColorType;
}
return SkImageInfo::Make(w, h, ct, kPremul_SkAlphaType, prev.refColorSpace());
}
void SkCanvas::internalSaveLayer(const SaveLayerRec& rec, SaveLayerStrategy strategy) {
TRACE_EVENT0("skia", TRACE_FUNC);
const SkRect* bounds = rec.fBounds;
SaveLayerFlags saveLayerFlags = rec.fSaveLayerFlags;
SkTCopyOnFirstWrite<SkPaint> paint(rec.fPaint);
// saveLayer ignores mask filters, so force it to null
if (paint.get() && paint->getMaskFilter()) {
paint.writable()->setMaskFilter(nullptr);
}
// If we have a backdrop filter, then we must apply it to the entire layer (clip-bounds)
// regardless of any hint-rect from the caller. skbug.com/8783
if (rec.fBackdrop) {
bounds = nullptr;
}
SkImageFilter* imageFilter = paint.get() ? paint->getImageFilter() : nullptr;
SkMatrix stashedMatrix = fMCRec->fMatrix.asM33();
MCRec* modifiedRec = nullptr;
/*
* Many ImageFilters (so far) do not (on their own) correctly handle matrices (CTM) that
* contain rotation/skew/etc. We rely on applyCTM to create a new image filter DAG as needed to
* accommodate this, but it requires update the CTM we use when drawing into the layer.
*
* 1. Stash off the current CTM
* 2. Apply the CTM to imagefilter, which decomposes it into simple and complex transforms
* if necessary.
* 3. Wack the CTM to be the remaining scale matrix and use the modified imagefilter, which
* is a MatrixImageFilter that contains the complex matrix.
* 4. Proceed as usual, allowing the client to draw into the layer (now with a scale-only CTM)
* 5. During restore, the MatrixImageFilter automatically applies complex stage to the output
* of the original imagefilter, and draw that (via drawSprite)
* 6. Unwack the CTM to its original state (i.e. stashedMatrix)
*
* Perhaps in the future we could augment #5 to apply REMAINDER as part of the draw (no longer
* a sprite operation) to avoid the extra buffer/overhead of MatrixImageFilter.
*/
if (imageFilter) {
SkMatrix modifiedCTM;
sk_sp<SkImageFilter> modifiedFilter = as_IFB(imageFilter)->applyCTM(stashedMatrix,
&modifiedCTM);
if (as_IFB(modifiedFilter)->uniqueID() != as_IFB(imageFilter)->uniqueID()) {
// The original filter couldn't support the CTM entirely
SkASSERT(modifiedCTM.isScaleTranslate() || as_IFB(imageFilter)->canHandleComplexCTM());
modifiedRec = fMCRec;
this->internalSetMatrix(modifiedCTM);
imageFilter = modifiedFilter.get();
paint.writable()->setImageFilter(std::move(modifiedFilter));
}
// Else the filter didn't change, so modifiedCTM == stashedMatrix and there's nothing
// left to do since the stack already has that as the CTM.
}
// do this before we create the layer. We don't call the public save() since
// that would invoke a possibly overridden virtual
this->internalSave();
SkIRect ir;
if (!this->clipRectBounds(bounds, saveLayerFlags, &ir, imageFilter)) {
if (modifiedRec) {
// In this case there will be no layer in which to stash the matrix so we need to
// revert the prior MCRec to its earlier state.
modifiedRec->fMatrix = SkM44(stashedMatrix);
}
return;
}
// FIXME: do willSaveLayer() overriders returning kNoLayer_SaveLayerStrategy really care about
// the clipRectBounds() call above?
if (kNoLayer_SaveLayerStrategy == strategy) {
return;
}
SkBaseDevice* priorDevice = this->getTopDevice();
if (nullptr == priorDevice) { // Do we still need this check???
SkDebugf("Unable to find device for layer.");
return;
}
SkImageInfo info = make_layer_info(priorDevice->imageInfo(), ir.width(), ir.height(), paint);
if (rec.fSaveLayerFlags & kF16ColorType) {
info = info.makeColorType(kRGBA_F16_SkColorType);
}
sk_sp<SkBaseDevice> newDevice;
{
SkASSERT(info.alphaType() != kOpaque_SkAlphaType);
SkPixelGeometry geo = saveLayerFlags & kPreserveLCDText_SaveLayerFlag
? fProps.pixelGeometry()
: kUnknown_SkPixelGeometry;
const bool trackCoverage =
SkToBool(saveLayerFlags & kMaskAgainstCoverage_EXPERIMENTAL_DONT_USE_SaveLayerFlag);
const auto createInfo = SkBaseDevice::CreateInfo(info,
geo,
SkBaseDevice::kNever_TileUsage,
trackCoverage,
fAllocator.get());
newDevice.reset(priorDevice->onCreateDevice(createInfo, paint));
if (!newDevice) {
return;
}
newDevice->setMarkerStack(fMarkerStack.get());
}
DeviceCM* layer = new DeviceCM(newDevice, paint, stashedMatrix, rec.fClipMask, rec.fClipMatrix);
// only have a "next" if this new layer doesn't affect the clip (rare)
layer->fNext = BoundsAffectsClip(saveLayerFlags) ? nullptr : fMCRec->fTopLayer;
fMCRec->fLayer = layer;
fMCRec->fTopLayer = layer; // this field is NOT an owner of layer
if ((rec.fSaveLayerFlags & kInitWithPrevious_SaveLayerFlag) || rec.fBackdrop) {
DrawDeviceWithFilter(priorDevice, rec.fBackdrop, newDevice.get(), { ir.fLeft, ir.fTop },
fMCRec->fMatrix.asM33());
}
newDevice->setOrigin(fMCRec->fMatrix, ir.fLeft, ir.fTop);
newDevice->androidFramework_setDeviceClipRestriction(&fClipRestrictionRect);
if (layer->fNext) {
// need to punch a hole in the previous device, so we don't draw there, given that
// the new top-layer will allow drawing to happen "below" it.
SkRegion hole(ir);
do {
layer = layer->fNext;
layer->fDevice->clipRegion(hole, SkClipOp::kDifference);
} while (layer->fNext);
}
}
int SkCanvas::saveLayerAlpha(const SkRect* bounds, U8CPU alpha) {
if (0xFF == alpha) {
return this->saveLayer(bounds, nullptr);
} else {
SkPaint tmpPaint;
tmpPaint.setAlpha(alpha);
return this->saveLayer(bounds, &tmpPaint);
}
}
void SkCanvas::internalSaveBehind(const SkRect* localBounds) {
SkBaseDevice* device = this->getTopDevice();
if (nullptr == device) { // Do we still need this check???
return;
}
// Map the local bounds into the top device's coordinate space (this is not
// necessarily the full global CTM transform).
SkIRect devBounds;
if (localBounds) {
SkRect tmp;
device->localToDevice().mapRect(&tmp, *localBounds);
if (!devBounds.intersect(tmp.round(), device->devClipBounds())) {
devBounds.setEmpty();
}
} else {
devBounds = device->devClipBounds();
}
if (devBounds.isEmpty()) {
return;
}
// This is getting the special image from the current device, which is then drawn into (both by
// a client, and the drawClippedToSaveBehind below). Since this is not saving a layer, with its
// own device, we need to explicitly copy the back image contents so that its original content
// is available when we splat it back later during restore.
auto backImage = device->snapSpecial(devBounds, /* copy */ true);
if (!backImage) {
return;
}
// we really need the save, so we can wack the fMCRec
this->checkForDeferredSave();
fMCRec->fBackImage.reset(new BackImage{std::move(backImage), devBounds.topLeft()});
SkPaint paint;
paint.setBlendMode(SkBlendMode::kClear);
this->drawClippedToSaveBehind(paint);
}
void SkCanvas::internalRestore() {
SkASSERT(fMCStack.count() != 0);
// reserve our layer (if any)
DeviceCM* layer = fMCRec->fLayer; // may be null
// now detach it from fMCRec so we can pop(). Gets freed after its drawn
fMCRec->fLayer = nullptr;
// move this out before we do the actual restore
auto backImage = std::move(fMCRec->fBackImage);
fMarkerStack->restore(fMCRec);
// now do the normal restore()
fMCRec->~MCRec(); // balanced in save()
fMCStack.pop_back();
fMCRec = (MCRec*)fMCStack.back();
if (fMCRec) {
FOR_EACH_TOP_DEVICE(device->restore(fMCRec->fMatrix));
}
if (backImage) {
SkPaint paint;
paint.setBlendMode(SkBlendMode::kDstOver);
const int x = backImage->fLoc.x();
const int y = backImage->fLoc.y();
this->getTopDevice()->drawSpecial(backImage->fImage.get(), x, y, paint,
nullptr, SkMatrix::I());
}
/* Time to draw the layer's offscreen. We can't call the public drawSprite,
since if we're being recorded, we don't want to record this (the
recorder will have already recorded the restore).
*/
if (layer) {
if (fMCRec) {
layer->fDevice->setImmutable();
// At this point, 'layer' has been removed from the device stack, so the devices that
// internalDrawDevice sees are the destinations that 'layer' is drawn into.
this->internalDrawDevice(layer->fDevice.get(), layer->fPaint.get(),
layer->fClipImage.get(), layer->fClipMatrix);
// restore what we smashed in internalSaveLayer
this->internalSetMatrix(layer->fStashedMatrix);
delete layer;
} else {
// we're at the root
SkASSERT(layer == (void*)fDeviceCMStorage);
layer->~DeviceCM();
// no need to update fMCRec, 'cause we're killing the canvas
}
}
if (fMCRec) {
fIsScaleTranslate = SkMatrixPriv::IsScaleTranslateAsM33(fMCRec->fMatrix);
fDeviceClipBounds = qr_clip_bounds(fMCRec->fRasterClip.getBounds());
}
}
sk_sp<SkSurface> SkCanvas::makeSurface(const SkImageInfo& info, const SkSurfaceProps* props) {
if (nullptr == props) {
props = &fProps;
}
return this->onNewSurface(info, *props);
}
sk_sp<SkSurface> SkCanvas::onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) {
SkBaseDevice* dev = this->getDevice();
return dev ? dev->makeSurface(info, props) : nullptr;
}
SkImageInfo SkCanvas::imageInfo() const {
return this->onImageInfo();
}
SkImageInfo SkCanvas::onImageInfo() const {
SkBaseDevice* dev = this->getDevice();
if (dev) {
return dev->imageInfo();
} else {
return SkImageInfo::MakeUnknown(0, 0);
}
}
bool SkCanvas::getProps(SkSurfaceProps* props) const {
return this->onGetProps(props);
}
bool SkCanvas::onGetProps(SkSurfaceProps* props) const {
SkBaseDevice* dev = this->getDevice();
if (dev) {
if (props) {
*props = fProps;
}
return true;
} else {
return false;
}
}
bool SkCanvas::peekPixels(SkPixmap* pmap) {
return this->onPeekPixels(pmap);
}
bool SkCanvas::onPeekPixels(SkPixmap* pmap) {
SkBaseDevice* dev = this->getDevice();
return dev && dev->peekPixels(pmap);
}
void* SkCanvas::accessTopLayerPixels(SkImageInfo* info, size_t* rowBytes, SkIPoint* origin) {
SkPixmap pmap;
if (!this->onAccessTopLayerPixels(&pmap)) {
return nullptr;
}
if (info) {
*info = pmap.info();
}
if (rowBytes) {
*rowBytes = pmap.rowBytes();
}
if (origin) {
// If the caller requested the origin, they presumably are expecting the returned pixels to
// be axis-aligned with the root canvas. If the top level device isn't axis aligned, that's
// not the case. Until we update accessTopLayerPixels() to accept a coord space matrix
// instead of an origin, just don't expose the pixels in that case. Note that this means
// that layers with complex coordinate spaces can still report their pixels if the caller
// does not ask for the origin (e.g. just to dump its output to a file, etc).
if (this->getTopDevice()->isPixelAlignedToGlobal()) {
*origin = this->getTopDevice()->getOrigin();
} else {
return nullptr;
}
}
return pmap.writable_addr();
}
bool SkCanvas::onAccessTopLayerPixels(SkPixmap* pmap) {
SkBaseDevice* dev = this->getTopDevice();
return dev && dev->accessPixels(pmap);
}
/////////////////////////////////////////////////////////////////////////////
// In our current design/features, we should never have a layer (src) in a different colorspace
// than its parent (dst), so we assert that here. This is called out from other asserts, in case
// we add some feature in the future to allow a given layer/imagefilter to operate in a specific
// colorspace.
static void check_drawdevice_colorspaces(SkColorSpace* src, SkColorSpace* dst) {
SkASSERT(src == dst);
}
void SkCanvas::internalDrawDevice(SkBaseDevice* srcDev, const SkPaint* paint,
SkImage* clipImage, const SkMatrix& clipMatrix) {
SkPaint tmp;
if (nullptr == paint) {
paint = &tmp;
}
DRAW_BEGIN_DRAWDEVICE(*paint)
while (iter.next()) {
SkBaseDevice* dstDev = iter.fDevice;
check_drawdevice_colorspaces(dstDev->imageInfo().colorSpace(),
srcDev->imageInfo().colorSpace());
paint = &draw.paint();
SkImageFilter* filter = paint->getImageFilter();
// TODO(michaelludwig) - Devices aren't created with complex coordinate systems yet,
// so it should always be possible to use the relative origin. Once drawDevice() and
// drawSpecial() take an SkMatrix, this can switch to getRelativeTransform() instead.
SkIPoint pos = srcDev->getOrigin() - dstDev->getOrigin();
if (filter || clipImage) {
sk_sp<SkSpecialImage> specialImage = srcDev->snapSpecial();
if (specialImage) {
check_drawdevice_colorspaces(dstDev->imageInfo().colorSpace(),
specialImage->getColorSpace());
dstDev->drawSpecial(specialImage.get(), pos.x(), pos.y(), *paint,
clipImage, clipMatrix);
}
} else {
dstDev->drawDevice(srcDev, pos.x(), pos.y(), *paint);
}
}
DRAW_END
}
/////////////////////////////////////////////////////////////////////////////
void SkCanvas::translate(SkScalar dx, SkScalar dy) {
if (dx || dy) {
this->checkForDeferredSave();
fMCRec->fMatrix.preTranslate(dx, dy);
// Translate shouldn't affect the is-scale-translateness of the matrix.
// However, if either is non-finite, we might still complicate the matrix type,
// so we still have to compute this.
fIsScaleTranslate = SkMatrixPriv::IsScaleTranslateAsM33(fMCRec->fMatrix);
FOR_EACH_TOP_DEVICE(device->setGlobalCTM(fMCRec->fMatrix));
this->didTranslate(dx,dy);
}
}
void SkCanvas::scale(SkScalar sx, SkScalar sy) {
if (sx != 1 || sy != 1) {
this->checkForDeferredSave();
fMCRec->fMatrix.preScale(sx, sy);
// shouldn't need to do this (theoretically), as the state shouldn't have changed,
// but pre-scaling by a non-finite does change it, so we have to recompute.
fIsScaleTranslate = SkMatrixPriv::IsScaleTranslateAsM33(fMCRec->fMatrix);
FOR_EACH_TOP_DEVICE(device->setGlobalCTM(fMCRec->fMatrix));
this->didScale(sx, sy);
}
}
void SkCanvas::rotate(SkScalar degrees) {
SkMatrix m;
m.setRotate(degrees);
this->concat(m);
}
void SkCanvas::rotate(SkScalar degrees, SkScalar px, SkScalar py) {
SkMatrix m;
m.setRotate(degrees, px, py);
this->concat(m);
}
void SkCanvas::skew(SkScalar sx, SkScalar sy) {
SkMatrix m;
m.setSkew(sx, sy);
this->concat(m);
}
void SkCanvas::concat(const SkMatrix& matrix) {
if (matrix.isIdentity()) {
return;
}
this->checkForDeferredSave();
fMCRec->fMatrix.preConcat(matrix);
fIsScaleTranslate = SkMatrixPriv::IsScaleTranslateAsM33(fMCRec->fMatrix);
FOR_EACH_TOP_DEVICE(device->setGlobalCTM(fMCRec->fMatrix));
this->didConcat(matrix);
}
void SkCanvas::internalConcat44(const SkM44& m) {
this->checkForDeferredSave();
fMCRec->fMatrix.preConcat(m);
fIsScaleTranslate = SkMatrixPriv::IsScaleTranslateAsM33(fMCRec->fMatrix);
FOR_EACH_TOP_DEVICE(device->setGlobalCTM(fMCRec->fMatrix));
}
void SkCanvas::concat(const SkM44& m) {
this->internalConcat44(m);
// notify subclasses
this->didConcat44(m);
}
void SkCanvas::internalSetMatrix(const SkMatrix& matrix) {
fMCRec->fMatrix = SkM44(matrix);
fIsScaleTranslate = matrix.isScaleTranslate();
FOR_EACH_TOP_DEVICE(device->setGlobalCTM(fMCRec->fMatrix));
}
void SkCanvas::setMatrix(const SkMatrix& matrix) {
this->checkForDeferredSave();
this->internalSetMatrix(matrix);
this->didSetMatrix(matrix);
}
void SkCanvas::resetMatrix() {
this->setMatrix(SkMatrix::I());
}
void SkCanvas::markCTM(const char* name) {
if (SkCanvasPriv::ValidateMarker(name)) {
fMarkerStack->setMarker(SkOpts::hash_fn(name, strlen(name), 0),
this->getLocalToDevice(), fMCRec);
this->onMarkCTM(name);
}
}
bool SkCanvas::findMarkedCTM(const char* name, SkM44* mx) const {
return SkCanvasPriv::ValidateMarker(name) &&
fMarkerStack->findMarker(SkOpts::hash_fn(name, strlen(name), 0), mx);
}
//////////////////////////////////////////////////////////////////////////////
void SkCanvas::clipRect(const SkRect& rect, SkClipOp op, bool doAA) {
if (!rect.isFinite()) {
return;
}
this->checkForDeferredSave();
ClipEdgeStyle edgeStyle = doAA ? kSoft_ClipEdgeStyle : kHard_ClipEdgeStyle;
this->onClipRect(rect, op, edgeStyle);
}
void SkCanvas::onClipRect(const SkRect& rect, SkClipOp op, ClipEdgeStyle edgeStyle) {
const bool isAA = kSoft_ClipEdgeStyle == edgeStyle;
FOR_EACH_TOP_DEVICE(device->clipRect(rect, op, isAA));
AutoValidateClip avc(this);
fMCRec->fRasterClip.opRect(rect, fMCRec->fMatrix.asM33(), this->getTopLayerBounds(),
(SkRegion::Op)op, isAA);
fDeviceClipBounds = qr_clip_bounds(fMCRec->fRasterClip.getBounds());
}
void SkCanvas::androidFramework_setDeviceClipRestriction(const SkIRect& rect) {
fClipRestrictionRect = rect;
if (fClipRestrictionRect.isEmpty()) {
// we notify the device, but we *dont* resolve deferred saves (since we're just
// removing the restriction if the rect is empty. how I hate this api.
FOR_EACH_TOP_DEVICE(device->androidFramework_setDeviceClipRestriction(&fClipRestrictionRect));
} else {
this->checkForDeferredSave();
FOR_EACH_TOP_DEVICE(device->androidFramework_setDeviceClipRestriction(&fClipRestrictionRect));
AutoValidateClip avc(this);
fMCRec->fRasterClip.opIRect(fClipRestrictionRect, SkRegion::kIntersect_Op);
fDeviceClipBounds = qr_clip_bounds(fMCRec->fRasterClip.getBounds());
}
}
void SkCanvas::clipRRect(const SkRRect& rrect, SkClipOp op, bool doAA) {
this->checkForDeferredSave();
ClipEdgeStyle edgeStyle = doAA ? kSoft_ClipEdgeStyle : kHard_ClipEdgeStyle;
if (rrect.isRect()) {
this->onClipRect(rrect.getBounds(), op, edgeStyle);
} else {
this->onClipRRect(rrect, op, edgeStyle);
}
}
void SkCanvas::onClipRRect(const SkRRect& rrect, SkClipOp op, ClipEdgeStyle edgeStyle) {
AutoValidateClip avc(this);
bool isAA = kSoft_ClipEdgeStyle == edgeStyle;
FOR_EACH_TOP_DEVICE(device->clipRRect(rrect, op, isAA));
fMCRec->fRasterClip.opRRect(rrect, fMCRec->fMatrix.asM33(), this->getTopLayerBounds(),
(SkRegion::Op)op, isAA);
fDeviceClipBounds = qr_clip_bounds(fMCRec->fRasterClip.getBounds());
}
void SkCanvas::clipPath(const SkPath& path, SkClipOp op, bool doAA) {
this->checkForDeferredSave();
ClipEdgeStyle edgeStyle = doAA ? kSoft_ClipEdgeStyle : kHard_ClipEdgeStyle;
if (!path.isInverseFillType() && fMCRec->fMatrix.asM33().rectStaysRect()) {
SkRect r;
if (path.isRect(&r)) {
this->onClipRect(r, op, edgeStyle);
return;
}
SkRRect rrect;
if (path.isOval(&r)) {
rrect.setOval(r);
this->onClipRRect(rrect, op, edgeStyle);
return;
}
if (path.isRRect(&rrect)) {
this->onClipRRect(rrect, op, edgeStyle);
return;
}
}
this->onClipPath(path, op, edgeStyle);
}
void SkCanvas::onClipPath(const SkPath& path, SkClipOp op, ClipEdgeStyle edgeStyle) {
AutoValidateClip avc(this);
bool isAA = kSoft_ClipEdgeStyle == edgeStyle;
FOR_EACH_TOP_DEVICE(device->clipPath(path, op, isAA));
const SkPath* rasterClipPath = &path;
fMCRec->fRasterClip.opPath(*rasterClipPath, fMCRec->fMatrix.asM33(), this->getTopLayerBounds(),
(SkRegion::Op)op, isAA);
fDeviceClipBounds = qr_clip_bounds(fMCRec->fRasterClip.getBounds());
}
void SkCanvas::clipShader(sk_sp<SkShader> sh, SkClipOp op) {
if (sh) {
if (sh->isOpaque()) {
if (op == SkClipOp::kIntersect) {
// we don't occlude anything, so skip this call
} else {
SkASSERT(op == SkClipOp::kDifference);
// we occlude everything, so set the clip to empty
this->clipRect({0,0,0,0});
}
} else {
this->onClipShader(std::move(sh), op);
}
}
}
void SkCanvas::onClipShader(sk_sp<SkShader> sh, SkClipOp op) {
AutoValidateClip avc(this);
FOR_EACH_TOP_DEVICE(device->clipShader(sh, op));
// we don't know how to mutate our conservative bounds, so we don't
}
void SkCanvas::clipRegion(const SkRegion& rgn, SkClipOp op) {
this->checkForDeferredSave();
this->onClipRegion(rgn, op);
}
void SkCanvas::onClipRegion(const SkRegion& rgn, SkClipOp op) {
FOR_EACH_TOP_DEVICE(device->clipRegion(rgn, op));
AutoValidateClip avc(this);
fMCRec->fRasterClip.opRegion(rgn, (SkRegion::Op)op);
fDeviceClipBounds = qr_clip_bounds(fMCRec->fRasterClip.getBounds());
}
#ifdef SK_DEBUG
void SkCanvas::validateClip() const {
// construct clipRgn from the clipstack
const SkBaseDevice* device = this->getDevice();
if (!device) {
SkASSERT(this->isClipEmpty());
return;
}
}
#endif
bool SkCanvas::androidFramework_isClipAA() const {
bool containsAA = false;
FOR_EACH_TOP_DEVICE(containsAA |= device->onClipIsAA());
return containsAA;
}
class RgnAccumulator {
SkRegion* fRgn;
public:
RgnAccumulator(SkRegion* total) : fRgn(total) {}
void accumulate(SkBaseDevice* device, SkRegion* rgn) {
SkIPoint origin = device->getOrigin();
if (origin.x() | origin.y()) {
rgn->translate(origin.x(), origin.y());
}
fRgn->op(*rgn, SkRegion::kUnion_Op);
}
};
void SkCanvas::temporary_internal_getRgnClip(SkRegion* rgn) {
RgnAccumulator accum(rgn);
SkRegion tmp;
rgn->setEmpty();
FOR_EACH_TOP_DEVICE(device->onAsRgnClip(&tmp); accum.accumulate(device, &tmp));
}
///////////////////////////////////////////////////////////////////////////////
bool SkCanvas::isClipEmpty() const {
return fMCRec->fRasterClip.isEmpty();
// TODO: should we only use the conservative answer in a recording canvas?
#if 0
SkBaseDevice* dev = this->getTopDevice();
// if no device we return true
return !dev || dev->onGetClipType() == SkBaseDevice::kEmpty_ClipType;
#endif
}
bool SkCanvas::isClipRect() const {
SkBaseDevice* dev = this->getTopDevice();
// if no device we return false
return dev && dev->onGetClipType() == SkBaseDevice::ClipType::kRect;
}
static inline bool is_nan_or_clipped(const Sk4f& devRect, const Sk4f& devClip) {
#if !defined(SKNX_NO_SIMD) && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE2
__m128 lLtT = _mm_unpacklo_ps(devRect.fVec, devClip.fVec);
__m128 RrBb = _mm_unpackhi_ps(devClip.fVec, devRect.fVec);
__m128 mask = _mm_cmplt_ps(lLtT, RrBb);
return 0xF != _mm_movemask_ps(mask);
#elif !defined(SKNX_NO_SIMD) && defined(SK_ARM_HAS_NEON)
float32x4_t lLtT = vzipq_f32(devRect.fVec, devClip.fVec).val[0];
float32x4_t RrBb = vzipq_f32(devClip.fVec, devRect.fVec).val[1];
uint32x4_t mask = vcltq_f32(lLtT, RrBb);
return 0xFFFFFFFFFFFFFFFF != (uint64_t) vmovn_u32(mask);
#else
SkRect devRectAsRect;
SkRect devClipAsRect;
devRect.store(&devRectAsRect.fLeft);
devClip.store(&devClipAsRect.fLeft);
return !devRectAsRect.isFinite() || !devRectAsRect.intersect(devClipAsRect);
#endif
}
// It's important for this function to not be inlined. Otherwise the compiler will share code
// between the fast path and the slow path, resulting in two slow paths.
static SK_NEVER_INLINE bool quick_reject_slow_path(const SkRect& src, const SkRect& deviceClip,
const SkMatrix& matrix) {
SkRect deviceRect;
matrix.mapRect(&deviceRect, src);
return !deviceRect.isFinite() || !deviceRect.intersect(deviceClip);
}
bool SkCanvas::quickReject(const SkRect& src) const {
#ifdef SK_DEBUG
// Verify that fDeviceClipBounds are set properly.
SkRect tmp = qr_clip_bounds(fMCRec->fRasterClip.getBounds());
if (fMCRec->fRasterClip.isEmpty()) {
SkASSERT(fDeviceClipBounds.isEmpty());
} else {
SkASSERT(tmp == fDeviceClipBounds);
}
// Verify that fIsScaleTranslate is set properly.
SkASSERT(fIsScaleTranslate == SkMatrixPriv::IsScaleTranslateAsM33(fMCRec->fMatrix));
#endif
if (!fIsScaleTranslate) {
return quick_reject_slow_path(src, fDeviceClipBounds, fMCRec->fMatrix.asM33());
}
// We inline the implementation of mapScaleTranslate() for the fast path.
float sx = fMCRec->fMatrix.rc(0, 0);
float sy = fMCRec->fMatrix.rc(1, 1);
float tx = fMCRec->fMatrix.rc(0, 3);
float ty = fMCRec->fMatrix.rc(1, 3);
Sk4f scale(sx, sy, sx, sy);
Sk4f trans(tx, ty, tx, ty);
// Apply matrix.
Sk4f ltrb = Sk4f::Load(&src.fLeft) * scale + trans;
// Make sure left < right, top < bottom.
Sk4f rblt(ltrb[2], ltrb[3], ltrb[0], ltrb[1]);
Sk4f min = Sk4f::Min(ltrb, rblt);
Sk4f max = Sk4f::Max(ltrb, rblt);
// We can extract either pair [0,1] or [2,3] from min and max and be correct, but on
// ARM this sequence generates the fastest (a single instruction).
Sk4f devRect = Sk4f(min[2], min[3], max[0], max[1]);
// Check if the device rect is NaN or outside the clip.
return is_nan_or_clipped(devRect, Sk4f::Load(&fDeviceClipBounds.fLeft));
}
bool SkCanvas::quickReject(const SkPath& path) const {
return path.isEmpty() || this->quickReject(path.getBounds());
}
SkRect SkCanvas::getLocalClipBounds() const {
SkIRect ibounds = this->getDeviceClipBounds();
if (ibounds.isEmpty()) {
return SkRect::MakeEmpty();
}
SkMatrix inverse;
// if we can't invert the CTM, we can't return local clip bounds
if (!fMCRec->fMatrix.asM33().invert(&inverse)) {
return SkRect::MakeEmpty();
}
SkRect bounds;
// adjust it outwards in case we are antialiasing
const int margin = 1;
SkRect r = SkRect::Make(ibounds.makeOutset(margin, margin));
inverse.mapRect(&bounds, r);
return bounds;
}
SkIRect SkCanvas::getDeviceClipBounds() const {
return fMCRec->fRasterClip.getBounds();
}
///////////////////////////////////////////////////////////////////////
SkMatrix SkCanvas::getTotalMatrix() const {
return fMCRec->fMatrix.asM33();
}
SkM44 SkCanvas::getLocalToDevice() const {
return fMCRec->fMatrix;
}
GrRenderTargetContext* SkCanvas::internal_private_accessTopLayerRenderTargetContext() {
SkBaseDevice* dev = this->getTopDevice();
return dev ? dev->accessRenderTargetContext() : nullptr;
}
GrContext* SkCanvas::getGrContext() {
SkBaseDevice* device = this->getTopDevice();
return device ? device->context() : nullptr;
}
void SkCanvas::drawDRRect(const SkRRect& outer, const SkRRect& inner,
const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
if (outer.isEmpty()) {
return;
}
if (inner.isEmpty()) {
this->drawRRect(outer, paint);
return;
}
// We don't have this method (yet), but technically this is what we should
// be able to return ...
// if (!outer.contains(inner))) {
//
// For now at least check for containment of bounds
if (!outer.getBounds().contains(inner.getBounds())) {
return;
}
this->onDrawDRRect(outer, inner, paint);
}
void SkCanvas::drawPaint(const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
this->onDrawPaint(paint);
}
void SkCanvas::drawRect(const SkRect& r, const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
// To avoid redundant logic in our culling code and various backends, we always sort rects
// before passing them along.
this->onDrawRect(r.makeSorted(), paint);
}
void SkCanvas::drawClippedToSaveBehind(const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
this->onDrawBehind(paint);
}
void SkCanvas::drawRegion(const SkRegion& region, const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
if (region.isEmpty()) {
return;
}
if (region.isRect()) {
return this->drawIRect(region.getBounds(), paint);
}
this->onDrawRegion(region, paint);
}
void SkCanvas::drawOval(const SkRect& r, const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
// To avoid redundant logic in our culling code and various backends, we always sort rects
// before passing them along.
this->onDrawOval(r.makeSorted(), paint);
}
void SkCanvas::drawRRect(const SkRRect& rrect, const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
this->onDrawRRect(rrect, paint);
}
void SkCanvas::drawPoints(PointMode mode, size_t count, const SkPoint pts[], const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
this->onDrawPoints(mode, count, pts, paint);
}
void SkCanvas::drawVertices(const sk_sp<SkVertices>& vertices, SkBlendMode mode,
const SkPaint& paint) {
this->drawVertices(vertices.get(), mode, paint);
}
void SkCanvas::drawVertices(const SkVertices* vertices, SkBlendMode mode, const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
RETURN_ON_NULL(vertices);
// We expect fans to be converted to triangles when building or deserializing SkVertices.
SkASSERT(vertices->priv().mode() != SkVertices::kTriangleFan_VertexMode);
// If the vertices contain custom attributes, ensure they line up with the paint's shader.
const SkRuntimeEffect* effect =
paint.getShader() ? as_SB(paint.getShader())->asRuntimeEffect() : nullptr;
if ((size_t)vertices->priv().attributeCount() != (effect ? effect->varyings().count() : 0)) {
return;
}
if (effect) {
int attrIndex = 0;
for (const auto& v : effect->varyings()) {
const SkVertices::Attribute& attr(vertices->priv().attributes()[attrIndex++]);
// Mismatch between the SkSL varying and the vertex shader output for this attribute
if (attr.channelCount() != v.fWidth) {
return;
}
// If we can't provide any of the asked-for matrices, we can't draw this
if (attr.fMarkerID && !fMarkerStack->findMarker(attr.fMarkerID, nullptr)) {
return;
}
}
}
#ifdef SK_BUILD_FOR_ANDROID_FRAMEWORK
// Preserve legacy behavior for Android: ignore the SkShader if there are no texCoords present
if (paint.getShader() &&
!(vertices->priv().hasTexCoords() || vertices->priv().hasCustomData())) {
SkPaint noShaderPaint(paint);
noShaderPaint.setShader(nullptr);
this->onDrawVerticesObject(vertices, mode, noShaderPaint);
return;
}
#endif
this->onDrawVerticesObject(vertices, mode, paint);
}
void SkCanvas::drawPath(const SkPath& path, const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
this->onDrawPath(path, paint);
}
void SkCanvas::drawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint* paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
RETURN_ON_NULL(image);
this->onDrawImage(image, x, y, paint);
}
// Returns true if the rect can be "filled" : non-empty and finite
static bool fillable(const SkRect& r) {
SkScalar w = r.width();
SkScalar h = r.height();
return SkScalarIsFinite(w) && w > 0 && SkScalarIsFinite(h) && h > 0;
}
void SkCanvas::drawImageRect(const SkImage* image, const SkRect& src, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) {
TRACE_EVENT0("skia", TRACE_FUNC);
RETURN_ON_NULL(image);
if (!fillable(dst) || !fillable(src)) {
return;
}
this->onDrawImageRect(image, &src, dst, paint, constraint);
}
void SkCanvas::drawImageRect(const SkImage* image, const SkIRect& isrc, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) {
RETURN_ON_NULL(image);
this->drawImageRect(image, SkRect::Make(isrc), dst, paint, constraint);
}
void SkCanvas::drawImageRect(const SkImage* image, const SkRect& dst, const SkPaint* paint) {
RETURN_ON_NULL(image);
this->drawImageRect(image, SkRect::MakeIWH(image->width(), image->height()), dst, paint,
kFast_SrcRectConstraint);
}
namespace {
class LatticePaint : SkNoncopyable {
public:
LatticePaint(const SkPaint* origPaint) : fPaint(origPaint) {
if (!origPaint) {
return;
}
if (origPaint->getFilterQuality() > kLow_SkFilterQuality) {
fPaint.writable()->setFilterQuality(kLow_SkFilterQuality);
}
if (origPaint->getMaskFilter()) {
fPaint.writable()->setMaskFilter(nullptr);
}
if (origPaint->isAntiAlias()) {
fPaint.writable()->setAntiAlias(false);
}
}
const SkPaint* get() const {
return fPaint;
}
private:
SkTCopyOnFirstWrite<SkPaint> fPaint;
};
} // namespace
void SkCanvas::drawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst,
const SkPaint* paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
RETURN_ON_NULL(image);
if (dst.isEmpty()) {
return;
}
if (SkLatticeIter::Valid(image->width(), image->height(), center)) {
LatticePaint latticePaint(paint);
this->onDrawImageNine(image, center, dst, latticePaint.get());
} else {
this->drawImageRect(image, dst, paint);
}
}
void SkCanvas::drawImageLattice(const SkImage* image, const Lattice& lattice, const SkRect& dst,
const SkPaint* paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
RETURN_ON_NULL(image);
if (dst.isEmpty()) {
return;
}
SkIRect bounds;
Lattice latticePlusBounds = lattice;
if (!latticePlusBounds.fBounds) {
bounds = SkIRect::MakeWH(image->width(), image->height());
latticePlusBounds.fBounds = &bounds;
}
if (SkLatticeIter::Valid(image->width(), image->height(), latticePlusBounds)) {
LatticePaint latticePaint(paint);
this->onDrawImageLattice(image, latticePlusBounds, dst, latticePaint.get());
} else {
this->drawImageRect(image, dst, paint);
}
}
static sk_sp<SkImage> bitmap_as_image(const SkBitmap& bitmap) {
if (bitmap.drawsNothing()) {
return nullptr;
}
return SkImage::MakeFromBitmap(bitmap);
}
void SkCanvas::drawBitmap(const SkBitmap& bitmap, SkScalar dx, SkScalar dy, const SkPaint* paint) {
this->drawImage(bitmap_as_image(bitmap), dx, dy, paint);
}
void SkCanvas::drawBitmapRect(const SkBitmap& bitmap, const SkRect& src, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) {
this->drawImageRect(bitmap_as_image(bitmap), src, dst, paint, constraint);
}
void SkCanvas::drawBitmapRect(const SkBitmap& bitmap, const SkIRect& isrc, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) {
this->drawBitmapRect(bitmap, SkRect::Make(isrc), dst, paint, constraint);
}
void SkCanvas::drawBitmapRect(const SkBitmap& bitmap, const SkRect& dst, const SkPaint* paint,
SrcRectConstraint constraint) {
this->drawBitmapRect(bitmap, SkRect::MakeIWH(bitmap.width(), bitmap.height()), dst, paint,
constraint);
}
void SkCanvas::drawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
const SkColor colors[], int count, SkBlendMode mode,
const SkRect* cull, const SkPaint* paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
RETURN_ON_NULL(atlas);
if (count <= 0) {
return;
}
SkASSERT(atlas);
SkASSERT(tex);
this->onDrawAtlas(atlas, xform, tex, colors, count, mode, cull, paint);
}
void SkCanvas::drawAnnotation(const SkRect& rect, const char key[], SkData* value) {
TRACE_EVENT0("skia", TRACE_FUNC);
if (key) {
this->onDrawAnnotation(rect, key, value);
}
}
void SkCanvas::legacy_drawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) {
if (src) {
this->drawImageRect(image, *src, dst, paint, constraint);
} else {
this->drawImageRect(image, SkRect::MakeIWH(image->width(), image->height()),
dst, paint, constraint);
}
}
void SkCanvas::private_draw_shadow_rec(const SkPath& path, const SkDrawShadowRec& rec) {
TRACE_EVENT0("skia", TRACE_FUNC);
this->onDrawShadowRec(path, rec);
}
void SkCanvas::onDrawShadowRec(const SkPath& path, const SkDrawShadowRec& rec) {
SkPaint paint;
const SkRect& pathBounds = path.getBounds();
DRAW_BEGIN(paint, &pathBounds)
while (iter.next()) {
iter.fDevice->drawShadow(path, rec);
}
DRAW_END
}
void SkCanvas::experimental_DrawEdgeAAQuad(const SkRect& rect, const SkPoint clip[4],
QuadAAFlags aaFlags, const SkColor4f& color,
SkBlendMode mode) {
TRACE_EVENT0("skia", TRACE_FUNC);
// Make sure the rect is sorted before passing it along
this->onDrawEdgeAAQuad(rect.makeSorted(), clip, aaFlags, color, mode);
}
void SkCanvas::experimental_DrawEdgeAAImageSet(const ImageSetEntry imageSet[], int cnt,
const SkPoint dstClips[],
const SkMatrix preViewMatrices[],
const SkPaint* paint,
SrcRectConstraint constraint) {
TRACE_EVENT0("skia", TRACE_FUNC);
this->onDrawEdgeAAImageSet(imageSet, cnt, dstClips, preViewMatrices, paint, constraint);
}
//////////////////////////////////////////////////////////////////////////////
// These are the virtual drawing methods
//////////////////////////////////////////////////////////////////////////////
void SkCanvas::onDiscard() {
if (fSurfaceBase) {
fSurfaceBase->aboutToDraw(SkSurface::kDiscard_ContentChangeMode);
}
}
void SkCanvas::onDrawPaint(const SkPaint& paint) {
this->internalDrawPaint(paint);
}
void SkCanvas::internalDrawPaint(const SkPaint& paint) {
DRAW_BEGIN_CHECK_COMPLETE_OVERWRITE(paint, nullptr, false)
while (iter.next()) {
iter.fDevice->drawPaint(draw.paint());
}
DRAW_END
}
void SkCanvas::onDrawPoints(PointMode mode, size_t count, const SkPoint pts[],
const SkPaint& paint) {
if ((long)count <= 0) {
return;
}
SkRect r;
const SkRect* bounds = nullptr;
if (paint.canComputeFastBounds()) {
// special-case 2 points (common for drawing a single line)
if (2 == count) {
r.set(pts[0], pts[1]);
} else {
r.setBounds(pts, SkToInt(count));
}
if (!r.isFinite()) {
return;
}
SkRect storage;
if (this->quickReject(paint.computeFastStrokeBounds(r, &storage))) {
return;
}
bounds = &r;
}
SkASSERT(pts != nullptr);
DRAW_BEGIN(paint, bounds)
while (iter.next()) {
iter.fDevice->drawPoints(mode, count, pts, draw.paint());
}
DRAW_END
}
static bool needs_autodrawlooper(SkCanvas* canvas, const SkPaint& paint) {
return paint.getImageFilter() != nullptr;
}
void SkCanvas::onDrawRect(const SkRect& r, const SkPaint& paint) {
SkASSERT(r.isSorted());
if (paint.canComputeFastBounds()) {
SkRect storage;
if (this->quickReject(paint.computeFastBounds(r, &storage))) {
return;
}
}
if (needs_autodrawlooper(this, paint)) {
DRAW_BEGIN_CHECK_COMPLETE_OVERWRITE(paint, &r, false)
while (iter.next()) {
iter.fDevice->drawRect(r, draw.paint());
}
DRAW_END
} else if (!paint.nothingToDraw()) {
this->predrawNotify(&r, &paint, false);
SkDrawIter iter(this);
while (iter.next()) {
iter.fDevice->drawRect(r, paint);
}
}
}
void SkCanvas::onDrawRegion(const SkRegion& region, const SkPaint& paint) {
SkRect regionRect = SkRect::Make(region.getBounds());
if (paint.canComputeFastBounds()) {
SkRect storage;
if (this->quickReject(paint.computeFastBounds(regionRect, &storage))) {
return;
}
}
DRAW_BEGIN(paint, ®ionRect)
while (iter.next()) {
iter.fDevice->drawRegion(region, draw.paint());
}
DRAW_END
}
void SkCanvas::onDrawBehind(const SkPaint& paint) {
SkIRect bounds;
SkDeque::Iter iter(fMCStack, SkDeque::Iter::kBack_IterStart);
for (;;) {
const MCRec* rec = (const MCRec*)iter.prev();
if (!rec) {
return; // no backimages, so nothing to draw
}
if (rec->fBackImage) {
bounds = SkIRect::MakeXYWH(rec->fBackImage->fLoc.fX, rec->fBackImage->fLoc.fY,
rec->fBackImage->fImage->width(),
rec->fBackImage->fImage->height());
break;
}
}
DRAW_BEGIN(paint, nullptr)
while (iter.next()) {
SkBaseDevice* dev = iter.fDevice;
dev->save();
// We use clipRegion because it is already defined to operate in dev-space
// (i.e. ignores the ctm). However, it is going to first translate by -origin,
// but we don't want that, so we undo that before calling in.
SkRegion rgn(bounds.makeOffset(dev->getOrigin()));
dev->clipRegion(rgn, SkClipOp::kIntersect);
dev->drawPaint(draw.paint());
dev->restore(fMCRec->fMatrix);
}
DRAW_END
}
void SkCanvas::onDrawOval(const SkRect& oval, const SkPaint& paint) {
SkASSERT(oval.isSorted());
if (paint.canComputeFastBounds()) {
SkRect storage;
if (this->quickReject(paint.computeFastBounds(oval, &storage))) {
return;
}
}
DRAW_BEGIN(paint, &oval)
while (iter.next()) {
iter.fDevice->drawOval(oval, draw.paint());
}
DRAW_END
}
void SkCanvas::onDrawArc(const SkRect& oval, SkScalar startAngle,
SkScalar sweepAngle, bool useCenter,
const SkPaint& paint) {
SkASSERT(oval.isSorted());
if (paint.canComputeFastBounds()) {
SkRect storage;
// Note we're using the entire oval as the bounds.
if (this->quickReject(paint.computeFastBounds(oval, &storage))) {
return;
}
}
DRAW_BEGIN(paint, &oval)
while (iter.next()) {
iter.fDevice->drawArc(oval, startAngle, sweepAngle, useCenter, draw.paint());
}
DRAW_END
}
void SkCanvas::onDrawRRect(const SkRRect& rrect, const SkPaint& paint) {
if (paint.canComputeFastBounds()) {
SkRect storage;
if (this->quickReject(paint.computeFastBounds(rrect.getBounds(), &storage))) {
return;
}
}
if (rrect.isRect()) {
// call the non-virtual version
this->SkCanvas::drawRect(rrect.getBounds(), paint);
return;
} else if (rrect.isOval()) {
// call the non-virtual version
this->SkCanvas::drawOval(rrect.getBounds(), paint);
return;
}
DRAW_BEGIN(paint, &rrect.getBounds())
while (iter.next()) {
iter.fDevice->drawRRect(rrect, draw.paint());
}
DRAW_END
}
void SkCanvas::onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) {
if (paint.canComputeFastBounds()) {
SkRect storage;
if (this->quickReject(paint.computeFastBounds(outer.getBounds(), &storage))) {
return;
}
}
DRAW_BEGIN(paint, &outer.getBounds())
while (iter.next()) {
iter.fDevice->drawDRRect(outer, inner, draw.paint());
}
DRAW_END
}
void SkCanvas::onDrawPath(const SkPath& path, const SkPaint& paint) {
if (!path.isFinite()) {
return;
}
const SkRect& pathBounds = path.getBounds();
if (!path.isInverseFillType() && paint.canComputeFastBounds()) {
SkRect storage;
if (this->quickReject(paint.computeFastBounds(pathBounds, &storage))) {
return;
}
}
if (pathBounds.width() <= 0 && pathBounds.height() <= 0) {
if (path.isInverseFillType()) {
this->internalDrawPaint(paint);
return;
}
}
DRAW_BEGIN(paint, &pathBounds)
while (iter.next()) {
iter.fDevice->drawPath(path, draw.paint());
}
DRAW_END
}
bool SkCanvas::canDrawBitmapAsSprite(SkScalar x, SkScalar y, int w, int h, const SkPaint& paint) {
if (!paint.getImageFilter()) {
return false;
}
const SkMatrix& ctm = this->getTotalMatrix();
if (!SkTreatAsSprite(ctm, SkISize::Make(w, h), paint)) {
return false;
}
// The other paint effects need to be applied before the image filter, but the sprite draw
// applies the filter explicitly first.
if (paint.getAlphaf() < 1.f || paint.getColorFilter() || paint.getMaskFilter()) {
return false;
}
// Currently we can only use the filterSprite code if we are clipped to the bitmap's bounds.
// Once we can filter and the filter will return a result larger than itself, we should be
// able to remove this constraint.
// skbug.com/4526
//
SkPoint pt;
ctm.mapXY(x, y, &pt);
SkIRect ir = SkIRect::MakeXYWH(SkScalarRoundToInt(pt.x()), SkScalarRoundToInt(pt.y()), w, h);
return ir.contains(fMCRec->fRasterClip.getBounds());
}
// Given storage for a real paint, and an optional paint parameter, clean-up the param (if non-null)
// given the drawing semantics for drawImage/bitmap (skbug.com/7804) and return it, or the original
// null.
static const SkPaint* init_image_paint(SkPaint* real, const SkPaint* paintParam) {
if (paintParam) {
*real = *paintParam;
real->setStyle(SkPaint::kFill_Style);
real->setPathEffect(nullptr);
paintParam = real;
}
return paintParam;
}
void SkCanvas::onDrawImage(const SkImage* image, SkScalar x, SkScalar y, const SkPaint* paint) {
SkPaint realPaint;
paint = init_image_paint(&realPaint, paint);
SkRect bounds = SkRect::MakeXYWH(x, y,
SkIntToScalar(image->width()), SkIntToScalar(image->height()));
if (nullptr == paint || paint->canComputeFastBounds()) {
SkRect tmp = bounds;
if (paint) {
paint->computeFastBounds(tmp, &tmp);
}
if (this->quickReject(tmp)) {
return;
}
}
// At this point we need a real paint object. If the caller passed null, then we should
// use realPaint (in its default state). If the caller did pass a paint, then we have copied
// (and modified) it in realPaint. Thus either way, "realPaint" is what we want to use.
paint = &realPaint;
sk_sp<SkSpecialImage> special;
bool drawAsSprite = this->canDrawBitmapAsSprite(x, y, image->width(), image->height(),
*paint);
if (drawAsSprite && paint->getImageFilter()) {
special = this->getDevice()->makeSpecial(image);
if (!special) {
drawAsSprite = false;
}
}
DRAW_BEGIN_DRAWBITMAP(*paint, drawAsSprite, &bounds)
while (iter.next()) {
const SkPaint& pnt = draw.paint();
if (special) {
SkPoint pt;
iter.fDevice->localToDevice().mapXY(x, y, &pt);
iter.fDevice->drawSpecial(special.get(),
SkScalarRoundToInt(pt.fX),
SkScalarRoundToInt(pt.fY), pnt,
nullptr, SkMatrix::I());
} else {
iter.fDevice->drawImageRect(
image, nullptr, SkRect::MakeXYWH(x, y, image->width(), image->height()), pnt,
kStrict_SrcRectConstraint);
}
}
DRAW_END
}
void SkCanvas::onDrawImageRect(const SkImage* image, const SkRect* src, const SkRect& dst,
const SkPaint* paint, SrcRectConstraint constraint) {
SkPaint realPaint;
paint = init_image_paint(&realPaint, paint);
if (nullptr == paint || paint->canComputeFastBounds()) {
SkRect storage = dst;
if (paint) {
paint->computeFastBounds(dst, &storage);
}
if (this->quickReject(storage)) {
return;
}
}
paint = &realPaint;
DRAW_BEGIN_CHECK_COMPLETE_OVERWRITE(*paint, &dst, image->isOpaque())
while (iter.next()) {
iter.fDevice->drawImageRect(image, src, dst, draw.paint(), constraint);
}
DRAW_END
}
void SkCanvas::onDrawImageNine(const SkImage* image, const SkIRect& center, const SkRect& dst,
const SkPaint* paint) {
SkPaint realPaint;
paint = init_image_paint(&realPaint, paint);
if (nullptr == paint || paint->canComputeFastBounds()) {
SkRect storage;
if (this->quickReject(paint ? paint->computeFastBounds(dst, &storage) : dst)) {
return;
}
}
paint = &realPaint;
DRAW_BEGIN(*paint, &dst)
while (iter.next()) {
iter.fDevice->drawImageNine(image, center, dst, draw.paint());
}
DRAW_END
}
void SkCanvas::onDrawImageLattice(const SkImage* image, const Lattice& lattice, const SkRect& dst,
const SkPaint* paint) {
SkPaint realPaint;
paint = init_image_paint(&realPaint, paint);
if (nullptr == paint || paint->canComputeFastBounds()) {
SkRect storage;
if (this->quickReject(paint ? paint->computeFastBounds(dst, &storage) : dst)) {
return;
}
}
paint = &realPaint;
DRAW_BEGIN(*paint, &dst)
while (iter.next()) {
iter.fDevice->drawImageLattice(image, lattice, dst, draw.paint());
}
DRAW_END
}
void SkCanvas::onDrawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
const SkPaint& paint) {
SkRect storage;
const SkRect* bounds = nullptr;
if (paint.canComputeFastBounds()) {
storage = blob->bounds().makeOffset(x, y);
SkRect tmp;
if (this->quickReject(paint.computeFastBounds(storage, &tmp))) {
return;
}
bounds = &storage;
}
// We cannot filter in the looper as we normally do, because the paint is
// incomplete at this point (text-related attributes are embedded within blob run paints).
DRAW_BEGIN(paint, bounds)
while (iter.next()) {
fScratchGlyphRunBuilder->drawTextBlob(draw.paint(), *blob, {x, y}, iter.fDevice);
}
DRAW_END
}
// These call the (virtual) onDraw... method
void SkCanvas::drawSimpleText(const void* text, size_t byteLength, SkTextEncoding encoding,
SkScalar x, SkScalar y, const SkFont& font, const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
if (byteLength) {
sk_msan_assert_initialized(text, SkTAddOffset<const void>(text, byteLength));
this->drawTextBlob(SkTextBlob::MakeFromText(text, byteLength, font, encoding), x, y, paint);
}
}
void SkCanvas::drawTextBlob(const SkTextBlob* blob, SkScalar x, SkScalar y,
const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
RETURN_ON_NULL(blob);
RETURN_ON_FALSE(blob->bounds().makeOffset(x, y).isFinite());
// Overflow if more than 2^21 glyphs stopping a buffer overflow latter in the stack.
// See chromium:1080481
// TODO: can consider unrolling a few at a time if this limit becomes a problem.
int totalGlyphCount = 0;
constexpr int kMaxGlyphCount = 1 << 21;
SkTextBlob::Iter i(*blob);
SkTextBlob::Iter::Run r;
while (i.next(&r)) {
int glyphsLeft = kMaxGlyphCount - totalGlyphCount;
RETURN_ON_FALSE(r.fGlyphCount <= glyphsLeft);
totalGlyphCount += r.fGlyphCount;
}
this->onDrawTextBlob(blob, x, y, paint);
}
void SkCanvas::onDrawVerticesObject(const SkVertices* vertices, SkBlendMode bmode,
const SkPaint& paint) {
DRAW_BEGIN(paint, nullptr)
while (iter.next()) {
// In the common case of one iteration we could std::move vertices here.
iter.fDevice->drawVertices(vertices, bmode, draw.paint());
}
DRAW_END
}
void SkCanvas::drawPatch(const SkPoint cubics[12], const SkColor colors[4],
const SkPoint texCoords[4], SkBlendMode bmode,
const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
if (nullptr == cubics) {
return;
}
this->onDrawPatch(cubics, colors, texCoords, bmode, paint);
}
void SkCanvas::onDrawPatch(const SkPoint cubics[12], const SkColor colors[4],
const SkPoint texCoords[4], SkBlendMode bmode,
const SkPaint& paint) {
// Since a patch is always within the convex hull of the control points, we discard it when its
// bounding rectangle is completely outside the current clip.
SkRect bounds;
bounds.setBounds(cubics, SkPatchUtils::kNumCtrlPts);
if (this->quickReject(bounds)) {
return;
}
DRAW_BEGIN(paint, nullptr)
while (iter.next()) {
iter.fDevice->drawPatch(cubics, colors, texCoords, bmode, paint);
}
DRAW_END
}
void SkCanvas::drawDrawable(SkDrawable* dr, SkScalar x, SkScalar y) {
#ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
TRACE_EVENT0("skia", TRACE_FUNC);
#endif
RETURN_ON_NULL(dr);
if (x || y) {
SkMatrix matrix = SkMatrix::Translate(x, y);
this->onDrawDrawable(dr, &matrix);
} else {
this->onDrawDrawable(dr, nullptr);
}
}
void SkCanvas::drawDrawable(SkDrawable* dr, const SkMatrix* matrix) {
#ifndef SK_BUILD_FOR_ANDROID_FRAMEWORK
TRACE_EVENT0("skia", TRACE_FUNC);
#endif
RETURN_ON_NULL(dr);
if (matrix && matrix->isIdentity()) {
matrix = nullptr;
}
this->onDrawDrawable(dr, matrix);
}
void SkCanvas::onDrawDrawable(SkDrawable* dr, const SkMatrix* matrix) {
// drawable bounds are no longer reliable (e.g. android displaylist)
// so don't use them for quick-reject
this->getDevice()->drawDrawable(dr, matrix, this);
}
void SkCanvas::onDrawAtlas(const SkImage* atlas, const SkRSXform xform[], const SkRect tex[],
const SkColor colors[], int count, SkBlendMode bmode,
const SkRect* cull, const SkPaint* paint) {
if (cull && this->quickReject(*cull)) {
return;
}
SkPaint pnt;
if (paint) {
pnt = *paint;
}
DRAW_BEGIN(pnt, nullptr)
while (iter.next()) {
iter.fDevice->drawAtlas(atlas, xform, tex, colors, count, bmode, pnt);
}
DRAW_END
}
void SkCanvas::onDrawAnnotation(const SkRect& rect, const char key[], SkData* value) {
SkASSERT(key);
SkPaint paint;
DRAW_BEGIN(paint, nullptr)
while (iter.next()) {
iter.fDevice->drawAnnotation(rect, key, value);
}
DRAW_END
}
void SkCanvas::onDrawEdgeAAQuad(const SkRect& r, const SkPoint clip[4], QuadAAFlags edgeAA,
const SkColor4f& color, SkBlendMode mode) {
SkASSERT(r.isSorted());
// If this used a paint, it would be a filled color with blend mode, which does not
// need to use an autodraw loop, so use SkDrawIter directly.
if (this->quickReject(r)) {
return;
}
this->predrawNotify(&r, nullptr, false);
SkDrawIter iter(this);
while(iter.next()) {
iter.fDevice->drawEdgeAAQuad(r, clip, edgeAA, color, mode);
}
}
void SkCanvas::onDrawEdgeAAImageSet(const ImageSetEntry imageSet[], int count,
const SkPoint dstClips[], const SkMatrix preViewMatrices[],
const SkPaint* paint, SrcRectConstraint constraint) {
if (count <= 0) {
// Nothing to draw
return;
}
SkPaint realPaint;
init_image_paint(&realPaint, paint);
// We could calculate the set's dstRect union to always check quickReject(), but we can't reject
// individual entries and Chromium's occlusion culling already makes it likely that at least one
// entry will be visible. So, we only calculate the draw bounds when it's trivial (count == 1),
// or we need it for the autolooper (since it greatly improves image filter perf).
bool needsAutoLooper = needs_autodrawlooper(this, realPaint);
bool setBoundsValid = count == 1 || needsAutoLooper;
SkRect setBounds = imageSet[0].fDstRect;
if (imageSet[0].fMatrixIndex >= 0) {
// Account for the per-entry transform that is applied prior to the CTM when drawing
preViewMatrices[imageSet[0].fMatrixIndex].mapRect(&setBounds);
}
if (needsAutoLooper) {
for (int i = 1; i < count; ++i) {
SkRect entryBounds = imageSet[i].fDstRect;
if (imageSet[i].fMatrixIndex >= 0) {
preViewMatrices[imageSet[i].fMatrixIndex].mapRect(&entryBounds);
}
setBounds.joinPossiblyEmptyRect(entryBounds);
}
}
// If we happen to have the draw bounds, though, might as well check quickReject().
if (setBoundsValid && realPaint.canComputeFastBounds()) {
SkRect tmp;
if (this->quickReject(realPaint.computeFastBounds(setBounds, &tmp))) {
return;
}
}
if (needsAutoLooper) {
SkASSERT(setBoundsValid);
DRAW_BEGIN(realPaint, &setBounds)
while (iter.next()) {
iter.fDevice->drawEdgeAAImageSet(
imageSet, count, dstClips, preViewMatrices, draw.paint(), constraint);
}
DRAW_END
} else {
this->predrawNotify();
SkDrawIter iter(this);
while(iter.next()) {
iter.fDevice->drawEdgeAAImageSet(
imageSet, count, dstClips, preViewMatrices, realPaint, constraint);
}
}
}
//////////////////////////////////////////////////////////////////////////////
// These methods are NOT virtual, and therefore must call back into virtual
// methods, rather than actually drawing themselves.
//////////////////////////////////////////////////////////////////////////////
void SkCanvas::drawColor(SkColor c, SkBlendMode mode) {
SkPaint paint;
paint.setColor(c);
paint.setBlendMode(mode);
this->drawPaint(paint);
}
void SkCanvas::drawPoint(SkScalar x, SkScalar y, const SkPaint& paint) {
const SkPoint pt = { x, y };
this->drawPoints(kPoints_PointMode, 1, &pt, paint);
}
void SkCanvas::drawLine(SkScalar x0, SkScalar y0, SkScalar x1, SkScalar y1, const SkPaint& paint) {
SkPoint pts[2];
pts[0].set(x0, y0);
pts[1].set(x1, y1);
this->drawPoints(kLines_PointMode, 2, pts, paint);
}
void SkCanvas::drawCircle(SkScalar cx, SkScalar cy, SkScalar radius, const SkPaint& paint) {
if (radius < 0) {
radius = 0;
}
SkRect r;
r.setLTRB(cx - radius, cy - radius, cx + radius, cy + radius);
this->drawOval(r, paint);
}
void SkCanvas::drawRoundRect(const SkRect& r, SkScalar rx, SkScalar ry,
const SkPaint& paint) {
if (rx > 0 && ry > 0) {
SkRRect rrect;
rrect.setRectXY(r, rx, ry);
this->drawRRect(rrect, paint);
} else {
this->drawRect(r, paint);
}
}
void SkCanvas::drawArc(const SkRect& oval, SkScalar startAngle,
SkScalar sweepAngle, bool useCenter,
const SkPaint& paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
if (oval.isEmpty() || !sweepAngle) {
return;
}
this->onDrawArc(oval, startAngle, sweepAngle, useCenter, paint);
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_DISABLE_SKPICTURE
void SkCanvas::drawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint) {}
void SkCanvas::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
const SkPaint* paint) {}
#else
/**
* This constant is trying to balance the speed of ref'ing a subpicture into a parent picture,
* against the playback cost of recursing into the subpicture to get at its actual ops.
*
* For now we pick a conservatively small value, though measurement (and other heuristics like
* the type of ops contained) may justify changing this value.
*/
#define kMaxPictureOpsToUnrollInsteadOfRef 1
void SkCanvas::drawPicture(const SkPicture* picture, const SkMatrix* matrix, const SkPaint* paint) {
TRACE_EVENT0("skia", TRACE_FUNC);
RETURN_ON_NULL(picture);
if (matrix && matrix->isIdentity()) {
matrix = nullptr;
}
if (picture->approximateOpCount() <= kMaxPictureOpsToUnrollInsteadOfRef) {
SkAutoCanvasMatrixPaint acmp(this, matrix, paint, picture->cullRect());
picture->playback(this);
} else {
this->onDrawPicture(picture, matrix, paint);
}
}
void SkCanvas::onDrawPicture(const SkPicture* picture, const SkMatrix* matrix,
const SkPaint* paint) {
if (!paint || paint->canComputeFastBounds()) {
SkRect bounds = picture->cullRect();
if (paint) {
paint->computeFastBounds(bounds, &bounds);
}
if (matrix) {
matrix->mapRect(&bounds);
}
if (this->quickReject(bounds)) {
return;
}
}
SkAutoCanvasMatrixPaint acmp(this, matrix, paint, picture->cullRect());
picture->playback(this);
}
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
SkCanvas::LayerIter::LayerIter(SkCanvas* canvas) {
static_assert(sizeof(fStorage) >= sizeof(SkDrawIter), "fStorage_too_small");
SkASSERT(canvas);
fImpl = new (fStorage) SkDrawIter(canvas);
// This advances the base iterator to the first device and caches its origin,
// correctly handling the case where there are no devices.
this->next();
}
SkCanvas::LayerIter::~LayerIter() {
fImpl->~SkDrawIter();
}
void SkCanvas::LayerIter::next() {
fDone = !fImpl->next();
if (!fDone) {
// Cache the device origin. LayerIter is only used in Android, which doesn't use image
// filters, so its devices will always be able to report the origin exactly.
fDeviceOrigin = fImpl->fDevice->getOrigin();
}
}
SkBaseDevice* SkCanvas::LayerIter::device() const {
return fImpl->fDevice;
}
const SkMatrix& SkCanvas::LayerIter::matrix() const {
return fImpl->fDevice->localToDevice();
}
const SkPaint& SkCanvas::LayerIter::paint() const {
const SkPaint* paint = fImpl->getPaint();
if (nullptr == paint) {
paint = &fDefaultPaint;
}
return *paint;
}
SkIRect SkCanvas::LayerIter::clipBounds() const {
return fImpl->fDevice->getGlobalBounds();
}
int SkCanvas::LayerIter::x() const { return fDeviceOrigin.fX; }
int SkCanvas::LayerIter::y() const { return fDeviceOrigin.fY; }
///////////////////////////////////////////////////////////////////////////////
SkCanvas::ImageSetEntry::ImageSetEntry() = default;
SkCanvas::ImageSetEntry::~ImageSetEntry() = default;
SkCanvas::ImageSetEntry::ImageSetEntry(const ImageSetEntry&) = default;
SkCanvas::ImageSetEntry& SkCanvas::ImageSetEntry::operator=(const ImageSetEntry&) = default;
SkCanvas::ImageSetEntry::ImageSetEntry(sk_sp<const SkImage> image, const SkRect& srcRect,
const SkRect& dstRect, int matrixIndex, float alpha,
unsigned aaFlags, bool hasClip)
: fImage(std::move(image))
, fSrcRect(srcRect)
, fDstRect(dstRect)
, fMatrixIndex(matrixIndex)
, fAlpha(alpha)
, fAAFlags(aaFlags)
, fHasClip(hasClip) {}
SkCanvas::ImageSetEntry::ImageSetEntry(sk_sp<const SkImage> image, const SkRect& srcRect,
const SkRect& dstRect, float alpha, unsigned aaFlags)
: fImage(std::move(image))
, fSrcRect(srcRect)
, fDstRect(dstRect)
, fAlpha(alpha)
, fAAFlags(aaFlags) {}
///////////////////////////////////////////////////////////////////////////////
std::unique_ptr<SkCanvas> SkCanvas::MakeRasterDirect(const SkImageInfo& info, void* pixels,
size_t rowBytes, const SkSurfaceProps* props) {
if (!SkSurfaceValidateRasterInfo(info, rowBytes)) {
return nullptr;
}
SkBitmap bitmap;
if (!bitmap.installPixels(info, pixels, rowBytes)) {
return nullptr;
}
return props ?
std::make_unique<SkCanvas>(bitmap, *props) :
std::make_unique<SkCanvas>(bitmap);
}
///////////////////////////////////////////////////////////////////////////////
SkNoDrawCanvas::SkNoDrawCanvas(int width, int height)
: INHERITED(SkIRect::MakeWH(width, height)) {}
SkNoDrawCanvas::SkNoDrawCanvas(const SkIRect& bounds)
: INHERITED(bounds) {}
SkNoDrawCanvas::SkNoDrawCanvas(sk_sp<SkBaseDevice> device)
: INHERITED(device) {}
SkCanvas::SaveLayerStrategy SkNoDrawCanvas::getSaveLayerStrategy(const SaveLayerRec& rec) {
(void)this->INHERITED::getSaveLayerStrategy(rec);
return kNoLayer_SaveLayerStrategy;
}
bool SkNoDrawCanvas::onDoSaveBehind(const SkRect*) {
return false;
}
///////////////////////////////////////////////////////////////////////////////
static_assert((int)SkRegion::kDifference_Op == (int)kDifference_SkClipOp, "");
static_assert((int)SkRegion::kIntersect_Op == (int)kIntersect_SkClipOp, "");
static_assert((int)SkRegion::kUnion_Op == (int)kUnion_SkClipOp, "");
static_assert((int)SkRegion::kXOR_Op == (int)kXOR_SkClipOp, "");
static_assert((int)SkRegion::kReverseDifference_Op == (int)kReverseDifference_SkClipOp, "");
static_assert((int)SkRegion::kReplace_Op == (int)kReplace_SkClipOp, "");
///////////////////////////////////////////////////////////////////////////////////////////////////
SkRasterHandleAllocator::Handle SkCanvas::accessTopRasterHandle() const {
if (fAllocator && fMCRec->fTopLayer->fDevice) {
const auto& dev = fMCRec->fTopLayer->fDevice;
SkRasterHandleAllocator::Handle handle = dev->getRasterHandle();
SkIRect clip = dev->devClipBounds();
if (!clip.intersect({0, 0, dev->width(), dev->height()})) {
clip.setEmpty();
}
fAllocator->updateHandle(handle, dev->localToDevice(), clip);
return handle;
}
return nullptr;
}
static bool install(SkBitmap* bm, const SkImageInfo& info,
const SkRasterHandleAllocator::Rec& rec) {
return bm->installPixels(info, rec.fPixels, rec.fRowBytes, rec.fReleaseProc, rec.fReleaseCtx);
}
SkRasterHandleAllocator::Handle SkRasterHandleAllocator::allocBitmap(const SkImageInfo& info,
SkBitmap* bm) {
SkRasterHandleAllocator::Rec rec;
if (!this->allocHandle(info, &rec) || !install(bm, info, rec)) {
return nullptr;
}
return rec.fHandle;
}
std::unique_ptr<SkCanvas>
SkRasterHandleAllocator::MakeCanvas(std::unique_ptr<SkRasterHandleAllocator> alloc,
const SkImageInfo& info, const Rec* rec) {
if (!alloc || !SkSurfaceValidateRasterInfo(info, rec ? rec->fRowBytes : kIgnoreRowBytesValue)) {
return nullptr;
}
SkBitmap bm;
Handle hndl;
if (rec) {
hndl = install(&bm, info, *rec) ? rec->fHandle : nullptr;
} else {
hndl = alloc->allocBitmap(info, &bm);
}
return hndl ? std::unique_ptr<SkCanvas>(new SkCanvas(bm, std::move(alloc), hndl)) : nullptr;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
|
; A021748: Decimal expansion of 1/744.
; 0,0,1,3,4,4,0,8,6,0,2,1,5,0,5,3,7,6,3,4,4,0,8,6,0,2,1,5,0,5,3,7,6,3,4,4,0,8,6,0,2,1,5,0,5,3,7,6,3,4,4,0,8,6,0,2,1,5,0,5,3,7,6,3,4,4,0,8,6,0,2,1,5,0,5,3,7,6,3,4,4,0,8,6,0,2,1,5,0,5,3,7,6,3,4,4,0,8,6
add $0,1
mov $1,10
pow $1,$0
mul $1,5
div $1,3720
mod $1,10
mov $0,$1
|
; A098790: a(n) = 2*a(n-1) + a(n-2) + 1, a(0) = 1, a(1) = 2.
; Submitted by Christian Krause
; 1,2,6,15,37,90,218,527,1273,3074,7422,17919,43261,104442,252146,608735,1469617,3547970,8565558,20679087,49923733,120526554,290976842,702480239,1695937321,4094354882,9884647086,23863649055,57611945197,139087539450,335787024098,810661587647,1957110199393,4724881986434,11406874172262,27538630330959,66484134834181,160506899999322,387497934832826,935502769664975,2258503474162777,5452509717990530,13163522910143838,31779555538278207,76722633986700253,185224823511678714,447172281010057682
mov $2,1
lpb $0
sub $0,1
add $4,1
mov $3,$4
mov $4,$2
add $2,$3
add $4,$2
lpe
mov $0,$2
|
;
; Timer handlers for Shock Lobster
;
; Copyright 2021 Dave VanEe
;
; This software is provided 'as-is', without any express or implied
; warranty. In no event will the authors be held liable for any damages
; arising from the use of this software.
;
; Permission is granted to anyone to use this software for any purpose,
; including commercial applications, and to alter it and redistribute it
; freely, subject to the following restrictions:
;
; 1. The origin of this software must not be misrepresented; you must not
; claim that you wrote the original software. If you use this software
; in a product, an acknowledgment in the product documentation would be
; appreciated but is not required.
; 2. Altered source versions must be plainly marked as such, and must not be
; misrepresented as being the original software.
; 3. This notice may not be removed or altered from any source distribution.
;
; These are the handlers for when timers tick/elapse
; Note: These are jumped to using `de`, and so we can safely destroy
; `de` without pushing/popping it. `hl` and `bc` must be protected though.
; Note: The timer updating code is heavily redundant and could easily be
; converted into a call, but we can spare the ROM and save the call time.
SECTION "Timer Handlers", ROM0
; Note: A physics delta of $10 causes things to move at 60fps. A value of $08
; would result in objects updating at 30fps, and $20 would still update
; at 60fps, but would update twice per frame. It's essentially a 4.4 fixed
; point physics update value, which is used to 'smoothly' scale the
; game speed to increase difficulty.
; Note: The engine seems to be able to handle things up to $F0, at which
; point things go sideways and it starts feeling like slow motion before
; falling apart when it hits zero (if un-capped).
; The max delta is meant to prevent the engine from falling apart, as we
; expect players to mess up well before then.
DEF MAX_PHYSICS_DELTA EQU $E0 ; Maximum physics delta
SpeedTimerTick::
; Speed up physics updates every N seconds, up to a maximum speed
push hl
dec l ; `hl` starts as wSpeedTimer+4
ld a, [hl] ; get seconds before speed increase
or a
jr nz, .noSpeedIncrease
push hl ; hl->de optimized for size
pop de
ld hl, wSpeedIncreaseSeconds
ld a, [hli]
ld [de], a ; reset delay until next speed increase
ld a, [hl] ; get wPhysicsUpdateDelta
cp MAX_PHYSICS_DELTA
jr z, .noSpeedIncrease
inc a
ld [hl], a
; Trick code we return to so it doesn't zero the frame counter
; and this timer can keep running
ld b, 1
.noSpeedIncrease
; Since we bypass the `ld b,1` when we hit max speed the speed timer
; will expire and stop running entirely
pop hl
ret
ShockTimerTick::
push hl
push bc
dec l ; `hl` starts as wShockTimer+4
ld a, [hl]
; Apply damage at 6/3/0 seconds remaining
cp 6
jr z, .damageTick
cp 3
jr z, .damageTick
or a
jr nz, .noDamage
.damageTick
ld a, [wShockDamageTick]
ld e, 0 ; shock dots can't crit
call DealDamage
.noDamage
; Update timer numerical display
ld a, [wShockTimer+3] ; DealDamage trashes `hl` and this is faster than push/pop
or a
jr z, .timerdone
ld hl, SHOCK_TIME_TILEMAP
call bcd8bit_baa
add a ; double for 8x16 tile layout
add $80 ; add base tile offset
ld b, a
: ldh a, [rSTAT]
and STATF_BUSY
jr nz, :-
ld [hl], b
.timerdone
pop bc
pop hl
ret
ElectrifyTimerTick::
push hl
dec l ; `hl` starts as wElectrifyTimer+4
ld a, [hl]
push bc
.fakeTimerValue
and %00000001 ; Apply damage on even ticks
jr nz, .noDamage
; determine if ticks can crit
ld a, [wEnabledUpgrades]
and UPGRADEF_RESIDUAL_CHARGE
ld e, 0 ; setup values for non-critical tick
ld a, [wElectrifyDamageTick]
jr z, .noCritTicks
ld a, [wCriticalThreshold]
ld e, a
call rand
cp e ; set flag for crit/non-crit
ld e, 0 ; setup values for non-critical tick
ld a, [wElectrifyDamageTick]
jr c, .noCritical
inc e ; replace with critical values
ld a, [wElectrifyDamageCrit]
.noCritTicks
.noCritical
call DealDamage
.noDamage
call .refreshElectrifyTimerDisplay
.generalTimerDone
pop bc
pop hl
ret
; This is broken out into a call so we can also call it after
; the refresh upgrade extends the duration. Sadly, due to the
; breaking of this out we can't jump to it and rely on it
; for the final pops/return like before, so several of the
; other timers now call this then jump to generalTimerDone.
.refreshElectrifyTimerDisplay
; Update timer numerical display
ld a, [wElectrifyTimer+3]
or a
jr z, .electrifyDone
ld hl, ELECTRIFY_TIME_TILEMAP
.generalTwoDigitTimer
call bcd8bit_baa
ld c, a
and $0F
add a ; double for 8x16 tile layout
add $80 ; add base tile offset
ld b, a
: ldh a, [rSTAT]
and STATF_BUSY
jr nz, :-
ld a, b
ld [hld], a
ld a, c
swap a
and $0F
jr z, .tensZero
add a ; double for 8x16 tile layout
add $80 ; add base tile offset
.tensZero
ld b, a
: ldh a, [rSTAT]
and STATF_BUSY
jr nz, :-
ld [hl], b
ret
.electrifyDone
ld [wRefreshCounter], a ; Clear refresh counter for next electrify
ret
FocusBuffTimerTick::
push hl
push bc
dec l ; `hl` starts as wFocusBuffTimer+4
ld a, [hl]
or a
jr z, .timerDone
ld hl, FOCUS_BUFF_TIME_TILEMAP
call ElectrifyTimerTick.generalTwoDigitTimer
jr ElectrifyTimerTick.generalTimerDone
.timerDone
; Buff expired, clear flag
xor a
ldh [hFocusBuffActive], a
; Activate focus cooldown
ld a, FRAME_COUNTER_MAX
ld [wFocusCooldownTimer], a
ld a, COOLDOWN_FOCUS
ld [wFocusCooldownTimer+3], a
pop bc
pop hl
ret
EmpowerTimerTick::
push hl
push bc
dec l ; `hl` starts as wEmpowerTimer+4
ld a, [hl]
or a
jr z, ElectrifyTimerTick.generalTimerDone
ld hl, EMPOWER_TIME_TILEMAP
call ElectrifyTimerTick.generalTwoDigitTimer
jr ElectrifyTimerTick.generalTimerDone
InvigorateTimerTick::
push hl
push bc
dec l ; `hl` starts as wInvigorateTimer+4
ld a, [hl]
or a
jr z, ElectrifyTimerTick.generalTimerDone
ld hl, INVIGORATE_TIME_TILEMAP
call ElectrifyTimerTick.generalTwoDigitTimer
jr ElectrifyTimerTick.generalTimerDone
FocusCooldownTimerTick:
push hl
push bc
push de
; Update timer numerical display
ld a, [wFocusCooldownTimer+3]
or a
jr z, .timerDone
call bcd8bit_baa
ld c, a
and $0F
add a ; double for 8x16 tile layout
add $80 ; add base tile offset
ld d, a
ld hl, FOCUS_COOL_TIME_TILEMAP
: ldh a, [rSTAT]
and STATF_BUSY
jr nz, :-
ld a, d
ld [hld], a
; check hundreds first
ld a, b
and %00000011 ; upper 6 bits are undefined
ld b, a
jr nz, .haveHundreds
ld a, c
and $F0
jr z, .storeFinal ; no hundreds or tens, done this entry
.haveHundreds
ld a, c
swap a
and $0F
add a ; double for 8x16 tile layout
add $80 ; add base tile offset
ld d, a
: ldh a, [rSTAT]
and STATF_BUSY
jr nz, :-
ld [hl], d
dec l
; hundreds digit
ld a, b
or a
jr z, .noHundreds
add a ; double for 8x16 tile layout
add $80 ; add base tile offset
.storeFinal
.noHundreds
ld d, a
: ldh a, [rSTAT]
and STATF_BUSY
jr nz, :-
ld [hl], d
; Since we'll never drop from 3 to 1 digit directly, there's no need to
; clear up both trailing digits if the tens/hundreds are both zero.
.timerDone
pop de
pop bc
pop hl
ret
|
; A108924: J(n)^2+J(n+1)^2, with J(n) the Jacobsthal number A001045(n).
; 1,2,10,34,146,562,2290,9074,36466,145522,582770,2329714,9321586,37280882,149134450,596515954,2386107506,9544342642,38177545330,152709831794,610840026226,2443358706802,9773437623410,39093744901234
mul $0,2
mov $2,1
mov $5,1
mov $6,1
lpb $0
sub $0,2
mov $1,2
add $1,$2
sub $1,1
mul $6,$1
mov $3,$6
add $4,2
mul $4,2
mov $2,$4
sub $3,1
add $4,$3
add $4,$3
mov $5,$6
mov $6,2
lpe
add $0,$5
mov $1,$0
|
INCLUDE "graphics/grafix.inc"
XLIB setxy
LIB l_cmp
XREF COORDS
;
; $Id: w_setxy.asm,v 1.1 2008/07/17 15:39:56 stefano Exp $
;
; ******************************************************************
;
; Move current pixel coordinate to (x0,y0). Only legal coordinates
; are accepted.
;
; Wide resolution (WORD based parameters) version by Stefano Bodrato
;
; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995
;
; X-range is always legal (0-255). Y-range must be 0 - 63.
;
; in: hl,de = (x,y) coordinate
;
; registers changed after return:
; ..bcdehl/ixiy same
; af....../.... different
;
.setxy
pop bc
pop de
pop hl
push hl
push de
push bc
push hl
ld hl,maxy
call l_cmp
pop hl
ret nc ; Return if Y overflows
push de
ld de,maxx
call l_cmp
pop de
ret c ; Return if X overflows
ld (COORDS),hl ; store X
ld (COORDS+2),de ; store Y: COORDS must be 2 bytes wider
ret
|
SECTION code_clib
SECTION code_l
PUBLIC l_fast_atoul
EXTERN l_fast_atou, error_mc
l_fast_atoul:
; ascii buffer to unsigned long conversion
; whitespace is not skipped
; char consumption stops on overflow
;
; enter : de = char *
;
; exit : bc = & next char to interpret in buffer
; dehl = unsigned result (0 on invalid input, and $ffffffff on overflow)
; carry set on unsigned overflow
;
; uses : af, bc, de, hl
call l_fast_atou ; try to do it in 16 bits
ld c,e
ld b,d
ld de,0
ret nc ; was 16-bit
ld e,a ; e = overflow from 16 bit result
; 32 bit loop
loop:
ld a,(bc)
; inlined isdigit
sub '0'
ccf
ret nc
cp 10
ret nc
inc bc
; dehl *= 10
add hl,hl
rl e
rl d
jr c, oflow_0
push de
push hl ; save dehl*2
add hl,hl
rl e
rl d
jr c, oflow_1
add hl,hl
rl e
rl d
jr c, oflow_1
ex de,hl
ex (sp),hl
add hl,de
pop de
ex (sp),hl
adc hl,de
ex de,hl
pop hl
jr c, oflow_0
; dehl += digit
add a,l
ld l,a
jr nc, loop
inc h
jr nz, loop
inc e
jr nz, loop
inc d
jr nz, loop
; unsigned overflow has occurred
dec de
dec h
ld l,h
ret
oflow_1:
pop de
pop de ; junk two items on stack
oflow_0:
ld de,$ffff
jp error_mc
|
; A097338: Positive integers n such that 2n-11 is prime.
; 7,8,9,11,12,14,15,17,20,21,24,26,27,29,32,35,36,39,41,42,45,47,50,54,56,57,59,60,62,69,71,74,75,80,81,84,87,89,92,95,96,101,102,104,105,111,117,119,120,122,125,126,131,134,137,140,141,144,146,147,152,159,161,162,164,171,174,179,180,182,185,189,192,195,197,200,204,206,210,215,216,221,222,225,227,230,234,236,237,239,245,249,251,255,257,260,266,267,276,279
seq $0,98090 ; Numbers k such that 2k-3 is prime.
add $0,4
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r14
push %r15
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x1320d, %r12
clflush (%r12)
nop
nop
nop
nop
cmp $14392, %r15
mov $0x6162636465666768, %rsi
movq %rsi, %xmm6
movups %xmm6, (%r12)
sub $41987, %r12
lea addresses_UC_ht+0xcc37, %rsi
lea addresses_D_ht+0x5b6f, %rdi
nop
nop
nop
add $58056, %r14
mov $75, %rcx
rep movsw
nop
inc %r12
lea addresses_WT_ht+0x12ac5, %rsi
lea addresses_normal_ht+0x122c5, %rdi
and %r11, %r11
mov $101, %rcx
rep movsl
nop
nop
and $12777, %r15
lea addresses_WT_ht+0xe6c5, %rdi
nop
add $49402, %r15
mov $0x6162636465666768, %r11
movq %r11, %xmm5
vmovups %ymm5, (%rdi)
and $53097, %rdi
lea addresses_A_ht+0x1cac5, %r12
clflush (%r12)
nop
nop
nop
nop
nop
add $50178, %rcx
movl $0x61626364, (%r12)
nop
xor $45267, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %r15
pop %r14
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r14
push %r9
push %rbp
push %rdi
push %rdx
// Store
lea addresses_WT+0x92c5, %r9
nop
nop
add %rbp, %rbp
movw $0x5152, (%r9)
nop
nop
nop
nop
add $35122, %rbp
// Store
lea addresses_UC+0x6ffd, %r14
nop
nop
nop
nop
nop
add %rdx, %rdx
mov $0x5152535455565758, %r12
movq %r12, (%r14)
nop
nop
xor $51943, %r14
// Store
lea addresses_PSE+0x10e8d, %r13
nop
nop
nop
nop
sub %rbp, %rbp
mov $0x5152535455565758, %r14
movq %r14, %xmm5
vmovups %ymm5, (%r13)
nop
nop
nop
and %r9, %r9
// Load
mov $0x383, %rdx
nop
nop
nop
nop
nop
and %r13, %r13
vmovups (%rdx), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $0, %xmm3, %rdi
nop
dec %r12
// Faulty Load
lea addresses_WT+0x92c5, %rdx
nop
nop
and %r14, %r14
movb (%rdx), %r12b
lea oracles, %rbp
and $0xff, %r12
shlq $12, %r12
mov (%rbp,%r12,1), %r12
pop %rdx
pop %rdi
pop %rbp
pop %r9
pop %r14
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'size': 8, 'AVXalign': True, 'NT': False, 'congruent': 3, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_P', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 4, 'AVXalign': False, 'NT': True, 'congruent': 11, 'same': False}}
{'52': 111}
52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52
*/
|
// ********************************************************
// * DEBUG FLAGS: *
// * *
// * - DEBUG_STAGE(INT STAGE_NUM): *
// * Enable Stage Select *
// * *
// * - DEBUG_SUBSTAGE(INT SUBSTAGE_NUM): *
// * Select Substage: Default 1 *
// * *
// * - DEBUG_INVENCIBILITY(BOOL ENABLE): *
// * Disable Player Collision: Default 0 *
// ********************************************************
define DEBUG(0)
define DEBUG_STAGE(0)
define DEBUG_SUBSTAGE(1)
define DEBUG_INVENCIBILITY(1)
// ********************************************************
// * SEGA GENESIS CONSTANTS: *
// * - VDP_DATA(INT OFFSET): *
// * Default SEGA GENESIS VDP Data Port *
// * *
// * - VDP_CTRL(INT OFFSET): *
// * Default SEGA GENESIS VDP Ctrl Port *
// * *
// * - M68K_RAM(INT OFFSET): *
// * Default SEGA GENESIS RAM Addr *
// ********************************************************
define VDP_DATA($00C00000)
define VDP_CTRL($00C00004)
define M68K_RAM($00FF0000)
// ********************************************************
// * GAME CONSTANTS: *
// * - GFX_FONT_SCORE(INT OFFSET): *
// * Default address of GAME FONT used in SCORE *
// * *
// * - GFX_FONT_DEFAULT(INT OFFSET): *
// * Default address of GAME FONT used in *
// * TITLE SCREEN, MENUS, COPYRIGHT *
// * *
// * - GFX_INGAME_FONT(INT OFFSET): *
// * Default address of GAME FONT used in INGAME *
// * messages like "STAGE 1 START" *
// * *
// * - STAGE_COUNTER(INT OFFSET): *
// * Count number of stages, used to know current *
// * stage on Stage Call Screen *
// ********************************************************
define GFX_FONT_SCORE($000ACA18)
define GFX_FONT_DEFAULT($000A8336)
define GFX_INGAME_FONT($00073B94)
define GFX_INTRO_FONT($000AC6CE)
define STAGE_COUNTER($FF90EC)
// ********************************************************
// * GAME FUNCTIONS: *
// * - loadCompressedGFXandSaveRegisters(INT OFFSET) *
// * *
// * - loadCompressedGFXandIncrementPointer(INT OFFSET) *
// * *
// * - loadCompressedGFX(INT OFFSET) *
// * *
// * - drawTilemap(INT OFFSET) *
// ********************************************************
define loadCompressedGFXandSaveRegisters($26E4)
define loadCompressedGFXandIncrementPointer($2628)
define loadCompressedGFX($262A)
define drawTilemap($AB7A) |
; A329684: Number of excursions of length n with Motzkin-steps forbidding all consecutive steps of length 2 except UD and HH.
; 1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
cmp $0,2
add $0,1
|
; A043554: Essentially same as A005811.
; 1,1,2,1,2,3,2,1,2,3,4,3,2,3,2,1,2,3,4,3,4,5,4,3,2,3,4,3
mov $2,$0
cmp $2,0
add $0,$2
cal $0,88748 ; a(n) = 1 + Sum_{k=0..n-1} 2 * A014577(k) - 1.
mov $1,$0
sub $1,1
|
psect atof_c,0,0,0,0,0
nam atof_c
ttl atof
atof: pshs u
ldu 4,s
leas -19,s
bra _2
_3 leau 1,u
_2 ldb 0,u
cmpb #32
beq _3
_4 ldb 0,u
cmpb #9
lbeq _3
_1 ldb 0,u
cmpb #45
bne _6
_5 ldd #1
bra _$1
_6 clra
clrb
_$1 std 7,s
_7 ldb 0,u
cmpb #45
beq _8
_10 ldb 0,u
cmpb #43
bne _9
_8 leau 1,u
_9 leax 11,s
pshs x
bsr _11
fdb 0,0,0,0
_11 puls x
lbsr _dmove
bra _13
_14 ldb 2,s
sex
pshs d
leax 13,s
pshs x
lbsr L0178
leas 4,s
leau 1,u
_13 ldb 0,u
stb 2,s
sex
leax _chcodes,y
leax d,x
ldb 0,x
clra
andb #8
bne _14
_12 clra
clrb
std 3,s
ldb 0,u
cmpb #46
bne _16
_15 leau 1,u
bra _18
_19 ldb 2,s
sex
pshs d
leax 13,s
pshs x
lbsr L0178
leas 4,s
leau 1,u
ldd 3,s
addd #1
std 3,s
_18 ldb 0,u
stb 2,s
sex
leax _chcodes,y
leax d,x
ldb 0,x
clra
andb #8
bne _19
_16
_17 leax 11,s
stx 0,s
ldd #184
ldx 0,s
stb 7,x
leax 11,s
pshs x
leax 13,s
pshs x
lbsr _dnorm
leas 2,s
lbsr _dmove
ldb 0,u
stb 2,s
cmpb #101
beq _20
_22 ldb 2,s
cmpb #69
lbne _21
_20 ldd #1
std 5,s
leau 1,u
ldb 0,u
cmpb #43
bne _24
_23 leau 1,u
bra _25
_24 ldb 0,u
cmpb #45
bne _27
_26 leau 1,u
clra
clrb
std 5,s
_25
_27 clra
clrb
bra _$2
_30 ldd 9,s
pshs d
ldd #10
lbsr ccmult
pshs d
ldb 4,s
sex
addd ,s++
addd #-48
_$2 std 9,s
_29 ldb ,u+
stb 2,s
sex
leax _chcodes,y
leax d,x
ldb 0,x
clra
andb #8
bne _30
_28 ldd 3,s
pshs d
ldd 7,s
beq _31
_32 ldd 11,s
nega
negb
sbca #0
bra _33
_31 ldd 11,s
_33 addd ,s++
std 3,s
_21 ldd 3,s
bge _35
_34 ldd 3,s
nega
negb
sbca #0
std 3,s
ldd #1
bra _$3
_35 clra
clrb
_$3 std 5,s
leax 11,s
pshs x
ldd 7,s
pshs d
ldd 7,s
pshs d
leax 17,s
lbsr _dstack
lbsr scale
leas 12,s
lbsr _dmove
_36 ldd 7,s
beq _38
_37 leax _flacc,y
pshs x
leax 13,s
lbsr _dneg
bra _$4
_38 leax _flacc,y
pshs x
leax 13,s
_$4 lbsr _dmove
_39 leas 19,s
puls u,pc
L0178 ldx 2,s
leas -8,s
ldd 5,x
lslb
rola
std 5,x
std 5,s
ldd 3,x
rolb
rola
std 3,x
std 3,s
ldd 1,x
rolb
rola
std 1,x
std 1,s
lda ,x
rola
sta ,x
sta ,s
asl 6,x
rol 5,x
rol 4,x
rol 3,x
rol 2,x
rol 1,x
rol ,x
lblo L0205
asl 6,x
rol 5,x
rol 4,x
rol 3,x
rol 2,x
rol 1,x
rol ,x
lblo L0205
ldd 5,x
addd 5,s
std 5,x
ldd 3,x
adcb 4,s
adca 3,s
std 3,x
ldd 1,x
adcb 2,s
adca 1,s
std 1,x
ldb ,x
adcb ,s
stb ,x
bcs L0205
ldb 13,s
andb #$0f
clra
addd 5,x
std 5,x
ldd #0
adcb 4,x
adca 3,x
std 3,x
ldd #0
adcb 2,x
adca 1,x
std 1,x
lda #0
adca ,x
sta ,x
bcs L0205
leas 8,s
clra
clrb
rts
L0205 ldd #1
leas 8,s
rts
ends
endsect
|
section .text
global _start ;must be declared for ld linker
_start: ;tell linker entry point
mov eax,'2' ;move 2 to eax register
sub eax, '0' ;set 2 as a signed integer
mov ebx, '3' ;move 3 to ebx register
sub ebx, '0' ;set 3 as a signed integer
add eax, ebx ;add ebx to eax
add eax, '0' ;convert from decimal to ASCII to print
;
mov [sum], eax ;set sum variable i.e. sum = eax
mov ecx,msg ;delacre msg as the message to write
mov edx, len ;set the message lenght
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
;
mov ecx,sum ;set sum as the message
mov edx, 1 ;set lenght 1 for len when printing
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
;
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
msg db "The sum is:", 0xA,0xD ;print msg to line(0xA) & carrige return(0xD)
len equ $ - msg ;the length of msg equates(equ) to len
segment .bss
sum resb 1 ;declare variable sum, reserving 4 byte's
|
;
; jquant.asm - sample data conversion and quantization (MMX)
;
; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB
;
; Based on
; x86 SIMD extension for IJG JPEG library
; Copyright (C) 1999-2006, MIYASAKA Masaru.
; For conditions of distribution and use, see copyright notice in jsimdext.inc
;
; This file should be assembled with NASM (Netwide Assembler),
; can *not* be assembled with Microsoft's MASM or any compatible
; assembler (including Borland's Turbo Assembler).
; NASM is available from http://nasm.sourceforge.net/ or
; http://sourceforge.net/project/showfiles.php?group_id=6208
;
; [TAB8]
%include "jsimdext.inc"
%include "jdct.inc"
; --------------------------------------------------------------------------
SECTION SEG_TEXT
BITS 32
;
; Load data into workspace, applying unsigned->signed conversion
;
; GLOBAL(void)
; jsimd_convsamp_mmx (JSAMPARRAY sample_data, JDIMENSION start_col,
; DCTELEM * workspace);
;
%define sample_data ebp+8 ; JSAMPARRAY sample_data
%define start_col ebp+12 ; JDIMENSION start_col
%define workspace ebp+16 ; DCTELEM * workspace
align 16
global EXTN(jsimd_convsamp_mmx)
EXTN(jsimd_convsamp_mmx):
push ebp
mov ebp,esp
push ebx
; push ecx ; need not be preserved
; push edx ; need not be preserved
push esi
push edi
pxor mm6,mm6 ; mm6=(all 0's)
pcmpeqw mm7,mm7
psllw mm7,7 ; mm7={0xFF80 0xFF80 0xFF80 0xFF80}
mov esi, JSAMPARRAY [sample_data] ; (JSAMPROW *)
mov eax, JDIMENSION [start_col]
mov edi, POINTER [workspace] ; (DCTELEM *)
mov ecx, DCTSIZE/4
alignx 16,7
.convloop:
mov ebx, JSAMPROW [esi+0*SIZEOF_JSAMPROW] ; (JSAMPLE *)
mov edx, JSAMPROW [esi+1*SIZEOF_JSAMPROW] ; (JSAMPLE *)
movq mm0, MMWORD [ebx+eax*SIZEOF_JSAMPLE] ; mm0=(01234567)
movq mm1, MMWORD [edx+eax*SIZEOF_JSAMPLE] ; mm1=(89ABCDEF)
mov ebx, JSAMPROW [esi+2*SIZEOF_JSAMPROW] ; (JSAMPLE *)
mov edx, JSAMPROW [esi+3*SIZEOF_JSAMPROW] ; (JSAMPLE *)
movq mm2, MMWORD [ebx+eax*SIZEOF_JSAMPLE] ; mm2=(GHIJKLMN)
movq mm3, MMWORD [edx+eax*SIZEOF_JSAMPLE] ; mm3=(OPQRSTUV)
movq mm4,mm0
punpcklbw mm0,mm6 ; mm0=(0123)
punpckhbw mm4,mm6 ; mm4=(4567)
movq mm5,mm1
punpcklbw mm1,mm6 ; mm1=(89AB)
punpckhbw mm5,mm6 ; mm5=(CDEF)
paddw mm0,mm7
paddw mm4,mm7
paddw mm1,mm7
paddw mm5,mm7
movq MMWORD [MMBLOCK(0,0,edi,SIZEOF_DCTELEM)], mm0
movq MMWORD [MMBLOCK(0,1,edi,SIZEOF_DCTELEM)], mm4
movq MMWORD [MMBLOCK(1,0,edi,SIZEOF_DCTELEM)], mm1
movq MMWORD [MMBLOCK(1,1,edi,SIZEOF_DCTELEM)], mm5
movq mm0,mm2
punpcklbw mm2,mm6 ; mm2=(GHIJ)
punpckhbw mm0,mm6 ; mm0=(KLMN)
movq mm4,mm3
punpcklbw mm3,mm6 ; mm3=(OPQR)
punpckhbw mm4,mm6 ; mm4=(STUV)
paddw mm2,mm7
paddw mm0,mm7
paddw mm3,mm7
paddw mm4,mm7
movq MMWORD [MMBLOCK(2,0,edi,SIZEOF_DCTELEM)], mm2
movq MMWORD [MMBLOCK(2,1,edi,SIZEOF_DCTELEM)], mm0
movq MMWORD [MMBLOCK(3,0,edi,SIZEOF_DCTELEM)], mm3
movq MMWORD [MMBLOCK(3,1,edi,SIZEOF_DCTELEM)], mm4
add esi, byte 4*SIZEOF_JSAMPROW
add edi, byte 4*DCTSIZE*SIZEOF_DCTELEM
dec ecx
%ifdef COMPILING_FOR_NACL
jnz near .convloop
%else
jnz short .convloop
%endif
emms ; empty MMX state
pop edi
pop esi
; pop edx ; need not be preserved
; pop ecx ; need not be preserved
pop ebx
pop ebp
ret
; --------------------------------------------------------------------------
;
; Quantize/descale the coefficients, and store into coef_block
;
; This implementation is based on an algorithm described in
; "How to optimize for the Pentium family of microprocessors"
; (http://www.agner.org/assem/).
;
; GLOBAL(void)
; jsimd_quantize_mmx (JCOEFPTR coef_block, DCTELEM * divisors,
; DCTELEM * workspace);
;
%define RECIPROCAL(m,n,b) MMBLOCK(DCTSIZE*0+(m),(n),(b),SIZEOF_DCTELEM)
%define CORRECTION(m,n,b) MMBLOCK(DCTSIZE*1+(m),(n),(b),SIZEOF_DCTELEM)
%define SCALE(m,n,b) MMBLOCK(DCTSIZE*2+(m),(n),(b),SIZEOF_DCTELEM)
%define SHIFT(m,n,b) MMBLOCK(DCTSIZE*3+(m),(n),(b),SIZEOF_DCTELEM)
%define coef_block ebp+8 ; JCOEFPTR coef_block
%define divisors ebp+12 ; DCTELEM * divisors
%define workspace ebp+16 ; DCTELEM * workspace
align 16
global EXTN(jsimd_quantize_mmx)
EXTN(jsimd_quantize_mmx):
push ebp
mov ebp,esp
; push ebx ; unused
; push ecx ; unused
; push edx ; need not be preserved
push esi
push edi
mov esi, POINTER [workspace]
mov edx, POINTER [divisors]
mov edi, JCOEFPTR [coef_block]
mov ah, 2
alignx 16,7
.quantloop1:
mov al, DCTSIZE2/8/2
alignx 16,7
.quantloop2:
movq mm2, MMWORD [MMBLOCK(0,0,esi,SIZEOF_DCTELEM)]
movq mm3, MMWORD [MMBLOCK(0,1,esi,SIZEOF_DCTELEM)]
movq mm0,mm2
movq mm1,mm3
psraw mm2,(WORD_BIT-1) ; -1 if value < 0, 0 otherwise
psraw mm3,(WORD_BIT-1)
pxor mm0,mm2 ; val = -val
pxor mm1,mm3
psubw mm0,mm2
psubw mm1,mm3
;
; MMX is an annoyingly crappy instruction set. It has two
; misfeatures that are causing problems here:
;
; - All multiplications are signed.
;
; - The second operand for the shifts is not treated as packed.
;
;
; We work around the first problem by implementing this algorithm:
;
; unsigned long unsigned_multiply(unsigned short x, unsigned short y)
; {
; enum { SHORT_BIT = 16 };
; signed short sx = (signed short) x;
; signed short sy = (signed short) y;
; signed long sz;
;
; sz = (long) sx * (long) sy; /* signed multiply */
;
; if (sx < 0) sz += (long) sy << SHORT_BIT;
; if (sy < 0) sz += (long) sx << SHORT_BIT;
;
; return (unsigned long) sz;
; }
;
; (note that a negative sx adds _sy_ and vice versa)
;
; For the second problem, we replace the shift by a multiplication.
; Unfortunately that means we have to deal with the signed issue again.
;
paddw mm0, MMWORD [CORRECTION(0,0,edx)] ; correction + roundfactor
paddw mm1, MMWORD [CORRECTION(0,1,edx)]
movq mm4,mm0 ; store current value for later
movq mm5,mm1
pmulhw mm0, MMWORD [RECIPROCAL(0,0,edx)] ; reciprocal
pmulhw mm1, MMWORD [RECIPROCAL(0,1,edx)]
paddw mm0,mm4 ; reciprocal is always negative (MSB=1),
paddw mm1,mm5 ; so we always need to add the initial value
; (input value is never negative as we
; inverted it at the start of this routine)
; here it gets a bit tricky as both scale
; and mm0/mm1 can be negative
movq mm6, MMWORD [SCALE(0,0,edx)] ; scale
movq mm7, MMWORD [SCALE(0,1,edx)]
movq mm4,mm0
movq mm5,mm1
pmulhw mm0,mm6
pmulhw mm1,mm7
psraw mm6,(WORD_BIT-1) ; determine if scale is negative
psraw mm7,(WORD_BIT-1)
pand mm6,mm4 ; and add input if it is
pand mm7,mm5
paddw mm0,mm6
paddw mm1,mm7
psraw mm4,(WORD_BIT-1) ; then check if negative input
psraw mm5,(WORD_BIT-1)
pand mm4, MMWORD [SCALE(0,0,edx)] ; and add scale if it is
pand mm5, MMWORD [SCALE(0,1,edx)]
paddw mm0,mm4
paddw mm1,mm5
pxor mm0,mm2 ; val = -val
pxor mm1,mm3
psubw mm0,mm2
psubw mm1,mm3
movq MMWORD [MMBLOCK(0,0,edi,SIZEOF_DCTELEM)], mm0
movq MMWORD [MMBLOCK(0,1,edi,SIZEOF_DCTELEM)], mm1
add esi, byte 8*SIZEOF_DCTELEM
add edx, byte 8*SIZEOF_DCTELEM
add edi, byte 8*SIZEOF_JCOEF
dec al
jnz near .quantloop2
dec ah
jnz near .quantloop1 ; to avoid branch misprediction
emms ; empty MMX state
pop edi
pop esi
; pop edx ; need not be preserved
; pop ecx ; unused
; pop ebx ; unused
pop ebp
ret
; For some reason, the OS X linker does not honor the request to align the
; segment unless we do this.
align 16
|
<%
from pwnlib.shellcraft.aarch64.linux import syscall
%>
<%page args="file, buf"/>
<%docstring>
Invokes the syscall lstat. See 'man 2 lstat' for more information.
Arguments:
file(char): file
buf(stat): buf
</%docstring>
${syscall('SYS_lstat', file, buf)}
|
;; last edit date: 2016/10/26
;; author: Forec
;; LICENSE
;; Copyright (c) 2015-2017, Forec <forec@bupt.edu.cn>
;; Permission to use, copy, modify, and/or distribute this code for any
;; purpose with or without fee is hereby granted, provided that the above
;; copyright notice and this permission notice appear in all copies.
;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
;; WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
;; MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
;; ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
;; WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
;; ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
;; OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
title forec_t38
data segment
val1 dw 1234h
bininfo db 'BIN: $'
octinfo db 'OCT: $'
skip db 0dh, 0ah, '$'
data ends
stack segment para stack 'stack'
db 100h dup(?)
stack ends
code segment
assume cs:code, ds:data
start:
mov ax, data
mov ds, ax
mov es, ax
call bando
quit_pro:
mov ah, 4ch
int 21h
bando proc near
push val1
call pairs
ret
bando endp
pairs proc near
pop bx
pop ax
push bx
call outbin
call outoct
ret
pairs endp
outbin proc near
push ax
push bx
push cx
push dx
mov bx, ax
mov ah, 09h
mov dx, offset bininfo
int 21h
mov cx, 10h
mov ah, 02h
loopp1:
mov dl, bh
and dl, 10000000b
push cx
mov cl, 07h
shr dl, cl
pop cx
add dl, 30h
int 21h
shl bx, 1
loop loopp1
mov ah, 02h
mov dl, 'B'
int 21h ;; 输出 B
call nextline
pop dx
pop cx
pop bx
pop ax
ret
outbin endp
outoct proc near
push ax
push bx
push cx
push dx
mov bx, ax
mov dx, offset octinfo
mov ah, 09h
int 21h
mov ah, 02h
mov dl, bh
and dl, 10000000b
mov cl, 07h
shr dl, cl
add dl, 30h
int 21h ;; 输出第一位
shl bx, 1
mov cx, 05h
loopp2:
mov dl, bh
and dl, 11100000b
push cx
mov cl, 05h
shr dl, cl ;; 八进制右移5位
mov cl, 03h
shl bx, cl ;; 原数左移3位
pop cx
add dl, 30h
int 21h
loop loopp2
mov ah, 02h
mov dl, 'O'
int 21h ;; 输出 O
call nextline
pop dx
pop cx
pop bx
pop ax
ret
outoct endp
nextline proc near
push ax
push dx
mov ah, 09h
mov dx, offset skip
int 21h
pop dx
pop ax
ret
nextline endp
code ends
end start |
; A229469: Numbers n such that T(n) + S(n) + 1 is prime, where T(n) and S(n) are the n-th triangular and square numbers.
; Submitted by Jamie Morken(s2)
; 1,5,8,9,12,17,21,24,29,32,41,44,45,53,56,57,60,68,69,77,81,84,89,92,96,108,113,117,120,132,144,149,156,164,185,197,200,201,212,213,224,233,236,248,252,260,264,269,281,288,300,312,317,321,324,329,344,353,356,357,360,368,369,372,377,380,381,389,392,393,405,417,420,429,437,440,453,476,485,492,500,512,516,524,533,536,549,552,573,585,588,597,600,609,624,629,636,641,648,653
mov $2,332202
lpb $2
sub $2,1
mov $3,$6
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,3
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $5,1
add $5,$1
mov $6,$5
lpe
div $1,3
sub $1,1
mov $0,$1
|
db 0 ; species ID placeholder
db 45, 45, 35, 20, 20, 30
; hp atk def spd sat sdf
db BUG, BUG ; type
db 255 ; catch rate
db 56 ; base exp
db PSNCUREBERRY, BRIGHTPOWDER ; items
db GENDER_F50 ; gender ratio
db 100 ; unknown 1
db 15 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/wurmple/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_BUG, EGG_BUG ; egg groups
; tm/hm learnset
tmhm DYNAMICPUNCH, HEADBUTT, CURSE, TOXIC, ZAP_CANNON, PSYCH_UP, HIDDEN_POWER, SUNNY_DAY, SNORE, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, RETURN, PSYCHIC_M, SHADOW_BALL, DOUBLE_TEAM, ICE_PUNCH, SWAGGER, SLEEP_TALK, THUNDERPUNCH, DREAM_EATER, REST, ATTRACT, THIEF, FIRE_PUNCH, NIGHTMARE, FLASH
; end
|
; A093461: a(1)=1, a(n) = 2*(n^(n-1)-1)/(n-1) for n >= 2.
; 1,2,8,42,312,3110,39216,599186,10761680,222222222,5187484920,135092431034,3883014187080,122109965116022,4170418003627232,153722867280912930,6082648984458358560,257166065851611356702
add $0,1
mov $2,$0
lpb $0
mov $3,$2
lpb $3
dif $3,$0
cmp $3,$2
cmp $3,0
mul $3,$0
mov $5,$4
add $4,1
mul $4,$2
lpe
sub $0,1
add $4,1
lpe
mov $0,$5
add $0,1
|
BPLIST "" invalid_type
BPLIST ""
BPLIST .
DEVICE ZXSPECTRUM48 ; global device specified at end of pass 1
|
// coding: utf-8
// ----------------------------------------------------------------------------
/* Copyright (c) 2011, Roboterclub Aachen e.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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.
*/
// ----------------------------------------------------------------------------
/*
* WARNING: This file is generated automatically, do not edit!
* Please modify the corresponding *.in file instead and rebuild this file.
*/
// ----------------------------------------------------------------------------
#include "../gpio.hpp"
#include "../device.h"
#include "timer_1.hpp"
#include <xpcc_config.hpp>
#if defined(STM32F10X_XL) || defined(STM32F2XX) || defined(STM32F4XX)
# define TIM1_BRK_IRQn TIM1_BRK_TIM9_IRQn
# define TIM1_UP_IRQn TIM1_UP_TIM10_IRQn
# define TIM1_TRG_COM_IRQn TIM1_TRG_COM_TIM11_IRQn
# define TIM8_BRK_IRQn TIM8_BRK_TIM12_IRQn
# define TIM8_UP_IRQn TIM8_UP_TIM13_IRQn
# define TIM8_TRG_COM_IRQn TIM8_TRG_COM_TIM14_IRQn
#elif defined(STM32F3XX)
# define TIM1_BRK_IRQn TIM1_BRK_TIM15_IRQn
# define TIM1_UP_IRQn TIM1_UP_TIM16_IRQn
# define TIM1_TRG_COM_IRQn TIM1_TRG_COM_TIM17_IRQn
#endif
// ----------------------------------------------------------------------------
void
xpcc::stm32::Timer1::enable()
{
// enable clock
RCC->APB2ENR |= RCC_APB2ENR_TIM1EN;
// reset timer
RCC->APB2RSTR |= RCC_APB2RSTR_TIM1RST;
RCC->APB2RSTR &= ~RCC_APB2RSTR_TIM1RST;
}
void
xpcc::stm32::Timer1::disable()
{
// disable clock
RCC->APB2ENR &= ~RCC_APB2ENR_TIM1EN;
TIM1->CR1 = 0;
TIM1->DIER = 0;
TIM1->CCER = 0;
}
// ----------------------------------------------------------------------------
void
xpcc::stm32::Timer1::setMode(Mode mode, SlaveMode slaveMode,
SlaveModeTrigger slaveModeTrigger, MasterMode masterMode
#if defined(STM32F3XX)
, MasterMode2 masterMode2
#endif /* defined(STM32F3XX) */
)
{
// disable timer
TIM1->CR1 = 0;
TIM1->CR2 = 0;
if (slaveMode == SLAVE_ENCODER_1 || slaveMode == SLAVE_ENCODER_2 || slaveMode == SLAVE_ENCODER_3)
{
setPrescaler(1);
}
// ARR Register is buffered, only Under/Overflow generates update interrupt
TIM1->CR1 = TIM_CR1_ARPE | TIM_CR1_URS | mode;
#if defined(STM32F3XX)
TIM1->CR2 = masterMode | masterMode2;
#else
TIM1->CR2 = masterMode;
#endif
TIM1->SMCR = slaveMode|slaveModeTrigger;
}
// ----------------------------------------------------------------------------
uint16_t
xpcc::stm32::Timer1::setPeriod(uint32_t microseconds, bool autoApply)
{
// This will be inaccurate for non-smooth frequencies (last six digits
// unequal to zero)
uint32_t cycles = microseconds * (
((STM32_APB2_FREQUENCY==STM32_AHB_FREQUENCY)?1:2) *
STM32_APB2_FREQUENCY / 1000000UL);
uint16_t prescaler = (cycles + 65535) / 65536; // always round up
uint16_t overflow = cycles / prescaler;
overflow = overflow - 1; // e.g. 36000 cycles are from 0 to 35999
setPrescaler(prescaler);
setOverflow(overflow);
if (autoApply) {
// Generate Update Event to apply the new settings for ARR
TIM1->EGR |= TIM_EGR_UG;
}
return overflow;
}
// ----------------------------------------------------------------------------
void
xpcc::stm32::Timer1::configureInputChannel(uint32_t channel,
InputCaptureMapping input, InputCapturePrescaler prescaler,
InputCapturePolarity polarity, uint8_t filter,
bool xor_ch1_3)
{
channel -= 1; // 1..4 -> 0..3
// disable channel
TIM1->CCER &= ~((TIM_CCER_CC1NP | TIM_CCER_CC1P | TIM_CCER_CC1E) << (channel * 4));
uint32_t flags = input;
flags |= ((uint32_t)prescaler) << 2;
flags |= ((uint32_t)(filter&0xf)) << 4;
if (channel <= 1)
{
uint32_t offset = 8 * channel;
flags <<= offset;
flags |= TIM1->CCMR1 & ~(0xff << offset);
TIM1->CCMR1 = flags;
if(channel == 0) {
if(xor_ch1_3)
TIM1->CR2 |= TIM_CR2_TI1S;
else
TIM1->CR2 &= ~TIM_CR2_TI1S;
}
}
else {
uint32_t offset = 8 * (channel - 2);
flags <<= offset;
flags |= TIM1->CCMR2 & ~(0xff << offset);
TIM1->CCMR2 = flags;
}
TIM1->CCER |= (TIM_CCER_CC1E | polarity) << (channel * 4);
}
// ----------------------------------------------------------------------------
void
xpcc::stm32::Timer1::configureOutputChannel(uint32_t channel,
OutputCompareMode mode, uint16_t compareValue)
{
channel -= 1; // 1..4 -> 0..3
// disable output
TIM1->CCER &= ~(0xf << (channel * 4));
setCompareValue(channel + 1, compareValue);
// enable preload (the compare value is loaded at each update event)
uint32_t flags = mode | TIM_CCMR1_OC1PE;
if (channel <= 1)
{
uint32_t offset = 8 * channel;
flags <<= offset;
flags |= TIM1->CCMR1 & ~(0xff << offset);
TIM1->CCMR1 = flags;
}
else {
uint32_t offset = 8 * (channel - 2);
flags <<= offset;
flags |= TIM1->CCMR2 & ~(0xff << offset);
TIM1->CCMR2 = flags;
}
// Disable Repetition Counter (FIXME has to be done here for some unknown reason)
TIM1->RCR = 0;
if (mode != OUTPUT_INACTIVE) {
TIM1->CCER |= (TIM_CCER_CC1E) << (channel * 4);
}
}
void
xpcc::stm32::Timer1::configureOutputChannel(uint32_t channel,
OutputCompareMode mode,
PinState out, OutputComparePolarity polarity,
PinState out_n, OutputComparePolarity polarity_n,
OutputComparePreload preload)
{
channel -= 1; // 1..4 -> 0..3
// disable output
TIM1->CCER &= ~(0xf << (channel * 4));
uint32_t flags = mode | preload;
if (channel <= 1)
{
uint32_t offset = 8 * channel;
flags <<= offset;
flags |= TIM1->CCMR1 & ~(0xff << offset);
TIM1->CCMR1 = flags;
}
else {
uint32_t offset = 8 * (channel - 2);
flags <<= offset;
flags |= TIM1->CCMR2 & ~(0xff << offset);
TIM1->CCMR2 = flags;
}
// Disable Repetition Counter (FIXME has to be done here for some unknown reason)
TIM1->RCR = 0;
// CCER Flags (Enable/Polarity)
flags = (polarity_n<<2) | (out_n<<2) | polarity | out;
TIM1->CCER |= flags << (channel * 4);
}
void
xpcc::stm32::Timer1::configureOutputChannel(uint32_t channel,
uint32_t modeOutputPorts)
{
channel -= 1; // 1..4 -> 0..3
// disable output
TIM1->CCER &= ~(0xf << (channel * 4));
uint32_t flags = modeOutputPorts & (0x70);
if (channel <= 1)
{
uint32_t offset = 8 * channel;
flags <<= offset;
flags |= TIM1->CCMR1 & ~(TIM_CCMR1_OC1M << offset);
TIM1->CCMR1 = flags;
}
else {
uint32_t offset = 8 * (channel - 2);
flags <<= offset;
flags |= TIM1->CCMR2 & ~(TIM_CCMR1_OC1M << offset);
TIM1->CCMR2 = flags;
}
// Disable Repetition Counter (FIXME has to be done here for some unknown reason)
TIM1->RCR = 0;
TIM1->CCER |= (modeOutputPorts & (0xf)) << (channel * 4);
}
// ----------------------------------------------------------------------------
// Re-implemented here to save some code space. As all arguments in the calls
// below are constant the compiler is able to calculate everything at
// compile time.
static ALWAYS_INLINE void
nvicEnableInterrupt(IRQn_Type IRQn)
{
NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F));
}
static ALWAYS_INLINE void
nvicDisableInterrupt(IRQn_Type IRQn)
{
NVIC_DisableIRQ(IRQn);
}
// ----------------------------------------------------------------------------
void
xpcc::stm32::Timer1::enableInterruptVector(Interrupt interrupt, bool enable, uint32_t priority)
{
if (enable)
{
if (interrupt & INTERRUPT_UPDATE) {
NVIC_SetPriority(TIM1_UP_IRQn, priority);
nvicEnableInterrupt(TIM1_UP_IRQn);
}
if (interrupt & INTERRUPT_BREAK) {
NVIC_SetPriority(TIM1_BRK_IRQn, priority);
nvicEnableInterrupt(TIM1_BRK_IRQn);
}
if (interrupt & (INTERRUPT_COM | INTERRUPT_TRIGGER)) {
NVIC_SetPriority(TIM1_TRG_COM_IRQn, priority);
nvicEnableInterrupt(TIM1_TRG_COM_IRQn);
}
if (interrupt &
(INTERRUPT_CAPTURE_COMPARE_1 | INTERRUPT_CAPTURE_COMPARE_2 |
INTERRUPT_CAPTURE_COMPARE_3 | INTERRUPT_CAPTURE_COMPARE_4)) {
NVIC_SetPriority(TIM1_CC_IRQn, priority);
nvicEnableInterrupt(TIM1_CC_IRQn);
}
}
else
{
if (interrupt & INTERRUPT_UPDATE) {
nvicDisableInterrupt(TIM1_UP_IRQn);
}
if (interrupt & INTERRUPT_BREAK) {
nvicDisableInterrupt(TIM1_BRK_IRQn);
}
if (interrupt & (INTERRUPT_COM | INTERRUPT_TRIGGER)) {
nvicDisableInterrupt(TIM1_TRG_COM_IRQn);
}
if (interrupt &
(INTERRUPT_CAPTURE_COMPARE_1 | INTERRUPT_CAPTURE_COMPARE_2 |
INTERRUPT_CAPTURE_COMPARE_3 | INTERRUPT_CAPTURE_COMPARE_4)) {
nvicDisableInterrupt(TIM1_CC_IRQn);
}
}
}
|
SECTION code_fp_am9511
PUBLIC tanh
EXTERN cam32_sccz80_tanh
defc tanh = cam32_sccz80_tanh
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _tanh
EXTERN cam32_sdcc_tanh
defc _tanh = cam32_sdcc_tanh
ENDIF
|
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 4, 0x90
Lpoly:
.quad 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF
LRR:
.quad 0x1, 0x2, 0x1
LOne:
.long 1,1,1,1,1,1,1,1
.p2align 4, 0x90
.globl y8_p192r1_mul_by_2
.type y8_p192r1_mul_by_2, @function
y8_p192r1_mul_by_2:
push %r12
xor %r12, %r12
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
shld $(1), %r10, %r12
shld $(1), %r9, %r10
shld $(1), %r8, %r9
shl $(1), %r8
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
pop %r12
ret
.Lfe1:
.size y8_p192r1_mul_by_2, .Lfe1-(y8_p192r1_mul_by_2)
.p2align 4, 0x90
.globl y8_p192r1_div_by_2
.type y8_p192r1_div_by_2, @function
y8_p192r1_div_by_2:
push %r12
push %r13
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
xor %r12, %r12
xor %r13, %r13
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
adc $(0), %r12
test $(1), %r8
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
cmovne %r12, %r13
shrd $(1), %r9, %r8
shrd $(1), %r10, %r9
shrd $(1), %r13, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
pop %r13
pop %r12
ret
.Lfe2:
.size y8_p192r1_div_by_2, .Lfe2-(y8_p192r1_div_by_2)
.p2align 4, 0x90
.globl y8_p192r1_mul_by_3
.type y8_p192r1_mul_by_3, @function
y8_p192r1_mul_by_3:
push %r12
xor %r12, %r12
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
shld $(1), %r10, %r12
shld $(1), %r9, %r10
shld $(1), %r8, %r9
shl $(1), %r8
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
xor %r12, %r12
addq (%rsi), %r8
adcq (8)(%rsi), %r9
adcq (16)(%rsi), %r10
adc $(0), %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
pop %r12
ret
.Lfe3:
.size y8_p192r1_mul_by_3, .Lfe3-(y8_p192r1_mul_by_3)
.p2align 4, 0x90
.globl y8_p192r1_add
.type y8_p192r1_add, @function
y8_p192r1_add:
push %r12
xor %r12, %r12
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
addq (%rdx), %r8
adcq (8)(%rdx), %r9
adcq (16)(%rdx), %r10
adc $(0), %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
pop %r12
ret
.Lfe4:
.size y8_p192r1_add, .Lfe4-(y8_p192r1_add)
.p2align 4, 0x90
.globl y8_p192r1_sub
.type y8_p192r1_sub, @function
y8_p192r1_sub:
push %r12
xor %r12, %r12
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
subq (%rdx), %r8
sbbq (8)(%rdx), %r9
sbbq (16)(%rdx), %r10
sbb $(0), %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
test %r12, %r12
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
pop %r12
ret
.Lfe5:
.size y8_p192r1_sub, .Lfe5-(y8_p192r1_sub)
.p2align 4, 0x90
.globl y8_p192r1_neg
.type y8_p192r1_neg, @function
y8_p192r1_neg:
push %r12
xor %r12, %r12
xor %r8, %r8
xor %r9, %r9
xor %r10, %r10
subq (%rsi), %r8
sbbq (8)(%rsi), %r9
sbbq (16)(%rsi), %r10
sbb $(0), %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
test %r12, %r12
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
pop %r12
ret
.Lfe6:
.size y8_p192r1_neg, .Lfe6-(y8_p192r1_neg)
.p2align 4, 0x90
p192r1_mmull:
xor %r12, %r12
movq (%rbx), %rax
mulq (%rsi)
mov %rax, %r8
mov %rdx, %r9
movq (%rbx), %rax
mulq (8)(%rsi)
add %rax, %r9
adc $(0), %rdx
mov %rdx, %r10
movq (%rbx), %rax
mulq (16)(%rsi)
add %rax, %r10
adc $(0), %rdx
mov %rdx, %r11
sub %r8, %r9
sbb $(0), %r10
sbb $(0), %r8
add %r8, %r11
adc $(0), %r12
xor %r8, %r8
movq (8)(%rbx), %rax
mulq (%rsi)
add %rax, %r9
adc $(0), %rdx
mov %rdx, %rcx
movq (8)(%rbx), %rax
mulq (8)(%rsi)
add %rcx, %r10
adc $(0), %rdx
add %rax, %r10
adc $(0), %rdx
mov %rdx, %rcx
movq (8)(%rbx), %rax
mulq (16)(%rsi)
add %rcx, %r11
adc $(0), %rdx
add %rax, %r11
adc %rdx, %r12
adc $(0), %r8
sub %r9, %r10
sbb $(0), %r11
sbb $(0), %r9
add %r9, %r12
adc $(0), %r8
xor %r9, %r9
movq (16)(%rbx), %rax
mulq (%rsi)
add %rax, %r10
adc $(0), %rdx
mov %rdx, %rcx
movq (16)(%rbx), %rax
mulq (8)(%rsi)
add %rcx, %r11
adc $(0), %rdx
add %rax, %r11
adc $(0), %rdx
mov %rdx, %rcx
movq (16)(%rbx), %rax
mulq (16)(%rsi)
add %rcx, %r12
adc $(0), %rdx
add %rax, %r12
adc %rdx, %r8
adc $(0), %r9
sub %r10, %r11
sbb $(0), %r12
sbb $(0), %r10
add %r10, %r8
adc $(0), %r9
xor %r10, %r10
mov %r11, %rax
mov %r12, %rdx
mov %r8, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r9
cmovnc %rax, %r11
cmovnc %rdx, %r12
cmovnc %rcx, %r8
movq %r11, (%rdi)
movq %r12, (8)(%rdi)
movq %r8, (16)(%rdi)
ret
.p2align 4, 0x90
.globl y8_p192r1_mul_montl
.type y8_p192r1_mul_montl, @function
y8_p192r1_mul_montl:
push %rbx
push %r12
mov %rdx, %rbx
call p192r1_mmull
pop %r12
pop %rbx
ret
.Lfe7:
.size y8_p192r1_mul_montl, .Lfe7-(y8_p192r1_mul_montl)
.p2align 4, 0x90
.globl y8_p192r1_to_mont
.type y8_p192r1_to_mont, @function
y8_p192r1_to_mont:
push %rbx
push %r12
lea LRR(%rip), %rbx
call p192r1_mmull
pop %r12
pop %rbx
ret
.Lfe8:
.size y8_p192r1_to_mont, .Lfe8-(y8_p192r1_to_mont)
.p2align 4, 0x90
.globl y8_p192r1_sqr_montl
.type y8_p192r1_sqr_montl, @function
y8_p192r1_sqr_montl:
push %r12
push %r13
movq (%rsi), %rcx
movq (8)(%rsi), %rax
mul %rcx
mov %rax, %r9
mov %rdx, %r10
movq (16)(%rsi), %rax
mul %rcx
add %rax, %r10
adc $(0), %rdx
mov %rdx, %r11
movq (8)(%rsi), %rcx
movq (16)(%rsi), %rax
mul %rcx
add %rax, %r11
adc $(0), %rdx
mov %rdx, %r12
xor %r13, %r13
shld $(1), %r12, %r13
shld $(1), %r11, %r12
shld $(1), %r10, %r11
shld $(1), %r9, %r10
shl $(1), %r9
movq (%rsi), %rax
mul %rax
mov %rax, %r8
add %rdx, %r9
adc $(0), %r10
movq (8)(%rsi), %rax
mul %rax
add %rax, %r10
adc %rdx, %r11
adc $(0), %r12
movq (16)(%rsi), %rax
mul %rax
add %rax, %r12
adc %rdx, %r13
sub %r8, %r9
sbb $(0), %r10
sbb $(0), %r8
add %r8, %r11
mov $(0), %r8
adc $(0), %r8
sub %r9, %r10
sbb $(0), %r11
sbb $(0), %r9
add %r9, %r12
mov $(0), %r9
adc $(0), %r9
add %r8, %r12
adc $(0), %r9
sub %r10, %r11
sbb $(0), %r12
sbb $(0), %r10
add %r10, %r13
mov $(0), %r10
adc $(0), %r10
add %r9, %r13
adc $(0), %r10
mov %r11, %rax
mov %r12, %rdx
mov %r13, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r10
cmovnc %rax, %r11
cmovnc %rdx, %r12
cmovnc %rcx, %r13
movq %r11, (%rdi)
movq %r12, (8)(%rdi)
movq %r13, (16)(%rdi)
pop %r13
pop %r12
ret
.Lfe9:
.size y8_p192r1_sqr_montl, .Lfe9-(y8_p192r1_sqr_montl)
.p2align 4, 0x90
.globl y8_p192r1_mont_back
.type y8_p192r1_mont_back, @function
y8_p192r1_mont_back:
push %r12
movq (%rsi), %r10
movq (8)(%rsi), %r11
movq (16)(%rsi), %r12
xor %r8, %r8
xor %r9, %r9
sub %r10, %r11
sbb $(0), %r12
sbb $(0), %r10
add %r10, %r8
adc $(0), %r9
xor %r10, %r10
sub %r11, %r12
sbb $(0), %r8
sbb $(0), %r11
add %r11, %r9
adc $(0), %r10
xor %r11, %r11
sub %r12, %r8
sbb $(0), %r9
sbb $(0), %r12
add %r12, %r10
adc $(0), %r11
xor %r12, %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmovnc %rax, %r8
cmovnc %rdx, %r9
cmovnc %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
pop %r12
ret
.Lfe10:
.size y8_p192r1_mont_back, .Lfe10-(y8_p192r1_mont_back)
.p2align 4, 0x90
.globl y8_p192r1_select_pp_w5
.type y8_p192r1_select_pp_w5, @function
y8_p192r1_select_pp_w5:
movdqa LOne(%rip), %xmm0
movdqa %xmm0, %xmm12
movd %edx, %xmm1
pshufd $(0), %xmm1, %xmm1
pxor %xmm2, %xmm2
pxor %xmm3, %xmm3
pxor %xmm4, %xmm4
pxor %xmm5, %xmm5
pxor %xmm6, %xmm6
mov $(16), %rcx
.Lselect_loop_sse_w5gas_11:
movdqa %xmm12, %xmm13
pcmpeqd %xmm1, %xmm13
paddd %xmm0, %xmm12
movdqu (%rsi), %xmm7
movdqu (16)(%rsi), %xmm8
movdqu (32)(%rsi), %xmm9
movdqu (48)(%rsi), %xmm10
movq (64)(%rsi), %xmm11
add $(72), %rsi
pand %xmm13, %xmm7
pand %xmm13, %xmm8
pand %xmm13, %xmm9
pand %xmm13, %xmm10
pand %xmm13, %xmm11
por %xmm7, %xmm2
por %xmm8, %xmm3
por %xmm9, %xmm4
por %xmm10, %xmm5
por %xmm11, %xmm6
dec %rcx
jnz .Lselect_loop_sse_w5gas_11
movdqu %xmm2, (%rdi)
movdqu %xmm3, (16)(%rdi)
movdqu %xmm4, (32)(%rdi)
movdqu %xmm5, (48)(%rdi)
movq %xmm6, (64)(%rdi)
ret
.Lfe11:
.size y8_p192r1_select_pp_w5, .Lfe11-(y8_p192r1_select_pp_w5)
.p2align 4, 0x90
.globl y8_p192r1_select_ap_w7
.type y8_p192r1_select_ap_w7, @function
y8_p192r1_select_ap_w7:
movdqa LOne(%rip), %xmm0
pxor %xmm2, %xmm2
pxor %xmm3, %xmm3
pxor %xmm4, %xmm4
movdqa %xmm0, %xmm8
movd %edx, %xmm1
pshufd $(0), %xmm1, %xmm1
mov $(64), %rcx
.Lselect_loop_sse_w7gas_12:
movdqa %xmm8, %xmm9
pcmpeqd %xmm1, %xmm9
paddd %xmm0, %xmm8
movdqa (%rsi), %xmm5
movdqa (16)(%rsi), %xmm6
movdqa (32)(%rsi), %xmm7
add $(48), %rsi
pand %xmm9, %xmm5
pand %xmm9, %xmm6
pand %xmm9, %xmm7
por %xmm5, %xmm2
por %xmm6, %xmm3
por %xmm7, %xmm4
dec %rcx
jnz .Lselect_loop_sse_w7gas_12
movdqu %xmm2, (%rdi)
movdqu %xmm3, (16)(%rdi)
movdqu %xmm4, (32)(%rdi)
ret
.Lfe12:
.size y8_p192r1_select_ap_w7, .Lfe12-(y8_p192r1_select_ap_w7)
|
//
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) Contributors to the OpenEXR Project.
//
//---------------------------------------------------------------------
//
// Constructors and destructors for our exception base class.
//
//---------------------------------------------------------------------
#include "IexExport.h"
#include "IexBaseExc.h"
#include "IexMacros.h"
#include "IexErrnoExc.h"
#include "IexMathExc.h"
#ifdef _WIN32
#include <windows.h>
#endif
#include <stdlib.h>
IEX_INTERNAL_NAMESPACE_SOURCE_ENTER
namespace {
StackTracer currentStackTracer = 0;
} // namespace
void
setStackTracer (StackTracer stackTracer)
{
currentStackTracer = stackTracer;
}
StackTracer
stackTracer ()
{
return currentStackTracer;
}
BaseExc::BaseExc (const char* s) :
_message (s? s : ""),
_stackTrace (currentStackTracer? currentStackTracer(): std::string())
{
}
BaseExc::BaseExc (const std::string &s) :
_message (s),
_stackTrace (currentStackTracer? currentStackTracer(): std::string())
{
// empty
}
BaseExc::BaseExc (std::string &&s) :
_message (std::move (s)),
_stackTrace (currentStackTracer? currentStackTracer(): std::string())
{
// empty
}
BaseExc::BaseExc (std::stringstream &s) :
_message (s.str()),
_stackTrace (currentStackTracer? currentStackTracer(): std::string())
{
// empty
}
BaseExc::BaseExc (const BaseExc &be)
: _message (be._message),
_stackTrace (be._stackTrace)
{
}
BaseExc::~BaseExc () noexcept
{
}
BaseExc &
BaseExc::operator = (const BaseExc& be)
{
if (this != &be)
{
_message = be._message;
_stackTrace = be._stackTrace;
}
return *this;
}
BaseExc &
BaseExc::operator = (BaseExc&& be) noexcept
{
if (this != &be)
{
_message = std::move (be._message);
_stackTrace = std::move (be._stackTrace);
}
return *this;
}
const char *
BaseExc::what () const noexcept
{
return _message.c_str();
}
BaseExc &
BaseExc::assign (std::stringstream &s)
{
_message.assign (s.str());
return *this;
}
BaseExc &
BaseExc::append (std::stringstream &s)
{
_message.append (s.str());
return *this;
}
const std::string &
BaseExc::message() const noexcept
{
return _message;
}
BaseExc &
BaseExc::operator = (std::stringstream &s)
{
return assign (s);
}
BaseExc &
BaseExc::operator += (std::stringstream &s)
{
return append (s);
}
BaseExc &
BaseExc::assign (const char *s)
{
_message.assign(s);
return *this;
}
BaseExc &
BaseExc::operator = (const char *s)
{
return assign(s);
}
BaseExc &
BaseExc::append (const char *s)
{
_message.append(s);
return *this;
}
BaseExc &
BaseExc::operator += (const char *s)
{
return append(s);
}
const std::string &
BaseExc::stackTrace () const noexcept
{
return _stackTrace;
}
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ArgExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, LogicExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, InputExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, IoExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, MathExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ErrnoExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, NoImplExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, NullExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, TypeExc, BaseExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EpermExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnoentExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EsrchExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EintrExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EioExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnxioExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, E2bigExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnoexecExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbadfExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EchildExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EagainExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnomemExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EaccesExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EfaultExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotblkExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbusyExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EexistExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ExdevExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnodevExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotdirExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EisdirExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EinvalExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnfileExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EmfileExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnottyExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EtxtbsyExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EfbigExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnospcExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EspipeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ErofsExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EmlinkExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EpipeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EdomExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ErangeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnomsgExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EidrmExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EchrngExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, El2nsyncExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, El3hltExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, El3rstExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ElnrngExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EunatchExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnocsiExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, El2hltExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EdeadlkExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnolckExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbadeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbadrExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ExfullExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnoanoExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbadrqcExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbadsltExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EdeadlockExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbfontExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnostrExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnodataExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EtimeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnosrExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnonetExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnopkgExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EremoteExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnolinkExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EadvExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EsrmntExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EcommExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EprotoExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EmultihopExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbadmsgExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnametoolongExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EoverflowExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotuniqExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbadfdExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EremchgExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ElibaccExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ElibbadExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ElibscnExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ElibmaxExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ElibexecExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EilseqExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnosysExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EloopExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, ErestartExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EstrpipeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotemptyExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EusersExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotsockExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EdestaddrreqExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EmsgsizeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EprototypeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnoprotooptExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EprotonosupportExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EsocktnosupportExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EopnotsuppExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EpfnosupportExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EafnosupportExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EaddrinuseExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EaddrnotavailExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnetdownExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnetunreachExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnetresetExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EconnabortedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EconnresetExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnobufsExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EisconnExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotconnExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EshutdownExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EtoomanyrefsExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EtimedoutExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EconnrefusedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EhostdownExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EhostunreachExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EalreadyExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EinprogressExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EstaleExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EioresidExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EucleanExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotnamExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnavailExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EisnamExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EremoteioExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EinitExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EremdevExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EcanceledExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnolimfileExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EproclimExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EdisjointExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnologinExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EloginlimExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EgrouploopExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnoattachExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotsupExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnoattrExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EdircorruptedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EdquotExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnfsremoteExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EcontrollerExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotcontrollerExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EenqueuedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotenqueuedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EjoinedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotjoinedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnoprocExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EmustrunExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnotstoppedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EclockcpuExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EinvalstateExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnoexistExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EendofminorExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EbufsizeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EemptyExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EnointrgroupExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EinvalmodeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EcantextentExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EinvaltimeExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, EdestroyedExc, ErrnoExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, OverflowExc, MathExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, UnderflowExc, MathExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, DivzeroExc, MathExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, InexactExc, MathExc)
DEFINE_EXC_EXP_IMPL (IEX_EXPORT, InvalidFpOpExc, MathExc)
IEX_INTERNAL_NAMESPACE_SOURCE_EXIT
#ifdef _WIN32
#pragma optimize("", off)
void
iex_debugTrap()
{
if (0 != getenv("IEXDEBUGTHROW"))
::DebugBreak();
}
#else
void
iex_debugTrap()
{
// how to in Linux?
if (0 != ::getenv("IEXDEBUGTHROW"))
__builtin_trap();
}
#endif
|
.text
main:
# Same sign
li $t0, 300
li $t1, 300
ble $t0, $t1, branch
li $a0, 0
li $v0, 1
syscall
j next
branch:
li $a0, 1
li $v0, 1
syscall
next:
# Diff sign
li $t0, 300
li $t1, -200
ble $t0, $t1, branch_2
li $a0, 0
li $v0, 1
syscall
j next_2
branch_2:
li $a0, 1
li $v0, 1
syscall
next_2:
# Same sign
li $t0, 300
li $t1, 300
bleu $t0, $t1, branch_3
li $a0, 0
li $v0, 1
syscall
j next_3
branch_3:
li $a0, 1
li $v0, 1
syscall
next_3:
li $t0, 300
li $t1, -200
bleu $t0, $t1, branch_4
li $a0, 0
li $v0, 1
syscall
j next_4
branch_4:
li $a0, 1
li $v0, 1
syscall
next_4: |
; A226761: G.f.: 1 / (1 + 12*x*G(x)^2 - 13*x*G(x)^3) where G(x) = 1 + x*G(x)^4 is the g.f. of A002293.
; Submitted by Christian Krause
; 1,1,16,118,1004,8601,75076,662796,5903676,52949332,477533356,4326309406,39343725716,358943047438,3283745710968,30112624408488,276715616909148,2547523969430508,23491659440021920,216942761366305144,2006084011596742384,18572529488934397689,172132908796580339844,1596933120428434077084,14828720847271158074724,137810801887839366436476,1281732932512910629317816,11929486281566524555689316,111105028526521487362182904,1035412994079293522441145868,9654806240893267036340937136,90075655659026185957361852576
mov $3,$0
mov $5,$0
add $5,1
lpb $5
mov $0,$3
mul $2,2
add $2,$3
sub $5,1
sub $0,$5
add $0,$2
bin $0,$2
sub $0,$4
mov $2,$3
mul $4,-2
add $4,$0
lpe
mov $0,$4
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_COMBINATORIAL_FUNCTIONS_COMBS_HPP_INCLUDED
#define NT2_COMBINATORIAL_FUNCTIONS_COMBS_HPP_INCLUDED
#include <nt2/include/functor.hpp>
namespace nt2 { namespace tag
{
/*!
@brief combs generic tag
Represents the combs function in generic contexts.
@par Models:
Hierarchy
**/
struct combs_ : ext::elementwise_<combs_>
{
/// @brief Parent hierarchy
typedef ext::elementwise_<combs_> parent;
template<class... Args>
static BOOST_FORCEINLINE BOOST_AUTO_DECLTYPE dispatch(Args&&... args)
BOOST_AUTO_DECLTYPE_BODY( dispatching_combs_( ext::adl_helper(), static_cast<Args&&>(args)... ) )
};
}
namespace ext
{
template<class Site>
BOOST_FORCEINLINE generic_dispatcher<tag::combs_, Site> dispatching_combs_(adl_helper, boost::dispatch::meta::unknown_<Site>, ...)
{
return generic_dispatcher<tag::combs_, Site>();
}
template<class... Args>
struct impl_combs_;
}
/*!
Computes combination number of combined subvectors.
@par Semantic:
@code
auto r = combs(a0, k);
@endcode
- when a0 (n) and k are non-negative integers the number of
combinations of k elements among n. If n or k are large a
warning will be produced indicating possible inexact results. in
such cases, the result is only accurate to 15 digits for
double-precision inputs, or 8 digits for single-precision
inputs.
- when a0 is a vector of length n, and k is an integer
produces a matrix with n!/k!(n-k)! rows and k columns. each row
of the result has k of the elements in the vector v. this syntax
is only practical for situations where n is less than about 15.
@see @funcref{cnp}
@param a0
@param a1
@return an expression which eventually will evaluate to the result
**/
NT2_FUNCTION_IMPLEMENTATION(tag::combs_, combs, 2)
}
#endif
|
; A017558: a(n) = (12*n + 3)^2.
; 9,225,729,1521,2601,3969,5625,7569,9801,12321,15129,18225,21609,25281,29241,33489,38025,42849,47961,53361,59049,65025,71289,77841,84681,91809,99225,106929,114921,123201
mul $0,12
mov $1,$0
add $1,3
pow $1,2
|
bits 16
write_status:
push si
push si
mov si, .msg
call write_string
pop si
call write_string
pop si
ret
.msg db "[ STATUS ] ", 0x00
write_warning:
push si
push si
mov si, .msg
call write_string
pop si
call write_string
pop si
ret
.msg db "[ WARNING ] ", 0x00
|
//
// Created by Matthew Gretton-Dann on 05/12/2021.
//
#include <algorithm>
#include <array>
#include <iostream>
#include <ostream>
#include <regex>
#include <set>
#include <string>
#include <vector>
/** \brief Item types. */
enum class ItemType { generator, chip };
/** \brief An Item - consists of a type and a name
*
* To improve performance we store all names in a lookup table and use IDs to map to strings. This
* makes comparing items a couple of integer comparisons and not a string compare.
*/
struct Item
{
/**
* \brief Constructor
* \param type Item type
* \param name Item name
*/
Item(ItemType type, std::string const& name) : type_(type)
{
auto it{std::find(names_.begin(), names_.end(), name)};
if (it == names_.end()) {
name_index_ = names_.size();
names_.push_back(name);
}
else {
name_index_ = it - names_.begin();
}
}
/**
* \brief Less than comparator
* \param rhs Right-hand side
* \return \c true if \c *this < \a rhs.
*/
[[nodiscard]] auto operator<(Item const& rhs) const noexcept -> bool
{
return (type_ < rhs.type_) || (type_ == rhs.type_ && name_index_ < rhs.name_index_);
}
/**
* \brief Equality comparator
* \param rhs Right hand side
* \return \c true iff \c *this == \a rhs
*/
[[nodiscard]] auto operator==(Item const& rhs) const noexcept -> bool
{
return name_index_ == rhs.name_index_ && type_ == rhs.type_;
}
ItemType type_{ItemType::generator};
size_t name_index_{0};
static std::vector<std::string> names_;
};
std::vector<std::string> Item::names_;
/**
* \brief A possible state to examine.
*
* Consists of the current floor of the elevator and floors containing items.
*/
struct State
{
static constexpr unsigned floor_count{4}; ///< Number of floors
/**
* \brief Less than comparator
* \param rhs Right-hand side
* \return \c true if \c *this < \a rhs.
*/
[[nodiscard]] auto operator==(State const& rhs) const noexcept -> bool
{
if (elevator_floor_ != rhs.elevator_floor_) {
return false;
}
for (unsigned i{0}; i < floor_count; ++i) {
if (floors_[i] != rhs.floors_[i]) {
return false;
}
}
return true;
}
/**
* \brief Equality comparator
* \param rhs Right hand side
* \return \c true iff \c *this == \a rhs
*/
[[nodiscard]] auto operator<(State const& rhs) const noexcept -> bool
{
if (elevator_floor_ < rhs.elevator_floor_) {
return true;
}
if (elevator_floor_ > rhs.elevator_floor_) {
return false;
}
for (unsigned i{0}; i < floor_count; ++i) {
if (floors_[i] < rhs.floors_[i]) {
return true;
}
if (floors_[i] > rhs.floors_[i]) {
return false;
}
}
return false;
}
/**
* \brief Are all items at the top.
* \return \c true iff the elevator and all items are on the top floor.
*/
[[nodiscard]] auto all_at_top() const noexcept -> bool
{
if (elevator_floor_ != floor_count - 1) {
return false;
}
for (unsigned i{0}; i < floor_count - 1; ++i) {
if (!floors_[i].empty()) {
return false;
}
}
return true;
}
/**
* \brief Move an item from the current floor
* \param dir Direction to move item
* \param item Item to move
* \return New state with item and elevator moved.
*/
[[nodiscard]] auto move(int dir, Item const& item) const -> State
{
State n{*this};
n.floors_[n.elevator_floor_].erase(item);
n.elevator_floor_ += dir;
n.floors_[n.elevator_floor_].insert(item);
return n;
}
/**
* \brief Move two items from the current floor
* \param dir Direction to move item
* \param i1 Item to move
* \param i2 Item to move
* \return New state with items and elevator moved.
*/
[[nodiscard]] auto move(int dir, Item const& i1, Item const& i2) const -> State
{
State n{*this};
n.floors_[n.elevator_floor_].erase(i1);
n.floors_[n.elevator_floor_].erase(i2);
n.elevator_floor_ += dir;
n.floors_[n.elevator_floor_].insert(i1);
n.floors_[n.elevator_floor_].insert(i2);
return n;
}
/**
* \brief Is this a valid state?
* \return \c true iff this state is valid.
*/
[[nodiscard]] auto valid() const noexcept -> bool
{
for (auto const& floor : floors_) {
for (auto item : floor) {
if (item.type_ != ItemType::chip) {
continue;
}
auto name = item.name_index_;
bool has_generator{false};
bool has_other_generators{false};
for (auto i2 : floor) {
if (i2.type_ == ItemType::generator && i2.name_index_ == name) {
has_generator = true;
}
if (i2.type_ == ItemType::generator && i2.name_index_ != name) {
has_other_generators = true;
}
}
if (has_other_generators && !has_generator) {
return false;
}
}
}
return true;
}
/** Insert an item onto a given floor. */
void insert_item(unsigned floor, Item const& item) { floors_.at(floor).insert(item); }
using FloorState = std::set<Item>;
unsigned elevator_floor_{0}; ///< Current floor
std::array<FloorState, floor_count> floors_; ///< Items on each floor.
};
/** Translate a floor name to a number. Note we translate to 0-based from 1-based. */
auto to_floor(std::string const& s) -> unsigned
{
if (s == "first") {
return 0;
}
if (s == "second") {
return 1;
}
if (s == "third") {
return 2;
}
if (s == "fourth") {
return 3;
}
abort();
}
/**
* \brief Update \a to_visit states with \a s if it is valid and hasn't been seen before.
* \param visited Previously visited states
* \param to_visit States to visit next iteration.
* \param s State to add
*/
void update_sets(std::set<State> const& visited, std::set<State>& to_visit, State const& s)
{
if (s.valid() && visited.find(s) == visited.end()) {
to_visit.insert(s);
}
}
auto main() -> int
{
std::string line;
static std::regex floor_re{"^The ([a-z]+) floor contains "};
static std::regex generator_re{"([a-z]+) generator"};
static std::regex microchip_re{"([a-z]+)-compatible microchip"};
State initial_state;
/* Read standard input to get the initial state. */
while (std::getline(std::cin, line)) {
std::smatch m;
if (!std::regex_search(line, m, floor_re)) {
std::cerr << "unable to interpret beginning";
return 1;
}
unsigned floor{to_floor(m.str(1))};
std::string generators{m.suffix()};
std::string microchips{m.suffix()};
while (!generators.empty()) {
if (!std::regex_search(generators, m, generator_re)) {
break;
}
initial_state.insert_item(floor, {ItemType::generator, m.str(1)});
generators = m.suffix();
}
while (!microchips.empty()) {
if (!std::regex_search(microchips, m, microchip_re)) {
break;
}
initial_state.insert_item(floor, {ItemType::chip, m.str(1)});
microchips = m.suffix();
}
}
initial_state.insert_item(0, {ItemType::generator, "elerium"});
initial_state.insert_item(0, {ItemType::chip, "elerium"});
initial_state.insert_item(0, {ItemType::generator, "dilithium"});
initial_state.insert_item(0, {ItemType::chip, "dilithium"});
/* This is basically Dijkstra's minimum distance graph algorithm. However, there are some slight
* optimisations to make this perform acceptably.
*
* Because the cost function is the number of moves of the elevator we can iterate through all
* States with cost N, knowing that every new state from those will have cost N + 1.
*
* So we have the set \c to_visit which is the set of states that cost \c cost to reach. We
* iterate over every state in that producing the states with cost \c cost + 1. These go into
* the set \c next_to_visit. We ensure there are no duplicates of previously visited states
* in that set, and then repeat the process.
*/
std::set<State> visited;
std::set<State> to_visit;
to_visit.insert(initial_state);
unsigned cost{0};
while (true) {
std::cout << "Cost: " << cost << " have visited: " << visited.size()
<< " visiting this time: " << to_visit.size() << '\n';
if (to_visit.empty()) {
std::cout << "No solution found.\n";
return 1;
}
std::set<State> next_to_visit;
std::copy(to_visit.begin(), to_visit.end(), std::inserter(visited, visited.end()));
for (auto const& state : to_visit) {
if (state.all_at_top()) {
std::cout << "Done in " << cost << " moves\n";
return 0;
}
auto current_floor{state.elevator_floor_};
for (auto i1{state.floors_[current_floor].begin()}; i1 != state.floors_[current_floor].end();
++i1) {
if (current_floor < State::floor_count - 1) {
update_sets(visited, next_to_visit, state.move(1, *i1));
auto i2{i1};
++i2;
for (; i2 != state.floors_[current_floor].end(); ++i2) {
update_sets(visited, next_to_visit, state.move(1, *i1, *i2));
}
}
if (current_floor > 0) {
update_sets(visited, next_to_visit, state.move(-1, *i1));
auto i2{i1};
++i2;
for (; i2 != state.floors_[current_floor].end(); ++i2) {
update_sets(visited, next_to_visit, state.move(-1, *i1, *i2));
}
}
}
}
std::swap(to_visit, next_to_visit);
++cost;
}
} |
// Copyright 2021, Autonomous Space Robotics Lab (ASRL)
//
// 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.
/**
* \file plan.cpp
* \brief
* \details
*
* \author Autonomous Space Robotics Lab (ASRL)
*/
#include <vtr_mission_planning/states/repeat/plan.hpp>
namespace vtr {
namespace mission_planning {
namespace state {
namespace repeat {
auto Plan::nextStep(const Base *newState) const -> BasePtr {
// If where we are going is not a child, delegate to the parent
if (!InChain(newState)) return Parent::nextStep(newState);
// If we aren't changing to a different chain, there is no intermediate step
return nullptr;
}
void Plan::processGoals(Tactic *tactic, UpgradableLockGuard &goal_lock,
const Event &event) {
switch (event.signal_) {
case Signal::Continue:
break;
#if 0
case Signal::RobotLost: {
// We need to reinitialize our location, so push a TopoLoc goal onto the
// stack as a temporary detour
Event tmp(Action::AppendGoal,
BasePtr(new repeat::TopologicalLocalize(*this)));
tmp.signal_ = event.signal_;
return Parent::processGoals(tactic, goal_lock, tmp);
}
case Signal::CantPlan: {
// We cannot come up with a plan to the goal, so drop everything and stop
Event tmp(Action::NewGoal, BasePtr(new Idle()));
tmp.signal_ = event.signal_;
return Parent::processGoals(tactic, goal_lock, tmp);
}
case Signal::PlanSuccess: {
// We have found a plan, so pop this goal from the stack
Event tmp(Action::EndGoal);
tmp.signal_ = event.signal_;
return Parent::processGoals(tactic, goal_lock, tmp);
}
case Signal::DoRepair: {
// Path repair has been requested; add a Merge goal as a temporary detour
Event tmp(Action::AppendGoal, BasePtr(new teach::Branch()));
tmp.signal_ = event.signal_;
return Parent::processGoals(tactic, goal_lock, tmp);
}
#endif
default:
// Any unhandled signals percolate upwards
return Parent::processGoals(tactic, goal_lock, event);
}
switch (event.type_) {
case Action::Continue:
if (!tactic->persistentLoc().v.isSet()) {
// If we are lost, redo topological localization
return Parent::processGoals(
tactic, goal_lock,
Event(Action::AppendGoal,
BasePtr(new repeat::TopologicalLocalize(*this))));
#if false
} else if (tactic->status().localization_ ==
LocalizationStatus::DeadReckoning) {
[[fallthrough]]; /// \todo (yuchen) block needed? for now it gets rid
/// of the fall through warning.
// If we are dead-reckoning, try to relocalize
// TODO: Need to incorporate state history here to avoid infinite loops
// return Parent::processGoals(tactic, goal_lock,
// Event(Action::EndGoal));
#endif
} else {
// If we are localized, then continue on to repeat
return Parent::processGoals(tactic, goal_lock, Event(Action::EndGoal));
}
// NOTE: the lack of a break statement here is intentional, to allow
// unhandled cases to percolate up the chain
default:
// Delegate all goal swapping/error handling to the base class
return Parent::processGoals(tactic, goal_lock, event);
}
}
void Plan::onExit(Tactic *tactic, Base *newState) {
// If the new target is a derived class, we are not exiting
if (InChain(newState)) return;
// Note: This is called *before* we call up the tree, as we destruct from
// leaves to root
if (repeat::MetricLocalize::InChain(newState)) {
std::stringstream ss;
for (auto &&it : this->waypoints_) ss << it << ", ";
LOG(INFO) << "Current vertex: " << tactic->persistentLoc().v
<< ", waypoints: " << ss.str();
PathType path = this->container_->planner()->path(
tactic->persistentLoc().v, this->waypoints_, &this->waypointSeq_);
tactic->setPath(path, true);
this->container_->callbacks()->stateUpdate(0);
}
// Recursively call up the inheritance chain until we get to the least common
// ancestor
Parent::onExit(tactic, newState);
}
void Plan::onEntry(Tactic *tactic, Base *oldState) {
// If the previous state was a derived class, we did not leave
if (InChain(oldState)) return;
// Recursively call up the inheritance chain until we get to the least common
// ancestor
Parent::onEntry(tactic, oldState);
// Note: This is called after we call up the tree, as we construct from root
// to leaves
// TODO: The stuff
}
} // namespace repeat
} // namespace state
} // namespace mission_planning
} // namespace vtr |
copyright zengfr site:http://github.com/zengfr/romhack
00042A move.l D1, (A0)+
00042C dbra D0, $42a
004D00 move.b D0, ($6bdc,A5)
004D04 move.b D0, ($6bdd,A5)
016A0C move.b ($6bdc,A5), D1
016A10 adda.w D1, A4 [base+6BDC]
016A54 move.b D1, ($6bdc,A5)
016A58 rts [base+6BDC]
016AEA move.b ($6bdc,A5), D1
016AEE adda.w D1, A4 [base+6BDC]
016B12 move.b D1, ($6bdc,A5)
016B16 rts [base+6BDC]
016BBC move.b ($6bdc,A5), D1
016BC0 adda.w D1, A4 [base+6BDC]
016BE4 move.b D1, ($6bdc,A5)
016BE8 rts [base+6BDC]
0AAACA move.l (A0), D2
0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
0AAAD4 bne $aaafc
0AAAD8 move.l D2, (A0)+
0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAE6 move.l (A0), D2
0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAF4 move.l D2, (A0)+
0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
copyright zengfr site:http://github.com/zengfr/romhack
|
; HOTKEY set stuffer buffer V2.02 1988 Tony Tebby QJUMP
section hotkey
xdef hk_sstbf ; set stuff buffer
xref cv_locas
include 'dev8_ee_hk_data'
include 'dev8_mac_assert'
;+++
; Set a new string in the stuffer buffer. It does not stuff a new string
; if this is the same as the previous string.
;
; d2 c p (word) number of characters to stuff
; a1 c p pointer to characters to stuff
; a3 c p linkage block
; status return 0
;---
hk_sstbf
reglist reg d1/d2/a1/a2/a4
stk_strl equ $04
stk_str equ $08
movem.l reglist,-(sp)
move.l hkd_bpnt(a3),a2 ; current stuffer pointer
hsb_fmatch
subq.w #1,d2
blt.s hsb_match ; run out of stuff string
move.b (a2)+,d1 ; next character to match
beq.s hsb_set ; run out of string in buffer
jsr cv_locas
move.b d1,d0
move.b (a1)+,d1 ; this matches?
jsr cv_locas
cmp.b d0,d1
beq.s hsb_fmatch ; not the end of match yet
bra.s hsb_fend ; ... end of match, look for end
hsb_match
tst.b (a2)+ ; length the same?
beq.s hsb_done ; ... yes, forget it
hsb_fend
tst.b (a2)+ ; find end
bne.s hsb_fend ; ... not there yet
hsb_set
move.l stk_str(sp),a1 ; reset string pointer
move.l stk_strl(sp),d2 ; and length
move.l hkd_btop(a3),d0
lea (a2,d2.w),a4 ; end of new string
cmp.l d0,a4 ; off end of buffer?
blt.s hsb_fbuf ; ... no, fill buffer
move.l hkd_bbas(a3),a2 ; start again at beginning
sub.l a2,d0 ; max length +1
cmp.w d0,d2
blt.s hsb_fbuf ; ... ok, fill it
move.w d0,d2
subq.w #1,d2
hsb_fbuf
move.l a2,hkd_bpnt(a3) ; set new pointer
move.l a2,hkd_ppnt(a3) ; and new previous pointer
bra.s hsb_fbend
hsb_fblp
move.b (a1)+,(a2)+ ; copy character
hsb_fbend
dbra d2,hsb_fblp
hsb_fbclr
tst.b (a2) ; clear up to
sf (a2)+ ; clear
bne.s hsb_fbclr
hsb_done
moveq #0,d0
movem.l (sp)+,reglist
rts
end
|
#include "Platform.inc"
#include "FarCalls.inc"
#include "Buttons.inc"
#include "TestFixture.inc"
radix decimal
ButtonFlagsTest code
global testArrange
testArrange:
testAct:
fcall initialiseButtons
testAssert:
banksel buttonFlags
.assert "buttonFlags == 0, 'Expected buttonFlags to be cleared.'"
return
end
|
; A107963: a(n) = (n+1)*(n+2)*(n+3)*(n+4)*(5*n^2 + 19*n + 15)/360.
; 1,13,73,273,798,1974,4326,8646,16071,28171,47047,75439,116844,175644,257244,368220,516477,711417,964117,1287517,1696618,2208690,2843490,3623490,4574115,5723991,7105203,8753563,10708888,13015288,15721464,18881016,22552761,26801061,31696161,37314537,43739254,51060334,59375134,68788734,79414335,91373667,104797407,119825607,136608132,155305108,176087380,199136980,224647605,252825105,283887981,318067893,355610178,396774378,441834778,491080954,544818331,603368751,667071051,736281651,811375152
lpb $0
mov $2,$0
sub $0,1
seq $2,208139 ; Number of n X 5 0..1 arrays avoiding 0 0 1 and 0 1 1 horizontally and 0 0 1 and 1 0 1 vertically.
add $1,$2
lpe
div $1,12
add $1,1
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r14
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x12f8d, %rsi
lea addresses_WT_ht+0x191e9, %rdi
clflush (%rsi)
nop
dec %r10
mov $87, %rcx
rep movsl
xor %r11, %r11
lea addresses_A_ht+0x695, %rdi
clflush (%rdi)
nop
nop
nop
nop
xor $28348, %rbx
vmovups (%rdi), %ymm0
vextracti128 $0, %ymm0, %xmm0
vpextrq $1, %xmm0, %r10
nop
nop
xor %rcx, %rcx
lea addresses_WT_ht+0x9d39, %rbx
nop
nop
nop
nop
nop
add %rdx, %rdx
vmovups (%rbx), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $1, %xmm7, %rcx
nop
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_WT_ht+0x92e9, %r11
nop
nop
nop
sub $303, %rbx
mov $0x6162636465666768, %r10
movq %r10, (%r11)
nop
nop
nop
nop
sub $55588, %rdi
lea addresses_A_ht+0x156a9, %rsi
lea addresses_D_ht+0xd4e9, %rdi
clflush (%rsi)
nop
add $19647, %r14
mov $59, %rcx
rep movsl
nop
nop
nop
sub $39575, %r11
lea addresses_A_ht+0x14ca9, %rsi
lea addresses_normal_ht+0x6529, %rdi
clflush (%rsi)
nop
nop
nop
nop
xor %rbx, %rbx
mov $74, %rcx
rep movsq
nop
nop
add $29907, %rbx
lea addresses_A_ht+0x1a669, %rsi
lea addresses_UC_ht+0x129e9, %rdi
nop
nop
nop
nop
nop
sub $20128, %rbx
mov $25, %rcx
rep movsq
nop
nop
nop
and $26823, %r11
lea addresses_WC_ht+0xece9, %rsi
lea addresses_UC_ht+0x44e9, %rdi
nop
nop
and $55, %rbx
mov $87, %rcx
rep movsw
nop
nop
nop
nop
nop
xor $54102, %rbx
lea addresses_D_ht+0x1cce9, %r10
clflush (%r10)
nop
add %rsi, %rsi
mov (%r10), %rdi
nop
nop
nop
nop
nop
add %r10, %r10
lea addresses_WC_ht+0xbba1, %rsi
lea addresses_D_ht+0x174e9, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
inc %rbx
mov $34, %rcx
rep movsw
nop
nop
nop
nop
sub $5769, %r14
lea addresses_normal_ht+0xaee9, %rdi
add %rcx, %rcx
movb (%rdi), %dl
nop
nop
add $65296, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r14
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %rbp
push %rbx
// Faulty Load
lea addresses_RW+0x144e9, %r10
nop
cmp $42805, %r13
mov (%r10), %r11
lea oracles, %rbx
and $0xff, %r11
shlq $12, %r11
mov (%rbx,%r11,1), %r11
pop %rbx
pop %rbp
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_WT_ht'}}
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_normal_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_UC_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_UC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 10}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 3, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_D_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 9}}
{'32': 21829}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; ScanMem8.Asm
;
; Abstract:
;
; ScanMem8 function
;
; Notes:
;
; The following BaseMemoryLib instances contain the same copy of this file:
;
; BaseMemoryLibRepStr
; BaseMemoryLibMmx
; BaseMemoryLibSse2
; BaseMemoryLibOptDxe
; BaseMemoryLibOptPei
;
;------------------------------------------------------------------------------
.code
;------------------------------------------------------------------------------
; CONST VOID *
; EFIAPI
; InternalMemScanMem8 (
; IN CONST VOID *Buffer,
; IN UINTN Length,
; IN UINT8 Value
; );
;------------------------------------------------------------------------------
InternalMemScanMem8 PROC USES rdi
mov rdi, rcx
mov rcx, rdx
mov rax, r8
repne scasb
lea rax, [rdi - 1]
cmovnz rax, rcx ; set rax to 0 if not found
ret
InternalMemScanMem8 ENDP
END
|
; Egg Hunter Shellcode Linux x86
; by Daniel Roberson -- SLAE 877
;
BITS 32
; If the egg is changed here, it must be changed in the shellcode as well
mov ebx, 0x424a424a ; EGG: inc edx
; dec edx
; inc edx
; dec edx
loop:
inc eax
cmp DWORD [eax], ebx
jne loop
jmp eax
|
; généré avec https://github.com/oxypomme/BMPtoASM
push AX
push BX
mov AX, playerX
mov BX, playerY
add AX, 2
mov BX, playerY
add BX, 8
oxgSHOWPIXEL AX, BX, 007h ; 2-8
inc AX
mov BX, playerY
add BX, 7
oxgSHOWPIXEL AX, BX, 007h ; 3-7
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 3-8
inc AX
mov BX, playerY
add BX, 7
oxgSHOWPIXEL AX, BX, 007h ; 4-7
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 4-8
inc AX
mov BX, playerY
add BX, 7
oxgSHOWPIXEL AX, BX, 007h ; 5-7
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 5-8
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 5-9
inc AX
mov BX, playerY
add BX, 6
oxgSHOWPIXEL AX, BX, 006h ; 6-6
inc BX
oxgSHOWPIXEL AX, BX, 032h ; 6-7
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 6-8
inc AX
mov BX, playerY
add BX, 3
oxgSHOWPIXEL AX, BX, 007h ; 7-3
add BX, 2
oxgSHOWPIXEL AX, BX, 006h ; 7-5
inc BX
oxgSHOWPIXEL AX, BX, 006h ; 7-6
inc BX
oxgSHOWPIXEL AX, BX, 032h ; 7-7
inc BX
oxgSHOWPIXEL AX, BX, 00Fh ; 7-8
add BX, 3
oxgSHOWPIXEL AX, BX, 001h ; 7-11
inc BX
oxgSHOWPIXEL AX, BX, 001h ; 7-12
inc BX
oxgSHOWPIXEL AX, BX, 001h ; 7-13
add BX, 2
oxgSHOWPIXEL AX, BX, 007h ; 7-15
inc AX
mov BX, playerY
oxgSHOWPIXEL AX, BX, 0B8h ; 8-0
inc BX
oxgSHOWPIXEL AX, BX, 0B8h ; 8-1
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 8-2
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 8-3
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 8-4
inc BX
oxgSHOWPIXEL AX, BX, 006h ; 8-5
inc BX
oxgSHOWPIXEL AX, BX, 006h ; 8-6
inc BX
oxgSHOWPIXEL AX, BX, 00Fh ; 8-7
inc BX
oxgSHOWPIXEL AX, BX, 00Fh ; 8-8
inc BX
oxgSHOWPIXEL AX, BX, 006h ; 8-9
inc BX
oxgSHOWPIXEL AX, BX, 001h ; 8-10
inc BX
oxgSHOWPIXEL AX, BX, 001h ; 8-11
add BX, 3
oxgSHOWPIXEL AX, BX, 001h ; 8-14
inc BX
oxgSHOWPIXEL AX, BX, 007h ; 8-15
inc AX
mov BX, playerY
oxgSHOWPIXEL AX, BX, 071h ; 9-0
inc BX
oxgSHOWPIXEL AX, BX, 071h ; 9-1
inc BX
oxgSHOWPIXEL AX, BX, 05Ah ; 9-2
inc BX
oxgSHOWPIXEL AX, BX, 05Ah ; 9-3
inc BX
oxgSHOWPIXEL AX, BX, 05Ah ; 9-4
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 9-5
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 9-6
inc BX
oxgSHOWPIXEL AX, BX, 00Fh ; 9-7
inc BX
oxgSHOWPIXEL AX, BX, 00Fh ; 9-8
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 9-9
inc BX
oxgSHOWPIXEL AX, BX, 036h ; 9-10
inc BX
oxgSHOWPIXEL AX, BX, 036h ; 9-11
inc AX
mov BX, playerY
inc BX
oxgSHOWPIXEL AX, BX, 071h ; 10-1
inc BX
oxgSHOWPIXEL AX, BX, 05Ah ; 10-2
inc BX
oxgSHOWPIXEL AX, BX, 05Ah ; 10-3
inc BX
oxgSHOWPIXEL AX, BX, 05Ah ; 10-4
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 10-5
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 10-6
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 10-7
inc BX
oxgSHOWPIXEL AX, BX, 00Fh ; 10-8
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 10-9
inc BX
oxgSHOWPIXEL AX, BX, 036h ; 10-10
inc BX
oxgSHOWPIXEL AX, BX, 036h ; 10-11
inc BX
oxgSHOWPIXEL AX, BX, 036h ; 10-12
add BX, 3
oxgSHOWPIXEL AX, BX, 01Dh ; 10-15
inc AX
mov BX, playerY
add BX, 5
oxgSHOWPIXEL AX, BX, 00Ch ; 11-5
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 11-6
add BX, 2
oxgSHOWPIXEL AX, BX, 00Fh ; 11-8
inc BX
oxgSHOWPIXEL AX, BX, 00Fh ; 11-9
add BX, 4
oxgSHOWPIXEL AX, BX, 036h ; 11-13
inc BX
oxgSHOWPIXEL AX, BX, 036h ; 11-14
inc BX
oxgSHOWPIXEL AX, BX, 01Dh ; 11-15
inc AX
mov BX, playerY
add BX, 6
oxgSHOWPIXEL AX, BX, 00Ch ; 12-6
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 12-7
add BX, 2
oxgSHOWPIXEL AX, BX, 00Fh ; 12-9
inc AX
mov BX, playerY
add BX, 7
oxgSHOWPIXEL AX, BX, 00Ch ; 13-7
inc BX
oxgSHOWPIXEL AX, BX, 00Ch ; 13-8
inc BX
oxgSHOWPIXEL AX, BX, 05Ah ; 13-9
pop BX
pop AX
|
section .init
global _init:function
_init:
push ebp
mov ebp, esp
; gcc will nicely put the contents of crtbegin.o's .init section here.
section .fini
global _fini:function
_fini:
push ebp
mov ebp, esp
; gcc will nicely put the contents of crtbegin.o's .fini section here.
|
/*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include <assert.h>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include "codegen/CodeGenerator.hpp"
#include "codegen/ConstantDataSnippet.hpp"
#include "codegen/FrontEnd.hpp"
#include "codegen/InstOpCode.hpp"
#include "codegen/Instruction.hpp"
#include "codegen/Linkage.hpp"
#include "codegen/Linkage_inlines.hpp"
#include "codegen/Machine.hpp"
#include "codegen/MemoryReference.hpp"
#include "codegen/RealRegister.hpp"
#include "codegen/Register.hpp"
#include "codegen/RegisterConstants.hpp"
#include "codegen/RegisterDependency.hpp"
#include "codegen/RegisterPair.hpp"
#include "codegen/Relocation.hpp"
#include "codegen/Snippet.hpp"
#include "codegen/S390Snippets.hpp"
#include "compile/Compilation.hpp"
#include "compile/ResolvedMethod.hpp"
#include "control/Options.hpp"
#include "control/Options_inlines.hpp"
#include "env/CompilerEnv.hpp"
#ifdef J9_PROJECT_SPECIFIC
#include "env/CHTable.hpp"
#endif
#include "env/TRMemory.hpp"
#include "env/jittypes.h"
#include "il/Block.hpp"
#include "il/ILOpCodes.hpp"
#include "il/ILOps.hpp"
#include "il/Node.hpp"
#include "il/Symbol.hpp"
#include "il/SymbolReference.hpp"
#include "il/symbol/LabelSymbol.hpp"
#include "il/symbol/MethodSymbol.hpp"
#include "il/symbol/ResolvedMethodSymbol.hpp"
#include "il/symbol/StaticSymbol.hpp"
#include "infra/Assert.hpp"
#include "infra/Bit.hpp"
#include "infra/List.hpp"
#include "infra/CfgEdge.hpp"
#include "optimizer/Structure.hpp"
#include "ras/Debug.hpp"
#include "runtime/CodeCacheManager.hpp"
#include "runtime/Runtime.hpp"
#include "z/codegen/EndianConversion.hpp"
#include "z/codegen/S390GenerateInstructions.hpp"
#include "z/codegen/S390Instruction.hpp"
#include "z/codegen/S390OutOfLineCodeSection.hpp"
void
TR::S390RSInstruction::generateAdditionalSourceRegisters(TR::Register * fReg, TR::Register *lReg)
{
int32_t firstRegNum = toRealRegister(fReg)->getRegisterNumber();
int32_t lastRegNum = toRealRegister(lReg)->getRegisterNumber();
if (firstRegNum != lastRegNum &&
lastRegNum - firstRegNum > 1)
{
TR::Machine *machine = cg()->machine();
int8_t numRegsToAdd = lastRegNum - firstRegNum - 1;
// _additionalRegisters = new (cg()->trHeapMemory(),TR_MemoryBase::Array) TR_Array<TR::Register *>(cg()->trMemory(), numRegsToAdd, false);
int8_t curReg = firstRegNum+1;
for (int8_t i=0; i < numRegsToAdd; i++)
{
// (*_additionalRegisters)[i] = machine->getRealRegister(((TR::RealRegister::RegNum)curReg));
TR::Register *temp = machine->getRealRegister(((TR::RealRegister::RegNum)curReg));
useSourceRegister(temp);
curReg++;
}
}
}
uint8_t *
TR::S390EInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t instructionLength = getOpCode().getInstructionLength();
getOpCode().copyBinaryToBuffer(instructionStart);
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
uint8_t *
TR::S390IEInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t instructionLength = getOpCode().getInstructionLength();
getOpCode().copyBinaryToBuffer(instructionStart);
*(cursor + 3) = getImmediateField1() << 4 | getImmediateField2();
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
bool isLoopEntryAlignmentEnabled(TR::Compilation *comp)
{
if(comp->getOption(TR_DisableLoopEntryAlignment))
return false;
if(comp->getOption(TR_EnableLoopEntryAlignment))
return true;
// Loop alignment not worth the extra bytes for <= warm compilations because if a loop at warm would have
// exhibited benefit from alignment then the loop must have been hot enough for us to recompile the method
// to > warm in the first place.
if(comp->getOptLevel() <= warm)
return false;
if (comp->getOption(TR_EnableLabelTargetNOPs)) // only one type of NOP insertion is currently supported
return false;
return true;
}
/**
* Determines whether the given instruction should be aligned with NOPs.
* Currently, it supports alignment of loop entry blocks.
*/
bool TR::S390LabeledInstruction::isNopCandidate()
{
TR::Compilation *comp = cg()->comp();
if (!isLoopEntryAlignmentEnabled(comp))
return false;
bool isNopCandidate = false;
TR::Node * node = getNode();
// Re: node->getLabel() == getLabelSymbol()
// Make sure the label is the one that corresponds with BBStart
// An example where this is not the case is labels in the pre-
// prologue where they take on the node of the first BB.
if (node != NULL && node->getOpCodeValue() == TR::BBStart &&
node->getLabel() == getLabelSymbol())
{
TR::Block * block = node->getBlock();
// Frequency 6 is "Don't Know". Do not bother aligning.
if (block->firstBlockInLoop() && !block->isCold() && block->getFrequency() > 1000)
{
TR_BlockStructure* blockStructure = block->getStructureOf();
if (blockStructure)
{
TR_RegionStructure *region = (TR_RegionStructure*)blockStructure->getContainingLoop();
if (region)
{
// make sure block == entry, so that you're doing stuff for loop entry
//
TR::Block *entry = region->getEntryBlock();
assert(entry==block);
uint32_t loopLength = 0;
for (auto e = entry->getPredecessors().begin(); e != entry->getPredecessors().end(); ++e)
{
TR::Block *predBlock = toBlock((*e)->getFrom());
if (!region->contains(predBlock->getStructureOf(), region->getParent()))
continue;
// Backedge found.
TR::Instruction* lastInstr = predBlock->getLastInstruction();
// Find the branch instruction.
int32_t window = 4; // limit search distance.
while(window >= 0 && !lastInstr->getOpCode().isBranchOp())
{
window--;
lastInstr = lastInstr->getPrev();
}
// Determine Length of Loop.
TR::Instruction * firstInstr = block->getFirstInstruction();
TR::Instruction * currInstr;
for(currInstr=firstInstr; ; currInstr=currInstr->getNext())
{
if(currInstr==NULL)
{
// We might be here if the loop structure isn't consecutive in memory
return false;
}
loopLength += currInstr->getOpCode().getInstructionLength();
if(loopLength>256)
return false;
if(currInstr==lastInstr)
break;
}
// Determine if the loop will cross cache line boundry
uint8_t * cursor = cg()->getBinaryBufferCursor();
if( loopLength <= 256 && (((uint64_t)cursor+loopLength)&0xffffff00) > ((uint64_t)cursor&0xffffff00) )
{
isNopCandidate = true;
traceMsg(comp, "Insert NOP instructions for loop alignment\n");
break;
}
else
{
isNopCandidate = false;
break;
}
}
}
}
}
}
return isNopCandidate;
}
////////////////////////////////////////////////////////
// TR::S390LabelInstruction:: member functions
////////////////////////////////////////////////////////
/**
* LabelInstruction is a pseudo instruction that generates a label or constant (with a label)
*
* Currently, this pseudo instruction handles the following 2 scenarios:
*
* 1. emit a label
*
* 2. emit a snippet label
*
*/
uint8_t *
TR::S390LabelInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
TR::Compilation *comp = cg()->comp();
bool tryToUseLabelTargetNOPs = comp->getOption(TR_EnableLabelTargetNOPs);
bool traceLabelTargetNOPs = comp->getOption(TR_TraceLabelTargetNOPs);
intptr_t offsetForLabelTargetNOPs = 0;
if (tryToUseLabelTargetNOPs)
{
tryToUseLabelTargetNOPs = considerForLabelTargetNOPs(true); // inEncodingPhase=true
if (tryToUseLabelTargetNOPs)
{
offsetForLabelTargetNOPs = instructionStart-cg()->getCodeStart();
// the offset that matters is the offset relative to the start of the object (the object start is 256 byte aligned but programs in this object may only be 8 byte aligned)
// instructionStart-cg()->getCodeStart() is the offset just for this one routine or nested routine so have to add in the object size for any already
// compiled separate programs (batchObjCodeSize) and any offset for any already compiled parent programs for the nested case (getCodeSize)
size_t batchObjCodeSize = 0;
size_t objCodeSize = 0;
if (traceLabelTargetNOPs)
traceMsg(comp,"\toffsetForLabelTargetNOPs = absOffset 0x%p + batchObjCodeSize 0x%p + objCodeSize 0x%p = 0x%p\n",
offsetForLabelTargetNOPs,batchObjCodeSize,objCodeSize,offsetForLabelTargetNOPs + batchObjCodeSize + objCodeSize);
offsetForLabelTargetNOPs = offsetForLabelTargetNOPs + batchObjCodeSize + objCodeSize;
if (traceLabelTargetNOPs)
{
TR::Instruction *thisInst = this;
TR::Instruction *prevInst = getPrev();
traceMsg(comp,"\tTR::S390LabeledInstruction %p (%s) at cursor %p (skipThisOne=%s, offset = %p, codeStart %p)\n",
this,thisInst->getOpCode().getMnemonicName(),instructionStart,isSkipForLabelTargetNOPs()?"true":"false",
offsetForLabelTargetNOPs,cg()->getCodeStart());
traceMsg(comp,"\tprev %p (%s)\n",
prevInst,prevInst->getOpCode().getMnemonicName());
}
}
}
TR::LabelSymbol * label = getLabelSymbol();
TR::Snippet * snippet = getCallSnippet();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
uint16_t binOpCode = *(uint16_t *) (getOpCode().getOpCodeBinaryRepresentation());
if (getOpCode().getOpCodeValue() == TR::InstOpCode::DC)
{
AOTcgDiag1(comp, "add TR_AbsoluteMethodAddress cursor=%x\n", cursor);
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelAbsoluteRelocation(cursor, label));
cg()->addProjectSpecializedRelocation(cursor, NULL, NULL, TR_AbsoluteMethodAddress,
__FILE__, __LINE__, getNode());
if (label->getCodeLocation() != NULL)
{
*((uintptrj_t *) cursor) = boa((uintptrj_t) label->getCodeLocation());
}
cursor += sizeof(uintptrj_t);
}
else // must be real LABEL instruction
{
// Insert Padding if necessary.
if (_alignment != 0)
{
if (tryToUseLabelTargetNOPs && traceLabelTargetNOPs)
traceMsg(comp,"force tryToUseLabelTargetNOPs to false because _alignment already needed on inst %p\n",this);
tryToUseLabelTargetNOPs = false;
int32_t padding = _alignment - (((uintptrj_t)instructionStart) % _alignment);
for (int i = padding / 6; i > 0; i--)
{
(*(uint16_t *) cursor) = 0xC004;
cursor += sizeof(uint16_t);
(*(uint32_t *) cursor) = 0xDEADBEEF;
cursor += sizeof(uint32_t);
}
padding = padding % 6;
for (int i = padding / 4; i > 0; i--)
{
(*(uint32_t *) cursor) = 0xA704BEEF;
cursor += sizeof(uint32_t);
}
padding = padding % 4;
if (padding == 2)
{
(*(uint16_t *) cursor) = 0x1800;
cursor += sizeof(uint16_t);
}
}
getLabelSymbol()->setCodeLocation(instructionStart);
TR_ASSERT(getOpCode().getOpCodeValue() == TR::InstOpCode::LABEL, "LabelInstr not DC or LABEL, what is it??");
}
// Insert NOPs for loop alignment if possible
uint64_t offset = 0;
bool doUseLabelTargetNOPs = false;
uint8_t * newInstructionStart = NULL;
int32_t labelTargetBytesInserted = 0;
if (tryToUseLabelTargetNOPs)
{
int32_t labelTargetNOPLimit = comp->getOptions()->getLabelTargetNOPLimit();
if (isOdd(labelTargetNOPLimit))
{
if (traceLabelTargetNOPs)
traceMsg(comp,"\tlabelTargetNOPLimit %d is odd reduce by 1 to %d\n",labelTargetNOPLimit,labelTargetNOPLimit-1);
labelTargetNOPLimit--;
}
offset = (uint64_t)offsetForLabelTargetNOPs&(0xff);
if (traceLabelTargetNOPs)
traceMsg(comp,"\tcomparing offset %lld >? labelTargetNOPLimit %d (offsetForLabelTargetNOPs = %p)\n",offset,labelTargetNOPLimit,offsetForLabelTargetNOPs);
if (offset > labelTargetNOPLimit)
{
doUseLabelTargetNOPs = true;
newInstructionStart = cursor + (256 - offset);
labelTargetBytesInserted = 256 - offset;
if (traceLabelTargetNOPs)
traceMsg(comp,"\tset useLabelTargetNOPs = true : offsetForLabelTargetNOPs=%p > labelTargetNOPLimit %d, offset=%lld, cursor %p -> %p, labelTargetBytesInserted=%d\n",
offsetForLabelTargetNOPs,labelTargetNOPLimit,offset,cursor,newInstructionStart,labelTargetBytesInserted);
}
}
else
{
offset = (uint64_t)cursor&(0xff);
newInstructionStart = (uint8_t *) (((uintptrj_t)cursor+256)/256*256);
}
if (offset && (doUseLabelTargetNOPs || isNopCandidate()))
{
if (!doUseLabelTargetNOPs)
setEstimatedBinaryLength(getEstimatedBinaryLength()+256-offset);
getLabelSymbol()->setCodeLocation(newInstructionStart); // Label location need to be updated
assert(offset%2==0);
TR::Instruction * prevInstr = getPrev();
TR::Instruction * instr;
TR_Debug * debugObj = cg()->getDebug();
// Insert a BRC instruction to skip NOP instructions if there're more than 3 NOPs to insert
if(offset<238)
{
uint8_t *curBeforeJump = cursor;
instr = generateS390BranchInstruction(cg(), TR::InstOpCode::BRC, TR::InstOpCode::COND_MASK15, getNode(), getLabelSymbol(), prevInstr);
instr->setEstimatedBinaryLength(10);
cg()->setBinaryBufferCursor(cursor = instr->generateBinaryEncoding());
if (debugObj)
debugObj->addInstructionComment(instr, "Skip NOP instructions for loop alignment");
if (doUseLabelTargetNOPs)
{
int32_t bytesOfJump = cursor - curBeforeJump;
if (traceLabelTargetNOPs)
traceMsg(comp,"\tbytesOfJump=%d : update offset %lld -> %lld\n",bytesOfJump,offset,offset+bytesOfJump);
offset+=bytesOfJump;
offset = (uint64_t)offset&0xff;
}
else
{
offset = (uint64_t)cursor&0xff;
}
prevInstr = instr;
}
// Insert NOP instructions until cursor is aligned
for(; offset;)
{
uint8_t *curBeforeNOPs = cursor;
if(offset<=250)
{
instr = new (cg()->trHeapMemory()) TR::S390NOPInstruction(TR::InstOpCode::NOP, 6, getNode(), prevInstr, cg());
if (doUseLabelTargetNOPs && traceLabelTargetNOPs)
traceMsg(comp,"\tgen 6 byte NOP at offset %lld\n",offset);
instr->setEstimatedBinaryLength(6);
}
else if(offset<=252)
{
instr = new (cg()->trHeapMemory()) TR::S390NOPInstruction(TR::InstOpCode::NOP, 4, getNode(), prevInstr, cg());
if (doUseLabelTargetNOPs && traceLabelTargetNOPs)
traceMsg(comp,"\tgen 4 byte NOP at offset %lld\n",offset);
instr->setEstimatedBinaryLength(4);
}
else if(offset<=254)
{
instr = new (cg()->trHeapMemory()) TR::S390NOPInstruction(TR::InstOpCode::NOP, 2, getNode(), prevInstr, cg());
if (doUseLabelTargetNOPs && traceLabelTargetNOPs)
traceMsg(comp,"\tgen 2 byte NOP at offset %lld\n",offset);
instr->setEstimatedBinaryLength(2);
}
cg()->setBinaryBufferCursor(cursor = instr->generateBinaryEncoding());
if (doUseLabelTargetNOPs)
{
int32_t bytesOfNOPs = cursor - curBeforeNOPs;
if (traceLabelTargetNOPs)
traceMsg(comp,"\tbytesOfNOPs=%d : end update offset %lld -> %lld\n",bytesOfNOPs,offset,offset+bytesOfNOPs);
offset+=bytesOfNOPs;
offset = (uint64_t)offset&0xff;
}
else
{
offset = (uint64_t)cursor&0xff;
}
prevInstr = instr;
}
instructionStart = cursor;
if (doUseLabelTargetNOPs)
{
if (traceLabelTargetNOPs)
traceMsg(comp,"\tfinished NOP insertion : setBinaryLength to 0, addAccumError = estBinLen %d - bytesInserted %d = %d, setBinaryEncoding to 0x%x\n",
getEstimatedBinaryLength(),labelTargetBytesInserted,getEstimatedBinaryLength() - labelTargetBytesInserted,instructionStart);
setBinaryLength(0);
TR_ASSERT(getEstimatedBinaryLength() >= labelTargetBytesInserted,"lable inst %p : estimatedBinaryLength %d must be >= labelTargetBytesInserted %d inserted\n",
this,getEstimatedBinaryLength(),labelTargetBytesInserted);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - labelTargetBytesInserted);
setBinaryEncoding(instructionStart);
return cursor;
}
}
setBinaryLength(cursor - instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
setBinaryEncoding(instructionStart);
return cursor;
}
bool
TR::S390LabelInstruction::considerForLabelTargetNOPs(bool inEncodingPhase)
{
TR::Compilation *comp = cg()->comp();
TR::Instruction *thisInst = this;
bool traceLabelTargetNOPs = comp->getOption(TR_TraceLabelTargetNOPs);
TR::Instruction *prevInst = getPrev();
while (prevInst && prevInst->getOpCode().getOpCodeValue() == TR::InstOpCode::ASSOCREGS)
prevInst = prevInst->getPrev();
bool doConsider = true;
if (traceLabelTargetNOPs)
traceMsg(comp,"considerForLabelTargetNOPs check during %s phase : %p (%s), prev %p (%s)\n",
inEncodingPhase?"encoding":"estimating",this,thisInst->getOpCode().getMnemonicName(),prevInst,prevInst->getOpCode().getMnemonicName());
if (isSkipForLabelTargetNOPs())
{
if (traceLabelTargetNOPs)
traceMsg(comp,"\t%p (%s) marked with isSkipForLabelTargetNOPs = true : set doConsider=false\n",this,thisInst->getOpCode().getMnemonicName());
doConsider = false;
}
else if (prevInst && prevInst->getOpCode().getOpCodeValue() == TR::InstOpCode::BASR)
{
if (traceLabelTargetNOPs)
traceMsg(comp,"\tprev %p is a BASR : set doConsider=false\n",prevInst);
doConsider = false;
}
else if (inEncodingPhase && !wasEstimateDoneForLabelTargetNOPs())
{
// this is the case where some instructions (e.g. SCHEDON/SCHEDOFF) have been inserted between the estimate and encoding phases
// and therefore this routine would return false during estimation and true during encoding and the estimate bump for NOPs would have been missed
if (traceLabelTargetNOPs)
traceMsg(comp,"\t%p (%s) marked with wasEstimateDoneForLabelTargetNOPs = false : set doConsider=false\n",this,thisInst->getOpCode().getMnemonicName());
doConsider = false;
}
else
{
if (traceLabelTargetNOPs)
traceMsg(comp,"\t%p (%s) may need to be aligned : set doConsider=true\n",this,thisInst->getOpCode().getMnemonicName());
doConsider = true;
}
return doConsider;
}
int32_t
TR::S390LabelInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getLabelSymbol() != NULL)
{
getLabelSymbol()->setEstimatedCodeLocation(currentEstimate);
}
TR::Compilation *comp = cg()->comp();
uint8_t estimatedSize = 0;
if (getOpCode().getOpCodeValue() == TR::InstOpCode::DC)
{
estimatedSize = sizeof(uintptrj_t);
}
else
{
estimatedSize = 0;
}
if (comp->getOption(TR_EnableLabelTargetNOPs))
{
if (considerForLabelTargetNOPs(false)) // inEncodingPhase=false (in estimating phase now)
{
bool traceLabelTargetNOPs = comp->getOption(TR_TraceLabelTargetNOPs);
int32_t maxNOPBump = 256 - comp->getOptions()->getLabelTargetNOPLimit();
if (traceLabelTargetNOPs)
traceMsg(comp,"\tmaxNOPBump = %d\n",maxNOPBump);
if (getLabelSymbol() != NULL)
{
if (traceLabelTargetNOPs)
traceMsg(comp,"\tupdate label %s (%p) estimatedCodeLocation with estimate %d + maxNOPBump %d = %d\n",
cg()->getDebug()->getName(getLabelSymbol()),getLabelSymbol(),currentEstimate,maxNOPBump,currentEstimate+maxNOPBump);
getLabelSymbol()->setEstimatedCodeLocation(currentEstimate+maxNOPBump);
}
if (traceLabelTargetNOPs)
traceMsg(comp,"\tupdate estimatedSize %d by maxNOPBump %d -> %d\n",estimatedSize,maxNOPBump,estimatedSize+maxNOPBump);
estimatedSize += maxNOPBump;
setEstimatedBinaryLength(estimatedSize);
setEstimateDoneForLabelTargetNOPs();
return currentEstimate + estimatedSize;
}
}
else if (isLoopEntryAlignmentEnabled(comp))
{
// increase estimate by 256 if it's a loop alignment candidate
TR::Node * node = getNode();
if(node != NULL && node->getOpCodeValue() == TR::BBStart &&
node->getLabel() == getLabelSymbol() && node->getBlock()->firstBlockInLoop() &&
!node->getBlock()->isCold() && node->getBlock()->getFrequency() > 1000)
{
setEstimatedBinaryLength(estimatedSize+256);
return currentEstimate + estimatedSize + 256;
}
}
setEstimatedBinaryLength(estimatedSize);
return currentEstimate + estimatedSize;
}
void
TR::S390LabelInstruction::assignRegistersAndDependencies(TR_RegisterKinds kindToBeAssigned)
{
//
TR::Register **_sourceReg = sourceRegBase();
TR::Register **_targetReg = targetRegBase();
TR::MemoryReference **_sourceMem = sourceMemBase();
TR::MemoryReference **_targetMem = targetMemBase();
TR::Compilation *comp = cg()->comp();
//
// If there are any dependency conditions on this instruction, apply them.
// Any register or memory references must be blocked before the condition
// is applied, then they must be subsequently unblocked.
//
if (getDependencyConditions())
{
block(_sourceReg, _sourceRegSize, _targetReg, _targetRegSize, _targetMem, _sourceMem);
getDependencyConditions()->assignPostConditionRegisters(this, kindToBeAssigned, cg());
unblock(_sourceReg, _sourceRegSize, _targetReg, _targetRegSize, _targetMem, _sourceMem);
}
assignOrderedRegisters(kindToBeAssigned);
// Compute bit vector of free regs
// if none found, find best spill register
assignFreeRegBitVector();
// this is the return label from OOL
if (getLabelSymbol()->isEndOfColdInstructionStream())
{
TR::Machine *machine = cg()->machine();
if (comp->getOptions()->getRegisterAssignmentTraceOption(TR_TraceRARegisterStates))
traceMsg (comp,"\nOOL: taking register state snap shot\n");
cg()->setIsOutOfLineHotPath(true);
machine->takeRegisterStateSnapShot();
}
}
////////////////////////////////////////////////////////
// TR::S390BranchInstruction:: member functions
////////////////////////////////////////////////////////
void
TR::S390BranchInstruction::assignRegistersAndDependencies(TR_RegisterKinds kindToBeAssigned)
{
//
// If there are any dependency conditions on this instruction, apply them.
// Any register or memory references must be blocked before the condition
// is applied, then they must be subsequently unblocked.
//
TR::Register **_sourceReg = sourceRegBase();
TR::Register **_targetReg = targetRegBase();
TR::MemoryReference **_sourceMem = sourceMemBase();
TR::MemoryReference **_targetMem = targetMemBase();
TR::Compilation *comp = cg()->comp();
if (getDependencyConditions())
{
block(_sourceReg, _sourceRegSize, _targetReg, _targetRegSize, _targetMem, _sourceMem);
getDependencyConditions()->assignPostConditionRegisters(this, kindToBeAssigned, cg());
unblock(_sourceReg, _sourceRegSize, _targetReg, _targetRegSize, _targetMem, _sourceMem);
}
assignOrderedRegisters(kindToBeAssigned);
// Compute bit vector of free regs
// if none found, find best spill register
assignFreeRegBitVector();
cg()->freeUnlatchedRegisters();
if (getOpCode().isBranchOp() && getLabelSymbol()->isStartOfColdInstructionStream())
{
// Switch to the outlined instruction stream and assign registers.
//
TR_S390OutOfLineCodeSection *oi = cg()->findS390OutOfLineCodeSectionFromLabel(getLabelSymbol());
TR_ASSERT(oi, "Could not find S390OutOfLineCodeSection stream from label. instr=%p, label=%p\n", this, getLabelSymbol());
if (!oi->hasBeenRegisterAssigned())
oi->assignRegisters(kindToBeAssigned);
}
if (getOpCode().getOpCodeValue() == TR::InstOpCode::AP /*&& toS390SS2Instruction(this)->getLabel()*/ )
{
TR_S390OutOfLineCodeSection *oi = cg()->findS390OutOfLineCodeSectionFromLabel(toS390SS2Instruction(this)->getLabel());
TR_ASSERT(oi, "Could not find S390OutOfLineCodeSection stream from label. instr=%p, label=%p\n", this, toS390SS2Instruction(this)->getLabel());
if (!oi->hasBeenRegisterAssigned())
oi->assignRegisters(kindToBeAssigned);
}
if (getOpCode().isBranchOp() && getLabelSymbol()->isEndOfColdInstructionStream())
{
// This if statement prevents RA to restore register snapshot on regular branches to the
// OOL section merging point. Register snapshot is a snapshot of register states taken at
// OOL merge label. Using this snapshot RA can enforce the similarity of register states
// at the end of main-stream code and OOL path.
// Generally the safer option is to not reuse OOL merge label for any other purpose. This
// can be done by creating an extra label right after merge point label.
if (cg()->getIsInOOLSection())
{
// Branches from inside an OOL section to the merge-points are not allowed. Branches
// in the OOL section can jump to the end of section and then only one branch (the
// last instruction of an OOL section) jumps to the merge-point. In other words, OOL
// section must contain exactly one exit point.
TR_ASSERT(cg()->getAppendInstruction() == this, "OOL section must have only one branch to the merge point\n");
// Start RA for OOL cold path, restore register state from snap shot
TR::Machine *machine = cg()->machine();
if (comp->getOptions()->getRegisterAssignmentTraceOption(TR_TraceRARegisterStates))
traceMsg (comp, "\nOOL: Restoring Register state from snap shot\n");
cg()->setIsOutOfLineHotPath(false);
machine->restoreRegisterStateFromSnapShot();
}
// Reusing the OOL Section merge label for other branches might be unsafe.
else if(comp->getOptions()->getRegisterAssignmentTraceOption(TR_TraceRARegisterStates))
traceMsg (comp, "\nOOL: Reusing the OOL Section merge label for other branches might be unsafe.\n");
}
}
/**
*
* BranchInstruction is a pseudo instruction that generates instructions to branch to a symbol.
*
* Currently, this pseudo instruction handles the following 2 scenarios:
*
* 1. emit branch instruction to a label.
* 2. emit branch instruction to a snippet.
*
* On G5, the instruction will be a branch relative or branch on condition instruction.
* If the branch distance is within +/- 2**16, it will be done with a relative branch.
* Otherwise, it will be done with the following (horrible) sequence:
* BRAS r7, 4
* DC branching target address
* L r7,0(,r7)
* BCR r7
* Subtle note: since 64-bit is running on a Freeway or above (by definition), slow muck
* will not be generated. Note this is different than BranchOnCount and BranchOnIndex
* since they don't have long branch equivalents for themselves.
*/
uint8_t *
TR::S390BranchInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
TR::LabelSymbol * label = getLabelSymbol();
TR::Snippet * snippet = getCallSnippet();
uint8_t * cursor = instructionStart;
memset(static_cast<void*>(cursor), 0, getEstimatedBinaryLength());
TR::Compilation *comp = cg()->comp();
intptrj_t distance;
uint8_t * relocationPoint = NULL;
bool doRelocation;
bool shortRelocation = false;
bool longRelocation = false;
// msf - commented out since it does not work in cross-compile mode - TR_ASSERT(((binOpCode & 0xFF0F)== 0xA704),"Only TR::InstOpCode::BRC is handled here\n");
if (label->getCodeLocation() != NULL)
{
// Label location is known
// calculate the relative branch distance
distance = (label->getCodeLocation() - cursor)/2;
doRelocation = false;
}
else if (label->isRelativeLabel())
{
distance = label->getDistance();
doRelocation = false;
}
else
{
// Label location is unknown
// estimate the relative branch distance
distance = (cg()->getBinaryBufferStart() + label->getEstimatedCodeLocation()) -
(cursor + cg()->getAccumulatedInstructionLengthError());
distance /= 2;
doRelocation = true;
}
if (distance >= MIN_IMMEDIATE_VAL && distance <= MAX_IMMEDIATE_VAL)
{
// if distance is within 32K limit, generate short instruction
getOpCode().copyBinaryToBuffer(cursor);
if (getOpCode().isBranchOp() && (getBranchCondition() != TR::InstOpCode::COND_NOP))
{
*(cursor + 1) &= (uint8_t) 0x0F;
*(cursor + 1) |= (uint8_t) getMask();
}
*(int16_t *) (cursor + 2) |= bos(distance);
relocationPoint = cursor + 2;
shortRelocation = true;
cursor += getOpCode().getInstructionLength();
}
else
{
// Since N3 and up, generate BRCL instruction
getOpCode().copyBinaryToBuffer(cursor);
*(uint8_t *) cursor = 0xC0; // change to BRCL,keep the mask
setOpCodeValue(TR::InstOpCode::BRCL);
if (getOpCode().isBranchOp() && (getBranchCondition() != TR::InstOpCode::COND_NOP))
{
*(cursor + 1) &= (uint8_t) 0x0F;
*(cursor + 1) |= (uint8_t) getMask();
}
*(int32_t *) (cursor + 2) |= boi(distance);
longRelocation = true;
relocationPoint = cursor;
cursor += 6;
}
if (doRelocation)
{
if (shortRelocation)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative16BitRelocation(relocationPoint, label));
}
else if (longRelocation)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(relocationPoint, label));
}
else
{
AOTcgDiag1(comp, "add TR_AbsoluteMethodAddress cursor=%x\n", cursor);
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelAbsoluteRelocation(relocationPoint, label));
cg()->addProjectSpecializedRelocation(relocationPoint, NULL, NULL, TR_AbsoluteMethodAddress,
__FILE__, __LINE__, getNode());
}
}
setBinaryLength(cursor - instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
setBinaryEncoding(instructionStart);
return cursor;
}
int32_t
TR::S390BranchInstruction::estimateBinaryLength(int32_t currentEstimate)
{
int32_t length = 6;
TR::Compilation *comp = cg()->comp();
setEstimatedBinaryLength(length);
return currentEstimate + getEstimatedBinaryLength();
}
////////////////////////////////////////////////////////
// TR::S390BranchOnCountInstruction:: member functions
////////////////////////////////////////////////////////
/**
* BranchOnCountInstruction is a pseudo instruction that generates instructions to branch on count to a symbol.
*
* Currently, this pseudo instruction handles the following scenario:
*
* 1. emit branch instruction to a label.
* On G5, the instruction will be a branch relative or branch on condition instruction.
* If the branch distance is within +/- 2**16, it will be done with a relative branch.
* Otherwise, it will be done with the following (horrible) sequence:
* BRAS r7, 4
* DC branching target address
* L r7,0(,r7)
* BCT Rx,R7
* MSF:: NB::: 64-bit support needs to be added
*
* For W-Code, we generate
* BRCT Rx,*+8
* BRC 0xf, *+10
* BCRL 0xf, label
*/
uint8_t *
TR::S390BranchOnCountInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
TR::LabelSymbol * label = getLabelSymbol();
TR::Snippet * snippet = getCallSnippet();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
uint16_t binOpCode = *(uint16_t *) (getOpCode().getOpCodeBinaryRepresentation());
TR::Compilation *comp = cg()->comp();
intptrj_t distance;
uint8_t * relocationPoint = NULL;
bool doRelocation;
bool shortRelocation = false;
if (label->getCodeLocation() != NULL)
{
// Label location is known
// calculate the relative branch distance
distance = (label->getCodeLocation() - cursor) / 2;
doRelocation = false;
}
else if (label->isRelativeLabel())
{
distance = label->getDistance();
doRelocation = false;
}
else
{
// Label location is unknown
// estimate the relative branch distance
distance = (cg()->getBinaryBufferStart() + label->getEstimatedCodeLocation()) -
cursor -
cg()->getAccumulatedInstructionLengthError();
distance /= 2;
doRelocation = true;
}
if ((binOpCode & 0xFF0F) == 0xCC06) //BRCTH
{
getOpCode().copyBinaryToBuffer(instructionStart);
*(int32_t *) (cursor + 2) |= boi(distance);
relocationPoint = cursor + 2;
cursor += getOpCode().getInstructionLength();
toRealRegister(getRegisterOperand(1))->setRegisterField((uint32_t *) instructionStart);
if (doRelocation)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(relocationPoint, label));
}
}
else
{
// if distance is within 32K limit on G5
if (distance >= MIN_IMMEDIATE_VAL && distance <= MAX_IMMEDIATE_VAL)
{
getOpCode().copyBinaryToBuffer(instructionStart);
*(int16_t *) (cursor + 2) |= bos(distance);
relocationPoint = cursor + 2;
shortRelocation = true;
cursor += getOpCode().getInstructionLength();
toRealRegister(getRegisterOperand(1))->setRegisterField((uint32_t *) instructionStart);
}
else
{
TR_ASSERT(((binOpCode & 0xFF0F) == 0xA706), "Only TR::InstOpCode::BRCT is handled here\n");
TR::LabelSymbol *relLabel = TR::LabelSymbol::createRelativeLabel(cg()->trHeapMemory(),
cg(),
+4);
setLabelSymbol(relLabel);
relLabel = TR::LabelSymbol::createRelativeLabel(cg()->trHeapMemory(),
cg(),
+5);
TR::Instruction *instr;
instr = generateS390BranchInstruction(cg(), TR::InstOpCode::BRC, TR::InstOpCode::COND_MASK15, getNode(), relLabel, this);
instr->setEstimatedBinaryLength(4);
instr = generateS390BranchInstruction(cg(), TR::InstOpCode::BRC, TR::InstOpCode::COND_MASK15, getNode(), label, instr);
instr->setEstimatedBinaryLength(8);
return generateBinaryEncoding();
}
if (doRelocation)
{
if (shortRelocation)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative16BitRelocation(relocationPoint, label));
}
else
{
AOTcgDiag1(comp, "add TR_AbsoluteMethodAddress cursor=%x\n", relocationPoint);
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelAbsoluteRelocation(relocationPoint, label));
cg()->addProjectSpecializedRelocation(relocationPoint, NULL, NULL, TR_AbsoluteMethodAddress,
__FILE__, __LINE__, getNode());
}
}
}
toRealRegister(getRegisterOperand(1))->setRegisterField((uint32_t *) instructionStart);
setBinaryLength(cursor - instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
setBinaryEncoding(instructionStart);
return cursor;
}
int32_t
TR::S390BranchOnCountInstruction::estimateBinaryLength(int32_t currentEstimate)
{
setEstimatedBinaryLength(getOpCode().getInstructionLength());
//code could be expanded into BRAS(4)+DC(4)+L(4)+BCT(4) sequence
setEstimatedBinaryLength(16);
return currentEstimate + getEstimatedBinaryLength();
}
bool
TR::S390BranchOnCountInstruction::refsRegister(TR::Register * reg)
{
if (matchesAnyRegister(reg, getRegisterOperand(1)))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
else
{
return false;
}
}
/**
* BranchOnIndexInstruction is a pseudo instruction that generates instructions to branch to a symbol.
*
* Currently, this pseudo instruction handles the following scenario:
*
* 1. emit branch instruction to a label.
* On G5, the instruction will be a branch relative or branch on condition instruction.
* If the branch distance is within +/- 2**16, it will be done with a relative branch.
* Otherwise, it will be done with the following (horrible) sequence:
* BRAS r7, 4
* DC branching target address
* L r7,0(,r7)
* BXL/BXH rx,ry,r7
* MSF:: NB::: 64-bit support needs to be added -- Done: LD
* LD: could do better for long displacement on N3 and 64bit--TODO
*/
uint8_t *
TR::S390BranchOnIndexInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
TR::LabelSymbol * label = getLabelSymbol();
TR::Snippet * snippet = getCallSnippet();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
uint16_t binOpCode = *(uint16_t *) (getOpCode().getOpCodeBinaryRepresentation());
bool shortRelocation = false;
intptrj_t distance;
uint8_t * relocationPoint = NULL;
bool doRelocation;
if (label->getCodeLocation() != NULL)
{
// Label location is known
// calculate the relative branch distance
distance = (label->getCodeLocation() - cursor) / 2;
doRelocation = false;
}
else
{
// Label location is unknown
// estimate the relative branch distance
distance = (cg()->getBinaryBufferStart() + label->getEstimatedCodeLocation()) -
cursor -
cg()->getAccumulatedInstructionLengthError();
distance /= 2;
doRelocation = true;
}
// if distance is within 32K limit on G5
if (distance >= MIN_IMMEDIATE_VAL && distance <= MAX_IMMEDIATE_VAL)
{
getOpCode().copyBinaryToBuffer(instructionStart);
TR::Register * srcReg = getRegForBinaryEncoding(getRegisterOperand(2));
*(int16_t *) (cursor + 2) |= bos(distance);
relocationPoint = cursor + 2;
shortRelocation = true;
cursor += getOpCode().getInstructionLength();
toRealRegister(getRegisterOperand(1))->setRegisterField((uint32_t *) instructionStart);
toRealRegister(srcReg)->setRegister2Field((uint32_t *) instructionStart);
}
else
{
TR_ASSERT_FATAL(false, "Cannot encode branch on index instruction because distance (%d) is out of range", distance);
}
if (doRelocation)
{
if (shortRelocation)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative16BitRelocation(relocationPoint, label));
}
else
{
AOTcgDiag1(cg()->comp(), "add TR_AbsoluteMethodAddress cursor=%x\n", relocationPoint);
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelAbsoluteRelocation(relocationPoint, label));
cg()->addProjectSpecializedRelocation(relocationPoint, NULL, NULL, TR_AbsoluteMethodAddress,
__FILE__, __LINE__, getNode());
}
}
toRealRegister(getRegisterOperand(1))->setRegisterField((uint32_t *) instructionStart);
setBinaryLength(cursor - instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
setBinaryEncoding(instructionStart);
return cursor;
}
int32_t
TR::S390BranchOnIndexInstruction::estimateBinaryLength(int32_t currentEstimate)
{
setEstimatedBinaryLength(getOpCode().getInstructionLength());
//code could be expanded into BRAS(4)+DC(4)+L(4)+BXLE(4) sequence
//or BRAS(4)+DC(8)+LG(6)+BXLG(6) sequence
if (sizeof(intptrj_t) == 8)
{
setEstimatedBinaryLength(24);
}
else
{
setEstimatedBinaryLength(16);
}
return currentEstimate + getEstimatedBinaryLength();
}
bool
TR::S390BranchOnIndexInstruction::refsRegister(TR::Register * reg)
{
if (matchesAnyRegister(reg, getRegisterOperand(1), getRegisterOperand(2)))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390FenceInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
uint8_t *
TR::S390PseudoInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
TR::Compilation *comp = cg()->comp();
if (_fenceNode != NULL) // must be fence node
{
if (_fenceNode->getRelocationType() == TR_AbsoluteAddress)
{
for (int32_t i = 0; i < _fenceNode->getNumRelocations(); ++i)
{
*(uint8_t * *) (_fenceNode->getRelocationDestination(i)) = instructionStart;
}
}
else if (_fenceNode->getRelocationType() == TR_EntryRelative32Bit)
{
for (int32_t i = 0; i < _fenceNode->getNumRelocations(); ++i)
{
*(uint32_t *) (_fenceNode->getRelocationDestination(i)) = boi(cg()->getCodeLength());
}
}
else // entryrelative16bit
{
for (int32_t i = 0; i < _fenceNode->getNumRelocations(); ++i)
{
*(uint16_t *) (_fenceNode->getRelocationDestination(i)) = bos((uint16_t) cg()->getCodeLength());
}
}
}
setBinaryLength(0);
if (_callDescLabel != NULL) // We have to emit a branch around a 8-byte aligned call descriptor.
{
// For zOS-31 XPLINK, if the call descriptor is too far away from the native call NOP, we have
// to manually emit a branch around the call descriptor in the main line code.
// BRC 4 + Padding
// <Padding>
// DC <call Descriptor> // 8-bytes aligned.
_padbytes = ((intptrj_t)(cursor + 4) + 7) / 8 * 8 - (intptrj_t)(cursor + 4);
// BRC 4 + padding.
*((uint32_t *) cursor) = boi(0xA7F40000 + 6 + _padbytes / 2);
cursor += sizeof(uint32_t);
// Add Padding to make sure Call Descriptor is aligned.
if (_padbytes == 2)
{
*(int16_t *) cursor = bos(0x0000); // padding 2-bytes
cursor += 2;
}
else if (_padbytes == 4)
{
*(int32_t *) cursor = boi(0x00000000);
cursor += 4;
}
else if (_padbytes == 6)
{
*(int32_t *) cursor = boi(0x00000000);
cursor += 4;
*(uint16_t *) cursor = bos(0x0000);
cursor += 2;
}
TR_ASSERT(((intptrj_t)cursor) % 8 == 0, "Call Descriptor not aligned\n");
// Encode the Call Descriptor
memcpy (cursor, &_callDescValue,8);
getCallDescLabel()->setCodeLocation(cursor);
cursor += 8;
setBinaryLength(cursor - instructionStart);
}
setBinaryEncoding(instructionStart);
return cursor;
}
int32_t
TR::S390PseudoInstruction::estimateBinaryLength(int32_t currentEstimate)
{
setEstimatedBinaryLength(0);
return currentEstimate;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390DebugCounterBumpInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
/**
* This instruction is bumps the value at the snippet corresponding to the address of the debug counter count.
* The valid opcode is TR::InstOpCode::DCB
*
* Either 2 or 4 instructions are encoded matching the following conditions:
*
* If a free register was saved: Otherwise if a spill is required:
* STG Rscrtch, offToLongDispSlot(,GPR5)
* LGRL Rscrtch, counterRelocation LGRL Rscrtch, counterRelocation
* AGSI 0(Rscrtch), delta AGSI 0(Rscrtch), delta
* LG Rscrtch, offToLongDispSlot(,GPR5)
*
* If the platform is 32-bit, ASI replaces AGSI
*/
uint8_t *
TR::S390DebugCounterBumpInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
TR::Compilation *comp = cg()->comp();
int32_t offsetToLongDispSlot = (cg()->getLinkage())->getOffsetToLongDispSlot();
TR::RealRegister * scratchReg = getAssignableReg();
bool spillNeeded = true;
// If we found a free register during RA, we don't need to spill
if (scratchReg)
{
spillNeeded = false;
}
else
{
scratchReg = assignBestSpillRegister();
}
TR_ASSERT(scratchReg!=NULL, "TR_S390DebugCounterBumpInstruction::generateBinaryEncoding -- A scratch reg should always be found.");
traceMsg(comp, "[%p] DCB using %s as scratch reg with spill=%s\n", this, cg()->getDebug()->getName(scratchReg), spillNeeded ? "true" : "false");
if (spillNeeded)
{
*(int32_t *) cursor = boi(0xE3005000 | (offsetToLongDispSlot&0xFFF)); // STG Rscrtch,offToLongDispSlot(,GPR5)
scratchReg->setRegisterField((uint32_t *)cursor); //
cursor += 4; //
*(int16_t *) cursor = bos(0x0024); //
cursor += 2; //
}
*(int16_t *) cursor = bos(0xC408); // LGRL Rscrtch, counterRelocation
scratchReg->setRegisterField((uint32_t *)cursor); //
cg()->addRelocation(new (cg()->trHeapMemory()) //
TR::LabelRelative32BitRelocation(cursor, getCounterSnippet()->getSnippetLabel())); //
cursor += 6; //
*(int32_t *) cursor = boi(0xEB000000 | (((int8_t) getDelta()) << 16)); // On 64-bit platforms
scratchReg->setBaseRegisterField((uint32_t *)cursor); // AGSI 0(Rscrtch), delta
cursor += 4; //
*(int16_t *) cursor = TR::Compiler->target.is64Bit() ? bos(0x007A) : bos(0x006A); // On 32-bit platforms
cursor += 2; // ASI 0(Rscrtch), delta
if (spillNeeded)
{
*(int32_t *) cursor = boi(0xE3005000 | (offsetToLongDispSlot&0xFFF)); // LG Rscrtch,offToLongDispSlot(,GPR5)
scratchReg->setRegisterField((uint32_t *)cursor); //
cursor += 4; //
*(int16_t *) cursor = bos(0x0004); //
cursor += 2; //
}
setEstimatedBinaryLength(spillNeeded ? 24 : 12);
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
return cursor;
}
// TR::S390ImmInstruction:: member functions
/**
* This instruction is used to generate a constant value in JIT code
* so the valid opcode is TR::InstOpCode::DC
*/
uint8_t *
TR::S390ImmInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
TR_ASSERT( getOpCode().getOpCodeValue() == TR::InstOpCode::DC, "ImmInstruction is for TR::InstOpCode::DC only!");
TR::Compilation *comp = cg()->comp();
/*
getOpCode().copyBinaryToBuffer(instructionStart);
(*(uint32_t*) cursor) &= 0xFFFF0000;
(*(uint32_t*) cursor) |= getSourceImmediate();
*/
(*(uint32_t *) cursor) = boi(getSourceImmediate());
#ifdef J9_PROJECT_SPECIFIC
//AOT Relocation
if (getEncodingRelocation())
addEncodingRelocation(cg(), cursor, __FILE__, __LINE__, getNode());
#endif
if (std::find(comp->getStaticPICSites()->begin(), comp->getStaticPICSites()->end(), this) != comp->getStaticPICSites()->end())
{
// On 64-bit, the second word of the pointer is the one in getStaticPICSites.
// We can't register the first word because the second word wouldn't yet
// be binary-encoded by the time we need to compute the proper hash key.
//
void **locationToPatch = (void**)(cursor - (TR::Compiler->target.is64Bit()?4:0));
cg()->jitAddPicToPatchOnClassUnload(*locationToPatch, locationToPatch);
}
if (std::find(comp->getStaticHCRPICSites()->begin(), comp->getStaticHCRPICSites()->end(), this) != comp->getStaticHCRPICSites()->end())
{
// On 64-bit, the second word of the pointer is the one in getStaticHCRPICSites.
// We can't register the first word because the second word wouldn't yet
// be binary-encoded by the time we need to compute the proper hash key.
//
void **locationToPatch = (void**)(cursor - (TR::Compiler->target.is64Bit()?4:0));
cg()->jitAddPicToPatchOnClassRedefinition(*locationToPatch, locationToPatch);
cg()->addExternalRelocation(new (cg()->trHeapMemory()) TR::ExternalRelocation((uint8_t *)locationToPatch, (uint8_t *)*locationToPatch, TR_HCR, cg()), __FILE__,__LINE__, getNode());
}
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
#if defined(DEBUG) || defined(PROD_WITH_ASSUMES)
/**
* The following safe virtual downcast method is only used in an assertion
* check within "toS390ImmInstruction"
*/
TR::S390ImmInstruction *
TR::S390ImmInstruction::getS390ImmInstruction()
{
return this;
}
#endif
// TR::S390ImmInstruction:: member functions
/**
* This instruction is used to generate a constant value in JIT code
* so the valid opcode is TR::InstOpCode::DC
*/
uint8_t *
TR::S390Imm2Instruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
TR_ASSERT( getOpCode().getOpCodeValue() == TR::InstOpCode::DC2,"ImmInstruction is for TR::InstOpCode::DC2 only!");
TR::Compilation *comp = cg()->comp();
(*(uint16_t *) cursor) = boi(getSourceImmediate());
#ifdef J9_PROJECT_SPECIFIC
//AOT Relocation
if (getEncodingRelocation())
addEncodingRelocation(cg(), cursor, __FILE__, __LINE__, getNode());
#endif
if (std::find(comp->getStaticPICSites()->begin(), comp->getStaticPICSites()->end(), this) != comp->getStaticPICSites()->end())
{
// On 64-bit, the second word of the pointer is the one in getStaticPICSites.
// We can't register the first word because the second word wouldn't yet
// be binary-encoded by the time we need to compute the proper hash key.
//
void **locationToPatch = (void**)(cursor - (TR::Compiler->target.is64Bit()?4:0));
cg()->jitAddPicToPatchOnClassUnload(*locationToPatch, locationToPatch);
}
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
// TR::S390ImmSnippetInstruction:: member functions
uint8_t *
TR::S390ImmSnippetInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
getOpCode().copyBinaryToBuffer(instructionStart);
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
///////////////////////////////////////////////////////////
// TR::S390ImmSymInstruction:: member functions
///////////////////////////////////////////////////////////
uint8_t *
TR::S390ImmSymInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
getOpCode().copyBinaryToBuffer(instructionStart);
(*(uint32_t *) cursor) |= boi(getSourceImmediate());
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
///////////////////////////////////////////////////////
// TR::S390RegInstruction:: member functions
///////////////////////////////////////////////////////
bool
TR::S390RegInstruction::refsRegister(TR::Register * reg)
{
if (matchesTargetRegister(reg))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
uint8_t *
TR::S390RegInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
getOpCode().copyBinaryToBuffer(instructionStart);
if (getOpCode().isBranchOp() && (getBranchCondition() != TR::InstOpCode::COND_NOP))
{
*(instructionStart + 1) &= (uint8_t) 0x0F;
*(instructionStart + 1) |= (uint8_t) getMask();
}
TR::Register * tgtReg = getRegForBinaryEncoding(getRegisterOperand(1));
toRealRegister(tgtReg)->setRegister2Field((uint32_t *) cursor);
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
void
TR::S390RegInstruction::assignRegistersNoDependencies(TR_RegisterKinds kindToBeAssigned)
{
TR::Machine *machine = cg()->machine();
setRegisterOperand(1,machine->assignBestRegister(getRegisterOperand(1), this, BOOKKEEPING));
return;
}
// TR::S390RRInstruction:: member functions /////////////////////////////////////////
bool
TR::S390RRInstruction::refsRegister(TR::Register * reg)
{
if (matchesTargetRegister(reg) || matchesAnyRegister(reg, getRegisterOperand(2)))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
uint8_t *
TR::S390RRInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t instructionLength = getOpCode().getInstructionLength();
getOpCode().copyBinaryToBuffer(instructionStart);
// HACK WARNING!!!!
// Should change references to use RRE Instruction instead of RR instruction
//
if (instructionLength == 4)
{
if (getRegisterOperand(2))
{
TR::Register * srcReg = getRegForBinaryEncoding(getRegisterOperand(2));
toRealRegister(srcReg)->setRegisterField((uint32_t *) cursor, 0);
}
TR::Register * tgtReg = getRegForBinaryEncoding(getRegisterOperand(1));
toRealRegister(tgtReg)->setRegisterField((uint32_t *) cursor, 1);
}
else // RR
{
int32_t i=1;
if (getFirstConstant() >=0)
{
(*(uint32_t *) cursor) &= boi(0xFF0FFFFF);
(*(uint32_t *) cursor) |= boi((getFirstConstant() & 0xF)<< 20);
}
else
toRealRegister(getRegForBinaryEncoding(getRegisterOperand(i++)))->setRegister1Field((uint32_t *) cursor);
if (getSecondConstant() >= 0)
{
(*(uint32_t *) cursor) &= boi(0xFFF0FFFF);
(*(uint32_t *) cursor) |= boi((getSecondConstant() & 0xF)<< 16);
}
else
toRealRegister(getRegForBinaryEncoding(getRegisterOperand(i)))->setRegister2Field((uint32_t *) cursor);
}
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
// TranslateInstruction
bool
TR::S390TranslateInstruction::refsRegister(TR::Register * reg)
{
if (matchesAnyRegister(reg, getRegisterOperand(1)) ||
matchesAnyRegister(reg, getTableRegister()) ||
matchesAnyRegister(reg, getTermCharRegister()) ||
matchesAnyRegister(reg, getRegisterOperand(2)))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
uint8_t *
TR::S390TranslateInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t instructionLength = getOpCode().getInstructionLength();
getOpCode().copyBinaryToBuffer(instructionStart);
toRealRegister(getRegisterOperand(2))->setRegisterField((uint32_t *) cursor, 0);
toRealRegister(getRegForBinaryEncoding(getRegisterOperand(1)))->setRegisterField((uint32_t *) cursor, 1);
// LL: Write mask if present
if (isMaskPresent())
{
setMaskField((uint32_t *) cursor, getMask(), 3);
}
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
// TR::S390RRFInstruction:: member functions /////////////////////////////////////////
bool
TR::S390RRFInstruction::refsRegister(TR::Register * reg)
{
if (matchesTargetRegister(reg) || matchesAnyRegister(reg, getRegisterOperand(2)) ||
(_isSourceReg2Present && matchesAnyRegister(reg, getRegisterOperand(3))))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
uint8_t *
TR::S390RRFInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t instructionLength = getOpCode().getInstructionLength();
getOpCode().copyBinaryToBuffer(instructionStart);
TR::Compilation *comp = cg()->comp();
TR::Register *srcReg = getRegisterOperand(2);
bool isSrcPair = false, isSrc2Pair = false, isTgtPair = false;
TR::RegisterPair* srcRegPair = srcReg != NULL ? srcReg->getRegisterPair() : NULL;
if (srcRegPair != NULL)
isSrcPair = true;
TR::Register *src2Reg = NULL;
TR::RegisterPair* src2RegPair = NULL;
if (isSourceRegister2Present())
{
src2Reg = getRegisterOperand(3);
src2RegPair = getRegisterOperand(3)->getRegisterPair();
}
if (src2RegPair != NULL) // handle VRFs!
isSrc2Pair = true;
TR::Register *tgtReg = getRegisterOperand(1);
TR::RegisterPair* tgtRegPair = tgtReg != NULL ? tgtReg->getRegisterPair() : NULL;
if (tgtRegPair != NULL)
isTgtPair = true;
switch(getKind())
{
// note that RRD and RRF have swapped R1 and R3 positions but in both cases R1 is the target and R3 is a source (src2 in particular)
case TR::Instruction::IsRRD: // nnnn 1x32 e.g. MSDBR/MSEBR/MSER/MSDR
if ( !isTgtPair )
toRealRegister(tgtReg)->setRegisterField((uint32_t *) cursor, 3); // encode target in R1 position
else
toRealRegister(tgtRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 3);
if ( !isSrcPair )
toRealRegister(srcReg)->setRegisterField((uint32_t *) cursor, 0); // encode src in R2 position
else
toRealRegister(srcRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 0);
if ( !isSrc2Pair )
toRealRegister(getRegisterOperand(3))->setRegisterField((uint32_t *) cursor, 1); // encode src2 in R3 position
else
toRealRegister(src2RegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 1);
break;
case TR::Instruction::IsRRF: // nnnn 3x12 e.g. IEDTR/IEXTR
if ( !isTgtPair )
toRealRegister(tgtReg)->setRegisterField((uint32_t *) cursor, 1); // encode target in R1 position
else
toRealRegister(tgtRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 1);
if ( !isSrcPair )
toRealRegister(srcReg)->setRegisterField((uint32_t *) cursor, 0); // encode src in R2 position
else
toRealRegister(srcRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 0);
if ( !isSrc2Pair )
toRealRegister(getRegisterOperand(3))->setRegisterField((uint32_t *) cursor, 3); // encode src2 in R3 position
else
toRealRegister(src2RegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 3);
break;
case TR::Instruction::IsRRF2: // M3, ., R1, R2
if (tgtReg != NULL)
{
if ( !isTgtPair )
toRealRegister(getRegForBinaryEncoding(tgtReg))->setRegisterField((uint32_t *) cursor, 1);
else
toRealRegister(tgtRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 1);
}
if (srcReg != NULL)
{
if ( !isSrcPair )
toRealRegister(getRegForBinaryEncoding(srcReg))->setRegisterField((uint32_t *) cursor, 0);
else
toRealRegister(srcRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 0);
}
setMaskField((uint32_t *) cursor, getMask3(), 3);
break;
case TR::Instruction::IsRRF3: // R3, M4, R1, R2
if ( !isTgtPair )
toRealRegister(tgtReg)->setRegisterField((uint32_t *) cursor, 1);
else
toRealRegister(tgtRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 1);
if ( !isSrcPair )
toRealRegister(srcReg)->setRegisterField((uint32_t *) cursor, 0);
else
toRealRegister(srcRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 0);
if ( !isSrc2Pair )
toRealRegister(getRegisterOperand(3))->setRegisterField((uint32_t *) cursor, 3);
else
toRealRegister(src2RegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 3);
setMaskField((uint32_t *) cursor, getMask4(), 2);
break;
case TR::Instruction::IsRRF4: // ., M4, R1, R2
if ( !isTgtPair )
toRealRegister(tgtReg)->setRegisterField((uint32_t *) cursor, 1);
else
toRealRegister(tgtRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 1);
if ( !isSrcPair )
toRealRegister(srcReg)->setRegisterField((uint32_t *) cursor, 0);
else
toRealRegister(srcRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 0);
setMaskField((uint32_t *) cursor, getMask4(), 2);
break;
case TR::Instruction::IsRRF5: // ., M4, R1, R2
if ( !isTgtPair )
toRealRegister(tgtReg)->setRegisterField((uint32_t *) cursor, 1);
else
toRealRegister(tgtRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 1);
if ( !isSrcPair )
toRealRegister(srcReg)->setRegisterField((uint32_t *) cursor, 0);
else
toRealRegister(srcRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 0);
setMaskField((uint32_t *) cursor, getMask4(), 2);
setMaskField((uint32_t *) cursor, getMask3(), 3);
break;
default:
TR_ASSERT( 0,"Unsupported RRF format!");
}
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
// TR::S390RRRInstruction:: member functions /////////////////////////////////////////
bool
TR::S390RRRInstruction::refsRegister(TR::Register * reg)
{
if (matchesTargetRegister(reg) || matchesAnyRegister(reg, getRegisterOperand(2)) ||
(matchesAnyRegister(reg, getRegisterOperand(3))))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
uint8_t *
TR::S390RRRInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t instructionLength = getOpCode().getInstructionLength();
getOpCode().copyBinaryToBuffer(instructionStart);
TR::Compilation *comp = cg()->comp();
TR::RegisterPair* srcRegPair = getRegisterOperand(2)->getRegisterPair();
TR::RegisterPair* src2RegPair = getRegisterOperand(3)->getRegisterPair();
TR::RegisterPair* tgtRegPair = getRegisterOperand(1)->getRegisterPair();
bool isTgtFPPair = false;
if (!isTgtFPPair)
{
toRealRegister(getRegisterOperand(2))->setRegisterField((uint32_t *) cursor, 0);
toRealRegister(getRegisterOperand(1))->setRegisterField((uint32_t *) cursor, 1);
toRealRegister(getRegisterOperand(3))->setRegisterField((uint32_t *) cursor, 3);
}
else
{
toRealRegister(srcRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 0);
toRealRegister(tgtRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 1);
toRealRegister(src2RegPair->getHighOrder())->setRegisterField((uint32_t *) cursor, 3);
}
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
////////////////////////////////////////////////////////////////////////////
// TR::S390RIInstruction:: member functions
////////////////////////////////////////////////////////////////////////////
/**
* RI Format
* ________ ____ ____ _________________
* |Op Code | R1 |OpCd| I2 |
* |________|____|____|_________________|
* 0 8 12 16 31
*
*/
uint8_t *
TR::S390RIInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
getOpCode().copyBinaryToBuffer(instructionStart);
if (getRegisterOperand(1) != NULL)
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
// it is either RI or RIL
if (getOpCode().getInstructionLength() == 4)
{
(*(int16_t *) (cursor + 2)) |= bos((int16_t) getSourceImmediate());
}
else
{
//TODO: to remove this code when it's sure there is
// no RIL instructions going through this path
TR_ASSERT( 0,"Do not use RI to generate RIL instructions");
(*(int32_t *) (cursor + 2)) |= boi((int32_t) getSourceImmediate());
}
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
////////////////////////////////////////////////////////////////////////////
// TR::S390RILInstruction:: member functions
////////////////////////////////////////////////////////////////////////////
/**
* RIL Format
* ________ ____ ____ ______________________________
* |Op Code | R1 |OpCd| I2 |
* |________|____|____|______________________________|
* 0 8 12 16 47
*/
bool
TR::S390RILInstruction::refsRegister(TR::Register * reg)
{
if (reg == getRegisterOperand(1))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
int32_t
TR::S390RILInstruction::estimateBinaryLength(int32_t currentEstimate)
{
int32_t delta = 0;
TR::Compilation *comp = cg()->comp();
if (TR::Compiler->target.is64Bit() &&
(getOpCode().getOpCodeValue() == TR::InstOpCode::LGRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LGFRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LLGFRL
)
)
{
// We could end up generating
// LLIHF Rscrtch, (addr&0xFFFFFFFF00000000)>>32
// IILF Rscrtch, (addr&0xFFFFFFFF)
// LG Rtgt , 0(,Rscrtch)
//
delta = 12;
}
else if (TR::Compiler->target.is64Bit() &&
getOpCode().getOpCodeValue() == TR::InstOpCode::STGRL
)
{
// We could end up generating
// LLIHF Rscrtch, (addr&0xFFFFFFFF00000000)>>32
// IILF Rscrtch, (addr&0xFFFFFFFF)
// STG Rscrtch, SPILLSLOT(,GPR5)
// STG Rtgt , 0(,Rscrtch)
// LG Rscrtch, SPILLSLOT(,GPR5)
//
delta = 24;
}
else if (TR::Compiler->target.is64Bit() &&
(getOpCode().getOpCodeValue() == TR::InstOpCode::STRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LRL))
{
// We could end up generating
// STG Rscrtch, SPILLSLOT(,GPR5)
// LLIHF Rscrtch, (addr&0xFFFFFFFF00000000)>>32
// IILF Rscrtch, (addr&0xFFFFFFFF)
// ST Rtgt , 0(,Rscrtch) / L Rtgt , 0(,Rscrtch)
// LG Rscrtch, SPILLSLOT(,GPR5)
//
delta = 22;
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::LARL || getOpCode().getOpCodeValue() == TR::InstOpCode::LRL)
{
//code could have 2 byte padding
// LARL could also have 8 more bytes for patching if target becomes unaddressable.
delta = 10;
}
else
{
delta = 2;
}
setEstimatedBinaryLength(getOpCode().getInstructionLength()+delta);
return currentEstimate + getEstimatedBinaryLength();
}
/**
* Compute Target Offset
* This method calculates the target address by computing the offset in halfwords. This value will
* be used by binary encoding to set the correct target. Example of instruction that uses this are
* BRCL and BRASL instruction. Usually its used for getting helper method's target addresses.
*
* @param offset original value of offset in halfwords.
* @param currInst current instruction address.
*
* @return offset to target address in half words
*/
int32_t
TR::S390RILInstruction::adjustCallOffsetWithTrampoline(int32_t offset, uint8_t * currentInst)
{
int32_t offsetHalfWords = offset;
// Check to make sure that we can reach our target! Otherwise, we need to look up appropriate
// trampoline and branch through the trampoline.
if (cg()->directCallRequiresTrampoline(getTargetPtr(), (intptrj_t)currentInst))
{
intptrj_t targetAddr;
#if defined(CODE_CACHE_TRAMPOLINE_DEBUG)
printf("Target: %p, Cursor: %p, Our Reference # is: %d\n",getTargetPtr(),(uintptrj_t)currentInst,getSymbolReference()->getReferenceNumber());
#endif
if (getSymbolReference()->getReferenceNumber() < TR_S390numRuntimeHelpers)
targetAddr = TR::CodeCacheManager::instance()->findHelperTrampoline(getSymbolReference()->getReferenceNumber(), (void *)currentInst);
else
targetAddr = cg()->fe()->methodTrampolineLookup(cg()->comp(), getSymbolReference(), (void *)currentInst);
TR_ASSERT_FATAL(TR::Compiler->target.cpu.isTargetWithinBranchRelativeRILRange(targetAddr, (intptrj_t)currentInst),
"Local trampoline must be directly reachable.");
offsetHalfWords = (int32_t)((targetAddr - (uintptrj_t)currentInst) / 2);
}
return offsetHalfWords;
}
uint8_t *
TR::S390RILInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t i2;
bool spillNeeded = false;
TR::Compilation *comp = cg()->comp();
int32_t offsetToLongDispSlot = (cg()->getLinkage())->getOffsetToLongDispSlot();
if (isLiteralPoolAddress())
{
setTargetSnippet(cg()->getFirstSnippet());
}
if (getTargetSnippet() &&
getTargetSnippet()->getKind() == TR::Snippet::IsConstantData)
{
// Using RIL to get to a literal pool entry
//
getOpCode().copyBinaryToBuffer(instructionStart);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, getTargetSnippet()->getSnippetLabel()));
cursor += getOpCode().getInstructionLength();
}
else if (getTargetSnippet() &&
getTargetSnippet()->getKind() == TR::Snippet::IsWritableData)
{
// Using RIL to get to a literal pool entry
//
getOpCode().copyBinaryToBuffer(instructionStart);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, getTargetSnippet()->getSnippetLabel()));
cursor += getOpCode().getInstructionLength();
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::LRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LGRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LGFRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LLGFRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::STRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::STGRL
)
{
{
// Using RIL to get to a Static
//
uintptrj_t addr = getTargetPtr();
i2 = (int32_t)((addr - (uintptrj_t)cursor) / 2);
if (TR::Compiler->target.cpu.isTargetWithinBranchRelativeRILRange((intptrj_t)getTargetPtr(), (intptrj_t)cursor))
{
getOpCode().copyBinaryToBuffer(instructionStart);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
(*(int32_t *) (cursor + 2)) |= boi(i2);
cursor += getOpCode().getInstructionLength();
}
else // We need to do things the old fashioned way
{
TR_ASSERT( TR::Compiler->target.is64Bit() ,"We should only be here on 64-bit platforms\n");
TR::RealRegister * scratchReg = NULL;
TR::RealRegister * sourceReg = NULL;
if (getOpCode().getOpCodeValue() == TR::InstOpCode::LGRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LGFRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LLGFRL )
{
sourceReg = (TR::RealRegister * )((TR::S390RegInstruction *)this)->getRegisterOperand(1);
if (!scratchReg) scratchReg = sourceReg;
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::STGRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::STRL ||
getOpCode().getOpCodeValue() == TR::InstOpCode::LRL)
{
sourceReg = (TR::RealRegister * )((TR::S390RegInstruction *)this)->getRegisterOperand(1);
if (!scratchReg) scratchReg = assignBestSpillRegister();
spillNeeded = true;
}
else
{
TR_ASSERT( 0, "Unsupported opcode\n");
}
// Spill the scratch register
//
if (spillNeeded)
{
*(int32_t *) cursor = boi(0xE3005000 | (offsetToLongDispSlot&0xFFF)); // STG scratchReg, offToLongDispSlot(,GPR5)
scratchReg->setRegisterField((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(0x0024);
cursor += 2;
}
// Get the target address into scratch register
//
if (((uint64_t)addr)>>32)
{
// LLIHF scratchReg, <addr&0xFFFFFFFF00000000>
//
*(int32_t *) cursor = boi(0xC00E0000 | (uint32_t)(0x0000FFFF&(((uint64_t)addr)>>48)));
scratchReg->setRegisterField((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(0xFFFF&(uint16_t)(((uint64_t)addr)>>32));
cursor += 2;
if (addr&0xFFFFFFFF) // LLIHF does zero out low word... so only do IILF if non-NULL
{
// IILF scratchReg, <addr&0x00000000FFFFFFFF>
//
*(int32_t *) cursor = boi(0xC0090000 | (0xFFFF&((uint32_t)addr>>16)));
scratchReg->setRegisterField((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(addr&0xFFFF);
cursor += 2;
}
}
else // Note, we must handle NULL correctly
{
// LLILF scratchReg, <addr&0x00000000FFFFFFFF>
//
*(int32_t *) cursor = boi(0xC00F0000 | (0xFFFF&((uint32_t)addr>>16)));
scratchReg->setRegisterField((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(addr&0xFFFF);
cursor += 2;
}
if (getOpCode().getOpCodeValue() == TR::InstOpCode::LGRL)
{
// LG sourceReg, 0(,scratchReg)
//
*(int32_t *) cursor = boi(0xE3000000); // LG sourceReg, 0(,scratchReg)
sourceReg->setRegisterField((uint32_t *)cursor);
scratchReg->setBaseRegisterField((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(0x0004);
cursor += 2;
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::LGFRL)
{
// LGF sourceReg, 0(,scratchReg)
//
*(int32_t *) cursor = boi(0xE3000000); // LGF sourceReg, 0(,scratchReg)
sourceReg->setRegisterField((uint32_t *)cursor);
scratchReg->setRegister2Field((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(0x0014);
cursor += 2;
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::LLGFRL)
{
// LLGF sourceReg, 0(,scratchReg)
//
*(int32_t *) cursor = boi(0xE3000000); // LLGF sourceReg, 0(,scratchReg)
sourceReg->setRegisterField((uint32_t *)cursor);
scratchReg->setRegister2Field((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(0x0016);
cursor += 2;
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::LRL)
{
// L sourceReg, 0(,scratchReg)
//
*(int32_t *) cursor = boi(0x58000000); // L sourceReg, 0(,scratchReg)
sourceReg->setRegisterField((uint32_t *)cursor);
scratchReg->setRegister2Field((uint32_t *)cursor);
cursor += 4;
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::STGRL)
{
// STGRL sourceReg, 0(,scratchReg)
//
*(int32_t *) cursor = boi(0xE3000000); // STG sourceReg, 0(,scratchReg)
sourceReg->setRegisterField((uint32_t *)cursor);
scratchReg->setRegister2Field((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(0x0024);
cursor += 2;
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::STRL)
{
// ST sourceReg, 0(,scratchReg)
//
*(int32_t *) cursor = boi(0x50000000); // ST sourceReg, 0(,scratchReg)
sourceReg->setRegisterField((uint32_t *)cursor);
scratchReg->setRegister2Field((uint32_t *)cursor);
cursor += 4;
}
else
{
TR_ASSERT( 0,"Unrecognized opcode\n");
}
// Unspill the scratch register
//
if (spillNeeded)
{
*(int32_t *) cursor = boi(0xE3005000 | (offsetToLongDispSlot&0xFFF)); // LG scratchReg, offToLongDispSlot(,GPR5)
scratchReg->setRegisterField((uint32_t *)cursor);
cursor += 4;
*(int16_t *) cursor = bos(0x0004);
cursor += 2;
}
}
}
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::EXRL)
{
i2 = (int32_t)((getTargetPtr() - (uintptrj_t)cursor) / 2);
if (isImmediateOffsetInBytes()) i2 = (int32_t)(getImmediateOffsetInBytes() / 2);
getOpCode().copyBinaryToBuffer(instructionStart);
(*(uint32_t *) cursor) &= boi(0xFFFF0000);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
if (getTargetSnippet() != NULL)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, getTargetSnippet()->getSnippetLabel()));
}
else if (getTargetLabel() != NULL)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, getTargetLabel()));
}
cursor += getOpCode().getInstructionLength();
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::LARL)
{
// Check if this LARL is loading unloadable constant
TR_OpaqueClassBlock * unloadableClass = NULL;
bool doRegisterPIC = false;
if (std::find(comp->getStaticPICSites()->begin(), comp->getStaticPICSites()->end(), this) != comp->getStaticPICSites()->end())
{
unloadableClass = (TR_OpaqueClassBlock *) getTargetPtr();
doRegisterPIC = true;
}
else if (std::find(comp->getStaticMethodPICSites()->begin(), comp->getStaticMethodPICSites()->end(), this) != comp->getStaticMethodPICSites()->end())
{
unloadableClass = (TR_OpaqueClassBlock *) cg()->fe()->createResolvedMethod(cg()->trMemory(),
(TR_OpaqueMethodBlock *) getTargetPtr(), comp->getCurrentMethod())->classOfMethod();
doRegisterPIC = true;
}
if (doRegisterPIC &&
!TR::Compiler->cls.sameClassLoaders(comp, unloadableClass, comp->getCurrentMethod()->classOfMethod()))
{
cg()->jitAdd32BitPicToPatchOnClassUnload((void *) unloadableClass, (void *) (uintptrj_t *) (cursor+2));
// register 32 bit patchable immediate part of a LARL instruction
}
TR::Symbol * sym = (getNode() && getNode()->getOpCode().hasSymbolReference())?getNode()->getSymbol():NULL;
if (!(sym && sym->isStartPC()) && getTargetSymbol() && getTargetSymbol()->isMethod())
{
setImmediateOffsetInBytes((uint8_t *) getSymbolReference()->getMethodAddress() - cursor);
}
if (sym && sym->isStartPC())
setImmediateOffsetInBytes((uint8_t *) sym->getStaticSymbol()->getStaticAddress() - cursor);
i2 = (int32_t)((getTargetPtr() - (uintptrj_t)cursor) / 2);
if (isImmediateOffsetInBytes()) i2 = (int32_t)(getImmediateOffsetInBytes() / 2);
getOpCode().copyBinaryToBuffer(instructionStart);
(*(uint32_t *) cursor) &= boi(0xFFFF0000);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
if (getTargetLabel() != NULL)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, getTargetLabel()));
}
else
{
if (getTargetSnippet() != NULL)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, getTargetSnippet()->getSnippetLabel()));
}
else
{
bool isHelper = getSymbolReference() && getSymbolReference()->getSymbol()->isMethod() &&
getSymbolReference()->getSymbol()->castToMethodSymbol()->isHelper();
#if defined(TR_TARGET_64BIT)
// Check to make sure that we can reach our target! Otherwise, we
// need to look up appropriate trampoline and branch through the
// trampoline.
if (!isImmediateOffsetInBytes() && !TR::Compiler->target.cpu.isTargetWithinBranchRelativeRILRange((intptrj_t)getTargetPtr(), (intptrj_t)cursor))
{
intptrj_t targetAddr = ((intptrj_t)(cursor) + ((intptrj_t)(i2) * 2));
TR_ASSERT( targetAddr != getTargetPtr(), "LARL is correct already!\n");
// lower 32 bits should be correct.
TR_ASSERT( (int32_t)(targetAddr) == (int32_t)(getTargetPtr()), "LARL lower 32-bits is incorrect!\n");
(*(int32_t *) (cursor + 2)) |= boi(i2);
cursor += getOpCode().getInstructionLength();
// Check upper 16-bits to see if we need to fix it with IIHH
if (targetAddr >> 48 != getTargetPtr() >> 48)
{
(*(uint16_t *) cursor) = bos(0xA5F0);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
(*(int16_t *) (cursor + 2)) |= bos((int16_t)(getTargetPtr() >> 48));
cursor += 4;
}
// Check upper lower 16-bits to see if we need to fix it with IIHL
if ((targetAddr << 16) >> 48 != (getTargetPtr() << 16) >> 48)
{
(*(uint16_t *) cursor) = bos(0xA5F1);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
(*(int16_t *) (cursor + 2)) |= bos((int16_t) ((getTargetPtr() << 16) >> 48));
cursor += 4;
}
cursor -= getOpCode().getInstructionLength();
}
else
{
(*(int32_t *) (cursor + 2)) |= boi(i2);
}
#else
(*(int32_t *) (cursor + 2)) |= boi(i2);
#endif
if (isHelper)
{
AOTcgDiag2(comp, "add TR_HelperAddress cursor=%p i2=%p\n", cursor, i2);
cg()->addProjectSpecializedRelocation(cursor+2, (uint8_t*) getSymbolReference(), NULL, TR_HelperAddress,
__FILE__, __LINE__, getNode());
}
}
}
cursor += getOpCode().getInstructionLength();
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::BRCL)
{
// If it is a branch to unresolvedData snippet, we need to align the immediate field so that it can be
// patched atomically using ST
if (getTargetSnippet() != NULL && (getTargetSnippet()->getKind() == TR::Snippet::IsUnresolvedData))
{
// address must be 4 byte aligned for atomic patching
int32_t padSize = 4 - ((uintptrj_t) (cursor + 2) % 4);
if (padSize == 2)
{
(*(uint16_t *) cursor) = bos(0x1800);
cursor += 2;
}
}
(*(uint16_t *) cursor) = bos(0xC0F4);
if (getMask() <= 0x000000f)
{
(*(uint16_t *) cursor) &= bos(0xFF0F);
(*(uint16_t *) cursor) |= bos(getMask() << 4);
}
if (getTargetSnippet() != NULL)
{
// delegate to targetSnippet Label to patch the imm. operand
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, getTargetSnippet()->getSnippetLabel()));
}
else
{
i2 = (int32_t)((getTargetPtr() - (uintptrj_t)cursor) / 2);
#if defined(TR_TARGET_64BIT)
#if defined(J9ZOS390)
if (comp->getOption(TR_EnableRMODE64))
#endif
{
// get the correct target addr for helpers
i2 = adjustCallOffsetWithTrampoline(i2, cursor);
}
#endif
(*(int32_t *) (cursor + 2)) = boi(i2);
}
cursor += getOpCode().getInstructionLength();
}
else if (getOpCode().getOpCodeValue() == TR::InstOpCode::BRASL)
{
// When a method is recompiled the entry point of the old implementation gets patched with a branch
// to the preprologue. The callee is then responsible for patching the address of the callers BRASL
// to point to the new implementation, and subsequently branch to the new location. Because this
// patching happens at runtime we must ensure that the store to the relative immediate offset in the
// BRASL is done atomically. On zOS we allow atomic patching on both a 4 and an 8 byte boundary. On
// zLinux 64 bit we only allow atomic patching on a 4 byte boundary as we use Multi-Code Caches and
// require trampolines.
#if defined(J9ZOS390) || !defined(TR_TARGET_64BIT)
// Address must not cross an 8 byte boundary for atomic patching
int32_t padSize = ((uintptrj_t) (cursor + 4) % 8) == 0 ? 2 : 0;
#else
// Address must be 4 byte aligned for atomic patching
int32_t padSize = 4 - ((uintptrj_t) (cursor + 2) % 4);
#endif
if (padSize == 2)
{
(*(uint16_t *) cursor) = bos(0x1800);
cursor += 2;
}
#if defined(TR_TARGET_64BIT)
#if defined(J9ZOS390)
if (comp->getOption(TR_EnableRMODE64))
#endif
{
if (cg()->hasCodeCacheSwitched())
{
TR::SymbolReference *calleeSymRef = NULL;
calleeSymRef = getSymbolReference();
if (calleeSymRef != NULL)
{
if (calleeSymRef->getReferenceNumber()>=TR_S390numRuntimeHelpers)
cg()->fe()->reserveTrampolineIfNecessary(comp, calleeSymRef, true);
}
else
{
#ifdef DEBUG
printf("Missing possible re-reservation for trampolines.\n");
#endif
}
}
}
#endif
(*(uint16_t *) cursor) = bos(0xC005);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
// delegate to targetSnippet Label to patch the imm. operand
if (getTargetSnippet() != NULL)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, getTargetSnippet()->getSnippetLabel()));
}
else
{
/**
* Three possible scenarios:
* 1- Recursive call: Address is calculated by getCodeStart. MethodAddress has not set yet
* 2- 'targetAddress' is provided: We use provided address to generate the brasl address
* 3- 'targetAddress' is not provided: In this case the address is extracted from TargetSymbol.
* If targetAddress is not provided, TargetSymbol should be a method symbol.
*/
TR_ASSERT(getTargetPtr() || (getTargetSymbol() && getTargetSymbol()->isMethod()),"targetAddress or method symbol should be provided for BRASL\n");
if (comp->isRecursiveMethodTarget(getTargetSymbol()))
{
// call myself case
uint8_t * jitTojitStart = cg()->getCodeStart();
// Calculate jit-to-jit entry point
jitTojitStart += ((*(int32_t *) (jitTojitStart - 4)) >> 16) & 0x0000ffff;
*(int32_t *) (cursor + 2) = boi(((intptrj_t) jitTojitStart - (intptrj_t) cursor) / 2);
}
else
{
TR::MethodSymbol *callSymbol = NULL;
if (getTargetSymbol())
{
callSymbol = getTargetSymbol()->isMethod() ? getTargetSymbol()->castToMethodSymbol() : NULL;
}
i2 = (int32_t)((getTargetPtr() - (uintptrj_t)cursor) / 2);
if (getTargetPtr() == 0 && callSymbol)
{
i2 = (int32_t)(((uintptrj_t)(callSymbol->getMethodAddress()) - (uintptrj_t)cursor) / 2);
}
#if defined(TR_TARGET_64BIT)
#if defined(J9ZOS390)
if (comp->getOption(TR_EnableRMODE64))
#endif
{
i2 = adjustCallOffsetWithTrampoline(i2, cursor);
}
#endif
(*(int32_t *) (cursor + 2)) = boi(i2);
if (getSymbolReference() && getSymbolReference()->getSymbol()->castToMethodSymbol()->isHelper())
{
AOTcgDiag1(comp, "add TR_HelperAddress cursor=%x\n", cursor);
cg()->addProjectSpecializedRelocation(cursor+2, (uint8_t*) getSymbolReference(), NULL, TR_HelperAddress,
__FILE__, __LINE__, getNode());
}
}
}
cursor += getOpCode().getInstructionLength();
}
else if (getOpCode().isExtendedImmediate())
{
getOpCode().copyBinaryToBuffer(instructionStart);
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
// LL: Verify extended immediate instruction length must be 6
TR_ASSERT( getOpCode().getInstructionLength()==6, "Extended immediate instruction must be length of 6\n");
(*(int32_t *) (cursor + 2)) |= boi((int32_t) getSourceImmediate());
cursor += getOpCode().getInstructionLength();
}
else
{
TR_ASSERT(0, "OpCode:%d is not handled in RILInstruction yet", getOpCode().getOpCodeValue());
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
/**
* RS Format
* ________ ____ ____ ____ ____________
* |Op Code | R1 | R3 | B2 | D2 |
* |________|____|____|____|____________|
* 0 8 12 16 20 31
* ________ ____ ____ ____ ____________
* |Op Code | R1 | M3 | B2 | D2 |
* |________|____|____|____|____________|
* 0 8 12 16 20 31
*
* There are three different uses for the RS type:
* 1. targetReg => (R1,R3), MemRef => (B2,D2) ... (STM, LM)
*
* 2. targetReg => R1, MemRef => (B2,D2), MaskImm => M3 ... (ICM)
*
* 3. targetReg => R1, MemRef => (B2,D2), secondReg => R3 ... (SLLG,...)
* targetReg => R1, , secondReg => R3 sourceImm => D2 ... (SLLG,...)
* targetReg => R1, MemRef => (B2,D2) ... (SLL,...)
* targetReg => R1, sourceImm => D2 ... (SLL,...)
*/
int32_t
TR::S390RSInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390RSInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
if (getMemoryReference() != NULL)
{
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
// Opcode could have been changed by memref for long disp RS => RSY
// It is also possible that we inserted ext code for large DISP field.
cursor += padding;
}
else
{
(*(int16_t *) (cursor + 2)) |= bos(getSourceImmediate());
}
if (getMaskImmediate())
{
(*(int8_t *) (cursor + 1)) |= getMaskImmediate();
}
TR::InstOpCode& opCode = getOpCode();
if (getMemoryReference() != NULL)
{
if (getMemoryReference()->isLongDisplacementRequired())
{
auto longDisplacementMnemonic = TR::InstOpCode::getEquivalentLongDisplacementMnemonic(getOpCodeValue());
if (longDisplacementMnemonic != TR::InstOpCode::BAD)
{
opCode = TR::InstOpCode(longDisplacementMnemonic);
}
}
}
opCode.copyBinaryToBufferWithoutClear(cursor);
// AKA Even Reg
toRealRegister(getFirstRegister())->setRegister1Field((uint32_t *) cursor);
// AKA Odd Reg
TR::InstOpCode::Mnemonic op = getOpCodeValue();
if (op == TR::InstOpCode::CDS || op == TR::InstOpCode::CDSG || op == TR::InstOpCode::MVCLE || op == TR::InstOpCode::MVCLU || op == TR::InstOpCode::CLCLE || op == TR::InstOpCode::CLCLU)
{
toRealRegister(getSecondRegister()->getHighOrder())->setRegister2Field((uint32_t *) cursor);
}
else if (getLastRegister())
{
toRealRegister(getLastRegister())->setRegister2Field((uint32_t *) cursor);
}
instructionStart = cursor;
cursor += opCode.getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
// TR::S390RRSInstruction:: member functions
/**
* RRS Format
* ________ ____ ____ ____ ____________ ___________________
* |Op Code | R1 | R2 | B4 | D4 | M3 |////| Op Code |
* |________|____|____|____|____________|____|____|_________|
* 0 8 12 16 20 32 36 40 47
*/
uint8_t *
TR::S390RRSInstruction::generateBinaryEncoding()
{
// acquire the current cursor location so we can start generating our
// instruction there.
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
// we'll need to keep the start location, and our current writing location.
uint8_t * cursor = instructionStart;
// clear the number of bytes we intend to use in the buffer.
memset( (void*)cursor, 0, getEstimatedBinaryLength());
// overlay the actual instruction op code to the buffer. this will properly
// set the second half of the op code in the 6th byte.
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// add the register number for the first register to the buffer. this will
// write in the first nibble after the op code.
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
// add the register number for the second register to the buffer this will
// write the reg evaluation into the right-most nibble of a byte which starts just
// after the bytecode.
toRealRegister(getRegisterOperand(2))->setRegister2Field((uint32_t *) cursor);
// advance the cursor in the buffer 2 bytes (op code + reg specifications).
cursor += 2;
// evaluate the memory reference into the buffer.
int32_t padding = getBranchDestinationLabel()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// add the comparison mask for the instruction to the buffer.
*(cursor) |= (uint8_t)getMask();
// the advance the cursor 1 byte for the mask byte we just wrote, and another
// byte for the tail part of the op code.
cursor += 2;
// set the binary length of our instruction
setBinaryLength(cursor - instructionStart);
// set the binary encoding to point at where our instruction begins in the
// buffer
setBinaryEncoding(instructionStart);
// account for the error in estimation
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
// return the the cursor for the next instruction.
return cursor;
}
// TR::S390RIEInstruction:: member functions
/**
* RIE Format
*
* RIE1: CRJ, GGRJ
* ________ ____ ____ _________________ ___________________
* |Op Code | R1 | R2 | I4 | M3 |////| Op Code |
* |________|____|____|_________________|____|____|_________|
* 0 8 12 16 32 36 40 47
*
* RIE2: CIJ, CGIJ
* ________ ____ ____ _________________ ___________________
* |Op Code | R1 | M3 | I4 | I2 | Op Code |
* |________|____|____|_________________|_________|_________|
* 0 8 12 16 32 40 47
*
* RIE3: CIT, CGIT
* ________ ____ ____ _________________ ___________________
* |Op Code | R1 | // | I2 | M3 |////| Op Code |
* |________|____|____|_________________|____|____|_________|
*
* RIE4: AHIK
* ________ ____ ____ ________ ________ _________ _________
* |Op Code | R1 | R3 | I2 |/////////| Op Code |
* |________|____|____|________|________|_________|_________|
* 0 8 12 16 24 32 40 47
*
* RIE5: RISBG
* ________ ____ ____ ________ ________ _________ _________
* |Op Code | R1 | R2 | I3 | I4 | I5 | Op Code |
* |________|____|____|________|________|_________|_________|
* 0 8 12 16 24 32 40 47
*
* RIE6: LOCHI
* ________ ____ ____ ________ ________ _________ _________
* |Op Code | R1 | M3 | I2 |/////////| Op Code |
* |________|____|____|_________________|_________|_________|
* 0 8 12 16 32 36 40 47
*/
int32_t
TR::S390RIEInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getBranchDestinationLabel())
setEstimatedBinaryLength(12);
else
setEstimatedBinaryLength(getOpCode().getInstructionLength());
return currentEstimate + getEstimatedBinaryLength();
}
uint8_t *
TR::S390RIEInstruction::generateBinaryEncoding()
{
// let's determine what form of RIE we are dealing with
bool RIE1 = (getRieForm() == TR::S390RIEInstruction::RIE_RR);
bool RIE2 = (getRieForm() == TR::S390RIEInstruction::RIE_RI8);
bool RIE3 = (getRieForm() == TR::S390RIEInstruction::RIE_RI16A);
bool RIE4 = (getRieForm() == TR::S390RIEInstruction::RIE_RRI16);
bool RIE5 = (getRieForm() == TR::S390RIEInstruction::RIE_IMM);
bool RIE6 = (getRieForm() == TR::S390RIEInstruction::RIE_RI16G);
// acquire the current cursor location so we can start generating our
// instruction there.
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
// we'll need to keep the start location, and our current writing location.
uint8_t * cursor = instructionStart;
// clear the number of bytes we intend to use in the buffer.
memset((void*)cursor, 0, getEstimatedBinaryLength());
// overlay the actual instruction op code to the buffer. this will properly
// set the second half of the op code in the 6th byte.
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// add the register number for the first register to the buffer after the op code.
TR::Register * tgtReg = getRegForBinaryEncoding(getRegisterOperand(1));
toRealRegister(tgtReg)->setRegister1Field((uint32_t *) cursor);
// for RIE1 or RIE5 form, we encode the second register.
if(RIE1 || RIE5 || RIE4)
{
// add the register number for the second register to the buffer after the first register.
TR::Register * srcReg = getRegForBinaryEncoding(getRegisterOperand(2));
toRealRegister(srcReg)->setRegister2Field((uint32_t *) cursor);
}
// for RIE2 or RIE6 form, we encode the branch mask.
else if(RIE2 || RIE6)
{
*(cursor + 1) |= (uint8_t)getMask()>>4;
}
// for RIE3 the field is empty
// advance the cursor past the the first 2 bytes.
cursor += 2;
// if we have a branch destination (RIE1, RIE2), we encode that now.
if (getBranchDestinationLabel())
{
TR::LabelSymbol * label = getBranchDestinationLabel();
int32_t distance = 0;
int32_t trampolineDistance = 0;
bool doRelocation = false;
if (label->getCodeLocation() != NULL)
{
// Label location is known
// calculate the relative branch distance
distance = (label->getCodeLocation() - instructionStart);
doRelocation = false;
}
else
{
// Label location is unknown
// estimate the relative branch distance
distance = (cg()->getBinaryBufferStart() + label->getEstimatedCodeLocation()) -
(instructionStart + cg()->getAccumulatedInstructionLengthError());
doRelocation = true;
}
// now we'll encode the branch destination.
if ((distance / 2) >= MIN_IMMEDIATE_VAL && (distance / 2) <= MAX_IMMEDIATE_VAL)
{
if (doRelocation)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative16BitRelocation(cursor, label));
}
else
{
*(int16_t *) (cursor) |= bos(distance / 2);
}
}
else
{
//generate CHI/CGHI BRCL sequence
cursor = instructionStart;
// clear the number of bytes we intend to use in the buffer.
memset((void*)cursor, 0, getEstimatedBinaryLength());
//Generate equivalent Compare instruction
TR::InstOpCode::Mnemonic cmpOp;
bool isRR=false;
bool isRRE=false;
bool isRI=false;
bool isRIL=false;
switch (getOpCodeValue())
{
case TR::InstOpCode::CGRJ :
cmpOp = TR::InstOpCode::CGR;
*(uint16_t *) (cursor) = bos(0xB920);
isRRE = true;
break;
case TR::InstOpCode::CLGRJ :
cmpOp = TR::InstOpCode::CLGR;
*(uint16_t *) (cursor) = bos(0xB921);
isRRE = true;
break;
case TR::InstOpCode::CLRJ :
cmpOp = TR::InstOpCode::CLR;
*(uint8_t *) (cursor) = 0x15;
isRR = true;
break;
case TR::InstOpCode::CRJ :
cmpOp = TR::InstOpCode::CR;
*(uint8_t *) (cursor) = 0x19;
isRR = true;
break;
case TR::InstOpCode::CGIJ :
cmpOp = TR::InstOpCode::CGHI;
*(uint16_t *) (cursor) = bos(0xA70F);
isRI = true;
break;
case TR::InstOpCode::CIJ :
cmpOp = TR::InstOpCode::CHI;
*(uint16_t *) (cursor) = bos(0xA70E);
isRI = true;
break;
case TR::InstOpCode::CLGIJ :
cmpOp = TR::InstOpCode::CLGFI;
*(uint16_t *) (cursor) = bos(0xC20E);
isRIL = true;
break;
case TR::InstOpCode::CLIJ :
cmpOp = TR::InstOpCode::CLFI;
*(uint16_t *) (cursor) = bos(0xC20F);
isRIL = true;
break;
}
if (isRRE)
{
//position cursor forward so that the registers encoding lines up with isRR
cursor += 2;
}
// add the register number for the first register to the buffer after the op code.
TR::Register * tgtReg = getRegForBinaryEncoding(getRegisterOperand(1));
toRealRegister(tgtReg)->setRegister1Field((uint32_t *) cursor);
if (isRI || isRIL)
{
cursor += 2;
}
if (isRR || isRRE)
{
// add the register number for the second register to the buffer after the first register.
TR::Register * srcReg = getRegForBinaryEncoding(getRegisterOperand(2));
toRealRegister(srcReg)->setRegister2Field((uint32_t *) cursor);
cursor += 2;
}
else if (isRI)
{
//TR::InstOpCode::CHI/TR::InstOpCode::CGHI are signed so sign extend the 8 bit immediate value to 16 bits
(*(int16_t *) (cursor)) = bos((int16_t) getSourceImmediate8());
cursor += 2;
}
else if (isRIL)
{
//TR::InstOpCode::CLGFI/TR::InstOpCode::CLFI are unsigned so zero extend the 8 bit immediate value to 32 bits
(*(int8_t *) (cursor+3)) = getSourceImmediate8();
cursor += 4;
}
//Now generate BRCL
*(uint16_t *) cursor = bos(0xC004);
*(cursor + 1) |= (uint8_t) getMask();
if (doRelocation)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(cursor, label));
}
else
{
distance = (label->getCodeLocation() - cursor);
*(int32_t *) (cursor + 2) |= boi(distance / 2);
}
cursor += 6;
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
}
// if we don't have a branch destination (and not type RIE5), we have a 16-bit immediate value to compare
else if (!RIE5)
{
*(int16_t *) (cursor) |= bos((int16_t)getSourceImmediate16());
TR_ASSERT( ((getSourceImmediate16() & 0xB900) != 0xB900) ||
((getOpCodeValue() != 0xEC71) && (getOpCodeValue() != 0xEC73)),
"CLFIT has Immediate value 0xB9XX, signalHandler might confuse DIVCHK with BNDCHK");
}
// if we are type RIE5 place the two immediate values in
else
{
if (getOpCodeValue() == TR::InstOpCode::RISBLG || getOpCodeValue() == TR::InstOpCode::RISBHG)
// mask the I3 field as bits 1-3 must be 0
*(int8_t *) (cursor) |= (int8_t)getSourceImmediate8One() & 0x1F;
else if (getOpCodeValue() == TR::InstOpCode::RISBG || getOpCodeValue() == TR::InstOpCode::RISBGN)
{
// mask the I3 field as bits 0-1 must be 0
*(int8_t *) (cursor) |= (int8_t)getSourceImmediate8One() & 0x3F;
TR_ASSERT(((int8_t)getSourceImmediate8One() & 0xC0) == 0, "Bits 0-1 in the I3 field for %s must be 0", getOpCodeValue() == TR::InstOpCode::RISBG ? "RISBG" : "RISBGN");
}
else
*(int8_t *) (cursor) |= (int8_t)getSourceImmediate8One();
cursor += 1;
if (getOpCodeValue() == TR::InstOpCode::RISBLG || getOpCodeValue() == TR::InstOpCode::RISBHG)
// mask the I4 field as bits 1-2 must be 0
*(int8_t *) (cursor) |= (int8_t)getSourceImmediate8Two() & 0x9F;
else if (getOpCodeValue() == TR::InstOpCode::RISBG || getOpCodeValue() == TR::InstOpCode::RISBGN)
{
*(int8_t *) (cursor) |= (int8_t)getSourceImmediate8Two() & 0xBF;
TR_ASSERT(((int8_t)getSourceImmediate8Two() & 0x40) == 0, "Bit 1 in the I4 field for %s must be 0", getOpCodeValue() == TR::InstOpCode::RISBG ? "RISBG" : "RISBGN");
}
else
*(int8_t *) (cursor) |= (int8_t)getSourceImmediate8Two();
cursor -= 1;
}
// advance the cursor past the 2 bytes we just wrote to the buffer.
cursor += 2;
// for RIE1 and RIE3 we now generate the branch mask
if (RIE1 || RIE3)
{
*(cursor) |= (uint8_t)getMask();
}
// for RIE2 we load the 8 bit immediate for comparison
else
{
// add in the immediate comparison value
(*(int8_t *) (cursor)) |= getSourceImmediate8();
}
// advance the cursor past the byte we just wrote and the op code byte at
// the end.
cursor += 2;
// set the binary length of our instruction
setBinaryLength(cursor - instructionStart);
// set the binary encoding to point at where our instruction begins in the buffer
setBinaryEncoding(instructionStart);
// account for the error in estimation
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
// return the updated cursor position.
return cursor;
}
/**
* Split the RIE instruction into separate compare and long branch
* Instructions. We need to do this so that compiler listings
* work properly, we can't just fix this up in the binary buffer
* like its done for JAVA
*/
uint8_t *
TR::S390RIEInstruction::splitIntoCompareAndLongBranch(void)
{
//Generate equivalent Compare instruction
TR::InstOpCode::Mnemonic cmpOp;
bool isRR = false;
bool isRRE = false;
bool isRI = false;
bool isRIL = false;
switch (getOpCodeValue())
{
case TR::InstOpCode::CGRJ :
cmpOp = TR::InstOpCode::CGR;
isRRE = true;
break;
case TR::InstOpCode::CLGRJ :
cmpOp = TR::InstOpCode::CLGR;
isRRE = true;
break;
case TR::InstOpCode::CLRJ :
cmpOp = TR::InstOpCode::CLR;
isRR = true;
break;
case TR::InstOpCode::CRJ :
cmpOp = TR::InstOpCode::CR;
isRR = true;
break;
case TR::InstOpCode::CGIJ :
cmpOp = TR::InstOpCode::CGHI;
isRI = true;
break;
case TR::InstOpCode::CIJ :
cmpOp = TR::InstOpCode::CHI;
isRI = true;
break;
case TR::InstOpCode::CLGIJ :
cmpOp = TR::InstOpCode::CLGFI;
isRIL = true;
break;
case TR::InstOpCode::CLIJ :
cmpOp = TR::InstOpCode::CLFI;
isRIL = true;
break;
}
TR::Instruction * prevInstr = this;
TR::Instruction * currInstr = prevInstr;
uint8_t *cursor;
if (isRRE || isRR)
currInstr = generateRRInstruction(cg(), cmpOp, getNode(), getRegisterOperand(1),
getRegisterOperand(2), prevInstr);
else if (isRI)
currInstr = generateRIInstruction(cg(), cmpOp, getNode(), getRegisterOperand(1),
(int16_t) getSourceImmediate8(),prevInstr);
else if (isRIL)
currInstr = generateRILInstruction(cg(), cmpOp, getNode(), getRegisterOperand(1),
(uint8_t) getSourceImmediate8(), prevInstr);
currInstr->setEstimatedBinaryLength(currInstr->getOpCode().getInstructionLength());
cg()->setBinaryBufferCursor(cursor = currInstr->generateBinaryEncoding());
prevInstr = currInstr;
// generate a BRC and the binary encoding will fix it up to a BRCL if needed
currInstr = generateS390BranchInstruction(cg(), TR::InstOpCode::BRC, getBranchCondition(), getNode(), getBranchDestinationLabel(), prevInstr);
currInstr->setEstimatedBinaryLength(6);
cg()->setBinaryBufferCursor(cursor = currInstr->generateBinaryEncoding());
// Remove the current instructions from the list
this->getPrev()->setNext(this->getNext());
this->getNext()->setPrev(this->getPrev());
// set 'this' - the compare and branch instruction being removed, 'next' pointer to the instruction after the inserted BRC/BRCL
// so the main cg generateBinaryEncoding loop does not encode the new CHI and BRC/BRCL instruction a second time
this->setNext(currInstr->getNext());
return cursor;
}
/**
* To be used at instruction level if combined compare and branch will not work.
* The current combined compare and branch instruction is split into seperate
* compare instruction and a new branch instruction. The insertion point for the
* branch is provided as an argument. The compare instruction is inserted right after
* the combined compare and branch instruction.
*/
void
TR::S390RIEInstruction::splitIntoCompareAndBranch(TR::Instruction *insertBranchAfterThis)
{
//Generate equivalent Compare instruction
TR::InstOpCode::Mnemonic cmpOp;
bool isRR = false;
bool isRRE = false;
bool isRI = false;
bool isRIL = false;
switch (getOpCodeValue())
{
case TR::InstOpCode::CGRJ :
cmpOp = TR::InstOpCode::CGR;
isRRE = true;
break;
case TR::InstOpCode::CLGRJ :
cmpOp = TR::InstOpCode::CLGR;
isRRE = true;
break;
case TR::InstOpCode::CLRJ :
cmpOp = TR::InstOpCode::CLR;
isRR = true;
break;
case TR::InstOpCode::CRJ :
cmpOp = TR::InstOpCode::CR;
isRR = true;
break;
case TR::InstOpCode::CGIJ :
cmpOp = TR::InstOpCode::CGHI;
isRI = true;
break;
case TR::InstOpCode::CIJ :
cmpOp = TR::InstOpCode::CHI;
isRI = true;
break;
case TR::InstOpCode::CLGIJ :
cmpOp = TR::InstOpCode::CLGFI;
isRIL = true;
break;
case TR::InstOpCode::CLIJ :
cmpOp = TR::InstOpCode::CLFI;
isRIL = true;
break;
default:
TR_ASSERT(false,"Don't know how to split this compare and branch opcode %s\n",getOpCode().getMnemonicName());
break;
}
TR::Instruction * prevInstr = this;
if (isRRE || isRR)
generateRRInstruction(cg(), cmpOp, getNode(), getRegisterOperand(1),getRegisterOperand(2), prevInstr);
else if (isRI)
generateRIInstruction(cg(), cmpOp, getNode(), getRegisterOperand(1),(int16_t) getSourceImmediate8(),prevInstr);
else if (isRIL)
generateRILInstruction(cg(), cmpOp, getNode(), getRegisterOperand(1),(uint8_t) getSourceImmediate8(), prevInstr);
// generate a BRC
generateS390BranchInstruction(cg(), TR::InstOpCode::BRC, getBranchCondition(), getNode(), getBranchDestinationLabel(), insertBranchAfterThis);
// Remove the current instructions from the list
this->getPrev()->setNext(this->getNext());
this->getNext()->setPrev(this->getPrev());
}
// TR::S390RISInstruction:: member functions
/**
* RIS Format
*
* ________ ____ ____ ____ ____________ ___________________
* |Op Code | R1 | M3 | B4 | D4 | I2 | Op Code |
* |________|____|____|____|____________|_________|_________|
* 0 8 12 16 20 32 40 47
*/
uint8_t *
TR::S390RISInstruction::generateBinaryEncoding()
{
// acquire the current cursor location so we can start generating our
// instruction there.
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
// we'll need to keep the start location, and our current writing location.
uint8_t * cursor = instructionStart;
// clear the number of bytes we intend to use in the buffer.
memset((void*)cursor, 0, getEstimatedBinaryLength());
// overlay the actual instruction op code to the buffer. this will properly
// set the second half of the op code in the 6th byte.
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// add the register number for the first register to the buffer right after the op code.
toRealRegister(getRegisterOperand(1))->setRegister1Field((uint32_t *) cursor);
// advance the cursor one byte.
cursor += 1;
// add the comparison mask for the instruction to the buffer.
*(cursor) |= (uint8_t)getMask();
// advance the cursor past the register and mask encoding.
cursor += 1;
// add the memory reference for the target to the buffer, and advance the
// cursor past what gets written.
int32_t padding = getBranchDestinationLabel()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// add in the immediate second operand to the instruction
(*(int8_t *) (cursor)) |= getSourceImmediate();
// advance the cursor past that byte and the op code byte.
cursor += 2;
// set the binary length of our instruction
setBinaryLength(cursor - instructionStart);
// set the binary encoding to point at where our instruction begins in the
// buffer
setBinaryEncoding(instructionStart);
// account for the error in estimation
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
// return the the cursor for the next instruction.
return cursor;
}
// TR::S390MemInstruction:: member functions
bool
TR::S390MemInstruction::refsRegister(TR::Register * reg)
{
// 64bit mem refs clobber high word regs
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && reg->getRealRegister())
{
TR::RealRegister * realReg = (TR::RealRegister *)reg;
TR::Register * regMem = reg;
if (getMemoryReference()->refsRegister(regMem))
{
return true;
}
}
if (getMemoryReference()->refsRegister(reg))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
uint8_t *
TR::S390MemInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
getOpCode().copyBinaryToBuffer(instructionStart);
if (getMemAccessMode() >= 0)
{
(*(uint32_t *) cursor) &= boi(0xFF0FFFFF);
(*(uint32_t *) cursor) |= boi((getMemAccessMode() & 0xF)<< 20);
}
getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
// TR::S390RXInstruction:: member functions
bool
TR::S390RXInstruction::refsRegister(TR::Register * reg)
{
// 64bit mem refs clobber high word regs
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && getMemoryReference()&& reg->getRealRegister())
{
TR::RealRegister * realReg = (TR::RealRegister *)reg;
TR::Register * regMem = reg;
if (getMemoryReference()->refsRegister(regMem))
{
return true;
}
}
if (matchesTargetRegister(reg))
{
return true;
}
else if ((getMemoryReference() != NULL) && (getMemoryReference()->refsRegister(reg) == true))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
int32_t
TR::S390RXInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390RXInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
TR::Compilation *comp = cg()->comp();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
TR::InstOpCode& opCode = getOpCode();
if (getMemoryReference()->isLongDisplacementRequired())
{
auto longDisplacementMnemonic = TR::InstOpCode::getEquivalentLongDisplacementMnemonic(getOpCodeValue());
if (longDisplacementMnemonic != TR::InstOpCode::BAD)
{
opCode = TR::InstOpCode(longDisplacementMnemonic);
}
}
opCode.copyBinaryToBufferWithoutClear(cursor);
TR::Register * trgReg = getRegForBinaryEncoding(getRegisterOperand(1));
toRealRegister(trgReg)->setRegisterField((uint32_t *) cursor);
instructionStart = cursor;
cursor += opCode.getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
int32_t
TR::S390RXEInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390RXEInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0;
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the actual instruction, reg, and mask
getOpCode().copyBinaryToBufferWithoutClear(cursor);
TR::Register * trgReg = getRegForBinaryEncoding(getRegisterOperand(1));
toRealRegister(trgReg)->setRegisterField((uint32_t *) cursor);
setMaskField(((uint32_t*)cursor + 1), getM3(), 7); // M3: bits 32-36
cursor += (getOpCode().getInstructionLength());
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding);
return cursor;
}
int32_t
TR::S390RXYInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390RXYInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the actual instruction and reg
getOpCode().copyBinaryToBufferWithoutClear(cursor);
TR::Register * trgReg = getRegForBinaryEncoding(getRegisterOperand(1));
toRealRegister(trgReg)->setRegisterField((uint32_t *) cursor);
instructionStart = cursor;
cursor += (getOpCode().getInstructionLength());
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
// TR::S390RXFInstruction:: member functions /////////////////////////////////////////
int32_t
TR::S390RXFInstruction::estimateBinaryLength(int32_t currentEstimate)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
bool
TR::S390RXFInstruction::refsRegister(TR::Register * reg)
{
// 64bit mem refs clobber high word regs
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && reg->getRealRegister())
{
TR::RealRegister * realReg = (TR::RealRegister *)reg;
TR::Register * regMem = reg;
if (getMemoryReference()->refsRegister(regMem))
{
return true;
}
}
if (matchesTargetRegister(reg) || matchesAnyRegister(reg, getRegisterOperand(2)) || getMemoryReference()->refsRegister(reg) == true)
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
uint8_t *
TR::S390RXFInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
int32_t padding = 0, longDispTouchUpPadding = 0;
memset( (void*)cursor,0,getEstimatedBinaryLength());
TR::Compilation *comp = cg()->comp();
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
getOpCode().copyBinaryToBufferWithoutClear(cursor);
TR::RegisterPair* srcRegPair = getRegisterOperand(2)->getRegisterPair();
TR::RegisterPair* tgtRegPair = getRegisterOperand(1)->getRegisterPair();
bool isTgtFPPair = false;
if(isTgtFPPair)
{
toRealRegister(srcRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor);
toRealRegister(tgtRegPair->getHighOrder())->setRegisterField((uint32_t *) cursor + 1, 7);
}
else
{
toRealRegister(getRegisterOperand(2))->setRegisterField((uint32_t *) cursor);
toRealRegister(getRegisterOperand(1))->setRegisterField((uint32_t *) cursor + 1, 7);
}
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// Vector Instruction Support //
////////////////////////////////////////////////////////////////////////////////
//
/**** Vector Instruction Generic ***/
void appendElementSizeMnemonic(char * opCodeBuffer, int8_t elementSize)
{
char *extendedMnemonic[] = {"B","H","F","G","Q"};
strcat(opCodeBuffer, extendedMnemonic[elementSize]);
}
const char *
getOpCodeName(TR::InstOpCode * opCode)
{
return TR::InstOpCode::metadata[opCode->getOpCodeValue()].name;
}
TR::S390VInstruction::~S390VInstruction()
{
if (_opCodeBuffer)
TR::Instruction::jitPersistentFree((char *)_opCodeBuffer);
}
int32_t
TR::S390VInstruction::estimateBinaryLength(int32_t currentEstimate)
{
setEstimatedBinaryLength(getOpCode().getInstructionLength());
return currentEstimate + getEstimatedBinaryLength();
}
char *
TR::S390VInstruction::setOpCodeBuffer(char *c)
{
if (_opCodeBuffer)
TR_ASSERT(false, "trying to set OpCodeBuffer after it has already been set!\n");
_opCodeBuffer = (char *) TR::Instruction::jitPersistentAlloc(strlen(c)+1);
return strcpy(_opCodeBuffer, c);
}
/**
*
* VRI getExtendedMnemonicName
*
*/
const char *
TR::S390VRIInstruction::getExtendedMnemonicName()
{
if (getOpCodeBuffer())
return getOpCodeBuffer();
char tmpOpCodeBuffer[16];
strcpy(tmpOpCodeBuffer, getOpCode().getMnemonicName());
if (!getOpCode().hasExtendedMnemonic())
return setOpCodeBuffer(tmpOpCodeBuffer);
bool printM3 = getPrintM3();
bool printM4 = getPrintM4();
bool printM5 = getPrintM5();
int32_t elementSize = -1;
if (getOpCode().usesM3())
{
elementSize = getM3();
printM3 = false;
}
else if (getOpCode().usesM4())
{
elementSize = getM4();
printM4 = false;
}
else if (getOpCode().usesM5())
{
elementSize = getM5();
printM5 = false;
}
// handles VFTCI
if (getOpCode().isVectorFPOp())
{
strcat(tmpOpCodeBuffer, "DB");
if (getM5() & 0x8)
tmpOpCodeBuffer[0] = 'W';
printM5 = false;
}
else
appendElementSizeMnemonic(tmpOpCodeBuffer, elementSize);
setPrintM3(printM3);
setPrintM4(printM4);
setPrintM5(printM5);
return setOpCodeBuffer(tmpOpCodeBuffer);
}
/**
* VRI preGenerateBinaryEncoding
*/
uint8_t*
TR::S390VRIInstruction::preGenerateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
memset(static_cast<void*>(instructionStart), 0, getEstimatedBinaryLength());
getOpCode().copyBinaryToBuffer(instructionStart);
return instructionStart;
}
/**
* VRI postGenerateBinaryEncoding
*/
uint8_t*
TR::S390VRIInstruction::postGenerateBinaryEncoding(uint8_t* cursor)
{
// move cursor
uint8_t* instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
/** \details
*
* VRI-a generate binary encoding for VRI-a instruction format
*/
uint8_t *
TR::S390VRIaInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
(*reinterpret_cast<uint16_t*>(cursor + 2)) |= bos(static_cast<uint16_t>(getImmediateField16()));
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t*>(cursor));
// Masks
setMaskField(reinterpret_cast<uint32_t*>(cursor), getM3(), 3);
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRI-b generate binary encoding for VRI-b instruction format
*/
uint8_t *
TR::S390VRIbInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
(*reinterpret_cast<uint16_t*>(cursor + 2)) |= bos(static_cast<uint16_t>(getImmediateField16()));
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t*>(cursor));
// Masks
setMaskField(reinterpret_cast<uint32_t*>(cursor), getM4(), 3);
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRI-c generate binary encoding for VRI-c instruction format
*/
uint8_t *
TR::S390VRIcInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
(*reinterpret_cast<uint16_t*>(cursor + 2)) |= bos(static_cast<uint16_t>(getImmediateField16()));
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t*>(cursor));
toRealRegister(getRegisterOperand(2))->setRegister2Field(reinterpret_cast<uint32_t*>(cursor));
// Masks
setMaskField(reinterpret_cast<uint32_t*>(cursor), getM4(), 3);
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRI-d generate binary encoding for VRI-d instruction format
*/
uint8_t *
TR::S390VRIdInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(3) != NULL, "3rd Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
(*reinterpret_cast<uint16_t*>(cursor + 2)) |= bos(static_cast<uint16_t>(getImmediateField16()));
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t*>(cursor));
toRealRegister(getRegisterOperand(2))->setRegister2Field(reinterpret_cast<uint32_t*>(cursor));
toRealRegister(getRegisterOperand(3))->setRegister3Field(reinterpret_cast<uint32_t*>(cursor));
// Masks
setMaskField(reinterpret_cast<uint32_t*>(cursor), getM5(), 3);
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRI-e generate binary encoding for VRI-e instruction format
*/
uint8_t *
TR::S390VRIeInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
(*reinterpret_cast<uint16_t*>(cursor + 2)) |= bos(static_cast<uint16_t>(getImmediateField16()));
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t*>(cursor));
toRealRegister(getRegisterOperand(2))->setRegister2Field(reinterpret_cast<uint32_t*>(cursor));
// Masks
setMaskField(reinterpret_cast<uint32_t*>(cursor), getM5(), 2);
setMaskField(reinterpret_cast<uint32_t*>(cursor), getM4(), 3);
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRI-f generate binary encoding for VRI-f instruction format
*/
uint8_t *
TR::S390VRIfInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(3) != NULL, "3rd Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
(*reinterpret_cast<uint16_t *>(cursor + 3)) |= bos(static_cast<uint16_t>((getImmediateField16() & 0xff) << 4));
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t *>(cursor));
toRealRegister(getRegisterOperand(2))->setRegister2Field(reinterpret_cast<uint32_t *>(cursor));
toRealRegister(getRegisterOperand(3))->setRegister3Field(reinterpret_cast<uint32_t *>(cursor));
// Masks
setMaskField(reinterpret_cast<uint32_t *>(cursor), getM5(), 1);
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRI-g generate binary encoding for VRI-g instruction format
*/
uint8_t *
TR::S390VRIgInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
// I3 stored in _constantImm16 as uint16_t
// I4 stored in _constantImm8 as uint8_t
(*reinterpret_cast<uint16_t*>(cursor + 3)) |= bos(static_cast<uint16_t>((getImmediateField16() & 0xff) << 4));
(*(cursor + 2)) |= bos(getImmediateField8());
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t*>(cursor));
toRealRegister(getRegisterOperand(2))->setRegister2Field(reinterpret_cast<uint32_t*>(cursor));
// Masks
setMaskField(reinterpret_cast<uint32_t*>(cursor), getM5(), 1);
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRI-h generate binary encoding for VRI-h instruction format
*/
uint8_t *
TR::S390VRIhInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
// do cursor +4 first
*(cursor + 4) |= bos(static_cast<uint8_t>(getImmediateField8() << 4)) ;
(*reinterpret_cast<uint16_t*>(cursor + 2)) |= bos(static_cast<uint16_t>(getImmediateField16()));
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t *>(cursor));
// Masks: none
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRI-i generate binary encoding for VRI-i instruction format
*/
uint8_t *
TR::S390VRIiInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
// Generate Binary Encoding
uint8_t* cursor = preGenerateBinaryEncoding();
// The Immediate field
(*reinterpret_cast<uint16_t *>(cursor + 3)) |= bos(static_cast<uint16_t>((getImmediateField8() & 0xff) << 4));
// Operands
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t *>(cursor));
toRealRegister(getRegisterOperand(2))->setRegister2Field(reinterpret_cast<uint32_t *>(cursor));
// Masks
setMaskField(reinterpret_cast<uint32_t *>(cursor), getM4(), 1);
return postGenerateBinaryEncoding(cursor);
}
/** \details
*
* VRR instruction format get extended mnemonic name returns a charactor array that contains
* the extended mnemonic names
*/
const char *
TR::S390VRRInstruction::getExtendedMnemonicName()
{
if (getOpCodeBuffer())
return getOpCodeBuffer();
char tmpOpCodeBuffer[16];
strcpy(tmpOpCodeBuffer, getOpCode().getMnemonicName());
if (!getOpCode().hasExtendedMnemonic())
return setOpCodeBuffer(tmpOpCodeBuffer);
bool printM3 = getPrintM3();
bool printM4 = getPrintM4();
bool printM5 = getPrintM5();
bool printM6 = getPrintM6();
bool useBInsteadOfDB = false;
uint8_t singleSelector = 0;
if (getOpCode().isVectorFPOp())
{
singleSelector = getM5();
printM5 = false;
}
uint8_t ccMask = 0;
// get condition code mask for printing out "S" suffix
if (getOpCode().setsCC())
{
if (getOpCode().isVectorFPOp())
{
ccMask = getM6();
printM6 = false;
}
else if (getOpCode().usesM5())
{
ccMask = getM5();
printM5 = false;
}
}
switch (getOpCode().getOpCodeValue())
{
case TR::InstOpCode::VSTRC:
// only string instruction that uses M6 as the CC mask
ccMask = getM6();
break;
case TR::InstOpCode::VFAE:
printM5 = true;
break;
// handle Vector FP extended mnemonics
case TR::InstOpCode::VLDE:
useBInsteadOfDB = true;
case TR::InstOpCode::VFSQ:
singleSelector = getM4();
case TR::InstOpCode::WFC:
case TR::InstOpCode::WFK:
printM4 = false;
break;
case TR::InstOpCode::VCDG:
case TR::InstOpCode::VCDLG:
case TR::InstOpCode::VCGD:
case TR::InstOpCode::VCLGD:
case TR::InstOpCode::VLED:
useBInsteadOfDB = true;
case TR::InstOpCode::VFI:
singleSelector = getM4();
printM5 = true;
break;
case TR::InstOpCode::VFM:
case TR::InstOpCode::VFMA:
case TR::InstOpCode::VFMS:
printM6 = false;
break;
case TR::InstOpCode::VFPSO:
printM3 = printM4 = printM5 = false;
singleSelector = getM4();
if (getM5() == 0)
strcpy(tmpOpCodeBuffer, "VFLC");
else if (getM5() == 1)
strcpy(tmpOpCodeBuffer, "VFLN");
else if (getM5() == 2)
strcpy(tmpOpCodeBuffer, "VFLP");
break;
}
// the first mask is generally not printed
// first mask is also the element size control mask
int32_t elementSize = -1;
if (getOpCode().usesM3())
{
elementSize = getM3();
printM3 = false;
}
else if (getOpCode().usesM4())
{
elementSize = getM4();
printM4 = false;
}
else if (getOpCode().usesM5())
{
elementSize = getM5();
printM5 = false;
}
// handle vector string and vector float opcodes
if (getOpCode().isVectorFPOp())
{
// if operating on single element, replace V with W
if (singleSelector & 0x8)
tmpOpCodeBuffer[0] = 'W';
// these FP instructions end with a B
if (useBInsteadOfDB)
strcat(tmpOpCodeBuffer, "B");
else
strcat(tmpOpCodeBuffer, "DB");
}
else
{
if (getOpCode().isVectorStringOp() && (ccMask & 0x2))
strcat(tmpOpCodeBuffer, "Z");
// these opcodes with +H suffix should be HW
// eg. VUPL+H should be VUPLHW since VUPLH is another opcode
if ((getOpCodeValue() == TR::InstOpCode::VUPL || getOpCodeValue() == TR::InstOpCode::VMAL || getOpCodeValue() == TR::InstOpCode::VML) && elementSize == 1)
strcat(tmpOpCodeBuffer, "HW");
else
appendElementSizeMnemonic(tmpOpCodeBuffer, elementSize);
}
// append "S" suffix if mask indicates that it sets condition code
if (ccMask & 0x1)
strcat(tmpOpCodeBuffer, "S");
setPrintM3(printM3);
setPrintM4(printM4);
setPrintM5(printM5);
setPrintM6(printM6);
return setOpCodeBuffer(tmpOpCodeBuffer);
}
/** \details
*
* VRR Generate Binary Encoding for most sub-types of the VRR instruction format
*
* VRR-g,h,i have their own implementations due to format differences.
*/
uint8_t *
TR::S390VRRInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset((void*)cursor, 0, getEstimatedBinaryLength());
// Copy binary
getOpCode().copyBinaryToBuffer(instructionStart);
// Masks
uint8_t maskIn0=0, maskIn1=0, maskIn2=0, maskIn3=0;
switch(getKind())
{
case TR::Instruction::IsVRRa: maskIn1 = getM5(); maskIn2 = getM4(); maskIn3 = getM3(); break;
case TR::Instruction::IsVRRb: maskIn1 = getM5(); maskIn3 = getM4(); break;
case TR::Instruction::IsVRRc: maskIn1 = getM6(); maskIn2 = getM5(); maskIn3 = getM4(); break;
case TR::Instruction::IsVRRd: maskIn0 = getM5(); maskIn1 = getM6(); break;
case TR::Instruction::IsVRRe: maskIn0 = getM6(); maskIn2 = getM5(); break;
case TR::Instruction::IsVRRf: break; // no mask
default: break;
}
setMaskField(reinterpret_cast<uint32_t *>(cursor), maskIn1, 1);
setMaskField(reinterpret_cast<uint32_t *>(cursor), maskIn2, 2);
setMaskField(reinterpret_cast<uint32_t *>(cursor), maskIn0, 0);
// Operands 1-4, sets RXB when in setRegisterXField() methods
if (getRegisterOperand(1) != NULL)
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t *>(cursor));
if (getRegisterOperand(2) != NULL)
toRealRegister(getRegisterOperand(2))->setRegister2Field(reinterpret_cast<uint32_t *>(cursor));
if (getRegisterOperand(3) != NULL)
toRealRegister(getRegisterOperand(3))->setRegister3Field(reinterpret_cast<uint32_t *>(cursor));
if (getRegisterOperand(4) != NULL)
{
// Will cause assertion failure by now
toRealRegister(getRegisterOperand(4))->setRegister4Field(reinterpret_cast<uint32_t *>(cursor));
}
else
{
// mask in mask field 3 (bit 32-35) is aliased with register operand 4
setMaskField(reinterpret_cast<uint32_t *>(cursor), maskIn3, 3);
}
// Cursor move
// update binary length
// update binary length estimate error
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
/** \details
*
* VRR-a generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRRaInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
// Generate Binary Encoding
return TR::S390VRRInstruction::generateBinaryEncoding();
}
/** \details
*
* VRR-b generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRRbInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(3) != NULL, "3rd Operand should not be NULL!");
// Generate Binary Encoding
return TR::S390VRRInstruction::generateBinaryEncoding();
}
/** \details
*
* VRR-d generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRRcInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(3) != NULL, "3rd Operand should not be NULL!");
// Generate Binary Encoding
return TR::S390VRRInstruction::generateBinaryEncoding();
}
/** \details
*
* VRR-d generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRRdInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(3) != NULL, "3rd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(4) != NULL, "4th Operand should not be NULL!");
// Generate Binary Encoding
return TR::S390VRRInstruction::generateBinaryEncoding();
}
/** \details
*
* VRR-e generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRReInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(3) != NULL, "3rd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(4) != NULL, "4th Operand should not be NULL!");
// Generate Binary Encoding
return TR::S390VRRInstruction::generateBinaryEncoding();
}
/** \details
*
* VRR-f generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRRfInstruction::generateBinaryEncoding()
{
// Error Checking
TR_ASSERT(getRegisterOperand(1) != NULL, "First Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(3) != NULL, "3rd Operand should not be NULL!");
// Generate Binary Encoding
return TR::S390VRRInstruction::generateBinaryEncoding();
}
/** \details
*
* VRR-g generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRRgInstruction::generateBinaryEncoding()
{
// Error Checking
TR::Register* v1Reg = getRegisterOperand(1);
TR_ASSERT( v1Reg != NULL, "VRR-g V1 should not be NULL!");
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset((void*)cursor, 0, getEstimatedBinaryLength());
// Copy binary
getOpCode().copyBinaryToBuffer(instructionStart);
// Operands 1 at the second field
toRealRegister(v1Reg)->setRegister2Field(reinterpret_cast<uint32_t *>(cursor));
// Cursor move
// update binary length
// update binary length estimate error
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
/** \details
*
* VRR-h generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRRhInstruction::generateBinaryEncoding()
{
// Error Checking
TR::Register* v1Reg = getRegisterOperand(1);
TR::Register* v2Reg = getRegisterOperand(2);
TR_ASSERT(v1Reg != NULL, "VRR-h operand should not be NULL!");
TR_ASSERT(v2Reg != NULL, "VRR-h Operand should not be NULL!");
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset((void*)cursor, 0, getEstimatedBinaryLength());
// Copy binary
getOpCode().copyBinaryToBuffer(instructionStart);
// Masks
uint8_t mask3 = getM3();
setMaskField(reinterpret_cast<uint32_t *>(cursor), mask3, 1);
// Operands
toRealRegister(v1Reg)->setRegister2Field(reinterpret_cast<uint32_t *>(cursor));
toRealRegister(v2Reg)->setRegister3Field(reinterpret_cast<uint32_t *>(cursor));
// Cursor move
// update binary length
// update binary length estimate error
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
/** \details
*
* VRR-i generate binary encoding
* Performs error checking on the operands and then deleagte the encoding work to its parent class
*/
uint8_t *
TR::S390VRRiInstruction::generateBinaryEncoding()
{
// Error Checking
TR::Register* r1Reg = getRegisterOperand(1);
TR::Register* v2Reg = getRegisterOperand(2);
TR_ASSERT(r1Reg != NULL, "First Operand should not be NULL!");
TR_ASSERT(v2Reg != NULL, "2nd Operand should not be NULL!");
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset((void*)cursor, 0, getEstimatedBinaryLength());
// Copy binary
getOpCode().copyBinaryToBuffer(instructionStart);
setMaskField(reinterpret_cast<uint32_t *>(cursor), getM3(), 1);
setMaskField(reinterpret_cast<uint32_t *>(cursor), getM4(), 2);
// Operands
toRealRegister(r1Reg)->setRegister1Field(reinterpret_cast<uint32_t *>(cursor));
toRealRegister(v2Reg)->setRegister2Field(reinterpret_cast<uint32_t *>(cursor));
// Cursor move
// update binary length
// update binary length estimate error
cursor += getOpCode().getInstructionLength();
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
/** \details
*
* VStorage Instruction get extended mnemonic name
*/
const char *
TR::S390VStorageInstruction::getExtendedMnemonicName()
{
if (getOpCodeBuffer())
return getOpCodeBuffer();
char tmpOpCodeBuffer[16];
strcpy(tmpOpCodeBuffer, getOpCode().getMnemonicName());
if (getOpCode().hasExtendedMnemonic())
{
appendElementSizeMnemonic(tmpOpCodeBuffer, getMaskField());
setPrintMaskField(false);
}
return setOpCodeBuffer(tmpOpCodeBuffer);
}
/**
* VStorage Instruction generate binary encoding
*
* Generate binary encoding for most vector register-storage formats: VRS, VRV, and VRX
* VSI, VRV, and VRS-d have their own implementations and are not handled here
*/
uint8_t *
TR::S390VStorageInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset(static_cast<void*>(cursor), 0, getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
// For large disp scenarios the memref could insert new inst
if (getMemoryReference() != NULL)
{
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
}
// Overlay the instruction
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// Overlay operands
if(getRegisterOperand(1))
{
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t*>(cursor));
}
if(getRegisterOperand(2))
{
toRealRegister(getRegisterOperand(2))->setRegister2Field(reinterpret_cast<uint32_t*>(cursor));
}
// Mask
setMaskField(reinterpret_cast<uint32_t*>(cursor), _maskField, 3);
instructionStart = cursor;
cursor += (getOpCode().getInstructionLength());
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
/**
* VStorageInstruction estimateBinaryLength
*/
int32_t
TR::S390VStorageInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
/**** VRS variants ***/
/** \details
*
* VRS-d generate binary encoding implementation.
* Differs from its base class's generic VStorage instruction implementation
*/
uint8_t *
TR::S390VRSdInstruction::generateBinaryEncoding()
{
TR::MemoryReference* memRef = getMemoryReference();
TR::Register* v1Reg = getOpCode().isStore() ? getRegisterOperand(2) : getRegisterOperand(1);
TR::Register* r3Reg = getOpCode().isStore() ? getRegisterOperand(1) : getRegisterOperand(2);
TR_ASSERT(v1Reg != NULL, "V1 in VRS-d should not be NULL!");
TR_ASSERT(r3Reg != NULL, "R3 in VRS-d should not be NULL!");
TR_ASSERT(memRef != NULL, "Memory Ref in VRS-d should not be NULL!");
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset((void*)cursor, 0, getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
// For large disp scenarios the memref could insert new inst
padding = memRef->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the instruction
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// Overlay register operands
toRealRegister(r3Reg)->setRegister2Field(reinterpret_cast<uint32_t*>(cursor));
toRealRegister(v1Reg)->setRegister4Field(reinterpret_cast<uint32_t*>(cursor));
instructionStart = cursor;
cursor += (getOpCode().getInstructionLength());
// Finish patching up if long disp was needed
longDispTouchUpPadding = memRef->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
/** \details
*
* VRV format generate binary encoding
* Differs from its base class's generic VStorage instruction implementation
*
*/
uint8_t *
TR::S390VRVInstruction::generateBinaryEncoding()
{
TR_ASSERT(getRegisterOperand(1) != NULL, "1st Operand should not be NULL!");
TR_ASSERT(getRegisterOperand(2) != NULL, "2nd Operand should not be NULL!");
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset(static_cast<void*>(cursor), 0, getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
// For large disp scenarios the memref could insert new inst
if (getMemoryReference() != NULL)
{
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
}
// Overlay the instruction
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// Overlay operands
// VRV target and source registers are the same. so don't handle operand(2)
toRealRegister(getRegisterOperand(1))->setRegister1Field(reinterpret_cast<uint32_t*>(cursor));
// Mask
setMaskField(reinterpret_cast<uint32_t*>(cursor), _maskField, 3);
instructionStart = cursor;
cursor += (getOpCode().getInstructionLength());
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
/** \details
*
* VSI format generate binary encoding implementation
* Differs from its base class's generic VStorage instruction implementation
*/
uint8_t *
TR::S390VSIInstruction::generateBinaryEncoding()
{
TR::MemoryReference* memRef = getMemoryReference();
TR::Register* v1Reg = getRegisterOperand(1);
TR_ASSERT(v1Reg != NULL, "Operand V1 should not be NULL!");
TR_ASSERT(memRef != NULL, "Memory Ref should not be NULL!");
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset((void*)cursor, 0, getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
// For large disp scenarios the memref could insert new inst
padding = memRef->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the instruction
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// Immediate I3
*(cursor + 1) |= bos(static_cast<uint8_t>(getImmediateField3()));
// Operand 4: get V1 and put it at the 4th operand field
toRealRegister(v1Reg)->setRegister4Field(reinterpret_cast<uint32_t*>(cursor));
instructionStart = cursor;
cursor += (getOpCode().getInstructionLength());
// Finish patching up if long disp was needed
longDispTouchUpPadding = memRef->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390MemMemInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390MemMemInstruction::estimateBinaryLength(int32_t currentEstimate)
{
int32_t length = 0;
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390MemMemInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
TR::Compilation *comp = cg()->comp();
memset(static_cast<void*>(cursor), 0, getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
// generate binary for first memory reference operand
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// generate binary for second memory reference operand
padding = getMemoryReference2()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the actual instruction op and length
getOpCode().copyBinaryToBufferWithoutClear(cursor);
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference())
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
if (getMemoryReference2())
longDispTouchUpPadding += getMemoryReference2()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390SS1Instruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390SS1Instruction::estimateBinaryLength(int32_t currentEstimate)
{
int32_t length = 0;
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390SS1Instruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
TR::Compilation *comp = cg()->comp();
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
// generate binary for first memory reference operand
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// generate binary for second memory reference operand
padding = getMemoryReference2()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// If we spilled the 2nd memref, than we need to ensure the base register field and the displacement
// for the first memref is re-written to the now changed cursor
if (getLocalLocalSpillReg2())
{
toRealRegister(getMemoryReference()->getBaseRegister())->setBaseRegisterField((uint32_t *)cursor);
*(uint32_t *)cursor &= boi(0xFFFFF000); // Clear out the memory first
*(uint32_t *)cursor |= boi(getMemoryReference()->getOffset() & 0x00000FFF);
}
// Overlay the actual instruction op and length
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// generate binary for the length field
TR_ASSERT(getLen() >= 0 && getLen() <= 255,"SS1 L must be in the range 0->255 and not %d on inst %p\n",getLen(),this);
(*(uint32_t *) cursor) &= boi(0xFF00FFFF);
(*(uint8_t *) (cursor + 1)) |= getLen();
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
longDispTouchUpPadding += getMemoryReference2()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390SS2Instruction:: member functions
////////////////////////////////////////////////////////////////////////////////
uint8_t *
TR::S390SS2Instruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
// generate binary for first memory reference operand
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
if (getMemoryReference2())
{
// generate binary for second memory reference operand
padding = getMemoryReference2()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
}
else
{
(*(int16_t *) (cursor + 4)) = bos(getShiftAmount() & 0xFFF);
}
// If we spilled the 2nd memref, than we need to ensure the base register field and the displacement
// for the first memref is re-written to the now changed cursor
if (getLocalLocalSpillReg2())
{
toRealRegister(getMemoryReference()->getBaseRegister())->setBaseRegisterField((uint32_t *)cursor);
*(uint32_t *)cursor &= boi(0xFFFFF000); // Clear out the memory first
*(uint32_t *)cursor |= boi(getMemoryReference()->getOffset() & 0x00000FFF);
}
// Overlay the actual instruction op and lengths
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// generate binary for the length field
TR_ASSERT(getLen() >= 0 && getLen() <= 15,"SS2 L1 must be in the range 0->15 and not %d from [%p]\n",getLen(), getNode());
TR_ASSERT(getLen2() >= 0 && getLen2() <= 15,"SS2 L2 must be in the range 0->15 and not %d\n",getLen2());
(*(uint32_t *) cursor) &= boi(0xFF00FFFF);
uint16_t lenField = (getLen() << 4) | getLen2();
(*(uint8_t *) (cursor + 1)) |= lenField;
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
if (getMemoryReference2())
longDispTouchUpPadding += getMemoryReference2()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390SS2Instruction:: member functions
////////////////////////////////////////////////////////////////////////////////
uint8_t *
TR::S390SS4Instruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
// generate binary for first memory reference operand
if(getMemoryReference())
{
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
}
// generate binary for second memory reference operand
if(getMemoryReference2())
{
padding = getMemoryReference2()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
}
// Overlay the actual instruction op and lengths
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// generate binary for the length and source key registers
if(getLengthReg())
toRealRegister(getRegForBinaryEncoding(getLengthReg()))->setRegisterField((uint32_t *)cursor, 5);
if(getSourceKeyReg())
toRealRegister(getRegForBinaryEncoding(getSourceKeyReg()))->setRegisterField((uint32_t *)cursor, 4);
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference())
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
if (getMemoryReference2())
longDispTouchUpPadding += getMemoryReference2()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390SSFInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
bool
TR::S390SSFInstruction::refsRegister(TR::Register * reg)
{
// 64bit mem refs clobber high word regs
if (reg->getKind() != TR_FPR && reg->getKind() != TR_VRF && getMemoryReference()&& reg->getRealRegister())
{
TR::RealRegister * realReg = (TR::RealRegister *)reg;
TR::Register * regMem = reg;
if (getMemoryReference()->refsRegister(regMem))
{
return true;
}
if (getMemoryReference2()->refsRegister(regMem))
{
return true;
}
}
if (matchesTargetRegister(reg))
{
return true;
}
else if ((getMemoryReference() != NULL) && (getMemoryReference()->refsRegister(reg) == true))
{
return true;
}
else if ((getMemoryReference2() != NULL) && (getMemoryReference2()->refsRegister(reg) == true))
{
return true;
}
else if (getDependencyConditions())
{
return getDependencyConditions()->refsRegister(reg);
}
return false;
}
int32_t
TR::S390SSFInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390SSFInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
getOpCode().copyBinaryToBuffer(instructionStart);
// encode target register
toRealRegister(getFirstRegister())->setRegister1Field((uint32_t *) cursor);
// generate binary for first memory reference operand
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// generate binary for second memory reference operand
padding = getMemoryReference2()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference())
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
if (getMemoryReference2())
longDispTouchUpPadding += getMemoryReference2()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390RSLInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390RSLInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390RSLInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the actual instruction and reg
getOpCode().copyBinaryToBufferWithoutClear(cursor);
// generate binary for the length field
TR_ASSERT(getLen() <= 0xf,"length %d is too large to encode in RSL instruction\n",getLen());
(*(uint32_t *) cursor) &= boi(0xFF0FFFFF);
(*(uint8_t *) (cursor + 1)) |= (getLen() << 4);
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390RSLbInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390RSLbInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390RSLbInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the actual instruction
getOpCode().copyBinaryToBufferWithoutClear(cursor);
instructionStart = cursor;
// generate binary for the length field
TR_ASSERT(getLen() <= UCHAR_MAX,"length %d is too large to encode in RSLb instruction\n",getLen());
(*(uint32_t *) cursor) &= boi(0xFF00FFFF);
(*(uint8_t *) (cursor + 1)) |= (getLen()&UCHAR_MAX);
cursor += 2;
TR_ASSERT(getRegisterOperand(1),"expecting a reg for RSLb instruction op %d\n",getOpCodeValue());
TR::Register *reg = getRegForBinaryEncoding(getRegisterOperand(1));
toRealRegister(reg)->setBaseRegisterField((uint32_t *)cursor);
cursor += 2;
TR_ASSERT(getMask() <= 0xf,"mask %d is too large to encode in RSLb instruction\n",getMask());
(*(uint16_t *) cursor) &= bos(0xF0FF);
(*(uint8_t *) (cursor)) |= (getMask()&0xf);
cursor += 2;
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390SIInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390SIInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390SIInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
TR::InstOpCode& opCode = getOpCode();
if (getMemoryReference()->isLongDisplacementRequired())
{
auto longDisplacementMnemonic = TR::InstOpCode::getEquivalentLongDisplacementMnemonic(getOpCodeValue());
if (longDisplacementMnemonic != TR::InstOpCode::BAD)
{
opCode = TR::InstOpCode(longDisplacementMnemonic);
}
}
opCode.copyBinaryToBufferWithoutClear(cursor);
(*(uint32_t *) cursor) &= boi(0xFF00FFFF);
(*(uint8_t *) (cursor + 1)) |= getSourceImmediate();
instructionStart = cursor;
cursor += opCode.getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// LL: TR::S390SIYInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390SIYInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390SIYInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
getOpCode().copyBinaryToBufferWithoutClear(cursor);
(*(uint32_t *) cursor) &= boi(0xFF00FFFF);
(*(uint8_t *) (cursor + 1)) |= getSourceImmediate();
instructionStart = cursor;
cursor += (getOpCode().getInstructionLength());
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390SILInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390SILInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
/**
* SIL Format
* ________________ ____ ____________ ________________
* | Op Code | B1 | D1 | I2 |
* |________________|____|____________|________________|
* 0 16 20 32 47
*/
uint8_t *
TR::S390SILInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the actual instruction and reg
getOpCode().copyBinaryToBufferWithoutClear(cursor);
(*(int16_t *) (cursor + 4)) |= bos((int16_t) getSourceImmediate());
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390SInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390SInstruction::estimateBinaryLength(int32_t currentEstimate)
{
if (getMemoryReference() != NULL)
{
return getMemoryReference()->estimateBinaryLength(currentEstimate, cg(), this);
}
else
{
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
}
uint8_t *
TR::S390SInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
int32_t padding = 0, longDispTouchUpPadding = 0;
TR::Compilation *comp = cg()->comp();
padding = getMemoryReference()->generateBinaryEncoding(cursor, cg(), this);
cursor += padding;
// Overlay the actual instruction and reg
getOpCode().copyBinaryToBufferWithoutClear(cursor);
instructionStart = cursor;
cursor += getOpCode().getInstructionLength();
// Finish patching up if long disp was needed
if (getMemoryReference() != NULL)
{
longDispTouchUpPadding = getMemoryReference()->generateBinaryEncodingTouchUpForLongDisp(cursor, cg(), this);
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength() - padding - longDispTouchUpPadding);
return cursor;
}
////////////////////////////////////////////////////////////////////////////////
// TR::S390NOPInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
int32_t
TR::S390NOPInstruction::estimateBinaryLength(int32_t currentEstimate)
{
// could have 2 byte, 4 byte or 6 byte NOP
setEstimatedBinaryLength(6);
return currentEstimate + getEstimatedBinaryLength();
}
uint8_t *
TR::S390NOPInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
TR::Compilation *comp = cg()->comp();
if (getBinaryLength() == 2)
{
uint16_t nopInst;
nopInst = 0x1800;
(*(uint16_t *) cursor) = bos(nopInst);
cursor += 2;
}
else if (getBinaryLength() == 4)
{
uint32_t nopInst = 0x47000000;
(*(uint32_t *) cursor) = boi(nopInst);
cursor += 4;
}
else if(getBinaryLength() == 6)
{
uint32_t nopInst1 = 0xc0040000;
uint16_t nopInst2 = 0x0;
*(uint32_t *) cursor = boi(nopInst1);
*(uint16_t *)(cursor+4) = bos(nopInst2);
cursor += 6;
}
else
{
TR_ASSERT(0, "TODO - NOP other than 2, 4 or 6 bytes not supported yet \n");
}
setBinaryLength(cursor - instructionStart);
setBinaryEncoding(instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
// ////////////////////////////////////////////////////////////////////////////////
// TR::S390MIIInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
/**
* MII Format
*
* ________ ____ _______________ _________________________
* |Op Code | M1 | RI2 | RI3 |
* |________|____|_______________|_________________________|
* 0 8 12 24 47
*/
int32_t
TR::S390MIIInstruction::estimateBinaryLength(int32_t currentEstimate)
{
//TODO:for now use instruction length (for case 0(R14), later need to add support for longer disposition
//potentially reuse Memoryreference->estimateBinaryLength
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
uint8_t *
TR::S390MIIInstruction::generateBinaryEncoding()
{
// acquire the current cursor location so we can start generating our
// instruction there.
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
// we'll need to keep the start location, and our current writing location.
uint8_t * cursor = instructionStart;
int distance = (cg()->getBinaryBufferStart() + getLabelSymbol()->getEstimatedCodeLocation()) -
(cursor + cg()->getAccumulatedInstructionLengthError());
static bool bpp = (feGetEnv("TR_BPPNOBINARY")!=NULL);
intptrj_t offset = (intptrj_t) getSymRef()->getMethodAddress() - (intptrj_t) instructionStart;
if (distance >= MIN_12_RELOCATION_VAL && distance <= MAX_12_RELOCATION_VAL && !bpp &&
offset >= MIN_24_RELOCATION_VAL && offset <= MAX_24_RELOCATION_VAL)
{
// clear the number of bytes we intend to use in the buffer.
memset((void*)cursor, 0, getEstimatedBinaryLength());
// overlay the actual instruction op code to the buffer.
getOpCode().copyBinaryToBuffer(cursor);
// advance the cursor one byte.
cursor += 1;
//add relocation 12-24 bits
//TODO: later add TR::12BitInstructionRelativeRelocation
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative12BitRelocation(cursor, getLabelSymbol(),false));
// add the comparison mask for the instruction to the buffer.
*(int16_t *) cursor |= ((uint16_t)getMask() << 12);
// advance the cursor past the mask encoding and part of RI2 (relocation) (cursor at 16th bit)
cursor += 1;
// add RI3 24-47 # of halfword from current or memory
//TODO need a check too
intptrj_t offset = (intptrj_t) getSymRef()->getMethodAddress() - (intptrj_t) instructionStart;
int32_t offsetInHalfWords = (int32_t) (offset/2);
//mask out first 8 bits
offsetInHalfWords &= 0x00ffffff;
// *(cursor) = (offsetInHalfWords << 8);
*(int32_t *) (cursor) |= offsetInHalfWords;
cursor += 4;
}
// set the binary length of our instruction
setBinaryLength(cursor - instructionStart);
// set the binary encoding to point at where our instruction begins in the
// buffer
setBinaryEncoding(instructionStart);
// account for the error in estimation
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
// return the the cursor for the next instruction.
return cursor;
}
// ////////////////////////////////////////////////////////////////////////////////
// TR::S390SMIInstruction:: member functions
////////////////////////////////////////////////////////////////////////////////
/**
* SMI Format
* ________ ____ ____ ____ ____________ ___________________
* |Op Code | M1 | | B3 | D3 | RI2 |
* |________|____|____|____|____________|___________________|
* 0 8 12 16 20 32 40 47
*/
int32_t
TR::S390SMIInstruction::estimateBinaryLength(int32_t currentEstimate)
{
//TODO:for now use instruction length (for case 0(R14), later need to add support for longer disposition
//potentially reuse Memoryreference->estimateBinaryLength
return TR::Instruction::estimateBinaryLength(currentEstimate);
}
uint8_t *
TR::S390SMIInstruction::generateBinaryEncoding()
{
// acquire the current cursor location so we can start generating our
// instruction there.
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
// we'll need to keep the start location, and our current writing location.
uint8_t * cursor = instructionStart;
int distance = (cg()->getBinaryBufferStart() + getLabelSymbol()->getEstimatedCodeLocation()) -
(cursor + cg()->getAccumulatedInstructionLengthError());
static bool bpp = (feGetEnv("TR_BPPNOBINARY")!=NULL);
if (distance >= MIN_RELOCATION_VAL && distance <= MAX_RELOCATION_VAL && !bpp)
{
// clear the number of bytes we intend to use in the buffer.
memset((void*)cursor, 0, getEstimatedBinaryLength());
// overlay the actual instruction op code to the buffer.
getOpCode().copyBinaryToBuffer(cursor);
// advance the cursor one byte.
cursor += 1;
// add the comparison mask for the instruction to the buffer.
*(cursor) |= ((uint8_t)getMask() << 4);
// advance the cursor past the mask encoding.
cursor += 1;
// add the memory reference for the target to the buffer, and advance the
// cursor past what gets written.
//TODO: make sure MemoryReference()->generateBinaryEncoding handles it correctly
int32_t padding = getMemoryReference()->generateBinaryEncoding(instructionStart, cg(), this);
//TODO: fix for when displacement is too big and need an extra instruction cursor += padding;
cursor += 2;
// add relocation
//TODO: later add TR::16BitInstructionRelativeRelocation
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative16BitRelocation(cursor, getLabelSymbol(), 4, true));
// advance the cursor past the immediate.
cursor += 2;
}
// set the binary length of our instruction
setBinaryLength(cursor - instructionStart);
// set the binary encoding to point at where our instruction begins in the
// buffer
setBinaryEncoding(instructionStart);
// account for the error in estimation
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
// return the the cursor for the next instruction.
return cursor;
}
#ifdef J9_PROJECT_SPECIFIC
/**
* VirtualGuardNOPInstruction is a pseudo instruction that generates a BRC or BRCL
* This branch will be to a label. It is assumed it is within range of a BRC on a G5--
* previous checking will ensure this. If on a freeway, we are free to choose either
* BRC or BRCL depending on the range.
*/
uint8_t *
TR::S390VirtualGuardNOPInstruction::generateBinaryEncoding()
{
uint8_t * instructionStart = cg()->getBinaryBufferCursor();
TR::LabelSymbol * label = getLabelSymbol();
uint8_t * cursor = instructionStart;
memset( (void*)cursor,0,getEstimatedBinaryLength());
uint16_t binOpCode;
intptrj_t distance;
bool doRelocation;
bool shortRelocation = false;
bool longRelocation = false;
uint8_t * relocationPoint = NULL;
TR::Compilation *comp = cg()->comp();
TR::Instruction *guardForPatching = cg()->getVirtualGuardForPatching(this);
// a previous guard is patching to the same destination and we can recycle the patch
// point so setup the patching location to use this previous guard and generate no
// instructions ourselves
if (guardForPatching != this)
{
_site->setLocation(guardForPatching->getBinaryEncoding());
setBinaryLength(0);
setBinaryEncoding(cursor);
if (label->getCodeLocation() == NULL)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelAbsoluteRelocation((uint8_t *) (&_site->getDestination()), label));
}
else
{
_site->setDestination(label->getCodeLocation());
}
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
return cursor;
}
_site->setLocation(cursor);
if (label->getCodeLocation() != NULL)
{
// Label location is known--doubt this will ever occur, but for completeness....
// calculate the relative branch distance
distance = (label->getCodeLocation() - cursor);
doRelocation = false;
_site->setDestination(label->getCodeLocation());
#ifdef DEBUG
if (debug("traceVGNOP"))
{
printf("####> virtual location = %p, label location = %p\n", cursor, label->getCodeLocation());
}
#endif
}
else
{
// Label location is unknown
// estimate the relative branch distance
_site->setDestination(cursor);
distance = (cg()->getBinaryBufferStart() + label->getEstimatedCodeLocation()) -
cursor -
cg()->getAccumulatedInstructionLengthError();
//bool brcRangeExceeded = (distance<MIN_IMMEDIATE_VAL || distance>MAX_IMMEDIATE_VAL);
AOTcgDiag1(comp, "add TR_AbsoluteMethodAddress cursor=%x\n", (uint8_t *) (&_site->getDestination()));
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelAbsoluteRelocation((uint8_t *) (&_site->getDestination()), label));
doRelocation = true;
#ifdef DEBUG
if (debug("traceVGNOP"))
{
printf("####> virtual location(est) = %p+%d, label (relocation) = %p\n", cursor, distance, label);
}
#endif
}
/**
* Z supports two types of patching:
* 1. NOP branch is inserted. When assumption is triggered, the condition
* nibble is changed from 0x0 to 0xf.
* 2. No branch instruction is inserted. When assumption is triggered, a
* full taken branch is patched in.
*/
// We can only do the empty patch (i.e. no instrs emitted, and a full taken patch is written
// in) if the patching occurs during GC pause times. The patching of up to 6-bytes is potentially
// not atomic.
bool performEmptyPatch = getNode()->isStopTheWorldGuard() || getNode()->isProfiledGuard();
// Stop the world guards that are merged with profiled guards never need to generate NOPs for patching because
// the profiled guard will generate the NOP branch to the same location the stop the world guard needs to branch
// to, so we can always use the NOP branch form the profiled guard as our stop the world patch point.
int32_t sumEstimatedBinaryLength = getNode()->isProfiledGuard() ? 6 : 0;
if (performEmptyPatch)
{
// so at this point we know we are an stop the world guard and that there may be other stop the world guards
// after us that will use us as their patch point. We now calculate how much space we
// are sure to have to overwrite to inform us about what to do next
TR::Node *firstBBEnd = NULL;
for (TR::Instruction *nextI = getNext(); nextI != NULL; nextI = nextI->getNext())
{
if (nextI->isVirtualGuardNOPInstruction())
{
// if we encounter a guard that will not use us as a patch point we need to stop
// counting and get out
if (cg()->getVirtualGuardForPatching(nextI) != this)
break;
// otherwise they are going to use us as patch point so skip them and keep going
continue;
}
if (comp->isPICSite(nextI))
break;
// the following instructions can be patched at runtime to set destinations etc
// and so we cannot include them in the region for an HCR guard to overwrite because
// the runtime patching could take place after the HCR guard has been patched
// TODO: BRCL and BRASL are only patchable under specific conditions - this check can be
// made more specific to let some cases through
if (nextI->getOpCodeValue() == TR::InstOpCode::LABEL ||
nextI->getOpCodeValue() == TR::InstOpCode::BRCL ||
nextI->getOpCodeValue() == TR::InstOpCode::BRASL ||
nextI->getOpCodeValue() == TR::InstOpCode::DC ||
nextI->getOpCodeValue() == TR::InstOpCode::DC2 ||
nextI->getOpCodeValue() == TR::InstOpCode::LARL)
break;
// we shouldn't need to check for PSEUDO instructions, but VGNOP has a non-zero length so
// skip PSEUDO instructions from length consideration because in practice they will generally
// be zero
if (nextI->getOpCode().getInstructionFormat() != PSEUDO)
sumEstimatedBinaryLength += nextI->getOpCode().getInstructionLength();
// we never need more than 6 bytes so save time and get out when we have found what we want
if (sumEstimatedBinaryLength >= 6)
break;
TR::Node *node = nextI->getNode();
if (node && node->getOpCodeValue() == TR::BBEnd)
{
if (firstBBEnd == NULL)
firstBBEnd = node;
else if (firstBBEnd != node &&
(node->getBlock()->getNextBlock() == NULL ||
!node->getBlock()->getNextBlock()->isExtensionOfPreviousBlock()))
break;
}
if (node && node->getOpCodeValue()==TR::BBStart && firstBBEnd!=NULL && !node->getBlock()->isExtensionOfPreviousBlock())
break;
}
}
// If we scanned ahead and see that the estimated binary length is zero (i.e. return point of slow path is right after the guard -
// methodEnter/Exit is an example of such) we'll just generate the NOP branch.
if (performEmptyPatch && (sumEstimatedBinaryLength > 0) &&
performTransformation(comp, "O^O CODE GENERATION: Generating empty patch for guard node %p\n", getNode()))
{
doRelocation = false;
if (sumEstimatedBinaryLength < 6)
{
// short branch
if (distance >= MIN_IMMEDIATE_VAL && distance <= MAX_IMMEDIATE_VAL)
{
if (sumEstimatedBinaryLength <= 2)
{
*(uint16_t *) cursor = bos(0x1800);
cursor += 2;
}
}
// long branch
else
{
if (sumEstimatedBinaryLength <= 2)
{
*(uint32_t *) cursor = boi(0xa7040000);
cursor += 4;
}
else if (sumEstimatedBinaryLength <= 4)
{
*(uint16_t *) cursor = bos(0x1800);
cursor += 2;
}
}
}
}
else if (distance >= MIN_IMMEDIATE_VAL && distance <= MAX_IMMEDIATE_VAL)
{
// if distance is within 32K limit, generate short instruction
binOpCode = *(uint16_t *) (TR::InstOpCode::getOpCodeBinaryRepresentation(TR::InstOpCode::BRC));
*(uint16_t *) cursor = bos(binOpCode);
*(uint16_t *) cursor &= bos(0xff0f); // turn into a nop
*(uint16_t *) (cursor + 2) |= bos(distance / 2);
relocationPoint = cursor + 2;
shortRelocation = true;
cursor += TR::InstOpCode::getInstructionLength(TR::InstOpCode::BRC);
}
else
{
// Since N3 and up, generate BRCL instruction
binOpCode = *(uint16_t *) (TR::InstOpCode::getOpCodeBinaryRepresentation(TR::InstOpCode::BRCL));
*(uint16_t *) cursor = bos(binOpCode);
*(uint16_t *) cursor &= bos(0xff0f); // turn into a nop
*(uint32_t *) (cursor + 2) |= boi(distance / 2);
longRelocation = true;
relocationPoint = cursor;
setOpCodeValue(TR::InstOpCode::BRCL);
cursor += TR::InstOpCode::getInstructionLength(TR::InstOpCode::BRCL);
}
// for debugging--a branch instead of NOP
static char * forceBranch = feGetEnv("TR_FORCEVGBR");
if (NULL != forceBranch)
{
*(int16_t *) (instructionStart) |= bos(0x00f0);
}
if (doRelocation)
{
if (shortRelocation)
{
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative16BitRelocation(relocationPoint, label));
}
else
{
TR_ASSERT( longRelocation, "how did I get here??\n");
cg()->addRelocation(new (cg()->trHeapMemory()) TR::LabelRelative32BitRelocation(relocationPoint, label));
}
}
setBinaryLength(cursor - instructionStart);
cg()->addAccumulatedInstructionLengthError(getEstimatedBinaryLength() - getBinaryLength());
setBinaryEncoding(instructionStart);
return cursor;
}
#endif
TR::MemoryReference *getFirstReadWriteMemoryReference(TR::Instruction *i)
{
TR::MemoryReference *mr = NULL;
switch(i->getKind())
{
case TR::Instruction::IsRS:
case TR::Instruction::IsRSY:
mr = toS390RSInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsSMI:
mr = toS390SMIInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsMem:
case TR::Instruction::IsMemMem:
case TR::Instruction::IsSI:
case TR::Instruction::IsSIY:
case TR::Instruction::IsSIL:
case TR::Instruction::IsS:
case TR::Instruction::IsRSL:
case TR::Instruction::IsSS1:
case TR::Instruction::IsSS2:
case TR::Instruction::IsSS4:
case TR::Instruction::IsSSE:
case TR::Instruction::IsRXYb:
mr = toS390MemInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsRSLb:
mr = toS390RSLbInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsRX:
case TR::Instruction::IsRXE:
case TR::Instruction::IsRXY:
case TR::Instruction::IsSSF:
mr = toS390RXInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsRXF:
mr = toS390RXFInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsVRSa:
mr = toS390VRSaInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsVRSb:
mr = toS390VRSbInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsVRSc:
mr = toS390VRScInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsVRSd:
mr = static_cast<TR::S390VRSdInstruction*>(i)->getMemoryReference();
break;
case TR::Instruction::IsVRV:
mr = toS390VRVInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsVRX:
mr = toS390VRXInstruction(i)->getMemoryReference();
break;
case TR::Instruction::IsVSI:
mr = static_cast<TR::S390VSIInstruction*>(i)->getMemoryReference();
break;
case TR::Instruction::IsBranch:
case TR::Instruction::IsVirtualGuardNOP:
case TR::Instruction::IsBranchOnCount:
case TR::Instruction::IsBranchOnIndex:
case TR::Instruction::IsLabel:
case TR::Instruction::IsPseudo:
case TR::Instruction::IsNotExtended:
case TR::Instruction::IsImm:
case TR::Instruction::IsImm2Byte:
case TR::Instruction::IsImmSnippet:
case TR::Instruction::IsImmSym:
case TR::Instruction::IsReg:
case TR::Instruction::IsRR:
case TR::Instruction::IsRRD:
case TR::Instruction::IsRRE:
case TR::Instruction::IsRRF:
case TR::Instruction::IsRRF2:
case TR::Instruction::IsRRF3:
case TR::Instruction::IsRRF4:
case TR::Instruction::IsRRF5:
case TR::Instruction::IsRRR:
case TR::Instruction::IsRI:
case TR::Instruction::IsRIL:
case TR::Instruction::IsRRS: // Storage is branch destination
case TR::Instruction::IsRIS: // Storage is branch destination
case TR::Instruction::IsIE:
case TR::Instruction::IsRIE:
case TR::Instruction::IsMII:
case TR::Instruction::IsVRIa:
case TR::Instruction::IsVRIb:
case TR::Instruction::IsVRIc:
case TR::Instruction::IsVRId:
case TR::Instruction::IsVRIe:
case TR::Instruction::IsVRIf:
case TR::Instruction::IsVRIg:
case TR::Instruction::IsVRIh:
case TR::Instruction::IsVRIi:
case TR::Instruction::IsVRRa:
case TR::Instruction::IsVRRb:
case TR::Instruction::IsVRRc:
case TR::Instruction::IsVRRd:
case TR::Instruction::IsVRRe:
case TR::Instruction::IsVRRf:
case TR::Instruction::IsVRRg:
case TR::Instruction::IsVRRh:
case TR::Instruction::IsVRRi:
case TR::Instruction::IsNOP:
case TR::Instruction::IsI:
case TR::Instruction::IsE:
case TR::Instruction::IsOpCodeOnly:
mr = NULL;
break;
default:
TR_ASSERT( 0, "This type of instruction needs to be told how to get memory reference if any. opcode=%s kind=%d\n",i->getOpCode().getMnemonicName(),
i->getKind());
break;
}
return mr;
}
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "assistantclient.h"
#include <QtCore/QString>
#include <QtCore/QProcess>
#include <QtCore/QDir>
#include <QtCore/QLibraryInfo>
#include <QtCore/QDebug>
#include <QtCore/QFileInfo>
#include <QtCore/QObject>
#include <QtCore/QTextStream>
#include <QtCore/QCoreApplication>
QT_BEGIN_NAMESPACE
enum { debugAssistantClient = 0 };
AssistantClient::AssistantClient() :
m_process(0)
{
}
AssistantClient::~AssistantClient()
{
if (isRunning()) {
m_process->terminate();
m_process->waitForFinished();
}
delete m_process;
}
bool AssistantClient::showPage(const QString &path, QString *errorMessage)
{
QString cmd = QStringLiteral("SetSource ");
cmd += path;
return sendCommand(cmd, errorMessage);
}
bool AssistantClient::activateIdentifier(const QString &identifier, QString *errorMessage)
{
QString cmd = QStringLiteral("ActivateIdentifier ");
cmd += identifier;
return sendCommand(cmd, errorMessage);
}
bool AssistantClient::activateKeyword(const QString &keyword, QString *errorMessage)
{
QString cmd = QStringLiteral("ActivateKeyword ");
cmd += keyword;
return sendCommand(cmd, errorMessage);
}
bool AssistantClient::sendCommand(const QString &cmd, QString *errorMessage)
{
if (debugAssistantClient)
qDebug() << "sendCommand " << cmd;
if (!ensureRunning(errorMessage))
return false;
if (!m_process->isWritable() || m_process->bytesToWrite() > 0) {
*errorMessage = QCoreApplication::translate("AssistantClient", "Unable to send request: Assistant is not responding.");
return false;
}
QTextStream str(m_process);
str << cmd << QLatin1Char('\n') << endl;
return true;
}
bool AssistantClient::isRunning() const
{
return m_process && m_process->state() != QProcess::NotRunning;
}
QString AssistantClient::binary()
{
QString app = QLibraryInfo::location(QLibraryInfo::BinariesPath) + QDir::separator();
#if !defined(Q_OS_MACOS)
app += QStringLiteral("assistant");
#else
app += QStringLiteral("Assistant.app/Contents/MacOS/Assistant");
#endif
#if defined(Q_OS_WIN)
app += QStringLiteral(".exe");
#endif
return app;
}
bool AssistantClient::ensureRunning(QString *errorMessage)
{
if (isRunning())
return true;
if (!m_process)
m_process = new QProcess;
const QString app = binary();
if (!QFileInfo(app).isFile()) {
*errorMessage = QCoreApplication::translate("AssistantClient", "The binary '%1' does not exist.").arg(app);
return false;
}
if (debugAssistantClient)
qDebug() << "Running " << app;
// run
QStringList args(QStringLiteral("-enableRemoteControl"));
m_process->start(app, args);
if (!m_process->waitForStarted()) {
*errorMessage = QCoreApplication::translate("AssistantClient", "Unable to launch assistant (%1).").arg(app);
return false;
}
return true;
}
QString AssistantClient::documentUrl(const QString &module, int qtVersion)
{
if (qtVersion == 0)
qtVersion = QT_VERSION;
QString rc;
QTextStream(&rc) << "qthelp://org.qt-project." << module << '.'
<< (qtVersion >> 16) << ((qtVersion >> 8) & 0xFF) << (qtVersion & 0xFF)
<< '/' << module << '/';
return rc;
}
QString AssistantClient::designerManualUrl(int qtVersion)
{
return documentUrl(QStringLiteral("qtdesigner"), qtVersion);
}
QString AssistantClient::qtReferenceManualUrl(int qtVersion)
{
return documentUrl(QStringLiteral("qtdoc"), qtVersion);
}
QT_END_NAMESPACE
|
;;
;; Copyright (c) 2019-2021, 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.
;;
; routine to do AES ECB encrypt/decrypt on 16n bytes doing AES by 4
; XMM registers are clobbered. Saving/restoring must be done at a higher level
; void aes_ecb_x_y_sse(void *in,
; UINT128 keys[],
; void *out,
; UINT64 len_bytes);
;
; x = direction (enc/dec)
; y = key size (128/192/256)
; arg 1: IN: pointer to input (cipher text)
; arg 2: KEYS: pointer to keys
; arg 3: OUT: pointer to output (plain text)
; arg 4: LEN: length in bytes (multiple of 16)
;
%include "include/os.asm"
%include "include/clear_regs.asm"
%ifndef AES_ECB_ENC_256
%ifndef AES_ECB_ENC_192
%ifndef AES_ECB_ENC_128
%define AES_ECB_ENC_128 aes_ecb_enc_128_sse
%define AES_ECB_DEC_128 aes_ecb_dec_128_sse
%endif
%endif
%endif
%ifdef LINUX
%define IN rdi
%define KEYS rsi
%define OUT rdx
%define LEN rcx
%else
%define IN rcx
%define KEYS rdx
%define OUT r8
%define LEN r9
%endif
%define IDX rax
%define TMP IDX
%define XDATA0 xmm0
%define XDATA1 xmm1
%define XDATA2 xmm2
%define XDATA3 xmm3
%define XKEY0 xmm4
%define XKEY2 xmm5
%define XKEY4 xmm6
%define XKEY6 xmm7
%define XKEY10 xmm8
%define XKEY_A xmm14
%define XKEY_B xmm15
section .text
%macro AES_ECB 2
%define %%NROUNDS %1 ; [in] Number of AES rounds, numerical value
%define %%DIR %2 ; [in] Direction (encrypt/decrypt)
%ifidn %%DIR, ENC
%define AES aesenc
%define AES_LAST aesenclast
%else ; DIR = DEC
%define AES aesdec
%define AES_LAST aesdeclast
%endif
mov TMP, LEN
and TMP, 3*16
jz %%initial_4
cmp TMP, 2*16
jb %%initial_1
ja %%initial_3
%%initial_2:
; load plain/cipher text
movdqu XDATA0, [IN + 0*16]
movdqu XDATA1, [IN + 1*16]
movdqa XKEY0, [KEYS + 0*16]
pxor XDATA0, XKEY0 ; 0. ARK
pxor XDATA1, XKEY0
movdqa XKEY2, [KEYS + 2*16]
AES XDATA0, [KEYS + 1*16] ; 1. ENC
AES XDATA1, [KEYS + 1*16]
mov IDX, 2*16
AES XDATA0, XKEY2 ; 2. ENC
AES XDATA1, XKEY2
movdqa XKEY4, [KEYS + 4*16]
AES XDATA0, [KEYS + 3*16] ; 3. ENC
AES XDATA1, [KEYS + 3*16]
AES XDATA0, XKEY4 ; 4. ENC
AES XDATA1, XKEY4
movdqa XKEY6, [KEYS + 6*16]
AES XDATA0, [KEYS + 5*16] ; 5. ENC
AES XDATA1, [KEYS + 5*16]
AES XDATA0, XKEY6 ; 6. ENC
AES XDATA1, XKEY6
movdqa XKEY_B, [KEYS + 8*16]
AES XDATA0, [KEYS + 7*16] ; 7. ENC
AES XDATA1, [KEYS + 7*16]
AES XDATA0, XKEY_B ; 8. ENC
AES XDATA1, XKEY_B
movdqa XKEY10, [KEYS + 10*16]
AES XDATA0, [KEYS + 9*16] ; 9. ENC
AES XDATA1, [KEYS + 9*16]
%if %%NROUNDS >= 12
AES XDATA0, XKEY10 ; 10. ENC
AES XDATA1, XKEY10
AES XDATA0, [KEYS + 11*16] ; 11. ENC
AES XDATA1, [KEYS + 11*16]
%endif
%if %%NROUNDS == 14
AES XDATA0, [KEYS + 12*16] ; 12. ENC
AES XDATA1, [KEYS + 12*16]
AES XDATA0, [KEYS + 13*16] ; 13. ENC
AES XDATA1, [KEYS + 13*16]
%endif
%if %%NROUNDS == 10
AES_LAST XDATA0, XKEY10 ; 10. ENC
AES_LAST XDATA1, XKEY10
%elif %%NROUNDS == 12
AES_LAST XDATA0, [KEYS + 12*16] ; 12. ENC
AES_LAST XDATA1, [KEYS + 12*16]
%else
AES_LAST XDATA0, [KEYS + 14*16] ; 14. ENC
AES_LAST XDATA1, [KEYS + 14*16]
%endif
movdqu [OUT + 0*16], XDATA0
movdqu [OUT + 1*16], XDATA1
cmp LEN, 2*16
je %%done
jmp %%main_loop
align 16
%%initial_1:
; load plain/cipher text
movdqu XDATA0, [IN + 0*16]
movdqa XKEY0, [KEYS + 0*16]
pxor XDATA0, XKEY0 ; 0. ARK
movdqa XKEY2, [KEYS + 2*16]
AES XDATA0, [KEYS + 1*16] ; 1. ENC
mov IDX, 1*16
AES XDATA0, XKEY2 ; 2. ENC
movdqa XKEY4, [KEYS + 4*16]
AES XDATA0, [KEYS + 3*16] ; 3. ENC
AES XDATA0, XKEY4 ; 4. ENC
movdqa XKEY6, [KEYS + 6*16]
AES XDATA0, [KEYS + 5*16] ; 5. ENC
AES XDATA0, XKEY6 ; 6. ENC
movdqa XKEY_B, [KEYS + 8*16]
AES XDATA0, [KEYS + 7*16] ; 7. ENC
AES XDATA0, XKEY_B ; 8. ENC
movdqa XKEY10, [KEYS + 10*16]
AES XDATA0, [KEYS + 9*16] ; 9. ENC
%if %%NROUNDS >= 12
AES XDATA0, XKEY10 ; 10. ENC
AES XDATA0, [KEYS + 11*16] ; 11. ENC
%endif
%if %%NROUNDS == 14
AES XDATA0, [KEYS + 12*16] ; 12. ENC
AES XDATA0, [KEYS + 13*16] ; 13. ENC
%endif
%if %%NROUNDS == 10
AES_LAST XDATA0, XKEY10 ; 10. ENC
%elif %%NROUNDS == 12
AES_LAST XDATA0, [KEYS + 12*16] ; 12. ENC
%else
AES_LAST XDATA0, [KEYS + 14*16] ; 14. ENC
%endif
movdqu [OUT + 0*16], XDATA0
cmp LEN, 1*16
je %%done
jmp %%main_loop
%%initial_3:
; load plain/cipher text
movdqu XDATA0, [IN + 0*16]
movdqu XDATA1, [IN + 1*16]
movdqu XDATA2, [IN + 2*16]
movdqa XKEY0, [KEYS + 0*16]
movdqa XKEY_A, [KEYS + 1*16]
pxor XDATA0, XKEY0 ; 0. ARK
pxor XDATA1, XKEY0
pxor XDATA2, XKEY0
movdqa XKEY2, [KEYS + 2*16]
AES XDATA0, XKEY_A ; 1. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
movdqa XKEY_A, [KEYS + 3*16]
mov IDX, 3*16
AES XDATA0, XKEY2 ; 2. ENC
AES XDATA1, XKEY2
AES XDATA2, XKEY2
movdqa XKEY4, [KEYS + 4*16]
AES XDATA0, XKEY_A ; 3. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
movdqa XKEY_A, [KEYS + 5*16]
AES XDATA0, XKEY4 ; 4. ENC
AES XDATA1, XKEY4
AES XDATA2, XKEY4
movdqa XKEY6, [KEYS + 6*16]
AES XDATA0, XKEY_A ; 5. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
movdqa XKEY_A, [KEYS + 7*16]
AES XDATA0, XKEY6 ; 6. ENC
AES XDATA1, XKEY6
AES XDATA2, XKEY6
movdqa XKEY_B, [KEYS + 8*16]
AES XDATA0, XKEY_A ; 7. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
movdqa XKEY_A, [KEYS + 9*16]
AES XDATA0, XKEY_B ; 8. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
movdqa XKEY_B, [KEYS + 10*16]
AES XDATA0, XKEY_A ; 9. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
%if %%NROUNDS >= 12
movdqa XKEY_A, [KEYS + 11*16]
AES XDATA0, XKEY_B ; 10. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
movdqa XKEY_B, [KEYS + 12*16]
AES XDATA0, XKEY_A ; 11. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
%endif
%if %%NROUNDS == 14
movdqa XKEY_A, [KEYS + 13*16]
AES XDATA0, XKEY_B ; 12. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
movdqa XKEY_B, [KEYS + 14*16]
AES XDATA0, XKEY_A ; 13. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
%endif
AES_LAST XDATA0, XKEY_B ; 10/12/14. ENC (depending on key size)
AES_LAST XDATA1, XKEY_B
AES_LAST XDATA2, XKEY_B
movdqu [OUT + 0*16], XDATA0
movdqu [OUT + 1*16], XDATA1
movdqu [OUT + 2*16], XDATA2
cmp LEN, 3*16
je %%done
jmp %%main_loop
align 16
%%initial_4:
; load plain/cipher text
movdqu XDATA0, [IN + 0*16]
movdqu XDATA1, [IN + 1*16]
movdqu XDATA2, [IN + 2*16]
movdqu XDATA3, [IN + 3*16]
movdqa XKEY0, [KEYS + 0*16]
movdqa XKEY_A, [KEYS + 1*16]
pxor XDATA0, XKEY0 ; 0. ARK
pxor XDATA1, XKEY0
pxor XDATA2, XKEY0
pxor XDATA3, XKEY0
movdqa XKEY2, [KEYS + 2*16]
AES XDATA0, XKEY_A ; 1. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
movdqa XKEY_A, [KEYS + 3*16]
mov IDX, 4*16
AES XDATA0, XKEY2 ; 2. ENC
AES XDATA1, XKEY2
AES XDATA2, XKEY2
AES XDATA3, XKEY2
movdqa XKEY4, [KEYS + 4*16]
AES XDATA0, XKEY_A ; 3. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
movdqa XKEY_A, [KEYS + 5*16]
AES XDATA0, XKEY4 ; 4. ENC
AES XDATA1, XKEY4
AES XDATA2, XKEY4
AES XDATA3, XKEY4
movdqa XKEY6, [KEYS + 6*16]
AES XDATA0, XKEY_A ; 5. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
movdqa XKEY_A, [KEYS + 7*16]
AES XDATA0, XKEY6 ; 6. ENC
AES XDATA1, XKEY6
AES XDATA2, XKEY6
AES XDATA3, XKEY6
movdqa XKEY_B, [KEYS + 8*16]
AES XDATA0, XKEY_A ; 7. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
movdqa XKEY_A, [KEYS + 9*16]
AES XDATA0, XKEY_B ; 8. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
AES XDATA3, XKEY_B
movdqa XKEY_B, [KEYS + 10*16]
AES XDATA0, XKEY_A ; 9. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
%if %%NROUNDS >= 12
movdqa XKEY_A, [KEYS + 11*16]
AES XDATA0, XKEY_B ; 10. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
AES XDATA3, XKEY_B
movdqa XKEY_B, [KEYS + 12*16]
AES XDATA0, XKEY_A ; 11. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
%endif
%if %%NROUNDS == 14
movdqa XKEY_A, [KEYS + 13*16]
AES XDATA0, XKEY_B ; 12. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
AES XDATA3, XKEY_B
movdqa XKEY_B, [KEYS + 14*16]
AES XDATA0, XKEY_A ; 13. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
%endif
AES_LAST XDATA0, XKEY_B ; 10/12/14. ENC (depending on key size)
AES_LAST XDATA1, XKEY_B
AES_LAST XDATA2, XKEY_B
AES_LAST XDATA3, XKEY_B
movdqu [OUT + 0*16], XDATA0
movdqu [OUT + 1*16], XDATA1
movdqu [OUT + 2*16], XDATA2
movdqu [OUT + 3*16], XDATA3
cmp LEN, 4*16
jz %%done
jmp %%main_loop
align 16
%%main_loop:
; load plain/cipher text
movdqu XDATA0, [IN + IDX + 0*16]
movdqu XDATA1, [IN + IDX + 1*16]
movdqu XDATA2, [IN + IDX + 2*16]
movdqu XDATA3, [IN + IDX + 3*16]
movdqa XKEY_A, [KEYS + 1*16]
pxor XDATA0, XKEY0 ; 0. ARK
pxor XDATA1, XKEY0
pxor XDATA2, XKEY0
pxor XDATA3, XKEY0
add IDX, 4*16
AES XDATA0, XKEY_A ; 1. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
movdqa XKEY_A, [KEYS + 3*16]
AES XDATA0, XKEY2 ; 2. ENC
AES XDATA1, XKEY2
AES XDATA2, XKEY2
AES XDATA3, XKEY2
AES XDATA0, XKEY_A ; 3. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
movdqa XKEY_A, [KEYS + 5*16]
AES XDATA0, XKEY4 ; 4. ENC
AES XDATA1, XKEY4
AES XDATA2, XKEY4
AES XDATA3, XKEY4
AES XDATA0, XKEY_A ; 5. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
movdqa XKEY_A, [KEYS + 7*16]
AES XDATA0, XKEY6 ; 6. ENC
AES XDATA1, XKEY6
AES XDATA2, XKEY6
AES XDATA3, XKEY6
movdqa XKEY_B, [KEYS + 8*16]
AES XDATA0, XKEY_A ; 7. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
movdqa XKEY_A, [KEYS + 9*16]
AES XDATA0, XKEY_B ; 8. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
AES XDATA3, XKEY_B
movdqa XKEY_B, [KEYS + 10*16]
AES XDATA0, XKEY_A ; 9. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
%if %%NROUNDS >= 12
movdqa XKEY_A, [KEYS + 11*16]
AES XDATA0, XKEY_B ; 10. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
AES XDATA3, XKEY_B
movdqa XKEY_B, [KEYS + 12*16]
AES XDATA0, XKEY_A ; 11. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
%endif
%if %%NROUNDS == 14
movdqa XKEY_A, [KEYS + 13*16]
AES XDATA0, XKEY_B ; 12. ENC
AES XDATA1, XKEY_B
AES XDATA2, XKEY_B
AES XDATA3, XKEY_B
movdqa XKEY_B, [KEYS + 14*16]
AES XDATA0, XKEY_A ; 13. ENC
AES XDATA1, XKEY_A
AES XDATA2, XKEY_A
AES XDATA3, XKEY_A
%endif
AES_LAST XDATA0, XKEY_B ; 10/12/14. ENC (depending on key size)
AES_LAST XDATA1, XKEY_B
AES_LAST XDATA2, XKEY_B
AES_LAST XDATA3, XKEY_B
movdqu [OUT + IDX + 0*16 - 4*16], XDATA0
movdqu [OUT + IDX + 1*16 - 4*16], XDATA1
movdqu [OUT + IDX + 2*16 - 4*16], XDATA2
movdqu [OUT + IDX + 3*16 - 4*16], XDATA3
cmp IDX, LEN
jne %%main_loop
%%done:
%ifdef SAFE_DATA
clear_all_xmms_sse_asm
%endif ;; SAFE_DATA
ret
%endmacro
;;
;; AES-ECB 128 functions
;;
%ifdef AES_ECB_ENC_128
align 16
MKGLOBAL(AES_ECB_ENC_128,function,internal)
AES_ECB_ENC_128:
AES_ECB 10, ENC
align 16
MKGLOBAL(AES_ECB_DEC_128,function,internal)
AES_ECB_DEC_128:
AES_ECB 10, DEC
%endif
;;
;; AES-ECB 192 functions
;;
%ifdef AES_ECB_ENC_192
align 16
MKGLOBAL(AES_ECB_ENC_192,function,internal)
AES_ECB_ENC_192:
AES_ECB 12, ENC
align 16
MKGLOBAL(AES_ECB_DEC_192,function,internal)
AES_ECB_DEC_192:
AES_ECB 12, DEC
%endif
;;
;; AES-ECB 256 functions
;;
%ifdef AES_ECB_ENC_256
align 16
MKGLOBAL(AES_ECB_ENC_256,function,internal)
AES_ECB_ENC_256:
AES_ECB 14, ENC
align 16
MKGLOBAL(AES_ECB_DEC_256,function,internal)
AES_ECB_DEC_256:
AES_ECB 14, DEC
%endif
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
/*
*/
#include "macros.h"
.globl exception_vector
.macro exception_handler name
.align 7 //start at 80 byte alignement ?
stp x29,x30, [sp, #-16]!
bl exception_enter
bl \name
b exception_return
.endm
.macro unhandled_exception
.align 7 //start at 80 byte alignement
stp x29,x30, [sp, #-16]!
bl exception_enter
bl exception_unhandled
b exception_return
.endm
/*
VBAR_ELn
+ 0x000 Synchronous Current EL with SP0
+ 0x080 IRQ/vIRQ
+ 0x100 FIQ/vFIQ
+ 0x180 SError/vSError
+ 0x200 Synchronous Current EL with SPx
+ 0x280 IRQ/vIRQ
+ 0x300 FIQ/vFIQ
+ 0x380 SError/vSError
+ 0x400 Synchronous Lower EL using AArch64
+ 0x480 IRQ/vIRQ
+ 0x500 FIQ/vFIQ
+ 0x580 SError/vSError
+ 0x600 Synchronous Lower EL using AArch32
+ 0x680 IRQ/vIRQ
+ 0x700 FIQ/vFIQ
+ 0x780 SError/vSError
*/
//2k alignement needed for vector
//TODO register one for each execution level ?
//.align 11 //2^11 = 2048 2k boundary in accordance with spec
.section .text.exception_table
.balign 0x800 //this needs to go after the section declaration!!!!
exception_vector:
//SP0 Not really tested yet
exception_handler exception_handler_syn_el
exception_handler exception_handler_irq_el
exception_handler exception_handler_fiq_el
exception_handler exception_handler_serror_el
//SPX
exception_handler exception_handler_syn_el
exception_handler exception_handler_irq_el
exception_handler exception_handler_fiq_el
exception_handler exception_handler_serror_el
//aarch64 el0
unhandled_exception
unhandled_exception
unhandled_exception
unhandled_exception
//aarch32 el0
unhandled_exception
unhandled_exception
unhandled_exception
unhandled_exception
exception_enter:
//ARM doc suggests a better way of saving regs
stp x27, x28, [sp, #-16]!
stp x25, x26, [sp, #-16]!
stp x23, x24, [sp, #-16]!
stp x21, x22, [sp, #-16]!
stp x19, x20, [sp, #-16]!
stp x17, x18, [sp, #-16]!
stp x15, x16, [sp, #-16]!
stp x13, x14, [sp, #-16]!
stp x11, x12, [sp, #-16]!
stp x9, x10, [sp, #-16]!
stp x7, x8, [sp, #-16]!
stp x5, x6, [sp, #-16]!
stp x3, x4, [sp, #-16]!
stp x1, x2, [sp, #-16]!
b save_el
save_el:
execution_level_switch x12, 3f, 2f, 1f
3:
mrs x1, esr_el3
mrs x2, elr_el3
b 0f
2:
mrs x1, esr_el2
mrs x2, elr_el2
b 0f
1:
mrs x1, esr_el1
mrs x2, elr_el1
0:
stp x2,x0, [sp,#-16]!
mov x0, sp
ret
exception_return:
//restrore EL state
ldp x2, x0, [sp], #16
execution_level_switch x12, 3f, 2f, 1f
3:
msr elr_el3, x2
b restore_regs
2:
msr elr_el2, x2
b restore_regs
1:
msr elr_el1, x2
b restore_regs
restore_regs:
ldp x1, x2, [sp],#16
ldp x3, x4, [sp],#16
ldp x5, x6, [sp],#16
ldp x7, x8, [sp],#16
ldp x9, x10, [sp],#16
ldp x11, x12, [sp],#16
ldp x13, x14, [sp],#16
ldp x15, x16, [sp],#16
ldp x17, x18, [sp],#16
ldp x19, x20, [sp],#16
ldp x21, x22, [sp],#16
ldp x23, x24, [sp],#16
ldp x25, x26, [sp],#16
ldp x27, x28, [sp],#16
ldp x29, x30, [sp],#16
eret
|
;
; Startup for S-OS (The Sentinel) Japanese OS
;
; Stefano Bodrato - Winter 2013
;
; $Id: sos_crt0.asm,v 1.16 2016-07-15 21:38:08 dom Exp $
;
; There are a couple of #pragma commands which affect
; this file:
;
; #pragma output nostreams - No stdio disc files
; #pragma output noredir - do not insert the file redirection option while parsing the
; command line arguments (useless if "nostreams" is set)
;
; These can cut down the size of the resultant executable
MODULE sos_crt0
;-------------------------------------------------
; Include zcc_opt.def to find out some information
;-------------------------------------------------
defc crt0 = 1
INCLUDE "zcc_opt.def"
;-----------------------
; Some scope definitions
;-----------------------
EXTERN _main ;main() is always external to crt0
PUBLIC cleanup ;jp'd to by exit()
PUBLIC l_dcal ;jp(hl)
IF !DEFINED_CRT_ORG_CODE
defc CRT_ORG_CODE = $3000
ENDIF
defc TAR__clib_exit_stack_size = 32
defc TAR__register_sp = -0x1f6a ;;Upper limit of the user area
defc __CPU_CLOCK = 4000000
INCLUDE "crt/classic/crt_rules.inc"
org CRT_ORG_CODE
; org $3000-18
;
;
; defm "_SOS 01 3000 3000"
; defb $0A
;----------------------
; Execution starts here
;----------------------
start:
ld (start1+1),sp ;Save entry stack
INCLUDE "crt/classic/crt_init_sp.asm"
INCLUDE "crt/classic/crt_init_atexit.asm"
dec sp
call crt0_init_bss
ld (exitsp),sp
; Optional definition for auto MALLOC init
; it assumes we have free space between the end of
; the compiled program and the stack pointer
IF DEFINED_USING_amalloc
INCLUDE "crt/classic/crt_init_amalloc.asm"
ENDIF
; Push pointers to argv[n] onto the stack now
; We must start from the end
ld hl,0 ;NULL pointer at end, just in case
push hl
ld b,h ; parameter counter
ld c,h ; character counter
ld hl,($1F76) ; #KBFAD
; Program is entered with a 'J' (jump command) at location 3000
; so the command name will be always 3000, we skip eventual balnks,
; so "J3000" and "J 3000" will have the same effect
skipblank:
inc hl
inc hl
ld a,(hl)
cp ' '
jr z,skipblank
ld a,(hl)
and a
jr z,argv_done
dec hl
find_end:
inc hl
inc c
ld a,(hl)
and a
jr nz,find_end
dec hl
; now HL points to the end of command line
; and C holds the length of args buffer
ld b,0
INCLUDE "crt/classic/crt_command_line.asm"
push hl ;argv
push bc ;argc
call _main ;Call user code
pop bc ;kill argv
pop bc ;kill argc
cleanup:
push hl ;Save return value
call crt0_exit
pop bc ;Get exit() value into bc
start1: ld sp,0 ;Pick up entry sp
jp $1FFA ; HOT boot
l_dcal: jp (hl) ;Used for call by function ptr
end: defb 0 ; null file name
INCLUDE "crt/classic/crt_runtime_selection.asm"
INCLUDE "crt/classic/crt_section.asm"
SECTION data_crt
; Default block size for "gendos.lib"
; every single block (up to 36) is written in a separate file
; the bigger RND_BLOCKSIZE, bigger can be the output file size
; but this comes at cost of the malloc'd space for the internal buffer
; Current block size is kept in a control block (just a structure saved
; in a separate file, so changing this value
; at runtime before creating a file is perfectly legal.
PUBLIC _RND_BLOCKSIZE;
_RND_BLOCKSIZE: defw 1000
IF !DEFINED_noredir
IF CRT_ENABLE_STDIO = 1
redir_fopen_flag: defb 'w', 0
redir_fopen_flagr: defb 'r', 0
ENDIF
ENDIF
|
; A224525: Number of idempotent 3 X 3 0..n matrices of rank 1.
; 27,69,123,195,273,375,477,603,735,885,1035,1221,1395,1593,1803,2031,2253,2511,2757,3039,3321,3615,3909,4251,4575,4917,5271,5649,6015,6429,6819,7245,7671,8109,8559,9051,9513,9999,10497,11031,11541,12099,12633,13203,13785,14367,14949,15591,16203,16845,17487,18153,18807,19509,20199,20925,21639,22365,23091,23889,24639,25413,26211,27027,27837,28683,29505,30363,31221,32115,32985,33927,34821,35739,36681,37635,38589,39579,40545,41571,42579,43593,44607,45693,46743,47805,48879,49989,51075,52233,53355
lpb $0
add $1,2
mov $2,$0
seq $2,62249 ; a(n) = n + d(n), where d(n) = number of divisors of n, cf. A000005.
add $1,$2
add $1,$0
sub $0,1
lpe
mul $1,6
add $1,27
mov $0,$1
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
(c) Copyright GeoWorks 1995. All Rights Reserved.
GEOWORKS CONFIDENTIAL
PROJECT: GEOS
MODULE: Sokoban
FILE: sokobanJBitmaps.asm
AUTHOR: Steve Yegge, Jul 27, 1995
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
stevey 7/27/95 Initial revision
DESCRIPTION:
Jedi game bitmaps.
$Id: sokobanJBitmaps.asm,v 1.1 97/04/04 15:13:18 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
if 0
/* The following is for Jedi version. They've been defined in
* sokobanBitmap.asm.
*/
Bitmaps segment lmem LMEM_TYPE_GENERAL
monoGroundBitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
db 0x00, 0x00
monoGroundBitmap endc
monoSafeBitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x55, 0x55
db 0xaa, 0xaa
db 0x55, 0x55
db 0xaa, 0xaa
db 0x55, 0x55
db 0xaa, 0xaa
db 0x55, 0x55
db 0xaa, 0xaa
db 0x55, 0x55
db 0xaa, 0xaa
db 0x55, 0x55
db 0xaa, 0xaa
monoSafeBitmap endc
;
; These are a coin.
;
monoPacketBitmap chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x1f, 0x00
db 0x20, 0x80
db 0x44, 0x40
db 0x8f, 0x20
db 0x94, 0x30
db 0x8e, 0x30
db 0x85, 0x30
db 0x9e, 0x30
db 0x44, 0x70
db 0x20, 0xe0
db 0x1f, 0xc0
db 0x0f, 0x80
monoPacketBitmap endc
monoSafePacketBitmap chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xa0, 0xa0
db 0x44, 0x50
db 0x8f, 0x20
db 0x94, 0x30
db 0x8e, 0x30
db 0x85, 0x30
db 0x9e, 0x30
db 0x44, 0x70
db 0xa0, 0xe0
db 0x5f, 0xd0
db 0xaf, 0xa0
monoSafePacketBitmap endc
ml1 chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x11, 0xc0
db 0x28, 0xc0
db 0x10, 0xc0
db 0x08, 0x40
db 0x11, 0x80
db 0x1d, 0x80
db 0x1d, 0x80
db 0x3d, 0x80
db 0x47, 0x80
db 0x7f, 0x00
ml1 endc
ml1d chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x11, 0xc0
db 0x28, 0xc0
db 0x10, 0xc0
db 0x08, 0x40
db 0x11, 0x80
db 0x1d, 0x80
db 0x1d, 0x80
db 0x3d, 0x80
db 0x44, 0x80
db 0x7f, 0x00
ml1d endc
ml1ds chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x51, 0xd0
db 0xa8, 0xe0
db 0x50, 0xd0
db 0xa8, 0x60
db 0x51, 0xd0
db 0xbd, 0xa0
db 0x5d, 0xd0
db 0xbd, 0xa0
db 0x44, 0xd0
db 0xff, 0xa0
ml1ds endc
ml1l chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x91, 0xc0
db 0xa8, 0xc0
db 0xd0, 0xc0
db 0xc8, 0x40
db 0x61, 0x80
db 0x3f, 0x80
db 0x1f, 0x80
db 0x3f, 0x80
db 0x47, 0x80
db 0x7f, 0x00
ml1l endc
ml1ls chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0xd1, 0xd0
db 0xa8, 0xe0
db 0xd0, 0xd0
db 0xc8, 0x60
db 0x61, 0xd0
db 0xbf, 0xa0
db 0x5f, 0xd0
db 0xbf, 0xa0
db 0x47, 0xd0
db 0xff, 0xa0
ml1ls endc
ml1s chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x51, 0xd0
db 0xa8, 0xe0
db 0x50, 0xd0
db 0xa8, 0x60
db 0x51, 0xd0
db 0xbd, 0xa0
db 0x5d, 0xd0
db 0xbd, 0xa0
db 0x47, 0xd0
db 0xff, 0xa0
ml1s endc
ml1u chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x18, 0x80
db 0x15, 0xc0
db 0x2d, 0xc0
db 0x15, 0xc0
db 0x0d, 0x40
db 0x15, 0x80
db 0x1f, 0x80
db 0x1f, 0x80
db 0x3f, 0x80
db 0x47, 0x80
db 0x7f, 0x00
ml1u endc
ml1us chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xb8, 0xa0
db 0x55, 0xd0
db 0xad, 0xe0
db 0x55, 0xd0
db 0xad, 0x60
db 0x55, 0xd0
db 0xbf, 0xa0
db 0x5f, 0xd0
db 0xbf, 0xa0
db 0x47, 0xd0
db 0xff, 0xa0
ml1us endc
ml2 chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x11, 0xc0
db 0x28, 0xc0
db 0x10, 0xc0
db 0x08, 0x40
db 0x11, 0x80
db 0x1d, 0xa0
db 0xdd, 0xd0
db 0xbd, 0xd0
db 0x5b, 0x90
db 0x30, 0x70
ml2 endc
ml2d chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x11, 0xc0
db 0x28, 0xc0
db 0x10, 0xc0
db 0x08, 0x40
db 0x11, 0x80
db 0x1d, 0xa0
db 0xdd, 0xd0
db 0xbd, 0xd0
db 0x58, 0x90
db 0x30, 0x70
ml2d endc
ml2ds chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x51, 0xd0
db 0xa8, 0xe0
db 0x50, 0xd0
db 0xa8, 0x60
db 0x51, 0xd0
db 0xbd, 0xa0
db 0xdd, 0xd0
db 0xbd, 0xd0
db 0x58, 0x90
db 0xb0, 0x70
ml2ds endc
ml2l chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x11, 0xc0
db 0xa8, 0xc0
db 0xd0, 0xc0
db 0xc8, 0x40
db 0x61, 0x80
db 0x3f, 0xa0
db 0xdf, 0xd0
db 0xbf, 0xd0
db 0x5b, 0x90
db 0x30, 0x70
ml2l endc
ml2ls chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x51, 0xd0
db 0xa8, 0xe0
db 0xd0, 0xd0
db 0xc8, 0x60
db 0x61, 0xd0
db 0x3f, 0xa0
db 0xdf, 0xd0
db 0xbf, 0xd0
db 0x5b, 0x90
db 0xb0, 0x70
ml2ls endc
ml2s chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x51, 0xd0
db 0xa8, 0xe0
db 0x50, 0xd0
db 0xa8, 0x60
db 0x51, 0xd0
db 0xbd, 0xa0
db 0xdd, 0xd0
db 0xbd, 0xd0
db 0x5b, 0x90
db 0x30, 0x70
ml2s endc
ml2u chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x18, 0x80
db 0x15, 0xc0
db 0x2d, 0xc0
db 0x15, 0xc0
db 0x0d, 0x40
db 0x15, 0x80
db 0x1f, 0xa0
db 0xdf, 0xd0
db 0xbf, 0xd0
db 0x5b, 0x90
db 0x30, 0x70
ml2u endc
ml2us chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xb8, 0xa0
db 0x55, 0xd0
db 0xad, 0xe0
db 0x55, 0xd0
db 0xad, 0x60
db 0x55, 0x90
db 0xbf, 0xa0
db 0xdf, 0xd0
db 0xbf, 0xd0
db 0x5b, 0x90
db 0xb0, 0x70
ml2us endc
mr1 chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x38, 0x80
db 0x31, 0x40
db 0x30, 0x80
db 0x21, 0x00
db 0x18, 0x80
db 0x1b, 0x80
db 0x1b, 0x80
db 0x1b, 0xc0
db 0x1e, 0x20
db 0x0f, 0xe0
mr1 endc
mr1d chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x38, 0x80
db 0x31, 0x40
db 0x30, 0x80
db 0x21, 0x00
db 0x18, 0x80
db 0x1b, 0x80
db 0x1b, 0x80
db 0x1b, 0xc0
db 0x12, 0x20
db 0x0f, 0xe0
mr1d endc
mr1ds chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x78, 0xd0
db 0xb1, 0x60
db 0x70, 0xd0
db 0xa1, 0xa0
db 0x58, 0xd0
db 0xbb, 0xa0
db 0x5b, 0xd0
db 0xbb, 0xe0
db 0x52, 0x30
db 0xaf, 0xe0
mr1ds endc
mr1r chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x38, 0x90
db 0x31, 0x50
db 0x30, 0xb0
db 0x21, 0x30
db 0x18, 0x60
db 0x1f, 0xc0
db 0x1f, 0x80
db 0x1f, 0xc0
db 0x1e, 0x20
db 0x0f, 0xe0
mr1r endc
mr1rs chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x78, 0xd0
db 0xb1, 0x70
db 0x70, 0xb0
db 0xa1, 0x30
db 0x58, 0x70
db 0xbf, 0xe0
db 0x5f, 0xd0
db 0xbf, 0xe0
db 0x5e, 0x30
db 0xaf, 0xe0
mr1rs endc
mr1s chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x78, 0xd0
db 0xb1, 0x60
db 0x70, 0xd0
db 0xa1, 0xa0
db 0x58, 0xd0
db 0xbb, 0xa0
db 0x5b, 0xd0
db 0xbb, 0xe0
db 0x5e, 0x30
db 0xaf, 0xe0
mr1s endc
mr1u chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x11, 0x80
db 0x3a, 0x80
db 0x3b, 0x40
db 0x3a, 0x80
db 0x2b, 0x00
db 0x1a, 0x80
db 0x1f, 0x80
db 0x1f, 0x80
db 0x1f, 0xc0
db 0x1e, 0x20
db 0x0f, 0xe0
mr1u endc
mr1us chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xb1, 0xa0
db 0x7a, 0xd0
db 0xbb, 0x60
db 0x7a, 0xd0
db 0xab, 0xa0
db 0x5a, 0xd0
db 0xbf, 0xa0
db 0x5f, 0xd0
db 0xbf, 0xe0
db 0x5e, 0x30
db 0xaf, 0xe0
mr1us endc
mr2 chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x38, 0x80
db 0x31, 0x40
db 0x30, 0x80
db 0x21, 0x00
db 0x18, 0x80
db 0x5b, 0x80
db 0xbb, 0xb0
db 0xbb, 0xd0
db 0x9d, 0xa0
db 0xe0, 0xc0
mr2 endc
mr2d chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x38, 0x80
db 0x31, 0x40
db 0x30, 0x80
db 0x21, 0x00
db 0x18, 0x80
db 0x5b, 0x80
db 0xbb, 0xb0
db 0xbb, 0xd0
db 0x91, 0xa0
db 0xe0, 0xc0
mr2d endc
mr2ds chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x78, 0xd0
db 0xb1, 0x60
db 0x70, 0xd0
db 0xa1, 0xa0
db 0x58, 0xd0
db 0xfb, 0xa0
db 0xbb, 0xf0
db 0xbb, 0xd0
db 0x91, 0xb0
db 0xe0, 0xe0
mr2ds endc
mr2r chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x1f, 0x80
db 0x38, 0x90
db 0x31, 0x50
db 0x30, 0xb0
db 0x21, 0x30
db 0x18, 0x60
db 0x5f, 0xc0
db 0xbf, 0xb0
db 0xbf, 0xd0
db 0x9d, 0xa0
db 0xe0, 0xc0
mr2r endc
mr2rs chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x78, 0xd0
db 0xb1, 0x70
db 0x70, 0xb0
db 0xa1, 0x30
db 0x58, 0x60
db 0xdf, 0xc0
db 0xbf, 0xb0
db 0xbf, 0xd0
db 0x9d, 0xb0
db 0xe0, 0xe0
mr2rs endc
mr2s chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xbf, 0xa0
db 0x78, 0xd0
db 0xb1, 0x60
db 0x70, 0xd0
db 0xa1, 0xa0
db 0x58, 0xd0
db 0xdb, 0xa0
db 0xbb, 0xf0
db 0xbb, 0xd0
db 0x9d, 0xb0
db 0xe0, 0xe0
mr2s endc
mr2u chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x0f, 0x00
db 0x11, 0x80
db 0x3a, 0x80
db 0x3b, 0x40
db 0x3a, 0x80
db 0x2b, 0x00
db 0x1a, 0x80
db 0x5f, 0x80
db 0xbf, 0xb0
db 0xbf, 0xd0
db 0x9d, 0xa0
db 0xe0, 0xc0
mr2u endc
mr2us chunk Bitmap
Bitmap <12,12,0,BMF_MONO>
db 0x5f, 0x50
db 0xb1, 0xa0
db 0x7a, 0xd0
db 0xbb, 0x60
db 0x7a, 0xd0
db 0xab, 0xa0
db 0x5a, 0xd0
db 0xff, 0xa0
db 0xbf, 0xf0
db 0xbf, 0xd0
db 0x9d, 0xb0
db 0xe0, 0xe0
mr2us endc
;-----------------------------------------------------------------------------
; Monochrome & VGA wall bitmaps
;-----------------------------------------------------------------------------
wallBitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x7f, 0xe0, 0xbf, 0xc0, 0xc0, 0x10, 0xdf, 0xa0
db 0xdf, 0x90, 0xdf, 0xa0, 0xdf, 0x90, 0xdf, 0xa0
db 0xdf, 0x90, 0xc0, 0x20, 0x95, 0x50, 0x2a, 0xa0
wallBitmap endc
wall_E_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x7f, 0xf0, 0xbf, 0xf0, 0xc0, 0x00, 0xdf, 0xf0
db 0xdf, 0xf0, 0xdf, 0xf0, 0xdf, 0xf0, 0xdf, 0xf0
db 0xdf, 0xf0, 0xc0, 0x00, 0x95, 0x50, 0x2a, 0xa0
wall_E_Bitmap endc
wall_EW_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0xff, 0xf0, 0xff, 0xf0, 0x00, 0x00, 0xff, 0xf0
db 0xff, 0xf0, 0xff, 0xf0, 0xff, 0xf0, 0xff, 0xf0
db 0xff, 0xf0, 0x00, 0x00, 0x55, 0x50, 0xaa, 0xa0
wall_EW_Bitmap endc
wall_N_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0xdf, 0x90, 0xdf, 0xa0, 0xdf, 0x90, 0xdf, 0xa0
db 0xdf, 0x90, 0xdf, 0xa0, 0xdf, 0x90, 0xdf, 0xa0
db 0xdf, 0x90, 0xc0, 0x20, 0x95, 0x50, 0x2a, 0xa0
wall_N_Bitmap endc
wall_NE_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0xdf, 0x80, 0xdf, 0x90, 0xdf, 0x80, 0xdf, 0xf0
db 0xdf, 0xf0, 0xdf, 0xf0, 0xdf, 0xf0, 0xdf, 0xf0
db 0xdf, 0xf0, 0xc0, 0x00, 0x95, 0x50, 0x2a, 0xa0
wall_NE_Bitmap endc
wall_NEW_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x5f, 0x80, 0x9f, 0x90, 0x1f, 0x80, 0xff, 0xf0
db 0xff, 0xf0, 0xff, 0xf0, 0xff, 0xf0, 0xff, 0xf0
db 0xff, 0xf0, 0x00, 0x00, 0x55, 0x50, 0xaa, 0xa0
wall_NEW_Bitmap endc
wall_NS_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0xdf, 0x90, 0xdf, 0xa0, 0xdf, 0x90, 0xdf, 0xa0
db 0xdf, 0x90, 0xdf, 0xa0, 0xdf, 0x90, 0xdf, 0xa0
db 0xdf, 0x90, 0xdf, 0xa0, 0xdf, 0x90, 0xdf, 0xa0
wall_NS_Bitmap endc
wall_NSE_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0xdf, 0x80, 0xdf, 0x90, 0xdf, 0x80, 0xdf, 0xf0
db 0xdf, 0xf0, 0xdf, 0xf0, 0xdf, 0xf0, 0xdf, 0xf0
db 0xdf, 0xf0, 0xdf, 0x80, 0xdf, 0x90, 0xdf, 0xa0
wall_NSE_Bitmap endc
wall_NSW_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x5f, 0x90, 0x9f, 0xa0, 0x1f, 0x90, 0xff, 0xa0
db 0xff, 0x90, 0xff, 0xa0, 0xff, 0x90, 0xff, 0xa0
db 0xff, 0x90, 0x1f, 0xa0, 0x1f, 0x90, 0x5f, 0xa0
wall_NSW_Bitmap endc
wall_NW_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x5f, 0x90, 0x9f, 0xa0, 0x1f, 0x90, 0xff, 0xa0
db 0xff, 0x90, 0xff, 0xa0, 0xff, 0x90, 0xff, 0xa0
db 0xff, 0x90, 0x00, 0x20, 0x55, 0x50, 0xaa, 0xa0
wall_NW_Bitmap endc
wall_S_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x7f, 0xe0, 0xbf, 0xc0, 0xc0, 0x10, 0xdf, 0xa0
db 0xdf, 0x90, 0xdf, 0xa0, 0xdf, 0x90, 0xdf, 0xa0
db 0xdf, 0x90, 0xdf, 0xa0, 0xdf, 0x90, 0xdf, 0xa0
wall_S_Bitmap endc
wall_SE_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x7f, 0xf0, 0xbf, 0xf0, 0xc0, 0x00, 0xdf, 0xf0
db 0xdf, 0xf0, 0xdf, 0xf0, 0xdf, 0xf0, 0xdf, 0xf0
db 0xdf, 0xf0, 0xdf, 0x80, 0xdf, 0x90, 0xdf, 0xa0
wall_SE_Bitmap endc
wall_SEW_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0xff, 0xf0, 0xff, 0xf0, 0x00, 0x00, 0xff, 0xf0
db 0xff, 0xf0, 0xff, 0xf0, 0xff, 0xf0, 0xff, 0xf0
db 0xff, 0xf0, 0x1f, 0x80, 0x1f, 0x90, 0x5f, 0xa0
wall_SEW_Bitmap endc
wall_SW_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0xff, 0xe0, 0xff, 0xc0, 0x00, 0x10, 0xff, 0xa0
db 0xff, 0x90, 0xff, 0xa0, 0xff, 0x90, 0xff, 0xa0
db 0xff, 0x90, 0x1f, 0xa0, 0x1f, 0x90, 0x5f, 0xa0
wall_SW_Bitmap endc
wall_W_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0xff, 0xe0, 0xff, 0xc0, 0x00, 0x10, 0xff, 0xa0
db 0xff, 0x90, 0xff, 0xa0, 0xff, 0x90, 0xff, 0xa0
db 0xff, 0x90, 0x00, 0x20, 0x55, 0x50, 0xaa, 0xa0
wall_W_Bitmap endc
wall_NSEW_Bitmap chunk Bitmap
Bitmap <12,12,BMC_UNCOMPACTED,BMF_MONO>
db 0x5f, 0x80, 0x9f, 0x90, 0x1f, 0x80, 0xff, 0xf0
db 0xff, 0xf0, 0xff, 0xf0, 0xff, 0xf0, 0xff, 0xf0
db 0xff, 0xf0, 0x1f, 0x80, 0x1f, 0x90, 0x5f, 0xa0
wall_NSEW_Bitmap endc
;-----------------------------------------------------------------------------
; CGA bitmaps - emptied for Jedi
;-----------------------------------------------------------------------------
cgaSafeBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_MONO>
db 0x00
cgaSafeBitmap endc
cgaGrassBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_MONO>
db 0x00
cgaGrassBitmap endc
cgaPacketBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_MONO>
db 0x00
cgaPacketBitmap endc
cgaSafePacketBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_MONO>
db 0x00
cgaSafePacketBitmap endc
cgaWallBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_MONO>
db 0x00
cgaWallBitmap endc
cgaPlayerBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_MONO>
db 0x00
cgaPlayerBitmap endc
cgaSafePlayerBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_MONO>
db 0x00
cgaSafePlayerBitmap endc
vgaGroundBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vgaGroundBitmap endc
vgaSafeBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vgaSafeBitmap endc
;
; This one needs a mask to let the background color show through.
;
vgaGrassBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED, mask BM_MASK or BMF_MONO>
db 0x00
vgaGrassBitmap endc
vgaPacketBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vgaPacketBitmap endc
vgaSafePacketBitmap chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vgaSafePacketBitmap endc
;-----------------------------------------------------------------------------
; Player Bitmaps -- all 32 of the suckers.
;
; -but stripped out for Jedi.
;-----------------------------------------------------------------------------
vl1 chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl1 endc
vl1d chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl1d endc
vl1ds chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl1ds endc
vl1l chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl1l endc
vl1ls chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl1ls endc
vl1s chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl1s endc
vl1u chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl1u endc
vl1us chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl1us endc
vl2 chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl2 endc
vl2d chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl2d endc
vl2ds chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl2ds endc
vl2l chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl2l endc
vl2ls chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl2ls endc
vl2s chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl2s endc
vl2u chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl2u endc
vl2us chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vl2us endc
vr1 chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr1 endc
vr1d chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr1d endc
vr1ds chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr1ds endc
vr1r chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr1r endc
vr1rs chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr1rs endc
vr1s chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr1s endc
vr1u chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr1u endc
vr1us chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr1us endc
vr2 chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr2 endc
vr2d chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr2d endc
vr2ds chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr2ds endc
vr2r chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr2r endc
vr2rs chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr2rs endc
vr2s chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr2s endc
vr2u chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr2u endc
vr2us chunk Bitmap
Bitmap <1,1,BMC_UNCOMPACTED,BMF_4BIT>
db 0x00
vr2us endc
Bitmaps ends
endif
|
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
.section .note.GNU-stack,"",%progbits
.text
.p2align 5, 0x90
.globl cpInc_BNU
.type cpInc_BNU, @function
cpInc_BNU:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
movl (8)(%ebp), %edi
movl (12)(%ebp), %esi
movl (20)(%ebp), %eax
movd (20)(%ebp), %mm0
movl (16)(%ebp), %edx
shl $(2), %edx
xor %ecx, %ecx
.p2align 5, 0x90
.Lmain_loopgas_1:
movd (%esi,%ecx), %mm1
paddq %mm0, %mm1
movd %mm1, (%edi,%ecx)
pshufw $(254), %mm1, %mm0
movd %mm0, %eax
add $(4), %ecx
cmp %edx, %ecx
jl .Lmain_loopgas_1
.Lexit_loopgas_1:
emms
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.Lfe1:
.size cpInc_BNU, .Lfe1-(cpInc_BNU)
|
; A000529: Powers of rooted tree enumerator.
; 20,74,186,388,721,1236,1995,3072,4554,6542,9152,12516,16783,22120,28713,36768,46512,58194,72086,88484,107709,130108,156055,185952,220230,259350,303804,354116,410843,474576,545941,625600,714252,812634,921522,1041732,1174121,1319588,1479075,1653568,1844098,2051742,2277624,2522916,2788839,3076664,3387713,3723360,4085032,4474210
mov $13,$0
mov $15,$0
add $15,1
lpb $15
clr $0,13
mov $0,$13
sub $15,1
sub $0,$15
mov $10,$0
mov $12,$0
add $12,1
lpb $12
clr $0,10
mov $0,$10
sub $12,1
sub $0,$12
mov $7,$0
mov $9,$0
add $9,1
lpb $9
mov $0,$7
sub $9,1
sub $0,$9
mov $1,$0
trn $1,1
mov $2,2
mov $4,1
trn $4,$0
mov $0,$1
mul $4,2
lpb $0
sub $0,1
add $1,5
add $1,$0
add $1,1
add $5,$2
div $4,$5
add $4,1
lpe
mul $4,3
add $4,1
add $4,$1
add $4,2
mov $1,$4
add $1,11
add $8,$1
lpe
add $11,$8
lpe
add $14,$11
lpe
mov $1,$14
|
; A176010: Positive numbers k such that k^2 == 2 (mod 97).
; 14,83,111,180,208,277,305,374,402,471,499,568,596,665,693,762,790,859,887,956,984,1053,1081,1150,1178,1247,1275,1344,1372,1441,1469,1538,1566,1635,1663,1732,1760,1829,1857,1926,1954,2023,2051,2120,2148,2217,2245,2314,2342,2411,2439,2508,2536,2605,2633,2702,2730,2799,2827,2896,2924,2993,3021,3090,3118,3187,3215,3284,3312,3381,3409,3478,3506,3575,3603,3672,3700,3769,3797,3866,3894,3963,3991,4060,4088,4157,4185,4254,4282,4351,4379,4448,4476,4545,4573,4642,4670,4739,4767,4836,4864,4933,4961,5030,5058,5127,5155,5224,5252,5321,5349,5418,5446,5515,5543,5612,5640,5709,5737,5806,5834,5903,5931,6000,6028,6097,6125,6194,6222,6291,6319,6388,6416,6485,6513,6582,6610,6679,6707,6776,6804,6873,6901,6970,6998,7067,7095,7164,7192,7261,7289,7358,7386,7455,7483,7552,7580,7649,7677,7746,7774,7843,7871,7940,7968,8037,8065,8134,8162,8231,8259,8328,8356,8425,8453,8522,8550,8619,8647,8716,8744,8813,8841,8910,8938,9007,9035,9104,9132,9201,9229,9298,9326,9395,9423,9492,9520,9589,9617,9686,9714,9783,9811,9880,9908,9977,10005,10074,10102,10171,10199,10268,10296,10365,10393,10462,10490,10559,10587,10656,10684,10753,10781,10850,10878,10947,10975,11044,11072,11141,11169,11238,11266,11335,11363,11432,11460,11529,11557,11626,11654,11723,11751,11820,11848,11917,11945,12014,12042,12111
mov $3,2
mov $7,$0
add $0,6
lpb $0
add $0,2
trn $2,$5
add $2,3
add $3,4
add $0,$3
add $0,1
add $4,$2
mov $5,6
add $5,$3
add $3,10
add $5,$3
sub $3,5
trn $0,$3
add $6,1
mov $1,$6
add $1,$3
add $5,3
mov $6,$3
add $3,1
add $6,$4
sub $4,2
add $6,1
lpe
add $1,$5
lpb $7
add $1,28
sub $7,1
lpe
sub $1,115
|
; A134058: Triangle read by rows, T(n,k) = 2*binomial(n,k) if k > 0, (0 <= k <= n), left column = (1,2,2,2,...).
; 1,2,2,2,4,2,2,6,6,2,2,8,12,8,2,2,10,20,20,10,2,2,12,30,40,30,12,2,2,14,42,70,70,42,14,2,2,16,56,112,140,112,56,16,2,2,18,72,168,252,252,168,72,18,2
lpb $0,1
cal $0,109128 ; Triangle read by rows: T(n,k) = T(n-1,k-1) + T(n-1,k) + 1 for 0<k<n, T(n,0) = T(n,n) = 1.
mov $1,$0
lpb $0,1
sub $0,1
lpe
lpe
add $1,1
|
; A281831: Number of nX2 0..1 arrays with no element equal to more than four of its king-move neighbors and with new values introduced in order 0 sequentially upwards.
; Submitted by Christian Krause
; 2,8,31,121,472,1841,7181,28010,109255,426157,1662256,6483749,25290329,98646746,384778723,1500857065,5854200856,22834731209,89068510325,347418126314,1355129372335,5285779516597,20617562919424,80420286052733,313685105949665,1223551301846042,4772549795492587,18615673503915217,72611772501915496,283227437608477313,1104748977339008861,4309152789846289514,16808160176772849751,65561436854535435517,255727096673617434832,997481920938004310549,3890749926543936107177,15176149735793056122842
add $0,1
mov $1,1
mov $2,6
lpb $0
sub $0,1
mul $1,2
add $3,$2
mov $2,$1
add $1,$4
mov $4,$3
add $3,$1
sub $4,4
add $1,$4
lpe
mov $0,$1
div $0,2
|
; Program 01 - Addition of two byte-numbers
; Written by Hamidreza Hosseinkhani (hosseinkhani@live.com)
; June, 2011
TITLE Addition of two byte-numbers
StkSeg SEGMENT para stack 'stack'
DB 64 DUP (?)
StkSeg ENDS
DtaSeg SEGMENT para private 'data'
Num1 DB 0FEh
Num2 DB 0EDh
ORG 000Ah
Sum DW ?
DtaSeg ENDS
CodSeg SEGMENT para private 'code'
Main PROC near
ASSUME cs:CodSeg, ds:DtaSeg, ss:StkSeg
mov ax, DtaSeg
mov ds, ax
mov ah, 00h
mov al, Num1
mov bh, 00h
mov bl, Num2
add ax, bx
mov Sum, ax
mov ax, 4C00h
int 21h
Main ENDP
CodSeg ENDS
END Main |
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include <algorithm>
#include "xfa/src/foxitlib.h"
#include "xfa/src/fxfa/src/common/xfa_common.h"
#include "xfa_ffapp.h"
#include "xfa_ffdoc.h"
#include "xfa_ffdocview.h"
#include "xfa_ffwidget.h"
#include "xfa_ffpageview.h"
#include "xfa_textlayout.h"
CXFA_FFWidget::CXFA_FFWidget(CXFA_FFPageView* pPageView,
CXFA_WidgetAcc* pDataAcc)
: CXFA_ContentLayoutItem(pDataAcc->GetNode()),
m_pPageView(pPageView),
m_pDataAcc(pDataAcc) {
m_rtWidget.Set(0, 0, 0, 0);
}
CXFA_FFWidget::~CXFA_FFWidget() {}
IXFA_PageView* CXFA_FFWidget::GetPageView() {
return m_pPageView;
}
void CXFA_FFWidget::SetPageView(IXFA_PageView* pPageView) {
m_pPageView = static_cast<CXFA_FFPageView*>(pPageView);
}
void CXFA_FFWidget::GetWidgetRect(CFX_RectF& rtWidget) {
if ((m_dwStatus & XFA_WIDGETSTATUS_RectCached) == 0) {
m_dwStatus |= XFA_WIDGETSTATUS_RectCached;
GetRect(m_rtWidget);
}
rtWidget = m_rtWidget;
}
CFX_RectF CXFA_FFWidget::ReCacheWidgetRect() {
m_dwStatus |= XFA_WIDGETSTATUS_RectCached;
GetRect(m_rtWidget);
return m_rtWidget;
}
void CXFA_FFWidget::GetRectWithoutRotate(CFX_RectF& rtWidget) {
GetWidgetRect(rtWidget);
FX_FLOAT fValue = 0;
switch (m_pDataAcc->GetRotate()) {
case 90:
rtWidget.top = rtWidget.bottom();
fValue = rtWidget.width;
rtWidget.width = rtWidget.height;
rtWidget.height = fValue;
break;
case 180:
rtWidget.left = rtWidget.right();
rtWidget.top = rtWidget.bottom();
break;
case 270:
rtWidget.left = rtWidget.right();
fValue = rtWidget.width;
rtWidget.width = rtWidget.height;
rtWidget.height = fValue;
break;
}
}
FX_DWORD CXFA_FFWidget::GetStatus() {
return m_dwStatus;
}
void CXFA_FFWidget::ModifyStatus(FX_DWORD dwAdded, FX_DWORD dwRemoved) {
m_dwStatus = (m_dwStatus & ~dwRemoved) | dwAdded;
}
FX_BOOL CXFA_FFWidget::GetBBox(CFX_RectF& rtBox,
FX_DWORD dwStatus,
FX_BOOL bDrawFocus) {
if (bDrawFocus) {
return FALSE;
}
#ifndef _XFA_EMB
if (m_pPageView) {
m_pPageView->GetPageViewRect(rtBox);
}
return TRUE;
#endif
GetWidgetRect(rtBox);
return TRUE;
}
CXFA_WidgetAcc* CXFA_FFWidget::GetDataAcc() {
return m_pDataAcc;
}
FX_BOOL CXFA_FFWidget::GetToolTip(CFX_WideString& wsToolTip) {
if (CXFA_Assist assist = m_pDataAcc->GetAssist()) {
if (CXFA_ToolTip toolTip = assist.GetToolTip()) {
return toolTip.GetTip(wsToolTip);
}
}
return GetCaptionText(wsToolTip);
}
void CXFA_FFWidget::RenderWidget(CFX_Graphics* pGS,
CFX_Matrix* pMatrix,
FX_DWORD dwStatus,
int32_t iRotate) {
if (!IsMatchVisibleStatus(dwStatus)) {
return;
}
CXFA_Border border = m_pDataAcc->GetBorder();
if (border) {
CFX_RectF rtBorder;
GetRectWithoutRotate(rtBorder);
CXFA_Margin margin = border.GetMargin();
if (margin.IsExistInXML()) {
XFA_RectWidthoutMargin(rtBorder, margin);
}
rtBorder.Normalize();
DrawBorder(pGS, border, rtBorder, pMatrix);
}
}
FX_BOOL CXFA_FFWidget::IsLoaded() {
return m_pPageView != NULL;
}
FX_BOOL CXFA_FFWidget::LoadWidget() {
PerformLayout();
return TRUE;
}
void CXFA_FFWidget::UnloadWidget() {}
FX_BOOL CXFA_FFWidget::PerformLayout() {
ReCacheWidgetRect();
return TRUE;
}
FX_BOOL CXFA_FFWidget::UpdateFWLData() {
return FALSE;
}
void CXFA_FFWidget::UpdateWidgetProperty() {}
void CXFA_FFWidget::DrawBorder(CFX_Graphics* pGS,
CXFA_Box box,
const CFX_RectF& rtBorder,
CFX_Matrix* pMatrix,
FX_DWORD dwFlags) {
XFA_DrawBox(box, pGS, rtBorder, pMatrix, dwFlags);
}
void CXFA_FFWidget::InvalidateWidget(const CFX_RectF* pRect) {
if (!pRect) {
CFX_RectF rtWidget;
GetBBox(rtWidget, XFA_WIDGETSTATUS_Focused);
rtWidget.Inflate(2, 2);
GetDoc()->GetDocProvider()->InvalidateRect(m_pPageView, rtWidget,
XFA_INVALIDATE_CurrentPage);
} else {
GetDoc()->GetDocProvider()->InvalidateRect(m_pPageView, *pRect,
XFA_INVALIDATE_CurrentPage);
}
}
void CXFA_FFWidget::AddInvalidateRect(const CFX_RectF* pRect) {
CFX_RectF rtWidget;
if (pRect) {
rtWidget = *pRect;
} else {
GetBBox(rtWidget, XFA_WIDGETSTATUS_Focused);
rtWidget.Inflate(2, 2);
}
m_pDocView->AddInvalidateRect(m_pPageView, rtWidget);
}
FX_BOOL CXFA_FFWidget::GetCaptionText(CFX_WideString& wsCap) {
CXFA_TextLayout* pCapTextlayout = m_pDataAcc->GetCaptionTextLayout();
if (!pCapTextlayout) {
return FALSE;
}
pCapTextlayout->GetText(wsCap);
return TRUE;
}
FX_BOOL CXFA_FFWidget::IsFocused() {
return m_dwStatus & XFA_WIDGETSTATUS_Focused;
}
FX_BOOL CXFA_FFWidget::OnMouseEnter() {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnMouseExit() {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnLButtonDown(FX_DWORD dwFlags,
FX_FLOAT fx,
FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnLButtonUp(FX_DWORD dwFlags, FX_FLOAT fx, FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnLButtonDblClk(FX_DWORD dwFlags,
FX_FLOAT fx,
FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnMouseMove(FX_DWORD dwFlags, FX_FLOAT fx, FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnMouseWheel(FX_DWORD dwFlags,
int16_t zDelta,
FX_FLOAT fx,
FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnRButtonDown(FX_DWORD dwFlags,
FX_FLOAT fx,
FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnRButtonUp(FX_DWORD dwFlags, FX_FLOAT fx, FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnRButtonDblClk(FX_DWORD dwFlags,
FX_FLOAT fx,
FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnSetFocus(CXFA_FFWidget* pOldWidget) {
CXFA_FFWidget* pParent = GetParent();
if (pParent != NULL && !pParent->IsAncestorOf(pOldWidget)) {
pParent->OnSetFocus(pOldWidget);
}
m_dwStatus |= XFA_WIDGETSTATUS_Focused;
CXFA_EventParam eParam;
eParam.m_eType = XFA_EVENT_Enter;
eParam.m_pTarget = m_pDataAcc;
m_pDataAcc->ProcessEvent(XFA_ATTRIBUTEENUM_Enter, &eParam);
return TRUE;
}
FX_BOOL CXFA_FFWidget::OnKillFocus(CXFA_FFWidget* pNewWidget) {
m_dwStatus &= ~XFA_WIDGETSTATUS_Focused;
EventKillFocus();
if (pNewWidget != NULL) {
CXFA_FFWidget* pParent = GetParent();
if (pParent != NULL && !pParent->IsAncestorOf(pNewWidget)) {
pParent->OnKillFocus(pNewWidget);
}
}
return TRUE;
}
FX_BOOL CXFA_FFWidget::OnKeyDown(FX_DWORD dwKeyCode, FX_DWORD dwFlags) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnKeyUp(FX_DWORD dwKeyCode, FX_DWORD dwFlags) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnChar(FX_DWORD dwChar, FX_DWORD dwFlags) {
return FALSE;
}
FX_DWORD CXFA_FFWidget::OnHitTest(FX_FLOAT fx, FX_FLOAT fy) {
return FALSE;
}
FX_BOOL CXFA_FFWidget::OnSetCursor(FX_FLOAT fx, FX_FLOAT fy) {
return FALSE;
}
void CXFA_FFWidget::Rotate2Normal(FX_FLOAT& fx, FX_FLOAT& fy) {
CFX_Matrix mt;
GetRotateMatrix(mt);
if (mt.IsIdentity()) {
return;
}
CFX_Matrix mtReverse;
mtReverse.SetReverse(mt);
mtReverse.TransformPoint(fx, fy);
}
static void XFA_GetMatrix(CFX_Matrix& m,
int32_t iRotate,
int32_t at,
const CFX_RectF& rt) {
if (!iRotate) {
return;
}
FX_FLOAT fAnchorX, fAnchorY;
switch (at) {
case XFA_ATTRIBUTEENUM_TopLeft:
fAnchorX = rt.left, fAnchorY = rt.top;
break;
case XFA_ATTRIBUTEENUM_TopCenter:
fAnchorX = (rt.left + rt.right()) / 2, fAnchorY = rt.top;
break;
case XFA_ATTRIBUTEENUM_TopRight:
fAnchorX = rt.right(), fAnchorY = rt.top;
break;
case XFA_ATTRIBUTEENUM_MiddleLeft:
fAnchorX = rt.left, fAnchorY = (rt.top + rt.bottom()) / 2;
break;
case XFA_ATTRIBUTEENUM_MiddleCenter:
fAnchorX = (rt.left + rt.right()) / 2,
fAnchorY = (rt.top + rt.bottom()) / 2;
break;
case XFA_ATTRIBUTEENUM_MiddleRight:
fAnchorX = rt.right(), fAnchorY = (rt.top + rt.bottom()) / 2;
break;
case XFA_ATTRIBUTEENUM_BottomLeft:
fAnchorX = rt.left, fAnchorY = rt.bottom();
break;
case XFA_ATTRIBUTEENUM_BottomCenter:
fAnchorX = (rt.left + rt.right()) / 2, fAnchorY = rt.bottom();
break;
case XFA_ATTRIBUTEENUM_BottomRight:
fAnchorX = rt.right(), fAnchorY = rt.bottom();
break;
}
switch (iRotate) {
case 90:
m.a = 0, m.b = -1, m.c = 1, m.d = 0, m.e = fAnchorX - fAnchorY,
m.f = fAnchorX + fAnchorY;
break;
case 180:
m.a = -1, m.b = 0, m.c = 0, m.d = -1, m.e = fAnchorX * 2,
m.f = fAnchorY * 2;
break;
case 270:
m.a = 0, m.b = 1, m.c = -1, m.d = 0, m.e = fAnchorX + fAnchorY,
m.f = fAnchorY - fAnchorX;
break;
}
}
void CXFA_FFWidget::GetRotateMatrix(CFX_Matrix& mt) {
mt.Set(1, 0, 0, 1, 0, 0);
int32_t iRotate = m_pDataAcc->GetRotate();
if (!iRotate) {
return;
}
CFX_RectF rcWidget;
GetRectWithoutRotate(rcWidget);
XFA_ATTRIBUTEENUM at = XFA_ATTRIBUTEENUM_TopLeft;
XFA_GetMatrix(mt, iRotate, at, rcWidget);
}
FX_BOOL CXFA_FFWidget::IsLayoutRectEmpty() {
CFX_RectF rtLayout;
GetRectWithoutRotate(rtLayout);
return rtLayout.width < 0.1f && rtLayout.height < 0.1f;
}
CXFA_FFWidget* CXFA_FFWidget::GetParent() {
CXFA_Node* pParentNode =
m_pDataAcc->GetNode()->GetNodeItem(XFA_NODEITEM_Parent);
if (pParentNode != NULL) {
CXFA_WidgetAcc* pParentWidgetAcc =
(CXFA_WidgetAcc*)pParentNode->GetWidgetData();
if (pParentWidgetAcc != NULL) {
return pParentWidgetAcc->GetNextWidget(NULL);
}
}
return NULL;
}
FX_BOOL CXFA_FFWidget::IsAncestorOf(CXFA_FFWidget* pWidget) {
if (!pWidget) {
return FALSE;
}
CXFA_Node* pNode = m_pDataAcc->GetNode();
CXFA_Node* pChildNode = pWidget->GetDataAcc()->GetNode();
while (pChildNode) {
if (pChildNode == pNode) {
return TRUE;
}
pChildNode = pChildNode->GetNodeItem(XFA_NODEITEM_Parent);
}
return FALSE;
}
FX_BOOL CXFA_FFWidget::PtInActiveRect(FX_FLOAT fx, FX_FLOAT fy) {
CFX_RectF rtWidget;
GetWidgetRect(rtWidget);
if (rtWidget.Contains(fx, fy)) {
return TRUE;
}
return FALSE;
}
CXFA_FFDocView* CXFA_FFWidget::GetDocView() {
return m_pDocView;
}
CXFA_FFDoc* CXFA_FFWidget::GetDoc() {
return (CXFA_FFDoc*)m_pDocView->GetDoc();
}
CXFA_FFApp* CXFA_FFWidget::GetApp() {
return GetDoc()->GetApp();
}
IXFA_AppProvider* CXFA_FFWidget::GetAppProvider() {
return GetApp()->GetAppProvider();
}
void CXFA_FFWidget::GetMinMaxWidth(FX_FLOAT fMinWidth, FX_FLOAT fMaxWidth) {
fMinWidth = fMaxWidth = 0;
FX_FLOAT fWidth = 0;
if (m_pDataAcc->GetWidth(fWidth)) {
fMinWidth = fMaxWidth = fWidth;
} else {
m_pDataAcc->GetMinWidth(fMinWidth);
m_pDataAcc->GetMaxWidth(fMaxWidth);
}
}
void CXFA_FFWidget::GetMinMaxHeight(FX_FLOAT fMinHeight, FX_FLOAT fMaxHeight) {
fMinHeight = fMaxHeight = 0;
FX_FLOAT fHeight = 0;
if (m_pDataAcc->GetHeight(fHeight)) {
fMinHeight = fMaxHeight = fHeight;
} else {
m_pDataAcc->GetMinHeight(fMinHeight);
m_pDataAcc->GetMaxHeight(fMaxHeight);
}
}
FX_BOOL CXFA_FFWidget::IsMatchVisibleStatus(FX_DWORD dwStatus) {
return m_dwStatus & XFA_WIDGETSTATUS_Visible;
}
void CXFA_FFWidget::EventKillFocus() {
if (m_dwStatus & XFA_WIDGETSTATUS_Access) {
m_dwStatus &= ~XFA_WIDGETSTATUS_Access;
return;
}
CXFA_EventParam eParam;
eParam.m_eType = XFA_EVENT_Exit;
eParam.m_pTarget = m_pDataAcc;
m_pDataAcc->ProcessEvent(XFA_ATTRIBUTEENUM_Exit, &eParam);
}
FX_BOOL CXFA_FFWidget::IsButtonDown() {
return (m_dwStatus & XFA_WIDGETSTATUS_ButtonDown) != 0;
}
void CXFA_FFWidget::SetButtonDown(FX_BOOL bSet) {
bSet ? m_dwStatus |= XFA_WIDGETSTATUS_ButtonDown
: m_dwStatus &= ~XFA_WIDGETSTATUS_ButtonDown;
}
int32_t XFA_StrokeTypeSetLineDash(CFX_Graphics* pGraphics,
int32_t iStrokeType,
int32_t iCapType) {
switch (iStrokeType) {
case XFA_ATTRIBUTEENUM_DashDot: {
FX_FLOAT dashArray[] = {4, 1, 2, 1};
if (iCapType != XFA_ATTRIBUTEENUM_Butt) {
dashArray[1] = 2;
dashArray[3] = 2;
}
pGraphics->SetLineDash(0, dashArray, 4);
return FX_DASHSTYLE_DashDot;
}
case XFA_ATTRIBUTEENUM_DashDotDot: {
FX_FLOAT dashArray[] = {4, 1, 2, 1, 2, 1};
if (iCapType != XFA_ATTRIBUTEENUM_Butt) {
dashArray[1] = 2;
dashArray[3] = 2;
dashArray[5] = 2;
}
pGraphics->SetLineDash(0, dashArray, 6);
return FX_DASHSTYLE_DashDotDot;
}
case XFA_ATTRIBUTEENUM_Dashed: {
FX_FLOAT dashArray[] = {5, 1};
if (iCapType != XFA_ATTRIBUTEENUM_Butt) {
dashArray[1] = 2;
}
pGraphics->SetLineDash(0, dashArray, 2);
return FX_DASHSTYLE_Dash;
}
case XFA_ATTRIBUTEENUM_Dotted: {
FX_FLOAT dashArray[] = {2, 1};
if (iCapType != XFA_ATTRIBUTEENUM_Butt) {
dashArray[1] = 2;
}
pGraphics->SetLineDash(0, dashArray, 2);
return FX_DASHSTYLE_Dot;
}
default:
break;
}
pGraphics->SetLineDash(FX_DASHSTYLE_Solid);
return FX_DASHSTYLE_Solid;
}
CFX_GraphStateData::LineCap XFA_LineCapToFXGE(int32_t iLineCap) {
switch (iLineCap) {
case XFA_ATTRIBUTEENUM_Round:
return CFX_GraphStateData::LineCapRound;
case XFA_ATTRIBUTEENUM_Butt:
return CFX_GraphStateData::LineCapButt;
default:
break;
}
return CFX_GraphStateData::LineCapSquare;
}
class CXFA_ImageRenderer {
public:
CXFA_ImageRenderer();
~CXFA_ImageRenderer();
FX_BOOL Start(CFX_RenderDevice* pDevice,
CFX_DIBSource* pDIBSource,
FX_ARGB bitmap_argb,
int bitmap_alpha,
const CFX_Matrix* pImage2Device,
FX_DWORD flags,
int blendType = FXDIB_BLEND_NORMAL);
FX_BOOL Continue(IFX_Pause* pPause);
protected:
CFX_RenderDevice* m_pDevice;
int m_Status;
CFX_Matrix m_ImageMatrix;
CFX_DIBSource* m_pDIBSource;
CFX_DIBitmap* m_pCloneConvert;
int m_BitmapAlpha;
FX_ARGB m_FillArgb;
FX_DWORD m_Flags;
CFX_ImageTransformer* m_pTransformer;
void* m_DeviceHandle;
int32_t m_BlendType;
FX_BOOL m_Result;
FX_BOOL m_bPrint;
FX_BOOL StartDIBSource();
void CompositeDIBitmap(CFX_DIBitmap* pDIBitmap,
int left,
int top,
FX_ARGB mask_argb,
int bitmap_alpha,
int blend_mode,
int Transparency);
};
CXFA_ImageRenderer::CXFA_ImageRenderer() {
m_pDevice = NULL;
m_Status = 0;
m_pDIBSource = NULL;
m_pCloneConvert = NULL;
m_BitmapAlpha = 255;
m_FillArgb = 0;
m_Flags = 0;
m_pTransformer = NULL;
m_DeviceHandle = NULL;
m_BlendType = FXDIB_BLEND_NORMAL;
m_Result = TRUE;
m_bPrint = FALSE;
}
CXFA_ImageRenderer::~CXFA_ImageRenderer() {
if (m_pCloneConvert) {
delete m_pCloneConvert;
}
if (m_pTransformer) {
delete m_pTransformer;
}
if (m_DeviceHandle) {
m_pDevice->CancelDIBits(m_DeviceHandle);
}
}
FX_BOOL CXFA_ImageRenderer::Start(CFX_RenderDevice* pDevice,
CFX_DIBSource* pDIBSource,
FX_ARGB bitmap_argb,
int bitmap_alpha,
const CFX_Matrix* pImage2Device,
FX_DWORD flags,
int blendType) {
m_pDevice = pDevice;
m_pDIBSource = pDIBSource;
m_FillArgb = bitmap_argb;
m_BitmapAlpha = bitmap_alpha;
m_ImageMatrix = *pImage2Device;
m_Flags = flags;
m_BlendType = blendType;
return StartDIBSource();
}
FX_BOOL CXFA_ImageRenderer::StartDIBSource() {
if (m_pDevice->StartDIBits(m_pDIBSource, m_BitmapAlpha, m_FillArgb,
&m_ImageMatrix, m_Flags, m_DeviceHandle, 0, NULL,
m_BlendType)) {
if (m_DeviceHandle != NULL) {
m_Status = 3;
return TRUE;
}
return FALSE;
}
CFX_FloatRect image_rect_f = m_ImageMatrix.GetUnitRect();
FX_RECT image_rect = image_rect_f.GetOutterRect();
int dest_width = image_rect.Width();
int dest_height = image_rect.Height();
if ((FXSYS_fabs(m_ImageMatrix.b) >= 0.5f || m_ImageMatrix.a == 0) ||
(FXSYS_fabs(m_ImageMatrix.c) >= 0.5f || m_ImageMatrix.d == 0)) {
if (m_bPrint && !(m_pDevice->GetRenderCaps() & FXRC_BLEND_MODE)) {
m_Result = FALSE;
return FALSE;
}
CFX_DIBSource* pDib = m_pDIBSource;
if (m_pDIBSource->HasAlpha() &&
!(m_pDevice->GetRenderCaps() & FXRC_ALPHA_IMAGE) &&
!(m_pDevice->GetRenderCaps() & FXRC_GET_BITS)) {
m_pCloneConvert = m_pDIBSource->CloneConvert(FXDIB_Rgb);
if (!m_pCloneConvert) {
m_Result = FALSE;
return FALSE;
}
pDib = m_pCloneConvert;
}
FX_RECT clip_box = m_pDevice->GetClipBox();
clip_box.Intersect(image_rect);
m_Status = 2;
m_pTransformer = new CFX_ImageTransformer;
m_pTransformer->Start(pDib, &m_ImageMatrix, m_Flags, &clip_box);
return TRUE;
}
if (m_ImageMatrix.a < 0) {
dest_width = -dest_width;
}
if (m_ImageMatrix.d > 0) {
dest_height = -dest_height;
}
int dest_left, dest_top;
dest_left = dest_width > 0 ? image_rect.left : image_rect.right;
dest_top = dest_height > 0 ? image_rect.top : image_rect.bottom;
if (m_pDIBSource->IsOpaqueImage() && m_BitmapAlpha == 255) {
if (m_pDevice->StretchDIBits(m_pDIBSource, dest_left, dest_top, dest_width,
dest_height, m_Flags, NULL, m_BlendType)) {
return FALSE;
}
}
if (m_pDIBSource->IsAlphaMask()) {
if (m_BitmapAlpha != 255) {
m_FillArgb = FXARGB_MUL_ALPHA(m_FillArgb, m_BitmapAlpha);
}
if (m_pDevice->StretchBitMask(m_pDIBSource, dest_left, dest_top, dest_width,
dest_height, m_FillArgb, m_Flags)) {
return FALSE;
}
}
if (m_bPrint && !(m_pDevice->GetRenderCaps() & FXRC_BLEND_MODE)) {
m_Result = FALSE;
return TRUE;
}
FX_RECT clip_box = m_pDevice->GetClipBox();
FX_RECT dest_rect = clip_box;
dest_rect.Intersect(image_rect);
FX_RECT dest_clip(
dest_rect.left - image_rect.left, dest_rect.top - image_rect.top,
dest_rect.right - image_rect.left, dest_rect.bottom - image_rect.top);
CFX_DIBitmap* pStretched =
m_pDIBSource->StretchTo(dest_width, dest_height, m_Flags, &dest_clip);
if (pStretched) {
CompositeDIBitmap(pStretched, dest_rect.left, dest_rect.top, m_FillArgb,
m_BitmapAlpha, m_BlendType, FALSE);
delete pStretched;
pStretched = NULL;
}
return FALSE;
}
FX_BOOL CXFA_ImageRenderer::Continue(IFX_Pause* pPause) {
if (m_Status == 2) {
if (m_pTransformer->Continue(pPause)) {
return TRUE;
}
CFX_DIBitmap* pBitmap = m_pTransformer->m_Storer.Detach();
if (pBitmap == NULL) {
return FALSE;
}
if (pBitmap->IsAlphaMask()) {
if (m_BitmapAlpha != 255) {
m_FillArgb = FXARGB_MUL_ALPHA(m_FillArgb, m_BitmapAlpha);
}
m_Result = m_pDevice->SetBitMask(pBitmap, m_pTransformer->m_ResultLeft,
m_pTransformer->m_ResultTop, m_FillArgb);
} else {
if (m_BitmapAlpha != 255) {
pBitmap->MultiplyAlpha(m_BitmapAlpha);
}
m_Result = m_pDevice->SetDIBits(pBitmap, m_pTransformer->m_ResultLeft,
m_pTransformer->m_ResultTop, m_BlendType);
}
delete pBitmap;
return FALSE;
} else if (m_Status == 3) {
return m_pDevice->ContinueDIBits(m_DeviceHandle, pPause);
}
return FALSE;
}
void CXFA_ImageRenderer::CompositeDIBitmap(CFX_DIBitmap* pDIBitmap,
int left,
int top,
FX_ARGB mask_argb,
int bitmap_alpha,
int blend_mode,
int Transparency) {
if (pDIBitmap == NULL) {
return;
}
FX_BOOL bIsolated = Transparency & PDFTRANS_ISOLATED;
FX_BOOL bGroup = Transparency & PDFTRANS_GROUP;
if (blend_mode == FXDIB_BLEND_NORMAL) {
if (!pDIBitmap->IsAlphaMask()) {
if (bitmap_alpha < 255) {
pDIBitmap->MultiplyAlpha(bitmap_alpha);
}
if (m_pDevice->SetDIBits(pDIBitmap, left, top)) {
return;
}
} else {
FX_DWORD fill_argb = (mask_argb);
if (bitmap_alpha < 255) {
((uint8_t*)&fill_argb)[3] =
((uint8_t*)&fill_argb)[3] * bitmap_alpha / 255;
}
if (m_pDevice->SetBitMask(pDIBitmap, left, top, fill_argb)) {
return;
}
}
}
FX_BOOL bBackAlphaRequired = blend_mode && bIsolated;
FX_BOOL bGetBackGround =
((m_pDevice->GetRenderCaps() & FXRC_ALPHA_OUTPUT)) ||
(!(m_pDevice->GetRenderCaps() & FXRC_ALPHA_OUTPUT) &&
(m_pDevice->GetRenderCaps() & FXRC_GET_BITS) && !bBackAlphaRequired);
if (bGetBackGround) {
if (bIsolated || !bGroup) {
if (pDIBitmap->IsAlphaMask()) {
return;
}
m_pDevice->SetDIBits(pDIBitmap, left, top, blend_mode);
} else {
FX_RECT rect(left, top, left + pDIBitmap->GetWidth(),
top + pDIBitmap->GetHeight());
rect.Intersect(m_pDevice->GetClipBox());
CFX_DIBitmap* pClone = NULL;
FX_BOOL bClone = FALSE;
if (m_pDevice->GetBackDrop() && m_pDevice->GetBitmap()) {
bClone = TRUE;
pClone = m_pDevice->GetBackDrop()->Clone(&rect);
CFX_DIBitmap* pForeBitmap = m_pDevice->GetBitmap();
pClone->CompositeBitmap(0, 0, pClone->GetWidth(), pClone->GetHeight(),
pForeBitmap, rect.left, rect.top);
left = left >= 0 ? 0 : left;
top = top >= 0 ? 0 : top;
if (!pDIBitmap->IsAlphaMask())
pClone->CompositeBitmap(0, 0, pClone->GetWidth(), pClone->GetHeight(),
pDIBitmap, left, top, blend_mode);
else
pClone->CompositeMask(0, 0, pClone->GetWidth(), pClone->GetHeight(),
pDIBitmap, mask_argb, left, top, blend_mode);
} else {
pClone = pDIBitmap;
}
if (m_pDevice->GetBackDrop()) {
m_pDevice->SetDIBits(pClone, rect.left, rect.top);
} else {
if (pDIBitmap->IsAlphaMask()) {
return;
}
m_pDevice->SetDIBits(pDIBitmap, rect.left, rect.top, blend_mode);
}
if (bClone) {
delete pClone;
}
}
return;
}
if (pDIBitmap->HasAlpha() &&
!(m_pDevice->GetRenderCaps() & FXRC_ALPHA_IMAGE)) {
CFX_DIBitmap* pCloneConvert = pDIBitmap->CloneConvert(FXDIB_Rgb);
if (!pCloneConvert) {
return;
}
CXFA_ImageRenderer imageRender;
FX_BOOL bRet = imageRender.Start(m_pDevice, pCloneConvert, m_FillArgb,
m_BitmapAlpha, &m_ImageMatrix, m_Flags);
while (bRet) {
bRet = imageRender.Continue(NULL);
}
delete pCloneConvert;
return;
}
}
void XFA_DrawImage(CFX_Graphics* pGS,
const CFX_RectF& rtImage,
CFX_Matrix* pMatrix,
CFX_DIBitmap* pDIBitmap,
int32_t iAspect,
int32_t iImageXDpi,
int32_t iImageYDpi,
int32_t iHorzAlign,
int32_t iVertAlign) {
if (rtImage.IsEmpty()) {
return;
}
if (!pDIBitmap || !pDIBitmap->GetBuffer()) {
return;
}
FX_FLOAT fWidth =
XFA_UnitPx2Pt((FX_FLOAT)pDIBitmap->GetWidth(), (FX_FLOAT)iImageXDpi);
FX_FLOAT fHeight =
XFA_UnitPx2Pt((FX_FLOAT)pDIBitmap->GetHeight(), (FX_FLOAT)iImageYDpi);
CFX_RectF rtFit;
rtFit.Set(rtImage.left, rtImage.top, fWidth, fHeight);
switch (iAspect) {
case XFA_ATTRIBUTEENUM_Fit: {
FX_FLOAT f1 = rtImage.height / rtFit.height;
FX_FLOAT f2 = rtImage.width / rtFit.width;
f1 = std::min(f1, f2);
rtFit.height = rtFit.height * f1;
rtFit.width = rtFit.width * f1;
} break;
case XFA_ATTRIBUTEENUM_Actual:
break;
case XFA_ATTRIBUTEENUM_Height: {
FX_FLOAT f1 = rtImage.height / rtFit.height;
rtFit.height = rtImage.height;
rtFit.width = f1 * rtFit.width;
} break;
case XFA_ATTRIBUTEENUM_None:
rtFit.height = rtImage.height;
rtFit.width = rtImage.width;
break;
case XFA_ATTRIBUTEENUM_Width: {
FX_FLOAT f1 = rtImage.width / rtFit.width;
rtFit.width = rtImage.width;
rtFit.height = rtFit.height * f1;
} break;
}
if (iHorzAlign == XFA_ATTRIBUTEENUM_Center) {
rtFit.left += (rtImage.width - rtFit.width) / 2;
} else if (iHorzAlign == XFA_ATTRIBUTEENUM_Right) {
rtFit.left = rtImage.right() - rtFit.width;
}
if (iVertAlign == XFA_ATTRIBUTEENUM_Middle) {
rtFit.top += (rtImage.height - rtFit.height) / 2;
} else if (iVertAlign == XFA_ATTRIBUTEENUM_Bottom) {
rtFit.top = rtImage.bottom() - rtImage.height;
}
CFX_RenderDevice* pRenderDevice = pGS->GetRenderDevice();
pRenderDevice->SaveState();
CFX_PathData path;
path.AppendRect(rtImage.left, rtImage.bottom(), rtImage.right(), rtImage.top);
pRenderDevice->SetClip_PathFill(&path, pMatrix, FXFILL_WINDING);
CFX_Matrix mtImage(1, 0, 0, -1, 0, 1);
mtImage.Concat(rtFit.width, 0, 0, rtFit.height, rtFit.left, rtFit.top);
mtImage.Concat(*pMatrix);
CXFA_ImageRenderer imageRender;
FX_BOOL bRet = imageRender.Start(pRenderDevice, pDIBitmap, 0, 255, &mtImage,
FXDIB_INTERPOL);
while (bRet) {
bRet = imageRender.Continue(NULL);
}
pRenderDevice->RestoreState();
}
const static uint8_t g_inv_base64[128] = {
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255,
255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255,
255, 255, 255, 255, 255, 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, 255, 255, 255, 255, 255, 255, 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, 255, 255, 255, 255, 255,
};
static uint8_t* XFA_RemoveBase64Whitespace(const uint8_t* pStr, int32_t iLen) {
uint8_t* pCP;
int32_t i = 0, j = 0;
if (iLen == 0) {
iLen = FXSYS_strlen((FX_CHAR*)pStr);
}
pCP = FX_Alloc(uint8_t, iLen + 1);
for (; i < iLen; i++) {
if ((pStr[i] & 128) == 0) {
if (g_inv_base64[pStr[i]] != 0xFF || pStr[i] == '=') {
pCP[j++] = pStr[i];
}
}
}
pCP[j] = '\0';
return pCP;
}
static int32_t XFA_Base64Decode(const FX_CHAR* pStr, uint8_t* pOutBuffer) {
if (pStr == NULL) {
return 0;
}
uint8_t* pBuffer =
XFA_RemoveBase64Whitespace((uint8_t*)pStr, FXSYS_strlen((FX_CHAR*)pStr));
if (pBuffer == NULL) {
return 0;
}
int32_t iLen = FXSYS_strlen((FX_CHAR*)pBuffer);
int32_t i = 0, j = 0;
FX_DWORD dwLimb = 0;
for (; i + 3 < iLen; i += 4) {
if (pBuffer[i] == '=' || pBuffer[i + 1] == '=' || pBuffer[i + 2] == '=' ||
pBuffer[i + 3] == '=') {
if (pBuffer[i] == '=' || pBuffer[i + 1] == '=') {
break;
}
if (pBuffer[i + 2] == '=') {
dwLimb = ((FX_DWORD)g_inv_base64[pBuffer[i]] << 6) |
((FX_DWORD)g_inv_base64[pBuffer[i + 1]]);
pOutBuffer[j] = (uint8_t)(dwLimb >> 4) & 0xFF;
j++;
} else {
dwLimb = ((FX_DWORD)g_inv_base64[pBuffer[i]] << 12) |
((FX_DWORD)g_inv_base64[pBuffer[i + 1]] << 6) |
((FX_DWORD)g_inv_base64[pBuffer[i + 2]]);
pOutBuffer[j] = (uint8_t)(dwLimb >> 10) & 0xFF;
pOutBuffer[j + 1] = (uint8_t)(dwLimb >> 2) & 0xFF;
j += 2;
}
} else {
dwLimb = ((FX_DWORD)g_inv_base64[pBuffer[i]] << 18) |
((FX_DWORD)g_inv_base64[pBuffer[i + 1]] << 12) |
((FX_DWORD)g_inv_base64[pBuffer[i + 2]] << 6) |
((FX_DWORD)g_inv_base64[pBuffer[i + 3]]);
pOutBuffer[j] = (uint8_t)(dwLimb >> 16) & 0xff;
pOutBuffer[j + 1] = (uint8_t)(dwLimb >> 8) & 0xff;
pOutBuffer[j + 2] = (uint8_t)(dwLimb)&0xff;
j += 3;
}
}
FX_Free(pBuffer);
return j;
}
static FX_CHAR g_base64_chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
FX_CHAR* XFA_Base64Encode(const uint8_t* buf, int32_t buf_len) {
FX_CHAR* out = NULL;
int i, j;
FX_DWORD limb;
out = FX_Alloc(FX_CHAR, ((buf_len * 8 + 5) / 6) + 5);
for (i = 0, j = 0, limb = 0; i + 2 < buf_len; i += 3, j += 4) {
limb = ((FX_DWORD)buf[i] << 16) | ((FX_DWORD)buf[i + 1] << 8) |
((FX_DWORD)buf[i + 2]);
out[j] = g_base64_chars[(limb >> 18) & 63];
out[j + 1] = g_base64_chars[(limb >> 12) & 63];
out[j + 2] = g_base64_chars[(limb >> 6) & 63];
out[j + 3] = g_base64_chars[(limb)&63];
}
switch (buf_len - i) {
case 0:
break;
case 1:
limb = ((FX_DWORD)buf[i]);
out[j++] = g_base64_chars[(limb >> 2) & 63];
out[j++] = g_base64_chars[(limb << 4) & 63];
out[j++] = '=';
out[j++] = '=';
break;
case 2:
limb = ((FX_DWORD)buf[i] << 8) | ((FX_DWORD)buf[i + 1]);
out[j++] = g_base64_chars[(limb >> 10) & 63];
out[j++] = g_base64_chars[(limb >> 4) & 63];
out[j++] = g_base64_chars[(limb << 2) & 63];
out[j++] = '=';
break;
default:
break;
}
out[j] = '\0';
return out;
}
FXCODEC_IMAGE_TYPE XFA_GetImageType(const CFX_WideStringC& wsType) {
CFX_WideString wsContentType(wsType);
wsContentType.MakeLower();
if (wsContentType == FX_WSTRC(L"image/jpg")) {
return FXCODEC_IMAGE_JPG;
}
if (wsContentType == FX_WSTRC(L"image/png")) {
return FXCODEC_IMAGE_PNG;
}
if (wsContentType == FX_WSTRC(L"image/gif")) {
return FXCODEC_IMAGE_GIF;
}
if (wsContentType == FX_WSTRC(L"image/bmp")) {
return FXCODEC_IMAGE_BMP;
}
if (wsContentType == FX_WSTRC(L"image/tif")) {
return FXCODEC_IMAGE_TIF;
}
return FXCODEC_IMAGE_UNKNOWN;
}
CFX_DIBitmap* XFA_LoadImageData(CXFA_FFDoc* pDoc,
CXFA_Image* pImage,
FX_BOOL& bNameImage,
int32_t& iImageXDpi,
int32_t& iImageYDpi) {
CFX_WideString wsHref;
pImage->GetHref(wsHref);
CFX_WideString wsImage;
pImage->GetContent(wsImage);
if (wsHref.IsEmpty() && wsImage.IsEmpty()) {
return NULL;
}
CFX_WideString wsContentType;
pImage->GetContentType(wsContentType);
FXCODEC_IMAGE_TYPE type = XFA_GetImageType(wsContentType);
CFX_ByteString bsContent;
uint8_t* pImageBuffer = NULL;
IFX_FileRead* pImageFileRead = NULL;
if (wsImage.GetLength() > 0) {
XFA_ATTRIBUTEENUM iEncoding =
(XFA_ATTRIBUTEENUM)pImage->GetTransferEncoding();
if (iEncoding == XFA_ATTRIBUTEENUM_Base64) {
CFX_ByteString bsData = wsImage.UTF8Encode();
int32_t iLength = bsData.GetLength();
pImageBuffer = FX_Alloc(uint8_t, iLength);
int32_t iRead = XFA_Base64Decode((const FX_CHAR*)bsData, pImageBuffer);
if (iRead > 0) {
pImageFileRead = FX_CreateMemoryStream(pImageBuffer, iRead);
}
} else {
bsContent = CFX_ByteString::FromUnicode(wsImage);
pImageFileRead = FX_CreateMemoryStream(
(uint8_t*)(const uint8_t*)bsContent, bsContent.GetLength());
}
} else {
CFX_WideString wsURL = wsHref;
if (wsURL.Left(7) != FX_WSTRC(L"http://") &&
wsURL.Left(6) != FX_WSTRC(L"ftp://")) {
CFX_DIBitmap* pBitmap =
pDoc->GetPDFNamedImage(wsURL, iImageXDpi, iImageYDpi);
if (pBitmap != NULL) {
bNameImage = TRUE;
return pBitmap;
}
}
pImageFileRead = pDoc->GetDocProvider()->OpenLinkedFile(pDoc, wsURL);
}
if (!pImageFileRead) {
FX_Free(pImageBuffer);
return NULL;
}
bNameImage = FALSE;
CFX_DIBitmap* pBitmap =
XFA_LoadImageFromBuffer(pImageFileRead, type, iImageXDpi, iImageYDpi);
FX_Free(pImageBuffer);
pImageFileRead->Release();
return pBitmap;
}
static FXDIB_Format XFA_GetDIBFormat(FXCODEC_IMAGE_TYPE type,
int32_t iComponents,
int32_t iBitsPerComponent) {
FXDIB_Format dibFormat = FXDIB_Argb;
switch (type) {
case FXCODEC_IMAGE_BMP:
case FXCODEC_IMAGE_JPG:
case FXCODEC_IMAGE_TIF: {
dibFormat = FXDIB_Rgb32;
int32_t bpp = iComponents * iBitsPerComponent;
if (bpp <= 24) {
dibFormat = FXDIB_Rgb;
}
} break;
case FXCODEC_IMAGE_PNG:
default:
break;
}
return dibFormat;
}
CFX_DIBitmap* XFA_LoadImageFromBuffer(IFX_FileRead* pImageFileRead,
FXCODEC_IMAGE_TYPE type,
int32_t& iImageXDpi,
int32_t& iImageYDpi) {
CFX_GEModule* pGeModule = CFX_GEModule::Get();
if (!pGeModule) {
return NULL;
}
CCodec_ModuleMgr* pCodecMgr = pGeModule->GetCodecModule();
if (!pCodecMgr) {
return NULL;
}
CFX_DIBAttribute dibAttr;
CFX_DIBitmap* pBitmap = NULL;
ICodec_ProgressiveDecoder* pProgressiveDecoder =
pCodecMgr->CreateProgressiveDecoder();
pProgressiveDecoder->LoadImageInfo(pImageFileRead, type, &dibAttr);
switch (dibAttr.m_wDPIUnit) {
case FXCODEC_RESUNIT_CENTIMETER:
dibAttr.m_nXDPI = (int32_t)(dibAttr.m_nXDPI * 2.54f);
dibAttr.m_nYDPI = (int32_t)(dibAttr.m_nYDPI * 2.54f);
break;
case FXCODEC_RESUNIT_METER:
dibAttr.m_nXDPI = (int32_t)(dibAttr.m_nXDPI / (FX_FLOAT)100 * 2.54f);
dibAttr.m_nYDPI = (int32_t)(dibAttr.m_nYDPI / (FX_FLOAT)100 * 2.54f);
break;
;
default:
break;
}
iImageXDpi = dibAttr.m_nXDPI > 1 ? dibAttr.m_nXDPI : (96);
iImageYDpi = dibAttr.m_nYDPI > 1 ? dibAttr.m_nYDPI : (96);
if (pProgressiveDecoder->GetWidth() > 0 &&
pProgressiveDecoder->GetHeight() > 0) {
type = pProgressiveDecoder->GetType();
int32_t iComponents = pProgressiveDecoder->GetNumComponents();
int32_t iBpc = pProgressiveDecoder->GetBPC();
FXDIB_Format dibFormat = XFA_GetDIBFormat(type, iComponents, iBpc);
pBitmap = new CFX_DIBitmap();
pBitmap->Create(pProgressiveDecoder->GetWidth(),
pProgressiveDecoder->GetHeight(), dibFormat);
pBitmap->Clear(0xffffffff);
int32_t nFrames;
if ((pProgressiveDecoder->GetFrames(nFrames) ==
FXCODEC_STATUS_DECODE_READY) &&
(nFrames > 0)) {
pProgressiveDecoder->StartDecode(pBitmap, 0, 0, pBitmap->GetWidth(),
pBitmap->GetHeight());
pProgressiveDecoder->ContinueDecode();
}
}
delete pProgressiveDecoder;
return pBitmap;
}
void XFA_RectWidthoutMargin(CFX_RectF& rt, const CXFA_Margin& mg, FX_BOOL bUI) {
if (!mg) {
return;
}
FX_FLOAT fLeftInset, fTopInset, fRightInset, fBottomInset;
mg.GetLeftInset(fLeftInset);
mg.GetTopInset(fTopInset);
mg.GetRightInset(fRightInset);
mg.GetBottomInset(fBottomInset);
rt.Deflate(fLeftInset, fTopInset, fRightInset, fBottomInset);
}
CXFA_FFWidget* XFA_GetWidgetFromLayoutItem(CXFA_LayoutItem* pLayoutItem) {
XFA_ELEMENT iType = pLayoutItem->GetFormNode()->GetClassID();
if (XFA_IsCreateWidget(iType)) {
return static_cast<CXFA_FFWidget*>(pLayoutItem);
}
return nullptr;
}
FX_BOOL XFA_IsCreateWidget(XFA_ELEMENT iType) {
return iType == XFA_ELEMENT_Field || iType == XFA_ELEMENT_Draw ||
iType == XFA_ELEMENT_Subform || iType == XFA_ELEMENT_ExclGroup;
}
static void XFA_BOX_GetPath_Arc(CXFA_Box box,
CFX_RectF rtDraw,
CFX_Path& fillPath,
FX_DWORD dwFlags) {
FX_FLOAT a, b;
a = rtDraw.width / 2.0f;
b = rtDraw.height / 2.0f;
if (box.IsCircular() || (dwFlags & XFA_DRAWBOX_ForceRound) != 0) {
a = b = std::min(a, b);
}
CFX_PointF center = rtDraw.Center();
rtDraw.left = center.x - a;
rtDraw.top = center.y - b;
rtDraw.width = a + a;
rtDraw.height = b + b;
FX_FLOAT startAngle = 0, sweepAngle = 360;
FX_BOOL bStart = box.GetStartAngle(startAngle);
FX_BOOL bEnd = box.GetSweepAngle(sweepAngle);
if (!bStart && !bEnd) {
fillPath.AddEllipse(rtDraw);
return;
}
startAngle = -startAngle * FX_PI / 180.0f;
sweepAngle = -sweepAngle * FX_PI / 180.0f;
fillPath.AddArc(rtDraw.left, rtDraw.top, rtDraw.width, rtDraw.height,
startAngle, sweepAngle);
}
static void XFA_BOX_GetPath(CXFA_Box box,
const CXFA_StrokeArray& strokes,
CFX_RectF rtWidget,
CFX_Path& path,
int32_t nIndex,
FX_BOOL bStart,
FX_BOOL bCorner) {
FXSYS_assert(nIndex >= 0 && nIndex < 8);
FX_BOOL bInverted, bRound;
FX_FLOAT fRadius1, fRadius2, sx, sy, vx, vy, nx, ny, offsetY, offsetX,
offsetEX, offsetEY;
CFX_PointF cpStart, cp, cp1, cp2;
CFX_RectF rtRadius;
int32_t n = (nIndex & 1) ? nIndex - 1 : nIndex;
CXFA_Corner corner1 = (CXFA_Node*)strokes[n];
CXFA_Corner corner2 = (CXFA_Node*)strokes[(n + 2) % 8];
fRadius1 = bCorner ? corner1.GetRadius() : 0;
fRadius2 = bCorner ? corner2.GetRadius() : 0;
bInverted = corner1.IsInverted();
offsetY = 0.0f;
offsetX = 0.0f;
bRound = corner1.GetJoinType() == XFA_ATTRIBUTEENUM_Round;
FX_FLOAT halfAfter = 0.0f;
FX_FLOAT halfBefore = 0.0f;
CXFA_Stroke stroke = strokes[nIndex];
if (stroke.IsCorner()) {
CXFA_Stroke edgeBefore = strokes[(nIndex + 1 * 8 - 1) % 8];
CXFA_Stroke edgeAfter = strokes[nIndex + 1];
if (stroke.IsInverted()) {
if (!stroke.SameStyles(edgeBefore)) {
halfBefore = edgeBefore.GetThickness() / 2;
}
if (!stroke.SameStyles(edgeAfter)) {
halfAfter = edgeAfter.GetThickness() / 2;
}
}
} else {
CXFA_Stroke edgeBefore = strokes[(nIndex + 8 - 2) % 8];
CXFA_Stroke edgeAfter = strokes[(nIndex + 2) % 8];
if (!bRound && !bInverted) {
{ halfBefore = edgeBefore.GetThickness() / 2; }
{ halfAfter = edgeAfter.GetThickness() / 2; }
}
}
offsetEX = 0.0f;
offsetEY = 0.0f;
if (bRound) {
sy = FX_PI / 2;
}
switch (nIndex) {
case 0:
case 1:
cp1 = rtWidget.TopLeft();
cp2 = rtWidget.TopRight();
if (nIndex == 0) {
cpStart.x = cp1.x - halfBefore;
cpStart.y = cp1.y + fRadius1, offsetY = -halfAfter;
} else {
cpStart.x = cp1.x + fRadius1 - halfBefore, cpStart.y = cp1.y,
offsetEX = halfAfter;
}
vx = 1, vy = 1;
nx = -1, ny = 0;
if (bRound) {
sx = bInverted ? FX_PI / 2 : FX_PI;
} else {
sx = 1, sy = 0;
}
break;
case 2:
case 3:
cp1 = rtWidget.TopRight();
cp2 = rtWidget.BottomRight();
if (nIndex == 2) {
cpStart.x = cp1.x - fRadius1, cpStart.y = cp1.y - halfBefore,
offsetX = halfAfter;
} else {
cpStart.x = cp1.x, cpStart.y = cp1.y + fRadius1 - halfBefore,
offsetEY = halfAfter;
}
vx = -1, vy = 1;
nx = 0, ny = -1;
if (bRound) {
sx = bInverted ? FX_PI : FX_PI * 3 / 2;
} else {
sx = 0, sy = 1;
}
break;
case 4:
case 5:
cp1 = rtWidget.BottomRight();
cp2 = rtWidget.BottomLeft();
if (nIndex == 4) {
cpStart.x = cp1.x + halfBefore, cpStart.y = cp1.y - fRadius1,
offsetY = halfAfter;
} else {
cpStart.x = cp1.x - fRadius1 + halfBefore, cpStart.y = cp1.y,
offsetEX = -halfAfter;
}
vx = -1, vy = -1;
nx = 1, ny = 0;
if (bRound) {
sx = bInverted ? FX_PI * 3 / 2 : 0;
} else {
sx = -1, sy = 0;
}
break;
case 6:
case 7:
cp1 = rtWidget.BottomLeft();
cp2 = rtWidget.TopLeft();
if (nIndex == 6) {
cpStart.x = cp1.x + fRadius1, cpStart.y = cp1.y + halfBefore,
offsetX = -halfAfter;
} else {
cpStart.x = cp1.x, cpStart.y = cp1.y - fRadius1 + halfBefore,
offsetEY = -halfAfter;
}
vx = 1, vy = -1;
nx = 0, ny = 1;
if (bRound) {
sx = bInverted ? 0 : FX_PI / 2;
} else {
sx = 0, sy = -1;
}
break;
}
if (bStart) {
path.MoveTo(cpStart.x, cpStart.y);
}
if (nIndex & 1) {
path.LineTo(cp2.x + fRadius2 * nx + offsetEX,
cp2.y + fRadius2 * ny + offsetEY);
return;
}
if (bRound) {
if (fRadius1 < 0) {
sx -= FX_PI;
}
if (bInverted) {
sy *= -1;
}
rtRadius.Set(cp1.x + offsetX * 2, cp1.y + offsetY * 2,
fRadius1 * 2 * vx - offsetX * 2,
fRadius1 * 2 * vy - offsetY * 2);
rtRadius.Normalize();
if (bInverted) {
rtRadius.Offset(-fRadius1 * vx, -fRadius1 * vy);
}
path.ArcTo(rtRadius.left, rtRadius.top, rtRadius.width, rtRadius.height, sx,
sy);
} else {
if (bInverted) {
cp.x = cp1.x + fRadius1 * vx, cp.y = cp1.y + fRadius1 * vy;
} else {
cp = cp1;
}
path.LineTo(cp.x, cp.y);
path.LineTo(cp1.x + fRadius1 * sx + offsetX,
cp1.y + fRadius1 * sy + offsetY);
}
}
static void XFA_BOX_GetFillPath(CXFA_Box box,
const CXFA_StrokeArray& strokes,
CFX_RectF rtWidget,
CFX_Path& fillPath,
FX_WORD dwFlags) {
if (box.IsArc() || (dwFlags & XFA_DRAWBOX_ForceRound) != 0) {
CXFA_Edge edge = box.GetEdge(0);
FX_FLOAT fThickness = edge.GetThickness();
if (fThickness < 0) {
fThickness = 0;
}
FX_FLOAT fHalf = fThickness / 2;
int32_t iHand = box.GetHand();
if (iHand == XFA_ATTRIBUTEENUM_Left) {
rtWidget.Inflate(fHalf, fHalf);
} else if (iHand == XFA_ATTRIBUTEENUM_Right) {
rtWidget.Deflate(fHalf, fHalf);
}
XFA_BOX_GetPath_Arc(box, rtWidget, fillPath, dwFlags);
return;
}
FX_BOOL bSameStyles = TRUE;
int32_t i;
CXFA_Stroke stroke1 = strokes[0];
for (i = 1; i < 8; i++) {
CXFA_Stroke stroke2 = strokes[i];
if (!stroke1.SameStyles(stroke2)) {
bSameStyles = FALSE;
break;
}
stroke1 = stroke2;
}
if (bSameStyles) {
stroke1 = strokes[0];
for (i = 2; i < 8; i += 2) {
CXFA_Stroke stroke2 = strokes[i];
if (!stroke1.SameStyles(stroke2, XFA_STROKE_SAMESTYLE_NoPresence |
XFA_STROKE_SAMESTYLE_Corner)) {
bSameStyles = FALSE;
break;
}
stroke1 = stroke2;
}
if (bSameStyles) {
stroke1 = strokes[0];
if (stroke1.IsInverted()) {
bSameStyles = FALSE;
}
if (stroke1.GetJoinType() != XFA_ATTRIBUTEENUM_Square) {
bSameStyles = FALSE;
}
}
}
if (bSameStyles) {
fillPath.AddRectangle(rtWidget.left, rtWidget.top, rtWidget.width,
rtWidget.height);
return;
}
FX_BOOL bInverted, bRound;
FX_FLOAT fRadius1, fRadius2, sx, sy, vx, vy, nx, ny;
CFX_PointF cp, cp1, cp2;
CFX_RectF rtRadius;
for (int32_t i = 0; i < 8; i += 2) {
CXFA_Corner corner1 = (CXFA_Node*)strokes[i];
CXFA_Corner corner2 = (CXFA_Node*)strokes[(i + 2) % 8];
fRadius1 = corner1.GetRadius();
fRadius2 = corner2.GetRadius();
bInverted = corner1.IsInverted();
bRound = corner1.GetJoinType() == XFA_ATTRIBUTEENUM_Round;
if (bRound) {
sy = FX_PI / 2;
}
switch (i) {
case 0:
cp1 = rtWidget.TopLeft();
cp2 = rtWidget.TopRight();
vx = 1, vy = 1;
nx = -1, ny = 0;
if (bRound) {
sx = bInverted ? FX_PI / 2 : FX_PI;
} else {
sx = 1, sy = 0;
}
break;
case 2:
cp1 = rtWidget.TopRight();
cp2 = rtWidget.BottomRight();
vx = -1, vy = 1;
nx = 0, ny = -1;
if (bRound) {
sx = bInverted ? FX_PI : FX_PI * 3 / 2;
} else {
sx = 0, sy = 1;
}
break;
case 4:
cp1 = rtWidget.BottomRight();
cp2 = rtWidget.BottomLeft();
vx = -1, vy = -1;
nx = 1, ny = 0;
if (bRound) {
sx = bInverted ? FX_PI * 3 / 2 : 0;
} else {
sx = -1, sy = 0;
}
break;
case 6:
cp1 = rtWidget.BottomLeft();
cp2 = rtWidget.TopLeft();
vx = 1, vy = -1;
nx = 0, ny = 1;
if (bRound) {
sx = bInverted ? 0 : FX_PI / 2;
} else {
sx = 0, sy = -1;
}
break;
}
if (i == 0) {
fillPath.MoveTo(cp1.x, cp1.y + fRadius1);
}
if (bRound) {
if (fRadius1 < 0) {
sx -= FX_PI;
}
if (bInverted) {
sy *= -1;
}
rtRadius.Set(cp1.x, cp1.y, fRadius1 * 2 * vx, fRadius1 * 2 * vy);
rtRadius.Normalize();
if (bInverted) {
rtRadius.Offset(-fRadius1 * vx, -fRadius1 * vy);
}
fillPath.ArcTo(rtRadius.left, rtRadius.top, rtRadius.width,
rtRadius.height, sx, sy);
} else {
if (bInverted) {
cp.x = cp1.x + fRadius1 * vx, cp.y = cp1.y + fRadius1 * vy;
} else {
cp = cp1;
}
fillPath.LineTo(cp.x, cp.y);
fillPath.LineTo(cp1.x + fRadius1 * sx, cp1.y + fRadius1 * sy);
}
fillPath.LineTo(cp2.x + fRadius2 * nx, cp2.y + fRadius2 * ny);
}
}
static void XFA_BOX_Fill_Radial(CXFA_Box box,
CFX_Graphics* pGS,
CFX_Path& fillPath,
CFX_RectF rtFill,
CFX_Matrix* pMatrix) {
CXFA_Fill fill = box.GetFill();
FX_ARGB crStart, crEnd;
crStart = fill.GetColor();
int32_t iType = fill.GetRadial(crEnd);
CFX_Shading shading;
if (iType != XFA_ATTRIBUTEENUM_ToEdge) {
FX_ARGB temp = crEnd;
crEnd = crStart;
crStart = temp;
}
shading.CreateRadial(rtFill.Center(), rtFill.Center(), 0,
FXSYS_sqrt(rtFill.Width() * rtFill.Width() +
rtFill.Height() * rtFill.Height()) /
2,
TRUE, TRUE, crStart, crEnd);
CFX_Color cr(&shading);
pGS->SetFillColor(&cr);
pGS->FillPath(&fillPath, FXFILL_WINDING, pMatrix);
}
static void XFA_BOX_Fill_Pattern(CXFA_Box box,
CFX_Graphics* pGS,
CFX_Path& fillPath,
CFX_RectF rtFill,
CFX_Matrix* pMatrix) {
CXFA_Fill fill = box.GetFill();
FX_ARGB crStart, crEnd;
crStart = fill.GetColor();
int32_t iType = fill.GetPattern(crEnd);
int32_t iHatch = FX_HATCHSTYLE_Cross;
switch (iType) {
case XFA_ATTRIBUTEENUM_CrossDiagonal:
iHatch = FX_HATCHSTYLE_DiagonalCross;
break;
case XFA_ATTRIBUTEENUM_DiagonalLeft:
iHatch = FX_HATCHSTYLE_ForwardDiagonal;
break;
case XFA_ATTRIBUTEENUM_DiagonalRight:
iHatch = FX_HATCHSTYLE_BackwardDiagonal;
break;
case XFA_ATTRIBUTEENUM_Horizontal:
iHatch = FX_HATCHSTYLE_Horizontal;
break;
case XFA_ATTRIBUTEENUM_Vertical:
iHatch = FX_HATCHSTYLE_Vertical;
break;
default:
break;
}
CFX_Pattern pattern;
pattern.Create(iHatch, crEnd, crStart);
CFX_Color cr(&pattern);
pGS->SetFillColor(&cr);
pGS->FillPath(&fillPath, FXFILL_WINDING, pMatrix);
}
static void XFA_BOX_Fill_Linear(CXFA_Box box,
CFX_Graphics* pGS,
CFX_Path& fillPath,
CFX_RectF rtFill,
CFX_Matrix* pMatrix) {
CXFA_Fill fill = box.GetFill();
FX_ARGB crStart, crEnd;
crStart = fill.GetColor();
int32_t iType = fill.GetLinear(crEnd);
CFX_PointF ptStart, ptEnd;
switch (iType) {
case XFA_ATTRIBUTEENUM_ToRight:
ptStart.Set(rtFill.left, rtFill.top);
ptEnd.Set(rtFill.right(), rtFill.top);
break;
case XFA_ATTRIBUTEENUM_ToBottom:
ptStart.Set(rtFill.left, rtFill.top);
ptEnd.Set(rtFill.left, rtFill.bottom());
break;
case XFA_ATTRIBUTEENUM_ToLeft:
ptStart.Set(rtFill.right(), rtFill.top);
ptEnd.Set(rtFill.left, rtFill.top);
break;
case XFA_ATTRIBUTEENUM_ToTop:
ptStart.Set(rtFill.left, rtFill.bottom());
ptEnd.Set(rtFill.left, rtFill.top);
break;
default:
break;
}
CFX_Shading shading;
shading.CreateAxial(ptStart, ptEnd, FALSE, FALSE, crStart, crEnd);
CFX_Color cr(&shading);
pGS->SetFillColor(&cr);
pGS->FillPath(&fillPath, FXFILL_WINDING, pMatrix);
}
static void XFA_BOX_Fill(CXFA_Box box,
const CXFA_StrokeArray& strokes,
CFX_Graphics* pGS,
const CFX_RectF& rtWidget,
CFX_Matrix* pMatrix,
FX_DWORD dwFlags) {
CXFA_Fill fill = box.GetFill();
if (!fill.IsExistInXML() || fill.GetPresence() != XFA_ATTRIBUTEENUM_Visible) {
return;
}
pGS->SaveGraphState();
CFX_Path fillPath;
fillPath.Create();
XFA_BOX_GetFillPath(box, strokes, rtWidget, fillPath,
(dwFlags & XFA_DRAWBOX_ForceRound) != 0);
fillPath.Close();
int32_t eType = fill.GetFillType();
switch (eType) {
case XFA_ELEMENT_Radial:
XFA_BOX_Fill_Radial(box, pGS, fillPath, rtWidget, pMatrix);
break;
case XFA_ELEMENT_Pattern:
XFA_BOX_Fill_Pattern(box, pGS, fillPath, rtWidget, pMatrix);
break;
case XFA_ELEMENT_Linear:
XFA_BOX_Fill_Linear(box, pGS, fillPath, rtWidget, pMatrix);
break;
default: {
FX_ARGB cr;
if (eType == XFA_ELEMENT_Stipple) {
int32_t iRate = fill.GetStipple(cr);
if (iRate == 0) {
iRate = 100;
}
int32_t a = 0;
FX_COLORREF rgb;
ArgbDecode(cr, a, rgb);
cr = ArgbEncode(iRate * a / 100, rgb);
} else {
cr = fill.GetColor();
}
CFX_Color fillColor(cr);
pGS->SetFillColor(&fillColor);
pGS->FillPath(&fillPath, FXFILL_WINDING, pMatrix);
} break;
}
pGS->RestoreGraphState();
}
static void XFA_BOX_StrokePath(CXFA_Stroke stroke,
CFX_Path* pPath,
CFX_Graphics* pGS,
CFX_Matrix* pMatrix) {
if (!stroke.IsExistInXML() || !stroke.IsVisible()) {
return;
}
FX_FLOAT fThickness = stroke.GetThickness();
if (fThickness < 0.001f) {
return;
}
pGS->SaveGraphState();
if (stroke.IsCorner() && fThickness > 2 * stroke.GetRadius()) {
fThickness = 2 * stroke.GetRadius();
}
pGS->SetLineWidth(fThickness, TRUE);
pGS->SetLineCap(CFX_GraphStateData::LineCapButt);
XFA_StrokeTypeSetLineDash(pGS, stroke.GetStrokeType(),
XFA_ATTRIBUTEENUM_Butt);
CFX_Color fxColor(stroke.GetColor());
pGS->SetStrokeColor(&fxColor);
pGS->StrokePath(pPath, pMatrix);
pGS->RestoreGraphState();
}
static void XFA_BOX_StrokeArc(CXFA_Box box,
CFX_Graphics* pGS,
CFX_RectF rtWidget,
CFX_Matrix* pMatrix,
FX_DWORD dwFlags) {
CXFA_Edge edge = box.GetEdge(0);
if (!edge.IsExistInXML() || !edge.IsVisible()) {
return;
}
FX_BOOL bVisible = FALSE;
FX_FLOAT fThickness = 0;
int32_t i3DType = box.Get3DStyle(bVisible, fThickness);
if (i3DType) {
if (bVisible && fThickness >= 0.001f) {
dwFlags |= XFA_DRAWBOX_Lowered3D;
}
}
FX_FLOAT fHalf = edge.GetThickness() / 2;
if (fHalf < 0) {
fHalf = 0;
}
int32_t iHand = box.GetHand();
if (iHand == XFA_ATTRIBUTEENUM_Left) {
rtWidget.Inflate(fHalf, fHalf);
} else if (iHand == XFA_ATTRIBUTEENUM_Right) {
rtWidget.Deflate(fHalf, fHalf);
}
if ((dwFlags & XFA_DRAWBOX_ForceRound) == 0 ||
(dwFlags & XFA_DRAWBOX_Lowered3D) == 0) {
if (fHalf < 0.001f) {
return;
}
CFX_Path arcPath;
arcPath.Create();
XFA_BOX_GetPath_Arc(box, rtWidget, arcPath, dwFlags);
XFA_BOX_StrokePath(edge, &arcPath, pGS, pMatrix);
return;
}
pGS->SaveGraphState();
pGS->SetLineWidth(fHalf);
FX_FLOAT a, b;
a = rtWidget.width / 2.0f;
b = rtWidget.height / 2.0f;
if (dwFlags & XFA_DRAWBOX_ForceRound) {
a = b = std::min(a, b);
}
CFX_PointF center = rtWidget.Center();
rtWidget.left = center.x - a;
rtWidget.top = center.y - b;
rtWidget.width = a + a;
rtWidget.height = b + b;
FX_FLOAT startAngle = 0, sweepAngle = 360;
startAngle = startAngle * FX_PI / 180.0f;
sweepAngle = -sweepAngle * FX_PI / 180.0f;
CFX_Path arcPath;
arcPath.Create();
arcPath.AddArc(rtWidget.left, rtWidget.top, rtWidget.width, rtWidget.height,
3.0f * FX_PI / 4.0f, FX_PI);
CFX_Color cr(0xFF808080);
pGS->SetStrokeColor(&cr);
pGS->StrokePath(&arcPath, pMatrix);
arcPath.Clear();
arcPath.AddArc(rtWidget.left, rtWidget.top, rtWidget.width, rtWidget.height,
-1.0f * FX_PI / 4.0f, FX_PI);
cr.Set(0xFFFFFFFF);
pGS->SetStrokeColor(&cr);
pGS->StrokePath(&arcPath, pMatrix);
rtWidget.Deflate(fHalf, fHalf);
arcPath.Clear();
arcPath.AddArc(rtWidget.left, rtWidget.top, rtWidget.width, rtWidget.height,
3.0f * FX_PI / 4.0f, FX_PI);
cr.Set(0xFF404040);
pGS->SetStrokeColor(&cr);
pGS->StrokePath(&arcPath, pMatrix);
arcPath.Clear();
arcPath.AddArc(rtWidget.left, rtWidget.top, rtWidget.width, rtWidget.height,
-1.0f * FX_PI / 4.0f, FX_PI);
cr.Set(0xFFC0C0C0);
pGS->SetStrokeColor(&cr);
pGS->StrokePath(&arcPath, pMatrix);
pGS->RestoreGraphState();
}
static void XFA_Draw3DRect(CFX_Graphics* pGraphic,
const CFX_RectF& rt,
FX_FLOAT fLineWidth,
CFX_Matrix* pMatrix,
FX_ARGB argbTopLeft,
FX_ARGB argbBottomRight) {
CFX_Color crLT(argbTopLeft);
pGraphic->SetFillColor(&crLT);
FX_FLOAT fBottom = rt.bottom();
FX_FLOAT fRight = rt.right();
CFX_Path pathLT;
pathLT.Create();
pathLT.MoveTo(rt.left, fBottom);
pathLT.LineTo(rt.left, rt.top);
pathLT.LineTo(fRight, rt.top);
pathLT.LineTo(fRight - fLineWidth, rt.top + fLineWidth);
pathLT.LineTo(rt.left + fLineWidth, rt.top + fLineWidth);
pathLT.LineTo(rt.left + fLineWidth, fBottom - fLineWidth);
pathLT.LineTo(rt.left, fBottom);
pGraphic->FillPath(&pathLT, FXFILL_WINDING, pMatrix);
CFX_Color crRB(argbBottomRight);
pGraphic->SetFillColor(&crRB);
CFX_Path pathRB;
pathRB.Create();
pathRB.MoveTo(fRight, rt.top);
pathRB.LineTo(fRight, fBottom);
pathRB.LineTo(rt.left, fBottom);
pathRB.LineTo(rt.left + fLineWidth, fBottom - fLineWidth);
pathRB.LineTo(fRight - fLineWidth, fBottom - fLineWidth);
pathRB.LineTo(fRight - fLineWidth, rt.top + fLineWidth);
pathRB.LineTo(fRight, rt.top);
pGraphic->FillPath(&pathRB, FXFILL_WINDING, pMatrix);
}
static void XFA_BOX_Stroke_3DRect_Lowered(CFX_Graphics* pGS,
CFX_RectF rt,
FX_FLOAT fThickness,
CFX_Matrix* pMatrix) {
FX_FLOAT fHalfWidth = fThickness / 2.0f;
CFX_RectF rtInner(rt);
rtInner.Deflate(fHalfWidth, fHalfWidth);
CFX_Color cr(0xFF000000);
pGS->SetFillColor(&cr);
CFX_Path path;
path.Create();
path.AddRectangle(rt.left, rt.top, rt.width, rt.height);
path.AddRectangle(rtInner.left, rtInner.top, rtInner.width, rtInner.height);
pGS->FillPath(&path, FXFILL_ALTERNATE, pMatrix);
XFA_Draw3DRect(pGS, rtInner, fHalfWidth, pMatrix, 0xFF808080, 0xFFC0C0C0);
}
static void XFA_BOX_Stroke_3DRect_Raised(CFX_Graphics* pGS,
CFX_RectF rt,
FX_FLOAT fThickness,
CFX_Matrix* pMatrix) {
FX_FLOAT fHalfWidth = fThickness / 2.0f;
CFX_RectF rtInner(rt);
rtInner.Deflate(fHalfWidth, fHalfWidth);
CFX_Color cr(0xFF000000);
pGS->SetFillColor(&cr);
CFX_Path path;
path.Create();
path.AddRectangle(rt.left, rt.top, rt.width, rt.height);
path.AddRectangle(rtInner.left, rtInner.top, rtInner.width, rtInner.height);
pGS->FillPath(&path, FXFILL_ALTERNATE, pMatrix);
XFA_Draw3DRect(pGS, rtInner, fHalfWidth, pMatrix, 0xFFFFFFFF, 0xFF808080);
}
static void XFA_BOX_Stroke_3DRect_Etched(CFX_Graphics* pGS,
CFX_RectF rt,
FX_FLOAT fThickness,
CFX_Matrix* pMatrix) {
FX_FLOAT fHalfWidth = fThickness / 2.0f;
XFA_Draw3DRect(pGS, rt, fThickness, pMatrix, 0xFF808080, 0xFFFFFFFF);
CFX_RectF rtInner(rt);
rtInner.Deflate(fHalfWidth, fHalfWidth);
XFA_Draw3DRect(pGS, rtInner, fHalfWidth, pMatrix, 0xFFFFFFFF, 0xFF808080);
}
static void XFA_BOX_Stroke_3DRect_Embossed(CFX_Graphics* pGS,
CFX_RectF rt,
FX_FLOAT fThickness,
CFX_Matrix* pMatrix) {
FX_FLOAT fHalfWidth = fThickness / 2.0f;
XFA_Draw3DRect(pGS, rt, fThickness, pMatrix, 0xFF808080, 0xFF000000);
CFX_RectF rtInner(rt);
rtInner.Deflate(fHalfWidth, fHalfWidth);
XFA_Draw3DRect(pGS, rtInner, fHalfWidth, pMatrix, 0xFF000000, 0xFF808080);
}
static void XFA_BOX_Stroke_Rect(CXFA_Box box,
const CXFA_StrokeArray& strokes,
CFX_Graphics* pGS,
CFX_RectF rtWidget,
CFX_Matrix* pMatrix) {
FX_BOOL bVisible = FALSE;
FX_FLOAT fThickness = 0;
int32_t i3DType = box.Get3DStyle(bVisible, fThickness);
if (i3DType) {
if (!bVisible || fThickness < 0.001f) {
return;
}
switch (i3DType) {
case XFA_ATTRIBUTEENUM_Lowered:
XFA_BOX_Stroke_3DRect_Lowered(pGS, rtWidget, fThickness, pMatrix);
break;
case XFA_ATTRIBUTEENUM_Raised:
XFA_BOX_Stroke_3DRect_Raised(pGS, rtWidget, fThickness, pMatrix);
break;
case XFA_ATTRIBUTEENUM_Etched:
XFA_BOX_Stroke_3DRect_Etched(pGS, rtWidget, fThickness, pMatrix);
break;
case XFA_ATTRIBUTEENUM_Embossed:
XFA_BOX_Stroke_3DRect_Embossed(pGS, rtWidget, fThickness, pMatrix);
break;
}
return;
}
FX_BOOL bClose = FALSE;
FX_BOOL bSameStyles = TRUE;
int32_t i;
CXFA_Stroke stroke1 = strokes[0];
for (i = 1; i < 8; i++) {
CXFA_Stroke stroke2 = strokes[i];
if (!stroke1.SameStyles(stroke2)) {
bSameStyles = FALSE;
break;
}
stroke1 = stroke2;
}
if (bSameStyles) {
stroke1 = strokes[0];
bClose = TRUE;
for (i = 2; i < 8; i += 2) {
CXFA_Stroke stroke2 = strokes[i];
if (!stroke1.SameStyles(stroke2, XFA_STROKE_SAMESTYLE_NoPresence |
XFA_STROKE_SAMESTYLE_Corner)) {
bSameStyles = FALSE;
break;
}
stroke1 = stroke2;
}
if (bSameStyles) {
stroke1 = strokes[0];
if (stroke1.IsInverted()) {
bSameStyles = FALSE;
}
if (stroke1.GetJoinType() != XFA_ATTRIBUTEENUM_Square) {
bSameStyles = FALSE;
}
}
}
FX_BOOL bStart = TRUE;
CFX_Path path;
path.Create();
for (i = 0; i < 8; i++) {
CXFA_Stroke stroke1 = strokes[i];
if ((i % 1) == 0 && stroke1.GetRadius() < 0) {
FX_BOOL bEmpty = path.IsEmpty();
if (!bEmpty) {
XFA_BOX_StrokePath(stroke1, &path, pGS, pMatrix);
path.Clear();
}
bStart = TRUE;
continue;
}
XFA_BOX_GetPath(box, strokes, rtWidget, path, i, bStart, !bSameStyles);
CXFA_Stroke stroke2 = strokes[(i + 1) % 8];
bStart = !stroke1.SameStyles(stroke2);
if (bStart) {
XFA_BOX_StrokePath(stroke1, &path, pGS, pMatrix);
path.Clear();
}
}
FX_BOOL bEmpty = path.IsEmpty();
if (!bEmpty) {
if (bClose) {
path.Close();
}
XFA_BOX_StrokePath(strokes[7], &path, pGS, pMatrix);
}
}
static void XFA_BOX_Stroke(CXFA_Box box,
const CXFA_StrokeArray& strokes,
CFX_Graphics* pGS,
CFX_RectF rtWidget,
CFX_Matrix* pMatrix,
FX_DWORD dwFlags) {
if (box.IsArc() || (dwFlags & XFA_DRAWBOX_ForceRound) != 0) {
XFA_BOX_StrokeArc(box, pGS, rtWidget, pMatrix, dwFlags);
return;
}
FX_BOOL bVisible = FALSE;
for (int32_t j = 0; j < 4; j++) {
bVisible |= strokes[j * 2 + 1].IsVisible();
if (bVisible) {
break;
}
}
if (!bVisible) {
return;
}
for (int32_t i = 1; i < 8; i += 2) {
CXFA_Edge edge = (CXFA_Node*)strokes[i];
FX_FLOAT fThickness = edge.GetThickness();
if (fThickness < 0) {
fThickness = 0;
}
FX_FLOAT fHalf = fThickness / 2;
int32_t iHand = box.GetHand();
switch (i) {
case 1:
if (iHand == XFA_ATTRIBUTEENUM_Left) {
rtWidget.top -= fHalf;
rtWidget.height += fHalf;
} else if (iHand == XFA_ATTRIBUTEENUM_Right) {
rtWidget.top += fHalf;
rtWidget.height -= fHalf;
}
break;
case 3:
if (iHand == XFA_ATTRIBUTEENUM_Left) {
rtWidget.width += fHalf;
} else if (iHand == XFA_ATTRIBUTEENUM_Right) {
rtWidget.width -= fHalf;
}
break;
case 5:
if (iHand == XFA_ATTRIBUTEENUM_Left) {
rtWidget.height += fHalf;
} else if (iHand == XFA_ATTRIBUTEENUM_Right) {
rtWidget.height -= fHalf;
}
break;
case 7:
if (iHand == XFA_ATTRIBUTEENUM_Left) {
rtWidget.left -= fHalf;
rtWidget.width += fHalf;
} else if (iHand == XFA_ATTRIBUTEENUM_Right) {
rtWidget.left += fHalf;
rtWidget.width -= fHalf;
}
break;
}
}
XFA_BOX_Stroke_Rect(box, strokes, pGS, rtWidget, pMatrix);
}
void XFA_DrawBox(CXFA_Box box,
CFX_Graphics* pGS,
const CFX_RectF& rtWidget,
CFX_Matrix* pMatrix,
FX_DWORD dwFlags) {
if (!box || box.GetPresence() != XFA_ATTRIBUTEENUM_Visible) {
return;
}
int32_t iType = box.GetClassID();
if (iType != XFA_ELEMENT_Arc && iType != XFA_ELEMENT_Border &&
iType != XFA_ELEMENT_Rectangle) {
return;
}
CXFA_StrokeArray strokes;
if (!(dwFlags & XFA_DRAWBOX_ForceRound) && iType != XFA_ELEMENT_Arc) {
box.GetStrokes(strokes);
}
XFA_BOX_Fill(box, strokes, pGS, rtWidget, pMatrix, dwFlags);
XFA_BOX_Stroke(box, strokes, pGS, rtWidget, pMatrix, dwFlags);
}
|
;
; jdmrgss2.asm - merged upsampling/color conversion (SSE2)
;
; Copyright 2009, 2012 Pierre Ossman <ossman@cendio.se> for Cendio AB
;
; Based on
; x86 SIMD extension for IJG JPEG library
; Copyright (C) 1999-2006, MIYASAKA Masaru.
; For conditions of distribution and use, see copyright notice in jsimdext.inc
;
; This file should be assembled with NASM (Netwide Assembler),
; can *not* be assembled with Microsoft's MASM or any compatible
; assembler (including Borland's Turbo Assembler).
; NASM is available from http://nasm.sourceforge.net/ or
; http://sourceforge.net/project/showfiles.php?group_id=6208
;
; [TAB8]
%include "jcolsamp.inc"
; --------------------------------------------------------------------------
;
; Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
;
; GLOBAL(void)
; jsimd_h2v1_merged_upsample_sse2 (JDIMENSION output_width,
; JSAMPIMAGE input_buf,
; JDIMENSION in_row_group_ctr,
; JSAMPARRAY output_buf);
;
%define output_width(b) (b)+8 ; JDIMENSION output_width
%define input_buf(b) (b)+12 ; JSAMPIMAGE input_buf
%define in_row_group_ctr(b) (b)+16 ; JDIMENSION in_row_group_ctr
%define output_buf(b) (b)+20 ; JSAMPARRAY output_buf
%define original_ebp ebp+0
%define wk(i) ebp-(WK_NUM-(i))*SIZEOF_XMMWORD ; xmmword wk[WK_NUM]
%define WK_NUM 3
%define gotptr wk(0)-SIZEOF_POINTER ; void * gotptr
align 16
global EXTN(jsimd_h2v1_merged_upsample_sse2)
EXTN(jsimd_h2v1_merged_upsample_sse2):
push ebp
mov eax,esp ; eax = original ebp
sub esp, byte 4
and esp, byte (-SIZEOF_XMMWORD) ; align to 128 bits
mov [esp],eax
mov ebp,esp ; ebp = aligned ebp
lea esp, [wk(0)]
pushpic eax ; make a room for GOT address
push ebx
; push ecx ; need not be preserved
; push edx ; need not be preserved
push esi
push edi
get_GOT ebx ; get GOT address
movpic POINTER [gotptr], ebx ; save GOT address
mov ecx, JDIMENSION [output_width(eax)] ; col
test ecx,ecx
jz near .return
push ecx
mov edi, JSAMPIMAGE [input_buf(eax)]
mov ecx, JDIMENSION [in_row_group_ctr(eax)]
mov esi, JSAMPARRAY [edi+0*SIZEOF_JSAMPARRAY]
mov ebx, JSAMPARRAY [edi+1*SIZEOF_JSAMPARRAY]
mov edx, JSAMPARRAY [edi+2*SIZEOF_JSAMPARRAY]
mov edi, JSAMPARRAY [output_buf(eax)]
mov esi, JSAMPROW [esi+ecx*SIZEOF_JSAMPROW] ; inptr0
mov ebx, JSAMPROW [ebx+ecx*SIZEOF_JSAMPROW] ; inptr1
mov edx, JSAMPROW [edx+ecx*SIZEOF_JSAMPROW] ; inptr2
mov edi, JSAMPROW [edi] ; outptr
pop ecx ; col
alignx 16,7
.columnloop:
movpic eax, POINTER [gotptr] ; load GOT address (eax)
movdqa xmm6, XMMWORD [ebx] ; xmm6=Cb(0123456789ABCDEF)
movdqa xmm7, XMMWORD [edx] ; xmm7=Cr(0123456789ABCDEF)
pxor xmm1,xmm1 ; xmm1=(all 0's)
pcmpeqw xmm3,xmm3
psllw xmm3,7 ; xmm3={0xFF80 0xFF80 0xFF80 0xFF80 ..}
movdqa xmm4,xmm6
punpckhbw xmm6,xmm1 ; xmm6=Cb(89ABCDEF)=CbH
punpcklbw xmm4,xmm1 ; xmm4=Cb(01234567)=CbL
movdqa xmm0,xmm7
punpckhbw xmm7,xmm1 ; xmm7=Cr(89ABCDEF)=CrH
punpcklbw xmm0,xmm1 ; xmm0=Cr(01234567)=CrL
paddw xmm6,xmm3
paddw xmm4,xmm3
paddw xmm7,xmm3
paddw xmm0,xmm3
; (Original)
; R = Y + 1.40200 * Cr
; G = Y - 0.34414 * Cb - 0.71414 * Cr
; B = Y + 1.77200 * Cb
;
; (This implementation)
; R = Y + 0.40200 * Cr + Cr
; G = Y - 0.34414 * Cb + 0.28586 * Cr - Cr
; B = Y - 0.22800 * Cb + Cb + Cb
movdqa xmm5,xmm6 ; xmm5=CbH
movdqa xmm2,xmm4 ; xmm2=CbL
paddw xmm6,xmm6 ; xmm6=2*CbH
paddw xmm4,xmm4 ; xmm4=2*CbL
movdqa xmm1,xmm7 ; xmm1=CrH
movdqa xmm3,xmm0 ; xmm3=CrL
paddw xmm7,xmm7 ; xmm7=2*CrH
paddw xmm0,xmm0 ; xmm0=2*CrL
pmulhw xmm6,[GOTOFF(eax,PW_MF0228)] ; xmm6=(2*CbH * -FIX(0.22800))
pmulhw xmm4,[GOTOFF(eax,PW_MF0228)] ; xmm4=(2*CbL * -FIX(0.22800))
pmulhw xmm7,[GOTOFF(eax,PW_F0402)] ; xmm7=(2*CrH * FIX(0.40200))
pmulhw xmm0,[GOTOFF(eax,PW_F0402)] ; xmm0=(2*CrL * FIX(0.40200))
paddw xmm6,[GOTOFF(eax,PW_ONE)]
paddw xmm4,[GOTOFF(eax,PW_ONE)]
psraw xmm6,1 ; xmm6=(CbH * -FIX(0.22800))
psraw xmm4,1 ; xmm4=(CbL * -FIX(0.22800))
paddw xmm7,[GOTOFF(eax,PW_ONE)]
paddw xmm0,[GOTOFF(eax,PW_ONE)]
psraw xmm7,1 ; xmm7=(CrH * FIX(0.40200))
psraw xmm0,1 ; xmm0=(CrL * FIX(0.40200))
paddw xmm6,xmm5
paddw xmm4,xmm2
paddw xmm6,xmm5 ; xmm6=(CbH * FIX(1.77200))=(B-Y)H
paddw xmm4,xmm2 ; xmm4=(CbL * FIX(1.77200))=(B-Y)L
paddw xmm7,xmm1 ; xmm7=(CrH * FIX(1.40200))=(R-Y)H
paddw xmm0,xmm3 ; xmm0=(CrL * FIX(1.40200))=(R-Y)L
movdqa XMMWORD [wk(0)], xmm6 ; wk(0)=(B-Y)H
movdqa XMMWORD [wk(1)], xmm7 ; wk(1)=(R-Y)H
movdqa xmm6,xmm5
movdqa xmm7,xmm2
punpcklwd xmm5,xmm1
punpckhwd xmm6,xmm1
pmaddwd xmm5,[GOTOFF(eax,PW_MF0344_F0285)]
pmaddwd xmm6,[GOTOFF(eax,PW_MF0344_F0285)]
punpcklwd xmm2,xmm3
punpckhwd xmm7,xmm3
pmaddwd xmm2,[GOTOFF(eax,PW_MF0344_F0285)]
pmaddwd xmm7,[GOTOFF(eax,PW_MF0344_F0285)]
paddd xmm5,[GOTOFF(eax,PD_ONEHALF)]
paddd xmm6,[GOTOFF(eax,PD_ONEHALF)]
psrad xmm5,SCALEBITS
psrad xmm6,SCALEBITS
paddd xmm2,[GOTOFF(eax,PD_ONEHALF)]
paddd xmm7,[GOTOFF(eax,PD_ONEHALF)]
psrad xmm2,SCALEBITS
psrad xmm7,SCALEBITS
packssdw xmm5,xmm6 ; xmm5=CbH*-FIX(0.344)+CrH*FIX(0.285)
packssdw xmm2,xmm7 ; xmm2=CbL*-FIX(0.344)+CrL*FIX(0.285)
psubw xmm5,xmm1 ; xmm5=CbH*-FIX(0.344)+CrH*-FIX(0.714)=(G-Y)H
psubw xmm2,xmm3 ; xmm2=CbL*-FIX(0.344)+CrL*-FIX(0.714)=(G-Y)L
movdqa XMMWORD [wk(2)], xmm5 ; wk(2)=(G-Y)H
mov al,2 ; Yctr
jmp short .Yloop_1st
alignx 16,7
.Yloop_2nd:
movdqa xmm0, XMMWORD [wk(1)] ; xmm0=(R-Y)H
movdqa xmm2, XMMWORD [wk(2)] ; xmm2=(G-Y)H
movdqa xmm4, XMMWORD [wk(0)] ; xmm4=(B-Y)H
alignx 16,7
.Yloop_1st:
movdqa xmm7, XMMWORD [esi] ; xmm7=Y(0123456789ABCDEF)
pcmpeqw xmm6,xmm6
psrlw xmm6,BYTE_BIT ; xmm6={0xFF 0x00 0xFF 0x00 ..}
pand xmm6,xmm7 ; xmm6=Y(02468ACE)=YE
psrlw xmm7,BYTE_BIT ; xmm7=Y(13579BDF)=YO
movdqa xmm1,xmm0 ; xmm1=xmm0=(R-Y)(L/H)
movdqa xmm3,xmm2 ; xmm3=xmm2=(G-Y)(L/H)
movdqa xmm5,xmm4 ; xmm5=xmm4=(B-Y)(L/H)
paddw xmm0,xmm6 ; xmm0=((R-Y)+YE)=RE=R(02468ACE)
paddw xmm1,xmm7 ; xmm1=((R-Y)+YO)=RO=R(13579BDF)
packuswb xmm0,xmm0 ; xmm0=R(02468ACE********)
packuswb xmm1,xmm1 ; xmm1=R(13579BDF********)
paddw xmm2,xmm6 ; xmm2=((G-Y)+YE)=GE=G(02468ACE)
paddw xmm3,xmm7 ; xmm3=((G-Y)+YO)=GO=G(13579BDF)
packuswb xmm2,xmm2 ; xmm2=G(02468ACE********)
packuswb xmm3,xmm3 ; xmm3=G(13579BDF********)
paddw xmm4,xmm6 ; xmm4=((B-Y)+YE)=BE=B(02468ACE)
paddw xmm5,xmm7 ; xmm5=((B-Y)+YO)=BO=B(13579BDF)
packuswb xmm4,xmm4 ; xmm4=B(02468ACE********)
packuswb xmm5,xmm5 ; xmm5=B(13579BDF********)
%if RGB_PIXELSIZE == 3 ; ---------------
; xmmA=(00 02 04 06 08 0A 0C 0E **), xmmB=(01 03 05 07 09 0B 0D 0F **)
; xmmC=(10 12 14 16 18 1A 1C 1E **), xmmD=(11 13 15 17 19 1B 1D 1F **)
; xmmE=(20 22 24 26 28 2A 2C 2E **), xmmF=(21 23 25 27 29 2B 2D 2F **)
; xmmG=(** ** ** ** ** ** ** ** **), xmmH=(** ** ** ** ** ** ** ** **)
punpcklbw xmmA,xmmC ; xmmA=(00 10 02 12 04 14 06 16 08 18 0A 1A 0C 1C 0E 1E)
punpcklbw xmmE,xmmB ; xmmE=(20 01 22 03 24 05 26 07 28 09 2A 0B 2C 0D 2E 0F)
punpcklbw xmmD,xmmF ; xmmD=(11 21 13 23 15 25 17 27 19 29 1B 2B 1D 2D 1F 2F)
movdqa xmmG,xmmA
movdqa xmmH,xmmA
punpcklwd xmmA,xmmE ; xmmA=(00 10 20 01 02 12 22 03 04 14 24 05 06 16 26 07)
punpckhwd xmmG,xmmE ; xmmG=(08 18 28 09 0A 1A 2A 0B 0C 1C 2C 0D 0E 1E 2E 0F)
psrldq xmmH,2 ; xmmH=(02 12 04 14 06 16 08 18 0A 1A 0C 1C 0E 1E -- --)
psrldq xmmE,2 ; xmmE=(22 03 24 05 26 07 28 09 2A 0B 2C 0D 2E 0F -- --)
movdqa xmmC,xmmD
movdqa xmmB,xmmD
punpcklwd xmmD,xmmH ; xmmD=(11 21 02 12 13 23 04 14 15 25 06 16 17 27 08 18)
punpckhwd xmmC,xmmH ; xmmC=(19 29 0A 1A 1B 2B 0C 1C 1D 2D 0E 1E 1F 2F -- --)
psrldq xmmB,2 ; xmmB=(13 23 15 25 17 27 19 29 1B 2B 1D 2D 1F 2F -- --)
movdqa xmmF,xmmE
punpcklwd xmmE,xmmB ; xmmE=(22 03 13 23 24 05 15 25 26 07 17 27 28 09 19 29)
punpckhwd xmmF,xmmB ; xmmF=(2A 0B 1B 2B 2C 0D 1D 2D 2E 0F 1F 2F -- -- -- --)
pshufd xmmH,xmmA,0x4E; xmmH=(04 14 24 05 06 16 26 07 00 10 20 01 02 12 22 03)
movdqa xmmB,xmmE
punpckldq xmmA,xmmD ; xmmA=(00 10 20 01 11 21 02 12 02 12 22 03 13 23 04 14)
punpckldq xmmE,xmmH ; xmmE=(22 03 13 23 04 14 24 05 24 05 15 25 06 16 26 07)
punpckhdq xmmD,xmmB ; xmmD=(15 25 06 16 26 07 17 27 17 27 08 18 28 09 19 29)
pshufd xmmH,xmmG,0x4E; xmmH=(0C 1C 2C 0D 0E 1E 2E 0F 08 18 28 09 0A 1A 2A 0B)
movdqa xmmB,xmmF
punpckldq xmmG,xmmC ; xmmG=(08 18 28 09 19 29 0A 1A 0A 1A 2A 0B 1B 2B 0C 1C)
punpckldq xmmF,xmmH ; xmmF=(2A 0B 1B 2B 0C 1C 2C 0D 2C 0D 1D 2D 0E 1E 2E 0F)
punpckhdq xmmC,xmmB ; xmmC=(1D 2D 0E 1E 2E 0F 1F 2F 1F 2F -- -- -- -- -- --)
punpcklqdq xmmA,xmmE ; xmmA=(00 10 20 01 11 21 02 12 22 03 13 23 04 14 24 05)
punpcklqdq xmmD,xmmG ; xmmD=(15 25 06 16 26 07 17 27 08 18 28 09 19 29 0A 1A)
punpcklqdq xmmF,xmmC ; xmmF=(2A 0B 1B 2B 0C 1C 2C 0D 1D 2D 0E 1E 2E 0F 1F 2F)
cmp ecx, byte SIZEOF_XMMWORD
jb short .column_st32
test edi, SIZEOF_XMMWORD-1
jnz short .out1
; --(aligned)-------------------
movntdq XMMWORD [edi+0*SIZEOF_XMMWORD], xmmA
movntdq XMMWORD [edi+1*SIZEOF_XMMWORD], xmmD
movntdq XMMWORD [edi+2*SIZEOF_XMMWORD], xmmF
jmp short .out0
.out1: ; --(unaligned)-----------------
movdqu XMMWORD [edi+0*SIZEOF_XMMWORD], xmmA
movdqu XMMWORD [edi+1*SIZEOF_XMMWORD], xmmD
movdqu XMMWORD [edi+2*SIZEOF_XMMWORD], xmmF
.out0:
add edi, byte RGB_PIXELSIZE*SIZEOF_XMMWORD ; outptr
sub ecx, byte SIZEOF_XMMWORD
jz near .endcolumn
add esi, byte SIZEOF_XMMWORD ; inptr0
dec al ; Yctr
jnz near .Yloop_2nd
add ebx, byte SIZEOF_XMMWORD ; inptr1
add edx, byte SIZEOF_XMMWORD ; inptr2
jmp near .columnloop
alignx 16,7
.column_st32:
lea ecx, [ecx+ecx*2] ; imul ecx, RGB_PIXELSIZE
cmp ecx, byte 2*SIZEOF_XMMWORD
jb short .column_st16
movdqu XMMWORD [edi+0*SIZEOF_XMMWORD], xmmA
movdqu XMMWORD [edi+1*SIZEOF_XMMWORD], xmmD
add edi, byte 2*SIZEOF_XMMWORD ; outptr
movdqa xmmA,xmmF
sub ecx, byte 2*SIZEOF_XMMWORD
jmp short .column_st15
.column_st16:
cmp ecx, byte SIZEOF_XMMWORD
jb short .column_st15
movdqu XMMWORD [edi+0*SIZEOF_XMMWORD], xmmA
add edi, byte SIZEOF_XMMWORD ; outptr
movdqa xmmA,xmmD
sub ecx, byte SIZEOF_XMMWORD
.column_st15:
; Store the lower 8 bytes of xmmA to the output when it has enough
; space.
cmp ecx, byte SIZEOF_MMWORD
jb short .column_st7
movq MMWORD [edi], xmmA
add edi, byte SIZEOF_MMWORD
sub ecx, byte SIZEOF_MMWORD
psrldq xmmA, SIZEOF_MMWORD
.column_st7:
; Store the lower 4 bytes of xmmA to the output when it has enough
; space.
cmp ecx, byte SIZEOF_DWORD
jb short .column_st3
movd DWORD [edi], xmmA
add edi, byte SIZEOF_DWORD
sub ecx, byte SIZEOF_DWORD
psrldq xmmA, SIZEOF_DWORD
.column_st3:
; Store the lower 2 bytes of eax to the output when it has enough
; space.
movd eax, xmmA
cmp ecx, byte SIZEOF_WORD
jb short .column_st1
mov WORD [edi], ax
add edi, byte SIZEOF_WORD
sub ecx, byte SIZEOF_WORD
shr eax, 16
.column_st1:
; Store the lower 1 byte of eax to the output when it has enough
; space.
test ecx, ecx
jz short .endcolumn
mov BYTE [edi], al
%else ; RGB_PIXELSIZE == 4 ; -----------
%ifdef RGBX_FILLER_0XFF
pcmpeqb xmm6,xmm6 ; xmm6=XE=X(02468ACE********)
pcmpeqb xmm7,xmm7 ; xmm7=XO=X(13579BDF********)
%else
pxor xmm6,xmm6 ; xmm6=XE=X(02468ACE********)
pxor xmm7,xmm7 ; xmm7=XO=X(13579BDF********)
%endif
; xmmA=(00 02 04 06 08 0A 0C 0E **), xmmB=(01 03 05 07 09 0B 0D 0F **)
; xmmC=(10 12 14 16 18 1A 1C 1E **), xmmD=(11 13 15 17 19 1B 1D 1F **)
; xmmE=(20 22 24 26 28 2A 2C 2E **), xmmF=(21 23 25 27 29 2B 2D 2F **)
; xmmG=(30 32 34 36 38 3A 3C 3E **), xmmH=(31 33 35 37 39 3B 3D 3F **)
punpcklbw xmmA,xmmC ; xmmA=(00 10 02 12 04 14 06 16 08 18 0A 1A 0C 1C 0E 1E)
punpcklbw xmmE,xmmG ; xmmE=(20 30 22 32 24 34 26 36 28 38 2A 3A 2C 3C 2E 3E)
punpcklbw xmmB,xmmD ; xmmB=(01 11 03 13 05 15 07 17 09 19 0B 1B 0D 1D 0F 1F)
punpcklbw xmmF,xmmH ; xmmF=(21 31 23 33 25 35 27 37 29 39 2B 3B 2D 3D 2F 3F)
movdqa xmmC,xmmA
punpcklwd xmmA,xmmE ; xmmA=(00 10 20 30 02 12 22 32 04 14 24 34 06 16 26 36)
punpckhwd xmmC,xmmE ; xmmC=(08 18 28 38 0A 1A 2A 3A 0C 1C 2C 3C 0E 1E 2E 3E)
movdqa xmmG,xmmB
punpcklwd xmmB,xmmF ; xmmB=(01 11 21 31 03 13 23 33 05 15 25 35 07 17 27 37)
punpckhwd xmmG,xmmF ; xmmG=(09 19 29 39 0B 1B 2B 3B 0D 1D 2D 3D 0F 1F 2F 3F)
movdqa xmmD,xmmA
punpckldq xmmA,xmmB ; xmmA=(00 10 20 30 01 11 21 31 02 12 22 32 03 13 23 33)
punpckhdq xmmD,xmmB ; xmmD=(04 14 24 34 05 15 25 35 06 16 26 36 07 17 27 37)
movdqa xmmH,xmmC
punpckldq xmmC,xmmG ; xmmC=(08 18 28 38 09 19 29 39 0A 1A 2A 3A 0B 1B 2B 3B)
punpckhdq xmmH,xmmG ; xmmH=(0C 1C 2C 3C 0D 1D 2D 3D 0E 1E 2E 3E 0F 1F 2F 3F)
cmp ecx, byte SIZEOF_XMMWORD
jb short .column_st32
test edi, SIZEOF_XMMWORD-1
jnz short .out1
; --(aligned)-------------------
movntdq XMMWORD [edi+0*SIZEOF_XMMWORD], xmmA
movntdq XMMWORD [edi+1*SIZEOF_XMMWORD], xmmD
movntdq XMMWORD [edi+2*SIZEOF_XMMWORD], xmmC
movntdq XMMWORD [edi+3*SIZEOF_XMMWORD], xmmH
jmp short .out0
.out1: ; --(unaligned)-----------------
movdqu XMMWORD [edi+0*SIZEOF_XMMWORD], xmmA
movdqu XMMWORD [edi+1*SIZEOF_XMMWORD], xmmD
movdqu XMMWORD [edi+2*SIZEOF_XMMWORD], xmmC
movdqu XMMWORD [edi+3*SIZEOF_XMMWORD], xmmH
.out0:
add edi, byte RGB_PIXELSIZE*SIZEOF_XMMWORD ; outptr
sub ecx, byte SIZEOF_XMMWORD
jz near .endcolumn
add esi, byte SIZEOF_XMMWORD ; inptr0
dec al ; Yctr
jnz near .Yloop_2nd
add ebx, byte SIZEOF_XMMWORD ; inptr1
add edx, byte SIZEOF_XMMWORD ; inptr2
jmp near .columnloop
alignx 16,7
.column_st32:
cmp ecx, byte SIZEOF_XMMWORD/2
jb short .column_st16
movdqu XMMWORD [edi+0*SIZEOF_XMMWORD], xmmA
movdqu XMMWORD [edi+1*SIZEOF_XMMWORD], xmmD
add edi, byte 2*SIZEOF_XMMWORD ; outptr
movdqa xmmA,xmmC
movdqa xmmD,xmmH
sub ecx, byte SIZEOF_XMMWORD/2
.column_st16:
cmp ecx, byte SIZEOF_XMMWORD/4
jb short .column_st15
movdqu XMMWORD [edi+0*SIZEOF_XMMWORD], xmmA
add edi, byte SIZEOF_XMMWORD ; outptr
movdqa xmmA,xmmD
sub ecx, byte SIZEOF_XMMWORD/4
.column_st15:
; Store two pixels (8 bytes) of xmmA to the output when it has enough
; space.
cmp ecx, byte SIZEOF_XMMWORD/8
jb short .column_st7
movq MMWORD [edi], xmmA
add edi, byte SIZEOF_XMMWORD/8*4
sub ecx, byte SIZEOF_XMMWORD/8
psrldq xmmA, SIZEOF_XMMWORD/8*4
.column_st7:
; Store one pixel (4 bytes) of xmmA to the output when it has enough
; space.
test ecx, ecx
jz short .endcolumn
movd DWORD [edi], xmmA
%endif ; RGB_PIXELSIZE ; ---------------
.endcolumn:
sfence ; flush the write buffer
.return:
pop edi
pop esi
; pop edx ; need not be preserved
; pop ecx ; need not be preserved
pop ebx
mov esp,ebp ; esp <- aligned ebp
pop esp ; esp <- original ebp
pop ebp
ret
; --------------------------------------------------------------------------
;
; Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
;
; GLOBAL(void)
; jsimd_h2v2_merged_upsample_sse2 (JDIMENSION output_width,
; JSAMPIMAGE input_buf,
; JDIMENSION in_row_group_ctr,
; JSAMPARRAY output_buf);
;
%define output_width(b) (b)+8 ; JDIMENSION output_width
%define input_buf(b) (b)+12 ; JSAMPIMAGE input_buf
%define in_row_group_ctr(b) (b)+16 ; JDIMENSION in_row_group_ctr
%define output_buf(b) (b)+20 ; JSAMPARRAY output_buf
align 16
global EXTN(jsimd_h2v2_merged_upsample_sse2)
EXTN(jsimd_h2v2_merged_upsample_sse2):
push ebp
mov ebp,esp
push ebx
; push ecx ; need not be preserved
; push edx ; need not be preserved
push esi
push edi
mov eax, POINTER [output_width(ebp)]
mov edi, JSAMPIMAGE [input_buf(ebp)]
mov ecx, JDIMENSION [in_row_group_ctr(ebp)]
mov esi, JSAMPARRAY [edi+0*SIZEOF_JSAMPARRAY]
mov ebx, JSAMPARRAY [edi+1*SIZEOF_JSAMPARRAY]
mov edx, JSAMPARRAY [edi+2*SIZEOF_JSAMPARRAY]
mov edi, JSAMPARRAY [output_buf(ebp)]
lea esi, [esi+ecx*SIZEOF_JSAMPROW]
push edx ; inptr2
push ebx ; inptr1
push esi ; inptr00
mov ebx,esp
push edi ; output_buf (outptr0)
push ecx ; in_row_group_ctr
push ebx ; input_buf
push eax ; output_width
call near EXTN(jsimd_h2v1_merged_upsample_sse2)
add esi, byte SIZEOF_JSAMPROW ; inptr01
add edi, byte SIZEOF_JSAMPROW ; outptr1
mov POINTER [ebx+0*SIZEOF_POINTER], esi
mov POINTER [ebx-1*SIZEOF_POINTER], edi
call near EXTN(jsimd_h2v1_merged_upsample_sse2)
add esp, byte 7*SIZEOF_DWORD
pop edi
pop esi
; pop edx ; need not be preserved
; pop ecx ; need not be preserved
pop ebx
pop ebp
ret
; For some reason, the OS X linker does not honor the request to align the
; segment unless we do this.
align 16
|
; void *zx_py2aaddr_fastcall(uchar y)
SECTION code_arch
PUBLIC _zx_py2aaddr_fastcall
_zx_py2aaddr_fastcall:
INCLUDE "arch/zx/display/z80/asm_zx_py2aaddr.asm"
|
; uint8_t hbios_e_de_hl(uint16_t func_device, uint16_t arg, void * buffer)
SECTION code_clib
SECTION code_arch
PUBLIC _hbios_e_de_hl
EXTERN asm_hbios_e
._hbios_e_de_hl
pop af
pop bc
pop de
pop hl
push hl
push de
push bc
push af
jp asm_hbios_e
|
/*
Copyright (c) 2005-2016, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford 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 HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _TESTACINARUNITMODELS_HPP_
#define _TESTACINARUNITMODELS_HPP_
#include <cxxtest/TestSuite.h>
#include "SimpleBalloonAcinarUnit.hpp"
#include "SimpleBalloonExplicitAcinarUnit.hpp"
#include "SigmoidalAcinarUnit.hpp"
#include "Swan2012AcinarUnit.hpp"
#include "TimeStepper.hpp"
#include "MathsCustomFunctions.hpp"
#include "OutputFileHandler.hpp"
#include "AbstractOdeSystem.hpp"
#include "OdeSystemInformation.hpp"
#include "BackwardEulerIvpOdeSolver.hpp"
#include <boost/math/tools/roots.hpp>
#include <boost/bind.hpp>
#include <iomanip>
//#include "PetscSetupAndFinalize.hpp"
//Class to benchmark sigmoidal solution against
class MySigmoidalOde : public AbstractOdeSystem
{
public:
MySigmoidalOde(double raw, double a, double b, double c, double d) : AbstractOdeSystem(1)
{
mpSystemInfo = OdeSystemInformation<MySigmoidalOde>::Instance();
mRaw = raw;
mA = a;
mB = b;
mC = c;
mD = d;
}
void EvaluateYDerivatives(double time, const std::vector<double>& rY,
std::vector<double>& rDY)
{
assert(rY[0] > mA);
//double pleural_pressure = -2400*(sin((M_PI)*time));
double pleural_pressure = -750 - 250*sin(2*M_PI*(time - 0.25));
rDY[0] = 1/mRaw*(-(mD*log(mB/(rY[0] - mA) - 1)) + mC + pleural_pressure);
}
double mRaw, mA, mB, mC, mD;
};
template<>
void OdeSystemInformation<MySigmoidalOde>::Initialise()
{
this->mVariableNames.push_back("V");
this->mVariableUnits.push_back("dimensionless");
this->mInitialConditions.push_back(2.3918/1e3);
this->mInitialised = true;
}
//Class to benchmark swan solution against
class MySwanOde : public AbstractOdeSystem
{
public:
MySwanOde(double raw, double a, double b, double xi) : AbstractOdeSystem(1)
{
mpSystemInfo = OdeSystemInformation<MySwanOde>::Instance();
mRaw = raw;
mA = a;
mB = b;
mXi = xi;
}
void EvaluateYDerivatives(double time, const std::vector<double>& rY,
std::vector<double>& rDY)
{
double pleural_pressure = -750 - 250*sin(2*M_PI*(time - 0.25));
double V0 = 1/1e3;
double lambda = std::pow(rY[0]/V0, 1.0/3.0);
double gamma = (3.0/4.0)*(3*mA + mB)*(lambda*lambda - 1)*(lambda*lambda - 1);
double Pe = mXi*std::exp(gamma)/(2.0*lambda)*(3*mA + mB)*(lambda*lambda -1);
rDY[0] = 1/mRaw*(-Pe - pleural_pressure);
}
double mRaw, mA, mB, mXi;
};
template<>
void OdeSystemInformation<MySwanOde>::Initialise()
{
this->mVariableNames.push_back("V");
this->mVariableUnits.push_back("dimensionless");
this->mInitialConditions.push_back(2.3918/1e3);
this->mInitialised = true;
}
class TestAcinarUnitModels: public CxxTest::TestSuite
{
public:
void TestSimpleBalloonAcinarUnitInspiration() throw (Exception)
{
double viscosity = 1.92e-5; //Pa s
double terminal_airway_radius = 0.05; //m
double terminal_airway_length = 0.02; //m
double terminal_airway_resistance = 8*viscosity*terminal_airway_length/(M_PI*SmallPow(terminal_airway_radius, 4));
SimpleBalloonAcinarUnit acinus;
acinus.SetAirwayPressure(0.0);
acinus.SetPleuralPressure(0.0);
acinus.SetFlow(0.0);
acinus.SetUndeformedVolume(0.0);
double compliance = 0.1/98.0665/1e3; //in m^3 / pa. Converted from 0.1 L/cmH2O per lung.
acinus.SetCompliance(compliance);
acinus.SetTerminalBronchioleResistance(terminal_airway_resistance);
acinus.SolveAndUpdateState(0.0, 0.2);
TS_ASSERT_DELTA(acinus.GetFlow(), 0.0, 1e-6); //With no pressure change we expect no flow
TS_ASSERT_DELTA(acinus.GetVolume(), 0.0, 1e-2); //With no pressure change we expect no volume change
TimeStepper time_stepper(0.0, 1.0, 0.0001);
acinus.SetAirwayPressure(0.0);
double pleural_pressure = 0.0;
double ode_volume = 0.0;
double flow_integral = 0.0;
while (!time_stepper.IsTimeAtEnd())
{
pleural_pressure = - 2400*(sin((M_PI)*(time_stepper.GetNextTime())));
//Solve the acinar problem coupled to a single bronchiole
acinus.SetPleuralPressure(pleural_pressure);
//acinus.SolveAndUpdateState(time_stepper.GetTime(), time_stepper.GetNextTime());
acinus.ComputeExceptFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
double airway_pressure = acinus.GetAirwayPressure();
double flow = -airway_pressure/terminal_airway_resistance;
flow_integral += (time_stepper.GetNextTime() - time_stepper.GetTime())*flow;
acinus.SetFlow(flow);
acinus.UpdateFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
//Solve the corresponding ODE problem using backward Euler for testing
// dv/dt = -1/R*(V/C - (Paw - Ppl))
// Discretise using backward euler and rearrange to obtain the below
double dt = time_stepper.GetNextTimeStep();
ode_volume = (ode_volume - dt*pleural_pressure/terminal_airway_resistance)/(1 + dt/(terminal_airway_resistance*compliance));
TS_ASSERT_DELTA(acinus.GetVolume(), ode_volume, 1e-8);
time_stepper.AdvanceOneTimeStep();
}
TS_ASSERT_DELTA(ode_volume, -compliance*pleural_pressure, 1e-8);
TS_ASSERT_DELTA(acinus.GetVolume(), -compliance*pleural_pressure, 1e-8);
TS_ASSERT_DELTA(flow_integral, -compliance*pleural_pressure, 1e-8);
}
void TestSimpleBalloonExplicitAcinarUnitInspiration() throw (Exception)
{
double viscosity = 1.92e-5; //Pa s
double terminal_airway_radius = 0.05; //m
double terminal_airway_length = 0.02; //m
double terminal_airway_resistance = 8*viscosity*terminal_airway_length/(M_PI*SmallPow(terminal_airway_radius, 4));
SimpleBalloonExplicitAcinarUnit acinus;
acinus.SetAirwayPressure(0.0);
acinus.SetPleuralPressure(0.0);
acinus.SetFlow(0.0);
acinus.SetUndeformedVolume(0.0);
double compliance = 0.1/98.0665/1e3; //in m^3 / pa. Converted from 0.1 L/cmH2O per lung.
acinus.SetCompliance(compliance);
acinus.SetTerminalBronchioleResistance(terminal_airway_resistance);
acinus.SolveAndUpdateState(0.0, 0.2);
TS_ASSERT_DELTA(acinus.GetFlow(), 0.0, 1e-6); //With no pressure change we expect no flow
TS_ASSERT_DELTA(acinus.GetVolume(), 0.0, 1e-2); //With no pressure change we expect no volume change
//Uncomment below to find time step bound
//std::cout << 2*terminal_airway_radius*compliance << std::endl; abort();
TimeStepper time_stepper(0.0, 0.01, 0.0000001); //Only solve for a very short time due to dt restriction, this test is mostly for coverage
acinus.SetAirwayPressure(0.0);
double pleural_pressure = 0.0;
double ode_volume = 0.0;
double flow_integral = 0.0;
while (!time_stepper.IsTimeAtEnd())
{
pleural_pressure = - 2400*(sin((M_PI)*(time_stepper.GetNextTime())));
//Solve the acinar problem coupled to a single bronchiole
acinus.SetPleuralPressure(pleural_pressure);
acinus.ComputeExceptFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
double airway_pressure = acinus.GetAirwayPressure();
double flow = -airway_pressure/terminal_airway_resistance;
flow_integral += (time_stepper.GetNextTime() - time_stepper.GetTime())*flow;
acinus.SetFlow(flow);
acinus.UpdateFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
//Solve the corresponding ODE problem using backward Euler for testing
// dv/dt = -1/R*(V/C - (Paw - Ppl))
// Discretise using backward euler and rearrange to obtain the below
double dt = time_stepper.GetNextTimeStep();
ode_volume = (ode_volume - dt*pleural_pressure/terminal_airway_resistance)/(1 + dt/(terminal_airway_resistance*compliance));
TS_ASSERT_DELTA(acinus.GetVolume(), ode_volume, 1e-8);
time_stepper.AdvanceOneTimeStep();
}
}
void TestSigmoidalAcinarUnitInspiration() throw (Exception)
{
double viscosity = 1.92e-5; //Pa s
double terminal_airway_radius = 0.05; //m
double terminal_airway_length = 0.02; //m
double terminal_airway_resistance = 8*viscosity*terminal_airway_length/(M_PI*SmallPow(terminal_airway_radius, 4));
double a = 2/1e3; //m^3 (RV 2L)
double b = (6 - 2)/1e3; //m^3 (TLC 6L, RV 2L)
double c = 667; //Pa (6.8 cmH2O)
double d = 300; //Pa (3.8 cmH2O)
SigmoidalAcinarUnit acinus;
acinus.SetA(a);
acinus.SetB(b);
acinus.SetC(c);
acinus.SetD(d);
acinus.SetAirwayPressure(0.0);
acinus.SetPleuralPressure(-1.0);
acinus.SetFlow(0.0);
acinus.SetUndeformedVolume(3.4573/1e3); //Nearly completely deflated acinus. Model is invalid if it becomes fully deflated.
acinus.SetTerminalBronchioleResistance(terminal_airway_resistance);
acinus.SolveAndUpdateState(0.0, 0.2);
TS_ASSERT_DELTA(acinus.GetFlow(), 0.0, 1e-6); //With no pressure change we expect no flow
TS_ASSERT_DELTA(acinus.GetVolume(), 0.0, 1e-2); //With no pressure change we expect no volume change
//Setup corresponding ODE for testing.
MySigmoidalOde my_ode(terminal_airway_resistance,a,b,c,d);
BackwardEulerIvpOdeSolver euler_solver(1);
std::vector<double> initial_condition;
initial_condition.push_back(3.4573/1e3);
OdeSolution solutions = euler_solver.Solve(&my_ode, initial_condition, 0, 2, 0.001, 0.001);
TimeStepper time_stepper(0.0, 2.0, 0.001);
unsigned i = 0;
while (!time_stepper.IsTimeAtEnd())
{
double pleural_pressure = -750 - 250*sin(2*M_PI*(time_stepper.GetNextTime() - 0.25));
TS_ASSERT_DELTA(acinus.GetVolume(), solutions.rGetSolutions()[i][0], 1e-5);
++i;
acinus.SetPleuralPressure(pleural_pressure);
acinus.ComputeExceptFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
double airway_pressure = acinus.GetAirwayPressure();
double flow = -airway_pressure/terminal_airway_resistance;
acinus.SetFlow(flow);
acinus.UpdateFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
time_stepper.AdvanceOneTimeStep();
}
}
void TestSwan2012AcinarUnit() throw(Exception)
{
Swan2012AcinarUnit acinus;
//Test against corresponding ODE
double viscosity = 1.92e-5; //Pa s
double terminal_airway_radius = 0.005; //m
double terminal_airway_length = 0.02; //m
double terminal_airway_resistance = 8*viscosity*terminal_airway_length/(M_PI*SmallPow(terminal_airway_radius, 4));
acinus.SetFlow(0.0);
acinus.SetAirwayPressure(0.0);
acinus.SetPleuralPressure(0.0);
acinus.SetUndeformedVolume(1/1e3);
acinus.SetStretchRatio(std::pow(2, 1.0/3.0));
acinus.SetTerminalBronchioleResistance(terminal_airway_resistance);
MySwanOde my_ode(terminal_airway_resistance, 0.433, -0.611, 2500);
BackwardEulerIvpOdeSolver euler_solver(1);
std::vector<double> initial_condition;
initial_condition.push_back(2/1e3);
OdeSolution solutions = euler_solver.Solve(&my_ode, initial_condition, 0, 2, 0.001, 0.001);
TimeStepper time_stepper(0.0, 2.0, 0.001);
unsigned i = 0;
while (!time_stepper.IsTimeAtEnd())
{
double pleural_pressure = -750 - 250*sin(2*M_PI*(time_stepper.GetNextTime() - 0.25));
TS_ASSERT_DELTA(acinus.GetVolume(), solutions.rGetSolutions()[i][0], 1e-5);
++i;
acinus.SetPleuralPressure(pleural_pressure);
acinus.ComputeExceptFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
double airway_pressure = acinus.GetAirwayPressure();
double flow = -airway_pressure/terminal_airway_resistance;
acinus.SetFlow(flow);
acinus.UpdateFlow(time_stepper.GetTime(), time_stepper.GetNextTime());
time_stepper.AdvanceOneTimeStep();
}
}
};
#endif /*_TESTACINARUNITMODELS_HPP_*/
|
; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
; kernel.asm
; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
; Forrest Yu, 2005
; ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
%include "sconst.inc"
; 导入函数
extern cstart
extern kernel_main
extern exception_handler
extern spurious_irq
extern clock_handler
extern disp_str
extern delay
; 导入全局变量
extern gdt_ptr
extern idt_ptr
extern p_proc_ready
extern tss
extern disp_pos
extern k_reenter
bits 32
[SECTION .data]
clock_int_msg db "^", 0
[SECTION .bss]
StackSpace resb 2 * 1024
StackTop: ; 栈顶
[section .text] ; 代码在此
global _start ; 导出 _start
global restart
global divide_error
global single_step_exception
global nmi
global breakpoint_exception
global overflow
global bounds_check
global inval_opcode
global copr_not_available
global double_fault
global copr_seg_overrun
global inval_tss
global segment_not_present
global stack_exception
global general_protection
global page_fault
global copr_error
global hwint00
global hwint01
global hwint02
global hwint03
global hwint04
global hwint05
global hwint06
global hwint07
global hwint08
global hwint09
global hwint10
global hwint11
global hwint12
global hwint13
global hwint14
global hwint15
_start:
; 此时内存看上去是这样的(更详细的内存情况在 LOADER.ASM 中有说明):
; ┃ ┃
; ┃ ... ┃
; ┣━━━━━━━━━━━━━━━━━━┫
; ┃■■■■■■Page Tables■■■■■■┃
; ┃■■■■■(大小由LOADER决定)■■■■┃ PageTblBase
; 00101000h ┣━━━━━━━━━━━━━━━━━━┫
; ┃■■■■Page Directory Table■■■■┃ PageDirBase = 1M
; 00100000h ┣━━━━━━━━━━━━━━━━━━┫
; ┃□□□□ Hardware Reserved □□□□┃ B8000h ← gs
; 9FC00h ┣━━━━━━━━━━━━━━━━━━┫
; ┃■■■■■■■LOADER.BIN■■■■■■┃ somewhere in LOADER ← esp
; 90000h ┣━━━━━━━━━━━━━━━━━━┫
; ┃■■■■■■■KERNEL.BIN■■■■■■┃
; 80000h ┣━━━━━━━━━━━━━━━━━━┫
; ┃■■■■■■■■KERNEL■■■■■■■┃ 30400h ← KERNEL 入口 (KernelEntryPointPhyAddr)
; 30000h ┣━━━━━━━━━━━━━━━━━━┫
; ┋ ... ┋
; ┋ ┋
; 0h ┗━━━━━━━━━━━━━━━━━━┛ ← cs, ds, es, fs, ss
;
;
; GDT 以及相应的描述符是这样的:
;
; Descriptors Selectors
; ┏━━━━━━━━━━━━━━━━━━┓
; ┃ Dummy Descriptor ┃
; ┣━━━━━━━━━━━━━━━━━━┫
; ┃ DESC_FLAT_C (0~4G) ┃ 8h = cs
; ┣━━━━━━━━━━━━━━━━━━┫
; ┃ DESC_FLAT_RW (0~4G) ┃ 10h = ds, es, fs, ss
; ┣━━━━━━━━━━━━━━━━━━┫
; ┃ DESC_VIDEO ┃ 1Bh = gs
; ┗━━━━━━━━━━━━━━━━━━┛
;
; 注意! 在使用 C 代码的时候一定要保证 ds, es, ss 这几个段寄存器的值是一样的
; 因为编译器有可能编译出使用它们的代码, 而编译器默认它们是一样的. 比如串拷贝操作会用到 ds 和 es.
;
;
; 把 esp 从 LOADER 挪到 KERNEL
mov esp, StackTop ; 堆栈在 bss 段中
mov dword [disp_pos], 0
sgdt [gdt_ptr] ; cstart() 中将会用到 gdt_ptr
call cstart ; 在此函数中改变了gdt_ptr,让它指向新的GDT
lgdt [gdt_ptr] ; 使用新的GDT
lidt [idt_ptr]
jmp SELECTOR_KERNEL_CS:csinit
csinit: ; “这个跳转指令强制使用刚刚初始化的结构”——<<OS:D&I 2nd>> P90.
;jmp 0x40:0
;ud2
xor eax, eax
mov ax, SELECTOR_TSS
ltr ax
;sti
jmp kernel_main
;hlt
; 中断和异常 -- 硬件中断
; ---------------------------------
%macro hwint_master 1
push %1
call spurious_irq
add esp, 4
hlt
%endmacro
ALIGN 16
hwint00: ; Interrupt routine for irq 0 (the clock).
sub esp, 4
pushad ; `.
push ds ; |
push es ; | 保存原寄存器值
push fs ; |
push gs ; /
mov dx, ss
mov ds, dx
mov es, dx
inc byte [gs:0] ; 改变屏幕第 0 行, 第 0 列的字符
mov al, EOI ; `. reenable
out INT_M_CTL, al ; / master 8259
inc dword [k_reenter]
cmp dword [k_reenter], 0
jne .re_enter
mov esp, StackTop ; 切到内核栈
sti
push 0
call clock_handler
add esp, 4
cli
mov esp, [p_proc_ready] ; 离开内核栈
lldt [esp + P_LDT_SEL]
lea eax, [esp + P_STACKTOP]
mov dword [tss + TSS3_S_SP0], eax
.re_enter: ; 如果(k_reenter != 0),会跳转到这里
dec dword [k_reenter]
pop gs ; `.
pop fs ; |
pop es ; | 恢复原寄存器值
pop ds ; |
popad ; /
add esp, 4
iretd
ALIGN 16
hwint01: ; Interrupt routine for irq 1 (keyboard)
hwint_master 1
ALIGN 16
hwint02: ; Interrupt routine for irq 2 (cascade!)
hwint_master 2
ALIGN 16
hwint03: ; Interrupt routine for irq 3 (second serial)
hwint_master 3
ALIGN 16
hwint04: ; Interrupt routine for irq 4 (first serial)
hwint_master 4
ALIGN 16
hwint05: ; Interrupt routine for irq 5 (XT winchester)
hwint_master 5
ALIGN 16
hwint06: ; Interrupt routine for irq 6 (floppy)
hwint_master 6
ALIGN 16
hwint07: ; Interrupt routine for irq 7 (printer)
hwint_master 7
; ---------------------------------
%macro hwint_slave 1
push %1
call spurious_irq
add esp, 4
hlt
%endmacro
; ---------------------------------
ALIGN 16
hwint08: ; Interrupt routine for irq 8 (realtime clock).
hwint_slave 8
ALIGN 16
hwint09: ; Interrupt routine for irq 9 (irq 2 redirected)
hwint_slave 9
ALIGN 16
hwint10: ; Interrupt routine for irq 10
hwint_slave 10
ALIGN 16
hwint11: ; Interrupt routine for irq 11
hwint_slave 11
ALIGN 16
hwint12: ; Interrupt routine for irq 12
hwint_slave 12
ALIGN 16
hwint13: ; Interrupt routine for irq 13 (FPU exception)
hwint_slave 13
ALIGN 16
hwint14: ; Interrupt routine for irq 14 (AT winchester)
hwint_slave 14
ALIGN 16
hwint15: ; Interrupt routine for irq 15
hwint_slave 15
; 中断和异常 -- 异常
divide_error:
push 0xFFFFFFFF ; no err code
push 0 ; vector_no = 0
jmp exception
single_step_exception:
push 0xFFFFFFFF ; no err code
push 1 ; vector_no = 1
jmp exception
nmi:
push 0xFFFFFFFF ; no err code
push 2 ; vector_no = 2
jmp exception
breakpoint_exception:
push 0xFFFFFFFF ; no err code
push 3 ; vector_no = 3
jmp exception
overflow:
push 0xFFFFFFFF ; no err code
push 4 ; vector_no = 4
jmp exception
bounds_check:
push 0xFFFFFFFF ; no err code
push 5 ; vector_no = 5
jmp exception
inval_opcode:
push 0xFFFFFFFF ; no err code
push 6 ; vector_no = 6
jmp exception
copr_not_available:
push 0xFFFFFFFF ; no err code
push 7 ; vector_no = 7
jmp exception
double_fault:
push 8 ; vector_no = 8
jmp exception
copr_seg_overrun:
push 0xFFFFFFFF ; no err code
push 9 ; vector_no = 9
jmp exception
inval_tss:
push 10 ; vector_no = A
jmp exception
segment_not_present:
push 11 ; vector_no = B
jmp exception
stack_exception:
push 12 ; vector_no = C
jmp exception
general_protection:
push 13 ; vector_no = D
jmp exception
page_fault:
push 14 ; vector_no = E
jmp exception
copr_error:
push 0xFFFFFFFF ; no err code
push 16 ; vector_no = 10h
jmp exception
exception:
call exception_handler
add esp, 4*2 ; 让栈顶指向 EIP,堆栈中从顶向下依次是:EIP、CS、EFLAGS
hlt
; ====================================================================================
; restart
; ====================================================================================
restart:
mov esp, [p_proc_ready]
lldt [esp + P_LDT_SEL]
lea eax, [esp + P_STACKTOP]
mov dword [tss + TSS3_S_SP0], eax
pop gs
pop fs
pop es
pop ds
popad
add esp, 4
iretd
|
dnl HP-PA mpn_lshift -- Shift a number left.
dnl Copyright 1992, 1994, 2000, 2001, 2002 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU Lesser General Public License as published
dnl by the Free Software Foundation; either version 3 of the License, or (at
dnl your option) any later version.
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
dnl License for more details.
dnl You should have received a copy of the GNU Lesser General Public License
dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/.
include(`../config.m4')
C INPUT PARAMETERS
C res_ptr gr26
C s_ptr gr25
C size gr24
C cnt gr23
ASM_START()
PROLOGUE(mpn_lshift)
sh2add %r24,%r25,%r25
sh2add %r24,%r26,%r26
ldws,mb -4(0,%r25),%r22
subi 32,%r23,%r1
mtsar %r1
addib,= -1,%r24,L(0004)
vshd %r0,%r22,%r28 C compute carry out limb
ldws,mb -4(0,%r25),%r29
addib,= -1,%r24,L(0002)
vshd %r22,%r29,%r20
LDEF(loop)
ldws,mb -4(0,%r25),%r22
stws,mb %r20,-4(0,%r26)
addib,= -1,%r24,L(0003)
vshd %r29,%r22,%r20
ldws,mb -4(0,%r25),%r29
stws,mb %r20,-4(0,%r26)
addib,<> -1,%r24,L(loop)
vshd %r22,%r29,%r20
LDEF(0002)
stws,mb %r20,-4(0,%r26)
vshd %r29,%r0,%r20
bv 0(%r2)
stw %r20,-4(0,%r26)
LDEF(0003)
stws,mb %r20,-4(0,%r26)
LDEF(0004)
vshd %r22,%r0,%r20
bv 0(%r2)
stw %r20,-4(0,%r26)
EPILOGUE()
|
; A277267: Minimum number of single-direction edges in leveled binary trees with n nodes.
; Submitted by Jon Maiga
; 0,0,1,1,1,2,3,3,3,3,3,4,5,6,7,7,7,7,7,7,7,7,7,8,9,10,11,12,13,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,32,33,34,35,36
lpb $0
add $1,1
add $1,$2
trn $0,$1
add $0,$2
mov $2,$1
lpe
|
; A288876: a(n) = binomial(n+4, n)^2. Square of the fifth diagonal sequence of A007318 (Pascal). Fifth diagonal sequence of A008459.
; 1,25,225,1225,4900,15876,44100,108900,245025,511225,1002001,1863225,3312400,5664400,9363600,15023376,23474025,35820225,53509225,78411025,112911876,160022500,223502500,308002500,419225625,564110001,751034025,990046225,1293121600,1674446400,2150733376
mov $1,-5
bin $1,$0
pow $1,2
mov $0,$1
|
global main
extern printf
extern scanf
extern getchar
section .text
main:
Entry_main:
push ebp ;Store base pointer
mov ebp, esp ;Create new base pointer
sub esp, 60
push Label0 ;Push address of string literal to stack
push stringFrmt ;Push format string for printf
call printf
add esp, 8
lea eax, [ebp - 60] ;Load address into eax
push eax
push intFrmtIn
call scanf ;Retrieve input from user
add esp, 8 ;Remove arguments from stack
Label1: call getchar ;Remove characters until \n
cmp eax, 0xA
jne Label1 ;If the character isn't \n, continue removing
push Label2 ;Push address of string literal to stack
push stringFrmt ;Push format string for printf
call printf
add esp, 8
lea eax, [ebp - 56] ;Load address into eax
push eax
push intFrmtIn
call scanf ;Retrieve input from user
add esp, 8 ;Remove arguments from stack
Label3: call getchar ;Remove characters until \n
cmp eax, 0xA
jne Label3 ;If the character isn't \n, continue removing
push 0 ;Push int literal to stack
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to esi
pop dword [esi] ;Pop expression to address in esi
Label4: ;Begin compiling for expression
push 9 ;Push int literal to stack
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to counter variable
mov dword eax, [esi]
pop ebx ;Remove for-condition for comparison
cmp eax, ebx
jg Label5
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
sub esp, 4 ;Make room for file descriptor later
lea eax, [ebp - 56] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
lea eax, [ebp - 60] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
mov eax, 5 ;Move sys_open call to eax
mov ebx, randIn ;filename to ebx
mov ecx, 0 ;Permissions are read-only
int 0x80 ;syscall
mov [esp + 8], eax ;Store file descriptor
mov ebx, eax ;Move file descriptor to ebx
mov eax, 3 ;Move sys_read call to eax
sub esp, 4 ;Make room for read integer
mov ecx, esp ;Make input pointer esp
mov edx, 4 ;Input 4 bytes
int 0x80 ;syscall
mov eax, [esp + 4] ;Move upper bound to eax
mov ebx, [esp + 8] ;Move lower bound to ebx
sub eax, ebx ;Calculate randint range
push eax ;Push range to stack
mov ebx, 0
cmp eax, ebx ;Test if the range is 0
je Label7 ;If it is, jump to the end
mov eax, [esp + 4] ;Move random int to eax
mov ebx, [esp] ;Move range to ebx
cdq
idiv ebx
mov eax, edx
mov ebx, 0
cmp eax, ebx ;Compare if the result is negative
jge Label7 ;If it's not, jump to the end
mov ebx, [esp] ;Move range to ebx
add eax, ebx ;Increment result by range
Label7:
mov ebx, [esp + 12] ;Move lower bound to ebx
add eax, ebx ;Add lower bound to result
add esp, 16 ;Clean up stack
pop ebx ;Move file descriptor for /dev/urandom
push eax ;Push result to stack
mov eax, 6 ;sys_close
int 0x80
pop eax ;Reorder address and expression on stack
pop ecx ;Pop address to stack
push eax ;Push expression back to stack
push ecx ;Push address to stack
pop esi ;Pop address to esi
pop dword [esi] ;Pop expression to address in esi
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
push intFrmt ;Push format string for printf
call printf
add esp, 8
push NewLine ;Push newline to stack for printf
call printf
add esp, 4 ;Clean up stack after printf
Label6: ;End-of-loop maintenance
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi
mov dword eax, [esi]
inc eax ;Increment Loop Counter
mov [esi], eax ;Put updated Loop Counter into memory location
jmp Label4
Label5: ;Exit destination for loop
push 0 ;Push int literal to stack
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to esi
pop dword [esi] ;Pop expression to address in esi
Label8: ;Begin compiling for expression
push 9 ;Push int literal to stack
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to counter variable
mov dword eax, [esi]
pop ebx ;Remove for-condition for comparison
cmp eax, ebx
jg Label9
push 0 ;Push int literal to stack
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi ;Pop address to esi
pop dword [esi] ;Pop expression to address in esi
Label11: ;Begin compiling for expression
push 8 ;Push int literal to stack
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop ebx ;Remove operands from stack to addop
pop eax
sub eax, ebx ;Subtract operands
push eax ;Push result to stack
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi ;Pop address to counter variable
mov dword eax, [esi]
pop ebx ;Remove for-condition for comparison
cmp eax, ebx
jg Label12
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
push 1 ;Push int literal to stack
pop ebx ;Remove operands from stack to addop
pop eax
add eax, ebx ;Add operands
push eax ;Push result to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop ebx ;Remove operands from stack for comparison
pop eax
cmp eax, ebx
jg Label14 ;Push appropriate bool if based on comparison
push 0 ;Push 0 for false comparison
jmp Label15 ;Skip pushing 1
Label14: ;Label if comparison was true
push 1 ;Push 1 for true comparison
Label15: ;End of comparison
pop eax ;Remove bool from stack
mov ebx, 0
cmp eax, ebx ;Compare bool to 0
je Label16 ;If bool is 0, jump to the else clause
lea eax, [ebp - 52] ;Load address into eax
push eax
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
push 1 ;Push int literal to stack
pop ebx ;Remove operands from stack to addop
pop eax
add eax, ebx ;Add operands
push eax ;Push result to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop eax ;Reorder address and expression on stack
pop ecx ;Pop address to stack
push eax ;Push expression back to stack
push ecx ;Push address to stack
pop esi ;Pop address to esi
pop dword [esi] ;Pop expression to address in esi
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
push 1 ;Push int literal to stack
pop ebx ;Remove operands from stack to addop
pop eax
add eax, ebx ;Add operands
push eax ;Push result to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop eax ;Reorder address and expression on stack
pop ecx ;Pop address to stack
push eax ;Push expression back to stack
push ecx ;Push address to stack
pop esi ;Pop address to esi
pop dword [esi] ;Pop expression to address in esi
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
lea eax, [ebp - 52] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop eax ;Reorder address and expression on stack
pop ecx ;Pop address to stack
push eax ;Push expression back to stack
push ecx ;Push address to stack
pop esi ;Pop address to esi
pop dword [esi] ;Pop expression to address in esi
jmp Label17 ;Skip the else clause
Label16: ;Beginning of else clause
Label17: ;End of else clause
Label13: ;End-of-loop maintenance
lea eax, [ebp - 48] ;Load address into eax
push eax
pop esi
mov dword eax, [esi]
inc eax ;Increment Loop Counter
mov [esi], eax ;Put updated Loop Counter into memory location
jmp Label11
Label12: ;Exit destination for loop
Label10: ;End-of-loop maintenance
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi
mov dword eax, [esi]
inc eax ;Increment Loop Counter
mov [esi], eax ;Put updated Loop Counter into memory location
jmp Label8
Label9: ;Exit destination for loop
push Label18 ;Push address of string literal to stack
push stringFrmt ;Push format string for printf
call printf
add esp, 8
push NewLine ;Push newline to stack for printf
call printf
add esp, 4 ;Clean up stack after printf
push 0 ;Push int literal to stack
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to esi
pop dword [esi] ;Pop expression to address in esi
Label19: ;Begin compiling for expression
push 9 ;Push int literal to stack
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to counter variable
mov dword eax, [esi]
pop ebx ;Remove for-condition for comparison
cmp eax, ebx
jg Label20
lea eax, [ebp - 40] ;Load address into eax
push eax
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
pop ebx ;Pop offset expression to ebx
pop eax ;Pop head address to eax
lea eax, [eax + ebx*4] ;Calculate new offset
push eax ;Push new address to stack
pop esi ;Pop address to esi
push dword [esi] ;Push factor to stack
push intFrmt ;Push format string for printf
call printf
add esp, 8
push NewLine ;Push newline to stack for printf
call printf
add esp, 4 ;Clean up stack after printf
Label21: ;End-of-loop maintenance
lea eax, [ebp - 44] ;Load address into eax
push eax
pop esi
mov dword eax, [esi]
inc eax ;Increment Loop Counter
mov [esi], eax ;Put updated Loop Counter into memory location
jmp Label19
Label20: ;Exit destination for loop
push Label22 ;Push address of string literal to stack
push stringFrmt ;Push format string for printf
call printf
add esp, 8
push NewLine ;Push newline to stack for printf
call printf
add esp, 4 ;Clean up stack after printf
Exit_main:
mov esp, ebp
pop ebp
ret ;Return control to calling function
section .data
realFrmt: db "%f", 0 ;Print real without \n
intFrmt: db "%d", 0 ;Print int without \n
stringFrmt: db "%s", 0 ;Print string without \n
realFrmtIn: db "%lf", 0 ;Read real
intFrmtIn: db "%i", 0 ;Read int
stringFrmtIn: db "%s", 0 ;Read string
NewLine: db 0xA, 0 ;Print NewLine
randIn: db "/dev/urandom" ;File for random bytes
negone: dq -1.0 ;Negative one
Label0: db "Enter the upper bound: ", 0
Label2: db "Enter the lower bound: ", 0
Label18: db "------", 0
Label22: db "", 0
section .bss
|
; $Id: zero.asm 69111 2017-10-17 14:26:02Z vboxsync $
;; @file
; IPRT - Zero Memory.
;
;
; Copyright (C) 2013-2017 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
;*******************************************************************************
;* Header Files *
;*******************************************************************************
%include "iprt/asmdefs.mac"
; Putting it in the code segment/section for now.
BEGINCODE
;;
; 64KB of zero memory with various sized labels.
;
EXPORTEDNAME_EX g_abRTZeroPage, object
EXPORTEDNAME_EX g_abRTZero4K, object
EXPORTEDNAME_EX g_abRTZero8K, object
EXPORTEDNAME_EX g_abRTZero16K, object
EXPORTEDNAME_EX g_abRTZero32K, object
EXPORTEDNAME_EX g_abRTZero64K, object
times 0x10000/(16*4) dd 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0
%ifdef ASM_FORMAT_ELF
size g_abRTZeroPage _4K
size g_abRTZero4K _4K
size g_abRTZero8K _8K
size g_abRTZero16K _16K
size g_abRTZero32K _32K
size g_abRTZero64K _64K
%endif
|
.text
.intel_syntax noprefix
.literal16
.p2align 4
MASK12:
.long 0
.long 0xffffffff
.long 0xffffffff
.long 0
.text
.globl __Z22matrixTransformG3_SIMDPiS_ii
.p2align 4, 0x90
__Z22matrixTransformG3_SIMDPiS_ii:
push rbp
mov rbp, rsp
push rbx
# деление L / 3
mov r9, rdx
imul rax, r9, 0x55555556
mov rdx, rax
shr rdx, 63
shr rax, 32
add rax, rdx
mov r11, rax # r11 = blockLength
add rax, rax # rax = blockLength * 2
mov r8d, ecx # r8d = Q
add rsi, 32 # rsi - newMatrix
shl r9, 2 # r9 = L * 4
lea rcx, [rdi + 4*rax] # matrix[blockLength * 2] или matrix+4*blockLength*2
lea rax, [rdi + 4*r11] # matrix[blockLength * 1] или matrix+4*blockLength
xor r10d, r10d
pxor xmm10, xmm10
movdqa xmm12, xmmword ptr [rip + MASK12] # xmm12 = [0,0xffffffff,0xffffffff,0]
.p2align 4, 0x90
# начало цикла for(int q = 0; q < Q; q++)
LOOP_ROWS:
mov rdx, rsi
xor ebx, ebx
.p2align 4, 0x90
# начало цикла for(int i = 0; i < blockLength; i += 4)
LOOP_BLOCKS:
movdqa xmm0, xmmword ptr [rdi + 4*rbx] # matrix[i] или matrix+4*i
movdqa xmm1, xmmword ptr [rax + 4*rbx] # matrix[i+blockLength] или matrix+4*i+4*blockLength
movdqa xmm2, xmmword ptr [rcx + 4*rbx] # matrix[i+blockLength*2] или matrix+4*i+4*blockLength*2
movdqa xmm3, xmm1
punpckldq xmm3, xmm10 # xmm3 = xmm1[0],0000000,xmm1[1],0000000
movdqa xmm4, xmm2
pslldq xmm4, 12 # xmm4 = 0000000,0000000,0000000,xmm2[0]
movdqa xmm5, xmm0
punpcklqdq xmm5, xmm3 # xmm5 = xmm0[0],xmm0[1],xmm3[0],xmm3[1]
# xmm5 = xmm0[0],xmm0[1],xmm1[0],0000000
por xmm5, xmm4 # xmm5 = xmm0[0],xmm0[1],xmm1[0],xmm2[0]
pshufd xmm3, xmm5, 120 # xmm3 = xmm5[0,2,3,1]
# xmm3 = xmm0[0],xmm1[0],xmm2[0],xmm0[1]
pxor xmm4, xmm4
punpckhdq xmm4, xmm1 # xmm4 = 0000000,xmm1[2],0000000,xmm1[3]
pand xmm1, xmm12 # xmm1 = 0000000,xmm1[1],xmm1[2],0000000
movq xmm5, xmm2 # xmm5 = xmm2[0],xmm2[1],0000000,0000000
psrldq xmm5, 4 # xmm5 = xmm2[1],0000000,0000000,0000000
movdqa xmm6, xmm0
movsd xmm6, xmm10 # xmm6 = 0000000,0000000,xmm0[2],xmm0[3]
pslldq xmm6, 4 # xmm6 = 0000000,0000000,0000000,xmm0[2]
por xmm6, xmm1 # xmm6 = 0000000,xmm1[1],xmm1[2],xmm0[2]
por xmm6, xmm5 # xmm6 = xmm2[1],xmm1[1],xmm1[2],xmm0[2]
pshufd xmm6, xmm6, 177 # xmm6 = xmm6[1,0,3,2]
# xmm6 = xmm1[1],xmm2[1],xmm0[2],xmm1[2]
movsd xmm2, xmm10 # xmm2 = 0000000,0000000,xmm2[2],xmm2[3]
psrldq xmm0, 12 # xmm0 = xmm0[3],0000000,0000000,0000000
por xmm0, xmm2 # xmm0 = xmm0[3],0000000,xmm2[2],xmm2[3]
psrldq xmm4, 8 # xmm4 = 0000000,xmm1[3],0000000,0000000
por xmm4, xmm0 # xmm4 = xmm0[3],xmm1[3],xmm2[2],xmm2[3]
pshufd xmm0, xmm4, 210 # xmm0 = xmm4[2,0,1,3]
# xmm0 = xmm2[2],xmm0[3],xmm1[3],xmm2[3]
movdqa xmmword ptr [rdx - 32], xmm3
movdqa xmmword ptr [rdx - 16], xmm6
movdqa xmmword ptr [rdx], xmm0
add rbx, 4 # i += 4
add rdx, 48 # newMatrix += G*i или newMatrix += 3*4*sizeof(int)
cmp rbx, r11
jl LOOP_BLOCKS
# конец цикла for(int i = 0; i < blockLength; i += 4)
inc r10
add rsi, r9
add rcx, r9
add rax, r9
add rdi, r9
cmp r10, r8
jne LOOP_ROWS
# конец цикла for (int q = 0; q < Q; q++)
pop rbx
pop rbp
ret
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r15
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x733c, %r11
nop
nop
nop
sub %r15, %r15
mov (%r11), %r12w
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_UC_ht+0xcdbc, %rsi
lea addresses_normal_ht+0x1749c, %rdi
add $60843, %r15
mov $67, %rcx
rep movsb
nop
nop
nop
nop
nop
sub %r11, %r11
lea addresses_D_ht+0x1459c, %r15
nop
xor $5435, %rbp
mov (%r15), %ecx
nop
nop
and $3745, %r12
lea addresses_WT_ht+0xc0ac, %rsi
lea addresses_A_ht+0xb8bc, %rdi
nop
add %rbx, %rbx
mov $26, %rcx
rep movsb
nop
sub %rcx, %rcx
lea addresses_normal_ht+0x401c, %rbx
nop
nop
nop
nop
nop
xor $38563, %r12
vmovups (%rbx), %ymm1
vextracti128 $0, %ymm1, %xmm1
vpextrq $0, %xmm1, %rbp
nop
sub $7842, %r11
lea addresses_A_ht+0x1033c, %rsi
nop
nop
nop
nop
cmp %rdi, %rdi
movw $0x6162, (%rsi)
nop
nop
add $6271, %rbx
lea addresses_normal_ht+0x1909e, %rsi
nop
nop
nop
nop
and $35459, %r11
mov $0x6162636465666768, %r12
movq %r12, (%rsi)
nop
nop
cmp $2019, %rsi
lea addresses_UC_ht+0x150d4, %rcx
nop
sub %rdi, %rdi
movb (%rcx), %r15b
nop
nop
nop
nop
add %r11, %r11
lea addresses_A_ht+0x11d68, %r11
nop
nop
inc %rbx
movl $0x61626364, (%r11)
nop
nop
and %rdi, %rdi
lea addresses_normal_ht+0x1ef2a, %rsi
nop
nop
nop
nop
nop
xor %rbx, %rbx
and $0xffffffffffffffc0, %rsi
movaps (%rsi), %xmm3
vpextrq $0, %xmm3, %r15
nop
nop
nop
nop
add $59440, %rsi
lea addresses_WT_ht+0x59de, %rsi
lea addresses_WC_ht+0x1873c, %rdi
nop
nop
nop
nop
add $50923, %r12
mov $66, %rcx
rep movsq
nop
nop
sub $17581, %rdi
lea addresses_A_ht+0x8b3c, %rbp
nop
nop
nop
nop
add %r11, %r11
movb (%rbp), %bl
nop
xor %r12, %r12
lea addresses_WC_ht+0x1fc4, %rsi
lea addresses_A_ht+0x1435c, %rdi
nop
cmp $45812, %r12
mov $2, %rcx
rep movsb
nop
xor $32285, %r11
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r15
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r15
push %r8
push %r9
push %rbx
push %rdi
push %rdx
// Store
lea addresses_PSE+0x1f33c, %r15
nop
nop
nop
nop
xor $57229, %rdi
movl $0x51525354, (%r15)
nop
nop
cmp %r8, %r8
// Store
lea addresses_A+0x589c, %r9
nop
nop
nop
nop
add %r11, %r11
movl $0x51525354, (%r9)
nop
nop
nop
nop
cmp $43798, %r11
// Faulty Load
lea addresses_UC+0x14b3c, %rdx
clflush (%rdx)
inc %r8
mov (%rdx), %r11w
lea oracles, %r9
and $0xff, %r11
shlq $12, %r11
mov (%r9,%r11,1), %r11
pop %rdx
pop %rdi
pop %rbx
pop %r9
pop %r8
pop %r15
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_UC', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_PSE', 'size': 4, 'AVXalign': True}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_A', 'size': 4, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_UC', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}}
{'src': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_D_ht', 'size': 4, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}}
{'src': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False}}
{'src': {'same': True, 'congruent': 3, 'NT': False, 'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': True}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': True, 'type': 'addresses_A_ht', 'size': 4, 'AVXalign': True}}
{'src': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': True}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}}
{'src': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_A_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}}
{'37': 21829}
37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37
*/
|
#include "GCAnimatedTexture.h"
#include "com/mojang/minecraftpe/client/renderer/texture/TextureGroup.h"
#include "com/mojang/minecraftpe/client/renderer/texture/TextureData.h"
#include "com/mojang/minecraftpe/client/renderer/texture/TextureAtlas.h"
#include "com/mojang/minecraftpe/client/renderer/texture/TextureAtlasTextureItem.h"
#include "com/mojang/minecraftpe/world/level/block/Block.h"
GTPipeline::GTPipeline(const std::string& main_texture) {
pixelCount = main_texture.width * main_texture.height * 4;
image = new char[pixelCount];
memcpy(image, main_texture.pixels, pixelCount);
}
void GTPipeline::addOperation(IVertexOperation op) {
ops.push_back(op);
}
void GTPipeline::add(vector<IVertexOperation> ops) {
this.ops.insert(std::end(this.ops), std::begin(ops), std::end(ops));
}
void GTPipeline::add(GTPipeline pl) {
this.ops.insert(std::end(this.ops), std::begin(pl.ops), std::end(pl.ops));
}
void GTPipeline::add(GTPipelineBuilder pl) {
this.ops.insert(std::end(this.ops), std::begin(pl.ops), std::end(pl.ops));
}
void GTPipeline::rebuild() {
}
void GTPipeline::render(frameBuffer) {
for(std::vector<IVertexOperation>::iterator it = this.ops.begin(); it != this.ops.end(); ++it) {
*it->operate(image, pixelCount);
}
memcpy(frameBuffer, image);
} |
Vs_BattlefieldTypical: .include "PRG/levels/2PVs/Typical"
Vs_Unused: .include "PRG/levels/2PVs/Unused"
Vs_BattlefieldLadders: .include "PRG/levels/2PVs/Ladders"
Vs_BattlefieldFountain: .include "PRG/levels/2PVs/Fountain"
|
; A341523: Number of prime factors (with multiplicity) shared by n and sigma(n): a(n) = bigomega(gcd(n, sigma(n))).
; 0,0,0,0,0,2,0,0,0,1,0,2,0,1,1,0,0,1,0,1,0,1,0,3,0,1,0,3,0,2,0,0,1,1,0,0,0,1,0,2,0,2,0,2,1,1,0,2,0,0,1,1,0,2,0,3,0,1,0,3,0,1,0,0,0,2,0,1,1,1,0,1,0,1,0,2,0,2,0,1,0,1,0,3,0,1,1,2,0,3,1,2,0,1,1,3,0,0,1,0
seq $0,9194 ; a(n) = gcd(n, sigma(n)).
sub $0,1
seq $0,1222 ; Number of prime divisors of n counted with multiplicity (also called bigomega(n) or Omega(n)).
|
#pragma once
#include <string>
#include "../../messages/message.hh"
namespace eclipse {
namespace messages {
struct IBlockInfoRequest: public Message {
IBlockInfoRequest() = default;
~IBlockInfoRequest() = default;
std::string get_type() const override;
uint32_t job_id;
uint32_t map_id;
uint32_t reducer_id;
uint32_t block_seq;
};
}
}
|
// Original test: ./rbatterm/hw4/problem6/xori_5.asm
// Author: rbatterm
// Test source code follows
// Test random sequence (from Random.org)
lbi r2, 8 //01000
xori r1, r2, 11 //01011
halt //= 00011
|
// Copyright (c) Microsoft Corporation.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include <algorithm>
#include <cassert>
#include <ranges>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include <range_algorithm_support.hpp>
using namespace std;
template <class Rng>
concept CanViewAll = requires(Rng&& r) {
views::all(static_cast<Rng&&>(r));
};
// Test a silly precomposed range adaptor pipeline
constexpr auto pipeline = views::all | views::all | views::all | views::all | views::all | views::all;
template <class Rng>
constexpr bool test_one(Rng&& rng) {
constexpr bool is_view = ranges::view<remove_cvref_t<Rng>>;
static_assert(is_view || is_lvalue_reference_v<Rng>);
using V = conditional_t<is_view, remove_cvref_t<Rng>, ranges::ref_view<remove_reference_t<Rng>>>;
static_assert(CanViewAll<Rng&> == (!is_view || copyable<V>) );
if constexpr (!is_view || copyable<V>) { // Validate lvalue
constexpr bool is_noexcept = !is_view || is_nothrow_copy_constructible_v<V>;
static_assert(same_as<views::all_t<Rng>, V>);
static_assert(same_as<decltype(views::all(rng)), V>);
static_assert(noexcept(views::all(rng)) == is_noexcept);
static_assert(same_as<decltype(rng | views::all), V>);
static_assert(noexcept(rng | views::all) == is_noexcept);
static_assert(same_as<decltype(views::all(rng)), decltype(rng | views::all | views::all | views::all)>);
static_assert(noexcept(rng | views::all | views::all | views::all) == is_noexcept);
static_assert(same_as<decltype(views::all(rng)), decltype(rng | pipeline)>);
static_assert(noexcept(rng | pipeline) == is_noexcept);
}
static_assert(CanViewAll<const remove_cvref_t<Rng>&> == (!is_view || copyable<V>) );
if constexpr (is_view && copyable<V>) {
constexpr bool is_noexcept = is_nothrow_copy_constructible_v<V>;
static_assert(same_as<views::all_t<const remove_cvref_t<Rng>&>, V>);
static_assert(same_as<decltype(views::all(as_const(rng))), V>);
static_assert(noexcept(views::all(as_const(rng))) == is_noexcept);
static_assert(same_as<decltype(as_const(rng) | views::all), V>);
static_assert(noexcept(as_const(rng) | views::all) == is_noexcept);
static_assert(same_as<decltype(as_const(rng) | views::all | views::all | views::all), V>);
static_assert(noexcept(as_const(rng) | views::all | views::all | views::all) == is_noexcept);
static_assert(same_as<decltype(as_const(rng) | pipeline), V>);
static_assert(noexcept(as_const(rng) | pipeline) == is_noexcept);
} else if constexpr (!is_view) {
using RV = ranges::ref_view<const remove_cvref_t<Rng>>;
static_assert(same_as<views::all_t<const remove_cvref_t<Rng>&>, RV>);
static_assert(same_as<decltype(views::all(as_const(rng))), RV>);
static_assert(noexcept(views::all(as_const(rng))));
static_assert(same_as<decltype(as_const(rng) | views::all), RV>);
static_assert(noexcept(as_const(rng) | views::all));
static_assert(same_as<decltype(as_const(rng) | views::all | views::all | views::all), RV>);
static_assert(noexcept(as_const(rng) | views::all | views::all | views::all));
static_assert(same_as<decltype(as_const(rng) | pipeline), RV>);
static_assert(noexcept(as_const(rng) | pipeline));
}
// Validate rvalue
static_assert(CanViewAll<remove_cvref_t<Rng>> == is_view || ranges::enable_borrowed_range<remove_cvref_t<Rng>>);
if constexpr (is_view) {
constexpr bool is_noexcept = is_nothrow_move_constructible_v<V>;
static_assert(same_as<views::all_t<remove_cvref_t<Rng>>, V>);
static_assert(same_as<decltype(views::all(move(rng))), V>);
static_assert(noexcept(views::all(move(rng))) == is_noexcept);
static_assert(same_as<decltype(move(rng) | views::all), V>);
static_assert(noexcept(move(rng) | views::all) == is_noexcept);
static_assert(same_as<decltype(move(rng) | views::all | views::all | views::all), V>);
static_assert(noexcept(move(rng) | views::all | views::all | views::all) == is_noexcept);
static_assert(same_as<decltype(move(rng) | pipeline), V>);
static_assert(noexcept(move(rng) | pipeline) == is_noexcept);
} else if constexpr (ranges::enable_borrowed_range<remove_cvref_t<Rng>>) {
using S = decltype(ranges::subrange{declval<Rng>()});
constexpr bool is_noexcept = noexcept(S{declval<Rng>()});
static_assert(same_as<views::all_t<remove_cvref_t<Rng>>, S>);
static_assert(same_as<decltype(views::all(move(rng))), S>);
static_assert(noexcept(views::all(move(rng))) == is_noexcept);
static_assert(same_as<decltype(move(rng) | views::all), S>);
static_assert(noexcept(move(rng) | views::all) == is_noexcept);
static_assert(same_as<decltype(move(rng) | views::all | views::all | views::all), S>);
static_assert(noexcept(move(rng) | views::all | views::all | views::all) == is_noexcept);
static_assert(same_as<decltype(move(rng) | pipeline), S>);
static_assert(noexcept(move(rng) | pipeline) == is_noexcept);
}
// Validate const rvalue
static_assert(CanViewAll<const remove_cvref_t<Rng>> == (is_view && copyable<V>)
|| (!is_view && ranges::enable_borrowed_range<remove_cvref_t<Rng>>) );
if constexpr (is_view && copyable<V>) {
constexpr bool is_noexcept = is_nothrow_copy_constructible_v<V>;
static_assert(same_as<views::all_t<const remove_cvref_t<Rng>>, V>);
static_assert(same_as<decltype(views::all(move(as_const(rng)))), V>);
static_assert(noexcept(views::all(move(as_const(rng)))) == is_noexcept);
static_assert(same_as<decltype(move(as_const(rng)) | views::all), V>);
static_assert(noexcept(move(as_const(rng)) | views::all) == is_noexcept);
static_assert(same_as<decltype(move(as_const(rng)) | views::all | views::all | views::all), V>);
static_assert(noexcept(move(as_const(rng)) | views::all | views::all | views::all) == is_noexcept);
static_assert(same_as<decltype(move(as_const(rng)) | pipeline), V>);
static_assert(noexcept(move(as_const(rng)) | pipeline) == is_noexcept);
} else if constexpr (!is_view && ranges::enable_borrowed_range<remove_cvref_t<Rng>>) {
using S = decltype(ranges::subrange{declval<const remove_cvref_t<Rng>>()});
constexpr bool is_noexcept = noexcept(S{declval<const remove_cvref_t<Rng>>()});
static_assert(same_as<views::all_t<const remove_cvref_t<Rng>>, S>);
static_assert(same_as<decltype(views::all(move(as_const(rng)))), S>);
static_assert(noexcept(views::all(move(as_const(rng)))) == is_noexcept);
static_assert(same_as<decltype(move(as_const(rng)) | views::all), S>);
static_assert(noexcept(move(as_const(rng)) | views::all) == is_noexcept);
static_assert(same_as<decltype(move(as_const(rng)) | views::all | views::all | views::all), S>);
static_assert(noexcept(move(as_const(rng)) | views::all | views::all | views::all) == is_noexcept);
static_assert(same_as<decltype(move(as_const(rng)) | pipeline), S>);
static_assert(noexcept(move(as_const(rng)) | pipeline) == is_noexcept);
}
return true;
}
struct non_view_borrowed_range {
int* begin() const;
int* end() const;
};
template <>
inline constexpr bool ranges::enable_borrowed_range<non_view_borrowed_range> = true;
template <class Category, test::Common IsCommon, bool is_random = derived_from<Category, random_access_iterator_tag>>
using move_only_view = test::range<Category, const int, test::Sized{is_random}, test::CanDifference{is_random},
IsCommon, test::CanCompare{derived_from<Category, forward_iterator_tag>},
test::ProxyRef{!derived_from<Category, contiguous_iterator_tag>}, test::CanView::yes, test::Copyability::move_only>;
int main() {
static constexpr int some_ints[] = {0, 1, 2};
// Validate views
{ // ... copyable
constexpr string_view str{"Hello, World!"};
static_assert(test_one(str));
test_one(str);
assert(ranges::equal(views::all(str), str));
}
{ // ... move-only
test_one(move_only_view<input_iterator_tag, test::Common::no>{some_ints});
assert(ranges::equal(views::all(move_only_view<input_iterator_tag, test::Common::no>{some_ints}), some_ints));
test_one(move_only_view<forward_iterator_tag, test::Common::no>{some_ints});
assert(ranges::equal(views::all(move_only_view<forward_iterator_tag, test::Common::no>{some_ints}), some_ints));
test_one(move_only_view<forward_iterator_tag, test::Common::yes>{some_ints});
assert(
ranges::equal(views::all(move_only_view<forward_iterator_tag, test::Common::yes>{some_ints}), some_ints));
test_one(move_only_view<bidirectional_iterator_tag, test::Common::no>{some_ints});
assert(ranges::equal(
views::all(move_only_view<bidirectional_iterator_tag, test::Common::no>{some_ints}), some_ints));
test_one(move_only_view<bidirectional_iterator_tag, test::Common::yes>{some_ints});
assert(ranges::equal(
views::all(move_only_view<bidirectional_iterator_tag, test::Common::yes>{some_ints}), some_ints));
test_one(move_only_view<random_access_iterator_tag, test::Common::no>{some_ints});
assert(ranges::equal(
views::all(move_only_view<random_access_iterator_tag, test::Common::no>{some_ints}), some_ints));
test_one(move_only_view<random_access_iterator_tag, test::Common::yes>{some_ints});
assert(ranges::equal(
views::all(move_only_view<random_access_iterator_tag, test::Common::yes>{some_ints}), some_ints));
}
// Validate non-views
{
static_assert(test_one(some_ints));
test_one(some_ints);
assert(ranges::equal(views::all(some_ints), some_ints));
}
{
string str{"Hello, World!"};
test_one(str);
assert(ranges::equal(views::all(str), str));
}
}
|
; AesOpt.asm -- AES optimized code for x86 AES hardware instructions
; 2021-03-10 : Igor Pavlov : Public domain
include 7zAsm.asm
ifdef ymm0
use_vaes_256 equ 1
ECHO "++ VAES 256"
else
ECHO "-- NO VAES 256"
endif
ifdef x64
ECHO "x86-64"
else
ECHO "x86"
if (IS_CDECL gt 0)
ECHO "ABI : CDECL"
else
ECHO "ABI : no CDECL : FASTCALL"
endif
endif
if (IS_LINUX gt 0)
ECHO "ABI : LINUX"
else
ECHO "ABI : WINDOWS"
endif
MY_ASM_START
ifndef x64
.686
.xmm
endif
; MY_ALIGN EQU ALIGN(64)
MY_ALIGN EQU
SEG_ALIGN EQU MY_ALIGN
MY_SEG_PROC macro name:req, numParams:req
; seg_name equ @CatStr(_TEXT$, name)
; seg_name SEGMENT SEG_ALIGN 'CODE'
MY_PROC name, numParams
endm
MY_SEG_ENDP macro
; seg_name ENDS
endm
NUM_AES_KEYS_MAX equ 15
; the number of push operators in function PROLOG
if (IS_LINUX eq 0) or (IS_X64 eq 0)
num_regs_push equ 2
stack_param_offset equ (REG_SIZE * (1 + num_regs_push))
endif
ifdef x64
num_param equ REG_ABI_PARAM_2
else
if (IS_CDECL gt 0)
; size_t size
; void * data
; UInt32 * aes
; ret-ip <- (r4)
aes_OFFS equ (stack_param_offset)
data_OFFS equ (REG_SIZE + aes_OFFS)
size_OFFS equ (REG_SIZE + data_OFFS)
num_param equ [r4 + size_OFFS]
else
num_param equ [r4 + stack_param_offset]
endif
endif
keys equ REG_PARAM_0 ; r1
rD equ REG_PARAM_1 ; r2
rN equ r0
koffs_x equ x7
koffs_r equ r7
ksize_x equ x6
ksize_r equ r6
keys2 equ r3
state equ xmm0
key equ xmm0
key_ymm equ ymm0
key_ymm_n equ 0
ifdef x64
ways = 11
else
ways = 4
endif
ways_start_reg equ 1
iv equ @CatStr(xmm, %(ways_start_reg + ways))
iv_ymm equ @CatStr(ymm, %(ways_start_reg + ways))
WOP macro op, op2
i = 0
rept ways
op @CatStr(xmm, %(ways_start_reg + i)), op2
i = i + 1
endm
endm
ifndef ABI_LINUX
ifdef x64
; we use 32 bytes of home space in stack in WIN64-x64
NUM_HOME_MM_REGS equ (32 / 16)
; we preserve xmm registers starting from xmm6 in WIN64-x64
MM_START_SAVE_REG equ 6
SAVE_XMM macro num_used_mm_regs:req
num_save_mm_regs = num_used_mm_regs - MM_START_SAVE_REG
if num_save_mm_regs GT 0
num_save_mm_regs2 = num_save_mm_regs - NUM_HOME_MM_REGS
; RSP is (16*x + 8) after entering the function in WIN64-x64
stack_offset = 16 * num_save_mm_regs2 + (stack_param_offset mod 16)
i = 0
rept num_save_mm_regs
if i eq NUM_HOME_MM_REGS
sub r4, stack_offset
endif
if i lt NUM_HOME_MM_REGS
movdqa [r4 + stack_param_offset + i * 16], @CatStr(xmm, %(MM_START_SAVE_REG + i))
else
movdqa [r4 + (i - NUM_HOME_MM_REGS) * 16], @CatStr(xmm, %(MM_START_SAVE_REG + i))
endif
i = i + 1
endm
endif
endm
RESTORE_XMM macro num_used_mm_regs:req
if num_save_mm_regs GT 0
i = 0
if num_save_mm_regs2 GT 0
rept num_save_mm_regs2
movdqa @CatStr(xmm, %(MM_START_SAVE_REG + NUM_HOME_MM_REGS + i)), [r4 + i * 16]
i = i + 1
endm
add r4, stack_offset
endif
num_low_regs = num_save_mm_regs - i
i = 0
rept num_low_regs
movdqa @CatStr(xmm, %(MM_START_SAVE_REG + i)), [r4 + stack_param_offset + i * 16]
i = i + 1
endm
endif
endm
endif ; x64
endif ; ABI_LINUX
MY_PROLOG macro num_used_mm_regs:req
; num_regs_push: must be equal to the number of push operators
; push r3
; push r5
if (IS_LINUX eq 0) or (IS_X64 eq 0)
push r6
push r7
endif
mov rN, num_param ; don't move it; num_param can use stack pointer (r4)
if (IS_X64 eq 0)
if (IS_CDECL gt 0)
mov rD, [r4 + data_OFFS]
mov keys, [r4 + aes_OFFS]
endif
elseif (IS_LINUX gt 0)
MY_ABI_LINUX_TO_WIN_2
endif
ifndef ABI_LINUX
ifdef x64
SAVE_XMM num_used_mm_regs
endif
endif
mov ksize_x, [keys + 16]
shl ksize_x, 5
endm
MY_EPILOG macro
ifndef ABI_LINUX
ifdef x64
RESTORE_XMM num_save_mm_regs
endif
endif
if (IS_LINUX eq 0) or (IS_X64 eq 0)
pop r7
pop r6
endif
; pop r5
; pop r3
MY_ENDP
endm
OP_KEY macro op:req, offs:req
op state, [keys + offs]
endm
WOP_KEY macro op:req, offs:req
movdqa key, [keys + offs]
WOP op, key
endm
; ---------- AES-CBC Decode ----------
XOR_WITH_DATA macro reg, _ppp_
pxor reg, [rD + i * 16]
endm
WRITE_TO_DATA macro reg, _ppp_
movdqa [rD + i * 16], reg
endm
; state0 equ @CatStr(xmm, %(ways_start_reg))
key0 equ @CatStr(xmm, %(ways_start_reg + ways + 1))
key0_ymm equ @CatStr(ymm, %(ways_start_reg + ways + 1))
key_last equ @CatStr(xmm, %(ways_start_reg + ways + 2))
key_last_ymm equ @CatStr(ymm, %(ways_start_reg + ways + 2))
key_last_ymm_n equ (ways_start_reg + ways + 2)
NUM_CBC_REGS equ (ways_start_reg + ways + 3)
MY_SEG_PROC AesCbc_Decode_HW, 3
AesCbc_Decode_HW_start::
MY_PROLOG NUM_CBC_REGS
AesCbc_Decode_HW_start_2::
movdqa iv, [keys]
add keys, 32
movdqa key0, [keys + 1 * ksize_r]
movdqa key_last, [keys]
sub ksize_x, 16
jmp check2
align 16
nextBlocks2:
WOP movdqa, [rD + i * 16]
mov koffs_x, ksize_x
; WOP_KEY pxor, ksize_r + 16
WOP pxor, key0
; align 16
@@:
WOP_KEY aesdec, 1 * koffs_r
sub koffs_r, 16
jnz @B
; WOP_KEY aesdeclast, 0
WOP aesdeclast, key_last
pxor @CatStr(xmm, %(ways_start_reg)), iv
i = 1
rept ways - 1
pxor @CatStr(xmm, %(ways_start_reg + i)), [rD + i * 16 - 16]
i = i + 1
endm
movdqa iv, [rD + ways * 16 - 16]
WOP WRITE_TO_DATA
add rD, ways * 16
AesCbc_Decode_HW_start_3::
check2:
sub rN, ways
jnc nextBlocks2
add rN, ways
sub ksize_x, 16
jmp check
nextBlock:
movdqa state, [rD]
mov koffs_x, ksize_x
; OP_KEY pxor, 1 * ksize_r + 32
pxor state, key0
; movdqa state0, [rD]
; movdqa state, key0
; pxor state, state0
@@:
OP_KEY aesdec, 1 * koffs_r + 16
OP_KEY aesdec, 1 * koffs_r
sub koffs_r, 32
jnz @B
OP_KEY aesdec, 16
; OP_KEY aesdeclast, 0
aesdeclast state, key_last
pxor state, iv
movdqa iv, [rD]
; movdqa iv, state0
movdqa [rD], state
add rD, 16
check:
sub rN, 1
jnc nextBlock
movdqa [keys - 32], iv
MY_EPILOG
; ---------- AVX ----------
AVX__WOP_n macro op
i = 0
rept ways
op (ways_start_reg + i)
i = i + 1
endm
endm
AVX__WOP macro op
i = 0
rept ways
op @CatStr(ymm, %(ways_start_reg + i))
i = i + 1
endm
endm
AVX__WOP_KEY macro op:req, offs:req
vmovdqa key_ymm, ymmword ptr [keys2 + offs]
AVX__WOP_n op
endm
AVX__CBC_START macro reg
; vpxor reg, key_ymm, ymmword ptr [rD + 32 * i]
vpxor reg, key0_ymm, ymmword ptr [rD + 32 * i]
endm
AVX__CBC_END macro reg
if i eq 0
vpxor reg, reg, iv_ymm
else
vpxor reg, reg, ymmword ptr [rD + i * 32 - 16]
endif
endm
AVX__WRITE_TO_DATA macro reg
vmovdqu ymmword ptr [rD + 32 * i], reg
endm
AVX__XOR_WITH_DATA macro reg
vpxor reg, reg, ymmword ptr [rD + 32 * i]
endm
AVX__CTR_START macro reg
vpaddq iv_ymm, iv_ymm, one_ymm
; vpxor reg, iv_ymm, key_ymm
vpxor reg, iv_ymm, key0_ymm
endm
MY_VAES_INSTR_2 macro cmd, dest, a1, a2
db 0c4H
db 2 + 040H + 020h * (1 - (a2) / 8) + 080h * (1 - (dest) / 8)
db 5 + 8 * ((not (a1)) and 15)
db cmd
db 0c0H + 8 * ((dest) and 7) + ((a2) and 7)
endm
MY_VAES_INSTR macro cmd, dest, a
MY_VAES_INSTR_2 cmd, dest, dest, a
endm
MY_vaesenc macro dest, a
MY_VAES_INSTR 0dcH, dest, a
endm
MY_vaesenclast macro dest, a
MY_VAES_INSTR 0ddH, dest, a
endm
MY_vaesdec macro dest, a
MY_VAES_INSTR 0deH, dest, a
endm
MY_vaesdeclast macro dest, a
MY_VAES_INSTR 0dfH, dest, a
endm
AVX__VAES_DEC macro reg
MY_vaesdec reg, key_ymm_n
endm
AVX__VAES_DEC_LAST_key_last macro reg
; MY_vaesdeclast reg, key_ymm_n
MY_vaesdeclast reg, key_last_ymm_n
endm
AVX__VAES_ENC macro reg
MY_vaesenc reg, key_ymm_n
endm
AVX__VAES_ENC_LAST macro reg
MY_vaesenclast reg, key_ymm_n
endm
AVX__vinserti128_TO_HIGH macro dest, src
vinserti128 dest, dest, src, 1
endm
MY_PROC AesCbc_Decode_HW_256, 3
ifdef use_vaes_256
MY_PROLOG NUM_CBC_REGS
cmp rN, ways * 2
jb AesCbc_Decode_HW_start_2
vmovdqa iv, xmmword ptr [keys]
add keys, 32
vbroadcasti128 key0_ymm, xmmword ptr [keys + 1 * ksize_r]
vbroadcasti128 key_last_ymm, xmmword ptr [keys]
sub ksize_x, 16
mov koffs_x, ksize_x
add ksize_x, ksize_x
AVX_STACK_SUB = ((NUM_AES_KEYS_MAX + 1 - 2) * 32)
push keys2
sub r4, AVX_STACK_SUB
; sub r4, 32
; sub r4, ksize_r
; lea keys2, [r4 + 32]
mov keys2, r4
and keys2, -32
broad:
vbroadcasti128 key_ymm, xmmword ptr [keys + 1 * koffs_r]
vmovdqa ymmword ptr [keys2 + koffs_r * 2], key_ymm
sub koffs_r, 16
; jnc broad
jnz broad
sub rN, ways * 2
align 16
avx_cbcdec_nextBlock2:
mov koffs_x, ksize_x
; AVX__WOP_KEY AVX__CBC_START, 1 * koffs_r + 32
AVX__WOP AVX__CBC_START
@@:
AVX__WOP_KEY AVX__VAES_DEC, 1 * koffs_r
sub koffs_r, 32
jnz @B
; AVX__WOP_KEY AVX__VAES_DEC_LAST, 0
AVX__WOP_n AVX__VAES_DEC_LAST_key_last
AVX__vinserti128_TO_HIGH iv_ymm, xmmword ptr [rD]
AVX__WOP AVX__CBC_END
vmovdqa iv, xmmword ptr [rD + ways * 32 - 16]
AVX__WOP AVX__WRITE_TO_DATA
add rD, ways * 32
sub rN, ways * 2
jnc avx_cbcdec_nextBlock2
add rN, ways * 2
shr ksize_x, 1
; lea r4, [r4 + 1 * ksize_r + 32]
add r4, AVX_STACK_SUB
pop keys2
vzeroupper
jmp AesCbc_Decode_HW_start_3
else
jmp AesCbc_Decode_HW_start
endif
MY_ENDP
MY_SEG_ENDP
; ---------- AES-CBC Encode ----------
e0 equ xmm1
CENC_START_KEY equ 2
CENC_NUM_REG_KEYS equ (3 * 2)
; last_key equ @CatStr(xmm, %(CENC_START_KEY + CENC_NUM_REG_KEYS))
MY_SEG_PROC AesCbc_Encode_HW, 3
MY_PROLOG (CENC_START_KEY + CENC_NUM_REG_KEYS + 0)
movdqa state, [keys]
add keys, 32
i = 0
rept CENC_NUM_REG_KEYS
movdqa @CatStr(xmm, %(CENC_START_KEY + i)), [keys + i * 16]
i = i + 1
endm
add keys, ksize_r
neg ksize_r
add ksize_r, (16 * CENC_NUM_REG_KEYS)
; movdqa last_key, [keys]
jmp check_e
align 16
nextBlock_e:
movdqa e0, [rD]
mov koffs_r, ksize_r
pxor e0, @CatStr(xmm, %(CENC_START_KEY))
pxor state, e0
i = 1
rept (CENC_NUM_REG_KEYS - 1)
aesenc state, @CatStr(xmm, %(CENC_START_KEY + i))
i = i + 1
endm
@@:
OP_KEY aesenc, 1 * koffs_r
OP_KEY aesenc, 1 * koffs_r + 16
add koffs_r, 32
jnz @B
OP_KEY aesenclast, 0
; aesenclast state, last_key
movdqa [rD], state
add rD, 16
check_e:
sub rN, 1
jnc nextBlock_e
; movdqa [keys - 32], state
movdqa [keys + 1 * ksize_r - (16 * CENC_NUM_REG_KEYS) - 32], state
MY_EPILOG
MY_SEG_ENDP
; ---------- AES-CTR ----------
ifdef x64
; ways = 11
endif
one equ @CatStr(xmm, %(ways_start_reg + ways + 1))
one_ymm equ @CatStr(ymm, %(ways_start_reg + ways + 1))
key0 equ @CatStr(xmm, %(ways_start_reg + ways + 2))
key0_ymm equ @CatStr(ymm, %(ways_start_reg + ways + 2))
NUM_CTR_REGS equ (ways_start_reg + ways + 3)
INIT_CTR macro reg, _ppp_
paddq iv, one
movdqa reg, iv
endm
MY_SEG_PROC AesCtr_Code_HW, 3
Ctr_start::
MY_PROLOG NUM_CTR_REGS
Ctr_start_2::
movdqa iv, [keys]
add keys, 32
movdqa key0, [keys]
add keys, ksize_r
neg ksize_r
add ksize_r, 16
Ctr_start_3::
mov koffs_x, 1
movd one, koffs_x
jmp check2_c
align 16
nextBlocks2_c:
WOP INIT_CTR, 0
mov koffs_r, ksize_r
; WOP_KEY pxor, 1 * koffs_r -16
WOP pxor, key0
@@:
WOP_KEY aesenc, 1 * koffs_r
add koffs_r, 16
jnz @B
WOP_KEY aesenclast, 0
WOP XOR_WITH_DATA
WOP WRITE_TO_DATA
add rD, ways * 16
check2_c:
sub rN, ways
jnc nextBlocks2_c
add rN, ways
sub keys, 16
add ksize_r, 16
jmp check_c
; align 16
nextBlock_c:
paddq iv, one
; movdqa state, [keys + 1 * koffs_r - 16]
movdqa state, key0
mov koffs_r, ksize_r
pxor state, iv
@@:
OP_KEY aesenc, 1 * koffs_r
OP_KEY aesenc, 1 * koffs_r + 16
add koffs_r, 32
jnz @B
OP_KEY aesenc, 0
OP_KEY aesenclast, 16
pxor state, [rD]
movdqa [rD], state
add rD, 16
check_c:
sub rN, 1
jnc nextBlock_c
; movdqa [keys - 32], iv
movdqa [keys + 1 * ksize_r - 16 - 32], iv
MY_EPILOG
MY_PROC AesCtr_Code_HW_256, 3
ifdef use_vaes_256
MY_PROLOG NUM_CTR_REGS
cmp rN, ways * 2
jb Ctr_start_2
vbroadcasti128 iv_ymm, xmmword ptr [keys]
add keys, 32
vbroadcasti128 key0_ymm, xmmword ptr [keys]
mov koffs_x, 1
vmovd one, koffs_x
vpsubq iv_ymm, iv_ymm, one_ymm
vpaddq one, one, one
AVX__vinserti128_TO_HIGH one_ymm, one
add keys, ksize_r
sub ksize_x, 16
neg ksize_r
mov koffs_r, ksize_r
add ksize_r, ksize_r
AVX_STACK_SUB = ((NUM_AES_KEYS_MAX + 1 - 1) * 32)
push keys2
lea keys2, [r4 - 32]
sub r4, AVX_STACK_SUB
and keys2, -32
vbroadcasti128 key_ymm, xmmword ptr [keys]
vmovdqa ymmword ptr [keys2], key_ymm
@@:
vbroadcasti128 key_ymm, xmmword ptr [keys + 1 * koffs_r]
vmovdqa ymmword ptr [keys2 + koffs_r * 2], key_ymm
add koffs_r, 16
jnz @B
sub rN, ways * 2
align 16
avx_ctr_nextBlock2:
mov koffs_r, ksize_r
AVX__WOP AVX__CTR_START
; AVX__WOP_KEY AVX__CTR_START, 1 * koffs_r - 32
@@:
AVX__WOP_KEY AVX__VAES_ENC, 1 * koffs_r
add koffs_r, 32
jnz @B
AVX__WOP_KEY AVX__VAES_ENC_LAST, 0
AVX__WOP AVX__XOR_WITH_DATA
AVX__WOP AVX__WRITE_TO_DATA
add rD, ways * 32
sub rN, ways * 2
jnc avx_ctr_nextBlock2
add rN, ways * 2
vextracti128 iv, iv_ymm, 1
sar ksize_r, 1
add r4, AVX_STACK_SUB
pop keys2
vzeroupper
jmp Ctr_start_3
else
jmp Ctr_start
endif
MY_ENDP
MY_SEG_ENDP
end
|
-- HUMAN RESOURCE MACHINE PROGRAM --
-- in1 % in2, ... -> out
JUMP b
a:
ADD 2
OUTBOX
b:
INBOX
COPYTO 0
INBOX
COPYTO 2
COPYFROM 0
c:
SUB 2
JUMPN a
JUMP c
|
.686
.model flat,stdcall
option casemap:none
include .\bnlib.inc
include .\bignum.inc
.code
bnDivpow2 proc bnX:DWORD,bitsY:DWORD,bnQuo:DWORD
invoke bnMov,bnQuo,bnX
invoke bnShr,bnQuo,bitsY
ret
bnDivpow2 endp
end |
#include "prefix/source_full_header.h"
int main() {
return 0;
}
|
PresetsMenu14speed:
dw #presets_goto_14speed_crateria
dw #presets_goto_14speed_brinstar
dw #presets_goto_14speed_wrecked_ship
dw #presets_goto_14speed_brinstar_revisit
dw #presets_goto_14speed_upper_norfair
dw #presets_goto_14speed_lower_norfair
dw #presets_goto_14speed_maridia
dw #presets_goto_14speed_tourian
dw #$0000
%cm_header("PRESETS FOR 14% SPEED")
presets_goto_14speed_crateria:
%cm_submenu("Crateria", #presets_submenu_14speed_crateria)
presets_goto_14speed_brinstar:
%cm_submenu("Brinstar", #presets_submenu_14speed_brinstar)
presets_goto_14speed_wrecked_ship:
%cm_submenu("Wrecked Ship", #presets_submenu_14speed_wrecked_ship)
presets_goto_14speed_brinstar_revisit:
%cm_submenu("Brinstar Revisit", #presets_submenu_14speed_brinstar_revisit)
presets_goto_14speed_upper_norfair:
%cm_submenu("Upper Norfair", #presets_submenu_14speed_upper_norfair)
presets_goto_14speed_lower_norfair:
%cm_submenu("Lower Norfair", #presets_submenu_14speed_lower_norfair)
presets_goto_14speed_maridia:
%cm_submenu("Maridia", #presets_submenu_14speed_maridia)
presets_goto_14speed_tourian:
%cm_submenu("Tourian", #presets_submenu_14speed_tourian)
presets_submenu_14speed_crateria:
dw #presets_14speed_crateria_ceres_elevator
dw #presets_14speed_crateria_ceres_escape
dw #presets_14speed_crateria_ceres_last_3_rooms
dw #presets_14speed_crateria_ship
dw #presets_14speed_crateria_parlor
dw #presets_14speed_crateria_climb_down
dw #presets_14speed_crateria_pit_room
dw #presets_14speed_crateria_morph
dw #presets_14speed_crateria_construction_zone_down
dw #presets_14speed_crateria_construction_zone_up
dw #presets_14speed_crateria_pit_room_revisit
dw #presets_14speed_crateria_climb_up
dw #presets_14speed_crateria_parlor_revisit
dw #presets_14speed_crateria_flyway
dw #presets_14speed_crateria_bomb_torizo
dw #presets_14speed_crateria_alcatraz
dw #presets_14speed_crateria_terminator
dw #presets_14speed_crateria_green_pirate_shaft
dw #$0000
%cm_header("CRATERIA")
presets_submenu_14speed_brinstar:
dw #presets_14speed_brinstar_green_brinstar_elevator
dw #presets_14speed_brinstar_big_pink
dw #presets_14speed_brinstar_red_tower
dw #presets_14speed_brinstar_hellway
dw #presets_14speed_brinstar_caterpillar_room
dw #presets_14speed_brinstar_leaving_power_bombs
dw #presets_14speed_brinstar_kihunter_room
dw #presets_14speed_brinstar_moat
dw #presets_14speed_brinstar_ocean
dw #$0000
%cm_header("BRINSTAR")
presets_submenu_14speed_wrecked_ship:
dw #presets_14speed_wrecked_ship_wrecked_ship_shaft
dw #presets_14speed_wrecked_ship_phantoon
dw #presets_14speed_wrecked_ship_wrecked_ship_supers
dw #presets_14speed_wrecked_ship_shaft_revisit
dw #presets_14speed_wrecked_ship_attic
dw #presets_14speed_wrecked_ship_bowling_alley_path
dw #presets_14speed_wrecked_ship_bowling_alley
dw #presets_14speed_wrecked_ship_leaving_gravity
dw #$0000
%cm_header("WRECKED SHIP")
presets_submenu_14speed_brinstar_revisit:
dw #presets_14speed_brinstar_revisit_red_tower_elevator
dw #presets_14speed_brinstar_revisit_breaking_tube
dw #presets_14speed_brinstar_revisit_entering_kraids_lair
dw #presets_14speed_brinstar_revisit_baby_kraid_entering
dw #presets_14speed_brinstar_revisit_kraid
dw #presets_14speed_brinstar_revisit_baby_kraid_exiting
dw #presets_14speed_brinstar_revisit_kraid_etank
dw #$0000
%cm_header("BRINSTAR REVISIT")
presets_submenu_14speed_upper_norfair:
dw #presets_14speed_upper_norfair_precathedral
dw #presets_14speed_upper_norfair_bubble_mountain
dw #presets_14speed_upper_norfair_bubble_mountain_revisit
dw #presets_14speed_upper_norfair_magdollite_room
dw #presets_14speed_upper_norfair_lava_spark
dw #$0000
%cm_header("UPPER NORFAIR")
presets_submenu_14speed_lower_norfair:
dw #presets_14speed_lower_norfair_ln_main_hall
dw #presets_14speed_lower_norfair_pillars
dw #presets_14speed_lower_norfair_worst_room
dw #presets_14speed_lower_norfair_amphitheatre
dw #presets_14speed_lower_norfair_kihunter_stairs
dw #presets_14speed_lower_norfair_wasteland
dw #presets_14speed_lower_norfair_metal_pirates
dw #presets_14speed_lower_norfair_ridley_farming_room
dw #presets_14speed_lower_norfair_ridley
dw #presets_14speed_lower_norfair_leaving_ridley
dw #presets_14speed_lower_norfair_wasteland_revisit
dw #presets_14speed_lower_norfair_kihunter_stairs_revisit
dw #presets_14speed_lower_norfair_fireflea_room
dw #presets_14speed_lower_norfair_three_musketeers
dw #presets_14speed_lower_norfair_bubble_mountain_revisit_2
dw #$0000
%cm_header("LOWER NORFAIR")
presets_submenu_14speed_maridia:
dw #presets_14speed_maridia_entering_maridia
dw #presets_14speed_maridia_mt_everest
dw #presets_14speed_maridia_aqueduct
dw #presets_14speed_maridia_botwoon
dw #presets_14speed_maridia_botwoon_etank_room
dw #presets_14speed_maridia_colosseum
dw #presets_14speed_maridia_draygon
dw #presets_14speed_maridia_colosseum_revisit
dw #presets_14speed_maridia_reverse_botwoon
dw #presets_14speed_maridia_aqueduct_revisit
dw #presets_14speed_maridia_everest_revisit
dw #presets_14speed_maridia_red_tower_green_gate
dw #$0000
%cm_header("MARIDIA")
presets_submenu_14speed_tourian:
dw #presets_14speed_tourian_kihunter_room_revisit
dw #presets_14speed_tourian_terminator_revisit
dw #presets_14speed_tourian_pirate_shaft_revisit
dw #presets_14speed_tourian_metroids_1
dw #presets_14speed_tourian_metroids_2
dw #presets_14speed_tourian_metroids_3
dw #presets_14speed_tourian_metroids_4
dw #presets_14speed_tourian_doors_and_refills
dw #presets_14speed_tourian_zeb_skip
dw #presets_14speed_tourian_mother_brain_2
dw #presets_14speed_tourian_mother_brain_3
dw #presets_14speed_tourian_zebes_escape
dw #presets_14speed_tourian_escape_room_3
dw #presets_14speed_tourian_escape_room_4
dw #presets_14speed_tourian_escape_climb
dw #presets_14speed_tourian_escape_parlor
dw #$0000
%cm_header("TOURIAN")
; Crateria
presets_14speed_crateria_ceres_elevator:
%cm_preset("Ceres Elevator", #preset_14speed_crateria_ceres_elevator)
presets_14speed_crateria_ceres_escape:
%cm_preset("Ceres Escape", #preset_14speed_crateria_ceres_escape)
presets_14speed_crateria_ceres_last_3_rooms:
%cm_preset("Ceres Last 3 rooms", #preset_14speed_crateria_ceres_last_3_rooms)
presets_14speed_crateria_ship:
%cm_preset("Ship", #preset_14speed_crateria_ship)
presets_14speed_crateria_parlor:
%cm_preset("Parlor", #preset_14speed_crateria_parlor)
presets_14speed_crateria_climb_down:
%cm_preset("Climb Down", #preset_14speed_crateria_climb_down)
presets_14speed_crateria_pit_room:
%cm_preset("Pit Room", #preset_14speed_crateria_pit_room)
presets_14speed_crateria_morph:
%cm_preset("Morph", #preset_14speed_crateria_morph)
presets_14speed_crateria_construction_zone_down:
%cm_preset("Construction Zone Down", #preset_14speed_crateria_construction_zone_down)
presets_14speed_crateria_construction_zone_up:
%cm_preset("Construction Zone Up", #preset_14speed_crateria_construction_zone_up)
presets_14speed_crateria_pit_room_revisit:
%cm_preset("Pit Room Revisit", #preset_14speed_crateria_pit_room_revisit)
presets_14speed_crateria_climb_up:
%cm_preset("Climb Up", #preset_14speed_crateria_climb_up)
presets_14speed_crateria_parlor_revisit:
%cm_preset("Parlor Revisit", #preset_14speed_crateria_parlor_revisit)
presets_14speed_crateria_flyway:
%cm_preset("Flyway", #preset_14speed_crateria_flyway)
presets_14speed_crateria_bomb_torizo:
%cm_preset("Bomb Torizo", #preset_14speed_crateria_bomb_torizo)
presets_14speed_crateria_alcatraz:
%cm_preset("Alcatraz", #preset_14speed_crateria_alcatraz)
presets_14speed_crateria_terminator:
%cm_preset("Terminator", #preset_14speed_crateria_terminator)
presets_14speed_crateria_green_pirate_shaft:
%cm_preset("Green Pirate Shaft", #preset_14speed_crateria_green_pirate_shaft)
; Brinstar
presets_14speed_brinstar_green_brinstar_elevator:
%cm_preset("Green Brinstar Elevator", #preset_14speed_brinstar_green_brinstar_elevator)
presets_14speed_brinstar_big_pink:
%cm_preset("Big Pink", #preset_14speed_brinstar_big_pink)
presets_14speed_brinstar_red_tower:
%cm_preset("Red Tower", #preset_14speed_brinstar_red_tower)
presets_14speed_brinstar_hellway:
%cm_preset("Hellway", #preset_14speed_brinstar_hellway)
presets_14speed_brinstar_caterpillar_room:
%cm_preset("Caterpillar Room", #preset_14speed_brinstar_caterpillar_room)
presets_14speed_brinstar_leaving_power_bombs:
%cm_preset("Leaving Power Bombs", #preset_14speed_brinstar_leaving_power_bombs)
presets_14speed_brinstar_kihunter_room:
%cm_preset("Kihunter Room", #preset_14speed_brinstar_kihunter_room)
presets_14speed_brinstar_moat:
%cm_preset("Moat", #preset_14speed_brinstar_moat)
presets_14speed_brinstar_ocean:
%cm_preset("Ocean", #preset_14speed_brinstar_ocean)
; Wrecked Ship
presets_14speed_wrecked_ship_wrecked_ship_shaft:
%cm_preset("Wrecked Ship Shaft", #preset_14speed_wrecked_ship_wrecked_ship_shaft)
presets_14speed_wrecked_ship_phantoon:
%cm_preset("Phantoon", #preset_14speed_wrecked_ship_phantoon)
presets_14speed_wrecked_ship_wrecked_ship_supers:
%cm_preset("Wrecked Ship Supers", #preset_14speed_wrecked_ship_wrecked_ship_supers)
presets_14speed_wrecked_ship_shaft_revisit:
%cm_preset("Shaft Revisit", #preset_14speed_wrecked_ship_shaft_revisit)
presets_14speed_wrecked_ship_attic:
%cm_preset("Attic", #preset_14speed_wrecked_ship_attic)
presets_14speed_wrecked_ship_bowling_alley_path:
%cm_preset("Bowling Alley Path", #preset_14speed_wrecked_ship_bowling_alley_path)
presets_14speed_wrecked_ship_bowling_alley:
%cm_preset("Bowling Alley", #preset_14speed_wrecked_ship_bowling_alley)
presets_14speed_wrecked_ship_leaving_gravity:
%cm_preset("Leaving Gravity", #preset_14speed_wrecked_ship_leaving_gravity)
; Brinstar Revisit
presets_14speed_brinstar_revisit_red_tower_elevator:
%cm_preset("Red Tower Elevator", #preset_14speed_brinstar_revisit_red_tower_elevator)
presets_14speed_brinstar_revisit_breaking_tube:
%cm_preset("Breaking Tube", #preset_14speed_brinstar_revisit_breaking_tube)
presets_14speed_brinstar_revisit_entering_kraids_lair:
%cm_preset("Entering Kraid's Lair", #preset_14speed_brinstar_revisit_entering_kraids_lair)
presets_14speed_brinstar_revisit_baby_kraid_entering:
%cm_preset("Baby Kraid (Entering)", #preset_14speed_brinstar_revisit_baby_kraid_entering)
presets_14speed_brinstar_revisit_kraid:
%cm_preset("Kraid", #preset_14speed_brinstar_revisit_kraid)
presets_14speed_brinstar_revisit_baby_kraid_exiting:
%cm_preset("Baby Kraid (Exiting)", #preset_14speed_brinstar_revisit_baby_kraid_exiting)
presets_14speed_brinstar_revisit_kraid_etank:
%cm_preset("Kraid E-tank", #preset_14speed_brinstar_revisit_kraid_etank)
; Upper Norfair
presets_14speed_upper_norfair_precathedral:
%cm_preset("Pre-Cathedral", #preset_14speed_upper_norfair_precathedral)
presets_14speed_upper_norfair_bubble_mountain:
%cm_preset("Bubble Mountain", #preset_14speed_upper_norfair_bubble_mountain)
presets_14speed_upper_norfair_bubble_mountain_revisit:
%cm_preset("Bubble Mountain Revisit", #preset_14speed_upper_norfair_bubble_mountain_revisit)
presets_14speed_upper_norfair_magdollite_room:
%cm_preset("Magdollite Room", #preset_14speed_upper_norfair_magdollite_room)
presets_14speed_upper_norfair_lava_spark:
%cm_preset("Lava Spark", #preset_14speed_upper_norfair_lava_spark)
; Lower Norfair
presets_14speed_lower_norfair_ln_main_hall:
%cm_preset("LN Main Hall", #preset_14speed_lower_norfair_ln_main_hall)
presets_14speed_lower_norfair_pillars:
%cm_preset("Pillars", #preset_14speed_lower_norfair_pillars)
presets_14speed_lower_norfair_worst_room:
%cm_preset("Worst Room", #preset_14speed_lower_norfair_worst_room)
presets_14speed_lower_norfair_amphitheatre:
%cm_preset("Amphitheatre", #preset_14speed_lower_norfair_amphitheatre)
presets_14speed_lower_norfair_kihunter_stairs:
%cm_preset("Kihunter Stairs", #preset_14speed_lower_norfair_kihunter_stairs)
presets_14speed_lower_norfair_wasteland:
%cm_preset("Wasteland", #preset_14speed_lower_norfair_wasteland)
presets_14speed_lower_norfair_metal_pirates:
%cm_preset("Metal Pirates", #preset_14speed_lower_norfair_metal_pirates)
presets_14speed_lower_norfair_ridley_farming_room:
%cm_preset("Ridley Farming Room", #preset_14speed_lower_norfair_ridley_farming_room)
presets_14speed_lower_norfair_ridley:
%cm_preset("Ridley", #preset_14speed_lower_norfair_ridley)
presets_14speed_lower_norfair_leaving_ridley:
%cm_preset("Leaving Ridley", #preset_14speed_lower_norfair_leaving_ridley)
presets_14speed_lower_norfair_wasteland_revisit:
%cm_preset("Wasteland Revisit", #preset_14speed_lower_norfair_wasteland_revisit)
presets_14speed_lower_norfair_kihunter_stairs_revisit:
%cm_preset("Kihunter Stairs Revisit", #preset_14speed_lower_norfair_kihunter_stairs_revisit)
presets_14speed_lower_norfair_fireflea_room:
%cm_preset("Fireflea Room", #preset_14speed_lower_norfair_fireflea_room)
presets_14speed_lower_norfair_three_musketeers:
%cm_preset("Three Musketeers", #preset_14speed_lower_norfair_three_musketeers)
presets_14speed_lower_norfair_bubble_mountain_revisit_2:
%cm_preset("Bubble Mountain Revisit", #preset_14speed_lower_norfair_bubble_mountain_revisit_2)
; Maridia
presets_14speed_maridia_entering_maridia:
%cm_preset("Entering Maridia", #preset_14speed_maridia_entering_maridia)
presets_14speed_maridia_mt_everest:
%cm_preset("Mt Everest", #preset_14speed_maridia_mt_everest)
presets_14speed_maridia_aqueduct:
%cm_preset("Aqueduct", #preset_14speed_maridia_aqueduct)
presets_14speed_maridia_botwoon:
%cm_preset("Botwoon", #preset_14speed_maridia_botwoon)
presets_14speed_maridia_botwoon_etank_room:
%cm_preset("Botwoon E-tank Room", #preset_14speed_maridia_botwoon_etank_room)
presets_14speed_maridia_colosseum:
%cm_preset("Colosseum", #preset_14speed_maridia_colosseum)
presets_14speed_maridia_draygon:
%cm_preset("Draygon", #preset_14speed_maridia_draygon)
presets_14speed_maridia_colosseum_revisit:
%cm_preset("Colosseum Revisit", #preset_14speed_maridia_colosseum_revisit)
presets_14speed_maridia_reverse_botwoon:
%cm_preset("Reverse Botwoon", #preset_14speed_maridia_reverse_botwoon)
presets_14speed_maridia_aqueduct_revisit:
%cm_preset("Aqueduct Revisit", #preset_14speed_maridia_aqueduct_revisit)
presets_14speed_maridia_everest_revisit:
%cm_preset("Everest Revisit", #preset_14speed_maridia_everest_revisit)
presets_14speed_maridia_red_tower_green_gate:
%cm_preset("Red Tower Green Gate", #preset_14speed_maridia_red_tower_green_gate)
; Tourian
presets_14speed_tourian_kihunter_room_revisit:
%cm_preset("Kihunter Room Revisit", #preset_14speed_tourian_kihunter_room_revisit)
presets_14speed_tourian_terminator_revisit:
%cm_preset("Terminator Revisit", #preset_14speed_tourian_terminator_revisit)
presets_14speed_tourian_pirate_shaft_revisit:
%cm_preset("Pirate Shaft Revisit", #preset_14speed_tourian_pirate_shaft_revisit)
presets_14speed_tourian_metroids_1:
%cm_preset("Metroids 1", #preset_14speed_tourian_metroids_1)
presets_14speed_tourian_metroids_2:
%cm_preset("Metroids 2", #preset_14speed_tourian_metroids_2)
presets_14speed_tourian_metroids_3:
%cm_preset("Metroids 3", #preset_14speed_tourian_metroids_3)
presets_14speed_tourian_metroids_4:
%cm_preset("Metroids 4", #preset_14speed_tourian_metroids_4)
presets_14speed_tourian_doors_and_refills:
%cm_preset("Doors and Refills", #preset_14speed_tourian_doors_and_refills)
presets_14speed_tourian_zeb_skip:
%cm_preset("Zeb Skip", #preset_14speed_tourian_zeb_skip)
presets_14speed_tourian_mother_brain_2:
%cm_preset("Mother Brain 2", #preset_14speed_tourian_mother_brain_2)
presets_14speed_tourian_mother_brain_3:
%cm_preset("Mother Brain 3", #preset_14speed_tourian_mother_brain_3)
presets_14speed_tourian_zebes_escape:
%cm_preset("Zebes Escape", #preset_14speed_tourian_zebes_escape)
presets_14speed_tourian_escape_room_3:
%cm_preset("Escape Room 3", #preset_14speed_tourian_escape_room_3)
presets_14speed_tourian_escape_room_4:
%cm_preset("Escape Room 4", #preset_14speed_tourian_escape_room_4)
presets_14speed_tourian_escape_climb:
%cm_preset("Escape Climb", #preset_14speed_tourian_escape_climb)
presets_14speed_tourian_escape_parlor:
%cm_preset("Escape Parlor", #preset_14speed_tourian_escape_parlor)
|
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
#include "sys_dev_wifi_native.h"
// clang-format off
static const CLR_RT_MethodHandler method_lookup[] =
{
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Library_sys_dev_wifi_native_System_Device_Wifi_WifiAdapter::DisposeNative___VOID,
Library_sys_dev_wifi_native_System_Device_Wifi_WifiAdapter::NativeInit___VOID,
Library_sys_dev_wifi_native_System_Device_Wifi_WifiAdapter::NativeConnect___SystemDeviceWifiWifiConnectionStatus__STRING__STRING__SystemDeviceWifiWifiReconnectionKind,
Library_sys_dev_wifi_native_System_Device_Wifi_WifiAdapter::NativeDisconnect___VOID,
Library_sys_dev_wifi_native_System_Device_Wifi_WifiAdapter::NativeScanAsync___VOID,
Library_sys_dev_wifi_native_System_Device_Wifi_WifiAdapter::GetNativeScanReport___SZARRAY_U1,
NULL,
Library_sys_dev_wifi_native_System_Device_Wifi_WifiAdapter::NativeFindWirelessAdapters___STATIC__SZARRAY_U1,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
};
const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_System_Device_Wifi =
{
"System.Device.Wifi",
0x1C1D3214,
method_lookup,
{ 100, 0, 6, 4 }
};
// clang-format on
|
; A222257: Lexicographically earliest injective sequence of positive integers such that the sum of 6 consecutive terms is always divisible by 6.
; 1,2,3,4,5,9,7,8,15,10,11,21,13,14,27,16,17,33,19,20,39,22,23,45,25,26,51,28,29,57,31,32,63,34,35,69,37,38,75,40,41,81,43,44,87,46,47,93,49,50,99,52,53,105,55,56,111,58,59,117,61,62,123,64,65,129,67,68,135,70,71,141,73
sub $0,2
mov $1,$0
mov $2,3
gcd $2,$0
mul $2,$0
add $2,5037
add $1,$2
sub $1,5031
div $1,2
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; InterlockedCompareExchange64.Asm
;
; Abstract:
;
; InterlockedCompareExchange64 function
;
; Notes:
;
;------------------------------------------------------------------------------
.586P
.model flat,C
.code
;------------------------------------------------------------------------------
; UINT64
; EFIAPI
; InternalSyncCompareExchange64 (
; IN volatile UINT64 *Value,
; IN UINT64 CompareValue,
; IN UINT64 ExchangeValue
; );
;------------------------------------------------------------------------------
InternalSyncCompareExchange64 PROC USES esi ebx
mov esi, [esp + 12]
mov eax, [esp + 16]
mov edx, [esp + 20]
mov ebx, [esp + 24]
mov ecx, [esp + 28]
lock cmpxchg8b qword ptr [esi]
ret
InternalSyncCompareExchange64 ENDP
END
|
; signed long __fs2ulong_callee(float f)
SECTION code_fp_math48
PUBLIC cm48_sdccixp_ds2ulong_callee
EXTERN cm48_sdccixp_dcallee1, am48_dfix32u
cm48_sdccixp_ds2ulong_callee:
; double to unsigned long
;
; enter : stack = sdcc_float x, ret
;
; exit : dehl = (unsigned long)(x)
;
; uses : af, bc, de, hl, bc', de', hl'
call cm48_sdccixp_dcallee1 ; AC'= math48(x)
jp am48_dfix32u
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r15
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0x1291f, %rdx
nop
nop
nop
nop
sub %rdi, %rdi
movb (%rdx), %r15b
nop
nop
nop
cmp $17390, %rsi
lea addresses_A_ht+0x1902b, %rsi
lea addresses_WC_ht+0x706b, %rdi
nop
nop
nop
inc %rbp
mov $20, %rcx
rep movsl
xor %rdi, %rdi
lea addresses_UC_ht+0x1b6d9, %rsi
clflush (%rsi)
nop
sub $7648, %r10
mov (%rsi), %rdx
nop
nop
nop
nop
dec %rbp
lea addresses_normal_ht+0x1d86b, %r10
nop
xor %rsi, %rsi
mov (%r10), %ecx
add $37086, %rbp
lea addresses_UC_ht+0xd8eb, %rbp
nop
nop
cmp $48950, %rdx
movl $0x61626364, (%rbp)
nop
nop
sub $24108, %r10
lea addresses_A_ht+0xbd83, %rsi
nop
nop
nop
nop
sub %rcx, %rcx
movups (%rsi), %xmm3
vpextrq $1, %xmm3, %r15
nop
nop
cmp %r10, %r10
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r15
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r15
push %rax
push %rcx
push %rdi
push %rdx
// Faulty Load
lea addresses_D+0x1486b, %rdi
nop
nop
nop
xor $31825, %rdx
mov (%rdi), %r15d
lea oracles, %rcx
and $0xff, %r15
shlq $12, %r15
mov (%rcx,%r15,1), %r15
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r15
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_D', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 2, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 10, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 6, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 3, 'size': 16, 'same': False, 'NT': False}}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r8
push %rdx
push %rsi
lea addresses_UC_ht+0x5629, %r8
add $14060, %r12
mov (%r8), %rsi
nop
nop
nop
add $62893, %rdx
pop %rsi
pop %rdx
pop %r8
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r14
push %r15
push %rbx
push %rsi
// Store
mov $0xd11, %r14
nop
nop
nop
lfence
mov $0x5152535455565758, %r10
movq %r10, %xmm1
movups %xmm1, (%r14)
xor %r14, %r14
// Faulty Load
lea addresses_A+0x18b29, %r11
nop
nop
nop
add $34970, %r15
mov (%r11), %r10w
lea oracles, %rbx
and $0xff, %r10
shlq $12, %r10
mov (%rbx,%r10,1), %r10
pop %rsi
pop %rbx
pop %r15
pop %r14
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_P', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_A', 'NT': True, 'AVXalign': False, 'size': 2, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
%include "include/PagingInit.mac"
[BITS 16]
;********************************************************************************************************
;Generacion de paginas para el mappeo de los 4 primeros megas de memoria en identity mapping
;
;
;********************************************************************************************************
RealModePageInit:
;INICIO Creacion de paginas
;notar que estoy en modo real por lo que las direcciones salen de la suma de DUP:_PML4_BASE
xor eax,eax
mov eax, DUP
mov ds, eax
mov dword [DS:_PML4_BASE],PDPT_BASE + 0x17;0x11
mov dword [DS:_PML4_BASE + 4], 0
mov dword [DS:_PDPT_BASE],PDT_BASE + 0x17;0x11
mov dword [DS:_PDPT_BASE + 4], 0
mov dword [DS:_PDT_BASE],PT_BASE + 0x17;0x11
mov dword [DS:_PDT_BASE + 4], 0
mov dword [DS:_PDT_BASE + 8],PT_BASE + 0x1000 + 0x17;0x11
mov dword [DS:_PDT_BASE + 12], 0
;Aca arrancamos a crear las paginas con un loop
mov ecx, 1024 ;creo 1024 entradas, (2 pt) 512 por pt
mov eax, 01000h + 0x07;0x01 ;0x07 para W
mov edi, _PT_BASE + 8
pageloop:
mov dword [DS:edi],eax
mov dword [DS:edi + 4],0
add edi, 8
add eax, 1000h
loop pageloop
mov dword [DS:_PT_BASE + 0x40 ],0x8000 + 1
mov dword [DS:_PT_BASE + 4], 0
mov dword [DS:_PT_BASE + 0x48 ],0x9000 + 1
mov dword [DS:_PT_BASE + 4], 0
;pagina de usuario para las tareas en 0xA000
;mov dword [DS:_PT_BASE + 0x50 ],USER_PAGE + 7;0x07 ;x50 es la 0xa000
;mov dword [DS:_PT_BASE + 4], 0
;pagina de usuario para las tareas en 0xA000
;mov dword [DS:_PT_BASE + 0x58 ],0xb000 + 5;0x07 ;x50 es la 0xa000
;mov dword [DS:_PT_BASE + 4], 0
;en la 0x0000 pagino la b8000 de video
mov dword [DS:_PT_BASE],0b8000h + 0x01
mov dword [DS:_PT_BASE + 4], 0
;FIN CREACION PAGINAS
xor eax,eax
mov ds, eax
mov eax, DUP
shl eax,4
add eax,_PML4_BASE
mov cr3,eax
xor eax,eax
ret
[bits 64]
;********************************************************************************************************
;Inicializacion de tablas para la Tarea A
;********************************************************************************************************
Task_A_PagingInit:
xor eax,eax
mov dword [PML4_BASE_TA],PDPT_BASE_TA + 0x17
mov dword [PML4_BASE_TA + 4], 0
mov dword [PDPT_BASE_TA],PDT_BASE_TA + 0x17
mov dword [PDPT_BASE_TA + 4], 0
mov dword [PDT_BASE_TA],PT_BASE_TA + 0x17
mov dword [PDT_BASE_TA + 4], 0
mov dword [PDT_BASE_TA + 8],PT_BASE_TA + 0x1000 + 0x17
mov dword [PDT_BASE_TA + 12], 0
;*********************Paginas visibles para la task en prioridad kernel*********************/
;en la 0x0000 pagino la b8000 de video
mov dword [PT_BASE_TA],0b8000h + 0x01
mov dword [PT_BASE_TA + 4], 0
mov dword [PT_BASE_TA + 0x40 ],0x8000 + 1
mov dword [PT_BASE_TA + 0x44], 0
mov dword [PT_BASE_TA + 0x48 ],0x9000 + 1
mov dword [PT_BASE_TA + 0x4C], 0
mov dword [PT_BASE_TA + 0x50 ],0xA000 + 1
mov dword [PT_BASE_TA + 0x54], 0
mov dword [PT_BASE_TA + 0x58 ],0xB000 + 1
mov dword [PT_BASE_TA + 0x5C], 0
;**********************Paginas de usuario de la task***************************************/
;pagina de usuario para la tarea
mov dword [PT_BASE_TA + 0x60 ],0xC000 + 0x17;0x07 ;a la zona de memoria de la tarea le doy RPL user
mov dword [PT_BASE_TA + 0x64], 0
ret
;********************************************************************************************************
;Inicializacion de tablas para la Tarea B
;********************************************************************************************************
Task_B_PagingInit:
xor eax,eax
mov dword [PML4_BASE_TB],PDPT_BASE_TB + 0x17
mov dword [PML4_BASE_TB + 4], 0
mov dword [PDPT_BASE_TB],PDT_BASE_TB + 0x17
mov dword [PDPT_BASE_TB + 4], 0
mov dword [PDT_BASE_TB],PT_BASE_TB + 0x17
mov dword [PDT_BASE_TB + 4], 0
mov dword [PDT_BASE_TB + 8],PT_BASE_TB + 0x1000 + 0x17
mov dword [PDT_BASE_TB + 12], 0
;*********************Paginas visibles para la task en prioridad kernel*********************/
;en la 0x0000 pagino la b8000 de video
mov dword [PT_BASE_TB],0b8000h + 0x01
mov dword [PT_BASE_TB + 4], 0
mov dword [PT_BASE_TB + 0x40 ],0x8000 + 1
mov dword [PT_BASE_TB + 0x44], 0
mov dword [PT_BASE_TB + 0x48 ],0x9000 + 1
mov dword [PT_BASE_TB + 0x4C], 0
mov dword [PT_BASE_TB + 0x50 ],0xA000 + 1
mov dword [PT_BASE_TB + 0x54], 0
mov dword [PT_BASE_TB + 0x58 ],0xB000 + 1
mov dword [PT_BASE_TB + 0x5C], 0
;**********************Paginas de usuario de la task***************************************/
;pagina de usuario para la tarea
mov dword [PT_BASE_TB + 0x68 ],0xD000 + 0x17;0x07 ;a la zona de memoria de la tarea le doy RPL user
mov dword [PT_BASE_TB + 0x6C], 0
ret
;********************************************************************************************************
;Inicializacion de tablas para la Tarea C
;********************************************************************************************************
Task_C_PagingInit:
xor eax,eax
mov dword [PML4_BASE_TC],PDPT_BASE_TC + 0x17
mov dword [PML4_BASE_TC + 4], 0
mov dword [PDPT_BASE_TC],PDT_BASE_TC + 0x17
mov dword [PDPT_BASE_TC + 4], 0
mov dword [PDT_BASE_TC],PT_BASE_TC + 0x17
mov dword [PDT_BASE_TC + 4], 0
mov dword [PDT_BASE_TC + 8],PT_BASE_TC + 0x1000 + 0x17
mov dword [PDT_BASE_TC + 12], 0
;*********************Paginas visibles para la task en prioridad kernel*********************/
;en la 0x0000 pagino la b8000 de video
mov dword [PT_BASE_TC],0b8000h + 0x01
mov dword [PT_BASE_TC + 4], 0
mov dword [PT_BASE_TC + 0x40 ],0x8000 + 1
mov dword [PT_BASE_TC + 0x44], 0
mov dword [PT_BASE_TC + 0x48 ],0x9000 + 1
mov dword [PT_BASE_TC + 0x4C], 0
mov dword [PT_BASE_TC + 0x50 ],0xA000 + 1
mov dword [PT_BASE_TC + 0x54], 0
mov dword [PT_BASE_TC + 0x58 ],0xB000 + 1
mov dword [PT_BASE_TC + 0x5C], 0
;**********************Paginas de usuario de la task***************************************/
;pagina de usuario para la tarea
mov dword [PT_BASE_TC + 0x70 ],0xE000 + 0x17;0x07 ;a la zona de memoria de la tarea le doy RPL user
mov dword [PT_BASE_TC + 0x74], 0
ret
;********************************************************************************************************
;Inicializacion de tablas para la Tarea C
;********************************************************************************************************
Task_D_PagingInit:
xor eax,eax
mov dword [PML4_BASE_TD],PDPT_BASE_TD + 0x17
mov dword [PML4_BASE_TD + 4], 0
mov dword [PDPT_BASE_TD],PDT_BASE_TD + 0x17
mov dword [PDPT_BASE_TD + 4], 0
mov dword [PDT_BASE_TD],PT_BASE_TD + 0x17
mov dword [PDT_BASE_TD + 4], 0
mov dword [PDT_BASE_TD + 8],PT_BASE_TD + 0x1000 + 0x17
mov dword [PDT_BASE_TD + 12], 0
;*********************Paginas visibles para la task en prioridad kernel*********************/
;en la 0x0000 pagino la b8000 de video
mov dword [PT_BASE_TD],0b8000h + 0x01
mov dword [PT_BASE_TD + 4], 0
mov dword [PT_BASE_TD + 0x40 ],0x8000 + 1
mov dword [PT_BASE_TD + 0x44], 0
mov dword [PT_BASE_TD + 0x48 ],0x9000 + 1
mov dword [PT_BASE_TD + 0x4C], 0
mov dword [PT_BASE_TD + 0x50 ],0xA000 + 1
mov dword [PT_BASE_TD + 0x54], 0
mov dword [PT_BASE_TD + 0x58 ],0xB000 + 1
mov dword [PT_BASE_TD + 0x5C], 0
;**********************Paginas de usuario de la task***************************************/
;pagina de usuario para la tarea
mov dword [PT_BASE_TD + 0x78 ],0xF000 + 0x17;0x07 ;a la zona de memoria de la tarea le doy RPL user
mov dword [PT_BASE_TD + 0x7C], 0
ret
|
;
; i8254 演奏 Test (チャネル2使用)
;
;==============================================
;使用例)
;>G 7000 CDEFGABO5C
;>G 7000 CDEFEDCR4EFGAGFER4O4CR4CR4CR4CR4L8CCDDEEFFL4EDC
;
org 7000h
;
PIT_C2 EQU 1Ah
PIT_CWR EQU 1Bh
;
C2_MODE0 EQU 0B0h
C2_MODE3 EQU 0B6h
;
SOUND_WAIT EQU 60000
SOUND_WAIT8 EQU 30000
NO_SOUND_WAIT EQU 100
;
;------------------------------------
; 処理メイン
;------------------------------------
MAIN:
;
LD HL,START_MSG
CALL STR_PR
;
LD A,4
CALL OCT_TBL_SET
LD HL,SOUND_WAIT
LD A,L
LD (SOUND_WAIT_TIME),A
LD A,H
LD (SOUND_WAIT_TIME+1),A
;
INC DE
INC DE
LD A,(DE)
LD L,A
INC DE
LD A,(DE)
LD H,A
;
_MAIN_LOOP:
LD DE,_MAIN_LOOP_NEXT
PUSH DE
;
LD A,(HL)
OR A
JR Z,_MAIN_LOOP_EXIT
;
CP 'O'
JR Z,OCT_CHG
;
CP 'R'
JR Z,REST
;
CP 'L'
JR Z,LEN_SET
;
JR SRCH_OUT
_MAIN_LOOP_NEXT:
INC HL
JR _MAIN_LOOP
;
_MAIN_LOOP_EXIT:
POP DE
LD HL,END_MSG
CALL STR_PR
RET
;
;------------------------------------
; 音の長さセット
;------------------------------------
LEN_SET:
INC HL
LD A,(HL)
PUSH HL
CP '4'
JR Z,_LEN_4
CP '8'
JR Z,_LEN_8
JR _LEN_SET_END
;
_LEN_4:
LD HL,SOUND_WAIT
LD A,L
LD (SOUND_WAIT_TIME),A
LD A,H
LD (SOUND_WAIT_TIME+1),A
JR _LEN_SET_END
;
_LEN_8
LD HL,SOUND_WAIT8
LD A,L
LD (SOUND_WAIT_TIME),A
LD A,H
LD (SOUND_WAIT_TIME+1),A
;
_LEN_SET_END:
POP HL
RET
;
;------------------------------------
; 休符
;------------------------------------
REST:
INC HL
LD A,(HL)
CP '4'
JR Z,_WAIT_4
CP '8'
JR Z,_WAIT_8
RET
;
_WAIT_4:
LD BC,SOUND_WAIT
JP WAIT
_WAIT_8
LD BC,SOUND_WAIT8
JP WAIT
;------------------------------------
; オクターブ変更
;------------------------------------
OCT_CHG:
INC HL
LD A,(HL)
SUB 30h
CALL OCT_TBL_SET
RET
;
;------------------------------------
; オクターブテーブルセット
;------------------------------------
OCT_TBL_SET:
PUSH BC
LD B,A
LD IY,OCT_TBL
_OCT_SET_LOOP:
DEC B
JR Z,_OCT_SET_EXIT
INC IY
INC IY
LD A,(IY+0)
CP 0FFh
JR Z,_OCT_SET_ERR
JR _OCT_SET_LOOP
;
_OCT_SET_ERR:
LD IY,OCT4
_OCT_SET_EXIT:
POP BC
RET
;------------------------------------
; 音検索検索&発声
;------------------------------------
SRCH_OUT:
LD E,(IY+0)
LD D,(IY+1)
PUSH DE
POP IX
LD D,7
_SRCH_LOOP:
LD A,(IX+0)
CP (HL)
JR Z,_SOUND_OUT
INC IX
INC IX
INC IX
DEC D
JR NZ,_SRCH_LOOP
RET
;
_SOUND_OUT:
LD A,(IX+0)
RST 08h
CALL CRLF_PR
CALL OUT_PIT
RET
;------------------------------------
; 1音発声
;------------------------------------
OUT_PIT:
LD A,C2_MODE3
OUT (PIT_CWR),A
LD A,(IX+1)
OUT (PIT_C2),A
LD A,(IX+2)
OUT (PIT_C2),A
LD BC,(SOUND_WAIT_TIME)
CALL WAIT
;
LD A,C2_MODE0
OUT (PIT_CWR),A
LD BC,NO_SOUND_WAIT
CALL WAIT
;
RET
;
;------------------------------------
; WAIT
;------------------------------------
WAIT:
LD A,A ; DUMMY
DEC BC
LD A,C
OR B
RET Z
JR WAIT
;
;------------------------------------
; 文字列 コンソール出力
;------------------------------------
STR_PR:
PUSH HL
_STR_PR_LOOP:
LD A,(HL)
OR A
JR Z,_STR_PR_EXIT
RST 08h
INC HL
JR _STR_PR_LOOP
;
_STR_PR_EXIT:
POP HL
RET
;
;------------------------------------
; CRLF コンソール出力
;------------------------------------
CRLF_PR:
PUSH AF
LD A,0Dh
RST 08h
LD A,0Ah
RST 08h
POP AF
RET
;
START_MSG DB "++ 8254 PLAY START ++",13,10,0
END_MSG DB "-- 8254 PLAY END --",13,10,0
;
OCT_TBL:
DW 0000h
DW 0000h
DW 0000h
DW OCT4
DW OCT5
DW 0FFFFh
;
;-----
; 音程データ
;-----
SOUND_DATA:
OCT4:
; ド
DB "C"
DW 1258h
; レ
DB "D"
DW 1058h
; ミ
DB "E"
DW 0E8Fh
; ファ
DB "F"
DW 0DBEh
; ソ
DB "G"
DW 0C3Eh
; ラ
DB "A"
DW 0AE8h
; シ
DB "B"
DW 9B8h
OCT5:
; ド
DB "C"
DW 92Ch
; レ
DB "D"
DW 82Ch
; ミ
DB "E"
DW 747h
; ファ
DB "F"
DW 6Dfh
; ソ
DB "G"
DW 61Fh
; ラ
DB "A"
DW 574h
; シ
DB "B"
DW 4DCh
;END
DB 00h
DW 0000h
; 変数
SOUND_WAIT_TIME DS 2
END |
; A100131: a(n) = Sum_{k=0..floor(n/4)} binomial(n-2k, 2k)*2^(n-4k).
; 1,2,4,8,17,38,88,208,497,1194,2876,6936,16737,40398,97520,235424,568353,1372114,3312564,7997224,19306993,46611190,112529352,271669872,655869073,1583407994,3822685036,9228778040,22280241089,53789260190,129858761440,313506783040,756872327489,1827251437986,4411375203428,10650001844808,25711378893009,62072759630790,149856898154552,361786555939856,873430010034225,2108646576008266,5090723162050716
add $0,2
mov $3,4
lpb $0,1
sub $0,1
mov $1,$3
add $1,$4
add $2,$4
add $2,1
mov $4,$2
trn $2,4
add $2,$1
trn $4,$3
add $3,1
lpe
sub $1,4
|
; A036547: a(n) = T(6,n), array T given by A048471.
; 1,65,257,833,2561,7745,23297,69953,209921,629825,1889537,5668673,17006081,51018305,153054977,459164993,1377495041,4132485185,12397455617,37192366913,111577100801,334731302465,1004193907457,3012581722433,9037745167361,27113235502145,81339706506497,244019119519553,732057358558721,2196172075676225,6588516227028737,19765548681086273,59296646043258881,177889938129776705,533669814389330177,1601009443167990593,4803028329503971841,14409084988511915585,43227254965535746817,129681764896607240513,389045294689821721601,1167135884069465164865,3501407652208395494657,10504222956625186484033,31512668869875559452161,94538006609626678356545,283614019828880035069697,850842059486640105209153,2552526178459920315627521,7657578535379760946882625,22972735606139282840647937,68918206818417848521943873,206754620455253545565831681,620263861365760636697495105,1860791584097281910092485377,5582374752291845730277456193,16747124256875537190832368641,50241372770626611572497105985,150724118311879834717491318017,452172354935639504152473954113,1356517064806918512457421862401,4069551194420755537372265587265,12208653583262266612116796761857,36625960749786799836350390285633,109877882249360399509051170856961,329633646748081198527153512570945,988900940244243595581460537712897,2966702820732730786744381613138753,8900108462198192360233144839416321,26700325386594577080699434518249025,80100976159783731242098303554747137,240302928479351193726294910664241473,720908785438053581178884731992724481
mov $1,3
pow $1,$0
div $1,2
mul $1,64
add $1,1
mov $0,$1
|
#ifndef VIENNACL_LINALG_LANCZOS_HPP_
#define VIENNACL_LINALG_LANCZOS_HPP_
/* =========================================================================
Copyright (c) 2010-2016, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
Portions of this software are copyright by UChicago Argonne, LLC.
-----------------
ViennaCL - The Vienna Computing Library
-----------------
Project Head: Karl Rupp rupp@iue.tuwien.ac.at
(A list of authors and contributors can be found in the manual)
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
/** @file viennacl/linalg/lanczos.hpp
* @brief Generic interface for the Lanczos algorithm.
*
* Contributed by Guenther Mader and Astrid Rupp.
*/
#include <cmath>
#include <vector>
#include "viennacl/vector.hpp"
#include "viennacl/compressed_matrix.hpp"
#include "viennacl/linalg/prod.hpp"
#include "viennacl/linalg/inner_prod.hpp"
#include "viennacl/linalg/norm_2.hpp"
#include "viennacl/io/matrix_market.hpp"
#include "viennacl/linalg/bisect.hpp"
#include "viennacl/tools/random.hpp"
namespace viennacl
{
namespace linalg
{
/** @brief A tag for the lanczos algorithm.
*/
class lanczos_tag
{
public:
enum
{
partial_reorthogonalization = 0,
full_reorthogonalization,
no_reorthogonalization
};
/** @brief The constructor
*
* @param factor Exponent of epsilon - tolerance for batches of Reorthogonalization
* @param numeig Number of eigenvalues to be returned
* @param met Method for Lanczos-Algorithm: 0 for partial Reorthogonalization, 1 for full Reorthogonalization and 2 for Lanczos without Reorthogonalization
* @param krylov Maximum krylov-space size
*/
lanczos_tag(double factor = 0.75,
vcl_size_t numeig = 10,
int met = 0,
vcl_size_t krylov = 100) : factor_(factor), num_eigenvalues_(numeig), method_(met), krylov_size_(krylov) {}
/** @brief Sets the number of eigenvalues */
void num_eigenvalues(vcl_size_t numeig){ num_eigenvalues_ = numeig; }
/** @brief Returns the number of eigenvalues */
vcl_size_t num_eigenvalues() const { return num_eigenvalues_; }
/** @brief Sets the exponent of epsilon. Values between 0.6 and 0.9 usually give best results. */
void factor(double fct) { factor_ = fct; }
/** @brief Returns the exponent */
double factor() const { return factor_; }
/** @brief Sets the size of the kylov space. Must be larger than number of eigenvalues to compute. */
void krylov_size(vcl_size_t max) { krylov_size_ = max; }
/** @brief Returns the size of the kylov space */
vcl_size_t krylov_size() const { return krylov_size_; }
/** @brief Sets the reorthogonalization method */
void method(int met){ method_ = met; }
/** @brief Returns the reorthogonalization method */
int method() const { return method_; }
private:
double factor_;
vcl_size_t num_eigenvalues_;
int method_; // see enum defined above for possible values
vcl_size_t krylov_size_;
};
namespace detail
{
/** @brief Inverse iteration for finding an eigenvector for an eigenvalue.
*
* beta[0] to be ignored for consistency.
*/
template<typename NumericT>
void inverse_iteration(std::vector<NumericT> const & alphas, std::vector<NumericT> const & betas,
NumericT & eigenvalue, std::vector<NumericT> & eigenvector)
{
std::vector<NumericT> alpha_sweeped = alphas;
for (vcl_size_t i=0; i<alpha_sweeped.size(); ++i)
alpha_sweeped[i] -= eigenvalue;
for (vcl_size_t row=1; row < alpha_sweeped.size(); ++row)
alpha_sweeped[row] -= betas[row] * betas[row] / alpha_sweeped[row-1];
// starting guess: ignore last equation
eigenvector[alphas.size() - 1] = 1.0;
for (vcl_size_t iter=0; iter<1; ++iter)
{
// solve first n-1 equations (A - \lambda I) y = -beta[n]
eigenvector[alphas.size() - 1] /= alpha_sweeped[alphas.size() - 1];
for (vcl_size_t row2=1; row2 < alphas.size(); ++row2)
{
vcl_size_t row = alphas.size() - row2 - 1;
eigenvector[row] -= eigenvector[row+1] * betas[row+1];
eigenvector[row] /= alpha_sweeped[row];
}
// normalize eigenvector:
NumericT norm_vector = 0;
for (vcl_size_t i=0; i<eigenvector.size(); ++i)
norm_vector += eigenvector[i] * eigenvector[i];
norm_vector = std::sqrt(norm_vector);
for (vcl_size_t i=0; i<eigenvector.size(); ++i)
eigenvector[i] /= norm_vector;
}
//eigenvalue = (alphas[0] * eigenvector[0] + betas[1] * eigenvector[1]) / eigenvector[0];
}
/**
* @brief Implementation of the Lanczos PRO algorithm (partial reorthogonalization)
*
* @param A The system matrix
* @param r Random start vector
* @param eigenvectors_A Dense matrix holding the eigenvectors of A (one eigenvector per column)
* @param size Size of krylov-space
* @param tag Lanczos_tag with several options for the algorithm
* @param compute_eigenvectors Boolean flag. If true, eigenvectors are computed. Otherwise the routine returns after calculating eigenvalues.
* @return Returns the eigenvalues (number of eigenvalues equals size of krylov-space)
*/
template<typename MatrixT, typename DenseMatrixT, typename NumericT>
std::vector<NumericT>
lanczosPRO (MatrixT const& A, vector_base<NumericT> & r, DenseMatrixT & eigenvectors_A, vcl_size_t size, lanczos_tag const & tag, bool compute_eigenvectors)
{
// generation of some random numbers, used for lanczos PRO algorithm
viennacl::tools::normal_random_numbers<NumericT> get_N;
std::vector<vcl_size_t> l_bound(size/2), u_bound(size/2);
vcl_size_t n = r.size();
std::vector<NumericT> w(size), w_old(size); //w_k, w_{k-1}
NumericT inner_rt;
std::vector<NumericT> alphas, betas;
viennacl::matrix<NumericT, viennacl::column_major> Q(n, size); //column-major matrix holding the Krylov basis vectors
bool second_step = false;
NumericT eps = std::numeric_limits<NumericT>::epsilon();
NumericT squ_eps = std::sqrt(eps);
NumericT eta = std::exp(std::log(eps) * tag.factor());
NumericT beta = viennacl::linalg::norm_2(r);
r /= beta;
viennacl::vector_base<NumericT> q_0(Q.handle(), Q.size1(), 0, 1);
q_0 = r;
viennacl::vector<NumericT> u = viennacl::linalg::prod(A, r);
NumericT alpha = viennacl::linalg::inner_prod(u, r);
alphas.push_back(alpha);
w[0] = 1;
betas.push_back(beta);
vcl_size_t batches = 0;
for (vcl_size_t i = 1; i < size; i++) // Main loop for setting up the Krylov space
{
viennacl::vector_base<NumericT> q_iminus1(Q.handle(), Q.size1(), (i-1) * Q.internal_size1(), 1);
r = u - alpha * q_iminus1;
beta = viennacl::linalg::norm_2(r);
betas.push_back(beta);
r = r / beta;
//
// Update recurrence relation for estimating orthogonality loss
//
w_old = w;
w[0] = (betas[1] * w_old[1] + (alphas[0] - alpha) * w_old[0] - betas[i - 1] * w_old[0]) / beta + eps * 0.3 * get_N() * (betas[1] + beta);
for (vcl_size_t j = 1; j < i - 1; j++)
w[j] = (betas[j + 1] * w_old[j + 1] + (alphas[j] - alpha) * w_old[j] + betas[j] * w_old[j - 1] - betas[i - 1] * w_old[j]) / beta + eps * 0.3 * get_N() * (betas[j + 1] + beta);
w[i-1] = 0.6 * eps * NumericT(n) * get_N() * betas[1] / beta;
//
// Check whether there has been a need for reorthogonalization detected in the previous iteration.
// If so, run the reorthogonalization for each batch
//
if (second_step)
{
for (vcl_size_t j = 0; j < batches; j++)
{
for (vcl_size_t k = l_bound[j] + 1; k < u_bound[j] - 1; k++)
{
viennacl::vector_base<NumericT> q_k(Q.handle(), Q.size1(), k * Q.internal_size1(), 1);
inner_rt = viennacl::linalg::inner_prod(r, q_k);
r = r - inner_rt * q_k;
w[k] = 1.5 * eps * get_N();
}
}
NumericT temp = viennacl::linalg::norm_2(r);
r = r / temp;
beta = beta * temp;
second_step = false;
}
batches = 0;
//
// Check for semiorthogonality
//
for (vcl_size_t j = 0; j < i; j++)
{
if (std::fabs(w[j]) >= squ_eps) // tentative loss of orthonormality, hence reorthonomalize
{
viennacl::vector_base<NumericT> q_j(Q.handle(), Q.size1(), j * Q.internal_size1(), 1);
inner_rt = viennacl::linalg::inner_prod(r, q_j);
r = r - inner_rt * q_j;
w[j] = 1.5 * eps * get_N();
vcl_size_t k = j - 1;
// orthogonalization with respect to earlier basis vectors
while (std::fabs(w[k]) > eta)
{
viennacl::vector_base<NumericT> q_k(Q.handle(), Q.size1(), k * Q.internal_size1(), 1);
inner_rt = viennacl::linalg::inner_prod(r, q_k);
r = r - inner_rt * q_k;
w[k] = 1.5 * eps * get_N();
if (k == 0) break;
k--;
}
l_bound[batches] = k;
// orthogonalization with respect to later basis vectors
k = j + 1;
while (k < i && std::fabs(w[k]) > eta)
{
viennacl::vector_base<NumericT> q_k(Q.handle(), Q.size1(), k * Q.internal_size1(), 1);
inner_rt = viennacl::linalg::inner_prod(r, q_k);
r = r - inner_rt * q_k;
w[k] = 1.5 * eps * get_N();
k++;
}
u_bound[batches] = k - 1;
batches++;
j = k-1; // go to end of current batch
}
}
//
// Normalize basis vector and reorthogonalize as needed
//
if (batches > 0)
{
NumericT temp = viennacl::linalg::norm_2(r);
r = r / temp;
beta = beta * temp;
second_step = true;
}
// store Krylov vector in Q:
viennacl::vector_base<NumericT> q_i(Q.handle(), Q.size1(), i * Q.internal_size1(), 1);
q_i = r;
//
// determine and store alpha = <r, u> with u = A q_i - beta q_{i-1}
//
u = viennacl::linalg::prod(A, r);
u += (-beta) * q_iminus1;
alpha = viennacl::linalg::inner_prod(u, r);
alphas.push_back(alpha);
}
//
// Step 2: Compute eigenvalues of tridiagonal matrix obtained during Lanczos iterations:
//
std::vector<NumericT> eigenvalues = bisect(alphas, betas);
//
// Step 3: Compute eigenvectors via inverse iteration. Does not update eigenvalues, so only approximate by nature.
//
if (compute_eigenvectors)
{
std::vector<NumericT> eigenvector_tridiag(alphas.size());
for (std::size_t i=0; i < tag.num_eigenvalues(); ++i)
{
// compute eigenvector of tridiagonal matrix via inverse:
inverse_iteration(alphas, betas, eigenvalues[eigenvalues.size() - i - 1], eigenvector_tridiag);
// eigenvector w of full matrix A. Given as w = Q * u, where u is the eigenvector of the tridiagonal matrix
viennacl::vector<NumericT> eigenvector_u(eigenvector_tridiag.size());
viennacl::copy(eigenvector_tridiag, eigenvector_u);
viennacl::vector_base<NumericT> eigenvector_A(eigenvectors_A.handle(),
eigenvectors_A.size1(),
eigenvectors_A.row_major() ? i : i * eigenvectors_A.internal_size1(),
eigenvectors_A.row_major() ? eigenvectors_A.internal_size2() : 1);
eigenvector_A = viennacl::linalg::prod(project(Q,
range(0, Q.size1()),
range(0, eigenvector_u.size())),
eigenvector_u);
}
}
return eigenvalues;
}
/**
* @brief Implementation of the Lanczos FRO algorithm
*
* @param A The system matrix
* @param r Random start vector
* @param eigenvectors_A A dense matrix in which the eigenvectors of A will be stored. Both row- and column-major matrices are supported.
* @param krylov_dim Size of krylov-space
* @param tag The Lanczos tag holding tolerances, etc.
* @param compute_eigenvectors Boolean flag. If true, eigenvectors are computed. Otherwise the routine returns after calculating eigenvalues.
* @return Returns the eigenvalues (number of eigenvalues equals size of krylov-space)
*/
template< typename MatrixT, typename DenseMatrixT, typename NumericT>
std::vector<NumericT>
lanczos(MatrixT const& A, vector_base<NumericT> & r, DenseMatrixT & eigenvectors_A, vcl_size_t krylov_dim, lanczos_tag const & tag, bool compute_eigenvectors)
{
std::vector<NumericT> alphas, betas;
viennacl::vector<NumericT> Aq(r.size());
viennacl::matrix<NumericT, viennacl::column_major> Q(r.size(), krylov_dim + 1); // Krylov basis (each Krylov vector is one column)
NumericT norm_r = norm_2(r);
NumericT beta = norm_r;
r /= norm_r;
// first Krylov vector:
viennacl::vector_base<NumericT> q0(Q.handle(), Q.size1(), 0, 1);
q0 = r;
//
// Step 1: Run Lanczos' method to obtain tridiagonal matrix
//
for (vcl_size_t i = 0; i < krylov_dim; i++)
{
betas.push_back(beta);
// last available vector from Krylov basis:
viennacl::vector_base<NumericT> q_i(Q.handle(), Q.size1(), i * Q.internal_size1(), 1);
// Lanczos algorithm:
// - Compute A * q:
Aq = viennacl::linalg::prod(A, q_i);
// - Form Aq <- Aq - <Aq, q_i> * q_i - beta * q_{i-1}, where beta is ||q_i|| before normalization in previous iteration
NumericT alpha = viennacl::linalg::inner_prod(Aq, q_i);
Aq -= alpha * q_i;
if (i > 0)
{
viennacl::vector_base<NumericT> q_iminus1(Q.handle(), Q.size1(), (i-1) * Q.internal_size1(), 1);
Aq -= beta * q_iminus1;
// Extra measures for improved numerical stability?
if (tag.method() == lanczos_tag::full_reorthogonalization)
{
// Gram-Schmidt (re-)orthogonalization:
// TODO: Reuse fast (pipelined) routines from GMRES or GEMV
for (vcl_size_t j = 0; j < i; j++)
{
viennacl::vector_base<NumericT> q_j(Q.handle(), Q.size1(), j * Q.internal_size1(), 1);
NumericT inner_rq = viennacl::linalg::inner_prod(Aq, q_j);
Aq -= inner_rq * q_j;
}
}
}
// normalize Aq and add to Krylov basis at column i+1 in Q:
beta = viennacl::linalg::norm_2(Aq);
viennacl::vector_base<NumericT> q_iplus1(Q.handle(), Q.size1(), (i+1) * Q.internal_size1(), 1);
q_iplus1 = Aq / beta;
alphas.push_back(alpha);
}
//
// Step 2: Compute eigenvalues of tridiagonal matrix obtained during Lanczos iterations:
//
std::vector<NumericT> eigenvalues = bisect(alphas, betas);
//
// Step 3: Compute eigenvectors via inverse iteration. Does not update eigenvalues, so only approximate by nature.
//
if (compute_eigenvectors)
{
std::vector<NumericT> eigenvector_tridiag(alphas.size());
for (std::size_t i=0; i < tag.num_eigenvalues(); ++i)
{
// compute eigenvector of tridiagonal matrix via inverse:
inverse_iteration(alphas, betas, eigenvalues[eigenvalues.size() - i - 1], eigenvector_tridiag);
// eigenvector w of full matrix A. Given as w = Q * u, where u is the eigenvector of the tridiagonal matrix
viennacl::vector<NumericT> eigenvector_u(eigenvector_tridiag.size());
viennacl::copy(eigenvector_tridiag, eigenvector_u);
viennacl::vector_base<NumericT> eigenvector_A(eigenvectors_A.handle(),
eigenvectors_A.size1(),
eigenvectors_A.row_major() ? i : i * eigenvectors_A.internal_size1(),
eigenvectors_A.row_major() ? eigenvectors_A.internal_size2() : 1);
eigenvector_A = viennacl::linalg::prod(project(Q,
range(0, Q.size1()),
range(0, eigenvector_u.size())),
eigenvector_u);
}
}
return eigenvalues;
}
} // end namespace detail
/**
* @brief Implementation of the calculation of eigenvalues using lanczos (with and without reorthogonalization).
*
* Implementation of Lanczos with partial reorthogonalization is implemented separately.
*
* @param matrix The system matrix
* @param eigenvectors_A A dense matrix in which the eigenvectors of A will be stored. Both row- and column-major matrices are supported.
* @param tag Tag with several options for the lanczos algorithm
* @param compute_eigenvectors Boolean flag. If true, eigenvectors are computed. Otherwise the routine returns after calculating eigenvalues.
* @return Returns the n largest eigenvalues (n defined in the lanczos_tag)
*/
template<typename MatrixT, typename DenseMatrixT>
std::vector< typename viennacl::result_of::cpu_value_type<typename MatrixT::value_type>::type >
eig(MatrixT const & matrix, DenseMatrixT & eigenvectors_A, lanczos_tag const & tag, bool compute_eigenvectors = true)
{
typedef typename viennacl::result_of::value_type<MatrixT>::type NumericType;
typedef typename viennacl::result_of::cpu_value_type<NumericType>::type CPU_NumericType;
typedef typename viennacl::result_of::vector_for_matrix<MatrixT>::type VectorT;
viennacl::tools::uniform_random_numbers<CPU_NumericType> random_gen;
std::vector<CPU_NumericType> eigenvalues;
vcl_size_t matrix_size = matrix.size1();
VectorT r(matrix_size);
std::vector<CPU_NumericType> s(matrix_size);
for (vcl_size_t i=0; i<s.size(); ++i)
s[i] = CPU_NumericType(0.5) + random_gen();
detail::copy_vec_to_vec(s,r);
vcl_size_t size_krylov = (matrix_size < tag.krylov_size()) ? matrix_size
: tag.krylov_size();
switch (tag.method())
{
case lanczos_tag::partial_reorthogonalization:
eigenvalues = detail::lanczosPRO(matrix, r, eigenvectors_A, size_krylov, tag, compute_eigenvectors);
break;
case lanczos_tag::full_reorthogonalization:
case lanczos_tag::no_reorthogonalization:
eigenvalues = detail::lanczos(matrix, r, eigenvectors_A, size_krylov, tag, compute_eigenvectors);
break;
}
std::vector<CPU_NumericType> largest_eigenvalues;
for (vcl_size_t i = 1; i<=tag.num_eigenvalues(); i++)
largest_eigenvalues.push_back(eigenvalues[size_krylov-i]);
return largest_eigenvalues;
}
/**
* @brief Implementation of the calculation of eigenvalues using lanczos (with and without reorthogonalization).
*
* Implementation of Lanczos with partial reorthogonalization is implemented separately.
*
* @param matrix The system matrix
* @param tag Tag with several options for the lanczos algorithm
* @return Returns the n largest eigenvalues (n defined in the lanczos_tag)
*/
template<typename MatrixT>
std::vector< typename viennacl::result_of::cpu_value_type<typename MatrixT::value_type>::type >
eig(MatrixT const & matrix, lanczos_tag const & tag)
{
typedef typename viennacl::result_of::cpu_value_type<typename MatrixT::value_type>::type NumericType;
viennacl::matrix<NumericType> eigenvectors(matrix.size1(), tag.num_eigenvalues());
return eig(matrix, eigenvectors, tag, false);
}
} // end namespace linalg
} // end namespace viennacl
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.